VR-Engage  2.2
Loading...
Searching...
No Matches
utilFunctions.h
Go to the documentation of this file.
1/*********************************************************************************
2** Copyright (c) 2025 MAK Technologies
3** All rights reserved.
4*********************************************************************************/
5
6//! \file utilFunctions.h
7//! \ingroup vreUtil
8//! \brief Provides common utility functions for the VREngage system
9//!
10//! This file contains various utility functions for timing, string manipulation,
11//! mathematical operations, and type conversions that are used throughout the
12//! VREngage codebase.
13
14#pragma once
15
16#include "vreUtil/export.h"
17
18#include <matrix/vlVector.h>
19#include <matrix/vlTaitBryan.h>
20
21#include <vlutil/vlString.h>
22
23#include <string>
24#include <vector>
25
26// Signals helpers
27#include <boost/signals2/signal.hpp>
28#include <boost/signals2/connection.hpp>
29
30namespace makVre
31{
32
33//! \brief Unsigned 16-bit integer type
34using UInt16 = unsigned short;
35//! \brief Signed 16-bit integer type
36using Int16 = short;
37//! \brief Unsigned 32-bit integer type
38using UInt32 = unsigned long;
39//! \brief Signed 32-bit integer type
40using Int32 = long;
41//! \brief Unsigned 64-bit integer type
42using UInt64 = unsigned long long;
43//! \brief Signed 64-bit integer type
44using Int64 = long long;
45
46//! \brief Inverse of CPU frequency for time calculations
47extern double invFreq;
48//! \brief Number of CPU ticks per second
50//! \brief Flag indicating if the high-resolution timer is initialized
51extern bool timerIsInitialized;
52
53//! \brief Initializes the high-resolution timer
54//!
55//! This function can be safely called multiple times, but only the first call has any effect.
56//! It is automatically called when the library is loaded and by the profiler, so users
57//! typically do not need to call it directly.
58//!
59//! \return True if initialization succeeded, false otherwise
61
62//! \brief Gets a high-resolution CPU timestamp
63//!
64//! Returns a high-resolution 64-bit timestamp from the CPU, typically used for profiling.
65//! If the CPU doesn't support high-resolution counter instructions, uses QueryPerformanceCounter()
66//! as a fallback on Windows. On Linux, this function uses gettime().
67//!
68//! \return 64-bit timestamp value
70
71//! \brief Gets a high-resolution time in seconds
72//!
73//! Returns the elapsed time in seconds since the system was started.
74//! Uses DtTimestamp() internally and converts the result to seconds.
75//!
76//! \return Time in seconds (double precision)
78
79//! \brief Gets the current thread ID
80//!
81//! Returns a platform-independent identifier for the current thread.
82//!
83//! \return Thread identifier as an unsigned integer
84unsigned int UTIL_DLL DtGetThreadId();
85
86//! \brief Checks if an environment variable is set
87//!
88//! Tests if the specified environment variable exists and optionally compares its
89//! value against a test value (case-insensitive comparison).
90//!
91//! \param env Name of the environment variable to check
92//! \param testValue Optional value to compare against (empty string to just check existence)
93//! \return True if the variable exists and equals testValue (if provided), false otherwise
94bool UTIL_DLL DtIsEnvironmentVariableSet(const std::string& env, const std::string& testValue = "");
95
96//! \brief Finds a command-line argument and its parameter
97//!
98//! Searches for a specific argument in an argv array and retrieves the parameter
99//! that follows it if requested.
100//!
101//! \param arg The argument to search for
102//! \param argc Number of arguments in the argv array
103//! \param argv Array of command-line arguments
104//! \param param Optional output parameter to store the value following the argument
105//! \return True if the argument was found, false otherwise
106bool UTIL_DLL findArg(const char* arg, int argc, char** argv, const char* param[]);
107
108//! \brief Finds a command-line argument
109//!
110//! Searches for a specific argument in an argv array without retrieving its parameter.
111//!
112//! \param arg The argument to search for
113//! \param argc Number of arguments in the argv array
114//! \param argv Array of command-line arguments
115//! \return True if the argument was found, false otherwise
116bool UTIL_DLL findArg(const char* arg, int argc, char** argv);
117
118//! \brief Converts a floating-point value to a string (radians to angle string)
119//!
120//! Converts a floating-point value (typically an angle in radians) to a string representation.
121//!
122//! \param r The floating-point value to convert
123//! \return String representation of the value
124std::string UTIL_DLL rtoa(float r);
125
126//! \brief Splits a string into tokens
127//!
128//! Divides a string into substrings (tokens) based on a delimiter.
129//!
130//! \param string The string to tokenize
131//! \param delimiter The delimiter string (defaults to space)
132//! \return Vector of tokens
133std::vector<std::string> UTIL_DLL tokenize(const std::string& string, const std::string& delimiter = " ");
134
135//! \brief Removes leading and trailing whitespace from a string
136//!
137//! Trims whitespace characters from the beginning and end of a string.
138//!
139//! \param str The string to trim
140//! \return Trimmed string
141std::string UTIL_DLL trim(const std::string& str);
142
143//! \brief Creates a new string with a substring range replaced
144//!
145//! Returns a new string with the range starting from 'start' and ending with 'end'
146//! replaced with the replacement string.
147//!
148//! \param string The original string
149//! \param start The starting substring
150//! \param end The ending substring
151//! \param replacement The replacement string
152//! \return New string with the substring range replaced
154 const std::string& string, const std::string& start, const std::string& end, const std::string& replacement);
155
156//! \brief Replaces a substring range in-place
157//!
158//! Modifies the original string, replacing the range starting from 'start' and
159//! ending with 'end' with the replacement string.
160//!
161//! \param string The string to modify
162//! \param start The starting substring
163//! \param end The ending substring
164//! \param replacement The replacement string
166 std::string& string, const std::string& start, const std::string& end, const std::string& replacement);
167
168//! \brief Creates a new string with all occurrences of a substring replaced
169//!
170//! Returns a new string with all occurrences of the target substring replaced
171//! with the replacement string.
172//!
173//! \param string The original string
174//! \param target The substring to replace
175//! \param replacement The replacement string
176//! \return New string with all occurrences replaced
178 const std::string& string, const std::string& target, const std::string& replacement);
179
180//! \brief Replaces all occurrences of a substring in-place
181//!
182//! Modifies the original string, replacing all occurrences of the target substring
183//! with the replacement string.
184//!
185//! \param string The string to modify
186//! \param target The substring to replace
187//! \param replacement The replacement string
188void UTIL_DLL replaceSubStr(std::string& string, const std::string& target, const std::string& replacement);
189
190//! \brief Creates a new string clamped to a maximum length
191//!
192//! Returns a new string clamped to the specified maximum length,
193//! appending a tail string (default "...") if truncated.
194//!
195//! \param string The original string
196//! \param length Maximum length of the resulting string
197//! \param tail String to append if truncation occurs (typically "...")
198//! \return New string clamped to the maximum length
199std::string UTIL_DLL lengthClamped(const std::string& string, size_t length, const std::string& tail = "...");
200
201//! \brief Clamps a string to a maximum length in-place
202//!
203//! Modifies the original string, clamping it to the specified maximum length
204//! and appending a tail string (default "...") if truncated.
205//!
206//! \param string The string to modify
207//! \param length Maximum length of the resulting string
208//! \param tail String to append if truncation occurs (typically "...")
209void UTIL_DLL clampLength(std::string& string, size_t length, const std::string& tail = "...");
210
211//! \brief Converts a string to lowercase in-place
212//!
213//! Modifies the original string, converting all characters to lowercase.
214//!
215//! \param str The string to modify
216void UTIL_DLL makeLower(std::string& str);
217
218//! \brief Creates a new string with all characters converted to lowercase
219//!
220//! Returns a new string with all characters converted to lowercase.
221//!
222//! \param in The original string
223//! \return New string in lowercase
224std::string UTIL_DLL lowerCase(const std::string& in);
225
226//! \brief Clamps a value to a specified precision
227//!
228//! Rounds a double value to the nearest multiple of the specified precision value.
229//! For example, with precision=0.001, the value 1.23456 would be clamped to 1.235.
230//!
231//! \param val The value to clamp
232//! \param precision The precision to clamp to (e.g., 0.001 for three decimal places)
233//! \return The clamped value
234double UTIL_DLL clampToPrecision(double val, double precision);
235
236//! \brief Clamps a vector to a specified precision
237//!
238//! Applies precision clamping to each component of a 3D vector.
239//!
240//! \param val The vector to clamp
241//! \param precision The precision to clamp to
242//! \return The clamped vector
243DtVector UTIL_DLL clampToPrecision(DtVector val, double precision);
244
245//! \brief Clamps Tait-Bryan angles to a specified precision
246//!
247//! Applies precision clamping to each angle in a Tait-Bryan representation.
248//!
249//! \param val The Tait-Bryan angles to clamp
250//! \param precision The precision to clamp to
251//! \return The clamped Tait-Bryan angles
252DtTaitBryan UTIL_DLL clampToPrecision(DtTaitBryan val, double precision);
253
254//! \brief Clamps a value between a minimum and maximum range
255//! \tparam T Type of the value and range bounds
256//! \param value The value to clamp
257//! \param min The minimum allowed value
258//! \param max The maximum allowed value
259//! \return The clamped value
260template <class T>
261T clampValue(T value, T min, T max)
262{
263 if (value < min)
264 {
265 return min;
266 }
267 else if (value > max)
268 {
269 return max;
270 }
271 return value;
272}
273
274//! \brief Explicit instantiation for int clampValue
275template int UTIL_DLL clampValue<int>(int, int, int);
276//! \brief Explicit instantiation for float clampValue
277template float UTIL_DLL clampValue<float>(float, float, float);
278//! \brief Explicit instantiation for double clampValue
279template double UTIL_DLL clampValue<double>(double, double, double);
280
281//! \brief Generates a random integer within a specified range
282//!
283//! Returns a random integer between min and max (inclusive).
284//!
285//! \param min The minimum value (inclusive)
286//! \param max The maximum value (inclusive)
287//! \return A random integer within the specified range
288int UTIL_DLL randomInt(int min, int max);
289
290//! \brief Generates a random number within a specified range
291//!
292//! Returns a double-precision random number between min and max (inclusive).
293//!
294//! \param min The minimum value (inclusive)
295//! \param max The maximum value (inclusive)
296//! \return A random integer within the specified range
297double UTIL_DLL randReal(double min, double max);
298
299//! \brief Converts a string to a boolean value
300//!
301//! Converts strings like "true", "1", "yes" to true, and "false", "0", "no" to false.
302//! Case-insensitive.
303//!
304//! \param in The string to convert
305//! \return The boolean value
306bool UTIL_DLL stob(const std::string& in);
307
308//! \brief Converts a string to an integer
309//!
310//! \param in The string to convert
311//! \return The integer value
312int UTIL_DLL stoi(const std::string& in);
313
314//! \brief Converts a string to a long integer
315//!
316//! \param in The string to convert
317//! \return The long integer value
318long UTIL_DLL stol(const std::string& in);
319
320//! \brief Converts a string to an unsigned long integer
321//!
322//! \param in The string to convert
323//! \return The unsigned long integer value
324unsigned long UTIL_DLL stoul(const std::string& in);
325
326//! \brief Converts a string to a long long integer
327//!
328//! \param in The string to convert
329//! \return The long long integer value
330long long UTIL_DLL stoll(const std::string& in);
331
332//! \brief Converts a string to an unsigned long long integer
333//!
334//! \param in The string to convert
335//! \return The unsigned long long integer value
336unsigned long long UTIL_DLL stoull(const std::string& in);
337
338//! \brief Converts a string to a float
339//!
340//! \param in The string to convert
341//! \return The float value
342float UTIL_DLL stof(const std::string& in);
343
344//! \brief Converts a string to a double
345//!
346//! \param in The string to convert
347//! \return The double value
348double UTIL_DLL stod(const std::string& in);
349
350
351class UTIL_DLL DtFileString : public DtString
352{
353public:
354 bool read(const DtFilename& filename);
355 bool write(const DtFilename& filename);
356};
357
359
360//! \brief Helper: connect a slot to a Boost.Signals2 signal to run only once (back).
361//!
362//! This helper connects a lambda or callable to a Boost.Signals2 signal such that the
363//! callable is invoked the next time the signal is emitted and then automatically
364//! disconnected. This avoids using boost::bind/std::bind and favors modern lambdas.
365//!
366//! Ordering: attaches at the back (default) to preserve existing emission order.
367//!
368//! Usage example:
369//! connectOnce(de.signal_postInitialize, [&de]{ postInit(&de); });
370//!
371//! \tparam Signal A boost::signals2::signal type
372//! \tparam F Callable type; signature should match the signal's arguments
373//! \param sig The signal instance to connect to
374//! \param f The callable to invoke on the next emission
375//! \return boost::signals2::connection for the installed slot
376template <class Signal, class F>
377inline boost::signals2::connection connectOnce(Signal& sig, F&& f)
378{
379 return sig.connect_extended(
380 [func = std::forward<F>(f)](const boost::signals2::connection& c, auto&&... args) mutable {
381 func(std::forward<decltype(args)>(args)...);
382 c.disconnect();
383 },
384 boost::signals2::at_back);
385}
386
387//! \brief Helper: connect a slot to a Boost.Signals2 signal to run only once (front).
388//!
389//! Same behavior as connectOnce(), but attaches the slot at the front so it runs before
390//! other slots. This is useful when initialization must occur first.
391//!
392//! Usage example:
393//! connectOnceFront(de.signal_postInitialize, [&de]{ postInit(&de); });
394//!
395//! \tparam Signal A boost::signals2::signal type
396//! \tparam F Callable type; signature should match the signal's arguments
397//! \param sig The signal instance to connect to
398//! \param f The callable to invoke on the next emission
399//! \return boost::signals2::connection for the installed slot
400template <class Signal, class F>
401inline boost::signals2::connection connectOnceFront(Signal& sig, F&& f)
402{
403 return sig.connect_extended(
404 [func = std::forward<F>(f)](const boost::signals2::connection& c, auto&&... args) mutable {
405 func(std::forward<decltype(args)>(args)...);
406 c.disconnect();
407 },
408 boost::signals2::at_front);
409}
410
411} // namespace makVre
Definition utilFunctions.h:352
bool read(const DtFilename &filename)
bool write(const DtFilename &filename)
Defines export macros for the VREngage Utility library.
#define UTIL_DLL
Export/import macro for non-Windows platforms.
Definition export.h:39
Include export definitions for this library.
Definition glsVreMessageUtil.h:49
double UTIL_DLL randReal(double min, double max)
Generates a random number within a specified range.
int UTIL_DLL randomInt(int min, int max)
Generates a random integer within a specified range.
void UTIL_DLL fixMissingBoostClosingTag(DtString &xml)
template double UTIL_DLL clampValue< double >(double, double, double)
Explicit instantiation for double clampValue.
unsigned long UInt32
Unsigned 32-bit integer type.
Definition utilFunctions.h:38
std::vector< std::string > UTIL_DLL tokenize(const std::string &string, const std::string &delimiter=" ")
Splits a string into tokens.
std::string UTIL_DLL subStrReplaced(const std::string &string, const std::string &target, const std::string &replacement)
Creates a new string with all occurrences of a substring replaced.
unsigned long long UTIL_DLL stoull(const std::string &in)
Converts a string to an unsigned long long integer.
std::string UTIL_DLL lowerCase(const std::string &in)
Creates a new string with all characters converted to lowercase.
template float UTIL_DLL clampValue< float >(float, float, float)
Explicit instantiation for float clampValue.
std::string UTIL_DLL trim(const std::string &str)
Removes leading and trailing whitespace from a string.
void UTIL_DLL clampLength(std::string &string, size_t length, const std::string &tail="...")
Clamps a string to a maximum length in-place.
unsigned long long UInt64
Unsigned 64-bit integer type.
Definition utilFunctions.h:42
double UTIL_DLL DtWallClockTime()
Gets a high-resolution time in seconds.
bool UTIL_DLL stob(const std::string &in)
Converts a string to a boolean value.
unsigned short UInt16
Unsigned 16-bit integer type.
Definition utilFunctions.h:34
short Int16
Signed 16-bit integer type.
Definition utilFunctions.h:36
UInt64 UTIL_DLL DtVreTimestamp()
Gets a high-resolution CPU timestamp.
boost::signals2::connection connectOnceFront(Signal &sig, F &&f)
Helper: connect a slot to a Boost.Signals2 signal to run only once (front).
Definition utilFunctions.h:401
bool UTIL_DLL DtIsEnvironmentVariableSet(const std::string &env, const std::string &testValue="")
Checks if an environment variable is set.
long long UTIL_DLL stoll(const std::string &in)
Converts a string to a long long integer.
void UTIL_DLL makeLower(std::string &str)
Converts a string to lowercase in-place.
double invFreq
Inverse of CPU frequency for time calculations.
std::string UTIL_DLL lengthClamped(const std::string &string, size_t length, const std::string &tail="...")
Creates a new string clamped to a maximum length.
unsigned int UTIL_DLL DtGetThreadId()
Gets the current thread ID.
std::string UTIL_DLL rtoa(float r)
Converts a floating-point value to a string (radians to angle string)
bool UTIL_DLL DtInitializeTimer()
Initializes the high-resolution timer.
bool timerIsInitialized
Flag indicating if the high-resolution timer is initialized.
float UTIL_DLL stof(const std::string &in)
Converts a string to a float.
double UTIL_DLL clampToPrecision(double val, double precision)
Clamps a value to a specified precision.
int UTIL_DLL stoi(const std::string &in)
Converts a string to an integer.
void UTIL_DLL replaceSubStr(std::string &string, const std::string &target, const std::string &replacement)
Replaces all occurrences of a substring in-place.
double UTIL_DLL stod(const std::string &in)
Converts a string to a double.
T clampValue(T value, T min, T max)
Clamps a value between a minimum and maximum range.
Definition utilFunctions.h:261
void UTIL_DLL replaceSubStrRange(std::string &string, const std::string &start, const std::string &end, const std::string &replacement)
Replaces a substring range in-place.
template int UTIL_DLL clampValue< int >(int, int, int)
Explicit instantiation for int clampValue.
std::string UTIL_DLL subStrRangeReplaced(const std::string &string, const std::string &start, const std::string &end, const std::string &replacement)
Creates a new string with a substring range replaced.
unsigned long UTIL_DLL stoul(const std::string &in)
Converts a string to an unsigned long integer.
boost::signals2::connection connectOnce(Signal &sig, F &&f)
Helper: connect a slot to a Boost.Signals2 signal to run only once (back).
Definition utilFunctions.h:377
long long Int64
Signed 64-bit integer type.
Definition utilFunctions.h:44
long Int32
Signed 32-bit integer type.
Definition utilFunctions.h:40
long UTIL_DLL stol(const std::string &in)
Converts a string to a long integer.
UInt64 ticksPerSecond
Number of CPU ticks per second.
bool UTIL_DLL findArg(const char *arg, int argc, char **argv, const char *param[])
Finds a command-line argument and its parameter.