XPMP2
X-Plane multiplayer library 2 - using instancing
Utilities.h
Go to the documentation of this file.
1
20
21#ifndef _Utilities_h_
22#define _Utilities_h_
23
24namespace XPMP2 {
25
26//
27// MARK: General texts
28//
29
30#define ERR_ASSERT "ASSERT FAILED: %s"
31#define ERR_EXCEPTION "EXCEPTION CAUGHT: %s"
32
33// Required supplemental files
34constexpr const char* RSRC_RELATED = "related.txt";
35constexpr const char* RSRC_REL_OP = "relOp.txt";
36constexpr const char* RSRC_DOC8643 = "Doc8643.txt";
37constexpr const char* RSRC_MAP_ICONS = "MapIcons.png";
38constexpr const char* RSRC_OBJ8DATAREFS = "Obj8DataRefs.txt";
39
40//
41// MARK: Default configuration callbacks
42//
43
44int PrefsFuncIntDefault (const char *, const char *, int _default);
45
46//
47// MARK: File access helpers
48//
49
50#if IBM
51#define PATH_DELIM_STD '\\'
52#else
53#define PATH_DELIM_STD '/'
54#endif
55
57bool ExistsFile (const std::string& filename);
58
60bool IsDir (const std::string& path);
61
64bool CreateDir(const std::string& path);
65
68bool CopyFileIfNewer(const std::string& source, const std::string& destDir);
69
71std::list<std::string> GetDirContents (const std::string& path);
72
74std::istream& safeGetline(std::istream& is, std::string& t);
75
77const std::string& GetXPSystemPath ();
78
80std::string StripXPSysDir (const std::string& path);
81
83void RemoveExtension (std::string& path);
84
85//
86// MARK: String helpers
87//
88
89#define WHITESPACE " \t\f\v\r\n"
90
92std::string& str_tolower(std::string& s);
93
96inline std::string& rtrim(std::string& s, const char* t = WHITESPACE)
97{
98 s.erase(s.find_last_not_of(t) + 1);
99 return s;
100}
101
104inline std::string& ltrim(std::string& s, const char* t = WHITESPACE)
105{
106 s.erase(0, s.find_first_not_of(t));
107 return s;
108}
109
112inline std::string& trim(std::string& s, const char* t = WHITESPACE)
113{
114 return ltrim(rtrim(s, t), t);
115}
116
118inline std::string leftOf(const std::string& s, const std::string& terminators)
119{
120 return s.substr(0, std::min(s.find_first_of(terminators), s.size()));
121}
122
124std::vector<std::string> str_tokenize (const std::string s,
125 const std::string tokens,
126 bool bSkipEmpty = true);
127
128//
129// MARK: Math helpers
130//
131
133constexpr double PI = 3.1415926535897932384626433832795028841971693993751;
134
136constexpr float EPSILON_F = 0.00001f;
137
139inline bool fequal (float a, float b)
140{ return ((a - EPSILON_F) < b) && ((a + EPSILON_F) > b); }
141
142
144template <class T>
145inline T rad2deg (const T _rad)
146{ return (_rad < T(0) ? T(360) : T(0)) + _rad * T(180) / T(PI); }
147
149template <class T>
150inline T deg2rad (const T _deg)
151{ return _deg * T(PI) / T(180); }
152
154template <class T>
155inline T sqr (const T a) { return a*a; }
156
158template <class T>
159inline T dist (const T x1, const T y1, const T z1,
160 const T x2, const T y2, const T z2)
161{
162 return std::hypot(x1-x2, y1-y2, z1-z2);
163}
164
166inline float atan2deg (float x, float y)
167{ return rad2deg(atan2(x,y)); }
168
176inline float angleLocCoord (float x1, float z1, float x2, float z2)
177{ return rad2deg(atan2(z2-z1,x2-x1) + float(PI/2.0)); }
178
180float headDiff (float head1, float head2);
181
183template <class numT>
184numT headNormalize (numT _head)
185{
186 if (_head < numT(0))
187 _head += std::ceil(_head/-numT(360)) * numT(360);
188 else if (_head >= numT(360))
189 _head -= std::floor(_head/numT(360)) * numT(360);
190 return _head;
191}
192
197std::valarray<float> HeadPitch2Vec (const float head, const float pitch);
198
200std::valarray<float> HeadPitchRoll2Normal(const float head, const float pitch, const float roll);
201
202//
203// MARK: Misc
204//
205
209
211float GetMiscNetwTime ();
212
215std::string GetMiscNetwTimeStr (float _time = NAN);
216
218const char* GetGraphicsDriverTxt ();
219
221bool IsPaused ();
222
224bool IsViewExternal ();
225
231bool CheckEverySoOften (float& _lastCheck, float _interval, float _now);
232
237inline bool CheckEverySoOften (float& _lastCheck, float _interval)
238{ return CheckEverySoOften(_lastCheck, _interval, GetMiscNetwTime()); }
239
240//
241// MARK: Logging Support
242//
243
246#if defined(__clang__) || defined(__GNUC__)
247#define XPMP2_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1)))
248#else
249#define XPMP2_FMTARGS(FMT)
250#endif
251
261
263const char* LogGetString ( const char* szFile, int ln, const char* szFunc, logLevelTy lvl, const char* szMsg, va_list args );
264
266void LogMsg ( const char* szFile, int ln, const char* szFunc, logLevelTy lvl, const char* szMsg, ... ) XPMP2_FMTARGS(5);
267
268//
269// MARK: Logging macros
270//
271
275#define LOG_MSG(lvl,...) { \
276 if (lvl >= XPMP2::glob.logLvl) \
277 {LogMsg(__FILE__, __LINE__, __func__, lvl, __VA_ARGS__);} \
278}
279
283#define LOG_MATCHING(lvl,...) { \
284 if (XPMP2::glob.bLogMdlMatch && lvl >= glob.logLvl) \
285 {LogMsg(__FILE__, __LINE__, __func__, lvl, __VA_ARGS__);} \
286}
287
291#define THROW_ERROR(...) \
292throw XPMP2Error(__FILE__, __LINE__, __func__, __VA_ARGS__);
293
296#define LOG_ASSERT(cond) \
297 if (!(cond)) { \
298 THROW_ERROR(ERR_ASSERT,#cond); \
299 }
300
302#define CATCH_AC(ac) \
303 catch (const std::exception& e) { \
304 LOG_MSG(logFATAL, ERR_EXCEPTION, e.what()); \
305 (ac).SetInvalid(); \
306 } \
307 catch (...) { \
308 LOG_MSG(logFATAL, ERR_EXCEPTION, "<unknown>"); \
309 (ac).SetInvalid(); \
310 }
311
312
313//
314// MARK: Compiler differences
315//
316
317#if APL == 1 || LIN == 1
318// not quite the same but close enough for our purposes
319inline void strncpy_s(char * dest, size_t destsz, const char * src, size_t count)
320{
321 strncpy(dest, src, std::min(destsz,count)); dest[destsz - 1] = 0;
322}
323
324// these simulate the VC++ version, not the C standard versions!
325inline struct tm *gmtime_s(struct tm * result, const time_t * time)
326{ return gmtime_r(time, result); }
327inline struct tm *localtime_s(struct tm * result, const time_t * time)
328{ return localtime_r(time, result); }
329
330#endif
331
333#define STRCPY_S(dest,src) strncpy_s(dest,sizeof(dest),src,sizeof(dest)-1)
334#define STRCPY_ATMOST(dest,src) strncpy_s(dest,sizeof(dest),strAtMost(src,sizeof(dest)-1).c_str(),sizeof(dest)-1)
335
336// XCode/Linux don't provide the _s functions, not even with __STDC_WANT_LIB_EXT1__ 1
337#if APL
338inline int strerror_s( char *buf, size_t bufsz, int errnum )
339{ return strerror_r(errnum, buf, bufsz); }
340#elif LIN
341inline int strerror_s( char *buf, size_t bufsz, int errnum )
342{ strerror_r(errnum, buf, bufsz); return 0; }
343#endif
344
345// In case of Mac we need to prepare for HFS-to-Posix path conversion
346#if APL
348std::string TOPOSIX (const std::string& p);
350std::string FROMPOSIX (const std::string& p);
351#else
353inline std::string TOPOSIX (const std::string& p) { return p; }
355inline std::string FROMPOSIX (const std::string& p) { return p; }
356#endif
357
358// MARK: Thread names
359#ifdef DEBUG
360// This might not work on older Windows version, which is why we don't publish it in release builds
361#if IBM
362#define SET_THREAD_NAME(sName) SetThreadDescription(GetCurrentThread(), L##sName)
363#elif APL
364#define SET_THREAD_NAME(sName) pthread_setname_np(sName)
365#elif LIN
366#define SET_THREAD_NAME(sName) pthread_setname_np(pthread_self(),sName)
367#endif
368#else
369#define SET_THREAD_NAME(sName)
370#endif
371
372} // namespace XPMP2
373
374#endif
#define WHITESPACE
Definition Utilities.h:89
#define XPMP2_FMTARGS(FMT)
To apply printf-style warnings to our functions.
Definition Utilities.h:249
Definition XPMPAircraft.h:76
std::valarray< float > HeadPitch2Vec(const float head, const float pitch)
Convert heading/pitch to normalized x/y/z vector.
Definition Utilities.cpp:681
T rad2deg(const T _rad)
Convert radians to degrees, normalized to [0..360)
Definition Utilities.h:145
logLevelTy
Logging level.
Definition Utilities.h:253
@ logFATAL
fatal is shortly before a crash
Definition Utilities.h:258
@ logMSG
will always be output, no matter what has been configured, cannot be suppressed
Definition Utilities.h:259
@ logDEBUG
Debug, highest level of detail.
Definition Utilities.h:254
@ logWARN
warnings, i.e. unexpected, but uncritical events, maybe leading to unwanted display,...
Definition Utilities.h:256
@ logERR
errors mean, aircraft can potentially not be displayed
Definition Utilities.h:257
@ logINFO
regular info messages
Definition Utilities.h:255
std::string leftOf(const std::string &s, const std::string &terminators)
Returns everything left of any of terminators.
Definition Utilities.h:118
const char * LogGetString(const char *szPath, int ln, const char *szFunc, logLevelTy lvl, const char *szMsg, va_list args)
Returns ptr to static buffer filled with formatted log string.
Definition Utilities.cpp:856
constexpr const char * RSRC_OBJ8DATAREFS
Definition Utilities.h:38
std::string TOPOSIX(const std::string &p)
On Lin/Win there is no need for a conversion, but we do treat p now as std::string
Definition Utilities.h:353
constexpr double PI
Pi.
Definition Utilities.h:133
void LogMsg(const char *szPath, int ln, const char *szFunc, logLevelTy lvl, const char *szMsg,...)
Log Text to log file.
Definition Utilities.cpp:897
bool CheckEverySoOften(float &_lastCheck, float _interval, float _now)
Convenience function to check on something at most every x seconds.
Definition Utilities.cpp:803
std::string & ltrim(std::string &s, const char *t=WHITESPACE)
trimming of string (from left)
Definition Utilities.h:104
std::string GetMiscNetwTimeStr(float _time)
Return the network time as a string like used in the XP's Log.txt.
Definition Utilities.cpp:759
std::string FROMPOSIX(const std::string &p)
On Lin/Win there is no need for a conversion, but we do treat p now as std::string
Definition Utilities.h:355
float angleLocCoord(float x1, float z1, float x2, float z2)
Angle of line from point (x1|z1) to point (x2|z2)
Definition Utilities.h:176
void RemoveExtension(std::string &path)
Removes everything after the last dot, the dot including.
Definition Utilities.cpp:496
std::list< std::string > GetDirContents(const std::string &path)
List of files in a directory (wrapper around XPLMGetDirectoryContents)
Definition Utilities.cpp:427
constexpr const char * RSRC_RELATED
Definition Utilities.h:34
std::valarray< float > HeadPitchRoll2Normal(const float head, const float pitch, const float roll)
Convert heading/pitch/roll to unit and normal vector, ie. returns 6 values, first 3 like HeadPitch2Ve...
Definition Utilities.cpp:702
float UpdateCachedValuesGetNetwTime()
Update cached values during a flight loop callback in XP's main thread to have them when called from ...
Definition Utilities.cpp:735
T sqr(const T a)
Square.
Definition Utilities.h:155
float GetMiscNetwTime()
Get synched network time from X-Plane (sim/network/misc/network_time_sec) as used in Log....
Definition Utilities.cpp:744
bool fequal(float a, float b)
Are these two float near-equal? (to avoid trying something like a == b)
Definition Utilities.h:139
const std::string & GetXPSystemPath()
Returns XP's system directory, including a trailing slash.
Definition Utilities.cpp:473
numT headNormalize(numT _head)
Normalize a heading value to [0..360), works for both float and double values.
Definition Utilities.h:184
constexpr float EPSILON_F
Epsilon, a small number.
Definition Utilities.h:136
const char * GetGraphicsDriverTxt()
Text string for current graphics driver in use.
Definition Utilities.cpp:776
float headDiff(float head1, float head2)
(Shortest) difference between 2 angles: How much to turn to go from h1 to h2?
Definition Utilities.cpp:661
bool ExistsFile(const std::string &filename)
Does a file path exist?
Definition Utilities.cpp:343
bool CreateDir(const std::string &path)
Create directory if it does not exist.
Definition Utilities.cpp:359
std::string & str_tolower(std::string &s)
change a std::string to uppercase
Definition Utilities.cpp:607
bool CopyFileIfNewer(const std::string &source, const std::string &destDir)
Copy file if source is newer or destination missing.
Definition Utilities.cpp:374
constexpr const char * RSRC_MAP_ICONS
Definition Utilities.h:37
bool IsPaused()
X-Plane in a Pause state?
Definition Utilities.cpp:789
bool IsViewExternal()
Is current X-Plane view an external view (outside a cockpit)?
Definition Utilities.cpp:796
T dist(const T x1, const T y1, const T z1, const T x2, const T y2, const T z2)
Pythagorean distance between two points in a 3-D world.
Definition Utilities.h:159
std::string StripXPSysDir(const std::string &path)
If a path starts with X-Plane's system directory it is stripped.
Definition Utilities.cpp:486
T deg2rad(const T _deg)
Convert degree to radians.
Definition Utilities.h:150
constexpr const char * RSRC_REL_OP
Definition Utilities.h:35
bool IsDir(const std::string &path)
Is path a directory?
Definition Utilities.cpp:350
float atan2deg(float x, float y)
atan2 converted to degrees: the angle between (0|0) and the given point
Definition Utilities.h:166
int PrefsFuncIntDefault(const char *, const char *, int _default)
Default config function just always returns the provided default value.
Definition Utilities.cpp:185
constexpr const char * RSRC_DOC8643
Definition Utilities.h:36
std::string & rtrim(std::string &s, const char *t=WHITESPACE)
trimming of string (from right)
Definition Utilities.h:96
std::vector< std::string > str_tokenize(const std::string s, const std::string tokens, bool bSkipEmpty)
separates string into tokens
Definition Utilities.cpp:614
std::string & trim(std::string &s, const char *t=WHITESPACE)
trimming of string (from both ends)
Definition Utilities.h:112
std::istream & safeGetline(std::istream &is, std::string &t)
Read a line from a text file, no matter if ending on CRLF or LF.
Definition Utilities.cpp:460