GL Studio C++ Runtime API
util.h
Go to the documentation of this file.
1 /*! \file
2  \brief Generally useful defines, macros, enumerations and function
3  prototypes.
4 
5  \par Copyright Information
6 
7  Copyright (c) 2017 by The DiSTI Corporation.<br>
8  11301 Corporate Blvd; Suite 100<br>
9  Orlando, Florida 32817<br>
10  USA<br>
11  <br>
12  All rights reserved.<br>
13 
14  This Software contains proprietary trade secrets of DiSTI and may not be
15 reproduced, in whole or part, in any form, or by any means of electronic,
16 mechanical, or otherwise, without the written permission of DiSTI. Said
17 permission may be derived through the purchase of applicable DiSTI product
18 licenses which detail the distribution rights of this content and any
19 Derivative Works based on this or other copyrighted DiSTI Software.
20 
21  NO WARRANTY. THE SOFTWARE IS PROVIDED "AS-IS," WITHOUT WARRANTY OF ANY KIND,
22 AND ANY USE OF THIS SOFTWARE PRODUCT IS AT YOUR OWN RISK. TO THE MAXIMUM EXTENT
23 PERMITTED BY APPLICABLE LAW, DISTI AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES
24 AND CONDITIONS, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
25 IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY AND/OR FITNESS FOR A
26 PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT, WITH REGARD TO THE SOFTWARE.
27 
28  LIMITATION OF LIABILITY. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW,
29 IN NO EVENT SHALL DISTI OR ITS SUPPLIERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
30 INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION,
31 DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS
32 INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
33 INABILITY TO USE THE SOFTWARE, EVEN IF DISTI HAS BEEN ADVISED OF THE POSSIBILITY
34 OF SUCH DAMAGES. DISTI'S ENTIRE LIABILITY AND YOUR EXCLUSIVE REMEDY SHALL NOT
35 EXCEED FIVE DOLLARS (US$5.00).
36 
37  The aforementioned terms and restrictions are governed by the laws of the
38 State of Florida and the United States of America.
39 
40 */
41 
42 #ifndef INCLUDED_GLS_RUNTIME_UTIL_H
43 #define INCLUDED_GLS_RUNTIME_UTIL_H
44 
45 #include "disti_assert.h"
46 #include "dynamic_array.h"
47 #include "gls_cpp_lang_support.h"
48 #include "gls_include.h"
49 #include "gls_matrix_affine.h"
50 #include "scoped_ptr.h"
51 #include "unhide_globals.h"
52 #include "vertex.h"
53 
54 #include <algorithm>
55 #include <cmath>
56 #include <iostream>
57 #include <sstream>
58 #include <string>
59 #include <typeinfo>
60 #include <vector>
61 
62 #ifdef WIN32
63 # include <direct.h>
64 #else
65 # include <unistd.h>
66 #endif
67 
68 #if defined( QNX )
69 # include <stdio.h>
70 #else
71 # include <cstdio>
72 #endif
73 
74 #if defined( LINUX ) || defined( __VXWORKS__ ) || defined( __APPLE__ ) || defined( QNX )
75 # include <strings.h>
76 #endif
77 
78 #ifdef ANDROID
79 # include <android/asset_manager.h>
80 #endif
81 
82 const int DIALOG_MAX_DIRECTORY_LENGTH = 1024; // Limited by FLTK FileBrowser
83 
84 class Fl_Window;
85 
86 // Wrap code that should only be compiled in debug in GLS_DEBUG_CODE()
87 #if defined( GLS_DEBUG ) || !defined( NDEBUG )
88 # define GLS_DEBUG_CODE( x ) x
89 #else
90 # define GLS_DEBUG_CODE( x )
91 #endif
92 
93 namespace disti
94 {
95 class Vertex;
96 class DisplayObject;
97 class DisplayFrame;
98 
99 #ifndef TRUE
100 # define TRUE 1
101 #endif
102 
103 #ifndef FALSE
104 # define FALSE 0
105 #endif
106 
107 #ifdef WIN32
108 inline int strcasecmp( const char* const x, const char* const y )
109 {
110  return _stricmp( x, y );
111 }
112 #endif
113 
114 /** Used to generate inline textures. The writing and reading of the lines need to know the length. */
116 
117 /* Used for parsing lines of clear text */
118 const char PARSER_CLEARSTRING_DELIMETER_START[] = "#$STRING_START$#";
119 const char PARSER_CLEARSTRING_DELIMETER_END[] = "#$STRING_END$#";
120 
121 const double HIT_TOLERANCE = 5.0;
122 
123 /** Determines if x is included in the range x1 to x2 */
124 template<class X, class X1, class X2>
125 bool BETWEEN( const X& x, const X1& x1, const X2& x2 )
126 {
127  return ( x >= x1 && x <= x2 )
128  || ( x >= x2 && x <= x1 );
129 }
130 
131 /** Determines if the argument is negative */
132 template<class X>
133 bool IS_NEGATIVE( const X& x ) { return std::fabs( x ) > 0.0001 ? ( x < 0.0 ) : 0; }
134 
135 /** Determines if the argument is positive */
136 template<class X>
137 bool IS_POSITIVE( const X& x ) { return std::fabs( x ) > 0.0001 ? ( x > 0.0 ) : 0; }
138 
139 /** Determines if the argument is small (< 1e-1) */
140 template<class X>
141 bool CloseToZero( const X x, const X threshold = X( 1e-1 ) )
142 {
143  return std::fabs( x ) < threshold;
144 }
145 
146 /** Determines if the argument is extremely small (< 10E-4) */
147 template<class X>
148 bool VeryCloseToZero( X x ) { return CloseToZero( x, X( 0.0001 ) ); }
149 
150 /** Determines if the argument is very small (< 10E-3) */
151 template<class X>
152 bool IsNearZero( X x ) { return CloseToZero( x, X( 0.001 ) ); }
153 
154 /** \deprecated Renamed to IsNearZero(). */
155 template<class X>
156 bool IS_ZERO( X x ) { return IsNearZero( x ); }
157 
158 #ifndef MIN
159 /// Determines which argument is smaller
160 /// \deprecated Use disti::Min() instead.
161 # define MIN( A, B ) ( ( A ) < ( B ) ? ( A ) : ( B ) )
162 #endif
163 
164 #ifndef MAX
165 /// Determines which argument is larger
166 /// \deprecated Use disti::Min() instead.
167 # define MAX( A, B ) ( ( A ) > ( B ) ? ( A ) : ( B ) )
168 #endif
169 
170 /** Use for determining the current OpenGL version available in the current
171  * runtime environment.
172  * It may not be valid until called after a valid rendering context has been assigned.
173  */
174 GLS_EXPORT float OpenGLVersion();
175 
176 GLS_EXPORT bool gltIsExtSupported( const char* extension );
177 
178 // Additional #defines
179 //From glext.h Available at http://oss.sgi.com/projects/ogl-sample/registry/ */
180 #ifndef GLES
181 # define GLSTUDIO_CLAMP_TO_EDGE ( OpenGLVersion() >= 1.2f ? 0x812F : GL_CLAMP )
182 #else
183 # define GLSTUDIO_CLAMP_TO_EDGE GL_CLAMP_TO_EDGE
184 #endif
185 
186 /** GL Studio color defines */
187 // \enum color enumerations for use with GlsDefinedColor methods
189 {
190  GLS_COLOR_WHITE,
191  GLS_COLOR_CYAN,
192  GLS_COLOR_RED,
193  GLS_COLOR_AMBER,
194  GLS_COLOR_GREEN,
195  GLS_COLOR_YELLOW,
196  GLS_COLOR_MAGENTA,
197  GLS_COLOR_BLACK,
198  GLS_COLOR_BLUE,
199  GLS_COLOR_MAX
200 };
201 
202 /** Predefined colors (see \sa GlsDefinedColorEnum for the values). Use \sa GlsDefinedColor() for a range-checked version. */
203 GLS_EXPORT extern unsigned char glsDefinedColors[ GLS_COLOR_MAX ][ 4 ];
204 
205 /** Gets a predefined color in \sa GlsDefinedColorEnum.
206  * \param index of defined color
207  * \return an unsigned char array of the specified index
208  */
209 inline unsigned char* GlsDefinedColor( GlsDefinedColorEnum index )
210 {
211  if( ( index < 0 ) || ( index >= GLS_COLOR_MAX ) )
212  return glsDefinedColors[ 0 ];
213  else
214  return glsDefinedColors[ index ];
215 }
216 /** Allows the user to change the predefined colors */
218  GlsDefinedColorEnum index,
219  unsigned char red,
220  unsigned char green,
221  unsigned char blue,
222  unsigned char alpha )
223 {
224  if( ( index >= 0 ) && ( index < GLS_COLOR_MAX ) )
225  {
226  glsDefinedColors[ index ][ 0 ] = red;
227  glsDefinedColors[ index ][ 1 ] = green;
228  glsDefinedColors[ index ][ 2 ] = blue;
229  glsDefinedColors[ index ][ 3 ] = alpha;
230  }
231 }
232 
233 //---------------------------------------------------------------------------
234 /**
235  * Return whether two numbers are "equal" to eachother taking into account
236  * a certain precision. You can use this method on any numeric types and
237  * even mix types as the parameters. Eg. you can compare integers with
238  * floating point types or compare floats and doubles without casting.
239  *
240  * \param x first number to use in the comparison which determines the range
241  * \param y number to check if within the range determined by x and precision
242  * \param precision number that is added to and subtracted from x to
243  * determine the range to check y against.
244  */
245 template<class T1, class T2>
246 bool Equal( T1 x, T2 y, float precision = 0.001f )
247 {
248  return ( x - precision ) <= y && y <= ( x + precision );
249 }
250 
251 //---------------------------------------------------------------------------
252 /**
253  * Return the minimum of two objects. The class T must have the < operator
254  * defined.
255  */
256 template<class T>
257 const T& Min( const T& x, const T& y )
258 {
259  return x < y ? x : y;
260 }
261 
262 //---------------------------------------------------------------------------
263 /**
264  * Return the maximum of two objects. The class T must have the < operator
265  * defined.
266  */
267 template<class T>
268 const T& Max( const T& x, const T& y )
269 {
270  return x < y ? y : x;
271 }
272 
273 //---------------------------------------------------------------------------
274 /**
275  * Return the minimum of two objects determined by a predicate.
276  * If pr(x, y) is true, x is returned else y.
277  */
278 template<class T, class Pred>
279 const T& Min( const T& x, const T& y, Pred pr )
280 {
281  return pr( x, y ) ? x : y;
282 }
283 
284 //---------------------------------------------------------------------------
285 /**
286  * Return the maximum of two objects determined by a predicate.
287  * If pr(x, y) is true, y is returned else x.
288  */
289 template<class T, class Pred>
290 const T& Max( const T& x, const T& y, Pred pr )
291 {
292  return pr( x, y ) ? y : x;
293 }
294 
295 /** \brief Class to contain current OpenGL view, projection and draw matrices */
297 {
298 private:
299  bool _needsDelete;
300 
301 public:
302  int* viewMatrix;
303  GlsMatrixType* projMatrix;
304  GlsMatrixType* modelMatrix;
305 
306  /** Default constructor
307  * Keeps everything NULL */
308  GLS_EXPORT OpenGLMatrices();
309 
310  /** Copy constructor
311  * Pointers are copied as-is, copies of the
312  * data are NOT made. */
313  GLS_EXPORT OpenGLMatrices( const OpenGLMatrices& src );
314 
315  /** Another constructor.
316  * Pointers are copied as-is, copies of the
317  * data are NOT made. */
318  GLS_EXPORT OpenGLMatrices( int* view,
319  GlsMatrixType* proj,
320  GlsMatrixType* model );
321 
322  /** Destructor */
323  GLS_EXPORT ~OpenGLMatrices();
324 
325  /** Retrieves the current OpenGL Matrices from the
326  * OpenGL Subsystem */
327  GLS_EXPORT void GetCurrent();
328 };
329 
330 /** Find a transformation that will convert to a new coordinate
331  * system defined by the given origin and basis vectors (i,j,k).
332  * \note The new i,j,k vectors are in respect to the current origin.
333  * (i.e. for transformation that moves the origin
334  * along the x axis by 5 units you should pass in
335  * (Vector(5,0,0), Vector(1,0,0), Vector(0,1,0) , Vector(0,0,1))
336  * NOT (Vector(5,0,0), Vector(6,0,0), Vector(5,1,0) , Vector(5,0,1))
337  * Template argument is either double or float.
338  * \param new_origin Vector to the new coordinate system origin.
339  * \param new_i Vector parallel to the new x-axis with magnitude equal to one unit in the new coordinate system.
340  * \param new_j Vector parallel to the new y-axis with magnitude equal to one unit in the new coordinate system.
341  * \param new_k Vector parallel to the new z-axis with magnitude equal to one unit in the new coordinate system.
342  *
343  * \returns transformation matrix to the new coordinate system
344  */
345 template<class T>
346 GlsMatrixAffine<T> FindCoordinateTransformation( const Vector& new_origin, const Vector& new_i, const Vector& new_j, const Vector& new_k )
347 {
348  GlsMatrixAffine<T> transform;
349  GlsMatrixAffine<T> rotation_scaling;
350 
351  // First translate to the new origin
352 
353  transform.Translate( -new_origin );
354 
355  // Build a matrix taking the standard basis vectors to the new basis vectors
356 
357  rotation_scaling( 0, 0 ) = new_i.x;
358  rotation_scaling( 0, 1 ) = new_j.x;
359  rotation_scaling( 0, 2 ) = new_k.x;
360  rotation_scaling( 1, 0 ) = new_i.y;
361  rotation_scaling( 1, 1 ) = new_j.y;
362  rotation_scaling( 1, 2 ) = new_k.y;
363  rotation_scaling( 2, 0 ) = new_i.z;
364  rotation_scaling( 2, 1 ) = new_j.z;
365  rotation_scaling( 2, 2 ) = new_k.z;
366 
367  // Invert because we want the new basis vectors to become the standard basis vectors
368  rotation_scaling.Invert();
369 
370  // Combine the translation and rotation to produce the complete transformation
371  return rotation_scaling * transform;
372 }
373 
374 template<class T>
375 void FindCoordinateTransformation( const Vector& new_origin, const Vector& new_i, const Vector& new_j, const Vector& new_k, GlsMatrixAffine<T>& result )
376 {
377  GlsMatrixAffine<T> transform;
378  GlsMatrixAffine<T> rotation_scaling;
379 
380  // First translate to the new origin
381 
382  transform.Translate( -new_origin );
383 
384  // Build a matrix taking the standard basis vectors to the new basis vectors
385 
386  rotation_scaling( 0, 0 ) = new_i.x;
387  rotation_scaling( 0, 1 ) = new_j.x;
388  rotation_scaling( 0, 2 ) = new_k.x;
389  rotation_scaling( 1, 0 ) = new_i.y;
390  rotation_scaling( 1, 1 ) = new_j.y;
391  rotation_scaling( 1, 2 ) = new_k.y;
392  rotation_scaling( 2, 0 ) = new_i.z;
393  rotation_scaling( 2, 1 ) = new_j.z;
394  rotation_scaling( 2, 2 ) = new_k.z;
395 
396  // Invert because we want the new basis vectors to become the standard basis vectors
397  rotation_scaling.Invert();
398 
399  // Combine the translation and rotation to produce the complete transformation
400  result = rotation_scaling * transform;
401 }
402 
403 /** Gets the transformation from one DisplayObject's object coordinates to another's
404  * Note: This method uses a screen-space transformation (DisplayObject::ModelMatrix). This requires that the two objects have been PreDrawn with the same view, but they do not need to be part of the same object heirarchy.
405  * Use GetObjectCoordinatesTransform unless GetObjectCoordinatesTransformSameView is required.
406  *
407  * \sa GetObjectCoordinatesTransform
408  *
409  * \param from The DisplayObject to start at
410  * \param to The DisplayObject to end at
411  * \param outTransform Out parameter - If the function returns true, this will contain the resulting transformation.
412  * \returns true on success, false if there was an error
413  */
414 GLS_EXPORT bool GetObjectCoordinatesTransformSameView( DisplayObject* from, DisplayObject* to, GlsMatrixType* outTransform );
415 
416 /** Gets the transformation from one DisplayObject's object coordinates to another's (if possible)
417  * This is the preferred method for determining the coordinate space relationship between two objects that have DynamicTransforms applied.
418  * Note: This method requires that the two objects are part of the same object heirarchy.
419  * Consider using GetObjectCoordinatesTransformSameView if your situation does not meet this requirement.
420  *
421  * \code
422  * // Example: Move objB to be in the same location as objA (including all DynamicTransforms)
423  * // Change Location of objB so that it's RotationPoint aligns with the RotationPoint of objA
424  * GlsMatrixType transform;
425  * if( GetObjectCoordinatesTransform( objA, objB, &transform ) )
426  * {
427  * Vector objA_rotationPoint_transformed = transform * (objA->Location() + objA->RotationPoint());
428  * objB->Location( objA_rotationPoint_transformed - objB->RotationPoint() );
429  * }
430  * else
431  * {
432  * // Error: objects are not in the same heirarchy
433  * }
434  * \endcode
435  *
436  * \sa GetObjectCoordinatesTransform
437  *
438  * \param from The DisplayObject to start at
439  * \param to The DisplayObject to end at
440  * \param outTransform Out parameter - If the function returns true, this will contain the resulting transformation.
441  * \returns true on success, false if the objects are not in the same heirarchy.
442  */
443 GLS_EXPORT bool GetObjectCoordinatesTransform( DisplayObject* from, DisplayObject* to, GlsMatrixType* outTransform );
444 
445 /** Test if the given points are not colinear (they are not in a line)
446  * \return true if the points are not colinear
447  * \return false if the points are colinear
448  */
449 GLS_EXPORT bool NotColinear( const Vector& a, const Vector& b, const Vector& c );
450 
451 /** Search the given Vertex array for the first three non-colinear vertices.
452  * \param arraySize The size of vertex_array
453  * \param array The Vertex array
454  * \param index1 variable to receive 1st array index
455  * \param index2 variable to receive 2nd array index
456  * \param index3 variable to receive 3rd array index
457  * \param isVectorArray true if array points to a Vector array, false if it
458  * points to a Vertex array
459  *
460  * \return true If the vertices were found
461  * \returns false If there are not three non-colinear vertices in the array
462  * if this occurs, the index values are undefined
463  */
464 GLS_EXPORT bool FindNonColinearVertices( int arraySize, Vector array[],
465  int& index1, int& index2, int& index3,
466  bool isVectorArray = true );
467 
468 /** Vertex version of FindNonColinearVertices */
469 inline bool FindNonColinearVertices( int arraySize, Vertex array[], int& index1, int& index2, int& index3 )
470 {
471  return FindNonColinearVertices( arraySize, array, index1, index2, index3, false );
472 }
473 
474 /** Recalculate the texture points of a given DisplayObject
475  * based on its valid texture coordinates
476  *
477  * \return true On success
478  * \return false If the texture points could not be calculated.
479  * (The object doesn't have three non-colinear vertices or doesn't have texture coordinates.)
480  */
481 GLS_EXPORT bool CalculateTexPointsFromTexCoords( DisplayObject* object );
482 
483 /** Encodes a string such that if it contains newlines, it will be wrapped with the "#$STRING_START$#" and "#$STRING_END$#" delimiters.
484  * \param dest Destination string
485  * \param src Source string
486  * \param dest_str_length Size of the destination buffer
487  * \return The length of the encoded string.
488  */
489 GLS_EXPORT int EncodeString( char* dest, const char* src, const int dest_str_length );
490 
491 /** Encodes a std::string such that there are no whitespace characters in the string
492  * \param src Source string
493  * \return The encoded string
494  */
495 GLS_EXPORT std::string EncodeString( const std::string& src );
496 
497 /** Returns a minimum length for a call to EncodeString.
498  * This is based on the clear text delimeters
499  */
500 GLS_EXPORT int EncodedStringMinLength();
501 
502 /** Encodes a string using C language encoding
503  * \param dest Destination string
504  * \param src Source string
505  * \param dest_str_length Size of the destination buffer
506  * \return The length of the encoded string
507  */
508 GLS_EXPORT int C_EncodeString( char* dest, const char* src, const int dest_str_length );
509 
510 /** Returns and encoded std::string using C language encoding
511  * \param src Source string
512  * \return The encoded string
513  */
514 GLS_EXPORT std::string C_EncodeString( const std::string& src );
515 
516 /** Decodes a string that was encoded using EncodeString
517  * \param dest Destination string
518  * \param src Source string
519  * \param dest_str_length Size of the destination buffer
520  * \return The length of the encoded string
521  */
522 GLS_EXPORT int DecodeString( char* dest, const char* src, const int dest_str_length );
523 
524 /** Decodes a std::string that was encoded using EncodeString
525  * \param src Encoded Source string
526  * \return The decoded string
527  */
528 GLS_EXPORT std::string DecodeString( const std::string& src );
529 
530 /** The InlinePixmap structure */
531 typedef struct
532 {
533  int width;
534  int height;
535  int comprSize;
536  unsigned char* pixels;
537 } InlinePixmap;
538 
539 GLS_EXPORT char* MakeRelativePath( const char* originalPath, const char* relativePath );
540 GLS_EXPORT void ConvertBackslashToSlash( char* str );
541 GLS_EXPORT void ConvertBackslashToSlash( std::string& str );
542 
543 /** Determines if the given value falls in any of the ranges passed in.
544  * range_check(int number_of_ranges, double test_value,
545  * int index_0,double range_0_min,double range_0_max,
546  *
547  * ...
548  *
549  * int index_n,double range_n_min,double range_n_max);
550  *
551  * For example, to return 1 for values 0-10 and 2 for values 10-20:
552  *
553  * index = range_check(2,val,
554  * 1, 0.0, 10.0,
555  * 2, 10.0, 20.0);
556  */
557 
558 GLS_EXPORT int range_check( int num, double val, ... );
559 
560 /** Attempts to open the given file. Pops up an error message box if the
561  * attempt fails
562  * \param filename The name of the file to open
563  * \param flags fopen style file arguments (e.g. "r")
564  * \param f Contains file pointer on success
565  * \return True if the operation was successful
566  */
567 GLS_EXPORT int Safe_fopen( const char* filename, char* flags, FILE** f );
568 /** Stream version */
569 GLS_EXPORT int Safe_fopen( const char* filename, char* flags, std::fstream& outstr );
570 
571 #ifdef ANDROID
572 /** Sets if assets should be loaded directly from the apk (default true).
573  * This only affects Android builds.
574  * \param enableDirectAssetLoading true to allow assets to be loaded directly from the apk
575  * false to force assets to be read from the resource directory (\see SetResourcePath)
576  * \post HasAssetExtension returns false for all filetypes if direct asset loading was disabled
577  */
578 GLS_EXPORT void EnableDirectAssetLoading( bool enableDirectAssetLoading );
579 
580 /** Returns if the filetype is one that can be loaded directly from the apk assets.
581  * This only affects Android builds.
582  * \param filename The filename with extension to check
583  * \return True if the filetype can be loaded directly from the apk assets,
584  * False if the file is loaded from internal or external storage
585  */
586 GLS_EXPORT bool HasAssetExtension( const char* filename );
587 
588 /** Returns if the file exists in the apk assets.
589  * This only affects Android builds.
590  * \param filename The name of the file
591  * \return True if the file is an asset that can be opened.
592  * Returns false if no asset exists with filename or the pointer to the AAssetManager, set with SetAssetManager, is null.
593  */
594 GLS_EXPORT bool AssetExists( const char* filename );
595 
596 /** Sets the Android Asset Manager to use.
597  * When the assetManager is null, apk assets cannot be loaded.
598  * This only affects Android builds.
599  * \param assetManager The pointer to the AAssetManager
600  */
601 GLS_EXPORT void SetAssetManager( AAssetManager* assetManager );
602 #endif
603 
604 #if defined( ANDROID ) || defined( __APPLE__ ) || ( defined( LINUX ) && defined( GLES ) ) || defined( QNX ) || defined( INTEGRITY )
605 /** Prepends the resource path to a file name.
606  * \param[in] filename_ The name of the file
607  * \return string containing ResourcePath+filename_, with OS specific path.
608  * On Android, apk asset files are not prepended with a path.
609  */
610 GLS_EXPORT std::string ResolvePath( const char* filename_ );
611 
612 /** Sets the path for locating resource files.
613  * On Android, this is the location where resources outside of apk assets are found.
614  * \param resourcePath The path where application resources will be found
615  */
616 GLS_EXPORT void SetResourcePath( const char* resourcePath );
617 
618 /** Attempts to open the given file. Prepends the filename with the path from SetResourcePath
619  * for non-absolute paths.
620  * On Android, filenames that match an apk asset are opened. Opened assets should be closed
621  * with fclose to free resources, not with the Android Asset Manager close function (AAsset_close)
622  * \param filename The name of the file to open
623  * \param flags fopen style file arguments (e.g. "r")
624  * \pre On Android, Asset Manager != NULL, set with SetAssetManager, when opening an apk asset
625  * \return FILE pointer or NULL otherwise
626  */
627 GLS_EXPORT FILE* gls_fopen( const char* filename, const char* flags );
628 #else
629 /** Pushes a resource search path onto the stack. The CWD is always
630  * implicitly searched first. The resource search paths are local to
631  * the calling thread only. This function should be called from the same
632  * thread as the resources are loaded from.
633  * \param resourcePath The directory path to add to the search paths
634  */
635 GLS_EXPORT void PushResourcePath( const char* resourcePath );
636 
637 /** Remove the first search path from the stack. The resource search paths
638  * are local to the calling thread only. This function should be called from
639  * the same thread as the matching PushResourcePath.
640  */
641 GLS_EXPORT void PopResourcePath();
642 
643 /** Pushes a function that can locate resources. The Resources finders are applied after the resource paths are searched
644  * \param finder The function that can locate resources to add to the search paths
645  */
646 GLS_EXPORT void PushResourceFinder( std::string ( *finder )( const std::string& ) );
647 
648 /** Resolves the given path searching the resource path list. The
649  * CWD is always implicity searched first.
650  * \param path The relative path to resolve
651  */
652 GLS_EXPORT std::string ResolvePath( const char* path );
653 
654 // helper method taking a std::string
655 inline std::string ResolvePath( const std::string& path )
656 {
657  return ResolvePath( path.c_str() );
658 }
659 
660 /** Attempts to open the given file. Relative file paths
661  * are resolved using ResolvePath.
662  * \param filename The name of the file to open
663  * \param flags fopen style file arguments (e.g. "r")
664  * \return FILE pointer or NULL otherwise
665  */
666 GLS_EXPORT FILE* gls_fopen( const char* filename, const char* flags );
667 #endif
668 
669 #ifdef __APPLE__
670 /** \return a string indicating the location of a specific file in the default resource bundle.
671  * This method is designed for runtime platforms that have a pre-defined bundle
672  * location that is not immediately known to the application until runtime.
673  * in iOS, this returns the path to the main application bundle with the file name appended.
674  * \param fileName A string referring to the file without a path.
675  */
676 GLS_EXPORT std::string GetAbsolutePathAndFileNameInDefaultResourceBundle( const char* fileName );
677 #endif
678 
679 /** Prepends the resource path to a file name.
680  * \param[in] fileName The name of the file
681  * \return string containing ResourcePath + fileName, with OS specific path.
682  * On Android, apk asset files are not prepended with a path.
683  */
684 GLS_EXPORT std::string ResolveRuntimeResourcePath( const char* fileName );
685 
686 /** \return true if the file exists, false otherwise
687  * \param filename The filename to check
688  */
689 GLS_EXPORT bool FileExists( const char* filename );
690 GLS_EXPORT bool FileExists( const std::string& filename );
691 
692 /** \return true if the file exists and is a directory, false otherwise
693  * \param filename The filename to check
694  */
695 GLS_EXPORT bool IsDirectory( const char* filename );
696 GLS_EXPORT bool IsDirectory( const std::string& filename );
697 
698 /** \return The file extension for a filepath
699  * \param filepath Filepath to get extension from
700  */
701 GLS_EXPORT std::string FileExtension( const std::string& filepath );
702 
703 /** \return The filename from a file path by stripping off anything to the left of a slash
704  * \param filepath
705  */
706 GLS_EXPORT std::string FileName( const std::string& filepath );
707 
708 /** \return a string containing the path portion of a filename
709  * by stripping off everything to the right of the rightmost slash
710  * \param filepath A string containing a file with a path
711  */
712 GLS_EXPORT std::string FilePath( const std::string& filepath );
713 
714 /** \return a pointer to the string containing the path portion of a filename
715  * by stripping off everything to the right of the rightmost slash
716  * \param name A string containing a file with a path
717  * \warning If this function is called more than once all previous values WILL CHANGE to contain the newest value
718  * \deprecated Use FilePath instead
719  */
720 GLS_EXPORT const char* GetFilePath( const char* name );
721 
722 /** \return The filename from a file path by stripping off anything to the left of a slash
723  * \param name A string containing just the file name without a path
724  * \warning If this function is called more than once all previous values WILL CHANGE to contain the newest value
725  * \deprecated Use FileName instead
726  */
727 GLS_EXPORT char* GetFileName( const char* name );
728 
729 /** Appends a trailing slash to a path string, if one isn't there already
730  * \param s File path
731  */
732 GLS_EXPORT void AppendTrailingSlash( char* s );
733 
734 /** Appends a trailing slash to a path string, if one isn't there already
735  * \param s File path
736  */
737 GLS_EXPORT void AppendTrailingSlash( std::string& s );
738 
739 /** Convert a directory path to have the correct OS
740  * slashes /, or \. Also make sure that the path ends in a \, or /.
741  * So you always have the form <name 1>\\<name 2>...<name n>\\\, or <name 1>/<name 2>...<name n>/
742  * \param path A path to convert
743  * \return a "new-ed" string which may be longer than the original.
744  * It is the calling functions responsibility to free the memory.
745  */
746 GLS_EXPORT char* PathToOS( const char* path );
747 
748 /** \return The file extension for a filename
749  * \param filename Filename to get extension from
750  * No longer allocates memory, you can let the returned string
751  * be colected as it falls out of scope
752  */
753 GLS_EXPORT std::string GetExtension( const std::string& filename );
754 
755 /** Gets the file name from a filename with path
756  * It does not allocate new memory, but rather just returns
757  * a pointer inside the original string
758  */
759 GLS_EXPORT const char* GetBaseName( const char* path );
760 
761 /** \return Pointer to a position within the given \a path where the filename starts.
762  * \deprecated This function is not const-correct. Prefer the const-correct version.
763  * \sa GetBaseName( const char* )
764  */
765 GLS_EXPORT char* GetBaseName( char* path );
766 
767 /** Removes and double slashes from a path.
768  * It will look for the specified type of slash.
769  * It will modify path, but since it can only shrink,
770  * no allocation is done.
771  * \param path The path to operate on.
772  * \param slash The type of slash to search for.
773  */
774 GLS_EXPORT void RemoveDoubleSlashes( char* path, char slash = '/' );
775 
776 /** Remove possible extra spaces the user might enter in the server name input field.
777  * \param entry String to be manupulated.
778  */
779 GLS_EXPORT void RemoveSpaces( std::string& entry );
780 
781 /** \return The minimum angular distance between angle1 and angle2 in degrees
782  * \param angle1 First angle
783  * \param angle2 Second angle
784  */
785 GLS_EXPORT float AngularDistanceDeg( float angle1, float angle2 );
786 
787 /** \return The minimum angular distance between angle1 and angle2 in radians
788  * \param angle1 First angle
789  * \param angle2 Second angle
790  */
791 GLS_EXPORT float AngularDistanceRad( float angle1, float angle2 );
792 
793 GLS_EXPORT bool ContainsNonBlank( const std::string& val );
794 
795 GLS_EXPORT bool GetNoSpaces( FILE* f, char* result, int maxLen );
796 GLS_EXPORT bool GetToEnd( std::istream& instr, std::string& result, bool decode );
797 GLS_EXPORT bool GetVertex( std::istream& instr, Vertex* vert, bool getColor );
798 
799 /** Searches the specified binary file for the specified tag, and adds what immediatly follows the tag to the nameList.
800  * Returns true if at least one is found, false otherwise.
801  */
802 GLS_EXPORT bool GetComponentClassNames( const char* dllFileName, DynamicArray<std::string>& nameList, const char* createClassTag = "CreateComponent_" );
803 
804 /** Opens the DLL and attempts to run GlsDefaultClassName(), if found.
805  * Returns an empty string if not found. */
806 GLS_EXPORT std::string GetDefaultComponentClassName( const char* dllFileName );
807 
808 /** Returns the qualified instance name of an object that is
809  * contained within given DisplayFrame. (e.g "cockpit.altimeter.needle")
810  * Note that names are only added for each DisplayFrame (not every Group)
811  * and the name of the topFrame is not included in the qualified name.
812  * \param topFrame The frame in which the qualification will make sense.
813  * \param obj The object which is a direct child or located somewhere below topFrame.
814  * \returns The qualified instance name or an empty string if the qualified
815  * instance name could not be determined. */
816 GLS_EXPORT std::string GetQualifiedInstanceName( const DisplayFrame* topFrame, const DisplayObject* obj );
817 
818 #if !defined( GLES ) || defined( GLES_ANGLE )
819 GLS_EXPORT bool OpenFileDialog( Fl_Window* win, char* filePath, unsigned int filePathSize,
820  char* directory = NULL, const char* filterStr = NULL,
821  const char* defaultExt = NULL, const char* title = NULL,
822  bool multiSelect = false, bool createFile = false,
823  bool fileMustExist = false, bool pathMustExist = false,
824  bool noChangeDirectory = false );
825 
826 GLS_EXPORT bool SaveFileDialog( Fl_Window* win, char* filePath, unsigned int filePathSize,
827  char* directory = NULL, const char* filterStr = NULL,
828  const char* defaultExt = NULL, const char* title = NULL,
829  bool createFile = false,
830  bool fileMustExist = false, bool pathMustExist = false,
831  bool noChangeDirectory = false );
832 #endif
833 GLS_EXPORT void CheckGLError( void );
834 
835 //---------------------------------------------------------------------------
836 /**
837  * Returns a string which is the uppercase version of the passed parameter.
838  *
839  * \param str original string to convert to Uppercase
840  *
841  * \return a string copy of the original but in all caps.
842  */
843 GLS_EXPORT std::string Uppercase( const std::string& str );
844 
845 GLS_EXPORT std::string ReplaceEnvironmentVariables( const char* originalPath );
846 
847 /** A singleton used for accessing the command line arguments in generated code */
849 {
850 public:
851  GLS_EXPORT glsCommandLine();
852  GLS_EXPORT void ReadCommandLine( int argc, char** argv );
853  GLS_EXPORT void Usage();
854 
855  int _argc;
856  char** _argv;
857 
858  /** Whether or not the app should run in silent mode */
859  bool SilentMode() const { return _silentMode; }
860 
861  static GLS_EXPORT glsCommandLine* Instance();
862 
863 private:
864  bool _silentMode;
865  static ScopedPtr<glsCommandLine> _instance;
866 };
867 
868 /** Used to make interface information visible to the user at design time*/
869 class InterfaceDescriptionClass DISTI_FINAL
870 {
871  char* _code; // e.g. "DynamicRotate("
872  char* _usage; // e.g. "void DynamicRotate(float angle, int axis)"
873  char* _comment; // e.g. "Sets dynamic rotation in degrees for the specified axis"
874 
875 public:
876  GLS_EXPORT InterfaceDescriptionClass();
877  GLS_EXPORT InterfaceDescriptionClass( const char* code, const char* usage, const char* comment );
878 
879  GLS_EXPORT ~InterfaceDescriptionClass();
880  GLS_EXPORT InterfaceDescriptionClass( const InterfaceDescriptionClass& source );
881  GLS_EXPORT InterfaceDescriptionClass& operator=( const InterfaceDescriptionClass& source );
882 
883  GLS_EXPORT void Code( const char* );
884  GLS_EXPORT void Usage( const char* );
885  GLS_EXPORT void Comment( const char* );
886 
887  const char* Code() const { return _code; }
888  const char* Usage() const { return _usage; }
889  const char* Comment() const { return _comment; }
890 
891 #if defined( DISTI_HAS_RVAL_REFS )
892  InterfaceDescriptionClass( InterfaceDescriptionClass&& source )
893  : _code( NULL )
894  , _usage( NULL )
895  , _comment( NULL )
896  {
897  StealFrom( source );
898  }
899 
900  InterfaceDescriptionClass& operator=( InterfaceDescriptionClass&& source )
901  {
902  if( this != &source )
903  {
904  // Destroy current values
905  delete[] _code;
906  delete[] _usage;
907  delete[] _comment;
908 
909  StealFrom( source );
910  }
911  return *this;
912  }
913 
914 private:
915  void StealFrom( InterfaceDescriptionClass& source )
916  {
917  // Take ownership
918  _code = source._code;
919  _usage = source._usage;
920  _comment = source._comment;
921 
922  // Relieve of ownership
923  source._code = NULL;
924  source._usage = NULL;
925  source._comment = NULL;
926  }
927 #endif
928 };
929 
931 
932 /** Base class for GlsMultiVal template */
934 {
935 public:
936  virtual ~GlsMultiValBase() {}
937 
938  //These are used to avoid template problems with VC6.0
939  typedef std::ostream ostreamType;
940  typedef std::istream istreamType;
941 
942  virtual void StreamOut( ostreamType& outstr ) const = 0;
943  virtual void StreamIn( istreamType& instr ) = 0;
944 };
945 
946 /** GlsMultiVal is used to effectivly create a structure containing up
947  * to 10 values of varying types. An instance of the class is capable
948  * of streaming itself to and from a text stream. The individual values
949  * will be separated by spaces when written and read from the stream.
950  * The types have to follow some rules:
951  * - They must themselves have the << and >> stream operators defined.
952  * - operator>> must read all data written by operator<< and must not consume spaces or other characters that follow it
953  * - They must have a default constructor
954  * - They must have a copy constructor
955  * - They shall not be void* (it is used for determining the end of the desired types).
956  * - If a GlsPropString is used, there must be only one, and it *must* be the
957  * last entry in the GlsMultiVal instance.
958  * - A GlsPropStringQuoted will work in any position.
959  * This is intended primarily for the GL Studio end user to use as a Class Property type.
960  */
961 template<class T1,
962  class T2 = void*,
963  class T3 = void*,
964  class T4 = void*,
965  class T5 = void*,
966  class T6 = void*,
967  class T7 = void*,
968  class T8 = void*,
969  class T9 = void*,
970  class T10 = void*>
972 {
973  int _numVals;
974  void CalcNumVals()
975  {
976  _numVals = 1;
977  if( typeid( T2 ) != typeid( void* ) )
978  _numVals++;
979  else
980  return;
981  if( typeid( T3 ) != typeid( void* ) )
982  _numVals++;
983  else
984  return;
985  if( typeid( T4 ) != typeid( void* ) )
986  _numVals++;
987  else
988  return;
989  if( typeid( T5 ) != typeid( void* ) )
990  _numVals++;
991  else
992  return;
993  if( typeid( T6 ) != typeid( void* ) )
994  _numVals++;
995  else
996  return;
997  if( typeid( T7 ) != typeid( void* ) )
998  _numVals++;
999  else
1000  return;
1001  if( typeid( T8 ) != typeid( void* ) )
1002  _numVals++;
1003  else
1004  return;
1005  if( typeid( T9 ) != typeid( void* ) )
1006  _numVals++;
1007  else
1008  return;
1009  if( typeid( T10 ) != typeid( void* ) )
1010  _numVals++;
1011  else
1012  return;
1013  }
1014 
1015 public:
1016  T1 _val1;
1017  T2 _val2;
1018  T3 _val3;
1019  T4 _val4;
1020  T5 _val5;
1021  T6 _val6;
1022  T7 _val7;
1023  T8 _val8;
1024  T9 _val9;
1025  T10 _val10;
1026 
1027  /** Default constructor.
1028  * The _val member types must have default constructors.
1029  */
1031  {
1032  CalcNumVals();
1033  }
1034 
1035  /** Copy constructor.
1036  * This GlsMultiVal will copy values from the src GlsMultiVal.
1037  * \param src GlsMultiVal object to use for initialization.
1038  * \return
1039  */
1040  GlsMultiVal( const GlsMultiVal& src )
1041  : _val1( src._val1 )
1042  , _val2( src._val2 )
1043  , _val3( src._val3 )
1044  , _val4( src._val4 )
1045  , _val5( src._val5 )
1046  , _val6( src._val6 )
1047  , _val7( src._val7 )
1048  , _val8( src._val8 )
1049  , _val9( src._val9 )
1050  , _val10( src._val10 )
1051  {
1052  CalcNumVals();
1053  }
1054  /** Full constructor. Creates a GlsMultiVal object with the provided data.
1055  * \param val1 First value to use for intialization of type T1.
1056  * \param val2 First value to use for intialization of type T2.
1057  * \param val3 First value to use for intialization of type T3.
1058  * \param val4 First value to use for intialization of type T4.
1059  * \param val5 First value to use for intialization of type T5.
1060  * \param val6 First value to use for intialization of type T6.
1061  * \param val7 First value to use for intialization of type T7.
1062  * \param val8 First value to use for intialization of type T8.
1063  * \param val9 First value to use for intialization of type T9.
1064  * \param val10 First value to use for intialization of type T10.
1065  * \return
1066  */
1068  const T1& val1,
1069  const T2& val2 = T2(),
1070  const T3& val3 = T3(),
1071  const T4& val4 = T4(),
1072  const T5& val5 = T5(),
1073  const T6& val6 = T6(),
1074  const T7& val7 = T7(),
1075  const T8& val8 = T8(),
1076  const T9& val9 = T9(),
1077  const T10& val10 = T10() )
1078  : _val1( val1 )
1079  , _val2( val2 )
1080  , _val3( val3 )
1081  , _val4( val4 )
1082  , _val5( val5 )
1083  , _val6( val6 )
1084  , _val7( val7 )
1085  , _val8( val8 )
1086  , _val9( val9 )
1087  , _val10( val10 )
1088  {
1089  CalcNumVals();
1090  }
1091 
1092  /** Compares two multival objects for equality */
1093  virtual bool operator==( const GlsMultiVal& val ) const
1094  {
1095  bool rval = true;
1096  // Only compare the number of used values.
1097  switch( _numVals )
1098  {
1099  // No breaks is intentional
1100  case 10: rval &= ( _val10 == val._val10 );
1101  case 9: rval &= ( _val9 == val._val9 );
1102  case 8: rval &= ( _val8 == val._val8 );
1103  case 7: rval &= ( _val7 == val._val7 );
1104  case 6: rval &= ( _val6 == val._val6 );
1105  case 5: rval &= ( _val5 == val._val5 );
1106  case 4: rval &= ( _val4 == val._val4 );
1107  case 3: rval &= ( _val3 == val._val3 );
1108  case 2: rval &= ( _val2 == val._val2 );
1109  case 1:
1110  rval &= ( _val1 == val._val1 );
1111  break;
1112  default:
1113  rval = false;
1114  }
1115  return rval;
1116  }
1117 
1118  /** Inverse of equality */
1119  virtual bool operator!=( const GlsMultiVal& val ) const
1120  {
1121  return !( *this == val );
1122  }
1123 
1124  /** StreamOut(). This function serializes itself into the provided stream object.
1125  * \param outstr This is the object used by the GlsMultiVal class to serialize itself onto.
1126  * \return
1127  */
1128  virtual void StreamOut( ostreamType& outstr ) const
1129  {
1130  outstr << _val1;
1131  if( _numVals >= 2 )
1132  outstr << " " << _val2;
1133  if( _numVals >= 3 )
1134  outstr << " " << _val3;
1135  if( _numVals >= 4 )
1136  outstr << " " << _val4;
1137  if( _numVals >= 5 )
1138  outstr << " " << _val5;
1139  if( _numVals >= 6 )
1140  outstr << " " << _val6;
1141  if( _numVals >= 7 )
1142  outstr << " " << _val7;
1143  if( _numVals >= 8 )
1144  outstr << " " << _val8;
1145  if( _numVals >= 9 )
1146  outstr << " " << _val9;
1147  if( _numVals >= 10 )
1148  outstr << " " << _val10;
1149  }
1150 
1151  /** StreamIn(). Uses the provided istream object to populate the current GlsMultiVal object
1152  * \param instr This is the stream object used by the GlsMultiVal instance to populate itself.
1153  * \return
1154  */
1155  virtual void StreamIn( istreamType& instr )
1156  {
1157  instr >> _val1;
1158  if( _numVals >= 2 )
1159  {
1160  instr.get(); // The separating space
1161  instr >> _val2;
1162  }
1163  if( _numVals >= 3 )
1164  {
1165  instr.get();
1166  instr >> _val3;
1167  }
1168  if( _numVals >= 4 )
1169  {
1170  instr.get();
1171  instr >> _val4;
1172  }
1173  if( _numVals >= 5 )
1174  {
1175  instr.get();
1176  instr >> _val5;
1177  }
1178  if( _numVals >= 6 )
1179  {
1180  instr.get();
1181  instr >> _val6;
1182  }
1183  if( _numVals >= 7 )
1184  {
1185  instr.get();
1186  instr >> _val7;
1187  }
1188  if( _numVals >= 8 )
1189  {
1190  instr.get();
1191  instr >> _val8;
1192  }
1193  if( _numVals >= 9 )
1194  {
1195  instr.get();
1196  instr >> _val9;
1197  }
1198  if( _numVals >= 10 )
1199  {
1200  instr.get();
1201  instr >> _val10;
1202  }
1203  }
1204 };
1205 
1206 GLS_EXPORT std::ostream& operator<<( std::ostream& outstr, const GlsMultiValBase& multiVal );
1207 GLS_EXPORT std::istream& operator>>( std::istream& instr, GlsMultiValBase& multiVal );
1208 
1209 /** GlsPropString is designed to be used as a string in GL Studio Class Properties.
1210  * It writes itself out as a single line, and will read in up to the next newline.
1211  * It will attempt to convert itself to and from std::strings.
1212  * If it is used in a GlsMultiVal, there must be only one, and it *must* be the
1213  * last entry in the GlsMultiVal instance.
1214  * See GlsPropStringQuoted for more usefulness in GlsMultiVal.
1215  */
1217 {
1218 public:
1219  std::string _string;
1220 
1221  /** Default constructor Creates an empty GlsPropString. */
1223  : _string( "" )
1224  {
1225  }
1226  /** Create a new GlsPropString using the provided std string.
1227  * \param str std::string to use to create the GlsPropString
1228  * \return
1229  */
1230  GlsPropString( const std::string& str )
1231  : _string( str )
1232  {
1233  }
1234 
1235  /** Create a new GlsPropString using the provided c-style string.
1236  * \param str c-style string to use to create the GlsPropString.
1237  * \return
1238  */
1239  GlsPropString( const char* str )
1240  : _string( str ? str : "" )
1241  {
1242  }
1243 
1244  operator std::string() const
1245  {
1246  return _string;
1247  }
1248 
1249  /** Get the string value for this object.
1250  * \return std::string containing the string value for this object.
1251  */
1252  std::string& String()
1253  {
1254  return _string;
1255  }
1256 
1257  /** Checks lexicographic equality of the two arguments */
1258  friend inline bool operator==( const GlsPropString& str1, const GlsPropString& str2 )
1259  {
1260  return str1._string == str2._string;
1261  }
1262 
1263  /** Checks lexicographic inequality of the two arguments */
1264  friend inline bool operator!=( const GlsPropString& str1, const GlsPropString& str2 )
1265  {
1266  return !( str1 == str2 );
1267  }
1268 };
1269 
1270 inline std::ostream& operator<<( std::ostream& outstr, const GlsPropString& str )
1271 {
1272  outstr << disti::C_EncodeString( str._string );
1273  return outstr;
1274 }
1275 inline std::istream& operator>>( std::istream& instr, GlsPropString& str )
1276 {
1277  std::string temp;
1278  disti::GetToEnd( instr, temp, false );
1279  str._string = disti::DecodeString( temp );
1280 
1281  return instr;
1282 }
1283 /** GlsPropStringQuoted is designed to be used as a string in GL Studio Class Properties.
1284  * It writes itself out as a single line surrounded with quotes (""), and will read in up to the next un-escaped quote.
1285  * It will attempt to convert itself to and from std::strings.
1286  * Use of GlsPropStringQuoted is preferred over GlsPropString for use in a GlsMultiVal.
1287  */
1289 {
1290 public:
1291  std::string _string;
1292 
1293  /** Default constructor, create an empty GlsPropStringQuoted object. */
1295  {
1296  }
1297  /** Constructor, create a new GlsPropStringQuoted object using the provided std::string object
1298  * \param str std::string object to use to create the GlsPropStringQuoted object
1299  * \return
1300  */
1301  GlsPropStringQuoted( const std::string& str )
1302  : _string( str )
1303  {
1304  }
1305  /** Constructor, create a new GlsPropStringQuoted object using the provided c-style string
1306  * \param str c-style string to use to create the GlsPropStringQuoted object
1307  * \return
1308  */
1309  GlsPropStringQuoted( const char* str )
1310  : _string( str )
1311  {
1312  }
1313 
1314  operator std::string() const
1315  {
1316  return _string;
1317  }
1318 
1319  std::string& String()
1320  {
1321  return _string;
1322  }
1323 
1324  bool operator==( const GlsPropStringQuoted& str ) const
1325  {
1326  return str._string == _string;
1327  }
1328 };
1329 
1330 inline std::ostream& operator<<( std::ostream& outstr, const GlsPropStringQuoted& str )
1331 {
1332  outstr << '\"' << disti::C_EncodeString( str._string ) << '\"';
1333  return outstr;
1334 }
1335 
1336 inline std::istream& operator>>( std::istream& instr, GlsPropStringQuoted& str )
1337 {
1338  std::string temp;
1339  str._string = "";
1340 
1341  // The next character should be a quote.
1342  // If it is not, we will attempt to do something useful anyway.
1343  if( instr.peek() != '\"' )
1344  {
1345  disti::GetToEnd( instr, temp, false );
1346  }
1347  else // Starts with quote
1348  {
1349  // Go ahead and consume the quote
1350  instr.get();
1351 
1352  int lastChar = 0;
1353  int currChar = 0;
1354  // Loop until we find an un-escaped quote or we run out of stream.
1355  while( instr.good() )
1356  {
1357  lastChar = currChar;
1358  currChar = instr.get();
1359  if( currChar != -1 )
1360  {
1361  if( currChar == '\"' && lastChar != '\\' )
1362  break; // We found the trailing quote
1363  temp += (char)currChar;
1364  }
1365  }
1366  }
1367 
1368  str._string = disti::DecodeString( temp );
1369 
1370  return instr;
1371 }
1372 
1373 #ifndef WIN32
1374 void SpawnBrowser( const char* url );
1375 #endif
1376 
1377 /** Call this to check for the availability of a DiSTI conrolled license.
1378  * It does not hold the license. It only checks it out and checks it back in.
1379  * \param licenseGroupName A name for what this license allows. i.e. "GL Studio Runtime".
1380  * \param feature The specific feature that will be checked out.
1381  * \param version The specific version that will be checked out.
1382  * \param quiet When true, no popup will occur upon missing license.
1383  */
1384 GLS_EXPORT bool CheckDistiLicense( const char* licenseGroupName, const char* feature, const char* version, bool quiet );
1385 
1386 /** This will set the m parameter to an orthographic projection.
1387  * The current value of m is ignored.
1388  * This does NOT make any OpenGL calls.
1389  */
1390 GLS_EXPORT void GlsGetOrtho( GlsMatrixType& m,
1391  double left,
1392  double right,
1393  double bottom,
1394  double top,
1395  double zNear,
1396  double zFar );
1397 
1398 /** This will set the m parameter to a perspective projection.
1399  * The current value of m is ignored
1400  * This does NOT make any OpenGL calls.
1401  */
1402 GLS_EXPORT void GlsGetPerspective( GlsMatrixType& m,
1403  double fovy,
1404  double aspect,
1405  double zNear,
1406  double zFar );
1407 
1408 // using a namespace to help avoid collisions with user code. Future functionality should prefer to go here
1409 namespace Util
1410 {
1411  ////////////////////////////////////////////////////////////////////////////////
1412  /// Clamps a value to the range [min, max]
1413  /// \param val The value to clamp
1414  /// \param min The minimum value in the range
1415  /// \param max The maximum value in the range
1416  ////////////////////////////////////////////////////////////////////////////////
1417  template<class T>
1418  T Clamp( const T& val, const T& min, const T& max )
1419  {
1420  return std::min( max, std::max( min, val ) );
1421  }
1422 
1423  ////////////////////////////////////////////////////////////////////////////////
1424  /// Split a string and add to existing vector of elements with delimeters removed.
1425  /// \param s The string to split
1426  /// \param delim The delimiter to split the string on.
1427  /// \param elems The vector of elements to append each split string to.
1428  /// \param maxElems The maximum number of elements to split. Remaining elements
1429  /// are appended unsplit as the last value. If 0, it does not
1430  /// have a maximum.
1431  /// \note Adapted from http://stackoverflow.com/questions/236129/split-a-string-in-c
1432  ////////////////////////////////////////////////////////////////////////////////
1433  inline void Split( const std::string& s, const char delim, std::vector<std::string>& elems, const std::size_t maxElems = 0 )
1434  {
1435  std::istringstream ss( s );
1436  std::string item;
1437  while( std::getline( ss, item, delim ) )
1438  {
1439  elems.push_back( DISTI_RVAL_MOVE( item ) );
1440  if( elems.size() == maxElems )
1441  {
1442  break;
1443  }
1444  }
1445  if( elems.size() == maxElems && ss.good() && maxElems > 0 )
1446  {
1447  std::string remainder;
1448  std::getline( ss, remainder, '\0' );
1449  elems.back() += delim + remainder;
1450  }
1451  }
1452 
1453  ////////////////////////////////////////////////////////////////////////////////
1454  /// Split a string return a vector of the elements with delimeters removed.
1455  /// \param s The string to split
1456  /// \param delim The delimiter to split the string on.
1457  /// \param maxElems The maximum number of elements to split. Remaining elements
1458  /// are appended unsplit as the last value. If 0, it does not
1459  /// have a maximum.
1460  /// \return The vector of split elements.
1461  /// \note Adapted from http://stackoverflow.com/questions/236129/split-a-string-in-c
1462  ////////////////////////////////////////////////////////////////////////////////
1463  inline std::vector<std::string> Split( const std::string& s, const char delim, const std::size_t maxElems = 0 )
1464  {
1465  std::vector<std::string> elems;
1466  Split( s, delim, elems, maxElems );
1467  return elems;
1468  }
1469 
1470  /// Passing null to std::string is not well-defined. Create a string safely.
1471  inline std::string MakeString( const char* const cStr )
1472  {
1473  return ( cStr ? cStr : "" );
1474  }
1475 } // namespace Util
1476 
1477 ///////////////////////////////////////////////////////////////////////////////////////////////////
1478 // Forward declarations for globals managed by GlsGlobals.
1479 class GlsFontMan;
1480 class IGlsStateManager;
1481 class List_c;
1482 class Mutex;
1483 class TextureLoaderList;
1484 
1485 /// Hold global objects so we can control order of destruction.
1487 {
1488 public:
1489  /// Singleton instance
1490  GLS_EXPORT static GlsGlobals& Instance();
1491 
1492  /// Gets the image list. \sa GetImageListMutex()
1493  GLS_EXPORT List_c& GetImageList();
1494 
1495  /// Gets the mutex for protecting the image list. \sa GetImageList()
1496  GLS_EXPORT Mutex& GetImageListMutex();
1497 
1498  /// Gets the global font manager.
1499  GLS_EXPORT GlsFontMan& GetFontMan();
1500 
1501  /// Gets the global state manager instance
1502  GLS_EXPORT IGlsStateManager& GetStateManager();
1503 
1504  /// Gets the global list of texture loaders
1505  GLS_EXPORT TextureLoaderList& GetTextureLoaders();
1506 
1507 private:
1508  // Order of objects is important here since they are destroyed in the reverse order listed
1509  ScopedPtr<List_c> _imageList;
1510  ScopedPtr<Mutex> _imageListMutex;
1511  ScopedPtr<GlsFontMan> _fontMan;
1512  ScopedPtr<IGlsStateManager> _stateManager;
1513  ScopedPtr<TextureLoaderList> _textureLoaders;
1514 
1515  GlsGlobals();
1516  GlsGlobals( const GlsGlobals& ) DISTI_SPECIAL_MEM_FUN_DELETE;
1517  void operator=( const GlsGlobals& ) DISTI_SPECIAL_MEM_FUN_DELETE;
1518 };
1519 
1520 // Check that bitness matches detected value
1521 namespace Detail
1522 {
1523  // We need this function because 'static_assert' replacements for pre-C++11 compilers cannot be at file scope.
1524  inline void _checkPointerSize()
1525  {
1526  // clang-format off
1527  DISTI_STATIC_ASSERT_STR( ( DISTI_IS_BITNESS( 64 ) && sizeof( void* ) == 8 )
1528  || ( DISTI_IS_BITNESS( 32 ) && sizeof( void* ) == 4 ),
1529  "Pointer size is unexpected for this bitness" );
1530  DISTI_STATIC_ASSERT_STR( DISTI_IS_BITNESS( 64 ) ^ DISTI_IS_BITNESS( 32 ), "Expected one bitness to be detected." );
1531  // clang-format on
1532  }
1533 } // namespace Detail
1534 } // namespace disti
1535 
1536 // Our own local versions of a few glu methods to avoid needing to include the GL Utility library
1537 GLS_EXPORT void glsPerspective( double fovy, double aspect, double zNear, double zFar );
1538 
1539 #ifdef MATRIX_TYPE_FLOAT
1540 GLS_EXPORT bool glsProject( double objx, double objy, double objz,
1541  const float modelMatrix[ 16 ],
1542  const float projMatrix[ 16 ],
1543  const int viewport[ 4 ],
1544  double* winx, double* winy, double* winz );
1545 
1546 GLS_EXPORT bool glsUnProject( double winx, double winy, double winz,
1547  const float modelMatrix[ 16 ],
1548  const float projMatrix[ 16 ],
1549  const int viewport[ 4 ],
1550  double* objx, double* objy, double* objz );
1551 #else
1552 GLS_EXPORT bool glsProject( double objx, double objy, double objz,
1553  const double modelMatrix[ 16 ],
1554  const double projMatrix[ 16 ],
1555  const int viewport[ 4 ],
1556  double* winx, double* winy, double* winz );
1557 
1558 GLS_EXPORT bool glsUnProject( double winx, double winy, double winz,
1559  const double modelMatrix[ 16 ],
1560  const double projMatrix[ 16 ],
1561  const int viewport[ 4 ],
1562  double* objx, double* objy, double* objz );
1563 #endif
1564 
1565 #endif
The DistiUnhideGlobalsDummyClass class.
const T & Min(const T &x, const T &y)
Definition: util.h:257
int EncodedStringMinLength()
GlsPropStringQuoted(const std::string &str)
Definition: util.h:1301
virtual void StreamOut(ostreamType &outstr) const
Definition: util.h:1128
#define DISTI_STATIC_ASSERT_STR(expr, msg)
Uses C++11's static_assert() because it is available on this platform.
Definition: gls_cpp_lang_support.h:384
std::string GetExtension(const std::string &filename)
Definition: vertex.h:409
GlsDefinedColorEnum
Definition: util.h:188
bool IS_NEGATIVE(const X &x)
Definition: util.h:133
const int INLINE_TEXTURE_LINE_LENGTH
Definition: util.h:115
Definition: util.h:1288
std::string & String()
Definition: util.h:1252
std::string FileExtension(const std::string &filepath)
void GlsGetPerspective(GlsMatrixType &m, double fovy, double aspect, double zNear, double zFar)
GlsPropString(const char *str)
Definition: util.h:1239
unsigned char glsDefinedColors[GLS_COLOR_MAX][4]
bool IsNearZero(X x)
Definition: util.h:152
virtual bool operator!=(const GlsMultiVal &val) const
Definition: util.h:1119
Definition: dynamic_array.h:66
The disti::DynamicArray class. A templated array of objects capable of dynamically growing...
Class to contain current OpenGL view, projection and draw matrices.
Definition: util.h:296
std::string FileName(const std::string &filepath)
const char * GetBaseName(const char *path)
bool VeryCloseToZero(X x)
Definition: util.h:148
int EncodeString(char *dest, const char *src, const int dest_str_length)
The GlsMatrixAffine class.
Definition: util.h:848
void AppendTrailingSlash(char *s)
Definition: util.h:971
GlsFontMan & GetFontMan()
Gets the global font manager.
void RemoveDoubleSlashes(char *path, char slash= '/')
Definition: texture_loader.h:55
bool CheckDistiLicense(const char *licenseGroupName, const char *feature, const char *version, bool quiet)
std::string GetQualifiedInstanceName(const DisplayFrame *topFrame, const DisplayObject *obj)
Hold global objects so we can control order of destruction.
Definition: util.h:1486
std::string GetDefaultComponentClassName(const char *dllFileName)
Definition: util.h:933
bool BETWEEN(const X &x, const X1 &x1, const X2 &x2)
Definition: util.h:125
GlsMultiVal()
Definition: util.h:1030
char * PathToOS(const char *path)
bool IS_ZERO(X x)
Definition: util.h:156
Definition: gls_state_manager_interface.h:67
void RemoveSpaces(std::string &entry)
float OpenGLVersion()
const T & Max(const T &x, const T &y)
Definition: util.h:268
virtual bool operator==(const GlsMultiVal &val) const
Definition: util.h:1093
GlsPropStringQuoted(const char *str)
Definition: util.h:1309
bool SilentMode() const
Definition: util.h:859
A file for all GL Studio files to include.
Mutex & GetImageListMutex()
Gets the mutex for protecting the image list.
int range_check(int num, double val,...)
std::ostream & operator<<(std::ostream &outstr, const AttributeName &name)
Defines the stream out operator.
bool GetObjectCoordinatesTransformSameView(DisplayObject *from, DisplayObject *to, GlsMatrixType *outTransform)
float AngularDistanceRad(float angle1, float angle2)
std::string Uppercase(const std::string &str)
void ChangeGlsDefinedColor(GlsDefinedColorEnum index, unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha)
Definition: util.h:217
Definition: scoped_ptr.h:53
GlsPropString()
Definition: util.h:1222
void PopResourcePath()
bool GetComponentClassNames(const char *dllFileName, DynamicArray< std::string > &nameList, const char *createClassTag="CreateComponent_")
VertexNoColor Vector
Definition: gls_font_base.h:66
GlsMatrixAffine< T > FindCoordinateTransformation(const Vector &new_origin, const Vector &new_i, const Vector &new_j, const Vector &new_k)
Definition: util.h:346
bool FindNonColinearVertices(int arraySize, Vector array[], int &index1, int &index2, int &index3, bool isVectorArray=true)
Definition: util.h:1216
bool GetObjectCoordinatesTransform(DisplayObject *from, DisplayObject *to, GlsMatrixType *outTransform)
int DecodeString(char *dest, const char *src, const int dest_str_length)
bool CalculateTexPointsFromTexCoords(DisplayObject *object)
TextureLoaderList & GetTextureLoaders()
Gets the global list of texture loaders.
Definition: gls_mutex.h:52
friend bool operator!=(const GlsPropString &str1, const GlsPropString &str2)
Definition: util.h:1264
Definition: util.h:531
The disti::Vertex class. A class for manipulating 3D vertices.
GlsMultiVal(const GlsMultiVal &src)
Definition: util.h:1040
void PushResourcePath(const char *resourcePath)
IGlsStateManager & GetStateManager()
Gets the global state manager instance.
void Translate(Type x, Type y, Type z)
Definition: gls_matrix_affine.h:198
bool FileExists(const char *filename)
int C_EncodeString(char *dest, const char *src, const int dest_str_length)
static GlsGlobals & Instance()
Singleton instance.
virtual void StreamIn(istreamType &instr)
Definition: util.h:1155
GlsMultiVal(const T1 &val1, const T2 &val2=T2(), const T3 &val3=T3(), const T4 &val4=T4(), const T5 &val5=T5(), const T6 &val6=T6(), const T7 &val7=T7(), const T8 &val8=T8(), const T9 &val9=T9(), const T10 &val10=T10())
Definition: util.h:1067
FILE * gls_fopen(const char *filename, const char *flags)
bool IsDirectory(const char *filename)
float AngularDistanceDeg(float angle1, float angle2)
std::string FilePath(const std::string &filepath)
Definition: gls_font_man.h:59
bool Equal(T1 x, T2 y, float precision=0.001f)
Definition: util.h:246
char * GetFileName(const char *name)
List_c & GetImageList()
Gets the image list.
bool NotColinear(const Vector &a, const Vector &b, const Vector &c)
const char * GetFilePath(const char *name)
Definition: vertex.h:84
std::string ResolveRuntimeResourcePath(const char *fileName)
void PushResourceFinder(std::string(*finder)(const std::string &))
A smart pointer with unique ownership – poor man's std::unique_ptr.
std::string ResolvePath(const char *path)
bool CloseToZero(const X x, const X threshold=X(1e-1))
Definition: util.h:141
friend bool operator==(const GlsPropString &str1, const GlsPropString &str2)
Definition: util.h:1258
Contains the DistiAssert macro.
Definition: util.h:869
Macros and helper code to determine what subset of C++11/14/17 is available.
void GlsGetOrtho(GlsMatrixType &m, double left, double right, double bottom, double top, double zNear, double zFar)
GlsPropString(const std::string &str)
Definition: util.h:1230
int Safe_fopen(const char *filename, char *flags, FILE **f)
unsigned char * GlsDefinedColor(GlsDefinedColorEnum index)
Definition: util.h:209
Definition: bmpimage.h:46
Definition: list.h:134
GlsPropStringQuoted()
Definition: util.h:1294
bool IS_POSITIVE(const X &x)
Definition: util.h:137