]> git.lizzy.rs Git - minetest.git/blob - src/porting.cpp
Use numeric indices and raw table access with LUA_REGISTRYINDEX
[minetest.git] / src / porting.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 /*
21         Random portability stuff
22
23         See comments in porting.h
24 */
25
26 #include "porting.h"
27
28 #if defined(__FreeBSD__)
29         #include <sys/types.h>
30         #include <sys/sysctl.h>
31 #elif defined(_WIN32)
32         #include <algorithm>
33 #endif
34 #if !defined(_WIN32)
35         #include <unistd.h>
36         #include <sys/utsname.h>
37 #endif
38 #if defined(__hpux)
39         #define _PSTAT64
40         #include <sys/pstat.h>
41 #endif
42 #if !defined(_WIN32) && !defined(__APPLE__) && \
43         !defined(__ANDROID__) && !defined(SERVER)
44         #define XORG_USED
45 #endif
46 #ifdef XORG_USED
47         #include <X11/Xlib.h>
48         #include <X11/Xutil.h>
49 #endif
50
51 #include "config.h"
52 #include "debug.h"
53 #include "filesys.h"
54 #include "log.h"
55 #include "util/string.h"
56 #include "settings.h"
57 #include <list>
58
59 namespace porting
60 {
61
62 /*
63         Signal handler (grabs Ctrl-C on POSIX systems)
64 */
65
66 bool g_killed = false;
67
68 bool * signal_handler_killstatus(void)
69 {
70         return &g_killed;
71 }
72
73 #if !defined(_WIN32) // POSIX
74         #include <signal.h>
75
76 void sigint_handler(int sig)
77 {
78         if(!g_killed) {
79                 dstream<<DTIME<<"INFO: sigint_handler(): "
80                                 <<"Ctrl-C pressed, shutting down."<<std::endl;
81
82                 // Comment out for less clutter when testing scripts
83                 /*dstream<<DTIME<<"INFO: sigint_handler(): "
84                                 <<"Printing debug stacks"<<std::endl;
85                 debug_stacks_print();*/
86
87                 g_killed = true;
88         } else {
89                 (void)signal(SIGINT, SIG_DFL);
90         }
91 }
92
93 void signal_handler_init(void)
94 {
95         (void)signal(SIGINT, sigint_handler);
96 }
97
98 #else // _WIN32
99         #include <signal.h>
100
101 BOOL WINAPI event_handler(DWORD sig)
102 {
103         switch (sig) {
104         case CTRL_C_EVENT:
105         case CTRL_CLOSE_EVENT:
106         case CTRL_LOGOFF_EVENT:
107         case CTRL_SHUTDOWN_EVENT:
108                 if (g_killed == false) {
109                         dstream << DTIME << "INFO: event_handler(): "
110                                 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
111                                 " shutting down." << std::endl;
112                         g_killed = true;
113                 } else {
114                         (void)signal(SIGINT, SIG_DFL);
115                 }
116                 break;
117         case CTRL_BREAK_EVENT:
118                 break;
119         }
120
121         return TRUE;
122 }
123
124 void signal_handler_init(void)
125 {
126         SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
127 }
128
129 #endif
130
131
132 /*
133         Path mangler
134 */
135
136 // Default to RUN_IN_PLACE style relative paths
137 std::string path_share = "..";
138 std::string path_user = "..";
139
140 std::string getDataPath(const char *subpath)
141 {
142         return path_share + DIR_DELIM + subpath;
143 }
144
145 void pathRemoveFile(char *path, char delim)
146 {
147         // Remove filename and path delimiter
148         int i;
149         for(i = strlen(path)-1; i>=0; i--)
150         {
151                 if(path[i] == delim)
152                         break;
153         }
154         path[i] = 0;
155 }
156
157 bool detectMSVCBuildDir(const std::string &path)
158 {
159         const char *ends[] = {
160                 "bin\\Release",
161                 "bin\\Debug",
162                 "bin\\Build",
163                 NULL
164         };
165         return (removeStringEnd(path, ends) != "");
166 }
167
168 std::string get_sysinfo()
169 {
170 #ifdef _WIN32
171         OSVERSIONINFO osvi;
172         std::ostringstream oss;
173         std::string tmp;
174         ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
175         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
176         GetVersionEx(&osvi);
177         tmp = osvi.szCSDVersion;
178         std::replace(tmp.begin(), tmp.end(), ' ', '_');
179
180         oss << "Windows/" << osvi.dwMajorVersion << "."
181                 << osvi.dwMinorVersion;
182         if (osvi.szCSDVersion[0])
183                 oss << "-" << tmp;
184         oss << " ";
185         #ifdef _WIN64
186         oss << "x86_64";
187         #else
188         BOOL is64 = FALSE;
189         if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
190                 oss << "x86_64"; // 32-bit app on 64-bit OS
191         else
192                 oss << "x86";
193         #endif
194
195         return oss.str();
196 #else
197         struct utsname osinfo;
198         uname(&osinfo);
199         return std::string(osinfo.sysname) + "/"
200                 + osinfo.release + " " + osinfo.machine;
201 #endif
202 }
203
204
205 bool getCurrentWorkingDir(char *buf, size_t len)
206 {
207 #ifdef _WIN32
208         DWORD ret = GetCurrentDirectory(len, buf);
209         return (ret != 0) && (ret <= len);
210 #else
211         return getcwd(buf, len);
212 #endif
213 }
214
215
216 bool getExecPathFromProcfs(char *buf, size_t buflen)
217 {
218 #ifndef _WIN32
219         buflen--;
220
221         ssize_t len;
222         if ((len = readlink("/proc/self/exe",     buf, buflen)) == -1 &&
223                 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
224                 (len = readlink("/proc/curproc/exe",  buf, buflen)) == -1)
225                 return false;
226
227         buf[len] = '\0';
228         return true;
229 #else
230         return false;
231 #endif
232 }
233
234 //// Windows
235 #if defined(_WIN32)
236
237 bool getCurrentExecPath(char *buf, size_t len)
238 {
239         DWORD written = GetModuleFileNameA(NULL, buf, len);
240         if (written == 0 || written == len)
241                 return false;
242
243         return true;
244 }
245
246
247 //// Linux
248 #elif defined(linux) || defined(__linux) || defined(__linux__)
249
250 bool getCurrentExecPath(char *buf, size_t len)
251 {
252         if (!getExecPathFromProcfs(buf, len))
253                 return false;
254
255         return true;
256 }
257
258
259 //// Mac OS X, Darwin
260 #elif defined(__APPLE__)
261
262 bool getCurrentExecPath(char *buf, size_t len)
263 {
264         uint32_t lenb = (uint32_t)len;
265         if (_NSGetExecutablePath(buf, &lenb) == -1)
266                 return false;
267
268         return true;
269 }
270
271
272 //// FreeBSD, NetBSD, DragonFlyBSD
273 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
274
275 bool getCurrentExecPath(char *buf, size_t len)
276 {
277         // Try getting path from procfs first, since valgrind
278         // doesn't work with the latter
279         if (getExecPathFromProcfs(buf, len))
280                 return true;
281
282         int mib[4];
283
284         mib[0] = CTL_KERN;
285         mib[1] = KERN_PROC;
286         mib[2] = KERN_PROC_PATHNAME;
287         mib[3] = -1;
288
289         if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
290                 return false;
291
292         return true;
293 }
294
295
296 //// Solaris
297 #elif defined(__sun) || defined(sun)
298
299 bool getCurrentExecPath(char *buf, size_t len)
300 {
301         const char *exec = getexecname();
302         if (exec == NULL)
303                 return false;
304
305         if (strlcpy(buf, exec, len) >= len)
306                 return false;
307
308         return true;
309 }
310
311
312 // HP-UX
313 #elif defined(__hpux)
314
315 bool getCurrentExecPath(char *buf, size_t len)
316 {
317         struct pst_status psts;
318
319         if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
320                 return false;
321
322         if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
323                 return false;
324
325         return true;
326 }
327
328
329 #else
330
331 bool getCurrentExecPath(char *buf, size_t len)
332 {
333         return false;
334 }
335
336 #endif
337
338
339 //// Windows
340 #if defined(_WIN32)
341
342 bool setSystemPaths()
343 {
344         char buf[BUFSIZ];
345
346         // Find path of executable and set path_share relative to it
347         FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
348                 "Failed to get current executable path");
349         pathRemoveFile(buf, '\\');
350
351         // Use ".\bin\.."
352         path_share = std::string(buf) + "\\..";
353
354         // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
355         DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
356         FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
357
358         path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
359         return true;
360 }
361
362
363 //// Linux
364 #elif defined(linux) || defined(__linux)
365
366 bool setSystemPaths()
367 {
368         char buf[BUFSIZ];
369
370         if (!getCurrentExecPath(buf, sizeof(buf))) {
371 #ifdef __ANDROID__
372                 errorstream << "Unable to read bindir "<< std::endl;
373 #else
374                 FATAL_ERROR("Unable to read bindir");
375 #endif
376                 return false;
377         }
378
379         pathRemoveFile(buf, '/');
380         std::string bindir(buf);
381
382         // Find share directory from these.
383         // It is identified by containing the subdirectory "builtin".
384         std::list<std::string> trylist;
385         std::string static_sharedir = STATIC_SHAREDIR;
386         if (static_sharedir != "" && static_sharedir != ".")
387                 trylist.push_back(static_sharedir);
388
389         trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
390                 DIR_DELIM + PROJECT_NAME);
391         trylist.push_back(bindir + DIR_DELIM "..");
392
393 #ifdef __ANDROID__
394         trylist.push_back(path_user);
395 #endif
396
397         for (std::list<std::string>::const_iterator
398                         i = trylist.begin(); i != trylist.end(); i++) {
399                 const std::string &trypath = *i;
400                 if (!fs::PathExists(trypath) ||
401                         !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
402                         dstream << "WARNING: system-wide share not found at \""
403                                         << trypath << "\""<< std::endl;
404                         continue;
405                 }
406
407                 // Warn if was not the first alternative
408                 if (i != trylist.begin()) {
409                         dstream << "WARNING: system-wide share found at \""
410                                         << trypath << "\"" << std::endl;
411                 }
412
413                 path_share = trypath;
414                 break;
415         }
416
417 #ifndef __ANDROID__
418         path_user = std::string(getenv("HOME")) + DIR_DELIM "."
419                 + PROJECT_NAME;
420 #endif
421
422         return true;
423 }
424
425
426 //// Mac OS X
427 #elif defined(__APPLE__)
428
429 bool setSystemPaths()
430 {
431         CFBundleRef main_bundle = CFBundleGetMainBundle();
432         CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
433         char path[PATH_MAX];
434         if (CFURLGetFileSystemRepresentation(resources_url,
435                         TRUE, (UInt8 *)path, PATH_MAX)) {
436                 path_share = std::string(path);
437         } else {
438                 dstream << "WARNING: Could not determine bundle resource path" << std::endl;
439         }
440         CFRelease(resources_url);
441
442         path_user = std::string(getenv("HOME"))
443                 + "/Library/Application Support/"
444                 + PROJECT_NAME;
445         return true;
446 }
447
448
449 #else
450
451 bool setSystemPaths()
452 {
453         path_share = STATIC_SHAREDIR;
454         path_user  = std::string(getenv("HOME")) + DIR_DELIM "."
455                 + lowercase(PROJECT_NAME);
456         return true;
457 }
458
459
460 #endif
461
462
463 void initializePaths()
464 {
465 #if RUN_IN_PLACE
466         char buf[BUFSIZ];
467
468         infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
469
470         bool success =
471                 getCurrentExecPath(buf, sizeof(buf)) ||
472                 getExecPathFromProcfs(buf, sizeof(buf));
473
474         if (success) {
475                 pathRemoveFile(buf, DIR_DELIM_CHAR);
476                 std::string execpath(buf);
477
478                 path_share = execpath + DIR_DELIM "..";
479                 path_user  = execpath + DIR_DELIM "..";
480
481                 if (detectMSVCBuildDir(execpath)) {
482                         path_share += DIR_DELIM "..";
483                         path_user  += DIR_DELIM "..";
484                 }
485         } else {
486                 errorstream << "Failed to get paths by executable location, "
487                         "trying cwd" << std::endl;
488
489                 if (!getCurrentWorkingDir(buf, sizeof(buf)))
490                         FATAL_ERROR("Ran out of methods to get paths");
491
492                 size_t cwdlen = strlen(buf);
493                 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
494                         cwdlen--;
495                         buf[cwdlen] = '\0';
496                 }
497
498                 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
499                         pathRemoveFile(buf, DIR_DELIM_CHAR);
500
501                 std::string execpath(buf);
502
503                 path_share = execpath;
504                 path_user  = execpath;
505         }
506
507 #else
508         infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
509
510         if (!setSystemPaths())
511                 errorstream << "Failed to get one or more system-wide path" << std::endl;
512
513 #endif
514
515         infostream << "Detected share path: " << path_share << std::endl;
516         infostream << "Detected user path: " << path_user << std::endl;
517 }
518
519
520
521 void setXorgClassHint(const video::SExposedVideoData &video_data,
522         const std::string &name)
523 {
524 #ifdef XORG_USED
525         if (video_data.OpenGLLinux.X11Display == NULL)
526                 return;
527
528         XClassHint *classhint = XAllocClassHint();
529         classhint->res_name  = (char *)name.c_str();
530         classhint->res_class = (char *)name.c_str();
531
532         XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
533                 video_data.OpenGLLinux.X11Window, classhint);
534         XFree(classhint);
535 #endif
536 }
537
538
539 ////
540 //// Video/Display Information (Client-only)
541 ////
542
543 #ifndef SERVER
544
545 static irr::IrrlichtDevice *device;
546
547 void initIrrlicht(irr::IrrlichtDevice *device_)
548 {
549         device = device_;
550 }
551
552 v2u32 getWindowSize()
553 {
554         return device->getVideoDriver()->getScreenSize();
555 }
556
557
558 std::vector<core::vector3d<u32> > getSupportedVideoModes()
559 {
560         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
561         sanity_check(nulldevice != NULL);
562
563         std::vector<core::vector3d<u32> > mlist;
564         video::IVideoModeList *modelist = nulldevice->getVideoModeList();
565
566         u32 num_modes = modelist->getVideoModeCount();
567         for (u32 i = 0; i != num_modes; i++) {
568                 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
569                 s32 mode_depth = modelist->getVideoModeDepth(i);
570                 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
571         }
572
573         nulldevice->drop();
574
575         return mlist;
576 }
577
578 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
579 {
580         std::vector<irr::video::E_DRIVER_TYPE> drivers;
581
582         for (int i = 0; i != irr::video::EDT_COUNT; i++) {
583                 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
584                         drivers.push_back((irr::video::E_DRIVER_TYPE)i);
585         }
586
587         return drivers;
588 }
589
590 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
591 {
592         static const char *driver_ids[] = {
593                 "null",
594                 "software",
595                 "burningsvideo",
596                 "direct3d8",
597                 "direct3d9",
598                 "opengl",
599                 "ogles1",
600                 "ogles2",
601         };
602
603         return driver_ids[type];
604 }
605
606
607 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
608 {
609         static const char *driver_names[] = {
610                 "NULL Driver",
611                 "Software Renderer",
612                 "Burning's Video",
613                 "Direct3D 8",
614                 "Direct3D 9",
615                 "OpenGL",
616                 "OpenGL ES1",
617                 "OpenGL ES2",
618         };
619
620         return driver_names[type];
621 }
622
623 #       ifndef __ANDROID__
624 #               ifdef XORG_USED
625
626 static float calcDisplayDensity()
627 {
628         const char *current_display = getenv("DISPLAY");
629
630         if (current_display != NULL) {
631                 Display *x11display = XOpenDisplay(current_display);
632
633                 if (x11display != NULL) {
634                         /* try x direct */
635                         float dpi_height = floor(DisplayHeight(x11display, 0) /
636                                                         (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
637                         float dpi_width = floor(DisplayWidth(x11display, 0) /
638                                                         (DisplayWidthMM(x11display, 0) * 0.039370) + 0.5);
639
640                         XCloseDisplay(x11display);
641
642                         return std::max(dpi_height,dpi_width) / 96.0;
643                 }
644         }
645
646         /* return manually specified dpi */
647         return g_settings->getFloat("screen_dpi")/96.0;
648 }
649
650
651 float getDisplayDensity()
652 {
653         static float cached_display_density = calcDisplayDensity();
654         return cached_display_density;
655 }
656
657
658 #               else // XORG_USED
659 float getDisplayDensity()
660 {
661         return g_settings->getFloat("screen_dpi")/96.0;
662 }
663 #               endif // XORG_USED
664
665 v2u32 getDisplaySize()
666 {
667         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
668
669         core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
670         nulldevice -> drop();
671
672         return deskres;
673 }
674 #       endif // __ANDROID__
675 #endif // SERVER
676
677 } //namespace porting
678