platform.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _PLATFORM_H_
  23. #define _PLATFORM_H_
  24. #include <stdlib.h>
  25. #ifndef _TORQUECONFIG_H_
  26. #include "torqueConfig.h"
  27. #endif
  28. #ifndef _TORQUE_TYPES_H_
  29. #include "platform/types.h"
  30. #endif
  31. #ifndef _PLATFORMASSERT_H_
  32. #include "platform/platformAssert.h"
  33. #endif
  34. #ifndef _MSGBOX_H_
  35. #include "platform/nativeDialogs/msgBox.h"
  36. #endif
  37. #ifndef _VERSION_H_
  38. #include "app/version.h"
  39. #endif
  40. #ifndef _TORQUE_STRING_H_
  41. #include "core/util/str.h"
  42. #endif
  43. #ifndef _TORQUE_SAFEDELETE_H_
  44. #include "core/util/safeDelete.h"
  45. #endif
  46. #include <new>
  47. #include <typeinfo>
  48. /// Global processor identifiers.
  49. ///
  50. /// @note These enums must be globally scoped so that they work with the inline assembly
  51. enum ProcessorType
  52. {
  53. CPU_X86Compatible,
  54. CPU_ArmCompatible,
  55. CPU_Intel,
  56. CPU_AMD,
  57. CPU_Apple
  58. };
  59. /// Properties for CPU.
  60. enum ProcessorProperties
  61. {
  62. CPU_PROP_C = (1<<0), ///< We should use C fallback math functions.
  63. CPU_PROP_FPU = (1<<1), ///< Has an FPU. (It better!)
  64. CPU_PROP_MMX = (1<<2), ///< Supports MMX instruction set extension.
  65. CPU_PROP_3DNOW = (1<<3), ///< Supports AMD 3dNow! instruction set extension.
  66. CPU_PROP_SSE = (1<<4), ///< Supports SSE instruction set extension.
  67. CPU_PROP_RDTSC = (1<<5), ///< Supports Read Time Stamp Counter op.
  68. CPU_PROP_SSE2 = (1<<6), ///< Supports SSE2 instruction set extension.
  69. CPU_PROP_SSE3 = (1<<7), ///< Supports SSE3 instruction set extension.
  70. CPU_PROP_SSE3ex = (1<<8), ///< Supports extended SSE3 instruction set
  71. CPU_PROP_SSE4_1 = (1<<9), ///< Supports SSE4_1 instruction set extension.
  72. CPU_PROP_SSE4_2 = (1<<10), ///< Supports SSE4_2 instruction set extension.
  73. CPU_PROP_AVX = (1<<11), ///< Supports AVX256 instruction set extension.
  74. CPU_PROP_MP = (1<<12), ///< This is a multi-processor system.
  75. CPU_PROP_LE = (1<<13), ///< This processor is LITTLE ENDIAN.
  76. CPU_PROP_64bit = (1<<14), ///< This processor is 64-bit capable
  77. CPU_PROP_NEON = (1<<15), ///< Supports the Arm Neon instruction set extension.
  78. };
  79. /// Processor info manager.
  80. struct Processor
  81. {
  82. /// Gather processor state information.
  83. static void init();
  84. };
  85. #if defined(TORQUE_SUPPORTS_GCC_INLINE_X86_ASM)
  86. #define TORQUE_DEBUGBREAK() { asm ( "int 3"); }
  87. #elif defined (TORQUE_SUPPORTS_VC_INLINE_X86_ASM) // put this test second so that the __asm syntax doesn't break the Visual Studio Intellisense parser
  88. #define TORQUE_DEBUGBREAK() { __asm { int 3 }; }
  89. #else
  90. /// Macro to do in-line debug breaks, used for asserts. Does inline assembly when possible.
  91. #define TORQUE_DEBUGBREAK() Platform::debugBreak();
  92. #endif
  93. /// Physical type of a drive.
  94. enum DriveType
  95. {
  96. DRIVETYPE_FIXED = 0, ///< Non-removable fixed drive.
  97. DRIVETYPE_REMOVABLE = 1, ///< Removable drive.
  98. DRIVETYPE_REMOTE = 2, ///< Networked/remote drive.
  99. DRIVETYPE_CDROM = 3, ///< CD-Rom.
  100. DRIVETYPE_RAMDISK = 4, ///< A ramdisk!
  101. DRIVETYPE_UNKNOWN = 5 ///< Don't know.
  102. };
  103. // Some forward declares for later.
  104. class Point2I;
  105. template<class T> class Vector;
  106. template<typename Signature> class Signal;
  107. struct InputEventInfo;
  108. namespace Platform
  109. {
  110. // Time
  111. struct LocalTime
  112. {
  113. U8 sec; ///< Seconds after minute (0-59)
  114. U8 min; ///< Minutes after hour (0-59)
  115. U8 hour; ///< Hours after midnight (0-23)
  116. U8 month; ///< Month (0-11; 0=january)
  117. U8 monthday; ///< Day of the month (1-31)
  118. U8 weekday; ///< Day of the week (0-6, 6=sunday)
  119. U16 year; ///< Current year minus 1900
  120. U16 yearday; ///< Day of year (0-365)
  121. bool isdst; ///< True if daylight savings time is active
  122. };
  123. enum ALERT_ASSERT_RESULT
  124. {
  125. ALERT_ASSERT_DEBUG,
  126. ALERT_ASSERT_IGNORE,
  127. ALERT_ASSERT_IGNORE_ALL,
  128. ALERT_ASSERT_EXIT
  129. };
  130. void getLocalTime(LocalTime &);
  131. /// Converts the local time to a formatted string appropriate
  132. /// for the current platform.
  133. String localTimeToString( const LocalTime &lt );
  134. U32 getTime();
  135. U32 getVirtualMilliseconds();
  136. /// Returns the milliseconds since the system was started. You should
  137. /// not depend on this for high precision timing.
  138. /// @see PlatformTimer
  139. U32 getRealMilliseconds();
  140. void advanceTime(U32 delta);
  141. S32 getBackgroundSleepTime();
  142. // Platform control
  143. void init();
  144. void initConsole();
  145. void shutdown();
  146. void process();
  147. // Math control state
  148. U32 getMathControlState();
  149. void setMathControlState(U32 state);
  150. void setMathControlStateKnown();
  151. // Process control
  152. void sleep(U32 ms);
  153. bool excludeOtherInstances(const char *string);
  154. bool checkOtherInstances(const char *string);
  155. void restartInstance();
  156. void postQuitMessage(const S32 in_quitVal);
  157. void forceShutdown(S32 returnValue);
  158. // Debug
  159. void outputDebugString(const char *string, ...);
  160. void debugBreak();
  161. // Random
  162. F32 getRandom();
  163. // Window state
  164. void setWindowLocked(bool locked);
  165. void minimizeWindow();
  166. //const Point2I &getWindowSize();
  167. void setWindowSize( U32 newWidth, U32 newHeight, bool fullScreen );
  168. void closeWindow();
  169. // File stuff
  170. bool doCDCheck();
  171. StringTableEntry createPlatformFriendlyFilename(const char *filename);
  172. struct FileInfo
  173. {
  174. const char* pFullPath;
  175. const char* pFileName;
  176. U32 fileSize;
  177. };
  178. bool cdFileExists(const char *filePath, const char *volumeName, S32 serialNum);
  179. void fileToLocalTime(const FileTime &ft, LocalTime *lt);
  180. /// compare file times returns < 0 if a is earlier than b, >0 if b is earlier than a
  181. S32 compareFileTimes(const FileTime &a, const FileTime &b);
  182. bool stringToFileTime(const char * string, FileTime * time);
  183. bool fileTimeToString(FileTime * time, char * string, U32 strLen);
  184. /// Compares the last modified time between two file paths. Returns < 0 if
  185. /// the first file is earlier than the second, > 0 if the second file is earlier
  186. /// than the first, and 0 if the files are equal.
  187. ///
  188. /// If either of the files doesn't exist it returns -1.
  189. S32 compareModifiedTimes( const char *firstPath, const char *secondPath );
  190. // Directory functions. Dump path returns false iff the directory cannot be
  191. // opened.
  192. StringTableEntry getCurrentDirectory();
  193. bool setCurrentDirectory(StringTableEntry newDir);
  194. StringTableEntry getTemporaryDirectory();
  195. StringTableEntry getTemporaryFileName();
  196. /// Returns the filename of the torque executable.
  197. /// On Win32, this is the .exe file.
  198. /// On Mac, this is the .app/ directory bundle.
  199. StringTableEntry getExecutableName();
  200. /// Returns full pathname of the torque executable without filename
  201. StringTableEntry getExecutablePath();
  202. /// Returns the full path to the directory that contains main.tscript.
  203. /// Tools scripts are validated as such if they are in this directory or a
  204. /// subdirectory of this directory.
  205. StringTableEntry getMainDotCsDir();
  206. /// Set main.tscript directory. Used in runEntryScript()
  207. void setMainDotCsDir(const char *dir);
  208. StringTableEntry getPrefsPath(const char *file = NULL);
  209. char *makeFullPathName(const char *path, char *buffer, U32 size, const char *cwd = NULL);
  210. StringTableEntry stripBasePath(const char *path);
  211. bool isFullPath(const char *path);
  212. StringTableEntry makeRelativePathName(const char *path, const char *to);
  213. String stripExtension( String fileName, Vector< String >& validExtensions );
  214. bool dumpPath(const char *in_pBasePath, Vector<FileInfo>& out_rFileVector, S32 recurseDepth = -1);
  215. bool dumpDirectories( const char *path, Vector<StringTableEntry> &directoryVector, S32 depth = 0, bool noBasePath = false );
  216. bool hasSubDirectory( const char *pPath );
  217. bool getFileTimes(const char *filePath, FileTime *createTime, FileTime *modifyTime);
  218. bool isFile(const char *pFilePath);
  219. S32 getFileSize(const char *pFilePath);
  220. bool isDirectory(const char *pDirPath);
  221. bool isSubDirectory(const char *pParent, const char *pDir);
  222. void addExcludedDirectory(const char *pDir);
  223. void clearExcludedDirectories();
  224. bool isExcludedDirectory(const char *pDir);
  225. bool deleteDirectory(const char* pPath);
  226. bool fileDelete(const char *name);
  227. /// Given a directory path, create all necessary directories for that path to exist.
  228. bool createPath(const char *path); // create a directory path
  229. // Alerts
  230. void AlertOK(const char *windowTitle, const char *message);
  231. bool AlertOKCancel(const char *windowTitle, const char *message);
  232. bool AlertRetry(const char *windowTitle, const char *message);
  233. ALERT_ASSERT_RESULT AlertAssert(const char *windowTitle, const char *message);
  234. // Volumes
  235. struct VolumeInformation
  236. {
  237. StringTableEntry RootPath;
  238. StringTableEntry Name;
  239. StringTableEntry FileSystem;
  240. U32 SerialNumber;
  241. U32 Type;
  242. bool ReadOnly;
  243. };
  244. extern struct VolumeInformation *PVolumeInformation;
  245. // Volume functions.
  246. void getVolumeNamesList( Vector<const char*>& out_rNameVector, bool bOnlyFixedDrives = false );
  247. void getVolumeInformationList( Vector<VolumeInformation>& out_rVolumeInfoVector, bool bOnlyFixedDrives = false );
  248. struct SystemInfo_struct
  249. {
  250. struct Processor
  251. {
  252. ProcessorType type;
  253. const char* name;
  254. U32 mhz;
  255. bool isMultiCore;
  256. bool isHyperThreaded;
  257. U32 numLogicalProcessors;
  258. U32 numPhysicalProcessors;
  259. U32 properties; // CPU type specific enum
  260. } processor;
  261. };
  262. extern Signal<void(void)> SystemInfoReady;
  263. extern SystemInfo_struct SystemInfo;
  264. // Web page launch function:
  265. bool openWebBrowser( const char* webAddress );
  266. // display Splash Window
  267. bool displaySplashWindow( String path );
  268. // close Splash Window
  269. bool closeSplashWindow();
  270. void openFolder( const char* path );
  271. // Open file at the OS level, according to registered file-types.
  272. void openFile( const char* path );
  273. const char* getLoginPassword();
  274. bool setLoginPassword( const char* password );
  275. const char* getClipboard();
  276. bool setClipboard(const char *text);
  277. // User Specific Functions
  278. StringTableEntry getUserHomeDirectory();
  279. StringTableEntry getUserDataDirectory();
  280. bool getUserIsAdministrator();
  281. // Displays a fancy platform specific message box
  282. S32 messageBox(const UTF8 *title, const UTF8 *message, MBButtons buttons = MBOkCancel, MBIcons icon = MIInformation);
  283. /// Description of a keyboard input we want to ignore.
  284. struct KeyboardInputExclusion
  285. {
  286. KeyboardInputExclusion()
  287. {
  288. key = 0;
  289. orModifierMask = 0;
  290. andModifierMask = 0;
  291. }
  292. /// The key code to ignore, e.g. KEY_TAB. If this and the other
  293. /// conditions match, ignore the key.
  294. S32 key;
  295. /// if(modifiers | orModifierMask) and the other conditions match,
  296. /// ignore the key.
  297. U32 orModifierMask;
  298. /// if((modifiers & andModifierMask) == andModifierMask) and the
  299. /// other conditions match, ignore the key stroke.
  300. U32 andModifierMask;
  301. /// Based on the values above, determine if a given input event
  302. /// matchs this exclusion rule.
  303. const bool checkAgainstInput(const InputEventInfo *info) const;
  304. };
  305. /// Reset the keyboard input exclusion list.
  306. void clearKeyboardInputExclusion();
  307. /// Add a new keyboard exclusion.
  308. void addKeyboardInputExclusion(const KeyboardInputExclusion &kie);
  309. /// Check if a given input event should be excluded.
  310. const bool checkKeyboardInputExclusion(const InputEventInfo *info);
  311. /// Set/Get whether this is a web deployment
  312. bool getWebDeployment();
  313. void setWebDeployment(bool v);
  314. };
  315. //------------------------------------------------------------------------------
  316. // Unicode string conversions
  317. // UNICODE is a windows platform API switching flag. Don't define it on other platforms.
  318. #ifdef UNICODE
  319. #define dT(s) L##s
  320. #else
  321. #define dT(s) s
  322. #endif
  323. //------------------------------------------------------------------------------
  324. // Misc StdLib functions
  325. #define QSORT_CALLBACK FN_CDECL
  326. inline void dQsort(void *base, U32 nelem, U32 width, S32 (QSORT_CALLBACK *fcmp)(const void *, const void *))
  327. {
  328. qsort(base, nelem, width, fcmp);
  329. }
  330. //-------------------------------------- Some all-around useful inlines and globals
  331. //
  332. ///@defgroup ObjTrickery Object Management Trickery
  333. ///
  334. /// These functions are to construct and destruct objects in memory
  335. /// without causing a free or malloc call to occur. This is so that
  336. /// we don't have to worry about allocating, say, space for a hundred
  337. /// NetAddresses with a single malloc call, calling delete on a single
  338. /// NetAdress, and having it try to free memory out from under us.
  339. ///
  340. /// @{
  341. /// Constructs an object that already has memory allocated for it.
  342. template <class T>
  343. inline T* constructInPlace(T* p)
  344. {
  345. return new ( p ) T;
  346. }
  347. template< class T >
  348. inline T* constructArrayInPlace( T* p, U32 num )
  349. {
  350. return new ( p ) T[ num ];
  351. }
  352. /// Copy constructs an object that already has memory allocated for it.
  353. template <class T>
  354. inline T* constructInPlace(T* p, const T* copy)
  355. {
  356. return new ( p ) T( *copy );
  357. }
  358. template <class T, class T2> inline T* constructInPlace(T* ptr, T2 t2)
  359. {
  360. return new ( ptr ) T( t2 );
  361. }
  362. template <class T, class T2, class T3> inline T* constructInPlace(T* ptr, T2 t2, T3 t3)
  363. {
  364. return new ( ptr ) T( t2, t3 );
  365. }
  366. template <class T, class T2, class T3, class T4> inline T* constructInPlace(T* ptr, T2 t2, T3 t3, T4 t4)
  367. {
  368. return new ( ptr ) T( t2, t3, t4 );
  369. }
  370. template <class T, class T2, class T3, class T4, class T5> inline T* constructInPlace(T* ptr, T2 t2, T3 t3, T4 t4, T5 t5)
  371. {
  372. return new ( ptr ) T( t2, t3, t4, t5 );
  373. }
  374. /// Destructs an object without freeing the memory associated with it.
  375. template <class T>
  376. inline void destructInPlace(T* p)
  377. {
  378. p->~T();
  379. }
  380. //------------------------------------------------------------------------------
  381. /// Memory functions
  382. #if !defined(TORQUE_DISABLE_MEMORY_MANAGER)
  383. # define TORQUE_TMM_ARGS_DECL , const char* fileName, const U32 lineNum
  384. # define TORQUE_TMM_ARGS , fileName, lineNum
  385. # define TORQUE_TMM_LOC , __FILE__, __LINE__
  386. extern void* FN_CDECL operator new(dsize_t size, const char*, const U32);
  387. extern void* FN_CDECL operator new[](dsize_t size, const char*, const U32);
  388. extern void FN_CDECL operator delete(void* ptr);
  389. extern void FN_CDECL operator delete[](void* ptr);
  390. # define _new new(__FILE__, __LINE__)
  391. # define new _new
  392. #else
  393. # define TORQUE_TMM_ARGS_DECL
  394. # define TORQUE_TMM_ARGS
  395. # define TORQUE_TMM_LOC
  396. #endif
  397. #define dMalloc(x) dMalloc_r(x, __FILE__, __LINE__)
  398. #define dRealloc(x, y) dRealloc_r(x, y, __FILE__, __LINE__)
  399. extern void setBreakAlloc(dsize_t);
  400. extern void setMinimumAllocUnit(U32);
  401. extern void* dMalloc_r(dsize_t in_size, const char*, const dsize_t);
  402. extern void dFree(void* in_pFree);
  403. extern void* dRealloc_r(void* in_pResize, dsize_t in_size, const char*, const dsize_t);
  404. extern void* dRealMalloc(dsize_t);
  405. extern void dRealFree(void*);
  406. extern void *dMalloc_aligned(dsize_t in_size, S32 alignment);
  407. extern void dFree_aligned(void *);
  408. inline void dFree( const void* p )
  409. {
  410. dFree( ( void* ) p );
  411. }
  412. // Helper function to copy one array into another of different type
  413. template<class T,class S> void dCopyArray(T *dst, const S *src, dsize_t size)
  414. {
  415. for (dsize_t i = 0; i < size; i++)
  416. dst[i] = (T)src[i];
  417. }
  418. extern void* dMemcpy(void *dst, const void *src, dsize_t size);
  419. extern void* dMemmove(void *dst, const void *src, dsize_t size);
  420. extern void* dMemset(void *dst, S32 c, dsize_t size);
  421. extern S32 dMemcmp(const void *ptr1, const void *ptr2, dsize_t size);
  422. // Special case of the above function when the arrays are the same type (use memcpy)
  423. template<class T> void dCopyArray(T *dst, const T *src, dsize_t size)
  424. {
  425. dMemcpy(dst, src, size * sizeof(T));
  426. }
  427. /// The dALIGN macro ensures the passed declaration is
  428. /// data aligned at 16 byte boundaries.
  429. #if defined( TORQUE_COMPILER_VISUALC )
  430. #define dALIGN( decl ) __declspec( align( 16 ) ) decl
  431. #define dALIGN_BEGIN __declspec( align( 16 ) )
  432. #define dALIGN_END
  433. #elif defined( TORQUE_COMPILER_GCC )
  434. #define dALIGN( decl ) decl __attribute__( ( aligned( 16 ) ) )
  435. #define dALIGN_BEGIN
  436. #define dALIGN_END __attribute__( ( aligned( 16 ) ) )
  437. #else
  438. #define dALIGN( decl ) decl
  439. #define dALIGN_BEGIN()
  440. #define dALIGN_END()
  441. #endif
  442. //------------------------------------------------------------------------------
  443. // FileIO functions
  444. extern bool dFileDelete(const char *name);
  445. extern bool dFileRename(const char *oldName, const char *newName);
  446. extern bool dFileTouch(const char *name);
  447. extern bool dPathCopy(const char *fromName, const char *toName, bool nooverwrite = true);
  448. typedef void* FILE_HANDLE;
  449. enum DFILE_STATUS
  450. {
  451. DFILE_OK = 1
  452. };
  453. extern FILE_HANDLE dOpenFileRead(const char *name, DFILE_STATUS &error);
  454. extern FILE_HANDLE dOpenFileReadWrite(const char *name, bool append, DFILE_STATUS &error);
  455. extern S32 dFileRead(FILE_HANDLE handle, U32 bytes, char *dst, DFILE_STATUS &error);
  456. extern S32 dFileWrite(FILE_HANDLE handle, U32 bytes, const char *dst, DFILE_STATUS &error);
  457. extern void dFileClose(FILE_HANDLE handle);
  458. extern StringTableEntry osGetTemporaryDirectory();
  459. //------------------------------------------------------------------------------
  460. struct Math
  461. {
  462. /// Initialize the math library with the appropriate libraries
  463. /// to support hardware acceleration features.
  464. ///
  465. /// @param properties Leave zero to detect available hardware. Otherwise,
  466. /// pass CPU instruction set flags that you want to load
  467. /// support for.
  468. static void init(U32 properties = 0);
  469. };
  470. /// @}
  471. #endif