]> git.lizzy.rs Git - minetest.git/blob - src/porting.cpp
d1e3cdd70d39444c589b3441168195fa98a5aba9
[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(__APPLE__)
29         #include <mach-o/dyld.h>
30         #include "CoreFoundation/CoreFoundation.h"
31 #elif defined(__FreeBSD__)
32         #include <sys/types.h>
33         #include <sys/sysctl.h>
34 #elif defined(_WIN32)
35         #include <algorithm>
36 #endif
37 #if !defined(_WIN32)
38         #include <unistd.h>
39         #include <sys/utsname.h>
40 #endif
41
42 #include "config.h"
43 #include "debug.h"
44 #include "filesys.h"
45 #include "log.h"
46 #include "util/string.h"
47 #include "main.h"
48 #include "settings.h"
49 #include <list>
50
51 namespace porting
52 {
53
54 /*
55         Signal handler (grabs Ctrl-C on POSIX systems)
56 */
57
58 bool g_killed = false;
59
60 bool * signal_handler_killstatus(void)
61 {
62         return &g_killed;
63 }
64
65 #if !defined(_WIN32) // POSIX
66         #include <signal.h>
67
68 void sigint_handler(int sig)
69 {
70         if(g_killed == false)
71         {
72                 dstream<<DTIME<<"INFO: sigint_handler(): "
73                                 <<"Ctrl-C pressed, shutting down."<<std::endl;
74
75                 // Comment out for less clutter when testing scripts
76                 /*dstream<<DTIME<<"INFO: sigint_handler(): "
77                                 <<"Printing debug stacks"<<std::endl;
78                 debug_stacks_print();*/
79
80                 g_killed = true;
81         }
82         else
83         {
84                 (void)signal(SIGINT, SIG_DFL);
85         }
86 }
87
88 void signal_handler_init(void)
89 {
90         (void)signal(SIGINT, sigint_handler);
91 }
92
93 #else // _WIN32
94         #include <signal.h>
95
96         BOOL WINAPI event_handler(DWORD sig)
97         {
98                 switch(sig)
99                 {
100                 case CTRL_C_EVENT:
101                 case CTRL_CLOSE_EVENT:
102                 case CTRL_LOGOFF_EVENT:
103                 case CTRL_SHUTDOWN_EVENT:
104
105                         if(g_killed == false)
106                         {
107                                 dstream<<DTIME<<"INFO: event_handler(): "
108                                                 <<"Ctrl+C, Close Event, Logoff Event or Shutdown Event, shutting down."<<std::endl;
109                                 // Comment out for less clutter when testing scripts
110                                 /*dstream<<DTIME<<"INFO: event_handler(): "
111                                                 <<"Printing debug stacks"<<std::endl;
112                                 debug_stacks_print();*/
113
114                                 g_killed = true;
115                         }
116                         else
117                         {
118                                 (void)signal(SIGINT, SIG_DFL);
119                         }
120
121                         break;
122                 case CTRL_BREAK_EVENT:
123                         break;
124                 }
125
126                 return TRUE;
127         }
128
129 void signal_handler_init(void)
130 {
131         SetConsoleCtrlHandler( (PHANDLER_ROUTINE)event_handler,TRUE);
132 }
133
134 #endif
135
136
137 /*
138         Multithreading support
139 */
140 int getNumberOfProcessors() {
141 #if defined(_SC_NPROCESSORS_ONLN)
142
143         return sysconf(_SC_NPROCESSORS_ONLN);
144
145 #elif defined(__FreeBSD__) || defined(__APPLE__)
146
147         unsigned int len, count;
148         len = sizeof(count);
149         return sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
150
151 #elif defined(_GNU_SOURCE)
152
153         return get_nprocs();
154
155 #elif defined(_WIN32)
156
157         SYSTEM_INFO sysinfo;
158         GetSystemInfo(&sysinfo);
159         return sysinfo.dwNumberOfProcessors;
160
161 #elif defined(PTW32_VERSION) || defined(__hpux)
162
163         return pthread_num_processors_np();
164
165 #else
166
167         return 1;
168
169 #endif
170 }
171
172
173 bool threadBindToProcessor(threadid_t tid, int pnumber) {
174 #if defined(_WIN32)
175
176         HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
177         if (!hThread)
178                 return false;
179
180         bool success = SetThreadAffinityMask(hThread, 1 << pnumber) != 0;
181
182         CloseHandle(hThread);
183         return success;
184
185 #elif (defined(__FreeBSD__) && (__FreeBSD_version >= 702106)) \
186         || defined(__linux) || defined(linux)
187
188         cpu_set_t cpuset;
189
190         CPU_ZERO(&cpuset);
191         CPU_SET(pnumber, &cpuset);
192         return pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset) == 0;
193
194 #elif defined(__sun) || defined(sun)
195
196         return processor_bind(P_LWPID, MAKE_LWPID_PTHREAD(tid),
197                                                 pnumber, NULL) == 0;
198
199 #elif defined(_AIX)
200         
201         return bindprocessor(BINDTHREAD, (tid_t)tid, pnumber) == 0;
202
203 #elif defined(__hpux) || defined(hpux)
204
205         pthread_spu_t answer;
206
207         return pthread_processor_bind_np(PTHREAD_BIND_ADVISORY_NP,
208                                                                         &answer, pnumber, tid) == 0;
209         
210 #elif defined(__APPLE__)
211
212         struct thread_affinity_policy tapol;
213         
214         thread_port_t threadport = pthread_mach_thread_np(tid);
215         tapol.affinity_tag = pnumber + 1;
216         return thread_policy_set(threadport, THREAD_AFFINITY_POLICY,
217                         (thread_policy_t)&tapol, THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS;
218
219 #else
220
221         return false;
222
223 #endif
224 }
225
226
227 bool threadSetPriority(threadid_t tid, int prio) {
228 #if defined(_WIN32)
229
230         HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, 0, tid);
231         if (!hThread)
232                 return false;
233
234         bool success = SetThreadPriority(hThread, prio) != 0;
235
236         CloseHandle(hThread);
237         return success;
238         
239 #else
240
241         struct sched_param sparam;
242         int policy;
243         
244         if (pthread_getschedparam(tid, &policy, &sparam) != 0)
245                 return false;
246                 
247         int min = sched_get_priority_min(policy);
248         int max = sched_get_priority_max(policy);
249
250         sparam.sched_priority = min + prio * (max - min) / THREAD_PRIORITY_HIGHEST;
251         return pthread_setschedparam(tid, policy, &sparam) == 0;
252         
253 #endif
254 }
255
256
257 /*
258         Path mangler
259 */
260
261 // Default to RUN_IN_PLACE style relative paths
262 std::string path_share = "..";
263 std::string path_user = "..";
264
265 std::string getDataPath(const char *subpath)
266 {
267         return path_share + DIR_DELIM + subpath;
268 }
269
270 void pathRemoveFile(char *path, char delim)
271 {
272         // Remove filename and path delimiter
273         int i;
274         for(i = strlen(path)-1; i>=0; i--)
275         {
276                 if(path[i] == delim)
277                         break;
278         }
279         path[i] = 0;
280 }
281
282 bool detectMSVCBuildDir(char *c_path)
283 {
284         std::string path(c_path);
285         const char *ends[] = {"bin\\Release", "bin\\Build", NULL};
286         return (removeStringEnd(path, ends) != "");
287 }
288
289 std::string get_sysinfo()
290 {
291 #ifdef _WIN32
292         OSVERSIONINFO osvi;
293         std::ostringstream oss;
294         std::string tmp;
295         ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
296         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
297         GetVersionEx(&osvi);
298         tmp = osvi.szCSDVersion;
299         std::replace(tmp.begin(), tmp.end(), ' ', '_');
300
301         oss << "Windows/" << osvi.dwMajorVersion << "."
302                 << osvi.dwMinorVersion;
303         if(osvi.szCSDVersion[0])
304                 oss << "-" << tmp;
305         oss << " ";
306         #ifdef _WIN64
307         oss << "x86_64";
308         #else
309         BOOL is64 = FALSE;
310         if(IsWow64Process(GetCurrentProcess(), &is64) && is64)
311                 oss << "x86_64"; // 32-bit app on 64-bit OS
312         else
313                 oss << "x86";
314         #endif
315
316         return oss.str();
317 #else
318         struct utsname osinfo;
319         uname(&osinfo);
320         return std::string(osinfo.sysname) + "/"
321                 + osinfo.release + " " + osinfo.machine;
322 #endif
323 }
324
325 void initializePaths()
326 {
327 #if RUN_IN_PLACE
328         /*
329                 Use relative paths if RUN_IN_PLACE
330         */
331
332         infostream<<"Using relative paths (RUN_IN_PLACE)"<<std::endl;
333
334         /*
335                 Windows
336         */
337         #if defined(_WIN32)
338
339         const DWORD buflen = 1000;
340         char buf[buflen];
341         DWORD len;
342
343         // Find path of executable and set path_share relative to it
344         len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
345         assert(len < buflen);
346         pathRemoveFile(buf, '\\');
347
348         if(detectMSVCBuildDir(buf)){
349                 infostream<<"MSVC build directory detected"<<std::endl;
350                 path_share = std::string(buf) + "\\..\\..";
351                 path_user = std::string(buf) + "\\..\\..";
352         }
353         else{
354                 path_share = std::string(buf) + "\\..";
355                 path_user = std::string(buf) + "\\..";
356         }
357
358         /*
359                 Linux
360         */
361         #elif defined(linux)
362
363         char buf[BUFSIZ];
364         memset(buf, 0, BUFSIZ);
365         // Get path to executable
366         assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
367
368         pathRemoveFile(buf, '/');
369
370         path_share = std::string(buf) + "/..";
371         path_user = std::string(buf) + "/..";
372
373         /*
374                 OS X
375         */
376         #elif defined(__APPLE__)
377
378         //https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dyld.3.html
379         //TODO: Test this code
380         char buf[BUFSIZ];
381         uint32_t len = sizeof(buf);
382         assert(_NSGetExecutablePath(buf, &len) != -1);
383
384         pathRemoveFile(buf, '/');
385
386         path_share = std::string(buf) + "/..";
387         path_user = std::string(buf) + "/..";
388
389         /*
390                 FreeBSD
391         */
392         #elif defined(__FreeBSD__)
393
394         int mib[4];
395         char buf[BUFSIZ];
396         size_t len = sizeof(buf);
397
398         mib[0] = CTL_KERN;
399         mib[1] = KERN_PROC;
400         mib[2] = KERN_PROC_PATHNAME;
401         mib[3] = -1;
402         assert(sysctl(mib, 4, buf, &len, NULL, 0) != -1);
403
404         pathRemoveFile(buf, '/');
405
406         path_share = std::string(buf) + "/..";
407         path_user = std::string(buf) + "/..";
408
409         #else
410
411         //TODO: Get path of executable. This assumes working directory is bin/
412         dstream<<"WARNING: Relative path not properly supported on this platform"
413                         <<std::endl;
414
415         /* scriptapi no longer allows paths that start with "..", so assuming that
416            the current working directory is bin/, strip off the last component. */
417         char *cwd = getcwd(NULL, 0);
418         pathRemoveFile(cwd, '/');
419         path_share = std::string(cwd);
420         path_user = std::string(cwd);
421
422         #endif
423
424 #else // RUN_IN_PLACE
425
426         /*
427                 Use platform-specific paths otherwise
428         */
429
430         infostream<<"Using system-wide paths (NOT RUN_IN_PLACE)"<<std::endl;
431
432         /*
433                 Windows
434         */
435         #if defined(_WIN32)
436
437         const DWORD buflen = 1000;
438         char buf[buflen];
439         DWORD len;
440
441         // Find path of executable and set path_share relative to it
442         len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
443         assert(len < buflen);
444         pathRemoveFile(buf, '\\');
445
446         // Use ".\bin\.."
447         path_share = std::string(buf) + "\\..";
448
449         // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
450         len = GetEnvironmentVariable("APPDATA", buf, buflen);
451         assert(len < buflen);
452         path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
453
454         /*
455                 Linux
456         */
457         #elif defined(linux)
458
459         // Get path to executable
460         std::string bindir = "";
461         {
462                 char buf[BUFSIZ];
463                 memset(buf, 0, BUFSIZ);
464                 assert(readlink("/proc/self/exe", buf, BUFSIZ-1) != -1);
465                 pathRemoveFile(buf, '/');
466                 bindir = buf;
467         }
468
469         // Find share directory from these.
470         // It is identified by containing the subdirectory "builtin".
471         std::list<std::string> trylist;
472         std::string static_sharedir = STATIC_SHAREDIR;
473         if(static_sharedir != "" && static_sharedir != ".")
474                 trylist.push_back(static_sharedir);
475         trylist.push_back(
476                         bindir + DIR_DELIM + ".." + DIR_DELIM + "share" + DIR_DELIM + PROJECT_NAME);
477         trylist.push_back(bindir + DIR_DELIM + "..");
478
479         for(std::list<std::string>::const_iterator i = trylist.begin();
480                         i != trylist.end(); i++)
481         {
482                 const std::string &trypath = *i;
483                 if(!fs::PathExists(trypath) || !fs::PathExists(trypath + DIR_DELIM + "builtin")){
484                         dstream<<"WARNING: system-wide share not found at \""
485                                         <<trypath<<"\""<<std::endl;
486                         continue;
487                 }
488                 // Warn if was not the first alternative
489                 if(i != trylist.begin()){
490                         dstream<<"WARNING: system-wide share found at \""
491                                         <<trypath<<"\""<<std::endl;
492                 }
493                 path_share = trypath;
494                 break;
495         }
496
497         path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
498
499         /*
500                 OS X
501         */
502         #elif defined(__APPLE__)
503
504         // Code based on
505         // http://stackoverflow.com/questions/516200/relative-paths-not-working-in-xcode-c
506         CFBundleRef main_bundle = CFBundleGetMainBundle();
507         CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
508         char path[PATH_MAX];
509         if(CFURLGetFileSystemRepresentation(resources_url, TRUE, (UInt8 *)path, PATH_MAX))
510         {
511                 dstream<<"Bundle resource path: "<<path<<std::endl;
512                 //chdir(path);
513                 path_share = std::string(path) + DIR_DELIM + "share";
514         }
515         else
516         {
517                 // error!
518                 dstream<<"WARNING: Could not determine bundle resource path"<<std::endl;
519         }
520         CFRelease(resources_url);
521
522         path_user = std::string(getenv("HOME")) + "/Library/Application Support/" + PROJECT_NAME;
523
524         #else // FreeBSD, and probably many other POSIX-like systems.
525
526         path_share = STATIC_SHAREDIR;
527         path_user = std::string(getenv("HOME")) + DIR_DELIM + "." + PROJECT_NAME;
528
529         #endif
530
531 #endif // RUN_IN_PLACE
532 }
533
534 static irr::IrrlichtDevice* device;
535
536 void initIrrlicht(irr::IrrlichtDevice * _device) {
537         device = _device;
538 }
539
540 #ifndef SERVER
541 v2u32 getWindowSize() {
542         return device->getVideoDriver()->getScreenSize();
543 }
544
545
546 float getDisplayDensity() {
547         float gui_scaling = g_settings->getFloat("gui_scaling");
548         // using Y here feels like a bug, this needs to be discussed later!
549         if (getWindowSize().Y <= 800) {
550                 return (2.0/3.0) * gui_scaling;
551         }
552         if (getWindowSize().Y <= 1280) {
553                 return 1.0 * gui_scaling;
554         }
555
556         return (4.0/3.0) * gui_scaling;
557 }
558
559 v2u32 getDisplaySize() {
560         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
561
562         core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
563         nulldevice -> drop();
564
565         return deskres;
566 }
567 #endif
568
569 } //namespace porting
570