diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000000..3aa0176041a --- /dev/null +++ b/.clang-format @@ -0,0 +1,82 @@ +# ============================================================================== +# Minimalist Clang-Format Configuration (Baseline) +# ============================================================================== +# ============================================================================== +# CUSTOM CLANG-FORMAT OFF FLAGS +# When disabling clang-format, please use one of the following standard flags +# to explain why, making it easier to search and maintain the codebase: +# +# Usage: // clang-format off: [FLAG_NAME] - optional details +# +# Available Flags: +# [LEGACY_VC6] - For strict C++03 / VC6 compiler compatibility. +# [MACRO_COMPACT] - To prevent concise macros from multi-line wrapping. +# [MACRO_INDENT] - When the formatter messes up a macro's internal indentation. +# [TABLE_ALIGN] - For matrices, lookup tables, and 2D arrays alignment. +# [MATH_ALIGN] - For preserving manual spaces in complex math/logic formulas. +# [X_MACRO] - For structured X-Macro lists. +# [INLINE_ASM] - For preserving inline assembly instruction formatting. +# [BITFIELD_ALIGN] - For aligning bitfield sizes (:) in structs / hardware maps. +# [BITMASK_ALIGN] - For visual alignment of bitwise operations and bit flags. +# ============================================================================== +Language: Cpp +Standard: c++20 + +# 1. Non-Destructive Core Setting +# ------------------------------------------------------------------------------ +# Completely disable automatic line wrapping to preserve manual formatting. +ColumnLimit: 0 + +# 2. Indentation & Tabs +# ------------------------------------------------------------------------------ +UseTab: AlignWithSpaces +IndentWidth: 2 +TabWidth: 2 +ContinuationIndentWidth: 2 +AccessModifierOffset: -2 +IndentCaseLabels: true +AlignTrailingComments: false +SpacesBeforeTrailingComments: 4 + +# 3. Braces Style: Allman +# ------------------------------------------------------------------------------ +BreakBeforeBraces: Custom +BraceWrapping: + AfterCaseLabel: true + AfterClass: true + AfterControlStatement: Always + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterStruct: true + AfterUnion: true + BeforeCatch: true + BeforeElse: true + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false +AllowShortEnumsOnASingleLine: false + +# 4. Pointers & Spaces +# ------------------------------------------------------------------------------ +PointerAlignment: Left +SpacesInParentheses: false +BreakConstructorInitializers: BeforeComma + +# 5. Legacy & Compatibility (VC6 / Custom Macros) +# ------------------------------------------------------------------------------ +# Prevent expanding/collapsing short blocks and functions to minimize diffs +AllowShortFunctionsOnASingleLine: All +AllowShortBlocksOnASingleLine: Always +AlignEscapedNewlines: Left + +# Handle custom legacy macros so the parser doesn't break +Macros: + - CPP_11(x)=x + +IndentPPDirectives: BeforeHash +ConstructorInitializerIndentWidth: 2 + +# 6. Includes +# ------------------------------------------------------------------------------ +SortIncludes: false \ No newline at end of file diff --git a/Core/GameEngine/Include/Common/AddonCompat.h b/Core/GameEngine/Include/Common/AddonCompat.h index 7b8bc2c9e97..c9ba341a4e1 100644 --- a/Core/GameEngine/Include/Common/AddonCompat.h +++ b/Core/GameEngine/Include/Common/AddonCompat.h @@ -22,4 +22,4 @@ namespace addon { extern Bool HasFullviewportDat(); -} // namespace addon +} // namespace addon diff --git a/Core/GameEngine/Include/Common/ArchiveFile.h b/Core/GameEngine/Include/Common/ArchiveFile.h index 63987f9c9cb..1ace08627c4 100644 --- a/Core/GameEngine/Include/Common/ArchiveFile.h +++ b/Core/GameEngine/Include/Common/ArchiveFile.h @@ -35,13 +35,13 @@ class File; /** - * An archive file is itself a collection of sub files. Each file inside the archive file - * has a unique name by which it can be accessed. The ArchiveFile object class is the - * runtime interface to the mix file and the sub files. Each file inside the mix - * file can be accessed by the openFile(). - * - * ArchiveFile interfaces can be created by the TheArchiveFileSystem object. - */ + * An archive file is itself a collection of sub files. Each file inside the archive file + * has a unique name by which it can be accessed. The ArchiveFile object class is the + * runtime interface to the mix file and the sub files. Each file inside the mix + * file can be accessed by the openFile(). + * + * ArchiveFile interfaces can be created by the TheArchiveFileSystem object. + */ //=============================== class ArchiveFile @@ -50,23 +50,23 @@ class ArchiveFile ArchiveFile(); virtual ~ArchiveFile(); - virtual Bool getFileInfo( const AsciiString& filename, FileInfo *fileInfo) const = 0; ///< fill in the fileInfo struct with info about the file requested. - virtual File* openFile( const Char *filename, Int access = 0) = 0; ///< Open the specified file within the archive file - virtual void closeAllFiles() = 0; ///< Close all file opened in this archive file - virtual AsciiString getName() = 0; ///< Returns the name of the archive file - virtual AsciiString getPath() = 0; ///< Returns full path and name of archive file - virtual void setSearchPriority( Int new_priority ) = 0; ///< Set this archive file's search priority - virtual void close() = 0; ///< Close this archive file - void attachFile(File *file); + virtual Bool getFileInfo(const AsciiString& filename, FileInfo* fileInfo) const = 0; ///< fill in the fileInfo struct with info about the file requested. + virtual File* openFile(const Char* filename, Int access = 0) = 0; ///< Open the specified file within the archive file + virtual void closeAllFiles() = 0; ///< Close all file opened in this archive file + virtual AsciiString getName() = 0; ///< Returns the name of the archive file + virtual AsciiString getPath() = 0; ///< Returns full path and name of archive file + virtual void setSearchPriority(Int new_priority) = 0; ///< Set this archive file's search priority + virtual void close() = 0; ///< Close this archive file + void attachFile(File* file); - void getFileListInDirectory(const AsciiString& currentDirectory, const AsciiString& originalDirectory, const AsciiString& searchName, FilenameList &filenameList, Bool searchSubdirectories) const; - void getFileListInDirectory(const DetailedArchivedDirectoryInfo *dirInfo, const AsciiString& currentDirectory, const AsciiString& searchName, FilenameList &filenameList, Bool searchSubdirectories) const; + void getFileListInDirectory(const AsciiString& currentDirectory, const AsciiString& originalDirectory, const AsciiString& searchName, FilenameList& filenameList, Bool searchSubdirectories) const; + void getFileListInDirectory(const DetailedArchivedDirectoryInfo* dirInfo, const AsciiString& currentDirectory, const AsciiString& searchName, FilenameList& filenameList, Bool searchSubdirectories) const; - void addFile(const AsciiString& path, const ArchivedFileInfo *fileInfo); ///< add this file to our directory tree. + void addFile(const AsciiString& path, const ArchivedFileInfo* fileInfo); ///< add this file to our directory tree. protected: - const ArchivedFileInfo * getArchivedFileInfo(const AsciiString& filename) const; ///< return the ArchivedFileInfo from the directory tree. + const ArchivedFileInfo* getArchivedFileInfo(const AsciiString& filename) const; ///< return the ArchivedFileInfo from the directory tree. - File *m_file; ///< file pointer to the archive file on disk. Kept open so we don't have to continuously open and close the file all the time. + File* m_file; ///< file pointer to the archive file on disk. Kept open so we don't have to continuously open and close the file all the time. DetailedArchivedDirectoryInfo m_rootDirectory; }; diff --git a/Core/GameEngine/Include/Common/ArchiveFileSystem.h b/Core/GameEngine/Include/Common/ArchiveFileSystem.h index 88c3e80170b..5eba8a2144e 100644 --- a/Core/GameEngine/Include/Common/ArchiveFileSystem.h +++ b/Core/GameEngine/Include/Common/ArchiveFileSystem.h @@ -51,7 +51,7 @@ #include "Common/SubsystemInterface.h" #include "Common/AsciiString.h" -#include "Common/FileSystem.h" // for typedefs, etc. +#include "Common/FileSystem.h" // for typedefs, etc. #include "Common/STLTypedefs.h" //---------------------------------------------------------------------------- @@ -65,43 +65,42 @@ class ArchiveFile; // Type Defines //---------------------------------------------------------------------------- - //=============================== // ArchiveFileSystem //=============================== /** - * Creates and manages ArchiveFile interfaces. ArchiveFiles can be accessed - * by calling the openArchiveFile() member. ArchiveFiles can be accessed by - * name or by File interface. - * - * openFile() member searches all Archive files for the specified sub file. - */ + * Creates and manages ArchiveFile interfaces. ArchiveFiles can be accessed + * by calling the openArchiveFile() member. ArchiveFiles can be accessed by + * name or by File interface. + * + * openFile() member searches all Archive files for the specified sub file. + */ //=============================== class ArchivedDirectoryInfo; class DetailedArchivedDirectoryInfo; class ArchivedFileInfo; -typedef std::map DetailedArchivedDirectoryInfoMap; // Archived directory name to detailed archived directory info -typedef std::map ArchivedDirectoryInfoMap; // Archived directory name to archived directory info -typedef std::map ArchivedFileInfoMap; // Archived file name to archived file info -typedef std::map ArchiveFileMap; // Archive file name to archive data -typedef std::multimap ArchivedFileLocationMap; // Archived file name to archive data +typedef std::map DetailedArchivedDirectoryInfoMap; // Archived directory name to detailed archived directory info +typedef std::map ArchivedDirectoryInfoMap; // Archived directory name to archived directory info +typedef std::map ArchivedFileInfoMap; // Archived file name to archived file info +typedef std::map ArchiveFileMap; // Archive file name to archive data +typedef std::multimap ArchivedFileLocationMap; // Archived file name to archive data class ArchivedDirectoryInfo { public: - AsciiString m_path; // The full path to this directory - AsciiString m_directoryName; // The current directory - ArchivedDirectoryInfoMap m_directories; // Contained leaf directories - ArchivedFileLocationMap m_files; // Contained files + AsciiString m_path; // The full path to this directory + AsciiString m_directoryName; // The current directory + ArchivedDirectoryInfoMap m_directories; // Contained leaf directories + ArchivedFileLocationMap m_files; // Contained files }; class DetailedArchivedDirectoryInfo { public: - AsciiString m_directoryName; - DetailedArchivedDirectoryInfoMap m_directories; - ArchivedFileInfoMap m_files; + AsciiString m_directoryName; + DetailedArchivedDirectoryInfoMap m_directories; + ArchivedFileInfoMap m_files; }; class ArchivedFileInfo @@ -119,7 +118,6 @@ class ArchivedFileInfo } }; - class ArchiveFileSystem : public SubsystemInterface { public: @@ -132,19 +130,19 @@ class ArchiveFileSystem : public SubsystemInterface virtual void postProcessLoad() = 0; // ArchiveFile operations - virtual ArchiveFile* openArchiveFile( const Char *filename ) = 0; ///< Create new or return existing Archive file from file name - virtual void closeArchiveFile( const Char *filename ) = 0; ///< Close the one specified big file. - virtual void closeAllArchiveFiles() = 0; ///< Close all Archive files currently open + virtual ArchiveFile* openArchiveFile(const Char* filename) = 0; ///< Create new or return existing Archive file from file name + virtual void closeArchiveFile(const Char* filename) = 0; ///< Close the one specified big file. + virtual void closeAllArchiveFiles() = 0; ///< Close all Archive files currently open // File operations - virtual File* openFile( const Char *filename, Int access = 0, FileInstance instance = 0); ///< Search Archive files for specified file name and open it if found - virtual void closeAllFiles() = 0; ///< Close all files associated with Archive files - virtual Bool doesFileExist(const Char *filename, FileInstance instance = 0) const; ///< return true if that file exists in an archive file somewhere. + virtual File* openFile(const Char* filename, Int access = 0, FileInstance instance = 0); ///< Search Archive files for specified file name and open it if found + virtual void closeAllFiles() = 0; ///< Close all files associated with Archive files + virtual Bool doesFileExist(const Char* filename, FileInstance instance = 0) const; ///< return true if that file exists in an archive file somewhere. - void getFileListInDirectory(const AsciiString& currentDirectory, const AsciiString& originalDirectory, const AsciiString& searchName, FilenameList &filenameList, Bool searchSubdirectories) const; ///< search the given directory for files matching the searchName (egs. *.ini, *.rep). Possibly search subdirectories. Scans each Archive file. - Bool getFileInfo(const AsciiString& filename, FileInfo *fileInfo, FileInstance instance = 0) const; ///< see FileSystem.h + void getFileListInDirectory(const AsciiString& currentDirectory, const AsciiString& originalDirectory, const AsciiString& searchName, FilenameList& filenameList, Bool searchSubdirectories) const; ///< search the given directory for files matching the searchName (egs. *.ini, *.rep). Possibly search subdirectories. Scans each Archive file. + Bool getFileInfo(const AsciiString& filename, FileInfo* fileInfo, FileInstance instance = 0) const; ///< see FileSystem.h - virtual Bool loadBigFilesFromDirectory(AsciiString dir, AsciiString fileMask, Bool overwrite = FALSE) = 0; + virtual Bool loadBigFilesFromDirectory(AsciiString dir, AsciiString fileMask, Bool overwrite = FALSE) = 0; // Unprotected this for copy-protection routines ArchiveFile* getArchiveFile(const AsciiString& filename, FileInstance instance = 0) const; @@ -156,23 +154,24 @@ class ArchiveFileSystem : public SubsystemInterface protected: struct ArchivedDirectoryInfoResult { - ArchivedDirectoryInfoResult() : dirInfo(nullptr) {} + ArchivedDirectoryInfoResult() + : dirInfo(nullptr) + {} Bool valid() const { return dirInfo != nullptr; } ArchivedDirectoryInfo* dirInfo; - AsciiString lastToken; ///< Synonymous for file name if the search directory was a file path + AsciiString lastToken; ///< Synonymous for file name if the search directory was a file path }; ArchivedDirectoryInfoResult getArchivedDirectoryInfo(const Char* directory); - virtual void loadIntoDirectoryTree(ArchiveFile *archiveFile, Bool overwrite = FALSE); ///< load the archive file's header information and apply it to the global archive directory tree. + virtual void loadIntoDirectoryTree(ArchiveFile* archiveFile, Bool overwrite = FALSE); ///< load the archive file's header information and apply it to the global archive directory tree. ArchiveFileMap m_archiveFileMap; ArchivedDirectoryInfo m_rootDirectory; }; - -extern ArchiveFileSystem *TheArchiveFileSystem; +extern ArchiveFileSystem* TheArchiveFileSystem; //---------------------------------------------------------------------------- // Inlining diff --git a/Core/GameEngine/Include/Common/AsciiString.h b/Core/GameEngine/Include/Common/AsciiString.h index f2cb2246021..a59f221c81e 100644 --- a/Core/GameEngine/Include/Common/AsciiString.h +++ b/Core/GameEngine/Include/Common/AsciiString.h @@ -54,190 +54,187 @@ class UnicodeString; // ----------------------------------------------------- /** - AsciiString is the fundamental single-byte string type used in the Generals - code base, and should be preferred over all other string constructions - (e.g., array of char, STL string<>, WWVegas StringClass, etc.) + AsciiString is the fundamental single-byte string type used in the Generals + code base, and should be preferred over all other string constructions + (e.g., array of char, STL string<>, WWVegas StringClass, etc.) - Of course, other string setups may be used when necessary or appropriate! + Of course, other string setups may be used when necessary or appropriate! - AsciiString is modeled after the MFC CString class, with some minor - syntactic differences to keep in line with our coding conventions. + AsciiString is modeled after the MFC CString class, with some minor + syntactic differences to keep in line with our coding conventions. - Basically, AsciiString allows you to treat a string as an intrinsic - type, rather analogous to 'int' -- when passed by value, a new string - is created, and modifying the new string doesn't modify the original. - This is done fairly efficiently, so that no new memory allocation is done - unless the string is actually modified. + Basically, AsciiString allows you to treat a string as an intrinsic + type, rather analogous to 'int' -- when passed by value, a new string + is created, and modifying the new string doesn't modify the original. + This is done fairly efficiently, so that no new memory allocation is done + unless the string is actually modified. - Naturally, AsciiString handles all memory issues, so there's no need - to do anything to free memory... just allow the AsciiString's - destructor to run. + Naturally, AsciiString handles all memory issues, so there's no need + to do anything to free memory... just allow the AsciiString's + destructor to run. - AsciiStrings are suitable for use as automatic, member, or static variables. + AsciiStrings are suitable for use as automatic, member, or static variables. */ class AsciiString { private: - // Note, this is a Plain Old Data Structure... don't // add a ctor/dtor, 'cuz they won't ever be called. struct AsciiStringData { #if defined(RTS_DEBUG) - const char* m_debugptr; // just makes it easier to read in the debugger + const char* m_debugptr; // just makes it easier to read in the debugger #endif - unsigned short m_refCount; // reference count - unsigned short m_numCharsAllocated; // length of data allocated + unsigned short m_refCount; // reference count + unsigned short m_numCharsAllocated; // length of data allocated // char m_stringdata[]; - char* peek() { return (char*)(this+1); } + char* peek() { return (char*)(this + 1); } }; - #ifdef RTS_DEBUG +#ifdef RTS_DEBUG void validate() const; - #else - void validate() const { } - #endif +#else + void validate() const {} +#endif protected: - AsciiStringData* m_data; // pointer to ref counted string data + AsciiStringData* m_data; // pointer to ref counted string data char* peek() const; void releaseBuffer(); void ensureUniqueBufferOfSize(int numCharsNeeded, Bool preserveData, const char* strToCpy, const char* strToCat); public: - typedef Char value_type; typedef value_type* pointer; typedef const value_type* const_pointer; enum { - MAX_FORMAT_BUF_LEN = 2048, ///< max total len of string created by format/format_va - MAX_LEN = 32767 ///< max total len of any AsciiString, in chars + MAX_FORMAT_BUF_LEN = 2048, ///< max total len of string created by format/format_va + MAX_LEN = 32767 ///< max total len of any AsciiString, in chars }; - /** - This is a convenient global used to indicate the empty - string, so we don't need to construct temporaries - for such a common thing. + This is a convenient global used to indicate the empty + string, so we don't need to construct temporaries + for such a common thing. */ static const AsciiString TheEmptyString; /** - Default constructor -- construct a new, empty AsciiString. + Default constructor -- construct a new, empty AsciiString. */ AsciiString(); /** - Copy constructor -- make this AsciiString identical to the - other AsciiString. (This is actually quite efficient, because - they will simply share the same string and increment the - refcount.) + Copy constructor -- make this AsciiString identical to the + other AsciiString. (This is actually quite efficient, because + they will simply share the same string and increment the + refcount.) */ AsciiString(const AsciiString& stringSrc); /** - Constructor -- from a literal string. Constructs an AsciiString - with the given string. Note that a copy of the string is made; - the input ptr is not saved. - Note that this is no longer explicit, as the conversion is almost - always wanted, anyhow. + Constructor -- from a literal string. Constructs an AsciiString + with the given string. Note that a copy of the string is made; + the input ptr is not saved. + Note that this is no longer explicit, as the conversion is almost + always wanted, anyhow. */ AsciiString(const char* s); /** - Constructs an AsciiString with the given string and length. - The length must not be larger than the actual string length. + Constructs an AsciiString with the given string and length. + The length must not be larger than the actual string length. */ AsciiString(const char* s, int len); /** - Destructor. Not too exciting... clean up the works and such. + Destructor. Not too exciting... clean up the works and such. */ ~AsciiString(); /** - Return the length, in characters, of the string up to the first zero or null terminator. + Return the length, in characters, of the string up to the first zero or null terminator. */ int getLength() const; /** - Return the number of bytes used by the string up to the first zero or null terminator. + Return the number of bytes used by the string up to the first zero or null terminator. */ int getByteCount() const; /** - Return true iff the length of the string is zero. Equivalent - to (getLength() == 0) but slightly more efficient. + Return true iff the length of the string is zero. Equivalent + to (getLength() == 0) but slightly more efficient. */ Bool isEmpty() const; /** - Make the string empty. Equivalent to (str = "") but slightly more efficient. + Make the string empty. Equivalent to (str = "") but slightly more efficient. */ void clear(); /** - Return the character and the given (zero-based) index into the string. - No range checking is done (except in debug mode). + Return the character and the given (zero-based) index into the string. + No range checking is done (except in debug mode). */ char getCharAt(int index) const; /** - Return a pointer to the (null-terminated) string. Note that this is - a const pointer: do NOT change this! It is imperative that it be - impossible (or at least, really difficuly) for someone to change our - private data, since it might be shared amongst other AsciiStrings. + Return a pointer to the (null-terminated) string. Note that this is + a const pointer: do NOT change this! It is imperative that it be + impossible (or at least, really difficuly) for someone to change our + private data, since it might be shared amongst other AsciiStrings. */ const char* str() const; /** - Makes sure there is room for a string of len+1 characters, and - returns a pointer to the string buffer. This ensures that the - string buffer is NOT shared. This is intended for the file reader, - that is reading new strings in from a file. jba. + Makes sure there is room for a string of len+1 characters, and + returns a pointer to the string buffer. This ensures that the + string buffer is NOT shared. This is intended for the file reader, + that is reading new strings in from a file. jba. */ char* getBufferForRead(Int len); /** - Replace the contents of self with the given string. - (This is actually quite efficient, because - they will simply share the same string and increment the - refcount.) + Replace the contents of self with the given string. + (This is actually quite efficient, because + they will simply share the same string and increment the + refcount.) */ void set(const AsciiString& stringSrc); /** - Replace the contents of self with the given string. - Note that a copy of the string is made; the input ptr is not saved. + Replace the contents of self with the given string. + Note that a copy of the string is made; the input ptr is not saved. */ void set(const char* s); /** - Replace the contents of self with the given string and length. - Note that a copy of the string is made; the input ptr is not saved. - The length must not be larger than the actual string length. + Replace the contents of self with the given string and length. + Note that a copy of the string is made; the input ptr is not saved. + The length must not be larger than the actual string length. */ void set(const char* s, int len); /** - replace contents of self with the given string. Note the - nomenclature is translate rather than set; this is because - not all single-byte strings translate one-for-one into - UnicodeStrings, so some data manipulation may be necessary, - and the resulting strings may not be equivalent. + replace contents of self with the given string. Note the + nomenclature is translate rather than set; this is because + not all single-byte strings translate one-for-one into + UnicodeStrings, so some data manipulation may be necessary, + and the resulting strings may not be equivalent. */ void translate(const UnicodeString& stringSrc); /** - Concatenate the given string onto self. + Concatenate the given string onto self. */ void concat(const AsciiString& stringSrc); /** - Concatenate the given string onto self. + Concatenate the given string onto self. */ void concat(const char* s); /** - Concatenate the given character onto self. + Concatenate the given character onto self. */ void concat(const char c); @@ -262,123 +259,122 @@ class AsciiString void toLower(); /** - Remove the final character in the string. If the string is empty, - do nothing. (This is a rather dorky method, but used a lot in - text editing, thus its presence here.) + Remove the final character in the string. If the string is empty, + do nothing. (This is a rather dorky method, but used a lot in + text editing, thus its presence here.) */ void removeLastChar(); /** - Remove the final charCount characters in the string. If the string is empty, - do nothing. + Remove the final charCount characters in the string. If the string is empty, + do nothing. */ void truncateBy(const Int charCount); /** - Truncate the string to a length of maxLength characters, not including null termination, - by removing from the end. If the string is empty or shorter than maxLength, do nothing. + Truncate the string to a length of maxLength characters, not including null termination, + by removing from the end. If the string is empty or shorter than maxLength, do nothing. */ void truncateTo(const Int maxLength); /** - Analogous to sprintf() -- this formats a string according to the - given sprintf-style format string (and the variable argument list) - and stores the result in self. + Analogous to sprintf() -- this formats a string according to the + given sprintf-style format string (and the variable argument list) + and stores the result in self. */ void format(AsciiString format, ...); void format(const char* format, ...); /** - Identical to format(), but takes a va_list rather than - a variable argument list. (i.e., analogous to vsprintf.) + Identical to format(), but takes a va_list rather than + a variable argument list. (i.e., analogous to vsprintf.) */ void format_va(const AsciiString& format, va_list args); void format_va(const char* format, va_list args); /** - Conceptually identical to strcmp(). + Conceptually identical to strcmp(). */ int compare(const AsciiString& stringSrc) const; /** - Conceptually identical to strcmp(). + Conceptually identical to strcmp(). */ int compare(const char* s) const; /** - Conceptually identical to _stricmp(). + Conceptually identical to _stricmp(). */ int compareNoCase(const AsciiString& stringSrc) const; /** - Conceptually identical to _stricmp(). + Conceptually identical to _stricmp(). */ int compareNoCase(const char* s) const; /** - Conceptually identical to strchr(). + Conceptually identical to strchr(). */ const char* find(char c) const; /** - Conceptually identical to strrchr(). + Conceptually identical to strrchr(). */ const char* reverseFind(char c) const; /** - return true iff self starts with the given string. + return true iff self starts with the given string. */ Bool startsWith(const char* p) const; Bool startsWith(const AsciiString& stringSrc) const { return startsWith(stringSrc.str()); } /** - return true iff self starts with the given string. (case insensitive) + return true iff self starts with the given string. (case insensitive) */ Bool startsWithNoCase(const char* p) const; Bool startsWithNoCase(const AsciiString& stringSrc) const { return startsWithNoCase(stringSrc.str()); } /** - return true iff self ends with the given string. + return true iff self ends with the given string. */ Bool endsWith(const char* p) const; Bool endsWith(const AsciiString& stringSrc) const { return endsWith(stringSrc.str()); } /** - return true iff self ends with the given string. (case insensitive) + return true iff self ends with the given string. (case insensitive) */ Bool endsWithNoCase(const char* p) const; Bool endsWithNoCase(const AsciiString& stringSrc) const { return endsWithNoCase(stringSrc.str()); } /** - conceptually similar to strtok(): + conceptually similar to strtok(): - extract the next seps-delimited token from the front - of 'this' and copy it into 'token', returning true if a nonempty - token was found. (note that this modifies 'this' as well, stripping - the token off!) + extract the next seps-delimited token from the front + of 'this' and copy it into 'token', returning true if a nonempty + token was found. (note that this modifies 'this' as well, stripping + the token off!) */ Bool nextToken(AsciiString* token, const char* seps = nullptr); /** - return true iff the string is "NONE" (case-insensitive). - Hey, hokey, but we use it a ton. + return true iff the string is "NONE" (case-insensitive). + Hey, hokey, but we use it a ton. */ Bool isNone() const; Bool isNotEmpty() const { return !isEmpty(); } Bool isNotNone() const { return !isNone(); } -// -// You might think it would be a good idea to overload the * operator -// to allow for an implicit conversion to an char*. This is -// (in theory) a good idea, but in practice, there's lots of code -// that assumes it should check text fields for null, which -// is meaningless for us, since we never return a null ptr. -// -// operator const char*() const { return str(); } -// + // + // You might think it would be a good idea to overload the * operator + // to allow for an implicit conversion to an char*. This is + // (in theory) a good idea, but in practice, there's lots of code + // that assumes it should check text fields for null, which + // is meaningless for us, since we never return a null ptr. + // + // operator const char*() const { return str(); } + // - AsciiString& operator=(const AsciiString& stringSrc); ///< the same as set() - AsciiString& operator=(const char* s); ///< the same as set() + AsciiString& operator=(const AsciiString& stringSrc); ///< the same as set() + AsciiString& operator=(const char* s); ///< the same as set() void debugIgnoreLeaks(); - }; // ----------------------------------------------------- @@ -390,7 +386,8 @@ inline char* AsciiString::peek() const } // ----------------------------------------------------- -inline AsciiString::AsciiString() : m_data(0) +inline AsciiString::AsciiString() + : m_data(0) { validate(); } @@ -478,7 +475,7 @@ inline void AsciiString::concat(const char c) { validate(); /// this can probably be made more efficient, if necessary - char tmp[2] = { c, 0 }; + char tmp[2] = {c, 0}; concat(tmp); validate(); } diff --git a/Core/GameEngine/Include/Common/AudioAffect.h b/Core/GameEngine/Include/Common/AudioAffect.h index f58cb9e18b2..9724bc42104 100644 --- a/Core/GameEngine/Include/Common/AudioAffect.h +++ b/Core/GameEngine/Include/Common/AudioAffect.h @@ -32,13 +32,13 @@ // if it is set by the options panel, use the system setting parameter. Otherwise, this will be // appended to whatever the current system volume is. -enum AudioAffect CPP_11(: Int) +enum AudioAffect CPP_11( : Int) { - AudioAffect_Music = 0x01, - AudioAffect_Sound = 0x02, - AudioAffect_Sound3D = 0x04, - AudioAffect_Speech = 0x08, - AudioAffect_All = (AudioAffect_Music | AudioAffect_Sound | AudioAffect_Sound3D | AudioAffect_Speech), + AudioAffect_Music = 0x01, + AudioAffect_Sound = 0x02, + AudioAffect_Sound3D = 0x04, + AudioAffect_Speech = 0x08, + AudioAffect_All = (AudioAffect_Music | AudioAffect_Sound | AudioAffect_Sound3D | AudioAffect_Speech), AudioAffect_SystemSetting = 0x10, }; diff --git a/Core/GameEngine/Include/Common/AudioEventInfo.h b/Core/GameEngine/Include/Common/AudioEventInfo.h index 741ffeacc90..5b344e9c396 100644 --- a/Core/GameEngine/Include/Common/AudioEventInfo.h +++ b/Core/GameEngine/Include/Common/AudioEventInfo.h @@ -39,7 +39,7 @@ struct FieldParse; // USEFUL DECLARATIONS //////////////////////////////////////////////////////////////////////////// -enum AudioType CPP_11(: Int) +enum AudioType CPP_11( : Int) { AT_Music, AT_Streaming, @@ -47,7 +47,7 @@ enum AudioType CPP_11(: Int) }; extern const char* const theAudioPriorityNames[]; -enum AudioPriority CPP_11(: Int) +enum AudioPriority CPP_11( : Int) { AP_LOWEST, AP_LOW, @@ -58,78 +58,77 @@ enum AudioPriority CPP_11(: Int) AP_COUNT }; -extern const char *const theSoundTypeNames[]; -enum SoundType CPP_11(: Int) +extern const char* const theSoundTypeNames[]; +enum SoundType CPP_11( : Int) { - ST_UI = 0x0001, - ST_WORLD = 0x0002, - ST_SHROUDED = 0x0004, - ST_GLOBAL = 0x0008, - ST_VOICE = 0x0010, - ST_PLAYER = 0x0020, - ST_ALLIES = 0x0040, - ST_ENEMIES = 0x0080, - ST_EVERYONE = 0x0100, + ST_UI = 0x0001, + ST_WORLD = 0x0002, + ST_SHROUDED = 0x0004, + ST_GLOBAL = 0x0008, + ST_VOICE = 0x0010, + ST_PLAYER = 0x0020, + ST_ALLIES = 0x0040, + ST_ENEMIES = 0x0080, + ST_EVERYONE = 0x0100, }; -extern const char *const theAudioControlNames[]; -enum AudioControl CPP_11(: Int) +extern const char* const theAudioControlNames[]; +enum AudioControl CPP_11( : Int) { - AC_LOOP = 0x0001, - AC_RANDOM = 0x0002, - AC_ALL = 0x0004, - AC_POSTDELAY = 0x0008, - AC_INTERRUPT = 0x0010, + AC_LOOP = 0x0001, + AC_RANDOM = 0x0002, + AC_ALL = 0x0004, + AC_POSTDELAY = 0x0008, + AC_INTERRUPT = 0x0010, }; class DynamicAudioEventInfo; struct AudioEventInfo : public MemoryPoolObject { - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( AudioEventInfo, "AudioEventInfo" ) + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(AudioEventInfo, "AudioEventInfo") public: - AsciiString m_audioName; // This name matches the name of the AudioEventRTS - AsciiString m_filename; // For music tracks, this is the filename of the track - - Real m_volume; // Desired volume of this audio - Real m_volumeShift; // Desired volume shift of the audio - Real m_minVolume; // Clamped minimum value, useful when muting sound effects - Real m_pitchShiftMin; // minimum pitch shift value - Real m_pitchShiftMax; // maximum pitch shift value - Int m_delayMin; // minimum delay before we'll fire up another one of these - Int m_delayMax; // maximum delay before we'll fire up another one of these - Int m_limit; // Limit to the number of these sounds that can be fired up simultaneously - Int m_loopCount; // number of times to loop this sound - - AudioPriority m_priority; // Priority of this sound - UnsignedInt m_type; // Type of sound - UnsignedInt m_control; // control of sound - - std::vector m_soundsMorning; // Sounds to play in the wee hours of the morning - std::vector m_sounds; // Default sounds to play - std::vector m_soundsNight; // Sounds to play at night - std::vector m_soundsEvening; // Sounds to play in the evening + AsciiString m_audioName; // This name matches the name of the AudioEventRTS + AsciiString m_filename; // For music tracks, this is the filename of the track + + Real m_volume; // Desired volume of this audio + Real m_volumeShift; // Desired volume shift of the audio + Real m_minVolume; // Clamped minimum value, useful when muting sound effects + Real m_pitchShiftMin; // minimum pitch shift value + Real m_pitchShiftMax; // maximum pitch shift value + Int m_delayMin; // minimum delay before we'll fire up another one of these + Int m_delayMax; // maximum delay before we'll fire up another one of these + Int m_limit; // Limit to the number of these sounds that can be fired up simultaneously + Int m_loopCount; // number of times to loop this sound + + AudioPriority m_priority; // Priority of this sound + UnsignedInt m_type; // Type of sound + UnsignedInt m_control; // control of sound + + std::vector m_soundsMorning; // Sounds to play in the wee hours of the morning + std::vector m_sounds; // Default sounds to play + std::vector m_soundsNight; // Sounds to play at night + std::vector m_soundsEvening; // Sounds to play in the evening std::vector m_attackSounds; std::vector m_decaySounds; - Real m_lowPassFreq; // When performing low pass filters, what is the maximum frequency heard, expressed as a percentage? - Real m_minDistance; // less than this distance and the sound behaves as though it is at minDistance - Real m_maxDistance; // greater than this distance and the sound behaves as though it is muted + Real m_lowPassFreq; // When performing low pass filters, what is the maximum frequency heard, expressed as a percentage? + Real m_minDistance; // less than this distance and the sound behaves as though it is at minDistance + Real m_maxDistance; // greater than this distance and the sound behaves as though it is muted - AudioType m_soundType; // This should be either Music, Streaming or SoundEffect + AudioType m_soundType; // This should be either Music, Streaming or SoundEffect + // DynamicAudioEventInfo interfacing functions + virtual Bool isLevelSpecific() const { return false; } ///< If true, this sound is only defined on the current level and can be deleted when that level ends + virtual DynamicAudioEventInfo* getDynamicAudioEventInfo() { return nullptr; } ///< If this object is REALLY a DynamicAudioEventInfo, return a pointer to the derived class + virtual const DynamicAudioEventInfo* getDynamicAudioEventInfo() const { return nullptr; } ///< If this object is REALLY a DynamicAudioEventInfo, return a pointer to the derived class - // DynamicAudioEventInfo interfacing functions - virtual Bool isLevelSpecific() const { return false; } ///< If true, this sound is only defined on the current level and can be deleted when that level ends - virtual DynamicAudioEventInfo * getDynamicAudioEventInfo() { return nullptr; } ///< If this object is REALLY a DynamicAudioEventInfo, return a pointer to the derived class - virtual const DynamicAudioEventInfo * getDynamicAudioEventInfo() const { return nullptr; } ///< If this object is REALLY a DynamicAudioEventInfo, return a pointer to the derived class + /// Is this a permanent sound? That is, if I start this sound up, will it ever end + /// "on its own" or only if I explicitly kill it? + Bool isPermanentSound() const { return BitIsSet(m_control, AC_LOOP) && (m_loopCount == 0); } - /// Is this a permanent sound? That is, if I start this sound up, will it ever end - /// "on its own" or only if I explicitly kill it? - Bool isPermanentSound() const { return BitIsSet( m_control, AC_LOOP ) && (m_loopCount == 0 ); } - - static const FieldParse m_audioEventInfo[]; ///< the parse table for INI definition - const FieldParse *getFieldParse() const { return m_audioEventInfo; } + static const FieldParse m_audioEventInfo[]; ///< the parse table for INI definition + const FieldParse* getFieldParse() const { return m_audioEventInfo; } }; diff --git a/Core/GameEngine/Include/Common/AudioEventRTS.h b/Core/GameEngine/Include/Common/AudioEventRTS.h index f38f1e5417a..1b5fbb6b368 100644 --- a/Core/GameEngine/Include/Common/AudioEventRTS.h +++ b/Core/GameEngine/Include/Common/AudioEventRTS.h @@ -36,7 +36,7 @@ // forward declarations /////////////////////////////////////////////////////////////////////////// struct AudioEventInfo; -enum OwnerType CPP_11(: Int) +enum OwnerType CPP_11( : Int) { OT_Positional, OT_Drawable, @@ -45,7 +45,7 @@ enum OwnerType CPP_11(: Int) OT_INVALID }; -enum PortionToPlay CPP_11(: Int) +enum PortionToPlay CPP_11( : Int) { PP_Attack, PP_Sound, @@ -53,7 +53,7 @@ enum PortionToPlay CPP_11(: Int) PP_Done }; -enum AudioPriority CPP_11(: Int); +enum AudioPriority CPP_11( : Int); // This is called AudioEventRTS because AudioEvent is a typedef in ww3d // You might want this to be memory pooled (I personally do), but it can't @@ -62,17 +62,17 @@ class AudioEventRTS { public: AudioEventRTS(); - AudioEventRTS( const AsciiString& eventName ); - AudioEventRTS( const AsciiString& eventName, ObjectID ownerID ); - AudioEventRTS( const AsciiString& eventName, DrawableID drawableID ); // Pass 0 for unused if attaching to drawable - AudioEventRTS( const AsciiString& eventName, const Coord3D *positionOfAudio ); + AudioEventRTS(const AsciiString& eventName); + AudioEventRTS(const AsciiString& eventName, ObjectID ownerID); + AudioEventRTS(const AsciiString& eventName, DrawableID drawableID); // Pass 0 for unused if attaching to drawable + AudioEventRTS(const AsciiString& eventName, const Coord3D* positionOfAudio); virtual ~AudioEventRTS(); - AudioEventRTS( const AudioEventRTS& right ); - AudioEventRTS& operator=( const AudioEventRTS& right ); + AudioEventRTS(const AudioEventRTS& right); + AudioEventRTS& operator=(const AudioEventRTS& right); - void setEventName( AsciiString name ); + void setEventName(AsciiString name); const AsciiString& getEventName() const { return m_eventName; } // generateFilename is separate from generatePlayInfo because generatePlayInfo should only be called once @@ -90,123 +90,124 @@ class AudioEventRTS AsciiString getDecayFilename() const; Real getDelay() const; - void decrementDelay( Real timeToDecrement ); + void decrementDelay(Real timeToDecrement); PortionToPlay getNextPlayPortion() const; void advanceNextPlayPortion(); - void setNextPlayPortion( PortionToPlay ptp ); + void setNextPlayPortion(PortionToPlay ptp); void decreaseLoopCount(); Bool hasMoreLoops() const; - void setAudioEventInfo( const AudioEventInfo *eventInfo ) const; // is mutable - const AudioEventInfo *getAudioEventInfo() const; + void setAudioEventInfo(const AudioEventInfo* eventInfo) const; // is mutable + const AudioEventInfo* getAudioEventInfo() const; - void setPlayingHandle( AudioHandle handle ); // for ID of this audio piece. - AudioHandle getPlayingHandle(); // for ID of this audio piece + void setPlayingHandle(AudioHandle handle); // for ID of this audio piece. + AudioHandle getPlayingHandle(); // for ID of this audio piece - void setPosition( const Coord3D *pos ); + void setPosition(const Coord3D* pos); const Coord3D* getPosition(); - void setObjectID( ObjectID objID ); + void setObjectID(ObjectID objID); ObjectID getObjectID(); Bool isDead() const { return m_ownerType == OT_Dead; } OwnerType getOwnerType() const { return m_ownerType; } - void setDrawableID( DrawableID drawID ); + void setDrawableID(DrawableID drawID); DrawableID getDrawableID(); - void setTimeOfDay( TimeOfDay tod ); + void setTimeOfDay(TimeOfDay tod); TimeOfDay getTimeOfDay() const; - void setHandleToKill( AudioHandle handleToKill ); + void setHandleToKill(AudioHandle handleToKill); AudioHandle getHandleToKill() const; - void setShouldFade( Bool shouldFade ); + void setShouldFade(Bool shouldFade); Bool getShouldFade() const; - void setIsLogicalAudio( Bool isLogicalAudio ); + void setIsLogicalAudio(Bool isLogicalAudio); Bool getIsLogicalAudio() const; Bool isPositionalAudio() const; Bool isCurrentlyPlaying() const; AudioPriority getAudioPriority() const; - void setAudioPriority( AudioPriority newPriority ); + void setAudioPriority(AudioPriority newPriority); Real getVolume() const; - void setVolume( Real vol ); + void setVolume(Real vol); Int getPlayerIndex() const; - void setPlayerIndex( Int playerNdx ); + void setPlayerIndex(Int playerNdx); Int getPlayingAudioIndex() const { return m_playingAudioIndex; } - void setPlayingAudioIndex( Int pai ) const { m_playingAudioIndex = pai; } // is mutable + void setPlayingAudioIndex(Int pai) const { m_playingAudioIndex = pai; } // is mutable Bool getUninterruptible() const { return m_uninterruptible; } - void setUninterruptible( Bool uninterruptible ) { m_uninterruptible = uninterruptible; } - + void setUninterruptible(Bool uninterruptible) { m_uninterruptible = uninterruptible; } // This will retrieve the appropriate position based on type. - const Coord3D *getCurrentPosition(); + const Coord3D* getCurrentPosition(); // This will return the directory leading up to the appropriate type, including the trailing '\\' // If localized is true, we'll append a language specific directory to the end of the path. - AsciiString generateFilenamePrefix( AudioType audioTypeToPlay, Bool localized ); - AsciiString generateFilenameExtension( AudioType audioTypeToPlay ); + AsciiString generateFilenamePrefix(AudioType audioTypeToPlay, Bool localized); + AsciiString generateFilenameExtension(AudioType audioTypeToPlay); + protected: - void adjustForLocalization( AsciiString &strToAdjust ); + void adjustForLocalization(AsciiString& strToAdjust); protected: AsciiString m_filenameToLoad; - mutable const AudioEventInfo *m_eventInfo; // Mutable so that it can be modified even on const objects + mutable const AudioEventInfo* m_eventInfo; // Mutable so that it can be modified even on const objects AudioHandle m_playingHandle; - AudioHandle m_killThisHandle; ///< Sometimes sounds will canabilize other sounds in order to take their handle away. - ///< This is one of those instances. + AudioHandle m_killThisHandle; ///< Sometimes sounds will canabilize other sounds in order to take their handle away. + ///< This is one of those instances. - AsciiString m_eventName; ///< This should correspond with an entry in Dialog.ini, Speech.ini, or Audio.ini - AsciiString m_attackName; ///< This is the filename that should be used during the attack. - AsciiString m_decayName; ///< This is the filename that should be used during the decay. + AsciiString m_eventName; ///< This should correspond with an entry in Dialog.ini, Speech.ini, or Audio.ini + AsciiString m_attackName; ///< This is the filename that should be used during the attack. + AsciiString m_decayName; ///< This is the filename that should be used during the decay. - AudioPriority m_priority; ///< This should be the priority as given by the event info, or the overridden priority. - Real m_volume; ///< This is the override for the volume. It will either be the normal volume or an overridden value. - TimeOfDay m_timeOfDay; ///< This should be the current Time Of Day. + AudioPriority m_priority; ///< This should be the priority as given by the event info, or the overridden priority. + Real m_volume; ///< This is the override for the volume. It will either be the normal volume or an overridden value. + TimeOfDay m_timeOfDay; ///< This should be the current Time Of Day. - Coord3D m_positionOfAudio; ///< Position of the sound if no further positional updates are necessary - union // These are now unioned. + Coord3D m_positionOfAudio; ///< Position of the sound if no further positional updates are necessary + union // These are now unioned. { - ObjectID m_objectID; ///< ObjectID of the object that this sound is tied to. Position can be automatically updated from this. - DrawableID m_drawableID; ///< DrawableID of the drawable that owns this sound + ObjectID m_objectID; ///< ObjectID of the object that this sound is tied to. Position can be automatically updated from this. + DrawableID m_drawableID; ///< DrawableID of the drawable that owns this sound }; OwnerType m_ownerType; - Bool m_shouldFade; ///< This should fade in or out (if it is starting or stopping) - Bool m_isLogicalAudio; ///< Should probably only be true for scripted sounds + Bool m_shouldFade; ///< This should fade in or out (if it is starting or stopping) + Bool m_isLogicalAudio; ///< Should probably only be true for scripted sounds Bool m_uninterruptible; // Playing attributes - Real m_pitchShift; ///< Pitch shift that should occur on this piece of audio - Real m_volumeShift; ///< Volume shift that should occur on this piece of audio - Real m_delay; ///< Amount to delay before playing this sound - Int m_loopCount; ///< The current loop count value. Only valid if this is a looping type event or the override has been set. - mutable Int m_playingAudioIndex; ///< The sound index we are currently playing. In the case of non-random, we increment this to move to the next sound - Int m_allCount; ///< If this sound is an ALL type, then this is how many sounds we have played so far. + Real m_pitchShift; ///< Pitch shift that should occur on this piece of audio + Real m_volumeShift; ///< Volume shift that should occur on this piece of audio + Real m_delay; ///< Amount to delay before playing this sound + Int m_loopCount; ///< The current loop count value. Only valid if this is a looping type event or the override has been set. + mutable Int m_playingAudioIndex; ///< The sound index we are currently playing. In the case of non-random, we increment this to move to the next sound + Int m_allCount; ///< If this sound is an ALL type, then this is how many sounds we have played so far. - Int m_playerIndex; ///< The index of the player who owns this sound. Used for sounds that should have an owner, but don't have an object, etc. + Int m_playerIndex; ///< The index of the player who owns this sound. Used for sounds that should have an owner, but don't have an object, etc. - PortionToPlay m_portionToPlayNext; ///< Which portion (attack, sound, decay) should be played next? + PortionToPlay m_portionToPlayNext; ///< Which portion (attack, sound, decay) should be played next? }; class DynamicAudioEventRTS : public MemoryPoolObject { - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(DynamicAudioEventRTS, "DynamicAudioEventRTS" ) + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(DynamicAudioEventRTS, "DynamicAudioEventRTS") public: + DynamicAudioEventRTS() {} + DynamicAudioEventRTS(const AudioEventRTS& a) + : m_event(a) + {} - DynamicAudioEventRTS() { } - DynamicAudioEventRTS(const AudioEventRTS& a) : m_event(a) { } - - AudioEventRTS m_event; + AudioEventRTS m_event; }; EMPTY_DTOR(DynamicAudioEventRTS) diff --git a/Core/GameEngine/Include/Common/AudioHandleSpecialValues.h b/Core/GameEngine/Include/Common/AudioHandleSpecialValues.h index 102f9ed860b..5d747b0f486 100644 --- a/Core/GameEngine/Include/Common/AudioHandleSpecialValues.h +++ b/Core/GameEngine/Include/Common/AudioHandleSpecialValues.h @@ -28,9 +28,9 @@ #pragma once -enum AudioHandleSpecialValues CPP_11(: Int) +enum AudioHandleSpecialValues CPP_11( : Int) { - AHSV_Error = 0x00, + AHSV_Error = 0x00, AHSV_NoSound, AHSV_Muted, AHSV_NotForLocal, diff --git a/Core/GameEngine/Include/Common/AudioRandomValue.h b/Core/GameEngine/Include/Common/AudioRandomValue.h index 4efc9c26b3d..50687bc6212 100644 --- a/Core/GameEngine/Include/Common/AudioRandomValue.h +++ b/Core/GameEngine/Include/Common/AudioRandomValue.h @@ -32,11 +32,11 @@ #include "Lib/BaseType.h" // do NOT use these functions directly, rather use the macros below -extern Int GetGameAudioRandomValue( int lo, int hi, const char *file, int line ); -extern Real GetGameAudioRandomValueReal( Real lo, Real hi, const char *file, int line ); +extern Int GetGameAudioRandomValue(int lo, int hi, const char* file, int line); +extern Real GetGameAudioRandomValueReal(Real lo, Real hi, const char* file, int line); // use these macros to access the random value functions -#define GameAudioRandomValue( lo, hi ) GetGameAudioRandomValue( lo, hi, __FILE__, __LINE__ ) -#define GameAudioRandomValueReal( lo, hi ) GetGameAudioRandomValueReal( lo, hi, __FILE__, __LINE__ ) +#define GameAudioRandomValue(lo, hi) GetGameAudioRandomValue(lo, hi, __FILE__, __LINE__) +#define GameAudioRandomValueReal(lo, hi) GetGameAudioRandomValueReal(lo, hi, __FILE__, __LINE__) //-------------------------------------------------------------------------------------------------------------- diff --git a/Core/GameEngine/Include/Common/AudioRequest.h b/Core/GameEngine/Include/Common/AudioRequest.h index a0321fdb481..4f74744c63b 100644 --- a/Core/GameEngine/Include/Common/AudioRequest.h +++ b/Core/GameEngine/Include/Common/AudioRequest.h @@ -33,7 +33,7 @@ class AudioEventRTS; -enum RequestType CPP_11(: Int) +enum RequestType CPP_11( : Int) { AR_Play, AR_Pause, @@ -42,13 +42,13 @@ enum RequestType CPP_11(: Int) struct AudioRequest : public MemoryPoolObject { - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( AudioRequest, "AudioRequest" ) + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(AudioRequest, "AudioRequest") public: RequestType m_request; union { - AudioEventRTS *m_pendingEvent; + AudioEventRTS* m_pendingEvent; AudioHandle m_handleToInteractOn; }; Bool m_usePendingEvent; diff --git a/Core/GameEngine/Include/Common/AudioSettings.h b/Core/GameEngine/Include/Common/AudioSettings.h index f7f99628890..ee73a23937b 100644 --- a/Core/GameEngine/Include/Common/AudioSettings.h +++ b/Core/GameEngine/Include/Common/AudioSettings.h @@ -30,17 +30,20 @@ #include "Common/AsciiString.h" -enum { MAX_HW_PROVIDERS = 4 }; +enum +{ + MAX_HW_PROVIDERS = 4 +}; struct AudioSettings { AudioSettings() - : m_use3DSoundRangeVolumeFade(true) // Enabled by default because it prevents audio cut off at the max range of 3D sounds - , m_3DSoundRangeVolumeFadeExponent(4.0f) // Exponent of 4 gives a nice balance between loud sounds and graceful fade + : m_use3DSoundRangeVolumeFade(true) // Enabled by default because it prevents audio cut off at the max range of 3D sounds + , m_3DSoundRangeVolumeFadeExponent(4.0f) // Exponent of 4 gives a nice balance between loud sounds and graceful fade #if RTS_GENERALS , m_defaultMoneyTransactionVolume(1.0f) #elif RTS_ZEROHOUR - , m_defaultMoneyTransactionVolume(0.0f) // Uses zero volume by default because originally the money sounds did not work in Zero Hour + , m_defaultMoneyTransactionVolume(0.0f) // Uses zero volume by default because originally the money sounds did not work in Zero Hour #endif { } @@ -58,21 +61,21 @@ struct AudioSettings Int m_sampleCount2D; Int m_sampleCount3D; Int m_streamCount; - Bool m_use3DSoundRangeVolumeFade; // TheSuperHackers @feature Enables 3D sound range volume fade as originally intended - Real m_3DSoundRangeVolumeFadeExponent; // TheSuperHackers @feature Sets 3D sound range volume fade exponent for non-linear fade. - // The higher the exponent, the sharper the decline at the max range. + Bool m_use3DSoundRangeVolumeFade; // TheSuperHackers @feature Enables 3D sound range volume fade as originally intended + Real m_3DSoundRangeVolumeFadeExponent; // TheSuperHackers @feature Sets 3D sound range volume fade exponent for non-linear fade. + // The higher the exponent, the sharper the decline at the max range. Int m_globalMinRange; Int m_globalMaxRange; Int m_drawableAmbientFrames; Int m_fadeAudioFrames; UnsignedInt m_maxCacheSize; - Real m_minVolume; // At volumes less than this, the sample will be culled. + Real m_minVolume; // At volumes less than this, the sample will be culled. AsciiString m_preferred3DProvider[MAX_HW_PROVIDERS + 1]; - //Defaults actually don't ever get changed! - Real m_relative2DVolume; //2D volume compared to 3D + // Defaults actually don't ever get changed! + Real m_relative2DVolume; // 2D volume compared to 3D Real m_defaultSoundVolume; Real m_default3DSoundVolume; Real m_defaultSpeechVolume; @@ -81,25 +84,25 @@ struct AudioSettings UnsignedInt m_defaultSpeakerType2D; UnsignedInt m_defaultSpeakerType3D; - //If you want to change a value, store it somewhere else (like here) + // If you want to change a value, store it somewhere else (like here) Real m_preferredSoundVolume; Real m_preferred3DSoundVolume; Real m_preferredSpeechVolume; Real m_preferredMusicVolume; - Real m_preferredMoneyTransactionVolume; // TheSuperHackers @feature Modifies the volume of money deposit and withdraw sounds + Real m_preferredMoneyTransactionVolume; // TheSuperHackers @feature Modifies the volume of money deposit and withdraw sounds - //The desired altitude of the microphone to improve panning relative to terrain. + // The desired altitude of the microphone to improve panning relative to terrain. Real m_microphoneDesiredHeightAboveTerrain; - //When tracing a line between the ground look-at-point and the camera, we want - //to ensure a maximum percentage, so the microphone never goes behind the camera. + // When tracing a line between the ground look-at-point and the camera, we want + // to ensure a maximum percentage, so the microphone never goes behind the camera. Real m_microphoneMaxPercentageBetweenGroundAndCamera; - //Handles changing sound volume whenever the camera is close to the microphone. - Real m_zoomMinDistance; //If we're closer than the minimum distance, then apply the full bonus no matter how close. - Real m_zoomMaxDistance; //The maximum distance from microphone we need to be before benefiting from any bonus. + // Handles changing sound volume whenever the camera is close to the microphone. + Real m_zoomMinDistance; // If we're closer than the minimum distance, then apply the full bonus no matter how close. + Real m_zoomMaxDistance; // The maximum distance from microphone we need to be before benefiting from any bonus. - //NOTE: The higher this value is, the lower normal sounds will be! If you specify a sound volume value of 25%, then sounds will play - //between 75% and 100%, not 100% to 125%! - Real m_zoomSoundVolumePercentageAmount; //The amount of sound volume dedicated to zooming. + // NOTE: The higher this value is, the lower normal sounds will be! If you specify a sound volume value of 25%, then sounds will play + // between 75% and 100%, not 100% to 125%! + Real m_zoomSoundVolumePercentageAmount; // The amount of sound volume dedicated to zooming. }; diff --git a/Core/GameEngine/Include/Common/CRCDebug.h b/Core/GameEngine/Include/Common/CRCDebug.h index 5fee31b43d3..a0cf7bc28f7 100644 --- a/Core/GameEngine/Include/Common/CRCDebug.h +++ b/Core/GameEngine/Include/Common/CRCDebug.h @@ -38,13 +38,13 @@ #ifdef DEBUG_CRC -#include "Common/AsciiString.h" -#include "GameLogic/GameLogic.h" -#include "Lib/BaseType.h" -#include "WWMath/vector3.h" -#include "WWMath/matrix3d.h" + #include "Common/AsciiString.h" + #include "GameLogic/GameLogic.h" + #include "Lib/BaseType.h" + #include "WWMath/vector3.h" + #include "WWMath/matrix3d.h" - #define AS_INT(x) (*(Int *)(&x)) + #define AS_INT(x) (*(Int*)(&x)) #define DUMPVEL DUMPCOORD3DNAMED(&m_vel, "m_vel") #define DUMPACCEL DUMPCOORD3DNAMED(&m_accel, "m_accel") #define DUMPVECTOR3(x) DUMPVECTOR3NAMED(x, #x) @@ -56,53 +56,54 @@ #define DUMPREAL(x) DUMPREALNAMED(x, #x) #define DUMPREALNAMED(x, y) dumpReal(x, y, __FILE__, __LINE__) - extern Int TheCRCFirstFrameToLog; - extern UnsignedInt TheCRCLastFrameToLog; +extern Int TheCRCFirstFrameToLog; +extern UnsignedInt TheCRCLastFrameToLog; - void dumpVector3(const Vector3 *v, AsciiString name, AsciiString fname, Int line); - void dumpCoord3D(const Coord3D *c, AsciiString name, AsciiString fname, Int line); - void dumpMatrix3D(const Matrix3D *m, AsciiString name, AsciiString fname, Int line); - void dumpReal(Real r, AsciiString name, AsciiString fname, Int line); +void dumpVector3(const Vector3* v, AsciiString name, AsciiString fname, Int line); +void dumpCoord3D(const Coord3D* c, AsciiString name, AsciiString fname, Int line); +void dumpMatrix3D(const Matrix3D* m, AsciiString name, AsciiString fname, Int line); +void dumpReal(Real r, AsciiString name, AsciiString fname, Int line); - void outputCRCDebugLines(); - void CRCDebugStartNewGame(); - void outputCRCDumpLines(); +void outputCRCDebugLines(); +void CRCDebugStartNewGame(); +void outputCRCDumpLines(); - void addCRCDebugLine(const char *fmt, ...); - void addCRCDebugLineNoCounter(const char *fmt, ...); - void addCRCDumpLine(const char *fmt, ...); - void addCRCGenLine(const char *fmt, ...); +void addCRCDebugLine(const char* fmt, ...); +void addCRCDebugLineNoCounter(const char* fmt, ...); +void addCRCDumpLine(const char* fmt, ...); +void addCRCGenLine(const char* fmt, ...); #define CRCDEBUG_LOG(x) addCRCDebugLine x #define CRCDUMP_LOG(x) addCRCDumpLine x #define CRCGEN_LOG(x) addCRCGenLine x - class CRCVerification - { - public: - CRCVerification(); - ~CRCVerification(); - protected: - UnsignedInt m_startCRC; - }; - #define VERIFY_CRC CRCVerification crcVerification; +class CRCVerification +{ +public: + CRCVerification(); + ~CRCVerification(); - extern Int lastCRCDebugFrame; - extern Int lastCRCDebugIndex; +protected: + UnsignedInt m_startCRC; +}; + #define VERIFY_CRC CRCVerification crcVerification; - extern Bool g_verifyClientCRC; - extern Bool g_clientDeepCRC; +extern Int lastCRCDebugFrame; +extern Int lastCRCDebugIndex; - extern Bool g_crcModuleDataFromClient; - extern Bool g_crcModuleDataFromLogic; +extern Bool g_verifyClientCRC; +extern Bool g_clientDeepCRC; - extern Bool g_keepCRCSaves; - extern Bool g_saveDebugCRCPerFrame; - extern AsciiString g_saveDebugCRCPerFrameDir; +extern Bool g_crcModuleDataFromClient; +extern Bool g_crcModuleDataFromLogic; - extern Bool g_logObjectCRCs; +extern Bool g_keepCRCSaves; +extern Bool g_saveDebugCRCPerFrame; +extern AsciiString g_saveDebugCRCPerFrameDir; -#else // DEBUG_CRC +extern Bool g_logObjectCRCs; +#else // DEBUG_CRC +// clang-format off: [MACRO_COMPACT] - keep empty block macro on one line #define DUMPVEL {} #define DUMPACCEL {} #define DUMPVECTOR3(x) {} @@ -120,7 +121,7 @@ #define CRCGEN_LOG(x) {} #define VERIFY_CRC {} - +// clang-format on #endif extern Int NET_CRC_INTERVAL; diff --git a/Core/GameEngine/Include/Common/Debug.h b/Core/GameEngine/Include/Common/Debug.h index 7288a753cda..c07296a3c72 100644 --- a/Core/GameEngine/Include/Common/Debug.h +++ b/Core/GameEngine/Include/Common/Debug.h @@ -49,7 +49,7 @@ class AsciiString; #define NO_RELEASE_DEBUG_LOGGING -#ifdef RELEASE_DEBUG_LOGGING ///< Creates a DebugLogFile.txt (No I or D) with all the debug log goodness. Good for startup problems. +#ifdef RELEASE_DEBUG_LOGGING ///< Creates a DebugLogFile.txt (No I or D) with all the debug log goodness. Good for startup problems. #define ALLOW_DEBUG_UTILS 1 #define DEBUG_LOGGING 1 #define DISABLE_DEBUG_CRASHING 1 @@ -59,8 +59,8 @@ class AsciiString; // These are stolen from the WW3D Debug file. REALLY useful. :-) #define STRING_IT(a) #a -#define TOKEN_IT(a) STRING_IT(,##a) -#define MESSAGE(a) message (__FILE__ "(" TOKEN_IT(__LINE__) ") : " a) +#define TOKEN_IT(a) STRING_IT(, ##a) +#define MESSAGE(a) message(__FILE__ "(" TOKEN_IT(__LINE__) ") : " a) // by default, turn on ALLOW_DEBUG_UTILS if RTS_DEBUG is turned on. #if defined(RTS_DEBUG) && !defined(ALLOW_DEBUG_UTILS) && !defined(DISABLE_ALLOW_DEBUG_UTILS) @@ -81,7 +81,7 @@ class AsciiString; #if defined(ALLOW_DEBUG_UTILS) && !defined(DEBUG_STACKTRACE) && !defined(DISABLE_DEBUG_STACKTRACE) #define DEBUG_STACKTRACE 1 #ifndef DEBUG_LOGGING - #define DEBUG_LOGGING 1 // TheSuperHackers @build Stack trace requires logging. + #define DEBUG_LOGGING 1 // TheSuperHackers @build Stack trace requires logging. #endif #endif #if defined(ALLOW_DEBUG_UTILS) && !defined(DEBUG_PROFILE) && !defined(DISABLE_DEBUG_PROFILE) @@ -94,7 +94,6 @@ class AsciiString; #define DEBUG_EXTERN_C extern #endif - // SYSTEM INCLUDES //////////////////////////////////////////////////////////// // USER INCLUDES ////////////////////////////////////////////////////////////// @@ -108,102 +107,152 @@ class AsciiString; // EXTERNALS ////////////////////////////////////////////////////////////////// /// @todo: the standard line-to-string trick isn't working correctly in vc6; figure out why -#define DEBUG_STRING_IT(b) #b -#define DEBUG_TOKEN_IT(a) DEBUG_STRING_IT(a) -#define DEBUG_FILENLINE __FILE__ ":" DEBUG_TOKEN_IT(__LINE__) +#define DEBUG_STRING_IT(b) #b +#define DEBUG_TOKEN_IT(a) DEBUG_STRING_IT(a) +#define DEBUG_FILENLINE __FILE__ ":" DEBUG_TOKEN_IT(__LINE__) #ifdef ALLOW_DEBUG_UTILS - enum - { - DEBUG_FLAG_LOG_TO_FILE = 0x01, - DEBUG_FLAG_LOG_TO_CONSOLE = 0x02, - DEBUG_FLAG_PREPEND_TIME = 0x04, - DEBUG_FLAGS_DEFAULT = (DEBUG_FLAG_LOG_TO_FILE | DEBUG_FLAG_LOG_TO_CONSOLE), - }; +enum +{ + DEBUG_FLAG_LOG_TO_FILE = 0x01, + DEBUG_FLAG_LOG_TO_CONSOLE = 0x02, + DEBUG_FLAG_PREPEND_TIME = 0x04, + DEBUG_FLAGS_DEFAULT = (DEBUG_FLAG_LOG_TO_FILE | DEBUG_FLAG_LOG_TO_CONSOLE), +}; - DEBUG_EXTERN_C void DebugInit(int flags); - DEBUG_EXTERN_C void DebugShutdown(); +DEBUG_EXTERN_C void DebugInit(int flags); +DEBUG_EXTERN_C void DebugShutdown(); - DEBUG_EXTERN_C int DebugGetFlags(); - DEBUG_EXTERN_C void DebugSetFlags(int flags); +DEBUG_EXTERN_C int DebugGetFlags(); +DEBUG_EXTERN_C void DebugSetFlags(int flags); - #define DEBUG_INIT(f) do { DebugInit(f); } while (0) - #define DEBUG_SHUTDOWN() do { DebugShutdown(); } while (0) + #define DEBUG_INIT(f) \ + do \ + { \ + DebugInit(f); \ + } while (0) + #define DEBUG_SHUTDOWN() \ + do \ + { \ + DebugShutdown(); \ + } while (0) #else - #define DEBUG_INIT(f) ((void)0) - #define DEBUG_SHUTDOWN() ((void)0) + #define DEBUG_INIT(f) ((void)0) + #define DEBUG_SHUTDOWN() ((void)0) #endif #ifdef DEBUG_LOGGING - DEBUG_EXTERN_C void DebugLog(const char *format, ...); - DEBUG_EXTERN_C void DebugLogRaw(const char *format, ...); - DEBUG_EXTERN_C const char* DebugGetLogFileName(); - DEBUG_EXTERN_C const char* DebugGetLogFileNamePrev(); - - // This defines a bitmask of log types that we care about, to allow some flexability - // in what gets logged. This should be extended to asserts, too, but the assert box - // is waiting to be rewritten. -MDC 3/19/2003 - extern unsigned int DebugLevelMask; - enum - { - DEBUG_LEVEL_NET = 0, // in-game network - DEBUG_LEVEL_MAX - }; - extern const char *TheDebugLevels[DEBUG_LEVEL_MAX]; - - #define DEBUG_LOG(m) do { { DebugLog m ; } } while (0) // Log message with trailing new line character (LF) - #define DEBUG_LOG_RAW(m) do { { DebugLogRaw m ; } } while (0) // Log message without trailing new line character (LF) - #define DEBUG_LOG_LEVEL(l, m) do { if (l & DebugLevelMask) { DebugLog m ; } } while (0) - #define DEBUG_LOG_LEVEL_RAW(l, m) do { if (l & DebugLevelMask) { DebugLogRaw m ; } } while (0) - #define DEBUG_ASSERTLOG(c, m) do { { if (!(c)) DebugLog m ; } } while (0) +DEBUG_EXTERN_C void DebugLog(const char* format, ...); +DEBUG_EXTERN_C void DebugLogRaw(const char* format, ...); +DEBUG_EXTERN_C const char* DebugGetLogFileName(); +DEBUG_EXTERN_C const char* DebugGetLogFileNamePrev(); + +// This defines a bitmask of log types that we care about, to allow some flexability +// in what gets logged. This should be extended to asserts, too, but the assert box +// is waiting to be rewritten. -MDC 3/19/2003 +extern unsigned int DebugLevelMask; +enum +{ + DEBUG_LEVEL_NET = 0, // in-game network + DEBUG_LEVEL_MAX +}; +extern const char* TheDebugLevels[DEBUG_LEVEL_MAX]; + + #define DEBUG_LOG(m) \ + do \ + { \ + { \ + DebugLog m; \ + } \ + } while (0) // Log message with trailing new line character (LF) + #define DEBUG_LOG_RAW(m) \ + do \ + { \ + { \ + DebugLogRaw m; \ + } \ + } while (0) // Log message without trailing new line character (LF) + #define DEBUG_LOG_LEVEL(l, m) \ + do \ + { \ + if (l & DebugLevelMask) \ + { \ + DebugLog m; \ + } \ + } while (0) + #define DEBUG_LOG_LEVEL_RAW(l, m) \ + do \ + { \ + if (l & DebugLevelMask) \ + { \ + DebugLogRaw m; \ + } \ + } while (0) + #define DEBUG_ASSERTLOG(c, m) \ + do \ + { \ + { \ + if (!(c)) \ + DebugLog m; \ + } \ + } while (0) #else - #define DEBUG_LOG(m) ((void)0) - #define DEBUG_LOG_RAW(m) ((void)0) - #define DEBUG_LOG_LEVEL(l, m) ((void)0) - #define DEBUG_LOG_LEVEL_RAW(l, m) ((void)0) - #define DEBUG_ASSERTLOG(c, m) ((void)0) + #define DEBUG_LOG(m) ((void)0) + #define DEBUG_LOG_RAW(m) ((void)0) + #define DEBUG_LOG_LEVEL(l, m) ((void)0) + #define DEBUG_LOG_LEVEL_RAW(l, m) ((void)0) + #define DEBUG_ASSERTLOG(c, m) ((void)0) #endif #ifdef DEBUG_CRASHING - DEBUG_EXTERN_C void DebugCrash(const char *format, ...); - - /* - Yeah, it's a sleazy global, since we can't reasonably add - any args to DebugCrash due to the varargs nature of it. - We'll just let it slide in this case... - */ - DEBUG_EXTERN_C char* TheCurrentIgnoreCrashPtr; +DEBUG_EXTERN_C void DebugCrash(const char* format, ...); - #define DEBUG_CRASH(m) \ - do { \ - { \ - static char ignoreCrash = 0; \ - if (!ignoreCrash) { \ +/* + Yeah, it's a sleazy global, since we can't reasonably add + any args to DebugCrash due to the varargs nature of it. + We'll just let it slide in this case... +*/ +DEBUG_EXTERN_C char* TheCurrentIgnoreCrashPtr; + + #define DEBUG_CRASH(m) \ + do \ + { \ + { \ + static char ignoreCrash = 0; \ + if (!ignoreCrash) \ + { \ TheCurrentIgnoreCrashPtr = &ignoreCrash; \ - DebugCrash m ; \ - TheCurrentIgnoreCrashPtr = nullptr; \ - } \ - } \ + DebugCrash m; \ + TheCurrentIgnoreCrashPtr = nullptr; \ + } \ + } \ } while (0) - #define DEBUG_ASSERTCRASH(c, m) do { { if (!(c)) DEBUG_CRASH(m); } } while (0) + #define DEBUG_ASSERTCRASH(c, m) \ + do \ + { \ + { \ + if (!(c)) \ + DEBUG_CRASH(m); \ + } \ + } while (0) - //Note: RELEASE_CRASH(m) is now always defined. - //#define RELEASE_CRASH(m) DEBUG_CRASH((m)) +// Note: RELEASE_CRASH(m) is now always defined. +// #define RELEASE_CRASH(m) DEBUG_CRASH((m)) #else - #define DEBUG_CRASH(m) ((void)0) - #define DEBUG_ASSERTCRASH(c, m) ((void)0) + #define DEBUG_CRASH(m) ((void)0) + #define DEBUG_ASSERTCRASH(c, m) ((void)0) // DEBUG_EXTERN_C void ReleaseCrash(const char* reason); @@ -214,9 +263,16 @@ class AsciiString; DEBUG_EXTERN_C void ReleaseCrash(const char* reason); DEBUG_EXTERN_C void ReleaseCrashLocalized(const AsciiString& p, const AsciiString& m); -#define RELEASE_CRASH(m) do { ReleaseCrash(m); } while (0) -#define RELEASE_CRASHLOCALIZED(p, m) do { ReleaseCrashLocalized(p, m); } while (0) - +#define RELEASE_CRASH(m) \ + do \ + { \ + ReleaseCrash(m); \ + } while (0) +#define RELEASE_CRASHLOCALIZED(p, m) \ + do \ + { \ + ReleaseCrashLocalized(p, m); \ + } while (0) #ifdef DEBUG_PROFILE @@ -227,32 +283,30 @@ class SimpleProfiler __int64 m_startThisSession; __int64 m_totalThisSession; __int64 m_totalAllSessions; - int m_numSessions; + int m_numSessions; public: - SimpleProfiler(); void start(); void stop(); - void stopAndLog(const char *msg, int howOftenToLog, int howOftenToResetAvg); - double getTime(); // of most recent session, in milliseconds + void stopAndLog(const char* msg, int howOftenToLog, int howOftenToResetAvg); + double getTime(); // of most recent session, in milliseconds int getNumSessions(); - double getTotalTime(); // total over all sessions, in milliseconds - double getAverageTime(); // averaged over all sessions, in milliseconds - + double getTotalTime(); // total over all sessions, in milliseconds + double getAverageTime(); // averaged over all sessions, in milliseconds }; -#define BEGIN_PROFILE(uniqueid) \ - static SimpleProfiler prof_##uniqueid; \ - prof_##uniqueid.start(); + #define BEGIN_PROFILE(uniqueid) \ + static SimpleProfiler prof_##uniqueid; \ + prof_##uniqueid.start(); -#define END_PROFILE(uniqueid, msg, howoftentolog, howoftentoreset) \ - prof_##uniqueid.stopAndLog(msg, howoftentolog, howoftentoreset); + #define END_PROFILE(uniqueid, msg, howoftentolog, howoftentoreset) \ + prof_##uniqueid.stopAndLog(msg, howoftentolog, howoftentoreset); #else -#define BEGIN_PROFILE(uniqueid) -#define END_PROFILE(uniqueid, msg, howoftentolog, howoftentoreset) + #define BEGIN_PROFILE(uniqueid) + #define END_PROFILE(uniqueid, msg, howoftentolog, howoftentoreset) #endif diff --git a/Core/GameEngine/Include/Common/DynamicAudioEventInfo.h b/Core/GameEngine/Include/Common/DynamicAudioEventInfo.h index 038ba2bbfff..fba074a22e9 100644 --- a/Core/GameEngine/Include/Common/DynamicAudioEventInfo.h +++ b/Core/GameEngine/Include/Common/DynamicAudioEventInfo.h @@ -39,115 +39,115 @@ class Xfer; *****************************************************************************/ class DynamicAudioEventInfo : public AudioEventInfo { - // NOTE: This implementation would be a lot cleaner & safer if AudioEventInfo was better - // written. Ideally, AudioEventInfo would be a class, not a struct, and provide only - // "get" functions, not "set" functions except for the INI parsing. Then we could - // force people to go through our override...() functions. - - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( DynamicAudioEventInfo, "DynamicAudioEventInfo" ) - - public: - DynamicAudioEventInfo(); - explicit DynamicAudioEventInfo( const AudioEventInfo & baseInfo ); - - // DynamicAudioEventInfo interfacing function overrides - virtual Bool isLevelSpecific() const override; - virtual DynamicAudioEventInfo * getDynamicAudioEventInfo() override; - virtual const DynamicAudioEventInfo * getDynamicAudioEventInfo() const override; - - // Change various fields from their default (INI) values - void overrideAudioName( const AsciiString & newName ); - void overrideLoopFlag( Bool newLoopFlag ); - void overrideLoopCount( Int newLoopCount ); - void overrideVolume( Real newVolume ); - void overrideMinVolume( Real newMinVolume ); - void overrideMinRange( Real newMinRange ); - void overrideMaxRange( Real newMaxRange ); - void overridePriority( AudioPriority newPriority ); - - // Query fields to see if they have been changed from their INI values - Bool wasAudioNameOverriden() const; - Bool wasLoopFlagOverriden() const; - Bool wasLoopCountOverriden() const; - Bool wasVolumeOverriden() const; - Bool wasMinVolumeOverriden() const; - Bool wasMinRangeOverriden() const; - Bool wasMaxRangeOverriden() const; - Bool wasPriorityOverriden() const; - - // Get the name of the audio event which this was based off of - const AsciiString & getOriginalName() const; - - // Transfer all overridden fields except the customized name - void xferNoName( Xfer * xfer ); - - private: - // List of fields we can override - enum OverriddenFields CPP_11(: Int) - { - OVERRIDE_NAME = 0, - OVERRIDE_LOOP_FLAG, - OVERRIDE_LOOP_COUNT, - OVERRIDE_VOLUME, - OVERRIDE_MIN_VOLUME, - OVERRIDE_MIN_RANGE, - OVERRIDE_MAX_RANGE, - OVERRIDE_PRIORITY, - - OVERRIDE_COUNT // Keep list - }; - // Warning: update xferNoName if you modify the enum list! - - BitFlags< OVERRIDE_COUNT > m_overriddenFields; - - // Retain the original name so we can look it up later - AsciiString m_originalName; + // NOTE: This implementation would be a lot cleaner & safer if AudioEventInfo was better + // written. Ideally, AudioEventInfo would be a class, not a struct, and provide only + // "get" functions, not "set" functions except for the INI parsing. Then we could + // force people to go through our override...() functions. + + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(DynamicAudioEventInfo, "DynamicAudioEventInfo") + +public: + DynamicAudioEventInfo(); + explicit DynamicAudioEventInfo(const AudioEventInfo& baseInfo); + + // DynamicAudioEventInfo interfacing function overrides + virtual Bool isLevelSpecific() const override; + virtual DynamicAudioEventInfo* getDynamicAudioEventInfo() override; + virtual const DynamicAudioEventInfo* getDynamicAudioEventInfo() const override; + + // Change various fields from their default (INI) values + void overrideAudioName(const AsciiString& newName); + void overrideLoopFlag(Bool newLoopFlag); + void overrideLoopCount(Int newLoopCount); + void overrideVolume(Real newVolume); + void overrideMinVolume(Real newMinVolume); + void overrideMinRange(Real newMinRange); + void overrideMaxRange(Real newMaxRange); + void overridePriority(AudioPriority newPriority); + + // Query fields to see if they have been changed from their INI values + Bool wasAudioNameOverriden() const; + Bool wasLoopFlagOverriden() const; + Bool wasLoopCountOverriden() const; + Bool wasVolumeOverriden() const; + Bool wasMinVolumeOverriden() const; + Bool wasMinRangeOverriden() const; + Bool wasMaxRangeOverriden() const; + Bool wasPriorityOverriden() const; + + // Get the name of the audio event which this was based off of + const AsciiString& getOriginalName() const; + + // Transfer all overridden fields except the customized name + void xferNoName(Xfer* xfer); + +private: + // List of fields we can override + enum OverriddenFields CPP_11( : Int) + { + OVERRIDE_NAME = 0, + OVERRIDE_LOOP_FLAG, + OVERRIDE_LOOP_COUNT, + OVERRIDE_VOLUME, + OVERRIDE_MIN_VOLUME, + OVERRIDE_MIN_RANGE, + OVERRIDE_MAX_RANGE, + OVERRIDE_PRIORITY, + + OVERRIDE_COUNT // Keep list + }; + // Warning: update xferNoName if you modify the enum list! + + BitFlags m_overriddenFields; + + // Retain the original name so we can look it up later + AsciiString m_originalName; }; /** Query: was overrideAudioName called? */ inline Bool DynamicAudioEventInfo::wasAudioNameOverriden() const { - return m_overriddenFields.test( OVERRIDE_NAME ); + return m_overriddenFields.test(OVERRIDE_NAME); } /** Query: was overrideLoopFlag called? */ inline Bool DynamicAudioEventInfo::wasLoopFlagOverriden() const { - return m_overriddenFields.test( OVERRIDE_LOOP_FLAG ); + return m_overriddenFields.test(OVERRIDE_LOOP_FLAG); } /** Query: was overrideLoopCount called? */ inline Bool DynamicAudioEventInfo::wasLoopCountOverriden() const { - return m_overriddenFields.test( OVERRIDE_LOOP_COUNT ); + return m_overriddenFields.test(OVERRIDE_LOOP_COUNT); } /** Query: was overrideVolume called? */ inline Bool DynamicAudioEventInfo::wasVolumeOverriden() const { - return m_overriddenFields.test( OVERRIDE_VOLUME ); + return m_overriddenFields.test(OVERRIDE_VOLUME); } /** Query: was overrideMinVolume called? */ inline Bool DynamicAudioEventInfo::wasMinVolumeOverriden() const { - return m_overriddenFields.test( OVERRIDE_MIN_VOLUME ); + return m_overriddenFields.test(OVERRIDE_MIN_VOLUME); } /** Query: was overrideMinRange called? */ inline Bool DynamicAudioEventInfo::wasMinRangeOverriden() const { - return m_overriddenFields.test( OVERRIDE_MIN_RANGE ); + return m_overriddenFields.test(OVERRIDE_MIN_RANGE); } /** Query: was overrideMaxRange called? */ inline Bool DynamicAudioEventInfo::wasMaxRangeOverriden() const { - return m_overriddenFields.test( OVERRIDE_MAX_RANGE ); + return m_overriddenFields.test(OVERRIDE_MAX_RANGE); } /** Query: was overridePriority called? */ inline Bool DynamicAudioEventInfo::wasPriorityOverriden() const { - return m_overriddenFields.test( OVERRIDE_PRIORITY ); + return m_overriddenFields.test(OVERRIDE_PRIORITY); } diff --git a/Core/GameEngine/Include/Common/Errors.h b/Core/GameEngine/Include/Common/Errors.h index 4b8316b0876..fe1722bee84 100644 --- a/Core/GameEngine/Include/Common/Errors.h +++ b/Core/GameEngine/Include/Common/Errors.h @@ -46,22 +46,22 @@ #pragma once /** - An ErrorCode is the repository for failure modes. In almost all situations, - these values will be THROWN, not returned as error codes. Feel free - to add to this list as necessary; however, there should generally be very - few codes needed. + An ErrorCode is the repository for failure modes. In almost all situations, + these values will be THROWN, not returned as error codes. Feel free + to add to this list as necessary; however, there should generally be very + few codes needed. */ -enum ErrorCode CPP_11(: UnsignedInt) +enum ErrorCode CPP_11( : UnsignedInt) { - ERROR_BASE = 0xdead0001, // a nice, distinctive value + ERROR_BASE = 0xdead0001, // a nice, distinctive value - ERROR_BUG = (ERROR_BASE + 0x0000), ///< should not be possible under normal operation - ERROR_OUT_OF_MEMORY = (ERROR_BASE + 0x0001), ///< unable to allocate memory. - ERROR_BAD_ARG = (ERROR_BASE + 0x0002), ///< generic "bad argument". - ERROR_INVALID_FILE_VERSION = (ERROR_BASE + 0x0003), ///< Unrecognized file version. - ERROR_CORRUPT_FILE_FORMAT = (ERROR_BASE + 0x0004), ///< Invalid file format. - ERROR_BAD_INI = (ERROR_BASE + 0x0005), ///< Bad INI data. - ERROR_INVALID_D3D = (ERROR_BASE + 0x0006), ///< Error initing D3D + ERROR_BUG = (ERROR_BASE + 0x0000), ///< should not be possible under normal operation + ERROR_OUT_OF_MEMORY = (ERROR_BASE + 0x0001), ///< unable to allocate memory. + ERROR_BAD_ARG = (ERROR_BASE + 0x0002), ///< generic "bad argument". + ERROR_INVALID_FILE_VERSION = (ERROR_BASE + 0x0003), ///< Unrecognized file version. + ERROR_CORRUPT_FILE_FORMAT = (ERROR_BASE + 0x0004), ///< Invalid file format. + ERROR_BAD_INI = (ERROR_BASE + 0x0005), ///< Bad INI data. + ERROR_INVALID_D3D = (ERROR_BASE + 0x0006), ///< Error initing D3D ERROR_LAST }; diff --git a/Core/GameEngine/Include/Common/FileSystem.h b/Core/GameEngine/Include/Common/FileSystem.h index 02a932f1313..bfbd8b42202 100644 --- a/Core/GameEngine/Include/Common/FileSystem.h +++ b/Core/GameEngine/Include/Common/FileSystem.h @@ -63,51 +63,53 @@ // Type Defines //---------------------------------------------------------------------------- +// clang-format off: [LEGACY_VC6] - preserve space in nested templates (> >) typedef std::set > FilenameList; +// clang-format on typedef FilenameList::iterator FilenameListIter; typedef UnsignedByte FileInstance; //---------------------------------------------------------------------------- // Type Defines //---------------------------------------------------------------------------- -//#define W3D_DIR_PATH "../FinalArt/W3D/" ///< .w3d files live here -//#define TGA_DIR_PATH "../FinalArt/Textures/" ///< .tga texture files live here -//#define TERRAIN_TGA_DIR_PATH "../FinalArt/Terrain/" ///< terrain .tga texture files live here -#define W3D_DIR_PATH "Art/W3D/" ///< .w3d files live here -#define TGA_DIR_PATH "Art/Textures/" ///< .tga texture files live here -#define TERRAIN_TGA_DIR_PATH "Art/Terrain/" ///< terrain .tga texture files live here -#define MAP_PREVIEW_DIR_PATH "%sMapPreviews/" ///< We need a common place we can copy the map previews to at runtime. -#define USER_W3D_DIR_PATH "%sW3D/" ///< .w3d files live here -#define USER_TGA_DIR_PATH "%sTextures/" ///< User .tga texture files live here +// #define W3D_DIR_PATH "../FinalArt/W3D/" ///< .w3d files live here +// #define TGA_DIR_PATH "../FinalArt/Textures/" ///< .tga texture files live here +// #define TERRAIN_TGA_DIR_PATH "../FinalArt/Terrain/" ///< terrain .tga texture files live here +#define W3D_DIR_PATH "Art/W3D/" ///< .w3d files live here +#define TGA_DIR_PATH "Art/Textures/" ///< .tga texture files live here +#define TERRAIN_TGA_DIR_PATH "Art/Terrain/" ///< terrain .tga texture files live here +#define MAP_PREVIEW_DIR_PATH "%sMapPreviews/" ///< We need a common place we can copy the map previews to at runtime. +#define USER_W3D_DIR_PATH "%sW3D/" ///< .w3d files live here +#define USER_TGA_DIR_PATH "%sTextures/" ///< User .tga texture files live here // the following defines are only to be used while maintaining legacy compatibility // with old files until they are completely gone and in the regular art set #ifdef MAINTAIN_LEGACY_FILES -#define LEGACY_W3D_DIR_PATH "../LegacyArt/W3D/" ///< .w3d files live here -#define LEGACY_TGA_DIR_PATH "../LegacyArt/Textures/" ///< .tga texture files live here -#endif // MAINTAIN_LEGACY_FILES + #define LEGACY_W3D_DIR_PATH "../LegacyArt/W3D/" ///< .w3d files live here + #define LEGACY_TGA_DIR_PATH "../LegacyArt/Textures/" ///< .tga texture files live here +#endif // MAINTAIN_LEGACY_FILES // LOAD_TEST_ASSETS automatically loads w3d assets from the TEST_W3D_DIR_PATH // without having to add an INI entry. #if defined(RTS_DEBUG) -#define LOAD_TEST_ASSETS 1 + #define LOAD_TEST_ASSETS 1 #endif #ifdef LOAD_TEST_ASSETS - #define ROAD_DIRECTORY "../TestArt/TestRoad/" - #define TEST_STRING "***TESTING" + #define ROAD_DIRECTORY "../TestArt/TestRoad/" + #define TEST_STRING "***TESTING" // the following directories will be used to look for test art #define LOOK_FOR_TEST_ART - #define TEST_W3D_DIR_PATH "../TestArt/" ///< .w3d files live here - #define TEST_TGA_DIR_PATH "../TestArt/" ///< .tga texture files live here + #define TEST_W3D_DIR_PATH "../TestArt/" ///< .w3d files live here + #define TEST_TGA_DIR_PATH "../TestArt/" ///< .tga texture files live here #endif #ifndef ENABLE_FILESYSTEM_LOGGING -#define ENABLE_FILESYSTEM_LOGGING (0) + #define ENABLE_FILESYSTEM_LOGGING (0) #endif - -struct FileInfo { +struct FileInfo +{ Int64 size() const { return (Int64)sizeHigh << 32 | sizeLow; } Int64 timestamp() const { return (Int64)timestampHigh << 32 | timestampLow; } @@ -122,23 +124,23 @@ struct FileInfo { // FileSystem //=============================== /** - * FileSystem is an interface class for creating specific FileSystem objects. - * - * A FileSystem object's implementation decides what derivative of File object needs to be - * created when FileSystem::Open() gets called. - */ + * FileSystem is an interface class for creating specific FileSystem objects. + * + * A FileSystem object's implementation decides what derivative of File object needs to be + * created when FileSystem::Open() gets called. + */ // TheSuperHackers @feature xezon 23/08/2025 Implements file instance access. // Can be used to access different versions of files in different archives under the same name. // Instance 0 refers to the top file that shadows all other files under the same name. -// +// // TheSuperHackers @bugfix xezon 26/10/2025 Adds a mutex to the file exist map to try prevent // application hangs during level load after the file exist map was corrupted because of writes // from multiple threads. //=============================== class FileSystem : public SubsystemInterface { - FileSystem(const FileSystem&); - FileSystem& operator=(const FileSystem&); + FileSystem(const FileSystem&); + FileSystem& operator=(const FileSystem&); public: FileSystem(); @@ -148,37 +150,41 @@ class FileSystem : public SubsystemInterface virtual void reset() override; virtual void update() override; - File* openFile( const Char *filename, Int access = File::NONE, size_t bufferSize = File::BUFFERSIZE, FileInstance instance = 0 ); ///< opens a File interface to the specified file - Bool doesFileExist(const Char *filename, FileInstance instance = 0) const; ///< returns TRUE if the file exists. filename should have no directory. - void getFileListInDirectory(const AsciiString& directory, const AsciiString& searchName, FilenameList &filenameList, Bool searchSubdirectories) const; ///< search the given directory for files matching the searchName (egs. *.ini, *.rep). Possibly search subdirectories. - Bool getFileInfo(const AsciiString& filename, FileInfo *fileInfo, FileInstance instance = 0) const; ///< fills in the FileInfo struct for the file given. returns TRUE if successful. + File* openFile(const Char* filename, Int access = File::NONE, size_t bufferSize = File::BUFFERSIZE, FileInstance instance = 0); ///< opens a File interface to the specified file + Bool doesFileExist(const Char* filename, FileInstance instance = 0) const; ///< returns TRUE if the file exists. filename should have no directory. + void getFileListInDirectory(const AsciiString& directory, const AsciiString& searchName, FilenameList& filenameList, Bool searchSubdirectories) const; ///< search the given directory for files matching the searchName (egs. *.ini, *.rep). Possibly search subdirectories. + Bool getFileInfo(const AsciiString& filename, FileInfo* fileInfo, FileInstance instance = 0) const; ///< fills in the FileInfo struct for the file given. returns TRUE if successful. - Bool createDirectory(AsciiString directory); ///< create a directory of the given name. + Bool createDirectory(AsciiString directory); ///< create a directory of the given name. - static AsciiString normalizePath(const AsciiString& path); ///< normalizes a file path. The path can refer to a directory. File path must be absolute, but does not need to exist. Returns an empty string on failure. - static Bool isPathInDirectory(const AsciiString& testPath, const AsciiString& basePath); ///< determines if a file path is within a base path. Both paths must be absolute, but do not need to exist. + static AsciiString normalizePath(const AsciiString& path); ///< normalizes a file path. The path can refer to a directory. File path must be absolute, but does not need to exist. Returns an empty string on failure. + static Bool isPathInDirectory(const AsciiString& testPath, const AsciiString& basePath); ///< determines if a file path is within a base path. Both paths must be absolute, but do not need to exist. protected: #if ENABLE_FILESYSTEM_EXISTENCE_CACHE struct FileExistData { - FileExistData() : instanceExists(0), instanceDoesNotExist(~FileInstance(0)) {} + FileExistData() + : instanceExists(0) + , instanceDoesNotExist(~FileInstance(0)) + {} FileInstance instanceExists; FileInstance instanceDoesNotExist; }; typedef std::hash_map< rts::string_key, FileExistData, rts::string_key_hash, - rts::string_key_equal > FileExistMap; + // clang-format off: [LEGACY_VC6] - preserve space in nested templates (> >) + rts::string_key_equal > + // clang-format on + FileExistMap; mutable FileExistMap m_fileExist; mutable FastCriticalSectionClass m_fileExistMutex; #endif }; -extern FileSystem* TheFileSystem; - - +extern FileSystem* TheFileSystem; //---------------------------------------------------------------------------- // Inlining diff --git a/Core/GameEngine/Include/Common/FramePacer.h b/Core/GameEngine/Include/Common/FramePacer.h index 5bba1a704e8..1890e37883b 100644 --- a/Core/GameEngine/Include/Common/FramePacer.h +++ b/Core/GameEngine/Include/Common/FramePacer.h @@ -20,60 +20,57 @@ #include "Common/FrameRateLimit.h" - // TheSuperHackers @todo Use unsigned integers for fps values // TheSuperHackers @todo Consolidate the GlobalData::m_useFpsLimit and FramePacer::m_enableFpsLimit // TheSuperHackers @todo Implement new fast forward in here class FramePacer { public: - typedef UnsignedInt LogicTimeQueryFlags; - enum LogicTimeQueryFlags_ CPP_11(: LogicTimeQueryFlags) + enum LogicTimeQueryFlags_ CPP_11( : LogicTimeQueryFlags) { - IgnoreFrozenTime = 1<<0, ///< Ignore frozen time for the query - IgnoreHaltedGame = 1<<1, ///< Ignore halted game for the query + IgnoreFrozenTime = 1 << 0, ///< Ignore frozen time for the query + IgnoreHaltedGame = 1 << 1, ///< Ignore halted game for the query }; FramePacer(); ~FramePacer(); - void update(); ///< Signal that the app/render update is done and wait for the fps limit if applicable. + void update(); ///< Signal that the app/render update is done and wait for the fps limit if applicable. - void setFramesPerSecondLimit( Int fps ); ///< Set the update fps limit. - Int getFramesPerSecondLimit() const; ///< Get the update fps limit. - void enableFramesPerSecondLimit( Bool enable ); ///< Enable or disable the update fps limit. - Bool isFramesPerSecondLimitEnabled() const; ///< Returns whether the fps limit is enabled here. - Bool isActualFramesPerSecondLimitEnabled() const; ///< Returns whether the fps limit is actually enabled when considering all game settings and setups. - Int getActualFramesPerSecondLimit() const; // Get the actual update fps limit. + void setFramesPerSecondLimit(Int fps); ///< Set the update fps limit. + Int getFramesPerSecondLimit() const; ///< Get the update fps limit. + void enableFramesPerSecondLimit(Bool enable); ///< Enable or disable the update fps limit. + Bool isFramesPerSecondLimitEnabled() const; ///< Returns whether the fps limit is enabled here. + Bool isActualFramesPerSecondLimitEnabled() const; ///< Returns whether the fps limit is actually enabled when considering all game settings and setups. + Int getActualFramesPerSecondLimit() const; // Get the actual update fps limit. - Real getUpdateTime() const; ///< Get the last update delta time in seconds. - Real getUpdateFps() const; ///< Get the last update fps. - Real getBaseOverUpdateFpsRatio(Real minUpdateFps = 5.0f); ///< Get the last engine base over update fps ratio. Used to scale user inputs to a frame rate independent speed. + Real getUpdateTime() const; ///< Get the last update delta time in seconds. + Real getUpdateFps() const; ///< Get the last update fps. + Real getBaseOverUpdateFpsRatio(Real minUpdateFps = 5.0f); ///< Get the last engine base over update fps ratio. Used to scale user inputs to a frame rate independent speed. - void setTimeFrozen(Bool frozen); ///< Set time frozen. Allows scripted camera movement. - void setGameHalted(Bool halted); ///< Set game halted. Does not allow scripted camera movement. + void setTimeFrozen(Bool frozen); ///< Set time frozen. Allows scripted camera movement. + void setGameHalted(Bool halted); ///< Set game halted. Does not allow scripted camera movement. Bool isTimeFrozen() const; Bool isGameHalted() const; - void setLogicTimeScaleFps( Int fps ); ///< Set the logic time scale fps and therefore scale the simulation time. Is capped by the max render fps and does not apply to network matches. - Int getLogicTimeScaleFps() const; ///< Get the raw logic time scale fps value. - void enableLogicTimeScale( Bool enable ); ///< Enable or disable the logic time scale setup. If disabled, the simulation time scale is bound to the render frame time or network update time. - Bool isLogicTimeScaleEnabled() const; ///< Check whether the logic time scale setup is enabled. - Int getActualLogicTimeScaleFps(LogicTimeQueryFlags flags = 0) const; ///< Get the real logic time scale fps, depending on the max render fps, network state and enabled state. - Real getActualLogicTimeScaleRatio(LogicTimeQueryFlags flags = 0) const; ///< Get the real logic time scale ratio, depending on the max render fps, network state and enabled state. - Real getActualLogicTimeScaleOverFpsRatio(LogicTimeQueryFlags flags = 0) const; ///< Get the real logic time scale over render fps ratio, used to scale down steps in render updates to match logic updates. - Real getLogicTimeStepSeconds(LogicTimeQueryFlags flags = 0) const; ///< Get the logic time step in seconds - Real getLogicTimeStepMilliseconds(LogicTimeQueryFlags flags = 0) const; ///< Get the logic time step in milliseconds + void setLogicTimeScaleFps(Int fps); ///< Set the logic time scale fps and therefore scale the simulation time. Is capped by the max render fps and does not apply to network matches. + Int getLogicTimeScaleFps() const; ///< Get the raw logic time scale fps value. + void enableLogicTimeScale(Bool enable); ///< Enable or disable the logic time scale setup. If disabled, the simulation time scale is bound to the render frame time or network update time. + Bool isLogicTimeScaleEnabled() const; ///< Check whether the logic time scale setup is enabled. + Int getActualLogicTimeScaleFps(LogicTimeQueryFlags flags = 0) const; ///< Get the real logic time scale fps, depending on the max render fps, network state and enabled state. + Real getActualLogicTimeScaleRatio(LogicTimeQueryFlags flags = 0) const; ///< Get the real logic time scale ratio, depending on the max render fps, network state and enabled state. + Real getActualLogicTimeScaleOverFpsRatio(LogicTimeQueryFlags flags = 0) const; ///< Get the real logic time scale over render fps ratio, used to scale down steps in render updates to match logic updates. + Real getLogicTimeStepSeconds(LogicTimeQueryFlags flags = 0) const; ///< Get the logic time step in seconds + Real getLogicTimeStepMilliseconds(LogicTimeQueryFlags flags = 0) const; ///< Get the logic time step in milliseconds protected: - FrameRateLimit m_frameRateLimit; - Int m_maxFPS; ///< Maximum frames per second for rendering - Int m_logicTimeScaleFPS; ///< Maximum frames per second for logic time scale + Int m_maxFPS; ///< Maximum frames per second for rendering + Int m_logicTimeScaleFPS; ///< Maximum frames per second for logic time scale - Real m_updateTime; ///< Last update delta time in seconds + Real m_updateTime; ///< Last update delta time in seconds Bool m_enableFpsLimit; Bool m_enableLogicTimeScale; diff --git a/Core/GameEngine/Include/Common/FrameRateLimit.h b/Core/GameEngine/Include/Common/FrameRateLimit.h index 5bb2b5fd3a7..bc8b6583c2a 100644 --- a/Core/GameEngine/Include/Common/FrameRateLimit.h +++ b/Core/GameEngine/Include/Common/FrameRateLimit.h @@ -20,7 +20,6 @@ #include "Common/GameCommon.h" - class FrameRateLimit { public: @@ -33,18 +32,16 @@ class FrameRateLimit Int64 m_start; }; - enum FpsValueChange { FpsValueChange_Increase, FpsValueChange_Decrease, }; - class RenderFpsPreset { public: - enum CPP_11(: UnsignedInt) + enum CPP_11( : UnsignedInt) { UncappedFpsValue = 1000000, }; @@ -57,11 +54,10 @@ class RenderFpsPreset static const UnsignedInt s_fpsValues[]; }; - class LogicTimeScaleFpsPreset { public: - enum CPP_11(: UnsignedInt) + enum CPP_11( : UnsignedInt) { #if RTS_DEBUG MinFpsValue = 5, @@ -75,4 +71,3 @@ class LogicTimeScaleFpsPreset static UnsignedInt getPrevFpsValue(UnsignedInt value); static UnsignedInt changeFpsValue(UnsignedInt value, FpsValueChange change); }; - diff --git a/Core/GameEngine/Include/Common/GameAudio.h b/Core/GameEngine/Include/Common/GameAudio.h index dae9d7cd132..87f7fb653a5 100644 --- a/Core/GameEngine/Include/Common/GameAudio.h +++ b/Core/GameEngine/Include/Common/GameAudio.h @@ -46,7 +46,6 @@ #include "Common/STLTypedefs.h" #include "Common/SubsystemInterface.h" - // Forward Declarations class AsciiString; @@ -57,20 +56,20 @@ class MusicManager; class Object; class SoundManager; - -enum AudioAffect CPP_11(: Int); -enum AudioType CPP_11(: Int); +enum AudioAffect CPP_11( : Int); +enum AudioType CPP_11( : Int); struct AudioEventInfo; struct AudioRequest; struct AudioSettings; struct MiscAudio; +// clang-format off: [LEGACY_VC6] - preserve space in nested templates (> >) typedef std::hash_map, rts::equal_to > AudioEventInfoHash; +// clang-format on typedef AudioEventInfoHash::iterator AudioEventInfoHashIt; typedef UnsignedInt AudioHandle; - // Defines enum { @@ -79,308 +78,309 @@ enum // Class AudioManager /** - The life of audio. - - When audio is requested to play, it is done so in the following manner: - 1) An AudioEventRTS is created on the stack. - 2) Its guts are copied from elsewhere (for instance, a ThingTemplate, or MiscAudio). - 3) It is added to TheAudio via TheAudio->addAudioEvent(...) - - The return value from addAudioEvent can be saved in case the sound needs to loop and/or be - terminated at some point. - - To reomve a playing sound, the call TheAudio->removeAudioEvent(...) is used. This will search - the list of currently playing audio for the specified handle, and kill the attached sound. It - will play a decay sound, if one is specified. - - The important functions of TheAudio, are therefore - GameAudio::addAudioEvent() - GameAudio::removeAudioEvent() - All other functions exist to support these two basic requirements. - - In addition to the fundamental requirements, the audio has a fairly complicated sound management - scheme. If all units were always allowed to sound off, the sound engine would be overwhelmed and - would sound awful. Therefore, when an audio event is requested, it goes through a series of - checks to determine if it is near enough to the camera, if it should be heard based on shroud, - local player affiliation, etc. (The entire list of checks is contained in shouldPlayLocally()). - - In addition, the world and unit audio are never allowed to exceed their footprint, as specified - in the audio settings INI file. In order to accommodate this, the audio uses an audio cache. The - audio cache will attempt to load a sample, assuming there is enough room. If there is not enough - room, then it goes through and finds any samples that are lower priority, and kills them until - enough room is present for the sample. If it cannot free enough room, nothing happens to the - cache. - - Although the audio is multithreaded, most of the operations are performed such that the worst - case scenario for thread miscommunication is that the main thread misses an event for one frame. - One specific case of this is the status of playing audio. Because audio is playing - asynchronously, it can complete at any time. When most audio completes, it sets a flag on the - event noting that it has completed. During the next update (from the main thread), anything with - that flag set is moved to the stopped list, and then is cleaned up. (Basically, the audio uses - a push model for its multithreadedness, which doesn't require thread safety such as mutexes or - semaphores). - - All in all, the best way to learn how the audio works is to track the lifetime of an event - through the system. This will give a better understanding than all the documentation I could - write. - - -jkmcd - -December 2002 + The life of audio. + + When audio is requested to play, it is done so in the following manner: + 1) An AudioEventRTS is created on the stack. + 2) Its guts are copied from elsewhere (for instance, a ThingTemplate, or MiscAudio). + 3) It is added to TheAudio via TheAudio->addAudioEvent(...) + + The return value from addAudioEvent can be saved in case the sound needs to loop and/or be + terminated at some point. + + To reomve a playing sound, the call TheAudio->removeAudioEvent(...) is used. This will search + the list of currently playing audio for the specified handle, and kill the attached sound. It + will play a decay sound, if one is specified. + + The important functions of TheAudio, are therefore + GameAudio::addAudioEvent() + GameAudio::removeAudioEvent() + All other functions exist to support these two basic requirements. + + In addition to the fundamental requirements, the audio has a fairly complicated sound management + scheme. If all units were always allowed to sound off, the sound engine would be overwhelmed and + would sound awful. Therefore, when an audio event is requested, it goes through a series of + checks to determine if it is near enough to the camera, if it should be heard based on shroud, + local player affiliation, etc. (The entire list of checks is contained in shouldPlayLocally()). + + In addition, the world and unit audio are never allowed to exceed their footprint, as specified + in the audio settings INI file. In order to accommodate this, the audio uses an audio cache. The + audio cache will attempt to load a sample, assuming there is enough room. If there is not enough + room, then it goes through and finds any samples that are lower priority, and kills them until + enough room is present for the sample. If it cannot free enough room, nothing happens to the + cache. + + Although the audio is multithreaded, most of the operations are performed such that the worst + case scenario for thread miscommunication is that the main thread misses an event for one frame. + One specific case of this is the status of playing audio. Because audio is playing + asynchronously, it can complete at any time. When most audio completes, it sets a flag on the + event noting that it has completed. During the next update (from the main thread), anything with + that flag set is moved to the stopped list, and then is cleaned up. (Basically, the audio uses + a push model for its multithreadedness, which doesn't require thread safety such as mutexes or + semaphores). + + All in all, the best way to learn how the audio works is to track the lifetime of an event + through the system. This will give a better understanding than all the documentation I could + write. + + -jkmcd + -December 2002 */ class AudioManager : public SubsystemInterface { - public: - typedef UnsignedInt MuteAudioReasonInt; +public: + typedef UnsignedInt MuteAudioReasonInt; - enum MuteAudioReason CPP_11(: UnsignedInt) - { - MuteAudioReason_WindowFocus, + enum MuteAudioReason CPP_11( : UnsignedInt) + { + MuteAudioReason_WindowFocus, - MuteAudioReason_Count - }; + MuteAudioReason_Count + }; - static const char *const MuteAudioReasonNames[]; + static const char* const MuteAudioReasonNames[]; - AudioManager(); - virtual ~AudioManager() override; + AudioManager(); + virtual ~AudioManager() override; #if defined(RTS_DEBUG) - virtual void audioDebugDisplay(DebugDisplayInterface *dd, void *userData, FILE *fp = nullptr ) = 0; + virtual void audioDebugDisplay(DebugDisplayInterface* dd, void* userData, FILE* fp = nullptr) = 0; #endif - // From SubsystemInterface - virtual void init() override; - virtual void postProcessLoad() override; - virtual void reset() override; - virtual void update() override; - - // device dependent stop, pause and resume - virtual void stopAudio( AudioAffect which ) = 0; - virtual void pauseAudio( AudioAffect which ) = 0; - virtual void resumeAudio( AudioAffect which ) = 0; - virtual void pauseAmbient( Bool shouldPause ) = 0; - - void muteAudio( MuteAudioReason reason ); - void unmuteAudio( MuteAudioReason reason ); - - // control for AudioEventsRTS - virtual AudioHandle addAudioEvent( const AudioEventRTS *eventToAdd ); ///< Add an audio event (event must be declared in an INI file) - virtual void removeAudioEvent( AudioHandle audioEvent ); ///< Remove an audio event, stop for instance. - virtual void killAudioEventImmediately( AudioHandle audioEvent ) = 0; - - virtual Bool isValidAudioEvent( const AudioEventRTS *eventToCheck ) const; ///< validate that this piece of audio exists - virtual Bool isValidAudioEvent( AudioEventRTS *eventToCheck ) const; ///< validate that this piece of audio exists - - // add tracks during INIification - void addTrackName( const AsciiString& trackName ); - AsciiString nextTrackName(const AsciiString& currentTrack ); - AsciiString prevTrackName(const AsciiString& currentTrack ); - - // changing music tracks - virtual void nextMusicTrack() = 0; - virtual void prevMusicTrack() = 0; - virtual Bool isMusicPlaying() const = 0; - virtual Bool hasMusicTrackCompleted( const AsciiString& trackName, Int numberOfTimes ) const = 0; - virtual AsciiString getMusicTrackName() const = 0; - - virtual void setAudioEventEnabled( AsciiString eventToAffect, Bool enable ); - virtual void setAudioEventVolumeOverride( AsciiString eventToAffect, Real newVolume ); - virtual void removeAudioEvent( AsciiString eventToRemove ); - virtual void removeDisabledEvents(); - - // Really meant for internal purposes only, but cannot be protected. - virtual void getInfoForAudioEvent( const AudioEventRTS *eventToFindAndFill ) const; // Note: m_eventInfo is Mutable, and so this function will overwrite it if found - - ///< Return whether the current audio is playing or not. - ///< NOTE NOTE NOTE !!DO NOT USE THIS IN FOR GAMELOGIC PURPOSES!! NOTE NOTE NOTE - virtual Bool isCurrentlyPlaying( AudioHandle handle ); - - // Device Dependent open and close functions - virtual void openDevice() = 0; - virtual void closeDevice() = 0; - virtual void *getDevice() = 0; - - // Device Dependent notification functions - virtual void notifyOfAudioCompletion( UnsignedInt audioCompleted, UnsignedInt flags ) = 0; - - // Device Dependent enumerate providers functions. It is okay for there to be only 1 provider (Miles provides a maximum of 64. - virtual UnsignedInt getProviderCount() const = 0; - virtual AsciiString getProviderName( UnsignedInt providerNum ) const = 0; - virtual UnsignedInt getProviderIndex( AsciiString providerName ) const = 0; - virtual void selectProvider( UnsignedInt providerNdx ) = 0; - virtual void unselectProvider() = 0; - virtual UnsignedInt getSelectedProvider() const = 0; - virtual void setSpeakerType( UnsignedInt speakerType ) = 0; - virtual UnsignedInt getSpeakerType() = 0; - - virtual UnsignedInt translateSpeakerTypeToUnsignedInt( const AsciiString& speakerType ); - virtual AsciiString translateUnsignedIntToSpeakerType( UnsignedInt speakerType ); - - // Device Dependent calls to get the number of channels for each type of audio (2-D, 3-D, Streams) - virtual UnsignedInt getNum2DSamples() const = 0; - virtual UnsignedInt getNum3DSamples() const = 0; - virtual UnsignedInt getNumStreams() const = 0; - - // Device Dependent calls to determine sound prioritization info - virtual Bool doesViolateLimit( AudioEventRTS *event ) const = 0; - virtual Bool isPlayingLowerPriority( AudioEventRTS *event ) const = 0; - virtual Bool isPlayingAlready( AudioEventRTS *event ) const = 0; - virtual Bool isObjectPlayingVoice( UnsignedInt objID ) const = 0; - - virtual void adjustVolumeOfPlayingAudio(AsciiString eventName, Real newVolume) = 0; - virtual void removePlayingAudio( AsciiString eventName ) = 0; - virtual void removeAllDisabledAudio() = 0; - - // Is the audio device on? We can skip a lot of audio processing if not. - virtual Bool isOn( AudioAffect whichToGet ) const; - virtual void setOn( Bool turnOn, AudioAffect whichToAffect ); - - // Set and get the device Volume - virtual void setVolume( Real volume, AudioAffect whichToAffect ); - virtual Real getVolume( AudioAffect whichToGet ); - - // To get a more 3-D feeling from the universe, we adjust the volume of the 3-D samples based - // on zoom. - virtual void set3DVolumeAdjustment( Real volumeAdjustment ); - - virtual Bool has3DSensitiveStreamsPlaying() const = 0; - - virtual void *getHandleForBink() = 0; - virtual void releaseHandleForBink() = 0; - - // this function will play an audio event rts by loading it into memory. It should not be used - // by anything except for the load screens. - virtual void friend_forcePlayAudioEventRTS(const AudioEventRTS* eventToPlay) = 0; + // From SubsystemInterface + virtual void init() override; + virtual void postProcessLoad() override; + virtual void reset() override; + virtual void update() override; + + // device dependent stop, pause and resume + virtual void stopAudio(AudioAffect which) = 0; + virtual void pauseAudio(AudioAffect which) = 0; + virtual void resumeAudio(AudioAffect which) = 0; + virtual void pauseAmbient(Bool shouldPause) = 0; + + void muteAudio(MuteAudioReason reason); + void unmuteAudio(MuteAudioReason reason); + + // control for AudioEventsRTS + virtual AudioHandle addAudioEvent(const AudioEventRTS* eventToAdd); ///< Add an audio event (event must be declared in an INI file) + virtual void removeAudioEvent(AudioHandle audioEvent); ///< Remove an audio event, stop for instance. + virtual void killAudioEventImmediately(AudioHandle audioEvent) = 0; + + virtual Bool isValidAudioEvent(const AudioEventRTS* eventToCheck) const; ///< validate that this piece of audio exists + virtual Bool isValidAudioEvent(AudioEventRTS* eventToCheck) const; ///< validate that this piece of audio exists + + // add tracks during INIification + void addTrackName(const AsciiString& trackName); + AsciiString nextTrackName(const AsciiString& currentTrack); + AsciiString prevTrackName(const AsciiString& currentTrack); + + // changing music tracks + virtual void nextMusicTrack() = 0; + virtual void prevMusicTrack() = 0; + virtual Bool isMusicPlaying() const = 0; + virtual Bool hasMusicTrackCompleted(const AsciiString& trackName, Int numberOfTimes) const = 0; + virtual AsciiString getMusicTrackName() const = 0; + + virtual void setAudioEventEnabled(AsciiString eventToAffect, Bool enable); + virtual void setAudioEventVolumeOverride(AsciiString eventToAffect, Real newVolume); + virtual void removeAudioEvent(AsciiString eventToRemove); + virtual void removeDisabledEvents(); + + // Really meant for internal purposes only, but cannot be protected. + virtual void getInfoForAudioEvent(const AudioEventRTS* eventToFindAndFill) const; // Note: m_eventInfo is Mutable, and so this function will overwrite it if found + + ///< Return whether the current audio is playing or not. + ///< NOTE NOTE NOTE !!DO NOT USE THIS IN FOR GAMELOGIC PURPOSES!! NOTE NOTE NOTE + virtual Bool isCurrentlyPlaying(AudioHandle handle); + + // Device Dependent open and close functions + virtual void openDevice() = 0; + virtual void closeDevice() = 0; + virtual void* getDevice() = 0; - // Update Listener position information - virtual void setListenerPosition( const Coord3D *newListenerPos, const Coord3D *newListenerOrientation ); - virtual const Coord3D *getListenerPosition() const; + // Device Dependent notification functions + virtual void notifyOfAudioCompletion(UnsignedInt audioCompleted, UnsignedInt flags) = 0; - virtual AudioRequest *allocateAudioRequest( Bool useAudioEvent ); - virtual void releaseAudioRequest( AudioRequest *requestToRelease ); - virtual void appendAudioRequest( AudioRequest *m_request ); - virtual void processRequestList(); + // Device Dependent enumerate providers functions. It is okay for there to be only 1 provider (Miles provides a maximum of 64. + virtual UnsignedInt getProviderCount() const = 0; + virtual AsciiString getProviderName(UnsignedInt providerNum) const = 0; + virtual UnsignedInt getProviderIndex(AsciiString providerName) const = 0; + virtual void selectProvider(UnsignedInt providerNdx) = 0; + virtual void unselectProvider() = 0; + virtual UnsignedInt getSelectedProvider() const = 0; + virtual void setSpeakerType(UnsignedInt speakerType) = 0; + virtual UnsignedInt getSpeakerType() = 0; - virtual AudioEventInfo *newAudioEventInfo( AsciiString newEventName ); - virtual void addAudioEventInfo( AudioEventInfo * newEventInfo ); - virtual AudioEventInfo *findAudioEventInfo( AsciiString eventName ) const; + virtual UnsignedInt translateSpeakerTypeToUnsignedInt(const AsciiString& speakerType); + virtual AsciiString translateUnsignedIntToSpeakerType(UnsignedInt speakerType); - const AudioSettings *getAudioSettings() const; - const MiscAudio *getMiscAudio() const; + // Device Dependent calls to get the number of channels for each type of audio (2-D, 3-D, Streams) + virtual UnsignedInt getNum2DSamples() const = 0; + virtual UnsignedInt getNum3DSamples() const = 0; + virtual UnsignedInt getNumStreams() const = 0; - // This function should only be called by AudioManager, MusicManager and SoundManager - virtual void releaseAudioEventRTS( AudioEventRTS *&eventToRelease ); + // Device Dependent calls to determine sound prioritization info + virtual Bool doesViolateLimit(AudioEventRTS* event) const = 0; + virtual Bool isPlayingLowerPriority(AudioEventRTS* event) const = 0; + virtual Bool isPlayingAlready(AudioEventRTS* event) const = 0; + virtual Bool isObjectPlayingVoice(UnsignedInt objID) const = 0; - // For INI - AudioSettings *friend_getAudioSettings(); - MiscAudio *friend_getMiscAudio(); - const FieldParse *getFieldParseTable() const; + virtual void adjustVolumeOfPlayingAudio(AsciiString eventName, Real newVolume) = 0; + virtual void removePlayingAudio(AsciiString eventName) = 0; + virtual void removeAllDisabledAudio() = 0; - const AudioEventRTS *getValidSilentAudioEvent() const { return m_silentAudioEvent; } - - virtual void setHardwareAccelerated(Bool accel) { m_hardwareAccel = accel; } - virtual Bool getHardwareAccelerated() { return m_hardwareAccel; } - - virtual void setSpeakerSurround(Bool surround) { m_surroundSpeakers = surround; } - virtual Bool getSpeakerSurround() { return m_surroundSpeakers; } - - virtual void refreshCachedVariables(); - - virtual void setPreferredProvider(AsciiString providerNdx) = 0; - virtual void setPreferredSpeaker(AsciiString speakerType) = 0; - - // For Scripting - virtual Real getAudioLengthMS( const AudioEventRTS *event ); - virtual Real getFileLengthMS( AsciiString strToLoad ) const = 0; - - // For the file cache to know when to remove files. - virtual void closeAnySamplesUsingFile( const void *fileToClose ) = 0; - - virtual Bool isMusicAlreadyLoaded() const; - - Bool getDisallowSpeech() const { return m_disallowSpeech; } - void setDisallowSpeech( Bool disallowSpeech ) { m_disallowSpeech = disallowSpeech; } - - // For Worldbuilder, to build lists from which to select - virtual void findAllAudioEventsOfType( AudioType audioType, std::vector& allEvents ); - virtual const AudioEventInfoHash & getAllAudioEvents() const { return m_allAudioEventInfo; } - - Real getZoomVolume() const { return m_zoomVolume; } - protected: + // Is the audio device on? We can skip a lot of audio processing if not. + virtual Bool isOn(AudioAffect whichToGet) const; + virtual void setOn(Bool turnOn, AudioAffect whichToAffect); - // Is the currently selected provider actually HW accelerated? - virtual Bool isCurrentProviderHardwareAccelerated(); + // Set and get the device Volume + virtual void setVolume(Real volume, AudioAffect whichToAffect); + virtual Real getVolume(AudioAffect whichToGet); - // Is the currently selected speaker type Surround sound? - virtual Bool isCurrentSpeakerTypeSurroundSound(); + // To get a more 3-D feeling from the universe, we adjust the volume of the 3-D samples based + // on zoom. + virtual void set3DVolumeAdjustment(Real volumeAdjustment); - // Should this piece of audio play on the local machine? - virtual Bool shouldPlayLocally(const AudioEventRTS *audioEvent); + virtual Bool has3DSensitiveStreamsPlaying() const = 0; - // Set the Listening position for the device - virtual void setDeviceListenerPosition() = 0; + virtual void* getHandleForBink() = 0; + virtual void releaseHandleForBink() = 0; - // For tracking purposes - virtual AudioHandle allocateNewHandle(); + // this function will play an audio event rts by loading it into memory. It should not be used + // by anything except for the load screens. + virtual void friend_forcePlayAudioEventRTS(const AudioEventRTS* eventToPlay) = 0; - // Remove all AudioEventInfo's with the m_isLevelSpecific flag - virtual void removeLevelSpecificAudioEventInfos(); + // Update Listener position information + virtual void setListenerPosition(const Coord3D* newListenerPos, const Coord3D* newListenerOrientation); + virtual const Coord3D* getListenerPosition() const; - void removeAllAudioRequests(); + virtual AudioRequest* allocateAudioRequest(Bool useAudioEvent); + virtual void releaseAudioRequest(AudioRequest* requestToRelease); + virtual void appendAudioRequest(AudioRequest* m_request); + virtual void processRequestList(); - protected: - AudioSettings *m_audioSettings; - MiscAudio *m_miscAudio; - MusicManager *m_music; - SoundManager *m_sound; - Coord3D m_listenerPosition; - Coord3D m_listenerOrientation; - std::list m_audioRequests; - std::vector m_musicTracks; + virtual AudioEventInfo* newAudioEventInfo(AsciiString newEventName); + virtual void addAudioEventInfo(AudioEventInfo* newEventInfo); + virtual AudioEventInfo* findAudioEventInfo(AsciiString eventName) const; - AudioEventInfoHash m_allAudioEventInfo; - AudioHandle theAudioHandlePool; - std::list > m_adjustedVolumes; + const AudioSettings* getAudioSettings() const; + const MiscAudio* getMiscAudio() const; - Real m_musicVolume; - Real m_soundVolume; - Real m_sound3DVolume; - Real m_speechVolume; + // This function should only be called by AudioManager, MusicManager and SoundManager + virtual void releaseAudioEventRTS(AudioEventRTS*& eventToRelease); + + // For INI + AudioSettings* friend_getAudioSettings(); + MiscAudio* friend_getMiscAudio(); + const FieldParse* getFieldParseTable() const; + + const AudioEventRTS* getValidSilentAudioEvent() const { return m_silentAudioEvent; } + + virtual void setHardwareAccelerated(Bool accel) { m_hardwareAccel = accel; } + virtual Bool getHardwareAccelerated() { return m_hardwareAccel; } + + virtual void setSpeakerSurround(Bool surround) { m_surroundSpeakers = surround; } + virtual Bool getSpeakerSurround() { return m_surroundSpeakers; } + + virtual void refreshCachedVariables(); + + virtual void setPreferredProvider(AsciiString providerNdx) = 0; + virtual void setPreferredSpeaker(AsciiString speakerType) = 0; + + // For Scripting + virtual Real getAudioLengthMS(const AudioEventRTS* event); + virtual Real getFileLengthMS(AsciiString strToLoad) const = 0; + + // For the file cache to know when to remove files. + virtual void closeAnySamplesUsingFile(const void* fileToClose) = 0; + + virtual Bool isMusicAlreadyLoaded() const; + + Bool getDisallowSpeech() const { return m_disallowSpeech; } + void setDisallowSpeech(Bool disallowSpeech) { m_disallowSpeech = disallowSpeech; } + + // For Worldbuilder, to build lists from which to select + virtual void findAllAudioEventsOfType(AudioType audioType, std::vector& allEvents); + virtual const AudioEventInfoHash& getAllAudioEvents() const { return m_allAudioEventInfo; } + + Real getZoomVolume() const { return m_zoomVolume; } + +protected: + // Is the currently selected provider actually HW accelerated? + virtual Bool isCurrentProviderHardwareAccelerated(); + + // Is the currently selected speaker type Surround sound? + virtual Bool isCurrentSpeakerTypeSurroundSound(); + + // Should this piece of audio play on the local machine? + virtual Bool shouldPlayLocally(const AudioEventRTS* audioEvent); + + // Set the Listening position for the device + virtual void setDeviceListenerPosition() = 0; - Real m_scriptMusicVolume; - Real m_scriptSoundVolume; - Real m_scriptSound3DVolume; - Real m_scriptSpeechVolume; + // For tracking purposes + virtual AudioHandle allocateNewHandle(); + + // Remove all AudioEventInfo's with the m_isLevelSpecific flag + virtual void removeLevelSpecificAudioEventInfos(); - Real m_systemMusicVolume; - Real m_systemSoundVolume; - Real m_systemSound3DVolume; - Real m_systemSpeechVolume; - Real m_zoomVolume; + void removeAllAudioRequests(); +protected: + AudioSettings* m_audioSettings; + MiscAudio* m_miscAudio; + MusicManager* m_music; + SoundManager* m_sound; + Coord3D m_listenerPosition; + Coord3D m_listenerOrientation; + std::list m_audioRequests; + std::vector m_musicTracks; - AudioEventRTS *m_silentAudioEvent; + AudioEventInfoHash m_allAudioEventInfo; + AudioHandle theAudioHandlePool; + // clang-format off: [LEGACY_VC6] - preserve space in nested templates (> >) + std::list > m_adjustedVolumes; + // clang-format on - enum - { - VOLUME_TYPE_MUSIC, - VOLUME_TYPE_SOUND, - VOLUME_TYPE_SOUND3D, - VOLUME_TYPE_SPEECH, - NUM_VOLUME_TYPES - }; - Real *m_savedValues; - MuteAudioReasonInt m_muteReasonBits; + Real m_musicVolume; + Real m_soundVolume; + Real m_sound3DVolume; + Real m_speechVolume; + + Real m_scriptMusicVolume; + Real m_scriptSoundVolume; + Real m_scriptSound3DVolume; + Real m_scriptSpeechVolume; + + Real m_systemMusicVolume; + Real m_systemSoundVolume; + Real m_systemSound3DVolume; + Real m_systemSpeechVolume; + Real m_zoomVolume; - // Group of 8 - Bool m_speechOn : 1; - Bool m_soundOn : 1; - Bool m_sound3DOn : 1; - Bool m_musicOn : 1; - Bool m_volumeHasChanged : 1; - Bool m_hardwareAccel : 1; - Bool m_surroundSpeakers : 1; - Bool m_disallowSpeech : 1; + AudioEventRTS* m_silentAudioEvent; + + enum + { + VOLUME_TYPE_MUSIC, + VOLUME_TYPE_SOUND, + VOLUME_TYPE_SOUND3D, + VOLUME_TYPE_SPEECH, + NUM_VOLUME_TYPES + }; + Real* m_savedValues; + MuteAudioReasonInt m_muteReasonBits; + + // Group of 8 + Bool m_speechOn : 1; + Bool m_soundOn : 1; + Bool m_sound3DOn : 1; + Bool m_musicOn : 1; + Bool m_volumeHasChanged : 1; + Bool m_hardwareAccel : 1; + Bool m_surroundSpeakers : 1; + Bool m_disallowSpeech : 1; }; -extern AudioManager *TheAudio; +extern AudioManager* TheAudio; diff --git a/Core/GameEngine/Include/Common/GameCommon.h b/Core/GameEngine/Include/Common/GameCommon.h index 62c6c3429f0..a2f8878e76f 100644 --- a/Core/GameEngine/Include/Common/GameCommon.h +++ b/Core/GameEngine/Include/Common/GameCommon.h @@ -47,7 +47,7 @@ #pragma once -//#define _CAMPEA_DEMO +// #define _CAMPEA_DEMO // ---------------------------------------------------------------------------------------------- #include "Lib/BaseType.h" @@ -64,7 +64,7 @@ // ---------------------------------------------------------------------------------------------- enum { - BaseFps = 30, // The historic base frame rate for this game. This value must never change. + BaseFps = 30, // The historic base frame rate for this game. This value must never change. LOGICFRAMES_PER_SECOND = WWSyncPerSecond, MSEC_PER_SECOND = 1000 }; @@ -106,17 +106,17 @@ inline Real ConvertAngularVelocityInDegreesPerSecToRadsPerFrame(Real degPerSec) // ---------------------------------------------------------------------------------------------- enum { - MAX_PLAYER_COUNT = 16 ///< max number of Players. + MAX_PLAYER_COUNT = 16 ///< max number of Players. }; // ---------------------------------------------------------------------------------------------- /** - a bitmask that can uniquely represent each player. + a bitmask that can uniquely represent each player. */ #if MAX_PLAYER_COUNT <= 16 - typedef UnsignedShort PlayerMaskType; - const PlayerMaskType PLAYERMASK_ALL = 0xffff; - const PlayerMaskType PLAYERMASK_NONE = 0x0; +typedef UnsignedShort PlayerMaskType; +const PlayerMaskType PLAYERMASK_ALL = 0xffff; +const PlayerMaskType PLAYERMASK_NONE = 0x0; #else #error "this is the wrong size" #endif @@ -124,7 +124,7 @@ enum // ---------------------------------------------------------------------------------------------- enum { - MAX_GLOBAL_GENERAL_TYPES = 9, ///< number of playable General Types, not including the boss) + MAX_GLOBAL_GENERAL_TYPES = 9, ///< number of playable General Types, not including the boss) /// The start of the playable global generals playertemplates GLOBAL_GENERAL_BEGIN = 5, @@ -134,7 +134,7 @@ enum }; //------------------------------------------------------------------------------------------------- -enum GameDifficulty CPP_11(: Int) +enum GameDifficulty CPP_11( : Int) { DIFFICULTY_EASY, DIFFICULTY_NORMAL, @@ -144,17 +144,17 @@ enum GameDifficulty CPP_11(: Int) }; //------------------------------------------------------------------------------------------------- -enum PlayerType CPP_11(: Int) +enum PlayerType CPP_11( : Int) { - PLAYER_HUMAN, ///< player is human-controlled - PLAYER_COMPUTER, ///< player is computer-controlled + PLAYER_HUMAN, ///< player is human-controlled + PLAYER_COMPUTER, ///< player is computer-controlled PLAYERTYPE_COUNT }; //------------------------------------------------------------------------------------------------- /// A PartitionCell can be one of three states for Shroud -enum CellShroudStatus CPP_11(: Int) +enum CellShroudStatus CPP_11( : Int) { CELLSHROUD_CLEAR, CELLSHROUD_FOGGED, @@ -163,30 +163,30 @@ enum CellShroudStatus CPP_11(: Int) //------------------------------------------------------------------------------------------------- /// Since an object can take up more than a single PartitionCell, this is a status that applies to the whole Object -enum ObjectShroudStatus CPP_11(: Int) +enum ObjectShroudStatus CPP_11( : Int) { - OBJECTSHROUD_INVALID, ///< indeterminate state, will recompute - OBJECTSHROUD_CLEAR, ///< object is not shrouded at all (ie, completely visible) - OBJECTSHROUD_PARTIAL_CLEAR, ///< object is partly clear (rest is shroud or fog) - OBJECTSHROUD_FOGGED, ///< object is completely fogged - OBJECTSHROUD_SHROUDED, ///< object is completely shrouded - OBJECTSHROUD_INVALID_BUT_PREVIOUS_VALID, ///< indeterminate state, will recompute, BUT previous status is valid, don't reset (used for save/load) + OBJECTSHROUD_INVALID, ///< indeterminate state, will recompute + OBJECTSHROUD_CLEAR, ///< object is not shrouded at all (ie, completely visible) + OBJECTSHROUD_PARTIAL_CLEAR, ///< object is partly clear (rest is shroud or fog) + OBJECTSHROUD_FOGGED, ///< object is completely fogged + OBJECTSHROUD_SHROUDED, ///< object is completely shrouded + OBJECTSHROUD_INVALID_BUT_PREVIOUS_VALID, ///< indeterminate state, will recompute, BUT previous status is valid, don't reset (used for save/load) }; //------------------------------------------------------------------------------------------------- -enum GuardMode CPP_11(: Int) +enum GuardMode CPP_11( : Int) { GUARDMODE_NORMAL, - GUARDMODE_GUARD_WITHOUT_PURSUIT, // no pursuit out of guard area - GUARDMODE_GUARD_FLYING_UNITS_ONLY // ignore nonflyers + GUARDMODE_GUARD_WITHOUT_PURSUIT, // no pursuit out of guard area + GUARDMODE_GUARD_FLYING_UNITS_ONLY // ignore nonflyers }; // --------------------------------------------------- enum { - NEVER = 0, - FOREVER = 0x3fffffff // (we use 0x3fffffff so that we can add offsets and not overflow... - // at 30fps we're still pretty safe!) + NEVER = 0, + FOREVER = 0x3fffffff // (we use 0x3fffffff so that we can add offsets and not overflow... + // at 30fps we're still pretty safe!) }; //------------------------------------------------------------------------------------------------- @@ -195,7 +195,7 @@ enum /// Veterancy level define needed by several files that don't need the full Experience code. // NOTE NOTE NOTE: Keep TheVeterencyNames in sync with these. -enum VeterancyLevel CPP_11(: Int) +enum VeterancyLevel CPP_11( : Int) { LEVEL_REGULAR, LEVEL_VETERAN, @@ -210,61 +210,60 @@ enum VeterancyLevel CPP_11(: Int) }; // TheVeterancyNames is defined in GameCommon.cpp -extern const char *const TheVeterancyNames[]; +extern const char* const TheVeterancyNames[]; //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -enum CommandSourceType CPP_11(: Int) +enum CommandSourceType CPP_11( : Int) { CMD_FROM_PLAYER = 0, CMD_FROM_SCRIPT, CMD_FROM_AI, - CMD_FROM_DOZER, // Special rare command when the dozer originates a command to attack a mine. Mines are not ai-attackable, and it seems deceitful for the dozer to generate a player or script command. jba. - CMD_DEFAULT_SWITCH_WEAPON, // Special case: A weapon that can be chosen -- this is the default case (machine gun vs flashbang). + CMD_FROM_DOZER, // Special rare command when the dozer originates a command to attack a mine. Mines are not ai-attackable, and it seems deceitful for the dozer to generate a player or script command. jba. + CMD_DEFAULT_SWITCH_WEAPON, // Special case: A weapon that can be chosen -- this is the default case (machine gun vs flashbang). COMMAND_SOURCE_TYPE_COUNT }; //------------------------------------------------------------------------------------------------- -enum AbleToAttackType CPP_11(: Int) +enum AbleToAttackType CPP_11( : Int) { - _ATTACK_FORCED = 0x01, - _ATTACK_CONTINUED = 0x02, + _ATTACK_FORCED = 0x01, + _ATTACK_CONTINUED = 0x02, _ATTACK_TUNNELNETWORK_GUARD = 0x04, /** - can we attack if this is a new target? + can we attack if this is a new target? */ ATTACK_NEW_TARGET = (0), /** - can we attack if this is a new target, via force-fire? - (The only current difference between this and ATTACK_NEW_TARGET is that disguised units - are force-attackable even when stealthed.) + can we attack if this is a new target, via force-fire? + (The only current difference between this and ATTACK_NEW_TARGET is that disguised units + are force-attackable even when stealthed.) */ - ATTACK_NEW_TARGET_FORCED= (_ATTACK_FORCED), + ATTACK_NEW_TARGET_FORCED = (_ATTACK_FORCED), /** - can we attack if this is continuation of an existing attack? - (The only current difference between this and ATTACK_NEW_TARGET is you are allowed to follow - immobile shrouded units into the fog) + can we attack if this is continuation of an existing attack? + (The only current difference between this and ATTACK_NEW_TARGET is you are allowed to follow + immobile shrouded units into the fog) */ ATTACK_CONTINUED_TARGET = (_ATTACK_CONTINUED), /** - can we attack if this is continuation of an existing attack? - (The only current difference between this and ATTACK_NEW_TARGET is you are allowed to follow - immobile shrouded units into the fog) + can we attack if this is continuation of an existing attack? + (The only current difference between this and ATTACK_NEW_TARGET is you are allowed to follow + immobile shrouded units into the fog) */ ATTACK_CONTINUED_TARGET_FORCED = (_ATTACK_FORCED | _ATTACK_CONTINUED), /** - Special case that bypasses some of the checks for units guarding from within tunnel networks! - For example, a unit inside couldn't normally see outside and would fail. + Special case that bypasses some of the checks for units guarding from within tunnel networks! + For example, a unit inside couldn't normally see outside and would fail. */ ATTACK_TUNNEL_NETWORK_GUARD = (_ATTACK_TUNNELNETWORK_GUARD) - }; //------------------------------------------------------------------------------------------------- @@ -306,144 +305,152 @@ inline VeterancyLevelFlags clearVeterancyLevelFlag(VeterancyLevelFlags flags, Ve #define BOGUSPTR(p) ((((unsigned int)(p)) & 1) != 0) // ---------------------------------------------------------------------------------------------- -#define MAKE_DLINK_HEAD(OBJCLASS, LISTNAME) \ -public: \ - inline DLINK_ITERATOR iterate_##LISTNAME() const \ - { \ - DEBUG_ASSERTCRASH(!BOGUSPTR(m_dlinkhead_##LISTNAME.m_head), ("bogus head ptr")); \ - return DLINK_ITERATOR(m_dlinkhead_##LISTNAME.m_head, &OBJCLASS::dlink_next_##LISTNAME); \ - } \ - inline OBJCLASS *getFirstItemIn_##LISTNAME() const \ - { \ - DEBUG_ASSERTCRASH(!BOGUSPTR(m_dlinkhead_##LISTNAME.m_head), ("bogus head ptr")); \ - return m_dlinkhead_##LISTNAME.m_head; \ - } \ - inline Bool isInList_##LISTNAME(OBJCLASS* o) const \ - { \ - DEBUG_ASSERTCRASH(!BOGUSPTR(m_dlinkhead_##LISTNAME.m_head), ("bogus head ptr")); \ - return o->dlink_isInList_##LISTNAME(&m_dlinkhead_##LISTNAME.m_head); \ - } \ - inline void prependTo_##LISTNAME(OBJCLASS* o) \ - { \ - DEBUG_ASSERTCRASH(!BOGUSPTR(m_dlinkhead_##LISTNAME.m_head), ("bogus head ptr")); \ - if (!isInList_##LISTNAME(o)) \ - o->dlink_prependTo_##LISTNAME(&m_dlinkhead_##LISTNAME.m_head); \ - } \ - inline void removeFrom_##LISTNAME(OBJCLASS* o) \ - { \ - DEBUG_ASSERTCRASH(!BOGUSPTR(m_dlinkhead_##LISTNAME.m_head), ("bogus head ptr")); \ - if (isInList_##LISTNAME(o)) \ - o->dlink_removeFrom_##LISTNAME(&m_dlinkhead_##LISTNAME.m_head); \ - } \ - typedef void (*RemoveAllProc_##LISTNAME)(OBJCLASS* o); \ - inline void removeAll_##LISTNAME(RemoveAllProc_##LISTNAME p = nullptr) \ - { \ - while (m_dlinkhead_##LISTNAME.m_head) \ - { \ - DEBUG_ASSERTCRASH(!BOGUSPTR(m_dlinkhead_##LISTNAME.m_head), ("bogus head ptr"));\ - OBJCLASS *tmp = m_dlinkhead_##LISTNAME.m_head; \ - removeFrom_##LISTNAME(tmp); \ - if (p) (*p)(tmp); \ - } \ - } \ - inline void reverse_##LISTNAME() \ - { \ - OBJCLASS* cur = m_dlinkhead_##LISTNAME.m_head; \ - OBJCLASS* prev = nullptr; \ - while (cur) \ - { \ - OBJCLASS* originalNext = cur->dlink_next_##LISTNAME(); \ - cur->dlink_swapLinks_##LISTNAME(); \ - prev = cur; \ - cur = originalNext; \ - } \ - m_dlinkhead_##LISTNAME.m_head = prev; \ - } \ -private: \ - /* a trick: init head to zero */ \ - struct DLINKHEAD_##LISTNAME \ - { \ - public: \ - OBJCLASS* m_head; \ - inline DLINKHEAD_##LISTNAME() : \ - m_head(0) { } \ - inline ~DLINKHEAD_##LISTNAME() \ - { DEBUG_ASSERTCRASH(!m_head,("destroying dlinkhead still in a list " #LISTNAME)); } \ - }; \ +#define MAKE_DLINK_HEAD(OBJCLASS, LISTNAME) \ +public: \ + inline DLINK_ITERATOR iterate_##LISTNAME() const \ + { \ + DEBUG_ASSERTCRASH(!BOGUSPTR(m_dlinkhead_##LISTNAME.m_head), ("bogus head ptr")); \ + return DLINK_ITERATOR(m_dlinkhead_##LISTNAME.m_head, &OBJCLASS::dlink_next_##LISTNAME); \ + } \ + inline OBJCLASS* getFirstItemIn_##LISTNAME() const \ + { \ + DEBUG_ASSERTCRASH(!BOGUSPTR(m_dlinkhead_##LISTNAME.m_head), ("bogus head ptr")); \ + return m_dlinkhead_##LISTNAME.m_head; \ + } \ + inline Bool isInList_##LISTNAME(OBJCLASS* o) const \ + { \ + DEBUG_ASSERTCRASH(!BOGUSPTR(m_dlinkhead_##LISTNAME.m_head), ("bogus head ptr")); \ + return o->dlink_isInList_##LISTNAME(&m_dlinkhead_##LISTNAME.m_head); \ + } \ + inline void prependTo_##LISTNAME(OBJCLASS* o) \ + { \ + DEBUG_ASSERTCRASH(!BOGUSPTR(m_dlinkhead_##LISTNAME.m_head), ("bogus head ptr")); \ + if (!isInList_##LISTNAME(o)) \ + o->dlink_prependTo_##LISTNAME(&m_dlinkhead_##LISTNAME.m_head); \ + } \ + inline void removeFrom_##LISTNAME(OBJCLASS* o) \ + { \ + DEBUG_ASSERTCRASH(!BOGUSPTR(m_dlinkhead_##LISTNAME.m_head), ("bogus head ptr")); \ + if (isInList_##LISTNAME(o)) \ + o->dlink_removeFrom_##LISTNAME(&m_dlinkhead_##LISTNAME.m_head); \ + } \ + typedef void (*RemoveAllProc_##LISTNAME)(OBJCLASS * o); \ + inline void removeAll_##LISTNAME(RemoveAllProc_##LISTNAME p = nullptr) \ + { \ + while (m_dlinkhead_##LISTNAME.m_head) \ + { \ + DEBUG_ASSERTCRASH(!BOGUSPTR(m_dlinkhead_##LISTNAME.m_head), ("bogus head ptr")); \ + OBJCLASS* tmp = m_dlinkhead_##LISTNAME.m_head; \ + removeFrom_##LISTNAME(tmp); \ + if (p) \ + (*p)(tmp); \ + } \ + } \ + inline void reverse_##LISTNAME() \ + { \ + OBJCLASS* cur = m_dlinkhead_##LISTNAME.m_head; \ + OBJCLASS* prev = nullptr; \ + while (cur) \ + { \ + OBJCLASS* originalNext = cur->dlink_next_##LISTNAME(); \ + cur->dlink_swapLinks_##LISTNAME(); \ + prev = cur; \ + cur = originalNext; \ + } \ + m_dlinkhead_##LISTNAME.m_head = prev; \ + } \ + \ +private: \ + /* a trick: init head to zero */ \ + struct DLINKHEAD_##LISTNAME \ + { \ + public: \ + OBJCLASS* m_head; \ + inline DLINKHEAD_##LISTNAME() \ + : m_head(0) \ + {} \ + inline ~DLINKHEAD_##LISTNAME() \ + { DEBUG_ASSERTCRASH(!m_head, ("destroying dlinkhead still in a list " #LISTNAME)); } \ + }; \ DLINKHEAD_##LISTNAME m_dlinkhead_##LISTNAME; // ---------------------------------------------------------------------------------------------- -#define MAKE_DLINK(OBJCLASS, LISTNAME) \ -public: \ - OBJCLASS* dlink_prev_##LISTNAME() const { return m_dlink_##LISTNAME.m_prev; } \ - OBJCLASS* dlink_next_##LISTNAME() const { return m_dlink_##LISTNAME.m_next; } \ - void dlink_swapLinks_##LISTNAME() \ - { \ - OBJCLASS* originalNext = m_dlink_##LISTNAME.m_next; \ - m_dlink_##LISTNAME.m_next = m_dlink_##LISTNAME.m_prev; \ - m_dlink_##LISTNAME.m_prev = originalNext; \ - } \ - Bool dlink_isInList_##LISTNAME(OBJCLASS* const* pListHead) const \ - { \ +#define MAKE_DLINK(OBJCLASS, LISTNAME) \ +public: \ + OBJCLASS* dlink_prev_##LISTNAME() const { return m_dlink_##LISTNAME.m_prev; } \ + OBJCLASS* dlink_next_##LISTNAME() const { return m_dlink_##LISTNAME.m_next; } \ + void dlink_swapLinks_##LISTNAME() \ + { \ + OBJCLASS* originalNext = m_dlink_##LISTNAME.m_next; \ + m_dlink_##LISTNAME.m_next = m_dlink_##LISTNAME.m_prev; \ + m_dlink_##LISTNAME.m_prev = originalNext; \ + } \ + Bool dlink_isInList_##LISTNAME(OBJCLASS* const* pListHead) const \ + { \ DEBUG_ASSERTCRASH(!BOGUSPTR(*pListHead) && !BOGUSPTR(m_dlink_##LISTNAME.m_next) && !BOGUSPTR(m_dlink_##LISTNAME.m_prev), ("bogus ptrs")); \ - return *pListHead == this || m_dlink_##LISTNAME.m_prev || m_dlink_##LISTNAME.m_next; \ - } \ - void dlink_prependTo_##LISTNAME(OBJCLASS** pListHead) \ - { \ - DEBUG_ASSERTCRASH(!dlink_isInList_##LISTNAME(pListHead), ("already in list " #LISTNAME)); \ + return *pListHead == this || m_dlink_##LISTNAME.m_prev || m_dlink_##LISTNAME.m_next; \ + } \ + void dlink_prependTo_##LISTNAME(OBJCLASS** pListHead) \ + { \ + DEBUG_ASSERTCRASH(!dlink_isInList_##LISTNAME(pListHead), ("already in list " #LISTNAME)); \ DEBUG_ASSERTCRASH(!BOGUSPTR(*pListHead) && !BOGUSPTR(m_dlink_##LISTNAME.m_next) && !BOGUSPTR(m_dlink_##LISTNAME.m_prev), ("bogus ptrs")); \ - m_dlink_##LISTNAME.m_next = *pListHead; \ - if (*pListHead) \ - (*pListHead)->m_dlink_##LISTNAME.m_prev = this; \ - *pListHead = this; \ + m_dlink_##LISTNAME.m_next = *pListHead; \ + if (*pListHead) \ + (*pListHead)->m_dlink_##LISTNAME.m_prev = this; \ + *pListHead = this; \ DEBUG_ASSERTCRASH(!BOGUSPTR(*pListHead) && !BOGUSPTR(m_dlink_##LISTNAME.m_next) && !BOGUSPTR(m_dlink_##LISTNAME.m_prev), ("bogus ptrs")); \ - } \ - void dlink_removeFrom_##LISTNAME(OBJCLASS** pListHead) \ - { \ - DEBUG_ASSERTCRASH(dlink_isInList_##LISTNAME(pListHead), ("not in list" #LISTNAME)); \ + } \ + void dlink_removeFrom_##LISTNAME(OBJCLASS** pListHead) \ + { \ + DEBUG_ASSERTCRASH(dlink_isInList_##LISTNAME(pListHead), ("not in list" #LISTNAME)); \ DEBUG_ASSERTCRASH(!BOGUSPTR(*pListHead) && !BOGUSPTR(m_dlink_##LISTNAME.m_next) && !BOGUSPTR(m_dlink_##LISTNAME.m_prev), ("bogus ptrs")); \ - if (m_dlink_##LISTNAME.m_next) \ - m_dlink_##LISTNAME.m_next->m_dlink_##LISTNAME.m_prev = m_dlink_##LISTNAME.m_prev; \ - if (m_dlink_##LISTNAME.m_prev) \ - m_dlink_##LISTNAME.m_prev->m_dlink_##LISTNAME.m_next = m_dlink_##LISTNAME.m_next; \ - else \ - *pListHead = m_dlink_##LISTNAME.m_next; \ - m_dlink_##LISTNAME.m_prev = 0; \ - m_dlink_##LISTNAME.m_next = 0; \ + if (m_dlink_##LISTNAME.m_next) \ + m_dlink_##LISTNAME.m_next->m_dlink_##LISTNAME.m_prev = m_dlink_##LISTNAME.m_prev; \ + if (m_dlink_##LISTNAME.m_prev) \ + m_dlink_##LISTNAME.m_prev->m_dlink_##LISTNAME.m_next = m_dlink_##LISTNAME.m_next; \ + else \ + *pListHead = m_dlink_##LISTNAME.m_next; \ + m_dlink_##LISTNAME.m_prev = 0; \ + m_dlink_##LISTNAME.m_next = 0; \ DEBUG_ASSERTCRASH(!BOGUSPTR(*pListHead) && !BOGUSPTR(m_dlink_##LISTNAME.m_next) && !BOGUSPTR(m_dlink_##LISTNAME.m_prev), ("bogus ptrs")); \ - } \ -private: \ - /* a trick: init links to zero */ \ - struct DLINK_##LISTNAME \ - { \ - public: \ - OBJCLASS* m_prev; \ - OBJCLASS* m_next; \ - inline DLINK_##LISTNAME() : \ - m_prev(0), m_next(0) { } \ - inline ~DLINK_##LISTNAME() \ - { DEBUG_ASSERTCRASH(!m_prev && !m_next,("destroying dlink still in a list " #LISTNAME)); } \ - }; \ + } \ + \ +private: \ + /* a trick: init links to zero */ \ + struct DLINK_##LISTNAME \ + { \ + public: \ + OBJCLASS* m_prev; \ + OBJCLASS* m_next; \ + inline DLINK_##LISTNAME() \ + : m_prev(0) \ + , m_next(0) \ + {} \ + inline ~DLINK_##LISTNAME() \ + { DEBUG_ASSERTCRASH(!m_prev && !m_next, ("destroying dlink still in a list " #LISTNAME)); } \ + }; \ DLINK_##LISTNAME m_dlink_##LISTNAME; // ------------------------------------------------------------------------ // this is the weird C++ syntax for "call pointer-to-member-function"... see C++ FAQ LITE for details. -#define callMemberFunction(object,ptrToMember) ((object).*(ptrToMember)) +#define callMemberFunction(object, ptrToMember) ((object).*(ptrToMember)) // ------------------------------------------------------------------------ -template +template class DLINK_ITERATOR { public: // this is the weird C++ syntax for "pointer-to-member-function" typedef OBJCLASS* (OBJCLASS::*GetNextFunc)() const; + private: OBJCLASS* m_cur; - GetNextFunc m_getNextFunc; // this is the weird C++ syntax for "pointer-to-member-function" + GetNextFunc m_getNextFunc; // this is the weird C++ syntax for "pointer-to-member-function" public: - DLINK_ITERATOR(OBJCLASS* cur, GetNextFunc getNextFunc) : m_cur(cur), m_getNextFunc(getNextFunc) - { - } + DLINK_ITERATOR(OBJCLASS* cur, GetNextFunc getNextFunc) + : m_cur(cur) + , m_getNextFunc(getNextFunc) + {} void advance() { @@ -460,12 +467,11 @@ class DLINK_ITERATOR { return m_cur; } - }; // ------------------------------------------------------------------------ -enum WhichTurretType CPP_11(: Int) +enum WhichTurretType CPP_11( : Int) { TURRET_INVALID = -1, @@ -489,7 +495,7 @@ inline Real stdAngleDiff(Real a1, Real a2) // ------------------------------------------------------------------------ // NOTE NOTE NOTE: Keep TheRelationShipNames in sync with this enum -enum Relationship CPP_11(: Int) +enum Relationship CPP_11( : Int) { ENEMIES, NEUTRAL, @@ -498,6 +504,5 @@ enum Relationship CPP_11(: Int) RELATIONSHIP_COUNT }; - // TheRelationShipNames is defined in Common/GameCommon.cpp -extern const char *const TheRelationshipNames[]; +extern const char* const TheRelationshipNames[]; diff --git a/Core/GameEngine/Include/Common/GameDefines.h b/Core/GameEngine/Include/Common/GameDefines.h index 627e5c76eab..82eefa401b5 100644 --- a/Core/GameEngine/Include/Common/GameDefines.h +++ b/Core/GameEngine/Include/Common/GameDefines.h @@ -24,38 +24,38 @@ // Use RETAIL_COMPATIBLE_CRC and RETAIL_COMPATIBLE_XFER_SAVE to guard breaking changes. #ifndef PRESERVE_RETAIL_BEHAVIOR -#define PRESERVE_RETAIL_BEHAVIOR (1) // Retain behavior present in retail Generals 1.08 and Zero Hour 1.04 + #define PRESERVE_RETAIL_BEHAVIOR (1) // Retain behavior present in retail Generals 1.08 and Zero Hour 1.04 #endif #ifndef PRESERVE_RETAIL_SCRIPTED_CAMERA -#define PRESERVE_RETAIL_SCRIPTED_CAMERA (1) // Retain scripted camera behavior present in retail Generals 1.08 and Zero Hour 1.04 + #define PRESERVE_RETAIL_SCRIPTED_CAMERA (1) // Retain scripted camera behavior present in retail Generals 1.08 and Zero Hour 1.04 #endif #ifndef RETAIL_COMPATIBLE_CRC -#define RETAIL_COMPATIBLE_CRC (1) // Game is expected to be CRC compatible with retail Generals 1.08, Zero Hour 1.04 + #define RETAIL_COMPATIBLE_CRC (1) // Game is expected to be CRC compatible with retail Generals 1.08, Zero Hour 1.04 #endif #ifndef RETAIL_COMPATIBLE_XFER_SAVE -#define RETAIL_COMPATIBLE_XFER_SAVE (1) // Game is expected to be Xfer Save compatible with retail Generals 1.08, Zero Hour 1.04 + #define RETAIL_COMPATIBLE_XFER_SAVE (1) // Game is expected to be Xfer Save compatible with retail Generals 1.08, Zero Hour 1.04 #endif // This is here to easily toggle between the retail compatible with fixed pathfinding fallback and pure fixed pathfinding mode #ifndef RETAIL_COMPATIBLE_PATHFINDING -#define RETAIL_COMPATIBLE_PATHFINDING (1) + #define RETAIL_COMPATIBLE_PATHFINDING (1) #endif // This is here to easily toggle between the retail compatible pathfinding memory allocation and the new static allocated data mode #ifndef RETAIL_COMPATIBLE_PATHFINDING_ALLOCATION -#define RETAIL_COMPATIBLE_PATHFINDING_ALLOCATION (1) + #define RETAIL_COMPATIBLE_PATHFINDING_ALLOCATION (1) #endif #ifndef RETAIL_COMPATIBLE_CIRCLE_FILL_ALGORITHM -#define RETAIL_COMPATIBLE_CIRCLE_FILL_ALGORITHM (1) // Use the original circle fill algorithm, which is more efficient but less accurate + #define RETAIL_COMPATIBLE_CIRCLE_FILL_ALGORITHM (1) // Use the original circle fill algorithm, which is more efficient but less accurate #endif // Disable non retail fixes in the networking, such as putting more data per UDP packet #ifndef RETAIL_COMPATIBLE_NETWORKING -#define RETAIL_COMPATIBLE_NETWORKING (1) + #define RETAIL_COMPATIBLE_NETWORKING (1) #endif // This is essentially synonymous for RETAIL_COMPATIBLE_CRC. There is a lot wrong with AIGroup, such as use-after-free, double-free, leaks, @@ -63,60 +63,60 @@ // but put them behind this macro. #ifndef RETAIL_COMPATIBLE_AIGROUP -#define RETAIL_COMPATIBLE_AIGROUP (1) // AIGroup logic is expected to be CRC compatible with retail Generals 1.08, Zero Hour 1.04 + #define RETAIL_COMPATIBLE_AIGROUP (1) // AIGroup logic is expected to be CRC compatible with retail Generals 1.08, Zero Hour 1.04 #endif #ifndef ENABLE_GAMETEXT_SUBSTITUTES -#define ENABLE_GAMETEXT_SUBSTITUTES (1) // The code can provide substitute texts when labels and strings are missing in the STR or CSF translation file + #define ENABLE_GAMETEXT_SUBSTITUTES (1) // The code can provide substitute texts when labels and strings are missing in the STR or CSF translation file #endif // Previously the configurable shroud sat behind #if defined(RTS_DEBUG) // Enable the configurable shroud to properly draw the terrain in World Builder without RTS_DEBUG compiled in. // Disable the configurable shroud to make shroud hacking a bit less accessible in Release game builds. #ifndef ENABLE_CONFIGURABLE_SHROUD -#define ENABLE_CONFIGURABLE_SHROUD (1) // When enabled, the GlobalData contains a field to turn on/off the shroud, otherwise shroud is always enabled + #define ENABLE_CONFIGURABLE_SHROUD (1) // When enabled, the GlobalData contains a field to turn on/off the shroud, otherwise shroud is always enabled #endif // Enable buffered IO in File System. Was disabled in retail game. // Buffered IO generally is much faster than unbuffered for small reads and writes. #ifndef USE_BUFFERED_IO -#define USE_BUFFERED_IO (1) + #define USE_BUFFERED_IO (1) #endif // Enable cache for local file existence. Reduces amount of disk accesses for better performance, // but decreases file existence correctness and runtime stability, if a cached file is deleted on runtime. #ifndef ENABLE_FILESYSTEM_EXISTENCE_CACHE -#define ENABLE_FILESYSTEM_EXISTENCE_CACHE (1) + #define ENABLE_FILESYSTEM_EXISTENCE_CACHE (1) #endif // Enable prioritization of textures by size. This will improve the texture quality of 481 textures in Zero Hour // by using the larger resolution textures from Generals. Content wise these textures are identical. #ifndef PRIORITIZE_TEXTURES_BY_SIZE -#define PRIORITIZE_TEXTURES_BY_SIZE (1) + #define PRIORITIZE_TEXTURES_BY_SIZE (1) #endif // Enable obsolete code. This mainly refers to code that existed in Generals but was removed in GeneralsMD. // Disable and remove this when Generals and GeneralsMD are merged. #if RTS_GENERALS -#ifndef USE_OBSOLETE_GENERALS_CODE -#define USE_OBSOLETE_GENERALS_CODE (1) -#endif + #ifndef USE_OBSOLETE_GENERALS_CODE + #define USE_OBSOLETE_GENERALS_CODE (1) + #endif #endif // Overwrite window settings until wnd data files are adapted or fixed. #ifndef ENABLE_GUI_HACKS -#define ENABLE_GUI_HACKS (1) + #define ENABLE_GUI_HACKS (1) #endif // Tell our computer identity in the LAN lobby. Disable for privacy. // Was enabled in the retail game and exposed the computer login and host names. #ifdef RTS_DEBUG -#ifndef TELL_COMPUTER_IDENTITY_IN_LAN_LOBBY -#define TELL_COMPUTER_IDENTITY_IN_LAN_LOBBY (1) -#endif + #ifndef TELL_COMPUTER_IDENTITY_IN_LAN_LOBBY + #define TELL_COMPUTER_IDENTITY_IN_LAN_LOBBY (1) + #endif #endif -#define MIN_DISPLAY_BIT_DEPTH 16 -#define DEFAULT_DISPLAY_BIT_DEPTH 32 -#define DEFAULT_DISPLAY_WIDTH 800 // The standard resolution this game was designed for -#define DEFAULT_DISPLAY_HEIGHT 600 // The standard resolution this game was designed for +#define MIN_DISPLAY_BIT_DEPTH 16 +#define DEFAULT_DISPLAY_BIT_DEPTH 32 +#define DEFAULT_DISPLAY_WIDTH 800 // The standard resolution this game was designed for +#define DEFAULT_DISPLAY_HEIGHT 600 // The standard resolution this game was designed for diff --git a/Core/GameEngine/Include/Common/GameMemory.h b/Core/GameEngine/Include/Common/GameMemory.h index 0e901b9d4af..572d57f2aea 100644 --- a/Core/GameEngine/Include/Common/GameMemory.h +++ b/Core/GameEngine/Include/Common/GameMemory.h @@ -54,7 +54,7 @@ #define MEMORYPOOL_DEBUG_CUSTOM_NEW #endif -//#if defined(RTS_DEBUG) && !defined(MEMORYPOOL_DEBUG) && !defined(DISABLE_MEMORYPOOL_DEBUG) +// #if defined(RTS_DEBUG) && !defined(MEMORYPOOL_DEBUG) && !defined(DISABLE_MEMORYPOOL_DEBUG) #if defined(RTS_DEBUG) && !defined(MEMORYPOOL_DEBUG) && !defined(DISABLE_MEMORYPOOL_DEBUG) #define MEMORYPOOL_DEBUG #endif @@ -91,129 +91,128 @@ #define MEMORYPOOL_STACKTRACE #endif - // flags for the memory-report options. - enum - { +// flags for the memory-report options. +enum +{ -#ifdef MEMORYPOOL_CHECKPOINTING - // ------------------------------------------------------ - // you usually won't use the _REPORT bits directly; see below for more convenient combinations. - - // you must set at least one of the 'allocate' bits. - _REPORT_CP_ALLOCATED_BEFORE = 0x0001, - _REPORT_CP_ALLOCATED_BETWEEN = 0x0002, - _REPORT_CP_ALLOCATED_DONTCARE = (_REPORT_CP_ALLOCATED_BEFORE|_REPORT_CP_ALLOCATED_BETWEEN), - - // you must set at least one of the 'freed' bits. - _REPORT_CP_FREED_BEFORE = 0x0010, - _REPORT_CP_FREED_BETWEEN = 0x0020, - _REPORT_CP_FREED_NEVER = 0x0040, // ie, still in existence - _REPORT_CP_FREED_DONTCARE = (_REPORT_CP_FREED_BEFORE|_REPORT_CP_FREED_BETWEEN|_REPORT_CP_FREED_NEVER), + #ifdef MEMORYPOOL_CHECKPOINTING + // ------------------------------------------------------ + // you usually won't use the _REPORT bits directly; see below for more convenient combinations. + + // you must set at least one of the 'allocate' bits. + _REPORT_CP_ALLOCATED_BEFORE = 0x0001, + _REPORT_CP_ALLOCATED_BETWEEN = 0x0002, + _REPORT_CP_ALLOCATED_DONTCARE = (_REPORT_CP_ALLOCATED_BEFORE | _REPORT_CP_ALLOCATED_BETWEEN), + + // you must set at least one of the 'freed' bits. + _REPORT_CP_FREED_BEFORE = 0x0010, + _REPORT_CP_FREED_BETWEEN = 0x0020, + _REPORT_CP_FREED_NEVER = 0x0040, // ie, still in existence + _REPORT_CP_FREED_DONTCARE = (_REPORT_CP_FREED_BEFORE | _REPORT_CP_FREED_BETWEEN | _REPORT_CP_FREED_NEVER), // ------------------------------------------------------ -#endif // MEMORYPOOL_CHECKPOINTING - -#ifdef MEMORYPOOL_CHECKPOINTING - /** display the stacktrace for allocation location for all blocks found. - this bit may be mixed-n-matched with any other flag. - */ - REPORT_CP_STACKTRACE = 0x0100, -#endif + #endif // MEMORYPOOL_CHECKPOINTING - /** display stats for each pool, in addition to each block. - (this is useful for finding suitable allocation counts for the pools.) - this bit may be mixed-n-matched with any other flag. - */ - REPORT_POOLINFO = 0x0200, + #ifdef MEMORYPOOL_CHECKPOINTING + /** display the stacktrace for allocation location for all blocks found. + this bit may be mixed-n-matched with any other flag. + */ + REPORT_CP_STACKTRACE = 0x0100, + #endif - /** report on the overall memory situation (including all pools and dma's). - this bit may be mixed-n-matched with any other flag. - */ - REPORT_FACTORYINFO = 0x0400, + /** display stats for each pool, in addition to each block. + (this is useful for finding suitable allocation counts for the pools.) + this bit may be mixed-n-matched with any other flag. + */ + REPORT_POOLINFO = 0x0200, - /** report on pools that have overflowed their initial allocation. - this bit may be mixed-n-matched with any other flag. - */ - REPORT_POOL_OVERFLOW = 0x0800, + /** report on the overall memory situation (including all pools and dma's). + this bit may be mixed-n-matched with any other flag. + */ + REPORT_FACTORYINFO = 0x0400, - /** simple-n-cheap leak checking */ - REPORT_SIMPLE_LEAKS = 0x1000, + /** report on pools that have overflowed their initial allocation. + this bit may be mixed-n-matched with any other flag. + */ + REPORT_POOL_OVERFLOW = 0x0800, -#ifdef MEMORYPOOL_CHECKPOINTING - /** report on blocks that were allocated between the checkpoints. - (don't care if they were freed or not.) - */ - REPORT_CP_ALLOCATES = (_REPORT_CP_ALLOCATED_BETWEEN | _REPORT_CP_FREED_DONTCARE), + /** simple-n-cheap leak checking */ + REPORT_SIMPLE_LEAKS = 0x1000, - /** report on blocks that were freed between the checkpoints. - (don't care when they were allocated.) - */ - REPORT_CP_FREES = (_REPORT_CP_ALLOCATED_DONTCARE | _REPORT_CP_FREED_BETWEEN), + #ifdef MEMORYPOOL_CHECKPOINTING + /** report on blocks that were allocated between the checkpoints. + (don't care if they were freed or not.) + */ + REPORT_CP_ALLOCATES = (_REPORT_CP_ALLOCATED_BETWEEN | _REPORT_CP_FREED_DONTCARE), - /** report on blocks that were allocated between the checkpoints, and still exist - (note that this reports *potential* leaks -- some such blocks may be desired) - */ - REPORT_CP_LEAKS = (_REPORT_CP_ALLOCATED_BETWEEN | _REPORT_CP_FREED_NEVER), + /** report on blocks that were freed between the checkpoints. + (don't care when they were allocated.) + */ + REPORT_CP_FREES = (_REPORT_CP_ALLOCATED_DONTCARE | _REPORT_CP_FREED_BETWEEN), - /** report on blocks that existed before checkpoint #1 and still exist now. - */ - REPORT_CP_LONGTERM = (_REPORT_CP_ALLOCATED_BEFORE | _REPORT_CP_FREED_NEVER), + /** report on blocks that were allocated between the checkpoints, and still exist + (note that this reports *potential* leaks -- some such blocks may be desired) + */ + REPORT_CP_LEAKS = (_REPORT_CP_ALLOCATED_BETWEEN | _REPORT_CP_FREED_NEVER), - /** report on blocks that were allocated-and-freed between the checkpoints. - */ - REPORT_CP_TRANSIENT = (_REPORT_CP_ALLOCATED_BETWEEN | _REPORT_CP_FREED_BETWEEN), + /** report on blocks that existed before checkpoint #1 and still exist now. + */ + REPORT_CP_LONGTERM = (_REPORT_CP_ALLOCATED_BEFORE | _REPORT_CP_FREED_NEVER), - /** report on all blocks that currently exist - */ - REPORT_CP_EXISTING = (_REPORT_CP_ALLOCATED_BEFORE | _REPORT_CP_ALLOCATED_BETWEEN | _REPORT_CP_FREED_NEVER), + /** report on blocks that were allocated-and-freed between the checkpoints. + */ + REPORT_CP_TRANSIENT = (_REPORT_CP_ALLOCATED_BETWEEN | _REPORT_CP_FREED_BETWEEN), - /** report on all blocks that have ever existed (!) (or at least, since the last call - to debugResetCheckpoints) - */ - REPORT_CP_ALL = (_REPORT_CP_ALLOCATED_DONTCARE | _REPORT_CP_FREED_DONTCARE) -#endif // MEMORYPOOL_CHECKPOINTING + /** report on all blocks that currently exist + */ + REPORT_CP_EXISTING = (_REPORT_CP_ALLOCATED_BEFORE | _REPORT_CP_ALLOCATED_BETWEEN | _REPORT_CP_FREED_NEVER), - }; + /** report on all blocks that have ever existed (!) (or at least, since the last call + to debugResetCheckpoints) + */ + REPORT_CP_ALL = (_REPORT_CP_ALLOCATED_DONTCARE | _REPORT_CP_FREED_DONTCARE) + #endif // MEMORYPOOL_CHECKPOINTING +}; -#endif // MEMORYPOOL_DEBUG +#endif // MEMORYPOOL_DEBUG // TheSuperHackers @build xezon 30/03/2025 Define DISABLE_GAMEMEMORY to use a null implementations for Game Memory. // Useful for address sanitizer checks and other investigations. // Is included below the macros so that memory pool debug code can still be used. #ifdef DISABLE_GAMEMEMORY -#include "GameMemoryNull.h" + #include "GameMemoryNull.h" #else -#ifdef MEMORYPOOL_DEBUG + #ifdef MEMORYPOOL_DEBUG - #define DECLARE_LITERALSTRING_ARG1 const char * debugLiteralTagString - #define PASS_LITERALSTRING_ARG1 debugLiteralTagString - #define DECLARE_LITERALSTRING_ARG2 , const char * debugLiteralTagString - #define PASS_LITERALSTRING_ARG2 , debugLiteralTagString + #define DECLARE_LITERALSTRING_ARG1 const char* debugLiteralTagString + #define PASS_LITERALSTRING_ARG1 debugLiteralTagString + #define DECLARE_LITERALSTRING_ARG2 , const char* debugLiteralTagString + #define PASS_LITERALSTRING_ARG2 , debugLiteralTagString - #define MP_LOC_SUFFIX /*" [" DEBUG_FILENLINE "]"*/ + #define MP_LOC_SUFFIX /*" [" DEBUG_FILENLINE "]"*/ - #define allocateBlock(ARGLITERAL) allocateBlockImplementation(ARGLITERAL MP_LOC_SUFFIX) - #define allocateBlockDoNotZero(ARGLITERAL) allocateBlockDoNotZeroImplementation(ARGLITERAL MP_LOC_SUFFIX) - #define allocateBytes(ARGCOUNT,ARGLITERAL) allocateBytesImplementation(ARGCOUNT, ARGLITERAL MP_LOC_SUFFIX) - #define allocateBytesDoNotZero(ARGCOUNT,ARGLITERAL) allocateBytesDoNotZeroImplementation(ARGCOUNT, ARGLITERAL MP_LOC_SUFFIX) - #define newInstanceDesc(ARGCLASS,ARGLITERAL) new(ARGCLASS::ARGCLASS##_GLUE_NOT_IMPLEMENTED, ARGLITERAL MP_LOC_SUFFIX) ARGCLASS - #define newInstance(ARGCLASS) new(ARGCLASS::ARGCLASS##_GLUE_NOT_IMPLEMENTED, __FILE__) ARGCLASS + #define allocateBlock(ARGLITERAL) allocateBlockImplementation(ARGLITERAL MP_LOC_SUFFIX) + #define allocateBlockDoNotZero(ARGLITERAL) allocateBlockDoNotZeroImplementation(ARGLITERAL MP_LOC_SUFFIX) + #define allocateBytes(ARGCOUNT, ARGLITERAL) allocateBytesImplementation(ARGCOUNT, ARGLITERAL MP_LOC_SUFFIX) + #define allocateBytesDoNotZero(ARGCOUNT, ARGLITERAL) allocateBytesDoNotZeroImplementation(ARGCOUNT, ARGLITERAL MP_LOC_SUFFIX) + #define newInstanceDesc(ARGCLASS, ARGLITERAL) new (ARGCLASS::ARGCLASS##_GLUE_NOT_IMPLEMENTED, ARGLITERAL MP_LOC_SUFFIX) ARGCLASS + #define newInstance(ARGCLASS) new (ARGCLASS::ARGCLASS##_GLUE_NOT_IMPLEMENTED, __FILE__) ARGCLASS -#else + #else - #define DECLARE_LITERALSTRING_ARG1 - #define PASS_LITERALSTRING_ARG1 - #define DECLARE_LITERALSTRING_ARG2 - #define PASS_LITERALSTRING_ARG2 + #define DECLARE_LITERALSTRING_ARG1 + #define PASS_LITERALSTRING_ARG1 + #define DECLARE_LITERALSTRING_ARG2 + #define PASS_LITERALSTRING_ARG2 - #define allocateBlock(ARGLITERAL) allocateBlockImplementation() - #define allocateBlockDoNotZero(ARGLITERAL) allocateBlockDoNotZeroImplementation() - #define allocateBytes(ARGCOUNT,ARGLITERAL) allocateBytesImplementation(ARGCOUNT) - #define allocateBytesDoNotZero(ARGCOUNT,ARGLITERAL) allocateBytesDoNotZeroImplementation(ARGCOUNT) - #define newInstanceDesc(ARGCLASS,ARGLITERAL) new(ARGCLASS::ARGCLASS##_GLUE_NOT_IMPLEMENTED) ARGCLASS - #define newInstance(ARGCLASS) new(ARGCLASS::ARGCLASS##_GLUE_NOT_IMPLEMENTED) ARGCLASS + #define allocateBlock(ARGLITERAL) allocateBlockImplementation() + #define allocateBlockDoNotZero(ARGLITERAL) allocateBlockDoNotZeroImplementation() + #define allocateBytes(ARGCOUNT, ARGLITERAL) allocateBytesImplementation(ARGCOUNT) + #define allocateBytesDoNotZero(ARGCOUNT, ARGLITERAL) allocateBytesDoNotZeroImplementation(ARGCOUNT) + #define newInstanceDesc(ARGCLASS, ARGLITERAL) new (ARGCLASS::ARGCLASS##_GLUE_NOT_IMPLEMENTED) ARGCLASS + #define newInstance(ARGCLASS) new (ARGCLASS::ARGCLASS##_GLUE_NOT_IMPLEMENTED) ARGCLASS -#endif + #endif // FORWARD REFERENCES ///////////////////////////////////////////////////////// @@ -228,131 +227,126 @@ class BlockCheckpointInfo; // ---------------------------------------------------------------------------- /** - This class is purely a convenience used to pass optional arguments to initMemoryManager(), - and by extension, to createDynamicMemoryAllocator(). You can specify how many sub-pools you - want, what size each is, what the allocation counts are to be, etc. Most apps will - construct an array of these to pass to initMemoryManager() and never use it elsewhere. + This class is purely a convenience used to pass optional arguments to initMemoryManager(), + and by extension, to createDynamicMemoryAllocator(). You can specify how many sub-pools you + want, what size each is, what the allocation counts are to be, etc. Most apps will + construct an array of these to pass to initMemoryManager() and never use it elsewhere. */ struct PoolInitRec { - const char *poolName; ///< name of the pool; by convention, "dmaPool_XXX" where XXX is allocationSize - Int allocationSize; ///< size, in bytes, of the pool. - Int initialAllocationCount; ///< initial number of blocks to allocate. - Int overflowAllocationCount; ///< when the pool runs out of space, allocate more blocks in this increment + const char* poolName; ///< name of the pool; by convention, "dmaPool_XXX" where XXX is allocationSize + Int allocationSize; ///< size, in bytes, of the pool. + Int initialAllocationCount; ///< initial number of blocks to allocate. + Int overflowAllocationCount; ///< when the pool runs out of space, allocate more blocks in this increment }; enum { - MAX_DYNAMICMEMORYALLOCATOR_SUBPOOLS = 8 ///< The max number of subpools allowed in a DynamicMemoryAllocator + MAX_DYNAMICMEMORYALLOCATOR_SUBPOOLS = 8 ///< The max number of subpools allowed in a DynamicMemoryAllocator }; -#ifdef MEMORYPOOL_CHECKPOINTING + #ifdef MEMORYPOOL_CHECKPOINTING // ---------------------------------------------------------------------------- /** - This class exists purely for coding convenience, and should never be used by external code. - It simply allows MemoryPool and DynamicMemoryAllocator to share checkpoint-related - code in a seamless way. + This class exists purely for coding convenience, and should never be used by external code. + It simply allows MemoryPool and DynamicMemoryAllocator to share checkpoint-related + code in a seamless way. */ class Checkpointable { private: - BlockCheckpointInfo *m_firstCheckpointInfo; ///< head of the linked list of checkpoint infos for this pool/dma - Bool m_cpiEverFailed; ///< flag to detect if we ran out of memory accumulating checkpoint info. + BlockCheckpointInfo* m_firstCheckpointInfo; ///< head of the linked list of checkpoint infos for this pool/dma + Bool m_cpiEverFailed; ///< flag to detect if we ran out of memory accumulating checkpoint info. protected: - Checkpointable(); ~Checkpointable(); /// create a new checkpoint info and add it to the list. - BlockCheckpointInfo *debugAddCheckpointInfo( - const char *debugLiteralTagString, + BlockCheckpointInfo* debugAddCheckpointInfo( + const char* debugLiteralTagString, Int allocCheckpoint, - Int blockSize - ); + Int blockSize); public: /// dump a checkpoint report to logfile - void debugCheckpointReport(Int flags, Int startCheckpoint, Int endCheckpoint, const char *poolName); + void debugCheckpointReport(Int flags, Int startCheckpoint, Int endCheckpoint, const char* poolName); /// reset all the checkpoints for this pool/dma void debugResetCheckpoints(); }; -#endif + #endif // ---------------------------------------------------------------------------- /** - A MemoryPool provides a way to efficiently allocate objects of the same (or similar) - size. We allocate large a large chunk of memory (a "blob") and subdivide it into - even-size chunks, doling these out as needed. If the first blob gets full, we allocate - additional blobs as necessary. A given pool can allocate blocks of only one size; - if you need a different size, you should use a different pool. + A MemoryPool provides a way to efficiently allocate objects of the same (or similar) + size. We allocate large a large chunk of memory (a "blob") and subdivide it into + even-size chunks, doling these out as needed. If the first blob gets full, we allocate + additional blobs as necessary. A given pool can allocate blocks of only one size; + if you need a different size, you should use a different pool. */ class MemoryPool -#ifdef MEMORYPOOL_CHECKPOINTING + #ifdef MEMORYPOOL_CHECKPOINTING : public Checkpointable -#endif + #endif { private: - - MemoryPoolFactory *m_factory; ///< the factory that created us - MemoryPool *m_nextPoolInFactory; ///< linked list node, managed by factory - const char *m_poolName; ///< name of this pool. (literal string; must not be freed) - Int m_allocationSize; ///< size of the blocks allocated by this pool, in bytes - Int m_initialAllocationCount; ///< number of blocks to be allocated in initial blob - Int m_overflowAllocationCount; ///< number of blocks to be allocated in any subsequent blob(s) - Int m_usedBlocksInPool; ///< total number of blocks in use in the pool. - Int m_totalBlocksInPool; ///< total number of blocks in all blobs of this pool (used or not). - Int m_peakUsedBlocksInPool; ///< high-water mark of m_usedBlocksInPool - MemoryPoolBlob *m_firstBlob; ///< head of linked list: first blob for this pool. - MemoryPoolBlob *m_lastBlob; ///< tail of linked list: last blob for this pool. (needed for efficiency) - MemoryPoolBlob *m_firstBlobWithFreeBlocks; ///< first blob in this pool that has at least one unallocated block. + MemoryPoolFactory* m_factory; ///< the factory that created us + MemoryPool* m_nextPoolInFactory; ///< linked list node, managed by factory + const char* m_poolName; ///< name of this pool. (literal string; must not be freed) + Int m_allocationSize; ///< size of the blocks allocated by this pool, in bytes + Int m_initialAllocationCount; ///< number of blocks to be allocated in initial blob + Int m_overflowAllocationCount; ///< number of blocks to be allocated in any subsequent blob(s) + Int m_usedBlocksInPool; ///< total number of blocks in use in the pool. + Int m_totalBlocksInPool; ///< total number of blocks in all blobs of this pool (used or not). + Int m_peakUsedBlocksInPool; ///< high-water mark of m_usedBlocksInPool + MemoryPoolBlob* m_firstBlob; ///< head of linked list: first blob for this pool. + MemoryPoolBlob* m_lastBlob; ///< tail of linked list: last blob for this pool. (needed for efficiency) + MemoryPoolBlob* m_firstBlobWithFreeBlocks; ///< first blob in this pool that has at least one unallocated block. private: /// create a new blob with the given number of blocks. MemoryPoolBlob* createBlob(Int allocationCount); /// destroy a blob. - Int freeBlob(MemoryPoolBlob *blob); + Int freeBlob(MemoryPoolBlob* blob); public: - // 'public' funcs that are really only for use by MemoryPoolFactory - MemoryPool *getNextPoolInList(); ///< return next pool in linked list - void addToList(MemoryPool **pHead); ///< add this pool to head of the linked list - void removeFromList(MemoryPool **pHead); ///< remove this pool from the linked list + MemoryPool* getNextPoolInList(); ///< return next pool in linked list + void addToList(MemoryPool** pHead); ///< add this pool to head of the linked list + void removeFromList(MemoryPool** pHead); ///< remove this pool from the linked list #ifdef MEMORYPOOL_DEBUG - static void debugPoolInfoReport( MemoryPool *pool, FILE *fp = nullptr ); ///< dump a report about this pool to the logfile - const char *debugGetBlockTagString(void *pBlock); ///< return the tagstring for the given block (assumed to belong to this pool) - void debugMemoryVerifyPool(); ///< perform internal consistency check on this pool. - Int debugPoolReportLeaks( const char* owner ); + static void debugPoolInfoReport(MemoryPool* pool, FILE* fp = nullptr); ///< dump a report about this pool to the logfile + const char* debugGetBlockTagString(void* pBlock); ///< return the tagstring for the given block (assumed to belong to this pool) + void debugMemoryVerifyPool(); ///< perform internal consistency check on this pool. + Int debugPoolReportLeaks(const char* owner); #endif #ifdef MEMORYPOOL_CHECKPOINTING - void debugResetCheckpoints(); ///< throw away all checkpoint information for this pool. + void debugResetCheckpoints(); ///< throw away all checkpoint information for this pool. #endif public: - MemoryPool(); /// initialize the given memory pool. - void init(MemoryPoolFactory *factory, const char *poolName, Int allocationSize, Int initialAllocationCount, Int overflowAllocationCount); + void init(MemoryPoolFactory* factory, const char* poolName, Int allocationSize, Int initialAllocationCount, Int overflowAllocationCount); ~MemoryPool(); /// allocate a block from this pool. (don't call directly; use allocateBlock() macro) - void *allocateBlockImplementation(DECLARE_LITERALSTRING_ARG1); + void* allocateBlockImplementation(DECLARE_LITERALSTRING_ARG1); /// same as allocateBlockImplementation, but memory returned is not zeroed - void *allocateBlockDoNotZeroImplementation(DECLARE_LITERALSTRING_ARG1); + void* allocateBlockDoNotZeroImplementation(DECLARE_LITERALSTRING_ARG1); /// free the block. it is OK to pass null. - void freeBlock(void *pMem); + void freeBlock(void* pMem); /// return the factory that created (and thus owns) this pool. - MemoryPoolFactory *getOwningFactory(); + MemoryPoolFactory* getOwningFactory(); /// return the name of this pool. the result is a literal string and must not be freed. - const char *getPoolName(); + const char* getPoolName(); /// return the block allocation size of this pool. Int getAllocationSize(); @@ -381,81 +375,79 @@ class MemoryPool void reset(); #ifdef MEMORYPOOL_DEBUG - /// return true iff this block was allocated by this pool. - Bool debugIsBlockInPool(void *pBlock); + /// return true iff this block was allocated by this pool. + Bool debugIsBlockInPool(void* pBlock); #endif }; // ---------------------------------------------------------------------------- /** - The DynamicMemoryAllocator class is used to handle unpredictably-sized - allocation requests. It basically allocates a number of (private) MemoryPools, - then routes request to the smallest-size pool that will satisfy the request. - (Requests too large for any of the pool are routed to the system memory allocator.) - You should normally use this in place of malloc/free or (global) new/delete. + The DynamicMemoryAllocator class is used to handle unpredictably-sized + allocation requests. It basically allocates a number of (private) MemoryPools, + then routes request to the smallest-size pool that will satisfy the request. + (Requests too large for any of the pool are routed to the system memory allocator.) + You should normally use this in place of malloc/free or (global) new/delete. */ class DynamicMemoryAllocator -#ifdef MEMORYPOOL_CHECKPOINTING + #ifdef MEMORYPOOL_CHECKPOINTING : public Checkpointable -#endif + #endif { private: - MemoryPoolFactory *m_factory; ///< the factory that created us - DynamicMemoryAllocator *m_nextDmaInFactory; ///< linked list node, managed by factory - Int m_numPools; ///< number of subpools (up to MAX_DYNAMICMEMORYALLOCATOR_SUBPOOLS) - Int m_usedBlocksInDma; ///< total number of blocks allocated, from subpools and "raw" - MemoryPool *m_pools[MAX_DYNAMICMEMORYALLOCATOR_SUBPOOLS]; ///< the subpools - MemoryPoolSingleBlock *m_rawBlocks; ///< linked list of "raw" blocks allocated directly from system + MemoryPoolFactory* m_factory; ///< the factory that created us + DynamicMemoryAllocator* m_nextDmaInFactory; ///< linked list node, managed by factory + Int m_numPools; ///< number of subpools (up to MAX_DYNAMICMEMORYALLOCATOR_SUBPOOLS) + Int m_usedBlocksInDma; ///< total number of blocks allocated, from subpools and "raw" + MemoryPool* m_pools[MAX_DYNAMICMEMORYALLOCATOR_SUBPOOLS]; ///< the subpools + MemoryPoolSingleBlock* m_rawBlocks; ///< linked list of "raw" blocks allocated directly from system /// return the best pool for the given allocSize, or null if none are suitable - MemoryPool *findPoolForSize(Int allocSize); + MemoryPool* findPoolForSize(Int allocSize); public: - // 'public' funcs that are really only for use by MemoryPoolFactory - DynamicMemoryAllocator *getNextDmaInList(); ///< return next dma in linked list - void addToList(DynamicMemoryAllocator **pHead); ///< add this dma to the list - void removeFromList(DynamicMemoryAllocator **pHead); ///< remove this dma from the list + DynamicMemoryAllocator* getNextDmaInList(); ///< return next dma in linked list + void addToList(DynamicMemoryAllocator** pHead); ///< add this dma to the list + void removeFromList(DynamicMemoryAllocator** pHead); ///< remove this dma from the list #ifdef MEMORYPOOL_DEBUG - Int debugCalcRawBlockBytes(Int *numBlocks); ///< calculate the number of bytes in "raw" (non-subpool) blocks - void debugMemoryVerifyDma(); ///< perform internal consistency check - const char *debugGetBlockTagString(void *pBlock); ///< return the tagstring for the given block (assumed to belong to this dma) - void debugDmaInfoReport( FILE *fp = nullptr ); ///< dump a report about this pool to the logfile - Int debugDmaReportLeaks(); + Int debugCalcRawBlockBytes(Int* numBlocks); ///< calculate the number of bytes in "raw" (non-subpool) blocks + void debugMemoryVerifyDma(); ///< perform internal consistency check + const char* debugGetBlockTagString(void* pBlock); ///< return the tagstring for the given block (assumed to belong to this dma) + void debugDmaInfoReport(FILE* fp = nullptr); ///< dump a report about this pool to the logfile + Int debugDmaReportLeaks(); #endif #ifdef MEMORYPOOL_CHECKPOINTING - void debugResetCheckpoints(); ///< toss all checkpoint information + void debugResetCheckpoints(); ///< toss all checkpoint information #endif public: - DynamicMemoryAllocator(); /// initialize the dma. pass 0/null for numSubPool/parms to get some reasonable default subpools. - void init(MemoryPoolFactory *factory, Int numSubPools, const PoolInitRec pParms[]); + void init(MemoryPoolFactory* factory, Int numSubPools, const PoolInitRec pParms[]); ~DynamicMemoryAllocator(); /// allocate bytes from this pool. (don't call directly; use allocateBytes() macro) - void *allocateBytesImplementation(Int numBytes DECLARE_LITERALSTRING_ARG2); + void* allocateBytesImplementation(Int numBytes DECLARE_LITERALSTRING_ARG2); /// like allocateBytesImplementation, but zeroes the memory before returning - void *allocateBytesDoNotZeroImplementation(Int numBytes DECLARE_LITERALSTRING_ARG2); + void* allocateBytesDoNotZeroImplementation(Int numBytes DECLARE_LITERALSTRING_ARG2); -#ifdef MEMORYPOOL_DEBUG + #ifdef MEMORYPOOL_DEBUG void debugIgnoreLeaksForThisBlock(void* pBlockPtr); -#endif + #endif /// free the bytes. (assumes allocated by this dma.) void freeBytes(void* pMem); /** - return the actual number of bytes that would be allocated - if you tried to allocate the given size. (It will generally be slightly - larger than you request.) This lets you use extra space if you're gonna get it anyway... - The idea is that you will call this before doing a memory allocation, to see if - you got any extra "bonus" space. + return the actual number of bytes that would be allocated + if you tried to allocate the given size. (It will generally be slightly + larger than you request.) This lets you use extra space if you're gonna get it anyway... + The idea is that you will call this before doing a memory allocation, to see if + you got any extra "bonus" space. */ Int getActualAllocationSize(Int numBytes); @@ -467,298 +459,311 @@ class DynamicMemoryAllocator #ifdef MEMORYPOOL_DEBUG - /// return true iff this block was allocated by this dma - Bool debugIsBlockInDma(void *pBlock); + /// return true iff this block was allocated by this dma + Bool debugIsBlockInDma(void* pBlock); - /// return true iff the pool is a subpool of this dma - Bool debugIsPoolInDma(MemoryPool *pool); + /// return true iff the pool is a subpool of this dma + Bool debugIsPoolInDma(MemoryPool* pool); - #endif // MEMORYPOOL_DEBUG + #endif // MEMORYPOOL_DEBUG }; -// ---------------------------------------------------------------------------- -#ifdef MEMORYPOOL_DEBUG -enum { MAX_SPECIAL_USED = 256 }; -#endif + // ---------------------------------------------------------------------------- + #ifdef MEMORYPOOL_DEBUG +enum +{ + MAX_SPECIAL_USED = 256 +}; + #endif // ---------------------------------------------------------------------------- /** - The class that manages all the MemoryPools and DynamicMemoryAllocators. - Usually you will create exactly one of these (TheMemoryPoolFactory) - and use it for everything. + The class that manages all the MemoryPools and DynamicMemoryAllocators. + Usually you will create exactly one of these (TheMemoryPoolFactory) + and use it for everything. */ class MemoryPoolFactory { private: - MemoryPool *m_firstPoolInFactory; ///< linked list of pools - DynamicMemoryAllocator *m_firstDmaInFactory; ///< linked list of dmas -#ifdef MEMORYPOOL_CHECKPOINTING - Int m_curCheckpoint; ///< most recent checkpoint value -#endif -#ifdef MEMORYPOOL_DEBUG - Int m_usedBytes; ///< total bytes in use - Int m_physBytes; ///< total bytes allocated to all pools (includes unused blocks) - Int m_peakUsedBytes; ///< high-water mark of m_usedBytes - Int m_peakPhysBytes; ///< high-water mark of m_physBytes - Int m_usedBytesSpecial[MAX_SPECIAL_USED]; - Int m_usedBytesSpecialPeak[MAX_SPECIAL_USED]; - Int m_physBytesSpecial[MAX_SPECIAL_USED]; - Int m_physBytesSpecialPeak[MAX_SPECIAL_USED]; -#endif + MemoryPool* m_firstPoolInFactory; ///< linked list of pools + DynamicMemoryAllocator* m_firstDmaInFactory; ///< linked list of dmas + #ifdef MEMORYPOOL_CHECKPOINTING + Int m_curCheckpoint; ///< most recent checkpoint value + #endif + #ifdef MEMORYPOOL_DEBUG + Int m_usedBytes; ///< total bytes in use + Int m_physBytes; ///< total bytes allocated to all pools (includes unused blocks) + Int m_peakUsedBytes; ///< high-water mark of m_usedBytes + Int m_peakPhysBytes; ///< high-water mark of m_physBytes + Int m_usedBytesSpecial[MAX_SPECIAL_USED]; + Int m_usedBytesSpecialPeak[MAX_SPECIAL_USED]; + Int m_physBytesSpecial[MAX_SPECIAL_USED]; + Int m_physBytesSpecialPeak[MAX_SPECIAL_USED]; + #endif public: - - // 'public' funcs that are really only for use by MemoryPool and friends + // 'public' funcs that are really only for use by MemoryPool and friends #ifdef MEMORYPOOL_DEBUG - /// adjust the usedBytes and physBytes variables by the given amoun ts. - void adjustTotals(const char* tagString, Int usedDelta, Int physDelta); + /// adjust the usedBytes and physBytes variables by the given amoun ts. + void adjustTotals(const char* tagString, Int usedDelta, Int physDelta); #endif #ifdef MEMORYPOOL_CHECKPOINTING - /// return the current checkpoint value. - Int getCurCheckpoint() { return m_curCheckpoint; } + /// return the current checkpoint value. + Int getCurCheckpoint() { return m_curCheckpoint; } #endif public: - MemoryPoolFactory(); void init(); ~MemoryPoolFactory(); /// create a new memory pool with the given settings. if a pool with the given name already exists, return it. - MemoryPool *createMemoryPool(const PoolInitRec *parms); + MemoryPool* createMemoryPool(const PoolInitRec* parms); /// overloaded version of createMemoryPool with explicit parms. - MemoryPool *createMemoryPool(const char *poolName, Int allocationSize, Int initialAllocationCount, Int overflowAllocationCount); + MemoryPool* createMemoryPool(const char* poolName, Int allocationSize, Int initialAllocationCount, Int overflowAllocationCount); /// return the pool with the given name. if no such pool exists, return null. - MemoryPool *findMemoryPool(const char *poolName); + MemoryPool* findMemoryPool(const char* poolName); /// destroy the given pool. - void destroyMemoryPool(MemoryPool *pMemoryPool); + void destroyMemoryPool(MemoryPool* pMemoryPool); /// create a DynamicMemoryAllocator with subpools with the given parms. - DynamicMemoryAllocator *createDynamicMemoryAllocator(Int numSubPools, const PoolInitRec pParms[]); + DynamicMemoryAllocator* createDynamicMemoryAllocator(Int numSubPools, const PoolInitRec pParms[]); /// destroy the given DynamicMemoryAllocator. - void destroyDynamicMemoryAllocator(DynamicMemoryAllocator *dma); + void destroyDynamicMemoryAllocator(DynamicMemoryAllocator* dma); /// destroy the contents of all pools and dmas. (the pools and dma's are not destroyed, just reset) void reset(); - void memoryPoolUsageReport( const char* filename, FILE *appendToFileInstead = nullptr ); + void memoryPoolUsageReport(const char* filename, FILE* appendToFileInstead = nullptr); #ifdef MEMORYPOOL_DEBUG - /// perform internal consistency checking - void debugMemoryVerify(); + /// perform internal consistency checking + void debugMemoryVerify(); - /// return true iff the block was allocated by any pool or dma owned by this factory. - Bool debugIsBlockInAnyPool(void *pBlock); + /// return true iff the block was allocated by any pool or dma owned by this factory. + Bool debugIsBlockInAnyPool(void* pBlock); - /// return the tag string for the block. - const char *debugGetBlockTagString(void *pBlock); + /// return the tag string for the block. + const char* debugGetBlockTagString(void* pBlock); - /// dump a report with the given options to the logfile. - void debugMemoryReport(Int flags, Int startCheckpoint, Int endCheckpoint, FILE *fp = nullptr ); + /// dump a report with the given options to the logfile. + void debugMemoryReport(Int flags, Int startCheckpoint, Int endCheckpoint, FILE* fp = nullptr); - void debugSetInitFillerIndex(Int index); + void debugSetInitFillerIndex(Int index); #endif #ifdef MEMORYPOOL_CHECKPOINTING - /// set a new checkpoint. - Int debugSetCheckpoint(); + /// set a new checkpoint. + Int debugSetCheckpoint(); - /// reset all checkpoint information. - void debugResetCheckpoints(); + /// reset all checkpoint information. + void debugResetCheckpoints(); #endif }; -// how many bytes are we allowed to 'waste' per pool allocation before the debug code starts yelling at us... -#define MEMORY_POOL_OBJECT_ALLOCATION_SLOP 16 - -// ---------------------------------------------------------------------------- -#define GCMP_FIND(ARGCLASS, ARGPOOLNAME) \ -private: \ - static MemoryPool *getClassMemoryPool() \ - { \ - /* \ - Note that this static variable will be initialized exactly once: the first time \ - control flows over this section of code. This allows us to neatly resolve the \ - order-of-execution problem for static variables, ensuring this is not executed \ - prior to the initialization of TheMemoryPoolFactory. \ - */ \ - DEBUG_ASSERTCRASH(TheMemoryPoolFactory, ("TheMemoryPoolFactory is null")); \ - static MemoryPool *The##ARGCLASS##Pool = TheMemoryPoolFactory->findMemoryPool(ARGPOOLNAME); \ - DEBUG_ASSERTCRASH(The##ARGCLASS##Pool, ("Pool \"%s\" not found (did you set it up in initMemoryPools?)", ARGPOOLNAME)); \ - DEBUG_ASSERTCRASH(The##ARGCLASS##Pool->getAllocationSize() >= sizeof(ARGCLASS), ("Pool \"%s\" is too small for this class (currently %d, need %d)", ARGPOOLNAME, The##ARGCLASS##Pool->getAllocationSize(), sizeof(ARGCLASS))); \ - DEBUG_ASSERTCRASH(The##ARGCLASS##Pool->getAllocationSize() <= sizeof(ARGCLASS)+MEMORY_POOL_OBJECT_ALLOCATION_SLOP, ("Pool \"%s\" is too large for this class (currently %d, need %d)", ARGPOOLNAME, The##ARGCLASS##Pool->getAllocationSize(), sizeof(ARGCLASS))); \ - return The##ARGCLASS##Pool; \ - } - -// ---------------------------------------------------------------------------- -#define GCMP_CREATE(ARGCLASS, ARGPOOLNAME, ARGINITIAL, ARGOVERFLOW) \ -private: \ - static MemoryPool *getClassMemoryPool() \ - { \ - /* \ - Note that this static variable will be initialized exactly once: the first time \ - control flows over this section of code. This allows us to neatly resolve the \ - order-of-execution problem for static variables, ensuring this is not executed \ - prior to the initialization of TheMemoryPoolFactory. \ - */ \ - DEBUG_ASSERTCRASH(TheMemoryPoolFactory, ("TheMemoryPoolFactory is null")); \ - static MemoryPool *The##ARGCLASS##Pool = TheMemoryPoolFactory->createMemoryPool(ARGPOOLNAME, sizeof(ARGCLASS), ARGINITIAL, ARGOVERFLOW); \ - DEBUG_ASSERTCRASH(The##ARGCLASS##Pool, ("Pool \"%s\" not found (did you set it up in initMemoryPools?)", ARGPOOLNAME)); \ - DEBUG_ASSERTCRASH(The##ARGCLASS##Pool->getAllocationSize() >= sizeof(ARGCLASS), ("Pool \"%s\" is too small for this class (currently %d, need %d)", ARGPOOLNAME, The##ARGCLASS##Pool->getAllocationSize(), sizeof(ARGCLASS))); \ - DEBUG_ASSERTCRASH(The##ARGCLASS##Pool->getAllocationSize() <= sizeof(ARGCLASS)+MEMORY_POOL_OBJECT_ALLOCATION_SLOP, ("Pool \"%s\" is too large for this class (currently %d, need %d)", ARGPOOLNAME, The##ARGCLASS##Pool->getAllocationSize(), sizeof(ARGCLASS))); \ - return The##ARGCLASS##Pool; \ - } - -// ---------------------------------------------------------------------------- -#define MEMORY_POOL_GLUE_WITHOUT_GCMP(ARGCLASS) \ -protected: \ - virtual ~ARGCLASS(); \ -public: \ - enum ARGCLASS##MagicEnum { ARGCLASS##_GLUE_NOT_IMPLEMENTED = 0 }; \ -public: \ - inline void *operator new(size_t s, ARGCLASS##MagicEnum e DECLARE_LITERALSTRING_ARG2) \ - { \ - DEBUG_ASSERTCRASH(s == sizeof(ARGCLASS), ("The wrong operator new is being called; ensure all objects in the hierarchy have MemoryPoolGlue set up correctly")); \ - return ARGCLASS::getClassMemoryPool()->allocateBlockImplementation(PASS_LITERALSTRING_ARG1); \ - } \ -public: \ - /* \ - Note that this delete operator can't be called directly; it is called \ - only if the analogous new operator is called, AND the constructor \ - throws an exception... \ - */ \ - inline void operator delete(void *p, ARGCLASS##MagicEnum e DECLARE_LITERALSTRING_ARG2) \ - { \ - ARGCLASS::getClassMemoryPool()->freeBlock(p); \ - } \ -protected: \ - /* \ - Make normal new and delete protected, so they can't be called by the outside world. \ - Note that delete is funny, in that it can still be called by the class itself; \ - this is safe but not recommended, for consistency purposes. More problematically, \ - it can be called by another class that has declared itself 'friend' to us. \ - In theory, this shouldn't work, since it may not use the right operator-delete, \ - and thus the wrong memory pool; in practice, it seems the right delete IS called \ - in MSVC -- it seems to make operator delete virtual if the destructor is also virtual. \ - At any rate, this is undocumented behavior as far as I can tell, so we put a big old \ - crash into operator delete telling people to do the right thing and call deleteInstance \ - instead -- it'd be nice if we could catch this at compile time, but catching it at \ - runtime seems to be the best we can do... \ - */ \ - inline void *operator new(size_t s) \ - { \ - DEBUG_CRASH(("This operator new should normally never be called... please use new(char*) instead.")); \ - DEBUG_ASSERTCRASH(s == sizeof(ARGCLASS), ("The wrong operator new is being called; ensure all objects in the hierarchy have MemoryPoolGlue set up correctly")); \ - throw ERROR_BUG; \ - return 0; \ - } \ - inline void operator delete(void *p) \ - { \ - DEBUG_CRASH(("Please call deleteInstance instead of delete.")); \ - ARGCLASS::getClassMemoryPool()->freeBlock(p); \ - } \ -private: \ - virtual MemoryPool *getObjectMemoryPool() \ - { \ - return ARGCLASS::getClassMemoryPool(); \ - } \ -public: /* include this line at the end to reset visibility to 'public' */ - -// ---------------------------------------------------------------------------- -#define MEMORY_POOL_GLUE(ARGCLASS, ARGPOOLNAME) \ - MEMORY_POOL_GLUE_WITHOUT_GCMP(ARGCLASS) \ - GCMP_FIND(ARGCLASS, ARGPOOLNAME) - -// ---------------------------------------------------------------------------- -#define MEMORY_POOL_GLUE_WITH_EXPLICIT_CREATE(ARGCLASS, ARGPOOLNAME, ARGINITIAL, ARGOVERFLOW) \ - MEMORY_POOL_GLUE_WITHOUT_GCMP(ARGCLASS) \ - GCMP_CREATE(ARGCLASS, ARGPOOLNAME, ARGINITIAL, ARGOVERFLOW) - -// ---------------------------------------------------------------------------- -#define MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ARGCLASS, ARGPOOLNAME) \ - MEMORY_POOL_GLUE_WITHOUT_GCMP(ARGCLASS) \ - GCMP_CREATE(ARGCLASS, ARGPOOLNAME, -1, -1) + // how many bytes are we allowed to 'waste' per pool allocation before the debug code starts yelling at us... + #define MEMORY_POOL_OBJECT_ALLOCATION_SLOP 16 + + // ---------------------------------------------------------------------------- + #define GCMP_FIND(ARGCLASS, ARGPOOLNAME) \ + private: \ + static MemoryPool* getClassMemoryPool() \ + { \ + /* \ + Note that this static variable will be initialized exactly once: the first time \ + control flows over this section of code. This allows us to neatly resolve the \ + order-of-execution problem for static variables, ensuring this is not executed \ + prior to the initialization of TheMemoryPoolFactory. \ + */ \ + DEBUG_ASSERTCRASH(TheMemoryPoolFactory, ("TheMemoryPoolFactory is null")); \ + static MemoryPool* The##ARGCLASS##Pool = TheMemoryPoolFactory->findMemoryPool(ARGPOOLNAME); \ + DEBUG_ASSERTCRASH(The##ARGCLASS##Pool, ("Pool \"%s\" not found (did you set it up in initMemoryPools?)", ARGPOOLNAME)); \ + DEBUG_ASSERTCRASH(The##ARGCLASS##Pool->getAllocationSize() >= sizeof(ARGCLASS), ("Pool \"%s\" is too small for this class (currently %d, need %d)", ARGPOOLNAME, The##ARGCLASS##Pool->getAllocationSize(), sizeof(ARGCLASS))); \ + DEBUG_ASSERTCRASH(The##ARGCLASS##Pool->getAllocationSize() <= sizeof(ARGCLASS) + MEMORY_POOL_OBJECT_ALLOCATION_SLOP, ("Pool \"%s\" is too large for this class (currently %d, need %d)", ARGPOOLNAME, The##ARGCLASS##Pool->getAllocationSize(), sizeof(ARGCLASS))); \ + return The##ARGCLASS##Pool; \ + } -// ---------------------------------------------------------------------------- -// this is the version for an Abstract Base Class, which will never be instantiated... -#define MEMORY_POOL_GLUE_ABC(ARGCLASS) \ -protected: \ - virtual ~ARGCLASS(); \ -public: \ - enum ARGCLASS##MagicEnum { ARGCLASS##_GLUE_NOT_IMPLEMENTED = 0 }; \ -protected: \ - inline void *operator new(size_t s, ARGCLASS##MagicEnum e DECLARE_LITERALSTRING_ARG2) \ - { \ - DEBUG_CRASH(("this should be impossible to call (abstract base class)")); \ - DEBUG_ASSERTCRASH(s == sizeof(ARGCLASS), ("The wrong operator new is being called; ensure all objects in the hierarchy have MemoryPoolGlue set up correctly")); \ - throw ERROR_BUG; \ - return 0; \ - } \ -protected: \ - inline void operator delete(void *p, ARGCLASS##MagicEnum e DECLARE_LITERALSTRING_ARG2) \ - { \ - DEBUG_CRASH(("this should be impossible to call (abstract base class)")); \ - } \ -protected: \ - inline void *operator new(size_t s) \ - { \ - DEBUG_CRASH(("this should be impossible to call (abstract base class)")); \ - DEBUG_ASSERTCRASH(s == sizeof(ARGCLASS), ("The wrong operator new is being called; ensure all objects in the hierarchy have MemoryPoolGlue set up correctly")); \ - throw ERROR_BUG; \ - return 0; \ - } \ - inline void operator delete(void *p) \ - { \ - DEBUG_CRASH(("this should be impossible to call (abstract base class)")); \ - } \ -private: \ - virtual MemoryPool *getObjectMemoryPool() \ - { \ - throw ERROR_BUG; \ - return 0; \ - } \ -public: /* include this line at the end to reset visibility to 'public' */ + // ---------------------------------------------------------------------------- + #define GCMP_CREATE(ARGCLASS, ARGPOOLNAME, ARGINITIAL, ARGOVERFLOW) \ + private: \ + static MemoryPool* getClassMemoryPool() \ + { \ + /* \ + Note that this static variable will be initialized exactly once: the first time \ + control flows over this section of code. This allows us to neatly resolve the \ + order-of-execution problem for static variables, ensuring this is not executed \ + prior to the initialization of TheMemoryPoolFactory. \ + */ \ + DEBUG_ASSERTCRASH(TheMemoryPoolFactory, ("TheMemoryPoolFactory is null")); \ + static MemoryPool* The##ARGCLASS##Pool = TheMemoryPoolFactory->createMemoryPool(ARGPOOLNAME, sizeof(ARGCLASS), ARGINITIAL, ARGOVERFLOW); \ + DEBUG_ASSERTCRASH(The##ARGCLASS##Pool, ("Pool \"%s\" not found (did you set it up in initMemoryPools?)", ARGPOOLNAME)); \ + DEBUG_ASSERTCRASH(The##ARGCLASS##Pool->getAllocationSize() >= sizeof(ARGCLASS), ("Pool \"%s\" is too small for this class (currently %d, need %d)", ARGPOOLNAME, The##ARGCLASS##Pool->getAllocationSize(), sizeof(ARGCLASS))); \ + DEBUG_ASSERTCRASH(The##ARGCLASS##Pool->getAllocationSize() <= sizeof(ARGCLASS) + MEMORY_POOL_OBJECT_ALLOCATION_SLOP, ("Pool \"%s\" is too large for this class (currently %d, need %d)", ARGPOOLNAME, The##ARGCLASS##Pool->getAllocationSize(), sizeof(ARGCLASS))); \ + return The##ARGCLASS##Pool; \ + } + // ---------------------------------------------------------------------------- + #define MEMORY_POOL_GLUE_WITHOUT_GCMP(ARGCLASS) \ + protected: \ + virtual ~ARGCLASS(); \ + \ + public: \ + enum ARGCLASS##MagicEnum{ARGCLASS##_GLUE_NOT_IMPLEMENTED = 0}; \ + \ + public: \ + inline void* operator new(size_t s, ARGCLASS##MagicEnum e DECLARE_LITERALSTRING_ARG2) \ + { \ + DEBUG_ASSERTCRASH(s == sizeof(ARGCLASS), ("The wrong operator new is being called; ensure all objects in the hierarchy have MemoryPoolGlue set up correctly")); \ + return ARGCLASS::getClassMemoryPool()->allocateBlockImplementation(PASS_LITERALSTRING_ARG1); \ + } \ + \ + public: \ + /* \ + Note that this delete operator can't be called directly; it is called \ + only if the analogous new operator is called, AND the constructor \ + throws an exception... \ + */ \ + inline void operator delete(void* p, ARGCLASS##MagicEnum e DECLARE_LITERALSTRING_ARG2) \ + { \ + ARGCLASS::getClassMemoryPool()->freeBlock(p); \ + } \ + \ + protected: \ + /* \ + Make normal new and delete protected, so they can't be called by the outside world. \ + Note that delete is funny, in that it can still be called by the class itself; \ + this is safe but not recommended, for consistency purposes. More problematically, \ + it can be called by another class that has declared itself 'friend' to us. \ + In theory, this shouldn't work, since it may not use the right operator-delete, \ + and thus the wrong memory pool; in practice, it seems the right delete IS called \ + in MSVC -- it seems to make operator delete virtual if the destructor is also virtual. \ + At any rate, this is undocumented behavior as far as I can tell, so we put a big old \ + crash into operator delete telling people to do the right thing and call deleteInstance \ + instead -- it'd be nice if we could catch this at compile time, but catching it at \ + runtime seems to be the best we can do... \ + */ \ + inline void* operator new(size_t s) \ + { \ + DEBUG_CRASH(("This operator new should normally never be called... please use new(char*) instead.")); \ + DEBUG_ASSERTCRASH(s == sizeof(ARGCLASS), ("The wrong operator new is being called; ensure all objects in the hierarchy have MemoryPoolGlue set up correctly")); \ + throw ERROR_BUG; \ + return 0; \ + } \ + inline void operator delete(void* p) \ + { \ + DEBUG_CRASH(("Please call deleteInstance instead of delete.")); \ + ARGCLASS::getClassMemoryPool()->freeBlock(p); \ + } \ + \ + private: \ + virtual MemoryPool* getObjectMemoryPool() \ + { \ + return ARGCLASS::getClassMemoryPool(); \ + } \ + \ + public: /* include this line at the end to reset visibility to 'public' */ + + // ---------------------------------------------------------------------------- + #define MEMORY_POOL_GLUE(ARGCLASS, ARGPOOLNAME) \ + MEMORY_POOL_GLUE_WITHOUT_GCMP(ARGCLASS) \ + GCMP_FIND(ARGCLASS, ARGPOOLNAME) + + // ---------------------------------------------------------------------------- + #define MEMORY_POOL_GLUE_WITH_EXPLICIT_CREATE(ARGCLASS, ARGPOOLNAME, ARGINITIAL, ARGOVERFLOW) \ + MEMORY_POOL_GLUE_WITHOUT_GCMP(ARGCLASS) \ + GCMP_CREATE(ARGCLASS, ARGPOOLNAME, ARGINITIAL, ARGOVERFLOW) + + // ---------------------------------------------------------------------------- + #define MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ARGCLASS, ARGPOOLNAME) \ + MEMORY_POOL_GLUE_WITHOUT_GCMP(ARGCLASS) \ + GCMP_CREATE(ARGCLASS, ARGPOOLNAME, -1, -1) + + // ---------------------------------------------------------------------------- + // this is the version for an Abstract Base Class, which will never be instantiated... + #define MEMORY_POOL_GLUE_ABC(ARGCLASS) \ + protected: \ + virtual ~ARGCLASS(); \ + \ + public: \ + enum ARGCLASS##MagicEnum{ARGCLASS##_GLUE_NOT_IMPLEMENTED = 0}; \ + \ + protected: \ + inline void* operator new(size_t s, ARGCLASS##MagicEnum e DECLARE_LITERALSTRING_ARG2) \ + { \ + DEBUG_CRASH(("this should be impossible to call (abstract base class)")); \ + DEBUG_ASSERTCRASH(s == sizeof(ARGCLASS), ("The wrong operator new is being called; ensure all objects in the hierarchy have MemoryPoolGlue set up correctly")); \ + throw ERROR_BUG; \ + return 0; \ + } \ + \ + protected: \ + inline void operator delete(void* p, ARGCLASS##MagicEnum e DECLARE_LITERALSTRING_ARG2) \ + { \ + DEBUG_CRASH(("this should be impossible to call (abstract base class)")); \ + } \ + \ + protected: \ + inline void* operator new(size_t s) \ + { \ + DEBUG_CRASH(("this should be impossible to call (abstract base class)")); \ + DEBUG_ASSERTCRASH(s == sizeof(ARGCLASS), ("The wrong operator new is being called; ensure all objects in the hierarchy have MemoryPoolGlue set up correctly")); \ + throw ERROR_BUG; \ + return 0; \ + } \ + inline void operator delete(void* p) \ + { \ + DEBUG_CRASH(("this should be impossible to call (abstract base class)")); \ + } \ + \ + private: \ + virtual MemoryPool* getObjectMemoryPool() \ + { \ + throw ERROR_BUG; \ + return 0; \ + } \ + \ + public: /* include this line at the end to reset visibility to 'public' */ // ---------------------------------------------------------------------------- /** - This class is provided as a simple and safe way to integrate C++ object allocation - into MemoryPool usage. To use it, you must have your class inherit from - MemoryPoolObject, then put the macro MEMORY_POOL_GLUE(MyClassName, "MyPoolName") - at the start of your class definition. (This does not create the pool itself -- you - must create that manually using MemoryPoolFactory::createMemoryPool) + This class is provided as a simple and safe way to integrate C++ object allocation + into MemoryPool usage. To use it, you must have your class inherit from + MemoryPoolObject, then put the macro MEMORY_POOL_GLUE(MyClassName, "MyPoolName") + at the start of your class definition. (This does not create the pool itself -- you + must create that manually using MemoryPoolFactory::createMemoryPool) */ class MemoryPoolObject { protected: - /** ensure that all destructors are virtual */ - virtual ~MemoryPoolObject() { } + virtual ~MemoryPoolObject() {} protected: - void *operator new(size_t s) { DEBUG_CRASH(("This should be impossible")); return 0; } - void operator delete(void *p) { DEBUG_CRASH(("This should be impossible")); } + void* operator new(size_t s) + { + DEBUG_CRASH(("This should be impossible")); + return 0; + } + void operator delete(void* p) { DEBUG_CRASH(("This should be impossible")); } protected: - - virtual MemoryPool *getObjectMemoryPool() = 0; + virtual MemoryPool* getObjectMemoryPool() = 0; public: - static void deleteInstanceInternal(MemoryPoolObject* mpo) { if (mpo) { - MemoryPool *pool = mpo->getObjectMemoryPool(); // save this, since the dtor will nuke our vtbl - mpo->~MemoryPoolObject(); // it's virtual, so the right one will be called. - pool->freeBlock((void *)mpo); + MemoryPool* pool = mpo->getObjectMemoryPool(); // save this, since the dtor will nuke our vtbl + mpo->~MemoryPoolObject(); // it's virtual, so the right one will be called. + pool->freeBlock((void*)mpo); } } }; @@ -768,13 +773,12 @@ inline void deleteInstance(MemoryPoolObject* mpo) MemoryPoolObject::deleteInstanceInternal(mpo); } - // INLINING /////////////////////////////////////////////////////////////////// // ---------------------------------------------------------------------------- -inline MemoryPoolFactory *MemoryPool::getOwningFactory() { return m_factory; } -inline MemoryPool *MemoryPool::getNextPoolInList() { return m_nextPoolInFactory; } -inline const char *MemoryPool::getPoolName() { return m_poolName; } +inline MemoryPoolFactory* MemoryPool::getOwningFactory() { return m_factory; } +inline MemoryPool* MemoryPool::getNextPoolInList() { return m_nextPoolInFactory; } +inline const char* MemoryPool::getPoolName() { return m_poolName; } inline Int MemoryPool::getAllocationSize() { return m_allocationSize; } inline Int MemoryPool::getFreeBlockCount() { return getTotalBlockCount() - getUsedBlockCount(); } inline Int MemoryPool::getUsedBlockCount() { return m_usedBlocksInPool; } @@ -783,105 +787,105 @@ inline Int MemoryPool::getPeakBlockCount() { return m_peakUsedBlocksInPool; } inline Int MemoryPool::getInitialBlockCount() { return m_initialAllocationCount; } // ---------------------------------------------------------------------------- -inline DynamicMemoryAllocator *DynamicMemoryAllocator::getNextDmaInList() { return m_nextDmaInFactory; } +inline DynamicMemoryAllocator* DynamicMemoryAllocator::getNextDmaInList() { return m_nextDmaInFactory; } // EXTERNALS ////////////////////////////////////////////////////////////////// /** - Initialize the memory manager. Construct a new MemoryPoolFactory and - DynamicMemoryAllocator and store 'em in the singletons of the relevant - names. + Initialize the memory manager. Construct a new MemoryPoolFactory and + DynamicMemoryAllocator and store 'em in the singletons of the relevant + names. */ extern void initMemoryManager(); /** - return true if initMemoryManager() has been called. - return false if only preMainInitMemoryManager() has been called. + return true if initMemoryManager() has been called. + return false if only preMainInitMemoryManager() has been called. */ extern Bool isMemoryManagerOfficiallyInited(); /** - similar to initMemoryManager, but this should be used if the memory manager must be initialized - prior to main() (e.g., from a static constructor). If preMainInitMemoryManager() is called prior - to initMemoryManager(), then subsequent calls to either are quietly ignored, AS IS any subsequent - call to shutdownMemoryManager() [since there's no safe way to ensure that shutdownMemoryManager - will execute after all static destructors]. + similar to initMemoryManager, but this should be used if the memory manager must be initialized + prior to main() (e.g., from a static constructor). If preMainInitMemoryManager() is called prior + to initMemoryManager(), then subsequent calls to either are quietly ignored, AS IS any subsequent + call to shutdownMemoryManager() [since there's no safe way to ensure that shutdownMemoryManager + will execute after all static destructors]. - (Note: this function is actually not externally visible, but is documented here for clarity.) + (Note: this function is actually not externally visible, but is documented here for clarity.) */ /* extern void preMainInitMemoryManager(); */ /** - Shut down the memory manager. Throw away TheMemoryPoolFactory and - TheDynamicMemoryAllocator. + Shut down the memory manager. Throw away TheMemoryPoolFactory and + TheDynamicMemoryAllocator. */ extern void shutdownMemoryManager(); -extern MemoryPoolFactory *TheMemoryPoolFactory; -extern DynamicMemoryAllocator *TheDynamicMemoryAllocator; +extern MemoryPoolFactory* TheMemoryPoolFactory; +extern DynamicMemoryAllocator* TheDynamicMemoryAllocator; /** - This function is declared in this header, but is not defined anywhere -- you must provide - it in your code. It is called by initMemoryManager() or preMainInitMemoryManager() in order - to get the specifics of the subpool for the dynamic memory allocator. (If you just want - some defaults, set both return arguments to zero.) The reason for this odd setup is that - we may need to init the memory manager prior to main() [due to static C++ ctors] and - this allows us a way to get the necessary parameters. + This function is declared in this header, but is not defined anywhere -- you must provide + it in your code. It is called by initMemoryManager() or preMainInitMemoryManager() in order + to get the specifics of the subpool for the dynamic memory allocator. (If you just want + some defaults, set both return arguments to zero.) The reason for this odd setup is that + we may need to init the memory manager prior to main() [due to static C++ ctors] and + this allows us a way to get the necessary parameters. */ -extern void userMemoryManagerGetDmaParms(Int *numSubPools, const PoolInitRec **pParms); +extern void userMemoryManagerGetDmaParms(Int* numSubPools, const PoolInitRec** pParms); /** - This function is declared in this header, but is not defined anywhere -- you must provide - it in your code. It is called by initMemoryManager() or preMainInitMemoryManager() in order - to initialize the pools to be used. (You can define an empty function if you like.) + This function is declared in this header, but is not defined anywhere -- you must provide + it in your code. It is called by initMemoryManager() or preMainInitMemoryManager() in order + to initialize the pools to be used. (You can define an empty function if you like.) */ extern void userMemoryManagerInitPools(); /** - This function is declared in this header, but is not defined anywhere -- you must provide - it in your code. It is called by createMemoryPool to adjust the allocation size(s) for a - given pool. Note that the counts are in-out parms! + This function is declared in this header, but is not defined anywhere -- you must provide + it in your code. It is called by createMemoryPool to adjust the allocation size(s) for a + given pool. Note that the counts are in-out parms! */ -extern void userMemoryAdjustPoolSize(const char *poolName, Int& initialAllocationCount, Int& overflowAllocationCount); +extern void userMemoryAdjustPoolSize(const char* poolName, Int& initialAllocationCount, Int& overflowAllocationCount); -#ifdef __cplusplus + #ifdef __cplusplus -#ifndef _OPERATOR_NEW_DEFINED_ + #ifndef _OPERATOR_NEW_DEFINED_ - #define _OPERATOR_NEW_DEFINED_ + #define _OPERATOR_NEW_DEFINED_ - extern void * __cdecl operator new (size_t size); - extern void __cdecl operator delete (void *p); +extern void* __cdecl operator new(size_t size); +extern void __cdecl operator delete(void* p); - extern void * __cdecl operator new[] (size_t size); - extern void __cdecl operator delete[] (void *p); +extern void* __cdecl operator new[](size_t size); +extern void __cdecl operator delete[](void* p); - // additional overloads to account for VC/MFC funky versions - extern void* __cdecl operator new(size_t nSize, const char *, int); - extern void __cdecl operator delete(void *, const char *, int); +// additional overloads to account for VC/MFC funky versions +extern void* __cdecl operator new(size_t nSize, const char*, int); +extern void __cdecl operator delete(void*, const char*, int); - extern void* __cdecl operator new[](size_t nSize, const char *, int); - extern void __cdecl operator delete[](void *, const char *, int); +extern void* __cdecl operator new[](size_t nSize, const char*, int); +extern void __cdecl operator delete[](void*, const char*, int); -#if defined(_MSC_VER) && _MSC_VER < 1300 - // additional overloads for 'placement new' - //inline void* __cdecl operator new (size_t s, void *p) { return p; } - //inline void __cdecl operator delete (void *, void *p) { } - inline void* __cdecl operator new[] (size_t s, void *p) { return p; } - inline void __cdecl operator delete[] (void *, void *p) { } -#endif + #if defined(_MSC_VER) && _MSC_VER < 1300 +// additional overloads for 'placement new' +// inline void* __cdecl operator new (size_t s, void *p) { return p; } +// inline void __cdecl operator delete (void *, void *p) { } +inline void* __cdecl operator new[](size_t s, void* p) { return p; } +inline void __cdecl operator delete[](void*, void* p) {} + #endif -#endif + #endif -#ifdef MEMORYPOOL_DEBUG_CUSTOM_NEW - #define MSGNEW(MSG) new(MSG, 0) - #define NEW new(__FILE__, __LINE__) -#else - #define MSGNEW(MSG) new - #define NEW new -#endif + #ifdef MEMORYPOOL_DEBUG_CUSTOM_NEW + #define MSGNEW(MSG) new (MSG, 0) + #define NEW new (__FILE__, __LINE__) + #else + #define MSGNEW(MSG) new + #define NEW new + #endif -#endif + #endif class STLSpecialAlloc { @@ -890,23 +894,29 @@ class STLSpecialAlloc static void deallocate(void* __p, size_t); }; -#endif // DISABLE_GAMEMEMORY - +#endif // DISABLE_GAMEMEMORY /** - A simple utility class to ensure exception safety; this holds a MemoryPoolObject - and deletes it in its destructor. Especially useful for iterators! + A simple utility class to ensure exception safety; this holds a MemoryPoolObject + and deletes it in its destructor. Especially useful for iterators! */ class MemoryPoolObjectHolder { private: - MemoryPoolObject *m_mpo; + MemoryPoolObject* m_mpo; + public: - MemoryPoolObjectHolder(MemoryPoolObject *mpo = nullptr) : m_mpo(mpo) { } - void hold(MemoryPoolObject *mpo) { DEBUG_ASSERTCRASH(!m_mpo, ("already holding")); m_mpo = mpo; } + MemoryPoolObjectHolder(MemoryPoolObject* mpo = nullptr) + : m_mpo(mpo) + {} + void hold(MemoryPoolObject* mpo) + { + DEBUG_ASSERTCRASH(!m_mpo, ("already holding")); + m_mpo = mpo; + } void release() { m_mpo = nullptr; } ~MemoryPoolObjectHolder() { deleteInstance(m_mpo); } }; - -#define EMPTY_DTOR(CLASS) inline CLASS::~CLASS() { } +#define EMPTY_DTOR(CLASS) \ + inline CLASS::~CLASS() {} diff --git a/Core/GameEngine/Include/Common/GameMemoryNull.h b/Core/GameEngine/Include/Common/GameMemoryNull.h index 263f7a1dcb9..c02b0455bc2 100644 --- a/Core/GameEngine/Include/Common/GameMemoryNull.h +++ b/Core/GameEngine/Include/Common/GameMemoryNull.h @@ -18,27 +18,25 @@ #pragma once -#define allocateBytes(ARGCOUNT,ARGLITERAL) allocateBytesImplementation(ARGCOUNT) -#define allocateBytesDoNotZero(ARGCOUNT,ARGLITERAL) allocateBytesDoNotZeroImplementation(ARGCOUNT) -#define newInstanceDesc(ARGCLASS,ARGLITERAL) new ARGCLASS -#define newInstance(ARGCLASS) new ARGCLASS -#define MSGNEW(MSG) new -#define NEW new - +#define allocateBytes(ARGCOUNT, ARGLITERAL) allocateBytesImplementation(ARGCOUNT) +#define allocateBytesDoNotZero(ARGCOUNT, ARGLITERAL) allocateBytesDoNotZeroImplementation(ARGCOUNT) +#define newInstanceDesc(ARGCLASS, ARGLITERAL) new ARGCLASS +#define newInstance(ARGCLASS) new ARGCLASS +#define MSGNEW(MSG) new +#define NEW new /** - The DynamicMemoryAllocator class is used to handle unpredictably-sized - allocation requests. + The DynamicMemoryAllocator class is used to handle unpredictably-sized + allocation requests. */ class DynamicMemoryAllocator { public: - /// allocate bytes from this pool. (don't call directly; use allocateBytes() macro) - void *allocateBytesImplementation(Int numBytes); + void* allocateBytesImplementation(Int numBytes); /// like allocateBytesImplementation, but zeroes the memory before returning - void *allocateBytesDoNotZeroImplementation(Int numBytes); + void* allocateBytesDoNotZeroImplementation(Int numBytes); #ifdef MEMORYPOOL_DEBUG void debugIgnoreLeaksForThisBlock(void* pBlockPtr); @@ -48,66 +46,60 @@ class DynamicMemoryAllocator void freeBytes(void* pMem); /** - return the actual number of bytes that would be allocated - if you tried to allocate the given size. + return the actual number of bytes that would be allocated + if you tried to allocate the given size. */ Int getActualAllocationSize(Int numBytes); }; - /** - The class that manages all the MemoryPools and DynamicMemoryAllocators. - Usually you will create exactly one of these (TheMemoryPoolFactory) - and use it for everything. + The class that manages all the MemoryPools and DynamicMemoryAllocators. + Usually you will create exactly one of these (TheMemoryPoolFactory) + and use it for everything. */ class MemoryPoolFactory { public: - - void memoryPoolUsageReport( const char* filename, FILE *appendToFileInstead = nullptr ); + void memoryPoolUsageReport(const char* filename, FILE* appendToFileInstead = nullptr); #ifdef MEMORYPOOL_DEBUG - void debugMemoryReport(Int flags, Int startCheckpoint, Int endCheckpoint, FILE *fp = nullptr ); + void debugMemoryReport(Int flags, Int startCheckpoint, Int endCheckpoint, FILE* fp = nullptr); void debugSetInitFillerIndex(Int index); #endif }; - #define MEMORY_POOL_GLUE_WITHOUT_GCMP(ARGCLASS) \ -protected: \ - virtual ~ARGCLASS(); \ +protected: \ + virtual ~ARGCLASS(); \ + \ public: /* include this line at the end to reset visibility to 'public' */ - #define MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(ARGCLASS, ARGPOOLNAME) \ MEMORY_POOL_GLUE_WITHOUT_GCMP(ARGCLASS) - // this is the version for an Abstract Base Class, which will never be instantiated... #define MEMORY_POOL_GLUE_ABC(ARGCLASS) \ -protected: \ - virtual ~ARGCLASS(); \ +protected: \ + virtual ~ARGCLASS(); \ + \ public: /* include this line at the end to reset visibility to 'public' */ - /** - This class is provided as a simple and safe way to integrate C++ object allocation - into MemoryPool usage. To use it, you must have your class inherit from - MemoryPoolObject, then put the macro MEMORY_POOL_GLUE(MyClassName, "MyPoolName") - at the start of your class definition. (This does not create the pool itself -- you - must create that manually using MemoryPoolFactory::createMemoryPool) + This class is provided as a simple and safe way to integrate C++ object allocation + into MemoryPool usage. To use it, you must have your class inherit from + MemoryPoolObject, then put the macro MEMORY_POOL_GLUE(MyClassName, "MyPoolName") + at the start of your class definition. (This does not create the pool itself -- you + must create that manually using MemoryPoolFactory::createMemoryPool) */ class MemoryPoolObject { protected: - /** ensure that all destructors are virtual */ - virtual ~MemoryPoolObject() { } + virtual ~MemoryPoolObject() {} public: - static void deleteInstanceInternal(MemoryPoolObject* mpo) { delete mpo; @@ -119,29 +111,27 @@ inline void deleteInstance(MemoryPoolObject* mpo) MemoryPoolObject::deleteInstanceInternal(mpo); } - /** - Initialize the memory manager. Construct a new MemoryPoolFactory and - DynamicMemoryAllocator and store 'em in the singletons of the relevant - names. + Initialize the memory manager. Construct a new MemoryPoolFactory and + DynamicMemoryAllocator and store 'em in the singletons of the relevant + names. */ extern void initMemoryManager(); /** - return true if initMemoryManager() has been called. - return false if only preMainInitMemoryManager() has been called. + return true if initMemoryManager() has been called. + return false if only preMainInitMemoryManager() has been called. */ extern Bool isMemoryManagerOfficiallyInited(); /** - Shut down the memory manager. Throw away TheMemoryPoolFactory and - TheDynamicMemoryAllocator. + Shut down the memory manager. Throw away TheMemoryPoolFactory and + TheDynamicMemoryAllocator. */ extern void shutdownMemoryManager(); -extern MemoryPoolFactory *TheMemoryPoolFactory; -extern DynamicMemoryAllocator *TheDynamicMemoryAllocator; - +extern MemoryPoolFactory* TheMemoryPoolFactory; +extern DynamicMemoryAllocator* TheDynamicMemoryAllocator; // TheSuperHackers @info // The new operator overloads will zero all memory after allocation. @@ -149,18 +139,18 @@ extern DynamicMemoryAllocator *TheDynamicMemoryAllocator; // where data is not properly zero initialized. Disable these operators when fixing those issues. #ifndef DISABLE_GAMEMEMORY_NEW_OPERATORS -extern void * __cdecl operator new(size_t size); -extern void __cdecl operator delete(void *p); +extern void* __cdecl operator new(size_t size); +extern void __cdecl operator delete(void* p); -extern void * __cdecl operator new[](size_t size); -extern void __cdecl operator delete[](void *p); +extern void* __cdecl operator new[](size_t size); +extern void __cdecl operator delete[](void* p); // additional overloads to account for VC/MFC funky versions -extern void* __cdecl operator new(size_t size, const char *, int); -extern void __cdecl operator delete(void *p, const char *, int); +extern void* __cdecl operator new(size_t size, const char*, int); +extern void __cdecl operator delete(void* p, const char*, int); -extern void* __cdecl operator new[](size_t size, const char *, int); -extern void __cdecl operator delete[](void *p, const char *, int); +extern void* __cdecl operator new[](size_t size, const char*, int); +extern void __cdecl operator delete[](void* p, const char*, int); #endif diff --git a/Core/GameEngine/Include/Common/GameMusic.h b/Core/GameEngine/Include/Common/GameMusic.h index cd47a3f8ece..19ad93840e8 100644 --- a/Core/GameEngine/Include/Common/GameMusic.h +++ b/Core/GameEngine/Include/Common/GameMusic.h @@ -48,7 +48,6 @@ #include "Common/GameAudio.h" #include "Common/GameMemory.h" - //---------------------------------------------------------------------------- // Forward References //---------------------------------------------------------------------------- @@ -60,53 +59,50 @@ struct FieldParse; // Type Defines //---------------------------------------------------------------------------- - //=============================== // MusicTrack //=============================== //------------------------------------------------------------------------------------------------- /** The MusicTrack struct holds all information about a music track. - * Place data in TrackInfo that is useful to the game code in determining - * what tracks to play. */ + * Place data in TrackInfo that is useful to the game code in determining + * what tracks to play. */ //------------------------------------------------------------------------------------------------- class MusicTrack : public MemoryPoolObject { - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( MusicTrack, "MusicTrack" ) + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(MusicTrack, "MusicTrack") public: + MusicTrack(); + // virtual destructor prototype defined by memory pool object - MusicTrack(); - // virtual destructor prototype defined by memory pool object - - const FieldParse *getFieldParse() const { return m_musicTrackFieldParseTable; } + const FieldParse* getFieldParse() const { return m_musicTrackFieldParseTable; } - Int index; ///< Track index - AsciiString name; ///< Logical name of track - AsciiString filename; ///< Filename with extension of music track - Real volume; ///< Mixing level for this track - Bool ambient; ///< Game info about this track(public) + Int index; ///< Track index + AsciiString name; ///< Logical name of track + AsciiString filename; ///< Filename with extension of music track + Real volume; ///< Mixing level for this track + Bool ambient; ///< Game info about this track(public) - MusicTrack *next; - MusicTrack *prev; - - static const FieldParse m_musicTrackFieldParseTable[]; ///< the parse table for INI definition + MusicTrack* next; + MusicTrack* prev; + static const FieldParse m_musicTrackFieldParseTable[]; ///< the parse table for INI definition }; class MusicManager { - public: - MusicManager(); - virtual ~MusicManager(); +public: + MusicManager(); + virtual ~MusicManager(); - void playTrack( AudioEventRTS *eventToUse ); - void stopTrack( AudioHandle eventToRemove ); + void playTrack(AudioEventRTS* eventToUse); + void stopTrack(AudioHandle eventToRemove); - virtual void addAudioEvent(AudioEventRTS *eventToAdd); // pre-copied - virtual void removeAudioEvent( AudioHandle eventToRemove ); + virtual void addAudioEvent(AudioEventRTS* eventToAdd); // pre-copied + virtual void removeAudioEvent(AudioHandle eventToRemove); - void setVolume( Real m_volume ); + void setVolume(Real m_volume); }; diff --git a/Core/GameEngine/Include/Common/GameSounds.h b/Core/GameEngine/Include/Common/GameSounds.h index 83c846957ac..80d31e6b687 100644 --- a/Core/GameEngine/Include/Common/GameSounds.h +++ b/Core/GameEngine/Include/Common/GameSounds.h @@ -50,49 +50,48 @@ class AudioEventRTS; class SoundManager : public SubsystemInterface { - public: - SoundManager(); - virtual ~SoundManager() override; +public: + SoundManager(); + virtual ~SoundManager() override; - virtual void init() override; ///< Initializes the sounds system - virtual void postProcessLoad() override; - virtual void update() override; ///< Services sounds tasks. Called by AudioInterface - virtual void reset() override; ///< Reset the sounds system + virtual void init() override; ///< Initializes the sounds system + virtual void postProcessLoad() override; + virtual void update() override; ///< Services sounds tasks. Called by AudioInterface + virtual void reset() override; ///< Reset the sounds system - virtual void loseFocus(); ///< Called when application loses focus - virtual void regainFocus(); ///< Called when application regains focus + virtual void loseFocus(); ///< Called when application loses focus + virtual void regainFocus(); ///< Called when application regains focus - virtual void setListenerPosition( const Coord3D *position ); ///< Set the listener position for map3DSound() calculations - virtual void setViewRadius( Real viewRadius );///< Sets the radius of the view from the center of the screen in world coordinate units - virtual void setCameraAudibleDistance( Real audibleDistance ); - virtual Real getCameraAudibleDistance(); + virtual void setListenerPosition(const Coord3D* position); ///< Set the listener position for map3DSound() calculations + virtual void setViewRadius(Real viewRadius); ///< Sets the radius of the view from the center of the screen in world coordinate units + virtual void setCameraAudibleDistance(Real audibleDistance); + virtual Real getCameraAudibleDistance(); - virtual void addAudioEvent(AudioEventRTS *&eventToAdd); // pre-copied + virtual void addAudioEvent(AudioEventRTS*& eventToAdd); // pre-copied - virtual void notifyOf2DSampleStart(); - virtual void notifyOf3DSampleStart(); + virtual void notifyOf2DSampleStart(); + virtual void notifyOf3DSampleStart(); - virtual void notifyOf2DSampleCompletion(); - virtual void notifyOf3DSampleCompletion(); + virtual void notifyOf2DSampleCompletion(); + virtual void notifyOf3DSampleCompletion(); - virtual Int getAvailableSamples(); - virtual Int getAvailable3DSamples(); + virtual Int getAvailableSamples(); + virtual Int getAvailable3DSamples(); - // empty string means that this sound wasn't found or some error occurred. CHECK FOR EMPTY STRING. - virtual AsciiString getFilenameForPlayFromAudioEvent( const AudioEventRTS *eventToGetFrom ); + // empty string means that this sound wasn't found or some error occurred. CHECK FOR EMPTY STRING. + virtual AsciiString getFilenameForPlayFromAudioEvent(const AudioEventRTS* eventToGetFrom); - // called by this class and MilesAudioManager to determine if a sound can still be played - virtual Bool canPlayNow( AudioEventRTS *event ); + // called by this class and MilesAudioManager to determine if a sound can still be played + virtual Bool canPlayNow(AudioEventRTS* event); - protected: - virtual Bool violatesVoice( AudioEventRTS *event ); - virtual Bool isInterrupting( AudioEventRTS *event ); +protected: + virtual Bool violatesVoice(AudioEventRTS* event); + virtual Bool isInterrupting(AudioEventRTS* event); +protected: + UnsignedInt m_num2DSamples; + UnsignedInt m_num3DSamples; - protected: - UnsignedInt m_num2DSamples; - UnsignedInt m_num3DSamples; - - UnsignedInt m_numPlaying2DSamples; - UnsignedInt m_numPlaying3DSamples; + UnsignedInt m_numPlaying2DSamples; + UnsignedInt m_numPlaying3DSamples; }; diff --git a/Core/GameEngine/Include/Common/GameType.h b/Core/GameEngine/Include/Common/GameType.h index eab2ec3e846..437b032f4c0 100644 --- a/Core/GameEngine/Include/Common/GameType.h +++ b/Core/GameEngine/Include/Common/GameType.h @@ -31,27 +31,27 @@ #include "Lib/BaseType.h" // the default size of the world map -#define DEFAULT_WORLD_WIDTH 64 -#define DEFAULT_WORLD_HEIGHT 64 +#define DEFAULT_WORLD_WIDTH 64 +#define DEFAULT_WORLD_HEIGHT 64 /// A unique, generic "identifier" used to access Objects. -enum ObjectID CPP_11(: Int) +enum ObjectID CPP_11( : Int) { INVALID_ID = 0, FORCE_OBJECTID_TO_LONG_SIZE = 0x7ffffff }; /// A unique, generic "identifier" used to access Drawables. -enum DrawableID CPP_11(: Int) +enum DrawableID CPP_11( : Int) { INVALID_DRAWABLE_ID = 0, FORCE_DRAWABLEID_TO_LONG_SIZE = 0x7ffffff }; /// A unique, generic "identifier" used to identify player specified formations. -enum FormationID CPP_11(: Int) +enum FormationID CPP_11( : Int) { - NO_FORMATION_ID = 0, // Unit is not a member of any formation + NO_FORMATION_ID = 0, // Unit is not a member of any formation FORCE_FORMATIONID_TO_LONG_SIZE = 0x7ffffff }; @@ -62,7 +62,7 @@ class INI; //------------------------------------------------------------------------------------------------- /** The time of day enumeration, keep in sync with TimeOfDayNames[] */ //------------------------------------------------------------------------------------------------- -enum TimeOfDay CPP_11(: Int) +enum TimeOfDay CPP_11( : Int) { TIME_OF_DAY_INVALID, @@ -75,11 +75,11 @@ enum TimeOfDay CPP_11(: Int) TIME_OF_DAY_FIRST = TIME_OF_DAY_MORNING, }; -extern const char *const TimeOfDayNames[]; +extern const char* const TimeOfDayNames[]; // defined in Common/GameType.cpp //------------------------------------------------------------------------------------------------- -enum Weather CPP_11(: Int) +enum Weather CPP_11( : Int) { WEATHER_NORMAL = 0, WEATHER_SNOWY = 1, @@ -87,88 +87,88 @@ enum Weather CPP_11(: Int) WEATHER_COUNT }; -extern const char *const WeatherNames[]; +extern const char* const WeatherNames[]; -enum Scorches CPP_11(: Int) +enum Scorches CPP_11( : Int) { SCORCH_1 = 0, SCORCH_2 = 1, SCORCH_3 = 2, SCORCH_4 = 3, SHADOW_SCORCH = 4, -/* SCORCH_6 = 5, - SCORCH_7 = 6, - SCORCH_8 = 7, - - CRATER_1 = 8, - CRATER_2 = 9, - CRATER_3 = 10, - CRATER_4 = 11, - CRATER_5 = 12, - CRATER_6 = 13, - CRATER_7 = 14, - CRATER_8 = 15, - - - MISC_DECAL_1 = 16, - MISC_DECAL_2 = 17, - MISC_DECAL_3 = 18, - MISC_DECAL_4 = 19, - MISC_DECAL_5 = 20, - MISC_DECAL_6 = 21, - MISC_DECAL_7 = 22, - MISC_DECAL_8 = 23, - - MISC_DECAL_9 = 24, - MISC_DECAL_10 = 25, - MISC_DECAL_11 = 26, - MISC_DECAL_12 = 27, - MISC_DECAL_13 = 28, - MISC_DECAL_14 = 29, - MISC_DECAL_15 = 30, - MISC_DECAL_16 = 31, - - MISC_DECAL_17 = 32, - MISC_DECAL_18 = 33, - MISC_DECAL_19 = 34, - MISC_DECAL_20 = 35, - MISC_DECAL_21 = 36, - MISC_DECAL_22 = 37, - MISC_DECAL_23 = 38, - MISC_DECAL_24 = 39, - - MISC_DECAL_25 = 40, - MISC_DECAL_26 = 41, - MISC_DECAL_27 = 42, - MISC_DECAL_28 = 43, - MISC_DECAL_29 = 44, - MISC_DECAL_30 = 45, - MISC_DECAL_31 = 46, - MISC_DECAL_32 = 47, - - MISC_DECAL_33 = 48, - MISC_DECAL_34 = 49, - MISC_DECAL_35 = 50, - MISC_DECAL_36 = 51, - MISC_DECAL_37 = 52, - MISC_DECAL_38 = 53, - MISC_DECAL_39 = 54, - MISC_DECAL_40 = 55, - - MISC_DECAL_41 = 56, - MISC_DECAL_42 = 57, - MISC_DECAL_43 = 58, - MISC_DECAL_44 = 59, - MISC_DECAL_45 = 60, - MISC_DECAL_46 = 61, - MISC_DECAL_47 = 62, - MISC_DECAL_48 = 63, -*/ + /* SCORCH_6 = 5, + SCORCH_7 = 6, + SCORCH_8 = 7, + + CRATER_1 = 8, + CRATER_2 = 9, + CRATER_3 = 10, + CRATER_4 = 11, + CRATER_5 = 12, + CRATER_6 = 13, + CRATER_7 = 14, + CRATER_8 = 15, + + + MISC_DECAL_1 = 16, + MISC_DECAL_2 = 17, + MISC_DECAL_3 = 18, + MISC_DECAL_4 = 19, + MISC_DECAL_5 = 20, + MISC_DECAL_6 = 21, + MISC_DECAL_7 = 22, + MISC_DECAL_8 = 23, + + MISC_DECAL_9 = 24, + MISC_DECAL_10 = 25, + MISC_DECAL_11 = 26, + MISC_DECAL_12 = 27, + MISC_DECAL_13 = 28, + MISC_DECAL_14 = 29, + MISC_DECAL_15 = 30, + MISC_DECAL_16 = 31, + + MISC_DECAL_17 = 32, + MISC_DECAL_18 = 33, + MISC_DECAL_19 = 34, + MISC_DECAL_20 = 35, + MISC_DECAL_21 = 36, + MISC_DECAL_22 = 37, + MISC_DECAL_23 = 38, + MISC_DECAL_24 = 39, + + MISC_DECAL_25 = 40, + MISC_DECAL_26 = 41, + MISC_DECAL_27 = 42, + MISC_DECAL_28 = 43, + MISC_DECAL_29 = 44, + MISC_DECAL_30 = 45, + MISC_DECAL_31 = 46, + MISC_DECAL_32 = 47, + + MISC_DECAL_33 = 48, + MISC_DECAL_34 = 49, + MISC_DECAL_35 = 50, + MISC_DECAL_36 = 51, + MISC_DECAL_37 = 52, + MISC_DECAL_38 = 53, + MISC_DECAL_39 = 54, + MISC_DECAL_40 = 55, + + MISC_DECAL_41 = 56, + MISC_DECAL_42 = 57, + MISC_DECAL_43 = 58, + MISC_DECAL_44 = 59, + MISC_DECAL_45 = 60, + MISC_DECAL_46 = 61, + MISC_DECAL_47 = 62, + MISC_DECAL_48 = 63, + */ SCORCH_COUNT }; //------------------------------------------------------------------------------------------------- -enum WeaponSlotType CPP_11(: Int) +enum WeaponSlotType CPP_11( : Int) { PRIMARY_WEAPON = 0, SECONDARY_WEAPON, @@ -186,6 +186,12 @@ enum WeaponSlotType CPP_11(: Int) // made of structures. // Note that the bridges just index in the pathfinder, so you don't actually // have a LAYER_BRIDGE_1 enum value. -enum PathfindLayerEnum CPP_11(: Int) {LAYER_INVALID = 0, LAYER_GROUND = 1, LAYER_WALL = 15, LAYER_LAST=15}; +enum PathfindLayerEnum CPP_11( : Int) +{ + LAYER_INVALID = 0, + LAYER_GROUND = 1, + LAYER_WALL = 15, + LAYER_LAST = 15 +}; //------------------------------------------------------------------------------------------------- diff --git a/Core/GameEngine/Include/Common/GameUtility.h b/Core/GameEngine/Include/Common/GameUtility.h index 86790ff4847..5cb77359690 100644 --- a/Core/GameEngine/Include/Common/GameUtility.h +++ b/Core/GameEngine/Include/Common/GameUtility.h @@ -29,11 +29,11 @@ namespace rts { bool localPlayerHasRadar(); -Player* getObservedOrLocalPlayer(); ///< Get the current observed or local player. Is never null. -Player* getObservedOrLocalPlayer_Safe(); ///< Get the current observed or local player. Is never null, except when the application does not have players. -PlayerIndex getObservedOrLocalPlayerIndex_Safe(); ///< Get the current observed or local player index. Returns 0 when the application does not have players. +Player* getObservedOrLocalPlayer(); ///< Get the current observed or local player. Is never null. +Player* getObservedOrLocalPlayer_Safe(); ///< Get the current observed or local player. Is never null, except when the application does not have players. +PlayerIndex getObservedOrLocalPlayerIndex_Safe(); ///< Get the current observed or local player index. Returns 0 when the application does not have players. -void changeLocalPlayer(Player* player); //< Change local player during game. Must not pass null. -void changeObservedPlayer(Player* player); ///< Change observed player during game. Can pass null: is identical to passing the "ReplayObserver" player. +void changeLocalPlayer(Player* player); //< Change local player during game. Must not pass null. +void changeObservedPlayer(Player* player); ///< Change observed player during game. Can pass null: is identical to passing the "ReplayObserver" player. -} // namespace rts +} // namespace rts diff --git a/Core/GameEngine/Include/Common/INI.h b/Core/GameEngine/Include/Common/INI.h index 746a2e60395..6b4ca2477bd 100644 --- a/Core/GameEngine/Include/Common/INI.h +++ b/Core/GameEngine/Include/Common/INI.h @@ -30,7 +30,7 @@ #pragma once // INCLUDES /////////////////////////////////////////////////////////////////////////////////////// -#include // for offsetof, which we don't use but everyone who includes us does +#include // for offsetof, which we don't use but everyone who includes us does #include "Common/STLTypedefs.h" #include "Common/AsciiString.h" #include "Common/GameCommon.h" @@ -39,17 +39,17 @@ class INI; class Xfer; class File; -enum ScienceType CPP_11(: Int); +enum ScienceType CPP_11( : Int); //------------------------------------------------------------------------------------------------- /** These control the behavior of loading the INI data into items */ //------------------------------------------------------------------------------------------------- -enum INILoadType CPP_11(: Int) +enum INILoadType CPP_11( : Int) { - INI_LOAD_INVALID, ///< invalid load type - INI_LOAD_OVERWRITE, ///< create new or load *over* existing data instance - INI_LOAD_CREATE_OVERRIDES, ///< create new or load into *new* override data instance - INI_LOAD_MULTIFILE ///< create new or continue loading into existing data instance. + INI_LOAD_INVALID, ///< invalid load type + INI_LOAD_OVERWRITE, ///< create new or load *over* existing data instance + INI_LOAD_CREATE_OVERRIDES, ///< create new or load into *new* override data instance + INI_LOAD_MULTIFILE ///< create new or continue loading into existing data instance. }; //------------------------------------------------------------------------------------------------- @@ -57,7 +57,7 @@ enum INILoadType CPP_11(: Int) //------------------------------------------------------------------------------------------------- enum { - INI_MAX_CHARS_PER_LINE = 1028, ///< max characters per line entry in any ini file + INI_MAX_CHARS_PER_LINE = 1028, ///< max characters per line entry in any ini file }; //------------------------------------------------------------------------------------------------- @@ -69,30 +69,30 @@ enum // we generally don't care why it failed; but since the code distinguishes, // I didn't want to wipe out that intelligence. if we ever need to distinguish // failure modes at runtime, just put in real values for these. - INI_CANT_SEARCH_DIR = ERROR_BAD_INI, + INI_CANT_SEARCH_DIR = ERROR_BAD_INI, INI_INVALID_DIRECTORY = ERROR_BAD_INI, - INI_INVALID_PARAMS = ERROR_BAD_INI, + INI_INVALID_PARAMS = ERROR_BAD_INI, INI_INVALID_NAME_LIST = ERROR_BAD_INI, - INI_INVALID_DATA = ERROR_BAD_INI, + INI_INVALID_DATA = ERROR_BAD_INI, INI_MISSING_END_TOKEN = ERROR_BAD_INI, - INI_UNKNOWN_TOKEN = ERROR_BAD_INI, - INI_BUFFER_TOO_SMALL = ERROR_BAD_INI, - INI_FILE_NOT_OPEN = ERROR_BAD_INI, + INI_UNKNOWN_TOKEN = ERROR_BAD_INI, + INI_BUFFER_TOO_SMALL = ERROR_BAD_INI, + INI_FILE_NOT_OPEN = ERROR_BAD_INI, INI_FILE_ALREADY_OPEN = ERROR_BAD_INI, - INI_CANT_OPEN_FILE = ERROR_BAD_INI, - INI_UNKNOWN_ERROR = ERROR_BAD_INI, - INI_END_OF_FILE = ERROR_BAD_INI + INI_CANT_OPEN_FILE = ERROR_BAD_INI, + INI_UNKNOWN_ERROR = ERROR_BAD_INI, + INI_END_OF_FILE = ERROR_BAD_INI }; //------------------------------------------------------------------------------------------------- /** Function typedef for parsing data block fields. - * - * buffer - the character buffer of the line from INI that we are reading and parsing - * instance - instance of what we're loading (for example a ThingTemplate instance) - * store - where to store the data parsed, this is a field in the *instance* 'instance' - */ + * + * buffer - the character buffer of the line from INI that we are reading and parsing + * instance - instance of what we're loading (for example a ThingTemplate instance) + * store - where to store the data parsed, this is a field in the *instance* 'instance' + */ //------------------------------------------------------------------------------------------------- -typedef void (*INIFieldParseProc)( INI *ini, void *instance, void *store, const void* userData ); +typedef void (*INIFieldParseProc)(INI* ini, void* instance, void* store, const void* userData); //------------------------------------------------------------------------------------------------- typedef const char* const ConstCharPtr; @@ -104,17 +104,17 @@ struct LookupListRec const char* name; Int value; }; -typedef const LookupListRec *ConstLookupListRecArray; +typedef const LookupListRec* ConstLookupListRecArray; //------------------------------------------------------------------------------------------------- /** Parse tables for all fields of each data block are created using these */ //------------------------------------------------------------------------------------------------- struct FieldParse { - const char* token; ///< token of the field - INIFieldParseProc parse; ///< the parse function - const void* userData; ///< field-specific data - Int offset; ///< offset to data field + const char* token; ///< token of the field + INIFieldParseProc parse; ///< the parse function + const void* userData; ///< field-specific data + Int offset; ///< offset to data field void set(const char* t, INIFieldParseProc p, const void* u, Int o) { @@ -129,16 +129,20 @@ struct FieldParse class MultiIniFieldParse { private: - enum { MAX_MULTI_FIELDS = 16 }; + enum + { + MAX_MULTI_FIELDS = 16 + }; const FieldParse* m_fieldParse[MAX_MULTI_FIELDS]; - UnsignedInt m_extraOffset[MAX_MULTI_FIELDS]; - Int m_count; + UnsignedInt m_extraOffset[MAX_MULTI_FIELDS]; + Int m_count; public: - MultiIniFieldParse() : m_count(0) + MultiIniFieldParse() + : m_count(0) { - for(Int i = 0; i < MAX_MULTI_FIELDS; i++) + for (Int i = 0; i < MAX_MULTI_FIELDS; i++) m_extraOffset[i] = 0; } @@ -152,7 +156,7 @@ class MultiIniFieldParse //------------------------------------------------------------------------------------------------- /** Function typedef for parsing INI types blocks */ //------------------------------------------------------------------------------------------------- -typedef void (*INIBlockParse)( INI *ini ); +typedef void (*INIBlockParse)(INI* ini); typedef void (*BuildMultiIniFieldProc)(MultiIniFieldParse& p); //------------------------------------------------------------------------------------------------- @@ -160,7 +164,8 @@ typedef void (*BuildMultiIniFieldProc)(MultiIniFieldParse& p); //------------------------------------------------------------------------------------------------- class INI { - INI(const INI&) CPP_11(= delete); + INI(const INI&) + CPP_11(= delete); INI& operator=(const INI&) CPP_11(= delete); public: @@ -170,211 +175,211 @@ class INI // Load a specific INI file by name and/or INI files from a directory (and its subdirectories). // For example "Data\INI\Armor" loads "Data\INI\Armor.ini" and all *.ini files in "Data\INI\Armor". // Throws if not a single INI file is found or one is not read correctly. - UnsignedInt loadFileDirectory( AsciiString fileDirName, INILoadType loadType, Xfer *pXfer, Bool subdirs = TRUE ); + UnsignedInt loadFileDirectory(AsciiString fileDirName, INILoadType loadType, Xfer* pXfer, Bool subdirs = TRUE); // Load INI files from a directory (and its subdirectories). // Throws if one INI file is not read correctly. - UnsignedInt loadDirectory( AsciiString dirName, INILoadType loadType, Xfer *pXfer, Bool subdirs = TRUE ); + UnsignedInt loadDirectory(AsciiString dirName, INILoadType loadType, Xfer* pXfer, Bool subdirs = TRUE); // Load one specific INI file by name. // Throws if the INI file is not found or is not read correctly. - UnsignedInt load( AsciiString filename, INILoadType loadType, Xfer *pXfer ); + UnsignedInt load(AsciiString filename, INILoadType loadType, Xfer* pXfer); - static Bool isDeclarationOfType( AsciiString blockType, AsciiString blockName, char *bufferToCheck ); - static Bool isEndOfBlock( char *bufferToCheck ); + static Bool isDeclarationOfType(AsciiString blockType, AsciiString blockName, char* bufferToCheck); + static Bool isEndOfBlock(char* bufferToCheck); // data type parsing (the highest level of what type of thing we're parsing) - static void parseObjectDefinition( INI *ini ); - static void parseObjectReskinDefinition( INI *ini ); - static void parseWeaponTemplateDefinition( INI *ini ); - static void parseScienceDefinition( INI *ini ); - static void parseRankDefinition( INI *ini ); - static void parseCrateTemplateDefinition( INI *ini ); - static void parseLocomotorTemplateDefinition( INI *ini ); - static void parseLanguageDefinition( INI *ini ); - static void parsePlayerTemplateDefinition( INI *ini ); - static void parseGameDataDefinition( INI *ini ); - static void parseMapDataDefinition( INI *ini ); - static void parseAnim2DDefinition( INI *ini ); - static void parseAudioEventDefinition( INI *ini ); - static void parseDialogDefinition( INI *ini ); - static void parseMusicTrackDefinition( INI *ini ); - static void parseWebpageURLDefinition( INI *ini ); - static void parseHeaderTemplateDefinition( INI *ini ); - static void parseParticleSystemDefinition( INI *ini ); - static void parseWaterSettingDefinition( INI *ini ); - static void parseWaterTransparencyDefinition( INI *ini ); - static void parseWeatherDefinition( INI *ini ); - static void parseMappedImageDefinition( INI *ini ); - static void parseArmorDefinition( INI *ini ); - static void parseDamageFXDefinition( INI *ini ); - static void parseDrawGroupNumberDefinition( INI *ini ); - static void parseTerrainDefinition( INI *ini ); - static void parseTerrainRoadDefinition( INI *ini ); - static void parseTerrainBridgeDefinition( INI *ini ); - static void parseMetaMapDefinition( INI *ini ); - static void parseFXListDefinition( INI *ini ); - static void parseObjectCreationListDefinition( INI* ini ); - static void parseMultiplayerSettingsDefinition( INI* ini ); - static void parseMultiplayerColorDefinition( INI* ini ); - static void parseMultiplayerStartingMoneyChoiceDefinition( INI* ini ); - static void parseOnlineChatColorDefinition( INI* ini ); - static void parseMapCacheDefinition( INI* ini ); - static void parseVideoDefinition( INI* ini ); - static void parseCommandButtonDefinition( INI *ini ); - static void parseCommandSetDefinition( INI *ini ); - static void parseUpgradeDefinition( INI *ini ); - static void parseMouseDefinition( INI* ini ); - static void parseMouseCursorDefinition( INI* ini ); - static void parseAIDataDefinition( INI *ini ); - static void parseSpecialPowerDefinition( INI *ini ); - static void parseInGameUIDefinition( INI *ini ); - static void parseControlBarSchemeDefinition( INI *ini ); - static void parseControlBarResizerDefinition( INI *ini ); - static void parseShellMenuSchemeDefinition( INI *ini ); - static void parseCampaignDefinition( INI *ini ); - static void parseAudioSettingsDefinition( INI *ini ); - static void parseMiscAudio( INI *ini ); - static void parseStaticGameLODDefinition( INI *ini); - static void parseDynamicGameLODDefinition( INI *ini); - static void parseStaticGameLODLevel( INI* ini, void * , void *store, const void*); - static void parseDynamicGameLODLevel( INI* ini, void * , void *store, const void*); - static void parseLODPreset( INI* ini); - static void parseBenchProfile( INI* ini); - static void parseEvaEvent( INI* ini ); - static void parseCredits( INI* ini ); - static void parseWindowTransitions( INI* ini ); - static void parseChallengeModeDefinition( INI* ini ); + static void parseObjectDefinition(INI* ini); + static void parseObjectReskinDefinition(INI* ini); + static void parseWeaponTemplateDefinition(INI* ini); + static void parseScienceDefinition(INI* ini); + static void parseRankDefinition(INI* ini); + static void parseCrateTemplateDefinition(INI* ini); + static void parseLocomotorTemplateDefinition(INI* ini); + static void parseLanguageDefinition(INI* ini); + static void parsePlayerTemplateDefinition(INI* ini); + static void parseGameDataDefinition(INI* ini); + static void parseMapDataDefinition(INI* ini); + static void parseAnim2DDefinition(INI* ini); + static void parseAudioEventDefinition(INI* ini); + static void parseDialogDefinition(INI* ini); + static void parseMusicTrackDefinition(INI* ini); + static void parseWebpageURLDefinition(INI* ini); + static void parseHeaderTemplateDefinition(INI* ini); + static void parseParticleSystemDefinition(INI* ini); + static void parseWaterSettingDefinition(INI* ini); + static void parseWaterTransparencyDefinition(INI* ini); + static void parseWeatherDefinition(INI* ini); + static void parseMappedImageDefinition(INI* ini); + static void parseArmorDefinition(INI* ini); + static void parseDamageFXDefinition(INI* ini); + static void parseDrawGroupNumberDefinition(INI* ini); + static void parseTerrainDefinition(INI* ini); + static void parseTerrainRoadDefinition(INI* ini); + static void parseTerrainBridgeDefinition(INI* ini); + static void parseMetaMapDefinition(INI* ini); + static void parseFXListDefinition(INI* ini); + static void parseObjectCreationListDefinition(INI* ini); + static void parseMultiplayerSettingsDefinition(INI* ini); + static void parseMultiplayerColorDefinition(INI* ini); + static void parseMultiplayerStartingMoneyChoiceDefinition(INI* ini); + static void parseOnlineChatColorDefinition(INI* ini); + static void parseMapCacheDefinition(INI* ini); + static void parseVideoDefinition(INI* ini); + static void parseCommandButtonDefinition(INI* ini); + static void parseCommandSetDefinition(INI* ini); + static void parseUpgradeDefinition(INI* ini); + static void parseMouseDefinition(INI* ini); + static void parseMouseCursorDefinition(INI* ini); + static void parseAIDataDefinition(INI* ini); + static void parseSpecialPowerDefinition(INI* ini); + static void parseInGameUIDefinition(INI* ini); + static void parseControlBarSchemeDefinition(INI* ini); + static void parseControlBarResizerDefinition(INI* ini); + static void parseShellMenuSchemeDefinition(INI* ini); + static void parseCampaignDefinition(INI* ini); + static void parseAudioSettingsDefinition(INI* ini); + static void parseMiscAudio(INI* ini); + static void parseStaticGameLODDefinition(INI* ini); + static void parseDynamicGameLODDefinition(INI* ini); + static void parseStaticGameLODLevel(INI* ini, void*, void* store, const void*); + static void parseDynamicGameLODLevel(INI* ini, void*, void* store, const void*); + static void parseLODPreset(INI* ini); + static void parseBenchProfile(INI* ini); + static void parseEvaEvent(INI* ini); + static void parseCredits(INI* ini); + static void parseWindowTransitions(INI* ini); + static void parseChallengeModeDefinition(INI* ini); AsciiString getFilename() const { return m_filename; } INILoadType getLoadType() const { return m_loadType; } UnsignedInt getLineNum() const { return m_lineNum; } Bool isEOF() const { return m_endOfFile; } - static const char *getSeps() { return " \n\r\t="; } ///< default delimiters for strtok parsing - static const char *getSepsPercent() { return " \n\r\t=%%"; } ///< default delimiters & percent delimiter - static const char *getSepsColon() { return " \n\r\t=:"; } ///< default delimiters & colon delimiter - static const char *getSepsQuote() { return "\"\n="; } ///< delimiters to represent a quoted ascii string - static const char *getEndToken() { return "End"; } ///< token to represent an end of data block - - void initFromINI( void *what, const FieldParse* parseTable ); - void initFromINIMulti( void *what, const MultiIniFieldParse& parseTableList ); - void initFromINIMultiProc( void *what, BuildMultiIniFieldProc proc ); - - static void parseUnsignedByte( INI *ini, void *instance, void *store, const void* userData ); - static void parseShort( INI *ini, void *instance, void *store, const void* userData ); - static void parseUnsignedShort( INI *ini, void *instance, void *store, const void* userData ); - static void parseInt( INI *ini, void *instance, void *store, const void* userData ); - static void parseUnsignedInt( INI *ini, void *instance, void *store, const void* userData ); - static void parseReal( INI *ini, void *instance, void *store, const void* userData ); - static void parsePositiveNonZeroReal( INI *ini, void *instance, void *store, const void* userData ); - static void parseBool( INI *ini, void *instance, void *store, const void* userData ); - static void parseBitInInt32( INI *ini, void *instance, void *store, const void* userData ); - static void parseAsciiString( INI *ini, void *instance, void *store, const void* userData ); - static void parseQuotedAsciiString( INI *ini, void *instance, void *store, const void* userData ); - static void parseAsciiStringVector( INI *ini, void *instance, void *store, const void* userData ); - static void parseAsciiStringVectorAppend( INI *ini, void *instance, void *store, const void* userData ); - static void parseAndTranslateLabel( INI *ini, void *instance, void *store, const void* userData ); - static void parseMappedImage( INI *ini, void *instance, void *store, const void *userData ); - static void parseAnim2DTemplate( INI *ini, void *instance, void *store, const void *userData ); - static void parsePercentToReal( INI *ini, void *instance, void *store, const void* userData ); - static void parseRGBColor( INI *ini, void *instance, void *store, const void* userData ); - static void parseRGBAColorInt( INI *ini, void *instance, void *store, const void* userData ); - static void parseColorInt( INI *ini, void *instance, void *store, const void* userData ); - static void parseCoord3D( INI *ini, void *instance, void *store, const void* userData ); - static void parseCoord2D( INI *ini, void *instance, void *store, const void *userData ); - static void parseICoord2D( INI *ini, void *instance, void *store, const void *userData ); - static void parseDynamicAudioEventRTS( INI *ini, void *instance, void *store, const void* userData ); - static void parseAudioEventRTS( INI *ini, void *instance, void *store, const void* userData ); - static void parseFXList( INI *ini, void *instance, void *store, const void* userData ); - static void parseParticleSystemTemplate( INI *ini, void *instance, void *store, const void *userData ); - static void parseObjectCreationList( INI *ini, void *instance, void *store, const void* userData ); - static void parseSpecialPowerTemplate( INI *ini, void *instance, void *store, const void *userData ); - static void parseUpgradeTemplate( INI *ini, void *instance, void *store, const void *userData ); - static void parseScience( INI *ini, void *instance, void *store, const void *userData ); - static void parseScienceVector( INI *ini, void *instance, void *store, const void *userData ); - static void parseGameClientRandomVariable( INI* ini, void *instance, void *store, const void* userData ); - static void parseBitString8( INI *ini, void *instance, void *store, const void* userData ); - static void parseBitString32( INI *ini, void *instance, void *store, const void* userData ); - static void parseByteSizedIndexList( INI *ini, void *instance, void *store, const void* userData ); - static void parseIndexList( INI *ini, void *instance, void *store, const void* userData ); - static void parseLookupList( INI *ini, void *instance, void *store, const void* userData ); - static void parseThingTemplate( INI *ini, void *instance, void *store, const void* userData ); - static void parseArmorTemplate( INI *ini, void *instance, void *store, const void* userData ); - static void parseDamageFX( INI *ini, void *instance, void *store, const void* userData ); - static void parseWeaponTemplate( INI *ini, void *instance, void *store, const void* userData ); + static const char* getSeps() { return " \n\r\t="; } ///< default delimiters for strtok parsing + static const char* getSepsPercent() { return " \n\r\t=%%"; } ///< default delimiters & percent delimiter + static const char* getSepsColon() { return " \n\r\t=:"; } ///< default delimiters & colon delimiter + static const char* getSepsQuote() { return "\"\n="; } ///< delimiters to represent a quoted ascii string + static const char* getEndToken() { return "End"; } ///< token to represent an end of data block + + void initFromINI(void* what, const FieldParse* parseTable); + void initFromINIMulti(void* what, const MultiIniFieldParse& parseTableList); + void initFromINIMultiProc(void* what, BuildMultiIniFieldProc proc); + + static void parseUnsignedByte(INI* ini, void* instance, void* store, const void* userData); + static void parseShort(INI* ini, void* instance, void* store, const void* userData); + static void parseUnsignedShort(INI* ini, void* instance, void* store, const void* userData); + static void parseInt(INI* ini, void* instance, void* store, const void* userData); + static void parseUnsignedInt(INI* ini, void* instance, void* store, const void* userData); + static void parseReal(INI* ini, void* instance, void* store, const void* userData); + static void parsePositiveNonZeroReal(INI* ini, void* instance, void* store, const void* userData); + static void parseBool(INI* ini, void* instance, void* store, const void* userData); + static void parseBitInInt32(INI* ini, void* instance, void* store, const void* userData); + static void parseAsciiString(INI* ini, void* instance, void* store, const void* userData); + static void parseQuotedAsciiString(INI* ini, void* instance, void* store, const void* userData); + static void parseAsciiStringVector(INI* ini, void* instance, void* store, const void* userData); + static void parseAsciiStringVectorAppend(INI* ini, void* instance, void* store, const void* userData); + static void parseAndTranslateLabel(INI* ini, void* instance, void* store, const void* userData); + static void parseMappedImage(INI* ini, void* instance, void* store, const void* userData); + static void parseAnim2DTemplate(INI* ini, void* instance, void* store, const void* userData); + static void parsePercentToReal(INI* ini, void* instance, void* store, const void* userData); + static void parseRGBColor(INI* ini, void* instance, void* store, const void* userData); + static void parseRGBAColorInt(INI* ini, void* instance, void* store, const void* userData); + static void parseColorInt(INI* ini, void* instance, void* store, const void* userData); + static void parseCoord3D(INI* ini, void* instance, void* store, const void* userData); + static void parseCoord2D(INI* ini, void* instance, void* store, const void* userData); + static void parseICoord2D(INI* ini, void* instance, void* store, const void* userData); + static void parseDynamicAudioEventRTS(INI* ini, void* instance, void* store, const void* userData); + static void parseAudioEventRTS(INI* ini, void* instance, void* store, const void* userData); + static void parseFXList(INI* ini, void* instance, void* store, const void* userData); + static void parseParticleSystemTemplate(INI* ini, void* instance, void* store, const void* userData); + static void parseObjectCreationList(INI* ini, void* instance, void* store, const void* userData); + static void parseSpecialPowerTemplate(INI* ini, void* instance, void* store, const void* userData); + static void parseUpgradeTemplate(INI* ini, void* instance, void* store, const void* userData); + static void parseScience(INI* ini, void* instance, void* store, const void* userData); + static void parseScienceVector(INI* ini, void* instance, void* store, const void* userData); + static void parseGameClientRandomVariable(INI* ini, void* instance, void* store, const void* userData); + static void parseBitString8(INI* ini, void* instance, void* store, const void* userData); + static void parseBitString32(INI* ini, void* instance, void* store, const void* userData); + static void parseByteSizedIndexList(INI* ini, void* instance, void* store, const void* userData); + static void parseIndexList(INI* ini, void* instance, void* store, const void* userData); + static void parseLookupList(INI* ini, void* instance, void* store, const void* userData); + static void parseThingTemplate(INI* ini, void* instance, void* store, const void* userData); + static void parseArmorTemplate(INI* ini, void* instance, void* store, const void* userData); + static void parseDamageFX(INI* ini, void* instance, void* store, const void* userData); + static void parseWeaponTemplate(INI* ini, void* instance, void* store, const void* userData); // parse a duration in msec and convert to duration in frames - static void parseDurationReal( INI *ini, void *instance, void *store, const void* userData ); + static void parseDurationReal(INI* ini, void* instance, void* store, const void* userData); // parse a duration in msec and convert to duration in integral number of frames, (unsignedint) rounding UP - static void parseDurationUnsignedInt( INI *ini, void *instance, void *store, const void* userData ); - static void parseDurationUnsignedShort( INI *ini, void *instance, void *store, const void *userData ); + static void parseDurationUnsignedInt(INI* ini, void* instance, void* store, const void* userData); + static void parseDurationUnsignedShort(INI* ini, void* instance, void* store, const void* userData); // parse acceleration in (dist/sec) and convert to (dist/frame) - static void parseVelocityReal( INI *ini, void *instance, void *store, const void* userData ); + static void parseVelocityReal(INI* ini, void* instance, void* store, const void* userData); // parse acceleration in (dist/sec^2) and convert to (dist/frame^2) - static void parseAccelerationReal( INI *ini, void *instance, void *store, const void* userData ); + static void parseAccelerationReal(INI* ini, void* instance, void* store, const void* userData); // parse angle in degrees and convert to radians - static void parseAngleReal( INI *ini, void *instance, void *store, const void *userData ); + static void parseAngleReal(INI* ini, void* instance, void* store, const void* userData); // note that this parses in degrees/sec, and converts to rads/frame! - static void parseAngularVelocityReal( INI *ini, void *instance, void *store, const void *userData ); + static void parseAngularVelocityReal(INI* ini, void* instance, void* store, const void* userData); static void parseDamageTypeFlags(INI* ini, void* instance, void* store, const void* userData); static void parseDeathTypeFlags(INI* ini, void* instance, void* store, const void* userData); static void parseVeterancyLevelFlags(INI* ini, void* instance, void* store, const void* userData); - static void parseSoundsList( INI* ini, void *instance, void *store, const void* /*userData*/ ); + static void parseSoundsList(INI* ini, void* instance, void* store, const void* /*userData*/); /** - return the next token. if seps is not specified, the standard seps are used. + return the next token. if seps is not specified, the standard seps are used. - this will *never* return null; if there are no more tokens, an exception will be thrown. + this will *never* return null; if there are no more tokens, an exception will be thrown. */ static const char* getNextToken(const char* seps = getSeps()); /** - just like getNextToken(), except that null is returned if no more tokens are present - (rather than throwing an exception). usually you should call getNextToken(), - but for some cases this is handier (ie, parsing a variable-length number of tokens). + just like getNextToken(), except that null is returned if no more tokens are present + (rather than throwing an exception). usually you should call getNextToken(), + but for some cases this is handier (ie, parsing a variable-length number of tokens). */ static const char* getNextTokenOrNull(const char* seps = getSeps()); /** - This is called when the next thing you expect is something like: + This is called when the next thing you expect is something like: - Tag:value + Tag:value - pass "Tag" (without the colon) for 'expected', and you will have the 'value' - token returned. + pass "Tag" (without the colon) for 'expected', and you will have the 'value' + token returned. - If "Tag" is not the next token, an error is thrown. + If "Tag" is not the next token, an error is thrown. */ static const char* getNextSubToken(const char* expected); /** - return the next ascii string. this is usually the same the result of getNextToken(), - except that it allows for quote-delimited strings (eg, "foo bar"), so you can - get strings with spaces, and/or empty strings. + return the next ascii string. this is usually the same the result of getNextToken(), + except that it allows for quote-delimited strings (eg, "foo bar"), so you can + get strings with spaces, and/or empty strings. */ AsciiString getNextAsciiString(); - AsciiString getNextQuotedAsciiString(); //fixed version of above. We can't fix the regular one for fear of breaking existing code. :-( + AsciiString getNextQuotedAsciiString(); // fixed version of above. We can't fix the regular one for fear of breaking existing code. :-( /** - utility routine that does a sscanf() on the string to get the Science, and throws - an exception if not of the right form. + utility routine that does a sscanf() on the string to get the Science, and throws + an exception if not of the right form. */ static ScienceType scanScience(const char* token); /** - utility routine that does a sscanf() on the string to get the int, and throws - an exception if not of the right form. + utility routine that does a sscanf() on the string to get the int, and throws + an exception if not of the right form. */ static Int scanInt(const char* token); /** - utility routine that does a sscanf() on the string to get the unsigned int, and throws - an exception if not of the right form. + utility routine that does a sscanf() on the string to get the unsigned int, and throws + an exception if not of the right form. */ static UnsignedInt scanUnsignedInt(const char* token); /** - utility routine that does a sscanf() on the string to get the real, and throws - an exception if not of the right form. + utility routine that does a sscanf() on the string to get the real, and throws + an exception if not of the right form. */ static Real scanReal(const char* token); static Real scanPercentToReal(const char* token); @@ -385,24 +390,23 @@ class INI static Bool scanBool(const char* token); protected: + static Bool isValidINIFilename(const char* filename); ///< is this a valid .ini filename - static Bool isValidINIFilename( const char *filename ); ///< is this a valid .ini filename - - void prepFile( AsciiString filename, INILoadType loadType ); + void prepFile(AsciiString filename, INILoadType loadType); void unPrepFile(); void readLine(); - char* m_readBuffer; ///< internal read buffer - unsigned m_readBufferNext; ///< next char in read buffer - unsigned m_readBufferUsed; ///< number of bytes in read buffer + char* m_readBuffer; ///< internal read buffer + unsigned m_readBufferNext; ///< next char in read buffer + unsigned m_readBufferUsed; ///< number of bytes in read buffer - AsciiString m_filename; ///< filename of file currently loading - INILoadType m_loadType; ///< load type for current file - UnsignedInt m_lineNum; ///< current line number that's been read - char m_buffer[ INI_MAX_CHARS_PER_LINE+1 ];///< buffer to read file contents into - Bool m_endOfFile; ///< TRUE when we've hit EOF + AsciiString m_filename; ///< filename of file currently loading + INILoadType m_loadType; ///< load type for current file + UnsignedInt m_lineNum; ///< current line number that's been read + char m_buffer[INI_MAX_CHARS_PER_LINE + 1]; ///< buffer to read file contents into + Bool m_endOfFile; ///< TRUE when we've hit EOF #ifdef DEBUG_CRASHING - char m_curBlockStart[ INI_MAX_CHARS_PER_LINE+1 ]; ///< first line of cur block + char m_curBlockStart[INI_MAX_CHARS_PER_LINE + 1]; ///< first line of cur block #endif }; diff --git a/Core/GameEngine/Include/Common/LocalFile.h b/Core/GameEngine/Include/Common/LocalFile.h index 8f98ab50c9c..4737ba94da0 100644 --- a/Core/GameEngine/Include/Common/LocalFile.h +++ b/Core/GameEngine/Include/Common/LocalFile.h @@ -50,14 +50,13 @@ #include "Common/file.h" #if USE_BUFFERED_IO -#include "Utility/stdio_adapter.h" + #include "Utility/stdio_adapter.h" #endif //---------------------------------------------------------------------------- // Forward References //---------------------------------------------------------------------------- - //---------------------------------------------------------------------------- // Type Defines //---------------------------------------------------------------------------- @@ -66,66 +65,59 @@ // LocalFile //=============================== /** - * File abstraction for standard C file operators: open, close, lseek, read, write - */ + * File abstraction for standard C file operators: open, close, lseek, read, write + */ //=============================== class LocalFile : public File { MEMORY_POOL_GLUE_ABC(LocalFile) - private: - +private: #if USE_BUFFERED_IO - // srj sez: this was purely an experiment in optimization. - // at the present time, it doesn't appear to be a good one. - // TheSuperHackers @info It is a good optimization and will be - // significantly faster than unbuffered IO with small reads and writes. - FILE* m_file; + // srj sez: this was purely an experiment in optimization. + // at the present time, it doesn't appear to be a good one. + // TheSuperHackers @info It is a good optimization and will be + // significantly faster than unbuffered IO with small reads and writes. + FILE* m_file; #else - int m_handle; ///< Local C file handle + int m_handle; ///< Local C file handle #endif - public: - - LocalFile(); - //virtual ~LocalFile(); - - - virtual Bool open( const Char *filename, Int access = NONE, size_t bufferSize = BUFFERSIZE ) override; ///< Open a file for access - virtual void close() override; ///< Close the file - virtual Int read( void *buffer, Int bytes ) override; ///< Read the specified number of bytes in to buffer: See File::read - virtual Int readChar() override; ///< Read a character from the file - virtual Int readWideChar() override; ///< Read a wide character from the file - virtual Int write( const void *buffer, Int bytes ) override; ///< Write the specified number of bytes from the buffer: See File::write - virtual Int writeFormat( const Char* format, ... ) override; ///< Write an unterminated formatted string to the file - virtual Int writeFormat( const WideChar* format, ... ) override; ///< Write an unterminated formatted string to the file - virtual Int writeChar( const Char* character ) override; ///< Write a character to the file - virtual Int writeChar( const WideChar* character ) override; ///< Write a wide character to the file - virtual Int seek( Int new_pos, seekMode mode = CURRENT ) override; ///< Set file position: See File::seek - virtual Bool flush() override; ///< flush data to disk - virtual void nextLine(Char *buf = nullptr, Int bufSize = 0) override; ///< moves file position to after the next new-line - virtual Bool scanInt(Int &newInt) override; ///< return what gets read in as an integer at the current file position. - virtual Bool scanReal(Real &newReal) override; ///< return what gets read in as a float at the current file position. - virtual Bool scanString(AsciiString &newString) override; ///< return what gets read in as a string at the current file position. - /** - Allocate a buffer large enough to hold entire file, read - the entire file into the buffer, then close the file. - the buffer is owned by the caller, who is responsible - for freeing is (via delete[]). This is a Good Thing to - use because it minimizes memory copies for BIG files. - */ - virtual char* readEntireAndClose() override; - virtual File* convertToRAMFile() override; - - protected: +public: + LocalFile(); + // virtual ~LocalFile(); + + virtual Bool open(const Char* filename, Int access = NONE, size_t bufferSize = BUFFERSIZE) override; ///< Open a file for access + virtual void close() override; ///< Close the file + virtual Int read(void* buffer, Int bytes) override; ///< Read the specified number of bytes in to buffer: See File::read + virtual Int readChar() override; ///< Read a character from the file + virtual Int readWideChar() override; ///< Read a wide character from the file + virtual Int write(const void* buffer, Int bytes) override; ///< Write the specified number of bytes from the buffer: See File::write + virtual Int writeFormat(const Char* format, ...) override; ///< Write an unterminated formatted string to the file + virtual Int writeFormat(const WideChar* format, ...) override; ///< Write an unterminated formatted string to the file + virtual Int writeChar(const Char* character) override; ///< Write a character to the file + virtual Int writeChar(const WideChar* character) override; ///< Write a wide character to the file + virtual Int seek(Int new_pos, seekMode mode = CURRENT) override; ///< Set file position: See File::seek + virtual Bool flush() override; ///< flush data to disk + virtual void nextLine(Char* buf = nullptr, Int bufSize = 0) override; ///< moves file position to after the next new-line + virtual Bool scanInt(Int& newInt) override; ///< return what gets read in as an integer at the current file position. + virtual Bool scanReal(Real& newReal) override; ///< return what gets read in as a float at the current file position. + virtual Bool scanString(AsciiString& newString) override; ///< return what gets read in as a string at the current file position. + /** + Allocate a buffer large enough to hold entire file, read + the entire file into the buffer, then close the file. + the buffer is owned by the caller, who is responsible + for freeing is (via delete[]). This is a Good Thing to + use because it minimizes memory copies for BIG files. + */ + virtual char* readEntireAndClose() override; + virtual File* convertToRAMFile() override; - void closeWithoutDelete(); - void closeFile(); +protected: + void closeWithoutDelete(); + void closeFile(); }; - - - //---------------------------------------------------------------------------- // Inlining //---------------------------------------------------------------------------- diff --git a/Core/GameEngine/Include/Common/LocalFileSystem.h b/Core/GameEngine/Include/Common/LocalFileSystem.h index 837e8992287..67b873c7824 100644 --- a/Core/GameEngine/Include/Common/LocalFileSystem.h +++ b/Core/GameEngine/Include/Common/LocalFileSystem.h @@ -29,7 +29,7 @@ #pragma once #include "Common/SubsystemInterface.h" -#include "FileSystem.h" // for typedefs, etc. +#include "FileSystem.h" // for typedefs, etc. class LocalFileSystem : public SubsystemInterface { @@ -40,14 +40,14 @@ class LocalFileSystem : public SubsystemInterface virtual void reset() = 0; virtual void update() = 0; - virtual File * openFile(const Char *filename, Int access = File::NONE, size_t bufferSize = File::BUFFERSIZE) = 0; - virtual Bool doesFileExist(const Char *filename) const = 0; - virtual void getFileListInDirectory(const AsciiString& currentDirectory, const AsciiString& originalDirectory, const AsciiString& searchName, FilenameList &filenameList, Bool searchSubdirectories) const = 0; ///< search the given directory for files matching the searchName (egs. *.ini, *.rep). Possibly search subdirectories. - virtual Bool getFileInfo(const AsciiString& filename, FileInfo *fileInfo) const = 0; ///< see FileSystem.h - virtual Bool createDirectory(AsciiString directory) = 0; ///< see FileSystem.h - virtual AsciiString normalizePath(const AsciiString& filePath) const = 0; ///< see FileSystem.h + virtual File* openFile(const Char* filename, Int access = File::NONE, size_t bufferSize = File::BUFFERSIZE) = 0; + virtual Bool doesFileExist(const Char* filename) const = 0; + virtual void getFileListInDirectory(const AsciiString& currentDirectory, const AsciiString& originalDirectory, const AsciiString& searchName, FilenameList& filenameList, Bool searchSubdirectories) const = 0; ///< search the given directory for files matching the searchName (egs. *.ini, *.rep). Possibly search subdirectories. + virtual Bool getFileInfo(const AsciiString& filename, FileInfo* fileInfo) const = 0; ///< see FileSystem.h + virtual Bool createDirectory(AsciiString directory) = 0; ///< see FileSystem.h + virtual AsciiString normalizePath(const AsciiString& filePath) const = 0; ///< see FileSystem.h protected: }; -extern LocalFileSystem *TheLocalFileSystem; +extern LocalFileSystem* TheLocalFileSystem; diff --git a/Core/GameEngine/Include/Common/MapObject.h b/Core/GameEngine/Include/Common/MapObject.h index 0ef54835bbd..1374cca24f0 100644 --- a/Core/GameEngine/Include/Common/MapObject.h +++ b/Core/GameEngine/Include/Common/MapObject.h @@ -22,7 +22,6 @@ // // //////////////////////////////////////////////////////////////////////////////// - // MapObject.h // Class to encapsulate height map. // Author: John Ahlquist, April 2001 @@ -33,17 +32,13 @@ #include "Common/GameMemory.h" #include "GameClient/TerrainRoads.h" - - class WorldHeightMapInterfaceClass { public: - - virtual Int getBorderSize() = 0; - virtual Real getSeismicZVelocity(Int xIndex, Int yIndex) const = 0; - virtual void setSeismicZVelocity(Int xIndex, Int yIndex, Real value) = 0; - virtual Real getBilinearSampleSeismicZVelocity( Int x, Int y) = 0; - + virtual Int getBorderSize() = 0; + virtual Real getSeismicZVelocity(Int xIndex, Int yIndex) const = 0; + virtual void setSeismicZVelocity(Int xIndex, Int yIndex, Real value) = 0; + virtual Real getBilinearSampleSeismicZVelocity(Int x, Int y) = 0; }; /** MapObject class @@ -52,35 +47,36 @@ class WorldHeightMap; class RenderObjClass; class ThingTemplate; class Shadow; -enum WaypointID CPP_11(: Int); +enum WaypointID CPP_11( : Int); -#define MAP_XY_FACTOR (10.0f) //How wide and tall each height map square is in world space. -#define MAP_HEIGHT_SCALE (MAP_XY_FACTOR/16.0f) //divide all map heights by 8. +#define MAP_XY_FACTOR (10.0f) // How wide and tall each height map square is in world space. +#define MAP_HEIGHT_SCALE (MAP_XY_FACTOR / 16.0f) // divide all map heights by 8. // m_flags bit values. -enum { - FLAG_DRAWS_IN_MIRROR = 0x00000001, ///< If set, draws in water mirror. - FLAG_ROAD_POINT1 = 0x00000002, ///< If set, is the first point in a road segment. - FLAG_ROAD_POINT2 = 0x00000004, ///< If set, is the second point in a road segment. - FLAG_ROAD_FLAGS = (FLAG_ROAD_POINT1|FLAG_ROAD_POINT2), ///< If nonzero, object is a road piece. - FLAG_ROAD_CORNER_ANGLED = 0x00000008, ///< If set, the road corner is angled rather than curved. - FLAG_BRIDGE_POINT1 = 0x00000010, ///< If set, is the first point in a bridge. - FLAG_BRIDGE_POINT2 = 0x00000020, ///< If set, is the second point in a bridge. - FLAG_BRIDGE_FLAGS = (FLAG_BRIDGE_POINT1|FLAG_BRIDGE_POINT2), ///< If nonzero, object is a bridge piece. - FLAG_ROAD_CORNER_TIGHT = 0x00000040, - FLAG_ROAD_JOIN = 0x00000080, ///< If set, this road end does a generic alpha join. - FLAG_DONT_RENDER = 0x00000100 ///< If set, do not render this object. Only WB pays attention to this. (Right now, anyways) +enum +{ + FLAG_DRAWS_IN_MIRROR = 0x00000001, ///< If set, draws in water mirror. + FLAG_ROAD_POINT1 = 0x00000002, ///< If set, is the first point in a road segment. + FLAG_ROAD_POINT2 = 0x00000004, ///< If set, is the second point in a road segment. + FLAG_ROAD_FLAGS = (FLAG_ROAD_POINT1 | FLAG_ROAD_POINT2), ///< If nonzero, object is a road piece. + FLAG_ROAD_CORNER_ANGLED = 0x00000008, ///< If set, the road corner is angled rather than curved. + FLAG_BRIDGE_POINT1 = 0x00000010, ///< If set, is the first point in a bridge. + FLAG_BRIDGE_POINT2 = 0x00000020, ///< If set, is the second point in a bridge. + FLAG_BRIDGE_FLAGS = (FLAG_BRIDGE_POINT1 | FLAG_BRIDGE_POINT2), ///< If nonzero, object is a bridge piece. + FLAG_ROAD_CORNER_TIGHT = 0x00000040, + FLAG_ROAD_JOIN = 0x00000080, ///< If set, this road end does a generic alpha join. + FLAG_DONT_RENDER = 0x00000100 ///< If set, do not render this object. Only WB pays attention to this. (Right now, anyways) }; class MapObject : public MemoryPoolObject { MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(MapObject, "MapObject") -// friend doesn't play well with MPO -- srj -// friend class WorldHeightMap; -// friend class WorldHeightMapEdit; -// friend class AddObjectUndoable; -// friend class DeleteInfo; + // friend doesn't play well with MPO -- srj + // friend class WorldHeightMap; + // friend class WorldHeightMapEdit; + // friend class AddObjectUndoable; + // friend class DeleteInfo; enum { @@ -91,71 +87,76 @@ class MapObject : public MemoryPoolObject }; // This data is currently written out into the map data file. - Coord3D m_location; ///< Location of the center of the object. - AsciiString m_objectName; ///< The object name. - const ThingTemplate* m_thingTemplate; ///< thing template for map object - Real m_angle; ///< positive x is 0 degrees, angle is counterclockwise in degrees. - MapObject* m_nextMapObject; ///< linked list. - Int m_flags; ///< Bit flags. - Dict m_properties; ///< general property sheet. + Coord3D m_location; ///< Location of the center of the object. + AsciiString m_objectName; ///< The object name. + const ThingTemplate* m_thingTemplate; ///< thing template for map object + Real m_angle; ///< positive x is 0 degrees, angle is counterclockwise in degrees. + MapObject* m_nextMapObject; ///< linked list. + Int m_flags; ///< Bit flags. + Dict m_properties; ///< general property sheet. // This data is runtime data that is used by the worldbuider editor, but // not saved in the map file. - Int m_color; ///< Display color. - RenderObjClass* m_renderObj; ///< object that renders in the 3d scene. - Shadow* m_shadowObj; ///< object that renders shadow in the 3d scene. - RenderObjClass* m_bridgeTowers[ BRIDGE_MAX_TOWERS ]; ///< for bridge towers - Int m_runtimeFlags; + Int m_color; ///< Display color. + RenderObjClass* m_renderObj; ///< object that renders in the 3d scene. + Shadow* m_shadowObj; ///< object that renders shadow in the 3d scene. + RenderObjClass* m_bridgeTowers[BRIDGE_MAX_TOWERS]; ///< for bridge towers + Int m_runtimeFlags; public: - static MapObject *TheMapObjectListPtr; + static MapObject* TheMapObjectListPtr; static Dict TheWorldDict; public: MapObject(Coord3D loc, AsciiString name, Real angle, Int flags, const Dict* props, - const ThingTemplate *thingTemplate ); + const ThingTemplate* thingTemplate); //~MapObject(); ///< Note that deleting the head of a list deletes all linked objects in the list. public: + Dict* getProperties() { return &m_properties; } ///< return the object's property sheet. + + void setNextMap(MapObject* nextMap) { m_nextMapObject = nextMap; } ///< Link the next map object. + const Coord3D* getLocation() const { return &m_location; } ///< Get the center point. + Real getAngle() const { return m_angle; } ///< Get the angle. + Int getColor() const { return m_color; } ///< Gets whatever ui color we set. + void setColor(Int color) { m_color = color; } ///< Sets the ui color. + AsciiString getName() const { return m_objectName; } ///< Gets the object name + void setName(AsciiString name); ///< Sets the object name + void setThingTemplate(const ThingTemplate* thing); ///< set template + const ThingTemplate* getThingTemplate() const; + MapObject* getNext() const { return m_nextMapObject; } ///< Next map object in the list. Not a copy, don't delete it. + MapObject* duplicate(); ///< Allocates a copy. Caller is responsible for delete-ing this when done with it. + + void setAngle(Real angle) { m_angle = normalizeAngle(angle); } + void setLocation(Coord3D* pLoc) { m_location = *pLoc; } + void setFlag(Int flag) { m_flags |= flag; } + void clearFlag(Int flag) { m_flags &= (~flag); } + Bool getFlag(Int flag) const { return (m_flags & flag) ? true : false; } + Int getFlags() const { return (m_flags); } + + Bool isSelected() const { return (m_runtimeFlags & MO_SELECTED) != 0; } + void setSelected(Bool sel) + { + if (sel) + m_runtimeFlags |= MO_SELECTED; + else + m_runtimeFlags &= ~MO_SELECTED; + } - Dict *getProperties() { return &m_properties; } ///< return the object's property sheet. - - void setNextMap(MapObject *nextMap) {m_nextMapObject = nextMap;} ///< Link the next map object. - const Coord3D *getLocation() const {return &m_location;} ///< Get the center point. - Real getAngle() const {return m_angle;} ///< Get the angle. - Int getColor() const {return m_color;} ///< Gets whatever ui color we set. - void setColor(Int color) {m_color=color;} ///< Sets the ui color. - AsciiString getName() const {return m_objectName;} ///< Gets the object name - void setName(AsciiString name); ///< Sets the object name - void setThingTemplate( const ThingTemplate* thing ); ///< set template - const ThingTemplate *getThingTemplate() const; - MapObject *getNext() const {return m_nextMapObject;} ///< Next map object in the list. Not a copy, don't delete it. - MapObject *duplicate(); ///< Allocates a copy. Caller is responsible for delete-ing this when done with it. - - void setAngle(Real angle) {m_angle = normalizeAngle(angle);} - void setLocation(Coord3D *pLoc) {m_location = *pLoc;} - void setFlag(Int flag) {m_flags |= flag;} - void clearFlag(Int flag) {m_flags &= (~flag);} - Bool getFlag(Int flag) const {return (m_flags&flag)?true:false;} - Int getFlags() const {return (m_flags);} - - Bool isSelected() const {return (m_runtimeFlags & MO_SELECTED) != 0;} - void setSelected(Bool sel) { if (sel) m_runtimeFlags |= MO_SELECTED; else m_runtimeFlags &= ~MO_SELECTED; } - - Bool isLight() const {return (m_runtimeFlags & MO_LIGHT) != 0;} - Bool isWaypoint() const {return (m_runtimeFlags & MO_WAYPOINT) != 0;} - Bool isScorch() const {return (m_runtimeFlags & MO_SCORCH) != 0;} - - void setIsLight() {m_runtimeFlags |= MO_LIGHT;} + Bool isLight() const { return (m_runtimeFlags & MO_LIGHT) != 0; } + Bool isWaypoint() const { return (m_runtimeFlags & MO_WAYPOINT) != 0; } + Bool isScorch() const { return (m_runtimeFlags & MO_SCORCH) != 0; } + + void setIsLight() { m_runtimeFlags |= MO_LIGHT; } void setIsWaypoint() { m_runtimeFlags |= MO_WAYPOINT; } void setIsScorch() { m_runtimeFlags |= MO_SCORCH; } - void setRenderObj(RenderObjClass *pObj); - RenderObjClass *getRenderObj() const {return m_renderObj;} - void setShadowObj(Shadow *pObj) {m_shadowObj=pObj;} - Shadow *getShadowObj() const {return m_shadowObj;} + void setRenderObj(RenderObjClass* pObj); + RenderObjClass* getRenderObj() const { return m_renderObj; } + void setShadowObj(Shadow* pObj) { m_shadowObj = pObj; } + Shadow* getShadowObj() const { return m_shadowObj; } - RenderObjClass* getBridgeRenderObject( BridgeTowerType type ); - void setBridgeRenderObject( BridgeTowerType type, RenderObjClass* renderObj ); + RenderObjClass* getBridgeRenderObject(BridgeTowerType type); + void setBridgeRenderObject(BridgeTowerType type, RenderObjClass* renderObj); WaypointID getWaypointID(); AsciiString getWaypointName(); @@ -175,8 +176,7 @@ class MapObject : public MemoryPoolObject // The fast version doesn't attempt to verify uniqueness. It goes static void fastAssignAllUniqueIDs(); - - static MapObject *getFirstMapObject() { return TheMapObjectListPtr; } + static MapObject* getFirstMapObject() { return TheMapObjectListPtr; } static Dict* getWorldDict() { return &TheWorldDict; } static Int countMapObjectsWithOwner(const AsciiString& n); }; diff --git a/Core/GameEngine/Include/Common/MiniDumper.h b/Core/GameEngine/Include/Common/MiniDumper.h index 44c03e96ef1..b3ac15f4d11 100644 --- a/Core/GameEngine/Include/Common/MiniDumper.h +++ b/Core/GameEngine/Include/Common/MiniDumper.h @@ -19,9 +19,9 @@ #pragma once #ifdef RTS_ENABLE_CRASHDUMP -#include "DbgHelpLoader.h" + #include "DbgHelpLoader.h" -enum DumpType CPP_11(: Char) +enum DumpType CPP_11( : Char) { // Smallest dump type with call stacks and some supporting variables DumpType_Minimal = 'M', @@ -31,7 +31,7 @@ enum DumpType CPP_11(: Char) class MiniDumper { - enum MiniDumperExitCode CPP_11(: Int) + enum MiniDumperExitCode CPP_11( : Int) { MiniDumperExitCode_Success = 0x0, MiniDumperExitCode_FailureWait = 0x37DA1040, diff --git a/Core/GameEngine/Include/Common/MiscAudio.h b/Core/GameEngine/Include/Common/MiscAudio.h index fa7b47f3c16..f8fb2e96639 100644 --- a/Core/GameEngine/Include/Common/MiscAudio.h +++ b/Core/GameEngine/Include/Common/MiscAudio.h @@ -22,7 +22,7 @@ // // //////////////////////////////////////////////////////////////////////////////// -///MiscAudio.h///////////////////////////////////////////////////////////////////////////////////// +/// MiscAudio.h///////////////////////////////////////////////////////////////////////////////////// // This file is for miscellaneous sound hooks that don't have another happy home. #pragma once @@ -33,40 +33,40 @@ struct MiscAudio { static const FieldParse m_fieldParseTable[]; - AudioEventRTS m_radarUnitUnderAttackSound; ///< radar sounds to play when unit under attack - AudioEventRTS m_radarHarvesterUnderAttackSound; ///< radar sounds to play when harvester under attack - AudioEventRTS m_radarStructureUnderAttackSound; ///< radar sounds to play when structure under attack - AudioEventRTS m_radarUnderAttackSound; ///< radar sounds to play when ? under attack - AudioEventRTS m_radarInfiltrationSound; ///< radar sounds to play when something is infiltrated - AudioEventRTS m_radarOnlineSound; ///< radar sounds to play when radar goes online - AudioEventRTS m_radarOfflineSound; ///< radar sounds to play when radar goes offline - AudioEventRTS m_defectorTimerTickSound; ///< snd to play during transient invulnerability while defecting // lorenzen - AudioEventRTS m_defectorTimerDingSound; ///< snd to play when you become vulnerable again // lorenzen - AudioEventRTS m_lockonTickSound; ///< snd to play during stealth-fighter-lockon period - AudioEventRTS m_allCheerSound; ///< snd to play when user presses 'cheer' key - AudioEventRTS m_battleCrySound; ///< snd to play when user presses 'battlecry' key - AudioEventRTS m_guiClickSound; ///< snd to play when user presses button in GUI - AudioEventRTS m_noCanDoSound; ///< Global "No Can Do" sound - AudioEventRTS m_stealthDiscoveredSound; ///< I have just discovered an enemy stealth unit - AudioEventRTS m_stealthNeutralizedSound; ///< One of my stealthed units has just been discovered by the enemy - AudioEventRTS m_moneyDepositSound; ///< Money was deposited in my bank - AudioEventRTS m_moneyWithdrawSound; ///< Money was withdrawn from my bank - AudioEventRTS m_buildingDisabled; ///< Building has lost power, been hit with an EMP, or disable hacked. - AudioEventRTS m_buildingReenabled; ///< Building has recovered from being disabled. - AudioEventRTS m_vehicleDisabled; ///< Vehicle has been disabled via EMP or hacker attack. - AudioEventRTS m_vehicleReenabled; ///< Vehicle has recovered from being disabled. - AudioEventRTS m_splatterVehiclePilotsBrain; ///< Pilot has been sniped by Jarmen Kell. - AudioEventRTS m_terroristInCarMoveVoice; ///< Terrorist issues a move order while in a car. - AudioEventRTS m_terroristInCarAttackVoice; ///< Terrorist issues attack order while in a car. - AudioEventRTS m_terroristInCarSelectVoice; ///< Terrorist is selected while in a car. - AudioEventRTS m_crateHeal; ///< When heal crate is picked up. - AudioEventRTS m_crateShroud; ///< When shroud crate is picked up. - AudioEventRTS m_crateSalvage; ///< When salvage crate is picked up. - AudioEventRTS m_crateFreeUnit; ///< When free unit crate is picked up. - AudioEventRTS m_crateMoney; ///< When money crate is picked up. - AudioEventRTS m_unitPromoted; ///< Unit is promoted. - AudioEventRTS m_repairSparks; ///< Battle drone repairs unit. - AudioEventRTS m_sabotageShutDownBuilding; ///< When Saboteur hits a building - AudioEventRTS m_sabotageResetTimerBuilding; ///< When Saboteur hits a building - AudioEventRTS m_aircraftWheelScreech; ///< When a jet lands on a runway. + AudioEventRTS m_radarUnitUnderAttackSound; ///< radar sounds to play when unit under attack + AudioEventRTS m_radarHarvesterUnderAttackSound; ///< radar sounds to play when harvester under attack + AudioEventRTS m_radarStructureUnderAttackSound; ///< radar sounds to play when structure under attack + AudioEventRTS m_radarUnderAttackSound; ///< radar sounds to play when ? under attack + AudioEventRTS m_radarInfiltrationSound; ///< radar sounds to play when something is infiltrated + AudioEventRTS m_radarOnlineSound; ///< radar sounds to play when radar goes online + AudioEventRTS m_radarOfflineSound; ///< radar sounds to play when radar goes offline + AudioEventRTS m_defectorTimerTickSound; ///< snd to play during transient invulnerability while defecting // lorenzen + AudioEventRTS m_defectorTimerDingSound; ///< snd to play when you become vulnerable again // lorenzen + AudioEventRTS m_lockonTickSound; ///< snd to play during stealth-fighter-lockon period + AudioEventRTS m_allCheerSound; ///< snd to play when user presses 'cheer' key + AudioEventRTS m_battleCrySound; ///< snd to play when user presses 'battlecry' key + AudioEventRTS m_guiClickSound; ///< snd to play when user presses button in GUI + AudioEventRTS m_noCanDoSound; ///< Global "No Can Do" sound + AudioEventRTS m_stealthDiscoveredSound; ///< I have just discovered an enemy stealth unit + AudioEventRTS m_stealthNeutralizedSound; ///< One of my stealthed units has just been discovered by the enemy + AudioEventRTS m_moneyDepositSound; ///< Money was deposited in my bank + AudioEventRTS m_moneyWithdrawSound; ///< Money was withdrawn from my bank + AudioEventRTS m_buildingDisabled; ///< Building has lost power, been hit with an EMP, or disable hacked. + AudioEventRTS m_buildingReenabled; ///< Building has recovered from being disabled. + AudioEventRTS m_vehicleDisabled; ///< Vehicle has been disabled via EMP or hacker attack. + AudioEventRTS m_vehicleReenabled; ///< Vehicle has recovered from being disabled. + AudioEventRTS m_splatterVehiclePilotsBrain; ///< Pilot has been sniped by Jarmen Kell. + AudioEventRTS m_terroristInCarMoveVoice; ///< Terrorist issues a move order while in a car. + AudioEventRTS m_terroristInCarAttackVoice; ///< Terrorist issues attack order while in a car. + AudioEventRTS m_terroristInCarSelectVoice; ///< Terrorist is selected while in a car. + AudioEventRTS m_crateHeal; ///< When heal crate is picked up. + AudioEventRTS m_crateShroud; ///< When shroud crate is picked up. + AudioEventRTS m_crateSalvage; ///< When salvage crate is picked up. + AudioEventRTS m_crateFreeUnit; ///< When free unit crate is picked up. + AudioEventRTS m_crateMoney; ///< When money crate is picked up. + AudioEventRTS m_unitPromoted; ///< Unit is promoted. + AudioEventRTS m_repairSparks; ///< Battle drone repairs unit. + AudioEventRTS m_sabotageShutDownBuilding; ///< When Saboteur hits a building + AudioEventRTS m_sabotageResetTimerBuilding; ///< When Saboteur hits a building + AudioEventRTS m_aircraftWheelScreech; ///< When a jet lands on a runway. }; diff --git a/Core/GameEngine/Include/Common/ObjectStatusTypes.h b/Core/GameEngine/Include/Common/ObjectStatusTypes.h index affa254c9e0..24195f1ee53 100644 --- a/Core/GameEngine/Include/Common/ObjectStatusTypes.h +++ b/Core/GameEngine/Include/Common/ObjectStatusTypes.h @@ -37,43 +37,43 @@ //------------------------------------------------------------------------------------------------- /** Object status types */ //------------------------------------------------------------------------------------------------- -enum ObjectStatusTypes CPP_11(: Int) +enum ObjectStatusTypes CPP_11( : Int) { - //These are saved. Do not insert or remove any! - - OBJECT_STATUS_NONE, ///< no status bit - OBJECT_STATUS_DESTROYED, ///< has been destroyed, pending delete - OBJECT_STATUS_CAN_ATTACK, ///< used by garrissoned buildings, is OR'ed with KINDOF_CAN_ATTACK in isAbleToAttack() - OBJECT_STATUS_UNDER_CONSTRUCTION, ///< object is being constructed and is not yet complete - OBJECT_STATUS_UNSELECTABLE, ///< This is a negative condition since these statuses are overrides. ie their presence forces the condition, but their absence means nothing - OBJECT_STATUS_NO_COLLISIONS, ///< object should be ignored for object-object collisions (but not object-ground); used for thing like collapsing parachutes that are intangible - OBJECT_STATUS_NO_ATTACK, ///< Absolute override to being able to attack - OBJECT_STATUS_AIRBORNE_TARGET, ///< InTheAir as far as AntiAir weapons are concerned only. - OBJECT_STATUS_PARACHUTING, ///< object is on a parachute - OBJECT_STATUS_REPULSOR, ///< object repulses "KINDOF_CAN_BE_REPULSED" objects. - OBJECT_STATUS_HIJACKED, ///< unit is in the possesion of an enemy criminal, call the authorities - OBJECT_STATUS_AFLAME, ///< This object is on fire. - OBJECT_STATUS_BURNED, ///< This object has already burned as much as it can. - OBJECT_STATUS_WET, ///< object has been soaked with water - OBJECT_STATUS_IS_FIRING_WEAPON, ///< Object is firing a weapon, now. Not true for special attacks. --Lorenzen - OBJECT_STATUS_BRAKING, ///< Object is braking, and subverts the physics. - OBJECT_STATUS_STEALTHED, ///< Object is currently "stealthed" - OBJECT_STATUS_DETECTED, ///< Object is in range of a stealth-detector unit (meaningless if STEALTHED not set) - OBJECT_STATUS_CAN_STEALTH, ///< Object has ability to stealth allowing the stealth update module to run. - OBJECT_STATUS_SOLD, ///< Object is being sold - OBJECT_STATUS_UNDERGOING_REPAIR, ///< Object is awaiting/undergoing a repair order that has been issued - OBJECT_STATUS_RECONSTRUCTING, ///< Reconstructing - OBJECT_STATUS_MASKED, ///< Masked objects are not selectable and targetable by players or AI - OBJECT_STATUS_IS_ATTACKING, ///< Object is in the general Attack state (incl. aim, approach, etc.). Note that IS_FIRING_WEAPON and IS_AIMING_WEAPON is a subset of this! - OBJECT_STATUS_IS_USING_ABILITY, ///< Object is in the process of preparing or firing a special ability. - OBJECT_STATUS_IS_AIMING_WEAPON, ///< Object is aiming a weapon, now. Not true for special attacks. - OBJECT_STATUS_NO_ATTACK_FROM_AI, ///< attacking this object may not be done from commandSource == CMD_FROM_AI - OBJECT_STATUS_IGNORING_STEALTH, ///< temporarily ignoring all stealth bits. (used only for some special-case mine clearing stuff.) - OBJECT_STATUS_IS_CARBOMB, ///< Object is now a carbomb. + // These are saved. Do not insert or remove any! + + OBJECT_STATUS_NONE, ///< no status bit + OBJECT_STATUS_DESTROYED, ///< has been destroyed, pending delete + OBJECT_STATUS_CAN_ATTACK, ///< used by garrissoned buildings, is OR'ed with KINDOF_CAN_ATTACK in isAbleToAttack() + OBJECT_STATUS_UNDER_CONSTRUCTION, ///< object is being constructed and is not yet complete + OBJECT_STATUS_UNSELECTABLE, ///< This is a negative condition since these statuses are overrides. ie their presence forces the condition, but their absence means nothing + OBJECT_STATUS_NO_COLLISIONS, ///< object should be ignored for object-object collisions (but not object-ground); used for thing like collapsing parachutes that are intangible + OBJECT_STATUS_NO_ATTACK, ///< Absolute override to being able to attack + OBJECT_STATUS_AIRBORNE_TARGET, ///< InTheAir as far as AntiAir weapons are concerned only. + OBJECT_STATUS_PARACHUTING, ///< object is on a parachute + OBJECT_STATUS_REPULSOR, ///< object repulses "KINDOF_CAN_BE_REPULSED" objects. + OBJECT_STATUS_HIJACKED, ///< unit is in the possesion of an enemy criminal, call the authorities + OBJECT_STATUS_AFLAME, ///< This object is on fire. + OBJECT_STATUS_BURNED, ///< This object has already burned as much as it can. + OBJECT_STATUS_WET, ///< object has been soaked with water + OBJECT_STATUS_IS_FIRING_WEAPON, ///< Object is firing a weapon, now. Not true for special attacks. --Lorenzen + OBJECT_STATUS_BRAKING, ///< Object is braking, and subverts the physics. + OBJECT_STATUS_STEALTHED, ///< Object is currently "stealthed" + OBJECT_STATUS_DETECTED, ///< Object is in range of a stealth-detector unit (meaningless if STEALTHED not set) + OBJECT_STATUS_CAN_STEALTH, ///< Object has ability to stealth allowing the stealth update module to run. + OBJECT_STATUS_SOLD, ///< Object is being sold + OBJECT_STATUS_UNDERGOING_REPAIR, ///< Object is awaiting/undergoing a repair order that has been issued + OBJECT_STATUS_RECONSTRUCTING, ///< Reconstructing + OBJECT_STATUS_MASKED, ///< Masked objects are not selectable and targetable by players or AI + OBJECT_STATUS_IS_ATTACKING, ///< Object is in the general Attack state (incl. aim, approach, etc.). Note that IS_FIRING_WEAPON and IS_AIMING_WEAPON is a subset of this! + OBJECT_STATUS_IS_USING_ABILITY, ///< Object is in the process of preparing or firing a special ability. + OBJECT_STATUS_IS_AIMING_WEAPON, ///< Object is aiming a weapon, now. Not true for special attacks. + OBJECT_STATUS_NO_ATTACK_FROM_AI, ///< attacking this object may not be done from commandSource == CMD_FROM_AI + OBJECT_STATUS_IGNORING_STEALTH, ///< temporarily ignoring all stealth bits. (used only for some special-case mine clearing stuff.) + OBJECT_STATUS_IS_CARBOMB, ///< Object is now a carbomb. // TheSuperHackers @info New statuses added in Zero Hour // Note: Loading old save games that do not track these flags in objects will not recover them. Expect logic bugs. - OBJECT_STATUS_DECK_HEIGHT_OFFSET, ///< Object factors deck height on top of ground altitude. + OBJECT_STATUS_DECK_HEIGHT_OFFSET, ///< Object factors deck height on top of ground altitude. OBJECT_STATUS_RIDER1, OBJECT_STATUS_RIDER2, OBJECT_STATUS_RIDER3, @@ -82,62 +82,61 @@ enum ObjectStatusTypes CPP_11(: Int) OBJECT_STATUS_RIDER6, OBJECT_STATUS_RIDER7, OBJECT_STATUS_RIDER8, - OBJECT_STATUS_FAERIE_FIRE, ///< Anyone shooting at you shoots faster than normal - OBJECT_STATUS_MISSILE_KILLING_SELF, ///< Object (likely a missile or bomb) is *BUSTING* its way through the *BUNKER*, building or ground, awaiting death at the bottom. - OBJECT_STATUS_REASSIGN_PARKING, ///< Jet is trying to get a better parking assignment. - OBJECT_STATUS_BOOBY_TRAPPED, ///< We need to know we have a booby trap on us so we can detonate it from many different code segments - OBJECT_STATUS_IMMOBILE, ///< Do not move! - OBJECT_STATUS_DISGUISED, ///< Object is disguised (a type of stealth) - OBJECT_STATUS_DEPLOYED, ///< Object is deployed. + OBJECT_STATUS_FAERIE_FIRE, ///< Anyone shooting at you shoots faster than normal + OBJECT_STATUS_MISSILE_KILLING_SELF, ///< Object (likely a missile or bomb) is *BUSTING* its way through the *BUNKER*, building or ground, awaiting death at the bottom. + OBJECT_STATUS_REASSIGN_PARKING, ///< Jet is trying to get a better parking assignment. + OBJECT_STATUS_BOOBY_TRAPPED, ///< We need to know we have a booby trap on us so we can detonate it from many different code segments + OBJECT_STATUS_IMMOBILE, ///< Do not move! + OBJECT_STATUS_DISGUISED, ///< Object is disguised (a type of stealth) + OBJECT_STATUS_DEPLOYED, ///< Object is deployed. // add more status types here and don't forget to add to the string table ObjectStatusMaskType::s_bitNameList[] OBJECT_STATUS_COUNT - }; -typedef BitFlags ObjectStatusMaskType; +typedef BitFlags ObjectStatusMaskType; #define MAKE_OBJECT_STATUS_MASK(k) ObjectStatusMaskType(ObjectStatusMaskType::kInit, (k)) -#define MAKE_OBJECT_STATUS_MASK2(k,a) ObjectStatusMaskType(ObjectStatusMaskType::kInit, (k), (a)) -#define MAKE_OBJECT_STATUS_MASK3(k,a,b) ObjectStatusMaskType(ObjectStatusMaskType::kInit, (k), (a), (b)) -#define MAKE_OBJECT_STATUS_MASK4(k,a,b,c) ObjectStatusMaskType(ObjectStatusMaskType::kInit, (k), (a), (b), (c)) -#define MAKE_OBJECT_STATUS_MASK5(k,a,b,c,d) ObjectStatusMaskType(ObjectStatusMaskType::kInit, (k), (a), (b), (c), (d)) +#define MAKE_OBJECT_STATUS_MASK2(k, a) ObjectStatusMaskType(ObjectStatusMaskType::kInit, (k), (a)) +#define MAKE_OBJECT_STATUS_MASK3(k, a, b) ObjectStatusMaskType(ObjectStatusMaskType::kInit, (k), (a), (b)) +#define MAKE_OBJECT_STATUS_MASK4(k, a, b, c) ObjectStatusMaskType(ObjectStatusMaskType::kInit, (k), (a), (b), (c)) +#define MAKE_OBJECT_STATUS_MASK5(k, a, b, c, d) ObjectStatusMaskType(ObjectStatusMaskType::kInit, (k), (a), (b), (c), (d)) -inline Bool TEST_OBJECT_STATUS_MASK( const ObjectStatusMaskType& m, ObjectStatusTypes t ) +inline Bool TEST_OBJECT_STATUS_MASK(const ObjectStatusMaskType& m, ObjectStatusTypes t) { - return m.test( t ); + return m.test(t); } -inline Bool TEST_OBJECT_STATUS_MASK_ANY( const ObjectStatusMaskType& m, const ObjectStatusMaskType& mask ) +inline Bool TEST_OBJECT_STATUS_MASK_ANY(const ObjectStatusMaskType& m, const ObjectStatusMaskType& mask) { - return m.anyIntersectionWith( mask ); + return m.anyIntersectionWith(mask); } -inline Bool TEST_OBJECT_STATUS_MASK_MULTI( const ObjectStatusMaskType& m, const ObjectStatusMaskType& mustBeSet, const ObjectStatusMaskType& mustBeClear ) +inline Bool TEST_OBJECT_STATUS_MASK_MULTI(const ObjectStatusMaskType& m, const ObjectStatusMaskType& mustBeSet, const ObjectStatusMaskType& mustBeClear) { - return m.testSetAndClear( mustBeSet, mustBeClear ); + return m.testSetAndClear(mustBeSet, mustBeClear); } -inline Bool OBJECT_STATUS_MASK_ANY_SET( const ObjectStatusMaskType& m) +inline Bool OBJECT_STATUS_MASK_ANY_SET(const ObjectStatusMaskType& m) { return m.any(); } -inline void CLEAR_OBJECT_STATUS_MASK( ObjectStatusMaskType& m ) +inline void CLEAR_OBJECT_STATUS_MASK(ObjectStatusMaskType& m) { m.clear(); } -inline void SET_ALL_OBJECT_STATUS_MASK_BITS( ObjectStatusMaskType& m ) +inline void SET_ALL_OBJECT_STATUS_MASK_BITS(ObjectStatusMaskType& m) { - m.clear( ); - m.flip( ); + m.clear(); + m.flip(); } -inline void FLIP_OBJECT_STATUS_MASK( ObjectStatusMaskType& m ) +inline void FLIP_OBJECT_STATUS_MASK(ObjectStatusMaskType& m) { m.flip(); } // defined in Common/System/ObjectStatusTypes.cpp -extern ObjectStatusMaskType OBJECT_STATUS_MASK_NONE; // inits to all zeroes +extern ObjectStatusMaskType OBJECT_STATUS_MASK_NONE; // inits to all zeroes diff --git a/Core/GameEngine/Include/Common/OptionPreferences.h b/Core/GameEngine/Include/Common/OptionPreferences.h index 2bacaa07105..4733b527acb 100644 --- a/Core/GameEngine/Include/Common/OptionPreferences.h +++ b/Core/GameEngine/Include/Common/OptionPreferences.h @@ -87,7 +87,7 @@ class OptionPreferences : public UserPreferences Int getIdealStaticGameDetail(); Real getGammaValue(); Int getTextureReduction(); - void getResolution(Int *xres, Int *yres); + void getResolution(Int* xres, Int* yres); Bool get3DShadowsEnabled(); Bool get2DShadowsEnabled(); Bool getCloudShadowsEnabled(); diff --git a/Core/GameEngine/Include/Common/RAMFile.h b/Core/GameEngine/Include/Common/RAMFile.h index b1f639f161e..228409d6a32 100644 --- a/Core/GameEngine/Include/Common/RAMFile.h +++ b/Core/GameEngine/Include/Common/RAMFile.h @@ -53,8 +53,6 @@ // Forward References //---------------------------------------------------------------------------- - - //---------------------------------------------------------------------------- // Type Defines //---------------------------------------------------------------------------- @@ -63,64 +61,57 @@ // RAMFile //=============================== /** - * File abstraction for standard C file operators: open, close, lseek, read, write - */ + * File abstraction for standard C file operators: open, close, lseek, read, write + */ //=============================== class RAMFile : public File { MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(RAMFile, "RAMFile") - protected: - - Char *m_data; ///< File data in memory - Int m_pos; ///< current read position - Int m_size; ///< size of file in memory - - public: - - RAMFile(); - //virtual ~RAMFile(); - - - virtual Bool open( const Char *filename, Int access = NONE, size_t bufferSize = 0 ) override; ///< Open a file for access - virtual void close() override; ///< Close the file - virtual Int read( void *buffer, Int bytes ) override; ///< Read the specified number of bytes in to buffer: See File::read - virtual Int readChar() override; ///< Read a character from the file - virtual Int readWideChar() override; ///< Read a wide character from the file - virtual Int write( const void *buffer, Int bytes ) override; ///< Write the specified number of bytes from the buffer: See File::write - virtual Int writeFormat( const Char* format, ... ) override; ///< Write the formatted string to the file - virtual Int writeFormat( const WideChar* format, ... ) override; ///< Write the formatted string to the file - virtual Int writeChar( const Char* character ) override; ///< Write a character to the file - virtual Int writeChar( const WideChar* character ) override; ///< Write a wide character to the file - virtual Int seek( Int new_pos, seekMode mode = CURRENT ) override; ///< Set file position: See File::seek - virtual Bool flush() override; ///< flush data to disk - virtual void nextLine(Char *buf = nullptr, Int bufSize = 0) override; ///< moves current position to after the next new-line - - virtual Bool scanInt(Int &newInt) override; ///< return what gets read as an integer from the current memory position. - virtual Bool scanReal(Real &newReal) override; ///< return what gets read as a float from the current memory position. - virtual Bool scanString(AsciiString &newString) override; ///< return what gets read as a string from the current memory position. - - virtual Bool open( File *file ); ///< Open file for fast RAM access - virtual Bool openFromArchive(File *archiveFile, const AsciiString& filename, Int offset, Int size); ///< copy file data from the given file at the given offset for the given size. - virtual Bool copyDataToFile(File *localFile); ///< write the contents of the RAM file to the given local file. This could be REALLY slow. - - /** - Allocate a buffer large enough to hold entire file, read - the entire file into the buffer, then close the file. - the buffer is owned by the caller, who is responsible - for freeing is (via delete[]). This is a Good Thing to - use because it minimizes memory copies for BIG files. - */ - virtual char* readEntireAndClose() override; - virtual File* convertToRAMFile() override; - - protected: - - void closeFile(); -}; - - +protected: + Char* m_data; ///< File data in memory + Int m_pos; ///< current read position + Int m_size; ///< size of file in memory + +public: + RAMFile(); + // virtual ~RAMFile(); + + virtual Bool open(const Char* filename, Int access = NONE, size_t bufferSize = 0) override; ///< Open a file for access + virtual void close() override; ///< Close the file + virtual Int read(void* buffer, Int bytes) override; ///< Read the specified number of bytes in to buffer: See File::read + virtual Int readChar() override; ///< Read a character from the file + virtual Int readWideChar() override; ///< Read a wide character from the file + virtual Int write(const void* buffer, Int bytes) override; ///< Write the specified number of bytes from the buffer: See File::write + virtual Int writeFormat(const Char* format, ...) override; ///< Write the formatted string to the file + virtual Int writeFormat(const WideChar* format, ...) override; ///< Write the formatted string to the file + virtual Int writeChar(const Char* character) override; ///< Write a character to the file + virtual Int writeChar(const WideChar* character) override; ///< Write a wide character to the file + virtual Int seek(Int new_pos, seekMode mode = CURRENT) override; ///< Set file position: See File::seek + virtual Bool flush() override; ///< flush data to disk + virtual void nextLine(Char* buf = nullptr, Int bufSize = 0) override; ///< moves current position to after the next new-line + + virtual Bool scanInt(Int& newInt) override; ///< return what gets read as an integer from the current memory position. + virtual Bool scanReal(Real& newReal) override; ///< return what gets read as a float from the current memory position. + virtual Bool scanString(AsciiString& newString) override; ///< return what gets read as a string from the current memory position. + + virtual Bool open(File* file); ///< Open file for fast RAM access + virtual Bool openFromArchive(File* archiveFile, const AsciiString& filename, Int offset, Int size); ///< copy file data from the given file at the given offset for the given size. + virtual Bool copyDataToFile(File* localFile); ///< write the contents of the RAM file to the given local file. This could be REALLY slow. + + /** + Allocate a buffer large enough to hold entire file, read + the entire file into the buffer, then close the file. + the buffer is owned by the caller, who is responsible + for freeing is (via delete[]). This is a Good Thing to + use because it minimizes memory copies for BIG files. + */ + virtual char* readEntireAndClose() override; + virtual File* convertToRAMFile() override; +protected: + void closeFile(); +}; //---------------------------------------------------------------------------- // Inlining diff --git a/Core/GameEngine/Include/Common/Radar.h b/Core/GameEngine/Include/Common/Radar.h index 5e170c261fc..ab533e5cc89 100644 --- a/Core/GameEngine/Include/Common/Radar.h +++ b/Core/GameEngine/Include/Common/Radar.h @@ -33,7 +33,7 @@ #include "Lib/BaseType.h" #include "Common/SubsystemInterface.h" #include "Common/GameMemory.h" -#include "GameClient/Display.h" // for ShroudLevel +#include "GameClient/Display.h" // for ShroudLevel #include "GameClient/Color.h" // FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// @@ -50,15 +50,15 @@ class TerrainLogic; // enum { - RADAR_CELL_WIDTH = 128, // radar created at this horz resolution - RADAR_CELL_HEIGHT = 128 // radar created at this vert resolution + RADAR_CELL_WIDTH = 128, // radar created at this horz resolution + RADAR_CELL_HEIGHT = 128 // radar created at this vert resolution }; //------------------------------------------------------------------------------------------------- /** These event types determine the colors radar events happen in to make it easier for us - * to play events with a consistent color scheme */ + * to play events with a consistent color scheme */ //------------------------------------------------------------------------------------------------- -enum RadarEventType CPP_11(: Int) +enum RadarEventType CPP_11( : Int) { RADAR_EVENT_INVALID = 0, RADAR_EVENT_CONSTRUCTION, @@ -66,15 +66,14 @@ enum RadarEventType CPP_11(: Int) RADAR_EVENT_UNDER_ATTACK, RADAR_EVENT_INFORMATION, RADAR_EVENT_BEACON_PULSE, - RADAR_EVENT_INFILTRATION, //for defection, hijacking, hacking, carbombing, and other sneaks + RADAR_EVENT_INFILTRATION, // for defection, hijacking, hacking, carbombing, and other sneaks RADAR_EVENT_BATTLE_PLAN, - RADAR_EVENT_STEALTH_DISCOVERED, // we discovered a stealth unit - RADAR_EVENT_STEALTH_NEUTRALIZED, // our stealth unit has been revealed - RADAR_EVENT_FAKE, //Internally creates a radar event, but doesn't notify the player (unit lost - //for example, so we can use the spacebar to jump to the event). + RADAR_EVENT_STEALTH_DISCOVERED, // we discovered a stealth unit + RADAR_EVENT_STEALTH_NEUTRALIZED, // our stealth unit has been revealed + RADAR_EVENT_FAKE, // Internally creates a radar event, but doesn't notify the player (unit lost + // for example, so we can use the spacebar to jump to the event). RADAR_EVENT_NUM_EVENTS - }; // PROTOTYPES ///////////////////////////////////////////////////////////////////////////////////// @@ -86,66 +85,62 @@ class RadarObject : public MemoryPoolObject, public Snapshot { - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( RadarObject, "RadarObject" ) + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(RadarObject, "RadarObject") public: - RadarObject(); // destructor prototype defined by memory pool glue // color management - void setColor( Color c ) { m_color = c; } + void setColor(Color c) { m_color = c; } Color getColor() const { return m_color; } - void friend_setObject( Object *obj ) { m_object = obj; } - Object *friend_getObject() { return m_object; } - const Object *friend_getObject() const { return m_object; } + void friend_setObject(Object* obj) { m_object = obj; } + Object* friend_getObject() { return m_object; } + const Object* friend_getObject() const { return m_object; } - void friend_setNext( RadarObject *next ) { m_next = next; } - RadarObject *friend_getNext() { return m_next; } - const RadarObject *friend_getNext() const { return m_next; } + void friend_setNext(RadarObject* next) { m_next = next; } + RadarObject* friend_getNext() { return m_next; } + const RadarObject* friend_getNext() const { return m_next; } Bool isTemporarilyHidden() const; protected: - // snapshot methods - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; + virtual void crc(Xfer* xfer) override; + virtual void xfer(Xfer* xfer) override; virtual void loadPostProcess() override; - Object *m_object; ///< the object - RadarObject *m_next; ///< next radar object - Color m_color; ///< color to draw for this object on the radar - + Object* m_object; ///< the object + RadarObject* m_next; ///< next radar object + Color m_color; ///< color to draw for this object on the radar }; //------------------------------------------------------------------------------------------------- /** Radar priorities. Keep this in sync with the priority names list below */ //------------------------------------------------------------------------------------------------- -enum RadarPriorityType CPP_11(: Int) +enum RadarPriorityType CPP_11( : Int) { - RADAR_PRIORITY_INVALID, // a priority that has not been set (in general it won't show up on the radar) - RADAR_PRIORITY_NOT_ON_RADAR, // object specifically forbidden from being on the radar - RADAR_PRIORITY_STRUCTURE, // structure level drawing priority - RADAR_PRIORITY_UNIT, // unit level drawing priority - RADAR_PRIORITY_LOCAL_UNIT_ONLY, // unit priority, but only on the radar if controlled by the local player + RADAR_PRIORITY_INVALID, // a priority that has not been set (in general it won't show up on the radar) + RADAR_PRIORITY_NOT_ON_RADAR, // object specifically forbidden from being on the radar + RADAR_PRIORITY_STRUCTURE, // structure level drawing priority + RADAR_PRIORITY_UNIT, // unit level drawing priority + RADAR_PRIORITY_LOCAL_UNIT_ONLY, // unit priority, but only on the radar if controlled by the local player RADAR_PRIORITY_NUM_PRIORITIES }; -#ifdef DEFINE_RADAR_PRIORITY_NAMES -static const char *const RadarPriorityNames[] = -{ - "INVALID", // a priority that has not been set (in general it won't show up on the radar) - "NOT_ON_RADAR", // object specifically forbidden from being on the radar - "STRUCTURE", // structure level drawing priority - "UNIT", // unit level drawing priority - "LOCAL_UNIT_ONLY", // unit priority, but only on the radar if controlled by the local player - nullptr -}; +#ifdef DEFINE_RADAR_PRIORITY_NAMES +static const char* const RadarPriorityNames[] = { + "INVALID", // a priority that has not been set (in general it won't show up on the radar) + "NOT_ON_RADAR", // object specifically forbidden from being on the radar + "STRUCTURE", // structure level drawing priority + "UNIT", // unit level drawing priority + "LOCAL_UNIT_ONLY", // unit priority, but only on the radar if controlled by the local player + + nullptr}; static_assert(ARRAY_SIZE(RadarPriorityNames) == RADAR_PRIORITY_NUM_PRIORITIES + 1, "Incorrect array size"); -#endif // DEFINE_RADAR_PRIOTITY_NAMES +#endif // DEFINE_RADAR_PRIOTITY_NAMES //------------------------------------------------------------------------------------------------- /** Interface for the radar */ @@ -155,54 +150,53 @@ class Radar : public Snapshot, { public: - Radar(); virtual ~Radar() override; - virtual void init() override { } ///< subsystem initialization - virtual void reset() override; ///< subsystem reset - virtual void update() override; ///< subsystem per frame update + virtual void init() override {} ///< subsystem initialization + virtual void reset() override; ///< subsystem reset + virtual void update() override; ///< subsystem per frame update // is the game window parameter the radar window - Bool isRadarWindow( GameWindow *window ) { return (m_radarWindow == window) && (m_radarWindow != nullptr); } + Bool isRadarWindow(GameWindow* window) { return (m_radarWindow == window) && (m_radarWindow != nullptr); } - Bool radarToWorld( const ICoord2D *radar, Coord3D *world ); ///< radar point to world point on terrain - Bool radarToWorld2D( const ICoord2D *radar, Coord3D *world ); ///< radar point to world point (x,y only!) - Bool worldToRadar( const Coord3D *world, ICoord2D *radar ); ///< translate world point to radar (x,y) - Bool localPixelToRadar( const ICoord2D *pixel, ICoord2D *radar ); ///< translate pixel (with UL of radar being (0,0)) to logical radar coordinates - Bool screenPixelToWorld( const ICoord2D *pixel, Coord3D *world ); ///< translate pixel (with UL of the screen being (0,0)) to world position in the world - Object *objectUnderRadarPixel( const ICoord2D *pixel ); ///< return the object (if any) represented by the pixel coordinates passed in - void findDrawPositions( Int startX, Int startY, Int width, Int height, - ICoord2D *ul, ICoord2D *lr ); ///< make translation for screen area of radar square to scaled aspect ratio preserving points inside the radar area + Bool radarToWorld(const ICoord2D* radar, Coord3D* world); ///< radar point to world point on terrain + Bool radarToWorld2D(const ICoord2D* radar, Coord3D* world); ///< radar point to world point (x,y only!) + Bool worldToRadar(const Coord3D* world, ICoord2D* radar); ///< translate world point to radar (x,y) + Bool localPixelToRadar(const ICoord2D* pixel, ICoord2D* radar); ///< translate pixel (with UL of radar being (0,0)) to logical radar coordinates + Bool screenPixelToWorld(const ICoord2D* pixel, Coord3D* world); ///< translate pixel (with UL of the screen being (0,0)) to world position in the world + Object* objectUnderRadarPixel(const ICoord2D* pixel); ///< return the object (if any) represented by the pixel coordinates passed in + void findDrawPositions(Int startX, Int startY, Int width, Int height, + ICoord2D* ul, ICoord2D* lr); ///< make translation for screen area of radar square to scaled aspect ratio preserving points inside the radar area // priority inquiry - static Bool isPriorityVisible( RadarPriorityType priority ); ///< is the priority passed in a "visible" one on the radar + static Bool isPriorityVisible(RadarPriorityType priority); ///< is the priority passed in a "visible" one on the radar // radar events - void createEvent( const Coord3D *world, RadarEventType type, Real secondsToLive = 4.0f ); ///< create radar event at location in world - void createPlayerEvent( Player *player, const Coord3D *world, RadarEventType type, Real secondsToLive = 4.0f ); ///< create radar event using player colors + void createEvent(const Coord3D* world, RadarEventType type, Real secondsToLive = 4.0f); ///< create radar event at location in world + void createPlayerEvent(Player* player, const Coord3D* world, RadarEventType type, Real secondsToLive = 4.0f); ///< create radar event using player colors - Bool getLastEventLoc( Coord3D *eventPos ); ///< get last event loc (if any) - void tryUnderAttackEvent( const Object *obj ); ///< try to make an "under attack" event if it's the proper time - void tryInfiltrationEvent( const Object *obj ); ///< try to make an "infiltration" event if it's the proper time - Bool tryEvent( RadarEventType event, const Coord3D *pos ); ///< try to make a "stealth" event + Bool getLastEventLoc(Coord3D* eventPos); ///< get last event loc (if any) + void tryUnderAttackEvent(const Object* obj); ///< try to make an "under attack" event if it's the proper time + void tryInfiltrationEvent(const Object* obj); ///< try to make an "infiltration" event if it's the proper time + Bool tryEvent(RadarEventType event, const Coord3D* pos); ///< try to make a "stealth" event // adding and removing objects from the radar - virtual Bool addObject( Object *obj ); ///< add object to radar - virtual Bool removeObject( Object *obj ); ///< remove object from radar + virtual Bool addObject(Object* obj); ///< add object to radar + virtual Bool removeObject(Object* obj); ///< remove object from radar // radar options - void hide( Int playerIndex, Bool hide ) { m_radarHidden[playerIndex] = hide; } ///< hide/show the radar - Bool isRadarHidden( Int playerIndex ) { return m_radarHidden[playerIndex]; } ///< is radar hidden + void hide(Int playerIndex, Bool hide) { m_radarHidden[playerIndex] = hide; } ///< hide/show the radar + Bool isRadarHidden(Int playerIndex) { return m_radarHidden[playerIndex]; } ///< is radar hidden // other radar option methods here like the ability to show a certain // team, show buildings, show units at all, etc // forcing the radar on/off regardless of player situation - void forceOn( Int playerIndex, Bool force ) { m_radarForceOn[playerIndex] = force; } ///< force the radar to be on - Bool isRadarForced( Int playerIndex ) { return m_radarForceOn[playerIndex]; } ///< is radar forced on? + void forceOn(Int playerIndex, Bool force) { m_radarForceOn[playerIndex] = force; } ///< force the radar to be on + Bool isRadarForced(Int playerIndex) { return m_radarForceOn[playerIndex]; } ///< is radar forced on? /// refresh the water values for the radar - virtual void refreshTerrain( TerrainLogic *terrain ); + virtual void refreshTerrain(TerrainLogic* terrain); /// refresh the radar when the state of world objects changes drastically virtual void refreshObjects() {}; @@ -210,57 +204,56 @@ class Radar : public Snapshot, /// queue a refresh of the terrain at the next available time virtual void queueTerrainRefresh(); - virtual void newMap( TerrainLogic *terrain ); ///< reset radar for new map + virtual void newMap(TerrainLogic* terrain); ///< reset radar for new map - virtual void draw( Int pixelX, Int pixelY, Int width, Int height ) = 0; ///< draw the radar + virtual void draw(Int pixelX, Int pixelY, Int width, Int height) = 0; ///< draw the radar /// empty the entire shroud virtual void clearShroud() = 0; /// TheSuperHackers @performance xezon 20/12/2025 Provides beginSetShroudLevel and endSetShroudLevel to improve performance. /// Calling setShroudLevel many times is very expensive because it will lock a render resource on every call. - virtual void setShroudLevel( Int x, Int y, CellShroudStatus setting ) = 0; ///< set the shroud level at shroud cell x,y - virtual void beginSetShroudLevel() {} ///< call this once before multiple calls to setShroudLevel for better performance - virtual void endSetShroudLevel() {} ///< call this once after beginSetShroudLevel and setShroudLevel + virtual void setShroudLevel(Int x, Int y, CellShroudStatus setting) = 0; ///< set the shroud level at shroud cell x,y + virtual void beginSetShroudLevel() {} ///< call this once before multiple calls to setShroudLevel for better performance + virtual void endSetShroudLevel() {} ///< call this once after beginSetShroudLevel and setShroudLevel - virtual void notifyViewChanged() {} ///< signals that the camera view has changed + virtual void notifyViewChanged() {} ///< signals that the camera view has changed protected: - // snapshot methods - virtual void crc( Xfer *xfer ) override; - virtual void xfer( Xfer *xfer ) override; + virtual void crc(Xfer* xfer) override; + virtual void xfer(Xfer* xfer) override; virtual void loadPostProcess() override; /// internal method for creating a radar event with specific colors - void internalCreateEvent( const Coord3D *world, RadarEventType type, Real secondsToLive, - const RGBAColorInt *color1, const RGBAColorInt *color2 ); + void internalCreateEvent(const Coord3D* world, RadarEventType type, Real secondsToLive, + const RGBAColorInt* color1, const RGBAColorInt* color2); - void deleteList( RadarObject **list ); - void deleteListResources(); ///< delete list radar resources used - Bool deleteFromList( Object *obj, RadarObject **list ); ///< try to remove object from specific list + void deleteList(RadarObject** list); + void deleteListResources(); ///< delete list radar resources used + Bool deleteFromList(Object* obj, RadarObject** list); ///< try to remove object from specific list Real getTerrainAverageZ() const { return m_terrainAverageZ; } Real getWaterAverageZ() const { return m_waterAverageZ; } - void clearAllEvents(); ///< remove all radar events in progress + void clearAllEvents(); ///< remove all radar events in progress // search the object list for an object that maps to the given logical radar coordinates - Object *searchListForRadarLocationMatch( RadarObject *listHead, ICoord2D *radarMatch ); + Object* searchListForRadarLocationMatch(RadarObject* listHead, ICoord2D* radarMatch); - void linkRadarObject( RadarObject *newObj, RadarObject **list ); - void assignObjectColorToRadarObject( RadarObject *radarObj, Object *obj ); + void linkRadarObject(RadarObject* newObj, RadarObject** list); + void assignObjectColorToRadarObject(RadarObject* radarObj, Object* obj); - Bool m_radarHidden[MAX_PLAYER_COUNT]; ///< true when radar is not visible - Bool m_radarForceOn[MAX_PLAYER_COUNT]; ///< true when radar is forced to be on + Bool m_radarHidden[MAX_PLAYER_COUNT]; ///< true when radar is not visible + Bool m_radarForceOn[MAX_PLAYER_COUNT]; ///< true when radar is forced to be on - RadarObject *m_objectList; ///< list of objects in the radar - RadarObject *m_localObjectList; /** list of objects for the local player, sorted - * in exactly the same priority as the regular - * object list for all other objects */ + RadarObject* m_objectList; ///< list of objects in the radar + RadarObject* m_localObjectList; /** list of objects for the local player, sorted + * in exactly the same priority as the regular + * object list for all other objects */ - Real m_terrainAverageZ; ///< average Z for terrain samples - Real m_waterAverageZ; ///< average Z for water samples + Real m_terrainAverageZ; ///< average Z for terrain samples + Real m_waterAverageZ; ///< average Z for water samples // // when dealing with world sampling we will sample at these intervals so that @@ -270,41 +263,43 @@ class Radar : public Snapshot, Real m_xSample; Real m_ySample; - enum { MAX_RADAR_EVENTS = 64 }; + enum + { + MAX_RADAR_EVENTS = 64 + }; struct RadarEvent { - RadarEventType type; ///< type of this radar event - Bool active; ///< TRUE when event is "active", otherwise it's just historical information in the event array to look through - UnsignedInt createFrame; ///< frame event was created on - UnsignedInt dieFrame; ///< frame the event will go away on - UnsignedInt fadeFrame; ///< start fading out on this frame - RGBAColorInt color1; ///< color 1 for drawing - RGBAColorInt color2; ///< color 2 for drawing - Coord3D worldLoc; ///< location of event in the world - ICoord2D radarLoc; ///< 2D radar location of the event - Bool soundPlayed; ///< TRUE when we have played the radar sound for this + RadarEventType type; ///< type of this radar event + Bool active; ///< TRUE when event is "active", otherwise it's just historical information in the event array to look through + UnsignedInt createFrame; ///< frame event was created on + UnsignedInt dieFrame; ///< frame the event will go away on + UnsignedInt fadeFrame; ///< start fading out on this frame + RGBAColorInt color1; ///< color 1 for drawing + RGBAColorInt color2; ///< color 2 for drawing + Coord3D worldLoc; ///< location of event in the world + ICoord2D radarLoc; ///< 2D radar location of the event + Bool soundPlayed; ///< TRUE when we have played the radar sound for this }; - RadarEvent m_event[ MAX_RADAR_EVENTS ];///< our radar events - Int m_nextFreeRadarEvent; ///< index into m_event for where to store the next event - Int m_lastRadarEvent; ///< index of the most recent radar event - - GameWindow *m_radarWindow; ///< window we display the radar in + RadarEvent m_event[MAX_RADAR_EVENTS]; ///< our radar events + Int m_nextFreeRadarEvent; ///< index into m_event for where to store the next event + Int m_lastRadarEvent; ///< index of the most recent radar event - Region3D m_mapExtent; ///< extents of the current map + GameWindow* m_radarWindow; ///< window we display the radar in - UnsignedInt m_queueTerrainRefreshFrame; ///< frame we requested the last terrain refresh on + Region3D m_mapExtent; ///< extents of the current map + UnsignedInt m_queueTerrainRefreshFrame; ///< frame we requested the last terrain refresh on }; // EXTERNALS ////////////////////////////////////////////////////////////////////////////////////// -extern Radar *TheRadar; ///< the radar singleton extern +extern Radar* TheRadar; ///< the radar singleton extern // TheSuperHackers @feature helmutbuhler 10/04/2025 // Radar that does nothing. Used for Headless Mode. class RadarDummy : public Radar { public: - virtual void draw(Int pixelX, Int pixelY, Int width, Int height) override { } - virtual void clearShroud() override { } - virtual void setShroudLevel(Int x, Int y, CellShroudStatus setting) override { } + virtual void draw(Int pixelX, Int pixelY, Int width, Int height) override {} + virtual void clearShroud() override {} + virtual void setShroudLevel(Int x, Int y, CellShroudStatus setting) override {} }; diff --git a/Core/GameEngine/Include/Common/RandomValue.h b/Core/GameEngine/Include/Common/RandomValue.h index 8cc97d5d844..7bf0e9d52a2 100644 --- a/Core/GameEngine/Include/Common/RandomValue.h +++ b/Core/GameEngine/Include/Common/RandomValue.h @@ -31,8 +31,8 @@ #include "Lib/BaseType.h" extern void InitRandom(); -extern void InitRandom( UnsignedInt seed ); -extern UnsignedInt GetGameLogicRandomSeed(); ///< Get the seed (used for replays) -extern UnsignedInt GetGameLogicRandomSeedCRC();///< Get the seed (used for CRCs) +extern void InitRandom(UnsignedInt seed); +extern UnsignedInt GetGameLogicRandomSeed(); ///< Get the seed (used for replays) +extern UnsignedInt GetGameLogicRandomSeedCRC(); ///< Get the seed (used for CRCs) //-------------------------------------------------------------------------------------------------------------- diff --git a/Core/GameEngine/Include/Common/ReplaySimulation.h b/Core/GameEngine/Include/Common/ReplaySimulation.h index 219f6233709..93774a8d069 100644 --- a/Core/GameEngine/Include/Common/ReplaySimulation.h +++ b/Core/GameEngine/Include/Common/ReplaySimulation.h @@ -21,12 +21,11 @@ class ReplaySimulation { public: - // TheSuperHackers @feature helmutbuhler 13/04/2025 // Simulate a list of replays without graphics. // Returns exit code 1 if mismatch or other error occurred // Returns exit code 0 if all replays were successfully simulated without mismatches - static int simulateReplays(const std::vector &filenames, int maxProcesses); + static int simulateReplays(const std::vector& filenames, int maxProcesses); static void stop() { s_isRunning = false; } @@ -35,13 +34,11 @@ class ReplaySimulation static UnsignedInt getReplayCount() { return s_replayCount; } private: - - static int simulateReplaysInThisProcess(const std::vector &filenames); - static int simulateReplaysInWorkerProcesses(const std::vector &filenames, int maxProcesses); - static std::vector resolveFilenameWildcards(const std::vector &filenames); + static int simulateReplaysInThisProcess(const std::vector& filenames); + static int simulateReplaysInWorkerProcesses(const std::vector& filenames, int maxProcesses); + static std::vector resolveFilenameWildcards(const std::vector& filenames); private: - static Bool s_isRunning; static UnsignedInt s_replayIndex; static UnsignedInt s_replayCount; diff --git a/Core/GameEngine/Include/Common/STLTypedefs.h b/Core/GameEngine/Include/Common/STLTypedefs.h index 0dc2ede1dc3..4080e3eba72 100644 --- a/Core/GameEngine/Include/Common/STLTypedefs.h +++ b/Core/GameEngine/Include/Common/STLTypedefs.h @@ -46,8 +46,8 @@ //----------------------------------------------------------------------------- // srj sez: this must come first, first, first. -#define _STLP_USE_NEWALLOC 1 -//#define _STLP_USE_CUSTOM_NEWALLOC STLSpecialAlloc +#define _STLP_USE_NEWALLOC 1 +// #define _STLP_USE_CUSTOM_NEWALLOC STLSpecialAlloc class STLSpecialAlloc; //----------------------------------------------------------------------------- @@ -58,13 +58,12 @@ class STLSpecialAlloc; //----------------------------------------------------------------------------- - // FORWARD DECLARATIONS class Object; -enum NameKeyType CPP_11(: Int); -enum ObjectID CPP_11(: Int); -enum DrawableID CPP_11(: Int); -enum ParticleSystemID CPP_11(: Int); +enum NameKeyType CPP_11( : Int); +enum ObjectID CPP_11( : Int); +enum DrawableID CPP_11( : Int); +enum ParticleSystemID CPP_11( : Int); #include #include @@ -79,231 +78,246 @@ enum ParticleSystemID CPP_11(: Int); #include // List of AsciiStrings to allow list of ThingTemplate names from INI and such -typedef std::list< AsciiString > AsciiStringList; -typedef std::list< AsciiString >::iterator AsciiStringListIterator; -typedef std::list< AsciiString >::const_iterator AsciiStringListConstIterator; +typedef std::list AsciiStringList; +typedef std::list::iterator AsciiStringListIterator; +typedef std::list::const_iterator AsciiStringListConstIterator; // One is used in GameLogic to keep track of objects to be destroyed -typedef std::list ObjectPointerList; -typedef std::list::iterator ObjectPointerListIterator; +typedef std::list ObjectPointerList; +typedef std::list::iterator ObjectPointerListIterator; -typedef std::vector ObjectIDVector; -typedef std::vector::iterator ObjectIDVectorIterator; +typedef std::vector ObjectIDVector; +typedef std::vector::iterator ObjectIDVectorIterator; // Terribly useful, especially with Bezier curves typedef std::vector VecCoord3D; typedef VecCoord3D::iterator VecCoord3DIt; // Used for cursor->3D position request caching in the heightmap -typedef std::pair PosRequest; -typedef std::vector VecPosRequests; -typedef std::vector::iterator VecPosRequestsIt; +typedef std::pair PosRequest; +typedef std::vector VecPosRequests; +typedef std::vector::iterator VecPosRequestsIt; // Used to cache off names of objects for faster lookup -typedef std::pair NamedRequest; -typedef std::vector VecNamedRequests; -typedef std::vector::iterator VecNamedRequestsIt; +typedef std::pair NamedRequest; +typedef std::vector VecNamedRequests; +typedef std::vector::iterator VecNamedRequestsIt; // Rumor has it that a Vector of Bools gets stored as a bitfield internally. -typedef std::vector BoolVector; -typedef std::vector::iterator BoolVectorIterator; +typedef std::vector BoolVector; +typedef std::vector::iterator BoolVectorIterator; -typedef std::map< NameKeyType, Real, std::less > ProductionChangeMap; -typedef std::map< NameKeyType, VeterancyLevel, std::less > ProductionVeterancyMap; +// clang-format off: [LEGACY_VC6] - preserve space in nested templates (> >) +typedef std::map > ProductionChangeMap; +typedef std::map > ProductionVeterancyMap; +// clang-format on // Some useful, common hash and equal_to functors for use with hash_map namespace rts { - // Generic hash functor. This should almost always be overridden for - // specific types. - template struct hash +// Generic hash functor. This should almost always be overridden for +// specific types. +template +struct hash +{ + size_t operator()(const T& __t) const { - size_t operator()(const T& __t) const - { - std::hash tmp; - return tmp(__t); - } - }; - - // Generic equal_to functor. This should be overridden if there is no - // operator==, or if that isn't the behavior desired. (For instance, in - // the case of pointers.) - template struct equal_to + std::hash tmp; + return tmp(__t); + } +}; + +// Generic equal_to functor. This should be overridden if there is no +// operator==, or if that isn't the behavior desired. (For instance, in +// the case of pointers.) +template +struct equal_to +{ + Bool operator()(const T& __t1, const T& __t2) const { - Bool operator()(const T& __t1, const T& __t2) const - { - return (__t1 == __t2); - } - }; - - // Generic less_than_nocase functor. This should be overridden if there is no - // operator<, or if that isn't the behavior desired. (For instance, in - // the case of pointers, or strings.) - template struct less_than_nocase + return (__t1 == __t2); + } +}; + +// Generic less_than_nocase functor. This should be overridden if there is no +// operator<, or if that isn't the behavior desired. (For instance, in +// the case of pointers, or strings.) +template +struct less_than_nocase +{ + bool operator()(const T& __t1, const T& __t2) const { - bool operator()(const T& __t1, const T& __t2) const - { - return (__t1 < __t2); - } - }; + return (__t1 < __t2); + } +}; #ifdef USING_STLPORT - template<> struct hash +template <> +struct hash +{ + size_t operator()(NameKeyType nkt) const { - size_t operator()(NameKeyType nkt) const - { - std::hash tmp; - return tmp((UnsignedInt)nkt); - } - }; - - template<> struct hash + std::hash tmp; + return tmp((UnsignedInt)nkt); + } +}; + +template <> +struct hash +{ + size_t operator()(DrawableID nkt) const { - size_t operator()(DrawableID nkt) const - { - std::hash tmp; - return tmp((UnsignedInt)nkt); - } - }; - - template<> struct hash + std::hash tmp; + return tmp((UnsignedInt)nkt); + } +}; + +template <> +struct hash +{ + size_t operator()(ObjectID nkt) const { - size_t operator()(ObjectID nkt) const - { - std::hash tmp; - return tmp((UnsignedInt)nkt); - } - }; - - template<> struct hash + std::hash tmp; + return tmp((UnsignedInt)nkt); + } +}; + +template <> +struct hash +{ + size_t operator()(ParticleSystemID nkt) const { - size_t operator()(ParticleSystemID nkt) const - { - std::hash tmp; - return tmp((UnsignedInt)nkt); - } - }; -#endif // USING_STLPORT - - template<> struct hash + std::hash tmp; + return tmp((UnsignedInt)nkt); + } +}; +#endif // USING_STLPORT + +template <> +struct hash +{ + size_t operator()(const Char* s) const { - size_t operator()(const Char* s) const - { #ifdef USING_STLPORT - std::hash hasher; - return hasher(s); + std::hash hasher; + return hasher(s); #else - std::hash hasher; - return hasher(s); + std::hash hasher; + return hasher(s); #endif - } - }; - - // This is the equal_to overload for char* comparisons. We compare the - // strings to determine whether they are equal or not. - // Other overloads should go into specific header files, not here (unless - // they are to be used in lots of places.) - template<> struct equal_to + } +}; + +// This is the equal_to overload for char* comparisons. We compare the +// strings to determine whether they are equal or not. +// Other overloads should go into specific header files, not here (unless +// they are to be used in lots of places.) +template <> +struct equal_to +{ + Bool operator()(const char* s1, const char* s2) const { - Bool operator()(const char* s1, const char* s2) const - { - return strcmp(s1, s2) == 0; - } - }; + return strcmp(s1, s2) == 0; + } +}; - template<> struct hash +template <> +struct hash +{ + size_t operator()(const AsciiString& ast) const { - size_t operator()(const AsciiString& ast) const - { #ifdef USING_STLPORT - std::hash tmp; - return tmp((const char *) ast.str()); + std::hash tmp; + return tmp((const char*)ast.str()); #else - // TheSuperHackers @bugfix xezon 16/03/2024 Re-implements hash function that works with non-STLPort. - std::hash hasher; - return hasher(std::string_view(ast.str(), ast.getLength())); + // TheSuperHackers @bugfix xezon 16/03/2024 Re-implements hash function that works with non-STLPort. + std::hash hasher; + return hasher(std::string_view(ast.str(), ast.getLength())); #endif - } - }; + } +}; - template<> struct equal_to +template <> +struct equal_to +{ + Bool operator()(const AsciiString& __t1, const AsciiString& __t2) const { - Bool operator()(const AsciiString& __t1, const AsciiString& __t2) const - { - return (__t1 == __t2); - } - }; + return (__t1 == __t2); + } +}; - template<> struct less_than_nocase +template <> +struct less_than_nocase +{ + bool operator()(const AsciiString& __t1, const AsciiString& __t2) const { - bool operator()(const AsciiString& __t1, const AsciiString& __t2) const - { - return (__t1.compareNoCase(__t2) < 0); - } - }; + return (__t1.compareNoCase(__t2) < 0); + } +}; - template<> struct less_than_nocase +template <> +struct less_than_nocase +{ + bool operator()(const UnicodeString& __t1, const UnicodeString& __t2) const { - bool operator()(const UnicodeString& __t1, const UnicodeString& __t2) const - { - return (__t1.compareNoCase(__t2) < 0); - } - }; - - // TheSuperHackers @info Structs to help create maps that can use C strings for - // lookups without the need to allocate a string. - template - struct string_key + return (__t1.compareNoCase(__t2) < 0); + } +}; + +// TheSuperHackers @info Structs to help create maps that can use C strings for +// lookups without the need to allocate a string. +template +struct string_key +{ + typedef typename String::const_pointer const_pointer; + + static string_key temporary(const_pointer s) { - typedef typename String::const_pointer const_pointer; - - static string_key temporary(const_pointer s) - { - string_key key; - key.cstr = s; - return key; - } - - string_key(const_pointer s) - : storage(s) - , cstr(storage.str()) - {} - - string_key(const String& s) - : storage(s) - , cstr(storage.str()) - {} - - const_pointer c_str() const - { - return cstr; - } - - private: - string_key() {} - - String storage; - const_pointer cstr; - }; - - template - struct string_key_hash + string_key key; + key.cstr = s; + return key; + } + + string_key(const_pointer s) + : storage(s) + , cstr(storage.str()) + {} + + string_key(const String& s) + : storage(s) + , cstr(storage.str()) + {} + + const_pointer c_str() const { - typedef typename String::const_pointer const_pointer; - size_t operator()(const string_key& key) const - { - return hash()(key.c_str()); - } - }; - - template - struct string_key_equal + return cstr; + } + +private: + string_key() {} + + String storage; + const_pointer cstr; +}; + +template +struct string_key_hash +{ + typedef typename String::const_pointer const_pointer; + size_t operator()(const string_key& key) const + { + return hash()(key.c_str()); + } +}; + +template +struct string_key_equal +{ + bool operator()(const string_key& a, const string_key& b) const { - bool operator()(const string_key& a, const string_key& b) const - { - return strcmp(a.c_str(), b.c_str()) == 0; - } - }; + return strcmp(a.c_str(), b.c_str()) == 0; + } +}; -} // namespace rts +} // namespace rts diff --git a/Core/GameEngine/Include/Common/Snapshot.h b/Core/GameEngine/Include/Common/Snapshot.h index fa223c6802d..2aa47ffb330 100644 --- a/Core/GameEngine/Include/Common/Snapshot.h +++ b/Core/GameEngine/Include/Common/Snapshot.h @@ -41,27 +41,24 @@ class Xfer; class Snapshot { -friend class GameState; -friend class XferLoad; -friend class XferSave; -friend class XferCRC; + friend class GameState; + friend class XferLoad; + friend class XferSave; + friend class XferCRC; public: - Snapshot(); ~Snapshot(); protected: - /// run the "light" crc check on this data structure - virtual void crc( Xfer *xfer ) = 0; + virtual void crc(Xfer* xfer) = 0; /** run save, load, or deep CRC check on this data structure, the type depends on the setup of the Xfer pointer */ - virtual void xfer( Xfer *xfer ) = 0; + virtual void xfer(Xfer* xfer) = 0; /** post process phase for loading save games. All save systems have their xfer run using XferLoad mode, and then all systems each have their post process run */ virtual void loadPostProcess() = 0; - }; diff --git a/Core/GameEngine/Include/Common/StreamingArchiveFile.h b/Core/GameEngine/Include/Common/StreamingArchiveFile.h index 72e3057afef..fab52eed647 100644 --- a/Core/GameEngine/Include/Common/StreamingArchiveFile.h +++ b/Core/GameEngine/Include/Common/StreamingArchiveFile.h @@ -53,8 +53,6 @@ // Forward References //---------------------------------------------------------------------------- - - //---------------------------------------------------------------------------- // Type Defines //---------------------------------------------------------------------------- @@ -63,49 +61,67 @@ // StreamingArchiveFile //=============================== /** - * File abstraction for standard C file operators: open, close, lseek, read, write - */ + * File abstraction for standard C file operators: open, close, lseek, read, write + */ //=============================== class StreamingArchiveFile : public RAMFile { MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(StreamingArchiveFile, "StreamingArchiveFile") - protected: - - File *m_file; ///< The archive file that I came from - Int m_startingPos; ///< My starting position in the archive - Int m_size; ///< My length - Int m_curPos; ///< My current position. - - public: - - StreamingArchiveFile(); - //virtual ~StreamingArchiveFile(); - - - virtual Bool open( const Char *filename, Int access = NONE, size_t bufferSize = BUFFERSIZE ) override; ///< Open a file for access - virtual void close() override; ///< Close the file - virtual Int read( void *buffer, Int bytes ) override; ///< Read the specified number of bytes in to buffer: See File::read - virtual Int write( const void *buffer, Int bytes ) override; ///< Write the specified number of bytes from the buffer: See File::write - virtual Int seek( Int new_pos, seekMode mode = CURRENT ) override; ///< Set file position: See File::seek - - // Ini's should not be parsed with streaming files, that's just dumb. - virtual void nextLine(Char *buf = nullptr, Int bufSize = 0) override { DEBUG_CRASH(("Should not call nextLine on a streaming file.")); } - virtual Bool scanInt(Int &newInt) override { DEBUG_CRASH(("Should not call scanInt on a streaming file.")); return FALSE; } - virtual Bool scanReal(Real &newReal) override { DEBUG_CRASH(("Should not call scanReal on a streaming file.")); return FALSE; } - virtual Bool scanString(AsciiString &newString) override { DEBUG_CRASH(("Should not call scanString on a streaming file.")); return FALSE; } - - virtual Bool open( File *file ) override; ///< Open file for fast RAM access - virtual Bool openFromArchive(File *archiveFile, const AsciiString& filename, Int offset, Int size) override; ///< copy file data from the given file at the given offset for the given size. - virtual Bool copyDataToFile(File *localFile) override { DEBUG_CRASH(("Are you sure you meant to copyDataToFile on a streaming file?")); return FALSE; } - - virtual char* readEntireAndClose() override { DEBUG_CRASH(("Are you sure you meant to readEntireAndClose on a streaming file?")); return nullptr; } - virtual File* convertToRAMFile() override { DEBUG_CRASH(("Are you sure you meant to readEntireAndClose on a streaming file?")); return this; } +protected: + File* m_file; ///< The archive file that I came from + Int m_startingPos; ///< My starting position in the archive + Int m_size; ///< My length + Int m_curPos; ///< My current position. + +public: + StreamingArchiveFile(); + // virtual ~StreamingArchiveFile(); + + virtual Bool open(const Char* filename, Int access = NONE, size_t bufferSize = BUFFERSIZE) override; ///< Open a file for access + virtual void close() override; ///< Close the file + virtual Int read(void* buffer, Int bytes) override; ///< Read the specified number of bytes in to buffer: See File::read + virtual Int write(const void* buffer, Int bytes) override; ///< Write the specified number of bytes from the buffer: See File::write + virtual Int seek(Int new_pos, seekMode mode = CURRENT) override; ///< Set file position: See File::seek + + // Ini's should not be parsed with streaming files, that's just dumb. + virtual void nextLine(Char* buf = nullptr, Int bufSize = 0) override { DEBUG_CRASH(("Should not call nextLine on a streaming file.")); } + virtual Bool scanInt(Int& newInt) override + { + DEBUG_CRASH(("Should not call scanInt on a streaming file.")); + return FALSE; + } + virtual Bool scanReal(Real& newReal) override + { + DEBUG_CRASH(("Should not call scanReal on a streaming file.")); + return FALSE; + } + virtual Bool scanString(AsciiString& newString) override + { + DEBUG_CRASH(("Should not call scanString on a streaming file.")); + return FALSE; + } + + virtual Bool open(File* file) override; ///< Open file for fast RAM access + virtual Bool openFromArchive(File* archiveFile, const AsciiString& filename, Int offset, Int size) override; ///< copy file data from the given file at the given offset for the given size. + virtual Bool copyDataToFile(File* localFile) override + { + DEBUG_CRASH(("Are you sure you meant to copyDataToFile on a streaming file?")); + return FALSE; + } + + virtual char* readEntireAndClose() override + { + DEBUG_CRASH(("Are you sure you meant to readEntireAndClose on a streaming file?")); + return nullptr; + } + virtual File* convertToRAMFile() override + { + DEBUG_CRASH(("Are you sure you meant to readEntireAndClose on a streaming file?")); + return this; + } }; - - - //---------------------------------------------------------------------------- // Inlining //---------------------------------------------------------------------------- diff --git a/Core/GameEngine/Include/Common/SubsystemInterface.h b/Core/GameEngine/Include/Common/SubsystemInterface.h index fba66ec1203..ae147d629b2 100644 --- a/Core/GameEngine/Include/Common/SubsystemInterface.h +++ b/Core/GameEngine/Include/Common/SubsystemInterface.h @@ -36,88 +36,87 @@ class Xfer; //------------------------------------------------------------------------------------------------- /** This is the abstract base class from which all game engine subsystems should derive from. - * In order to provide consistent behaviors across all these systems, any implementation - * must obey the rules defined in here - * - * Nothing about the subsystems is automatic, this interface does not wrap up automated - * functions, it is only here to provide a basic interface and rules for behavior - * all subsystems - */ + * In order to provide consistent behaviors across all these systems, any implementation + * must obey the rules defined in here + * + * Nothing about the subsystems is automatic, this interface does not wrap up automated + * functions, it is only here to provide a basic interface and rules for behavior + * all subsystems + */ class SubsystemInterface { public: - //----------------------------------------------------------------------------------------------- /** - Constructors should initialize any data to a valid state. That DOES NOT mean - * the data has default values (something done in the init() method), only that - * nothing is left pointing to garbage, un-initialized memory. In most cases - * this probably means just setting members to zero or nullptr. - */ + * the data has default values (something done in the init() method), only that + * nothing is left pointing to garbage, un-initialized memory. In most cases + * this probably means just setting members to zero or nullptr. + */ SubsystemInterface(); //----------------------------------------------------------------------------------------------- /** - Free any resources allocated for this class. - * - * - DO NOT throw exceptions during any destruction ever, and do not call other - * methods that have the possibility of throwing exceptions. Try to keep it - * simple and keep as much work actually inside the destructor as possible. - */ + * + * - DO NOT throw exceptions during any destruction ever, and do not call other + * methods that have the possibility of throwing exceptions. Try to keep it + * simple and keep as much work actually inside the destructor as possible. + */ virtual ~SubsystemInterface(); //----------------------------------------------------------------------------------------------- /** - Assign any default values to data required for the class - * - * - Allocate any memory and resources needed throughout the lifetime of the class - */ + * + * - Allocate any memory and resources needed throughout the lifetime of the class + */ virtual void init() = 0; //----------------------------------------------------------------------------------------------- /** - Called for all subsystems after all other Subsystems are inited. - * (allows for initializing inter-system dependencies) - */ - virtual void postProcessLoad() { } + * (allows for initializing inter-system dependencies) + */ + virtual void postProcessLoad() {} //----------------------------------------------------------------------------------------------- /** - Any system should be able to reset all data and go back to an empty state - * that is ready to accept a completely new set of data. Reset() can expect - * to be used in the context of resetting the engine in order to start or - * load a new game. - * - * - Do NOT free and re-allocate resources needed, where possible reorganize and - * re-initialize the resources already allocated. - * - * - After a reset, the system does not need to be in EXACTLY the same state as a - * fresh instantiation. If there are persistent state information for the - * system make sure you maintain it while restoring or re-initializing other - * transient parts. - */ + * that is ready to accept a completely new set of data. Reset() can expect + * to be used in the context of resetting the engine in order to start or + * load a new game. + * + * - Do NOT free and re-allocate resources needed, where possible reorganize and + * re-initialize the resources already allocated. + * + * - After a reset, the system does not need to be in EXACTLY the same state as a + * fresh instantiation. If there are persistent state information for the + * system make sure you maintain it while restoring or re-initializing other + * transient parts. + */ virtual void reset() = 0; //----------------------------------------------------------------------------------------------- /** - Update methods are the place to do system per frame processing. You - * should call the system update once each time through the game loop - * to service the system. - * - * - Note that currently the GameClient and GameLogic will be updating - * at different rates where the logic is running real time, and the - * client will adjust how many loops can be done during one server - * time slice in order to improve performance on low end machines. - */ + * should call the system update once each time through the game loop + * to service the system. + * + * - Note that currently the GameClient and GameLogic will be updating + * at different rates where the logic is running real time, and the + * client will adjust how many loops can be done during one server + * time slice in order to improve performance on low end machines. + */ virtual void update() = 0; - - virtual void draw(){DEBUG_CRASH(("Shouldn't call base class. jba."));} + virtual void draw() { DEBUG_CRASH(("Shouldn't call base class. jba.")); } #ifdef DUMP_PERF_STATS void UPDATE(); void DRAW(); - Real getUpdateTime() {return m_curUpdateTime;} - Real getDrawTime() {return m_curDrawTime;} - Bool doDumpUpdate() {return m_dumpUpdate;} - Bool doDumpDraw() {return m_dumpDraw;} - static Real getTotalTime() {return s_msConsumed;} - static void clearTotalTime() {s_msConsumed = 0;} + Real getUpdateTime() { return m_curUpdateTime; } + Real getDrawTime() { return m_curDrawTime; } + Bool doDumpUpdate() { return m_dumpUpdate; } + Bool doDumpDraw() { return m_dumpDraw; } + static Real getTotalTime() { return s_msConsumed; } + static void clearTotalTime() { s_msConsumed = 0; } + protected: static Real s_msConsumed; Real m_startTimeConsumed; @@ -128,26 +127,25 @@ class SubsystemInterface Bool m_dumpUpdate; Bool m_dumpDraw; #else - void UPDATE() {update();} - void DRAW() {draw();} + void UPDATE() { update(); } + void DRAW() { draw(); } #endif protected: AsciiString m_name; -public: - AsciiString getName() {return m_name;} - void setName(AsciiString name) {m_name = name;} +public: + AsciiString getName() { return m_name; } + void setName(AsciiString name) { m_name = name; } }; //------------------------------------------------------------------------------------------------- class SubsystemInterfaceList { public: - SubsystemInterfaceList(); ~SubsystemInterfaceList(); - void initSubsystem(SubsystemInterface* sys, const char* path1, const char* path2, Xfer *pXfer, AsciiString name=""); + void initSubsystem(SubsystemInterface* sys, const char* path1, const char* path2, Xfer* pXfer, AsciiString name = ""); void addSubsystem(SubsystemInterface* sys); void removeSubsystem(SubsystemInterface* sys); void postProcessLoadAll(); @@ -158,11 +156,9 @@ class SubsystemInterfaceList #endif private: - typedef std::vector SubsystemList; SubsystemList m_subsystems; SubsystemList m_allSubsystems; - }; extern SubsystemInterfaceList* TheSubsystemList; diff --git a/Core/GameEngine/Include/Common/UnicodeString.h b/Core/GameEngine/Include/Common/UnicodeString.h index a6fbcab367e..8ba9518f4d8 100644 --- a/Core/GameEngine/Include/Common/UnicodeString.h +++ b/Core/GameEngine/Include/Common/UnicodeString.h @@ -54,190 +54,187 @@ class AsciiString; // ----------------------------------------------------- /** - UnicodeString is the fundamental double-byte string type used in the Generals - code base, and should be preferred over all other string constructions - (e.g., array of WideChar, STL string<>, WWVegas StringClass, etc.) + UnicodeString is the fundamental double-byte string type used in the Generals + code base, and should be preferred over all other string constructions + (e.g., array of WideChar, STL string<>, WWVegas StringClass, etc.) - Of course, other string setups may be used when necessary or appropriate! + Of course, other string setups may be used when necessary or appropriate! - UnicodeString is modeled after the MFC CString class, with some minor - syntactic differences to keep in line with our coding conventions. + UnicodeString is modeled after the MFC CString class, with some minor + syntactic differences to keep in line with our coding conventions. - Basically, UnicodeString allows you to treat a string as an intrinsic - type, rather analogous to 'int' -- when passed by value, a new string - is created, and modifying the new string doesn't modify the original. - This is done fairly efficiently, so that no new memory allocation is done - unless the string is actually modified. + Basically, UnicodeString allows you to treat a string as an intrinsic + type, rather analogous to 'int' -- when passed by value, a new string + is created, and modifying the new string doesn't modify the original. + This is done fairly efficiently, so that no new memory allocation is done + unless the string is actually modified. - Naturally, UnicodeString handles all memory issues, so there's no need - to do anything to free memory... just allow the UnicodeString's - destructor to run. + Naturally, UnicodeString handles all memory issues, so there's no need + to do anything to free memory... just allow the UnicodeString's + destructor to run. - UnicodeStrings are suitable for use as automatic, member, or static variables. + UnicodeStrings are suitable for use as automatic, member, or static variables. */ class UnicodeString { private: - // Note, this is a Plain Old Data Structure... don't // add a ctor/dtor, 'cuz they won't ever be called. struct UnicodeStringData { #if defined(RTS_DEBUG) - const WideChar* m_debugptr; // just makes it easier to read in the debugger + const WideChar* m_debugptr; // just makes it easier to read in the debugger #endif - unsigned short m_refCount; // reference count - unsigned short m_numCharsAllocated; // length of data allocated + unsigned short m_refCount; // reference count + unsigned short m_numCharsAllocated; // length of data allocated // WideChar m_stringdata[]; - WideChar* peek() { return (WideChar*)(this+1); } + WideChar* peek() { return (WideChar*)(this + 1); } }; - #ifdef RTS_DEBUG +#ifdef RTS_DEBUG void validate() const; - #else - void validate() const { } - #endif +#else + void validate() const {} +#endif protected: - UnicodeStringData* m_data; // pointer to ref counted string data + UnicodeStringData* m_data; // pointer to ref counted string data WideChar* peek() const; void releaseBuffer(); void ensureUniqueBufferOfSize(int numCharsNeeded, Bool preserveData, const WideChar* strToCpy, const WideChar* strToCat); public: - typedef WideChar value_type; typedef value_type* pointer; typedef const value_type* const_pointer; enum { - MAX_FORMAT_BUF_LEN = 2048, ///< max total len of string created by format/format_va - MAX_LEN = 32767 ///< max total len of any UnicodeString, in chars + MAX_FORMAT_BUF_LEN = 2048, ///< max total len of string created by format/format_va + MAX_LEN = 32767 ///< max total len of any UnicodeString, in chars }; - /** - This is a convenient global used to indicate the empty - string, so we don't need to construct temporaries - for such a common thing. + This is a convenient global used to indicate the empty + string, so we don't need to construct temporaries + for such a common thing. */ static const UnicodeString TheEmptyString; /** - Default constructor -- construct a new, empty UnicodeString. + Default constructor -- construct a new, empty UnicodeString. */ UnicodeString(); /** - Copy constructor -- make this UnicodeString identical to the - other UnicodeString. (This is actually quite efficient, because - they will simply share the same string and increment the - refcount.) + Copy constructor -- make this UnicodeString identical to the + other UnicodeString. (This is actually quite efficient, because + they will simply share the same string and increment the + refcount.) */ UnicodeString(const UnicodeString& stringSrc); /** - Constructor -- from a literal string. Constructs an UnicodeString - with the given string. Note that a copy of the string is made; - the input ptr is not saved. - Note that this is no longer explicit, as the conversion is almost - always wanted, anyhow. + Constructor -- from a literal string. Constructs an UnicodeString + with the given string. Note that a copy of the string is made; + the input ptr is not saved. + Note that this is no longer explicit, as the conversion is almost + always wanted, anyhow. */ UnicodeString(const WideChar* s); /** - Constructs an UnicodeString with the given string and length. - The length must not be larger than the actual string length. + Constructs an UnicodeString with the given string and length. + The length must not be larger than the actual string length. */ UnicodeString(const WideChar* s, int len); /** - Destructor. Not too exciting... clean up the works and such. + Destructor. Not too exciting... clean up the works and such. */ ~UnicodeString(); /** - Return the length, in characters, of the string up to the first zero or null terminator. + Return the length, in characters, of the string up to the first zero or null terminator. */ int getLength() const; /** - Return the number of bytes used by the string up to the first zero or null terminator. + Return the number of bytes used by the string up to the first zero or null terminator. */ int getByteCount() const; /** - Return true iff the length of the string is zero. Equivalent - to (getLength() == 0) but slightly more efficient. + Return true iff the length of the string is zero. Equivalent + to (getLength() == 0) but slightly more efficient. */ Bool isEmpty() const; /** - Make the string empty. Equivalent to (str = "") but slightly more efficient. + Make the string empty. Equivalent to (str = "") but slightly more efficient. */ void clear(); /** - Return the character and the given (zero-based) index into the string. - No range checking is done (except in debug mode). + Return the character and the given (zero-based) index into the string. + No range checking is done (except in debug mode). */ WideChar getCharAt(int index) const; /** - Return a pointer to the (null-terminated) string. Note that this is - a const pointer: do NOT change this! It is imperative that it be - impossible (or at least, really difficuly) for someone to change our - private data, since it might be shared amongst other UnicodeStrings. + Return a pointer to the (null-terminated) string. Note that this is + a const pointer: do NOT change this! It is imperative that it be + impossible (or at least, really difficuly) for someone to change our + private data, since it might be shared amongst other UnicodeStrings. */ const WideChar* str() const; /** - Makes sure there is room for a string of len+1 characters, and - returns a pointer to the string buffer. This ensures that the - string buffer is NOT shared. This is intended for the file reader, - that is reading new strings in from a file. jba. + Makes sure there is room for a string of len+1 characters, and + returns a pointer to the string buffer. This ensures that the + string buffer is NOT shared. This is intended for the file reader, + that is reading new strings in from a file. jba. */ WideChar* getBufferForRead(Int len); /** - Replace the contents of self with the given string. - (This is actually quite efficient, because - they will simply share the same string and increment the - refcount.) + Replace the contents of self with the given string. + (This is actually quite efficient, because + they will simply share the same string and increment the + refcount.) */ void set(const UnicodeString& stringSrc); /** - Replace the contents of self with the given string. - Note that a copy of the string is made; the input ptr is not saved. + Replace the contents of self with the given string. + Note that a copy of the string is made; the input ptr is not saved. */ void set(const WideChar* s); /** - Replace the contents of self with the given string and length. - Note that a copy of the string is made; the input ptr is not saved. - The length must not be larger than the actual string length. + Replace the contents of self with the given string and length. + Note that a copy of the string is made; the input ptr is not saved. + The length must not be larger than the actual string length. */ void set(const WideChar* s, int len); /** - replace contents of self with the given string. Note the - nomenclature is translate rather than set; this is because - not all single-byte strings translate one-for-one into - UnicodeStrings, so some data manipulation may be necessary, - and the resulting strings may not be equivalent. + replace contents of self with the given string. Note the + nomenclature is translate rather than set; this is because + not all single-byte strings translate one-for-one into + UnicodeStrings, so some data manipulation may be necessary, + and the resulting strings may not be equivalent. */ void translate(const AsciiString& stringSrc); /** - Concatenate the given string onto self. + Concatenate the given string onto self. */ void concat(const UnicodeString& stringSrc); /** - Concatenate the given string onto self. + Concatenate the given string onto self. */ void concat(const WideChar* s); /** - Concatenate the given character onto self. + Concatenate the given character onto self. */ void concat(const WideChar c); @@ -257,104 +254,103 @@ class UnicodeString void trimEnd(const WideChar c); /** - Remove the final character in the string. If the string is empty, - do nothing. (This is a rather dorky method, but used a lot in - text editing, thus its presence here.) + Remove the final character in the string. If the string is empty, + do nothing. (This is a rather dorky method, but used a lot in + text editing, thus its presence here.) */ void removeLastChar(); /** - Remove the final charCount characters in the string. If the string is empty, - do nothing. + Remove the final charCount characters in the string. If the string is empty, + do nothing. */ void truncateBy(const Int charCount); /** - Truncate the string to a length of maxLength characters, not including null termination, - by removing from the end. If the string is empty or shorter than maxLength, do nothing. + Truncate the string to a length of maxLength characters, not including null termination, + by removing from the end. If the string is empty or shorter than maxLength, do nothing. */ void truncateTo(const Int maxLength); /** - Analogous to sprintf() -- this formats a string according to the - given sprintf-style format string (and the variable argument list) - and stores the result in self. + Analogous to sprintf() -- this formats a string according to the + given sprintf-style format string (and the variable argument list) + and stores the result in self. */ void format(UnicodeString format, ...); void format(const WideChar* format, ...); /** - Identical to format(), but takes a va_list rather than - a variable argument list. (i.e., analogous to vsprintf.) + Identical to format(), but takes a va_list rather than + a variable argument list. (i.e., analogous to vsprintf.) */ void format_va(const UnicodeString& format, va_list args); void format_va(const WideChar* format, va_list args); /** - Conceptually identical to wsccmp(). + Conceptually identical to wsccmp(). */ int compare(const UnicodeString& stringSrc) const; /** - Conceptually identical to wsccmp(). + Conceptually identical to wsccmp(). */ int compare(const WideChar* s) const; /** - Conceptually identical to _wcsicmp(). + Conceptually identical to _wcsicmp(). */ int compareNoCase(const UnicodeString& stringSrc) const; /** - Conceptually identical to _wcsicmp(). + Conceptually identical to _wcsicmp(). */ int compareNoCase(const WideChar* s) const; /** - return true iff self starts with the given string. + return true iff self starts with the given string. */ Bool startsWith(const WideChar* p) const; Bool startsWith(const UnicodeString& stringSrc) const { return startsWith(stringSrc.str()); } /** - return true iff self starts with the given string. (case insensitive) + return true iff self starts with the given string. (case insensitive) */ Bool startsWithNoCase(const WideChar* p) const; Bool startsWithNoCase(const UnicodeString& stringSrc) const { return startsWithNoCase(stringSrc.str()); } /** - return true iff self ends with the given string. + return true iff self ends with the given string. */ Bool endsWith(const WideChar* p) const; Bool endsWith(const UnicodeString& stringSrc) const { return endsWith(stringSrc.str()); } /** - return true iff self ends with the given string. (case insensitive) + return true iff self ends with the given string. (case insensitive) */ Bool endsWithNoCase(const WideChar* p) const; Bool endsWithNoCase(const UnicodeString& stringSrc) const { return endsWithNoCase(stringSrc.str()); } /** - conceptually similar to strtok(): + conceptually similar to strtok(): - extract the next whitespace-delimited token from the front - of 'this' and copy it into 'token', returning true if a nonempty - token was found. (note that this modifies 'this' as well, stripping - the token off!) + extract the next whitespace-delimited token from the front + of 'this' and copy it into 'token', returning true if a nonempty + token was found. (note that this modifies 'this' as well, stripping + the token off!) */ Bool nextToken(UnicodeString* token, UnicodeString delimiters = UnicodeString::TheEmptyString); -// -// You might think it would be a good idea to overload the * operator -// to allow for an implicit conversion to an WideChar*. This is -// in theory a good idea, but in practice, there's lots of code -// that assumes it should check text fields for null, which -// is meaningless for us, since we never return a null ptr. -// -// operator const WideChar*() const { return str(); } -// - - UnicodeString& operator=(const UnicodeString& stringSrc); ///< the same as set() - UnicodeString& operator=(const WideChar* s); ///< the same as set() + // + // You might think it would be a good idea to overload the * operator + // to allow for an implicit conversion to an WideChar*. This is + // in theory a good idea, but in practice, there's lots of code + // that assumes it should check text fields for null, which + // is meaningless for us, since we never return a null ptr. + // + // operator const WideChar*() const { return str(); } + // + + UnicodeString& operator=(const UnicodeString& stringSrc); ///< the same as set() + UnicodeString& operator=(const WideChar* s); ///< the same as set() }; - // ----------------------------------------------------- inline WideChar* UnicodeString::peek() const { @@ -364,7 +360,8 @@ inline WideChar* UnicodeString::peek() const } // ----------------------------------------------------- -inline UnicodeString::UnicodeString() : m_data(0) +inline UnicodeString::UnicodeString() + : m_data(0) { validate(); } @@ -452,7 +449,7 @@ inline void UnicodeString::concat(const WideChar c) { validate(); /// this can probably be made more efficient, if necessary - WideChar tmp[2] = { c, 0 }; + WideChar tmp[2] = {c, 0}; concat(tmp); validate(); } diff --git a/Core/GameEngine/Include/Common/UserPreferences.h b/Core/GameEngine/Include/Common/UserPreferences.h index 541303f6866..ccba2507039 100644 --- a/Core/GameEngine/Include/Common/UserPreferences.h +++ b/Core/GameEngine/Include/Common/UserPreferences.h @@ -81,16 +81,16 @@ class LANPreferences : public UserPreferences Bool loadFromIniFile(); - UnicodeString getUserName(); // convenience function - Int getPreferredFaction(); // convenience function - Int getPreferredColor(); // convenience function - AsciiString getPreferredMap(); // convenience function - Bool usesSystemMapDir(); // convenience function - Int getNumRemoteIPs(); // convenience function - UnicodeString getRemoteIPEntry(Int i); // convenience function - - Bool getSuperweaponRestricted() const; - Money getStartingCash() const; - void setSuperweaponRestricted( Bool superweaponRestricted); - void setStartingCash( const Money & startingCash ); + UnicodeString getUserName(); // convenience function + Int getPreferredFaction(); // convenience function + Int getPreferredColor(); // convenience function + AsciiString getPreferredMap(); // convenience function + Bool usesSystemMapDir(); // convenience function + Int getNumRemoteIPs(); // convenience function + UnicodeString getRemoteIPEntry(Int i); // convenience function + + Bool getSuperweaponRestricted() const; + Money getStartingCash() const; + void setSuperweaponRestricted(Bool superweaponRestricted); + void setStartingCash(const Money& startingCash); }; diff --git a/Core/GameEngine/Include/Common/Xfer.h b/Core/GameEngine/Include/Common/Xfer.h index 617b8e75e38..c9836f3a276 100644 --- a/Core/GameEngine/Include/Common/Xfer.h +++ b/Core/GameEngine/Include/Common/Xfer.h @@ -46,10 +46,10 @@ // FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// class Snapshot; typedef Int Color; -enum ObjectID CPP_11(: Int); -enum DrawableID CPP_11(: Int); -enum KindOfType CPP_11(: Int); -enum ScienceType CPP_11(: Int); +enum ObjectID CPP_11( : Int); +enum DrawableID CPP_11( : Int); +enum KindOfType CPP_11( : Int); +enum ScienceType CPP_11( : Int); class Matrix3D; // ------------------------------------------------------------------------------------------------ @@ -57,7 +57,7 @@ typedef UnsignedByte XferVersion; //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -enum XferMode CPP_11(: Int) +enum XferMode CPP_11( : Int) { XFER_INVALID = 0, @@ -70,40 +70,40 @@ enum XferMode CPP_11(: Int) //------------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------- -enum XferStatus CPP_11(: Int) +enum XferStatus CPP_11( : Int) { XFER_STATUS_INVALID = 0, - XFER_OK, ///< all is green and good - XFER_EOF, ///< end of file encountered - XFER_FILE_NOT_FOUND, ///< requested file does not exist - XFER_FILE_NOT_OPEN, ///< file was not open - XFER_FILE_ALREADY_OPEN, ///< this xfer is already open - XFER_READ_ERROR, ///< error reading from file - XFER_WRITE_ERROR, ///< error writing to file - XFER_MODE_UNKNOWN, ///< unknown xfer mode - XFER_SKIP_ERROR, ///< error skipping file - XFER_BEGIN_END_MISMATCH, ///< mismatched pair calls of begin/end block - XFER_OUT_OF_MEMORY, ///< out of memory - XFER_STRING_ERROR, ///< error with strings - XFER_INVALID_VERSION, ///< invalid version encountered - XFER_INVALID_PARAMETERS, ///< invalid parameters - XFER_LIST_NOT_EMPTY, ///< trying to xfer into a list that should be empty, but isn't - XFER_UNKNOWN_STRING, ///< unrecognized string value - - XFER_ERROR_UNKNOWN, ///< unknown error (isn't that useful!) + XFER_OK, ///< all is green and good + XFER_EOF, ///< end of file encountered + XFER_FILE_NOT_FOUND, ///< requested file does not exist + XFER_FILE_NOT_OPEN, ///< file was not open + XFER_FILE_ALREADY_OPEN, ///< this xfer is already open + XFER_READ_ERROR, ///< error reading from file + XFER_WRITE_ERROR, ///< error writing to file + XFER_MODE_UNKNOWN, ///< unknown xfer mode + XFER_SKIP_ERROR, ///< error skipping file + XFER_BEGIN_END_MISMATCH, ///< mismatched pair calls of begin/end block + XFER_OUT_OF_MEMORY, ///< out of memory + XFER_STRING_ERROR, ///< error with strings + XFER_INVALID_VERSION, ///< invalid version encountered + XFER_INVALID_PARAMETERS, ///< invalid parameters + XFER_LIST_NOT_EMPTY, ///< trying to xfer into a list that should be empty, but isn't + XFER_UNKNOWN_STRING, ///< unrecognized string value + + XFER_ERROR_UNKNOWN, ///< unknown error (isn't that useful!) NUM_XFER_STATUS }; // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ -enum XferOptions CPP_11(: UnsignedInt) +enum XferOptions CPP_11( : UnsignedInt) { - XO_NONE = 0x00000000, - XO_NO_POST_PROCESSING = 0x00000001, + XO_NONE = 0x00000000, + XO_NO_POST_PROCESSING = 0x00000001, - XO_ALL = 0xFFFFFFFF + XO_ALL = 0xFFFFFFFF }; /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -115,7 +115,6 @@ class Xfer { public: - Xfer(); virtual ~Xfer(); @@ -123,68 +122,66 @@ class Xfer AsciiString getIdentifier() { return m_identifier; } // xfer management - virtual void setOptions( UnsignedInt options ) { BitSet( m_options, options ); } - virtual void clearOptions( UnsignedInt options ) { BitClear( m_options, options ); } + virtual void setOptions(UnsignedInt options) { BitSet(m_options, options); } + virtual void clearOptions(UnsignedInt options) { BitClear(m_options, options); } virtual UnsignedInt getOptions() { return m_options; } - virtual void open( AsciiString identifier ) = 0; ///< xfer open event - virtual void close() = 0; ///< xfer close event - virtual Int beginBlock() = 0; ///< xfer begin block event - virtual void endBlock() = 0; ///< xfer end block event - virtual void skip( Int dataSize ) = 0; ///< xfer skip data + virtual void open(AsciiString identifier) = 0; ///< xfer open event + virtual void close() = 0; ///< xfer close event + virtual Int beginBlock() = 0; ///< xfer begin block event + virtual void endBlock() = 0; ///< xfer end block event + virtual void skip(Int dataSize) = 0; ///< xfer skip data - virtual void xferSnapshot( Snapshot *snapshot ) = 0; ///< entry point for xfering a snapshot + virtual void xferSnapshot(Snapshot* snapshot) = 0; ///< entry point for xfering a snapshot // // default transfer methods, these call the implementation method with the data // parameters. You may use the default, or derive and create new ways to xfer each // of these types of data // - virtual void xferVersion( XferVersion *versionData, XferVersion currentVersion ); - virtual void xferByte( Byte *byteData ); - virtual void xferUnsignedByte( UnsignedByte *unsignedByteData ); - virtual void xferBool( Bool *boolData ); - virtual void xferInt( Int *intData ); - virtual void xferInt64( Int64 *int64Data ); - virtual void xferUnsignedInt( UnsignedInt *unsignedIntData ); - virtual void xferShort( Short *shortData ); - virtual void xferUnsignedShort( UnsignedShort *unsignedShortData ); - virtual void xferReal( Real *realData ); - virtual void xferMarkerLabel( AsciiString asciiStringData ); // This is purely for readability purposes - it is explicitly discarded on load. - virtual void xferAsciiString( AsciiString *asciiStringData ); - virtual void xferUnicodeString( UnicodeString *unicodeStringData ); - virtual void xferCoord3D( Coord3D *coord3D ); - virtual void xferICoord3D( ICoord3D *iCoord3D ); - virtual void xferRegion3D( Region3D *region3D ); - virtual void xferIRegion3D( IRegion3D *iRegion3D ); - virtual void xferCoord2D( Coord2D *coord2D ); - virtual void xferICoord2D( ICoord2D *iCoord2D ); - virtual void xferRegion2D( Region2D *region2D ); - virtual void xferIRegion2D( IRegion2D *iRegion2D ); - virtual void xferRealRange( RealRange *realRange ); - virtual void xferColor( Color *color ); - virtual void xferRGBColor( RGBColor *rgbColor ); - virtual void xferRGBAColorReal( RGBAColorReal *rgbaColorReal ); - virtual void xferRGBAColorInt( RGBAColorInt *rgbaColorInt ); - virtual void xferObjectID( ObjectID *objectID ); - virtual void xferDrawableID( DrawableID *drawableID ); - virtual void xferSTLObjectIDVector( std::vector *objectIDVectorData ); - virtual void xferSTLObjectIDList( std::list< ObjectID > *objectIDListData ); - virtual void xferSTLIntList( std::list< Int > *intListData ); - virtual void xferScienceType( ScienceType *science ); - virtual void xferScienceVec( ScienceVec *scienceVec ); - virtual void xferKindOf( KindOfType *kindOfData ); - virtual void xferUpgradeMask( UpgradeMaskType *upgradeMaskData ); - virtual void xferUser( void *data, Int dataSize ); - virtual void xferMatrix3D( Matrix3D* mtx ); - virtual void xferMapName( AsciiString *mapNameData ); + virtual void xferVersion(XferVersion* versionData, XferVersion currentVersion); + virtual void xferByte(Byte* byteData); + virtual void xferUnsignedByte(UnsignedByte* unsignedByteData); + virtual void xferBool(Bool* boolData); + virtual void xferInt(Int* intData); + virtual void xferInt64(Int64* int64Data); + virtual void xferUnsignedInt(UnsignedInt* unsignedIntData); + virtual void xferShort(Short* shortData); + virtual void xferUnsignedShort(UnsignedShort* unsignedShortData); + virtual void xferReal(Real* realData); + virtual void xferMarkerLabel(AsciiString asciiStringData); // This is purely for readability purposes - it is explicitly discarded on load. + virtual void xferAsciiString(AsciiString* asciiStringData); + virtual void xferUnicodeString(UnicodeString* unicodeStringData); + virtual void xferCoord3D(Coord3D* coord3D); + virtual void xferICoord3D(ICoord3D* iCoord3D); + virtual void xferRegion3D(Region3D* region3D); + virtual void xferIRegion3D(IRegion3D* iRegion3D); + virtual void xferCoord2D(Coord2D* coord2D); + virtual void xferICoord2D(ICoord2D* iCoord2D); + virtual void xferRegion2D(Region2D* region2D); + virtual void xferIRegion2D(IRegion2D* iRegion2D); + virtual void xferRealRange(RealRange* realRange); + virtual void xferColor(Color* color); + virtual void xferRGBColor(RGBColor* rgbColor); + virtual void xferRGBAColorReal(RGBAColorReal* rgbaColorReal); + virtual void xferRGBAColorInt(RGBAColorInt* rgbaColorInt); + virtual void xferObjectID(ObjectID* objectID); + virtual void xferDrawableID(DrawableID* drawableID); + virtual void xferSTLObjectIDVector(std::vector* objectIDVectorData); + virtual void xferSTLObjectIDList(std::list* objectIDListData); + virtual void xferSTLIntList(std::list* intListData); + virtual void xferScienceType(ScienceType* science); + virtual void xferScienceVec(ScienceVec* scienceVec); + virtual void xferKindOf(KindOfType* kindOfData); + virtual void xferUpgradeMask(UpgradeMaskType* upgradeMaskData); + virtual void xferUser(void* data, Int dataSize); + virtual void xferMatrix3D(Matrix3D* mtx); + virtual void xferMapName(AsciiString* mapNameData); protected: - // this is the actual xfer implementation that each derived class should implement - virtual void xferImplementation( void *data, Int dataSize ) = 0; - - UnsignedInt m_options; ///< xfer options - XferMode m_xferMode; ///< the current xfer mode - AsciiString m_identifier; ///< the string identifier + virtual void xferImplementation(void* data, Int dataSize) = 0; + UnsignedInt m_options; ///< xfer options + XferMode m_xferMode; ///< the current xfer mode + AsciiString m_identifier; ///< the string identifier }; diff --git a/Core/GameEngine/Include/Common/XferCRC.h b/Core/GameEngine/Include/Common/XferCRC.h index 8a728048c78..59052337e79 100644 --- a/Core/GameEngine/Include/Common/XferCRC.h +++ b/Core/GameEngine/Include/Common/XferCRC.h @@ -41,28 +41,25 @@ class XferCRC : public Xfer { public: - XferCRC(); virtual ~XferCRC() override; // Xfer methods - virtual void open( AsciiString identifier ) override; ///< start a CRC session with this xfer instance - virtual void close() override; ///< stop CRC session - virtual Int beginBlock() override; ///< start block event - virtual void endBlock() override; ///< end block event - virtual void skip( Int dataSize ) override; ///< skip xfer event + virtual void open(AsciiString identifier) override; ///< start a CRC session with this xfer instance + virtual void close() override; ///< stop CRC session + virtual Int beginBlock() override; ///< start block event + virtual void endBlock() override; ///< end block event + virtual void skip(Int dataSize) override; ///< skip xfer event - virtual void xferSnapshot( Snapshot *snapshot ) override; ///< entry point for xfering a snapshot + virtual void xferSnapshot(Snapshot* snapshot) override; ///< entry point for xfering a snapshot // Xfer CRC methods - virtual UnsignedInt getCRC(); ///< get computed CRC in network byte order + virtual UnsignedInt getCRC(); ///< get computed CRC in network byte order protected: + virtual void xferImplementation(void* data, Int dataSize) override; - virtual void xferImplementation( void *data, Int dataSize ) override; - - inline void addCRC( UnsignedInt val ); ///< CRC a 4-byte block + inline void addCRC(UnsignedInt val); ///< CRC a 4-byte block UnsignedInt m_crc; - }; diff --git a/Core/GameEngine/Include/Common/XferDeepCRC.h b/Core/GameEngine/Include/Common/XferDeepCRC.h index 729e37bf1c8..121148a2fe0 100644 --- a/Core/GameEngine/Include/Common/XferDeepCRC.h +++ b/Core/GameEngine/Include/Common/XferDeepCRC.h @@ -42,22 +42,20 @@ class XferDeepCRC : public XferCRC { public: - XferDeepCRC(); virtual ~XferDeepCRC() override; // Xfer methods - virtual void open( AsciiString identifier ) override; ///< start a CRC session with this xfer instance - virtual void close() override; ///< stop CRC session + virtual void open(AsciiString identifier) override; ///< start a CRC session with this xfer instance + virtual void close() override; ///< stop CRC session // xfer methods - virtual void xferMarkerLabel( AsciiString asciiStringData ) override; ///< xfer ascii string (need our own) - virtual void xferAsciiString( AsciiString *asciiStringData ) override; ///< xfer ascii string (need our own) - virtual void xferUnicodeString( UnicodeString *unicodeStringData ) override; ///< xfer unicode string (need our own); + virtual void xferMarkerLabel(AsciiString asciiStringData) override; ///< xfer ascii string (need our own) + virtual void xferAsciiString(AsciiString* asciiStringData) override; ///< xfer ascii string (need our own) + virtual void xferUnicodeString(UnicodeString* unicodeStringData) override; ///< xfer unicode string (need our own); protected: + virtual void xferImplementation(void* data, Int dataSize) override; - virtual void xferImplementation( void *data, Int dataSize ) override; - - FILE * m_fileFP; ///< pointer to file + FILE* m_fileFP; ///< pointer to file }; diff --git a/Core/GameEngine/Include/Common/XferLoad.h b/Core/GameEngine/Include/Common/XferLoad.h index 0a5505a388f..6b9530f8f6f 100644 --- a/Core/GameEngine/Include/Common/XferLoad.h +++ b/Core/GameEngine/Include/Common/XferLoad.h @@ -41,26 +41,23 @@ class XferLoad : public Xfer { public: - XferLoad(); virtual ~XferLoad() override; - virtual void open( AsciiString identifier ) override; ///< open file for writing - virtual void close() override; ///< close file - virtual Int beginBlock() override; ///< read placeholder block size - virtual void endBlock() override; ///< reading an end block is a no-op - virtual void skip( Int dataSize ) override; ///< skip forward dataSize bytes in file + virtual void open(AsciiString identifier) override; ///< open file for writing + virtual void close() override; ///< close file + virtual Int beginBlock() override; ///< read placeholder block size + virtual void endBlock() override; ///< reading an end block is a no-op + virtual void skip(Int dataSize) override; ///< skip forward dataSize bytes in file - virtual void xferSnapshot( Snapshot *snapshot ) override; ///< entry point for xfering a snapshot + virtual void xferSnapshot(Snapshot* snapshot) override; ///< entry point for xfering a snapshot // xfer methods - virtual void xferAsciiString( AsciiString *asciiStringData ) override; ///< xfer ascii string (need our own) - virtual void xferUnicodeString( UnicodeString *unicodeStringData ) override; ///< xfer unicode string (need our own); + virtual void xferAsciiString(AsciiString* asciiStringData) override; ///< xfer ascii string (need our own) + virtual void xferUnicodeString(UnicodeString* unicodeStringData) override; ///< xfer unicode string (need our own); protected: + virtual void xferImplementation(void* data, Int dataSize) override; ///< the xfer implementation - virtual void xferImplementation( void *data, Int dataSize ) override; ///< the xfer implementation - - FILE * m_fileFP; ///< pointer to file - + FILE* m_fileFP; ///< pointer to file }; diff --git a/Core/GameEngine/Include/Common/XferSave.h b/Core/GameEngine/Include/Common/XferSave.h index 9cf6593bdd6..01e9bf253c3 100644 --- a/Core/GameEngine/Include/Common/XferSave.h +++ b/Core/GameEngine/Include/Common/XferSave.h @@ -45,28 +45,25 @@ class XferSave : public Xfer { public: - XferSave(); virtual ~XferSave() override; // Xfer methods - virtual void open( AsciiString identifier ) override; ///< open file for writing - virtual void close() override; ///< close file - virtual Int beginBlock() override; ///< write placeholder block size - virtual void endBlock() override; ///< backup to last begin block and write size - virtual void skip( Int dataSize ) override; ///< skipping during a write is a no-op + virtual void open(AsciiString identifier) override; ///< open file for writing + virtual void close() override; ///< close file + virtual Int beginBlock() override; ///< write placeholder block size + virtual void endBlock() override; ///< backup to last begin block and write size + virtual void skip(Int dataSize) override; ///< skipping during a write is a no-op - virtual void xferSnapshot( Snapshot *snapshot ) override; ///< entry point for xfering a snapshot + virtual void xferSnapshot(Snapshot* snapshot) override; ///< entry point for xfering a snapshot // xfer methods - virtual void xferAsciiString( AsciiString *asciiStringData ) override; ///< xfer ascii string (need our own) - virtual void xferUnicodeString( UnicodeString *unicodeStringData ) override; ///< xfer unicode string (need our own); + virtual void xferAsciiString(AsciiString* asciiStringData) override; ///< xfer ascii string (need our own) + virtual void xferUnicodeString(UnicodeString* unicodeStringData) override; ///< xfer unicode string (need our own); protected: + virtual void xferImplementation(void* data, Int dataSize) override; ///< the xfer implementation - virtual void xferImplementation( void *data, Int dataSize ) override; ///< the xfer implementation - - FILE * m_fileFP; ///< pointer to file - XferBlockData *m_blockStack; ///< stack of block data - + FILE* m_fileFP; ///< pointer to file + XferBlockData* m_blockStack; ///< stack of block data }; diff --git a/Core/GameEngine/Include/Common/crc.h b/Core/GameEngine/Include/Common/crc.h index 08db4af6757..5cae4b2642b 100644 --- a/Core/GameEngine/Include/Common/crc.h +++ b/Core/GameEngine/Include/Common/crc.h @@ -32,27 +32,27 @@ #ifdef RTS_DEBUG -//#include "winsock2.h" // for htonl +// #include "winsock2.h" // for htonl class CRC { public: CRC() { crc = 0; } - void computeCRC( const void *buf, Int len ); ///< Compute the CRC for a buffer, added into current CRC - void clear() { crc = 0; } ///< Clears the CRC to 0 -// UnsignedInt get() { return htonl(crc); } ///< Get the combined CRC + void computeCRC(const void* buf, Int len); ///< Compute the CRC for a buffer, added into current CRC + void clear() { crc = 0; } ///< Clears the CRC to 0 + // UnsignedInt get() { return htonl(crc); } ///< Get the combined CRC UnsignedInt get(); -#if (defined(_MSC_VER) && _MSC_VER < 1300) && RETAIL_COMPATIBLE_CRC - void set( UnsignedInt v ) - { - crc = v; - } -#endif + #if (defined(_MSC_VER) && _MSC_VER < 1300) && RETAIL_COMPATIBLE_CRC + void set(UnsignedInt v) + { + crc = v; + } + #endif private: - void addCRC( UnsignedByte val ); ///< CRC a 4-byte block + void addCRC(UnsignedByte val); ///< CRC a 4-byte block UnsignedInt crc; }; @@ -63,73 +63,77 @@ class CRC class CRC { public: - CRC() { crc=0; } - - /// Compute the CRC for a buffer, added into current CRC - __forceinline void computeCRC( const void *buf, Int len ) - { - if (!buf||len<1) - return; - -#if !(defined(_MSC_VER) && _MSC_VER < 1300) - // C++ version left in for reference purposes - for (UnsignedByte *uintPtr=(UnsignedByte *)buf;len>0;len--,uintPtr++) - { - int hibit; - if (crc & 0x80000000) - { - hibit = 1; - } - else - { - hibit = 0; - } - - crc <<= 1; - crc += *uintPtr; - crc += hibit; - } -#else - // ASM version, verified by comparing resulting data with C++ version data - unsigned *crcPtr=&crc; - _asm - { - mov esi,[buf] - mov ecx,[len] - dec ecx - mov edi,[crcPtr] - mov ebx,dword ptr [edi] - xor eax,eax - lp: - mov al,byte ptr [esi] - shl ebx,1 - inc esi - adc ebx,eax - dec ecx - jns lp - mov dword ptr [edi],ebx - }; -#endif - } + CRC() { crc = 0; } - /// Clears the CRC to 0 + /// Compute the CRC for a buffer, added into current CRC + __forceinline void computeCRC(const void* buf, Int len) + { + if (!buf || len < 1) + return; + + #if !(defined(_MSC_VER) && _MSC_VER < 1300) + // C++ version left in for reference purposes + for (UnsignedByte* uintPtr = (UnsignedByte*)buf; len > 0; len--, uintPtr++) + { + int hibit; + if (crc & 0x80000000) + { + hibit = 1; + } + else + { + hibit = 0; + } + + crc <<= 1; + crc += *uintPtr; + crc += hibit; + } + #else + // ASM version, verified by comparing resulting data with C++ version data + unsigned* crcPtr = &crc; + + // clang-format off: [INLINE_ASM] - Preserving manual alignment of assembly instructions + _asm + { + mov esi, [buf] + mov ecx, [len] + dec ecx + mov edi, [crcPtr] + mov ebx, dword ptr [edi] + xor eax, eax + lp: + mov al, byte ptr [esi] + shl ebx, 1 + inc esi + adc ebx, eax + dec ecx + jns lp + mov dword ptr [edi], ebx + }; + // clang-format on + + #endif + } + + /// Clears the CRC to 0 void clear() - { - crc = 0; - } + { + crc = 0; + } - ///< Get the combined CRC + ///< Get the combined CRC UnsignedInt get() const - { - return crc; - } - -#if (defined(_MSC_VER) && _MSC_VER < 1300) && RETAIL_COMPATIBLE_CRC - void set( UnsignedInt v ) - { - crc = v; - } -#endif + { + return crc; + } + + #if (defined(_MSC_VER) && _MSC_VER < 1300) && RETAIL_COMPATIBLE_CRC + void set(UnsignedInt v) + { + crc = v; + } + #endif private: UnsignedInt crc; diff --git a/Core/GameEngine/Include/Common/file.h b/Core/GameEngine/Include/Common/file.h index a88fddb51bb..b64a34f5dc2 100644 --- a/Core/GameEngine/Include/Common/file.h +++ b/Core/GameEngine/Include/Common/file.h @@ -55,8 +55,6 @@ // Forward References //---------------------------------------------------------------------------- - - //---------------------------------------------------------------------------- // Type Defines //---------------------------------------------------------------------------- @@ -65,160 +63,151 @@ // File //=============================== /** - * File is an interface class for basic file operations. - * - * All code should use the File class and not its derivatives, unless - * absolutely necessary. Also FS::Open should be used to create File objects and open files. - * - * TheSuperHackers @feature Adds LINEBUF and FULLBUF modes and buffer size argument for file open. - */ + * File is an interface class for basic file operations. + * + * All code should use the File class and not its derivatives, unless + * absolutely necessary. Also FS::Open should be used to create File objects and open files. + * + * TheSuperHackers @feature Adds LINEBUF and FULLBUF modes and buffer size argument for file open. + */ //=============================== class File : public MemoryPoolObject { MEMORY_POOL_GLUE_ABC(File) -// friend doesn't play well with MPO (srj) -// friend class FileSystem; - - public: - - enum access - { - NONE = 0x00000000, ///< Access file. Reading by default - - READ = 0x00000001, ///< Access file for reading - WRITE = 0x00000002, ///< Access file for writing - READWRITE = (READ | WRITE), - - APPEND = 0x00000004, ///< Seek to end of file on open - CREATE = 0x00000008, ///< Create file if it does not exist - TRUNCATE = 0x00000010, ///< Delete all data in file when opened - - // NOTE: accesses file as binary data if neither TEXT and BINARY are set - TEXT = 0x00000020, ///< Access file as text data - BINARY = 0x00000040, ///< Access file as binary data - - ONLYNEW = 0x00000080, ///< Only create file if it does not exist - - // NOTE: STREAMING is Mutually exclusive with WRITE - STREAMING = 0x00000100, ///< Do not read this file into a ram file, read it as requested. - - // NOTE: accesses file with full buffering if neither LINEBUF and FULLBUF are set - LINEBUF = 0x00000200, ///< Access file with line buffering - FULLBUF = 0x00000400, ///< Access file with full buffering - }; - - enum seekMode - { - START, ///< Seek position is relative to start of file - CURRENT, ///< Seek position is relative to current file position - END ///< Seek position is relative from the end of the file - }; - - enum - { - BUFFERSIZE = BUFSIZ, - }; - - protected: - - AsciiString m_nameStr; ///< Stores file name - Int m_access; ///< How the file was opened - Bool m_open; ///< Has the file been opened - Bool m_deleteOnClose; ///< delete File object on close() - - - File(); ///< This class can only used as a base class - //virtual ~File(); - - void closeWithoutDelete(); - - public: - - - Bool eof(); - virtual Bool open( const Char *filename, Int access = NONE, size_t bufferSize = BUFFERSIZE ); ///< Open a file for access - virtual void close(); ///< Close the file !!! File object no longer valid after this call !!! - - virtual Int read( void *buffer, Int bytes ) = 0 ; /**< Read the specified number of bytes from the file in to the - * memory pointed at by buffer. Returns the number of bytes read. - * Returns -1 if an error occurred. - */ - virtual Int readChar() = 0 ; /**< Read a character from the file - * Returns the character converted to an integer. - * Returns EOF if an error occurred. - */ - virtual Int readWideChar() = 0 ; /**< Read a wide character from the file - * Returns the wide character converted to an integer. - * Returns wide EOF if an error occurred. - */ - virtual Int write( const void *buffer, Int bytes ) = 0 ; /**< Write the specified number of bytes from the - * memory pointed at by buffer to the file. Returns the number of bytes written. - * Returns -1 if an error occurred. - */ - virtual Int writeFormat( const Char* format, ... ) = 0 ; /**< Write an unterminated formatted string to the file - * Returns the number of bytes written. - * Returns -1 if an error occurred. - */ - virtual Int writeFormat( const WideChar* format, ... ) = 0 ; /**< Write an unterminated formatted wide character string to the file - * Returns the number of bytes written. - * Returns -1 if an error occurred. - */ - virtual Int writeChar( const Char* character ) = 0 ; /**< Write a character to the file - * Returns a copy of the character written. - * Returns EOF if an error occurred. - */ - virtual Int writeChar( const WideChar* character ) = 0 ; /**< Write a wide character to the file - * Returns a copy of the wide character written. - * Returns wide EOF if an error occurred. - */ - virtual Int seek( Int bytes, seekMode mode = CURRENT ) = 0; /**< Sets the file position of the next read/write operation. Returns the new file - * position as the number of bytes from the start of the file. - * Returns -1 if an error occurred. - * - * seekMode determines how the seek is done: - * - * START : means seek to the specified number of bytes from the start of the file - * CURRENT: means seek the specified the number of bytes from the current file position - * END: means seek the specified number of bytes back from the end of the file - */ - virtual Bool flush() = 0; ///< flush data to disk - virtual void nextLine(Char *buf = nullptr, Int bufSize = 0) = 0; ///< reads until it reaches a new-line character - - virtual Bool scanInt(Int &newInt) = 0; ///< read an integer from the current file position. - virtual Bool scanReal(Real &newReal) = 0; ///< read a real number from the current file position. - virtual Bool scanString(AsciiString &newString) = 0; ///< read a string from the current file position. - - virtual Bool print ( const Char *format, ...); ///< Prints formatted string to text file - virtual Int size(); ///< Returns the size of the file - virtual Int position(); ///< Returns the current read/write position - - - void setName( const char *name ); ///< Set the name of the file - const char* getName() const; ///< Returns a pointer to the name of the file - Int getAccess() const; ///< Returns file's access flags - - void deleteOnClose (); ///< Causes the File object to delete itself when it closes - - /** - Allocate a buffer large enough to hold entire file, read - the entire file into the buffer, then close the file. - the buffer is owned by the caller, who is responsible - for freeing is (via delete[]). This is a Good Thing to - use because it minimizes memory copies for BIG files. - */ - virtual char* readEntireAndClose() = 0; - virtual File* convertToRAMFile() = 0; + // friend doesn't play well with MPO (srj) + // friend class FileSystem; + +public: + enum access + { + NONE = 0x00000000, ///< Access file. Reading by default + + READ = 0x00000001, ///< Access file for reading + WRITE = 0x00000002, ///< Access file for writing + READWRITE = (READ | WRITE), + + APPEND = 0x00000004, ///< Seek to end of file on open + CREATE = 0x00000008, ///< Create file if it does not exist + TRUNCATE = 0x00000010, ///< Delete all data in file when opened + + // NOTE: accesses file as binary data if neither TEXT and BINARY are set + TEXT = 0x00000020, ///< Access file as text data + BINARY = 0x00000040, ///< Access file as binary data + + ONLYNEW = 0x00000080, ///< Only create file if it does not exist + + // NOTE: STREAMING is Mutually exclusive with WRITE + STREAMING = 0x00000100, ///< Do not read this file into a ram file, read it as requested. + + // NOTE: accesses file with full buffering if neither LINEBUF and FULLBUF are set + LINEBUF = 0x00000200, ///< Access file with line buffering + FULLBUF = 0x00000400, ///< Access file with full buffering + }; + + enum seekMode + { + START, ///< Seek position is relative to start of file + CURRENT, ///< Seek position is relative to current file position + END ///< Seek position is relative from the end of the file + }; + + enum + { + BUFFERSIZE = BUFSIZ, + }; + +protected: + AsciiString m_nameStr; ///< Stores file name + Int m_access; ///< How the file was opened + Bool m_open; ///< Has the file been opened + Bool m_deleteOnClose; ///< delete File object on close() + + File(); ///< This class can only used as a base class + // virtual ~File(); + + void closeWithoutDelete(); + +public: + Bool eof(); + virtual Bool open(const Char* filename, Int access = NONE, size_t bufferSize = BUFFERSIZE); ///< Open a file for access + virtual void close(); ///< Close the file !!! File object no longer valid after this call !!! + + virtual Int read(void* buffer, Int bytes) = 0; /**< Read the specified number of bytes from the file in to the + * memory pointed at by buffer. Returns the number of bytes read. + * Returns -1 if an error occurred. + */ + virtual Int readChar() = 0; /**< Read a character from the file + * Returns the character converted to an integer. + * Returns EOF if an error occurred. + */ + virtual Int readWideChar() = 0; /**< Read a wide character from the file + * Returns the wide character converted to an integer. + * Returns wide EOF if an error occurred. + */ + virtual Int write(const void* buffer, Int bytes) = 0; /**< Write the specified number of bytes from the + * memory pointed at by buffer to the file. Returns the number of bytes written. + * Returns -1 if an error occurred. + */ + virtual Int writeFormat(const Char* format, ...) = 0; /**< Write an unterminated formatted string to the file + * Returns the number of bytes written. + * Returns -1 if an error occurred. + */ + virtual Int writeFormat(const WideChar* format, ...) = 0; /**< Write an unterminated formatted wide character string to the file + * Returns the number of bytes written. + * Returns -1 if an error occurred. + */ + virtual Int writeChar(const Char* character) = 0; /**< Write a character to the file + * Returns a copy of the character written. + * Returns EOF if an error occurred. + */ + virtual Int writeChar(const WideChar* character) = 0; /**< Write a wide character to the file + * Returns a copy of the wide character written. + * Returns wide EOF if an error occurred. + */ + virtual Int seek(Int bytes, seekMode mode = CURRENT) = 0; /**< Sets the file position of the next read/write operation. Returns the new file + * position as the number of bytes from the start of the file. + * Returns -1 if an error occurred. + * + * seekMode determines how the seek is done: + * + * START : means seek to the specified number of bytes from the start of the file + * CURRENT: means seek the specified the number of bytes from the current file position + * END: means seek the specified number of bytes back from the end of the file + */ + virtual Bool flush() = 0; ///< flush data to disk + virtual void nextLine(Char* buf = nullptr, Int bufSize = 0) = 0; ///< reads until it reaches a new-line character + + virtual Bool scanInt(Int& newInt) = 0; ///< read an integer from the current file position. + virtual Bool scanReal(Real& newReal) = 0; ///< read a real number from the current file position. + virtual Bool scanString(AsciiString& newString) = 0; ///< read a string from the current file position. + + virtual Bool print(const Char* format, ...); ///< Prints formatted string to text file + virtual Int size(); ///< Returns the size of the file + virtual Int position(); ///< Returns the current read/write position + + void setName(const char* name); ///< Set the name of the file + const char* getName() const; ///< Returns a pointer to the name of the file + Int getAccess() const; ///< Returns file's access flags + + void deleteOnClose(); ///< Causes the File object to delete itself when it closes + + /** + Allocate a buffer large enough to hold entire file, read + the entire file into the buffer, then close the file. + the buffer is owned by the caller, who is responsible + for freeing is (via delete[]). This is a Good Thing to + use because it minimizes memory copies for BIG files. + */ + virtual char* readEntireAndClose() = 0; + virtual File* convertToRAMFile() = 0; }; - - - //---------------------------------------------------------------------------- // Inlining //---------------------------------------------------------------------------- inline const char* File::getName() const { return m_nameStr.str(); } -inline void File::setName( const char *name ) { m_nameStr.set(name); } +inline void File::setName(const char* name) { m_nameStr.set(name); } inline Int File::getAccess() const { return m_access; } inline void File::deleteOnClose() { m_deleteOnClose = TRUE; } diff --git a/Core/GameEngine/Include/Common/simpleplayer.h b/Core/GameEngine/Include/Common/simpleplayer.h index f799458f5b6..1c0c2cb8870 100644 --- a/Core/GameEngine/Include/Common/simpleplayer.h +++ b/Core/GameEngine/Include/Common/simpleplayer.h @@ -24,96 +24,95 @@ // we preserve a list of "ready-to-free" list of wave headers for the // caller to unprepare and free // -typedef struct WAVEHDR_LIST { - LPWAVEHDR pwh; - struct WAVEHDR_LIST *next; -} WAVEHDR_LIST; +typedef struct WAVEHDR_LIST +{ + LPWAVEHDR pwh; + struct WAVEHDR_LIST* next; +} WAVEHDR_LIST; -#define SIMPLE_PLAYER_OPEN_EVENT _T( "45ab58e0-382e-4d1c-ac50-88a5f9601851" ) +#define SIMPLE_PLAYER_OPEN_EVENT _T( "45ab58e0-382e-4d1c-ac50-88a5f9601851" ) #define SIMPLE_PLAYER_CLOSE_EVENT _T( "276095fa-a8e0-48e6-ac61-8b0002345607" ) -#define WMAPLAY_EVENT _T( "9e828a72-64f3-48f0-9de8-13dafd0cbd3a" ) +#define WMAPLAY_EVENT _T( "9e828a72-64f3-48f0-9de8-13dafd0cbd3a" ) /////////////////////////////////////////////////////////////////////////////// class CSimplePlayer : public IWMReaderCallback { public: - CSimplePlayer( HRESULT* phr ); - ~CSimplePlayer(); + CSimplePlayer(HRESULT* phr); + ~CSimplePlayer(); - virtual HRESULT Play( LPCWSTR pszUrl, DWORD dwSecDuration, HANDLE hCompletionEvent, HRESULT *phrCompletion ); + virtual HRESULT Play(LPCWSTR pszUrl, DWORD dwSecDuration, HANDLE hCompletionEvent, HRESULT* phrCompletion); -// -// IUnknown Implemenation -// + // + // IUnknown Implemenation + // public: - virtual HRESULT STDMETHODCALLTYPE QueryInterface( - REFIID riid, - void **ppvObject ); + virtual HRESULT STDMETHODCALLTYPE QueryInterface( + REFIID riid, + void** ppvObject); - virtual ULONG STDMETHODCALLTYPE AddRef(); - virtual ULONG STDMETHODCALLTYPE Release(); + virtual ULONG STDMETHODCALLTYPE AddRef(); + virtual ULONG STDMETHODCALLTYPE Release(); -// -// IWMReaderCallback Implemenation -// + // + // IWMReaderCallback Implemenation + // public: - virtual HRESULT STDMETHODCALLTYPE OnSample( - /* [in] */ DWORD dwOutputNum, - /* [in] */ QWORD cnsSampleTime, - /* [in] */ QWORD cnsSampleDuration, - /* [in] */ DWORD dwFlags, - /* [in] */ INSSBuffer __RPC_FAR *pSample, - /* [in] */ void __RPC_FAR *pvContext); - - virtual HRESULT STDMETHODCALLTYPE OnStatus( - /* [in] */ WMT_STATUS Status, - /* [in] */ HRESULT hr, - /* [in] */ WMT_ATTR_DATATYPE dwType, - /* [in] */ BYTE __RPC_FAR *pValue, - /* [in] */ void __RPC_FAR *pvContext); - -// -// Helper Methods -// + virtual HRESULT STDMETHODCALLTYPE OnSample( + /* [in] */ DWORD dwOutputNum, + /* [in] */ QWORD cnsSampleTime, + /* [in] */ QWORD cnsSampleDuration, + /* [in] */ DWORD dwFlags, + /* [in] */ INSSBuffer __RPC_FAR* pSample, + /* [in] */ void __RPC_FAR* pvContext); + + virtual HRESULT STDMETHODCALLTYPE OnStatus( + /* [in] */ WMT_STATUS Status, + /* [in] */ HRESULT hr, + /* [in] */ WMT_ATTR_DATATYPE dwType, + /* [in] */ BYTE __RPC_FAR* pValue, + /* [in] */ void __RPC_FAR* pvContext); + + // + // Helper Methods + // protected: + HRESULT Close(); - HRESULT Close(); - - void OnWaveOutMsg( UINT uMsg, DWORD dwParam1, DWORD dwParam2 ); - - static void CALLBACK WaveProc( - HWAVEOUT hwo, - UINT uMsg, - DWORD dwInstance, - DWORD dwParam1, - DWORD dwParam2 ); + void OnWaveOutMsg(UINT uMsg, DWORD dwParam1, DWORD dwParam2); - HRESULT AddWaveHeader( LPWAVEHDR pwh ); - void RemoveWaveHeaders(); + static void CALLBACK WaveProc( + HWAVEOUT hwo, + UINT uMsg, + DWORD dwInstance, + DWORD dwParam1, + DWORD dwParam2); - CRITICAL_SECTION m_CriSec; - WAVEHDR_LIST *m_whdrHead; + HRESULT AddWaveHeader(LPWAVEHDR pwh); + void RemoveWaveHeaders(); - LONG m_cRef; - LONG m_cBuffersOutstanding; - BOOL m_fEof; - HANDLE m_hCompletionEvent; + CRITICAL_SECTION m_CriSec; + WAVEHDR_LIST* m_whdrHead; - IWMReader *m_pReader; - IWMHeaderInfo *m_pHeader; - HWAVEOUT m_hwo; + LONG m_cRef; + LONG m_cBuffersOutstanding; + BOOL m_fEof; + HANDLE m_hCompletionEvent; - HRESULT *m_phrCompletion; + IWMReader* m_pReader; + IWMHeaderInfo* m_pHeader; + HWAVEOUT m_hwo; - HRESULT m_hrOpen; - HANDLE m_hOpenEvent; - HANDLE m_hCloseEvent; + HRESULT* m_phrCompletion; - union - { - WAVEFORMATEX m_wfx; - BYTE m_WfxBuf[1024]; - }; + HRESULT m_hrOpen; + HANDLE m_hOpenEvent; + HANDLE m_hCloseEvent; - LPWSTR m_pszUrl; + union + { + WAVEFORMATEX m_wfx; + BYTE m_WfxBuf[1024]; + }; + LPWSTR m_pszUrl; }; diff --git a/Core/GameEngine/Include/Common/urllaunch.h b/Core/GameEngine/Include/Common/urllaunch.h index ca23690143d..e03d23b569d 100644 --- a/Core/GameEngine/Include/Common/urllaunch.h +++ b/Core/GameEngine/Include/Common/urllaunch.h @@ -18,6 +18,6 @@ #pragma once -HRESULT MakeEscapedURL( LPWSTR pszInURL, LPWSTR *ppszOutURL ); +HRESULT MakeEscapedURL(LPWSTR pszInURL, LPWSTR* ppszOutURL); -HRESULT LaunchURL( LPCWSTR pszURL ); +HRESULT LaunchURL(LPCWSTR pszURL); diff --git a/Core/GameEngine/Include/GameClient/ChallengeGenerals.h b/Core/GameEngine/Include/GameClient/ChallengeGenerals.h index 7952d67eb1c..f7f3b21795a 100644 --- a/Core/GameEngine/Include/GameClient/ChallengeGenerals.h +++ b/Core/GameEngine/Include/GameClient/ChallengeGenerals.h @@ -35,7 +35,7 @@ #include "Common/Overridable.h" // DEFINES //////////////////////////////////////////////////////////////////////////////////////// -//static const Int NUM_GENERALS = 12; // ChallengeMenu.wnd dependent +// static const Int NUM_GENERALS = 12; // ChallengeMenu.wnd dependent #define NUM_GENERALS (12) // FORWARD REFERENCES ///////////////////////////////////////////////////////////////////////////// @@ -55,14 +55,14 @@ class GeneralPersona AsciiString m_strBioRank; AsciiString m_strBioBranch; AsciiString m_strBioClassNumber; - Image *m_imageBioPortraitSmall; - Image *m_imageBioPortraitLarge; + Image* m_imageBioPortraitSmall; + Image* m_imageBioPortraitLarge; AsciiString m_strCampaign; AsciiString m_strPlayerTemplateName; AsciiString m_strPortraitMovieLeftName; AsciiString m_strPortraitMovieRightName; - Image *m_imageDefeated; - Image *m_imageVictorious; + Image* m_imageDefeated; + Image* m_imageVictorious; AsciiString m_strDefeated; AsciiString m_strVictorious; AsciiString m_strSelectionSound; @@ -72,16 +72,15 @@ class GeneralPersona AsciiString m_strWinSound; AsciiString m_strLossSound; AsciiString m_strPreviewSound; - AsciiString m_strNameSound ; - + AsciiString m_strNameSound; public: - GeneralPersona() : - m_imageBioPortraitSmall(nullptr), - m_imageBioPortraitLarge(nullptr) + GeneralPersona() + : m_imageBioPortraitSmall(nullptr) + , m_imageBioPortraitLarge(nullptr) { } -// ~GeneralPersona(); + // ~GeneralPersona(); Bool isStartingEnabled() const { return m_bStartsEnabled; } const AsciiString& getBioName() const { return m_strBioName; } @@ -91,22 +90,25 @@ class GeneralPersona const AsciiString& getBioRank() const { return m_strBioRank; } const AsciiString& getBioClassNumber() const { return m_strBioClassNumber; } const AsciiString& getBioBranch() const { return m_strBioBranch; } - const Image *getBioPortraitSmall() const { return m_imageBioPortraitSmall; } - const Image *getBioPortraitLarge() const { return m_imageBioPortraitLarge; } + const Image* getBioPortraitSmall() const { return m_imageBioPortraitSmall; } + const Image* getBioPortraitLarge() const { return m_imageBioPortraitLarge; } const AsciiString& getPortraitMovieLeftName() const { return m_strPortraitMovieLeftName; } const AsciiString& getPortraitMovieRightName() const { return m_strPortraitMovieRightName; } const AsciiString& getCampaign() const { return m_strCampaign; } - const AsciiString& getPlayerTemplateName() const { return m_strPlayerTemplateName; } // template name, as parsed in from ini - const Image *getImageDefeated() const { return m_imageDefeated; } - const Image *getImageVictorious() const { return m_imageVictorious; } + const AsciiString& getPlayerTemplateName() const { return m_strPlayerTemplateName; } // template name, as parsed in from ini + const Image* getImageDefeated() const { return m_imageDefeated; } + const Image* getImageVictorious() const { return m_imageVictorious; } const AsciiString& getStringDefeated() const { return m_strDefeated; } const AsciiString& getStringVictorious() const { return m_strVictorious; } const AsciiString& getSelectionSound() const { return m_strSelectionSound; } - const AsciiString& getRandomTauntSound() const { - switch (rand()%3) // don't care about distribution or exactly how random this is + const AsciiString& getRandomTauntSound() const + { + switch (rand() % 3) // don't care about distribution or exactly how random this is { - case 0: return m_strTauntSound1; - case 1: return m_strTauntSound2; + case 0: + return m_strTauntSound1; + case 1: + return m_strTauntSound2; } return m_strTauntSound3; } @@ -116,16 +118,15 @@ class GeneralPersona const AsciiString& getNameSound() const { return m_strNameSound; } }; - class ChallengeGenerals { private: - /*const*/ GeneralPersona m_position[ NUM_GENERALS ]; - Int m_PlayerTemplateNum; // the template number as ThePlayerTemplateStore has it - GameDifficulty m_currentDifficulty; // the last selected game difficulty for the challenge generals + /*const*/ GeneralPersona m_position[NUM_GENERALS]; + Int m_PlayerTemplateNum; // the template number as ThePlayerTemplateStore has it + GameDifficulty m_currentDifficulty; // the last selected game difficulty for the challenge generals - static void parseGeneralPersona( INI* ini, void *instance, void *store, const void *userData ); + static void parseGeneralPersona(INI* ini, void* instance, void* store, const void* userData); public: ChallengeGenerals(); @@ -133,23 +134,21 @@ class ChallengeGenerals void init(); const GeneralPersona* getChallengeGenerals() const { return m_position; } - const FieldParse* getFieldParse() const { return s_fieldParseTable; } // for INI file parsing - const GeneralPersona* getPlayerGeneralByCampaignName( AsciiString name ) const; - const GeneralPersona* getGeneralByGeneralName( AsciiString name ) const; - const GeneralPersona* getGeneralByTemplateName( AsciiString name ) const; + const FieldParse* getFieldParse() const { return s_fieldParseTable; } // for INI file parsing + const GeneralPersona* getPlayerGeneralByCampaignName(AsciiString name) const; + const GeneralPersona* getGeneralByGeneralName(AsciiString name) const; + const GeneralPersona* getGeneralByTemplateName(AsciiString name) const; - void setCurrentPlayerTemplateNum( Int playerTemplateNum) { m_PlayerTemplateNum = playerTemplateNum; } + void setCurrentPlayerTemplateNum(Int playerTemplateNum) { m_PlayerTemplateNum = playerTemplateNum; } Int getCurrentPlayerTemplateNum() { return m_PlayerTemplateNum; } - void setCurrentDifficulty( GameDifficulty diff ) { m_currentDifficulty = diff; } + void setCurrentDifficulty(GameDifficulty diff) { m_currentDifficulty = diff; } GameDifficulty getCurrentDifficulty() { return m_currentDifficulty; } + protected: static const FieldParse s_fieldParseTable[]; - }; - - // EXTERNALS ////////////////////////////////////////////////////////////////////////////////////// -extern ChallengeGenerals *TheChallengeGenerals; -extern ChallengeGenerals *createChallengeGenerals(); +extern ChallengeGenerals* TheChallengeGenerals; +extern ChallengeGenerals* createChallengeGenerals(); diff --git a/Core/GameEngine/Include/GameClient/ClientInstance.h b/Core/GameEngine/Include/GameClient/ClientInstance.h index 1f1ada1daca..43ee5beb1a6 100644 --- a/Core/GameEngine/Include/GameClient/ClientInstance.h +++ b/Core/GameEngine/Include/GameClient/ClientInstance.h @@ -54,4 +54,4 @@ class ClientInstance static Bool s_isMultiInstance; }; -} // namespace rts +} // namespace rts diff --git a/Core/GameEngine/Include/GameClient/ClientRandomValue.h b/Core/GameEngine/Include/GameClient/ClientRandomValue.h index bd0842d22a8..fb2b8c40eb4 100644 --- a/Core/GameEngine/Include/GameClient/ClientRandomValue.h +++ b/Core/GameEngine/Include/GameClient/ClientRandomValue.h @@ -32,12 +32,12 @@ #include "Lib/BaseType.h" // do NOT use these functions directly, rather use the macros below -extern Int GetGameClientRandomValue( int lo, int hi, const char *file, int line ); -extern Real GetGameClientRandomValueReal( Real lo, Real hi, const char *file, int line ); +extern Int GetGameClientRandomValue(int lo, int hi, const char* file, int line); +extern Real GetGameClientRandomValueReal(Real lo, Real hi, const char* file, int line); // use these macros to access the random value functions -#define GameClientRandomValue( lo, hi ) GetGameClientRandomValue( lo, hi, __FILE__, __LINE__ ) -#define GameClientRandomValueReal( lo, hi ) GetGameClientRandomValueReal( lo, hi, __FILE__, __LINE__ ) +#define GameClientRandomValue(lo, hi) GetGameClientRandomValue(lo, hi, __FILE__, __LINE__) +#define GameClientRandomValueReal(lo, hi) GetGameClientRandomValueReal(lo, hi, __FILE__, __LINE__) //-------------------------------------------------------------------------------------------------------------- class CColorAlphaDialog; @@ -65,27 +65,32 @@ class GameClientRandomVariable */ enum DistributionType { - CONSTANT, UNIFORM, GAUSSIAN, TRIANGULAR, LOW_BIAS, HIGH_BIAS, + CONSTANT, + UNIFORM, + GAUSSIAN, + TRIANGULAR, + LOW_BIAS, + HIGH_BIAS, DISTRIBUTION_COUNT }; - static const char *const DistributionTypeNames[]; + static const char* const DistributionTypeNames[]; /// define the range of random values, and the distribution of values - void setRange( Real low, Real high, DistributionType type = UNIFORM ); + void setRange(Real low, Real high, DistributionType type = UNIFORM); - Real getValue() const; ///< return a value from the random distribution + Real getValue() const; ///< return a value from the random distribution Real getMinimumValue() const { return m_low; } Real getMaximumValue() const { return m_high; } DistributionType getDistributionType() const { return m_type; } + protected: - DistributionType m_type; ///< the kind of random distribution - Real m_low, m_high; ///< the range of random values + DistributionType m_type; ///< the kind of random distribution + Real m_low, m_high; ///< the range of random values // These two friends are for particle editing. friend CColorAlphaDialog; friend DebugWindowDialog; - }; //-------------------------------------------------------------------------------------------------------------- diff --git a/Core/GameEngine/Include/GameClient/Color.h b/Core/GameEngine/Include/GameClient/Color.h index 3146f86fc26..9d6b7009fc7 100644 --- a/Core/GameEngine/Include/GameClient/Color.h +++ b/Core/GameEngine/Include/GameClient/Color.h @@ -53,7 +53,10 @@ // FORWARD REFERENCES ///////////////////////////////////////////////////////// // TYPE DEFINES /////////////////////////////////////////////////////////////// -enum { GAME_COLOR_UNDEFINED = 0x00FFFFFF }; // this is white with zero alpha... safe to use! +enum +{ + GAME_COLOR_UNDEFINED = 0x00FFFFFF +}; // this is white with zero alpha... safe to use! /** @todo we need real color representation, this is just placeholder so we can more easily identify sections of the code that need it */ @@ -63,25 +66,24 @@ typedef Int Color; // EXTERNALS ////////////////////////////////////////////////////////////////// -inline Color GameMakeColor( UnsignedByte red, UnsignedByte green, UnsignedByte blue, UnsignedByte alpha ) +inline Color GameMakeColor(UnsignedByte red, UnsignedByte green, UnsignedByte blue, UnsignedByte alpha) { return (alpha << 24) | (red << 16) | (green << 8) | (blue); } -extern void GameGetColorComponents( Color color, - UnsignedByte *red, - UnsignedByte *green, - UnsignedByte *blue, - UnsignedByte *alpha ); +extern void GameGetColorComponents(Color color, + UnsignedByte* red, + UnsignedByte* green, + UnsignedByte* blue, + UnsignedByte* alpha); // Put on ice until later - M Lorenzen -//extern void GameGetColorComponentsWithCheatSpy( Color color, +// extern void GameGetColorComponentsWithCheatSpy( Color color, // UnsignedByte *red, // UnsignedByte *green, // UnsignedByte *blue, // UnsignedByte *alpha ); +extern void GameGetColorComponentsReal(Color color, Real* red, Real* green, Real* blue, Real* alpha); -extern void GameGetColorComponentsReal( Color color, Real *red, Real *green, Real *blue, Real *alpha ); - -extern Color GameDarkenColor( Color color, Int percent = 10 ); +extern Color GameDarkenColor(Color color, Int percent = 10); diff --git a/Core/GameEngine/Include/GameClient/Credits.h b/Core/GameEngine/Include/GameClient/Credits.h index 2a9f19952e6..1eb8d90802d 100644 --- a/Core/GameEngine/Include/GameClient/Credits.h +++ b/Core/GameEngine/Include/GameClient/Credits.h @@ -63,28 +63,28 @@ class DisplayString; //----------------------------------------------------------------------------- enum { -CREDIT_STYLE_TITLE = 0, -CREDIT_STYLE_POSITION, -CREDIT_STYLE_NORMAL, -CREDIT_STYLE_COLUMN, -CREDIT_STYLE_BLANK, ///< Keep this second to last + CREDIT_STYLE_TITLE = 0, + CREDIT_STYLE_POSITION, + CREDIT_STYLE_NORMAL, + CREDIT_STYLE_COLUMN, + CREDIT_STYLE_BLANK, ///< Keep this second to last -MAX_CREDIT_STYLES + MAX_CREDIT_STYLES }; -enum{ CREDIT_SPACE_OFFSET = 2 }; - -static const LookupListRec CreditStyleNames[] = +enum { - { "TITLE", CREDIT_STYLE_TITLE }, - { "MINORTITLE", CREDIT_STYLE_POSITION }, - { "NORMAL", CREDIT_STYLE_NORMAL }, - { "COLUMN", CREDIT_STYLE_COLUMN }, - // CREDIT_STYLE_BLANK - { nullptr, 0 } + CREDIT_SPACE_OFFSET = 2 }; -static_assert(ARRAY_SIZE(CreditStyleNames) == MAX_CREDIT_STYLES, "Incorrect array size"); +static const LookupListRec CreditStyleNames[] = { + {"TITLE", CREDIT_STYLE_TITLE}, + {"MINORTITLE", CREDIT_STYLE_POSITION}, + {"NORMAL", CREDIT_STYLE_NORMAL}, + {"COLUMN", CREDIT_STYLE_COLUMN}, + // CREDIT_STYLE_BLANK + {nullptr, 0}}; +static_assert(ARRAY_SIZE(CreditStyleNames) == MAX_CREDIT_STYLES, "Incorrect array size"); class CreditsLine { @@ -92,22 +92,22 @@ class CreditsLine CreditsLine(); ~CreditsLine(); -// parsing variables + // parsing variables Int m_style; UnicodeString m_text; UnicodeString m_secondText; Bool m_useSecond; Bool m_done; -// drawing variables - DisplayString *m_displayString; - DisplayString *m_secondDisplayString; + // drawing variables + DisplayString* m_displayString; + DisplayString* m_secondDisplayString; ICoord2D m_pos; Int m_height; Int m_color; }; -class CreditsManager: public SubsystemInterface +class CreditsManager : public SubsystemInterface { public: CreditsManager(); @@ -119,31 +119,31 @@ class CreditsManager: public SubsystemInterface virtual void update() override; virtual void draw() override; - const FieldParse *getFieldParse() const { return m_creditsFieldParseTable; } ///< returns the parsing fields - static const FieldParse m_creditsFieldParseTable[]; ///< the parse table - static void parseBlank( INI* ini, void *instance, void *store, const void *userData ); ///< Parse the image part of the INI file - static void parseText( INI* ini, void *instance, void *store, const void *userData ); ///< Parse the image part of the INI file + const FieldParse* getFieldParse() const { return m_creditsFieldParseTable; } ///< returns the parsing fields + static const FieldParse m_creditsFieldParseTable[]; ///< the parse table + static void parseBlank(INI* ini, void* instance, void* store, const void* userData); ///< Parse the image part of the INI file + static void parseText(INI* ini, void* instance, void* store, const void* userData); ///< Parse the image part of the INI file - Bool isFinished() { return m_isFinished; } + Bool isFinished() { return m_isFinished; } void addBlank(); - void addText( AsciiString text ); -private: + void addText(AsciiString text); +private: UnicodeString getUnicodeString(AsciiString str); - typedef std::list CreditsLineList; + typedef std::list CreditsLineList; CreditsLineList m_creditLineList; CreditsLineList::iterator m_creditLineListIt; CreditsLineList m_displayedCreditLineList; - Int m_scrollRate; // in pixels + Int m_scrollRate; // in pixels Int m_scrollRatePerFrames; - Bool m_scrollDown; // if TRUE text will come from the top to the bottom if False, it will go from the bottom up + Bool m_scrollDown; // if TRUE text will come from the top to the bottom if False, it will go from the bottom up - Color m_titleColor; - Color m_positionColor; - Color m_normalColor; + Color m_titleColor; + Color m_positionColor; + Color m_normalColor; Int m_currentStyle; @@ -153,7 +153,6 @@ class CreditsManager: public SubsystemInterface Int m_normalFontHeight; }; - //----------------------------------------------------------------------------- // INLINING /////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- @@ -161,4 +160,4 @@ class CreditsManager: public SubsystemInterface //----------------------------------------------------------------------------- // EXTERNALS ////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- -extern CreditsManager *TheCredits; +extern CreditsManager* TheCredits; diff --git a/Core/GameEngine/Include/GameClient/DisplayString.h b/Core/GameEngine/Include/GameClient/DisplayString.h index 042ab1e6963..0da729ab619 100644 --- a/Core/GameEngine/Include/GameClient/DisplayString.h +++ b/Core/GameEngine/Include/GameClient/DisplayString.h @@ -63,55 +63,52 @@ class DisplayStringManager; // DisplayString -------------------------------------------------------------- /** String representation that can also has additional information and - * methods for drawing to the screen */ + * methods for drawing to the screen */ //----------------------------------------------------------------------------- class DisplayString : public MemoryPoolObject { - MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE( DisplayString, "DisplayString" ) + MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(DisplayString, "DisplayString") public: - friend DisplayStringManager; DisplayString(); // virtual ~DisplayString(); // destructor defined by memory pool - virtual void setText( UnicodeString text ); ///< set text for this string - virtual UnicodeString getText(); ///< get text for this string - virtual Int getTextLength(); ///< return number of chars in string - virtual void notifyTextChanged(); ///< called when text has changed - virtual void reset(); ///< reset all contents of string + virtual void setText(UnicodeString text); ///< set text for this string + virtual UnicodeString getText(); ///< get text for this string + virtual Int getTextLength(); ///< return number of chars in string + virtual void notifyTextChanged(); ///< called when text has changed + virtual void reset(); ///< reset all contents of string - virtual void setFont( GameFont *font ); ///< set a font for display - virtual GameFont *getFont(); ///< return font in string - virtual void setWordWrap( Int wordWrap ) = 0; ///< Set the width that we want to start wrapping text - virtual void setWordWrapCentered( Bool isCentered ) = 0; ///< If this is set to true, the text on a new line is centered - virtual void draw( Int x, Int y, Color color, Color dropColor ) = 0; ///< render text - virtual void draw( Int x, Int y, Color color, Color dropColor, Int xDrop, Int yDrop ) = 0; ///< render text with the drop shadow being at the offsets passed in - virtual void getSize( Int *width, Int *height ) = 0; ///< get render size - virtual Int getWidth( Int charPos = -1 ) = 0; ///< get text with up to charPos characters, 1- = all characters + virtual void setFont(GameFont* font); ///< set a font for display + virtual GameFont* getFont(); ///< return font in string + virtual void setWordWrap(Int wordWrap) = 0; ///< Set the width that we want to start wrapping text + virtual void setWordWrapCentered(Bool isCentered) = 0; ///< If this is set to true, the text on a new line is centered + virtual void draw(Int x, Int y, Color color, Color dropColor) = 0; ///< render text + virtual void draw(Int x, Int y, Color color, Color dropColor, Int xDrop, Int yDrop) = 0; ///< render text with the drop shadow being at the offsets passed in + virtual void getSize(Int* width, Int* height) = 0; ///< get render size + virtual Int getWidth(Int charPos = -1) = 0; ///< get text with up to charPos characters, 1- = all characters - virtual void setUseHotkey( Bool useHotkey, Color hotKeyColor ) = 0; + virtual void setUseHotkey(Bool useHotkey, Color hotKeyColor) = 0; - virtual void setClipRegion( IRegion2D *region ); ///< clip text in this region + virtual void setClipRegion(IRegion2D* region); ///< clip text in this region - virtual void removeLastChar(); ///< remove the last character - virtual void truncateBy(const Int charCount); ///< remove the last charCount characters - virtual void truncateTo(const Int maxLength); ///< remove characters, if needed, until the string is maxLength long excluding null terminator + virtual void removeLastChar(); ///< remove the last character + virtual void truncateBy(const Int charCount); ///< remove the last charCount characters + virtual void truncateTo(const Int maxLength); ///< remove characters, if needed, until the string is maxLength long excluding null terminator - virtual void appendChar( WideChar c ); ///< append character to end + virtual void appendChar(WideChar c); ///< append character to end - DisplayString *next(); ///< return next string + DisplayString* next(); ///< return next string protected: - UnicodeString m_textString; - GameFont *m_font; ///< font to display this string with - - DisplayString *m_next; ///< for the display string factory list ONLY - DisplayString *m_prev; ///< for the display string factory list ONLY + GameFont* m_font; ///< font to display this string with + DisplayString* m_next; ///< for the display string factory list ONLY + DisplayString* m_prev; ///< for the display string factory list ONLY }; /////////////////////////////////////////////////////////////////////////////// @@ -119,10 +116,10 @@ class DisplayString : public MemoryPoolObject /////////////////////////////////////////////////////////////////////////////// inline UnicodeString DisplayString::getText() { return m_textString; } inline Int DisplayString::getTextLength() { return m_textString.getLength(); } -inline void DisplayString::setFont( GameFont *font ) { m_font = font; } -inline GameFont *DisplayString::getFont() { return m_font; } -inline void DisplayString::setClipRegion( IRegion2D *region ) {} +inline void DisplayString::setFont(GameFont* font) { m_font = font; } +inline GameFont* DisplayString::getFont() { return m_font; } +inline void DisplayString::setClipRegion(IRegion2D* region) {} inline void DisplayString::notifyTextChanged() {} -inline DisplayString *DisplayString::next() { return m_next; } +inline DisplayString* DisplayString::next() { return m_next; } // EXTERNALS ////////////////////////////////////////////////////////////////// diff --git a/Core/GameEngine/Include/GameClient/DisplayStringManager.h b/Core/GameEngine/Include/GameClient/DisplayStringManager.h index bca43f0214f..ad5909def9d 100644 --- a/Core/GameEngine/Include/GameClient/DisplayStringManager.h +++ b/Core/GameEngine/Include/GameClient/DisplayStringManager.h @@ -39,27 +39,26 @@ class DisplayStringManager : public SubsystemInterface { public: - DisplayStringManager(); virtual ~DisplayStringManager() override; - virtual void init() override {} ///< initialize the factory - virtual void reset() override {} ///< reset system - virtual void update() override {}; ///< update anything we need to in our strings + virtual void init() override {} ///< initialize the factory + virtual void reset() override {} ///< reset system + virtual void update() override {}; ///< update anything we need to in our strings - virtual DisplayString *newDisplayString() = 0; ///< allocate new display string - virtual void freeDisplayString( DisplayString *string ) = 0; ///< free string + virtual DisplayString* newDisplayString() = 0; ///< allocate new display string + virtual void freeDisplayString(DisplayString* string) = 0; ///< free string - virtual DisplayString *getGroupNumeralString( Int numeral ) = 0; - virtual DisplayString *getFormationLetterString() = 0; -protected: + virtual DisplayString* getGroupNumeralString(Int numeral) = 0; + virtual DisplayString* getFormationLetterString() = 0; - void link( DisplayString *string ); ///< link display string to list - void unLink( DisplayString *string ); ///< unlink display string from list +protected: + void link(DisplayString* string); ///< link display string to list + void unLink(DisplayString* string); ///< unlink display string from list - DisplayString *m_stringList; ///< list of all display strings - DisplayString *m_currentCheckpoint; ///< current checkpoint of strings to be freed + DisplayString* m_stringList; ///< list of all display strings + DisplayString* m_currentCheckpoint; ///< current checkpoint of strings to be freed }; // EXTERNALS ////////////////////////////////////////////////////////////////////////////////////// -extern DisplayStringManager *TheDisplayStringManager; ///< singleton extern +extern DisplayStringManager* TheDisplayStringManager; ///< singleton extern diff --git a/Core/GameEngine/Include/GameClient/DrawGroupInfo.h b/Core/GameEngine/Include/GameClient/DrawGroupInfo.h index 1ece4db4b5c..681390d9a23 100644 --- a/Core/GameEngine/Include/GameClient/DrawGroupInfo.h +++ b/Core/GameEngine/Include/GameClient/DrawGroupInfo.h @@ -57,8 +57,8 @@ struct DrawGroupInfo DrawGroupInfo(); - static const FieldParse s_fieldParseTable[]; ///< the parse table for INI definition - const FieldParse *getFieldParse() const { return s_fieldParseTable; } + static const FieldParse s_fieldParseTable[]; ///< the parse table for INI definition + const FieldParse* getFieldParse() const { return s_fieldParseTable; } }; -extern DrawGroupInfo *TheDrawGroupInfo; +extern DrawGroupInfo* TheDrawGroupInfo; diff --git a/Core/GameEngine/Include/GameClient/FXList.h b/Core/GameEngine/Include/GameClient/FXList.h index 2d08f0335ec..c093bce14c4 100644 --- a/Core/GameEngine/Include/GameClient/FXList.h +++ b/Core/GameEngine/Include/GameClient/FXList.h @@ -44,104 +44,102 @@ class Matrix3D; //------------------------------------------------------------------------------------------------- /** - An FXNugget encapsulates a particular type of audio/video effect. FXNuggets are virtually - never used on their own, but rather, as a component of an FXList (see below). + An FXNugget encapsulates a particular type of audio/video effect. FXNuggets are virtually + never used on their own, but rather, as a component of an FXList (see below). - Important notes: + Important notes: - -- FXNugget is an ABC; all the implementations are (currently) located in FXList.cpp, - thought they will probably be spread out more as we add more implementations. + -- FXNugget is an ABC; all the implementations are (currently) located in FXList.cpp, + thought they will probably be spread out more as we add more implementations. - -- As part of an FXList, an FXNugget is shared between multiple units. The implication is that - an FXNugget should not require private data storage to do what it needs to do, aside from stuff - initialized at FXNugget instantiation time (eg, parameters from an INI file). To help - enforce this, all it's methods are declared 'const'. If you can't implement what you - need within this framework, please *don't* simply de-const things, because it could lead to very - strange side-effects. Instead, the system will have to be enhanced to allow for multiple instances - of each FXNugget. + -- As part of an FXList, an FXNugget is shared between multiple units. The implication is that + an FXNugget should not require private data storage to do what it needs to do, aside from stuff + initialized at FXNugget instantiation time (eg, parameters from an INI file). To help + enforce this, all it's methods are declared 'const'. If you can't implement what you + need within this framework, please *don't* simply de-const things, because it could lead to very + strange side-effects. Instead, the system will have to be enhanced to allow for multiple instances + of each FXNugget. - -- an individual FXNugget is generally not directly accessible to anyone outside of the - FXList system; in fact, it could probably be a private class, but isn't, mainly for coding convenience. + -- an individual FXNugget is generally not directly accessible to anyone outside of the + FXList system; in fact, it could probably be a private class, but isn't, mainly for coding convenience. - -- Unlike most other game systems, FXNuggets can't be overridden by subsequent INI file - loads. This isn't really a problem, because all you really need to do to "override" one is to - specify a different one. + -- Unlike most other game systems, FXNuggets can't be overridden by subsequent INI file + loads. This isn't really a problem, because all you really need to do to "override" one is to + specify a different one. */ class FXNugget : public MemoryPoolObject { MEMORY_POOL_GLUE_ABC(FXNugget) public: - - FXNugget() { } - //virtual ~FXNugget() { } + FXNugget() {} + // virtual ~FXNugget() { } /** - The main guts of the system: actually perform the sound and/or video effects - needed. Note that primary and/or secondary can be null, so you must check for this. + The main guts of the system: actually perform the sound and/or video effects + needed. Note that primary and/or secondary can be null, so you must check for this. */ - virtual void doFXPos(const Coord3D *primary, const Matrix3D* primaryMtx = nullptr, const Real primarySpeed = 0.0f, const Coord3D *secondary = nullptr, const Real overrideRadius = 0.0f) const = 0; + virtual void doFXPos(const Coord3D* primary, const Matrix3D* primaryMtx = nullptr, const Real primarySpeed = 0.0f, const Coord3D* secondary = nullptr, const Real overrideRadius = 0.0f) const = 0; /** - the object-based version... by default, just call the location-based implementation. - Note that primary and/or secondary can be null, so you must check for this. + the object-based version... by default, just call the location-based implementation. + Note that primary and/or secondary can be null, so you must check for this. */ virtual void doFXObj(const Object* primary, const Object* secondary = nullptr) const; private: - }; EMPTY_DTOR(FXNugget) //------------------------------------------------------------------------------------------------- /** - An FXList is a way of encapsulating a particular set of audio/video effect(s). - Lots of other game systems (eg, DamageFX) use FXLists to abstract AV effects into data files - (rather than hardcoding them, which would be suboptimal). + An FXList is a way of encapsulating a particular set of audio/video effect(s). + Lots of other game systems (eg, DamageFX) use FXLists to abstract AV effects into data files + (rather than hardcoding them, which would be suboptimal). - Important notes: + Important notes: - -- an FXList is specified solely by name, and the only parameters it receives when performing - its AV effects are a primary (and optional secondary) object position. + -- an FXList is specified solely by name, and the only parameters it receives when performing + its AV effects are a primary (and optional secondary) object position. - -- There is no inheritance or overriding of FXLists; if you need an FXList that is nearly-but-not-quite - identical to an existing one, you must simply make an entirely new FXList. Realistically, this shouldn't - be a problem, since they are pretty simple to specify, and don't consume a lot of memory. + -- There is no inheritance or overriding of FXLists; if you need an FXList that is nearly-but-not-quite + identical to an existing one, you must simply make an entirely new FXList. Realistically, this shouldn't + be a problem, since they are pretty simple to specify, and don't consume a lot of memory. - -- an FXList is shared between multiple units. To help - enforce this, all it's methods are declared 'const'. If you can't implement the stuff you - need within this framework, please *don't* simply de-const things, because it could lead to very - strange side-effects. Instead, the system will have to be enhanced to allow for multiple instances - of each FXNugget. + -- an FXList is shared between multiple units. To help + enforce this, all it's methods are declared 'const'. If you can't implement the stuff you + need within this framework, please *don't* simply de-const things, because it could lead to very + strange side-effects. Instead, the system will have to be enhanced to allow for multiple instances + of each FXNugget. - -- Unlike most other game systems, FXList can't be overridden by subsequent INI file - loads. This isn't really a problem, because all you really need to do to "override" one is to - specify a different one. + -- Unlike most other game systems, FXList can't be overridden by subsequent INI file + loads. This isn't really a problem, because all you really need to do to "override" one is to + specify a different one. */ class FXList { public: - FXList(); virtual ~FXList(); /** - Toss the contents. + Toss the contents. */ void clear(); /** - add a nugget to the list. It belongs to the FXList, who is responsible for freeing it. + add a nugget to the list. It belongs to the FXList, who is responsible for freeing it. */ - void addFXNugget(FXNugget *fxn) + void addFXNugget(FXNugget* fxn) { m_nuggets.push_back(fxn); } /// inline convenience method to avoid having to check for null. - inline static void doFXPos(const FXList* fx, const Coord3D *primary, const Matrix3D* primaryMtx = nullptr, const Real primarySpeed = 0.0f, const Coord3D *secondary = nullptr, const Real overrideRadius = 0.0f) + inline static void doFXPos(const FXList* fx, const Coord3D* primary, const Matrix3D* primaryMtx = nullptr, const Real primarySpeed = 0.0f, const Coord3D* secondary = nullptr, const Real overrideRadius = 0.0f) { - if (fx) fx->doFXPos(primary, primaryMtx, primarySpeed, secondary, overrideRadius); + if (fx) + fx->doFXPos(primary, primaryMtx, primarySpeed, secondary, overrideRadius); } /// inline convenience method to avoid having to check for null. @@ -151,69 +149,60 @@ class FXList { fx->doFXObj(primary, secondary); - //if (fx->) // here we need to cal doFXRicochet, if fx calls for it - + // if (fx->) // here we need to cal doFXRicochet, if fx calls for it } - } - - protected: - - /** - The main guts of the system: actually perform the sound and/or video effects - needed. Note that primary and/or secondary can be null, so you must check for this. + The main guts of the system: actually perform the sound and/or video effects + needed. Note that primary and/or secondary can be null, so you must check for this. */ - void doFXPos(const Coord3D *primary, const Matrix3D* primaryMtx = nullptr, const Real primarySpeed = 0.0f, const Coord3D *secondary = nullptr, const Real overrideRadius = 0.0f) const; + void doFXPos(const Coord3D* primary, const Matrix3D* primaryMtx = nullptr, const Real primarySpeed = 0.0f, const Coord3D* secondary = nullptr, const Real overrideRadius = 0.0f) const; /** - the object-based version... by default, just call the location-based implementation. - Note that primary and/or secondary can be null, so you must check for this. + the object-based version... by default, just call the location-based implementation. + Note that primary and/or secondary can be null, so you must check for this. */ void doFXObj(const Object* primary, const Object* secondary = nullptr) const; private: - - typedef std::list< FXNugget* > FXNuggetList; + typedef std::list FXNuggetList; FXNuggetList m_nuggets; - }; //------------------------------------------------------------------------------------------------- /** - The "store" used to hold all the FXLists in existence. + The "store" used to hold all the FXLists in existence. */ class FXListStore : public SubsystemInterface { public: - FXListStore(); virtual ~FXListStore() override; - virtual void init() override { } - virtual void reset() override { } - virtual void update() override { } + virtual void init() override {} + virtual void reset() override {} + virtual void update() override {} /** - return the FXList with the given namekey. - return nullptr if no such FXList exists. + return the FXList with the given namekey. + return nullptr if no such FXList exists. */ - const FXList *findFXList( const char* name ) const; + const FXList* findFXList(const char* name) const; static void parseFXListDefinition(INI* ini); private: - // use the hashing function for Ints. - typedef std::hash_map< NameKeyType, FXList, rts::hash, rts::equal_to > FXListMap; + // clang-format off: [LEGACY_VC6] - preserve space in nested templates (> >) + typedef std::hash_map, rts::equal_to > FXListMap; + // clang-format on FXListMap m_fxmap; - }; // EXTERNALS ////////////////////////////////////////////////////////////////////////////////////// -extern FXListStore *TheFXListStore; +extern FXListStore* TheFXListStore; diff --git a/Core/GameEngine/Include/GameClient/GameFont.h b/Core/GameEngine/Include/GameClient/GameFont.h index 3b67bd19bb6..1b62f5adbb9 100644 --- a/Core/GameEngine/Include/GameClient/GameFont.h +++ b/Core/GameEngine/Include/GameClient/GameFont.h @@ -41,12 +41,12 @@ class GameFont : public MemoryPoolObject { MEMORY_POOL_GLUE_WITH_USERLOOKUP_CREATE(GameFont, "GameFont") public: - GameFont* next; ///< for library use - AsciiString nameString; - Int pointSize; ///< point size of font - Int height; ///< pixel height of font - void* fontData; ///< font data to be filled out for device specific font - Bool bold; ///< is this font bold + GameFont* next; ///< for library use + AsciiString nameString; + Int pointSize; ///< point size of font + Int height; ///< pixel height of font + void* fontData; ///< font data to be filled out for device specific font + Bool bold; ///< is this font bold }; EMPTY_DTOR(GameFont) @@ -57,49 +57,44 @@ class FontLibrary : public SubsystemInterface { public: - - public: - FontLibrary(); virtual ~FontLibrary() override; virtual void init() override; virtual void reset() override; - virtual void update() override { } + virtual void update() override {} - GameFont *getFont( AsciiString name, Int pointSize, Bool bold ); ///< get a font pointer + GameFont* getFont(AsciiString name, Int pointSize, Bool bold); ///< get a font pointer - GameFont *firstFont(); ///< return first font - GameFont *nextFont( GameFont *font ); ///< get next font in library + GameFont* firstFont(); ///< return first font + GameFont* nextFont(GameFont* font); ///< get next font in library - Int getCount(); ///< return how many fonts are loaded in this lib + Int getCount(); ///< return how many fonts are loaded in this lib protected: - - void deleteAllFonts(); ///< delete all fonts in this library - void linkFont( GameFont *font ); ///< add to font list - void unlinkFont( GameFont *font ); ///< remove font from list + void deleteAllFonts(); ///< delete all fonts in this library + void linkFont(GameFont* font); ///< add to font list + void unlinkFont(GameFont* font); ///< remove font from list /// load the font data pointer based on everything else we already have set - virtual Bool loadFontData( GameFont *font ) = 0; + virtual Bool loadFontData(GameFont* font) = 0; /// release the font data pointer - virtual void releaseFontData( GameFont *font ) { }; - - GameFont *m_fontList; ///< list of fonts we have loaded - Int m_count; ///< number of unique fonts loaded in this lib + virtual void releaseFontData(GameFont* font) {}; + GameFont* m_fontList; ///< list of fonts we have loaded + Int m_count; ///< number of unique fonts loaded in this lib }; // INLINING /////////////////////////////////////////////////////////////////////////////////////// inline Int FontLibrary::getCount() { return m_count; } -inline GameFont *FontLibrary::firstFont() { return m_fontList; } -inline GameFont *FontLibrary::nextFont( GameFont *font ) +inline GameFont* FontLibrary::firstFont() { return m_fontList; } +inline GameFont* FontLibrary::nextFont(GameFont* font) { - if( font ) + if (font) return font->next; return nullptr; } // EXTERNALS ////////////////////////////////////////////////////////////////////////////////////// -extern FontLibrary *TheFontLibrary; ///< font library external +extern FontLibrary* TheFontLibrary; ///< font library external diff --git a/Core/GameEngine/Include/GameClient/GameText.h b/Core/GameEngine/Include/GameClient/GameText.h index e7f6be21017..5e0b812700f 100644 --- a/Core/GameEngine/Include/GameClient/GameText.h +++ b/Core/GameEngine/Include/GameClient/GameText.h @@ -22,7 +22,6 @@ // // //////////////////////////////////////////////////////////////////////////////// - //---------------------------------------------------------------------------- // // Westwood Studios Pacific. @@ -62,44 +61,42 @@ typedef std::vector AsciiStringVec; // GameTextInterface //=============================== /** Game text interface object for localised text. - */ + */ //=============================== class GameTextInterface : public SubsystemInterface { - public: - - virtual ~GameTextInterface() override {}; +public: + virtual ~GameTextInterface() override {}; - virtual UnicodeString fetch( const Char *label, Bool *exists = nullptr ) = 0; ///< Returns the associated labeled unicode text - virtual UnicodeString fetch( AsciiString label, Bool *exists = nullptr ) = 0; ///< Returns the associated labeled unicode text ; TheSuperHackers @todo Remove - virtual UnicodeString fetchFormat( const Char *label, ... ) = 0; + virtual UnicodeString fetch(const Char* label, Bool* exists = nullptr) = 0; ///< Returns the associated labeled unicode text + virtual UnicodeString fetch(AsciiString label, Bool* exists = nullptr) = 0; ///< Returns the associated labeled unicode text ; TheSuperHackers @todo Remove + virtual UnicodeString fetchFormat(const Char* label, ...) = 0; - // Do not call this directly, but use the FETCH_OR_SUBSTITUTE macro - virtual UnicodeString fetchOrSubstitute( const Char *label, const WideChar *substituteText ) = 0; - virtual UnicodeString fetchOrSubstituteFormat( const Char *label, const WideChar *substituteFormat, ... ) = 0; - virtual UnicodeString fetchOrSubstituteFormatVA( const Char *label, const WideChar *substituteFormat, va_list args ) = 0; + // Do not call this directly, but use the FETCH_OR_SUBSTITUTE macro + virtual UnicodeString fetchOrSubstitute(const Char* label, const WideChar* substituteText) = 0; + virtual UnicodeString fetchOrSubstituteFormat(const Char* label, const WideChar* substituteFormat, ...) = 0; + virtual UnicodeString fetchOrSubstituteFormatVA(const Char* label, const WideChar* substituteFormat, va_list args) = 0; - // This function is not performance tuned.. Its really only for Worldbuilder. jkmcd - virtual AsciiStringVec& getStringsWithLabelPrefix(AsciiString label) = 0; + // This function is not performance tuned.. Its really only for Worldbuilder. jkmcd + virtual AsciiStringVec& getStringsWithLabelPrefix(AsciiString label) = 0; - virtual void initMapStringFile( const AsciiString& filename ) = 0; + virtual void initMapStringFile(const AsciiString& filename) = 0; -#if __cplusplus < 201103L // TheSuperHackers @todo Remove function when abandoning VC6 - inline UnicodeString FETCH_OR_SUBSTITUTE_FORMAT( const Char *label, const WideChar *substituteFormat, ... ) - { - va_list args; - va_start(args, substituteFormat); - UnicodeString str = fetchOrSubstituteFormatVA(label, substituteFormat, args); - va_end(args); - return str; - } +#if __cplusplus < 201103L // TheSuperHackers @todo Remove function when abandoning VC6 + inline UnicodeString FETCH_OR_SUBSTITUTE_FORMAT(const Char* label, const WideChar* substituteFormat, ...) + { + va_list args; + va_start(args, substituteFormat); + UnicodeString str = fetchOrSubstituteFormatVA(label, substituteFormat, args); + va_end(args); + return str; + } #endif }; - -extern GameTextInterface *TheGameText; +extern GameTextInterface* TheGameText; extern GameTextInterface* CreateGameTextInterface(); //---------------------------------------------------------------------------- @@ -118,16 +115,16 @@ extern GameTextInterface* CreateGameTextInterface(); // alternative, but ##__VA_ARGS__ is simpler and compatible across C++11/14/17/20. #if ENABLE_GAMETEXT_SUBSTITUTES -#define FETCH_OR_SUBSTITUTE(labelA, substituteTextW) fetchOrSubstitute(labelA, substituteTextW) -#if __cplusplus >= 201103L // TheSuperHackers @todo Remove condition when abandoning VC6 -#define FETCH_OR_SUBSTITUTE_FORMAT(labelA, substituteFormatW, ...) fetchOrSubstituteFormat(labelA, substituteFormatW, ##__VA_ARGS__) -#endif + #define FETCH_OR_SUBSTITUTE(labelA, substituteTextW) fetchOrSubstitute(labelA, substituteTextW) + #if __cplusplus >= 201103L // TheSuperHackers @todo Remove condition when abandoning VC6 + #define FETCH_OR_SUBSTITUTE_FORMAT(labelA, substituteFormatW, ...) fetchOrSubstituteFormat(labelA, substituteFormatW, ##__VA_ARGS__) + #endif #else -#define FETCH_OR_SUBSTITUTE(labelA, substituteTextW) fetch(labelA) -#if __cplusplus >= 201103L // TheSuperHackers @todo Remove condition when abandoning VC6 -#define FETCH_OR_SUBSTITUTE_FORMAT(labelA, substituteFormatW, ...) fetchFormat(labelA, ##__VA_ARGS__) -#endif + #define FETCH_OR_SUBSTITUTE(labelA, substituteTextW) fetch(labelA) + #if __cplusplus >= 201103L // TheSuperHackers @todo Remove condition when abandoning VC6 + #define FETCH_OR_SUBSTITUTE_FORMAT(labelA, substituteFormatW, ...) fetchFormat(labelA, ##__VA_ARGS__) + #endif -#endif // ENABLE_GAMETEXT_SUBSTITUTES +#endif // ENABLE_GAMETEXT_SUBSTITUTES diff --git a/Core/GameEngine/Include/GameClient/GameWindow.h b/Core/GameEngine/Include/GameClient/GameWindow.h index e96c94c96a0..0f344ff1844 100644 --- a/Core/GameEngine/Include/GameClient/GameWindow.h +++ b/Core/GameEngine/Include/GameClient/GameWindow.h @@ -69,83 +69,100 @@ struct GameWindowEditData; // TYPE DEFINES /////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// -enum { WIN_COLOR_UNDEFINED = GAME_COLOR_UNDEFINED }; +enum +{ + WIN_COLOR_UNDEFINED = GAME_COLOR_UNDEFINED +}; // WindowMsgData -------------------------------------------------------------- //----------------------------------------------------------------------------- typedef UnsignedInt WindowMsgData; //----------------------------------------------------------------------------- -enum WindowMsgHandledType CPP_11(: Int) { MSG_IGNORED, MSG_HANDLED }; +enum WindowMsgHandledType CPP_11( : Int) +{ + MSG_IGNORED, + MSG_HANDLED +}; // callback types ------------------------------------------------------------- -typedef void (*GameWinMsgBoxFunc)(); //used for the Message box callbacks. -typedef void (*GameWinDrawFunc)( GameWindow *, - WinInstanceData * ); -typedef void (*GameWinTooltipFunc)( GameWindow *, - WinInstanceData *, - UnsignedInt ); -typedef WindowMsgHandledType (*GameWinInputFunc)( GameWindow *, - UnsignedInt, - WindowMsgData, - WindowMsgData ); -typedef WindowMsgHandledType (*GameWinSystemFunc)( GameWindow *, - UnsignedInt, - WindowMsgData, - WindowMsgData ); +typedef void (*GameWinMsgBoxFunc)(); // used for the Message box callbacks. +typedef void (*GameWinDrawFunc)(GameWindow*, + WinInstanceData*); +typedef void (*GameWinTooltipFunc)(GameWindow*, + WinInstanceData*, + UnsignedInt); +typedef WindowMsgHandledType (*GameWinInputFunc)(GameWindow*, + UnsignedInt, + WindowMsgData, + WindowMsgData); +typedef WindowMsgHandledType (*GameWinSystemFunc)(GameWindow*, + UnsignedInt, + WindowMsgData, + WindowMsgData); enum { - WIN_MAX_WINDOWS = 576, - CURSOR_MOVE_TOL_SQ = 4, - TOOLTIP_DELAY = 10, - WIN_TOOLTIP_LEN = 64, // max length of tooltip text - + WIN_MAX_WINDOWS = 576, + CURSOR_MOVE_TOL_SQ = 4, + TOOLTIP_DELAY = 10, + WIN_TOOLTIP_LEN = 64, // max length of tooltip text }; // macros for easier conversion ----------------------------------------------- #define SHORTTOLONG(a, b) ((UnsignedShort)(a) | ((UnsignedShort)(b) << 16)) -#define LOLONGTOSHORT(a) ((a) & 0x0000FFFF) -#define HILONGTOSHORT(b) (((b) & 0xFFFF0000) >> 16) +#define LOLONGTOSHORT(a) ((a) & 0x0000FFFF) +#define HILONGTOSHORT(b) (((b) & 0xFFFF0000) >> 16) // Game window messages ------------------------------------------------------- //----------------------------------------------------------------------------- -enum GameWindowMessage CPP_11(: Int) +enum GameWindowMessage CPP_11( : Int) { GWM_NONE = 0, - GWM_CREATE, GWM_DESTROY, - GWM_ACTIVATE, GWM_ENABLE, - GWM_LEFT_DOWN, GWM_LEFT_UP, - GWM_LEFT_DOUBLE_CLICK, GWM_LEFT_DRAG, - GWM_MIDDLE_DOWN, GWM_MIDDLE_UP, - GWM_MIDDLE_DOUBLE_CLICK, GWM_MIDDLE_DRAG, - GWM_RIGHT_DOWN, GWM_RIGHT_UP, - GWM_RIGHT_DOUBLE_CLICK, GWM_RIGHT_DRAG, - GWM_MOUSE_ENTERING, GWM_MOUSE_LEAVING, - GWM_WHEEL_UP, GWM_WHEEL_DOWN, - GWM_CHAR, GWM_SCRIPT_CREATE, + GWM_CREATE, + GWM_DESTROY, + GWM_ACTIVATE, + GWM_ENABLE, + GWM_LEFT_DOWN, + GWM_LEFT_UP, + GWM_LEFT_DOUBLE_CLICK, + GWM_LEFT_DRAG, + GWM_MIDDLE_DOWN, + GWM_MIDDLE_UP, + GWM_MIDDLE_DOUBLE_CLICK, + GWM_MIDDLE_DRAG, + GWM_RIGHT_DOWN, + GWM_RIGHT_UP, + GWM_RIGHT_DOUBLE_CLICK, + GWM_RIGHT_DRAG, + GWM_MOUSE_ENTERING, + GWM_MOUSE_LEAVING, + GWM_WHEEL_UP, + GWM_WHEEL_DOWN, + GWM_CHAR, + GWM_SCRIPT_CREATE, // note that GWM_MOUSE_POS is only actually propagated to windows if the static // sendMousePosMessages is set to true in the window manager file. See the // comment on the static declaration for additional info - GWM_INPUT_FOCUS, GWM_MOUSE_POS, - GWM_IME_CHAR, GWM_IME_STRING - + GWM_INPUT_FOCUS, + GWM_MOUSE_POS, + GWM_IME_CHAR, + GWM_IME_STRING }; // WinInputReturnCode ------------------------------------------------------ /** These return codes are returned when after processing events through - * the window system */ + * the window system */ //----------------------------------------------------------------------------- -enum WinInputReturnCode CPP_11(: Int) +enum WinInputReturnCode CPP_11( : Int) { WIN_INPUT_NOT_USED = 0, WIN_INPUT_USED, }; - #define GWM_USER 32768 // Window status flags -------------------------------------------------------- @@ -154,59 +171,56 @@ enum { // when you edit this, remember to edit WindowStatusNames[] - WIN_STATUS_NONE = 0x00000000, // No status bits set at all - WIN_STATUS_ACTIVE = 0x00000001, // At the top of the window list - WIN_STATUS_TOGGLE = 0x00000002, // If set, click to toggle - WIN_STATUS_DRAGGABLE = 0x00000004, // Window can be dragged - WIN_STATUS_ENABLED = 0x00000008, // Window can receive input - WIN_STATUS_HIDDEN = 0x00000010, // Window is hidden, no input - WIN_STATUS_ABOVE = 0x00000020, // Window is always above others - WIN_STATUS_BELOW = 0x00000040, // Window is always below others - WIN_STATUS_IMAGE = 0x00000080, // Window is drawn with images - WIN_STATUS_TAB_STOP = 0x00000100, // Window is a tab stop - WIN_STATUS_NO_INPUT = 0x00000200, // Window does not take input - WIN_STATUS_NO_FOCUS = 0x00000400, // Window does not take focus - WIN_STATUS_DESTROYED = 0x00000800, // Window has been destroyed - WIN_STATUS_BORDER = 0x00001000, // Window will be drawn with Borders & Corners - WIN_STATUS_SMOOTH_TEXT = 0x00002000, // Window text will be drawn with smoothing - WIN_STATUS_ONE_LINE = 0x00004000, // Window text will be drawn on only one line - WIN_STATUS_NO_FLUSH = 0x00008000, // Window images will not be unloaded when window is hidden - WIN_STATUS_SEE_THRU = 0x00010000, // Will not draw, but it NOT hidden ... does not apply to children - WIN_STATUS_RIGHT_CLICK = 0x00020000, // Window pays attention to right clicks - WIN_STATUS_WRAP_CENTERED = 0x00040000, // Text will be centered on each word wrap or \n - WIN_STATUS_CHECK_LIKE = 0x00080000, // Make push buttons "check-like" with dual state - WIN_STATUS_HOTKEY_TEXT = 0x00100000, // Make push buttons "check-like" with dual state - WIN_STATUS_USE_OVERLAY_STATES = 0x00200000, // Push buttons will use the global automatic rendering overlay for disabled, hilited, and pushed. - WIN_STATUS_NOT_READY = 0x00400000, // A disabled button that is available -- but not yet (power charge, fire delay). - WIN_STATUS_FLASHING = 0x00800000, // Used for buttons that do cameo flashes. - WIN_STATUS_ALWAYS_COLOR = 0x01000000, // Never render these buttons using greyscale renderer when button disabled. - WIN_STATUS_ON_MOUSE_DOWN = 0x02000000, // Pushbutton triggers on mouse down. - WIN_STATUS_SHORTCUT_BUTTON = 0x04000000, // Oh god... this is a total hack for shortcut buttons to handle rendering text top left corner... - // when you edit this, remember to edit WindowStatusNames[] - + WIN_STATUS_NONE = 0x00000000, // No status bits set at all + WIN_STATUS_ACTIVE = 0x00000001, // At the top of the window list + WIN_STATUS_TOGGLE = 0x00000002, // If set, click to toggle + WIN_STATUS_DRAGGABLE = 0x00000004, // Window can be dragged + WIN_STATUS_ENABLED = 0x00000008, // Window can receive input + WIN_STATUS_HIDDEN = 0x00000010, // Window is hidden, no input + WIN_STATUS_ABOVE = 0x00000020, // Window is always above others + WIN_STATUS_BELOW = 0x00000040, // Window is always below others + WIN_STATUS_IMAGE = 0x00000080, // Window is drawn with images + WIN_STATUS_TAB_STOP = 0x00000100, // Window is a tab stop + WIN_STATUS_NO_INPUT = 0x00000200, // Window does not take input + WIN_STATUS_NO_FOCUS = 0x00000400, // Window does not take focus + WIN_STATUS_DESTROYED = 0x00000800, // Window has been destroyed + WIN_STATUS_BORDER = 0x00001000, // Window will be drawn with Borders & Corners + WIN_STATUS_SMOOTH_TEXT = 0x00002000, // Window text will be drawn with smoothing + WIN_STATUS_ONE_LINE = 0x00004000, // Window text will be drawn on only one line + WIN_STATUS_NO_FLUSH = 0x00008000, // Window images will not be unloaded when window is hidden + WIN_STATUS_SEE_THRU = 0x00010000, // Will not draw, but it NOT hidden ... does not apply to children + WIN_STATUS_RIGHT_CLICK = 0x00020000, // Window pays attention to right clicks + WIN_STATUS_WRAP_CENTERED = 0x00040000, // Text will be centered on each word wrap or \n + WIN_STATUS_CHECK_LIKE = 0x00080000, // Make push buttons "check-like" with dual state + WIN_STATUS_HOTKEY_TEXT = 0x00100000, // Make push buttons "check-like" with dual state + WIN_STATUS_USE_OVERLAY_STATES = 0x00200000, // Push buttons will use the global automatic rendering overlay for disabled, hilited, and pushed. + WIN_STATUS_NOT_READY = 0x00400000, // A disabled button that is available -- but not yet (power charge, fire delay). + WIN_STATUS_FLASHING = 0x00800000, // Used for buttons that do cameo flashes. + WIN_STATUS_ALWAYS_COLOR = 0x01000000, // Never render these buttons using greyscale renderer when button disabled. + WIN_STATUS_ON_MOUSE_DOWN = 0x02000000, // Pushbutton triggers on mouse down. + WIN_STATUS_SHORTCUT_BUTTON = 0x04000000, // Oh god... this is a total hack for shortcut buttons to handle rendering text top left corner... + // when you edit this, remember to edit WindowStatusNames[] }; - // Message Box Button flags -------------------------------------------------------- //----------------------------------------------------------------------------- enum { - MSG_BOX_YES = 0x01, //Display the yes button - MSG_BOX_NO = 0x02, //Display the No button - MSG_BOX_OK = 0x08, //Display the Ok button - MSG_BOX_CANCEL = 0x04, //Display the Cancel button + MSG_BOX_YES = 0x01, // Display the yes button + MSG_BOX_NO = 0x02, // Display the No button + MSG_BOX_OK = 0x08, // Display the Ok button + MSG_BOX_CANCEL = 0x04, // Display the Cancel button }; - // WindowMessageBoxData --------------------------------------------------------- /** Data attached to each Message box window */ //----------------------------------------------------------------------------- struct WindowMessageBoxData { - GameWinMsgBoxFunc yesCallback; ///