3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
21 Random portability stuff
23 See comments in porting.h
28 #if defined(__FreeBSD__)
29 #include <sys/types.h>
30 #include <sys/sysctl.h>
36 #include <sys/utsname.h>
40 #include <sys/pstat.h>
42 #if !defined(_WIN32) && !defined(__APPLE__) && \
43 !defined(__ANDROID__) && !defined(SERVER)
48 #include <X11/Xutil.h>
55 #include "util/string.h"
63 Signal handler (grabs Ctrl-C on POSIX systems)
66 bool g_killed = false;
68 bool * signal_handler_killstatus(void)
73 #if !defined(_WIN32) // POSIX
76 void sigint_handler(int sig)
80 dstream<<DTIME<<"INFO: sigint_handler(): "
81 <<"Ctrl-C pressed, shutting down."<<std::endl;
83 // Comment out for less clutter when testing scripts
84 /*dstream<<DTIME<<"INFO: sigint_handler(): "
85 <<"Printing debug stacks"<<std::endl;
86 debug_stacks_print();*/
92 (void)signal(SIGINT, SIG_DFL);
96 void signal_handler_init(void)
98 (void)signal(SIGINT, sigint_handler);
104 BOOL WINAPI event_handler(DWORD sig)
108 case CTRL_CLOSE_EVENT:
109 case CTRL_LOGOFF_EVENT:
110 case CTRL_SHUTDOWN_EVENT:
111 if (g_killed == false) {
112 dstream << DTIME << "INFO: event_handler(): "
113 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
114 " shutting down." << std::endl;
117 (void)signal(SIGINT, SIG_DFL);
120 case CTRL_BREAK_EVENT:
127 void signal_handler_init(void)
129 SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE);
136 Multithreading support
138 int getNumberOfProcessors()
140 #if defined(_SC_NPROCESSORS_ONLN)
142 return sysconf(_SC_NPROCESSORS_ONLN);
144 #elif defined(__FreeBSD__) || defined(__APPLE__)
146 unsigned int len, count;
148 return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
150 #elif defined(_GNU_SOURCE)
154 #elif defined(_WIN32)
157 GetSystemInfo(&sysinfo);
158 return sysinfo.dwNumberOfProcessors;
160 #elif defined(PTW32_VERSION) || defined(__hpux)
162 return pthread_num_processors_np();
173 bool threadBindToProcessor(threadid_t tid, int pnumber)
177 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
181 bool success = SetThreadAffinityMask(hThread, 1 << pnumber) != 0;
183 CloseHandle(hThread);
186 #elif (defined(__FreeBSD__) && (__FreeBSD_version >= 702106)) \
187 || defined(__linux) || defined(linux)
192 CPU_SET(pnumber, &cpuset);
193 return pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset) == 0;
195 #elif defined(__sun) || defined(sun)
197 return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid),
202 return bindprocessor(BINDTHREAD, (tid_t)tid, pnumber) == 0;
204 #elif defined(__hpux) || defined(hpux)
206 pthread_spu_t answer;
208 return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
209 &answer, pnumber, tid) == 0;
211 #elif defined(__APPLE__)
213 struct thread_affinity_policy tapol;
215 thread_port_t threadport = pthread_mach_thread_np(tid);
216 tapol.affinity_tag = pnumber + 1;
217 return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
218 (thread_policy_t)&tapol, THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;
228 bool threadSetPriority(threadid_t tid, int prio)
232 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
236 bool success = SetThreadPriority(hThread, prio) != 0;
238 CloseHandle(hThread);
243 struct sched_param sparam;
246 if (pthread_getschedparam(tid, &policy, &sparam) != 0)
249 int min = sched_get_priority_min(policy);
250 int max = sched_get_priority_max(policy);
252 sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
253 return pthread_setschedparam(tid, policy, &sparam) == 0;
263 // Default to RUN_IN_PLACE style relative paths
264 std::string path_share = "..";
265 std::string path_user = "..";
267 std::string getDataPath(const char *subpath)
269 return path_share + DIR_DELIM + subpath;
272 void pathRemoveFile(char *path, char delim)
274 // Remove filename and path delimiter
276 for(i = strlen(path)-1; i>=0; i--)
284 bool detectMSVCBuildDir(const std::string &path)
286 const char *ends[] = {
292 return (removeStringEnd(path, ends) != "");
295 std::string get_sysinfo()
299 std::ostringstream oss;
301 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
302 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
304 tmp = osvi.szCSDVersion;
305 std::replace(tmp.begin(), tmp.end(), ' ', '_');
307 oss << "Windows/" << osvi.dwMajorVersion << "."
308 << osvi.dwMinorVersion;
309 if(osvi.szCSDVersion[0])
316 if(IsWow64Process(GetCurrentProcess(), &is64) && is64)
317 oss << "x86_64"; // 32-bit app on 64-bit OS
324 struct utsname osinfo;
326 return std::string(osinfo.sysname) + "/"
327 + osinfo.release + " " + osinfo.machine;
332 bool getCurrentWorkingDir(char *buf, size_t len)
335 DWORD ret = GetCurrentDirectory(len, buf);
336 return (ret != 0) && (ret <= len);
338 return getcwd(buf, len);
343 bool getExecPathFromProcfs(char *buf, size_t buflen)
349 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
350 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
351 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
364 bool getCurrentExecPath(char *buf, size_t len)
366 DWORD written = GetModuleFileNameA(NULL, buf, len);
367 if (written == 0 || written == len)
375 #elif defined(linux) || defined(__linux) || defined(__linux__)
377 bool getCurrentExecPath(char *buf, size_t len)
379 if (!getExecPathFromProcfs(buf, len))
386 //// Mac OS X, Darwin
387 #elif defined(__APPLE__)
389 bool getCurrentExecPath(char *buf, size_t len)
391 if (_NSGetExecutablePath(buf, &len) == -1)
398 //// FreeBSD, NetBSD, DragonFlyBSD
399 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
401 bool getCurrentExecPath(char *buf, size_t len)
403 // Try getting path from procfs first, since valgrind
404 // doesn't work with the latter
405 if (getExecPathFromProcfs(buf, len))
412 mib[2] = KERN_PROC_PATHNAME;
415 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
423 #elif defined(__sun) || defined(sun)
425 bool getCurrentExecPath(char *buf, size_t len)
427 const char *exec = getexecname();
431 if (strlcpy(buf, exec, len) >= len)
439 #elif defined(__hpux)
441 bool getCurrentExecPath(char *buf, size_t len)
443 struct pst_status psts;
445 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
448 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
457 bool getCurrentExecPath(char *buf, size_t len)
468 bool setSystemPaths()
472 // Find path of executable and set path_share relative to it
473 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
474 "Failed to get current executable path");
475 pathRemoveFile(buf, '\\');
478 path_share = std::string(buf) + "\\..";
480 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
481 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
482 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
484 path_user = std::string(buf) + DIR_DELIM + lowercase(PROJECT_NAME);
490 #elif defined(linux) || defined(__linux)
492 bool setSystemPaths()
496 if (!getCurrentExecPath(buf, sizeof(buf))) {
498 errorstream << "Unable to read bindir "<< std::endl;
500 FATAL_ERROR("Unable to read bindir");
505 pathRemoveFile(buf, '/');
506 std::string bindir(buf);
508 // Find share directory from these.
509 // It is identified by containing the subdirectory "builtin".
510 std::list<std::string> trylist;
511 std::string static_sharedir = STATIC_SHAREDIR;
512 if (static_sharedir != "" && static_sharedir != ".")
513 trylist.push_back(static_sharedir);
515 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
516 DIR_DELIM + lowercase(PROJECT_NAME));
517 trylist.push_back(bindir + DIR_DELIM "..");
520 trylist.push_back(path_user);
523 for (std::list<std::string>::const_iterator
524 i = trylist.begin(); i != trylist.end(); i++) {
525 const std::string &trypath = *i;
526 if (!fs::PathExists(trypath) ||
527 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
528 dstream << "WARNING: system-wide share not found at \""
529 << trypath << "\""<< std::endl;
533 // Warn if was not the first alternative
534 if (i != trylist.begin()) {
535 dstream << "WARNING: system-wide share found at \""
536 << trypath << "\"" << std::endl;
539 path_share = trypath;
544 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
545 + lowercase(PROJECT_NAME);
553 #elif defined(__APPLE__)
555 bool setSystemPaths()
557 CFBundleRef main_bundle = CFBundleGetMainBundle();
558 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
560 if (CFURLGetFileSystemRepresentation(resources_url,
561 TRUE, (UInt8 *)path, PATH_MAX)) {
562 path_share = std::string(path);
564 dstream << "WARNING: Could not determine bundle resource path" << std::endl;
566 CFRelease(resources_url);
568 path_user = std::string(getenv("HOME"))
569 + "/Library/Application Support/"
570 + lowercase(PROJECT_NAME);
577 bool setSystemPaths()
579 path_share = STATIC_SHAREDIR;
580 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
581 + lowercase(PROJECT_NAME);
589 void initializePaths()
594 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
597 getCurrentExecPath(buf, sizeof(buf)) ||
598 getExecPathFromProcfs(buf, sizeof(buf));
601 pathRemoveFile(buf, '/');
602 std::string execpath(buf);
604 path_share = execpath + DIR_DELIM "..";
605 path_user = execpath + DIR_DELIM "..";
607 if (detectMSVCBuildDir(execpath)) {
608 path_share += DIR_DELIM "..";
609 path_user += DIR_DELIM "..";
612 errorstream << "Failed to get paths by executable location, "
613 "trying cwd" << std::endl;
615 if (!getCurrentWorkingDir(buf, sizeof(buf)))
616 FATAL_ERROR("Ran out of methods to get paths");
618 size_t cwdlen = strlen(buf);
619 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
624 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
625 pathRemoveFile(buf, DIR_DELIM_CHAR);
627 std::string execpath(buf);
629 path_share = execpath;
630 path_user = execpath;
634 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
636 if (!setSystemPaths())
637 errorstream << "Failed to get one or more system-wide path" << std::endl;
641 infostream << "Detected share path: " << path_share << std::endl;
642 infostream << "Detected user path: " << path_user << std::endl;
647 void setXorgClassHint(const video::SExposedVideoData &video_data,
648 const std::string &name)
651 if (video_data.OpenGLLinux.X11Display == NULL)
654 XClassHint *classhint = XAllocClassHint();
655 classhint->res_name = (char *)name.c_str();
656 classhint->res_class = (char *)name.c_str();
658 XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
659 video_data.OpenGLLinux.X11Window, classhint);
666 //// Video/Display Information (Client-only)
671 static irr::IrrlichtDevice *device;
673 void initIrrlicht(irr::IrrlichtDevice *device_)
678 v2u32 getWindowSize()
680 return device->getVideoDriver()->getScreenSize();
684 std::vector<core::vector3d<u32> > getSupportedVideoModes()
686 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
687 sanity_check(nulldevice != NULL);
689 std::vector<core::vector3d<u32> > mlist;
690 video::IVideoModeList *modelist = nulldevice->getVideoModeList();
692 u32 num_modes = modelist->getVideoModeCount();
693 for (u32 i = 0; i != num_modes; i++) {
694 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
695 s32 mode_depth = modelist->getVideoModeDepth(i);
696 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
704 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
706 std::vector<irr::video::E_DRIVER_TYPE> drivers;
708 for (int i = 0; i != irr::video::EDT_COUNT; i++) {
709 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
710 drivers.push_back((irr::video::E_DRIVER_TYPE)i);
716 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
718 static const char *driver_ids[] = {
729 return driver_ids[type];
733 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
735 static const char *driver_names[] = {
746 return driver_names[type];
752 static float calcDisplayDensity()
754 const char* current_display = getenv("DISPLAY");
756 if (current_display != NULL) {
757 Display * x11display = XOpenDisplay(current_display);
759 if (x11display != NULL) {
762 floor(DisplayHeight(x11display, 0) /
763 (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
765 floor(DisplayWidth(x11display, 0) /
766 (DisplayWidthMM(x11display, 0) * 0.039370) +0.5);
768 XCloseDisplay(x11display);
770 return std::max(dpi_height,dpi_width) / 96.0;
774 /* return manually specified dpi */
775 return g_settings->getFloat("screen_dpi")/96.0;
779 float getDisplayDensity()
781 static float cached_display_density = calcDisplayDensity();
782 return cached_display_density;
787 float getDisplayDensity()
789 return g_settings->getFloat("screen_dpi")/96.0;
793 v2u32 getDisplaySize()
795 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
797 core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
798 nulldevice -> drop();
802 # endif // __ANDROID__
805 } //namespace porting