]> git.lizzy.rs Git - dragonfireclient.git/blob - src/client/renderingengine.cpp
Merge branch 'master' of https://github.com/minetest/minetest
[dragonfireclient.git] / src / client / renderingengine.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2017 nerzhul, Loic Blot <loic.blot@unix-experience.fr>
5
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.
10
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.
15
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.
19 */
20
21 #include <IrrlichtDevice.h>
22 #include "fontengine.h"
23 #include "client.h"
24 #include "clouds.h"
25 #include "util/numeric.h"
26 #include "guiscalingfilter.h"
27 #include "localplayer.h"
28 #include "client/hud.h"
29 #include "camera.h"
30 #include "minimap.h"
31 #include "clientmap.h"
32 #include "renderingengine.h"
33 #include "render/core.h"
34 #include "render/factory.h"
35 #include "inputhandler.h"
36 #include "gettext.h"
37 #include "../gui/guiSkin.h"
38
39 #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__) && \
40                 !defined(SERVER) && !defined(__HAIKU__)
41 #define XORG_USED
42 #endif
43 #ifdef XORG_USED
44 #include <X11/Xlib.h>
45 #include <X11/Xutil.h>
46 #include <X11/Xatom.h>
47 #endif
48
49 #ifdef _WIN32
50 #include <windows.h>
51 #include <winuser.h>
52 #endif
53
54 #if ENABLE_GLES
55 #include "filesys.h"
56 #endif
57
58 RenderingEngine *RenderingEngine::s_singleton = nullptr;
59
60
61 static gui::GUISkin *createSkin(gui::IGUIEnvironment *environment,
62                 gui::EGUI_SKIN_TYPE type, video::IVideoDriver *driver)
63 {
64         gui::GUISkin *skin = new gui::GUISkin(type, driver);
65
66         gui::IGUIFont *builtinfont = environment->getBuiltInFont();
67         gui::IGUIFontBitmap *bitfont = nullptr;
68         if (builtinfont && builtinfont->getType() == gui::EGFT_BITMAP)
69                 bitfont = (gui::IGUIFontBitmap*)builtinfont;
70
71         gui::IGUISpriteBank *bank = 0;
72         skin->setFont(builtinfont);
73
74         if (bitfont)
75                 bank = bitfont->getSpriteBank();
76
77         skin->setSpriteBank(bank);
78
79         return skin;
80 }
81
82
83 RenderingEngine::RenderingEngine(IEventReceiver *receiver)
84 {
85         sanity_check(!s_singleton);
86
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");
91
92         // bpp, fsaa, vsync
93         bool vsync = g_settings->getBool("vsync");
94         u16 fsaa = g_settings->getU16("fsaa");
95
96         // stereo buffer required for pageflip stereo
97         bool stereo_buffer = g_settings->get("3d_mode") == "pageflip";
98
99         // Determine driver
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();
104         u32 i;
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];
109                         break;
110                 }
111         }
112         if (i == drivers.size()) {
113                 errorstream << "Invalid video_driver specified; "
114                                "defaulting to opengl"
115                             << std::endl;
116         }
117
118         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
119         if (tracestream)
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;
130 #ifdef __ANDROID__
131         params.PrivateData = porting::app_global;
132 #endif
133 #if ENABLE_GLES
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();
138 #endif
139
140         m_device = createDeviceEx(params);
141         driver = m_device->getVideoDriver();
142
143         s_singleton = this;
144
145         auto skin = createSkin(m_device->getGUIEnvironment(),
146                         gui::EGST_WINDOWS_METALLIC, driver);
147         m_device->getGUIEnvironment()->setSkin(skin);
148         skin->drop();
149 }
150
151 RenderingEngine::~RenderingEngine()
152 {
153         core.reset();
154         m_device->closeDevice();
155         s_singleton = nullptr;
156 }
157
158 v2u32 RenderingEngine::_getWindowSize() const
159 {
160         if (core)
161                 return core->getVirtualSize();
162         return m_device->getVideoDriver()->getScreenSize();
163 }
164
165 void RenderingEngine::setResizable(bool resize)
166 {
167         m_device->setResizable(resize);
168 }
169
170 void RenderingEngine::removeMesh(const scene::IMesh* mesh)
171 {
172         m_device->getSceneManager()->getMeshCache()->removeMesh(mesh);
173 }
174
175 void RenderingEngine::cleanupMeshCache()
176 {
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);
181         }
182 }
183
184 bool RenderingEngine::setupTopLevelWindow(const std::string &name)
185 {
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.
189
190         /* Setting Xorg properties for the top level window */
191         setupTopLevelXorgWindow(name);
192
193         /* Setting general properties for the top level window */
194         verbosestream << "Client: Configuring general top level"
195                 << " window properties"
196                 << std::endl;
197         bool result = setWindowIcon();
198
199         return result;
200 }
201
202 void RenderingEngine::setupTopLevelXorgWindow(const std::string &name)
203 {
204 #ifdef XORG_USED
205         const video::SExposedVideoData exposedData = driver->getExposedVideoData();
206
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"
210                         << std::endl;
211                 return;
212         }
213
214         verbosestream << "Client: Configuring X11-specific top level"
215                 << " window properties"
216                 << std::endl;
217
218
219         Window x11_win = reinterpret_cast<Window>(exposedData.OpenGLLinux.X11Window);
220
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());
225
226         XSetClassHint(x11_dpl, x11_win, classhint);
227         XFree(classhint);
228
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.
233
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.
244
245         verbosestream << "Client: Setting Xorg window manager Properties"
246                 << std::endl;
247
248         XSetWMProperties (x11_dpl, x11_win, NULL, NULL, NULL, 0, NULL, NULL, NULL);
249
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
253         // window message.
254
255         verbosestream << "Client: Setting Xorg _NET_WM_PID extended window manager property"
256                 << std::endl;
257
258         Atom NET_WM_PID = XInternAtom(x11_dpl, "_NET_WM_PID", false);
259
260         pid_t pid = getpid();
261
262         XChangeProperty(x11_dpl, x11_win, NET_WM_PID,
263                         XA_CARDINAL, 32, PropModeReplace,
264                         reinterpret_cast<unsigned char *>(&pid),1);
265
266         // Set the WM_CLIENT_LEADER window property here. Minetest has only one
267         // window and that window will always be the leader.
268
269         verbosestream << "Client: Setting Xorg WM_CLIENT_LEADER property"
270                 << std::endl;
271
272         Atom WM_CLIENT_LEADER = XInternAtom(x11_dpl, "WM_CLIENT_LEADER", false);
273
274         XChangeProperty (x11_dpl, x11_win, WM_CLIENT_LEADER,
275                 XA_WINDOW, 32, PropModeReplace,
276                 reinterpret_cast<unsigned char *>(&x11_win), 1);
277 #endif
278 }
279
280 #ifdef _WIN32
281 static bool getWindowHandle(irr::video::IVideoDriver *driver, HWND &hWnd)
282 {
283         const video::SExposedVideoData exposedData = driver->getExposedVideoData();
284
285         switch (driver->getDriverType()) {
286 #if ENABLE_GLES
287         case video::EDT_OGLES1:
288         case video::EDT_OGLES2:
289 #endif
290         case video::EDT_OPENGL:
291                 hWnd = reinterpret_cast<HWND>(exposedData.OpenGLWin32.HWnd);
292                 break;
293         default:
294                 return false;
295         }
296
297         return true;
298 }
299 #endif
300
301 bool RenderingEngine::setWindowIcon()
302 {
303 #if defined(XORG_USED)
304 #if RUN_IN_PLACE
305         return setXorgWindowIconFromPath(
306                         porting::path_share + "/misc/dragonfire-xorg-icon-128.png");
307 #else
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");
314 #endif
315 #elif defined(_WIN32)
316         HWND hWnd; // Window handle
317         if (!getWindowHandle(driver, hWnd))
318                 return false;
319
320         // Load the ICON from resource file
321         const HICON hicon = LoadIcon(GetModuleHandle(NULL),
322                         MAKEINTRESOURCE(130) // The ID of the ICON defined in
323                                              // winresource.rc
324         );
325
326         if (hicon) {
327                 SendMessage(hWnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(hicon));
328                 SendMessage(hWnd, WM_SETICON, ICON_SMALL,
329                                 reinterpret_cast<LPARAM>(hicon));
330                 return true;
331         }
332         return false;
333 #else
334         return false;
335 #endif
336 }
337
338 bool RenderingEngine::setXorgWindowIconFromPath(const std::string &icon_file)
339 {
340 #ifdef XORG_USED
341
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);
348                         break;
349                 }
350         }
351
352         if (!image_loader) {
353                 warningstream << "Could not find image loader for file '" << icon_file
354                               << "'" << std::endl;
355                 return false;
356         }
357
358         io::IReadFile *icon_f =
359                         m_device->getFileSystem()->createAndOpenFile(icon_file.c_str());
360
361         if (!icon_f) {
362                 warningstream << "Could not load icon file '" << icon_file << "'"
363                               << std::endl;
364                 return false;
365         }
366
367         video::IImage *img = image_loader->loadImage(icon_f);
368
369         if (!img) {
370                 warningstream << "Could not load icon file '" << icon_file << "'"
371                               << std::endl;
372                 icon_f->drop();
373                 return false;
374         }
375
376         u32 height = img->getDimension().Height;
377         u32 width = img->getDimension().Width;
378
379         size_t icon_buffer_len = 2 + height * width;
380         long *icon_buffer = new long[icon_buffer_len];
381
382         icon_buffer[0] = width;
383         icon_buffer[1] = height;
384
385         for (u32 x = 0; x < width; x++) {
386                 for (u32 y = 0; y < height; y++) {
387                         video::SColor col = img->getPixel(x, y);
388                         long pixel_val = 0;
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;
394                 }
395         }
396
397         img->drop();
398         icon_f->drop();
399
400         const video::SExposedVideoData &video_data = driver->getExposedVideoData();
401
402         Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display;
403
404         if (x11_dpl == NULL) {
405                 warningstream << "Could not find x11 display for setting its icon."
406                               << std::endl;
407                 delete[] icon_buffer;
408                 return false;
409         }
410
411         Window x11_win = (Window)video_data.OpenGLLinux.X11Window;
412
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);
417
418         delete[] icon_buffer;
419
420 #endif
421         return true;
422 }
423
424 /*
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.
428 */
429 void RenderingEngine::draw_load_screen(const std::wstring &text,
430                 gui::IGUIEnvironment *guienv, ITextureSource *tsrc, float dtime,
431                 int percent, bool clouds)
432 {
433         v2u32 screensize = getWindowSize();
434
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);
438
439         gui::IGUIStaticText *guitext =
440                         guienv->addStaticText(text.c_str(), textrect, false, false);
441         guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
442
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();
450         } else
451                 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
452
453         // draw progress bar
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");
458
459                 if (progress_img && progress_img_bg) {
460 #ifndef __ANDROID__
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);
465 #else
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);
470 #endif
471                         v2s32 img_pos((screensize.X - imgW) / 2,
472                                         (screensize.Y - imgH) / 2);
473
474                         draw2DImageFilterScaled(get_video_driver(), progress_img_bg,
475                                         core::rect<s32>(img_pos.X, img_pos.Y,
476                                                         img_pos.X + imgW,
477                                                         img_pos.Y + imgH),
478                                         core::rect<s32>(0, 0, img_size.Width,
479                                                         img_size.Height),
480                                         0, 0, true);
481
482                         draw2DImageFilterScaled(get_video_driver(), progress_img,
483                                         core::rect<s32>(img_pos.X, img_pos.Y,
484                                                         img_pos.X + (percent * imgW) / 100,
485                                                         img_pos.Y + imgH),
486                                         core::rect<s32>(0, 0,
487                                                         (percent * img_size.Width) / 100,
488                                                         img_size.Height),
489                                         0, 0, true);
490                 }
491         }
492
493         guienv->drawAll();
494         get_video_driver()->endScene();
495         guitext->remove();
496 }
497
498 /*
499         Draws the menu scene including (optional) cloud background.
500 */
501 void RenderingEngine::draw_menu_scene(gui::IGUIEnvironment *guienv,
502                 float dtime, bool clouds)
503 {
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();
511         } else
512                 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
513
514         guienv->drawAll();
515         get_video_driver()->endScene();
516 }
517
518 std::vector<irr::video::E_DRIVER_TYPE> RenderingEngine::getSupportedVideoDrivers()
519 {
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,
527         };
528         std::vector<irr::video::E_DRIVER_TYPE> drivers;
529
530         for (int i = 0; i < 4; i++) {
531                 if (irr::IrrlichtDevice::isDriverSupported(glDrivers[i]))
532                         drivers.push_back(glDrivers[i]);
533         }
534
535         return drivers;
536 }
537
538 void RenderingEngine::initialize(Client *client, Hud *hud)
539 {
540         const std::string &draw_mode = g_settings->get("3d_mode");
541         core.reset(createRenderingCore(draw_mode, m_device, client, hud));
542         core->initialize();
543 }
544
545 void RenderingEngine::finalize()
546 {
547         core.reset();
548 }
549
550 void RenderingEngine::draw_scene(video::SColor skycolor, bool show_hud,
551                 bool show_minimap, bool draw_wield_tool, bool draw_crosshair)
552 {
553         core->draw(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair);
554 }
555
556 const VideoDriverInfo &RenderingEngine::getVideoDriverInfo(irr::video::E_DRIVER_TYPE type)
557 {
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"}},
563         };
564         return driver_info_map.at((int)type);
565 }
566
567 #ifndef __ANDROID__
568 #if defined(XORG_USED)
569
570 static float calcDisplayDensity()
571 {
572         const char *current_display = getenv("DISPLAY");
573
574         if (current_display != NULL) {
575                 Display *x11display = XOpenDisplay(current_display);
576
577                 if (x11display != NULL) {
578                         /* try x direct */
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);
584
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;
589                         }
590                 }
591         }
592
593         /* return manually specified dpi */
594         return g_settings->getFloat("screen_dpi") / 96.0;
595 }
596
597 float RenderingEngine::getDisplayDensity()
598 {
599         static float cached_display_density = calcDisplayDensity();
600         return cached_display_density * g_settings->getFloat("display_density_factor");
601 }
602
603 #elif defined(_WIN32)
604
605
606 static float calcDisplayDensity(irr::video::IVideoDriver *driver)
607 {
608         HWND hWnd;
609         if (getWindowHandle(driver, hWnd)) {
610                 HDC hdc = GetDC(hWnd);
611                 float dpi = GetDeviceCaps(hdc, LOGPIXELSX);
612                 ReleaseDC(hWnd, hdc);
613                 return dpi / 96.0f;
614         }
615
616         /* return manually specified dpi */
617         return g_settings->getFloat("screen_dpi") / 96.0f;
618 }
619
620 float RenderingEngine::getDisplayDensity()
621 {
622         static bool cached = false;
623         static float display_density;
624         if (!cached) {
625                 display_density = calcDisplayDensity(get_video_driver());
626                 cached = true;
627         }
628         return display_density * g_settings->getFloat("display_density_factor");
629 }
630
631 #else
632
633 float RenderingEngine::getDisplayDensity()
634 {
635         return (g_settings->getFloat("screen_dpi") / 96.0) * g_settings->getFloat("display_density_factor");
636 }
637
638 #endif
639
640 #else // __ANDROID__
641 float RenderingEngine::getDisplayDensity()
642 {
643         return porting::getDisplayDensity();
644 }
645
646 #endif // __ANDROID__