source: network-game/common/Common.cpp@ 6fab975

Last change on this file since 6fab975 was 8554263, checked in by dportnoy <dmp1488@…>, 11 years ago

Restructuring and code cleanup

  • Property mode set to 100644
File size: 2.1 KB
Line 
1#include "Common.h"
2
3#include "Compiler.h"
4
5#if defined WINDOWS
6 #include <winsock2.h>
7#elif defined LINUX
8 #include <fcntl.h>
9 #include <assert.h>
10#endif
11
12#include <sstream>
13#include <cmath>
14#include <ctime>
15#include <cstdlib>
16#include <cstdio>
17
18using namespace std;
19
20FLOAT_POSITION POSITION::toFloat() {
21 FLOAT_POSITION floatPosition;
22 floatPosition.x = x;
23 floatPosition.y = y;
24
25 return floatPosition;
26}
27
28POSITION FLOAT_POSITION::toInt() {
29 POSITION position;
30 position.x = x;
31 position.y = y;
32
33 return position;
34}
35
36// This might not be cross-platform. Verify that this works correctly or fix it.
37void error(const char *msg)
38{
39 perror(msg);
40 exit(0);
41}
42
43void set_nonblock(int sock)
44{
45 #if defined WINDOWS
46 unsigned long mode = 1;
47 ioctlsocket(sock, FIONBIO, &mode);
48 #elif defined LINUX
49 int flags = fcntl(sock, F_GETFL,0);
50 assert(flags != -1);
51 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
52 #endif
53}
54
55unsigned long long getCurrentMillis()
56{
57 unsigned long long numMilliseconds;
58
59 #if defined WINDOWS
60 numMilliseconds = GetTickCount();
61 #elif defined LINUX
62 timespec curTime;
63 clock_gettime(CLOCK_REALTIME, &curTime);
64
65 numMilliseconds = curTime.tv_sec*(unsigned long long)1000+curTime.tv_nsec/(unsigned long long)1000000;
66 #endif
67
68 return numMilliseconds;
69}
70
71string getCurrentDateTimeString() {
72 ostringstream timeString;
73
74 time_t millis = time(NULL);
75 struct tm *time = localtime(&millis);
76
77 timeString << time->tm_hour << ":" << time->tm_min << ":"<< time->tm_sec << " " << (time->tm_mon+1) << "/" << time->tm_mday << "/" << (time->tm_year+1900);
78
79 return timeString.str();
80}
81
82float posDistance(FLOAT_POSITION pos1, FLOAT_POSITION pos2) {
83 float xDiff = pos2.x - pos1.x;
84 float yDiff = pos2.y - pos1.y;
85
86 return sqrt( pow(xDiff,2) + pow(yDiff,2) );
87}
88
89POSITION screenToMap(POSITION pos)
90{
91 pos.x = pos.x-300;
92 pos.y = pos.y-100;
93
94 if (pos.x < 0 || pos.y < 0)
95 {
96 pos.x = -1;
97 pos.y = -1;
98 }
99
100 return pos;
101}
102
103POSITION mapToScreen(POSITION pos)
104{
105 pos.x = pos.x+300;
106 pos.y = pos.y+100;
107
108 return pos;
109}
Note: See TracBrowser for help on using the repository browser.