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>
39 #if !defined(_WIN32) && !defined(__APPLE__) && \
40 !defined(__ANDROID__) && !defined(SERVER)
46 #include <X11/Xutil.h>
53 #include "util/string.h"
62 Signal handler (grabs Ctrl-C on POSIX systems)
65 bool g_killed = false;
67 bool * signal_handler_killstatus(void)
72 #if !defined(_WIN32) // POSIX
75 void sigint_handler(int sig)
79 dstream<<DTIME<<"INFO: sigint_handler(): "
80 <<"Ctrl-C pressed, shutting down."<<std::endl;
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();*/
91 (void)signal(SIGINT, SIG_DFL);
95 void signal_handler_init(void)
97 (void)signal(SIGINT, sigint_handler);
103 BOOL WINAPI event_handler(DWORD sig)
108 case CTRL_CLOSE_EVENT:
109 case CTRL_LOGOFF_EVENT:
110 case CTRL_SHUTDOWN_EVENT:
112 if(g_killed == false)
114 dstream<<DTIME<<"INFO: event_handler(): "
115 <<"Ctrl+C, Close Event, Logoff Event or Shutdown Event, shutting down."<<std::endl;
116 // Comment out for less clutter when testing scripts
117 /*dstream<<DTIME<<"INFO: event_handler(): "
118 <<"Printing debug stacks"<<std::endl;
119 debug_stacks_print();*/
125 (void)signal(SIGINT, SIG_DFL);
129 case CTRL_BREAK_EVENT:
136 void signal_handler_init(void)
138 SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE);
145 Multithreading support
147 int getNumberOfProcessors() {
148 #if defined(_SC_NPROCESSORS_ONLN)
150 return sysconf(_SC_NPROCESSORS_ONLN);
152 #elif defined(__FreeBSD__) || defined(__APPLE__)
154 unsigned int len, count;
156 return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
158 #elif defined(_GNU_SOURCE)
162 #elif defined(_WIN32)
165 GetSystemInfo(&sysinfo);
166 return sysinfo.dwNumberOfProcessors;
168 #elif defined(PTW32_VERSION) || defined(__hpux)
170 return pthread_num_processors_np();
181 bool threadBindToProcessor(threadid_t tid, int pnumber) {
184 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
188 bool success = SetThreadAffinityMask(hThread, 1 << pnumber) != 0;
190 CloseHandle(hThread);
193 #elif (defined(__FreeBSD__) && (__FreeBSD_version >= 702106)) \
194 || defined(__linux) || defined(linux)
199 CPU_SET(pnumber, &cpuset);
200 return pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset) == 0;
202 #elif defined(__sun) || defined(sun)
204 return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid),
209 return bindprocessor(BINDTHREAD, (tid_t)tid, pnumber) == 0;
211 #elif defined(__hpux) || defined(hpux)
213 pthread_spu_t answer;
215 return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
216 &answer, pnumber, tid) == 0;
218 #elif defined(__APPLE__)
220 struct thread_affinity_policy tapol;
222 thread_port_t threadport = pthread_mach_thread_np(tid);
223 tapol.affinity_tag = pnumber + 1;
224 return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
225 (thread_policy_t)&tapol, THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;
235 bool threadSetPriority(threadid_t tid, int prio) {
238 HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
242 bool success = SetThreadPriority(hThread, prio) != 0;
244 CloseHandle(hThread);
249 struct sched_param sparam;
252 if (pthread_getschedparam(tid, &policy, &sparam) != 0)
255 int min = sched_get_priority_min(policy);
256 int max = sched_get_priority_max(policy);
258 sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
259 return pthread_setschedparam(tid, policy, &sparam) == 0;
269 // Default to RUN_IN_PLACE style relative paths
270 std::string path_share = "..";
271 std::string path_user = "..";
273 std::string getDataPath(const char *subpath)
275 return path_share + DIR_DELIM + subpath;
278 void pathRemoveFile(char *path, char delim)
280 // Remove filename and path delimiter
282 for(i = strlen(path)-1; i>=0; i--)
290 bool detectMSVCBuildDir(char *c_path)
292 std::string path(c_path);
293 const char *ends[] = {"bin\\Release", "bin\\Build", NULL};
294 return (removeStringEnd(path, ends) != "");
297 std::string get_sysinfo()
301 std::ostringstream oss;
303 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
304 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
306 tmp = osvi.szCSDVersion;
307 std::replace(tmp.begin(), tmp.end(), ' ', '_');
309 oss << "Windows/" << osvi.dwMajorVersion << "."
310 << osvi.dwMinorVersion;
311 if(osvi.szCSDVersion[0])
318 if(IsWow64Process(GetCurrentProcess(), &is64) && is64)
319 oss << "x86_64"; // 32-bit app on 64-bit OS
326 struct utsname osinfo;
328 return std::string(osinfo.sysname) + "/"
329 + osinfo.release + " " + osinfo.machine;
333 void initializePaths()
337 Use relative paths if RUN_IN_PLACE
340 infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;
347 const DWORD buflen = 1000;
351 // Find path of executable and set path_share relative to it
352 len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
353 assert(len < buflen);
354 pathRemoveFile(buf, '\\');
356 if(detectMSVCBuildDir(buf)){
357 infostream<<"MSVC build directory detected"<<std::endl;
358 path_share = std::string(buf) + "\\..\\..";
359 path_user = std::string(buf) + "\\..\\..";
362 path_share = std::string(buf) + "\\..";
363 path_user = std::string(buf) + "\\..";
372 memset(buf, 0, BUFSIZ);
373 // Get path to executable
374 assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
376 pathRemoveFile(buf, '/');
378 path_share = std::string(buf) + "/..";
379 path_user = std::string(buf) + "/..";
384 #elif defined(__APPLE__)
386 //https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dyld.3.html
387 //TODO: Test this code
389 uint32_t len = sizeof(buf);
390 assert(_NSGetExecutablePath(buf, &len) != -1);
392 pathRemoveFile(buf, '/');
394 path_share = std::string(buf) + "/..";
395 path_user = std::string(buf) + "/..";
400 #elif defined(__FreeBSD__)
404 size_t len = sizeof(buf);
408 mib[2] = KERN_PROC_PATHNAME;
410 assert(sysctl(mib, 4, buf, &len, NULL, 0) != -1);
412 pathRemoveFile(buf, '/');
414 path_share = std::string(buf) + "/..";
415 path_user = std::string(buf) + "/..";
419 //TODO: Get path of executable. This assumes working directory is bin/
420 dstream<<"WARNING: Relative path not properly supported on this platform"
423 /* scriptapi no longer allows paths that start with "..", so assuming that
424 the current working directory is bin/, strip off the last component. */
425 char *cwd = getcwd(NULL, 0);
426 pathRemoveFile(cwd, '/');
427 path_share = std::string(cwd);
428 path_user = std::string(cwd);
432 #else // RUN_IN_PLACE
435 Use platform-specific paths otherwise
438 infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;
445 const DWORD buflen = 1000;
449 // Find path of executable and set path_share relative to it
450 len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
451 assert(len < buflen);
452 pathRemoveFile(buf, '\\');
455 path_share = std::string(buf) + "\\..";
457 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
458 len = GetEnvironmentVariable("APPDATA", buf, buflen);
459 assert(len < buflen);
460 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
467 // Get path to executable
468 std::string bindir = "";
471 memset(buf, 0, BUFSIZ);
472 if (readlink("/proc/self/exe", buf, BUFSIZ-1) == -1) {
473 errorstream << "Unable to read bindir "<< std::endl;
475 assert("Unable to read bindir" == 0);
478 pathRemoveFile(buf, '/');
483 // Find share directory from these.
484 // It is identified by containing the subdirectory "builtin".
485 std::list<std::string> trylist;
486 std::string static_sharedir = STATIC_SHAREDIR;
487 if(static_sharedir != "" && static_sharedir != ".")
488 trylist.push_back(static_sharedir);
490 bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + PROJECT_NAME);
491 trylist.push_back(bindir + DIR_DELIM + "..");
493 trylist.push_back(path_user);
496 for(std::list<std::string>::const_iterator i = trylist.begin();
497 i != trylist.end(); i++)
499 const std::string &trypath = *i;
500 if(!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")){
501 dstream<<"WARNING: system-wide share not found at \""
502 <<trypath<<"\""<<std::endl;
505 // Warn if was not the first alternative
506 if(i != trylist.begin()){
507 dstream<<"WARNING: system-wide share found at \""
508 <<trypath<<"\""<<std::endl;
510 path_share = trypath;
514 path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
520 #elif defined(__APPLE__)
523 // http://stackoverflow.com/questions/516200/relative-paths-not-working-in-xcode-c
524 CFBundleRef main_bundle = CFBundleGetMainBundle();
525 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
527 if(CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX))
529 dstream<<"Bundle resource path: "<<path<<std::endl;
531 path_share = std::string(path) + DIR_DELIM + STATIC_SHAREDIR;
536 dstream<<"WARNING: Could not determine bundle resource path"<<std::endl;
538 CFRelease(resources_url);
540 path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + PROJECT_NAME;
542 #else // FreeBSD, and probably many other POSIX-like systems.
544 path_share = STATIC_SHAREDIR;
545 path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
549 #endif // RUN_IN_PLACE
552 static irr::IrrlichtDevice* device;
554 void initIrrlicht(irr::IrrlichtDevice * _device) {
558 void setXorgClassHint(const video::SExposedVideoData &video_data,
559 const std::string &name)
562 XClassHint *classhint = XAllocClassHint();
563 classhint->res_name = (char *)name.c_str();
564 classhint->res_class = (char *)name.c_str();
566 XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
567 video_data.OpenGLLinux.X11Window, classhint);
573 v2u32 getWindowSize()
575 return device->getVideoDriver()->getScreenSize();
580 float getDisplayDensity()
582 const char* current_display = getenv("DISPLAY");
584 if (current_display != NULL) {
585 Display * x11display = XOpenDisplay(current_display);
587 if (x11display != NULL) {
590 floor(DisplayHeight(x11display, 0) /
591 (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
593 floor(DisplayWidth(x11display, 0) /
594 (DisplayWidthMM(x11display, 0) * 0.039370) +0.5);
596 XCloseDisplay(x11display);
598 return (std::max(dpi_height,dpi_width) / 96.0);
602 /* return manually specified dpi */
603 return g_settings->getFloat("screen_dpi")/96.0;
607 float getDisplayDensity()
609 return g_settings->getFloat("screen_dpi")/96.0;
613 v2u32 getDisplaySize()
615 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
617 core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
618 nulldevice -> drop();
625 } //namespace porting