]> git.lizzy.rs Git - dragonfireclient.git/blob - src/client/renderingengine.cpp
Android build fixes for c++11
[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 <irrlicht.h>
23 #include "fontengine.h"
24 #include "client.h"
25 #include "clouds.h"
26 #include "util/numeric.h"
27 #include "guiscalingfilter.h"
28 #include "localplayer.h"
29 #include "client/hud.h"
30 #include "camera.h"
31 #include "minimap.h"
32 #include "clientmap.h"
33 #include "renderingengine.h"
34 #include "render/core.h"
35 #include "render/factory.h"
36 #include "inputhandler.h"
37 #include "gettext.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 #endif
47
48 #ifdef __ANDROID__
49 #include "filesys.h"
50 #endif
51
52 RenderingEngine *RenderingEngine::s_singleton = nullptr;
53
54 RenderingEngine::RenderingEngine(IEventReceiver *receiver)
55 {
56         sanity_check(!s_singleton);
57
58         // Resolution selection
59         bool fullscreen = g_settings->getBool("fullscreen");
60         u16 screen_w = g_settings->getU16("screen_w");
61         u16 screen_h = g_settings->getU16("screen_h");
62
63         // bpp, fsaa, vsync
64         bool vsync = g_settings->getBool("vsync");
65         u16 bits = g_settings->getU16("fullscreen_bpp");
66         u16 fsaa = g_settings->getU16("fsaa");
67
68         // stereo buffer required for pageflip stereo
69         bool stereo_buffer = g_settings->get("3d_mode") == "pageflip";
70
71         // Determine driver
72         video::E_DRIVER_TYPE driverType = video::EDT_OPENGL;
73         const std::string &driverstring = g_settings->get("video_driver");
74         std::vector<video::E_DRIVER_TYPE> drivers =
75                         RenderingEngine::getSupportedVideoDrivers();
76         u32 i;
77         for (i = 0; i != drivers.size(); i++) {
78                 if (!strcasecmp(driverstring.c_str(),
79                                     RenderingEngine::getVideoDriverName(drivers[i]))) {
80                         driverType = drivers[i];
81                         break;
82                 }
83         }
84         if (i == drivers.size()) {
85                 errorstream << "Invalid video_driver specified; "
86                                "defaulting to opengl"
87                             << std::endl;
88         }
89
90         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
91         params.DriverType = driverType;
92         params.WindowSize = core::dimension2d<u32>(screen_w, screen_h);
93         params.Bits = bits;
94         params.AntiAlias = fsaa;
95         params.Fullscreen = fullscreen;
96         params.Stencilbuffer = false;
97         params.Stereobuffer = stereo_buffer;
98         params.Vsync = vsync;
99         params.EventReceiver = receiver;
100         params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
101         params.ZBufferBits = 24;
102 #ifdef __ANDROID__
103         // clang-format off
104         params.PrivateData = porting::app_global;
105         params.OGLES2ShaderPath = std::string(porting::path_user + DIR_DELIM + "media" +
106                 DIR_DELIM + "Shaders" + DIR_DELIM).c_str();
107         // clang-format on
108 #endif
109
110         m_device = createDeviceEx(params);
111         driver = m_device->getVideoDriver();
112
113         s_singleton = this;
114 }
115
116 RenderingEngine::~RenderingEngine()
117 {
118         core.reset();
119         m_device->drop();
120         s_singleton = nullptr;
121 }
122
123 v2u32 RenderingEngine::getWindowSize() const
124 {
125         if (core)
126                 return core->getVirtualSize();
127         return m_device->getVideoDriver()->getScreenSize();
128 }
129
130 void RenderingEngine::setResizable(bool resize)
131 {
132         m_device->setResizable(resize);
133 }
134
135 bool RenderingEngine::print_video_modes()
136 {
137         IrrlichtDevice *nulldevice;
138
139         bool vsync = g_settings->getBool("vsync");
140         u16 fsaa = g_settings->getU16("fsaa");
141         MyEventReceiver *receiver = new MyEventReceiver();
142
143         SIrrlichtCreationParameters params = SIrrlichtCreationParameters();
144         params.DriverType = video::EDT_NULL;
145         params.WindowSize = core::dimension2d<u32>(640, 480);
146         params.Bits = 24;
147         params.AntiAlias = fsaa;
148         params.Fullscreen = false;
149         params.Stencilbuffer = false;
150         params.Vsync = vsync;
151         params.EventReceiver = receiver;
152         params.HighPrecisionFPU = g_settings->getBool("high_precision_fpu");
153
154         nulldevice = createDeviceEx(params);
155
156         if (!nulldevice) {
157                 delete receiver;
158                 return false;
159         }
160
161         std::cout << _("Available video modes (WxHxD):") << std::endl;
162
163         video::IVideoModeList *videomode_list = nulldevice->getVideoModeList();
164
165         if (videomode_list != NULL) {
166                 s32 videomode_count = videomode_list->getVideoModeCount();
167                 core::dimension2d<u32> videomode_res;
168                 s32 videomode_depth;
169                 for (s32 i = 0; i < videomode_count; ++i) {
170                         videomode_res = videomode_list->getVideoModeResolution(i);
171                         videomode_depth = videomode_list->getVideoModeDepth(i);
172                         std::cout << videomode_res.Width << "x" << videomode_res.Height
173                                   << "x" << videomode_depth << std::endl;
174                 }
175
176                 std::cout << _("Active video mode (WxHxD):") << std::endl;
177                 videomode_res = videomode_list->getDesktopResolution();
178                 videomode_depth = videomode_list->getDesktopDepth();
179                 std::cout << videomode_res.Width << "x" << videomode_res.Height << "x"
180                           << videomode_depth << std::endl;
181         }
182
183         nulldevice->drop();
184         delete receiver;
185
186         return videomode_list != NULL;
187 }
188
189 void RenderingEngine::setXorgClassHint(
190                 const video::SExposedVideoData &video_data, const std::string &name)
191 {
192 #ifdef XORG_USED
193         if (video_data.OpenGLLinux.X11Display == NULL)
194                 return;
195
196         XClassHint *classhint = XAllocClassHint();
197         classhint->res_name = (char *)name.c_str();
198         classhint->res_class = (char *)name.c_str();
199
200         XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
201                         video_data.OpenGLLinux.X11Window, classhint);
202         XFree(classhint);
203 #endif
204 }
205
206 bool RenderingEngine::setWindowIcon()
207 {
208 #if defined(XORG_USED)
209 #if RUN_IN_PLACE
210         return setXorgWindowIconFromPath(
211                         porting::path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png");
212 #else
213         // We have semi-support for reading in-place data if we are
214         // compiled with RUN_IN_PLACE. Don't break with this and
215         // also try the path_share location.
216         return setXorgWindowIconFromPath(
217                                ICON_DIR "/hicolor/128x128/apps/" PROJECT_NAME ".png") ||
218                setXorgWindowIconFromPath(porting::path_share + "/misc/" PROJECT_NAME
219                                                                "-xorg-icon-128.png");
220 #endif
221 #elif defined(_WIN32)
222         const video::SExposedVideoData exposedData = driver->getExposedVideoData();
223         HWND hWnd; // Window handle
224
225         switch (driver->getDriverType()) {
226         case video::EDT_DIRECT3D8:
227                 hWnd = reinterpret_cast<HWND>(exposedData.D3D8.HWnd);
228                 break;
229         case video::EDT_DIRECT3D9:
230                 hWnd = reinterpret_cast<HWND>(exposedData.D3D9.HWnd);
231                 break;
232         case video::EDT_OPENGL:
233                 hWnd = reinterpret_cast<HWND>(exposedData.OpenGLWin32.HWnd);
234                 break;
235         default:
236                 return false;
237         }
238
239         // Load the ICON from resource file
240         const HICON hicon = LoadIcon(GetModuleHandle(NULL),
241                         MAKEINTRESOURCE(130) // The ID of the ICON defined in
242                                              // winresource.rc
243         );
244
245         if (hicon) {
246                 SendMessage(hWnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(hicon));
247                 SendMessage(hWnd, WM_SETICON, ICON_SMALL,
248                                 reinterpret_cast<LPARAM>(hicon));
249                 return true;
250         }
251         return false;
252 #else
253         return false;
254 #endif
255 }
256
257 bool RenderingEngine::setXorgWindowIconFromPath(const std::string &icon_file)
258 {
259 #ifdef XORG_USED
260
261         video::IImageLoader *image_loader = NULL;
262         u32 cnt = driver->getImageLoaderCount();
263         for (u32 i = 0; i < cnt; i++) {
264                 if (driver->getImageLoader(i)->isALoadableFileExtension(
265                                     icon_file.c_str())) {
266                         image_loader = driver->getImageLoader(i);
267                         break;
268                 }
269         }
270
271         if (!image_loader) {
272                 warningstream << "Could not find image loader for file '" << icon_file
273                               << "'" << std::endl;
274                 return false;
275         }
276
277         io::IReadFile *icon_f =
278                         m_device->getFileSystem()->createAndOpenFile(icon_file.c_str());
279
280         if (!icon_f) {
281                 warningstream << "Could not load icon file '" << icon_file << "'"
282                               << std::endl;
283                 return false;
284         }
285
286         video::IImage *img = image_loader->loadImage(icon_f);
287
288         if (!img) {
289                 warningstream << "Could not load icon file '" << icon_file << "'"
290                               << std::endl;
291                 icon_f->drop();
292                 return false;
293         }
294
295         u32 height = img->getDimension().Height;
296         u32 width = img->getDimension().Width;
297
298         size_t icon_buffer_len = 2 + height * width;
299         long *icon_buffer = new long[icon_buffer_len];
300
301         icon_buffer[0] = width;
302         icon_buffer[1] = height;
303
304         for (u32 x = 0; x < width; x++) {
305                 for (u32 y = 0; y < height; y++) {
306                         video::SColor col = img->getPixel(x, y);
307                         long pixel_val = 0;
308                         pixel_val |= (u8)col.getAlpha() << 24;
309                         pixel_val |= (u8)col.getRed() << 16;
310                         pixel_val |= (u8)col.getGreen() << 8;
311                         pixel_val |= (u8)col.getBlue();
312                         icon_buffer[2 + x + y * width] = pixel_val;
313                 }
314         }
315
316         img->drop();
317         icon_f->drop();
318
319         const video::SExposedVideoData &video_data = driver->getExposedVideoData();
320
321         Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display;
322
323         if (x11_dpl == NULL) {
324                 warningstream << "Could not find x11 display for setting its icon."
325                               << std::endl;
326                 delete[] icon_buffer;
327                 return false;
328         }
329
330         Window x11_win = (Window)video_data.OpenGLLinux.X11Window;
331
332         Atom net_wm_icon = XInternAtom(x11_dpl, "_NET_WM_ICON", False);
333         Atom cardinal = XInternAtom(x11_dpl, "CARDINAL", False);
334         XChangeProperty(x11_dpl, x11_win, net_wm_icon, cardinal, 32, PropModeReplace,
335                         (const unsigned char *)icon_buffer, icon_buffer_len);
336
337         delete[] icon_buffer;
338
339 #endif
340         return true;
341 }
342
343 /*
344         Draws a screen with a single text on it.
345         Text will be removed when the screen is drawn the next time.
346         Additionally, a progressbar can be drawn when percent is set between 0 and 100.
347 */
348 void RenderingEngine::_draw_load_screen(const std::wstring &text,
349                 gui::IGUIEnvironment *guienv, ITextureSource *tsrc, float dtime,
350                 int percent, bool clouds)
351 {
352         v2u32 screensize = RenderingEngine::get_instance()->getWindowSize();
353
354         v2s32 textsize(g_fontengine->getTextWidth(text), g_fontengine->getLineHeight());
355         v2s32 center(screensize.X / 2, screensize.Y / 2);
356         core::rect<s32> textrect(center - textsize / 2, center + textsize / 2);
357
358         gui::IGUIStaticText *guitext =
359                         guienv->addStaticText(text.c_str(), textrect, false, false);
360         guitext->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
361
362         bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
363         if (cloud_menu_background) {
364                 g_menuclouds->step(dtime * 3);
365                 g_menuclouds->render();
366                 get_video_driver()->beginScene(
367                                 true, true, video::SColor(255, 140, 186, 250));
368                 g_menucloudsmgr->drawAll();
369         } else
370                 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
371
372         // draw progress bar
373         if ((percent >= 0) && (percent <= 100)) {
374                 video::ITexture *progress_img = tsrc->getTexture("progress_bar.png");
375                 video::ITexture *progress_img_bg =
376                                 tsrc->getTexture("progress_bar_bg.png");
377
378                 if (progress_img && progress_img_bg) {
379 #ifndef __ANDROID__
380                         const core::dimension2d<u32> &img_size =
381                                         progress_img_bg->getSize();
382                         u32 imgW = rangelim(img_size.Width, 200, 600);
383                         u32 imgH = rangelim(img_size.Height, 24, 72);
384 #else
385                         const core::dimension2d<u32> img_size(256, 48);
386                         float imgRatio = (float)img_size.Height / img_size.Width;
387                         u32 imgW = screensize.X / 2.2f;
388                         u32 imgH = floor(imgW * imgRatio);
389 #endif
390                         v2s32 img_pos((screensize.X - imgW) / 2,
391                                         (screensize.Y - imgH) / 2);
392
393                         draw2DImageFilterScaled(get_video_driver(), progress_img_bg,
394                                         core::rect<s32>(img_pos.X, img_pos.Y,
395                                                         img_pos.X + imgW,
396                                                         img_pos.Y + imgH),
397                                         core::rect<s32>(0, 0, img_size.Width,
398                                                         img_size.Height),
399                                         0, 0, true);
400
401                         draw2DImageFilterScaled(get_video_driver(), progress_img,
402                                         core::rect<s32>(img_pos.X, img_pos.Y,
403                                                         img_pos.X + (percent * imgW) / 100,
404                                                         img_pos.Y + imgH),
405                                         core::rect<s32>(0, 0,
406                                                         (percent * img_size.Width) / 100,
407                                                         img_size.Height),
408                                         0, 0, true);
409                 }
410         }
411
412         guienv->drawAll();
413         get_video_driver()->endScene();
414         guitext->remove();
415 }
416
417 /*
418         Draws the menu scene including (optional) cloud background.
419 */
420 void RenderingEngine::_draw_menu_scene(gui::IGUIEnvironment *guienv,
421                 float dtime, bool clouds)
422 {
423         bool cloud_menu_background = clouds && g_settings->getBool("menu_clouds");
424         if (cloud_menu_background) {
425                 g_menuclouds->step(dtime * 3);
426                 g_menuclouds->render();
427                 get_video_driver()->beginScene(
428                                 true, true, video::SColor(255, 140, 186, 250));
429                 g_menucloudsmgr->drawAll();
430         } else
431                 get_video_driver()->beginScene(true, true, video::SColor(255, 0, 0, 0));
432
433         guienv->drawAll();
434         get_video_driver()->endScene();
435 }
436
437 std::vector<core::vector3d<u32>> RenderingEngine::getSupportedVideoModes()
438 {
439         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
440         sanity_check(nulldevice);
441
442         std::vector<core::vector3d<u32>> mlist;
443         video::IVideoModeList *modelist = nulldevice->getVideoModeList();
444
445         s32 num_modes = modelist->getVideoModeCount();
446         for (s32 i = 0; i != num_modes; i++) {
447                 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
448                 u32 mode_depth = (u32)modelist->getVideoModeDepth(i);
449                 mlist.emplace_back(mode_res.Width, mode_res.Height, mode_depth);
450         }
451
452         nulldevice->drop();
453         return mlist;
454 }
455
456 std::vector<irr::video::E_DRIVER_TYPE> RenderingEngine::getSupportedVideoDrivers()
457 {
458         std::vector<irr::video::E_DRIVER_TYPE> drivers;
459
460         for (int i = 0; i != irr::video::EDT_COUNT; i++) {
461                 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
462                         drivers.push_back((irr::video::E_DRIVER_TYPE)i);
463         }
464
465         return drivers;
466 }
467
468 void RenderingEngine::_initialize(Client *client, Hud *hud)
469 {
470         const std::string &draw_mode = g_settings->get("3d_mode");
471         core.reset(createRenderingCore(draw_mode, m_device, client, hud));
472         core->initialize();
473 }
474
475 void RenderingEngine::_finalize()
476 {
477         core.reset();
478 }
479
480 void RenderingEngine::_draw_scene(video::SColor skycolor, bool show_hud,
481                 bool show_minimap, bool draw_wield_tool, bool draw_crosshair)
482 {
483         core->draw(skycolor, show_hud, show_minimap, draw_wield_tool, draw_crosshair);
484 }
485
486 const char *RenderingEngine::getVideoDriverName(irr::video::E_DRIVER_TYPE type)
487 {
488         static const char *driver_ids[] = {
489                         "null",
490                         "software",
491                         "burningsvideo",
492                         "direct3d8",
493                         "direct3d9",
494                         "opengl",
495                         "ogles1",
496                         "ogles2",
497         };
498
499         return driver_ids[type];
500 }
501
502 const char *RenderingEngine::getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
503 {
504         static const char *driver_names[] = {
505                         "NULL Driver",
506                         "Software Renderer",
507                         "Burning's Video",
508                         "Direct3D 8",
509                         "Direct3D 9",
510                         "OpenGL",
511                         "OpenGL ES1",
512                         "OpenGL ES2",
513         };
514
515         return driver_names[type];
516 }
517
518 #ifndef __ANDROID__
519 #ifdef XORG_USED
520
521 static float calcDisplayDensity()
522 {
523         const char *current_display = getenv("DISPLAY");
524
525         if (current_display != NULL) {
526                 Display *x11display = XOpenDisplay(current_display);
527
528                 if (x11display != NULL) {
529                         /* try x direct */
530                         float dpi_height = floor(
531                                         DisplayHeight(x11display, 0) /
532                                                         (DisplayHeightMM(x11display, 0) *
533                                                                         0.039370) +
534                                         0.5);
535                         float dpi_width = floor(
536                                         DisplayWidth(x11display, 0) /
537                                                         (DisplayWidthMM(x11display, 0) *
538                                                                         0.039370) +
539                                         0.5);
540
541                         XCloseDisplay(x11display);
542
543                         return std::max(dpi_height, dpi_width) / 96.0;
544                 }
545         }
546
547         /* return manually specified dpi */
548         return g_settings->getFloat("screen_dpi") / 96.0;
549 }
550
551 float RenderingEngine::getDisplayDensity()
552 {
553         static float cached_display_density = calcDisplayDensity();
554         return cached_display_density;
555 }
556
557 #else  // XORG_USED
558 float RenderingEngine::getDisplayDensity()
559 {
560         return g_settings->getFloat("screen_dpi") / 96.0;
561 }
562 #endif // XORG_USED
563
564 v2u32 RenderingEngine::getDisplaySize()
565 {
566         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
567
568         core::dimension2d<u32> deskres =
569                         nulldevice->getVideoModeList()->getDesktopResolution();
570         nulldevice->drop();
571
572         return deskres;
573 }
574
575 #else // __ANDROID__
576 float RenderingEngine::getDisplayDensity()
577 {
578         return porting::getDisplayDensity();
579 }
580
581 v2u32 RenderingEngine::getDisplaySize()
582 {
583         return porting::getDisplaySize();
584 }
585 #endif // __ANDROID__