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>
55 RenderingEngine *RenderingEngine::s_singleton = nullptr;
58 static gui::GUISkin *createSkin(gui::IGUIEnvironment *environment,
59 gui::EGUI_SKIN_TYPE type, video::IVideoDriver *driver)
61 gui::GUISkin *skin = new gui::GUISkin(type, driver);
63 gui::IGUIFont *builtinfont = environment->getBuiltInFont();
64 gui::IGUIFontBitmap *bitfont = nullptr;
65 if (builtinfont && builtinfont->getType() == gui::EGFT_BITMAP)
66 bitfont = (gui::IGUIFontBitmap*)builtinfont;
68 gui::IGUISpriteBank *bank = 0;
69 skin->setFont(builtinfont);
72 bank = bitfont->getSpriteBank();
74 skin->setSpriteBank(bank);
80 RenderingEngine::RenderingEngine(IEventReceiver *receiver)
82 sanity_check(!s_singleton);
84 // Resolution selection
85 bool fullscreen = g_settings->getBool("fullscreen");
86 u16 screen_w = g_settings->getU16("screen_w");
87 u16 screen_h = g_settings->getU16("screen_h");
90 bool vsync = g_settings->getBool("vsync");
91 u16 bits = g_settings->getU16("fullscreen_bpp");
92 u16 fsaa = g_settings->getU16("fsaa");
94 // stereo buffer required for pageflip stereo
95 bool stereo_buffer = g_settings->get("3d_mode") == "pageflip";
98 video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
99 const std::string &driverstring = g_settings->get("video_driver");
100 std::vector<video::E_DRIVER_TYPE> drivers =
101 RenderingEngine::getSupportedVideoDrivers();
103 for (i = 0; i != drivers.size(); i++) {
104 if (!strcasecmp(driverstring.c_str(),
105 RenderingEngine::getVideoDriverName(drivers[i]))) {
106 driverType = drivers[i];
110 if (i == drivers.size()) {
111 errorstream << "Invalid video_driver specified; "
112 "defaulting to opengl"
116 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
117 params.DriverType = driverType;
118 params.WindowSize = core::dimension2d<u32>(screen_w, screen_h);
120 params.AntiAlias = fsaa;
121 params.Fullscreen = fullscreen;
122 params.Stencilbuffer = false;
123 params.Stereobuffer = stereo_buffer;
124 params.Vsync = vsync;
125 params.EventReceiver = receiver;
126 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
127 params.ZBufferBits = 24;
130 params.PrivateData = porting::app_global;
131 params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM + "media" +
132 DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
135 // there is no standardized path for these on desktop
136 std::string rel_path = std::string("client") + DIR_DELIM
137 + "shaders" + DIR_DELIM + "Irrlicht";
138 params.OGLES2ShaderPath = (porting::path_share + DIR_DELIM + rel_path + DIR_DELIM).c_str();
141 m_device = createDeviceEx(params);
142 driver = m_device->getVideoDriver();
146 auto skin = createSkin(m_device->getGUIEnvironment(),
147 gui::EGST_WINDOWS_METALLIC, driver);
148 m_device->getGUIEnvironment()->setSkin(skin);
152 RenderingEngine::~RenderingEngine()
156 s_singleton = nullptr;
159 v2u32 RenderingEngine::getWindowSize() const
162 return core->getVirtualSize();
163 return m_device->getVideoDriver()->getScreenSize();
166 void RenderingEngine::setResizable(bool resize)
168 m_device->setResizable(resize);
171 bool RenderingEngine::print_video_modes()
173 IrrlichtDevice *nulldevice;
175 bool vsync = g_settings->getBool("vsync");
176 u16 fsaa = g_settings->getU16("fsaa");
177 MyEventReceiver *receiver = new MyEventReceiver();
179 SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
180 params.DriverType = video::EDT_NULL;
181 params.WindowSize = core::dimension2d<u32>(640, 480);
183 params.AntiAlias = fsaa;
184 params.Fullscreen = false;
185 params.Stencilbuffer = false;
186 params.Vsync = vsync;
187 params.EventReceiver = receiver;
188 params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
190 nulldevice = createDeviceEx(params);
197 std::cout << _("Available video modes (WxHxD):") << std::endl;
199 video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
201 if (videomode_list != NULL) {
202 s32 videomode_count = videomode_list->getVideoModeCount();
203 core::dimension2d<u32> videomode_res;
205 for (s32 i = 0; i < videomode_count; ++i) {
206 videomode_res = videomode_list->getVideoModeResolution(i);
207 videomode_depth = videomode_list->getVideoModeDepth(i);
208 std::cout << videomode_res.Width << "x" << videomode_res.Height
209 << "x" << videomode_depth << std::endl;
212 std::cout << _("Active video mode (WxHxD):") << std::endl;
213 videomode_res = videomode_list->getDesktopResolution();
214 videomode_depth = videomode_list->getDesktopDepth();
215 std::cout << videomode_res.Width << "x" << videomode_res.Height << "x"
216 << videomode_depth << std::endl;
222 return videomode_list != NULL;
225 bool RenderingEngine::setupTopLevelWindow(const std::string &name)
227 // FIXME: It would make more sense for there to be a switch of some
228 // sort here that would call the correct toplevel setup methods for
229 // the environment Minetest is running in but for now not deviating
230 // from the original pattern.
232 /* Setting Xorg properties for the top level window */
233 setupTopLevelXorgWindow(name);
234 /* Done with Xorg properties */
236 /* Setting general properties for the top level window */
237 verbosestream << "Client: Configuring general top level"
238 << " window properties"
241 bool result = setWindowIcon();
243 verbosestream << "Client: Finished configuring general top level"
244 << " window properties"
246 /* Done with general properties */
248 // FIXME: setWindowIcon returns a bool result but it is unused.
249 // For now continue to return this result.
253 void RenderingEngine::setupTopLevelXorgWindow(const std::string &name)
256 const video::SExposedVideoData exposedData = driver->getExposedVideoData();
258 Display *x11_dpl = reinterpret_cast<Display *>(exposedData.OpenGLLinux.X11Display);
259 if (x11_dpl == NULL) {
260 warningstream << "Client: Could not find X11 Display in ExposedVideoData"
265 verbosestream << "Client: Configuring Xorg specific top level"
266 << " window properties"
270 Window x11_win = reinterpret_cast<Window>(exposedData.OpenGLLinux.X11Window);
272 // Set application name and class hints. For now name and class are the same.
273 XClassHint *classhint = XAllocClassHint();
274 classhint->res_name = const_cast<char *>(name.c_str());
275 classhint->res_class = const_cast<char *>(name.c_str());
277 XSetClassHint(x11_dpl, x11_win, classhint);
280 // FIXME: In the future WMNormalHints should be set ... e.g see the
281 // gtk/gdk code (gdk/x11/gdksurface-x11.c) for the setup_top_level
282 // method. But for now (as it would require some significant changes)
283 // leave the code as is.
285 // The following is borrowed from the above gdk source for setting top
286 // level windows. The source indicates and the Xlib docs suggest that
287 // this will set the WM_CLIENT_MACHINE and WM_LOCAL_NAME. This will not
288 // set the WM_CLIENT_MACHINE to a Fully Qualified Domain Name (FQDN) which is
289 // required by the Extended Window Manager Hints (EWMH) spec when setting
290 // the _NET_WM_PID (see further down) but running Minetest in an env
291 // where the window manager is on another machine from Minetest (therefore
292 // making the PID useless) is not expected to be a problem. Further
293 // more, using gtk/gdk as the model it would seem that not using a FQDN is
294 // not an issue for modern Xorg window managers.
296 verbosestream << "Client: Setting Xorg window manager Properties"
299 XSetWMProperties (x11_dpl, x11_win, NULL, NULL, NULL, 0, NULL, NULL, NULL);
301 // Set the _NET_WM_PID window property according to the EWMH spec. _NET_WM_PID
302 // (in conjunction with WM_CLIENT_MACHINE) can be used by window managers to
303 // force a shutdown of an application if it doesn't respond to the destroy
306 verbosestream << "Client: Setting Xorg _NET_WM_PID extened window manager property"
309 Atom NET_WM_PID = XInternAtom(x11_dpl, "_NET_WM_PID", false);
311 pid_t pid = getpid();
312 infostream << "Client: PID is '" << static_cast<long>(pid) << "'"
315 XChangeProperty(x11_dpl, x11_win, NET_WM_PID,
316 XA_CARDINAL, 32, PropModeReplace,
317 reinterpret_cast<unsigned char *>(&pid),1);
319 // Set the WM_CLIENT_LEADER window property here. Minetest has only one
320 // window and that window will always be the leader.
322 verbosestream << "Client: Setting Xorg WM_CLIENT_LEADER property"
325 Atom WM_CLIENT_LEADER = XInternAtom(x11_dpl, "WM_CLIENT_LEADER", false);
327 XChangeProperty (x11_dpl, x11_win, WM_CLIENT_LEADER,
328 XA_WINDOW, 32, PropModeReplace,
329 reinterpret_cast<unsigned char *>(&x11_win), 1);
331 verbosestream << "Client: Finished configuring Xorg specific top level"
332 << " window properties"
338 bool RenderingEngine::setWindowIcon()
340 #if defined(XORG_USED)
342 return setXorgWindowIconFromPath(
343 porting::path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png");
345 // We have semi-support for reading in-place data if we are
346 // compiled with RUN_IN_PLACE. Don't break with this and
347 // also try the path_share location.
348 return setXorgWindowIconFromPath(
349 ICON_DIR "/hicolor/128x128/apps/" PROJECT_NAME ".png") ||
350 setXorgWindowIconFromPath(porting::path_share + "/misc/" PROJECT_NAME
351 "-xorg-icon-128.png");
353 #elif defined(_WIN32)
354 const video::SExposedVideoData exposedData = driver->getExposedVideoData();
355 HWND hWnd; // Window handle
357 switch (driver->getDriverType()) {
358 case video::EDT_DIRECT3D8:
359 hWnd = reinterpret_cast<HWND>(exposedData.D3D8.HWnd);
361 case video::EDT_DIRECT3D9:
362 hWnd = reinterpret_cast<HWND>(exposedData.D3D9.HWnd);
364 case video::EDT_OPENGL:
365 hWnd = reinterpret_cast<HWND>(exposedData.OpenGLWin32.HWnd);
371 // Load the ICON from resource file
372 const HICON hicon = LoadIcon(GetModuleHandle(NULL),
373 MAKEINTRESOURCE(130) // The ID of the ICON defined in
378 SendMessage(hWnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(hicon));
379 SendMessage(hWnd, WM_SETICON, ICON_SMALL,
380 reinterpret_cast<LPARAM>(hicon));
389 bool RenderingEngine::setXorgWindowIconFromPath(const std::string &icon_file)
393 video::IImageLoader *image_loader = NULL;
394 u32 cnt = driver->getImageLoaderCount();
395 for (u32 i = 0; i < cnt; i++) {
396 if (driver->getImageLoader(i)->isALoadableFileExtension(
397 icon_file.c_str())) {
398 image_loader = driver->getImageLoader(i);
404 warningstream << "Could not find image loader for file '" << icon_file
409 io::IReadFile *icon_f =
410 m_device->getFileSystem()->createAndOpenFile(icon_file.c_str());
413 warningstream << "Could not load icon file '" << icon_file << "'"
418 video::IImage *img = image_loader->loadImage(icon_f);
421 warningstream << "Could not load icon file '" << icon_file << "'"
427 u32 height = img->getDimension().Height;
428 u32 width = img->getDimension().Width;
430 size_t icon_buffer_len = 2 + height * width;
431 long *icon_buffer = new long[icon_buffer_len];
433 icon_buffer[0] = width;
434 icon_buffer[1] = height;
436 for (u32 x = 0; x < width; x++) {
437 for (u32 y = 0; y < height; y++) {
438 video::SColor col = img->getPixel(x, y);
440 pixel_val |= (u8)col.getAlpha() << 24;
441 pixel_val |= (u8)col.getRed() << 16;
442 pixel_val |= (u8)col.getGreen() << 8;
443 pixel_val |= (u8)col.getBlue();
444 icon_buffer[2 + x + y * width] = pixel_val;
451 const video::SExposedVideoData &video_data = driver->getExposedVideoData();
453 Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display;
455 if (x11_dpl == NULL) {
456 warningstream << "Could not find x11 display for setting its icon."
458 delete[] icon_buffer;
462 Window x11_win = (Window)video_data.OpenGLLinux.X11Window;
464 Atom net_wm_icon = XInternAtom(x11_dpl, "_NET_WM_ICON", False);
465 Atom cardinal = XInternAtom(x11_dpl, "CARDINAL", False);
466 XChangeProperty(x11_dpl, x11_win, net_wm_icon, cardinal, 32, PropModeReplace,
467 (const unsigned char *)icon_buffer, icon_buffer_len);
469 delete[] icon_buffer;
476 Draws a screen with a single text on it.
477 Text will be removed when the screen is drawn the next time.
478 Additionally, a progressbar can be drawn when percent is set between 0 and 100.
480 void RenderingEngine::_draw_load_screen(const std::wstring &text,
481 gui::IGUIEnvironment *guienv, ITextureSource *tsrc, float dtime,
482 int percent, bool clouds)
484 v2u32 screensize = RenderingEngine::get_instance()->getWindowSize();
486 v2s32 textsize(g_fontengine->getTextWidth(text), g_fontengine->getLineHeight());
487 v2s32 center(screensize.X / 2, screensize.Y / 2);
488 core::rect<s32> textrect(center - textsize / 2, center + textsize / 2);
490 gui::IGUIStaticText *guitext =
491 guienv->addStaticText(text.c_str(), textrect, false, false);
492 guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
494 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
495 if (cloud_menu_background) {
496 g_menuclouds->step(dtime * 3);
497 g_menuclouds->render();
498 get_video_driver()->beginScene(
499 true, true, video::SColor(255, 140, 186, 250));
500 g_menucloudsmgr->drawAll();
502 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
505 if ((percent >= 0) && (percent <= 100)) {
506 video::ITexture *progress_img = tsrc->getTexture("progress_bar.png");
507 video::ITexture *progress_img_bg =
508 tsrc->getTexture("progress_bar_bg.png");
510 if (progress_img && progress_img_bg) {
512 const core::dimension2d<u32> &img_size =
513 progress_img_bg->getSize();
514 u32 imgW = rangelim(img_size.Width, 200, 600);
515 u32 imgH = rangelim(img_size.Height, 24, 72);
517 const core::dimension2d<u32> img_size(256, 48);
518 float imgRatio = (float)img_size.Height / img_size.Width;
519 u32 imgW = screensize.X / 2.2f;
520 u32 imgH = floor(imgW * imgRatio);
522 v2s32 img_pos((screensize.X - imgW) / 2,
523 (screensize.Y - imgH) / 2);
525 draw2DImageFilterScaled(get_video_driver(), progress_img_bg,
526 core::rect<s32>(img_pos.X, img_pos.Y,
529 core::rect<s32>(0, 0, img_size.Width,
533 draw2DImageFilterScaled(get_video_driver(), progress_img,
534 core::rect<s32>(img_pos.X, img_pos.Y,
535 img_pos.X + (percent * imgW) / 100,
537 core::rect<s32>(0, 0,
538 (percent * img_size.Width) / 100,
545 get_video_driver()->endScene();
550 Draws the menu scene including (optional) cloud background.
552 void RenderingEngine::_draw_menu_scene(gui::IGUIEnvironment *guienv,
553 float dtime, bool clouds)
555 bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
556 if (cloud_menu_background) {
557 g_menuclouds->step(dtime * 3);
558 g_menuclouds->render();
559 get_video_driver()->beginScene(
560 true, true, video::SColor(255, 140, 186, 250));
561 g_menucloudsmgr->drawAll();
563 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
566 get_video_driver()->endScene();
569 std::vector<core::vector3d<u32>> RenderingEngine::getSupportedVideoModes()
571 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
572 sanity_check(nulldevice);
574 std::vector<core::vector3d<u32>> mlist;
575 video::IVideoModeList *modelist = nulldevice->getVideoModeList();
577 s32 num_modes = modelist->getVideoModeCount();
578 for (s32 i = 0; i != num_modes; i++) {
579 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
580 u32 mode_depth = (u32)modelist->getVideoModeDepth(i);
581 mlist.emplace_back(mode_res.Width, mode_res.Height, mode_depth);
588 std::vector<irr::video::E_DRIVER_TYPE> RenderingEngine::getSupportedVideoDrivers()
590 std::vector<irr::video::E_DRIVER_TYPE> drivers;
592 for (int i = 0; i != irr::video::EDT_COUNT; i++) {
593 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
594 drivers.push_back((irr::video::E_DRIVER_TYPE)i);
600 void RenderingEngine::_initialize(Client *client, Hud *hud)
602 const std::string &draw_mode = g_settings->get("3d_mode");
603 core.reset(createRenderingCore(draw_mode, m_device, client, hud));
607 void RenderingEngine::_finalize()
612 void RenderingEngine::_draw_scene(video::SColor skycolor, bool show_hud,
613 bool show_minimap, bool draw_wield_tool, bool draw_crosshair)
615 core->draw(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair);
618 const char *RenderingEngine::getVideoDriverName(irr::video::E_DRIVER_TYPE type)
620 static const char *driver_ids[] = {
631 return driver_ids[type];
634 const char *RenderingEngine::getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
636 static const char *driver_names[] = {
647 return driver_names[type];
653 static float calcDisplayDensity()
655 const char *current_display = getenv("DISPLAY");
657 if (current_display != NULL) {
658 Display *x11display = XOpenDisplay(current_display);
660 if (x11display != NULL) {
662 int dh = DisplayHeight(x11display, 0);
663 int dw = DisplayWidth(x11display, 0);
664 int dh_mm = DisplayHeightMM(x11display, 0);
665 int dw_mm = DisplayWidthMM(x11display, 0);
666 XCloseDisplay(x11display);
668 if (dh_mm != 0 && dw_mm != 0) {
669 float dpi_height = floor(dh / (dh_mm * 0.039370) + 0.5);
670 float dpi_width = floor(dw / (dw_mm * 0.039370) + 0.5);
671 return std::max(dpi_height, dpi_width) / 96.0;
676 /* return manually specified dpi */
677 return g_settings->getFloat("screen_dpi") / 96.0;
680 float RenderingEngine::getDisplayDensity()
682 static float cached_display_density = calcDisplayDensity();
683 return cached_display_density;
687 float RenderingEngine::getDisplayDensity()
689 return g_settings->getFloat("screen_dpi") / 96.0;
693 v2u32 RenderingEngine::getDisplaySize()
695 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
697 core::dimension2d<u32> deskres =
698 nulldevice->getVideoModeList()->getDesktopResolution();
705 float RenderingEngine::getDisplayDensity()
707 return porting::getDisplayDensity();
710 v2u32 RenderingEngine::getDisplaySize()
712 return porting::getDisplaySize();
714 #endif // __ANDROID__