diff --git a/engine/shared/library/CMakeLists.txt b/engine/shared/library/CMakeLists.txt index f48f8838..ba4d0d11 100644 --- a/engine/shared/library/CMakeLists.txt +++ b/engine/shared/library/CMakeLists.txt @@ -4,8 +4,10 @@ add_subdirectory(sharedDebug) add_subdirectory(sharedFile) add_subdirectory(sharedFoundation) add_subdirectory(sharedFoundationTypes) +add_subdirectory(sharedGame) add_subdirectory(sharedLog) add_subdirectory(sharedMath) +add_subdirectory(sharedMathArchive) add_subdirectory(sharedMemoryManager) add_subdirectory(sharedMessageDispatch) add_subdirectory(sharedNetwork) @@ -13,3 +15,4 @@ add_subdirectory(sharedNetworkMessages) add_subdirectory(sharedRandom) add_subdirectory(sharedSynchronization) add_subdirectory(sharedThread) +add_subdirectory(sharedUtility) diff --git a/engine/shared/library/sharedGame/CMakeLists.txt b/engine/shared/library/sharedGame/CMakeLists.txt new file mode 100644 index 00000000..46239e97 --- /dev/null +++ b/engine/shared/library/sharedGame/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 2.8) + +project(sharedGame) + +if(WIN32) + add_definitions(/D_CRT_SECURE_NO_WARNINGS) +endif() + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/public) + +add_subdirectory(src) diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/AiDebugString.h b/engine/shared/library/sharedGame/include/public/sharedGame/AiDebugString.h new file mode 100644 index 00000000..18aac301 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/AiDebugString.h @@ -0,0 +1 @@ +#include "../../src/shared/core/AiDebugString.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/AppearanceManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/AppearanceManager.h new file mode 100644 index 00000000..81dbb739 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/AppearanceManager.h @@ -0,0 +1 @@ +#include "../../src/shared/object/AppearanceManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/AssetCustomizationManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/AssetCustomizationManager.h new file mode 100644 index 00000000..37d1296e --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/AssetCustomizationManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/AssetCustomizationManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/AsteroidGenerationManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/AsteroidGenerationManager.h new file mode 100644 index 00000000..6537375b --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/AsteroidGenerationManager.h @@ -0,0 +1 @@ +#include "../../src/shared/space/AsteroidGenerationManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/AttribMod.h b/engine/shared/library/sharedGame/include/public/sharedGame/AttribMod.h new file mode 100644 index 00000000..2ad1fdb0 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/AttribMod.h @@ -0,0 +1 @@ +#include "../../src/shared/object/AttribMod.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/AttribModArchive.h b/engine/shared/library/sharedGame/include/public/sharedGame/AttribModArchive.h new file mode 100644 index 00000000..04982ad9 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/AttribModArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/object/AttribModArchive.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/AuctionManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/AuctionManager.h new file mode 100644 index 00000000..07bd103f --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/AuctionManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/AuctionManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/AuctionToken.h b/engine/shared/library/sharedGame/include/public/sharedGame/AuctionToken.h new file mode 100644 index 00000000..3400b7aa --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/AuctionToken.h @@ -0,0 +1 @@ +#include "../../src/shared/core/AuctionToken.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/AuctionTokenArchive.h b/engine/shared/library/sharedGame/include/public/sharedGame/AuctionTokenArchive.h new file mode 100644 index 00000000..0138433a --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/AuctionTokenArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/core/AuctionTokenArchive.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/Buff.h b/engine/shared/library/sharedGame/include/public/sharedGame/Buff.h new file mode 100644 index 00000000..48a67577 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/Buff.h @@ -0,0 +1 @@ +#include "../../src/shared/object/Buff.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/CitizenRankDataTable.h b/engine/shared/library/sharedGame/include/public/sharedGame/CitizenRankDataTable.h new file mode 100644 index 00000000..bc65d830 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/CitizenRankDataTable.h @@ -0,0 +1 @@ +#include "../../src/shared/core/CitizenRankDataTable.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/CityData.h b/engine/shared/library/sharedGame/include/public/sharedGame/CityData.h new file mode 100644 index 00000000..678f8f23 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/CityData.h @@ -0,0 +1 @@ +#include "../../src/shared/core/CityData.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ClearCollidableFloraNotification.h b/engine/shared/library/sharedGame/include/public/sharedGame/ClearCollidableFloraNotification.h new file mode 100644 index 00000000..841ac4c1 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ClearCollidableFloraNotification.h @@ -0,0 +1 @@ +#error obsolete diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ClientCombatManagerSupport.h b/engine/shared/library/sharedGame/include/public/sharedGame/ClientCombatManagerSupport.h new file mode 100644 index 00000000..fc4506df --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ClientCombatManagerSupport.h @@ -0,0 +1 @@ +#include "../../src/shared/core/ClientCombatManagerSupport.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/CollectionsDataTable.h b/engine/shared/library/sharedGame/include/public/sharedGame/CollectionsDataTable.h new file mode 100644 index 00000000..0e9ab44f --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/CollectionsDataTable.h @@ -0,0 +1 @@ +#include "../../src/shared/core/CollectionsDataTable.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/CollisionCallbackManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/CollisionCallbackManager.h new file mode 100644 index 00000000..e7be364e --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/CollisionCallbackManager.h @@ -0,0 +1 @@ +#include "../../src/shared/collision/CollisionCallbackManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/CombatDataTable.h b/engine/shared/library/sharedGame/include/public/sharedGame/CombatDataTable.h new file mode 100644 index 00000000..eee3b02a --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/CombatDataTable.h @@ -0,0 +1 @@ +#include "../../src/shared/combat/CombatDataTable.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/CombatTimingTable.h b/engine/shared/library/sharedGame/include/public/sharedGame/CombatTimingTable.h new file mode 100644 index 00000000..5e723b68 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/CombatTimingTable.h @@ -0,0 +1 @@ +#include "../../src/shared/combat/CombatTimingTable.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/Command.h b/engine/shared/library/sharedGame/include/public/sharedGame/Command.h new file mode 100644 index 00000000..251a4afa --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/Command.h @@ -0,0 +1 @@ +#include "../../src/shared/command/Command.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/CommandChecks.h b/engine/shared/library/sharedGame/include/public/sharedGame/CommandChecks.h new file mode 100644 index 00000000..605db20b --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/CommandChecks.h @@ -0,0 +1 @@ +#include "../../src/shared/command/CommandChecks.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/CommandCppFunc.def b/engine/shared/library/sharedGame/include/public/sharedGame/CommandCppFunc.def new file mode 100644 index 00000000..69678583 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/CommandCppFunc.def @@ -0,0 +1 @@ +#include "../../src/shared/command/CommandCppFunc.def" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/CommandTable.h b/engine/shared/library/sharedGame/include/public/sharedGame/CommandTable.h new file mode 100644 index 00000000..43328354 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/CommandTable.h @@ -0,0 +1 @@ +#include "../../src/shared/command/CommandTable.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/CommoditiesAdvancedSearchAttribute.h b/engine/shared/library/sharedGame/include/public/sharedGame/CommoditiesAdvancedSearchAttribute.h new file mode 100644 index 00000000..669f5ce7 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/CommoditiesAdvancedSearchAttribute.h @@ -0,0 +1 @@ +#include "../../src/shared/core/CommoditiesAdvancedSearchAttribute.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ConfigSharedGame.h b/engine/shared/library/sharedGame/include/public/sharedGame/ConfigSharedGame.h new file mode 100644 index 00000000..74562ea7 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ConfigSharedGame.h @@ -0,0 +1 @@ +#include "../../src/shared/core/ConfigSharedGame.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/CraftingData.h b/engine/shared/library/sharedGame/include/public/sharedGame/CraftingData.h new file mode 100644 index 00000000..38f97dde --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/CraftingData.h @@ -0,0 +1,2 @@ +#include "../../src/shared/core/CraftingData.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/CraftingDataArchive.h b/engine/shared/library/sharedGame/include/public/sharedGame/CraftingDataArchive.h new file mode 100644 index 00000000..a4bea99e --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/CraftingDataArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/core/CraftingDataArchive.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/CustomizationManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/CustomizationManager.h new file mode 100644 index 00000000..f9dffd76 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/CustomizationManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/CustomizationManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/CustomizationManager_MorphParameter.h b/engine/shared/library/sharedGame/include/public/sharedGame/CustomizationManager_MorphParameter.h new file mode 100644 index 00000000..55b2d70a --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/CustomizationManager_MorphParameter.h @@ -0,0 +1 @@ +#include "../../src/shared/core/CustomizationManager_MorphParameter.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/DraftSchematicGroupManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/DraftSchematicGroupManager.h new file mode 100644 index 00000000..452aa6ef --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/DraftSchematicGroupManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/DraftSchematicGroupManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/FirstSharedGame.h b/engine/shared/library/sharedGame/include/public/sharedGame/FirstSharedGame.h new file mode 100644 index 00000000..5fb02c1e --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/FirstSharedGame.h @@ -0,0 +1 @@ +#include "../../src/shared/core/FirstSharedGame.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/FormManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/FormManager.h new file mode 100644 index 00000000..623932ae --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/FormManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/FormManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/GameLanguageManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/GameLanguageManager.h new file mode 100644 index 00000000..293b6645 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/GameLanguageManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/GameLanguageManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/GameObjectTypes.h b/engine/shared/library/sharedGame/include/public/sharedGame/GameObjectTypes.h new file mode 100644 index 00000000..31040c9f --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/GameObjectTypes.h @@ -0,0 +1 @@ +#include "../../src/shared/core/GameObjectTypes.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/GameScheduler.h b/engine/shared/library/sharedGame/include/public/sharedGame/GameScheduler.h new file mode 100644 index 00000000..06dbca2b --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/GameScheduler.h @@ -0,0 +1 @@ +#include "../../src/shared/core/GameScheduler.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/GroundZoneManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/GroundZoneManager.h new file mode 100644 index 00000000..687d23a3 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/GroundZoneManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/GroundZoneManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/GroupPickupPoint.h b/engine/shared/library/sharedGame/include/public/sharedGame/GroupPickupPoint.h new file mode 100644 index 00000000..a08d1879 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/GroupPickupPoint.h @@ -0,0 +1 @@ +#include "../../src/shared/object/GroupPickupPoint.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/GuildRankDataTable.h b/engine/shared/library/sharedGame/include/public/sharedGame/GuildRankDataTable.h new file mode 100644 index 00000000..5913d820 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/GuildRankDataTable.h @@ -0,0 +1 @@ +#include "../../src/shared/core/GuildRankDataTable.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/HoverPlaneHelper.h b/engine/shared/library/sharedGame/include/public/sharedGame/HoverPlaneHelper.h new file mode 100644 index 00000000..e20b87cb --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/HoverPlaneHelper.h @@ -0,0 +1 @@ +#include "../../src/shared/core/HoverPlaneHelper.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/HyperspaceManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/HyperspaceManager.h new file mode 100644 index 00000000..bdc9e384 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/HyperspaceManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/HyperspaceManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/LfgCharacterData.h b/engine/shared/library/sharedGame/include/public/sharedGame/LfgCharacterData.h new file mode 100644 index 00000000..8b4912dc --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/LfgCharacterData.h @@ -0,0 +1 @@ +#include "../../src/shared/core/LfgCharacterData.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/LfgDataTable.h b/engine/shared/library/sharedGame/include/public/sharedGame/LfgDataTable.h new file mode 100644 index 00000000..22e0a36e --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/LfgDataTable.h @@ -0,0 +1 @@ +#include "../../src/shared/core/LfgDataTable.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/LotManagerNotification.h b/engine/shared/library/sharedGame/include/public/sharedGame/LotManagerNotification.h new file mode 100644 index 00000000..1b33d115 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/LotManagerNotification.h @@ -0,0 +1 @@ +#include "../../src/shared/object/LotManagerNotification.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/MatchMakingCharacterPreferenceId.h b/engine/shared/library/sharedGame/include/public/sharedGame/MatchMakingCharacterPreferenceId.h new file mode 100644 index 00000000..ebe73be7 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/MatchMakingCharacterPreferenceId.h @@ -0,0 +1 @@ +#include "../../src/shared/object/MatchMakingCharacterPreferenceId.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/MatchMakingCharacterProfileId.h b/engine/shared/library/sharedGame/include/public/sharedGame/MatchMakingCharacterProfileId.h new file mode 100644 index 00000000..43f1f3f9 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/MatchMakingCharacterProfileId.h @@ -0,0 +1 @@ +#include "../../src/shared/object/MatchMakingCharacterProfileId.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/MatchMakingCharacterResult.h b/engine/shared/library/sharedGame/include/public/sharedGame/MatchMakingCharacterResult.h new file mode 100644 index 00000000..7f811adb --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/MatchMakingCharacterResult.h @@ -0,0 +1 @@ +#include "../../src/shared/object/MatchMakingCharacterResult.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/MatchMakingId.h b/engine/shared/library/sharedGame/include/public/sharedGame/MatchMakingId.h new file mode 100644 index 00000000..36bf0ab5 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/MatchMakingId.h @@ -0,0 +1 @@ +#include "../../src/shared/object/MatchMakingId.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/MoodManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/MoodManager.h new file mode 100644 index 00000000..3f409dc5 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/MoodManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/MoodManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/MountValidScaleRangeTable.h b/engine/shared/library/sharedGame/include/public/sharedGame/MountValidScaleRangeTable.h new file mode 100644 index 00000000..326ac814 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/MountValidScaleRangeTable.h @@ -0,0 +1 @@ +#include "../../src/shared/mount/MountValidScaleRangeTable.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/Nebula.h b/engine/shared/library/sharedGame/include/public/sharedGame/Nebula.h new file mode 100644 index 00000000..d96b26ce --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/Nebula.h @@ -0,0 +1 @@ +#include "../../src/shared/space/Nebula.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/NebulaManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/NebulaManager.h new file mode 100644 index 00000000..127e7a19 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/NebulaManager.h @@ -0,0 +1 @@ +#include "../../src/shared/space/NebulaManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/NoBuildNotification.h b/engine/shared/library/sharedGame/include/public/sharedGame/NoBuildNotification.h new file mode 100644 index 00000000..7dba3590 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/NoBuildNotification.h @@ -0,0 +1 @@ +#include "../../src/shared/object/NoBuildNotification.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/NpcConversationData.h b/engine/shared/library/sharedGame/include/public/sharedGame/NpcConversationData.h new file mode 100644 index 00000000..bc198c64 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/NpcConversationData.h @@ -0,0 +1,2 @@ +#include "../../src/shared/core/NpcConversationData.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ObjectUsabilityManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/ObjectUsabilityManager.h new file mode 100644 index 00000000..f3153e9d --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ObjectUsabilityManager.h @@ -0,0 +1 @@ +#include "../../src/shared/object/ObjectUsabilityManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/OutOfBand.h b/engine/shared/library/sharedGame/include/public/sharedGame/OutOfBand.h new file mode 100644 index 00000000..ba9a826a --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/OutOfBand.h @@ -0,0 +1 @@ +#include "../../src/shared/core/OutOfBand.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/OutOfBandBase.h b/engine/shared/library/sharedGame/include/public/sharedGame/OutOfBandBase.h new file mode 100644 index 00000000..eaf5d8fc --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/OutOfBandBase.h @@ -0,0 +1 @@ +#include "../../src/shared/core/OutOfBandBase.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/OutOfBandPackager.h b/engine/shared/library/sharedGame/include/public/sharedGame/OutOfBandPackager.h new file mode 100644 index 00000000..096e6094 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/OutOfBandPackager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/OutOfBandPackager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/PlanetMapManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/PlanetMapManager.h new file mode 100644 index 00000000..f26caaf5 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/PlanetMapManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/PlanetMapManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/PlatformFeatureBits.h b/engine/shared/library/sharedGame/include/public/sharedGame/PlatformFeatureBits.h new file mode 100644 index 00000000..2636309c --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/PlatformFeatureBits.h @@ -0,0 +1 @@ +#include "../../src/shared/core/PlatformFeatureBits.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/PlayerCreationManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/PlayerCreationManager.h new file mode 100644 index 00000000..1967cbf9 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/PlayerCreationManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/PlayerCreationManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/PlayerData.h b/engine/shared/library/sharedGame/include/public/sharedGame/PlayerData.h new file mode 100644 index 00000000..77d2fbd9 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/PlayerData.h @@ -0,0 +1 @@ +#include "../../src/shared/core/PlayerData.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/PlayerFormationManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/PlayerFormationManager.h new file mode 100644 index 00000000..2f91b139 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/PlayerFormationManager.h @@ -0,0 +1 @@ +#include "../../src/shared/space/PlayerFormationManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/PlayerQuestData.h b/engine/shared/library/sharedGame/include/public/sharedGame/PlayerQuestData.h new file mode 100644 index 00000000..8d470b5e --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/PlayerQuestData.h @@ -0,0 +1 @@ +#include "../../src/shared/quest/PlayerQuestData.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ProsePackage.h b/engine/shared/library/sharedGame/include/public/sharedGame/ProsePackage.h new file mode 100644 index 00000000..8c8ebbde --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ProsePackage.h @@ -0,0 +1 @@ +#include "../../src/shared/core/ProsePackage.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ProsePackageArchive.h b/engine/shared/library/sharedGame/include/public/sharedGame/ProsePackageArchive.h new file mode 100644 index 00000000..fd973b1b --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ProsePackageArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/core/ProsePackageArchive.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ProsePackageParticipant.h b/engine/shared/library/sharedGame/include/public/sharedGame/ProsePackageParticipant.h new file mode 100644 index 00000000..80b8d2b2 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ProsePackageParticipant.h @@ -0,0 +1 @@ +#include "../../src/shared/core/ProsePackageParticipant.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ProsePackageParticipantArchive.h b/engine/shared/library/sharedGame/include/public/sharedGame/ProsePackageParticipantArchive.h new file mode 100644 index 00000000..37edc6e9 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ProsePackageParticipantArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/core/ProsePackageParticipantArchive.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/PvpData.h b/engine/shared/library/sharedGame/include/public/sharedGame/PvpData.h new file mode 100644 index 00000000..6ac67be4 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/PvpData.h @@ -0,0 +1 @@ +#include "../../src/shared/core/PvpData.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/Quest.h b/engine/shared/library/sharedGame/include/public/sharedGame/Quest.h new file mode 100644 index 00000000..ef1747af --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/Quest.h @@ -0,0 +1 @@ +#include "../../src/shared/quest/Quest.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/QuestManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/QuestManager.h new file mode 100644 index 00000000..d92ff1e6 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/QuestManager.h @@ -0,0 +1 @@ +#include "../../src/shared/quest/QuestManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/QuestTask.h b/engine/shared/library/sharedGame/include/public/sharedGame/QuestTask.h new file mode 100644 index 00000000..59985036 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/QuestTask.h @@ -0,0 +1,2 @@ +#include "../../src/shared/quest/QuestTask.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/RadialMenuManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/RadialMenuManager.h new file mode 100644 index 00000000..24e80e28 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/RadialMenuManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/RadialMenuManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ResourceClassObject.h b/engine/shared/library/sharedGame/include/public/sharedGame/ResourceClassObject.h new file mode 100644 index 00000000..f2dffa8d --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ResourceClassObject.h @@ -0,0 +1 @@ +#include "../../src/shared/object/ResourceClassObject.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SetupSharedGame.h b/engine/shared/library/sharedGame/include/public/sharedGame/SetupSharedGame.h new file mode 100644 index 00000000..ac3029ac --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SetupSharedGame.h @@ -0,0 +1 @@ +#include "../../src/shared/core/SetupSharedGame.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedBattlefieldMarkerObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedBattlefieldMarkerObjectTemplate.h new file mode 100644 index 00000000..48068a55 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedBattlefieldMarkerObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedBattlefieldMarkerObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedBuffBuilderManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedBuffBuilderManager.h new file mode 100644 index 00000000..83ffdb87 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedBuffBuilderManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/SharedBuffBuilderManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedBuildingObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedBuildingObjectTemplate.h new file mode 100644 index 00000000..2ff94e26 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedBuildingObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedBuildingObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedBuildoutAreaManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedBuildoutAreaManager.h new file mode 100644 index 00000000..9cff5345 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedBuildoutAreaManager.h @@ -0,0 +1,2 @@ +#include "../../src/shared/core/SharedBuildoutAreaManager.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedCellObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedCellObjectTemplate.h new file mode 100644 index 00000000..799a01dd --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedCellObjectTemplate.h @@ -0,0 +1 @@ +#include "../../src/shared/objectTemplate/SharedCellObjectTemplate.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedConstructionContractObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedConstructionContractObjectTemplate.h new file mode 100644 index 00000000..214202f2 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedConstructionContractObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedConstructionContractObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedCreatureObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedCreatureObjectTemplate.h new file mode 100644 index 00000000..6a456b22 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedCreatureObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedCreatureObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedDraftSchematicObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedDraftSchematicObjectTemplate.h new file mode 100644 index 00000000..113e2309 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedDraftSchematicObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedDraftSchematicObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedFactoryObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedFactoryObjectTemplate.h new file mode 100644 index 00000000..83da9e20 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedFactoryObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedFactoryObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedGroupObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedGroupObjectTemplate.h new file mode 100644 index 00000000..e82f9803 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedGroupObjectTemplate.h @@ -0,0 +1 @@ +#include "../../src/shared/objectTemplate/SharedGroupObjectTemplate.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedGuildObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedGuildObjectTemplate.h new file mode 100644 index 00000000..9abd3ae3 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedGuildObjectTemplate.h @@ -0,0 +1 @@ +#include "../../src/shared/objectTemplate/SharedGuildObjectTemplate.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedHyperspaceStringIds.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedHyperspaceStringIds.h new file mode 100644 index 00000000..43cba857 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedHyperspaceStringIds.h @@ -0,0 +1 @@ +#include "../../src/shared/core/SharedHyperspaceStringIds.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedImageDesignerManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedImageDesignerManager.h new file mode 100644 index 00000000..e24bfe95 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedImageDesignerManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/SharedImageDesignerManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedInstallationObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedInstallationObjectTemplate.h new file mode 100644 index 00000000..6cdb24bb --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedInstallationObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedInstallationObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedIntangibleObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedIntangibleObjectTemplate.h new file mode 100644 index 00000000..c8c621b4 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedIntangibleObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedIntangibleObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedJediManagerObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedJediManagerObjectTemplate.h new file mode 100644 index 00000000..7e86da5b --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedJediManagerObjectTemplate.h @@ -0,0 +1 @@ +#include "../../src/shared/objectTemplate/SharedJediManagerObjectTemplate.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedManufactureSchematicObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedManufactureSchematicObjectTemplate.h new file mode 100644 index 00000000..b45f2b10 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedManufactureSchematicObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedManufactureSchematicObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedMissionObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedMissionObjectTemplate.h new file mode 100644 index 00000000..400b118a --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedMissionObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedMissionObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedObjectAttributes.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedObjectAttributes.h new file mode 100644 index 00000000..1a21e354 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedObjectAttributes.h @@ -0,0 +1 @@ +#include "../../src/shared/core/SharedObjectAttributes.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedObjectTemplate.h new file mode 100644 index 00000000..ee00d9cb --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedObjectTemplateClientData.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedObjectTemplateClientData.h new file mode 100644 index 00000000..d05d4214 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedObjectTemplateClientData.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedObjectTemplateClientData.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedObjectTemplateInterface.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedObjectTemplateInterface.h new file mode 100644 index 00000000..1414f027 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedObjectTemplateInterface.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedObjectTemplateInterface.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedPlayerObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedPlayerObjectTemplate.h new file mode 100644 index 00000000..fd18fc91 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedPlayerObjectTemplate.h @@ -0,0 +1 @@ +#include "../../src/shared/objectTemplate/SharedPlayerObjectTemplate.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedPlayerQuestObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedPlayerQuestObjectTemplate.h new file mode 100644 index 00000000..c4796c56 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedPlayerQuestObjectTemplate.h @@ -0,0 +1 @@ +#include "../../src/shared/objectTemplate/SharedPlayerQuestObjectTemplate.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedResourceContainerObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedResourceContainerObjectTemplate.h new file mode 100644 index 00000000..5444f609 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedResourceContainerObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedResourceContainerObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedSaddleManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedSaddleManager.h new file mode 100644 index 00000000..ea52c93d --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedSaddleManager.h @@ -0,0 +1 @@ +#include "../../src/shared/mount/SharedSaddleManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedShipObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedShipObjectTemplate.h new file mode 100644 index 00000000..04c6c225 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedShipObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedShipObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedStaticObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedStaticObjectTemplate.h new file mode 100644 index 00000000..b6010593 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedStaticObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedStaticObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedStringIds.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedStringIds.h new file mode 100644 index 00000000..f4c92c59 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedStringIds.h @@ -0,0 +1 @@ +#include "../../src/shared/core/SharedStringIds.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedTangibleObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedTangibleObjectTemplate.h new file mode 100644 index 00000000..963d7aa3 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedTangibleObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedTangibleObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedTerrainSurfaceObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedTerrainSurfaceObjectTemplate.h new file mode 100644 index 00000000..1cdfb867 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedTerrainSurfaceObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedTerrainSurfaceObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedUniverseObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedUniverseObjectTemplate.h new file mode 100644 index 00000000..c24390df --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedUniverseObjectTemplate.h @@ -0,0 +1 @@ +#include "../../src/shared/objectTemplate/SharedUniverseObjectTemplate.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedVehicleObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedVehicleObjectTemplate.h new file mode 100644 index 00000000..c95724db --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedVehicleObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedVehicleObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedWaypointObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedWaypointObjectTemplate.h new file mode 100644 index 00000000..724d6fb5 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedWaypointObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedWaypointObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SharedWeaponObjectTemplate.h b/engine/shared/library/sharedGame/include/public/sharedGame/SharedWeaponObjectTemplate.h new file mode 100644 index 00000000..612c723c --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SharedWeaponObjectTemplate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/objectTemplate/SharedWeaponObjectTemplate.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipChassis.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipChassis.h new file mode 100644 index 00000000..cf039444 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipChassis.h @@ -0,0 +1 @@ +#include "../../src/shared/space/ShipChassis.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipChassisSlot.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipChassisSlot.h new file mode 100644 index 00000000..edbe5237 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipChassisSlot.h @@ -0,0 +1 @@ +#include "../../src/shared/space/ShipChassisSlot.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipChassisSlotType.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipChassisSlotType.h new file mode 100644 index 00000000..3a853b4e --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipChassisSlotType.h @@ -0,0 +1 @@ +#include "../../src/shared/space/ShipChassisSlotType.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipChassisWritable.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipChassisWritable.h new file mode 100644 index 00000000..0394d63d --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipChassisWritable.h @@ -0,0 +1 @@ +#include "../../src/shared/space/ShipChassisWritable.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentAttachmentManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentAttachmentManager.h new file mode 100644 index 00000000..a4641298 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentAttachmentManager.h @@ -0,0 +1 @@ +#include "../../src/shared/space/ShipComponentAttachmentManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentData.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentData.h new file mode 100644 index 00000000..4a50b2a8 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentData.h @@ -0,0 +1 @@ +#include "../../src/shared/space/ShipComponentData.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentDescriptor.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentDescriptor.h new file mode 100644 index 00000000..11a4266d --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentDescriptor.h @@ -0,0 +1 @@ +#include "../../src/shared/space/ShipComponentDescriptor.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentDescriptorWritable.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentDescriptorWritable.h new file mode 100644 index 00000000..cf9d985a --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentDescriptorWritable.h @@ -0,0 +1 @@ +#include "../../src/shared/space/ShipComponentDescriptorWritable.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentFlags.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentFlags.h new file mode 100644 index 00000000..63d497c8 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentFlags.h @@ -0,0 +1 @@ +#include "../../src/shared/space/ShipComponentFlags.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentType.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentType.h new file mode 100644 index 00000000..43dcfff6 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentType.h @@ -0,0 +1 @@ +#include "../../src/shared/space/ShipComponentType.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentWeaponManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentWeaponManager.h new file mode 100644 index 00000000..48539ff5 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipComponentWeaponManager.h @@ -0,0 +1 @@ +#include "../../src/shared/space/ShipComponentWeaponManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipDynamicsModel.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipDynamicsModel.h new file mode 100644 index 00000000..ad42c5d8 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipDynamicsModel.h @@ -0,0 +1 @@ +#include "../../src/shared/dynamics/ShipDynamicsModel.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipHitEffectsManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipHitEffectsManager.h new file mode 100644 index 00000000..89b7d7e7 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipHitEffectsManager.h @@ -0,0 +1 @@ +#include "../../src/shared/space/ShipHitEffectsManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipObjectInterface.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipObjectInterface.h new file mode 100644 index 00000000..762bee26 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipObjectInterface.h @@ -0,0 +1 @@ +#include "../../src/shared/object/ShipObjectInterface.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipSlotIdManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipSlotIdManager.h new file mode 100644 index 00000000..5c8348e1 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipSlotIdManager.h @@ -0,0 +1,2 @@ +#include "../../src/shared/space/ShipSlotIdManager.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipTargeting.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipTargeting.h new file mode 100644 index 00000000..da733663 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipTargeting.h @@ -0,0 +1 @@ +#include "../../src/shared/space/ShipTargeting.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/ShipTurretManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/ShipTurretManager.h new file mode 100644 index 00000000..94ffa1b1 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/ShipTurretManager.h @@ -0,0 +1 @@ +#include "../../src/shared/space/ShipTurretManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SlopeEffectProperty.h b/engine/shared/library/sharedGame/include/public/sharedGame/SlopeEffectProperty.h new file mode 100644 index 00000000..265a808c --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SlopeEffectProperty.h @@ -0,0 +1 @@ +#include "../../src/shared/object/SlopeEffectProperty.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SlowDownProperty.h b/engine/shared/library/sharedGame/include/public/sharedGame/SlowDownProperty.h new file mode 100644 index 00000000..453d9abd --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SlowDownProperty.h @@ -0,0 +1 @@ +#include "../../src/shared/object/SlowDownProperty.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SocialsManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/SocialsManager.h new file mode 100644 index 00000000..a179aacc --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SocialsManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/SocialsManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SpaceStringIds.h b/engine/shared/library/sharedGame/include/public/sharedGame/SpaceStringIds.h new file mode 100644 index 00000000..ee2400f1 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SpaceStringIds.h @@ -0,0 +1 @@ +#include "../../src/shared/core/SpaceStringIds.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SpatialChatManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/SpatialChatManager.h new file mode 100644 index 00000000..ecf19926 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SpatialChatManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/SpatialChatManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/StartingLocationData.h b/engine/shared/library/sharedGame/include/public/sharedGame/StartingLocationData.h new file mode 100644 index 00000000..ff9ad809 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/StartingLocationData.h @@ -0,0 +1 @@ +#include "../../src/shared/core/StartingLocationData.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/StartingLocationDataArchive.h b/engine/shared/library/sharedGame/include/public/sharedGame/StartingLocationDataArchive.h new file mode 100644 index 00000000..95ddc02f --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/StartingLocationDataArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/core/StartingLocationDataArchive.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/StartingLocationManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/StartingLocationManager.h new file mode 100644 index 00000000..c1ae9946 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/StartingLocationManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/StartingLocationManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SuiCommand.h b/engine/shared/library/sharedGame/include/public/sharedGame/SuiCommand.h new file mode 100644 index 00000000..f938389f --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SuiCommand.h @@ -0,0 +1 @@ +#include "../../src/shared/sui/SuiCommand.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SuiCommandArchive.h b/engine/shared/library/sharedGame/include/public/sharedGame/SuiCommandArchive.h new file mode 100644 index 00000000..c7d7a22c --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SuiCommandArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/sui/SuiCommandArchive.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SuiEventSubscription.h b/engine/shared/library/sharedGame/include/public/sharedGame/SuiEventSubscription.h new file mode 100644 index 00000000..d464c5f1 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SuiEventSubscription.h @@ -0,0 +1 @@ +#include "../../src/shared/sui/SuiEventSubscription.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SuiEventType.h b/engine/shared/library/sharedGame/include/public/sharedGame/SuiEventType.h new file mode 100644 index 00000000..cfd39921 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SuiEventType.h @@ -0,0 +1 @@ +#include "../../src/shared/sui/SuiEventType.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SuiPageData.h b/engine/shared/library/sharedGame/include/public/sharedGame/SuiPageData.h new file mode 100644 index 00000000..e2b9c2d0 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SuiPageData.h @@ -0,0 +1 @@ +#include "../../src/shared/sui/SuiPageData.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SuiPageDataArchive.h b/engine/shared/library/sharedGame/include/public/sharedGame/SuiPageDataArchive.h new file mode 100644 index 00000000..5c369e22 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SuiPageDataArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/sui/SuiPageDataArchive.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/SuiWidgetProperty.h b/engine/shared/library/sharedGame/include/public/sharedGame/SuiWidgetProperty.h new file mode 100644 index 00000000..1f7593b5 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/SuiWidgetProperty.h @@ -0,0 +1 @@ +#include "../../src/shared/sui/SuiWidgetProperty.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/TextIterator.h b/engine/shared/library/sharedGame/include/public/sharedGame/TextIterator.h new file mode 100644 index 00000000..e248112e --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/TextIterator.h @@ -0,0 +1 @@ +#include "../../src/shared/core/TextIterator.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/TextManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/TextManager.h new file mode 100644 index 00000000..902cde96 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/TextManager.h @@ -0,0 +1 @@ +#include "../../src/shared/core/TextManager.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/TravelManager.h b/engine/shared/library/sharedGame/include/public/sharedGame/TravelManager.h new file mode 100644 index 00000000..0fdd3e9e --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/TravelManager.h @@ -0,0 +1,2 @@ +#include "../../src/shared/travel/TravelManager.h" + diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/TravelPoint.h b/engine/shared/library/sharedGame/include/public/sharedGame/TravelPoint.h new file mode 100644 index 00000000..59141f53 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/TravelPoint.h @@ -0,0 +1 @@ +#include "../../src/shared/travel/TravelPoint.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/Universe.h b/engine/shared/library/sharedGame/include/public/sharedGame/Universe.h new file mode 100644 index 00000000..f63d0fb0 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/Universe.h @@ -0,0 +1 @@ +#include "../../src/shared/core/Universe.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/VehicleHoverDynamics.h b/engine/shared/library/sharedGame/include/public/sharedGame/VehicleHoverDynamics.h new file mode 100644 index 00000000..84d7814d --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/VehicleHoverDynamics.h @@ -0,0 +1 @@ +#include "../../src/shared/object/VehicleHoverDynamics.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/Waypoint.h b/engine/shared/library/sharedGame/include/public/sharedGame/Waypoint.h new file mode 100644 index 00000000..74b5aceb --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/Waypoint.h @@ -0,0 +1 @@ +#include "../../src/shared/object/Waypoint.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/WaypointData.h b/engine/shared/library/sharedGame/include/public/sharedGame/WaypointData.h new file mode 100644 index 00000000..048535f3 --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/WaypointData.h @@ -0,0 +1 @@ +#include "../../src/shared/object/WaypointData.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/WearableAppearanceMap.h b/engine/shared/library/sharedGame/include/public/sharedGame/WearableAppearanceMap.h new file mode 100644 index 00000000..4e9e7d2c --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/WearableAppearanceMap.h @@ -0,0 +1 @@ +#include "../../src/shared/appearance/WearableAppearanceMap.h" diff --git a/engine/shared/library/sharedGame/include/public/sharedGame/WearableEntry.h b/engine/shared/library/sharedGame/include/public/sharedGame/WearableEntry.h new file mode 100644 index 00000000..badd47be --- /dev/null +++ b/engine/shared/library/sharedGame/include/public/sharedGame/WearableEntry.h @@ -0,0 +1 @@ +#include "../../src/shared/core/WearableEntry.h" diff --git a/engine/shared/library/sharedGame/src/CMakeLists.txt b/engine/shared/library/sharedGame/src/CMakeLists.txt new file mode 100644 index 00000000..f313e640 --- /dev/null +++ b/engine/shared/library/sharedGame/src/CMakeLists.txt @@ -0,0 +1,336 @@ + +set(SHARED_SOURCES + shared/appearance/WearableAppearanceMap.cpp + shared/appearance/WearableAppearanceMap.h + + shared/collision/CollisionCallbackManager.cpp + shared/collision/CollisionCallbackManager.h + + shared/combat/CombatDataTable.cpp + shared/combat/CombatDataTable.h + shared/combat/CombatTimingTable.cpp + shared/combat/CombatTimingTable.h + + shared/command/Command.cpp + shared/command/Command.h + shared/command/CommandChecks.cpp + shared/command/CommandChecks.h + shared/command/CommandCppFunc.def + shared/command/CommandTable.cpp + shared/command/CommandTable.h + + shared/core/AiDebugString.cpp + shared/core/AiDebugString.h + shared/core/AssetCustomizationManager.cpp + shared/core/AssetCustomizationManager.h + shared/core/AuctionManager.cpp + shared/core/AuctionManager.h + shared/core/AuctionTokenArchive.cpp + shared/core/AuctionTokenArchive.h + shared/core/AuctionToken.cpp + shared/core/AuctionToken.h + shared/core/CitizenRankDataTable.h + shared/core/CitizenRankDataTable.cpp + shared/core/CityData.h + shared/core/ClientCombatManagerSupport.cpp + shared/core/ClientCombatManagerSupport.h + shared/core/CollectionsDataTable.cpp + shared/core/CollectionsDataTable.h + shared/core/CommoditiesAdvancedSearchAttribute.cpp + shared/core/CommoditiesAdvancedSearchAttribute.h + shared/core/ConfigSharedGame.cpp + shared/core/ConfigSharedGame.h + shared/core/CraftingDataArchive.cpp + shared/core/CraftingDataArchive.h + shared/core/CraftingData.cpp + shared/core/CraftingData.h + shared/core/CustomizationManager.cpp + shared/core/CustomizationManager.h + shared/core/CustomizationManager_MorphParameter.cpp + shared/core/CustomizationManager_MorphParameter.h + shared/core/DraftSchematicGroupManager.cpp + shared/core/DraftSchematicGroupManager.h + shared/core/FirstSharedGame.h + shared/core/FormManager.cpp + shared/core/FormManager.h + shared/core/GameLanguageManager.cpp + shared/core/GameLanguageManager.h + shared/core/GameObjectTypes.cpp + shared/core/GameObjectTypes.h + shared/core/GameScheduler.cpp + shared/core/GameScheduler.h + shared/core/GroundZoneManager.h + shared/core/GroundZoneManager.cpp + shared/core/GuildRankDataTable.h + shared/core/GuildRankDataTable.cpp + shared/core/HoverPlaneHelper.cpp + shared/core/HoverPlaneHelper.h + shared/core/HyperspaceManager.cpp + shared/core/HyperspaceManager.h + shared/core/LfgCharacterData.cpp + shared/core/LfgCharacterData.h + shared/core/LfgDataTable.cpp + shared/core/LfgDataTable.h + shared/core/MoodManager.cpp + shared/core/MoodManager.h + shared/core/NpcConversationData.h + shared/core/OutOfBandBase.cpp + shared/core/OutOfBandBase.h + shared/core/OutOfBand.h + shared/core/OutOfBandPackager.cpp + shared/core/OutOfBandPackager.h + shared/core/PlanetMapManager.cpp + shared/core/PlanetMapManager.h + shared/core/PlatformFeatureBits.cpp + shared/core/PlatformFeatureBits.h + shared/core/PlayerCreationManager.cpp + shared/core/PlayerCreationManager.h + shared/core/PlayerData.h + shared/core/ProsePackageArchive.cpp + shared/core/ProsePackageArchive.h + shared/core/ProsePackage.cpp + shared/core/ProsePackage.h + shared/core/ProsePackageParticipantArchive.cpp + shared/core/ProsePackageParticipantArchive.h + shared/core/ProsePackageParticipant.cpp + shared/core/ProsePackageParticipant.h + shared/core/PvpData.h + shared/core/RadialMenuManager.cpp + shared/core/RadialMenuManager.h + shared/core/SetupSharedGame.cpp + shared/core/SetupSharedGame.h + shared/core/SharedBuffBuilderManager.cpp + shared/core/SharedBuffBuilderManager.h + shared/core/SharedBuildoutAreaManager.cpp + shared/core/SharedBuildoutAreaManager.h + shared/core/SharedImageDesignerManager.cpp + shared/core/SharedImageDesignerManager.h + shared/core/SharedObjectAttributes.cpp + shared/core/SharedObjectAttributes.h + shared/core/SharedHyperspaceStringIds.cpp + shared/core/SharedHyperspaceStringIds.h + shared/core/SharedStringIds.cpp + shared/core/SharedStringIds.h + shared/core/SocialsManager.cpp + shared/core/SocialsManager.h + shared/core/SpatialChatManager.cpp + shared/core/SpatialChatManager.h + shared/core/TextIterator.cpp + shared/core/TextIterator.h + shared/core/TextManager.cpp + shared/core/TextManager.h + shared/core/Universe.cpp + shared/core/Universe.h + shared/core/WearableEntry.cpp + shared/core/WearableEntry.h + + shared/dynamics/ShipDynamicsModel.cpp + shared/dynamics/ShipDynamicsModel.h + + shared/mount/MountValidScaleRangeTable.cpp + shared/mount/MountValidScaleRangeTable.h + shared/mount/SharedSaddleManager.cpp + shared/mount/SharedSaddleManager.h + + shared/object/AppearanceManager.cpp + shared/object/AppearanceManager.h + shared/object/AttribMod.cpp + shared/object/AttribMod.h + shared/object/AttribModArchive.cpp + shared/object/AttribModArchive.h + shared/object/Buff.cpp + shared/object/Buff.h + shared/object/GroupPickupPoint.cpp + shared/object/GroupPickupPoint.h + shared/object/LotManagerNotification.cpp + shared/object/LotManagerNotification.h + shared/object/MatchMakingCharacterPreferenceId.cpp + shared/object/MatchMakingCharacterPreferenceId.h + shared/object/MatchMakingCharacterProfileId.cpp + shared/object/MatchMakingCharacterProfileId.h + shared/object/MatchMakingCharacterResult.cpp + shared/object/MatchMakingCharacterResult.h + shared/object/MatchMakingId.cpp + shared/object/MatchMakingId.h + shared/object/NoBuildNotification.cpp + shared/object/NoBuildNotification.h + shared/object/ObjectUsabilityManager.cpp + shared/object/ObjectUsabilityManager.h + shared/object/ShipObjectInterface.cpp + shared/object/ShipObjectInterface.h + shared/object/SlopeEffectProperty.cpp + shared/object/SlopeEffectProperty.h + shared/object/SlowDownProperty.cpp + shared/object/SlowDownProperty.h + shared/object/ResourceClassObject.cpp + shared/object/ResourceClassObject.h + shared/object/VehicleHoverDynamics.cpp + shared/object/VehicleHoverDynamics.h + shared/object/Waypoint.cpp + shared/object/WaypointData.cpp + shared/object/WaypointData.h + shared/object/Waypoint.h + + shared/objectTemplate/SharedBattlefieldMarkerObjectTemplate.cpp + shared/objectTemplate/SharedBattlefieldMarkerObjectTemplate.h + shared/objectTemplate/SharedBuildingObjectTemplate.cpp + shared/objectTemplate/SharedBuildingObjectTemplate.h + shared/objectTemplate/SharedCellObjectTemplate.cpp + shared/objectTemplate/SharedCellObjectTemplate.h + shared/objectTemplate/SharedConstructionContractObjectTemplate.cpp + shared/objectTemplate/SharedConstructionContractObjectTemplate.h + shared/objectTemplate/SharedCreatureObjectTemplate.cpp + shared/objectTemplate/SharedCreatureObjectTemplate.h + shared/objectTemplate/SharedDraftSchematicObjectTemplate.cpp + shared/objectTemplate/SharedDraftSchematicObjectTemplate.h + shared/objectTemplate/SharedFactoryObjectTemplate.cpp + shared/objectTemplate/SharedFactoryObjectTemplate.h + shared/objectTemplate/SharedGroupObjectTemplate.cpp + shared/objectTemplate/SharedGroupObjectTemplate.h + shared/objectTemplate/SharedGuildObjectTemplate.cpp + shared/objectTemplate/SharedGuildObjectTemplate.h + shared/objectTemplate/SharedInstallationObjectTemplate.cpp + shared/objectTemplate/SharedInstallationObjectTemplate.h + shared/objectTemplate/SharedIntangibleObjectTemplate.cpp + shared/objectTemplate/SharedIntangibleObjectTemplate.h + shared/objectTemplate/SharedJediManagerObjectTemplate.cpp + shared/objectTemplate/SharedJediManagerObjectTemplate.h + shared/objectTemplate/SharedManufactureSchematicObjectTemplate.cpp + shared/objectTemplate/SharedManufactureSchematicObjectTemplate.h + shared/objectTemplate/SharedMissionObjectTemplate.cpp + shared/objectTemplate/SharedMissionObjectTemplate.h + shared/objectTemplate/SharedObjectTemplateClientData.cpp + shared/objectTemplate/SharedObjectTemplateClientData.h + shared/objectTemplate/SharedObjectTemplateInterface.cpp + shared/objectTemplate/SharedObjectTemplateInterface.h + shared/objectTemplate/SharedObjectTemplate.cpp + shared/objectTemplate/SharedObjectTemplate.h + shared/objectTemplate/SharedPlayerQuestObjectTemplate.h + shared/objectTemplate/SharedPlayerQuestObjectTemplate.cpp + shared/objectTemplate/SharedPlayerObjectTemplate.cpp + shared/objectTemplate/SharedPlayerObjectTemplate.h + shared/objectTemplate/SharedResourceContainerObjectTemplate.cpp + shared/objectTemplate/SharedResourceContainerObjectTemplate.h + shared/objectTemplate/SharedShipObjectTemplate.cpp + shared/objectTemplate/SharedShipObjectTemplate.h + shared/objectTemplate/SharedStaticObjectTemplate.cpp + shared/objectTemplate/SharedStaticObjectTemplate.h + shared/objectTemplate/SharedTangibleObjectTemplate.cpp + shared/objectTemplate/SharedTangibleObjectTemplate.h + shared/objectTemplate/SharedTerrainSurfaceObjectTemplate.cpp + shared/objectTemplate/SharedTerrainSurfaceObjectTemplate.h + shared/objectTemplate/SharedUniverseObjectTemplate.cpp + shared/objectTemplate/SharedUniverseObjectTemplate.h + shared/objectTemplate/SharedVehicleObjectTemplate.cpp + shared/objectTemplate/SharedVehicleObjectTemplate.h + shared/objectTemplate/SharedWaypointObjectTemplate.cpp + shared/objectTemplate/SharedWaypointObjectTemplate.h + shared/objectTemplate/SharedWeaponObjectTemplate.cpp + shared/objectTemplate/SharedWeaponObjectTemplate.h + + shared/quest/PlayerQuestData.cpp + shared/quest/PlayerQuestData.h + shared/quest/Quest.cpp + shared/quest/Quest.h + shared/quest/QuestManager.cpp + shared/quest/QuestManager.h + shared/quest/QuestTask.cpp + shared/quest/QuestTask.h + + shared/space/AsteroidGenerationManager.cpp + shared/space/AsteroidGenerationManager.h + shared/space/Nebula.cpp + shared/space/Nebula.h + shared/space/NebulaManager.cpp + shared/space/NebulaManager.h + shared/space/PlayerFormationManager.cpp + shared/space/PlayerFormationManager.h + shared/space/ShipChassis.cpp + shared/space/ShipChassis.h + shared/space/ShipChassisWritable.cpp + shared/space/ShipChassisWritable.h + shared/space/ShipChassisSlot.cpp + shared/space/ShipChassisSlot.h + shared/space/ShipChassisSlotType.cpp + shared/space/ShipChassisSlotType.h + shared/space/ShipComponentAttachmentManager.cpp + shared/space/ShipComponentAttachmentManager.h + shared/space/ShipComponentData.cpp + shared/space/ShipComponentData.h + shared/space/ShipComponentDescriptor.cpp + shared/space/ShipComponentDescriptor.h + shared/space/ShipComponentDescriptorWritable.cpp + shared/space/ShipComponentDescriptorWritable.h + shared/space/ShipComponentFlags.cpp + shared/space/ShipComponentFlags.h + shared/space/ShipComponentType.cpp + shared/space/ShipComponentType.h + shared/space/ShipComponentWeaponManager.cpp + shared/space/ShipComponentWeaponManager.h + shared/space/ShipSlotIdManager.cpp + shared/space/ShipSlotIdManager.h + shared/space/ShipTargeting.cpp + shared/space/ShipTargeting.h + shared/space/ShipTurretManager.cpp + shared/space/ShipTurretManager.h + + shared/sui/SuiCommand.cpp + shared/sui/SuiCommand.h + shared/sui/SuiCommandArchive.cpp + shared/sui/SuiCommandArchive.h + shared/sui/SuiEventSubscription.cpp + shared/sui/SuiEventSubscription.h + shared/sui/SuiEventType.cpp + shared/sui/SuiEventType.h + shared/sui/SuiPageData.cpp + shared/sui/SuiPageData.h + shared/sui/SuiPageDataArchive.cpp + shared/sui/SuiPageDataArchive.h + shared/sui/SuiWidgetProperty.cpp + shared/sui/SuiWidgetProperty.h + + shared/travel/TravelManager.cpp + shared/travel/TravelManager.h + shared/travel/TravelPoint.cpp + shared/travel/TravelPoint.h +) + +if(WIN32) + set(PLATFORM_SOURCES + win32/FirstSharedGame.cpp + ) + + include_directories(${CMAKE_CURRENT_SOURCE_DIR}/win32) +else() + set(PLATFORM_SOURCES "") +endif() + +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR}/shared + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedCollision/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedDebug/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedFile/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedFoundation/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedFoundationTypes/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedMath/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedMathArchive/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedMemoryManager/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedMessageDispatch/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedNetworkMessages/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedObject/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedRandom/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedSkillSystem/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedTerrain/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedUtility/include/public + ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/archive/include + ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/fileInterface/include/public + ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/localization/include + ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/localizationArchive/include/public + ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/unicode/include + ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/unicodeArchive/include/public +) + +add_library(sharedGame STATIC + ${SHARED_SOURCES} + ${PLATFORM_SOURCES} +) diff --git a/engine/shared/library/sharedGame/src/shared/appearance/WearableAppearanceMap.cpp b/engine/shared/library/sharedGame/src/shared/appearance/WearableAppearanceMap.cpp new file mode 100644 index 00000000..63d98b04 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/appearance/WearableAppearanceMap.cpp @@ -0,0 +1,405 @@ +// ====================================================================== +// +// WearableAppearanceMap.cpp +// Copyright 2003 Sony Online Entertainment, Inc. +// All Rights Reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/WearableAppearanceMap.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/PersistentCrcString.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" + +#include +#include + +// ====================================================================== + +namespace WearableAppearanceMapNamespace +{ + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class MapEntry + { + public: + + virtual ~MapEntry(); + + // Key fields. + virtual CrcString const &getSourceWearableAppearanceName() const = 0; //lint -esym(754, *::getSourceWearableAppearanceName) // unreferenced // wrong, referenced through virtual interface. + virtual CrcString const &getWearerAppearanceName() const = 0; //lint -esym(754, *::getWearerAppearanceName) // unreferenced // wrong, referenced through virtual interface. + + // Payload field. + virtual CrcString const *getMappedWearableAppearanceName() const = 0; //lint -esym(754, *::getMappedWearableAppearanceName) // unreferenced // wrong, referenced through virtual interface. + + protected: + + MapEntry(); + + private: + + // Disabled. + MapEntry &operator =(MapEntry const &); + + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class PersistentMapEntry: public MapEntry + { + public: + + PersistentMapEntry(char const *sourceWearableAppearanceName, char const *wearerAppearanceName, char const *mappedWearableAppearanceName); + virtual ~PersistentMapEntry(); + + virtual CrcString const &getSourceWearableAppearanceName() const; + virtual CrcString const &getWearerAppearanceName() const; + virtual CrcString const *getMappedWearableAppearanceName() const; + + private: + + // Disabled. + PersistentMapEntry(); + PersistentMapEntry(PersistentMapEntry const&); //lint -esym(754, PersistentMapEntry::PersistentMapEntry) // local member not accessed // defensive hiding. + PersistentMapEntry &operator =(PersistentMapEntry const &); + + private: + + PersistentCrcString const m_sourceWearableAppearanceName; + PersistentCrcString const m_wearerAppearanceName; + PersistentCrcString *m_mappedWearableAppearanceName; + + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class TemporaryMapEntry: public MapEntry + { + public: + + TemporaryMapEntry(CrcString const &sourceWearableAppearanceName, CrcString const &wearerAppearanceName); + + virtual CrcString const &getSourceWearableAppearanceName() const; + virtual CrcString const &getWearerAppearanceName() const; + virtual CrcString const *getMappedWearableAppearanceName() const; + + private: + + // Disabled. + TemporaryMapEntry(); + TemporaryMapEntry &operator =(TemporaryMapEntry const &); + + private: + + CrcString const &m_sourceWearableAppearanceName; + CrcString const &m_wearerAppearanceName; + + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + struct LessMapEntryComparator + { + bool operator ()(MapEntry const *lhs, MapEntry const *rhs) const; + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + typedef std::vector MapEntryVector; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + void remove(); + int getRequiredColumnNumberFromNamedTable(char const *filename, DataTable const *table, char const *columnName); + void loadTableData(char const *filename); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + std::string const cs_forbiddenWearableCellContents(":block"); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + bool s_installed; + MapEntryVector s_mapEntries; + +} + +using namespace WearableAppearanceMapNamespace; + +// ====================================================================== +// class WearableAppearanceMapNamespace::MapEntry +// ====================================================================== + +WearableAppearanceMapNamespace::MapEntry::~MapEntry() +{ + // Placeholder for derived classes. +} + +// ---------------------------------------------------------------------- + +WearableAppearanceMapNamespace::MapEntry::MapEntry() +{ +} + +// ====================================================================== +// class WearableAppearanceMapNamespace::PersistentMapEntry +// ====================================================================== + +WearableAppearanceMapNamespace::PersistentMapEntry::PersistentMapEntry(char const *sourceWearableAppearanceName, char const *wearerAppearanceName, char const *mappedWearableAppearanceName) : + MapEntry(), + m_sourceWearableAppearanceName(sourceWearableAppearanceName, true), + m_wearerAppearanceName(wearerAppearanceName, true), + m_mappedWearableAppearanceName(NULL) +{ + if (mappedWearableAppearanceName != NULL) + m_mappedWearableAppearanceName = new PersistentCrcString(mappedWearableAppearanceName, true); +} + +// ---------------------------------------------------------------------- + +WearableAppearanceMapNamespace::PersistentMapEntry::~PersistentMapEntry() +{ + delete m_mappedWearableAppearanceName; +} + +// ---------------------------------------------------------------------- + +CrcString const &WearableAppearanceMapNamespace::PersistentMapEntry::getSourceWearableAppearanceName() const +{ + return m_sourceWearableAppearanceName; +} + +// ---------------------------------------------------------------------- + +CrcString const &WearableAppearanceMapNamespace::PersistentMapEntry::getWearerAppearanceName() const +{ + return m_wearerAppearanceName; +} + +// ---------------------------------------------------------------------- + +CrcString const *WearableAppearanceMapNamespace::PersistentMapEntry::getMappedWearableAppearanceName() const +{ + return m_mappedWearableAppearanceName; +} + +// ====================================================================== +// class WearableAppearanceMapNamespace::TemporaryMapEntry +// ====================================================================== + +WearableAppearanceMapNamespace::TemporaryMapEntry::TemporaryMapEntry(CrcString const &sourceWearableAppearanceName, CrcString const &wearerAppearanceName) : + MapEntry(), + m_sourceWearableAppearanceName(sourceWearableAppearanceName), + m_wearerAppearanceName(wearerAppearanceName) +{ +} + +// ---------------------------------------------------------------------- + +CrcString const &WearableAppearanceMapNamespace::TemporaryMapEntry::getSourceWearableAppearanceName() const +{ + return m_sourceWearableAppearanceName; +} + +// ---------------------------------------------------------------------- + +CrcString const &WearableAppearanceMapNamespace::TemporaryMapEntry::getWearerAppearanceName() const +{ + return m_wearerAppearanceName; +} + +// ---------------------------------------------------------------------- + +CrcString const *WearableAppearanceMapNamespace::TemporaryMapEntry::getMappedWearableAppearanceName() const +{ + return NULL; +} + +// ====================================================================== +// struct WearableAppearanceMapNamespace::LessMapEntryComparator +// ====================================================================== + +bool WearableAppearanceMapNamespace::LessMapEntryComparator::operator ()(MapEntry const *lhs, MapEntry const *rhs) const +{ + NOT_NULL(lhs); + NOT_NULL(rhs); + + // First compare by source wearable appearance name... + CrcString const &lhsSourceWearableAppearanceName = lhs->getSourceWearableAppearanceName(); + CrcString const &rhsSourceWearableAppearanceName = rhs->getSourceWearableAppearanceName(); + + if (lhsSourceWearableAppearanceName < rhsSourceWearableAppearanceName) + return true; + else if (lhsSourceWearableAppearanceName > rhsSourceWearableAppearanceName) + return false; + else + { + // ... then compare by wearer appearance name. + return lhs->getWearerAppearanceName() < rhs->getWearerAppearanceName(); + } +} + +// ====================================================================== +// namespace WearableAppearanceMapNamespace +// ====================================================================== + +void WearableAppearanceMapNamespace::remove() +{ + DEBUG_FATAL(!s_installed, ("WearableAppearanceMap not installed.")); + s_installed = false; + + std::for_each(s_mapEntries.begin(), s_mapEntries.end(), PointerDeleter()); + s_mapEntries.clear(); +} + +// ---------------------------------------------------------------------- + +int WearableAppearanceMapNamespace::getRequiredColumnNumberFromNamedTable(char const *filename, DataTable const *table, char const *columnName) +{ + NOT_NULL(columnName); + + int const columnNumber = table->findColumnNumber(columnName); + FATAL(columnNumber < 0, ("failed to find column name [%s] in MountValidScaleRangeTable file [%s].", columnName, filename)); + + return columnNumber; +} + +// ---------------------------------------------------------------------- + +void WearableAppearanceMapNamespace::loadTableData(char const *filename) +{ + NOT_NULL(filename); + + //-- Load the data table. + DataTable *const table = DataTableManager::getTable(filename, true); + FATAL(!table, ("WearableAppearanceMap data file [%s] failed to open.", filename)); + + //-- Find required data column numbers. + int const sourceWearableAppearanceNameColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "source_wearable_appearance_name"); + int const wearerAppearanceNameColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "wearer_appearance_name"); + int const mappedWearableAppearanceNameColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "mapped_wearable_appearance_name"); + + //-- Loop through data, constructing entries as necessary. + int const rowCount = table->getNumRows(); + s_mapEntries.reserve(static_cast(rowCount)); + + for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex) + { + //-- Get entry data. + std::string const &sourceWearableAppearanceName = table->getStringValue(sourceWearableAppearanceNameColumnNumber, rowIndex); + std::string const &wearerAppearanceName = table->getStringValue(wearerAppearanceNameColumnNumber, rowIndex); + std::string const &mappedWearableAppearanceName = table->getStringValue(mappedWearableAppearanceNameColumnNumber, rowIndex); + + //-- Create map entry, add to vector. + s_mapEntries.push_back(new PersistentMapEntry(sourceWearableAppearanceName.c_str(), wearerAppearanceName.c_str(), (mappedWearableAppearanceName == cs_forbiddenWearableCellContents) ? NULL : mappedWearableAppearanceName.c_str())); + } + + DataTableManager::close(filename); + + //-- Sort the list in ascending key order. + std::sort(s_mapEntries.begin(), s_mapEntries.end(), LessMapEntryComparator()); + + // @todo: search for duplicates and FATAL if this occurs. +} + +// ====================================================================== +// class WearableAppearanceMap::MapResult: PUBLIC +// ====================================================================== + +WearableAppearanceMap::MapResult::MapResult(MapResult const &rhs) : + m_hasMapping(rhs.m_hasMapping), + m_wearableIsForbidden(rhs.m_wearableIsForbidden), + m_mappedWearableAppearanceName(rhs.m_mappedWearableAppearanceName) //lint !e1554 // direct copy of pointer in copy constructor // yes, it's okay, we don't own this and won't try to delete it. +{ +} + +// ---------------------------------------------------------------------- + +#if 0 + +WearableAppearanceMap::MapResult &WearableAppearanceMap::MapResult::operator =(MapResult const &rhs) +{ +} + +#endif + +// ---------------------------------------------------------------------- + +bool WearableAppearanceMap::MapResult::hasMapping() const +{ + return m_hasMapping; +} + +// ---------------------------------------------------------------------- + +bool WearableAppearanceMap::MapResult::isWearableForbidden() const +{ + return m_wearableIsForbidden; +} + +// ---------------------------------------------------------------------- + +CrcString const *WearableAppearanceMap::MapResult::getMappedWearableAppearanceName() const +{ + return m_mappedWearableAppearanceName; +} + +// ====================================================================== + +WearableAppearanceMap::MapResult::MapResult(bool newHasMapping, bool wearableIsForbidden, CrcString const *mappedWearableAppearanceName) : + m_hasMapping(newHasMapping), + m_wearableIsForbidden(wearableIsForbidden), + m_mappedWearableAppearanceName(mappedWearableAppearanceName) +{ +} + +// ====================================================================== +// class WearableAppearanceMap +// ====================================================================== + +void WearableAppearanceMap::install(char const *filename) +{ + InstallTimer const installTimer("WearableAppearanceMap::install"); + + DEBUG_FATAL(s_installed, ("WearableAppearanceMap already installed.")); + + loadTableData(filename); + + s_installed = true; + ExitChain::add(WearableAppearanceMapNamespace::remove, "WearableAppearanceMap"); +} + +// ---------------------------------------------------------------------- + +WearableAppearanceMap::MapResult WearableAppearanceMap::getMapResultForWearableAndWearer(CrcString const &sourceWearableAppearanceName, CrcString const &wearerAppearanceName) +{ + DEBUG_FATAL(!s_installed, ("WearableAppearanceMap not installed.")); + + //-- Find entry. + TemporaryMapEntry searchKey(sourceWearableAppearanceName, wearerAppearanceName); + + std::pair findResult = std::equal_range(s_mapEntries.begin(), s_mapEntries.end(), &searchKey, LessMapEntryComparator()); + if (findResult.first == findResult.second) + { + // We have no mapping for this entry. That implies the source wearable appearance name can be used as is. + return MapResult(false, false, NULL); + } + else + { + MapEntry const *const mapEntry = *findResult.first; + NOT_NULL(mapEntry); + DEBUG_WARNING(std::distance(findResult.first, findResult.second) > 1, ("WearableAppearanceMap: there are multiple entries for source wearable=[%s], wearer=[%s]. Art leads: please fix data!", mapEntry->getSourceWearableAppearanceName().getString(), mapEntry->getWearerAppearanceName().getString())); + + // We have a mapping. Return it. + CrcString const *const mappedWearableAppearanceName = mapEntry->getMappedWearableAppearanceName(); + return MapResult(true, mappedWearableAppearanceName == NULL, mappedWearableAppearanceName); + } +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/appearance/WearableAppearanceMap.h b/engine/shared/library/sharedGame/src/shared/appearance/WearableAppearanceMap.h new file mode 100644 index 00000000..c3f01040 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/appearance/WearableAppearanceMap.h @@ -0,0 +1,64 @@ +// ====================================================================== +// +// WearableAppearanceMap.h +// Copyright 2003 Sony Online Entertainment, Inc. +// All Rights Reserved. +// +// ====================================================================== + +#ifndef INCLUDED_WearableAppearanceMap_H +#define INCLUDED_WearableAppearanceMap_H + +// ====================================================================== + +class CrcString; + +// ====================================================================== + +class WearableAppearanceMap +{ +public: + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class MapResult + { + friend class WearableAppearanceMap; + + public: + + MapResult(MapResult const &rhs); + + bool hasMapping() const; + + bool isWearableForbidden() const; + CrcString const *getMappedWearableAppearanceName() const; + + private: + + MapResult(bool hasMapping, bool wearableIsForbidden, CrcString const *mappedWearableAppearanceName); + + // Disabled. + MapResult(); + MapResult &operator =(MapResult const &rhs); + + private: + + bool const m_hasMapping; + bool const m_wearableIsForbidden; + CrcString const *const m_mappedWearableAppearanceName; + + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +public: + + static void install(char const *filename); + static MapResult getMapResultForWearableAndWearer(CrcString const &sourceWearableAppearanceName, CrcString const &wearerAppearanceName); + +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/collision/CollisionCallbackManager.cpp b/engine/shared/library/sharedGame/src/shared/collision/CollisionCallbackManager.cpp new file mode 100644 index 00000000..fc8d7b13 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/collision/CollisionCallbackManager.cpp @@ -0,0 +1,431 @@ +// ====================================================================== +// +// CollisionCallbackManager.cpp +// tford +// +// copyright 2004, sony online entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/CollisionCallbackManager.h" + +#include "sharedCollision/BaseExtent.h" +#include "sharedCollision/CollisionProperty.h" +#include "sharedCollision/CollisionUtils.h" +#include "sharedCollision/CollisionInfo.h" +#include "sharedCollision/CollisionWorld.h" +#include "sharedCollision/ConfigSharedCollision.h" +#include "sharedDebug/DebugFlags.h" +#include "sharedDebug/InstallTimer.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedLog/Log.h" +#include "sharedMath/Capsule.h" +#include "sharedObject/Object.h" +#include "sharedTerrain/TerrainObject.h" +#include + +// ====================================================================== + +namespace CollisionCallbackManagerNamespace +{ + typedef std::map NoHitFunctionArray; + typedef std::map OnHitRow; + typedef std::map OnHitByObjectFunctionMatrix; + + NoHitFunctionArray ms_NoHitFunctionArray; + OnHitByObjectFunctionMatrix ms_functionMatrix; + + CollisionCallbackManager::ConvertObjectToIndexFunction ms_convertObjectToIndex = 0; + CollisionCallbackManager::DoCollisionWithTerrainFunction ms_doCollisionWithTerrain = 0; + + bool ms_debugReport; + + void remove(); + void noCollisionDetectionThisFrame(Object * const object); + bool collisionDetectionOnHit(Object * const object, Object * const wasHitByThisObject); + bool doCollisionWithTerrain(Object * const object); + + typedef std::map > IgnoreIntersectList; + IgnoreIntersectList s_ignoreIntersectList; +} + +using namespace CollisionCallbackManagerNamespace; + +// ====================================================================== + +CollisionCallbackManager::Result::Result() +: m_pointOfCollision_p() +, m_deltaToMoveBack_p() +, m_newReflection_p() +, m_normalOfSurface_p() +{ +} + +// ====================================================================== + +void CollisionCallbackManager::install() +{ + InstallTimer const installTimer("CollisionCallbackManager::install"); + + CollisionWorld::registerNoCollisionDetectionThisFrame(CollisionCallbackManagerNamespace::noCollisionDetectionThisFrame); + CollisionWorld::registerDoCollisionDetectionOnHit(CollisionCallbackManagerNamespace::collisionDetectionOnHit); + CollisionWorld::registerDoCollisionWithTerrain(CollisionCallbackManagerNamespace::doCollisionWithTerrain); + + ms_debugReport = ConfigSharedCollision::getReportEvents(); + DebugFlags::registerFlag(ms_debugReport, "SharedGame/CollisionCallbackManager", "debugReport"); + + ExitChain::add(remove, "CollisionCallbackManagerNamespace::remove"); +} + +// ---------------------------------------------------------------------- + +void CollisionCallbackManagerNamespace::remove() +{ + DebugFlags::unregisterFlag(ms_debugReport); + + if (!s_ignoreIntersectList.empty()) + { + //-- If you see this warning, it means that addIgnoreIntersect was called without a corresponding removeIgnoreIntersect. + WARNING(true, ("CollisionCallbackManagerNamespace::remove() The s_ignoreIntersectList is not empty(%u), this is a sign of a reference counting problem.", s_ignoreIntersectList.size())); + } +} + +// ---------------------------------------------------------------------- + +void CollisionCallbackManager::registerCanTestCollisionDetectionOnObjectThisFrame(CanTestCollisionDetectionOnObjectThisFrameFunction function) +{ + CollisionWorld::registerCanTestCollisionDetectionOnObjectThisFrame(function); +} + +// ---------------------------------------------------------------------- + +void CollisionCallbackManager::registerNoHitFunction(NoHitFunction function, int theObjectGOT) +{ + ms_NoHitFunctionArray[theObjectGOT] = function; +} + +// ---------------------------------------------------------------------- + +void CollisionCallbackManager::registerOnHitFunction(OnHitByObjectFunction function, int theObjectGOT, int ObjectThatWasHitByGOT) +{ + ms_functionMatrix[theObjectGOT][ObjectThatWasHitByGOT] = function; +} + +// ---------------------------------------------------------------------- + +void CollisionCallbackManager::registerConvertObjectToIndexFunction(ConvertObjectToIndexFunction function) +{ + ms_convertObjectToIndex = function; +} + +// ---------------------------------------------------------------------- + +void CollisionCallbackManager::registerDoCollisionWithTerrainFunction(DoCollisionWithTerrainFunction function) +{ + ms_doCollisionWithTerrain = function; +} + +// ---------------------------------------------------------------------- + +bool CollisionCallbackManager::intersectAndReflect(Object * const object, Object * const wasHitByThisObject, Result & result) +{ + // See if we need to ignore this collision + + if (!s_ignoreIntersectList.empty()) + { + NetworkId first(object->getNetworkId()); + NetworkId second(wasHitByThisObject->getNetworkId()); + + if (second < first) + { + first = wasHitByThisObject->getNetworkId(); + second = object->getNetworkId(); + } + + IgnoreIntersectList::const_iterator iterIgnoreIntersectList = s_ignoreIntersectList.find(first); + + if (iterIgnoreIntersectList != s_ignoreIntersectList.end()) + { + std::map::const_iterator iter = iterIgnoreIntersectList->second.find(second); + + if (iter != iterIgnoreIntersectList->second.end()) + { + // Ignore this intersection + + return false; + } + } + } + + // The pair is not in the ignore list, so allow the intersection check + + CollisionProperty const * collision = object->getCollisionProperty(); + NOT_NULL(collision); + + CollisionProperty const * wasHitByThisCollision = wasHitByThisObject->getCollisionProperty(); + NOT_NULL(wasHitByThisCollision); + + Capsule queryCapsule_w(collision->getQueryCapsule_w()); + + float const radius = queryCapsule_w.getRadius(); + + Vector const deltaTraveled_w(queryCapsule_w.getDelta()); + Vector direction_w(deltaTraveled_w); + if (direction_w.normalize()) + { + Vector const begin_w(queryCapsule_w.getPointA()); + Vector const end_w(queryCapsule_w.getPointB() + direction_w * radius); + + DEBUG_REPORT_LOG(ms_debugReport, ("begin = %f %f %f\n", begin_w.x, begin_w.y, begin_w.z)); + DEBUG_REPORT_LOG(ms_debugReport, ("end = %f %f %f\n", end_w.x, end_w.y, end_w.z)); + DEBUG_REPORT_LOG(ms_debugReport, ("direction = %f %f %f\n", direction_w.x, direction_w.y, direction_w.z)); + DEBUG_REPORT_LOG(ms_debugReport, ("length = %f\n", deltaTraveled_w.magnitude())); + + Vector normal_l; + float time = 0.0f; + + Vector const begin_l(wasHitByThisObject->rotateTranslate_w2o(begin_w)); + Vector const end_l(wasHitByThisObject->rotateTranslate_w2o(end_w)); + + BaseExtent const * const wasHitByThisBaseExtent_l = wasHitByThisCollision->getExtent_l(); + NOT_NULL(wasHitByThisBaseExtent_l); + + if (wasHitByThisBaseExtent_l->intersect(begin_l, end_l, &normal_l, &time)) + { + Vector const pointOfCollision_w(Vector::linearInterpolate (begin_w, end_w, time)); + Vector const normal_w(wasHitByThisObject->rotate_o2w(normal_l)); + + DEBUG_REPORT_LOG(ms_debugReport, ("\t\tHIT!\n")); + DEBUG_REPORT_LOG(ms_debugReport, ("\t\ttime = %f\n", time)); + DEBUG_REPORT_LOG(ms_debugReport, ("\t\tpoint = %f %f %f\n", pointOfCollision_w.x, pointOfCollision_w.y, pointOfCollision_w.z)); + + result.m_pointOfCollision_p = pointOfCollision_w; + result.m_normalOfSurface_p = normal_w; + result.m_deltaToMoveBack_p = pointOfCollision_w - end_w; + result.m_newReflection_p = normal_w.reflectIncoming(direction_w); + + DEBUG_REPORT_LOG(ms_debugReport, ("\t\t = %f %f %f\n", result.m_deltaToMoveBack_p.x, result.m_deltaToMoveBack_p.y, result.m_deltaToMoveBack_p.z)); + + return true; + } + } + + return false; +} + +// ---------------------------------------------------------------------- + +bool CollisionCallbackManager::intersectAndReflectWithTerrain(Object * const object, Result & result) +{ + CollisionProperty const * collision = object->getCollisionProperty(); + NOT_NULL(collision); + + Capsule queryCapsule_w(collision->getQueryCapsule_w()); + + float const radius = queryCapsule_w.getRadius(); + + Vector const deltaTraveled_w(queryCapsule_w.getDelta()); + Vector direction_w(deltaTraveled_w); + if (direction_w.normalize()) + { + Vector const begin_w(queryCapsule_w.getPointA()); + Vector const end_w(queryCapsule_w.getPointB() + direction_w * radius); + + DEBUG_REPORT_LOG(ms_debugReport, ("terrain begin = %f %f %f\n", begin_w.x, begin_w.y, begin_w.z)); + DEBUG_REPORT_LOG(ms_debugReport, ("terrain end = %f %f %f\n", end_w.x, end_w.y, end_w.z)); + DEBUG_REPORT_LOG(ms_debugReport, ("terrain direction = %f %f %f\n", direction_w.x, direction_w.y, direction_w.z)); + DEBUG_REPORT_LOG(ms_debugReport, ("terrain length = %f\n", deltaTraveled_w.magnitude())); + + TerrainObject const * const terrainObject = TerrainObject::getConstInstance(); + if (terrainObject != 0) + { + CollisionInfo info; + if (terrainObject->collide (begin_w, end_w, info)) + { + #ifdef _DEBUG + // calculate the parametric time for logging + float const actualDistance = begin_w.magnitudeBetween(info.getPoint()); + float const attemptedDistance = begin_w.magnitudeBetween(end_w); + float const parametricTime = (attemptedDistance != 0.0f) ? (actualDistance / attemptedDistance) : 0.0f; + #endif + + Vector const & pointOfCollision_w = info.getPoint(); + + #ifdef _DEBUG + DEBUG_REPORT_LOG(ms_debugReport, ("\t\tterrain HIT!\n")); + DEBUG_REPORT_LOG(ms_debugReport, ("\t\tterrain time = %f\n", parametricTime)); + DEBUG_REPORT_LOG(ms_debugReport, ("\t\tterrain point = %f %f %f\n", pointOfCollision_w.x, pointOfCollision_w.y, pointOfCollision_w.z)); + #endif + + result.m_pointOfCollision_p = pointOfCollision_w; + result.m_normalOfSurface_p = info.getNormal(); + result.m_deltaToMoveBack_p = pointOfCollision_w - end_w; + result.m_newReflection_p = result.m_normalOfSurface_p.reflectIncoming(direction_w); + + #ifdef _DEBUG + DEBUG_REPORT_LOG(ms_debugReport, ("\t\tterrain = %f %f %f\n", result.m_deltaToMoveBack_p.x, result.m_deltaToMoveBack_p.y, result.m_deltaToMoveBack_p.z)); + #endif + + return true; + } + } + } + + return false; +} + +// ====================================================================== + +void CollisionCallbackManagerNamespace::noCollisionDetectionThisFrame(Object * const object) +{ + FATAL(!ms_convertObjectToIndex, ("CollisionCallbackManagerNamespace::noCollisionDetectionThisFrame: ms_convertObjectToIndex == NULL.")); + FATAL(!object, ("CollisionCallbackManagerNamespace::noCollisionDetectionThisFrame: object == NULL.")); + + int const index = ms_convertObjectToIndex(object); + + NoHitFunctionArray::const_iterator ii = ms_NoHitFunctionArray.find(index); + + CollisionCallbackManager::NoHitFunction const function = (ii != ms_NoHitFunctionArray.end()) ? ii->second : 0; + + if (function) + { + (*function)(object); + } +} + +// ---------------------------------------------------------------------- + +bool CollisionCallbackManagerNamespace::collisionDetectionOnHit(Object * const object, Object * const wasHitByThisObject) +{ + FATAL(!ms_convertObjectToIndex, ("CollisionCallbackManagerNamespace::collisionDetectionOnHit: ms_convertObjectToIndex == NULL.")); + FATAL(!object, ("CollisionCallbackManagerNamespace::collisionDetectionOnHit: object == NULL.")); + FATAL(!wasHitByThisObject, ("CollisionCallbackManagerNamespace::collisionDetectionOnHit: wasHitByThisObject == NULL.")); + + CollisionCallbackManager::OnHitByObjectFunction function = 0; + + int const objectColumn = ms_convertObjectToIndex(object); + int const wasHitByThisObjectRow = ms_convertObjectToIndex(wasHitByThisObject); + + OnHitByObjectFunctionMatrix::const_iterator ii = ms_functionMatrix.find(objectColumn); + + if (ii != ms_functionMatrix.end()) + { + OnHitRow const & row = ii->second; + + OnHitRow::const_iterator jj = row.find(wasHitByThisObjectRow); + + function = (jj != row.end()) ? jj->second : 0; + } + + if (function) + { + return (*function)(object, wasHitByThisObject); + } + + return false; +} + +// ---------------------------------------------------------------------- + +bool CollisionCallbackManagerNamespace::doCollisionWithTerrain(Object * const object) +{ + if (ms_doCollisionWithTerrain) + { + return (*ms_doCollisionWithTerrain)(object); + } + return false; +} + +// ---------------------------------------------------------------------- + +void CollisionCallbackManager::addIgnoreIntersect(NetworkId const & networkId1, NetworkId const & networkId2) +{ + NetworkId first(networkId1); + NetworkId second(networkId2); + + if (second < first) + { + first = networkId2; + second = networkId1; + } + + // See if this pair is already in the list + + IgnoreIntersectList::iterator iterIgnoreIntersectList = s_ignoreIntersectList.find(first); + + if (iterIgnoreIntersectList != s_ignoreIntersectList.end()) + { + std::map::iterator iter = iterIgnoreIntersectList->second.find(second); + + if (iter != iterIgnoreIntersectList->second.end()) + { + // Already in the list, don't add it again, just ref count it + + ++iter->second; + + //LOG("space_debug_ai", ("CollisionCallbackManager::addIgnoreIntersect() networkId1(%s) networkId1(%s) REF COUNTING IGNORE", networkId1.getValueString().c_str(), networkId2.getValueString().c_str())); + + return; + } + } + + // The pair is not in the list so add it + + std::map newEntry; + newEntry.insert(std::make_pair(second, 1)); + s_ignoreIntersectList.insert(std::make_pair(first, newEntry)); + + //LOG("space_debug_ai", ("CollisionCallbackManager::addIgnoreIntersect() networkId1(%s) networkId1(%s) ADDING NEW IGNORE", networkId1.getValueString().c_str(), networkId2.getValueString().c_str())); +} + +// ---------------------------------------------------------------------- + +void CollisionCallbackManager::removeIgnoreIntersect(NetworkId const & networkId1, NetworkId const & networkId2) +{ + //LOG("space_debug_ai", ("CollisionCallbackManager::removeIgnoreIntersect() networkId1(%s) networkId1(%s)", networkId1.getValueString().c_str(), networkId2.getValueString().c_str())); + + NetworkId first(networkId1); + NetworkId second(networkId2); + + if (second < first) + { + first = networkId2; + second = networkId1; + } + + // See if this pair is already in the list + + IgnoreIntersectList::iterator iterIgnoreIntersectList = s_ignoreIntersectList.find(first); + + if (iterIgnoreIntersectList != s_ignoreIntersectList.end()) + { + std::map::iterator iter = iterIgnoreIntersectList->second.find(second); + + if (iter != iterIgnoreIntersectList->second.end()) + { + //LOG("space_debug_ai", ("CollisionCallbackManager::removeIgnoreIntersect() networkId1(%s) networkId1(%s) MATCH FOUND", networkId1.getValueString().c_str(), networkId2.getValueString().c_str())); + + if (--iter->second <= 0) + { + iterIgnoreIntersectList->second.erase(iter); + + if (iterIgnoreIntersectList->second.empty()) + { + s_ignoreIntersectList.erase(iterIgnoreIntersectList); + } + + //LOG("space_debug_ai", ("CollisionCallbackManager::removeIgnoreIntersect() networkId1(%s) networkId1(%s) REMOVING IGNORE", networkId1.getValueString().c_str(), networkId2.getValueString().c_str())); + } + } + } +} + +// ---------------------------------------------------------------------- + +int CollisionCallbackManager::getIgnoredIntersectionCount() +{ + return static_cast(s_ignoreIntersectList.size()); +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/collision/CollisionCallbackManager.h b/engine/shared/library/sharedGame/src/shared/collision/CollisionCallbackManager.h new file mode 100644 index 00000000..7ff39401 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/collision/CollisionCallbackManager.h @@ -0,0 +1,65 @@ +// ====================================================================== +// +// CollisionCallbackManager.h +// Copyright 2004, Sony Online Entertainment Inc. +// All Rights Reserved. +// +// ====================================================================== + +#ifndef INCLUDED_CollisionCallbackManager_H +#define INCLUDED_CollisionCallbackManager_H + +#include "sharedMath/Vector.h" + +// ====================================================================== + +class Object; +class NetworkId; + +// CollisionCallbackManager sits on top of CollisionWorld and offers a bridge between +// the game and CollisionWorld. It also acts as a dispatch mediator for implementing +// collisions between objects with different GOT types. + +class CollisionCallbackManager +{ +public: + typedef bool (*CanTestCollisionDetectionOnObjectThisFrameFunction)(Object * const object); + typedef void (*NoHitFunction)(Object * const object); + typedef bool (*OnHitByObjectFunction)(Object * const object, Object * const wasHitByThisObject); + typedef bool (*DoCollisionWithTerrainFunction)(Object * const object); + typedef int (*ConvertObjectToIndexFunction)(Object * const object); + + static void install(); + + static void registerCanTestCollisionDetectionOnObjectThisFrame(CanTestCollisionDetectionOnObjectThisFrameFunction); + static void registerNoHitFunction(NoHitFunction function, int theObjectGOT); + static void registerOnHitFunction(OnHitByObjectFunction function, int theObjectGOT, int ObjectThatWasHitByGOT); + static void registerDoCollisionWithTerrainFunction(DoCollisionWithTerrainFunction function); + static void registerConvertObjectToIndexFunction(ConvertObjectToIndexFunction function); + + struct Result + { + Vector m_pointOfCollision_p; + Vector m_deltaToMoveBack_p; + Vector m_newReflection_p; + Vector m_normalOfSurface_p; + + Result(); + }; + + static bool intersectAndReflect(Object * const object, Object * const wasHitByThisObject, Result & result); + static bool intersectAndReflectWithTerrain(Object * const object, Result & result); + static void addIgnoreIntersect(NetworkId const & networkId1, NetworkId const & networkId2); + static void removeIgnoreIntersect(NetworkId const & networkId1, NetworkId const & networkId2); + static int getIgnoredIntersectionCount(); + +private: + CollisionCallbackManager(); + CollisionCallbackManager(CollisionCallbackManager const & copy); + CollisionCallbackManager & operator = (CollisionCallbackManager const & copy); +}; + +// ====================================================================== + +#endif + diff --git a/engine/shared/library/sharedGame/src/shared/combat/CombatDataTable.cpp b/engine/shared/library/sharedGame/src/shared/combat/CombatDataTable.cpp new file mode 100644 index 00000000..21bf8b23 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/combat/CombatDataTable.cpp @@ -0,0 +1,454 @@ +// ====================================================================== +// +// CombatDataTable.cpp +// Copyright 2006 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/CombatDataTable.h" + +#include "sharedUtility/DataTableManager.h" +#include "sharedUtility/DataTable.h" + +#include +#include +#include +#include + +// ====================================================================== + +namespace CombatDataTableNamespace +{ + char const * const cs_combatDataTableName = "datatables/combat/combat_data.iff"; + std::string const cs_columnActionNameCrc("actionNameCrc"); + int s_actionNameCrcColumn; + + std::hash_map s_commandsWithMinInvisLevelRequired; +} + +using namespace CombatDataTableNamespace; + +// ====================================================================== + +void CombatDataTable::install() +{ + DataTable const * const actionData = DataTableManager::getTable(cs_combatDataTableName, true); + if (!actionData) + { + DEBUG_WARNING(true, ("Could not find table [%s].", cs_combatDataTableName)); + return; + } + s_actionNameCrcColumn = actionData->findColumnNumber(cs_columnActionNameCrc); + + // cache off commands with a minInvisLevelRequired specified for later use/reuse + unsigned int const numRows = static_cast(actionData->getNumRows()); + int const minInvisLevelRequiredColumn = actionData->findColumnNumber("minInvisLevelRequired"); + if ((numRows > 0) && (s_actionNameCrcColumn != -1) && (minInvisLevelRequiredColumn != -1)) + { + uint32 actionNameCrc; + int minInvisLevelRequired; + for (unsigned int i = 0; i < numRows; ++i) + { + actionNameCrc = actionData->getIntValue(s_actionNameCrcColumn, i); + minInvisLevelRequired = actionData->getIntValue(minInvisLevelRequiredColumn, i); + + if (minInvisLevelRequired != -1) + s_commandsWithMinInvisLevelRequired.insert(std::make_pair(actionNameCrc, minInvisLevelRequired)); + } + } +} + +// ---------------------------------------------------------------------- + +bool CombatDataTable::isActionClientAnim(uint32 commandHash) +{ + if(commandHash == 0) + return false; + + DataTable const * const actionData = DataTableManager::getTable(cs_combatDataTableName, true); + if (!actionData) + { + DEBUG_WARNING(true, ("Could not find table [%s].", cs_combatDataTableName)); + return false; + } + + int const row = actionData->searchColumnInt(s_actionNameCrcColumn, commandHash); + if (row < 0) + { + DEBUG_WARNING(true, ("Could not find string hash [%u] in table [%s, %d].", commandHash, cs_combatDataTableName, s_actionNameCrcColumn)); + return false; + } + + //get/return action animation field "doClientAnim" from action data + return (0 != actionData->getIntValue("doClientAnim", row)); +} + +// ---------------------------------------------------------------------- + +std::string CombatDataTable::getActionAnimationData(uint32 commandHash, char const * const weaponType) +{ + if(commandHash == 0) + return ""; + + std::string actionAnimationData; + + DataTable const * const actionData = DataTableManager::getTable(cs_combatDataTableName, true); + if (!actionData) + { + DEBUG_WARNING(true, ("Could not find table [%s].", cs_combatDataTableName)); + return ""; + } + + + int const row = actionData->searchColumnInt(s_actionNameCrcColumn, commandHash); + if (row < 0) + { + DEBUG_WARNING(true, ("Could not find string hash [%u] in table [%s].", commandHash, cs_combatDataTableName)); + return ""; + } + + //get action animation name from action data (need to parse) + std::string fieldName = "anim_"; + + std::string lowerWeaponType(weaponType); + int (*pf)(int)=::tolower; + std::transform(lowerWeaponType.begin(), lowerWeaponType.end(), lowerWeaponType.begin(), pf); + + fieldName += lowerWeaponType; + + if (actionData->doesColumnExist(fieldName)) + { + actionAnimationData = actionData->getStringValue(fieldName, row); + } + if (0 >= actionAnimationData.length()) + { + actionAnimationData = actionData->getStringValue("animDefault", row); + } + + return actionAnimationData; +} + +// ---------------------------------------------------------------------- + +bool CombatDataTable::actionForcesCharacterIntoCombat(uint32 commandHash) +{ + if(commandHash == 0) + return false; + + DataTable const * const actionData = DataTableManager::getTable(cs_combatDataTableName, true); + if (actionData == 0) + { + DEBUG_WARNING(true, ("Could not find table [%s].", cs_combatDataTableName)); + return false; + } + + int const row = actionData->searchColumnInt(s_actionNameCrcColumn, commandHash); + if (row < 0) + { + DEBUG_WARNING(true, ("Could not find string hash [%u] in table [%s].", commandHash, cs_combatDataTableName)); + return false; + } + + //get/return action animation field "forcesCharacterIntoCombat" from action data + return (actionData->getIntValue("forcesCharacterIntoCombat", row) != 0); +} + +// ---------------------------------------------------------------------- + +int32 CombatDataTable::getAttackType(uint32 commandHash) +{ + if(commandHash == 0) + return AT_none; + + DataTable const * const actionData = DataTableManager::getTable(cs_combatDataTableName, true); + if (actionData == 0) + { + DEBUG_WARNING(true, ("Could not find table [%s].", cs_combatDataTableName)); + return AT_none; + } + + int const row = actionData->searchColumnInt(s_actionNameCrcColumn, commandHash); + if (row < 0) + { + DEBUG_WARNING(true, ("Could not find string hash [%u] in table [%s].", commandHash, cs_combatDataTableName)); + return AT_none; + } + + return (actionData->getIntValue("attackType", row)); +} + +// ---------------------------------------------------------------------- + +int32 CombatDataTable::getHitType(uint32 commandHash) +{ + if(commandHash == 0) + return HT_attack; + + DataTable const * const actionData = DataTableManager::getTable(cs_combatDataTableName, true); + if (actionData == 0) + { + DEBUG_WARNING(true, ("Could not find table [%s].", cs_combatDataTableName)); + return HT_attack; + } + + int const row = actionData->searchColumnInt(s_actionNameCrcColumn, commandHash); + if (row < 0) + { + DEBUG_WARNING(true, ("Could not find string hash [%u] in table [%s].", commandHash, cs_combatDataTableName)); + return HT_attack; + } + + return (actionData->getIntValue("hitType", row)); +} + +// ---------------------------------------------------------------------- + +int32 CombatDataTable::getValidTarget(uint32 commandHash) +{ + if(commandHash == 0) + return VTT_none; + + DataTable const * const actionData = DataTableManager::getTable(cs_combatDataTableName, true); + if (!actionData) + { + DEBUG_WARNING(true, ("Could not find table [%s].", cs_combatDataTableName)); + return VTT_none; + } + + int const row = actionData->searchColumnInt(s_actionNameCrcColumn, commandHash); + if (row < 0) + { + DEBUG_WARNING(true, ("Could not find string hash [%u] in table [%s].", commandHash, cs_combatDataTableName)); + return VTT_none; + } + + return (actionData->getIntValue("validTarget", row)); +} + +// ---------------------------------------------------------------------- + +float CombatDataTable::getMinRange(uint32 commandHash) +{ + if(commandHash == 0) + return 0.0f; + + DataTable const * const actionData = DataTableManager::getTable(cs_combatDataTableName, true); + if (!actionData) + { + DEBUG_WARNING(true, ("Could not find table [%s].", cs_combatDataTableName)); + return 0.0f; + } + + int const row = actionData->searchColumnInt(s_actionNameCrcColumn, commandHash); + if (row < 0) + { + DEBUG_WARNING(true, ("Could not find string hash [%u] in table [%s].", commandHash, cs_combatDataTableName)); + return 0.0f; + } + + return (actionData->getFloatValue("minRange", row)); +} + +// ---------------------------------------------------------------------- + +float CombatDataTable::getMaxRange(uint32 commandHash) +{ + if(commandHash == 0) + return 0.0f; + + DataTable const * const actionData = DataTableManager::getTable(cs_combatDataTableName, true); + if (!actionData) + { + DEBUG_WARNING(true, ("Could not find table [%s].", cs_combatDataTableName)); + return 0.0f; + } + + int const row = actionData->searchColumnInt(s_actionNameCrcColumn, commandHash); + if (row < 0) + { + DEBUG_WARNING(true, ("Could not find string hash [%u] in table [%s].", commandHash, cs_combatDataTableName)); + return 0.0f; + } + + return (actionData->getFloatValue("maxRange", row)); +} + +// ---------------------------------------------------------------------- + +float CombatDataTable::getActionCost(uint32 commandHash) +{ + if(commandHash == 0) + return 0.0f; + + DataTable const * const actionData = DataTableManager::getTable(cs_combatDataTableName, true); + if (!actionData) + { + DEBUG_WARNING(true, ("Could not find table [%s].", cs_combatDataTableName)); + return 0.0f; + } + + int const row = actionData->searchColumnInt(s_actionNameCrcColumn, commandHash); + if (row < 0) + { + DEBUG_WARNING(true, ("Could not find string hash [%u] in table [%s].", commandHash, cs_combatDataTableName)); + return 0.0f; + } + + return (actionData->getFloatValue("actionCost", row)); +} + +// ---------------------------------------------------------------------- + +float CombatDataTable::getMindCost(uint32 commandHash) +{ + if(commandHash == 0) + return 0.0f; + + DataTable const * const actionData = DataTableManager::getTable(cs_combatDataTableName, true); + if (!actionData) + { + DEBUG_WARNING(true, ("Could not find table [%s].", cs_combatDataTableName)); + return 0.0f; + } + + int const row = actionData->searchColumnInt(s_actionNameCrcColumn, commandHash); + if (row < 0) + { + DEBUG_WARNING(true, ("Could not find string hash [%u] in table [%s].", commandHash, cs_combatDataTableName)); + return 0.0f; + } + + return (actionData->getFloatValue("mindCost", row)); +} + +// ---------------------------------------------------------------------- + +bool CombatDataTable::getCancelsAutoAttack(uint32 commandHash) +{ + if(commandHash == 0) + return false; + + DataTable const * const actionData = DataTableManager::getTable(cs_combatDataTableName, true); + if (!actionData) + { + DEBUG_WARNING(true, ("Could not find table [%s].", cs_combatDataTableName)); + return false; + } + + int const row = actionData->searchColumnInt(s_actionNameCrcColumn, commandHash); + if (row < 0) + { + DEBUG_WARNING(true, ("Could not find string hash [%u] in table [%s].", commandHash, cs_combatDataTableName)); + return false; + } + + return (actionData->getIntValue("cancelsAutoAttack", row) == 1); +} + +// ---------------------------------------------------------------------- + +float CombatDataTable::getPercentAddFromWeapon(uint32 commandHash) +{ + if(commandHash == 0) + return 0.0f; + + DataTable const * const actionData = DataTableManager::getTable(cs_combatDataTableName, true); + if (!actionData) + { + DEBUG_WARNING(true, ("Could not find table [%s].", cs_combatDataTableName)); + return 0.0f; + } + + int const row = actionData->searchColumnInt(s_actionNameCrcColumn, commandHash); + if (row < 0) + { + DEBUG_WARNING(true, ("Could not find string hash [%u] in table [%s].", commandHash, cs_combatDataTableName)); + return 0.0f; + } + + return actionData->getFloatValue("percentAddFromWeapon", row); +} + +// ---------------------------------------------------------------------- + +std::string CombatDataTable::getSpecialLine(uint32 commandHash) +{ + if(commandHash == 0) + return ""; + + DataTable const * const actionData = DataTableManager::getTable(cs_combatDataTableName, true); + if (!actionData) + { + DEBUG_WARNING(true, ("Could not find table [%s].", cs_combatDataTableName)); + return ""; + } + + int const row = actionData->searchColumnInt(s_actionNameCrcColumn, commandHash); + if (row < 0) + { + DEBUG_WARNING(true, ("Could not find string hash [%u] in table [%s].", commandHash, cs_combatDataTableName)); + return ""; + } + + return actionData->getStringValue("specialLine", row); +} + +// ---------------------------------------------------------------------- + +int CombatDataTable::getMinInvisLevelRequired(uint32 commandHash) +{ + if(commandHash == 0) + return -1; + + std::hash_map::const_iterator it = s_commandsWithMinInvisLevelRequired.find(commandHash); + if (it != s_commandsWithMinInvisLevelRequired.end()) + return it->second; + + return -1; +} + +// ---------------------------------------------------------------------- + +int CombatDataTable::getTrailBits(uint32 commandHash) +{ + if(commandHash == 0) + return 0; + + DataTable const * const actionData = DataTableManager::getTable(cs_combatDataTableName, true); + if (!actionData) + { + DEBUG_WARNING(true, ("Could not find table [%s].", cs_combatDataTableName)); + return 0; + } + + int const row = actionData->searchColumnInt(s_actionNameCrcColumn, commandHash); + if (row < 0) + { + DEBUG_WARNING(true, ("Could not find string hash [%u] in table [%s].", commandHash, cs_combatDataTableName)); + return 0; + } + + bool rightHand = (actionData->getIntValue("intRightHand", row) == 1); + bool leftHand = (actionData->getIntValue("intLeftHand", row) == 1); + bool rightFoot = (actionData->getIntValue("intRightFoot", row) == 1); + bool leftFoot = (actionData->getIntValue("intLeftFoot", row) == 1); + bool weapon = (actionData->getIntValue("intWeapon", row) == 1); + + int bits = 0; + + if(leftFoot) + bits = bits | 1 << 0; + if(rightFoot) + bits = bits | 1 << 1; + if(leftHand) + bits = bits | 1 << 2; + if(rightHand) + bits = bits | 1 << 3; + if(weapon) + bits = bits | 1 << 4; + + return bits; +} +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/combat/CombatDataTable.h b/engine/shared/library/sharedGame/src/shared/combat/CombatDataTable.h new file mode 100644 index 00000000..b07dd7ee --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/combat/CombatDataTable.h @@ -0,0 +1,88 @@ +// ====================================================================== +// +// CombatDataTable.h +// Copyright 2006 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#ifndef INCLUDED_CombatDataTable_H +#define INCLUDED_CombatDataTable_H + +// ====================================================================== + +class CombatDataTable // static class +{ +public: + // the order and value of these are tied to the order and value that + // are displayed in the drop down list in the chat option window + enum CombatSpamFilterType + { + CSFT_All = 0, + CSFT_Self, + CSFT_Group, + CSFT_None + }; + + enum ValidTargetType + { + VTT_none =-1, + VTT_standard = 0, + VTT_mob = 1, + VTT_creature = 2, + VTT_npc = 3, + VTT_droid = 4, + VTT_pvp = 5, + VTT_jedi = 6, + VTT_dead = 7, + VTT_friend = 8 + }; + + enum AttackType + { + AT_none =-1, + AT_cone = 0, + AT_singleTarget = 1, + AT_area = 2, + AT_targetArea = 3, + AT_dualWield = 4 + }; + + enum HitType + { + HT_attack =-1, + HT_nonAttack = 0, + HT_nonDamageAttack = 4, + HT_heal = 5, + HT_delayAttack = 6, + HT_revive = 7 + }; + + static void install(); + + static bool isActionClientAnim(uint32 commandHash); + static std::string getActionAnimationData(uint32 commandHash, char const * const weaponType); + static bool actionForcesCharacterIntoCombat(uint32 commandHash); + static int32 getAttackType(uint32 commandHash); + static int32 getHitType(uint32 commandHash); + static int32 getValidTarget(uint32 commandHash); + static float getMinRange(uint32 commandHash); + static float getMaxRange(uint32 commandHash); + static float getActionCost(uint32 commandHash); + static float getMindCost(uint32 commandHash); + static bool getCancelsAutoAttack(uint32 commandHash); + static float getPercentAddFromWeapon(uint32 commandHash); + static std::string getSpecialLine(uint32 commandHash); + static int getMinInvisLevelRequired(uint32 commandHash); + static int getTrailBits(uint32 commandHash); + +private: // disabled + + CombatDataTable(); + CombatDataTable(CombatDataTable const &); + CombatDataTable &operator =(CombatDataTable const &); +}; + +// ====================================================================== + +#endif // INCLUDED_CombatDataTable_H diff --git a/engine/shared/library/sharedGame/src/shared/combat/CombatTimingTable.cpp b/engine/shared/library/sharedGame/src/shared/combat/CombatTimingTable.cpp new file mode 100644 index 00000000..183c8afe --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/combat/CombatTimingTable.cpp @@ -0,0 +1,100 @@ +// ====================================================================== +// +// CombatTimingTable.cpp +// +// Copyright 2005 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/CombatTimingTable.h" + +#include "sharedUtility/DataTableManager.h" +#include "sharedUtility/DataTable.h" + +// ====================================================================== + +namespace CombatTimingTableNamespace +{ + // ---------------------------------------------------------------------- + + char const * const cs_combatTimingTableName = "datatables/combat/combat_timing.iff"; + + // ---------------------------------------------------------------------- +} + +// ====================================================================== + +using namespace CombatTimingTableNamespace; + +int CombatTimingTable::getMaximumShotsTillWeaponReload(std::string const & weaponType) +{ + int result = 0; + + DataTable * combatTimingTable = DataTableManager::getTable(cs_combatTimingTableName, true); + if (combatTimingTable) + { + int rowNum = combatTimingTable->searchColumnString(0, weaponType); + result = combatTimingTable->getIntValue("MaximumShotsTillWeaponReload", rowNum); + } + + return result; +} + +bool CombatTimingTable::isContinuous(std::string const & weaponType) +{ + bool result = false; + + DataTable * combatTimingTable = DataTableManager::getTable(cs_combatTimingTableName, true); + if (combatTimingTable) + { + int rowNum = combatTimingTable->searchColumnString(0, weaponType); + result = combatTimingTable->getIntValue("Continuous", rowNum) ? true : false; + } + + return result; +} + +float CombatTimingTable::getWeaponReloadTimeSeconds(std::string const & weaponType) +{ + float result = 0; + + DataTable * combatTimingTable = DataTableManager::getTable(cs_combatTimingTableName, true); + if (combatTimingTable) + { + int rowNum = combatTimingTable->searchColumnString(0, weaponType); + result = combatTimingTable->getFloatValue("WeaponReloadTimeSeconds", rowNum); + } + + return result; +} + +const char *CombatTimingTable::getWeaponReloadClientEffect(std::string const & weaponType) +{ + const char * result = 0; + + DataTable * combatTimingTable = DataTableManager::getTable(cs_combatTimingTableName, true); + if (combatTimingTable) + { + int rowNum = combatTimingTable->searchColumnString(0, weaponType); + result = combatTimingTable->getStringValue("WeaponReloadClientEffect", rowNum); + } + + return result; +} + +const char *CombatTimingTable::getWeaponReloadClientAnimation(std::string const & weaponType) +{ + const char * result = 0; + + DataTable * combatTimingTable = DataTableManager::getTable(cs_combatTimingTableName, true); + if (combatTimingTable) + { + int rowNum = combatTimingTable->searchColumnString(0, weaponType); + result = combatTimingTable->getStringValue("WeaponReloadClientAnimation", rowNum); + } + + return result; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/combat/CombatTimingTable.h b/engine/shared/library/sharedGame/src/shared/combat/CombatTimingTable.h new file mode 100644 index 00000000..5f47d6c6 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/combat/CombatTimingTable.h @@ -0,0 +1,26 @@ +// ====================================================================== +// +// CombatTimingTable.h +// +// Copyright 2005 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_CombatTimingTable_H +#define INCLUDED_CombatTimingTable_H + +// ====================================================================== + +class CombatTimingTable // static class +{ +public: + static int getMaximumShotsTillWeaponReload(std::string const & weaponType); + static bool isContinuous(std::string const & weaponType); + static float getWeaponReloadTimeSeconds(std::string const & weaponType); + static const char *getWeaponReloadClientEffect(std::string const & weaponType); + static const char *getWeaponReloadClientAnimation(std::string const & weaponType); +}; + +// ====================================================================== + +#endif // INCLUDED_CombatTimingTable_H diff --git a/engine/shared/library/sharedGame/src/shared/command/Command.cpp b/engine/shared/library/sharedGame/src/shared/command/Command.cpp new file mode 100644 index 00000000..02ad01be --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/command/Command.cpp @@ -0,0 +1,183 @@ +// ====================================================================== +// +// Command.cpp +// +// Copyright 2002 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/Command.h" +#include "sharedFoundation/Crc.h" +#include "StringId.h" + +// ====================================================================== + +namespace CommandNamespace +{ + const uint32 s_defaultAttackCoolGroup = 0x399ea293; // "defaultattack" +}; + +using namespace CommandNamespace; + +Command::Command() : + m_commandName(), + m_commandHash(Crc::crcNull), + m_defaultPriority(CP_NumberOfPriorities), + m_scriptHook(), + m_failScriptHook(), + m_cppHook(), + m_failCppHook(), + m_defaultTime(0.0f), + m_characterAbility(), + m_locomotionPermissions(), + m_statePermissions(), + m_stateRequired(), + m_tempScript(), + m_targetType(CTT_NumberOfTargetTypes), + m_stringId(), + m_visibleToClients(0), + m_callOnTarget(false), + m_commandGroup(0), + m_maxRangeToTarget(0.0f), + m_maxRangeToTargetSquared(0.0f), + m_godLevel(0), + m_displayGroup(0), + m_addToCombatQueue(false), + m_warmTime(0), + m_execTime(0), + m_coolTime(0), + m_coolGroup(0), + m_weaponTypesValid(0), + m_weaponTypesInvalid(0), + m_coolGroup2(0), + m_coolTime2(0), + m_toolbarOnly(false), + m_fromServerOnly(false) +{ +} + +// ---------------------------------------------------------------------- + +Command::Command(Command const &rhs) : + m_commandName(rhs.m_commandName), + m_commandHash(rhs.m_commandHash), + m_defaultPriority(rhs.m_defaultPriority), + m_scriptHook(rhs.m_scriptHook), + m_failScriptHook(rhs.m_failScriptHook), + m_cppHook(rhs.m_cppHook), + m_failCppHook(rhs.m_failCppHook), + m_defaultTime(rhs.m_defaultTime), + m_characterAbility(rhs.m_characterAbility), + m_locomotionPermissions(rhs.m_locomotionPermissions), + m_statePermissions(rhs.m_statePermissions), + m_stateRequired(rhs.m_stateRequired), + m_tempScript(rhs.m_tempScript), + m_targetType(rhs.m_targetType), + m_stringId(rhs.m_stringId), + m_visibleToClients(rhs.m_visibleToClients), + m_callOnTarget(rhs.m_callOnTarget), + m_commandGroup(rhs.m_commandGroup), + m_maxRangeToTarget(rhs.m_maxRangeToTarget), + m_maxRangeToTargetSquared(rhs.m_maxRangeToTargetSquared), + m_godLevel(rhs.m_godLevel), + m_displayGroup(rhs.m_displayGroup), + m_addToCombatQueue(rhs.m_addToCombatQueue), + m_warmTime(rhs.m_warmTime), + m_execTime(rhs.m_execTime), + m_coolTime(rhs.m_coolTime), + m_coolGroup(rhs.m_coolGroup), + m_weaponTypesValid(rhs.m_weaponTypesValid), + m_weaponTypesInvalid(rhs.m_weaponTypesInvalid), + m_coolGroup2(rhs.m_coolGroup2), + m_coolTime2(rhs.m_coolTime2), + m_toolbarOnly(rhs.m_toolbarOnly), + m_fromServerOnly(rhs.m_fromServerOnly) +{ +} + +// ---------------------------------------------------------------------- + +Command &Command::operator=(Command const &rhs) +{ + if (&rhs != this) + { + m_commandName = rhs.m_commandName; + m_commandHash = rhs.m_commandHash; + m_defaultPriority = rhs.m_defaultPriority; + m_scriptHook = rhs.m_scriptHook; + m_failScriptHook = rhs.m_failScriptHook; + m_cppHook = rhs.m_cppHook; + m_failCppHook = rhs.m_failCppHook; + m_defaultTime = rhs.m_defaultTime; + m_characterAbility = rhs.m_characterAbility; + m_locomotionPermissions = rhs.m_locomotionPermissions; + m_statePermissions = rhs.m_statePermissions; + m_stateRequired = rhs.m_stateRequired; + m_tempScript = rhs.m_tempScript; + m_targetType = rhs.m_targetType; + m_stringId = rhs.m_stringId; + m_visibleToClients = rhs.m_visibleToClients; + m_callOnTarget = rhs.m_callOnTarget; + m_commandGroup = rhs.m_commandGroup; + m_maxRangeToTarget = rhs.m_maxRangeToTarget; + m_maxRangeToTargetSquared = rhs.m_maxRangeToTargetSquared; + m_godLevel = rhs.m_godLevel; + m_displayGroup = rhs.m_displayGroup; + m_addToCombatQueue = rhs.m_addToCombatQueue; + m_warmTime = rhs.m_warmTime; + m_execTime = rhs.m_execTime; + m_coolTime = rhs.m_coolTime; + m_coolGroup = rhs.m_coolGroup; + m_weaponTypesValid = rhs.m_weaponTypesValid; + m_weaponTypesInvalid = rhs.m_weaponTypesInvalid; + m_coolGroup2 = rhs.m_coolGroup2; + m_coolTime2 = rhs.m_coolTime2; + m_toolbarOnly = rhs.m_toolbarOnly; + m_fromServerOnly = rhs.m_fromServerOnly; + } + return *this; +} + +// ---------------------------------------------------------------------- + +bool Command::isNull() const +{ + return m_commandHash == Crc::crcNull; +} + +// ---------------------------------------------------------------------- + +bool Command::isPrimaryCommand() const +{ + return m_coolGroup == s_defaultAttackCoolGroup; +} + +//---------------------------------------------------------------------- + +const StringId & Command::getStringIdForErrorCode (const ErrorCode code) +{ + static const std::string table = "cmd_err"; + + static const StringId ids [Command::CEC_Max] = + { + StringId (table, "success_prose"), + StringId (table, "locomotion_prose"), + StringId (table, "ability_prose"), + StringId (table, "target_type_prose"), + StringId (table, "target_range_prose"), + StringId (table, "state_prose"), + StringId (table, "state_must_have_prose"), + StringId (table, "god_level_prose") + }; + + if (code < 0 || code >= Command::CEC_Max) + { + WARNING(true, ("Command::getStringIdForErrorCode received invalid code %d", static_cast(code))); + return ids [static_cast(Command::CEC_Success)]; + } + return ids [static_cast(code)]; +} + +// ====================================================================== + diff --git a/engine/shared/library/sharedGame/src/shared/command/Command.h b/engine/shared/library/sharedGame/src/shared/command/Command.h new file mode 100644 index 00000000..8d1b252f --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/command/Command.h @@ -0,0 +1,141 @@ +// ====================================================================== +// +// Command.h +// +// Copyright 2002 Sony Online Entertainment +// +// ====================================================================== + + +#ifndef INCLUDED_Command_H +#define INCLUDED_Command_H + +#include "sharedGame/CommandCppFunc.def" +#include "swgSharedUtility/Locomotions.h" +#include "swgSharedUtility/States.h" +#include + +class NetworkId; +class StringId; + +//---------------------------------------------------------------------- + +class Command +{ +public: + + Command(); + Command(Command const &); + Command &operator=(Command const &); + + bool isNull() const; + bool isPrimaryCommand() const; // test cooldown group against "defaultAttack" + + enum Priority + { + CP_Immediate = 0, + CP_Front = 1, + CP_Normal = 2, + CP_Default = 3, // not a real priority, falls through + CP_NumberOfPriorities = 4, + }; + + enum Target + { + CT_Friend = 0, + CT_Enemy = 1, + CT_Other = 2, + CT_NumberOfTargets = 3 + }; + + enum TargetType + { + CTT_None = 0, + CTT_Required = 1, + CTT_Optional = 2, + CTT_Location = 3, + CTT_All = 4, + CTT_NumberOfTargetTypes = 5 + }; + + enum ErrorCode + { + CEC_Success = 0, + CEC_Locomotion = 1, + CEC_Ability = 2, + CEC_TargetType = 3, + CEC_TargetRange = 4, + CEC_StateMustNotHave = 5, // command not allowed while in a particular state + CEC_StateMustHave = 6, // command not allowed until in a particular state + CEC_GodLevel = 7, + CEC_Cancelled = 8, + CEC_Max = 9 + }; + + enum WeaponType + { + CWT_Rifle = 0, + CWT_Carbine = 1, + CWT_Pistol = 2, + CWT_Heavy = 3, + CWT_1handMelee = 4, + CWT_2handMelee = 5, + CWT_Unarmed = 6, + CWT_Polearm = 7, + CWT_Thrown = 8, + CWT_1handLightsaber = 9, + CWT_2handLightsaber = 10, + CWT_PolearmLightsaber = 11, + CWT_Ranged = -1, + CWT_Melee = -2, + CWT_All = -3, + CWT_AllLightsabers = -4, + CWT_ForcePower = -5, + CWT_AllButHeavy = -6 + }; + + static const StringId & getStringIdForErrorCode (const ErrorCode code); + + typedef CommandCppFunc::Type CppFunc; + +public: + std::string m_commandName; + uint32 m_commandHash; + Priority m_defaultPriority; + std::string m_scriptHook; + std::string m_failScriptHook; + CppFunc m_cppHook; + CppFunc m_failCppHook; + float m_defaultTime; + std::string m_characterAbility; + std::bitset m_locomotionPermissions; + std::bitset m_statePermissions; + std::bitset m_stateRequired; + std::string m_tempScript; + Target m_target; + TargetType m_targetType; + std::string m_stringId; + int m_visibleToClients; + bool m_callOnTarget; + uint32 m_commandGroup; + float m_maxRangeToTarget; + float m_maxRangeToTargetSquared; + int m_godLevel; + uint32 m_displayGroup; + bool m_addToCombatQueue; + float m_warmTime; + float m_execTime; + float m_coolTime; + uint32 m_coolGroup; + uint32 m_weaponTypesValid; + uint32 m_weaponTypesInvalid; + uint32 m_coolGroup2; + float m_coolTime2; + bool m_toolbarOnly; + bool m_fromServerOnly; +}; + +//---------------------------------------------------------------------- + +#endif // INCLUDED_Command_H + diff --git a/engine/shared/library/sharedGame/src/shared/command/CommandChecks.cpp b/engine/shared/library/sharedGame/src/shared/command/CommandChecks.cpp new file mode 100644 index 00000000..96691ae9 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/command/CommandChecks.cpp @@ -0,0 +1,200 @@ +// ====================================================================== +// +// CommandChecks.cpp +// Copyright 2006 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/CommandChecks.h" + +#include "sharedGame/CombatDataTable.h" +#include "sharedGame/Command.h" +#include "sharedGame/ConfigSharedGame.h" +#include "sharedGame/GameObjectTypes.h" +#include "sharedGame/SharedObjectTemplate.h" +#include "sharedGame/SharedCreatureObjectTemplate.h" +#include "sharedObject/NetworkIdManager.h" +#include "sharedObject/Object.h" +#include "swgSharedUtility/Locomotions.h" + +// ====================================================================== + +void CommandChecks::getRangeForCommand(Command const * command, float minWeaponRange, float maxWeaponRange, bool weaponCheckLast, float & min, float & max) +{ + // DEFAULT: weapon range + if (!weaponCheckLast && (minWeaponRange > 0.0f || maxWeaponRange > 0.0f)) + { + min = minWeaponRange; + max = maxWeaponRange; + } + + // OVERRIDDEN BY: command_table + if (command->m_maxRangeToTarget > 0.0f) + { + min = -1; + max = command->m_maxRangeToTarget; + } + + // OVERRIDDEN BY: combat_data table + const float minDist = CombatDataTable::getMinRange(command->m_commandHash); + const float maxDist = CombatDataTable::getMaxRange(command->m_commandHash); + if (minDist > 0.0f || maxDist > 0.0f) + { + min = minDist; + max = maxDist; + } + + // OVERRIDDEN BY: optionally the weapon check can be last and most authoratative check... + if (weaponCheckLast && (minWeaponRange > 0.0f || maxWeaponRange > 0.0f)) + { + min = minWeaponRange; + max = maxWeaponRange; + } +} + +//----------------------------------------------------------------------- + +bool CommandChecks::isLocomotionValidForCommand(Command const * command, Locomotions::Enumerator locomotion, float speed) +{ + // if you are not allowed to run, still allow the command if you are running slowly enough + if(locomotion == Locomotions::Running && !command->m_locomotionPermissions[Locomotions::Running]) + { + return (speed < ConfigSharedGame::getMovementThresholdForActionValidation()); + } + + return command->m_locomotionPermissions[locomotion]; +} + +//----------------------------------------------------------------------- + +bool CommandChecks::isEnoughActionPointsForCommand(Command const * command, int currentActionPoints) +{ + bool result = false; + + float actionCost = CombatDataTable::getActionCost(command->m_commandHash); + + if (actionCost <= currentActionPoints) + result = true; + + return result; +} + +//----------------------------------------------------------------------- + +bool CommandChecks::isEnoughMindPointsForCommand(Command const * command, int currentMindPoints) +{ + bool result = false; + + float mindCost = CombatDataTable::getMindCost(command->m_commandHash); + + if (mindCost <= currentMindPoints) + result = true; + + return result; +} + +// ====================================================================== + +bool CommandChecks::isMob(NetworkId const & targetId) +{ + bool isMob = false; + + Object * targetObj = NetworkIdManager::getObjectById(targetId); + if (targetObj) + { + SharedCreatureObjectTemplate const * sharedTemplate = dynamic_cast(targetObj->getObjectTemplate()); + if (sharedTemplate) + { + isMob = true; + } + } + + return isMob; +} + +//----------------------------------------------------------------------- + +bool CommandChecks::isVehicle(NetworkId const & targetId) +{ + bool isVehicle = false; + + Object * targetObj = NetworkIdManager::getObjectById(targetId); + if (targetObj) + { + SharedObjectTemplate const * sharedTemplate = dynamic_cast(targetObj->getObjectTemplate()); + if (sharedTemplate) + { + isVehicle = GameObjectTypes::isTypeOf(sharedTemplate->getGameObjectType(), SharedObjectTemplate::GOT_vehicle); + } + } + + return isVehicle; +} + +//----------------------------------------------------------------------- + +bool CommandChecks::isMonster(NetworkId const & targetId) +{ + bool isMonster = false; + + Object * targetObj = NetworkIdManager::getObjectById(targetId); + if (targetObj) + { + SharedCreatureObjectTemplate const * sharedTemplate = dynamic_cast(targetObj->getObjectTemplate()); + SharedCreatureObjectTemplate::Niche niche = sharedTemplate->getNiche(); + if (niche == SharedCreatureObjectTemplate::NI_monster + || niche == SharedCreatureObjectTemplate::NI_herbivore + || niche == SharedCreatureObjectTemplate::NI_carnivore + || niche == SharedCreatureObjectTemplate::NI_predator) + { + isMonster = true; + } + } + + return isMonster; +} + +//----------------------------------------------------------------------- + +bool CommandChecks::isNpc(NetworkId const & targetId) +{ + bool isNPC = false; + + Object * targetObj = NetworkIdManager::getObjectById(targetId); + if (targetObj) + { + SharedCreatureObjectTemplate const * sharedTemplate = dynamic_cast(targetObj->getObjectTemplate()); + SharedCreatureObjectTemplate::Niche niche = sharedTemplate->getNiche(); + if (niche == SharedCreatureObjectTemplate::NI_npc) + { + isNPC = true; + } + } + + return isNPC; +} + +//----------------------------------------------------------------------- + +bool CommandChecks::isDroid(NetworkId const & targetId) +{ + bool isDroid = false; + + Object * targetObj = NetworkIdManager::getObjectById(targetId); + if (targetObj) + { + SharedCreatureObjectTemplate const * sharedTemplate = dynamic_cast(targetObj->getObjectTemplate()); + SharedCreatureObjectTemplate::Niche niche = sharedTemplate->getNiche(); + if (niche == SharedCreatureObjectTemplate::NI_droid) + { + isDroid = true; + } + } + + return isDroid; +} + +// ====================================================================== + diff --git a/engine/shared/library/sharedGame/src/shared/command/CommandChecks.h b/engine/shared/library/sharedGame/src/shared/command/CommandChecks.h new file mode 100644 index 00000000..62371023 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/command/CommandChecks.h @@ -0,0 +1,40 @@ +// ====================================================================== +// +// CommandChecks.h +// +// Copyright 2005 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_CommandChecks_H +#define INCLUDED_CommandChecks_H + +// ====================================================================== + + +// ====================================================================== + +class Command; +class NetworkId; + +//---------------------------------------------------------------------- + +class CommandChecks // static class +{ +public: + static void getRangeForCommand(Command const * command, float minWeaponRange, float maxWeaponRange, bool weaponCheckLast, float & min, float & max); + static bool isLocomotionValidForCommand(Command const * command, int8 locomotion, float speed); + static bool isEnoughActionPointsForCommand(Command const * command, int actionPoints); + static bool isEnoughMindPointsForCommand(Command const * command, int mindPoints); + + static bool isMob(NetworkId const & targetId); + static bool isVehicle(NetworkId const & targetId); + static bool isMonster(NetworkId const & targetId); + static bool isNpc(NetworkId const & targetId); + static bool isDroid(NetworkId const & targetId); +}; + +//---------------------------------------------------------------------- + +#endif // INCLUDED_CommandChecks_H + diff --git a/engine/shared/library/sharedGame/src/shared/command/CommandCppFunc.def b/engine/shared/library/sharedGame/src/shared/command/CommandCppFunc.def new file mode 100644 index 00000000..ef57c341 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/command/CommandCppFunc.def @@ -0,0 +1,27 @@ +//====================================================================== +// +// CommandCppFunc.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_CommandCppFunc_H +#define INCLUDED_CommandCppFunc_H + +//====================================================================== + +class NetworkId; +class Command; + +//---------------------------------------------------------------------- + +namespace CommandCppFunc +{ + typedef void (*Type)(Command const &, NetworkId const &, NetworkId const &, Unicode::String const &); +} + +//---------------------------------------------------------------------- + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/command/CommandTable.cpp b/engine/shared/library/sharedGame/src/shared/command/CommandTable.cpp new file mode 100644 index 00000000..78ab0636 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/command/CommandTable.cpp @@ -0,0 +1,279 @@ +// ====================================================================== +// +// CommandTable.cpp +// +// Copyright 2002 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/CommandTable.h" + +#include "sharedFile/Iff.h" +#include "sharedFoundation/Crc.h" +#include "sharedFoundation/NetworkId.h" +#include "sharedGame/Command.h" +#include "sharedUtility/DataTable.h" +#include "UnicodeUtils.h" +#include + +// ====================================================================== + +namespace CommandTableNamespace +{ + // ---------------------------------------------------------------------- + + typedef std::map CommandFunctionMap; + + CommandFunctionMap s_functionMap; + CommandTable::CommandMap s_commandMap; + Command const s_nullCommand; + + // ---------------------------------------------------------------------- + + Command::CppFunc lookupCppFunc(std::string const &funcName); + void loadCommandRow(DataTable const &t, int row); + + // ---------------------------------------------------------------------- +} + +using namespace CommandTableNamespace; + +// ====================================================================== + +void CommandTable::loadCommandTables(std::vector const &commandTableFilenames) +{ + // clear out all commands + { + for (CommandTable::CommandMap::iterator i = s_commandMap.begin(); i != s_commandMap.end(); ++i) + (*i).second = s_nullCommand; + } + + // load the command tables + { + for (std::vector::const_iterator i = commandTableFilenames.begin(); i != commandTableFilenames.end(); ++i) + { + Iff iff; + if (iff.open((*i).c_str(), true)) + { + DataTable commandTable; + commandTable.load(iff); + + for (int row = 0; row < commandTable.getNumRows(); ++row) + loadCommandRow(commandTable, row); + } + } + } +} + +// ---------------------------------------------------------------------- + +void CommandTable::addCppFunction(std::string const &funcName, Command::CppFunc func) +{ + std::map::iterator i = s_functionMap.find(funcName); + if (i == s_functionMap.end()) + s_functionMap[funcName] = func; + else + { + // attempted to add a c function more that once - this is an error if + // the functions don't match + FATAL((*i).second != func, ("Tried to add multiple cpp functions with identical names to the command table.")); + } +} + +// ---------------------------------------------------------------------- + +Command const &CommandTable::getCommand(uint32 commandHash) +{ + std::pair const result = s_commandMap.insert(std::make_pair(commandHash, s_nullCommand)); + return (*result.first).second; +} + +// ---------------------------------------------------------------------- + +CommandTable::CommandMap const &CommandTable::getCommandMap() +{ + return s_commandMap; +} + +// ---------------------------------------------------------------------- + +Command const &CommandTable::getNullCommand() +{ + return s_nullCommand; +} + +// ---------------------------------------------------------------------- + +Command::CppFunc CommandTableNamespace::lookupCppFunc(std::string const &funcName) +{ + std::map::iterator i = s_functionMap.find(funcName); + if (i != s_functionMap.end()) + return (*i).second; + return 0; +} + +// ---------------------------------------------------------------------- + +void CommandTableNamespace::loadCommandRow(DataTable const &t, int row) +{ + std::string const &commandName = Unicode::getTrim(t.getStringValue("commandName", row)); + uint32 const commandHash = Crc::normalizeAndCalculate(commandName.c_str()); + + Command &cmd = s_commandMap[commandHash]; + + if (t.getIntValue("disabled", row)) + { + cmd = s_nullCommand; + return; + } + + cmd.m_commandName = commandName; + cmd.m_commandHash = commandHash; + + { + int const priority = t.getIntValue("defaultPriority", row); + if (priority < 0 || priority >= static_cast(Command::CP_NumberOfPriorities)) + cmd.m_defaultPriority = Command::CP_Default; + else + cmd.m_defaultPriority = static_cast(priority); + } + + cmd.m_scriptHook = Unicode::getTrim(t.getStringValue("scriptHook", row)); + cmd.m_failScriptHook = Unicode::getTrim(t.getStringValue("failScriptHook", row)); + + std::string const cppHook = Unicode::getTrim(t.getStringValue("cppHook", row)); + cmd.m_cppHook = cppHook.empty() ? 0 : lookupCppFunc(cppHook); + + std::string const failCppHook = Unicode::getTrim(t.getStringValue("failCppHook", row)); + cmd.m_failCppHook = failCppHook.empty() ? 0 : lookupCppFunc(failCppHook); + + cmd.m_defaultTime = 0.f;//t.getFloatValue("defaultTime", row); // <-- defaultTime column is deprecated by combat upgrade - 3/16/05 jmatzen + cmd.m_characterAbility = Unicode::getTrim(t.getStringValue("characterAbility", row)); + + { + for (Locomotions::Enumerator i = 0; i != Locomotions::NumberOfLocomotions; ++i) + { + char colName[128]; + IGNORE_RETURN(snprintf(colName, sizeof(colName)-1, "L:%s", Locomotions::getLocomotionName(i))); + colName[sizeof(colName)-1] = '\0'; + int const colNumber = t.findColumnNumber(colName); + if (colNumber >= 0) + cmd.m_locomotionPermissions[i] = t.getIntValue(colNumber, row) ? true : false; + else + cmd.m_locomotionPermissions[i] = true; + } + } + + { + for (States::Enumerator i = 0; i != States::NumberOfStates; ++i) + { + char colName[128]; + IGNORE_RETURN(snprintf(colName, sizeof(colName)-1, "S:%s", States::getStateName(i))); + colName[sizeof(colName)-1] = '\0'; + int const colNumber = t.findColumnNumber(colName); + if (colNumber >= 0) + cmd.m_statePermissions[i] = t.getIntValue(colNumber, row) ? true : false; + else + cmd.m_statePermissions[i] = true; + } + } + + { + for (States::Enumerator i = 0; i != States::NumberOfStates; ++i) + { + char colName[128]; + IGNORE_RETURN(snprintf(colName, sizeof(colName)-1, "R:%s", States::getStateName(i))); + colName[sizeof(colName)-1] = '\0'; + int const colNumber = t.findColumnNumber(colName); + if (colNumber >= 0) + cmd.m_stateRequired[i] = t.getIntValue(colNumber, row) ? true : false; + else + cmd.m_stateRequired[i] = false; + } + } + + cmd.m_tempScript = Unicode::getTrim(t.getStringValue("tempScript", row)); + + { + cmd.m_target = Command::CT_Other; + int column = t.findColumnNumber("target"); + if (column >= 0) + { + int const target = t.getIntValue(column, row); + if (target >= 0 && target < static_cast(Command::CT_NumberOfTargets)) + cmd.m_target = static_cast(target); + } + } + + { + int const targetType = t.getIntValue("targetType", row); + if (targetType < 0 || targetType >= static_cast(Command::CTT_NumberOfTargetTypes)) + cmd.m_targetType = Command::CTT_None; + else + cmd.m_targetType = static_cast(targetType); + } + + cmd.m_callOnTarget = t.getIntValue("callOnTarget", row) ? true : false; + cmd.m_maxRangeToTarget = t.getFloatValue("maxRangeToTarget", row); + cmd.m_maxRangeToTargetSquared = sqr(cmd.m_maxRangeToTarget); + cmd.m_godLevel = t.getIntValue("godLevel", row); + + int queueColNumber = t.findColumnNumber("addToCombatQueue"); + if (queueColNumber >= 0) + cmd.m_addToCombatQueue= t.getIntValue(queueColNumber, row) ? true : false; + + // The following preserve previously set values if the default value is in the new entry + std::string const &stringId = Unicode::getTrim(t.getStringValue("stringId", row)); + if (!stringId.empty()) + cmd.m_stringId = stringId; + int const visibleToClients = t.getIntValue("visible", row); + if (visibleToClients) + cmd.m_visibleToClients = visibleToClients; + uint32 const commandGroup = static_cast(t.getIntValue("commandGroup", row)); + if (commandGroup) + cmd.m_commandGroup = commandGroup; + uint32 const displayGroup = static_cast(t.getIntValue("displayGroup", row)); + if (displayGroup) + cmd.m_displayGroup = displayGroup; + + cmd.m_warmTime = t.getFloatValue( "warmupTime", row ); + cmd.m_execTime = t.getFloatValue( "executeTime", row ); + cmd.m_coolTime = t.getFloatValue( "cooldownTime", row ); + cmd.m_coolTime2 = t.getFloatValue( "cooldownTime2", row ); + + const std::string cooldownGroupName( Unicode::getTrim( t.getStringValue( "cooldownGroup", row ) ) ); + if(cooldownGroupName.empty()) + cmd.m_coolGroup = static_cast(-1); + else + cmd.m_coolGroup = Crc::normalizeAndCalculate( cooldownGroupName.c_str() ); + + const std::string cooldownGroup2Name( Unicode::getTrim( t.getStringValue( "cooldownGroup2", row ) ) ); + if(cooldownGroup2Name.empty()) + cmd.m_coolGroup2 = static_cast(-1); + else + cmd.m_coolGroup2 = Crc::normalizeAndCalculate( cooldownGroup2Name.c_str() ); + + cmd.m_weaponTypesValid = static_cast(t.getIntValue( "validWeapon", row)); + cmd.m_weaponTypesInvalid = static_cast(t.getIntValue( "invalidWeapon", row)); + + cmd.m_toolbarOnly = t.getIntValue("toolbarOnly", row) ? true : false; + cmd.m_fromServerOnly = t.getIntValue("fromServerOnly", row) ? true : false; +} + +// ---------------------------------------------------------------------- + +bool CommandTable::isCommandQueueCommand(uint32 const hash) +{ + bool result = false; + Command const & command = getCommand(hash); + + if (command.m_commandHash && command.m_addToCombatQueue) + { + result = true; + } + + return result; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/command/CommandTable.h b/engine/shared/library/sharedGame/src/shared/command/CommandTable.h new file mode 100644 index 00000000..c4cd12ac --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/command/CommandTable.h @@ -0,0 +1,38 @@ +// ====================================================================== +// +// CommandTable.h +// +// Copyright 2002-2004 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_CommandTable_H +#define INCLUDED_CommandTable_H + +// ====================================================================== + +#include "sharedGame/CommandCppFunc.def" + +// ====================================================================== + +class Command; + +// ====================================================================== + +class CommandTable // static class +{ +public: + typedef stdmap::fwd CommandMap; + + static void loadCommandTables (stdvector::fwd const &commandTableFilenames); + static void addCppFunction (std::string const &funcName, CommandCppFunc::Type func); + static Command const & getCommand (uint32 commandHash); + static CommandMap const & getCommandMap (); + static Command const & getNullCommand (); + static bool isCommandQueueCommand(uint32 hash); +}; + +// ====================================================================== + +#endif // INCLUDED_CommandTable_H + diff --git a/engine/shared/library/sharedGame/src/shared/core/AiDebugString.cpp b/engine/shared/library/sharedGame/src/shared/core/AiDebugString.cpp new file mode 100644 index 00000000..3f0fe7f6 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/AiDebugString.cpp @@ -0,0 +1,613 @@ +// ====================================================================== +// +// AiDebugString.cpp +// Copyright Sony Online Entertainment, Inc. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/AiDebugString.h" + +#ifdef _DEBUG + +#include "sharedFoundation/Crc.h" +#include "sharedFoundation/FormattedString.h" +#include "sharedMath/Circle.h" +#include "sharedMath/Transform.h" +#include "sharedMath/Vector.h" +#include "sharedObject/CachedNetworkId.h" +#include "Unicode.h" +#include "UnicodeUtils.h" + +#include + +// ====================================================================== +// +// AiDebugStringNamespace +// +// ====================================================================== + +namespace AiDebugStringNamespace +{ + char const * const s_resetColorCode = "\\#."; + int s_sequenceId = 0; + bool s_textEnabled = true; +} + +using namespace AiDebugStringNamespace; + +// ====================================================================== +// +// AiDebugString.cpp +// +// ====================================================================== + +// ---------------------------------------------------------------------- +AiDebugString::AiDebugString() + : m_sequenceId(s_sequenceId++) + , m_clearClientFlag(false) + , m_textList(new TextList) + , m_lineList(new LineList) + , m_pathList(new PathList) + , m_circleList(new CircleList) + , m_axisList(new AxisList) + , m_coneList(new ConeList) +{ +} + +// ---------------------------------------------------------------------- +AiDebugString::AiDebugString(std::string const & text) + : m_sequenceId(0) + , m_clearClientFlag(false) + , m_textList(new TextList) + , m_lineList(new LineList) + , m_pathList(new PathList) + , m_circleList(new CircleList) + , m_axisList(new AxisList) + , m_coneList(new ConeList) +{ + Unicode::String const delimiters(Unicode::narrowToWide("`")); + Unicode::UnicodeStringVector result; + + if (Unicode::tokenize(Unicode::narrowToWide(text), result, &delimiters, NULL)) + { + Unicode::UnicodeStringVector::const_iterator iterStringVector = result.begin(); + + m_sequenceId = Unicode::toInt(*iterStringVector); + ++iterStringVector; + m_clearClientFlag = (Unicode::toInt(*iterStringVector) != 0); + ++iterStringVector; + + // Extract the text + + { + int const textCount = Unicode::toInt(*iterStringVector); + //DEBUG_REPORT_LOG(true, ("textCount: %d\n", textCount)); + ++iterStringVector; + + for (int count = 0; (iterStringVector != result.end()) && (count < textCount); ++count) + { + m_textList->push_back(Unicode::wideToNarrow(*iterStringVector)); + ++iterStringVector; + } + } + + // Extract the lines to objects + + { + int const lineCount = Unicode::toInt(*iterStringVector); + //DEBUG_REPORT_LOG(true, ("lineCount: %d\n", lineCount)); + ++iterStringVector; + + for (int count = 0; (iterStringVector != result.end()) && (count < lineCount); ++count) + { + NetworkId const networkId(Unicode::wideToNarrow(*iterStringVector)); + ++iterStringVector; + + Vector position; + position.x = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + + position.y = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + + position.z = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + + PackedRgb color; + color.r = static_cast(Unicode::toInt(*iterStringVector)); + ++iterStringVector; + + color.g = static_cast(Unicode::toInt(*iterStringVector)); + ++iterStringVector; + + color.b = static_cast(Unicode::toInt(*iterStringVector)); + ++iterStringVector; + + m_lineList->push_back(std::make_pair(CachedNetworkId(networkId), std::make_pair(position, PackedRgb(color.r, color.g, color.b)))); + } + } + + // Extract the paths + + { + int const pathCount = Unicode::toInt(*iterStringVector); + //DEBUG_REPORT_LOG(true, ("pathCount: %d\n", pathCount)); + ++iterStringVector; + + for (int count = 0; (iterStringVector != result.end()) && (count < pathCount); ++count) + { + bool const cyclic = Unicode::toInt(*iterStringVector) ? true : false; + //DEBUG_REPORT_LOG(true, ("cyclic: %s\n", cyclic ? "yes" : "no")); + ++iterStringVector; + + int const pathSize = Unicode::toInt(*iterStringVector); + //DEBUG_REPORT_LOG(true, ("pathSize: %d\n", pathSize)); + ++iterStringVector; + TransformList transformList; + + for (int pathIndex = 0; pathIndex < pathSize; ++pathIndex) + { + float const x = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + float const y = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + float const z = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + + Transform transform; + transform.setPosition_p(x, y, z); + transformList.push_back(transform); + } + + m_pathList->push_back(std::make_pair(transformList, cyclic)); + } + } + + // Extract the circles + + { + int const circleCount = Unicode::toInt(*iterStringVector); + ++iterStringVector; + + //DEBUG_REPORT_LOG(true, ("circleCount: %d\n", circleCount)); + + for (int count = 0; (iterStringVector != result.end()) && (count < circleCount); ++count) + { + NetworkId const networkId(Unicode::wideToNarrow(*iterStringVector)); + ++iterStringVector; + + float const x = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + + float const y = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + + float const z = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + + float const radius = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + + PackedRgb color; + color.r = static_cast(Unicode::toInt(*iterStringVector)); + ++iterStringVector; + + color.g = static_cast(Unicode::toInt(*iterStringVector)); + ++iterStringVector; + + color.b = static_cast(Unicode::toInt(*iterStringVector)); + ++iterStringVector; + + m_circleList->push_back(std::make_pair(CachedNetworkId(networkId), std::make_pair(Circle(Vector(x, y, z), radius), color))); + } + } + + // Extract the axes + + { + int const axisCount = Unicode::toInt(*iterStringVector); + ++iterStringVector; + + for (int count = 0; (iterStringVector != result.end()) && (count < axisCount); ++count) + { + float const ix = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + float const iy = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + float const iz = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + + float const jx = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + float const jy = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + float const jz = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + + float const kx = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + float const ky = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + float const kz = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + + float const x = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + float const y = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + float const z = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + + Transform transform; + Vector i(ix, iy, iz); + Vector j(jx, jy, jz); + Vector k(kx, ky, kz); + transform.setLocalFrameIJK_p(i, j, k); + transform.setPosition_p(x, y, z); + + float const axisLength = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + + m_axisList->push_back(std::make_pair(transform, axisLength)); + } + } + + // Extract the cones + + { + int const coneCount = Unicode::toInt(*iterStringVector); + ++iterStringVector; + + for (int count = 0; (iterStringVector != result.end()) && (count < coneCount); ++count) + { + float const length = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + + float const angle = Unicode::toFloat(*iterStringVector); + ++iterStringVector; + + PackedRgb color; + color.r = static_cast(Unicode::toInt(*iterStringVector)); + ++iterStringVector; + + color.g = static_cast(Unicode::toInt(*iterStringVector)); + ++iterStringVector; + + color.b = static_cast(Unicode::toInt(*iterStringVector)); + ++iterStringVector; + + m_coneList->push_back(std::make_pair(length, std::make_pair(angle, color))); + } + } + } +} + +// ---------------------------------------------------------------------- +AiDebugString::AiDebugString(AiDebugString const & rhs) + : m_sequenceId(rhs.m_sequenceId) + , m_clearClientFlag(rhs.m_clearClientFlag) + , m_textList(new TextList(*rhs.m_textList)) + , m_lineList(new LineList(*rhs.m_lineList)) + , m_pathList(new PathList(*rhs.m_pathList)) + , m_circleList(new CircleList(*rhs.m_circleList)) + , m_axisList(new AxisList(*rhs.m_axisList)) + , m_coneList(new ConeList(*rhs.m_coneList)) +{ +} + +// ---------------------------------------------------------------------- +AiDebugString::~AiDebugString() +{ + delete m_textList; + delete m_lineList; + delete m_pathList; + delete m_circleList; + delete m_axisList; + delete m_coneList; +} + +// ---------------------------------------------------------------------- +void AiDebugString::addText(std::string const & text, PackedRgb const & color) +{ + std::string coloredText; + coloredText += getColorCode(color); + coloredText += text; + coloredText += getResetColorCode(); + + m_textList->push_back(coloredText); +} + +// ---------------------------------------------------------------------- +void AiDebugString::addLineToObject(NetworkId const & target, PackedRgb const & color) +{ + m_lineList->push_back(std::make_pair(CachedNetworkId(target), std::make_pair(Vector::zero, color))); +} + +// ---------------------------------------------------------------------- +void AiDebugString::addLineToObjectOffset(NetworkId const & target, Vector const & position_o, PackedRgb const & color) +{ + m_lineList->push_back(std::make_pair(CachedNetworkId(target), std::make_pair(position_o, color))); +} + +// ---------------------------------------------------------------------- +void AiDebugString::addLineToPosition(Vector const & position_w, PackedRgb const & color) +{ + m_lineList->push_back(std::make_pair(CachedNetworkId::cms_cachedInvalid, std::make_pair(position_w, color))); +} + +// ---------------------------------------------------------------------- +void AiDebugString::addPath(TransformList const & transformList, bool const cyclic) +{ + m_pathList->push_back(std::make_pair(transformList, cyclic)); +} + +// ---------------------------------------------------------------------- +std::string AiDebugString::toString() const +{ + std::string text; + + IGNORE_RETURN(AiDebugString::toString(text)); + + return text; +} + +// ---------------------------------------------------------------------- +uint32 AiDebugString::toString(std::string & text) const +{ + text.clear(); + + FormattedString<4096> formattedString; + + //DEBUG_REPORT_LOG(true, ("m_sequenceId: %d\n", m_sequenceId)); + //DEBUG_REPORT_LOG(true, ("m_clearClientFlag: %s\n", m_clearClientFlag ? "yes" : "no")); + + text += formattedString.sprintf("%d`", m_sequenceId); + text += m_clearClientFlag ? "1`" : "0`"; + + if (s_textEnabled) + { + // Add the text + + text += formattedString.sprintf("%u`", m_textList->size()); + //DEBUG_REPORT_LOG(true, ("m_textList->size(): %u\n", m_textList->size())); + + TextList::const_iterator iterTextList = m_textList->begin(); + + for (; iterTextList != m_textList->end(); ++iterTextList) + { + text += *iterTextList; + text += "`"; + } + } + else + { + // No text + + text += "0`"; + } + + // Add the lines + + text += formattedString.sprintf("%u`", m_lineList->size()); + //DEBUG_REPORT_LOG(true, ("m_lineList->size(): %u\n", m_lineList->size())); + + LineList::const_iterator iterLineList = m_lineList->begin(); + + for (; iterLineList != m_lineList->end(); ++iterLineList) + { + NetworkId const & target = iterLineList->first; + Vector const & position = iterLineList->second.first; + PackedRgb const & color = iterLineList->second.second; + + text += formattedString.sprintf("%s`%.1f`%.1f`%.1f`%d`%d`%d`", target.getValueString().c_str(), position.x, position.y, position.z, color.r, color.g, color.b); + } + + // Add the paths + + text += formattedString.sprintf("%u`", m_pathList->size()); + //DEBUG_REPORT_LOG(true, ("m_pathList->size(): %u\n", m_pathList->size())); + + PathList::const_iterator iterPathList = m_pathList->begin(); + + for (; iterPathList != m_pathList->end(); ++iterPathList) + { + TransformList const & path = iterPathList->first; + bool const cyclic = iterPathList->second; + TransformList::const_iterator iterPath = path.begin(); + //DEBUG_REPORT_LOG(true, ("cyclic: %s\n", cyclic ? "yes" : "no")); + //DEBUG_REPORT_LOG(true, ("path.size(): %u\n", path.size())); + text += formattedString.sprintf("%d`%u`", cyclic ? 1 : 0, path.size()); + + for (; iterPath != path.end(); ++iterPath) + { + Transform const & transform = *iterPath; + text += formattedString.sprintf("%.1f`%.1f`%.1f`", transform.getPosition_p().x, transform.getPosition_p().y, transform.getPosition_p().z); + } + } + + // Add the circles + + text += formattedString.sprintf("%u`", m_circleList->size()); + //DEBUG_REPORT_LOG(true, ("m_circleList->size(): %u\n", m_circleList->size())); + + CircleList::const_iterator iterCircleList = m_circleList->begin(); + + for (; iterCircleList != m_circleList->end(); ++iterCircleList) + { + NetworkId const & target = iterCircleList->first; + Circle const & circle = iterCircleList->second.first; + PackedRgb const & color = iterCircleList->second.second; + + text += formattedString.sprintf("%s`%.1f`%.1f`%.1f`%.1f`%d`%d`%d`", target.getValueString().c_str(), circle.getCenter().x, circle.getCenter().y, circle.getCenter().z, circle.getRadius(), color.r, color.g, color.b); + } + + // Add the axes + + text += formattedString.sprintf("%u`", m_axisList->size()); + + AxisList::const_iterator iterAxisList = m_axisList->begin(); + + for (; iterAxisList != m_axisList->end(); ++iterAxisList) + { + Transform const & transform = iterAxisList->first; + float const axisLength = iterAxisList->second; + Vector const i(transform.getLocalFrameI_p()); + Vector const j(transform.getLocalFrameJ_p()); + Vector const k(transform.getLocalFrameK_p()); + Vector const position(transform.getPosition_p()); + + text += formattedString.sprintf("%.3f`%.3f`%.3f`%.3f`%.3f`%.3f`%.3f`%.3f`%.3f`%.1f`%.1f`%.1f`%.2f`", i.x, i.y, i.z, j.x, j.y, j.z, k.x, k.y, k.z, position.x, position.y, position.z, axisLength); + } + + // Add the cones + + text += formattedString.sprintf("%u`", m_coneList->size()); + + ConeList::const_iterator iterConeList = m_coneList->begin(); + + for (; iterConeList != m_coneList->end(); ++iterConeList) + { + float const length = iterConeList->first; + float const angle = iterConeList->second.first; + PackedRgb const & color = iterConeList->second.second; + + text += formattedString.sprintf("%.2f`%.2f`%d`%d`%d`", length, angle, color.r, color.g, color.b); + } + + // Skip the sequenceId during the Crc calculation + + uint32 crc = 0; + std::string::const_iterator iterString = text.begin(); + + for (; iterString != text.end(); ++iterString) + { + if (*iterString == '`') + { + crc = Crc::calculate(&*iterString); + break; + } + } + + return crc; +} + +// ---------------------------------------------------------------------- +AiDebugString::TextList const & AiDebugString::getTextList() const +{ + return *m_textList; +} + +// ---------------------------------------------------------------------- +AiDebugString::LineList const & AiDebugString::getLineList() const +{ + return *m_lineList; +} + +// ---------------------------------------------------------------------- +AiDebugString::PathList const & AiDebugString::getPathList() const +{ + return *m_pathList; +} + +// ---------------------------------------------------------------------- +void AiDebugString::enableClearClientFlag() +{ + m_clearClientFlag = true; +} + +// ---------------------------------------------------------------------- +bool AiDebugString::isClearClientFlagEnabled() const +{ + return m_clearClientFlag; +} + +// ---------------------------------------------------------------------- +void AiDebugString::addCircle(Vector const & center_w, float const radius, PackedRgb const & color) +{ + // World-space circle + + if (radius > 0.0f) + { + m_circleList->push_back(std::make_pair(CachedNetworkId::cms_cachedInvalid, std::make_pair(Circle(center_w, radius), color))); + } + else + { + DEBUG_REPORT_LOG(true, ("AiDebugString::addCircle() Invalid radius(%f) specified. Must be > 0\n", radius)); + } +} + +// ---------------------------------------------------------------------- +void AiDebugString::addCircleAtObjectOffset(NetworkId const & target, Vector const & position_o, float const radius, PackedRgb const & color) +{ + // Object-space circle relative to the target + + if (radius > 0.0f) + { + m_circleList->push_back(std::make_pair(target, std::make_pair(Circle(position_o, radius), color))); + } + else + { + DEBUG_REPORT_LOG(true, ("AiDebugString::addCircleAtObjectOffset() Invalid radius(%f) specified. Must be > 0\n", radius)); + } +} + +// ---------------------------------------------------------------------- +AiDebugString::CircleList const & AiDebugString::getCircleList() const +{ + return *m_circleList; +} + +// ---------------------------------------------------------------------------- +void AiDebugString::addAxis(Transform const & transform, float const axisLength) +{ + m_axisList->push_back(std::make_pair(transform, axisLength)); +} + +// ---------------------------------------------------------------------------- +AiDebugString::AxisList const & AiDebugString::getAxisList() const +{ + return *m_axisList; +} + +// ---------------------------------------------------------------------------- +void AiDebugString::addCone(float const length, float const angle, PackedRgb const & color) +{ + m_coneList->push_back(std::make_pair(length, std::make_pair(angle, color))); +} + +// ---------------------------------------------------------------------------- +AiDebugString::ConeList const & AiDebugString::getConeList() const +{ + return *m_coneList; +} + +// ---------------------------------------------------------------------------- +std::string const AiDebugString::getColorCode(PackedRgb const & packedRgb) +{ + unsigned const code = packedRgb.asUint32(); + unsigned const rgb = code & 0xFFFFFF; + + return FormattedString<32>().sprintf("\\#%06x", rgb); +} + +// ---------------------------------------------------------------------------- +char const * const AiDebugString::getResetColorCode() +{ + return s_resetColorCode; +} + +// ---------------------------------------------------------------------------- +void AiDebugString::setTextEnabled(bool const enabled) +{ + s_textEnabled = enabled; +} + +bool AiDebugString::isTextEnabled() +{ + return s_textEnabled; +} + +// ====================================================================== + +#endif // _DEBUG diff --git a/engine/shared/library/sharedGame/src/shared/core/AiDebugString.h b/engine/shared/library/sharedGame/src/shared/core/AiDebugString.h new file mode 100644 index 00000000..a45d3649 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/AiDebugString.h @@ -0,0 +1,107 @@ +// ====================================================================== +// +// AiDebugString.h +// Copyright Sony Online Entertainment, Inc. +// +// ====================================================================== + +#ifndef INCLUDED_AiDebugString_H +#define INCLUDED_AiDebugString_H + +#ifdef _DEBUG + +#include "sharedMath/PackedRgb.h" + +class CachedNetworkId; +class Circle; +class NetworkId; +class Transform; +class Vector; + +// ---------------------------------------------------------------------- +class AiDebugString +{ +public: + + typedef stdvector::fwd TransformList; + typedef stdvector::fwd TextList; + typedef stdvector > >::fwd LineList; + typedef stdvector >::fwd PathList; + typedef stdvector > >::fwd CircleList; + typedef stdvector >::fwd AxisList; + typedef stdvector > >::fwd ConeList; + + // Use to custom embed multiple colors in text + + static std::string const getColorCode(PackedRgb const & packedRgb); + static char const * const getResetColorCode(); + + static void setTextEnabled(bool const enabled); + static bool isTextEnabled(); + +public: + + AiDebugString(); + explicit AiDebugString(std::string const & text); + explicit AiDebugString(AiDebugString const & rhs); + ~AiDebugString(); + + uint32 toString(std::string & text) const; + std::string toString() const; + + void enableClearClientFlag(); + bool isClearClientFlagEnabled() const; + + // Text + + void addText(std::string const & text, PackedRgb const & color = PackedRgb::solidWhite); + TextList const & getTextList() const; + + // Lines + + void addLineToObject(NetworkId const & target, PackedRgb const & color = PackedRgb::solidWhite); + void addLineToObjectOffset(NetworkId const & target, Vector const & position_o, PackedRgb const & color = PackedRgb::solidWhite); + void addLineToPosition(Vector const & position_w, PackedRgb const & color = PackedRgb::solidWhite); + LineList const & getLineList() const; + + // Paths + + void addPath(TransformList const & transformList, bool const cyclic); + PathList const & getPathList() const; + + // Circles + + void addCircle(Vector const & center_w, float const radius, PackedRgb const & color = PackedRgb::solidWhite); + void addCircleAtObjectOffset(NetworkId const & target, Vector const & position_o, float const radius, PackedRgb const & color = PackedRgb::solidWhite); + CircleList const & getCircleList() const; + + // Axes + + void addAxis(Transform const & transform, float const axisLength); + AxisList const & getAxisList() const; + + // Cone (in the direction of the owner z-axis) + + void addCone(float const length, float const coneAngle, PackedRgb const & color = PackedRgb::solidWhite); + ConeList const & getConeList() const; + +private: + + int m_sequenceId; + bool m_clearClientFlag; + TextList * const m_textList; + LineList * const m_lineList; + PathList * const m_pathList; + CircleList * const m_circleList; + AxisList * const m_axisList; + ConeList * const m_coneList; + + // Disabled + + AiDebugString const & operator =(AiDebugString const &); +}; + +// ====================================================================== + +#endif // _DEBUG +#endif // INCLUDED_AiDebugString_H diff --git a/engine/shared/library/sharedGame/src/shared/core/AssetCustomizationManager.cpp b/engine/shared/library/sharedGame/src/shared/core/AssetCustomizationManager.cpp new file mode 100644 index 00000000..34acdca1 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/AssetCustomizationManager.cpp @@ -0,0 +1,690 @@ +// ====================================================================== +// +// AssetCustomizationManager.cpp +// Copyright 2003 Sony Online Entertainment, Inc. +// All Rights Reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/AssetCustomizationManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/Iff.h" +#include "sharedFoundation/CrcString.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/TemporaryCrcString.h" +#include "sharedMath/PaletteArgb.h" +#include "sharedMath/PaletteArgbList.h" +#include "sharedObject/BasicRangedIntCustomizationVariable.h" +#include "sharedObject/CustomizationData.h" +#include "sharedObject/PaletteColorCustomizationVariable.h" + +#include + +// ====================================================================== + +#if defined(PLATFORM_WIN32) + +#define PACKING_END_STRUCT + +#elif defined(PLATFORM_LINUX) + +#define PACKING_END_STRUCT __attribute__ ((packed)) + +#else + +#error figure out how to handle structure packing for this platform. + +#endif + +// ====================================================================== + +namespace AssetCustomizationManagerNamespace +{ + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +#ifdef PLATFORM_WIN32 +#pragma pack(push, 1) +#endif + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + struct IntRange + { + int32 minRangeInclusive; + int32 maxRangeExclusive; + } PACKING_END_STRUCT; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + struct VariableUsage + { + uint16 variableId; + uint16 rangeId; + uint16 defaultId; + } PACKING_END_STRUCT; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + struct UsageIndexEntry + { + uint16 assetId; //lint -esym(754, UsageIndexEntry::assetId) // error 754: (Info -- local structure member not referenced) // Wrong, accessed indirectly. + uint16 listStartIndex; + uint8 count; + } PACKING_END_STRUCT; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + struct LinkIndexEntry + { + uint16 assetId; //lint -esym(754, LinkIndexEntry::assetId) // error 754: (Info -- local structure member not referenced) // Wrong, accessed indirectly. + uint16 listStartIndex; + uint8 count; + } PACKING_END_STRUCT; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + struct CrcLookupEntry + { + uint32 assetNameCrc; //lint -esym(754, CrcLookupEntry::assetNameCrc) // error 754: (Info -- local structure member not referenced) // Wrong, accessed indirectly. + uint16 assetId; + } PACKING_END_STRUCT; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +#ifdef PLATFORM_WIN32 +#pragma pack(pop) +#endif + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + void remove(); + + void load(Iff &iff); + void load_0000(Iff &iff); + + char const *getNameFromOffset(int offset); + char const *getPaletteNameFromPaletteId(int paletteId); + char const *getVariableNameFromVariableId(int variableId); + int getDefaultValueFromDefaultId(int defaultId); + void getIntRangeFromIntRangeId(int intRangeId, IntRange &intRange); + void getRangeTypeInfoFromRangeId(int rangeId, bool &isPalette, int &idForRealType); + VariableUsage const *getVariableUsageFromId(int variableUsageId); + + UsageIndexEntry const *lookupVariableUsageIndexEntry(int assetId); + LinkIndexEntry const *lookupAssetLinkIndexEntry(int assetId); + int lookupAssetId(CrcString const &assetName); + + void addVariablesForAssetAndLinks(int assetId, CustomizationData &customizationData, bool skipSharedOwnerVariables, int &addedVariableCount); + + int compare_uint16(void const *lhs, void const *rhs); + int compare_uint32(void const *lhs, void const *rhs); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + Tag const TAG_ACST = TAG(A,C,S,T); + Tag const TAG_CIDX = TAG(C,I,D,X); + Tag const TAG_DEFV = TAG(D,E,F,V); + Tag const TAG_IRNG = TAG(I,R,N,G); + Tag const TAG_LIDX = TAG(L,I,D,X); + Tag const TAG_LLST = TAG(L,L,S,T); + Tag const TAG_NAME = TAG(N,A,M,E); + Tag const TAG_PNOF = TAG(P,N,O,F); + Tag const TAG_RTYP = TAG(R,T,Y,P); + Tag const TAG_UCMP = TAG(U,C,M,P); + Tag const TAG_UIDX = TAG(U,I,D,X); + Tag const TAG_ULST = TAG(U,L,S,T); + Tag const TAG_VNOF = TAG(V,N,O,F); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + bool s_installed; + + char *s_nameDataBlock; + int s_nameDataBlockSize; + + uint16 *s_paletteIdNameOffsetMap; + int s_maxValidPaletteId; + + uint16 *s_variableIdNameOffsetMap; + int s_maxValidVariableId; + + int32 *s_defaultValueMap; + int s_maxValidDefaultId; + + IntRange *s_intRangeMap; + int s_maxValidIntRangeId; // int range IDs map only into this int range table and are not the same thing as range IDs. + + uint16 *s_rangeTypeMap; + int s_maxValidRangeId; // range IDs map into this range type map and include both palettized ranges and int-range ranges. + + VariableUsage *s_variableUsageMap; + int s_maxValidVariableUsageId; + + uint16 *s_variableUsageList; + int s_variableUsageListEntryCount; + + UsageIndexEntry *s_usageIndex; + int s_usageIndexEntryCount; + + uint16 *s_linkList; + int s_linkListEntryCount; + + LinkIndexEntry *s_linkIndex; + int s_linkIndexEntryCount; + + CrcLookupEntry *s_crcLookupTable; + int s_crcLookupEntryCount; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +} + +using namespace AssetCustomizationManagerNamespace; + +// ====================================================================== +// namespace AssetCustomizationManagerNamespace +// ====================================================================== + +void AssetCustomizationManagerNamespace::remove() +{ + DEBUG_FATAL(!s_installed, ("AssetCustomizationManager not installed.")); + s_installed = false; + + delete [] s_nameDataBlock; + s_nameDataBlock = NULL; + s_nameDataBlockSize = 0; + + delete [] s_paletteIdNameOffsetMap; + s_paletteIdNameOffsetMap = NULL; + s_maxValidPaletteId = 0; + + delete [] s_variableIdNameOffsetMap; + s_variableIdNameOffsetMap = NULL; + s_maxValidVariableId = 0; + + delete [] s_defaultValueMap; + s_defaultValueMap = NULL; + s_maxValidDefaultId = 0; + + delete [] s_intRangeMap; + s_intRangeMap = NULL; + s_maxValidIntRangeId = 0; + + delete [] s_rangeTypeMap; + s_rangeTypeMap = NULL; + s_maxValidRangeId = 0; + + delete [] s_variableUsageMap; + s_variableUsageMap = NULL; + s_maxValidVariableUsageId = 0; + + delete [] s_variableUsageList; + s_variableUsageList = 0; + s_variableUsageListEntryCount = 0; + + delete [] s_usageIndex; + s_usageIndex = NULL; + s_usageIndexEntryCount = 0; + + delete [] s_linkList; + s_linkList = NULL; + s_linkListEntryCount = 0; + + delete [] s_linkIndex; + s_linkIndex = NULL; + s_linkIndexEntryCount = 0; + + delete [] s_crcLookupTable; + s_crcLookupTable = NULL; + s_crcLookupEntryCount = 0; +} + +// ---------------------------------------------------------------------- + +void AssetCustomizationManagerNamespace::load(Iff &iff) +{ + iff.enterForm(TAG_ACST); + + Tag const version = iff.getCurrentName(); + switch (version) + { + case TAG_0000: + load_0000(iff); + break; + + default: + { + char buffer[5]; + ConvertTagToString(version, buffer); + FATAL(true, ("unsupported AssetCustomizationManager file version [%s].", buffer)); + } + } + + iff.exitForm(TAG_ACST); +} + +// ---------------------------------------------------------------------- + +void AssetCustomizationManagerNamespace::load_0000(Iff &iff) +{ + iff.enterForm(TAG_0000); + + //-- Read name data as one big block. + iff.enterChunk(TAG_NAME); + + s_nameDataBlockSize = iff.getChunkLengthLeft(); + s_nameDataBlock = new char[static_cast(s_nameDataBlockSize)]; + iff.read_char(s_nameDataBlockSize, s_nameDataBlock); + + iff.exitChunk(TAG_NAME); + + //-- Read palette id to palette name offset block. Palette IDs start at 1. + iff.enterChunk(TAG_PNOF); + + s_maxValidPaletteId = iff.getChunkLengthLeft(sizeof(uint16)); + s_paletteIdNameOffsetMap = new uint16[static_cast(s_maxValidPaletteId)]; + iff.read_uint16(s_maxValidPaletteId, s_paletteIdNameOffsetMap); + + iff.exitChunk(TAG_PNOF); + + //-- Read variable id to variable name offset block. Variable IDs start at 1. + iff.enterChunk(TAG_VNOF); + + s_maxValidVariableId = iff.getChunkLengthLeft(sizeof(uint16)); + s_variableIdNameOffsetMap = new uint16[static_cast(s_maxValidVariableId)]; + iff.read_uint16(s_maxValidVariableId, s_variableIdNameOffsetMap); + + iff.exitChunk(TAG_VNOF); + + //-- Read default value id. + iff.enterChunk(TAG_DEFV); + + s_maxValidDefaultId = iff.getChunkLengthLeft(sizeof(int32)); + s_defaultValueMap = new int32[static_cast(s_maxValidDefaultId)]; + iff.read_int32(s_maxValidDefaultId, s_defaultValueMap); + + iff.exitChunk(TAG_DEFV); + + //-- Read the integer range table. + iff.enterChunk(TAG_IRNG); + + s_maxValidIntRangeId = iff.getChunkLengthLeft(sizeof(IntRange)); + s_intRangeMap = new IntRange[static_cast(s_maxValidIntRangeId)]; + iff.read_int32(2 * s_maxValidIntRangeId, reinterpret_cast(s_intRangeMap)); //lint !e740 // unusual pointer cast. // Yes; its fine and is worth the bug savings over handling directly as array of int32. + + iff.exitChunk(TAG_IRNG); + + //-- Read the range type table. + iff.enterChunk(TAG_RTYP); + + s_maxValidRangeId = iff.getChunkLengthLeft(sizeof(uint16)); + s_rangeTypeMap = new uint16[static_cast(s_maxValidRangeId)]; + iff.read_uint16(s_maxValidRangeId, s_rangeTypeMap); + + iff.exitChunk(TAG_RTYP); + + //-- Read the variable usage composition table. + iff.enterChunk(TAG_UCMP); + + s_maxValidVariableUsageId = iff.getChunkLengthLeft(sizeof(VariableUsage)); + s_variableUsageMap = new VariableUsage[static_cast(s_maxValidVariableUsageId)]; + iff.read_uint16(3 * s_maxValidVariableUsageId, reinterpret_cast(s_variableUsageMap)); + + iff.exitChunk(TAG_UCMP); + + //-- Read variable usage list. + iff.enterChunk(TAG_ULST); + + s_variableUsageListEntryCount = iff.getChunkLengthLeft(sizeof(uint16)); + s_variableUsageList = new uint16[static_cast(s_variableUsageListEntryCount)]; + iff.read_uint16(s_variableUsageListEntryCount, s_variableUsageList); + + iff.exitChunk(TAG_ULST); + + //-- Read variable usage index. + iff.enterChunk(TAG_UIDX); + + s_usageIndexEntryCount = iff.getChunkLengthLeft(sizeof(UsageIndexEntry)); + s_usageIndex = new UsageIndexEntry[static_cast(s_usageIndexEntryCount)]; + iff.read_uint8(isizeof(UsageIndexEntry) * s_usageIndexEntryCount, reinterpret_cast(s_usageIndex)); + + iff.exitChunk(TAG_UIDX); + + //-- Read asset linkage list. + iff.enterChunk(TAG_LLST); + + s_linkListEntryCount = iff.getChunkLengthLeft(sizeof(uint16)); + s_linkList = new uint16[static_cast(s_linkListEntryCount)]; + iff.read_uint16(s_linkListEntryCount, s_linkList); + + iff.exitChunk(TAG_LLST); + + //-- Read asset linkage index. + iff.enterChunk(TAG_LIDX); + + s_linkIndexEntryCount = iff.getChunkLengthLeft(sizeof(LinkIndexEntry)); + s_linkIndex = new LinkIndexEntry[static_cast(s_linkIndexEntryCount)]; + iff.read_uint8(isizeof(LinkIndexEntry) * s_linkIndexEntryCount, reinterpret_cast(s_linkIndex)); + + iff.exitChunk(TAG_LIDX); + + //-- Read crc name -> asset id lookup table. + iff.enterChunk(TAG_CIDX); + + s_crcLookupEntryCount = iff.getChunkLengthLeft(sizeof(CrcLookupEntry)); + s_crcLookupTable = new CrcLookupEntry[static_cast(s_crcLookupEntryCount)]; + iff.read_uint8(isizeof(CrcLookupEntry) * s_crcLookupEntryCount, reinterpret_cast(s_crcLookupTable)); + + iff.exitChunk(TAG_CIDX); + + iff.exitForm(TAG_0000); +} + +// ---------------------------------------------------------------------- + +char const *AssetCustomizationManagerNamespace::getNameFromOffset(int offset) +{ + VALIDATE_RANGE_INCLUSIVE_EXCLUSIVE(0, offset, s_nameDataBlockSize); + return s_nameDataBlock + offset; +} + +// ---------------------------------------------------------------------- + +char const *AssetCustomizationManagerNamespace::getPaletteNameFromPaletteId(int paletteId) +{ + VALIDATE_RANGE_INCLUSIVE_INCLUSIVE(1, paletteId, s_maxValidPaletteId); + + //-- Get name offset from palette id. Palette ids start at 1 and must be shifted down one + // index to lookup offset data. + int const nameOffset = static_cast(s_paletteIdNameOffsetMap[paletteId - 1]); + return getNameFromOffset(nameOffset); +} + +// ---------------------------------------------------------------------- + +char const *AssetCustomizationManagerNamespace::getVariableNameFromVariableId(int variableId) +{ + VALIDATE_RANGE_INCLUSIVE_INCLUSIVE(1, variableId, s_maxValidVariableId); + + //-- Get name offset from variable id. Variable ids start at 1 and must be shifted down one + // index to lookup offset data. + int const nameOffset = static_cast(s_variableIdNameOffsetMap[variableId - 1]); + return getNameFromOffset(nameOffset); +} + +// ---------------------------------------------------------------------- + +int AssetCustomizationManagerNamespace::getDefaultValueFromDefaultId(int defaultId) +{ + VALIDATE_RANGE_INCLUSIVE_INCLUSIVE(1, defaultId, s_maxValidDefaultId); + + //-- Get default value from default id. Default ids start at 1 and must be shifted down one + // index to lookup value data. + return static_cast(s_defaultValueMap[defaultId - 1]); +} + +// ---------------------------------------------------------------------- + +void AssetCustomizationManagerNamespace::getIntRangeFromIntRangeId(int intRangeId, IntRange &intRange) +{ + VALIDATE_RANGE_INCLUSIVE_INCLUSIVE(1, intRangeId, s_maxValidIntRangeId); + + //-- Get int range from id. Int range ids start at 1 and need to be shifted down one + // index to lookup int range data. + intRange = s_intRangeMap[intRangeId - 1]; +} + +// ---------------------------------------------------------------------- + +void AssetCustomizationManagerNamespace::getRangeTypeInfoFromRangeId(int rangeId, bool &isPalette, int &idForRealType) +{ + VALIDATE_RANGE_INCLUSIVE_INCLUSIVE(1, rangeId, s_maxValidRangeId); + + //-- Get range type from range id. Range ids start at 1 and need to be shifted down one + // index to lookup int range type info. + uint16 const rangeType = s_rangeTypeMap[rangeId - 1]; + isPalette = ((rangeType & 0x8000) != 0); + idForRealType = (rangeType & 0x7fff); +} + +// ---------------------------------------------------------------------- + +VariableUsage const *AssetCustomizationManagerNamespace::getVariableUsageFromId(int variableUsageId) +{ + VALIDATE_RANGE_INCLUSIVE_INCLUSIVE(1, variableUsageId, s_maxValidVariableUsageId); + + //-- Get variable usage from id. Variable usage ids start at 1 and need to be shifted down one + // when accessing table data. + return s_variableUsageMap + (variableUsageId - 1); +} + +// ---------------------------------------------------------------------- + +AssetCustomizationManagerNamespace::UsageIndexEntry const *AssetCustomizationManagerNamespace::lookupVariableUsageIndexEntry(int assetId) +{ + VALIDATE_RANGE_INCLUSIVE_INCLUSIVE(1, assetId, s_crcLookupEntryCount); + + //-- Do a binary search on the UsageIndexEntry list. + uint16 const key = static_cast(assetId); + return static_cast(bsearch(&key, s_usageIndex, static_cast(s_usageIndexEntryCount), sizeof(UsageIndexEntry), compare_uint16)); +} + +// ---------------------------------------------------------------------- + +AssetCustomizationManagerNamespace::LinkIndexEntry const *AssetCustomizationManagerNamespace::lookupAssetLinkIndexEntry(int assetId) +{ + VALIDATE_RANGE_INCLUSIVE_INCLUSIVE(1, assetId, s_crcLookupEntryCount); + + //-- Do a binary search on the UsageIndexEntry list. + uint16 const key = static_cast(assetId); + return static_cast(bsearch(&key, s_linkIndex, static_cast(s_linkIndexEntryCount), sizeof(LinkIndexEntry), compare_uint16)); +} + +// ---------------------------------------------------------------------- + +int AssetCustomizationManagerNamespace::lookupAssetId(CrcString const &assetName) +{ + uint32 const key = assetName.getCrc(); + CrcLookupEntry const *entry = static_cast(bsearch(&key, s_crcLookupTable, static_cast(s_crcLookupEntryCount), sizeof(CrcLookupEntry), compare_uint32)); + + return (entry != NULL) ? entry->assetId : 0; +} + +// ---------------------------------------------------------------------- + +int AssetCustomizationManagerNamespace::compare_uint16(void const *lhs, void const *rhs) +{ + NOT_NULL(lhs); + NOT_NULL(rhs); + + // return: + // negative if rhs > lhs, + // 0 if rhs == lhs, + // positive if rhs < lhs + return static_cast(*static_cast(lhs)) - static_cast(*static_cast(rhs)); +} + +// ---------------------------------------------------------------------- + +int AssetCustomizationManagerNamespace::compare_uint32(void const *lhs, void const *rhs) +{ + NOT_NULL(lhs); + NOT_NULL(rhs); + + // return: + // negative if rhs > lhs, + // 0 if rhs == lhs, + // positive if rhs < lhs + // + // Don't want to do this: I don't want to worry about how overflow influences this. + // return static_cast(*static_cast(lhs)) - static_cast(*static_cast(rhs)); + + uint32 const a = *static_cast(lhs); + uint32 const b = *static_cast(rhs); + + if (a < b) + return -1; + else if (a > b) + return 1; + else + return 0; +} + +// ---------------------------------------------------------------------- + +void AssetCustomizationManagerNamespace::addVariablesForAssetAndLinks(int assetId, CustomizationData &customizationData, bool skipSharedOwnerVariables, int &addedVariableCount) +{ + //-- Find variables used directly by specified asset. + UsageIndexEntry const *usageIndexEntry = lookupVariableUsageIndexEntry(assetId); + if (usageIndexEntry) + { + // This variable uses customization variables. Process each one. + int const startIndex = static_cast(usageIndexEntry->listStartIndex); + VALIDATE_RANGE_INCLUSIVE_EXCLUSIVE(0, startIndex, s_variableUsageListEntryCount); + + int const endIndex = startIndex + static_cast(usageIndexEntry->count); + VALIDATE_RANGE_INCLUSIVE_INCLUSIVE(0, endIndex, s_variableUsageListEntryCount); + + for (int i = startIndex; i < endIndex; ++i) + { + //-- Get variable usage info. + uint16 const variableUsageId = s_variableUsageList[i]; + + VariableUsage const *variableUsage = getVariableUsageFromId(variableUsageId); + NOT_NULL(variableUsage); + + //-- Get variable name and check if we should process further. + char const *variablePathName = getVariableNameFromVariableId(variableUsage->variableId); + NOT_NULL(variablePathName); + + if (skipSharedOwnerVariables && (strncmp(variablePathName, "/shared_owner/", 14) == 0)) + { + // Skip this variable: it is a shared_owner variable and we've been directed to skip them. + continue; + } + + // We're going to create and add this variable if it doesn't already exist. + + //-- Check if variable already exists. If so, we skip this and log. + std::string const variablePathName2(variablePathName); + if (customizationData.findVariable(variablePathName2)) + { + // @todo: add appropriate DEBUG_REPORT_LOG + // Skip this variable: another already exists with the same name. + continue; + } + + //-- Get default value. + int const defaultValue = getDefaultValueFromDefaultId(variableUsage->defaultId); + + //-- Get variable type. + bool isPalette = false; + int idForRealType = 0; + getRangeTypeInfoFromRangeId(variableUsage->rangeId, isPalette, idForRealType); + + //-- Create variable based on type. + CustomizationVariable *variable = NULL; + if (isPalette) + { + //-- Get palette. + char const *const paletteName = getPaletteNameFromPaletteId(idForRealType); + PaletteArgb const *const palette = PaletteArgbList::fetch(TemporaryCrcString(paletteName, true)); + if (!palette) + { + DEBUG_WARNING(true, ("failed to load palette [%s], skipping variable [%s]", paletteName, variablePathName)); + continue; + } + + variable = new PaletteColorCustomizationVariable(palette, defaultValue); + + //-- Release local reference. + palette->release(); + } + else + { + IntRange intRange; + getIntRangeFromIntRangeId(idForRealType, intRange); + + variable = new BasicRangedIntCustomizationVariable(intRange.minRangeInclusive, defaultValue, intRange.maxRangeExclusive); + } + + //-- Add the variable to the CustomizationData. + NOT_NULL(variable); + customizationData.addVariableTakeOwnership(variablePathName2, variable); + + ++addedVariableCount; + } + } + + + //-- Recursively call on assets that this asset is dependent upon. These assets + // could be providing additional variables. + LinkIndexEntry const *linkIndexEntry = lookupAssetLinkIndexEntry(assetId); + if (linkIndexEntry) + { + // This variable uses customization variables. Process each one. + int const startIndex = static_cast(linkIndexEntry->listStartIndex); + VALIDATE_RANGE_INCLUSIVE_EXCLUSIVE(0, startIndex, s_linkListEntryCount); + + int const endIndex = startIndex + static_cast(linkIndexEntry->count); + VALIDATE_RANGE_INCLUSIVE_INCLUSIVE(0, endIndex, s_linkListEntryCount); + + for (int i = startIndex; i < endIndex; ++i) + { + //-- Get asset id for the linked asset, call this function recursively on it. + uint16 const dependencyAssetId = s_linkList[i]; + addVariablesForAssetAndLinks(dependencyAssetId, customizationData, skipSharedOwnerVariables, addedVariableCount); + } + } +} + +// ====================================================================== +// class AssetCustomizationManager: PUBLIC STATIC +// ====================================================================== + +void AssetCustomizationManager::install(char const *filename) +{ + InstallTimer const installTimer("AssetCustomizationManager::install"); + + DEBUG_FATAL(s_installed, ("AssetCustomizationManager already installed.")); + DEBUG_FATAL(!filename || !*filename, ("AssetCustomizationManager requires a valid filename for successful installation.")); + + //-- Check endian-ness of platform. This code assumes little-endian due to the way + // the data image is loaded directly into memory. If we ever hit this, + // we can do a conversion at load time to big-endian. + uint32 testValue = 1; + FATAL(*reinterpret_cast(&testValue) != 1, ("AssetCustomizationManager: running on a non-little-endian architecture, unsupported by this class at this time.")); + + Iff iff; + bool const openResult = iff.open(filename, true); + FATAL(!openResult, ("AssetCustomizationManager data file [%s] does not exist or failed to open. This is likely a configuration file issue.", filename)); + + load(iff); + + s_installed = true; + ExitChain::add(remove, "AssetCustomizationManager"); +} + +// ---------------------------------------------------------------------- + +int AssetCustomizationManager::addCustomizationVariablesForAsset(CrcString const &assetName, CustomizationData &customizationData, bool skipSharedOwnerVariables) +{ + DEBUG_FATAL(!s_installed, ("AssetCustomizationManager not installed.")); + + //-- Convert asset name to internal asset id. + int const assetId = lookupAssetId(assetName); + if (!assetId) + { + // Exit: there are no customization variables for this asset or its dependencies. + return 0; + } + + //-- Recursively add customization variables used directly by an asset and then check any child assets used by the asset. + int addedVariableCount = 0; + addVariablesForAssetAndLinks(assetId, customizationData, skipSharedOwnerVariables, addedVariableCount); + + return addedVariableCount; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/AssetCustomizationManager.h b/engine/shared/library/sharedGame/src/shared/core/AssetCustomizationManager.h new file mode 100644 index 00000000..b63c681e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/AssetCustomizationManager.h @@ -0,0 +1,31 @@ +// ====================================================================== +// +// AssetCustomizationManager.h +// Copyright 2003 Sony Online Entertainment, Inc. +// All Rights Reserved. +// +// ====================================================================== + +#ifndef INCLUDED_AssetCustomizationManager_H +#define INCLUDED_AssetCustomizationManager_H + +// ====================================================================== + +class CrcString; +class CustomizationData; + +// ====================================================================== + +class AssetCustomizationManager +{ +public: + + static void install(char const *filename); + + static int addCustomizationVariablesForAsset(CrcString const &assetName, CustomizationData &customizationData, bool skipSharedOwnerVariables); + +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/AuctionManager.cpp b/engine/shared/library/sharedGame/src/shared/core/AuctionManager.cpp new file mode 100644 index 00000000..0f2b3ad0 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/AuctionManager.cpp @@ -0,0 +1,82 @@ +//====================================================================== +// +// AuctionManager.cpp +// copyright (c) 2003 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/AuctionManager.h" + +#include "UnicodeUtils.h" +#include "sharedFoundation/NetworkId.h" +#include "sharedMath/Vector.h" +#include + +//====================================================================== + +bool AuctionManager::separateLocation (const std::string & location, std::string & planet, std::string & region, std::string & name, NetworkId & id, int & x, int & z) +{ + const char * const whitespace = "."; + size_t endpos = 0; + std::string token; + + typedef std::vector StringVector; + static StringVector sv; + sv.clear (); + + std::string first; + std::string vectorString; + + const size_t hashPos = location.rfind ('#'); + if (hashPos != std::string::npos) + { + first = location.substr (0, hashPos); + vectorString = location.substr (hashPos + 1); + } + + while (endpos != Unicode::String::npos && Unicode::getFirstToken (first, endpos, endpos, token, whitespace)) + { + sv.push_back (token); + if (endpos != Unicode::String::npos) + ++endpos; + } + + if (sv.size () != 4) + { + WARNING (true, ("AuctionManagerClient invalid location [%s]", location.c_str ())); + return false; + } + + planet = sv [0]; + region = sv [1]; + name = sv [2]; + id = NetworkId (sv [3]); + + x = 0; + z = 0; + + if (!vectorString.empty ()) + { + const size_t commaPos = vectorString.rfind (','); + if (commaPos != std::string::npos) + { + x = atoi (vectorString.c_str ()); + z = atoi (vectorString.c_str () + commaPos + 1); + } + } + + return true; +} + +//---------------------------------------------------------------------- + +bool AuctionManager::separateLocation (const std::string & location, std::string & planet, std::string & region, std::string & name) +{ + NetworkId id; + int x = 0; + int z = 0; + return separateLocation (location, planet, region, name, id, x, z); +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/AuctionManager.h b/engine/shared/library/sharedGame/src/shared/core/AuctionManager.h new file mode 100644 index 00000000..1c1f66c2 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/AuctionManager.h @@ -0,0 +1,36 @@ +//====================================================================== +// +// AuctionManager.h +// copyright (c) 2003 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_AuctionManager_H +#define INCLUDED_AuctionManager_H + +//====================================================================== + +class NetworkId; + +//---------------------------------------------------------------------- + +class AuctionManager +{ +public: + static bool separateLocation (const std::string & location, std::string & planet, std::string & region, std::string & name, NetworkId & id, int & x, int & z); + static bool separateLocation (const std::string & location, std::string & planet, std::string & region, std::string & name, NetworkId & id); + static bool separateLocation (const std::string & location, std::string & planet, std::string & region, std::string & name); +}; + +//---------------------------------------------------------------------- + +inline bool AuctionManager::separateLocation (const std::string & location, std::string & planet, std::string & region, std::string & name, NetworkId & id) +{ + int x = 0; + int z = 0; + return separateLocation (location, planet, region, name, id, x, z); +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/AuctionToken.cpp b/engine/shared/library/sharedGame/src/shared/core/AuctionToken.cpp new file mode 100644 index 00000000..228ea611 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/AuctionToken.cpp @@ -0,0 +1,19 @@ +//====================================================================== +// +// AuctionToken.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/AuctionToken.h" + +//====================================================================== + +AuctionToken::AuctionToken () : +sharedTemplateName (), +customizationData () +{ +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/AuctionToken.h b/engine/shared/library/sharedGame/src/shared/core/AuctionToken.h new file mode 100644 index 00000000..50b33f65 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/AuctionToken.h @@ -0,0 +1,29 @@ +//====================================================================== +// +// AuctionToken.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_AuctionToken_H +#define INCLUDED_AuctionToken_H + +//====================================================================== + +#include + +//---------------------------------------------------------------------- + +class AuctionToken +{ +public: + + AuctionToken (); + + std::string sharedTemplateName; + std::string customizationData; +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/AuctionTokenArchive.cpp b/engine/shared/library/sharedGame/src/shared/core/AuctionTokenArchive.cpp new file mode 100644 index 00000000..e590cf33 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/AuctionTokenArchive.cpp @@ -0,0 +1,53 @@ +//====================================================================== +// +// AuctionTokenArchive.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/AuctionTokenArchive.h" + +#include "Archive/Archive.h" +#include "localizationArchive/StringIdArchive.h" +#include "sharedFoundation/NetworkIdArchive.h" +#include "sharedGame/AuctionToken.h" +#include "unicodeArchive/UnicodeArchive.h" + +//====================================================================== + +namespace Archive +{ + //---------------------------------------------------------------------- + + void get (Archive::ReadIterator & source, AuctionToken & target) + { + int version = 0; + get (source, version); + + switch (version) + { + case 0: + get (source, target.sharedTemplateName); + get (source, target.customizationData); + break; + default: + WARNING (true, ("invalid AuctionTokenArchive version %d", version)); + ReadException ex("invalid AuctionTokenArchive version"); + throw (ex); + } + + } + + //---------------------------------------------------------------------- + + void put (ByteStream & target, const AuctionToken & source) + { + put (target, int(0)); + + put (target, source.sharedTemplateName); + put (target, source.customizationData); + } +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/AuctionTokenArchive.h b/engine/shared/library/sharedGame/src/shared/core/AuctionTokenArchive.h new file mode 100644 index 00000000..c55dae6a --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/AuctionTokenArchive.h @@ -0,0 +1,26 @@ +//====================================================================== +// +// AuctionTokenArchive.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_AuctionTokenArchive_H +#define INCLUDED_AuctionTokenArchive_H + +//====================================================================== + +class AuctionToken; + +namespace Archive +{ + class ReadIterator; + class ByteStream; + + void get (Archive::ReadIterator & source, AuctionToken & target); + void put (ByteStream & target, const AuctionToken & source); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/CitizenRankDataTable.cpp b/engine/shared/library/sharedGame/src/shared/core/CitizenRankDataTable.cpp new file mode 100644 index 00000000..2edf349d --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/CitizenRankDataTable.cpp @@ -0,0 +1,216 @@ +// ====================================================================== +// +// CitizenRankDataTable.cpp +// Copyright 2006 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/CitizenRankDataTable.h" + +#include "sharedFoundation/ExitChain.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" + +#include + +// ====================================================================== + +namespace CitizenRankDataTableNamespace +{ + char const * const cs_citizenRankDataTableName = "datatables/city/citizen_rank.iff"; + + std::vector s_allCitizenRankNames; + std::vector s_allCitizenRanks; + std::vector s_allTitleableCitizenRanks; + std::map s_allCitizenRanksByName; + std::map s_allCitizenRanksByTitle; +} + +using namespace CitizenRankDataTableNamespace; + +// ====================================================================== + +void CitizenRankDataTable::install() +{ + DataTable * table = DataTableManager::getTable(cs_citizenRankDataTableName, true); + if (table) + { + int const columnRankName = table->findColumnNumber("rankName"); + int const columnRankSlotId = table->findColumnNumber("rankSlotId"); + int const columnTitle = table->findColumnNumber("title"); + + // the can be a variable number of "alternate title" columns, as long as the columns + // are named alternateTitle1, alternateTitle2, alternateTitle3, alternateTitle4, + // alternateTitle5, and so on + std::vector columnAlternateTitle; + char buffer[128]; + int columnNumber; + for (int i = 1; i <= 1000000000; ++i) + { + snprintf(buffer, sizeof(buffer)-1, "alternateTitle%d", i); + buffer[sizeof(buffer)-1] = '\0'; + + columnNumber = table->findColumnNumber(buffer); + if (columnNumber < 0) + break; + + columnAlternateTitle.push_back(columnNumber); + } + + FATAL((columnRankName < 0), ("column \"rankName\" not found in %s", cs_citizenRankDataTableName)); + FATAL((columnRankSlotId < 0), ("column \"rankSlotId\" not found in %s", cs_citizenRankDataTableName)); + FATAL((columnTitle < 0), ("column \"title\" not found in %s", cs_citizenRankDataTableName)); + + CitizenRankDataTable::CitizenRank const * currentRank = NULL; + + int const numRows = table->getNumRows(); + std::string rankName, alternateTitle; + int slotId; + bool title; + std::vector titles; + std::map names; + std::map allRanksById; + for (int i = 0; i < numRows; ++i) + { + rankName = table->getStringValue(columnRankName, i); + + if (rankName.empty()) + continue; + + FATAL((names.count(rankName) >= 1), ("%s, row %d: rank name %s already used at row %d (either as a rank name or rank alternate title)", cs_citizenRankDataTableName, (i+3), rankName.c_str(), names[rankName])); + names[rankName] = (i+3); + + slotId = table->getIntValue(columnRankSlotId, i); + title = (table->getIntValue(columnTitle, i) != 0); + + // read all alternate titles + titles.clear(); + if (title) + titles.push_back(rankName); + + for (std::vector::const_iterator iterColumnAlternateTitle = columnAlternateTitle.begin(); iterColumnAlternateTitle != columnAlternateTitle.end(); ++iterColumnAlternateTitle) + { + alternateTitle = table->getStringValue(*iterColumnAlternateTitle, i); + + if (!alternateTitle.empty()) + { + FATAL((names.count(alternateTitle) >= 1), ("%s, row %d: alternate title %s already used at row %d (either as a rank name or rank alternate title)", cs_citizenRankDataTableName, (i+3), alternateTitle.c_str(), names[alternateTitle])); + names[alternateTitle] = (i+3); + + titles.push_back(alternateTitle); + } + } + + FATAL((!titles.empty() && !title), ("%s: rank %s cannot have any alternate titles unless it is defined as \"titleable\")", cs_citizenRankDataTableName, rankName.c_str())); + + // check for valid slot id + FATAL((slotId < 0), ("%s, row %d: rank slot id %d must be >= 0", cs_citizenRankDataTableName, (i+3), slotId)); + + // create citizen rank info + currentRank = new CitizenRank(rankName, slotId, titles); + + // check for duplicate slot id + FATAL((allRanksById.count(slotId) >= 1), ("%s, row %d: rank slot id %d already used by rank %s", cs_citizenRankDataTableName, (i+3), slotId, allRanksById[slotId]->name.c_str())); + allRanksById[slotId] = currentRank; + + s_allCitizenRankNames.push_back(currentRank->name); + s_allCitizenRanks.push_back(currentRank); + + if (!currentRank->titles.empty()) + s_allTitleableCitizenRanks.push_back(currentRank); + + s_allCitizenRanksByName[currentRank->name] = currentRank; + + for (std::vector::const_iterator iterTitle = currentRank->titles.begin(); iterTitle != currentRank->titles.end(); ++iterTitle) + s_allCitizenRanksByTitle[*iterTitle] = currentRank; + } + + DataTableManager::close(cs_citizenRankDataTableName); + + // do additional verification + slotId = -1; + for (std::map::const_iterator iterSlotId = allRanksById.begin(); iterSlotId != allRanksById.end(); ++iterSlotId) + { + FATAL((iterSlotId->first != iterSlotId->second->slotId), ("%s: slot id mismatch for slot %s (%d, %d)", cs_citizenRankDataTableName, iterSlotId->second->name.c_str(), iterSlotId->first, iterSlotId->second->slotId)); + + // make sure that slot ids start at 0 and there are no "holes" in the slot ids + if (iterSlotId == allRanksById.begin()) + { + FATAL((iterSlotId->first != 0), ("%s: slot id must start at 0", cs_citizenRankDataTableName)); + } + else + { + FATAL(((slotId + 1) != iterSlotId->first), ("%s: slot id must be contiguous (there is a \"hole\" between %d and %d)", cs_citizenRankDataTableName, slotId, iterSlotId->first)); + } + + slotId = iterSlotId->first; + } + } + else + { + FATAL(true, ("citizen rank datatable %s not found", cs_citizenRankDataTableName)); + } + + ExitChain::add(remove, "CitizenRankDataTable::remove"); +} + +//---------------------------------------------------------------------- + +void CitizenRankDataTable::remove() +{ + for (std::vector::const_iterator iter = s_allCitizenRanks.begin(); iter != s_allCitizenRanks.end(); ++iter) + delete *iter; + + s_allCitizenRankNames.clear(); + s_allCitizenRanks.clear(); + s_allTitleableCitizenRanks.clear(); + s_allCitizenRanksByName.clear(); + s_allCitizenRanksByTitle.clear(); +} + +//---------------------------------------------------------------------- + +std::vector const & CitizenRankDataTable::getAllRankNames() +{ + return s_allCitizenRankNames; +} + +//---------------------------------------------------------------------- + +std::vector const & CitizenRankDataTable::getAllRanks() +{ + return s_allCitizenRanks; +} + +//---------------------------------------------------------------------- + +std::vector const & CitizenRankDataTable::getAllTitleableRanks() +{ + return s_allTitleableCitizenRanks; +} + +//---------------------------------------------------------------------- + +CitizenRankDataTable::CitizenRank const * CitizenRankDataTable::getRank(std::string const & rankName) +{ + std::map::const_iterator iterFind = s_allCitizenRanksByName.find(rankName); + if (iterFind != s_allCitizenRanksByName.end()) + return iterFind->second; + + return NULL; +} + +//---------------------------------------------------------------------- + +CitizenRankDataTable::CitizenRank const * CitizenRankDataTable::isARankTitle(std::string const & rankTitle) +{ + std::map::const_iterator iterFind = s_allCitizenRanksByTitle.find(rankTitle); + if (iterFind != s_allCitizenRanksByTitle.end()) + return iterFind->second; + + return NULL; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/CitizenRankDataTable.h b/engine/shared/library/sharedGame/src/shared/core/CitizenRankDataTable.h new file mode 100644 index 00000000..6958d90b --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/CitizenRankDataTable.h @@ -0,0 +1,53 @@ +// ====================================================================== +// +// CitizenRankDataTable.h +// Copyright 2006 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#ifndef INCLUDED_CitizenRankDataTable_H +#define INCLUDED_CitizenRankDataTable_H + +#include + +// ====================================================================== + +class CitizenRankDataTable // static class +{ +public: + static void install(); + static void remove(); + + class CitizenRank + { + public: + CitizenRank(std::string const & pName, int pSlotId, std::vector const & pTitles) : + name(pName), slotId(pSlotId), titles(pTitles) {}; + + std::string const name; + int const slotId; + std::vector const titles; + + private: + CitizenRank(); + CitizenRank(CitizenRank const &); + CitizenRank &operator =(CitizenRank const &); + }; + + static std::vector const & getAllRankNames(); + static std::vector const & getAllRanks(); + static std::vector const & getAllTitleableRanks(); + static CitizenRankDataTable::CitizenRank const * getRank(std::string const & rankName); + static CitizenRankDataTable::CitizenRank const * isARankTitle(std::string const & rankTitle); + +private: // disabled + + CitizenRankDataTable(); + CitizenRankDataTable(CitizenRankDataTable const &); + CitizenRankDataTable &operator =(CitizenRankDataTable const &); +}; + +// ====================================================================== + +#endif // INCLUDED_CitizenRankDataTable_H diff --git a/engine/shared/library/sharedGame/src/shared/core/CityData.h b/engine/shared/library/sharedGame/src/shared/core/CityData.h new file mode 100644 index 00000000..00fa2626 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/CityData.h @@ -0,0 +1,25 @@ +//======================================================================== +// +// CityData.h +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef INCLUDED_CityData_H +#define INCLUDED_CityData_H + +namespace CityDataCitizenType +{ + enum + { + NotACitizen = 0, + Mayor = 1, + Militia = 2, + Citizen = 3 + }; +} // namespace CityDataCitizenType + +//======================================================================== + +#endif // INCLUDED_CityData_H diff --git a/engine/shared/library/sharedGame/src/shared/core/ClientCombatManagerSupport.cpp b/engine/shared/library/sharedGame/src/shared/core/ClientCombatManagerSupport.cpp new file mode 100644 index 00000000..f4ccad49 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/ClientCombatManagerSupport.cpp @@ -0,0 +1,148 @@ +// ====================================================================== +// +// ClientCombatManagerSupport.cpp +// Copyright 2004 Sony Online Entertainment, Inc. +// All Rights Reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ClientCombatManagerSupport.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/Iff.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/LessPointerComparator.h" +#include "sharedFoundation/PersistentCrcString.h" +#include "sharedFoundation/PointerDeleter.h" + +#include +#include + +// ====================================================================== + +namespace ClientCombatManagerSupportNamespace +{ + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + typedef std::set ActionNameSet; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + Tag const TAG_CBTM = TAG(C,B,T,M); + Tag const TAG_KEY = TAG3(K,E,Y); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + void remove(); + void load(char const *pathName); + void load_0002(Iff &iff); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + bool s_installed; + ActionNameSet s_actionNameSet; +} + +using namespace ClientCombatManagerSupportNamespace; + +// ====================================================================== +// ClientCombatManagerSupportNamespace +// ====================================================================== + +void ClientCombatManagerSupportNamespace::remove() +{ + FATAL(!s_installed, ("ClientCombatManagerSupport not installed.")); + s_installed = false; + + std::for_each(s_actionNameSet.begin(), s_actionNameSet.end(), PointerDeleter()); + + s_actionNameSet.clear(); +} + +// ---------------------------------------------------------------------- + +void ClientCombatManagerSupportNamespace::load(char const *pathName) +{ + Iff iff(pathName); + + iff.enterForm(TAG_CBTM); + { + Tag const version = iff.getCurrentName(); + switch (version) + { + case TAG_0002: + load_0002(iff); + break; + + default: + { + char buffer[5]; + ConvertTagToString(version, buffer); + FATAL(true, ("ClientCombatManagerSupport: unsupported client combat manager file version [%s].", buffer)); + } + } + } + iff.exitForm(TAG_CBTM); +} + +// ---------------------------------------------------------------------- + +void ClientCombatManagerSupportNamespace::load_0002(Iff &iff) +{ + iff.enterForm(TAG_0002); + { + while (!iff.atEndOfForm()) + { + iff.enterForm(TAG_ENTR); + { + iff.enterChunk(TAG_KEY); + { + //-- Read the client combat playback manager's combat action name. + char buffer[1024]; + iff.read_string(buffer, sizeof(buffer) - 1); + buffer[sizeof(buffer) - 1] = '\0'; + + //-- Add the key to the set of combat action names. + CrcString *const newKey = new PersistentCrcString(buffer, true); + std::pair insertResult = s_actionNameSet.insert(newKey); + if (!insertResult.second) + { + // Must be a duplicate. + WARNING(true, ("ClientCombatManagerSupport: the combat manager iff has multiple entries for combat action name [%s], please fix so that only one entry appears for each combat action name key.", newKey->getString())); + delete newKey; + } + } + iff.exitChunk(TAG_KEY); + } + iff.exitForm(TAG_ENTR, true); + } + } + iff.exitForm(TAG_0002); +} + +// ====================================================================== +// ClientCombatManagerSupport PUBLIC STATIC +// ====================================================================== + +void ClientCombatManagerSupport::install(char const *clientCombatManagerPath) +{ + InstallTimer const installTimer("ClientCombatManagerSupport::install"); + + FATAL(s_installed, ("ClientCombatManagerSupport already installed.")); + + load(clientCombatManagerPath); + + s_installed = true; + ExitChain::add(ClientCombatManagerSupportNamespace::remove, "ClientCombatManagerSupport"); +} + +// ---------------------------------------------------------------------- + +bool ClientCombatManagerSupport::doesCombatActionNameExist(CrcString const &combatActionName) +{ + FATAL(!s_installed, ("ClientCombatManagerSupport not installed.")); + return (s_actionNameSet.find(&combatActionName) != s_actionNameSet.end()); +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/ClientCombatManagerSupport.h b/engine/shared/library/sharedGame/src/shared/core/ClientCombatManagerSupport.h new file mode 100644 index 00000000..b705bc11 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/ClientCombatManagerSupport.h @@ -0,0 +1,47 @@ +// ====================================================================== +// +// ClientCombatManagerSupport.h +// Copyright 2004 Sony Online Entertainment, Inc. +// All Rights Reserved. +// +// ====================================================================== + +#ifndef INCLUDED_ClientCombatManagerSupport_H +#define INCLUDED_ClientCombatManagerSupport_H + +// ====================================================================== + +class CrcString; + +// ====================================================================== +/** + * Provides support for the server to determine if a given combat action name + * is supported via the client combat playback visualization system. + * + * The primary interface is the doesCombatActionNameExist() member function. + * It returns true if the client visualization system has an entry for the + * specified combat action name key. + * + * This system was added to address the infrequent but hard-to-track issue + * where server-side script generates a combat action name (via doCombatResults) + * when the client has no mapping for the action name. Since the action name + * comes across as a 32-bit CRC value, we don't even know which name the server + * is trying to generate. This class will provide a way for the server to + * check if a given action name is valid prior to converting to a CRC value. + * + * This class runs off of the same data used by the client's + * ClientCombatPlaybackManager class in the clientGame library. + */ + +class ClientCombatManagerSupport +{ +public: + + static void install(char const *clientCombatManagerPath); + static bool doesCombatActionNameExist(CrcString const &combatActionName); + +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/CollectionsDataTable.cpp b/engine/shared/library/sharedGame/src/shared/core/CollectionsDataTable.cpp new file mode 100644 index 00000000..74cc78cc --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/CollectionsDataTable.cpp @@ -0,0 +1,1124 @@ +// ====================================================================== +// +// CollectionsDataTable.cpp +// Copyright 2006 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/CollectionsDataTable.h" + +#include "UnicodeUtils.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedUtility/DataTableManager.h" +#include "sharedUtility/DataTable.h" + +#include +#include +#include + +// ====================================================================== + +namespace CollectionsDataTableNamespace +{ + char const * const cs_collectionsDataTableName = "datatables/collection/collection.iff"; + + //---------------------------------------------------------------------- + // slots + + // all slots by slot name + std::map s_allSlotsByName; + + // all slots by begin slot id + // for quick lookup of a slot by begin slot id, we use a vector because + // slot id are guaranteed to start at 0 and be contiguous; for counter-type + // slot, only the begin slot id index points to the slot; the other slot + // id indices point to NULL + std::vector s_allSlotsById; + + // all title(able) slots + std::vector s_allTitleableSlots; + + // all slot titles + std::map s_allSlotTitles; + + //---------------------------------------------------------------------- + + //---------------------------------------------------------------------- + // collections + + // slots in each collection + std::map > s_slotsInCollection; + + // all title(able) collections + std::vector s_allTitleableCollections; + + // all collection titles + std::map s_allCollectionTitles; + + // all collections that have "server first" tracking + std::map s_allServerFirstCollections; + + // all collections by collection name + std::map s_allCollectionsByName; + + //---------------------------------------------------------------------- + + //---------------------------------------------------------------------- + // pages + + // slots in each page + std::map > s_slotsInPage; + + // collections in each page + std::map > s_collectionsInPage; + + // all title(able) pages + std::vector s_allTitleablePages; + + // all page titles + std::map s_allPageTitles; + + // all pages by page name + std::map s_allPagesByName; + + //---------------------------------------------------------------------- + + //---------------------------------------------------------------------- + // books + + // slots in each book + std::map > s_slotsInBook; + + // collections in each book + std::map > s_collectionsInBook; + + // pages in each book + std::map > s_pagesInBook; + + // all books + std::vector s_allBooks; + + // all books by book name + std::map s_allBooksByName; + + //---------------------------------------------------------------------- + + //---------------------------------------------------------------------- + // categories + + // slots in each category + std::map > s_slotsInCategory; + + // slots in each (collection, category) + std::map, std::vector > s_slotsInCategoryByCollection; + + // slots in each (page, category) + std::map, std::vector > s_slotsInCategoryByPage; + + // slots in each (book, category) + std::map, std::vector > s_slotsInCategoryByBook; + + // all categories + std::set s_slotCategories; + + // categories in each collection + std::map > s_slotCategoriesByCollection; + + // categories in each page + std::map > s_slotCategoriesByPage; + + // categories in each book + std::map > s_slotCategoriesByBook; + + //---------------------------------------------------------------------- + + // the DB can only currently handle this many collections + // + // !!!!!!!!!!!!!!!!!!!!!!!!!WARNING!!!!!!!!!!!!!!!!!!!!!!!!! + // ***DO NOT*** change this value unless you know what you + // are doing, or you will crash the SWG DB Server!!!!!!!!!!! + // !!!!!!!!!!!!!!!!!!!!!!!!!WARNING!!!!!!!!!!!!!!!!!!!!!!!!! + int const COLLECTIONS_PER_INDEX = 16000; + int const MAX_COLLECTIONS = COLLECTIONS_PER_INDEX * 2; +} + +using namespace CollectionsDataTableNamespace; + +// ====================================================================== + +void CollectionsDataTable::install() +{ + DataTable * table = DataTableManager::getTable(cs_collectionsDataTableName, true); + if (table) + { + int const columnBookName = table->findColumnNumber("bookName"); + int const columnPageName = table->findColumnNumber("pageName"); + int const columnCollectionName = table->findColumnNumber("collectionName"); + int const columnSlotName = table->findColumnNumber("slotName"); + int const columnBeginSlotId = table->findColumnNumber("beginSlotId"); + int const columnEndSlotId = table->findColumnNumber("endSlotId"); + int const columnMaxSlotValue = table->findColumnNumber("maxSlotValue"); + int const columnIcon = table->findColumnNumber("icon"); + int const columnMusic = table->findColumnNumber("music"); + int const columnShowIfNotYetEarned = table->findColumnNumber("showIfNotYetEarned"); + int const columnHidden = table->findColumnNumber("hidden"); + int const columnTitle = table->findColumnNumber("title"); + int const columnNoReward = table->findColumnNumber("noReward"); + int const columnTrackServerFirst = table->findColumnNumber("trackServerFirst"); + + // the can be a variable number of "category" columns, as long as the columns + // are named category1, category2, category3, category4, category5, and so on + std::vector columnCategory; + char buffer[128]; + int columnNumber; + for (int i = 1; i <= 1000000000; ++i) + { + snprintf(buffer, sizeof(buffer)-1, "category%d", i); + buffer[sizeof(buffer)-1] = '\0'; + + columnNumber = table->findColumnNumber(buffer); + if (columnNumber < 0) + break; + + columnCategory.push_back(columnNumber); + } + + // the can be a variable number of "prereq" columns, as long as the columns + // are named prereqSlotName1, prereqSlotName2, prereqSlotName3, prereqSlotName4, + // prereqSlotName5, and so on + std::vector columnPrereq; + for (int i = 1; i <= 1000000000; ++i) + { + snprintf(buffer, sizeof(buffer)-1, "prereqSlotName%d", i); + buffer[sizeof(buffer)-1] = '\0'; + + columnNumber = table->findColumnNumber(buffer); + if (columnNumber < 0) + break; + + columnPrereq.push_back(columnNumber); + } + + // the can be a variable number of "alternate title" columns, as long as the columns + // are named alternateTitle1, alternateTitle2, alternateTitle3, alternateTitle4, + // alternateTitle5, and so on + std::vector columnAlternateTitle; + for (int i = 1; i <= 1000000000; ++i) + { + snprintf(buffer, sizeof(buffer)-1, "alternateTitle%d", i); + buffer[sizeof(buffer)-1] = '\0'; + + columnNumber = table->findColumnNumber(buffer); + if (columnNumber < 0) + break; + + columnAlternateTitle.push_back(columnNumber); + } + + FATAL((columnBookName < 0), ("column \"bookName\" not found in %s", cs_collectionsDataTableName)); + FATAL((columnPageName < 0), ("column \"pageName\" not found in %s", cs_collectionsDataTableName)); + FATAL((columnCollectionName < 0), ("column \"collectionName\" not found in %s", cs_collectionsDataTableName)); + FATAL((columnSlotName < 0), ("column \"slotName\" not found in %s", cs_collectionsDataTableName)); + FATAL((columnBeginSlotId < 0), ("column \"beginSlotId\" not found in %s", cs_collectionsDataTableName)); + FATAL((columnEndSlotId < 0), ("column \"endSlotId\" not found in %s", cs_collectionsDataTableName)); + FATAL((columnMaxSlotValue < 0), ("column \"maxSlotValue\" not found in %s", cs_collectionsDataTableName)); + FATAL((columnIcon < 0), ("column \"icon\" not found in %s", cs_collectionsDataTableName)); + FATAL((columnMusic < 0), ("column \"music\" not found in %s", cs_collectionsDataTableName)); + FATAL((columnShowIfNotYetEarned < 0), ("column \"showIfNotYetEarned\" not found in %s", cs_collectionsDataTableName)); + FATAL((columnHidden < 0), ("column \"hidden\" not found in %s", cs_collectionsDataTableName)); + FATAL((columnTitle < 0), ("column \"title\" not found in %s", cs_collectionsDataTableName)); + FATAL((columnNoReward < 0), ("column \"noReward\" not found in %s", cs_collectionsDataTableName)); + FATAL((columnTrackServerFirst < 0), ("column \"trackServerFirst\" not found in %s", cs_collectionsDataTableName)); + + CollectionsDataTable::CollectionInfoBook const * currentBook = NULL; + CollectionsDataTable::CollectionInfoPage const * currentPage = NULL; + CollectionsDataTable::CollectionInfoCollection const * currentCollection = NULL; + CollectionsDataTable::CollectionInfoSlot const * currentSlot = NULL; + + int const numRows = table->getNumRows(); + std::string bookName, pageName, collectionName, slotName, category, prereq, alternateTitle, icon, music; + std::vector categories; + std::vector prereqs; + std::vector titles; + int beginSlotId, endSlotId, tempBeginSlotId, tempEndSlotId, maxSlotValue; + unsigned long maxValueForNumBits; + ShowIfNotYetEarnedType showIfNotYetEarned; + bool hidden, notifyScriptOnModify, title, noReward, trackServerFirst; + int tempCount; + std::map names; + std::map allPrereqs; + std::map allSlotsById; + for (int i = 0; i < numRows; ++i) + { + bookName = table->getStringValue(columnBookName, i); + pageName = table->getStringValue(columnPageName, i); + collectionName = table->getStringValue(columnCollectionName, i); + slotName = table->getStringValue(columnSlotName, i); + + if (bookName.empty() && pageName.empty() && collectionName.empty() && slotName.empty()) + continue; + + // only one of bookName, pageName, collectionName, or slotName can be specified + // and bookName, pageName, collectionName, and slotName must be unique + tempCount = 0; + if (!bookName.empty()) + { + FATAL((names.count(bookName) >= 1), ("%s, row %d: book name %s already used at row %d (either as a book, page, collection, slot, or alternate title)", cs_collectionsDataTableName, (i+3), bookName.c_str(), names[bookName])); + names[bookName] = (i+3); + ++tempCount; + } + if (!pageName.empty()) + { + FATAL((names.count(pageName) >= 1), ("%s, row %d: page name %s already used at row %d (either as a book, page, collection, slot, or alternate title)", cs_collectionsDataTableName, (i+3), pageName.c_str(), names[pageName])); + names[pageName] = (i+3); + ++tempCount; + } + if (!collectionName.empty()) + { + FATAL((names.count(collectionName) >= 1), ("%s, row %d: collection name %s already used at row %d (either as a book, page, collection, slot, or alternate title)", cs_collectionsDataTableName, (i+3), collectionName.c_str(), names[collectionName])); + names[collectionName] = (i+3); + ++tempCount; + } + if (!slotName.empty()) + { + FATAL((names.count(slotName) >= 1), ("%s, row %d: slot name %s already used at row %d (either as a book, page, collection, slot, or alternate title)", cs_collectionsDataTableName, (i+3), slotName.c_str(), names[slotName])); + names[slotName] = (i+3); + ++tempCount; + } + + FATAL((tempCount != 1), ("%s, row %d: only one of bookName, pageName, collectionName, or slotName can be specified", cs_collectionsDataTableName, (i+3))); + + beginSlotId = table->getIntValue(columnBeginSlotId, i); + endSlotId = table->getIntValue(columnEndSlotId, i); + maxSlotValue = table->getIntValue(columnMaxSlotValue, i); + icon = table->getStringValue(columnIcon, i); + music = table->getStringValue(columnMusic, i); + showIfNotYetEarned = static_cast(table->getIntValue(columnShowIfNotYetEarned, i)); + hidden = (table->getIntValue(columnHidden, i) != 0); + title = (table->getIntValue(columnTitle, i) != 0); + noReward = (table->getIntValue(columnNoReward, i) != 0); + trackServerFirst = (table->getIntValue(columnTrackServerFirst, i) != 0); + + // read all alternate titles + titles.clear(); + if (title) + { + if (!pageName.empty()) + titles.push_back(pageName); + else if (!collectionName.empty()) + titles.push_back(collectionName); + else if (!slotName.empty()) + titles.push_back(slotName); + } + + for (std::vector::const_iterator iterColumnAlternateTitle = columnAlternateTitle.begin(); iterColumnAlternateTitle != columnAlternateTitle.end(); ++iterColumnAlternateTitle) + { + alternateTitle = table->getStringValue(*iterColumnAlternateTitle, i); + + if (!alternateTitle.empty()) + { + FATAL((names.count(alternateTitle) >= 1), ("%s, row %d: alternate title %s already used at row %d (either as a book, page, collection, slot, or alternate title)", cs_collectionsDataTableName, (i+3), alternateTitle.c_str(), names[alternateTitle])); + names[alternateTitle] = (i+3); + + titles.push_back(alternateTitle); + } + } + + // start of new book + if (!bookName.empty()) + { + // verify previous book, unless it's the first book + if (currentBook) + { + // make sure previous book is not empty + FATAL(s_pagesInBook[currentBook->name].empty(), ("%s: book %s has no pages", cs_collectionsDataTableName, currentBook->name.c_str())); + FATAL(!currentPage, ("%s: book %s has no pages", cs_collectionsDataTableName, currentBook->name.c_str())); + FATAL(s_slotsInBook[currentBook->name].empty(), ("%s: book %s has no slots", cs_collectionsDataTableName, currentBook->name.c_str())); + + // make sure last page of previous book is not empty + FATAL(s_collectionsInPage[currentPage->name].empty(), ("%s: page %s has no collections", cs_collectionsDataTableName, currentPage->name.c_str())); + FATAL(!currentCollection, ("%s: page %s has no collections", cs_collectionsDataTableName, currentPage->name.c_str())); + FATAL(s_slotsInPage[currentPage->name].empty(), ("%s: page %s has no slots", cs_collectionsDataTableName, currentPage->name.c_str())); + + // make sure last collection of last page of previous book is not empty + FATAL(s_slotsInCollection[currentCollection->name].empty(), ("%s: page %s has empty collection %s", cs_collectionsDataTableName, currentPage->name.c_str(), currentCollection->name.c_str())); + } + + // start new book + FATAL(title, ("%s: book %s cannot be \"titleable\")", cs_collectionsDataTableName, bookName.c_str())); + FATAL(!titles.empty(), ("%s: book %s cannot have any alternate titles (books are not \"titleable\")", cs_collectionsDataTableName, bookName.c_str())); + currentBook = new CollectionInfoBook(bookName, icon, showIfNotYetEarned, hidden); + currentPage = NULL; + currentCollection = NULL; + s_allBooks.push_back(currentBook); + s_allBooksByName[bookName] = currentBook; + } + // start of new page + else if (!pageName.empty()) + { + // cannot start page without a book + FATAL(!currentBook, ("%s, row %d: page %s must be in a book", cs_collectionsDataTableName, (i+3), pageName.c_str())); + + // verify previous page, unless it's the first page + if (currentPage) + { + // make sure previous page is not empty + FATAL(s_collectionsInPage[currentPage->name].empty(), ("%s: page %s has no collections", cs_collectionsDataTableName, currentPage->name.c_str())); + FATAL(!currentCollection, ("%s: page %s has no collections", cs_collectionsDataTableName, currentPage->name.c_str())); + FATAL(s_slotsInPage[currentPage->name].empty(), ("%s: page %s has no slots", cs_collectionsDataTableName, currentPage->name.c_str())); + + // make sure last collection of previous page is not empty + FATAL(s_slotsInCollection[currentCollection->name].empty(), ("%s: page %s has empty collection %s", cs_collectionsDataTableName, currentPage->name.c_str(), currentCollection->name.c_str())); + } + + // start new page + FATAL((!titles.empty() && !title), ("%s: page %s cannot have any alternate titles unless it is defined as \"titleable\")", cs_collectionsDataTableName, pageName.c_str())); + currentPage = new CollectionInfoPage(pageName, icon, showIfNotYetEarned, hidden, titles, *currentBook); + currentCollection = NULL; + s_pagesInBook[currentBook->name].push_back(currentPage); + s_allPagesByName[pageName] = currentPage; + + if (!currentPage->titles.empty()) + { + s_allTitleablePages.push_back(currentPage); + + for (std::vector::const_iterator iterTitles = currentPage->titles.begin(); iterTitles != currentPage->titles.end(); ++iterTitles) + s_allPageTitles[*iterTitles] = currentPage; + } + } + else if (!collectionName.empty()) + { + // cannot start collection without a page or a book + FATAL(!currentBook, ("%s, row %d: collection %s must be in a book", cs_collectionsDataTableName, (i+3), collectionName.c_str())); + FATAL(!currentPage, ("%s, row %d: collection %s must be in a page", cs_collectionsDataTableName, (i+3), collectionName.c_str())); + + // verify previous collection, unless it's the first collection in the page + if (currentCollection) + { + // make sure previous collection is not empty + FATAL(s_slotsInCollection[currentCollection->name].empty(), ("%s: page %s has empty collection %s", cs_collectionsDataTableName, currentPage->name.c_str(), currentCollection->name.c_str())); + } + + // read all category for collection + for (std::vector::const_iterator iterColumnCategory = columnCategory.begin(); iterColumnCategory != columnCategory.end(); ++iterColumnCategory) + { + category = table->getStringValue(*iterColumnCategory, i); + + if (!category.empty()) + { + categories.push_back(category); + } + } + + // start new collection + FATAL((!titles.empty() && !title), ("%s: collection %s cannot have any alternate titles unless it is defined as \"titleable\")", cs_collectionsDataTableName, collectionName.c_str())); + currentCollection = new CollectionInfoCollection(collectionName, icon, showIfNotYetEarned, hidden, categories, titles, noReward, trackServerFirst, *currentPage); + s_collectionsInPage[currentPage->name].push_back(currentCollection); + s_collectionsInBook[currentBook->name].push_back(currentCollection); + s_allCollectionsByName[collectionName] = currentCollection; + + if (!currentCollection->titles.empty()) + { + s_allTitleableCollections.push_back(currentCollection); + + for (std::vector::const_iterator iterTitles = currentCollection->titles.begin(); iterTitles != currentCollection->titles.end(); ++iterTitles) + s_allCollectionTitles[*iterTitles] = currentCollection; + } + + if (currentCollection->trackServerFirst) + s_allServerFirstCollections[collectionName] = currentCollection; + + categories.clear(); + } + else + { + // cannot have a slot without a collection or a page or a book + FATAL(!currentBook, ("%s, row %d: slot %s must be in a book", cs_collectionsDataTableName, (i+3), slotName.c_str())); + FATAL(!currentPage, ("%s, row %d: slot %s must be in a page", cs_collectionsDataTableName, (i+3), slotName.c_str())); + FATAL(!currentCollection, ("%s, row %d: slot %s must be in a collection", cs_collectionsDataTableName, (i+3), slotName.c_str())); + + // check for valid slot id + FATAL(((beginSlotId < 0) || (beginSlotId >= MAX_COLLECTIONS)), ("%s, row %d: begin slot id %d must be 0-%d", cs_collectionsDataTableName, (i+3), beginSlotId, (MAX_COLLECTIONS-1))); + FATAL((((endSlotId < 0) && (endSlotId != -1)) || (endSlotId >= MAX_COLLECTIONS)), ("%s, row %d: end slot id %d must be 0-%d", cs_collectionsDataTableName, (i+3), endSlotId, (MAX_COLLECTIONS-1))); + + // check for valid beginSlotId/endSlotId combination + FATAL(((endSlotId != -1) && (beginSlotId >= endSlotId)), ("%s, row %d: begin slot id %d must be < end slot id %d", cs_collectionsDataTableName, (i+3), beginSlotId, endSlotId)); + FATAL(((endSlotId != -1) && ((beginSlotId / COLLECTIONS_PER_INDEX) != (endSlotId / COLLECTIONS_PER_INDEX))), ("%s, row %d: counter-type slot cannot span across the 15999-16000 / 31999-32000 / 47999-48000 / 63999-64000 / etc slot id boundary", cs_collectionsDataTableName, (i+3))); + + // max number of bits for a counter-type slot is 32 bits + FATAL(((endSlotId != -1) && ((endSlotId - beginSlotId) > 31)), ("%s, row %d: counter-type slot uses %d bits which exceeds the limit of 32 bits for counter-type slot", cs_collectionsDataTableName, (i+3), (endSlotId - beginSlotId + 1))); + + // maxSlotValue is only valid if both beginSlotId and endSlotId specified + FATAL(((endSlotId == -1) && (maxSlotValue != -1)), ("%s, row %d: max slot value %d cannot be specified for a non counter-type slot", cs_collectionsDataTableName, (i+3), maxSlotValue)); + + // check for valid maxSlotValue + FATAL(((maxSlotValue <= 1) && (maxSlotValue != -1)), ("%s, row %d: max slot value %d must be > 1", cs_collectionsDataTableName, (i+3), maxSlotValue)); + + // if maxSlotValue specified, make sure there are enough bits allocated to be able to store the value + maxValueForNumBits = 1; + if (endSlotId != -1) + { + unsigned long const numBits = static_cast(endSlotId - beginSlotId + 1); + maxValueForNumBits = (0xffffffff >> (32 - numBits)); + + if (maxSlotValue != -1) + FATAL((maxValueForNumBits < static_cast(maxSlotValue)), ("%s, row %d: counter-type slot uses %lu bits, which can only hold a max value of %lu, which is less than the specified max value of %d", cs_collectionsDataTableName, (i+3), numBits, maxValueForNumBits, maxSlotValue)); + } + + // read all category for slot + notifyScriptOnModify = true; + for (std::vector::const_iterator iterColumnCategory = columnCategory.begin(); iterColumnCategory != columnCategory.end(); ++iterColumnCategory) + { + category = table->getStringValue(*iterColumnCategory, i); + + if (!category.empty()) + { + categories.push_back(category); + + if (category == "noScriptNotifyOnModify") + notifyScriptOnModify = false; + } + } + + // read all prereq for slot + for (std::vector::const_iterator iterColumnPrereq = columnPrereq.begin(); iterColumnPrereq != columnPrereq.end(); ++iterColumnPrereq) + { + prereq = table->getStringValue(*iterColumnPrereq, i); + + if (!prereq.empty()) + { + FATAL((prereq == slotName), ("%s, row %d: slot %s cannot have itself as a prereq", cs_collectionsDataTableName, (i+3), slotName.c_str())); + + prereqs.push_back(prereq); + + if (allPrereqs.count(prereq) < 1) + allPrereqs[prereq] = (i+3); + } + } + + // new slot + FATAL((!titles.empty() && !title), ("%s: slot %s cannot have any alternate titles unless it is defined as \"titleable\")", cs_collectionsDataTableName, slotName.c_str())); + currentSlot = new CollectionInfoSlot(slotName, icon, showIfNotYetEarned, hidden, notifyScriptOnModify, (beginSlotId / COLLECTIONS_PER_INDEX), (beginSlotId % COLLECTIONS_PER_INDEX), beginSlotId, ((endSlotId < 0) ? -1 : (endSlotId % COLLECTIONS_PER_INDEX)), ((endSlotId < 0) ? -1 : endSlotId), (((endSlotId < 0) || (maxSlotValue <= 1)) ? 0 : static_cast(maxSlotValue)), maxValueForNumBits, categories, prereqs, music, titles, *currentCollection); + + // check for duplicate slot id across all collections + if (endSlotId == -1) + { + FATAL((allSlotsById.count(beginSlotId) >= 1), ("%s, row %d: slot id %d already used by slot %s", cs_collectionsDataTableName, (i+3), beginSlotId, allSlotsById[beginSlotId]->name.c_str())); + } + else + { + for (int j = beginSlotId; j <= endSlotId; ++j) + FATAL((allSlotsById.count(j) >= 1), ("%s, row %d: slot id %d already used by slot %s", cs_collectionsDataTableName, (i+3), j, allSlotsById[j]->name.c_str())); + } + + s_slotsInCollection[currentCollection->name].push_back(currentSlot); + s_slotsInPage[currentPage->name].push_back(currentSlot); + s_slotsInBook[currentBook->name].push_back(currentSlot); + s_allSlotsByName[currentSlot->name] = currentSlot; + + if (endSlotId == -1) + { + allSlotsById[beginSlotId] = currentSlot; + } + else + { + for (int j = beginSlotId; j <= endSlotId; ++j) + allSlotsById[j] = currentSlot; + } + + if (!currentSlot->titles.empty()) + { + s_allTitleableSlots.push_back(currentSlot); + + for (std::vector::const_iterator iterTitles = currentSlot->titles.begin(); iterTitles != currentSlot->titles.end(); ++iterTitles) + s_allSlotTitles[*iterTitles] = currentSlot; + } + + for (std::vector::const_iterator iterCategories = categories.begin(); iterCategories != categories.end(); ++iterCategories) + { + s_slotsInCategory[*iterCategories].push_back(currentSlot); + s_slotsInCategoryByBook[std::make_pair(currentBook->name, *iterCategories)].push_back(currentSlot); + s_slotsInCategoryByPage[std::make_pair(currentPage->name, *iterCategories)].push_back(currentSlot); + s_slotsInCategoryByCollection[std::make_pair(currentCollection->name, *iterCategories)].push_back(currentSlot); + + IGNORE_RETURN(s_slotCategories.insert(*iterCategories)); + IGNORE_RETURN(s_slotCategoriesByBook[currentBook->name].insert(*iterCategories)); + IGNORE_RETURN(s_slotCategoriesByPage[currentPage->name].insert(*iterCategories)); + IGNORE_RETURN(s_slotCategoriesByCollection[currentCollection->name].insert(*iterCategories)); + } + + currentSlot = NULL; + categories.clear(); + prereqs.clear(); + } + } + + DataTableManager::close(cs_collectionsDataTableName); + + // verify last book + if (currentBook) + { + // make sure last book is not empty + FATAL(s_pagesInBook[currentBook->name].empty(), ("%s: book %s has no pages", cs_collectionsDataTableName, currentBook->name.c_str())); + FATAL(!currentPage, ("%s: book %s has no pages", cs_collectionsDataTableName, currentBook->name.c_str())); + FATAL(s_slotsInBook[currentBook->name].empty(), ("%s: book %s has no slots", cs_collectionsDataTableName, currentBook->name.c_str())); + + // make sure last page of last book is not empty + FATAL(s_collectionsInPage[currentPage->name].empty(), ("%s: page %s has no collections", cs_collectionsDataTableName, currentPage->name.c_str())); + FATAL(!currentCollection, ("%s: page %s has no collections", cs_collectionsDataTableName, currentPage->name.c_str())); + FATAL(s_slotsInPage[currentPage->name].empty(), ("%s: page %s has no slots", cs_collectionsDataTableName, currentPage->name.c_str())); + + // make sure last collection of last page of last book is not empty + FATAL(s_slotsInCollection[currentCollection->name].empty(), ("%s: page %s has empty collection %s", cs_collectionsDataTableName, currentPage->name.c_str(), currentCollection->name.c_str())); + } + + // save off all slots ordered by slot ids + s_allSlotsById.resize(allSlotsById.size(), NULL); + beginSlotId = -1; + for (std::map::const_iterator iterSlotId = allSlotsById.begin(); iterSlotId != allSlotsById.end(); ++iterSlotId) + { + tempBeginSlotId = ((iterSlotId->second->beginSlotId == -1) ? iterSlotId->second->beginSlotId : ((iterSlotId->second->slotIdIndex * COLLECTIONS_PER_INDEX) + iterSlotId->second->beginSlotId)); + FATAL((tempBeginSlotId != iterSlotId->second->absoluteBeginSlotId), ("%s: beginSlotId/absoluteBeginSlotId mismatch for slot %s (%d, %d, %d)", cs_collectionsDataTableName, iterSlotId->second->name.c_str(), iterSlotId->second->slotIdIndex, iterSlotId->second->beginSlotId, iterSlotId->second->absoluteBeginSlotId)); + + tempEndSlotId = ((iterSlotId->second->endSlotId == -1) ? iterSlotId->second->endSlotId : ((iterSlotId->second->slotIdIndex * COLLECTIONS_PER_INDEX) + iterSlotId->second->endSlotId)); + FATAL((tempEndSlotId != iterSlotId->second->absoluteEndSlotId), ("%s: endSlotId/absoluteEndSlotId mismatch for slot %s (%d, %d, %d)", cs_collectionsDataTableName, iterSlotId->second->name.c_str(), iterSlotId->second->slotIdIndex, iterSlotId->second->endSlotId, iterSlotId->second->absoluteEndSlotId)); + + if (tempEndSlotId == -1) + { + FATAL((iterSlotId->first != tempBeginSlotId), ("%s: begin slot id mismatch for slot %s (%d, %d)", cs_collectionsDataTableName, iterSlotId->second->name.c_str(), iterSlotId->first, tempBeginSlotId)); + } + else + { + FATAL(((iterSlotId->first < tempBeginSlotId) || (iterSlotId->first > tempEndSlotId)), ("%s: slot id mismatch for slot %s (%d, %d, %d)", cs_collectionsDataTableName, iterSlotId->second->name.c_str(), iterSlotId->first, tempBeginSlotId, tempEndSlotId)); + } + + // make sure that slot ids start at 0 and there are no "holes" in the slot ids + if (iterSlotId == allSlotsById.begin()) + { + FATAL((iterSlotId->first != 0), ("%s: slot id must start at 0", cs_collectionsDataTableName)); + } + else + { + FATAL(((beginSlotId + 1) != iterSlotId->first), ("%s: slot id must be contiguous (there is a \"hole\" between %d and %d)", cs_collectionsDataTableName, beginSlotId, iterSlotId->first)); + } + + beginSlotId = iterSlotId->first; + + if (iterSlotId->first == tempBeginSlotId) + { + s_allSlotsById[iterSlotId->first] = iterSlotId->second; + } + else + { + s_allSlotsById[iterSlotId->first] = NULL; + } + } + + // make sure that all collection slot name specified as prereqs actually exists + for (std::map::const_iterator iterAllPrereqs = allPrereqs.begin(); iterAllPrereqs != allPrereqs.end(); ++iterAllPrereqs) + { + FATAL((s_allSlotsByName.count(iterAllPrereqs->first) < 1), ("%s, row %d: prereq slot name %s does not exist", cs_collectionsDataTableName, iterAllPrereqs->second, iterAllPrereqs->first.c_str())); + } + + // set up collection slot prereqs as pointers to the actual prereq slot, for faster access + for (std::map::const_iterator iterAllSlotsByName = s_allSlotsByName.begin(); iterAllSlotsByName != s_allSlotsByName.end(); ++iterAllSlotsByName) + { + CollectionsDataTable::CollectionInfoSlot * slot = const_cast(iterAllSlotsByName->second); + for (std::vector::const_iterator iterPrereq = slot->prereqs.begin(); iterPrereq != slot->prereqs.end(); ++iterPrereq) + { + CollectionsDataTable::CollectionInfoSlot const * prereqSlot = getSlotByName(*iterPrereq); + FATAL((!prereqSlot), ("%s: prereq slot name %s does not exist", cs_collectionsDataTableName, iterPrereq->c_str())); + (const_cast *>(&slot->prereqsPtr))->push_back(prereqSlot); + } + } + } + else + { + FATAL(true, ("collection datatable %s not found", cs_collectionsDataTableName)); + } + + ExitChain::add(remove, "CollectionsDataTable::remove"); +} + +//---------------------------------------------------------------------- + +void CollectionsDataTable::remove() +{ + // free slots + { + for (std::map::const_iterator iterSlot = s_allSlotsByName.begin(); iterSlot != s_allSlotsByName.end(); ++iterSlot) + { + delete iterSlot->second; + } + } + + // free collections + { + for (std::map >::const_iterator iterPage = s_collectionsInPage.begin(); iterPage != s_collectionsInPage.end(); ++iterPage) + { + for (std::vector::const_iterator iterCollection = iterPage->second.begin(); iterCollection != iterPage->second.end(); ++iterCollection) + { + delete *iterCollection; + } + } + + } + + // free pages + { + for (std::map >::const_iterator iterBook = s_pagesInBook.begin(); iterBook != s_pagesInBook.end(); ++iterBook) + { + for (std::vector::const_iterator iterPage = iterBook->second.begin(); iterPage != iterBook->second.end(); ++iterPage) + { + delete *iterPage; + } + } + } + + // free books + { + for (std::vector::const_iterator iterBook = s_allBooks.begin(); iterBook != s_allBooks.end(); ++iterBook) + { + delete *iterBook; + } + } + + // slots + s_allSlotsByName.clear(); + s_allSlotsById.clear(); + s_allTitleableSlots.clear(); + s_allSlotTitles.clear(); + + // collections + s_slotsInCollection.clear(); + s_allTitleableCollections.clear(); + s_allCollectionTitles.clear(); + s_allServerFirstCollections.clear(); + s_allCollectionsByName.clear(); + + // pages + s_slotsInPage.clear(); + s_collectionsInPage.clear(); + s_allTitleablePages.clear(); + s_allPageTitles.clear(); + s_allPagesByName.clear(); + + // books + s_slotsInBook.clear(); + s_collectionsInBook.clear(); + s_pagesInBook.clear(); + s_allBooks.clear(); + s_allBooksByName.clear(); + + // categories + s_slotsInCategory.clear(); + s_slotsInCategoryByCollection.clear(); + s_slotsInCategoryByPage.clear(); + s_slotsInCategoryByBook.clear(); + s_slotCategories.clear(); + s_slotCategoriesByCollection.clear(); + s_slotCategoriesByPage.clear(); + s_slotCategoriesByBook.clear(); +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +CollectionsDataTable::CollectionInfoSlot const * CollectionsDataTable::getSlotByName(std::string const & slotName) +{ + std::map::const_iterator iterFind = s_allSlotsByName.find(slotName); + if (iterFind != s_allSlotsByName.end()) + return iterFind->second; + + return NULL; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +CollectionsDataTable::CollectionInfoSlot const * CollectionsDataTable::getSlotByBeginSlotId(int slotId) +{ + if ((slotId < 0) || (slotId >= static_cast(s_allSlotsById.size()))) + return NULL; + + return s_allSlotsById[slotId]; +} + +//---------------------------------------------------------------------- + +std::vector const & CollectionsDataTable::getAllTitleableSlots() +{ + return s_allTitleableSlots; +} + +//---------------------------------------------------------------------- + +CollectionsDataTable::CollectionInfoSlot const * CollectionsDataTable::isASlotTitle(std::string const & titleName) +{ + std::map::const_iterator iterFind = s_allSlotTitles.find(titleName); + if (iterFind != s_allSlotTitles.end()) + return iterFind->second; + + return NULL; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +std::vector const & CollectionsDataTable::getSlotsInCollection(std::string const & collectionName) +{ + static std::vector empty; + + std::map >::const_iterator iterFind = s_slotsInCollection.find(collectionName); + if (iterFind != s_slotsInCollection.end()) + return iterFind->second; + + return empty; +} + +//---------------------------------------------------------------------- + +std::vector const & CollectionsDataTable::getAllTitleableCollections() +{ + return s_allTitleableCollections; +} + +//---------------------------------------------------------------------- + +CollectionsDataTable::CollectionInfoCollection const * CollectionsDataTable::isACollectionTitle(std::string const & titleName) +{ + std::map::const_iterator iterFind = s_allCollectionTitles.find(titleName); + if (iterFind != s_allCollectionTitles.end()) + return iterFind->second; + + return NULL; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +std::map const & CollectionsDataTable::getAllServerFirstCollections() +{ + return s_allServerFirstCollections; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +CollectionsDataTable::CollectionInfoCollection const * CollectionsDataTable::getCollectionByName(std::string const & collectionName) +{ + std::map::const_iterator iterFind = s_allCollectionsByName.find(collectionName); + if (iterFind != s_allCollectionsByName.end()) + return iterFind->second; + + return NULL; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +std::vector const & CollectionsDataTable::getSlotsInPage(std::string const & pageName) +{ + static std::vector empty; + + std::map >::const_iterator iterFind = s_slotsInPage.find(pageName); + if (iterFind != s_slotsInPage.end()) + return iterFind->second; + + return empty; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +std::vector const & CollectionsDataTable::getCollectionsInPage(std::string const & pageName) +{ + static std::vector empty; + + std::map >::const_iterator iterFind = s_collectionsInPage.find(pageName); + if (iterFind != s_collectionsInPage.end()) + return iterFind->second; + + return empty; +} + +//---------------------------------------------------------------------- + +std::vector const & CollectionsDataTable::getAllTitleablePages() +{ + return s_allTitleablePages; +} + +//---------------------------------------------------------------------- + +CollectionsDataTable::CollectionInfoPage const * CollectionsDataTable::isAPageTitle(std::string const & titleName) +{ + std::map::const_iterator iterFind = s_allPageTitles.find(titleName); + if (iterFind != s_allPageTitles.end()) + return iterFind->second; + + return NULL; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +CollectionsDataTable::CollectionInfoPage const * CollectionsDataTable::getPageByName(std::string const & pageName) +{ + std::map::const_iterator iterFind = s_allPagesByName.find(pageName); + if (iterFind != s_allPagesByName.end()) + return iterFind->second; + + return NULL; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +std::vector const & CollectionsDataTable::getSlotsInBook(std::string const & bookName) +{ + static std::vector empty; + + std::map >::const_iterator iterFind = s_slotsInBook.find(bookName); + if (iterFind != s_slotsInBook.end()) + return iterFind->second; + + return empty; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +std::vector const & CollectionsDataTable::getCollectionsInBook(std::string const & bookName) +{ + static std::vector empty; + + std::map >::const_iterator iterFind = s_collectionsInBook.find(bookName); + if (iterFind != s_collectionsInBook.end()) + return iterFind->second; + + return empty; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +std::vector const & CollectionsDataTable::getPagesInBook(std::string const & bookName) +{ + static std::vector empty; + + std::map >::const_iterator iterFind = s_pagesInBook.find(bookName); + if (iterFind != s_pagesInBook.end()) + return iterFind->second; + + return empty; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +std::vector const & CollectionsDataTable::getAllBooks() +{ + return s_allBooks; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +CollectionsDataTable::CollectionInfoBook const * CollectionsDataTable::getBookByName(std::string const & bookName) +{ + std::map::const_iterator iterFind = s_allBooksByName.find(bookName); + if (iterFind != s_allBooksByName.end()) + return iterFind->second; + + return NULL; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +std::vector const & CollectionsDataTable::getSlotsInCategory(std::string const & categoryName) +{ + static std::vector empty; + + std::map >::const_iterator iterFind = s_slotsInCategory.find(categoryName); + if (iterFind != s_slotsInCategory.end()) + return iterFind->second; + + return empty; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +std::vector const & CollectionsDataTable::getSlotsInCategoryByCollection(std::string const & collectionName, std::string const & categoryName) +{ + static std::vector empty; + + std::map, std::vector >::const_iterator iterFind = s_slotsInCategoryByCollection.find(std::make_pair(collectionName, categoryName)); + if (iterFind != s_slotsInCategoryByCollection.end()) + return iterFind->second; + + return empty; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +std::vector const & CollectionsDataTable::getSlotsInCategoryByPage(std::string const & pageName, std::string const & categoryName) +{ + static std::vector empty; + + std::map, std::vector >::const_iterator iterFind = s_slotsInCategoryByPage.find(std::make_pair(pageName, categoryName)); + if (iterFind != s_slotsInCategoryByPage.end()) + return iterFind->second; + + return empty; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +std::vector const & CollectionsDataTable::getSlotsInCategoryByBook(std::string const & bookName, std::string const & categoryName) +{ + static std::vector empty; + + std::map, std::vector >::const_iterator iterFind = s_slotsInCategoryByBook.find(std::make_pair(bookName, categoryName)); + if (iterFind != s_slotsInCategoryByBook.end()) + return iterFind->second; + + return empty; +} + +//---------------------------------------------------------------------- + +std::set const & CollectionsDataTable::getAllSlotCategoriesInCollection(std::string const & collectionName) +{ + static std::set empty; + + std::map >::const_iterator iterFind = s_slotCategoriesByCollection.find(collectionName); + if (iterFind != s_slotCategoriesByCollection.end()) + return iterFind->second; + + return empty; +} + +//---------------------------------------------------------------------- + +std::set const & CollectionsDataTable::getAllSlotCategoriesInPage(std::string const & pageName) +{ + static std::set empty; + + std::map >::const_iterator iterFind = s_slotCategoriesByPage.find(pageName); + if (iterFind != s_slotCategoriesByPage.end()) + return iterFind->second; + + return empty; +} + +//---------------------------------------------------------------------- + +std::set const & CollectionsDataTable::getAllSlotCategoriesInBook(std::string const & bookName) +{ + static std::set empty; + + std::map >::const_iterator iterFind = s_slotCategoriesByBook.find(bookName); + if (iterFind != s_slotCategoriesByBook.end()) + return iterFind->second; + + return empty; +} + +//---------------------------------------------------------------------- + +std::set const & CollectionsDataTable::getAllSlotCategories() +{ + return s_slotCategories; +} + +//---------------------------------------------------------------------- + +Unicode::String CollectionsDataTable::localizeCollectionName(std::string const & name) +{ + return StringId("collection_n", name).localize(); +} + +//---------------------------------------------------------------------- + +Unicode::String CollectionsDataTable::localizeCollectionDescription(std::string const & name) +{ + return StringId("collection_d", name).localize(); +} + +//---------------------------------------------------------------------- + +Unicode::String CollectionsDataTable::localizeCollectionTitle(std::string const & name) +{ + return StringId("collection_title", name).localize(); +} + +//---------------------------------------------------------------------- + +void CollectionsDataTable::setServerFirstData(std::set, std::pair > > const & collectionServerFirst) +{ + // clear all "server first" info + for (std::map::const_iterator iter = s_allServerFirstCollections.begin(); iter != s_allServerFirstCollections.end(); ++iter) + { + time_t * serverFirstClaimTime = const_cast(&(iter->second->serverFirstClaimTime)); + NetworkId * serverFirstClaimantId = const_cast(&(iter->second->serverFirstClaimantId)); + Unicode::String * serverFirstClaimantName = const_cast(&(iter->second->serverFirstClaimantName)); + + *serverFirstClaimTime = 0; + *serverFirstClaimantId = NetworkId::cms_invalid; + serverFirstClaimantName->clear(); + } + + // set all "server first" info + for (std::set, std::pair > >::const_iterator iter2 = collectionServerFirst.begin(); iter2 != collectionServerFirst.end(); ++iter2) + { + std::map::const_iterator iterFind = s_allServerFirstCollections.find(iter2->first.second); + if (iterFind != s_allServerFirstCollections.end()) + { + time_t * serverFirstClaimTime = const_cast(&(iterFind->second->serverFirstClaimTime)); + NetworkId * serverFirstClaimantId = const_cast(&(iterFind->second->serverFirstClaimantId)); + Unicode::String * serverFirstClaimantName = const_cast(&(iterFind->second->serverFirstClaimantName)); + + *serverFirstClaimTime = static_cast(iter2->first.first); + *serverFirstClaimantId = iter2->second.first; + *serverFirstClaimantName = iter2->second.second; + } + } +} + +//---------------------------------------------------------------------- + +char const * CollectionsDataTable::getShowIfNotYetEarnedTypeString(ShowIfNotYetEarnedType const showIfNotYetEarned) +{ + if (showIfNotYetEarned == SE_gray) + return "gray"; + else if (showIfNotYetEarned == SE_unknown) + return "unknown"; + + return "none"; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/CollectionsDataTable.h b/engine/shared/library/sharedGame/src/shared/core/CollectionsDataTable.h new file mode 100644 index 00000000..64537442 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/CollectionsDataTable.h @@ -0,0 +1,193 @@ +// ====================================================================== +// +// CollectionsDataTable.h +// Copyright 2006 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#ifndef INCLUDED_CollectionsDataTable_H +#define INCLUDED_CollectionsDataTable_H + +#include "sharedFoundation/NetworkId.h" + +#include + +// ====================================================================== + +class CollectionsDataTable // static class +{ +public: + static void install(); + static void remove(); + + enum ShowIfNotYetEarnedType + { + SE_gray, + SE_unknown, + SE_none + }; + + class CollectionInfoBook + { + public: + CollectionInfoBook(std::string const & pName, std::string const & pIcon, ShowIfNotYetEarnedType pShowIfNotYetEarned, bool pHidden) : + name(pName), icon(pIcon), showIfNotYetEarned(pShowIfNotYetEarned), hidden(pHidden) {}; + + std::string const name; + std::string const icon; + ShowIfNotYetEarnedType const showIfNotYetEarned; + bool const hidden; + + private: + CollectionInfoBook(); + CollectionInfoBook(CollectionInfoBook const &); + CollectionInfoBook &operator =(CollectionInfoBook const &); + }; + + class CollectionInfoPage + { + public: + CollectionInfoPage(std::string const & pName, std::string const & pIcon, ShowIfNotYetEarnedType pShowIfNotYetEarned, bool pHidden, std::vector const & pTitles, CollectionInfoBook const & pBook) : + name(pName), icon(pIcon), showIfNotYetEarned(pShowIfNotYetEarned), hidden(pHidden), titles(pTitles), book(pBook) {}; + + std::string const name; + std::string const icon; + ShowIfNotYetEarnedType const showIfNotYetEarned; + bool const hidden; + std::vector const titles; + + CollectionInfoBook const & book; + + private: + CollectionInfoPage(); + CollectionInfoPage(CollectionInfoPage const &); + CollectionInfoPage &operator =(CollectionInfoPage const &); + }; + + class CollectionInfoCollection + { + public: + CollectionInfoCollection(std::string const & cName, std::string const & pIcon, ShowIfNotYetEarnedType pShowIfNotYetEarned, bool pHidden, stdvector::fwd const & pCategories, std::vector const & pTitles, bool pNoReward, bool pTrackServerFirst, CollectionInfoPage const & pPage) : + name(cName), icon(pIcon), showIfNotYetEarned(pShowIfNotYetEarned), hidden(pHidden), categories(pCategories), titles(pTitles), noReward(pNoReward), trackServerFirst(pTrackServerFirst), serverFirstClaimTime(0), serverFirstClaimantId(), serverFirstClaimantName(), page(pPage) {}; + + std::string const name; + std::string const icon; + ShowIfNotYetEarnedType const showIfNotYetEarned; + bool const hidden; + std::vector const categories; + std::vector const titles; + bool const noReward; + bool const trackServerFirst; + time_t const serverFirstClaimTime; + NetworkId const serverFirstClaimantId; + Unicode::String const serverFirstClaimantName; + + CollectionInfoPage const & page; + + private: + CollectionInfoCollection(); + CollectionInfoCollection(CollectionInfoCollection const &); + CollectionInfoCollection &operator =(CollectionInfoCollection const &); + }; + + class CollectionInfoSlot + { + friend class CollectionsDataTable; + + public: + CollectionInfoSlot(std::string const & pName, std::string const & pIcon, ShowIfNotYetEarnedType pShowIfNotYetEarned, bool pHidden, bool pNotifyScriptOnModify, int pSlotIdIndex, int pBeginSlotId, int pAbsoluteBeginSlotId, int pEndSlotId, int pAbsoluteEndSlotId, unsigned long pMaxSlotValue, unsigned long pMaxValueForNumBits, stdvector::fwd const & pCategories, stdvector::fwd const & pPrereqs, std::string const & pMusic, std::vector const & pTitles, CollectionInfoCollection const & pCollection) : + name(pName), icon(pIcon), showIfNotYetEarned(pShowIfNotYetEarned), hidden(pHidden), notifyScriptOnModify(pNotifyScriptOnModify), slotIdIndex(pSlotIdIndex), beginSlotId(pBeginSlotId), absoluteBeginSlotId(pAbsoluteBeginSlotId), endSlotId(pEndSlotId), absoluteEndSlotId(pAbsoluteEndSlotId), counterTypeSlot(pEndSlotId > 0), maxSlotValue(pMaxSlotValue), maxValueForNumBits(pMaxValueForNumBits), categories(pCategories), prereqsPtr(), music(pMusic), titles(pTitles), collection(pCollection), prereqs(pPrereqs) {}; + + std::string const name; + std::string const icon; + ShowIfNotYetEarnedType const showIfNotYetEarned; + bool const hidden; + bool const notifyScriptOnModify; + + int const slotIdIndex; + int const beginSlotId; + int const absoluteBeginSlotId; + int const endSlotId; + int const absoluteEndSlotId; + bool const counterTypeSlot; + unsigned long const maxSlotValue; + + // for bit-type slot, 1 + // for counter-type slot, the maximum value that can be stored in the number of bits (endSlotId - beginSlotId + 1) + unsigned long const maxValueForNumBits; + + std::vector const categories; + std::vector const prereqsPtr; + std::string const music; + std::vector const titles; + CollectionInfoCollection const & collection; + + private: + std::vector const prereqs; + + CollectionInfoSlot(); + CollectionInfoSlot(CollectionInfoSlot const &); + CollectionInfoSlot &operator =(CollectionInfoSlot const &); + }; + + // *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** + // owned by the caller, they are owned/managed/freed by this class + + // slots + static CollectionsDataTable::CollectionInfoSlot const * getSlotByName(std::string const & slotName); + static CollectionsDataTable::CollectionInfoSlot const * getSlotByBeginSlotId(int slotId); + static std::vector const & getAllTitleableSlots(); + static CollectionsDataTable::CollectionInfoSlot const * isASlotTitle(std::string const & titleName); + + // collections + static stdvector::fwd const & getSlotsInCollection(std::string const & collectionName); + static std::vector const & getAllTitleableCollections(); + static CollectionsDataTable::CollectionInfoCollection const * isACollectionTitle(std::string const & titleName); + static stdmap::fwd const & getAllServerFirstCollections(); + static CollectionsDataTable::CollectionInfoCollection const * getCollectionByName(std::string const & collectionName); + + // pages + static stdvector::fwd const & getSlotsInPage(std::string const & pageName); + static stdvector::fwd const & getCollectionsInPage(std::string const & pageName); + static std::vector const & getAllTitleablePages(); + static CollectionsDataTable::CollectionInfoPage const * isAPageTitle(std::string const & titleName); + static CollectionsDataTable::CollectionInfoPage const * getPageByName(std::string const & pageName); + + // books + static stdvector::fwd const & getSlotsInBook(std::string const & bookName); + static stdvector::fwd const & getCollectionsInBook(std::string const & bookName); + static stdvector::fwd const & getPagesInBook(std::string const & bookName); + static stdvector::fwd const & getAllBooks(); + static CollectionsDataTable::CollectionInfoBook const * getBookByName(std::string const & bookName); + + // categories + static stdvector::fwd const & getSlotsInCategory(std::string const & categoryName); + static stdvector::fwd const & getSlotsInCategoryByCollection(std::string const & collectionName, std::string const & categoryName); + static stdvector::fwd const & getSlotsInCategoryByPage(std::string const & pageName, std::string const & categoryName); + static stdvector::fwd const & getSlotsInCategoryByBook(std::string const & bookName, std::string const & categoryName); + + static stdset::fwd const & getAllSlotCategoriesInCollection(std::string const & collectionName); + static stdset::fwd const & getAllSlotCategoriesInPage(std::string const & pageName); + static stdset::fwd const & getAllSlotCategoriesInBook(std::string const & bookName); + static stdset::fwd const & getAllSlotCategories(); + + // misc + static Unicode::String localizeCollectionName(std::string const & name); + static Unicode::String localizeCollectionDescription(std::string const & name); + static Unicode::String localizeCollectionTitle(std::string const & name); + static char const * getShowIfNotYetEarnedTypeString(ShowIfNotYetEarnedType const showIfNotYetEarned); + + // "server first" processing + static void setServerFirstData(stdset, std::pair > >::fwd const & collectionServerFirst); + +private: // disabled + + CollectionsDataTable(); + CollectionsDataTable(CollectionsDataTable const &); + CollectionsDataTable &operator =(CollectionsDataTable const &); +}; + +// ====================================================================== + +#endif // INCLUDED_CollectionsDataTable_H diff --git a/engine/shared/library/sharedGame/src/shared/core/CommoditiesAdvancedSearchAttribute.cpp b/engine/shared/library/sharedGame/src/shared/core/CommoditiesAdvancedSearchAttribute.cpp new file mode 100644 index 00000000..585dbd1d --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/CommoditiesAdvancedSearchAttribute.cpp @@ -0,0 +1,366 @@ +// ====================================================================== +// +// CommoditiesAdvancedSearchAttribute.cpp +// Copyright 2006 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/CommoditiesAdvancedSearchAttribute.h" + +#include "sharedFoundation/Crc.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedGame/GameObjectTypes.h" +#include "sharedGame/SharedObjectTemplate.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" +#include "UnicodeUtils.h" + +#include + +// ====================================================================== + +namespace CommoditiesAdvancedSearchAttributeNamespace +{ + char const * const cs_advancedSearchAttributeDataTableName = "datatables/commodity/advanced_search_attribute.iff"; + + std::map > s_commoditiesAdvancedSearchAttributes; + std::map > s_searchAttributeNameAliases; + std::set s_gameObjectTypeNoChildInherit; +} + +using namespace CommoditiesAdvancedSearchAttributeNamespace; + +// ====================================================================== + +void CommoditiesAdvancedSearchAttribute::install() +{ + DataTable * table = DataTableManager::getTable(cs_advancedSearchAttributeDataTableName, true); + if (table) + { + int const columnGameObjectType = table->findColumnNumber("Game Object Type"); + int const columnSearchAttributeName = table->findColumnNumber("Search Attribute Name"); + int const columnSearchAttributeDataType = table->findColumnNumber("Search Attribute Data Type"); + + FATAL((columnGameObjectType < 0), ("column \"Game Object Type\" not found in %s", cs_advancedSearchAttributeDataTableName)); + FATAL((columnSearchAttributeName < 0), ("column \"Search Attribute Name\" not found in %s", cs_advancedSearchAttributeDataTableName)); + FATAL((columnSearchAttributeDataType < 0), ("column \"Search Attribute Data Type\" not found in %s", cs_advancedSearchAttributeDataTableName)); + + // the can be a variable number of "Default Search Value" columns, as long as the columns are + // named "Default Search Value 1", "Default Search Value 2", "Default Search Value 3", and so on + std::vector columnDefaultSearchValue; + char buffer[128]; + int columnNumber; + for (int i = 1; i <= 1000000000; ++i) + { + snprintf(buffer, sizeof(buffer)-1, "Default Search Value %d", i); + buffer[sizeof(buffer)-1] = '\0'; + + columnNumber = table->findColumnNumber(buffer); + if (columnNumber < 0) + break; + + columnDefaultSearchValue.push_back(columnNumber); + } + + int currentGameObjectType = 0; + std::string currentGameObjectTypeString; + + int const numRows = table->getNumRows(); + std::string gameObjectType, searchAttributeName; + uint32 searchAttributeNameCrc; + int searchAttributeDataType; + std::string defaultSearchValue; + std::set defaultSearchValueList; + std::map enumValueAliasList; + std::set > excludedSearchAttribute; + std::map > commoditiesAdvancedSearchAttributesCrc; + CommoditiesAdvancedSearchAttribute::SearchAttribute const * searchAttribute; + Unicode::UnicodeStringVector tokens; + std::string alias; + std::map::const_iterator iterFindAlias; + for (int i = 0; i < numRows; ++i) + { + gameObjectType = Unicode::getTrim(table->getStringValue(columnGameObjectType, i)); + FATAL((gameObjectType != table->getStringValue(columnGameObjectType, i)), ("%s, row %d: gameObjectType (%s) has leading/trailing blanks(s)", cs_advancedSearchAttributeDataTableName, (i+3), gameObjectType.c_str())); + + searchAttributeName = Unicode::getTrim(table->getStringValue(columnSearchAttributeName, i)); + FATAL((searchAttributeName != table->getStringValue(columnSearchAttributeName, i)), ("%s, row %d: searchAttributeName (%s) has leading/trailing blanks(s)", cs_advancedSearchAttributeDataTableName, (i+3), searchAttributeName.c_str())); + + if (!gameObjectType.empty()) + { + currentGameObjectTypeString = gameObjectType; + currentGameObjectType = GameObjectTypes::getGameObjectType(gameObjectType); + FATAL((currentGameObjectType <= 0), ("%s, row %d: invalid game object type (%s)", cs_advancedSearchAttributeDataTableName, (i+3), gameObjectType.c_str())); + } + + FATAL((searchAttributeName.empty() && gameObjectType.empty()), ("%s, row %d: no search attribute specified", cs_advancedSearchAttributeDataTableName, (i+3))); + FATAL((currentGameObjectType <= 0), ("%s, row %d: search attribute (%s) specified without corresponding game object type", cs_advancedSearchAttributeDataTableName, (i+3), searchAttributeName.c_str())); + FATAL((searchAttributeName.empty() && !GameObjectTypes::isSubType(currentGameObjectType)), ("%s, row %d: no search attribute specified", cs_advancedSearchAttributeDataTableName, (i+3))); + + // this means that this (base) game object type's search attributes + // should not be inherited by any of the derived game object type + if (searchAttributeName == "no child inherit") + { + FATAL((GameObjectTypes::isSubType(currentGameObjectType)), ("%s, row %d: \"no child inherit\" qualifier for game object type (%d, %s) can only be used for a base game object type", cs_advancedSearchAttributeDataTableName, (i+3), currentGameObjectType, GameObjectTypes::getCanonicalName(currentGameObjectType).c_str())); + + s_gameObjectTypeNoChildInherit.insert(currentGameObjectType); + + searchAttributeName.clear(); + } + // this means the derived game object type does not want to + // include this search attribute from the parent game object type + else if (searchAttributeName.find("exclude ") == 0) + { + FATAL((!GameObjectTypes::isSubType(currentGameObjectType)), ("%s, row %d: \"exclude\" qualifier for search attribute (%s) cannot be used with a base game object type", cs_advancedSearchAttributeDataTableName, (i+3), searchAttributeName.c_str())); + + searchAttributeName = searchAttributeName.substr(8); + if (!searchAttributeName.empty()) + excludedSearchAttribute.insert(std::make_pair(currentGameObjectType, searchAttributeName)); + + searchAttributeName.clear(); + } + else + { + // handle search attribute name alias + tokens.clear(); + if (Unicode::tokenize(Unicode::narrowToWide(searchAttributeName), tokens, NULL, NULL) && (tokens.size() > 1)) + { + // the first value is the search attribute name to display + searchAttributeName = Unicode::wideToNarrow(tokens[0]); + + // the other values will be aliased by the first value + for (size_t j = 1, size = tokens.size(); j < size; ++j) + { + alias = Unicode::wideToNarrow(tokens[j]); + + FATAL((getSearchAttributeForGameObjectType(currentGameObjectType).count(alias) > 0), ("%s, row %d: aliased search attribute (%s) for game object type (%s) has already been defined as a search attribute", cs_advancedSearchAttributeDataTableName, (i+3), alias.c_str(), currentGameObjectTypeString.c_str())); + + iterFindAlias = getSearchAttributeNameAliasesForGameObjectType(currentGameObjectType).find(alias); + FATAL((iterFindAlias != getSearchAttributeNameAliasesForGameObjectType(currentGameObjectType).end()), ("%s, row %d: aliased search attribute (%s) for game object type (%s) has already been defined as an alias for search attribute (%s)", cs_advancedSearchAttributeDataTableName, (i+3), alias.c_str(), currentGameObjectTypeString.c_str(), iterFindAlias->second.c_str())); + + s_searchAttributeNameAliases[currentGameObjectType].insert(std::make_pair(alias, searchAttributeName)); + } + } + } + + // if necessary, insert new entries for the game object type + std::map & attributes = s_commoditiesAdvancedSearchAttributes[currentGameObjectType]; + std::map & attributesCrc = commoditiesAdvancedSearchAttributesCrc[currentGameObjectType]; + if (!searchAttributeName.empty()) + { + FATAL((attributes.count(searchAttributeName) > 0), ("%s, row %d: duplicate search attribute (%s) for game object type (%s)", cs_advancedSearchAttributeDataTableName, (i+3), searchAttributeName.c_str(), currentGameObjectTypeString.c_str())); + + iterFindAlias = getSearchAttributeNameAliasesForGameObjectType(currentGameObjectType).find(searchAttributeName); + FATAL((iterFindAlias != getSearchAttributeNameAliasesForGameObjectType(currentGameObjectType).end()), ("%s, row %d: search attribute (%s) for game object type (%s) has already been defined as an alias for search attribute (%s)", cs_advancedSearchAttributeDataTableName, (i+3), searchAttributeName.c_str(), currentGameObjectTypeString.c_str(), iterFindAlias->second.c_str())); + + searchAttributeNameCrc = Crc::calculate(searchAttributeName.c_str()); + FATAL((attributesCrc.count(searchAttributeNameCrc) > 0), ("%s, row %d: search attribute (%s) for game object type (%s) has the same crc value as search attribute (%s)", cs_advancedSearchAttributeDataTableName, (i+3), searchAttributeName.c_str(), currentGameObjectTypeString.c_str(), attributesCrc[searchAttributeNameCrc]->attributeName.c_str())); + + searchAttributeDataType = table->getIntValue(columnSearchAttributeDataType, i); + FATAL(((searchAttributeDataType < 0) || (searchAttributeDataType == static_cast(SADT_unknown)) || (searchAttributeDataType >= static_cast(SADT_LAST_ENUM))), ("%s, row %d: invalid search attribute data type (%d)", cs_advancedSearchAttributeDataTableName, (i+3), searchAttributeDataType)); + + // if search attribute is string or enum, read list of default search value, if any + defaultSearchValueList.clear(); + enumValueAliasList.clear(); + if ((static_cast(searchAttributeDataType) == SADT_string) || (static_cast(searchAttributeDataType) == SADT_enum)) + { + for (std::vector::const_iterator iterColumnDefaultSearchValue = columnDefaultSearchValue.begin(); iterColumnDefaultSearchValue != columnDefaultSearchValue.end(); ++iterColumnDefaultSearchValue) + { + defaultSearchValue = Unicode::getTrim(table->getStringValue(*iterColumnDefaultSearchValue, i)); + FATAL((defaultSearchValue != table->getStringValue(*iterColumnDefaultSearchValue, i)), ("%s, row %d: defaultSearchValue (%s) has leading/trailing blanks(s)", cs_advancedSearchAttributeDataTableName, (i+3), defaultSearchValue.c_str())); + + if (!defaultSearchValue.empty()) + { + if (static_cast(searchAttributeDataType) == SADT_enum) + { + // for enum, parse out the aliases (if any) for the enum value + tokens.clear(); + if (Unicode::tokenize(Unicode::narrowToWide(defaultSearchValue), tokens, NULL, NULL) && !tokens.empty()) + { +#ifdef _WIN32 +#ifdef _DEBUG + Unicode::String const enumDisplayString(StringId::decodeString(tokens[0])); +#endif +#endif + // the first value is the enum value to display + std::string const aliasMaster(Unicode::wideToNarrow(tokens[0])); + defaultSearchValueList.insert(aliasMaster); + + // the other values will be aliased by the first value + for (size_t j = 1, size = tokens.size(); j < size; ++j) + { + std::string narrowStr(Unicode::wideToNarrow(tokens[j])); + if (narrowStr == "<<>>") + narrowStr = " "; + + enumValueAliasList[narrowStr] = aliasMaster; + +#ifdef _WIN32 +#ifdef _DEBUG + Unicode::String const enumAliasDisplayString(StringId::decodeString(Unicode::narrowToWide(narrowStr))); + DEBUG_WARNING((enumDisplayString != enumAliasDisplayString), ("%s, row %d: enum alias (%s) (%s) has a different display string than the alias master (%s) (%s), so may not need to be aliased", cs_advancedSearchAttributeDataTableName, (i+3), narrowStr.c_str(), Unicode::wideToNarrow(enumAliasDisplayString).c_str(), aliasMaster.c_str(), Unicode::wideToNarrow(enumDisplayString).c_str())); +#endif +#endif + } + } + } + else + { + defaultSearchValueList.insert(defaultSearchValue); + } + } + } + } + + FATAL(((static_cast(searchAttributeDataType) == SADT_enum) && defaultSearchValueList.empty()), ("%s, row %d: no default value specified for enum search attribute (%s)", cs_advancedSearchAttributeDataTableName, (i+3), searchAttributeName.c_str())); + + // for factory crate object_type attribute, only allow an enum + // alias to represent a single enum value, so that we can support + // search by attribute on the item contained inside the crate + if ((currentGameObjectType == SharedObjectTemplate::GOT_misc_factory_crate) && (searchAttributeName == "object_type") && !enumValueAliasList.empty()) + { + std::set enumAliasCount; + for (std::map::const_iterator iterAlias = enumValueAliasList.begin(); iterAlias != enumValueAliasList.end(); ++iterAlias) + { + FATAL((enumAliasCount.count(iterAlias->second) > 0), ("%s, row %d: for factory crate object_type attribute, an enum alias (%s) can only represent a single enum value", cs_advancedSearchAttributeDataTableName, (i+3), iterAlias->second.c_str())); + + enumAliasCount.insert(iterAlias->second); + } + } + + searchAttribute = new SearchAttribute(searchAttributeName, searchAttributeNameCrc, static_cast(searchAttributeDataType), defaultSearchValueList, enumValueAliasList); + attributes[searchAttributeName] = searchAttribute; + attributesCrc[searchAttributeNameCrc] = searchAttribute; + } + } + + DataTableManager::close(cs_advancedSearchAttributeDataTableName); + + // copy attributes from parent game object type into child game object type + for (std::map >::iterator iterGameObjectType = s_commoditiesAdvancedSearchAttributes.begin(); iterGameObjectType != s_commoditiesAdvancedSearchAttributes.end(); ++iterGameObjectType) + { + if (!GameObjectTypes::isSubType(iterGameObjectType->first)) + continue; + + // parent game object type doesn't allow child game object type to inherit search attribute + if (!allowChildGameObjectTypeToInheritSearchAttribute(GameObjectTypes::getMaskedType(iterGameObjectType->first))) + continue; + + std::map >::const_iterator const iterParentGameObjectType = s_commoditiesAdvancedSearchAttributes.find(GameObjectTypes::getMaskedType(iterGameObjectType->first)); + if (iterParentGameObjectType != s_commoditiesAdvancedSearchAttributes.end()) + { + std::map & attributesCrc = commoditiesAdvancedSearchAttributesCrc[iterGameObjectType->first]; + + for (std::map::const_iterator iterParentAttribute = iterParentGameObjectType->second.begin(); iterParentAttribute != iterParentGameObjectType->second.end(); ++iterParentAttribute) + { + FATAL((iterGameObjectType->second.count(iterParentAttribute->second->attributeName) > 0), ("search attribute (%s) for game object type (%s) is already defined in parent game object type (%s)", iterParentAttribute->second->attributeName.c_str(), GameObjectTypes::getCanonicalName(iterGameObjectType->first).c_str(), GameObjectTypes::getCanonicalName(iterParentGameObjectType->first).c_str())); + FATAL((attributesCrc.count(iterParentAttribute->second->attributeNameCrc) > 0), ("search attribute (%s) for parent game object type (%s) has the same crc value as search attribute (%s) in the game object type (%s)", iterParentAttribute->second->attributeName.c_str(), GameObjectTypes::getCanonicalName(iterParentGameObjectType->first).c_str(), attributesCrc[iterParentAttribute->second->attributeNameCrc]->attributeName.c_str(), GameObjectTypes::getCanonicalName(iterGameObjectType->first).c_str())); + + if (excludedSearchAttribute.count(std::make_pair(iterGameObjectType->first, iterParentAttribute->second->attributeName)) < 1) + { + iterGameObjectType->second[iterParentAttribute->second->attributeName] = iterParentAttribute->second; + attributesCrc[iterParentAttribute->second->attributeNameCrc] = iterParentAttribute->second; + } + } + } + + std::map >::const_iterator const iterParentAttributeNameAliases = s_searchAttributeNameAliases.find(GameObjectTypes::getMaskedType(iterGameObjectType->first)); + if (iterParentAttributeNameAliases != s_searchAttributeNameAliases.end()) + { + std::map & alias = s_searchAttributeNameAliases[iterGameObjectType->first]; + for (std::map::const_iterator iterAlias = iterParentAttributeNameAliases->second.begin(); iterAlias != iterParentAttributeNameAliases->second.end(); ++iterAlias) + { + alias.insert(*iterAlias); + } + } + } + } + else + { + FATAL(true, ("commodities advanced search attribute datatable %s not found", cs_advancedSearchAttributeDataTableName)); + } + + ExitChain::add(remove, "CommoditiesAdvancedSearchAttribute::remove"); +} + +//---------------------------------------------------------------------- + +void CommoditiesAdvancedSearchAttribute::remove() +{ + std::set allSearchAttributes; + + for (std::map >::const_iterator iterGameObjectType = s_commoditiesAdvancedSearchAttributes.begin(); iterGameObjectType != s_commoditiesAdvancedSearchAttributes.end(); ++iterGameObjectType) + { + for (std::map::const_iterator iterAttribute = iterGameObjectType->second.begin(); iterAttribute != iterGameObjectType->second.end(); ++iterAttribute) + { + allSearchAttributes.insert(iterAttribute->second); + } + } + + s_commoditiesAdvancedSearchAttributes.clear(); + + for (std::set::const_iterator iterAttribute = allSearchAttributes.begin(); iterAttribute != allSearchAttributes.end(); ++iterAttribute) + { + delete *iterAttribute; + } + + s_searchAttributeNameAliases.clear(); + + s_gameObjectTypeNoChildInherit.clear(); +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +std::map const & CommoditiesAdvancedSearchAttribute::getSearchAttributeForGameObjectType(int gameObjectType) +{ + static std::map const empty; + + std::map >::const_iterator const iterFind = s_commoditiesAdvancedSearchAttributes.find(gameObjectType); + if (iterFind != s_commoditiesAdvancedSearchAttributes.end()) + return iterFind->second; + + return empty; +} + +//---------------------------------------------------------------------- +// *****NOTE***** the pointers returned by these functions *****ARE NOT!!!***** +// owned by the caller, they are owned/managed/freed by this class + +CommoditiesAdvancedSearchAttribute::SearchAttribute const * CommoditiesAdvancedSearchAttribute::getSearchAttribute(int gameObjectType, std::string const & attributeName) +{ + std::map >::const_iterator const iterFindGot = s_commoditiesAdvancedSearchAttributes.find(gameObjectType); + if (iterFindGot != s_commoditiesAdvancedSearchAttributes.end()) + { + std::map::const_iterator const iterFindAttribute = iterFindGot->second.find(attributeName); + if (iterFindAttribute != iterFindGot->second.end()) + return iterFindAttribute->second; + } + + return NULL; +} + +//---------------------------------------------------------------------- + +std::map const & CommoditiesAdvancedSearchAttribute::getSearchAttributeNameAliasesForGameObjectType(int gameObjectType) +{ + static std::map const empty; + + std::map >::const_iterator const iterFind = s_searchAttributeNameAliases.find(gameObjectType); + if (iterFind != s_searchAttributeNameAliases.end()) + return iterFind->second; + + return empty; +} + +//---------------------------------------------------------------------- + +bool CommoditiesAdvancedSearchAttribute::allowChildGameObjectTypeToInheritSearchAttribute(int gameObjectType) +{ + return (s_gameObjectTypeNoChildInherit.count(gameObjectType) <= 0); +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/CommoditiesAdvancedSearchAttribute.h b/engine/shared/library/sharedGame/src/shared/core/CommoditiesAdvancedSearchAttribute.h new file mode 100644 index 00000000..5ae6ee30 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/CommoditiesAdvancedSearchAttribute.h @@ -0,0 +1,68 @@ +// ====================================================================== +// +// CommoditiesAdvancedSearchAttribute.h +// Copyright 2006 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#ifndef INCLUDED_CommoditiesAdvancedSearchAttribute_H +#define INCLUDED_CommoditiesAdvancedSearchAttribute_H + +#include +#include +#include + +// ====================================================================== + +class CommoditiesAdvancedSearchAttribute // static class +{ +public: + static void install(); + static void remove(); + + enum SearchAttributeDataType + { + SADT_unknown = 0, + SADT_int, + SADT_float, + SADT_string, + SADT_enum, + SADT_LAST_ENUM + }; + + class SearchAttribute + { + public: + SearchAttribute(std::string const & pAttributeName, uint32 pAttributeNameCrc, SearchAttributeDataType const pAttributeDataType, std::set const & pDefaultSearchValueList, std::map const & pEnumValueAliasList) : + attributeName(pAttributeName), attributeNameCrc(pAttributeNameCrc), attributeDataType(pAttributeDataType), defaultSearchValueList(pDefaultSearchValueList), enumValueAliasList(pEnumValueAliasList) {}; + + std::string const attributeName; + uint32 const attributeNameCrc; + SearchAttributeDataType const attributeDataType; + std::set const defaultSearchValueList; + std::map const enumValueAliasList; + + private: + SearchAttribute(); + SearchAttribute(SearchAttribute const &); + SearchAttribute &operator =(SearchAttribute const &); + }; + + static stdmap::fwd const & getSearchAttributeForGameObjectType(int gameObjectType); + static CommoditiesAdvancedSearchAttribute::SearchAttribute const * getSearchAttribute(int gameObjectType, std::string const & attributeName); + + static stdmap::fwd const & getSearchAttributeNameAliasesForGameObjectType(int gameObjectType); + + static bool allowChildGameObjectTypeToInheritSearchAttribute(int gameObjectType); + +private: // disabled + + CommoditiesAdvancedSearchAttribute(); + CommoditiesAdvancedSearchAttribute(CommoditiesAdvancedSearchAttribute const &); + CommoditiesAdvancedSearchAttribute &operator =(CommoditiesAdvancedSearchAttribute const &); +}; + +// ====================================================================== + +#endif // INCLUDED_CommoditiesAdvancedSearchAttribute_H diff --git a/engine/shared/library/sharedGame/src/shared/core/ConfigSharedGame.cpp b/engine/shared/library/sharedGame/src/shared/core/ConfigSharedGame.cpp new file mode 100644 index 00000000..f5548552 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/ConfigSharedGame.cpp @@ -0,0 +1,176 @@ +//=================================================================== +// +// ConfigSharedGame.cpp +// copyright 2000, verant interactive +// +//=================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ConfigSharedGame.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFoundation/ConfigFile.h" +#include "sharedFoundation/Production.h" + +//=================================================================== + +namespace ConfigSharedGameNamespace +{ + bool ms_sample; + const char * ms_defaultLocale; + const char * ms_fontLocale; + bool ms_debugStringIds; + const char * ms_schematicGroupDataTable; + bool ms_displayBadStringIds; + int ms_maxCreatureSkillModBonus; + bool ms_imageDesignerVerboseOutput; + int ms_imageDesignerCosmeticSessionTimeSeconds; + int ms_imageDesignerPhysicalSessionTimeSeconds; + int ms_imageDesignerStatMigrationSessionTimeSeconds; + bool ms_fatalOnBadFormData; + bool ms_spamAsteroidGenerationData; + float ms_movementThresholdForActionValidation; +} + +using namespace ConfigSharedGameNamespace; + +//=================================================================== + +bool ConfigSharedGame::getSample () +{ + return ms_sample; +} + +//----------------------------------------------------------------- + +const char * ConfigSharedGame::getDefaultLocale() +{ + return ms_defaultLocale; +} + +//----------------------------------------------------------------- + +bool ConfigSharedGame::defaultLocaleIgnoresLAlt() +{ + if(strncmp("ja", ms_defaultLocale, 2) == 0) + return true; + return false; +} + +//----------------------------------------------------------------- + +const char * ConfigSharedGame::getFontLocale() +{ + return ms_fontLocale; +} + +//---------------------------------------------------------------------- + +bool ConfigSharedGame::getDebugStringIds () +{ + return ms_debugStringIds; +} + +//---------------------------------------------------------------------- + +const char * ConfigSharedGame::getSchematicGroupDataTable () +{ + return ms_schematicGroupDataTable; +} + +//---------------------------------------------------------------------- + +bool ConfigSharedGame::getDisplayBadStringIds () +{ + return ms_displayBadStringIds; +} + +//---------------------------------------------------------------------- + +bool ConfigSharedGame::getFatalOnBadFormData () +{ + return ms_fatalOnBadFormData; +} + +//---------------------------------------------------------------------- + +int ConfigSharedGame::getMaxCreatureSkillModBonus() +{ + return ms_maxCreatureSkillModBonus; +} + +//---------------------------------------------------------------------- + +bool ConfigSharedGame::getImageDesignerVerboseOutput() +{ + return ms_imageDesignerVerboseOutput; +} + +//---------------------------------------------------------------------- + +int ConfigSharedGame::getImageDesignerCosmeticSessionTimeSeconds() +{ + return ms_imageDesignerCosmeticSessionTimeSeconds; +} + +//---------------------------------------------------------------------- + +int ConfigSharedGame::getImageDesignerPhysicalSessionTimeSeconds() +{ + return ms_imageDesignerPhysicalSessionTimeSeconds; +} + +//---------------------------------------------------------------------- + +int ConfigSharedGame::getImageDesignerStatMigrationSessionTimeSeconds() +{ + return ms_imageDesignerStatMigrationSessionTimeSeconds; +} + +//---------------------------------------------------------------------- + +bool ConfigSharedGame::getSpamAsteroidGenerationData() +{ + return ms_spamAsteroidGenerationData; +} + +//---------------------------------------------------------------------- + +float ConfigSharedGame::getMovementThresholdForActionValidation() +{ + return ms_movementThresholdForActionValidation; +} + +//=================================================================== + +#define KEY_BOOL(a,b) (ms_ ## a = ConfigFile::getKeyBool("SharedGame", #a, b)) +#define KEY_INT(a,b) (ms_ ## a = ConfigFile::getKeyInt("SharedGame", #a, b)) +#define KEY_FLOAT(a,b) (ms_ ## a = ConfigFile::getKeyFloat("SharedGame", #a, b)) +#define KEY_STRING(a,b) (ms_ ## a = ConfigFile::getKeyString("SharedGame", #a, b)) + +//=================================================================== + +void ConfigSharedGame::install() +{ + InstallTimer const installTimer("ConfigSharedGame::install"); + + KEY_BOOL (sample, false); + KEY_STRING (defaultLocale, "en"); + KEY_STRING (fontLocale, "en"); + KEY_BOOL (debugStringIds, true); + KEY_STRING (schematicGroupDataTable, "datatables/crafting/schematic_group.iff"); + KEY_BOOL (fatalOnBadFormData, false); + KEY_BOOL (spamAsteroidGenerationData, false); + + bool defaultDisplayBadStringIds = true; + + KEY_BOOL (displayBadStringIds, defaultDisplayBadStringIds); + KEY_INT (maxCreatureSkillModBonus, 25); + KEY_BOOL (imageDesignerVerboseOutput, false); + KEY_INT (imageDesignerCosmeticSessionTimeSeconds, 0); + KEY_INT (imageDesignerPhysicalSessionTimeSeconds, 0); + KEY_INT (imageDesignerStatMigrationSessionTimeSeconds, 240); + KEY_FLOAT (movementThresholdForActionValidation, 0.5f); +} + +//=================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/ConfigSharedGame.h b/engine/shared/library/sharedGame/src/shared/core/ConfigSharedGame.h new file mode 100644 index 00000000..21ad23b4 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/ConfigSharedGame.h @@ -0,0 +1,44 @@ +//=================================================================== +// +// ConfigSharedGame.h +// copyright 2000, verant interactive +// +//=================================================================== + +#ifndef INCLUDED_ConfigSharedGame_H +#define INCLUDED_ConfigSharedGame_H + +//=================================================================== + +class ConfigSharedGame +{ +public: + + static void install (); + + static bool getSample (); + static const char * getDefaultLocale (); + static bool defaultLocaleIgnoresLAlt (); + static const char * getFontLocale (); + static bool getDebugStringIds (); + static const char * getSchematicGroupDataTable (); + static bool getDisplayBadStringIds (); + static int getMaxCreatureSkillModBonus(); + static bool getImageDesignerVerboseOutput(); + static int getImageDesignerCosmeticSessionTimeSeconds(); + static int getImageDesignerPhysicalSessionTimeSeconds(); + static int getImageDesignerStatMigrationSessionTimeSeconds(); + static bool getFatalOnBadFormData (); + static bool getSpamAsteroidGenerationData (); + static float getMovementThresholdForActionValidation (); + +private: + + ConfigSharedGame (); + ConfigSharedGame (const ConfigSharedGame&); + ConfigSharedGame& operator= (const ConfigSharedGame&); +}; + +//=================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/CraftingData.cpp b/engine/shared/library/sharedGame/src/shared/core/CraftingData.cpp new file mode 100644 index 00000000..ac84c697 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/CraftingData.cpp @@ -0,0 +1,224 @@ +//======================================================================== +// +// CraftingData.cpp +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/CraftingData.h" + +#include "localizationArchive/StringIdArchive.h" +#include "sharedGame/SharedObjectAttributes.h" +#include + +//---------------------------------------------------------------------- + +Crafting::SimpleIngredient::SimpleIngredient(const NetworkId & _ingredient, int _count, const NetworkId & _source, int _xpType) : +ingredient(_ingredient), +count(_count), +source(_source), +xpType(_xpType) +{ +} + +//---------------------------------------------------------------------- + +Crafting::IngredientSlot::IngredientSlot() : +ingredientType(IT_invalid), +name(), +ingredients(), +complexity(-1), +draftSlotOption(-1), +draftSlotIndex(-1) +{ +} + +//---------------------------------------------------------------------- + +Crafting::IngredientSlot::IngredientSlot(enum IngredientType _ingredientType, + const StringId & _name, + const std::vector slotIngredients, + const std::vector slotIngredientsCount, + float _complexity, + int _draftSlotOption, + int _draftSlotIndex) : +ingredientType(_ingredientType), +name(_name), +ingredients(), +complexity(_complexity), +draftSlotOption(_draftSlotOption), +draftSlotIndex(_draftSlotIndex) +{ + int count = slotIngredients.size(); + for (int i = 0; i < count; ++i) + ingredients.push_back(SimpleIngredientPtr(new SimpleIngredient(slotIngredients[i], slotIngredientsCount[i], NetworkId::cms_invalid, 0))); +} + +//---------------------------------------------------------------------- + + +bool operator==(const Crafting::SimpleIngredient & x, const Crafting::SimpleIngredient & y) +{ + if (x.ingredient != y.ingredient) + return false; + + if (x.count != y.count) + return false; + + return true; +} + +//---------------------------------------------------------------------- + +bool operator==(const Crafting::IngredientSlot & x, const Crafting::IngredientSlot & y) +{ + if (x.name != y.name) + return false; + + if (x.draftSlotOption != y.draftSlotOption) + return false; + + if (x.complexity != y.complexity) + return false; + + Crafting::Ingredients::const_iterator xiter, yiter; + const Crafting::Ingredients::const_iterator xend = x.ingredients.end(); + const Crafting::Ingredients::const_iterator yend = y.ingredients.end(); + for (xiter = x.ingredients.begin(), yiter = y.ingredients.begin(); + xiter != xend && yiter != yend; ++xiter, ++yiter) + { + if ((*xiter)->ingredient != (*yiter)->ingredient) + return false; + + if ((*xiter)->count != (*yiter)->count) + return false; + } + if (xiter != xend || yiter != yend) + return false; + + return true; +} + +//---------------------------------------------------------------------- + +void Crafting::getCraftingTypeNames (uint32 types, StringVector & sv) +{ + static const std::string s_craftingTypeNames [] = + { + "weapon", + "armor", + "food", + "clothing", + "vehicle", + "droid", + "chemical", + "plant_breeding", + "animal_breeding", + "furniture", + "installation", + "lightsaber", + "generic_item", + "genetics", + "mandalorian_tailor", + "mandalorian_armorsmith", + "mandalorian_droid_engineer", + "space", + "reverse_engineering", + "misc", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "mission" + }; + + static const size_t s_numCraftingTypeNames = sizeof (s_craftingTypeNames) / sizeof (s_craftingTypeNames [0]); + + for (size_t i = 0; i < s_numCraftingTypeNames; ++i) + { + uint32 bit = 1 << i; + + if ((types & bit) != 0) + sv.push_back (s_craftingTypeNames [i]); + } +} + +//---------------------------------------------------------------------- + +void Crafting::getCraftingResultName (CraftingResult result, std::string & name) +{ + static const std::string s_resultName_internal_failure = "internal_failure"; + + static const std::string s_resultNames [CR_numResults] = + { + "critical_success", + "great_success", + "good_success", + "moderate_success", + "success", + "failure", + "moderate_failure", + "big_failure", + "critical_failure" + }; + + if (result == CR_internalFailure) + name = s_resultName_internal_failure; + else + name = s_resultNames [static_cast(result)]; +} + +//---------------------------------------------------------------------- + +const std::string & Crafting::getResourceAttributeName (int attr) +{ + static const std::string empty; + + if (attr < 0 || attr >= RA_numResourceAttributes) + return empty; + + static const std::string s_resourceAttribteNames [RA_numResourceAttributes] = + { + "res_bulk", + "res_cold_resist", + "res_conductivity", + "res_decay_resist", + "res_heat_resist", + "res_flavor", + "res_malleability", + "res_potential_energy", + "res_quality", + "res_shock_resistance", + "res_toughness", + "res_volume" + }; + + return s_resourceAttribteNames [attr]; +} + +//---------------------------------------------------------------------- + +const StringId & Crafting::getResourceAttributeNameStringId (int attr) +{ + typedef stdmap::fwd ResourceAttributeNameStringIds; + static ResourceAttributeNameStringIds sids; + + const ResourceAttributeNameStringIds::iterator it = sids.find (attr); + + if (it != sids.end ()) + return (*it).second; + + return (sids [attr] = StringId (SharedObjectAttributes::StringTables::Name, getResourceAttributeName (attr))); +} + +//---------------------------------------------------------------------- + diff --git a/engine/shared/library/sharedGame/src/shared/core/CraftingData.h b/engine/shared/library/sharedGame/src/shared/core/CraftingData.h new file mode 100644 index 00000000..dbd89dcb --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/CraftingData.h @@ -0,0 +1,280 @@ +//======================================================================== +// +// CraftingData.h +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef INCLUDED_CraftingData_H +#define INCLUDED_CraftingData_H + +#include "sharedFoundation/NetworkId.h" +#include "boost/smart_ptr.hpp" +#include "StringId.h" +#include + +class CreatureObject; +class DraftSchematicObject; +class ServerCraftingDataTemplate; + + +//======================================================================== + +namespace Crafting +{ + // Crafting levels + const int MAX_CRAFTING_LEVEL = 4; + + // level 0 = generic tool, no input hopper, no experiment, no manf schematic + // level 1 = specific tool, no input hopper, no experiment, no manf schematic + // level 2 = specific tool, public station, no input hopper + // level 3 = specific tool, private station + // level 4 = specific tool, private station, no input hopper + + //------------------------------------------------------------------------------ + + // attributes associated with resources; also defined in craftinglib.scriptlib + enum ResourceAttributes + { + RA_bulk, + RA_coldResistance, + RA_conductivity, + RA_decayResistance, + RA_heatResistance, + RA_flavor, + RA_malleability, + RA_potentialEnergy, + RA_quality, + RA_shockResistance, + RA_toughness, + RA_volume, + RA_numResourceAttributes + }; + + const std::string & getResourceAttributeName (int attr); + const StringId & getResourceAttributeNameStringId (int attr); + + //------------------------------------------------------------------------------ + + enum CraftingStage + { + CS_none, + CS_selectDraftSchematic, + CS_assembly, + CS_experiment, + CS_customize, + CS_finish + }; + + //------------------------------------------------------------------------------ + + enum CraftingResult + { + CR_internalFailure = -1, + CR_criticalSuccess = 0, + CR_greatSuccess, + CR_goodSuccess, + CR_moderateSuccess, + CR_success, + CR_failure, + CR_moderateFailure, + CR_bigFailure, + CR_criticalFailure, + CR_criticalFailureNoDestroy, + CR_numResults = CR_criticalFailureNoDestroy, + }; + + void getCraftingResultName (CraftingResult result, std::string & name); + + //------------------------------------------------------------------------------ + + enum CraftingError + { + CE_success, + CE_noOwner, + CE_notAssemblyStage, + CE_notCustomizeStage, + CE_noDraftSchematic, + CE_noCraftingTool, + CE_noManfSchematic, + CE_invalidSlot, + CE_invalidSlotOption, + CE_invalidIngredientSize, + CE_slotFull, + CE_invalidIngredient, + CE_ingredientNotInInventory, + CE_cantRemoveResource, + CE_wrongResource, + CE_damagedComponent, + CE_cantTransferComponent, + CE_wrongComponent, + CE_noInventory, + CE_badTargetHopper, + CE_badTargetContainer, + CE_emptySlot, + CE_cantCreateResourceCrate, + CE_emptySlotAssembly, + CE_partialSlotAssembly, + CE_noPrototype, + CE_invalidCraftedName, + CE_readOnlyDraftSchematic, + CE_invalidBioLink, + CE_stackedLoot + }; + + //---------------------------------------------------------------------- + // the following struct mirrors the ones in ServerObjectTemplate + + enum CraftingType + { + CT_weapon = 0x00000001, + CT_armor = 0x00000002, + CT_food = 0x00000004, + CT_clothing = 0x00000008, + CT_vehicle = 0x00000010, + CT_droid = 0x00000020, + CT_chemical = 0x00000040, + CT_plantBreeding = 0x00000080, + CT_animalBreeding = 0x00000100, + CT_furniture = 0x00000200, + CT_installation = 0x00000400, + CT_lightsaber = 0x00000800, + CT_genericItem = 0x00001000, + CT_genetics = 0x00002000, + CT_mission = 0x80000000, + CraftingType_Last = CT_mission, + }; + + typedef stdvector::fwd StringVector; + void getCraftingTypeNames (uint32 types, StringVector & sv); + + //------------------------------------------------------------------------------ + + // the following structs mirror the ones in ServerCraftingDataTemplate + // and ServerIntangibleObjectTemplate, except that SimpleIngredient references + // a NetworkId instead of a StringId + + enum IngredientType + { + IT_invalid = -1, // uninitialized IngredientSlot + IT_none = 0, // no item (for empty/unused slots) + IT_item, // a specific item (Skywalker barrel mark V) + IT_template, // any item created from a template (any small_blaster_barrel) + IT_resourceType, // a specific resource type (iron type 5) + IT_resourceClass, // any resource of a resource class (ferrous metal) + IT_templateGeneric, // same as IT_template, but if multiple components are required, they don't have to be the same exact type as the first component used + IT_schematic, // item crafted from a draft schematic + IT_schematicGeneric,// same as IT_schematic, but if multiple components are required, they don't have to be the same exact type as the first component used + IngredientType_Last = IT_schematicGeneric + }; + + //------------------------------------------------------------------------------ + + class SimpleIngredient + { + public: + + // the ingredient is the resource type id for resources, or the manf + // schematic id for components + NetworkId ingredient; + int count; + NetworkId source; // who gets experience for this ingredient + int xpType; // what kind of experience to grant + + SimpleIngredient() : ingredient(), count(0), source(), xpType(0) {} + SimpleIngredient(const NetworkId & _ingredient, int _count, const NetworkId & _source, int _xpType); + virtual ~SimpleIngredient() {} + }; + + //------------------------------------------------------------------------------ + + class ComponentIngredient : public SimpleIngredient + { + public: + + std::string templateName; + Unicode::String componentName; + int sourceXp; + + ComponentIngredient(); + virtual ~ComponentIngredient() {} + }; + + inline ComponentIngredient::ComponentIngredient() : + SimpleIngredient(NetworkId::cms_invalid, 1, NetworkId::cms_invalid, 0), + templateName(), + componentName(), + sourceXp(0) + {} + + //------------------------------------------------------------------------------ + + typedef boost::shared_ptr SimpleIngredientPtr; + typedef std::vector Ingredients; + + //------------------------------------------------------------------------------ + + struct IngredientSlot + { + enum IngredientType ingredientType; + StringId name; + Ingredients ingredients; + float complexity; + int draftSlotOption; + int draftSlotIndex; + + IngredientSlot(); + + IngredientSlot(enum IngredientType _ingredientType, + const StringId & _name, + const stdvector::fwd slotIngredients, + const stdvector::fwd slotIngredientsCount, + float _complexity, + int _draftSlotOption, + int _draftSlotIndex); + }; + + //------------------------------------------------------------------------------ + + struct CustomInfo + { + std::string name; // customization property name + int index; // current palette/decal index + int minIndex; // minimum palette/decal index + int maxIndex; // maximum palette/decal index + }; + + //------------------------------------------------------------------------------ + + struct CustomValue + { + int property; // index of the customization property + int value; // value the property + + + CustomValue() : + property(0), + value(0) + { + } + + CustomValue(int p, int v) : + property(p), + value(v) + { + } + }; + +} // namespace Crafting + +//======================================================================== + +extern bool operator==(const Crafting::SimpleIngredient & x, const Crafting::SimpleIngredient & y); +extern bool operator==(const Crafting::IngredientSlot & x, const Crafting::IngredientSlot & y); + + +//======================================================================== + + +#endif // INCLUDED_CraftingData_H diff --git a/engine/shared/library/sharedGame/src/shared/core/CraftingDataArchive.cpp b/engine/shared/library/sharedGame/src/shared/core/CraftingDataArchive.cpp new file mode 100644 index 00000000..154e37ed --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/CraftingDataArchive.cpp @@ -0,0 +1,47 @@ +//====================================================================== +// +// CraftingDataArchive.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/CraftingDataArchive.h" + +#include "sharedFoundation/NetworkIdArchive.h" +#include "sharedObject/Object.h" + +//====================================================================== +namespace Archive +{ + + void get(ReadIterator & source, enum Crafting::CraftingStage & target) + { + source.get(&target, 4); + } + + //------------------------------------------------------------------------------ + + void put(ByteStream & target, const enum Crafting::CraftingStage & source) + { + target.put(&source, 4); + } + + //------------------------------------------------------------------------------ + + void get(ReadIterator & source, enum Crafting::IngredientType & target) + { + source.get(&target, 4); + } + + //------------------------------------------------------------------------------ + + void put(ByteStream & target, const enum Crafting::IngredientType & source) + { + target.put(&source, 4); + } + +} + + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/CraftingDataArchive.h b/engine/shared/library/sharedGame/src/shared/core/CraftingDataArchive.h new file mode 100644 index 00000000..8bbb9673 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/CraftingDataArchive.h @@ -0,0 +1,30 @@ +//====================================================================== +// +// CraftingDataArchive.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_CraftingDataArchive_H +#define INCLUDED_CraftingDataArchive_H + +#include "sharedGame/CraftingData.h" +#include "Archive/AutoByteStream.h" + +//====================================================================== +// archive functions + +namespace Archive +{ + + void get(ReadIterator & source, enum Crafting::CraftingStage & target); + void get(ReadIterator & source, enum Crafting::IngredientType & target); + + void put(ByteStream & target, const enum Crafting::CraftingStage & source); + void put(ByteStream & target, const enum Crafting::IngredientType & source); + +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/CustomizationManager.cpp b/engine/shared/library/sharedGame/src/shared/core/CustomizationManager.cpp new file mode 100644 index 00000000..051bb14e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/CustomizationManager.cpp @@ -0,0 +1,614 @@ +// ====================================================================== +// +// CustomizationManager.cpp +// copyright (c) 2004 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/CustomizationManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/Iff.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedMessageDispatch/Receiver.h" +#include "sharedMessageDispatch/Transceiver.h" +#include "sharedObject/CustomizationData.h" +#include "sharedObject/NetworkIdManager.h" +#include "sharedObject/Object.h" +#include "sharedObject/RangedIntCustomizationVariable.h" +#include "sharedUtility/DataTable.h" + +#include +#include +#include + +// ====================================================================== + +//allow long container names +#if WIN32 +#pragma warning (disable:4503) +#endif + + +// ====================================================================== + +std::string const CustomizationManager::cms_shared_owner = "/shared_owner/"; +std::string const CustomizationManager::cms_shared_owner_no_slash = "/shared_owner"; +std::string const CustomizationManager::cms_priv = "/private/"; + +// ====================================================================== + +namespace CustomizationManagerNamespace +{ + namespace AllowBaldColumnNames + { + char const * const species_gender = "SPECIES_GENDER"; + char const * const allowBald = "ALLOW_BALD"; + } + + namespace CustomizationGroupSharedColumnNames + { + char const * const customizationGroup = "CUSTOMIZATION_GROUP"; + char const * const isMarking = "IS_MARKING"; + char const * const isHair = "IS_HAIR"; + } + + namespace CustomizationGroupInstanceColumnNames + { + char const * const species_gender = "SPECIES_GENDER"; + char const * const customizationGroup = "CUSTOMIZATION_GROUP"; + char const * const isColorLinkedToHair = "IS_COLOR_LINKED_TO_HAIR"; + char const * const isColorLinkedToBody = "IS_COLOR_LINKED_TO_BODY"; + char const * const lookAtBone = "LOOK_AT_BONE"; + char const * const zoomFactor = "ZOOM_FACTOR"; + } + + namespace CustomizationDataColumnNames + { + char const * const species_gender = "SPECIES_GENDER"; + char const * const customizationGroup = "CUSTOMIZATION_GROUP"; + char const * const type = "TYPE"; + char const * const customizationName = "CUSTOMIZATION_NAME"; + char const * const variables = "VARIABLES"; + char const * const isScale = "IS_SCALE"; + char const * const reverse = "REVERSE"; + char const * const colorLinked = "COLOR_LINKED"; + char const * const colorLinkedToSelf0 = "COLOR_LINKED_TO_SELF_0"; + char const * const colorLinkedToSelf1 = "COLOR_LINKED_TO_SELF_1"; + char const * const cameraYaw = "CAMERA_YAW"; + char const * const discrete = "DISCRETE"; + char const * const randomizable = "RAMDOMIZABLE"; + char const * const randomizableGroup = "RANDOMIZABLE_GROUP"; + char const * const isVarHairColor = "IS_VAR_HAIR_COLOR"; + char const * const imagedesignSkillMod = "IMAGEDESIGN_SKILLMOD"; + char const * const skillModValue = "SKILLMOD_VALUE"; + char const * const modificationType = "MODIFICATION_TYPE"; + } + + namespace PaletteDataColumnNames + { + char const * const palette = "PALETTE"; + char const * const creationColumns = "CREATION_COLUMNS"; + char const * const creationIndexes = "CREATION_INDEXES"; + char const * const noviceColumns = "ID_NOVICE_COLUMNS"; + char const * const noviceIndexes = "ID_NOVICE_INDEXES"; + char const * const level1Columns = "ID_LEVEL1_COLUMNS"; + char const * const level1Indexes = "ID_LEVEL1_INDEXES"; + char const * const level2Columns = "ID_LEVEL2_COLUMNS"; + char const * const level2Indexes = "ID_LEVEL2_INDEXES"; + char const * const level3Columns = "ID_LEVEL3_COLUMNS"; + char const * const level3Indexes = "ID_LEVEL3_INDEXES"; + char const * const level4Columns = "ID_LEVEL4_COLUMNS"; + char const * const level4Indexes = "ID_LEVEL4_INDEXES"; + char const * const masterColumns = "ID_MASTER_COLUMNS"; + char const * const masterIndexes = "ID_MASTER_INDEXES"; + } + + namespace HoloemoteColumnNames + { + char const * const holoemoteName = "HOLOEMOTE"; + char const * const requiredHairSkillMod = "REQUIRED_HAIR_SKILLMOD"; + } + + std::map ms_allowBald; + ///all the customization data, indexed by species_gender, then by groupName + std::map ms_customizationsBySpeciesGenderAndGroup; + ///all the customization data, indexed by species_gender only + std::map ms_customizationsBySpeciesGender; + std::map ms_customizationGroupsShared; + std::map, CustomizationManager::CustomizationGroupInstanceData> ms_customizationGroupsInstance; + std::map ms_paletteColumnData; + std::map ms_holoemoteHairSkillRequired; + + bool ms_installed = false; +} + +using namespace CustomizationManagerNamespace; + +// ====================================================================== + +void CustomizationManager::install () +{ + InstallTimer const installTimer("CustomizationManager::install "); + + DEBUG_FATAL(ms_installed, ("Already Installed")); + ms_installed = true; + clearData(); + + //load in allow bald table + DataTable allowBaldDataTable; + Iff allowBaldIff("datatables/customization/allow_bald.iff"); + allowBaldDataTable.load(allowBaldIff); + std::string species_gender; + int allowBaldInt = 0; + for (int i = 0; i < allowBaldDataTable.getNumRows(); ++i) + { + species_gender = allowBaldDataTable.getStringValue(AllowBaldColumnNames::species_gender, i); + allowBaldInt = allowBaldDataTable.getIntValue(AllowBaldColumnNames::allowBald, i); + ms_allowBald[species_gender] = (allowBaldInt == 1) ? true : false; + } + + //load customization_group_shared table + DataTable customizationGroupSharedDataTable; + Iff customizationGroupSharedIff("datatables/customization/customization_group_shared.iff"); + customizationGroupSharedDataTable.load(customizationGroupSharedIff); + int isMarkingInt = 0; + int isHairInt = 0; + for (int j = 0; j < customizationGroupSharedDataTable.getNumRows(); ++j) + { + CustomizationGroupSharedData group; + group.name = customizationGroupSharedDataTable.getStringValue(CustomizationGroupSharedColumnNames::customizationGroup, j); + isMarkingInt = customizationGroupSharedDataTable.getIntValue(CustomizationGroupSharedColumnNames::isMarking, j); + isHairInt = customizationGroupSharedDataTable.getIntValue(CustomizationGroupSharedColumnNames::isHair, j); + group.isMarking = (isMarkingInt == 1) ? true : false; + group.isHair = (isHairInt == 1) ? true : false; + ms_customizationGroupsShared[group.name] = group; + } + + //load customization_group_instance table + DataTable customizationGroupInstanceDataTable; + Iff customizationGroupInstanceIff("datatables/customization/customization_group_instance.iff"); + customizationGroupInstanceDataTable.load(customizationGroupInstanceIff); + int isColorLinkedToHairInt = 0; + int isColorLinkedToBodyInt = 0; + for (int k = 0; k < customizationGroupInstanceDataTable.getNumRows(); ++k) + { + CustomizationGroupInstanceData data; + data.species_gender = customizationGroupInstanceDataTable.getStringValue(CustomizationGroupInstanceColumnNames::species_gender, k); + data.groupName = customizationGroupInstanceDataTable.getStringValue(CustomizationGroupInstanceColumnNames::customizationGroup, k); + isColorLinkedToHairInt = customizationGroupInstanceDataTable.getIntValue(CustomizationGroupInstanceColumnNames::isColorLinkedToHair, k); + data.isColorLinkedToHair = (isColorLinkedToHairInt == 1) ? true : false; + isColorLinkedToBodyInt = customizationGroupInstanceDataTable.getIntValue(CustomizationGroupInstanceColumnNames::isColorLinkedToBody, k); + data.isColorLinkedToBody = (isColorLinkedToBodyInt == 1) ? true : false; + data.lookAtBone = customizationGroupInstanceDataTable.getStringValue(CustomizationGroupInstanceColumnNames::lookAtBone, k); + data.zoomFactor = customizationGroupInstanceDataTable.getFloatValue(CustomizationGroupInstanceColumnNames::zoomFactor, k); + ms_customizationGroupsInstance[std::make_pair(data.species_gender, data.groupName)] = data; + } + + //load customization_data table + DataTable customizationDataTable; + Iff customizationIff("datatables/customization/customization_data.iff"); + customizationDataTable.load(customizationIff); + std::string customizationGroup; + int isScaleInt = 0; + int reverseInt = 0; + int discreteInt = 0; + int randomizableInt = 0; + int randomizableGroupInt = 0; + int isVarHairColorInt = 0; + for (int l = 0; l < customizationDataTable.getNumRows(); ++l) + { + species_gender = customizationDataTable.getStringValue(CustomizationDataColumnNames::species_gender, l); + customizationGroup = customizationDataTable.getStringValue(CustomizationDataColumnNames::customizationGroup, l); + + Customization cust; + cust.name = customizationDataTable.getStringValue(CustomizationDataColumnNames::customizationName, l); + cust.type = customizationDataTable.getStringValue(CustomizationDataColumnNames::type, l); + cust.variables = customizationDataTable.getStringValue(CustomizationDataColumnNames::variables, l); + isScaleInt = customizationDataTable.getIntValue(CustomizationDataColumnNames::isScale, l); + cust.isScale = (isScaleInt == 1) ? true : false; + reverseInt = customizationDataTable.getIntValue(CustomizationDataColumnNames::reverse, l); + cust.reverse = (reverseInt == 1) ? true : false; + cust.colorLinked = customizationDataTable.getStringValue(CustomizationDataColumnNames::colorLinked, l); + cust.colorLinkedToSelf0= customizationDataTable.getStringValue(CustomizationDataColumnNames::colorLinkedToSelf0, l); + cust.colorLinkedToSelf1= customizationDataTable.getStringValue(CustomizationDataColumnNames::colorLinkedToSelf1, l); + cust.cameraYaw = customizationDataTable.getFloatValue(CustomizationDataColumnNames::cameraYaw, l); + discreteInt = customizationDataTable.getIntValue(CustomizationDataColumnNames::discrete, l); + cust.discrete = (discreteInt == 1) ? true : false; + randomizableInt = customizationDataTable.getIntValue(CustomizationDataColumnNames::randomizable, l); + cust.randomizable = (randomizableInt == 1) ? true : false; + randomizableGroupInt = customizationDataTable.getIntValue(CustomizationDataColumnNames::randomizableGroup, l); + cust.randomizableGroup = (randomizableGroupInt == 1) ? true : false; + isVarHairColorInt = customizationDataTable.getIntValue(CustomizationDataColumnNames::isVarHairColor, l); + cust.isVarHairColor = (isVarHairColorInt == 1) ? true : false; + cust.skillMod = customizationDataTable.getStringValue(CustomizationDataColumnNames::imagedesignSkillMod, l); + cust.skillModValue = customizationDataTable.getIntValue(CustomizationDataColumnNames::skillModValue, l); + cust.modificationType = customizationDataTable.getStringValue(CustomizationDataColumnNames::modificationType, l); + + //we specifically want a CustomizationSpeciesMap created if we don't already have one + CustomizationSpeciesMap customizationMap = ms_customizationsBySpeciesGenderAndGroup[species_gender]; + //we specifically want a CustomizationVector created if we don't already have one + CustomizationVector customizationVector = customizationMap[customizationGroup]; + customizationVector.push_back(cust); + customizationMap[customizationGroup] = customizationVector; + ms_customizationsBySpeciesGenderAndGroup[species_gender] = customizationMap; + + customizationVector = ms_customizationsBySpeciesGender[species_gender]; + customizationVector.push_back(cust); + ms_customizationsBySpeciesGender[species_gender] = customizationVector; + } + + //load palette data + DataTable paletteDataTable; + Iff paletteDataIff("datatables/customization/palette_columns.iff"); + paletteDataTable.load(paletteDataIff); + for (int m = 0; m < paletteDataTable.getNumRows(); ++m) + { + PaletteColumns paletteData; + std::string const & palette = paletteDataTable.getStringValue(PaletteDataColumnNames::palette, m); + paletteData.creationColumns = paletteDataTable.getIntValue(PaletteDataColumnNames::creationColumns, m); + paletteData.creationIndexes = paletteDataTable.getIntValue(PaletteDataColumnNames::creationIndexes, m); + paletteData.noviceColumns = paletteDataTable.getIntValue(PaletteDataColumnNames::noviceColumns, m); + paletteData.noviceIndexes = paletteDataTable.getIntValue(PaletteDataColumnNames::noviceIndexes, m); + paletteData.level1Columns = paletteDataTable.getIntValue(PaletteDataColumnNames::level1Columns, m); + paletteData.level1Indexes = paletteDataTable.getIntValue(PaletteDataColumnNames::level1Indexes, m); + paletteData.level2Columns = paletteDataTable.getIntValue(PaletteDataColumnNames::level2Columns, m); + paletteData.level2Indexes = paletteDataTable.getIntValue(PaletteDataColumnNames::level2Indexes, m); + paletteData.level3Columns = paletteDataTable.getIntValue(PaletteDataColumnNames::level3Columns, m); + paletteData.level3Indexes = paletteDataTable.getIntValue(PaletteDataColumnNames::level3Indexes, m); + paletteData.level4Columns = paletteDataTable.getIntValue(PaletteDataColumnNames::level4Columns, m); + paletteData.level4Indexes = paletteDataTable.getIntValue(PaletteDataColumnNames::level4Indexes, m); + paletteData.masterColumns = paletteDataTable.getIntValue(PaletteDataColumnNames::masterColumns, m); + paletteData.masterIndexes = paletteDataTable.getIntValue(PaletteDataColumnNames::masterIndexes, m); + ms_paletteColumnData[palette] = paletteData; + } + + //load holoemotes table + DataTable holoemoteDataTable; + Iff holoemoteDataIff("datatables/customization/holoemotes.iff"); + holoemoteDataTable.load(holoemoteDataIff); + for (int n = 0; n < holoemoteDataTable.getNumRows(); ++n) + { + std::string const & holoemoteName = holoemoteDataTable.getStringValue(HoloemoteColumnNames::holoemoteName, n); + int const requiredHairSkillMod = holoemoteDataTable.getIntValue(HoloemoteColumnNames::requiredHairSkillMod, n); + ms_holoemoteHairSkillRequired[holoemoteName] = requiredHairSkillMod; + } + + + ExitChain::add(CustomizationManager::remove, "CustomizationManager::remove", 0, false); +} + +//---------------------------------------------------------------------- + +void CustomizationManager::remove () +{ + clearData(); + DEBUG_FATAL(!ms_installed, ("Not Installed")); + ms_installed = false; +} + +//---------------------------------------------------------------------- + +void CustomizationManager::clearData() +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("CustomizationManager not installed")); + return; //lint !e527 unreachable (reachable in release) + } + + ms_allowBald.clear(); + ms_customizationsBySpeciesGenderAndGroup.clear(); + ms_customizationsBySpeciesGender.clear(); + ms_customizationGroupsShared.clear(); + ms_customizationGroupsInstance.clear(); + ms_paletteColumnData.clear(); + ms_holoemoteHairSkillRequired.clear(); +} + +//---------------------------------------------------------------------- + +bool CustomizationManager::getAllowBald(std::string const & species_gender) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("CustomizationManager not installed")); + return false; //lint !e527 unreachable (reachable in release) + } + + std::map::const_iterator i = ms_allowBald.find(species_gender); + if(i != ms_allowBald.end()) + { + return i->second; + } + return false; +} + +//---------------------------------------------------------------------- + +CustomizationManager::CustomizationSpeciesMap const & CustomizationManager::getCustomizationSpeciesMap(std::string const & species_gender) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("CustomizationManager not installed")); + } + + return ms_customizationsBySpeciesGenderAndGroup[species_gender]; +} + +//---------------------------------------------------------------------- + +CustomizationManager::CustomizationGroupSharedData const & CustomizationManager::getCustomizationGroupSharedData(std::string const & customizationGroupName) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("CustomizationManager not installed")); + } + + return ms_customizationGroupsShared[customizationGroupName]; +} + +//---------------------------------------------------------------------- + +CustomizationManager::CustomizationGroupInstanceData const & CustomizationManager::getCustomizationGroupInstanceData(std::string const & species_gender, std::string const & customizationGroupName) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("CustomizationManager not installed")); + } + + return ms_customizationGroupsInstance[std::make_pair(species_gender, customizationGroupName)]; +} + +//---------------------------------------------------------------------- + +bool CustomizationManager::getCustomization(std::string const & species_gender, std::string const & customizationName, CustomizationManager::Customization & /*OUT*/ result) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("CustomizationManager not installed")); + return false; //lint !e527 unreachable (reachable in release) + } + + std::map::const_iterator i = ms_customizationsBySpeciesGender.find(species_gender); + if(i != ms_customizationsBySpeciesGender.end()) + { + CustomizationVector customizations = i->second; + for(CustomizationVector::const_iterator j = customizations.begin(); j != customizations.end(); ++j) + { + if(j->name == customizationName) + { + result = *j; + return true; + } + } + } + return false; +} + +//---------------------------------------------------------------------- + +std::string CustomizationManager::getServerSpeciesGender(Object const & creature) +{ + std::string result; + + if(!ms_installed) + { + DEBUG_FATAL(true, ("CustomizationManager not installed")); + return result; //lint !e527 unreachable (reachable in release) + } + + std::string const templateName = creature.getObjectTemplateName(); + std::string::size_type serverPos = templateName.find_last_of("/"); + std::string::size_type const iffPos = templateName.find(".iff", 0); + if (serverPos != static_cast(std::string::npos) && iffPos != static_cast(std::string::npos)) + { + serverPos += strlen("/"); + result = templateName.substr(serverPos, iffPos - serverPos); + } + return result; +} + +//---------------------------------------------------------------------- + +std::string CustomizationManager::getSharedSpeciesGender(Object const & creature) +{ + std::string result; + + if(!ms_installed) + { + DEBUG_FATAL(true, ("CustomizationManager not installed")); + return result; //lint !e527 unreachable (reachable in release) + } + + std::string const templateName = creature.getObjectTemplateName(); + std::string::size_type sharedPos = templateName.find("shared_", 0); + std::string::size_type const iffPos = templateName.find(".iff", 0); + if (sharedPos != static_cast(std::string::npos) && iffPos != static_cast(std::string::npos)) + { + sharedPos += strlen("shared_"); + result = templateName.substr(sharedPos, iffPos - sharedPos); + } + return result; +} + +//---------------------------------------------------------------------- + +CustomizationVariable * CustomizationManager::findVariable (CustomizationData & cdata, std::string const & partialName) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("CustomizationManager not installed")); + return NULL; //lint !e527 unreachable (reachable in release) + } + + PathType type = PT_none; + return findVariable (cdata, partialName, type); +} + +//---------------------------------------------------------------------- + +CustomizationVariable * CustomizationManager::findVariable (CustomizationData & cdata, std::string const & partialName, PathType & type) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("CustomizationManager not installed")); + return NULL; //lint !e527 unreachable (reachable in release) + } + + type = PT_none; + CustomizationVariable * cv = 0; + cv = cdata.findVariable (CustomizationManager::cms_shared_owner + partialName); + + RangedIntCustomizationVariable const * const rangedCV = dynamic_cast(cv); + if(rangedCV) + { + //if we have the ranged customization variable is a dependent variable, ignore it (there will be another that controls it) + if(rangedCV->getIsDependentVariable()) + cv = NULL; + } + + if (!cv) + { + cv = cdata.findVariable (CustomizationManager::cms_priv + partialName); + if (cv) + type = PT_private; + } + else + type = PT_shared; + + return cv; +} + +//---------------------------------------------------------------------- + +std::string CustomizationManager::getCustomizationNameForVariables(std::string const & species_gender, std::string const & variables, bool isOnHair) +{ + std::string result; + if(!ms_installed) + { + DEBUG_FATAL(true, ("CustomizationManager not installed")); + return result; //lint !e527 unreachable (reachable in release) + } + + std::map::const_iterator i = ms_customizationsBySpeciesGender.find(species_gender); + if(i != ms_customizationsBySpeciesGender.end()) + { + for(CustomizationManager::CustomizationVector::const_iterator j = i->second.begin(); j != i->second.end(); ++j) + { + Customization const & customization = *j; + if(customization.variables == variables) + { + //a given variable might exist on both the creature AND their hair object, make sure we get the right customization + if((!customization.isVarHairColor && !isOnHair) || + (customization.isVarHairColor && isOnHair)) + return customization.name; + } + } + } + + return result; +} + +//---------------------------------------------------------------------- + +std::string CustomizationManager::convertSharedHairTemplateNameToServerHairTemplateName(std::string const &sharedHairTemplateName) +{ + static std::string const shared("shared_"); + std::string::size_type pos = sharedHairTemplateName.find(shared); + std::string result; + if(pos != sharedHairTemplateName.npos) //lint !e737 size_type and npos mismatch bogosity + { + result = sharedHairTemplateName.substr(0, pos); + result += sharedHairTemplateName.substr(pos + shared.size()); + } + return result; +} + +//---------------------------------------------------------------------- + +std::string CustomizationManager::convertServerHairTemplateNameToSharedHairTemplateName(std::string const &serverHairTemplateName) +{ + static std::string const shared("shared_"); + std::string result; + std::string::size_type pos = serverHairTemplateName.find_last_of("/"); + if(pos != serverHairTemplateName.npos) //lint !e737 size_type and npos mismatch bogosity + { + result = serverHairTemplateName.substr(0, pos + 1); + result += shared; + result += serverHairTemplateName.substr(pos + 1); + } + return result; +} + +//---------------------------------------------------------------------- + +/** Get the palette column data for a given palette. + The paletteName should be of the format "pn_hum_eyes" +*/ +CustomizationManager::PaletteColumns CustomizationManager::getPaletteColumnDataShortName(std::string const & paletteName) +{ + return ms_paletteColumnData[paletteName]; +} + +//---------------------------------------------------------------------- + +/** Get the palette column data for a given palette. + The paletteName should be of the format "palette/pn_hum_eyes.pal" +*/ +CustomizationManager::PaletteColumns CustomizationManager::getPaletteColumnDataLongName(std::string const & paletteName) +{ + std::string const & shortPaletteName = shortenPaletteName(paletteName); + return ms_paletteColumnData[shortPaletteName]; +} + +//---------------------------------------------------------------------- + +std::map const & CustomizationManager::getPaletteColumnData() +{ + return ms_paletteColumnData; +} + +//---------------------------------------------------------------------- + +std::string CustomizationManager::shortenPaletteName(std::string const & longPaletteName) +{ + std::string result; + std::string::size_type startingPos = longPaletteName.find_last_of("/"); + if(startingPos != longPaletteName.npos) //lint !e737 size_type and npos mismatch bogosity + { + ++startingPos; + std::string::size_type const endingPos = longPaletteName.find(".pal", startingPos); + if(endingPos != longPaletteName.npos) //lint !e737 size_type and npos mismatch bogosity + if(endingPos > startingPos) + result = longPaletteName.substr(startingPos, endingPos - startingPos); + } + return result; +} + +//---------------------------------------------------------------------- + +bool CustomizationManager::isHoloemoteName(std::string const & holoemoteName) +{ + std::map::const_iterator i = ms_holoemoteHairSkillRequired.find(holoemoteName); + return (i != ms_holoemoteHairSkillRequired.end()); +} + +//---------------------------------------------------------------------- + +int const CustomizationManager::getRequiredHairSkillForHoloemote(std::string const & holoemoteName) +{ + if(holoemoteName.empty()) + return 0; + std::map::const_iterator i = ms_holoemoteHairSkillRequired.find(holoemoteName); + if (i != ms_holoemoteHairSkillRequired.end()) + { + return i->second; + } + else + return 10000; +} + +// ===================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/CustomizationManager.h b/engine/shared/library/sharedGame/src/shared/core/CustomizationManager.h new file mode 100644 index 00000000..316e7fc1 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/CustomizationManager.h @@ -0,0 +1,132 @@ +// ====================================================================== +// +// CustomizationManager.h +// copyright (c) 2004 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_CustomizationManager_H +#define INCLUDED_CustomizationManager_H + +// ====================================================================== + +class CustomizationData; +class CustomizationVariable; +class Object; +class NetworkId; + +//----------------------------------------------------------------------- + +//for forward declaration purposed +class CustomizationManagerPaletteColumns +{ +public: + int palette; + int creationColumns; + int creationIndexes; + int noviceColumns; + int noviceIndexes; + int level1Columns; + int level1Indexes; + int level2Columns; + int level2Indexes; + int level3Columns; + int level3Indexes; + int level4Columns; + int level4Indexes; + int masterColumns; + int masterIndexes; +}; + +class CustomizationManager +{ +public: + struct MorphParameter; + + struct Customization + { + std::string name; + std::string type; + std::string variables; + bool isScale; + bool reverse; + std::string colorLinked; + std::string colorLinkedToSelf0; + std::string colorLinkedToSelf1; + float cameraYaw; + bool discrete; + bool randomizable; + bool randomizableGroup; + bool isVarHairColor; + std::string skillMod; + int skillModValue; + std::string modificationType; + }; + + struct CustomizationGroupSharedData + { + std::string name; + bool isMarking; + bool isHair; + }; + + struct CustomizationGroupInstanceData + { + std::string species_gender; + std::string groupName; + bool isColorLinkedToHair; + bool isColorLinkedToBody; + std::string lookAtBone; + float zoomFactor; + }; + + enum PathType + { + PT_none, + PT_shared, + PT_private + }; + + typedef CustomizationManagerPaletteColumns PaletteColumns; + + static std::string const cms_shared_owner; + static std::string const cms_shared_owner_no_slash; + static std::string const cms_priv; + + typedef stdvector::fwd CustomizationVector; + typedef stdmap::fwd CustomizationSpeciesMap; + + static void install(); + static void remove(); + + static bool getAllowBald(std::string const & species_gender); + static CustomizationSpeciesMap const & getCustomizationSpeciesMap(std::string const & species_gender); + static CustomizationGroupSharedData const & getCustomizationGroupSharedData(std::string const & customizationGroupName); + static CustomizationGroupInstanceData const & getCustomizationGroupInstanceData(std::string const & species_gender, std::string const & customizationGroupName); + static bool getCustomization(std::string const & species_gender, std::string const & customizationName, CustomizationManager::Customization & /*OUT*/ result); + static std::string getServerSpeciesGender(Object const & creature); + static std::string getSharedSpeciesGender(Object const & creature); + static CustomizationVariable * findVariable(CustomizationData & cdata, std::string const & partialName, PathType & type); + static CustomizationVariable * findVariable(CustomizationData & cdata, std::string const & partialName); + static std::string getCustomizationNameForVariables(std::string const & species_gender, std::string const & variables, bool isOnHair); + static std::string convertSharedHairTemplateNameToServerHairTemplateName(std::string const &sharedHairTemplateName); + static std::string convertServerHairTemplateNameToSharedHairTemplateName(std::string const &serverHairTemplateName); + static PaletteColumns getPaletteColumnDataShortName(std::string const & paletteName); + static PaletteColumns getPaletteColumnDataLongName(std::string const & paletteName); + static stdmap::fwd const & getPaletteColumnData(); + static bool isHoloemoteName(std::string const & holoemoteName); + static int const getRequiredHairSkillForHoloemote(std::string const & holoemoteName); + +private: + //disabled + CustomizationManager (CustomizationManager const & rhs); + CustomizationManager & operator= (CustomizationManager const & rhs); + +private: + static void clearData(); + static std::string shortenPaletteName(std::string const & longPaletteName); +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/CustomizationManager_MorphParameter.cpp b/engine/shared/library/sharedGame/src/shared/core/CustomizationManager_MorphParameter.cpp new file mode 100644 index 00000000..620bd07e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/CustomizationManager_MorphParameter.cpp @@ -0,0 +1,236 @@ +//====================================================================== +// +// CustomizationManager_MorphParameter.cpp +// copyright (c) 2002-2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/CustomizationManager_MorphParameter.h" + +#include "sharedGame/SharedObjectTemplate.h" +#include "sharedMessageDispatch/Transceiver.h" +#include "sharedObject/CustomizationData.h" +#include "sharedObject/Object.h" +#include "sharedObject/RangedIntCustomizationVariable.h" + +#include "Unicode.h" +#include "UnicodeUtils.h" + +//====================================================================== + +namespace CustomizationManagerMorphParameterNamespace +{ + namespace Transceivers + { + MessageDispatch::Transceiver scaleFactorChanged; + } + + int ParseTwoTokens (Unicode::String const & str, Unicode::String tokens[]) + { + assert (tokens); + const size_t comma_pos = str.find_first_of (','); + tokens [0] = str.substr (0, comma_pos); + Unicode::trim (tokens [0]); + if (comma_pos != Unicode::String::npos) + { + tokens [1] = str.substr (comma_pos+1); + Unicode::trim (tokens [1]); + return 2; + } + return 1; + } +} + +using namespace CustomizationManagerMorphParameterNamespace; + +//---------------------------------------------------------------------- + +CustomizationManager::MorphParameter::MorphParameter (CustomizationData & cdata, CustomizationManager::Customization const & data) +: name(), + varStartName(), + varEndName(), + varStart(0), + varEnd(0), + target(0.0f), + current(0.0f), + theDefault(0.0f), + pictureIconName(), + cameraYaw(0.0f), + cameraYawValid(false), + isScale(false), + isDiscrete(false), + discreteRange(100), + reverse(false), + randomizable(true), + randomizableGroup(false) +{ + name = Unicode::narrowToWide(data.name); + + Unicode::String tokens [2]; + Unicode::String tmpStr = Unicode::narrowToWide(data.variables); + { + IGNORE_RETURN (ParseTwoTokens (tmpStr, tokens)); + + varStartName = Unicode::wideToNarrow (tokens [0]); + varEndName = Unicode::wideToNarrow (tokens [1]); + + if (!varStartName.empty ()) + varStart = dynamic_cast(CustomizationManager::findVariable (cdata, varStartName)); + + if (!varEndName.empty ()) + varEnd = dynamic_cast(CustomizationManager::findVariable (cdata, varEndName)); + } + + cameraYaw = data.cameraYaw; + cameraYawValid = (cameraYaw != 0.0f) ? true: false; + + isScale = data.isScale; + isDiscrete = data.discrete; + reverse = data.reverse; + randomizable = data.randomizable; + randomizableGroup = data.randomizableGroup; + + if (isDiscrete && varStart) + { + int begin = 0; + varStart->getRange (begin, discreteRange); + --discreteRange; + } + + //-- convert cameraYaw from degrees to radians + if (cameraYawValid) + cameraYaw = cameraYaw * PI / 180.0f; +} + +//---------------------------------------------------------------------- + +void CustomizationManager::MorphParameter::debugPrint (std::string & result) const +{ + char buf [256]; + snprintf (buf, sizeof (buf), "%20s ", Unicode::wideToNarrow (name).c_str ()); + result += buf; + snprintf (buf, sizeof (buf), "%20s", varStartName.c_str ()); + result += buf; + if (!varEndName.empty ()) + { + snprintf (buf, sizeof (buf), ",%20s", varEndName.c_str ()); + result += buf; + } + + result.append (1, '\n'); +} + +//---------------------------------------------------------------------- + +void CustomizationManager::MorphParameter::computeDefaults (Object const & obj, SharedObjectTemplate const * const tmpl) +{ + if (varStart) + { + current = varStart->getNormalizedFloatValue (); + + if (varEnd) + current = (1.0f + varEnd->getNormalizedFloatValue () - current) * 0.5f; + } + else if (isScale) + { + current = normalizeScale (obj, tmpl); + } + else + current = 0.0f; + if (reverse) + current = (1.0f - current); + theDefault = current; + target = current; +} + +//---------------------------------------------------------------------- + +void CustomizationManager::MorphParameter::update (Object const & obj, float const value) +{ + float const localValue = clamp (0.0f, value, 1.0f); + + if (varStart) + { + float varValue = localValue; + if (reverse) + varValue = (1.0f - varValue); + if (!varEnd) + { + varStart->setNormalizedFloatValue (varValue); + } + else + { + varStart->setNormalizedFloatValue (std::max (0.0f, (0.5f - varValue) * 2.0f)); + varEnd->setNormalizedFloatValue (std::max (0.0f, (varValue - 0.5f) * 2.0f)); + } + } + else if (isScale) + { + Transceivers::scaleFactorChanged.emitMessage (std::make_pair(obj.getNetworkId(), value)); + } + current = localValue; +} + +//---------------------------------------------------------------------- + +bool CustomizationManager::MorphParameter::incrementTarget (Object & obj, float const increment) +{ + float const old = current; + if (target > current) + update (obj, std::min (target, current + increment)); + else if (target < current) + update (obj, std::max (target, current - increment)); + return current != old || current != target; //lint !e777 //testing floats +} + +//---------------------------------------------------------------------- + +void CustomizationManager::MorphParameter::resetDefaults (Object & obj, bool const interpolate) +{ + target = theDefault; + if (!interpolate) + update (obj, theDefault); +} + +//---------------------------------------------------------------------- + +void CustomizationManager::MorphParameter::setTarget (float const t) +{ + target = t; + target = 1.0f - target; +} + +//---------------------------------------------------------------------- + +float CustomizationManager::MorphParameter::normalizeScale (Object const & obj, SharedObjectTemplate const * const tmpl) +{ + if (tmpl) + { + float const scaleMax = tmpl->getScaleMax (); + float const scaleMin = tmpl->getScaleMin (); + float const scaleRange = scaleMax - scaleMin; + if (scaleRange > 0.0f) + { + return (obj.getScale ().y - scaleMin) / scaleRange; + } + DEBUG_WARNING (scaleMin == 0.0f || scaleMax == 0.0f, ("SharedObjectTemplate [%s] scalemin/max is set to %f/%f, this is probably not what you want.", tmpl->getName (), scaleMin, scaleMax)); + } + return 1.0f; +} + +//---------------------------------------------------------------------- + +float CustomizationManager::MorphParameter::denormalizeScale (SharedObjectTemplate const * const tmpl, float const normalizedValue) +{ + if (tmpl) + { + float const scaleMax = tmpl->getScaleMax (); + float const scaleMin = tmpl->getScaleMin (); + float const scaleRange = scaleMax - scaleMin; + return scaleMin + (normalizedValue * scaleRange); + } + return 1.0f; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/CustomizationManager_MorphParameter.h b/engine/shared/library/sharedGame/src/shared/core/CustomizationManager_MorphParameter.h new file mode 100644 index 00000000..b0b7685d --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/CustomizationManager_MorphParameter.h @@ -0,0 +1,72 @@ +//====================================================================== +// +// CustomizationManager_MorphParameter.h +// copyright (c) 2002-2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_CustomizationManager_MorphParameter_H +#define INCLUDED_CustomizationManager_MorphParameter_H + +//====================================================================== + +#include "sharedGame/CustomizationManager.h" +//#include "Unicode.h" + +//---------------------------------------------------------------------- + +class CustomizationData; +class NetworkId; +class Object; +class RangedIntCustomizationVariable; +class SharedObjectTemplate; + +//---------------------------------------------------------------------- + +struct CustomizationManager::MorphParameter +{ +public: + struct Messages + { + struct ScaleFactorChanged + { + typedef std::pair Payload; + }; + }; + +public: + static float normalizeScale (Object const & obj, SharedObjectTemplate const * tmpl); + static float denormalizeScale (SharedObjectTemplate const * tmpl, float normalizedValue); + +public: + Unicode::String name; + std::string varStartName; + std::string varEndName; + RangedIntCustomizationVariable * varStart; + RangedIntCustomizationVariable * varEnd; + float target; + float current; + float theDefault; + std::string pictureIconName; + float cameraYaw; + bool cameraYawValid; + bool isScale; + bool isDiscrete; + int discreteRange; + bool reverse; + bool randomizable; + bool randomizableGroup; + +public: + MorphParameter (CustomizationData & cdata, CustomizationManager::Customization const & data); + void computeDefaults (Object const & obj, SharedObjectTemplate const * tmpl); + void update (Object const & obj, float value); + bool incrementTarget (Object & obj, float increment); + void resetDefaults (Object & obj, bool interpolate); + void setTarget (float target); + void debugPrint (std::string & result) const; +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/DraftSchematicGroupManager.cpp b/engine/shared/library/sharedGame/src/shared/core/DraftSchematicGroupManager.cpp new file mode 100644 index 00000000..670d76c9 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/DraftSchematicGroupManager.cpp @@ -0,0 +1,101 @@ +//====================================================================== +// +// DraftSchematicGroupManager.cpp +// copyright (c) 2003 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/DraftSchematicGroupManager.h" + +#include "UnicodeUtils.h" +#include "sharedFoundation/Crc.h" +#include "sharedGame/ConfigSharedGame.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" +#include +#include + +//====================================================================== + +namespace DraftSchematicGroupManagerNamespace +{ + typedef DraftSchematicGroupManager::StringVector StringVector; + typedef DraftSchematicGroupManager::SchematicVector SchematicVector; + typedef stdmap::fwd GroupMapping; + + GroupMapping s_groupMapping; + bool s_installed = false; + + void install () + { + if (s_installed) + return; + + s_installed = true; + + const std::string path = ConfigSharedGame::getSchematicGroupDataTable(); + + const DataTable * const schematicGroupTable = DataTableManager::getTable (path, true); + if (!schematicGroupTable) + { + WARNING_STRICT_FATAL(true, ("Cannot load schematic group datatable [%s]", path.c_str ())); + return; + } + + const int numRows = schematicGroupTable->getNumRows(); + for (int i = 0; i < numRows; ++i) + { + const std::string & group = schematicGroupTable->getStringValue (0, i); + const std::string & schematic = schematicGroupTable->getStringValue (1, i); + const std::string::size_type slash = schematic.rfind('/'); + const std::string sharedSchematic(schematic.substr(0, slash + 1) + "shared_" + schematic.substr(slash + 1)); + const uint32 serverCrc = Crc::calculate(schematic.c_str()); + const uint32 sharedCrc = Crc::calculate(sharedSchematic.c_str()); + const std::pair crc(serverCrc, sharedCrc); + + SchematicVector & sv = s_groupMapping [Unicode::toLower (group)]; + + if (std::find (sv.begin (), sv.end (), crc) != sv.end ()) + WARNING_STRICT_FATAL (true, ("DraftSchematicGroupManager group [%s] schematic [%s] appears multiple times", group.c_str (), schematic.c_str ())); + + sv.push_back (crc); + } + } +} + +using namespace DraftSchematicGroupManagerNamespace; + +//---------------------------------------------------------------------- + +void DraftSchematicGroupManager::getGroups (StringVector & sv) +{ + if (!s_installed) + install (); + + for (GroupMapping::const_iterator it = s_groupMapping.begin (); it != s_groupMapping.end (); ++it) + { + sv.push_back ((*it).first); + } +} + +//---------------------------------------------------------------------- + +bool DraftSchematicGroupManager::getSchematicsForGroup (const std::string & group, SchematicVector & sv) +{ + if (!s_installed) + install (); + + const GroupMapping::const_iterator it = s_groupMapping.find (Unicode::toLower (group)); + if (it != s_groupMapping.end ()) + { + sv = (*it).second; + return true; + } + + return false; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/DraftSchematicGroupManager.h b/engine/shared/library/sharedGame/src/shared/core/DraftSchematicGroupManager.h new file mode 100644 index 00000000..84d93d87 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/DraftSchematicGroupManager.h @@ -0,0 +1,26 @@ +//====================================================================== +// +// DraftSchematicGroupManager.h +// copyright (c) 2003 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_DraftSchematicGroupManager_H +#define INCLUDED_DraftSchematicGroupManager_H + +//====================================================================== + +class DraftSchematicGroupManager +{ +public: + + typedef stdvector::fwd StringVector; + typedef stdvector >::fwd SchematicVector; + + static void getGroups (StringVector & sv); + static bool getSchematicsForGroup (const std::string & group, SchematicVector & sv); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/FirstSharedGame.h b/engine/shared/library/sharedGame/src/shared/core/FirstSharedGame.h new file mode 100644 index 00000000..2047f92b --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/FirstSharedGame.h @@ -0,0 +1,21 @@ +// ====================================================================== +// +// FirstSharedGame.h +// copyright (c) 2001 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_FirstSharedGame_H +#define INCLUDED_FirstSharedGame_H + +// ====================================================================== + +#include "sharedFoundation/FirstSharedFoundation.h" +#include "sharedDebug/FirstSharedDebug.h" +#include "sharedMemoryManager/FirstSharedMemoryManager.h" +#include "StringId.h" + +// ====================================================================== + +#endif + diff --git a/engine/shared/library/sharedGame/src/shared/core/FormManager.cpp b/engine/shared/library/sharedGame/src/shared/core/FormManager.cpp new file mode 100644 index 00000000..7074ff4c --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/FormManager.cpp @@ -0,0 +1,887 @@ +//====================================================================== +// +// FormManager.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/FormManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFoundation/ConstCharCrcString.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedGame/ConfigSharedGame.h" +#include "sharedObject/ObjectTemplateList.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" + +#include "UnicodeUtils.h" + +#include + +#include +#include +#include + +//====================================================================== + +namespace FormManagerNamespace +{ + bool s_installed = false; + bool s_fatalOnBadFormData = true; + bool s_tablesLoaded = false; + + std::string const cs_baseDir ("datatables/form/"); + std::string const cs_filenameExt (".iff"); + std::string const cs_fileTableName ("datatables/form/filelist.iff"); + std::string const cs_formMapTableName ("datatables/form/formmap.iff"); + + std::string const cs_commandName ("sendFormObjectData"); + + Unicode::String const cs_space(Unicode::narrowToWide(" ")); + Unicode::String const cs_comma(Unicode::narrowToWide(",")); + + std::string const cs_emptyStringPlaceholder(""); +} + +using namespace FormManagerNamespace; + +//---------------------------------------------------------------------- + +std::map* FormManager::ms_forms; +std::map * FormManager::ms_serverObjectTemplateToForms; +std::map * FormManager::ms_sharedObjectTemplateToForms; +std::map * FormManager::ms_automaticallyCreateObjectForServerObjectTemplate; + +//====================================================================== + +FormManager::Field::Field(Form const * const parent) +: m_name(), + m_type(INT), + m_externalName(), + m_defaultValue(), + m_minimumValue(), + m_maximumValue(), + m_minimumValueSet(false), + m_maximumValueSet(false), + m_choices(new std::vector), + m_mustUseList(false), + m_validationFilename(), + m_validationFilenameColumn(-1), + m_otherValidationRules(new std::vector), + m_parentForm(parent), + m_objvarBinding() +{ +} + +//---------------------------------------------------------------------- + +FormManager::Field::~Field() +{ + delete m_choices; + m_choices = NULL; + delete m_otherValidationRules; + m_otherValidationRules = NULL; + m_parentForm = NULL; +} + +//---------------------------------------------------------------------- + +bool FormManager::Field::isIntType() const +{ + return (m_type == FormManager::INT || m_type == FormManager::INTARRAY); +} + +//---------------------------------------------------------------------- + +bool FormManager::Field::isFloatType() const +{ + return (m_type == FormManager::FLOAT || m_type == FormManager::FLOATARRAY); +} + +//---------------------------------------------------------------------- + +bool FormManager::Field::isStringType() const +{ + return (m_type == FormManager::STRING || m_type == FormManager::STRINGARRAY); +} + +//---------------------------------------------------------------------- + +bool FormManager::Field::isArrayType() const +{ + return (m_type == FormManager::INTARRAY || m_type == FormManager::FLOATARRAY || m_type == FormManager::STRINGARRAY); +} + +//---------------------------------------------------------------------- + +int FormManager::Field::getMinimumIntValue(std::map const & pendingData, std::string & validationField /*OUT*/) const +{ + if(!isIntType()) + { + DEBUG_FATAL(true, ("not an int value")); + return 0; //lint !e527 reachable in release + } + if(!m_minimumValueSet) + { + DEBUG_FATAL(true, ("no min value set")); + return 0; //lint !e527 reachable in release + } + + //try to turn the field value directly into a number + int min = atoi(m_minimumValue.c_str()); + + //see if the field value actually holds the name of another field, if so, find its value in the pending data set + if(m_parentForm->isNameOfField(m_minimumValue)) + { + std::map::const_iterator i = pendingData.find(m_minimumValue); + if(i != pendingData.end()) + { + std::string const & fieldNameValueString = i->second; + min = atoi(fieldNameValueString.c_str()); + validationField = i->first; + } + else + return 0; + } + + return min; +} + +//---------------------------------------------------------------------- + +int FormManager::Field::getMaximumIntValue(std::map const & pendingData, std::string & validationField /*OUT*/) const +{ + if(!isIntType()) + { + DEBUG_FATAL(true, ("not an int value")); + return 0; //lint !e527 reachable in release + } + if(!m_maximumValueSet) + { + DEBUG_FATAL(true, ("no max value set")); + return 0; //lint !e527 reachable in release + } + + //try to turn the field value directly into a number + int max = atoi(m_maximumValue.c_str()); + + //see if the field value actually holds the name of another field, if so, find its value in the pending data set + if(m_parentForm->isNameOfField(m_minimumValue)) + { + std::map::const_iterator i = pendingData.find(m_maximumValue); + if(i != pendingData.end()) + { + std::string const & fieldNameValueString = i->second; + max = atoi(fieldNameValueString.c_str()); + validationField = i->first; + } + else + return 0; + } + + return max; +} + +//---------------------------------------------------------------------- + +float FormManager::Field::getMinimumFloatValue(std::map const & pendingData, std::string & validationField /*OUT*/) const +{ + if(!isFloatType()) + { + DEBUG_FATAL(true, ("not an int value")); + return 0; //lint !e527 reachable in release + } + if(!m_minimumValueSet) + { + DEBUG_FATAL(true, ("no min value set")); + return 0; //lint !e527 reachable in release + } + + //try to turn the field value directly into a number + float min = static_cast(atof(m_minimumValue.c_str())); + + //see if the field value actually holds the name of another field, if so, find its value in the pending data set + if(m_parentForm->isNameOfField(m_minimumValue)) + { + std::map::const_iterator i = pendingData.find(m_minimumValue); + if(i != pendingData.end()) + { + std::string const & fieldNameValueString = i->second; + min = static_cast(atof(fieldNameValueString.c_str())); + validationField = i->first; + } + else + return 0; + } + + return min; +} + +//---------------------------------------------------------------------- + +float FormManager::Field::getMaximumFloatValue(std::map const & pendingData, std::string & validationField /*OUT*/) const +{ + if(!isFloatType()) + { + DEBUG_FATAL(true, ("not an int value")); + return 0; //lint !e527 reachable in release + } + if(!m_maximumValueSet) + { + DEBUG_FATAL(true, ("no max value set")); + return 0; //lint !e527 reachable in release + } + + //try to turn the field value directly into a number + float max = static_cast(atof(m_maximumValue.c_str())); + + //see if the field value actually holds the name of another field, if so, find its value in the pending data set + if(m_parentForm->isNameOfField(m_minimumValue)) + { + std::map::const_iterator i = pendingData.find(m_maximumValue); + if(i != pendingData.end()) + { + std::string const & fieldNameValueString = i->second; + max = static_cast(atof(fieldNameValueString.c_str())); + validationField = i->first; + } + else + return 0; + } + + return max; +} + +//---------------------------------------------------------------------- + +bool FormManager::Field::isValidValue(int value, std::map const & pendingData, std::string & errorString /*OUT*/) const +{ + if(!isIntType()) + { + DEBUG_FATAL(true, ("FormManager::Field::isValidValue(int) called on a non-int field")); + return false; //lint !e527 reachable in release + } + + std::string validationField; + std::string displayField; + //check against any minimum value if there is one + if(m_minimumValueSet) + { + int const minimumValue = getMinimumIntValue(pendingData, validationField); + //if the value is invalid, fill out the error string with the appropriate data + if(value < minimumValue) + { + if(!validationField.empty()) + { + Field const * f = m_parentForm->getField(validationField); + if(f) + displayField = f->m_externalName; + else + displayField = validationField; + errorString = std::string("Field: \"") + m_externalName + std::string("\" must be >= \"") + displayField + std::string("\"."); + } + else + { + char buf[256]; + IGNORE_RETURN(_itoa(minimumValue, buf, 10)); + errorString = std::string("Field: \"") + m_externalName + std::string("\" must be >= ") + buf + std::string("."); + } + return false; + } + } + + //check against any maximum value if there is one + if(m_maximumValueSet) + { + int const maximumValue = getMaximumIntValue(pendingData, validationField); + //if the value is invalid, fill out the error string with the appropriate data + if(value > maximumValue) + { + if(!validationField.empty()) + { + Field const * f = m_parentForm->getField(validationField); + if(f) + displayField = f->m_externalName; + else + displayField = validationField; + errorString = std::string("Field: \"") + m_externalName + std::string("\" must be <= \"") + displayField + std::string("\"."); + } + else + { + char buf[256]; + IGNORE_RETURN(_itoa(maximumValue, buf, 10)); + errorString = std::string("Field: \"") + m_externalName + std::string("\" must <= ") + buf + std::string("."); + } + return false; + } + } + return true; +} + +//---------------------------------------------------------------------- + +bool FormManager::Field::isValidValue(float value, std::map const & pendingData, std::string & errorString /*OUT*/) const +{ + if(!isFloatType()) + { + DEBUG_FATAL(true, ("FormManager::Field::isValidValue(float) called on a non-float field")); + return false; //lint !e527 reachable in release + } + + std::string validationField; + std::string displayField; + //check against any minimum value if there is one + if(m_minimumValueSet) + { + float const minimumValue = getMinimumFloatValue(pendingData, validationField); + //if the value is invalid, fill out the error string with the appropriate data + if(value < minimumValue) + { + if(!validationField.empty()) + { + Field const * f = m_parentForm->getField(validationField); + if(f) + displayField = f->m_externalName; + else + displayField = validationField; + errorString = std::string("Field: \"") + m_externalName + std::string("\" must be >= \"") + displayField + std::string("\"."); + } + else + { + char buf[1024]; + IGNORE_RETURN(snprintf(buf, sizeof(buf), "%f", minimumValue)); + errorString = std::string("Field: \"") + m_externalName + std::string("\" must be >= ") + buf + std::string("."); + } + return false; + } + } + + //check against any maximum value if there is one + if(m_maximumValueSet) + { + float const maximumValue = getMaximumFloatValue(pendingData, validationField); + //if the value is invalid, fill out the error string with the appropriate data + if(value > maximumValue) + { + if(!validationField.empty()) + { + Field const * f = m_parentForm->getField(validationField); + if(f) + displayField = f->m_externalName; + else + displayField = validationField; + errorString = std::string("Field: \"") + m_externalName + std::string("\" must be <= \"") + displayField + std::string("\"."); + } + else + { + char buf[1024]; + IGNORE_RETURN(snprintf(buf, sizeof(buf), "%f", maximumValue)); + errorString = std::string("Field: \"") + m_externalName + std::string("\" must be <= ") + buf + std::string("."); + } + return false; + } + } + return true; +} + +//---------------------------------------------------------------------- + +bool FormManager::Field::isValidValue(std::string const & value, std::map const & pendingData, std::string & errorString /*OUT*/) const +{ + if(!isStringType()) + { + DEBUG_FATAL(true, ("FormManager::Field::isValidValue(string) called on a non-string field")); + return false; //lint !e527 reachable in release + } + + UNREF(value); + UNREF(errorString); + UNREF(pendingData); + return true; +} + +//---------------------------------------------------------------------- + +std::string const & FormManager::Field::getName() const +{ + return m_name; +} + +//---------------------------------------------------------------------- + +std::string const & FormManager::Field::getExternalName() const +{ + return m_externalName; +} + +//---------------------------------------------------------------------- + +std::vector const & FormManager::Field::getOtherValidationRules() const +{ + return *m_otherValidationRules; +} + +//---------------------------------------------------------------------- + +std::string const & FormManager::Field::getDefaultValue() const +{ + return m_defaultValue; +} + +//---------------------------------------------------------------------- + +std::string const & FormManager::Field::getObjvarBinding() const +{ + return m_objvarBinding; +} + +//====================================================================== + +FormManager::Form::Form() +: m_name(), + m_fields(new std::map), + m_orderedFieldList(new std::vector) +{ +} + +//---------------------------------------------------------------------- + +FormManager::Form::~Form() +{ + //this vector does NOT own the pointers + delete m_orderedFieldList; + m_orderedFieldList = NULL; + + //this list owns the pointers, so release it + std::for_each(m_fields->begin(), m_fields->end(), PointerDeleterPairSecond()); + delete m_fields; + m_fields = NULL; +} + +//---------------------------------------------------------------------- + +bool FormManager::Form::isNameOfField(std::string const & fieldName) const +{ + std::map::iterator i = m_fields->find(fieldName); + return(i != m_fields->end()); +} + +//---------------------------------------------------------------------- + +FormManager::Field const * FormManager::Form::getField(std::string const & fieldName) const +{ + std::map::iterator i = m_fields->find(fieldName); + if(i != m_fields->end()) + return i->second; + else + return NULL; +} + +//---------------------------------------------------------------------- + +std::string const & FormManager::Form::getName() const +{ + return m_name; +} + +//---------------------------------------------------------------------- + +std::vector const & FormManager::Form::getOrderedFieldList() const +{ + return *m_orderedFieldList; +} + +//====================================================================== + +void FormManager::install () +{ + InstallTimer const installTimer("FormManager::install "); + + DEBUG_FATAL (s_installed, ("installed")); + if(s_installed) + return; + + s_installed = true; + + s_fatalOnBadFormData = ConfigSharedGame::getFatalOnBadFormData(); + + ExitChain::add(remove,"FormManager::remove"); + + ms_forms = new std::map; + ms_serverObjectTemplateToForms = new std::map; + ms_sharedObjectTemplateToForms = new std::map; + ms_automaticallyCreateObjectForServerObjectTemplate = new std::map; + + s_tablesLoaded = false; + + loadData(); +} + +//---------------------------------------------------------------------- + +void FormManager::remove () +{ + DEBUG_FATAL (!s_installed, ("not installed")); + if(!s_installed) + return; + + clearData(); + + delete ms_forms; + ms_forms = NULL; + delete ms_serverObjectTemplateToForms; + ms_serverObjectTemplateToForms = NULL; + delete ms_sharedObjectTemplateToForms; + ms_sharedObjectTemplateToForms = NULL; + delete ms_automaticallyCreateObjectForServerObjectTemplate; + ms_automaticallyCreateObjectForServerObjectTemplate = NULL; + + s_tablesLoaded = false; + s_installed = false; +} + +//---------------------------------------------------------------------- + +std::string const & FormManager::getFormCommandName() +{ + return cs_commandName; +} + +//---------------------------------------------------------------------- + +void FormManager::reloadData() +{ + DEBUG_FATAL (!s_installed, ("not installed")); + if(!s_installed) + return; + + clearData(); + loadData(); +} + +//---------------------------------------------------------------------- + +void FormManager::clearData() +{ + DEBUG_FATAL (!s_installed, ("not installed")); + if(!s_installed) + return; + + //do NOT release the Forms that we point to, this map does not own them + ms_serverObjectTemplateToForms->clear(); + ms_sharedObjectTemplateToForms->clear(); + ms_automaticallyCreateObjectForServerObjectTemplate->clear(); + + //delete the Form pointers, since this map owns them + std::for_each(ms_forms->begin(), ms_forms->end(), PointerDeleterPairSecond()); + ms_forms->clear(); + + s_tablesLoaded = false; +} + +//---------------------------------------------------------------------- + +void FormManager::loadData() +{ + DEBUG_FATAL (!s_installed, ("not installed")); + if(!s_installed) + return; + + //read in the file list, read each file + //reload the table if necessary in case we're rebuilding the form data + if(s_tablesLoaded) + IGNORE_RETURN(DataTableManager::reload(cs_fileTableName)); + + DataTable const * const fileTable = DataTableManager::getTable (cs_fileTableName.c_str(), true); + if (fileTable) + { + int const numRows = fileTable->getNumRows (); + + for (int i = 0; i < numRows; ++i) + { + std::string const & formName = fileTable->getStringValue (0, i); + std::string const & filename = fileTable->getStringValue (1, i); + + std::string const tableName = cs_baseDir + filename; + if(s_tablesLoaded) + IGNORE_RETURN(DataTableManager::reload(tableName)); + DataTable const * const table = DataTableManager::getTable (tableName.c_str(), true); + if (table) + { + //reload the table first in case we're rebuilding the kb + loadTable(*table, tableName, formName); + } + else + { + DEBUG_FATAL(s_fatalOnBadFormData, ("Could not load form file %s", filename.c_str())); + } + } + } + + const DataTable * formMapTable = DataTableManager::getTable(cs_formMapTableName.c_str(), true); + if(formMapTable) + { + int const numRows = formMapTable->getNumRows (); + + for (int i = 0; i < numRows; ++i) + { + std::string const & serverTemplateName = formMapTable->getStringValue (0, i); + std::string const & sharedTemplateName = formMapTable->getStringValue (1, i); + ConstCharCrcString const & sharedCrcStr = ObjectTemplateList::lookUp(sharedTemplateName.c_str()); + uint32 const sharedCrc = sharedCrcStr.getCrc(); + if(sharedCrc == 0) + { + if(ConfigSharedGame::getFatalOnBadFormData()) + { + DEBUG_FATAL(true, ("Malformed Form data: File %s row %d has has a sharedTemplate: %s which is not in the object template list", cs_formMapTableName.c_str(), i, sharedTemplateName.c_str())); + continue; + } + } + + std::string const & form = formMapTable->getStringValue (2, i); + int const autoCreateObject = formMapTable->getIntValue(3, i); + + if(autoCreateObject == 0) + (*ms_automaticallyCreateObjectForServerObjectTemplate)[serverTemplateName] = false; + else if(autoCreateObject == 1) + { + (*ms_automaticallyCreateObjectForServerObjectTemplate)[serverTemplateName] = true; + } + else + { + if(ConfigSharedGame::getFatalOnBadFormData()) + { + DEBUG_FATAL(true, ("Malformed Form data: File %s row %d has neither 0 nor 1 for AUTOMATICALLY_CREATE_OBJECT", cs_formMapTableName.c_str(), i)); + (*ms_automaticallyCreateObjectForServerObjectTemplate)[serverTemplateName] = false; + } + } + + //make sure the template names aren't dupes of other rows in the table + std::map::iterator i2 = ms_serverObjectTemplateToForms->find(serverTemplateName); + if(i2 != ms_serverObjectTemplateToForms->end()) + { + if(ConfigSharedGame::getFatalOnBadFormData()) + { + DEBUG_FATAL(true, ("Malformed Form data: File %s row %d has a serverTemplate: %s already found in the table, this must be unique", cs_formMapTableName.c_str(), i, serverTemplateName.c_str())); + } + continue; + } + i2 = ms_sharedObjectTemplateToForms->find(sharedTemplateName); + if(i2 != ms_sharedObjectTemplateToForms->end()) + { + if(ConfigSharedGame::getFatalOnBadFormData()) + { + DEBUG_FATAL(true, ("Malformed Form data: File %s row %d has a sharedTemplate: %s already found in the table, this must be unique", cs_formMapTableName.c_str(), i, sharedTemplateName.c_str())); + } + continue; + } + + Form const * const f = getFormByName(form); + if(f) + { + (*ms_serverObjectTemplateToForms)[serverTemplateName] = f; + (*ms_sharedObjectTemplateToForms)[sharedTemplateName] = f; + } + } + } + + if(!s_tablesLoaded) + s_tablesLoaded = true; +} + +//---------------------------------------------------------------------- + +void FormManager::loadTable(DataTable const & table, std::string const & tableName, std::string const & formName) +{ + DEBUG_FATAL (!s_installed, ("not installed")); + if(!s_installed) + return; + + UNREF(tableName); + + Form * const form = new Form(); + form->m_name = formName; + + int const numRows = table.getNumRows (); + + for (int i = 0; i < numRows; ++i) + { + std::string const & entryName = table.getStringValue (0, i); + int const entryType = table.getIntValue (1, i); + std::string const & externalName = table.getStringValue (2, i); + std::string const & defaultValue = table.getStringValue (3, i); + std::string const & minValue = table.getStringValue (4, i); + std::string const & maxValue = table.getStringValue (5, i); + std::string const & choiceList = table.getStringValue (6, i); + int const mustUseList = table.getIntValue (7, i); + std::string const & validationFilename = table.getStringValue (8, i); + int const validationFilenameColumn = table.getIntValue (9, i); + std::string const & otherValidationRules = table.getStringValue (10, i); + std::string const & objvarBinding = table.getStringValue (11, i); + + Field * const field = new Field(form); + + const FieldType fieldType = static_cast(entryType); + + field->m_name = entryName; + field->m_type = fieldType; + field->m_defaultValue = defaultValue; + field->m_externalName = externalName; + field->m_minimumValue = minValue; + field->m_maximumValue = maxValue; + if(!minValue.empty()) + field->m_minimumValueSet = true; + if(!maxValue.empty()) + field->m_maximumValueSet = true; + //TODO parse choices + UNREF(choiceList); + field->m_mustUseList = (mustUseList != 0 ? true : false); + field->m_validationFilename = validationFilename; + field->m_validationFilenameColumn = validationFilenameColumn; + if(otherValidationRules == "NOT_EMPTY") + field->m_otherValidationRules->push_back(FormManager::NOT_EMPTY); + field->m_objvarBinding = objvarBinding; + + //put this field into the form + std::map * const fields = form->m_fields; + if(fields) + (*fields)[entryName] = field; + std::vector * const orderedFields = form->m_orderedFieldList; + if(orderedFields) + orderedFields->push_back(field); + } + + //put the form into our form list + (*ms_forms)[formName] = form; +} + +//---------------------------------------------------------------------- + +FormManager::Form const * FormManager::getFormByName(std::string const & formName) +{ + DEBUG_FATAL (!s_installed, ("not installed")); + if(!s_installed) + return NULL; + + std::map::iterator i = ms_forms->find(formName); + if(i != ms_forms->end()) + return i->second; + else + return NULL; +} + +//---------------------------------------------------------------------- + +FormManager::Form const * FormManager::getFormForServerObjectTemplate(std::string const & serverTemplateName) +{ + DEBUG_FATAL (!s_installed, ("not installed")); + if(!s_installed) + return NULL; + + std::map::iterator i = ms_serverObjectTemplateToForms->find(serverTemplateName); + if(i != ms_serverObjectTemplateToForms->end()) + return i->second; + else + return NULL; +} + +//---------------------------------------------------------------------- + +FormManager::Form const * FormManager::getFormForSharedObjectTemplate(std::string const & sharedTemplateName) +{ + DEBUG_FATAL (!s_installed, ("not installed")); + if(!s_installed) + return NULL; + + std::map::iterator i = ms_sharedObjectTemplateToForms->find(sharedTemplateName); + if(i != ms_sharedObjectTemplateToForms->end()) + return i->second; + else + return NULL; +} + +//---------------------------------------------------------------------- + +FormManager::PackedFormData FormManager::packFormData(UnpackedFormData const & unpackedData) +{ + PackedFormData result; + bool first = true; + + //turn a map > into a unicode::string formatted as "key1 value1,value2,value3 key2 value1 key3 value1,value2..." + + for(UnpackedFormData::const_iterator i = unpackedData.begin(); i != unpackedData.end(); ++i) + { + if(first) + first = false; + else + result += cs_space; + result += Unicode::narrowToWide(i->first) + cs_space; + bool firstInList = true; + for(std::vector::const_iterator i2 = i->second.begin(); i2 != i->second.end(); ++i2) + { + if(firstInList) + firstInList = false; + else + result += cs_comma; + result += i2->empty() ? Unicode::narrowToWide(getEmptyStringPlaceholder()) : Unicode::narrowToWide(*i2); + } + } + return result; +} + +//---------------------------------------------------------------------- + +FormManager::UnpackedFormData FormManager::unpackFormData(PackedFormData const & packedData) +{ + UnpackedFormData result; + + //turn unicode::string formatted as "key1 value1,value2,value3 key2 value1 key3 value1,value2..." into a map > + + Unicode::UnicodeStringVector tokens; + IGNORE_RETURN(Unicode::tokenize(packedData, tokens)); + + //must have an even number of tokens (key/value pairs) + if(tokens.size() % 2 != 0) + return result; + + std::string key; + std::string value; + std::vector values; + for(unsigned int i = 0; i + 1 < tokens.size(); i += 2) + { + key = Unicode::wideToNarrow(tokens[i]); + value = Unicode::wideToNarrow(tokens[i + 1]); + if(value == getEmptyStringPlaceholder()) + value.clear(); + + values.clear(); + //TODO parse out comma lists here + values.push_back(value); + result[key] = values; + } + + return result; +} + +//---------------------------------------------------------------------- + +bool FormManager::getAutomaticallyCreateObject(std::string const & serverObjectTemplate) +{ + std::map::iterator i = ms_automaticallyCreateObjectForServerObjectTemplate->find(serverObjectTemplate); + if(i != ms_automaticallyCreateObjectForServerObjectTemplate->end()) + return i->second; + else + return false; +} + +//---------------------------------------------------------------------- + +std::string const & FormManager::getEmptyStringPlaceholder() +{ + return cs_emptyStringPlaceholder; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/FormManager.h b/engine/shared/library/sharedGame/src/shared/core/FormManager.h new file mode 100644 index 00000000..19ac513a --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/FormManager.h @@ -0,0 +1,169 @@ +//====================================================================== +// +// FormManager.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_FormManager_H +#define INCLUDED_FormManager_H + +//====================================================================== + +class DataTable; + +//#include "sharedFoundation/StlForwardDeclaration.h" + +//---------------------------------------------------------------------- + +class FormManager +{ +public: + typedef Unicode::String PackedFormData; + typedef stdmap::fwd >::fwd UnpackedFormData; + + //the various types of fields that the form can support + enum FieldType + { + INT, + FLOAT, + STRING, + INTARRAY, + FLOATARRAY, + STRINGARRAY + }; + + //validation rules not expressed elsewhere in the data + enum OtherValidationRules + { + NOT_EMPTY + }; + + //the list of commands that are sent from the client to the server + enum Command + { + CREATE_OBJECT, + EDIT_OBJECT, + REQUEST_EDIT_OBJECT + }; + + class Form; + + /**A field inside the form. It represents one logical field, and can validate its own data + */ + class Field + { + //allow fellow inner class and containing manager to access privates + friend class Form; + friend class FormManager; + + public: + Field(Form const * const parent); + ~Field(); + + bool isIntType() const; + bool isFloatType() const; + bool isStringType() const; + bool isArrayType() const; + bool isValidValue(std::string const & value, stdmap::fwd const & pendingData, std::string & errorString /*OUT*/) const; + bool isValidValue(int value, stdmap::fwd const & pendingData, std::string & errorString /*OUT*/) const; + bool isValidValue(float value, stdmap::fwd const & pendingData, std::string & errorString /*OUT*/) const; + int getMinimumIntValue(stdmap::fwd const & pendingData, std::string & validationField /*OUT*/) const; + int getMaximumIntValue(stdmap::fwd const & pendingData, std::string & validationField /*OUT*/) const; + float getMinimumFloatValue(stdmap::fwd const & pendingData, std::string & validationField /*OUT*/) const; + float getMaximumFloatValue(stdmap::fwd const & pendingData, std::string & validationField /*OUT*/) const; + + std::string const & getName() const; + std::string const & getExternalName() const; + stdvector::fwd const & getOtherValidationRules() const; + std::string const & getDefaultValue() const; + std::string const & getObjvarBinding() const; + + private: + Field(); + Field (const Field &); + Field & operator= (const Field &); + + private: + std::string m_name; + FieldType m_type; + std::string m_externalName; + std::string m_defaultValue; + std::string m_minimumValue; + std::string m_maximumValue; + bool m_minimumValueSet; + bool m_maximumValueSet; + stdvector::fwd * m_choices; + bool m_mustUseList; + std::string m_validationFilename; + int m_validationFilenameColumn; + stdvector::fwd * m_otherValidationRules; + Form const * m_parentForm; + std::string m_objvarBinding; + }; + + /**Representation of the form. It holds a set of fields + */ + class Form + { + //allow containing manager to access privates + friend class FormManager; + + public: + bool isNameOfField(std::string const & fieldName) const; + Field const * getField(std::string const & fieldName) const; + std::string const & getName() const; + stdvector::fwd const & getOrderedFieldList() const; + + Form(); + virtual ~Form(); + + private: + Form (const Form &); + Form & operator= (const Form &); + + private: + std::string m_name; + stdmap::fwd* m_fields; + stdvector::fwd* m_orderedFieldList; + }; + +//This is an "abstract" static manager, which is instanciated by clientGame/FormManagerClient and serverGame/FormManagerServer +protected: + static void install (); + static void remove (); + virtual ~FormManager(); + +public: + static void reloadData(); + static Form const * getFormByName(std::string const & formName); + static Form const * getFormForServerObjectTemplate(std::string const & serverObjectTemplate); + static Form const * getFormForSharedObjectTemplate(std::string const & sharedObjectTemplate); + static bool getAutomaticallyCreateObject(std::string const & serverObjectTemplate); + static std::string const & getEmptyStringPlaceholder(); + + static PackedFormData packFormData(UnpackedFormData const & unpackedData); + static UnpackedFormData unpackFormData(PackedFormData const & packedData); + + static std::string const & getFormCommandName(); + +private: + static void clearData(); + static void loadData(); + static void validateData(); + static void loadTable(DataTable const & table, std::string const & tableName, std::string const & formName); + +private: + //this map OWNS the Form pointers + static stdmap::fwd * ms_forms; + //this map hold pointers to Forms, but does NOT own them + static stdmap::fwd * ms_serverObjectTemplateToForms; + //this map hold pointers to Forms, but does NOT own them + static stdmap::fwd * ms_sharedObjectTemplateToForms; + //this map stores whether a particular server template was mapped for an "auto-object-creating" form in formmap.tab + static stdmap::fwd * ms_automaticallyCreateObjectForServerObjectTemplate; +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/GameLanguageManager.cpp b/engine/shared/library/sharedGame/src/shared/core/GameLanguageManager.cpp new file mode 100644 index 00000000..58530671 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/GameLanguageManager.cpp @@ -0,0 +1,432 @@ +// ============================================================================ +// +// GameLanguageManager.cpp +// Copyright Sony Online Entertainment, Inc. +// +// ============================================================================ + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/GameLanguageManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/Iff.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedGame/SharedStringIds.h" +#include "sharedUtility/DataTable.h" +#include "UnicodeUtils.h" + +#include +#include + +// ============================================================================ +// +// GameLanguageManagerNamespace +// +// ============================================================================ + +namespace GameLanguageManagerNamespace +{ + typedef std::vector StringVector; + + struct LanguageInfo + { + LanguageInfo(); + + Unicode::String m_localizedName; + StringVector m_alphabet; + int m_id; + bool m_audible; + std::string m_speakSkillModName; + std::string m_comprehendSkillModName; + std::string m_stringIdName; + }; + + typedef std::map GameLanguages; + + bool s_installed = false; + unsigned int s_minimumAbbreviationLength = 5; + GameLanguages s_gameLanguages; +} + +using namespace GameLanguageManagerNamespace; + +//----------------------------------------------------------------------------- +GameLanguageManagerNamespace::LanguageInfo::LanguageInfo() + : m_localizedName() + , m_alphabet() + , m_id(0) // basic language +{ +} + +// ============================================================================ +// +// GameLanguageManager +// +// ============================================================================ + +//----------------------------------------------------------------------------- +void GameLanguageManager::install() +{ + InstallTimer const installTimer("GameLanguageManager::install"); + + DEBUG_FATAL(s_installed,("GameLanguageManager already installed.\n")); + s_installed = true; + ExitChain::add(remove,"GameLanguageManager::remove"); + + // Languages + + char const gameLanguageFile[] = "datatables/game_language/game_language.iff"; + Iff gameLanguageIff; + + if (gameLanguageIff.open(gameLanguageFile, true)) + { + DataTable dataTable; + + dataTable.load(gameLanguageIff); + + int const rowCount = dataTable.getNumRows(); + + s_gameLanguages.clear(); + + // Add all the words to the list in lowercase + + int languageId = 1; + + for (int index = 0; index < rowCount; ++index) + { + LanguageInfo languageInfo; + + languageInfo.m_alphabet.reserve(26); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("a", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("b", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("c", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("d", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("e", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("f", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("g", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("h", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("h", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("j", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("k", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("l", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("m", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("n", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("o", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("p", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("q", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("r", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("s", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("t", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("u", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("v", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("w", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("x", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("y", index)); + languageInfo.m_alphabet.push_back(dataTable.getStringValue("z", index)); + languageInfo.m_stringIdName = Unicode::toLower(dataTable.getStringValue("stringId", index)); + languageInfo.m_localizedName = StringId("game_language", languageInfo.m_stringIdName).localize(); + languageInfo.m_id = languageId; + languageInfo.m_audible = (dataTable.getIntValue("audible", index) != 0); + languageInfo.m_speakSkillModName = Unicode::toLower(dataTable.getStringValue("speakSkillModName", index)); + languageInfo.m_comprehendSkillModName = Unicode::toLower(dataTable.getStringValue("comprehendSkillModName", index)); + + s_gameLanguages.insert(std::make_pair(languageInfo.m_stringIdName, languageInfo)); + ++languageId; + } + } + else + { + DEBUG_WARNING(true, ("Unable to load the species language data table: %s", gameLanguageFile)); + } +} + +// ---------------------------------------------------------------------------- +void GameLanguageManager::remove() +{ + s_installed = false; +} + +//----------------------------------------------------------------------------- +void GameLanguageManager::getLanguages(StringVector &languages) +{ + languages.clear(); + languages.reserve(s_gameLanguages.size()); + + GameLanguages::const_iterator iterGameLanguages = s_gameLanguages.begin(); + + for (; iterGameLanguages != s_gameLanguages.end(); ++iterGameLanguages) + { + std::string const &gameLanguage = iterGameLanguages->first; + + languages.push_back(gameLanguage); + } +} + +//----------------------------------------------------------------------------- +bool GameLanguageManager::isLanguageValid(std::string const &languageName) +{ + bool result = false; + GameLanguages::const_iterator iterGameLanguages = s_gameLanguages.find(languageName); + + if (iterGameLanguages != s_gameLanguages.end()) + { + result = true; + } + + return result; +} + +//----------------------------------------------------------------------------- +bool GameLanguageManager::isLanguageAbbreviationValid(Unicode::String const &abbreviation, uint32 &language) +{ + bool result = false; + GameLanguages::const_iterator iterGameLanguages = s_gameLanguages.begin(); + + for (; iterGameLanguages != s_gameLanguages.end(); ++iterGameLanguages) + { + std::string lowerAbbreviation(Unicode::wideToNarrow(Unicode::toLower(abbreviation))); + + // See if the first three characters match up + + if (((lowerAbbreviation.size() >= s_minimumAbbreviationLength) || + (lowerAbbreviation.size() == iterGameLanguages->second.m_stringIdName.size())) && + (lowerAbbreviation.size() <= iterGameLanguages->second.m_stringIdName.size())) + { + result = true; + + // Check the characters of the abbreviation vs the actual name + + for (unsigned int i = 0; i < lowerAbbreviation.size(); ++i) + { + if (lowerAbbreviation[i] != iterGameLanguages->second.m_stringIdName[i]) + { + result = false; + break; + } + } + + if (result) + { + language = static_cast(iterGameLanguages->second.m_id); + break; + } + } + } + + return result; +} + +//----------------------------------------------------------------------------- +bool GameLanguageManager::isLanguageValid(int const languageId) +{ + bool result = false; + GameLanguages::const_iterator iterGameLanguages = s_gameLanguages.begin(); + + for (; iterGameLanguages != s_gameLanguages.end(); ++iterGameLanguages) + { + if (iterGameLanguages->second.m_id == languageId) + { + result = true; + break; + } + } + + return result; +} + +//----------------------------------------------------------------------------- +void GameLanguageManager::getLanguageSpeakSkillModName(int const languageId, std::string &skillModName) +{ + skillModName.clear(); + + std::string languageName; + getLanguageName(languageId, languageName); + + GameLanguages::const_iterator iterGameLanguages = s_gameLanguages.find(languageName); + + if (iterGameLanguages != s_gameLanguages.end()) + { + skillModName = iterGameLanguages->second.m_speakSkillModName; + } +} + +//----------------------------------------------------------------------------- +void GameLanguageManager::getLanguageComprehendSkillModName(int const languageId, std::string &skillModName) +{ + skillModName.clear(); + + std::string languageName; + getLanguageName(languageId, languageName); + + GameLanguages::const_iterator iterGameLanguages = s_gameLanguages.find(languageName); + + if (iterGameLanguages != s_gameLanguages.end()) + { + skillModName = iterGameLanguages->second.m_comprehendSkillModName; + } +} + +//----------------------------------------------------------------------------- +int GameLanguageManager::getLanguageId(std::string const &language) +{ + int result = 0; + + GameLanguages::const_iterator iterGameLanguages = s_gameLanguages.find(language); + + if (iterGameLanguages != s_gameLanguages.end()) + { + result = iterGameLanguages->second.m_id; + } + + return result; +} + +//----------------------------------------------------------------------------- +bool GameLanguageManager::isLanguageAudible(int const languageId) +{ + bool result = false; + + if (languageId > 0) + { + GameLanguages::const_iterator iterGameLanguages = s_gameLanguages.begin(); + + for (; iterGameLanguages != s_gameLanguages.end(); ++iterGameLanguages) + { + if (iterGameLanguages->second.m_id == languageId) + { + result = iterGameLanguages->second.m_audible; + } + } + } + + return result; +} + +//----------------------------------------------------------------------------- +void GameLanguageManager::convertToLanguage(Unicode::String const &source, int const languageId, Unicode::String &destination) +{ + if (languageId > 0) + { + GameLanguages::const_iterator iterGameLanguages = s_gameLanguages.begin(); + + for (; iterGameLanguages != s_gameLanguages.end(); ++iterGameLanguages) + { + if (iterGameLanguages->second.m_id == languageId) + { + destination.clear(); + + // Found the destination language, convert the string + + std::string result; + std::string narrowString(Unicode::wideToNarrow(source)); + int const narrowStringSize = static_cast(narrowString.size()); + + for (int i = 0; i < narrowStringSize; ++i) + { + char const character = narrowString[i]; + int const adjustedCharacter = static_cast((character < 97) ? (character + 32) : character) - 97; + int const alphabetSize = static_cast(iterGameLanguages->second.m_alphabet.size()); + + if ((alphabetSize == 26) && + (adjustedCharacter >= 0) && + (adjustedCharacter < alphabetSize) && + !iterGameLanguages->second.m_alphabet[adjustedCharacter].empty()) + { + if (character >= 97) + { + // lowercase + + result += iterGameLanguages->second.m_alphabet[adjustedCharacter]; + } + else + { + // uppercase + + result += Unicode::toUpper(iterGameLanguages->second.m_alphabet[adjustedCharacter]); + } + } + else + { + result += narrowString[i]; + } + } + + destination = Unicode::narrowToWide(result); + + break; + } + } + } + else + { + destination = source; + } +} + +//----------------------------------------------------------------------------- +void GameLanguageManager::getLanguageName(int const languageId, std::string &name) +{ + name.clear(); + GameLanguages::const_iterator iterGameLanguages = s_gameLanguages.begin(); + + for (; iterGameLanguages != s_gameLanguages.end(); ++iterGameLanguages) + { + if (iterGameLanguages->second.m_id == languageId) + { + name = iterGameLanguages->first; + break; + } + } +} + +//----------------------------------------------------------------------------- +int GameLanguageManager::getBasicLanguageId() +{ + return getLanguageId("basic"); +} + +//----------------------------------------------------------------------------- +void GameLanguageManager::getLocalizedLanguageName(int const languageId, Unicode::String &localizedLanguage) +{ + std::string name; + + getLanguageName(languageId, name); + getLocalizedLanguageName(name, localizedLanguage); +} + +//----------------------------------------------------------------------------- +void GameLanguageManager::getLocalizedLanguageName(std::string const &language, Unicode::String &localizedLanguage) +{ + localizedLanguage.clear(); + + if (language.empty()) + { + localizedLanguage = SharedStringIds::basic.localize(); + } + else + { + GameLanguages::const_iterator iterGameLanguages = s_gameLanguages.find(language); + + if (iterGameLanguages != s_gameLanguages.end()) + { + localizedLanguage = iterGameLanguages->second.m_localizedName; + } + } +} + +//----------------------------------------------------------------------------- +int GameLanguageManager::getStartingLanguage(SharedCreatureObjectTemplate::Species const species) +{ + int result = getBasicLanguageId(); + + // Wookies start with Shyriiwook + + if (species == SharedCreatureObjectTemplate::SP_wookiee) + { + result = getLanguageId("shyriiwook"); + } + + return result; +} + +// ============================================================================ diff --git a/engine/shared/library/sharedGame/src/shared/core/GameLanguageManager.h b/engine/shared/library/sharedGame/src/shared/core/GameLanguageManager.h new file mode 100644 index 00000000..d4f3b031 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/GameLanguageManager.h @@ -0,0 +1,55 @@ +// ============================================================================ +// +// GameGameLanguageManager.h +// Copyright Sony Online Entertainment, Inc. +// +// ============================================================================ + +#ifndef INCLUDED_GameLanguageManager_H +#define INCLUDED_GameLanguageManager_H + +#include "sharedGame/SharedCreatureObjectTemplate.h" + +//----------------------------------------------------------------------------- +class GameLanguageManager +{ +public: + + typedef stdvector::fwd StringVector; + + static void install(); + +public: + + static bool isLanguageValid(std::string const &languageName); + static bool isLanguageValid(int const languageId); + static bool isLanguageAbbreviationValid(Unicode::String const &abbreviation, uint32 &language); + static bool isLanguageAudible(int const languageId); + + static void getLanguages(StringVector &languages); + static void getLanguageName(int const languageId, std::string &name); + static void getLocalizedLanguageName(int const languageId, Unicode::String &localizedLanguage); + static void getLocalizedLanguageName(std::string const &language, Unicode::String &localizedLanguage); + static void getLanguageSpeakSkillModName(int const languageId, std::string &skillModName); + static void getLanguageComprehendSkillModName(int const languageId, std::string &skillModName); + static int getBasicLanguageId(); + static int getStartingLanguage(SharedCreatureObjectTemplate::Species const species); + static int getLanguageId(std::string const &language); + + static void convertToLanguage(Unicode::String const &source, int const languageId, Unicode::String &destination); + +private: + + static void remove(); + + // Disable + + GameLanguageManager(); + ~GameLanguageManager(); + GameLanguageManager(GameLanguageManager const &); + GameLanguageManager &operator =(GameLanguageManager const &); +}; + +// ============================================================================ + +#endif // INCLUDED_GameLanguageManager_H diff --git a/engine/shared/library/sharedGame/src/shared/core/GameObjectTypes.cpp b/engine/shared/library/sharedGame/src/shared/core/GameObjectTypes.cpp new file mode 100644 index 00000000..4e23e9c0 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/GameObjectTypes.cpp @@ -0,0 +1,562 @@ +//====================================================================== +// +// GameObjectTypes.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/GameObjectTypes.h" + +#include "sharedGame/SharedObjectTemplate.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" +#include "UnicodeUtils.h" +#include +#include +#include + +//====================================================================== + +namespace +{ + typedef GameObjectTypes::TypeStringIdMap TypeStringIdMap; + typedef GameObjectTypes::TypeStringMap TypeStringMap; + typedef GameObjectTypes::StringTypeMap StringTypeMap; + typedef GameObjectTypes::TypeUnicodeStringMap TypeUnicodeStringMap; + + TypeStringIdMap typeStringIds; + TypeStringMap typeStrings; + StringTypeMap stringTypes; + TypeUnicodeStringMap typeUnicodeStrings; + std::map typeExcludedFromCommodities; + + bool installed = false; + + static const std::string stringTableName = "got_n"; + + const std::string emptyString ("unknown"); + const StringId emptyStringId (stringTableName, "unknown"); + const Unicode::String emptyUnicodeString (Unicode::narrowToWide ("Serious Error")); + + void install () + { + DEBUG_FATAL (installed, ("already installed")); + + installed = true; + +#define MAKE_NAME(a) typeStrings [SharedObjectTemplate::GOT_##a] = #a ; + + MAKE_NAME(none); + MAKE_NAME(corpse); + MAKE_NAME(group); + MAKE_NAME(guild); + MAKE_NAME(lair); + MAKE_NAME(static); + MAKE_NAME(camp); + MAKE_NAME(vendor); + MAKE_NAME(loadbeacon); + MAKE_NAME(armor); + MAKE_NAME(armor_body); + MAKE_NAME(armor_head); + MAKE_NAME(armor_misc); + MAKE_NAME(armor_leg); + MAKE_NAME(armor_arm); + MAKE_NAME(armor_hand); + MAKE_NAME(armor_foot); + MAKE_NAME(armor_shield); + MAKE_NAME(armor_layer); + MAKE_NAME(armor_segment); + MAKE_NAME(armor_core); + MAKE_NAME(armor_psg); + MAKE_NAME(building); + MAKE_NAME(building_municipal); + MAKE_NAME(building_player); + MAKE_NAME(building_factional); + MAKE_NAME(creature); + MAKE_NAME(creature_character); + MAKE_NAME(creature_droid); + MAKE_NAME(creature_droid_probe); + MAKE_NAME(creature_monster); + MAKE_NAME(data); + MAKE_NAME(data_draft_schematic); + MAKE_NAME(data_manufacturing_schematic); + MAKE_NAME(data_mission_object); + MAKE_NAME(data_token); + MAKE_NAME(data_waypoint); + MAKE_NAME(data_fictional); + MAKE_NAME(data_pet_control_device); + MAKE_NAME(data_vehicle_control_device); + MAKE_NAME(data_draft_schematic_read_only); + MAKE_NAME(data_ship_control_device); + MAKE_NAME(data_droid_control_device); + MAKE_NAME(data_house_control_device); + MAKE_NAME(data_vendor_control_device); + MAKE_NAME(data_player_quest_object); + MAKE_NAME(installation); + MAKE_NAME(installation_factory); + MAKE_NAME(installation_generator); + MAKE_NAME(installation_harvester); + MAKE_NAME(installation_turret); + MAKE_NAME(installation_minefield); + MAKE_NAME(misc); + MAKE_NAME(misc_ammunition); + MAKE_NAME(misc_chemical); + MAKE_NAME(misc_clothing_DUMMY); + MAKE_NAME(misc_component_DUMMY); + MAKE_NAME(misc_container); + MAKE_NAME(misc_crafting_station); + MAKE_NAME(misc_deed_DUMMY); + MAKE_NAME(misc_electronics); + MAKE_NAME(misc_flora); + MAKE_NAME(misc_food); + MAKE_NAME(misc_furniture); + MAKE_NAME(misc_instrument); + MAKE_NAME(misc_pharmaceutical); + MAKE_NAME(misc_resource_container_DUMMY); + MAKE_NAME(misc_sign); + MAKE_NAME(misc_counter); + MAKE_NAME(misc_factory_crate); + MAKE_NAME(misc_ticket_travel); + MAKE_NAME(misc_item); + MAKE_NAME(misc_trap); + MAKE_NAME(misc_container_wearable); + MAKE_NAME(misc_fishing_pole); + MAKE_NAME(misc_fishing_bait); + MAKE_NAME(misc_drink); + MAKE_NAME(misc_firework); + MAKE_NAME(misc_item_usable); + MAKE_NAME(misc_petmed); + MAKE_NAME(misc_firework_show); + MAKE_NAME(misc_clothing_attachment); + MAKE_NAME(misc_live_sample); + MAKE_NAME(misc_armor_attachment); + MAKE_NAME(misc_community_crafting_project); + MAKE_NAME(misc_force_crystal); + MAKE_NAME(misc_droid_programming_chip); + MAKE_NAME(misc_asteroid); + MAKE_NAME(misc_pob_ship_pilot_chair); + MAKE_NAME(misc_operations_chair); + MAKE_NAME(misc_turret_access_ladder); + MAKE_NAME(misc_container_ship_loot); + MAKE_NAME(misc_armor_noequip); + MAKE_NAME(misc_enzyme); + MAKE_NAME(misc_food_pet); + MAKE_NAME(misc_collection); + MAKE_NAME(misc_container_public); + MAKE_NAME(misc_ground_target); + MAKE_NAME(misc_blueprint); + MAKE_NAME(misc_enzyme_isomerase); + MAKE_NAME(misc_enzyme_lyase); + MAKE_NAME(misc_enzyme_hydrolase); + MAKE_NAME(misc_tcg_card); + MAKE_NAME(misc_appearance_only); + MAKE_NAME(misc_appearance_only_invisible); + MAKE_NAME(terminal); + MAKE_NAME(terminal_bank); + MAKE_NAME(terminal_bazaar); + MAKE_NAME(terminal_cloning); + MAKE_NAME(terminal_insurance); + MAKE_NAME(terminal_manage); + MAKE_NAME(terminal_mission); + MAKE_NAME(terminal_permissions); + MAKE_NAME(terminal_player_structure); + MAKE_NAME(terminal_shipping); + MAKE_NAME(terminal_travel); + MAKE_NAME(terminal_space); + MAKE_NAME(terminal_misc); + MAKE_NAME(terminal_space_npe); + MAKE_NAME(tool); + MAKE_NAME(tool_crafting); + MAKE_NAME(tool_survey); + MAKE_NAME(tool_repair); + MAKE_NAME(tool_camp_kit); + MAKE_NAME(tool_ship_component_repair); + MAKE_NAME(vehicle); + MAKE_NAME(vehicle_hover); + MAKE_NAME(vehicle_hover_ai); + MAKE_NAME(weapon); + MAKE_NAME(weapon_melee_misc); + MAKE_NAME(weapon_ranged_misc); + MAKE_NAME(weapon_ranged_thrown); + MAKE_NAME(weapon_heavy_misc); + MAKE_NAME(weapon_heavy_mine); + MAKE_NAME(weapon_heavy_special); + MAKE_NAME(weapon_melee_1h); + MAKE_NAME(weapon_melee_2h); + MAKE_NAME(weapon_melee_polearm); + MAKE_NAME(weapon_ranged_pistol); + MAKE_NAME(weapon_ranged_carbine); + MAKE_NAME(weapon_ranged_rifle); + MAKE_NAME(component); + MAKE_NAME(component_armor); + MAKE_NAME(component_chemistry); + MAKE_NAME(component_clothing); + MAKE_NAME(component_droid); + MAKE_NAME(component_electronics); + MAKE_NAME(component_munition); + MAKE_NAME(component_structure); + MAKE_NAME(component_weapon_melee); + MAKE_NAME(component_weapon_ranged); + MAKE_NAME(component_tissue); + MAKE_NAME(component_genetic); + MAKE_NAME(component_saber_crystal); + MAKE_NAME(component_community_crafting); + MAKE_NAME(component_new_armor); + MAKE_NAME(powerup_weapon); + MAKE_NAME(powerup_weapon_melee); + MAKE_NAME(powerup_weapon_ranged); + MAKE_NAME(powerup_weapon_thrown); + MAKE_NAME(powerup_weapon_heavy); + MAKE_NAME(powerup_weapon_mine); + MAKE_NAME(powerup_weapon_heavy_special); + MAKE_NAME(powerup_armor); + MAKE_NAME(powerup_armor_body); + MAKE_NAME(powerup_armor_head); + MAKE_NAME(powerup_armor_misc); + MAKE_NAME(powerup_armor_leg); + MAKE_NAME(powerup_armor_arm); + MAKE_NAME(powerup_armor_hand); + MAKE_NAME(powerup_armor_foot); + MAKE_NAME(powerup_armor_layer); + MAKE_NAME(powerup_armor_segment); + MAKE_NAME(powerup_armor_core); + MAKE_NAME(jewelry); + MAKE_NAME(jewelry_ring); + MAKE_NAME(jewelry_bracelet); + MAKE_NAME(jewelry_necklace); + MAKE_NAME(jewelry_earring); + MAKE_NAME(resource_container); + MAKE_NAME(resource_container_energy_gas); + MAKE_NAME(resource_container_energy_liquid); + MAKE_NAME(resource_container_energy_radioactive); + MAKE_NAME(resource_container_energy_solid); + MAKE_NAME(resource_container_inorganic_chemicals); + MAKE_NAME(resource_container_inorganic_gas); + MAKE_NAME(resource_container_inorganic_minerals); + MAKE_NAME(resource_container_inorganic_water); + MAKE_NAME(resource_container_organic_food); + MAKE_NAME(resource_container_organic_hide); + MAKE_NAME(resource_container_organic_structure); + MAKE_NAME(resource_container_pseudo); + MAKE_NAME(resource_container_space); + MAKE_NAME(deed); + MAKE_NAME(deed_building); + MAKE_NAME(deed_installation); + MAKE_NAME(deed_pet); + MAKE_NAME(deed_droid); + MAKE_NAME(deed_vehicle); + MAKE_NAME(clothing); + MAKE_NAME(clothing_bandolier); + MAKE_NAME(clothing_belt); + MAKE_NAME(clothing_bodysuit); + MAKE_NAME(clothing_cape); + MAKE_NAME(clothing_cloak); + MAKE_NAME(clothing_foot); + MAKE_NAME(clothing_dress); + MAKE_NAME(clothing_hand); + MAKE_NAME(clothing_eye); + MAKE_NAME(clothing_head); + MAKE_NAME(clothing_jacket); + MAKE_NAME(clothing_pants); + MAKE_NAME(clothing_robe); + MAKE_NAME(clothing_shirt); + MAKE_NAME(clothing_vest); + MAKE_NAME(clothing_wookiee); + MAKE_NAME(clothing_misc); + MAKE_NAME(clothing_skirt); + MAKE_NAME(ship_component); + MAKE_NAME(ship_component_reactor); + MAKE_NAME(ship_component_engine); + MAKE_NAME(ship_component_shield); + MAKE_NAME(ship_component_armor); + MAKE_NAME(ship_component_weapon); + MAKE_NAME(ship_component_capacitor); + MAKE_NAME(ship_component_booster); + MAKE_NAME(ship_component_droid_interface); + MAKE_NAME(ship_component_hangar); + MAKE_NAME(ship_component_targeting_station); + MAKE_NAME(ship_component_bridge); + MAKE_NAME(ship_component_chassis); + MAKE_NAME(ship_component_missilepack); + MAKE_NAME(ship_component_countermeasurepack); + MAKE_NAME(ship_component_missilelauncher); + MAKE_NAME(ship_component_countermeasurelauncher); + MAKE_NAME(ship_component_cargo_hold); + MAKE_NAME(ship_component_modification); + MAKE_NAME(ship); + MAKE_NAME(ship_fighter); + MAKE_NAME(ship_capital); + MAKE_NAME(ship_station); + MAKE_NAME(ship_transport); + MAKE_NAME(ship_mining_asteroid_static); + MAKE_NAME(ship_mining_asteroid_dynamic); + MAKE_NAME(cybernetic); + MAKE_NAME(cybernetic_arm); + MAKE_NAME(cybernetic_legs); + MAKE_NAME(cybernetic_torso); + MAKE_NAME(cybernetic_forearm); + MAKE_NAME(cybernetic_hand); + MAKE_NAME(cybernetic_component); + MAKE_NAME(chronicles); + MAKE_NAME(chronicles_relic); + MAKE_NAME(chronicles_chronicle); + MAKE_NAME(chronicles_quest_holocron); + MAKE_NAME(chronicles_quest_holocron_recipe); + MAKE_NAME(chronicles_relic_fragment); + +#undef MAKE_NAME + + for (TypeStringMap::const_iterator it = typeStrings.begin (); it != typeStrings.end (); ++it) + { + const int got = (*it).first; + const std::string & gotName = (*it).second; + typeStringIds.insert (std::make_pair (got, StringId (stringTableName, gotName))); + stringTypes.insert (std::make_pair (Unicode::toLower(gotName), got)); + } + + DataTable const * const commoditiesExclusionData = DataTableManager::getTable("datatables/commodity/got_exclusion.iff", true); + if (!commoditiesExclusionData) + { + WARNING(true, ("Could not find commodities GOT type exclusion data table datatables/commodity/got_exclusion.iff")); + return; + } + + int const gotColumn = commoditiesExclusionData->findColumnNumber("got"); + if (gotColumn < 0) + { + WARNING(true, ("Could not find column \"got\" in commodities GOT type exclusion data table datatables/commodity/got_exclusion.iff")); + return; + } + + unsigned int const numRows = static_cast(commoditiesExclusionData->getNumRows()); + if (numRows == 0) + { + WARNING(true, ("Commodities GOT type exclusion data table datatables/commodity/got_exclusion.iff is empty")); + return; + } + + for (unsigned int i = 0; i < numRows; ++i) + { + std::string const excludeGot = commoditiesExclusionData->getStringValue(gotColumn, i); + + StringTypeMap::const_iterator const it = stringTypes.find(Unicode::toLower(excludeGot)); + FATAL((it == stringTypes.end()), ("Commodities GOT type exclusion data table datatables/commodity/got_exclusion.iff contains a non-existing GOT type %s", excludeGot.c_str())); + + typeExcludedFromCommodities[it->second] = excludeGot; + } + } +} + +//---------------------------------------------------------------------- + +const int GameObjectTypes::ms_type_mask = 0xffffff00; + +//---------------------------------------------------------------------- + +bool GameObjectTypes::getTypeByName (const std::string & name, int & type) +{ + if (!installed) + install (); + + StringTypeMap::const_iterator const it = stringTypes.find (Unicode::toLower (name.c_str ())); + if (it != stringTypes.end ()) + { + type = (*it).second; + return true; + } + + return false; +} + +//---------------------------------------------------------------------- + +const std::string & GameObjectTypes::getCanonicalName (int type) +{ + if (!installed) + install (); + + TypeStringMap::const_iterator it = typeStrings.find (type); + if (it != typeStrings.end ()) + return (*it).second; + + return emptyString; +} + +//---------------------------------------------------------------------- + +int GameObjectTypes::getGameObjectType (std::string const & canonicalName) +{ + if (!installed) + install (); + + StringTypeMap::const_iterator const it = stringTypes.find (Unicode::toLower (canonicalName.c_str ())); + if (it != stringTypes.end ()) + { + return it->second; + } + + return 0; +} + +//---------------------------------------------------------------------- + +const StringId & GameObjectTypes::getStringId (int type) +{ + if (!installed) + install (); + + const SharedObjectTemplate::GameObjectType got = static_cast(type); + + TypeStringIdMap::const_iterator it = typeStringIds.find (got); + if (it != typeStringIds.end ()) + return (*it).second; + + return emptyStringId; +} + +//---------------------------------------------------------------------- + +const Unicode::String & GameObjectTypes::getLocalizedName (int type) +{ + if (!installed) + install (); + + const SharedObjectTemplate::GameObjectType got = static_cast(type); + + TypeUnicodeStringMap::const_iterator it = typeUnicodeStrings.find (got); + if (it != typeUnicodeStrings.end ()) + return (*it).second; + + const StringId & stringId = getStringId (type); + + if (!stringId.isInvalid ()) + { + return (typeUnicodeStrings [got] = stringId.localize ()); + } + + return emptyUnicodeString; +} + +//---------------------------------------------------------------------- + +bool GameObjectTypes::isTypeOf (int type, int typeToTestAgainst) +{ + if (type == typeToTestAgainst) + return true; + + if (getMaskedType (type) == typeToTestAgainst) + return true; + + return false; +} + +//---------------------------------------------------------------------- + +const GameObjectTypes::TypeStringMap & GameObjectTypes::getTypeStringMap () +{ + if (!installed) + install (); + + return typeStrings; +} + +//---------------------------------------------------------------------- + +bool GameObjectTypes::isSubType (int type) +{ + return (type & ~ms_type_mask) != 0; +} + +//---------------------------------------------------------------------- + +bool GameObjectTypes::doesPowerupApply (int powerupType, int targetType) +{ + //@todo: this should be data driven + typedef stdvector::fwd IntVector; + typedef stdmap::fwd IntVectorMap; + static IntVectorMap s_powerupGotMap; + static bool s_powerupGotMapInstalled = false; + if (!s_powerupGotMapInstalled) + { + s_powerupGotMapInstalled = true; + + IntVector iv; + iv.clear (); + iv.push_back (SharedObjectTemplate::GOT_weapon_melee_misc); + iv.push_back (SharedObjectTemplate::GOT_weapon_melee_1h); + iv.push_back (SharedObjectTemplate::GOT_weapon_melee_2h); + iv.push_back (SharedObjectTemplate::GOT_weapon_melee_polearm); + std::sort (iv.begin (), iv.end ()); + s_powerupGotMap.insert (std::make_pair (SharedObjectTemplate::GOT_powerup_weapon_melee, iv)); + + iv.clear (); + iv.push_back (SharedObjectTemplate::GOT_weapon_ranged_misc); + iv.push_back (SharedObjectTemplate::GOT_weapon_ranged_pistol); + iv.push_back (SharedObjectTemplate::GOT_weapon_ranged_carbine); + iv.push_back (SharedObjectTemplate::GOT_weapon_ranged_rifle); + std::sort (iv.begin (), iv.end ()); + s_powerupGotMap.insert (std::make_pair (SharedObjectTemplate::GOT_powerup_weapon_ranged, iv)); + + iv.clear (); + iv.push_back (SharedObjectTemplate::GOT_weapon_ranged_thrown); + std::sort (iv.begin (), iv.end ()); + s_powerupGotMap.insert (std::make_pair (SharedObjectTemplate::GOT_powerup_weapon_thrown, iv)); + + iv.clear (); + iv.push_back (SharedObjectTemplate::GOT_weapon_heavy_misc); + std::sort (iv.begin (), iv.end ()); + s_powerupGotMap.insert (std::make_pair (SharedObjectTemplate::GOT_powerup_weapon_heavy, iv)); + + iv.clear (); + iv.push_back (SharedObjectTemplate::GOT_weapon_heavy_special); + std::sort (iv.begin (), iv.end ()); + s_powerupGotMap.insert (std::make_pair (SharedObjectTemplate::GOT_powerup_weapon_heavy_special, iv)); + + iv.clear (); + iv.push_back (SharedObjectTemplate::GOT_weapon_heavy_mine); + std::sort (iv.begin (), iv.end ()); + s_powerupGotMap.insert (std::make_pair (SharedObjectTemplate::GOT_powerup_weapon_mine, iv)); + } + + if ((GameObjectTypes::isTypeOf (powerupType, SharedObjectTemplate::GOT_powerup_armor) && GameObjectTypes::isTypeOf (targetType, SharedObjectTemplate::GOT_armor)) || + (GameObjectTypes::isTypeOf (powerupType, SharedObjectTemplate::GOT_powerup_weapon) && GameObjectTypes::isTypeOf (targetType, SharedObjectTemplate::GOT_weapon))) + { + const IntVectorMap::const_iterator it = s_powerupGotMap.find (powerupType); + + if (it != s_powerupGotMap.end ()) + { + const IntVector & iv = (*it).second; + + //-- powerup not applicable to target + if (!std::binary_search (iv.begin (), iv.end (), targetType)) + return false; + } + + return true; + } + + return false; +} + +//---------------------------------------------------------------------- + +bool GameObjectTypes::isExcludedFromCommodities(int type) +{ + if (!installed) + install(); + + return (typeExcludedFromCommodities.count(type) > 0); +} + +//---------------------------------------------------------------------- + +std::map const & GameObjectTypes::getTypesExcludedFromCommodities() +{ + if (!installed) + install(); + + return typeExcludedFromCommodities; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/GameObjectTypes.h b/engine/shared/library/sharedGame/src/shared/core/GameObjectTypes.h new file mode 100644 index 00000000..bbd51b23 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/GameObjectTypes.h @@ -0,0 +1,65 @@ +//====================================================================== +// +// GameObjectTypes.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_GameObjectTypes_H +#define INCLUDED_GameObjectTypes_H + +//====================================================================== + +class StringId; + +//---------------------------------------------------------------------- + +class GameObjectTypes +{ +public: + + typedef stdmap::fwd TypeStringIdMap; + typedef stdmap::fwd TypeStringMap; + typedef stdmap::fwd StringTypeMap; + typedef stdmap::fwd TypeUnicodeStringMap; + + static const TypeStringMap & getTypeStringMap (); + + static const std::string & getCanonicalName (int type); + static const StringId & getStringId (int type); + static const Unicode::String & getLocalizedName (int type); + static int getGameObjectType (std::string const & canonicalName); + + static bool getTypeByName (const std::string & name, int & type); + + static bool isTypeOf (int type, int typeToTestAgainst); + static bool isSubType (int type); + + static int getMaskedType (int type); + static int getSubType (int type); + + static bool doesPowerupApply (int powerupType, int targetType); + + static bool isExcludedFromCommodities(int type); + static stdmap::fwd const & getTypesExcludedFromCommodities(); + + static const int ms_type_mask; +}; + +//---------------------------------------------------------------------- + +inline int GameObjectTypes::getMaskedType (int type) +{ + return (type & ms_type_mask); +} + +//---------------------------------------------------------------------- + +inline int GameObjectTypes::getSubType (int type) +{ + return (type & ~ms_type_mask); +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/GameScheduler.cpp b/engine/shared/library/sharedGame/src/shared/core/GameScheduler.cpp new file mode 100644 index 00000000..c23d15af --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/GameScheduler.cpp @@ -0,0 +1,83 @@ +// ====================================================================== +// +// GameScheduler.cpp +// Copyright 2002 Sony Online Entertainment Inc. +// All Rights Reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/GameScheduler.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/Scheduler.h" + +// ====================================================================== + +namespace GameSchedulerNamespace +{ + const int cs_ticksPerSecond = 60; + //const float cs_secondsPerTick = 1.0f / static_cast(cs_ticksPerSecond); + + Scheduler *s_scheduler; + bool s_installed; +} + +using namespace GameSchedulerNamespace; + +// ====================================================================== +// class GameScheduler: public static member functions. +// ====================================================================== + +void GameScheduler::install() +{ + InstallTimer const installTimer("GameScheduler::install"); + + DEBUG_FATAL(s_installed, ("GameScheduler already installed.")); + + IS_NULL(s_scheduler); + s_scheduler = new Scheduler(); + + s_installed = true; + ExitChain::add(remove, "GameScheduler"); +} + +// ---------------------------------------------------------------------- + +void GameScheduler::addCallback(Callback callback, const void *context, float elapsedTime) +{ + DEBUG_FATAL(!s_installed, ("GameScheduler not installed.")); + NOT_NULL(s_scheduler); + + const unsigned long elapsedTickCount = static_cast(elapsedTime * static_cast(cs_ticksPerSecond)); + s_scheduler->setCallback(callback, context, elapsedTickCount); +} + +// ---------------------------------------------------------------------- + +void GameScheduler::alter(float elapsedTime) +{ + DEBUG_FATAL(!s_installed, ("GameScheduler not installed.")); + NOT_NULL(s_scheduler); + + const unsigned long schedulerTickCount = s_scheduler->getCurrentCount() + static_cast(elapsedTime * static_cast(cs_ticksPerSecond)); + s_scheduler->update(schedulerTickCount); +} + +// ====================================================================== +// class GameScheduler: private static member functions. +// ====================================================================== + +void GameScheduler::remove() +{ + DEBUG_FATAL(!s_installed, ("GameScheduler not installed.")); + + delete s_scheduler; + s_scheduler = false; + + s_installed = false; +} + +// ====================================================================== + diff --git a/engine/shared/library/sharedGame/src/shared/core/GameScheduler.h b/engine/shared/library/sharedGame/src/shared/core/GameScheduler.h new file mode 100644 index 00000000..f2a1db6b --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/GameScheduler.h @@ -0,0 +1,36 @@ +// ====================================================================== +// +// GameScheduler.h +// Copyright 2002 Sony Online Entertainment Inc. +// All Rights Reserved. +// +// ====================================================================== + +#ifndef INCLUDED_GameScheduler_H +#define INCLUDED_GameScheduler_H + +// ====================================================================== + +class GameScheduler +{ +public: + + typedef void (*Callback)(const void *context); + +public: + + static void install(); + + static void addCallback(Callback callback, const void *context, float elapsedTime); + static void alter(float elapsedTime); + +private: + + static void remove(); + +}; + +// ====================================================================== + +#endif + diff --git a/engine/shared/library/sharedGame/src/shared/core/GroundZoneManager.cpp b/engine/shared/library/sharedGame/src/shared/core/GroundZoneManager.cpp new file mode 100644 index 00000000..bc38d3e0 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/GroundZoneManager.cpp @@ -0,0 +1,281 @@ +//====================================================================== +// +// GroundZoneManager.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/GroundZoneManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedGame/SharedBuildoutAreaManager.h" +#include "sharedTerrain/ProceduralTerrainAppearance.h" +#include "sharedTerrain/TerrainObject.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" + +#include + +//===================================================================== + +namespace GroundZoneManagerNamespace +{ + + static bool s_installed = false; + static std::string const ms_zoneSizesFile("datatables/instance/instance_areas.iff"); + + typedef std::map > ZoneSizeMap; + + static ZoneSizeMap ms_zoneSizes; + static std::map ms_adjustForNonSquare; + + static std::string cms_sceneAndAreaDelimeter("__"); +} + +using namespace GroundZoneManagerNamespace; + +//---------------------------------------------------------------------- + +void GroundZoneManager::install () +{ + InstallTimer const installTimer("GroundZoneManager::install"); + + DEBUG_FATAL (s_installed, ("already installed.\n")); + + ms_zoneSizes.clear(); + ms_adjustForNonSquare.clear(); + + DataTable * table = DataTableManager::getTable(ms_zoneSizesFile, true); + if(table) + { + int const numRows = table->getNumRows (); + + for (int i = 0; i < numRows; ++i) + { + const std::string &areaName = table->getStringValue("area", i); + const float x = table->getFloatValue("x", i); + const float z = table->getFloatValue("z", i); + const bool adjustForNonSquare = table->getIntValue("adjustForNonSquare", i) != 0; + + FATAL(z == 0, ("z CANNOT be 0.0f")); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + ZoneSizeMap::iterator result = ms_zoneSizes.insert( + ZoneSizeMap::value_type( + areaName, + std::pair(x, z) + ) + ).first; + + const std::string &actualKeyString = result->first; + ms_adjustForNonSquare[actualKeyString] = adjustForNonSquare; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + } + + DataTableManager::close(ms_zoneSizesFile); + } + + ExitChain::add(remove, "GroundZoneManager::remove"); + s_installed = true; +} + +//---------------------------------------------------------------------- + +void GroundZoneManager::remove () +{ + DEBUG_FATAL (!s_installed, ("not installed.\n")); + + ms_zoneSizes.clear(); + ms_adjustForNonSquare.clear(); + + s_installed = false; +} + +//---------------------------------------------------------------------- + +BuildoutArea const * GroundZoneManager::getZoneName(std::string const & sceneName, Vector const & location_w, std::string & zoneName) +{ + zoneName = sceneName; + + if(!SharedBuildoutAreaManager::isBuildoutScene(sceneName)) + { + return NULL; + } + else + { + BuildoutArea const * const ba = SharedBuildoutAreaManager::findBuildoutAreaAtPosition(sceneName, location_w.x, location_w.z, true); + if (NULL != ba) + { + if (!ba->compositeName.empty()) + zoneName = ba->compositeName; + else + zoneName = ba->areaName; + } + return ba; + } +} + +//---------------------------------------------------------------------- + +Vector GroundZoneManager::transformWorldLocationToZoneLocation(std::string const & sceneName, Vector const & location_w) +{ + Vector pos_w = location_w; + std::string zoneName; + BuildoutArea const * const ba = GroundZoneManager::getZoneName(sceneName, location_w, zoneName); + if (NULL != ba) + { + pos_w = ba->getRelativePosition(location_w, true); + } + + //if if this scene needs to be adjusted + if(!SharedBuildoutAreaManager::adjustMapCoordinatesForScene(sceneName)) + { + return pos_w; + } + + if (ba) + zoneName = sceneName + cms_sceneAndAreaDelimeter + zoneName; + + return adjustForNonSquareZones(zoneName, pos_w); +} + +//---------------------------------------------------------------------- + +Vector GroundZoneManager::adjustForNonSquareZones(std::string const & encodedZoneName, Vector const & zoneLocation) +{ + Vector result = zoneLocation; + + static std::string currentZone; + static Vector2d zoneSize; + static float xToZRatio = 1.0f; + + if (encodedZoneName != currentZone) + { + currentZone = encodedZoneName; + zoneSize = getZoneSize(currentZone.c_str()); + xToZRatio = getXToZRatioOfZone(currentZone.c_str()); + } + + if (ms_adjustForNonSquare[currentZone.c_str()]) + { + // now adjust for non-square zones + + //scale + if(xToZRatio != 1.0f) + { + if(xToZRatio > 1.0f) + result.z /= xToZRatio; + else + result.x *= xToZRatio; + + //offset + if(zoneSize.x > zoneSize.y) + { + result.z -= ((zoneSize.x - zoneSize.y)/2); + } + else if(zoneSize.x < zoneSize.y) + { + result.x -= ((zoneSize.y - zoneSize.x)/2); + } + } + } + + return result; +} + +//---------------------------------------------------------------------- + +Vector2d GroundZoneManager::getZoneSize(std::string const & encodedZoneName) +{ + const ZoneSizeMap::const_iterator zi = ms_zoneSizes.find(encodedZoneName); + if (zi != ms_zoneSizes.end()) + { + std::pair const & size = zi->second; + return Vector2d(size.first, size.second); + } + + return SharedBuildoutAreaManager::getBuildoutAreaSize(encodedZoneName, true); +} + +//---------------------------------------------------------------------- + +float GroundZoneManager::getXToZRatioOfZone(std::string const & zoneName) +{ + const ZoneSizeMap::const_iterator zi = ms_zoneSizes.find(zoneName); + if (zi != ms_zoneSizes.end()) + { + std::pair const & size = zi->second; + return size.first / size.second; + } + else + { + //any zone not in the map is assumed to be square (i.e. regular planets) + return 1.0f; + } +} + +//---------------------------------------------------------------------- + +float GroundZoneManager::getXToZRatioOfZoneFromScene(std::string const & sceneName, Vector const & location_w) +{ + std::string zoneName; + getZoneName(sceneName, location_w, zoneName); + return getXToZRatioOfZone(zoneName.c_str()); +} + +//---------------------------------------------------------------------- + +Vector GroundZoneManager::getRelativePositionFromPlayer(const char *sceneName, Vector const & playerPosition_w, Vector const & worldPosition_w) +{ + Vector relativePosition(worldPosition_w); + + if (sceneName && *sceneName) + { + if (SharedBuildoutAreaManager::adjustMapCoordinatesForScene(sceneName)) + { + std::string worldZoneName; + if (GroundZoneManager::getZoneName(sceneName, worldPosition_w, worldZoneName)) + { + std::string encodedZoneName = SharedBuildoutAreaManager::createEncodedBuildoutName(sceneName, worldZoneName); + + relativePosition = SharedBuildoutAreaManager::getRelativePositionInArea(encodedZoneName.c_str(), worldPosition_w, TRUE); + + std::string playerZoneName; + if (GroundZoneManager::getZoneName(sceneName, playerPosition_w, playerZoneName)) + { + encodedZoneName = SharedBuildoutAreaManager::createEncodedBuildoutName(sceneName, playerZoneName); + relativePosition += SharedBuildoutAreaManager::getCenterPositionInArea(encodedZoneName.c_str(), playerPosition_w); + } + } + } + } + return relativePosition; +} + +//---------------------------------------------------------------------- + +Vector GroundZoneManager::getRelativePosition(const char *sceneName, Vector const & worldPosition_w) +{ + Vector relativePosition(worldPosition_w); + + if (sceneName && *sceneName) + { + if (SharedBuildoutAreaManager::adjustMapCoordinatesForScene(sceneName)) + { + std::string zoneName; + if (GroundZoneManager::getZoneName(sceneName, worldPosition_w, zoneName)) + { + relativePosition = SharedBuildoutAreaManager::getRelativePositionInArea(zoneName.c_str(), worldPosition_w, TRUE); + } + } + } + + return relativePosition; +} + +//====================================================================== + diff --git a/engine/shared/library/sharedGame/src/shared/core/GroundZoneManager.h b/engine/shared/library/sharedGame/src/shared/core/GroundZoneManager.h new file mode 100644 index 00000000..2e90fabc --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/GroundZoneManager.h @@ -0,0 +1,36 @@ +//====================================================================== +// +// GroundZoneManager.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_GroundZoneManager_H +#define INCLUDED_GroundZoneManager_H + +#include "sharedMath/Vector.h" +#include "sharedMath/Vector2d.h" + +class BuildoutArea; + +//====================================================================== + +class GroundZoneManager +{ +public: + static void install (); + static void remove (); + + static BuildoutArea const * getZoneName(std::string const & sceneName, Vector const & location_w, std::string & zoneName); + static Vector2d getZoneSize(std::string const & zoneName); + static Vector transformWorldLocationToZoneLocation(std::string const & sceneName, Vector const & location_w); + static Vector adjustForNonSquareZones(std::string const & encodedZoneName, Vector const & zoneLocation); + static float getXToZRatioOfZone(std::string const & zoneName); + static float getXToZRatioOfZoneFromScene(std::string const & sceneName, Vector const & location_w); + static Vector getRelativePositionFromPlayer(const char *sceneName, Vector const & playerPosition_w, Vector const & worldPosition_w); + static Vector getRelativePosition(const char *sceneName, Vector const & worldPosition_w); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/GuildRankDataTable.cpp b/engine/shared/library/sharedGame/src/shared/core/GuildRankDataTable.cpp new file mode 100644 index 00000000..2bd66b99 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/GuildRankDataTable.cpp @@ -0,0 +1,235 @@ +// ====================================================================== +// +// GuildRankDataTable.cpp +// Copyright 2006 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/GuildRankDataTable.h" + +#include "sharedFoundation/ExitChain.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" +#include "UnicodeUtils.h" + +#include + +// ====================================================================== + +namespace GuildRankDataTableNamespace +{ + char const * const cs_guildRankDataTableName = "datatables/guild/guild_rank.iff"; + + std::vector s_allGuildRankNames; + std::vector s_allGuildRanks; + std::vector s_allTitleableGuildRanks; + std::map s_allGuildRanksByName; + std::map s_allGuildRanksByDisplayName; + std::map s_allGuildRanksByTitle; +} + +using namespace GuildRankDataTableNamespace; + +// ====================================================================== + +void GuildRankDataTable::install() +{ + DataTable * table = DataTableManager::getTable(cs_guildRankDataTableName, true); + if (table) + { + int const columnRankName = table->findColumnNumber("rankName"); + int const columnRankSlotId = table->findColumnNumber("rankSlotId"); + int const columnTitle = table->findColumnNumber("title"); + + // the can be a variable number of "alternate title" columns, as long as the columns + // are named alternateTitle1, alternateTitle2, alternateTitle3, alternateTitle4, + // alternateTitle5, and so on + std::vector columnAlternateTitle; + char buffer[128]; + int columnNumber; + for (int i = 1; i <= 1000000000; ++i) + { + snprintf(buffer, sizeof(buffer)-1, "alternateTitle%d", i); + buffer[sizeof(buffer)-1] = '\0'; + + columnNumber = table->findColumnNumber(buffer); + if (columnNumber < 0) + break; + + columnAlternateTitle.push_back(columnNumber); + } + + FATAL((columnRankName < 0), ("column \"rankName\" not found in %s", cs_guildRankDataTableName)); + FATAL((columnRankSlotId < 0), ("column \"rankSlotId\" not found in %s", cs_guildRankDataTableName)); + FATAL((columnTitle < 0), ("column \"title\" not found in %s", cs_guildRankDataTableName)); + + GuildRankDataTable::GuildRank const * currentRank = NULL; + + int const numRows = table->getNumRows(); + std::string rankName, alternateTitle; + Unicode::String displayRankName; + int slotId; + bool title; + std::vector titles; + std::map names; + std::map allRanksById; + for (int i = 0; i < numRows; ++i) + { + rankName = table->getStringValue(columnRankName, i); + + if (rankName.empty()) + continue; + + FATAL((names.count(rankName) >= 1), ("%s, row %d: rank name %s already used at row %d (either as a rank name or rank alternate title)", cs_guildRankDataTableName, (i+3), rankName.c_str(), names[rankName])); + names[rankName] = (i+3); + + FATAL(!StringId("guild_rank_title", rankName).localize(displayRankName, true), ("%s, row %d: unable to load display string for guild rank %s from guild_rank_title.stf", cs_guildRankDataTableName, (i+3), rankName.c_str())); + FATAL((s_allGuildRanksByDisplayName.count(Unicode::toLower(Unicode::wideToNarrow(displayRankName))) > 0), ("%s, row %d: guild rank %s has display string %s from guild_rank_title.stf that is already used by another guild rank", cs_guildRankDataTableName, (i+3), rankName.c_str(), Unicode::wideToNarrow(displayRankName).c_str())); + + slotId = table->getIntValue(columnRankSlotId, i); + title = (table->getIntValue(columnTitle, i) != 0); + + // read all alternate titles + titles.clear(); + if (title) + titles.push_back(rankName); + + for (std::vector::const_iterator iterColumnAlternateTitle = columnAlternateTitle.begin(); iterColumnAlternateTitle != columnAlternateTitle.end(); ++iterColumnAlternateTitle) + { + alternateTitle = table->getStringValue(*iterColumnAlternateTitle, i); + + if (!alternateTitle.empty()) + { + FATAL((names.count(alternateTitle) >= 1), ("%s, row %d: alternate title %s already used at row %d (either as a rank name or rank alternate title)", cs_guildRankDataTableName, (i+3), alternateTitle.c_str(), names[alternateTitle])); + names[alternateTitle] = (i+3); + + titles.push_back(alternateTitle); + } + } + + FATAL((!titles.empty() && !title), ("%s: rank %s cannot have any alternate titles unless it is defined as \"titleable\")", cs_guildRankDataTableName, rankName.c_str())); + + // check for valid slot id + FATAL((slotId < 0), ("%s, row %d: rank slot id %d must be >= 0", cs_guildRankDataTableName, (i+3), slotId)); + + // create guild rank info + currentRank = new GuildRank(rankName, Unicode::wideToNarrow(displayRankName), slotId, titles); + + // check for duplicate slot id + FATAL((allRanksById.count(slotId) >= 1), ("%s, row %d: rank slot id %d already used by rank %s", cs_guildRankDataTableName, (i+3), slotId, allRanksById[slotId]->name.c_str())); + allRanksById[slotId] = currentRank; + + s_allGuildRankNames.push_back(currentRank->name); + s_allGuildRanks.push_back(currentRank); + + if (!currentRank->titles.empty()) + s_allTitleableGuildRanks.push_back(currentRank); + + s_allGuildRanksByName[currentRank->name] = currentRank; + s_allGuildRanksByDisplayName[Unicode::toLower(currentRank->displayName)] = currentRank; + + for (std::vector::const_iterator iterTitle = currentRank->titles.begin(); iterTitle != currentRank->titles.end(); ++iterTitle) + s_allGuildRanksByTitle[*iterTitle] = currentRank; + } + + DataTableManager::close(cs_guildRankDataTableName); + + // do additional verification + slotId = -1; + for (std::map::const_iterator iterSlotId = allRanksById.begin(); iterSlotId != allRanksById.end(); ++iterSlotId) + { + FATAL((iterSlotId->first != iterSlotId->second->slotId), ("%s: slot id mismatch for slot %s (%d, %d)", cs_guildRankDataTableName, iterSlotId->second->name.c_str(), iterSlotId->first, iterSlotId->second->slotId)); + + // make sure that slot ids start at 0 and there are no "holes" in the slot ids + if (iterSlotId == allRanksById.begin()) + { + FATAL((iterSlotId->first != 0), ("%s: slot id must start at 0", cs_guildRankDataTableName)); + } + else + { + FATAL(((slotId + 1) != iterSlotId->first), ("%s: slot id must be contiguous (there is a \"hole\" between %d and %d)", cs_guildRankDataTableName, slotId, iterSlotId->first)); + } + + slotId = iterSlotId->first; + } + } + else + { + FATAL(true, ("guild rank datatable %s not found", cs_guildRankDataTableName)); + } + + ExitChain::add(remove, "GuildRankDataTable::remove"); +} + +//---------------------------------------------------------------------- + +void GuildRankDataTable::remove() +{ + for (std::vector::const_iterator iter = s_allGuildRanks.begin(); iter != s_allGuildRanks.end(); ++iter) + delete *iter; + + s_allGuildRankNames.clear(); + s_allGuildRanks.clear(); + s_allTitleableGuildRanks.clear(); + s_allGuildRanksByName.clear(); + s_allGuildRanksByDisplayName.clear(); + s_allGuildRanksByTitle.clear(); +} + +//---------------------------------------------------------------------- + +std::vector const & GuildRankDataTable::getAllRankNames() +{ + return s_allGuildRankNames; +} + +//---------------------------------------------------------------------- + +std::vector const & GuildRankDataTable::getAllRanks() +{ + return s_allGuildRanks; +} + +//---------------------------------------------------------------------- + +std::vector const & GuildRankDataTable::getAllTitleableRanks() +{ + return s_allTitleableGuildRanks; +} + +//---------------------------------------------------------------------- + +GuildRankDataTable::GuildRank const * GuildRankDataTable::getRank(std::string const & rankName) +{ + std::map::const_iterator iterFind = s_allGuildRanksByName.find(rankName); + if (iterFind != s_allGuildRanksByName.end()) + return iterFind->second; + + return NULL; +} + +//---------------------------------------------------------------------- + +GuildRankDataTable::GuildRank const * GuildRankDataTable::getRankForDisplayRankName(std::string const & displayRankName) +{ + std::map::const_iterator iterFind = s_allGuildRanksByDisplayName.find(Unicode::toLower(displayRankName)); + if (iterFind != s_allGuildRanksByDisplayName.end()) + return iterFind->second; + + return NULL; +} + +//---------------------------------------------------------------------- + +GuildRankDataTable::GuildRank const * GuildRankDataTable::isARankTitle(std::string const & rankTitle) +{ + std::map::const_iterator iterFind = s_allGuildRanksByTitle.find(rankTitle); + if (iterFind != s_allGuildRanksByTitle.end()) + return iterFind->second; + + return NULL; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/GuildRankDataTable.h b/engine/shared/library/sharedGame/src/shared/core/GuildRankDataTable.h new file mode 100644 index 00000000..167d9137 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/GuildRankDataTable.h @@ -0,0 +1,55 @@ +// ====================================================================== +// +// GuildRankDataTable.h +// Copyright 2006 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#ifndef INCLUDED_GuildRankDataTable_H +#define INCLUDED_GuildRankDataTable_H + +#include + +// ====================================================================== + +class GuildRankDataTable // static class +{ +public: + static void install(); + static void remove(); + + class GuildRank + { + public: + GuildRank(std::string const & pName, std::string const & pDisplayName, int pSlotId, std::vector const & pTitles) : + name(pName), displayName(pDisplayName), slotId(pSlotId), titles(pTitles) {}; + + std::string const name; + std::string const displayName; + int const slotId; + std::vector const titles; + + private: + GuildRank(); + GuildRank(GuildRank const &); + GuildRank &operator =(GuildRank const &); + }; + + static std::vector const & getAllRankNames(); + static std::vector const & getAllRanks(); + static std::vector const & getAllTitleableRanks(); + static GuildRankDataTable::GuildRank const * getRank(std::string const & rankName); + static GuildRankDataTable::GuildRank const * getRankForDisplayRankName(std::string const & displayRankName); + static GuildRankDataTable::GuildRank const * isARankTitle(std::string const & rankTitle); + +private: // disabled + + GuildRankDataTable(); + GuildRankDataTable(GuildRankDataTable const &); + GuildRankDataTable &operator =(GuildRankDataTable const &); +}; + +// ====================================================================== + +#endif // INCLUDED_GuildRankDataTable_H diff --git a/engine/shared/library/sharedGame/src/shared/core/HoverPlaneHelper.cpp b/engine/shared/library/sharedGame/src/shared/core/HoverPlaneHelper.cpp new file mode 100644 index 00000000..05cf4344 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/HoverPlaneHelper.cpp @@ -0,0 +1,348 @@ +//====================================================================== +// +// HoverPlaneHelper.cpp +// copyright (c) 2003 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/HoverPlaneHelper.h" + +#include "sharedMath/Plane.h" +#include "sharedObject/Object.h" +#include "sharedObject/Appearance.h" +#include "sharedCollision/BoxExtent.h" +#include "sharedCollision/CollisionInfo.h" +#include "sharedCollision/CollisionProperty.h" +#include "sharedCollision/Footprint.h" +#include "sharedTerrain/TerrainObject.h" + +//---------------------------------------------------------------------- + +namespace +{ + /** + * @param points an array of 10 Vectors, 5 for the main body and 5 for the lookAhead + */ + + bool transformBoxPoints (const BoxExtent & box, const Transform & transform, Vector * points, const Vector & lookAhead) + { + const Vector & minV = box.getMin (); + const Vector & maxV = box.getMax (); + + if (maxV.x == minV.x || maxV.z == minV.z) + return false; + + //-- centerpoint + points [0].x = (minV.x + maxV.x) * 0.5f; + points [0].z = (minV.z + maxV.z) * 0.5f; + + //-- front right + points [1].x = maxV.x; + points [1].z = maxV.z; + + //-- front left + points [2].x = minV.x; + points [2].z = maxV.z; + + //-- back left + points [3].x = minV.x; + points [3].z = minV.z; + + //-- back right + points [4].x = maxV.x; + points [4].z = minV.z; + + for (int i = 0; i < 5; ++i) + { + Vector & v = points [i]; + v.y = minV.y; + v = transform.rotateTranslate_l2p (v); + + points [i + 5] = v + lookAhead; + } + + return true; + } + + inline void computeRollPitch (const Vector & normal, float & roll, float & pitch) + { + Vector normalX = normal; + normalX.z = 0.0f; + if (normalX.normalize ()) + roll = normalX.phi () + PI_OVER_2; + else + roll = 0.0f; + + if (normalX.x > 0.0f) + roll = -roll; + + Vector normalZ = normal; + normalZ.x = 0.0f; + if (normalZ.normalize ()) + pitch = normalZ.phi () + PI_OVER_2; + else + pitch = 0.0f; + + if (normalZ.z < 0.0f) + pitch = -pitch; + + } +} + +//---------------------------------------------------------------------- + +bool HoverPlaneHelper::findMinimumHoverPlane (const Object & obj, float & roll, float & pitch, const Vector & lookAhead) +{ + Object const * motor = obj.getParent (); + + if(motor) + { + CollisionProperty const * collision = motor->getCollisionProperty(); + + if(collision) + { + Footprint const * foot = collision->getFootprint(); + + if(foot && foot->isOnSolidFloor()) + { + Vector const & groundNormal_w = foot->getGroundNormal_w(); + + const Transform & transform_o2w = obj.getTransform_o2w (); + + computeRollPitch (transform_o2w.rotate_p2l (groundNormal_w), roll, pitch); + + return true; + } + } + } + + // ---------- + + const Appearance * const app = obj.getAppearance (); + if (!app) + return false; + + const BoxExtent * const box = dynamic_cast(app->getExtent ()); + if (!box) + return false; + + const Transform & transform_o2w = obj.getTransform_o2w (); + + Vector points [10]; + if (!transformBoxPoints (*box, transform_o2w, points, lookAhead)) + return false; + + const TerrainObject * const terrainObject = TerrainObject::getInstance (); + + if (!terrainObject) + return false; + + float oldPointHeights [10]; + Vector normals [10]; + Vector avgNormal; + + Vector avgLookAhead; + int lookAheadContribCount = 0; + + Sphere s = box->getSphere (); + s.setCenter (transform_o2w.getPosition_p ()); + float avgDistanceAboveTerrain = 0.0f; + float minDistanceAboveTerrain = 10000.0f; + + //- find terrain heights for points + { + const Vector oldCenterPoint = points [0]; + + float y = 0.0f; + for (int i = 0; i < 10; ++i) + { + oldPointHeights [i] = points [i].y; + + if (terrainObject->getHeight (points [i], y, normals [i])) + { + float waterHeight = 0.0f; + const bool isWater = terrainObject->getWaterHeight (points[i], waterHeight); + if(isWater && waterHeight > y) + { + normals[i] = Vector::unitY; + y = waterHeight; + } + + if (i >= 5) + { + //-- lookahead point is not in the sphere, let it contribute to the lookahead normal + if (!s.contains (points [i])) + { + points [i].y = y; + avgLookAhead += points [i] - oldCenterPoint; + ++lookAheadContribCount; + } + points [i].y = y; + } + else + { + const float distanceAbove = points [i].y - y; + avgDistanceAboveTerrain += distanceAbove; + minDistanceAboveTerrain = std::max (0.0f, std::min (minDistanceAboveTerrain, distanceAbove)); + points [i].y = y; + avgNormal += normals [i]; + } + } + else + return false; + } + } + + avgNormal /= 5.0f; + avgDistanceAboveTerrain /= 5.0f; + + computeRollPitch (transform_o2w.rotate_p2l (avgNormal), roll, pitch); + + //-- decrease the roll & pitch based on height over terrain + //-- + + const float extentRadius = s.getRadius (); + + avgDistanceAboveTerrain -= extentRadius; + + if (avgDistanceAboveTerrain > 0.0f) + { + if (extentRadius > 0.0f) + { + const float relativeDistance = 1.0f + (avgDistanceAboveTerrain / (extentRadius * 0.5f)); + roll /= relativeDistance; + pitch /= relativeDistance; + } + } + + if (lookAheadContribCount) + { + avgLookAhead /= static_cast(lookAheadContribCount); + + Vector vectorToLookAhead = transform_o2w.rotate_p2l (avgLookAhead); + + float pitchLookAhead = 0.0f; + + if (vectorToLookAhead.normalize ()) + pitchLookAhead = vectorToLookAhead.phi (); + else + pitchLookAhead = 0.0f; + + if (pitchLookAhead < pitch) + { + pitch = pitchLookAhead; + } + } + + return true; +} + +//---------------------------------------------------------------------- + +bool HoverPlaneHelper::findMinimumHoverHeight (const Object & obj, float & height, const Vector & lookAhead) +{ + Object const * motor = obj.getParent (); + + const float obj_y_w = obj.getPosition_w ().y; + + float minDeltaY = 10000.0f; + + if(motor) + { + CollisionProperty const * collision = motor->getCollisionProperty(); + + if(collision) + { + Footprint const * foot = collision->getFootprint(); + + if(foot && foot->isOnSolidFloor()) + { + float groundHeight = -REAL_MAX; + + if(foot->getGroundHeight(groundHeight)) + { + minDeltaY = obj_y_w - groundHeight; + } + } + } + } + + // ---------- + + const Appearance * const app = obj.getAppearance (); + if (!app) + return false; + + const BoxExtent * const box = dynamic_cast(app->getExtent ()); + if (!box) + return false; + + const Transform & transform_o2w = obj.getTransform_o2w (); + + Vector points [10]; + if (!transformBoxPoints (*box, transform_o2w, points, lookAhead)) + return false; + + const TerrainObject * const terrainObject = TerrainObject::getInstance (); + + if (!terrainObject) + return false; + + float minDeltaYLookAhead = 10000.0f; + + bool foundLookAhead = false; + + //- find terrain heights for points + { + bool foundStrict = false; + + for (int i = 0; i < 10; ++i) + { + const Vector & p = points [i]; + + float pointHeight = 0.0f; + + if (terrainObject->getHeight (p, pointHeight)) + { + float deltaPointHeight = p.y - pointHeight; + + //-- lookahead box, non-strict + if (i >= 5) + { + foundLookAhead = true; + minDeltaYLookAhead = std::min (minDeltaYLookAhead, deltaPointHeight); + } + else + { + foundStrict = true; + + float waterHeight = 0.0f; + if (terrainObject->getWaterHeight (p, waterHeight)) + { + pointHeight = std::max (pointHeight, waterHeight); + deltaPointHeight = p.y - pointHeight; + } + + minDeltaY = std::min (minDeltaY, deltaPointHeight); + } + } + } + + if (!foundStrict) + return false; + } + + height = obj_y_w - minDeltaY; + + if (foundLookAhead) + { + float heightLookAhead = obj_y_w - minDeltaYLookAhead; + if (heightLookAhead > height) + height = (height + heightLookAhead) * 0.5f; + } + + return true; +} + +//---------------------------------------------------------------------- diff --git a/engine/shared/library/sharedGame/src/shared/core/HoverPlaneHelper.h b/engine/shared/library/sharedGame/src/shared/core/HoverPlaneHelper.h new file mode 100644 index 00000000..e20a091a --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/HoverPlaneHelper.h @@ -0,0 +1,31 @@ +//====================================================================== +// +// HoverPlaneHelper.h +// copyright (c) 2003 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_HoverPlaneHelper_H +#define INCLUDED_HoverPlaneHelper_H + +//====================================================================== + +class NetworkId; +class Plane; +class Object; +class Vector; + +//---------------------------------------------------------------------- + +class HoverPlaneHelper +{ +public: + + static bool findMinimumHoverPlane (const Object & obj, float & roll, float & pitch, const Vector & lookAhead); + static bool findMinimumHoverHeight (const Object & obj, float & height, const Vector & lookAhead); + +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/HyperspaceManager.cpp b/engine/shared/library/sharedGame/src/shared/core/HyperspaceManager.cpp new file mode 100644 index 00000000..4ab19f54 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/HyperspaceManager.cpp @@ -0,0 +1,280 @@ +//====================================================================== +// +// HyperspaceManager.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/HyperspaceManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/TreeFile.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" + +#include + +//====================================================================== + +namespace HyperspaceManagerNamespace +{ + namespace SystemLocationsColumnNames + { + char const * const scene = "SCENE"; + char const * const x = "X"; + char const * const y = "Y"; + char const * const z = "Z"; + } + + namespace HyperspaceLocationsColumnNames + { + char const * const hyperspacePointName = "HYPERSPACE_POINT_NAME"; + char const * const scene = "SCENE"; + char const * const x = "X"; + char const * const y = "Y"; + char const * const z = "Z"; + char const * const requiredCommand = "REQUIRED_COMMAND"; + } + + char const * const cms_systemLocationsTableName = "datatables/space/hyperspace/system_locations.iff"; + char const * const cms_hyperspaceLocationsTableName = "datatables/space/hyperspace/hyperspace_locations.iff"; + char const * const cms_hyperspaceHomeLocationHyperspacePointName = "space_home_location"; + char const * const cms_invalidHomeLocationHyperspaceScene = "space_npe_falcon"; + + const int cms_minSystemLoc = 0; + const int cms_maxSystemLoc = 100; + + std::map ms_sceneToRelativeSystemLocations; + std::map ms_hyperspaceLocationNameToHyperspaceLocations; + std::map > ms_sceneToHyperspaceLocations; +} + +using namespace HyperspaceManagerNamespace; + +//---------------------------------------------------------------------- + +void HyperspaceManager::install() +{ + InstallTimer const installTimer("HyperspaceManager::install"); + + ms_hyperspaceLocationNameToHyperspaceLocations.clear(); + ms_sceneToRelativeSystemLocations.clear(); + ms_sceneToHyperspaceLocations.clear(); + { + if(!TreeFile::exists(cms_systemLocationsTableName)) + { + DEBUG_WARNING(true, ("Datatable [%s] not found to build the system locations", cms_systemLocationsTableName)); + return; + } + + DataTable const * const systemLocationsTable = DataTableManager::getTable(cms_systemLocationsTableName, true); + std::string scene; + Vector loc; + if(systemLocationsTable) + { + for(int i = 0; i < systemLocationsTable->getNumRows(); ++i) + { + scene = systemLocationsTable->getStringValue(SystemLocationsColumnNames::scene, i); + loc.x = static_cast(systemLocationsTable->getIntValue(SystemLocationsColumnNames::x, i)); + loc.y = static_cast(systemLocationsTable->getIntValue(SystemLocationsColumnNames::y, i)); + loc.z = static_cast(systemLocationsTable->getIntValue(SystemLocationsColumnNames::z, i)); + + for(std::map::const_iterator it = ms_sceneToRelativeSystemLocations.begin(); it != ms_sceneToRelativeSystemLocations.end(); ++it) + { + DEBUG_FATAL(it->second == loc, ("Data error: System location [%s] has same location as other system [%s] , in [%s], row[%d]. All systems must have a unique location", scene.c_str(), it->first.c_str(), cms_systemLocationsTableName, i)); + } + + DEBUG_FATAL(loc.x < cms_minSystemLoc, ("Data error: System location x < %d in [%s], row[%d], all system locations must be between %d and %d", cms_minSystemLoc, cms_systemLocationsTableName, i, cms_minSystemLoc, cms_maxSystemLoc)); + DEBUG_FATAL(loc.x > cms_maxSystemLoc, ("Data error: System location x > %d in [%s], row[%d], all system locations must be between %d and %d", cms_maxSystemLoc, cms_systemLocationsTableName, i, cms_minSystemLoc, cms_maxSystemLoc)); + DEBUG_FATAL(loc.y < cms_minSystemLoc, ("Data error: System location y < %d in [%s], row[%d], all system locations must be between %d and %d", cms_minSystemLoc, cms_systemLocationsTableName, i, cms_minSystemLoc, cms_maxSystemLoc)); + DEBUG_FATAL(loc.y > cms_maxSystemLoc, ("Data error: System location y > %d in [%s], row[%d], all system locations must be between %d and %d", cms_maxSystemLoc, cms_systemLocationsTableName, i, cms_minSystemLoc, cms_maxSystemLoc)); + DEBUG_FATAL(loc.z < cms_minSystemLoc, ("Data error: System location z < %d in [%s], row[%d], all system locations must be between %d and %d", cms_minSystemLoc, cms_systemLocationsTableName, i, cms_minSystemLoc, cms_maxSystemLoc)); + DEBUG_FATAL(loc.z > cms_maxSystemLoc, ("Data error: System location z > %d in [%s], row[%d], all system locations must be between %d and %d", cms_maxSystemLoc, cms_systemLocationsTableName, i, cms_minSystemLoc, cms_maxSystemLoc)); + + ms_sceneToRelativeSystemLocations[scene] = loc; + } + } + } + + { + if(!TreeFile::exists(cms_hyperspaceLocationsTableName)) + { + DEBUG_WARNING(true, ("Datatable [%s] not found to build the hyperspace locations", cms_hyperspaceLocationsTableName)); + return; + } + DataTable const * const hyperspaceLocationsTable = DataTableManager::getTable(cms_hyperspaceLocationsTableName, true); + std::string hyperspacePointName; + if(hyperspaceLocationsTable) + { + HyperspaceLocation hyperspaceLoc; + for(int i = 0; i < hyperspaceLocationsTable->getNumRows(); ++i) + { + hyperspaceLoc.name = hyperspaceLocationsTable->getStringValue(HyperspaceLocationsColumnNames::hyperspacePointName, i); + hyperspaceLoc.sceneName = hyperspaceLocationsTable->getStringValue(HyperspaceLocationsColumnNames::scene, i); + hyperspaceLoc.location.x = static_cast(hyperspaceLocationsTable->getIntValue(HyperspaceLocationsColumnNames::x, i)); + hyperspaceLoc.location.y = static_cast(hyperspaceLocationsTable->getIntValue(HyperspaceLocationsColumnNames::y, i)); + hyperspaceLoc.location.z = static_cast(hyperspaceLocationsTable->getIntValue(HyperspaceLocationsColumnNames::z, i)); + hyperspaceLoc.requiredCommand = hyperspaceLocationsTable->getStringValue(HyperspaceLocationsColumnNames::requiredCommand, i); + ms_hyperspaceLocationNameToHyperspaceLocations[hyperspaceLoc.name] = hyperspaceLoc; + ms_sceneToHyperspaceLocations[hyperspaceLoc.sceneName].push_back(hyperspaceLoc); + } + } + + // add in the home location hyperspace point name into the map so it's recognized as a valid point + HyperspaceLocation hyperspaceLoc; + + hyperspaceLoc.name = cms_hyperspaceHomeLocationHyperspacePointName; + hyperspaceLoc.sceneName = ""; + hyperspaceLoc.location.x = 0; + hyperspaceLoc.location.y = 0; + hyperspaceLoc.location.z = 0; + hyperspaceLoc.requiredCommand = ""; + + ms_hyperspaceLocationNameToHyperspaceLocations[hyperspaceLoc.name] = hyperspaceLoc; + } + ExitChain::add(HyperspaceManager::remove, "HyperspaceManager::remove"); +} + +//---------------------------------------------------------------------- + +void HyperspaceManager::remove() +{ + ms_sceneToRelativeSystemLocations.clear(); + ms_hyperspaceLocationNameToHyperspaceLocations.clear(); + ms_sceneToHyperspaceLocations.clear(); +} + +//---------------------------------------------------------------------- + +Vector HyperspaceManager::getDirectionToHyperspacePoint_w(std::string const & fromSceneName, Vector const & fromLocation_w, std::string const & hyperspacePoint) +{ + if(!isValidHyperspacePoint(hyperspacePoint)) + return Vector::unitZ; + + HyperspaceLocation toLocation; + getHyperspacePoint(hyperspacePoint, toLocation); + //if warping to point in the same scene, aim at new point in this scene + Vector directionVec(Vector::unitZ); + if(fromSceneName == toLocation.sceneName) + { + Vector const & endLoc = toLocation.location; + Vector const & startLoc = fromLocation_w; + directionVec = endLoc - startLoc; + } + //else point at the new system + else + { + std::map::const_iterator i = ms_sceneToRelativeSystemLocations.find(fromSceneName); + if(i == ms_sceneToRelativeSystemLocations.end()) + return Vector::unitZ; + + std::map::const_iterator j = ms_sceneToRelativeSystemLocations.find(toLocation.sceneName); + if(j == ms_sceneToRelativeSystemLocations.end()) + return Vector::unitZ; + + Vector const & endLoc = j->second; + Vector const & startLoc = i->second; + directionVec = endLoc - startLoc; + } + + if (directionVec.normalize()) + return directionVec; + else + return Vector::unitZ; +} + +//---------------------------------------------------------------------- + +Vector HyperspaceManager::getDirectionToHyperspacePoint_w(std::string const & fromSceneName, Vector const & fromLocation_w, std::string const & toSceneName, Vector const & toLocation_w) +{ + //if warping to point in the same scene, aim at new point in this scene + Vector directionVec(Vector::unitZ); + if(fromSceneName == toSceneName) + { + directionVec = toLocation_w - fromLocation_w; + } + //else point at the new system + else + { + std::map::const_iterator i = ms_sceneToRelativeSystemLocations.find(fromSceneName); + if(i == ms_sceneToRelativeSystemLocations.end()) + return Vector::unitZ; + + std::map::const_iterator j = ms_sceneToRelativeSystemLocations.find(toSceneName); + if(j == ms_sceneToRelativeSystemLocations.end()) + return Vector::unitZ; + + Vector const & endLoc = j->second; + Vector const & startLoc = i->second; + directionVec = endLoc - startLoc; + } + + if (directionVec.normalize()) + return directionVec; + else + return Vector::unitZ; +} + +//---------------------------------------------------------------------- + +bool HyperspaceManager::isValidHyperspacePoint(std::string const & hyperspacePointName) +{ + std::map::const_iterator i = ms_hyperspaceLocationNameToHyperspaceLocations.find(hyperspacePointName); + return (i != ms_hyperspaceLocationNameToHyperspaceLocations.end()); +} + +//---------------------------------------------------------------------- + +bool HyperspaceManager::getHyperspacePoint(std::string const & hyperspacePointName, HyperspaceManager::HyperspaceLocation & /*OUT*/ location) +{ + std::map::const_iterator i = ms_hyperspaceLocationNameToHyperspaceLocations.find(hyperspacePointName); + if(i != ms_hyperspaceLocationNameToHyperspaceLocations.end()) + { + location = i->second; + return true; + } + else + { + location.name.clear(); + location.sceneName.clear(); + location.location.makeZero(); + return false; + } +} + +//---------------------------------------------------------------------- + +bool HyperspaceManager::getHyperspacePoints(std::string const & sceneName, std::vector & /*OUT*/ locations) +{ + locations.clear(); + std::map >::const_iterator i = ms_sceneToHyperspaceLocations.find(sceneName); + if(i != ms_sceneToHyperspaceLocations.end()) + { + locations = i->second; + return true; + } + else + return false; +} + +//---------------------------------------------------------------------- + +std::string HyperspaceManager::getHomeLocationHyperspacePointName() +{ + return cms_hyperspaceHomeLocationHyperspacePointName; +} + +//---------------------------------------------------------------------- + +bool HyperspaceManager::isValidSceneForHomeLocationHyperspace(std::string const & sceneName) +{ + // we do a find instead of a compare because we want to check for _2, _3, etc... + if (sceneName.find(cms_invalidHomeLocationHyperspaceScene, 0) != std::string::npos) + return false; + + return true; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/HyperspaceManager.h b/engine/shared/library/sharedGame/src/shared/core/HyperspaceManager.h new file mode 100644 index 00000000..3905427f --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/HyperspaceManager.h @@ -0,0 +1,44 @@ +//====================================================================== +// +// HyperspaceManager.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_HyperspaceManager_H +#define INCLUDED_HyperspaceManager_H + +//====================================================================== + +#include "sharedMath/Vector.h" + +//---------------------------------------------------------------------- + +class HyperspaceManager +{ +public: + + struct HyperspaceLocation + { + std::string name; + std::string sceneName; + Vector location; + std::string requiredCommand; + }; + + static void install(); + static void remove(); + + static Vector getDirectionToHyperspacePoint_w(std::string const & fromSceneName, Vector const & fromLocation_w, std::string const & hyperspacePoint); + static Vector getDirectionToHyperspacePoint_w(std::string const & fromSceneName, Vector const & fromLocation_w, std::string const & toSceneName, Vector const & toLocation_w); + static bool isValidHyperspacePoint(std::string const & hyperspacePointName); + static bool getHyperspacePoint(std::string const & hyperspacePointName, HyperspaceLocation & /*OUT*/ location); + static bool getHyperspacePoints(std::string const & sceneName, stdvector::fwd & /*OUT*/ locations); + + static std::string getHomeLocationHyperspacePointName(); + static bool isValidSceneForHomeLocationHyperspace(std::string const & sceneName); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/LfgCharacterData.cpp b/engine/shared/library/sharedGame/src/shared/core/LfgCharacterData.cpp new file mode 100644 index 00000000..615cf0b8 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/LfgCharacterData.cpp @@ -0,0 +1,1635 @@ +// ====================================================================== +// +// LfgCharacterData.cpp +// Copyright 2008 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/LfgCharacterData.h" + +#include "sharedFoundation/CalendarTime.h" +#include "sharedFoundation/FormattedString.h" +#include "sharedFoundation/NetworkIdArchive.h" +#include "sharedGame/LfgDataTable.h" +#include "sharedGame/PvpData.h" +#include "unicodeArchive/UnicodeArchive.h" +#include "UnicodeUtils.h" + +// ====================================================================== + +namespace LfgCharacterDataNamespace +{ + std::vector s_professionDisplayString; + + // ***strings used to display connected character statistics in SOEMon*** + + // searchable/anonymous + std::string const s_stat_searchable_section("searchable"); + std::string const s_stat_anonymous(s_stat_searchable_section + ".anonymous"); + std::string const s_stat_searchable(s_stat_searchable_section + ".searchable"); + + // active/inactive + std::string const s_stat_active_section("active"); + std::string const s_stat_active(s_stat_active_section + ".active"); + std::string const s_stat_inactive(s_stat_active_section + ".inactive"); + + // grouped/ungrouped + std::string const s_stat_grouped_section("grouped"); + std::string const s_stat_grouped(s_stat_grouped_section + ".grouped"); + std::string const s_stat_ungrouped(s_stat_grouped_section + ".ungrouped"); + + // guilded/unguilded + std::string const s_stat_guilded_section("guilded"); + std::string const s_stat_guilded(s_stat_guilded_section + ".guilded"); + std::string const s_stat_unguilded(s_stat_guilded_section + ".unguilded"); + + // searchableByCtsSourceGalaxy + std::string const s_stat_searchablebyctssourcegalaxy_section("searchableByCtsSourceGalaxy"); + std::string const s_stat_searchablebyctssourcegalaxy_yes(s_stat_searchablebyctssourcegalaxy_section + ".yes"); + std::string const s_stat_searchablebyctssourcegalaxy_no(s_stat_searchablebyctssourcegalaxy_section + ".no"); + + // displayLocationInSearchResults + std::string const s_stat_displayLocation_section("displayLocation"); + std::string const s_stat_displayLocation(s_stat_displayLocation_section + ".displayLocation"); + std::string const s_stat_hideLocation(s_stat_displayLocation_section + ".hideLocation"); + + // gender + std::string const s_stat_gender_section("gender"); + std::string const s_stat_female(s_stat_gender_section + ".female"); + std::string const s_stat_male(s_stat_gender_section + ".male"); + + // faction + std::string const s_stat_faction_section("faction"); + std::string const s_stat_faction_imperial(s_stat_faction_section + ".imperial"); + std::string const s_stat_faction_neutral(s_stat_faction_section + ".neutral"); + std::string const s_stat_faction_rebel(s_stat_faction_section + ".rebel"); + + // pilot + std::string const s_stat_pilot_section("pilot"); + std::string const s_stat_pilot_imperial(s_stat_pilot_section + ".imperial"); + std::string const s_stat_pilot_neutral(s_stat_pilot_section + ".neutral"); + std::string const s_stat_pilot_none(s_stat_pilot_section + ".none"); + std::string const s_stat_pilot_rebel(s_stat_pilot_section + ".rebel"); + + // species + std::string const s_stat_species_section("species"); + std::string const s_stat_bothan(s_stat_species_section + ".bothan"); + std::string const s_stat_human(s_stat_species_section + ".human"); + std::string const s_stat_ithorian(s_stat_species_section + ".ithorian"); + std::string const s_stat_monCalamari(s_stat_species_section + ".monCalamari"); + std::string const s_stat_rodian(s_stat_species_section + ".rodian"); + std::string const s_stat_sullustan(s_stat_species_section + ".sullustan"); + std::string const s_stat_trandoshan(s_stat_species_section + ".trandoshan"); + std::string const s_stat_twilek(s_stat_species_section + ".twilek"); + std::string const s_stat_wookiee(s_stat_species_section + ".wookiee"); + std::string const s_stat_zabrak(s_stat_species_section + ".zabrak"); + + // species by gender + std::string const s_stat_species_gender_section("speciesGender"); + std::string const s_stat_bothan_m(s_stat_species_gender_section + ".bothan_m"); + std::string const s_stat_bothan_f(s_stat_species_gender_section + ".bothan_f"); + std::string const s_stat_human_m(s_stat_species_gender_section + ".human_m"); + std::string const s_stat_human_f(s_stat_species_gender_section + ".human_f"); + std::string const s_stat_ithorian_m(s_stat_species_gender_section + ".ithorian_m"); + std::string const s_stat_ithorian_f(s_stat_species_gender_section + ".ithorian_f"); + std::string const s_stat_monCalamari_m(s_stat_species_gender_section + ".monCalamari_m"); + std::string const s_stat_monCalamari_f(s_stat_species_gender_section + ".monCalamari_f"); + std::string const s_stat_rodian_m(s_stat_species_gender_section + ".rodian_m"); + std::string const s_stat_rodian_f(s_stat_species_gender_section + ".rodian_f"); + std::string const s_stat_sullustan_m(s_stat_species_gender_section + ".sullustan_m"); + std::string const s_stat_sullustan_f(s_stat_species_gender_section + ".sullustan_f"); + std::string const s_stat_trandoshan_m(s_stat_species_gender_section + ".trandoshan_m"); + std::string const s_stat_trandoshan_f(s_stat_species_gender_section + ".trandoshan_f"); + std::string const s_stat_twilek_m(s_stat_species_gender_section + ".twilek_m"); + std::string const s_stat_twilek_f(s_stat_species_gender_section + ".twilek_f"); + std::string const s_stat_wookiee_m(s_stat_species_gender_section + ".wookiee_m"); + std::string const s_stat_wookiee_f(s_stat_species_gender_section + ".wookiee_f"); + std::string const s_stat_zabrak_m(s_stat_species_gender_section + ".zabrak_m"); + std::string const s_stat_zabrak_f(s_stat_species_gender_section + ".zabrak_f"); + + // profession + std::string const s_stat_profession_section("profession"); + std::string const s_stat_bountyHunter(s_stat_profession_section + ".bountyHunter"); + std::string const s_stat_commando(s_stat_profession_section + ".commando"); + std::string const s_stat_entertainer(s_stat_profession_section + ".entertainer"); + std::string const s_stat_jedi(s_stat_profession_section + ".jedi"); + std::string const s_stat_medic(s_stat_profession_section + ".medic"); + std::string const s_stat_officer(s_stat_profession_section + ".officer"); + std::string const s_stat_smuggler(s_stat_profession_section + ".smuggler"); + std::string const s_stat_spy(s_stat_profession_section + ".spy"); + std::string const s_stat_traderDomestics(s_stat_profession_section + ".traderDomestics"); + std::string const s_stat_traderEngineering(s_stat_profession_section + ".traderEngineering"); + std::string const s_stat_traderMunitions(s_stat_profession_section + ".traderMunitions"); + std::string const s_stat_traderStructures(s_stat_profession_section + ".traderStructures"); + + // profession by gender + std::string const s_stat_profession_gender_section("professionGender"); + std::string const s_stat_bountyHunter_m(s_stat_profession_gender_section + ".bountyHunter_m"); + std::string const s_stat_bountyHunter_f(s_stat_profession_gender_section + ".bountyHunter_f"); + std::string const s_stat_commando_m(s_stat_profession_gender_section + ".commando_m"); + std::string const s_stat_commando_f(s_stat_profession_gender_section + ".commando_f"); + std::string const s_stat_entertainer_m(s_stat_profession_gender_section + ".entertainer_m"); + std::string const s_stat_entertainer_f(s_stat_profession_gender_section + ".entertainer_f"); + std::string const s_stat_jedi_m(s_stat_profession_gender_section + ".jedi_m"); + std::string const s_stat_jedi_f(s_stat_profession_gender_section + ".jedi_f"); + std::string const s_stat_medic_m(s_stat_profession_gender_section + ".medic_m"); + std::string const s_stat_medic_f(s_stat_profession_gender_section + ".medic_f"); + std::string const s_stat_officer_m(s_stat_profession_gender_section + ".officer_m"); + std::string const s_stat_officer_f(s_stat_profession_gender_section + ".officer_f"); + std::string const s_stat_smuggler_m(s_stat_profession_gender_section + ".smuggler_m"); + std::string const s_stat_smuggler_f(s_stat_profession_gender_section + ".smuggler_f"); + std::string const s_stat_spy_m(s_stat_profession_gender_section + ".spy_m"); + std::string const s_stat_spy_f(s_stat_profession_gender_section + ".spy_f"); + std::string const s_stat_traderDomestics_m(s_stat_profession_gender_section + ".traderDomestics_m"); + std::string const s_stat_traderDomestics_f(s_stat_profession_gender_section + ".traderDomestics_f"); + std::string const s_stat_traderEngineering_m(s_stat_profession_gender_section + ".traderEngineering_m"); + std::string const s_stat_traderEngineering_f(s_stat_profession_gender_section + ".traderEngineering_f"); + std::string const s_stat_traderMunitions_m(s_stat_profession_gender_section + ".traderMunitions_m"); + std::string const s_stat_traderMunitions_f(s_stat_profession_gender_section + ".traderMunitions_f"); + std::string const s_stat_traderStructures_m(s_stat_profession_gender_section + ".traderStructures_m"); + std::string const s_stat_traderStructures_f(s_stat_profession_gender_section + ".traderStructures_f"); + + // level + std::string const s_stat_level_section("level"); + std::string const s_stat_level_10(s_stat_level_section + ".01_10"); + std::string const s_stat_level_10_imperial(s_stat_level_10 + ".imperial"); + std::string const s_stat_level_10_neutral(s_stat_level_10 + ".neutral"); + std::string const s_stat_level_10_rebel(s_stat_level_10 + ".rebel"); + std::string const s_stat_level_20(s_stat_level_section + ".11_20"); + std::string const s_stat_level_20_imperial(s_stat_level_20 + ".imperial"); + std::string const s_stat_level_20_neutral(s_stat_level_20 + ".neutral"); + std::string const s_stat_level_20_rebel(s_stat_level_20 + ".rebel"); + std::string const s_stat_level_30(s_stat_level_section + ".21_30"); + std::string const s_stat_level_30_imperial(s_stat_level_30 + ".imperial"); + std::string const s_stat_level_30_neutral(s_stat_level_30 + ".neutral"); + std::string const s_stat_level_30_rebel(s_stat_level_30 + ".rebel"); + std::string const s_stat_level_40(s_stat_level_section + ".31_40"); + std::string const s_stat_level_40_imperial(s_stat_level_40 + ".imperial"); + std::string const s_stat_level_40_neutral(s_stat_level_40 + ".neutral"); + std::string const s_stat_level_40_rebel(s_stat_level_40 + ".rebel"); + std::string const s_stat_level_50(s_stat_level_section + ".41_50"); + std::string const s_stat_level_50_imperial(s_stat_level_50 + ".imperial"); + std::string const s_stat_level_50_neutral(s_stat_level_50 + ".neutral"); + std::string const s_stat_level_50_rebel(s_stat_level_50 + ".rebel"); + std::string const s_stat_level_60(s_stat_level_section + ".51_60"); + std::string const s_stat_level_60_imperial(s_stat_level_60 + ".imperial"); + std::string const s_stat_level_60_neutral(s_stat_level_60 + ".neutral"); + std::string const s_stat_level_60_rebel(s_stat_level_60 + ".rebel"); + std::string const s_stat_level_70(s_stat_level_section + ".61_70"); + std::string const s_stat_level_70_imperial(s_stat_level_70 + ".imperial"); + std::string const s_stat_level_70_neutral(s_stat_level_70 + ".neutral"); + std::string const s_stat_level_70_rebel(s_stat_level_70 + ".rebel"); + std::string const s_stat_level_80(s_stat_level_section + ".71_80"); + std::string const s_stat_level_80_imperial(s_stat_level_80 + ".imperial"); + std::string const s_stat_level_80_neutral(s_stat_level_80 + ".neutral"); + std::string const s_stat_level_80_rebel(s_stat_level_80 + ".rebel"); + std::string const s_stat_level_89(s_stat_level_section + ".81_89"); + std::string const s_stat_level_89_imperial(s_stat_level_89 + ".imperial"); + std::string const s_stat_level_89_neutral(s_stat_level_89 + ".neutral"); + std::string const s_stat_level_89_rebel(s_stat_level_89 + ".rebel"); + std::string const s_stat_level_90(s_stat_level_section + ".90"); + std::string const s_stat_level_90_imperial(s_stat_level_90 + ".imperial"); + std::string const s_stat_level_90_neutral(s_stat_level_90 + ".neutral"); + std::string const s_stat_level_90_rebel(s_stat_level_90 + ".rebel"); + + // location planet + std::string const s_stat_location_section("location"); + + // ***MUST*** contain all the planets that are started + // ***MUST*** be named exactly like the planet name in the startPlanet= line + std::string const s_all_planets[] = { + "tutorial", + "tatooine", + "naboo", + "corellia", + "rori", + "talus", + "yavin4", + "endor", + "lok", + "dantooine", + "dathomir", + "dungeon1", + "adventure1", + "adventure2", + "space_corellia", + "space_naboo", + "space_tatooine", + "space_lok", + "space_dantooine", + "space_dathomir", + "space_yavin4", + "space_endor", + "space_heavy1", + "space_light1", + "kashyyyk_main", + "kashyyyk_pob_dungeons", + "kashyyyk_south_dungeons", + "kashyyyk_north_dungeons", + "kashyyyk_rryatt_trail", + "kashyyyk_hunting", + "kashyyyk_dead_forest", + "space_kashyyyk", + "space_npe_falcon", + "space_npe_falcon_2", + "space_npe_falcon_3", + "space_ord_mantell", + "mustafar", + "space_nova_orion", + "" // last one must be blank/empty + }; + + // activities + std::string const s_stat_activities_section("activities"); + std::map s_activities; + void initializeActivitiesList() + { + // these are also defined in session.scriptlib so ***MUST*** be kept in sync + s_activities[1] = s_stat_activities_section + ".pve"; + s_activities[2] = s_stat_activities_section + ".pvp"; + s_activities[4] = s_stat_activities_section + ".crafting"; + s_activities[8] = s_stat_activities_section + ".entertainPerformed"; + s_activities[16] = s_stat_activities_section + ".entertainObserved"; + s_activities[32] = s_stat_activities_section + ".terminalBazaar"; + s_activities[64] = s_stat_activities_section + ".terminalMission"; + s_activities[128] = s_stat_activities_section + ".spaceLaunch"; + s_activities[256] = s_stat_activities_section + ".decorate"; + s_activities[512] = s_stat_activities_section + ".accessVendorOwner"; + s_activities[1024] = s_stat_activities_section + ".accessVendorOther"; + s_activities[2048] = s_stat_activities_section + ".accessHarvester"; + s_activities[4096] = s_stat_activities_section + ".accessFactory"; + s_activities[8192] = s_stat_activities_section + ".accessStructure"; + s_activities[16384] = s_stat_activities_section + ".fishing"; + } + + // character create time + std::string const s_stat_character_create_time_section("characterCreateTime"); + std::string const s_stat_character_create_time_001day(s_stat_character_create_time_section + ".createdWithinPast_Day001"); + std::string const s_stat_character_create_time_002day(s_stat_character_create_time_section + ".createdWithinPast_Day002"); + std::string const s_stat_character_create_time_003day(s_stat_character_create_time_section + ".createdWithinPast_Day003"); + std::string const s_stat_character_create_time_004day(s_stat_character_create_time_section + ".createdWithinPast_Day004"); + std::string const s_stat_character_create_time_005day(s_stat_character_create_time_section + ".createdWithinPast_Day005"); + std::string const s_stat_character_create_time_006day(s_stat_character_create_time_section + ".createdWithinPast_Day006"); + std::string const s_stat_character_create_time_007day(s_stat_character_create_time_section + ".createdWithinPast_Day007"); + std::string const s_stat_character_create_time_014day(s_stat_character_create_time_section + ".createdWithinPast_Day014"); + std::string const s_stat_character_create_time_021day(s_stat_character_create_time_section + ".createdWithinPast_Day021"); + std::string const s_stat_character_create_time_030day(s_stat_character_create_time_section + ".createdWithinPast_Day030"); + std::string const s_stat_character_create_time_060day(s_stat_character_create_time_section + ".createdWithinPast_Day060"); + std::string const s_stat_character_create_time_090day(s_stat_character_create_time_section + ".createdWithinPast_Day090"); + std::string const s_stat_character_create_time_180day(s_stat_character_create_time_section + ".createdWithinPast_Day180"); + std::string const s_stat_character_create_time_270day(s_stat_character_create_time_section + ".createdWithinPast_Day270"); + std::string const s_stat_character_create_time_1year (s_stat_character_create_time_section + ".createdWithinPast_Year1"); + std::string const s_stat_character_create_time_2year (s_stat_character_create_time_section + ".createdWithinPast_Year2"); + std::string const s_stat_character_create_time_3year (s_stat_character_create_time_section + ".createdWithinPast_Year3"); + + // character age + std::string const s_stat_character_age_section("characterAge"); + std::string const s_stat_character_age_001day(s_stat_character_age_section + ".lessThanOrEqual_Day001"); + std::string const s_stat_character_age_002day(s_stat_character_age_section + ".lessThanOrEqual_Day002"); + std::string const s_stat_character_age_003day(s_stat_character_age_section + ".lessThanOrEqual_Day003"); + std::string const s_stat_character_age_004day(s_stat_character_age_section + ".lessThanOrEqual_Day004"); + std::string const s_stat_character_age_005day(s_stat_character_age_section + ".lessThanOrEqual_Day005"); + std::string const s_stat_character_age_006day(s_stat_character_age_section + ".lessThanOrEqual_Day006"); + std::string const s_stat_character_age_007day(s_stat_character_age_section + ".lessThanOrEqual_Day007"); + std::string const s_stat_character_age_014day(s_stat_character_age_section + ".lessThanOrEqual_Day014"); + std::string const s_stat_character_age_021day(s_stat_character_age_section + ".lessThanOrEqual_Day021"); + std::string const s_stat_character_age_030day(s_stat_character_age_section + ".lessThanOrEqual_Day030"); + std::string const s_stat_character_age_060day(s_stat_character_age_section + ".lessThanOrEqual_Day060"); + std::string const s_stat_character_age_090day(s_stat_character_age_section + ".lessThanOrEqual_Day090"); + std::string const s_stat_character_age_180day(s_stat_character_age_section + ".lessThanOrEqual_Day180"); + std::string const s_stat_character_age_270day(s_stat_character_age_section + ".lessThanOrEqual_Day270"); + std::string const s_stat_character_age_1year (s_stat_character_age_section + ".lessThanOrEqual_Year1"); + std::string const s_stat_character_age_2year (s_stat_character_age_section + ".lessThanOrEqual_Year2"); + std::string const s_stat_character_age_3year (s_stat_character_age_section + ".lessThanOrEqual_Year3"); + + // ***strings used to display connected character statistics in SOEMon*** +} + +using namespace LfgCharacterDataNamespace; + +// ====================================================================== + +namespace Archive +{ + void get(ReadIterator & source, LfgCharacterData & target) + { + get(source, target.characterId); + get(source, target.characterCreateTime); + get(source, target.characterAge); + get(source, target.characterName); + get(source, target.characterLowercaseFirstName); + + uint16 uShort = 0; + get(source, uShort); + target.species = static_cast(uShort); + + uint8 uChar = 0; + get(source, uChar); + target.gender = static_cast(uChar); + + get(source, uChar); + target.profession = static_cast(uChar); + + get(source, uChar); + target.pilot = static_cast(uChar); + + get(source, target.level); + get(source, target.faction); + get(source, target.guildName); + get(source, target.guildAbbrev); + get(source, target.citizenOfCity); + get(source, target.groupId); + get(source, target.locationPlanet); + get(source, target.locationRegion); + get(source, target.locationFactionalPresenceGcwRegion); + get(source, target.locationFactionalPresenceGridX); + get(source, target.locationFactionalPresenceGridZ); + get(source, target.locationPlayerCity); + get(source, target.ctsSourceGalaxy); + + get(source, uChar); + target.searchableByCtsSourceGalaxy = ((uChar == 0) ? false : true); + + get(source, uChar); + target.displayLocationInSearchResults = ((uChar == 0) ? false : true); + + get(source, uChar); + target.anonymous = ((uChar == 0) ? false : true); + + get(source, uChar); + target.active = ((uChar == 0) ? false : true); + + get(source, target.characterInterests); + get(source, target.sessionActivity); + } + + void put(ByteStream & target, const LfgCharacterData & source) + { + put(target, source.characterId); + put(target, source.characterCreateTime); + put(target, source.characterAge); + put(target, source.characterName); + put(target, source.characterLowercaseFirstName); + put(target, static_cast(source.species)); + put(target, static_cast(source.gender)); + put(target, static_cast(source.profession)); + put(target, static_cast(source.pilot)); + put(target, source.level); + put(target, source.faction); + put(target, source.guildName); + put(target, source.guildAbbrev); + put(target, source.citizenOfCity); + put(target, source.groupId); + put(target, source.locationPlanet); + put(target, source.locationRegion); + put(target, source.locationFactionalPresenceGcwRegion); + put(target, source.locationFactionalPresenceGridX); + put(target, source.locationFactionalPresenceGridZ); + put(target, source.locationPlayerCity); + put(target, source.ctsSourceGalaxy); + put(target, static_cast(source.searchableByCtsSourceGalaxy ? 1 : 0)); + put(target, static_cast(source.displayLocationInSearchResults ? 1 : 0)); + put(target, static_cast(source.anonymous ? 1 : 0)); + put(target, static_cast(source.active ? 1 : 0)); + put(target, source.characterInterests); + put(target, source.sessionActivity); + } + + void get(ReadIterator & source, LfgCharacterSearchResultData & target) + { + get(source, target.characterId); + get(source, target.characterName); + + uint16 uShort = 0; + get(source, uShort); + target.species = static_cast(uShort); + + uint8 uChar = 0; + get(source, uChar); + target.profession = static_cast(uChar); + + get(source, target.level); + get(source, target.faction); + get(source, target.guildName); + get(source, target.guildAbbrev); + get(source, target.groupId); + get(source, target.locationPlanet); + get(source, target.locationRegion); + get(source, target.locationPlayerCity); + get(source, target.ctsSourceGalaxy); + get(source, target.characterInterests); + } + + void put(ByteStream & target, const LfgCharacterSearchResultData & source) + { + put(target, source.characterId); + put(target, source.characterName); + put(target, static_cast(source.species)); + put(target, static_cast(source.profession)); + put(target, source.level); + put(target, source.faction); + put(target, source.guildName); + put(target, source.guildAbbrev); + put(target, source.groupId); + put(target, source.locationPlanet); + put(target, source.locationRegion); + put(target, source.locationPlayerCity); + put(target, source.ctsSourceGalaxy); + put(target, source.characterInterests); + } +} + +// ====================================================================== + +LfgCharacterData::LfgCharacterData() : + characterId(), + characterCreateTime(-1), + characterAge(-1), + characterName(), + characterLowercaseFirstName(), + species(SharedCreatureObjectTemplate::SP_human), + gender(SharedCreatureObjectTemplate::GE_other), + profession(LfgCharacterData::Prof_Unknown), + pilot(LfgCharacterData::Pilot_None), + level(0), + faction(0), + guildName(), + guildAbbrev(), + citizenOfCity(), + groupId(), + locationPlanet(), + locationRegion(), + locationFactionalPresenceGcwRegion(), + locationFactionalPresenceGridX(0), + locationFactionalPresenceGridZ(0), + locationPlayerCity(), + ctsSourceGalaxy(), + searchableByCtsSourceGalaxy(false), + displayLocationInSearchResults(false), + anonymous(false), + active(false), + characterInterests(), + sessionActivity(0) +{ +} + +// ---------------------------------------------------------------------- + +bool LfgCharacterData::operator== (const LfgCharacterData& rhs) const +{ + return ((characterId == rhs.characterId) && + (characterCreateTime == rhs.characterCreateTime) && + (characterAge == rhs.characterAge) && + (characterName == rhs.characterName) && + (characterLowercaseFirstName == rhs.characterLowercaseFirstName) && + (species == rhs.species) && + (gender == rhs.gender) && + (profession == rhs.profession) && + (pilot == rhs.pilot) && + (level == rhs.level) && + (faction == rhs.faction) && + (guildName == rhs.guildName) && + (guildAbbrev == rhs.guildAbbrev) && + (citizenOfCity == rhs.citizenOfCity) && + (groupId == rhs.groupId) && + (locationPlanet == rhs.locationPlanet) && + (locationRegion == rhs.locationRegion) && + (locationFactionalPresenceGcwRegion == rhs.locationFactionalPresenceGcwRegion) && + (locationFactionalPresenceGridX == rhs.locationFactionalPresenceGridX) && + (locationFactionalPresenceGridZ == rhs.locationFactionalPresenceGridZ) && + (locationPlayerCity == rhs.locationPlayerCity) && + (ctsSourceGalaxy == rhs.ctsSourceGalaxy) && + (searchableByCtsSourceGalaxy == rhs.searchableByCtsSourceGalaxy) && + (displayLocationInSearchResults == rhs.displayLocationInSearchResults) && + (anonymous == rhs.anonymous) && + (active == rhs.active) && + (characterInterests == rhs.characterInterests) && + (sessionActivity == rhs.sessionActivity) + ); +} + +// ---------------------------------------------------------------------- + +bool LfgCharacterData::operator!= (const LfgCharacterData& rhs) const +{ + return !operator==(rhs); +} + +// ---------------------------------------------------------------------- + +LfgCharacterData::Profession LfgCharacterData::convertSkillTemplateToProfession(const std::string & skillTemplate) +{ + if (skillTemplate.find("smuggler_") == 0) + return LfgCharacterData::Prof_Smuggler; + else if (skillTemplate.find("bounty_hunter_") == 0) + return LfgCharacterData::Prof_Bh; + else if (skillTemplate.find("officer_") == 0) + return LfgCharacterData::Prof_Officer; + else if (skillTemplate.find("commando_") == 0) + return LfgCharacterData::Prof_Commando; + else if (skillTemplate.find("force_sensitive_") == 0) + return LfgCharacterData::Prof_Jedi; + else if (skillTemplate.find("medic_") == 0) + return LfgCharacterData::Prof_Medic; + else if (skillTemplate.find("spy_") == 0) + return LfgCharacterData::Prof_Spy; + else if (skillTemplate.find("entertainer_") == 0) + return LfgCharacterData::Prof_Entertainer; + else if (skillTemplate == "trader_0a") + return LfgCharacterData::Prof_Trader_Domestics; + else if (skillTemplate == "trader_0b") + return LfgCharacterData::Prof_Trader_Structures; + else if (skillTemplate == "trader_0c") + return LfgCharacterData::Prof_Trader_Munitions; + else if (skillTemplate == "trader_0d") + return LfgCharacterData::Prof_Trader_Engineering; + + return LfgCharacterData::Prof_Unknown; +} + +// ---------------------------------------------------------------------- + +std::string LfgCharacterData::getProfessionDebugString(LfgCharacterData::Profession profession) +{ + std::string output; + + if (profession == LfgCharacterData::Prof_Bh) + output = "Bounty Hunter"; + else if (profession == LfgCharacterData::Prof_Commando) + output = "Commando"; + else if (profession == LfgCharacterData::Prof_Entertainer) + output = "Entertainer"; + else if (profession == LfgCharacterData::Prof_Jedi) + output = "Jedi"; + else if (profession == LfgCharacterData::Prof_Medic) + output = "Medic"; + else if (profession == LfgCharacterData::Prof_Officer) + output = "Officer"; + else if (profession == LfgCharacterData::Prof_Smuggler) + output = "Smuggler"; + else if (profession == LfgCharacterData::Prof_Spy) + output = "Spy"; + else if (profession == LfgCharacterData::Prof_Trader_Domestics) + output = "Trader - Domestics"; + else if (profession == LfgCharacterData::Prof_Trader_Engineering) + output = "Trader - Engineering"; + else if (profession == LfgCharacterData::Prof_Trader_Munitions) + output = "Trader - Munitions"; + else if (profession == LfgCharacterData::Prof_Trader_Structures) + output = "Trader - Structures"; + else if (profession == LfgCharacterData::Prof_NPC) + output = "NPC"; + else if (profession == LfgCharacterData::Prof_Unknown) + output = "Unknown"; + else + output = FormattedString<32>().sprintf("%d", static_cast(profession)); + + return output; +} + +// ---------------------------------------------------------------------- + +Unicode::String const & LfgCharacterData::getProfessionDisplayString(LfgCharacterData::Profession profession) +{ + if (s_professionDisplayString.empty()) + { + s_professionDisplayString.resize(static_cast(LfgCharacterData::Profession_MAX)); + s_professionDisplayString[static_cast(LfgCharacterData::Prof_Unknown)] = StringId("ui_prof", "unknown").localize(); + s_professionDisplayString[static_cast(LfgCharacterData::Prof_Bh)] = StringId("ui_roadmap", "bounty_hunter").localize(); + s_professionDisplayString[static_cast(LfgCharacterData::Prof_Commando)] = StringId("ui_roadmap", "commando").localize(); + s_professionDisplayString[static_cast(LfgCharacterData::Prof_Entertainer)] = StringId("ui_roadmap", "entertainer").localize(); + s_professionDisplayString[static_cast(LfgCharacterData::Prof_Jedi)] = StringId("ui_roadmap", "force_sensitive").localize(); + s_professionDisplayString[static_cast(LfgCharacterData::Prof_Medic)] = StringId("ui_roadmap", "medic").localize(); + s_professionDisplayString[static_cast(LfgCharacterData::Prof_Officer)] = StringId("ui_roadmap", "officer").localize(); + s_professionDisplayString[static_cast(LfgCharacterData::Prof_Smuggler)] = StringId("ui_roadmap", "smuggler").localize(); + s_professionDisplayString[static_cast(LfgCharacterData::Prof_Spy)] = StringId("ui_roadmap", "spy").localize(); + s_professionDisplayString[static_cast(LfgCharacterData::Prof_Trader_Domestics)] = StringId("ui_roadmap", "trader_0a").localize(); + s_professionDisplayString[static_cast(LfgCharacterData::Prof_Trader_Engineering)] = StringId("ui_roadmap", "trader_0d").localize(); + s_professionDisplayString[static_cast(LfgCharacterData::Prof_Trader_Munitions)] = StringId("ui_roadmap", "trader_0c").localize(); + s_professionDisplayString[static_cast(LfgCharacterData::Prof_Trader_Structures)] = StringId("ui_roadmap", "trader_0b").localize(); + s_professionDisplayString[static_cast(LfgCharacterData::Prof_NPC)] = StringId("ui_prof", "npc").localize(); + } + + static Unicode::String empty; + + if ((static_cast(profession) >= 0) && (static_cast(profession) < s_professionDisplayString.size())) + return s_professionDisplayString[static_cast(profession)]; + + return empty; +} + +// ---------------------------------------------------------------------- + +std::string LfgCharacterData::getDebugString() const +{ + if (s_activities.empty()) + initializeActivitiesList(); + + std::string output = Unicode::wideToNarrow(characterName); + output += " ("; + output += characterId.getValueString(); + output += ")"; + + output += "\nFirst Name: "; + output += characterLowercaseFirstName; + + output += "\nCreate Time: "; + if (characterCreateTime > 0) + output += CalendarTime::convertEpochToTimeStringLocal(static_cast(characterCreateTime)) + ", " + CalendarTime::convertEpochToTimeStringGMT(static_cast(characterCreateTime)); + else + output += "N/A"; + + output += "\nAge: "; + output += FormattedString<128>().sprintf("%d days", characterAge); + + output += "\nCTS Source Galaxy: "; + if (ctsSourceGalaxy.empty()) + { + output += "(none)"; + } + else + { + bool first = true; + for (std::set::const_iterator iter = ctsSourceGalaxy.begin(); iter != ctsSourceGalaxy.end(); ++iter) + { + if (first) + first = false; + else + output += ", "; + + output += *iter; + } + } + + output += "\nSearchable By CTS Source Galaxy: "; + output += (searchableByCtsSourceGalaxy ? "yes" : "no"); + + output += "\nDisplay Location In Search Results: "; + output += (displayLocationInSearchResults ? "yes" : "no"); + + output += "\nAnonymous: "; + output += (anonymous ? "yes" : "no"); + + output += "\nActive: "; + output += (active ? "yes" : "no"); + + output += "\nLocation: "; + + if (!locationPlayerCity.empty()) + { + output += locationPlayerCity; + output += ", "; + } + + output += locationPlanet; + + if (!locationRegion.empty()) + { + output += ","; + output += locationRegion; + } + + if (!locationFactionalPresenceGcwRegion.empty()) + { + output += ","; + output += locationFactionalPresenceGcwRegion; + + if (::strncmp("space_", locationPlanet.c_str(), 6)) + output += FormattedString<128>().sprintf(" (%d, %d) [grid (%d, %d) -> (%d, %d)]", locationFactionalPresenceGridX, locationFactionalPresenceGridZ, (locationFactionalPresenceGridX - (PvpData::getGcwFactionalPresenceGridSize() / 2)), (locationFactionalPresenceGridZ - (PvpData::getGcwFactionalPresenceGridSize() / 2)), (locationFactionalPresenceGridX + (PvpData::getGcwFactionalPresenceGridSize() / 2)), (locationFactionalPresenceGridZ + (PvpData::getGcwFactionalPresenceGridSize() / 2))); + } + + output += "\nSpecies: "; + if (species == SharedCreatureObjectTemplate::SP_bothan) + output += "Bothan"; + else if (species == SharedCreatureObjectTemplate::SP_human) + output += "Human"; + else if (species == SharedCreatureObjectTemplate::SP_ithorian) + output += "Ithorian"; + else if (species == SharedCreatureObjectTemplate::SP_monCalamari) + output += "Mon Calamari"; + else if (species == SharedCreatureObjectTemplate::SP_rodian) + output += "Rodian"; + else if (species == SharedCreatureObjectTemplate::SP_sullustan) + output += "Sullustan"; + else if (species == SharedCreatureObjectTemplate::SP_trandoshan) + output += "Trandoshan"; + else if (species == SharedCreatureObjectTemplate::SP_twilek) + output += "Twilek"; + else if (species == SharedCreatureObjectTemplate::SP_wookiee) + output += "Wookiee"; + else if (species == SharedCreatureObjectTemplate::SP_zabrak) + output += "Zabrak"; + else + output += FormattedString<32>().sprintf("%d", static_cast(species)); + + output += "\nGender: "; + if (gender == SharedCreatureObjectTemplate::GE_male) + output += "Male"; + else if (gender == SharedCreatureObjectTemplate::GE_female) + output += "Female"; + else if (gender == SharedCreatureObjectTemplate::GE_other) + output += "Other"; + else + output += FormattedString<32>().sprintf("%d", static_cast(gender)); + + output += "\nProfession: "; + output += getProfessionDebugString(profession); + + output += FormattedString<64>().sprintf("\nLevel: %d", level); + + output += "\nFaction: "; + if (PvpData::isImperialFactionId(faction)) + output += "Imperial"; + else if (PvpData::isRebelFactionId(faction)) + output += "Rebel"; + else if (PvpData::isNeutralFactionId(faction)) + output += "Neutral"; + else + output += FormattedString<32>().sprintf("%lu", faction); + + output += "\nPilot: "; + if (pilot == LfgCharacterData::Pilot_Imperial) + output += "Imperial"; + else if (pilot == LfgCharacterData::Pilot_Rebel) + output += "Rebel"; + else if (pilot == LfgCharacterData::Pilot_Neutral) + output += "Neutral"; + else if (pilot == LfgCharacterData::Pilot_None) + output += "(not a pilot)"; + else + output += FormattedString<32>().sprintf("%d", static_cast(pilot)); + + output += "\nGuild: "; + if (guildName.empty()) + { + output += "(unguilded)"; + } + else + { + output += guildName; + output += " ("; + output += guildAbbrev; + output += ")"; + } + + output += "\nCitizen Of: "; + if (!citizenOfCity.empty()) + { + output += citizenOfCity; + } + + output += "\nGroup Id: "; + output += groupId.getValueString(); + + output += "\nActivities: "; + std::string activities; + for (std::map::const_iterator iterActivities = s_activities.begin(); iterActivities != s_activities.end(); ++iterActivities) + { + if ((sessionActivity & iterActivities->first) == iterActivities->first) + { + std::string activity = iterActivities->second; + std::string::size_type const dotPos = activity.find('.'); + if ((dotPos != std::string::npos) && ((dotPos + 1) < activity.size())) + activity = activity.substr(dotPos + 1); + + if (!activity.empty()) + { + if (!activities.empty()) + activities += ", "; + + activities += activity; + } + } + } + + if (activities.empty()) + activities = "None"; + + output += activities; + + output += "\nInterests: "; + std::string sInterests = LfgDataTable::getSetLfgNodeDebugString(characterInterests, false); + if (sInterests.empty()) + { + output += "(none specified)\n"; + } + else + { + output += "\n"; + output += sInterests; + } + + return output; +} + +// ---------------------------------------------------------------------- + +std::map const & LfgCharacterData::calculateStatistics(std::map const & connectedCharacterLfgData) +{ + if (s_activities.empty()) + initializeActivitiesList(); + + static std::map statistics; + if (statistics.empty()) + { + // all possible statistics ***SHOULD*** be inserted/initialized here + // ***DO NOT*** insert new statistics into the statistics map outside + // of this initialization block; outside of this initialization block, + // the only change to the statistics map should be to update the count + // for individual statistics; + + // searchable/anonymous + statistics[s_stat_searchable_section] = -1; + statistics[s_stat_anonymous] = 0; + statistics[s_stat_searchable] = 0; + + // active/inactive + statistics[s_stat_active_section] = -1; + statistics[s_stat_active] = 0; + statistics[s_stat_inactive] = 0; + + // grouped/ungrouped + statistics[s_stat_grouped_section] = -1; + statistics[s_stat_grouped] = 0; + statistics[s_stat_ungrouped] = 0; + + // guilded/unguilded + statistics[s_stat_guilded_section] = -1; + statistics[s_stat_guilded] = 0; + statistics[s_stat_unguilded] = 0; + + // searchableByCtsSourceGalaxy + statistics[s_stat_searchablebyctssourcegalaxy_section] = -1; + statistics[s_stat_searchablebyctssourcegalaxy_yes] = 0; + statistics[s_stat_searchablebyctssourcegalaxy_no] = 0; + + // displayLocationInSearchResults + statistics[s_stat_displayLocation_section] = -1; + statistics[s_stat_displayLocation] = 0; + statistics[s_stat_hideLocation] = 0; + + // gender + statistics[s_stat_gender_section] = -1; + statistics[s_stat_female] = 0; + statistics[s_stat_male] = 0; + + // faction + statistics[s_stat_faction_section] = -1; + statistics[s_stat_faction_imperial] = 0; + statistics[s_stat_faction_neutral] = 0; + statistics[s_stat_faction_rebel] = 0; + + // pilot + statistics[s_stat_pilot_section] = -1; + statistics[s_stat_pilot_imperial] = 0; + statistics[s_stat_pilot_neutral] = 0; + statistics[s_stat_pilot_none] = 0; + statistics[s_stat_pilot_rebel] = 0; + + // species + statistics[s_stat_species_section] = -1; + statistics[s_stat_bothan] = 0; + statistics[s_stat_human] = 0; + statistics[s_stat_ithorian] = 0; + statistics[s_stat_monCalamari] = 0; + statistics[s_stat_rodian] = 0; + statistics[s_stat_sullustan] = 0; + statistics[s_stat_trandoshan] = 0; + statistics[s_stat_twilek] = 0; + statistics[s_stat_wookiee] = 0; + statistics[s_stat_zabrak] = 0; + + // species by gender + statistics[s_stat_species_gender_section] = -1; + statistics[s_stat_bothan_m] = 0; + statistics[s_stat_bothan_f] = 0; + statistics[s_stat_human_m] = 0; + statistics[s_stat_human_f] = 0; + statistics[s_stat_ithorian_m] = 0; + statistics[s_stat_ithorian_f] = 0; + statistics[s_stat_monCalamari_m] = 0; + statistics[s_stat_monCalamari_f] = 0; + statistics[s_stat_rodian_m] = 0; + statistics[s_stat_rodian_f] = 0; + statistics[s_stat_sullustan_m] = 0; + statistics[s_stat_sullustan_f] = 0; + statistics[s_stat_trandoshan_m] = 0; + statistics[s_stat_trandoshan_f] = 0; + statistics[s_stat_twilek_m] = 0; + statistics[s_stat_twilek_f] = 0; + statistics[s_stat_wookiee_m] = 0; + statistics[s_stat_wookiee_f] = 0; + statistics[s_stat_zabrak_m] = 0; + statistics[s_stat_zabrak_f] = 0; + + // profession + statistics[s_stat_profession_section] = -1; + statistics[s_stat_bountyHunter] = 0; + statistics[s_stat_commando] = 0; + statistics[s_stat_entertainer] = 0; + statistics[s_stat_jedi] = 0; + statistics[s_stat_medic] = 0; + statistics[s_stat_officer] = 0; + statistics[s_stat_smuggler] = 0; + statistics[s_stat_spy] = 0; + statistics[s_stat_traderDomestics] = 0; + statistics[s_stat_traderEngineering] = 0; + statistics[s_stat_traderMunitions] = 0; + statistics[s_stat_traderStructures] = 0; + + // profession by gender + statistics[s_stat_profession_gender_section] = -1; + statistics[s_stat_bountyHunter_m] = 0; + statistics[s_stat_bountyHunter_f] = 0; + statistics[s_stat_commando_m] = 0; + statistics[s_stat_commando_f] = 0; + statistics[s_stat_entertainer_m] = 0; + statistics[s_stat_entertainer_f] = 0; + statistics[s_stat_jedi_m] = 0; + statistics[s_stat_jedi_f] = 0; + statistics[s_stat_medic_m] = 0; + statistics[s_stat_medic_f] = 0; + statistics[s_stat_officer_m] = 0; + statistics[s_stat_officer_f] = 0; + statistics[s_stat_smuggler_m] = 0; + statistics[s_stat_smuggler_f] = 0; + statistics[s_stat_spy_m] = 0; + statistics[s_stat_spy_f] = 0; + statistics[s_stat_traderDomestics_m] = 0; + statistics[s_stat_traderDomestics_f] = 0; + statistics[s_stat_traderEngineering_m] = 0; + statistics[s_stat_traderEngineering_f] = 0; + statistics[s_stat_traderMunitions_m] = 0; + statistics[s_stat_traderMunitions_f] = 0; + statistics[s_stat_traderStructures_m] = 0; + statistics[s_stat_traderStructures_f] = 0; + + // level + statistics[s_stat_level_section] = -1; + statistics[s_stat_level_10] = 0; + statistics[s_stat_level_10_imperial] = 0; + statistics[s_stat_level_10_neutral] = 0; + statistics[s_stat_level_10_rebel] = 0; + statistics[s_stat_level_20] = 0; + statistics[s_stat_level_20_imperial] = 0; + statistics[s_stat_level_20_neutral] = 0; + statistics[s_stat_level_20_rebel] = 0; + statistics[s_stat_level_30] = 0; + statistics[s_stat_level_30_imperial] = 0; + statistics[s_stat_level_30_neutral] = 0; + statistics[s_stat_level_30_rebel] = 0; + statistics[s_stat_level_40] = 0; + statistics[s_stat_level_40_imperial] = 0; + statistics[s_stat_level_40_neutral] = 0; + statistics[s_stat_level_40_rebel] = 0; + statistics[s_stat_level_50] = 0; + statistics[s_stat_level_50_imperial] = 0; + statistics[s_stat_level_50_neutral] = 0; + statistics[s_stat_level_50_rebel] = 0; + statistics[s_stat_level_60] = 0; + statistics[s_stat_level_60_imperial] = 0; + statistics[s_stat_level_60_neutral] = 0; + statistics[s_stat_level_60_rebel] = 0; + statistics[s_stat_level_70] = 0; + statistics[s_stat_level_70_imperial] = 0; + statistics[s_stat_level_70_neutral] = 0; + statistics[s_stat_level_70_rebel] = 0; + statistics[s_stat_level_80] = 0; + statistics[s_stat_level_80_imperial] = 0; + statistics[s_stat_level_80_neutral] = 0; + statistics[s_stat_level_80_rebel] = 0; + statistics[s_stat_level_89] = 0; + statistics[s_stat_level_89_imperial] = 0; + statistics[s_stat_level_89_neutral] = 0; + statistics[s_stat_level_89_rebel] = 0; + statistics[s_stat_level_90] = 0; + statistics[s_stat_level_90_imperial] = 0; + statistics[s_stat_level_90_neutral] = 0; + statistics[s_stat_level_90_rebel] = 0; + + // location planet + statistics[s_stat_location_section] = -1; + for (int i = 0; !s_all_planets[i].empty(); ++i) + statistics[s_stat_location_section + "." + s_all_planets[i]] = 0; + + // activities + statistics[s_stat_activities_section] = -1; + for (std::map::const_iterator iterActivities = s_activities.begin(); iterActivities != s_activities.end(); ++iterActivities) + statistics[iterActivities->second] = 0; + + // character create time + statistics[s_stat_character_create_time_section] = -1; + statistics[s_stat_character_create_time_001day] = 0; + statistics[s_stat_character_create_time_002day] = 0; + statistics[s_stat_character_create_time_003day] = 0; + statistics[s_stat_character_create_time_004day] = 0; + statistics[s_stat_character_create_time_005day] = 0; + statistics[s_stat_character_create_time_006day] = 0; + statistics[s_stat_character_create_time_007day] = 0; + statistics[s_stat_character_create_time_014day] = 0; + statistics[s_stat_character_create_time_021day] = 0; + statistics[s_stat_character_create_time_030day] = 0; + statistics[s_stat_character_create_time_060day] = 0; + statistics[s_stat_character_create_time_090day] = 0; + statistics[s_stat_character_create_time_180day] = 0; + statistics[s_stat_character_create_time_270day] = 0; + statistics[s_stat_character_create_time_1year] = 0; + statistics[s_stat_character_create_time_2year] = 0; + statistics[s_stat_character_create_time_3year] = 0; + + // character age + statistics[s_stat_character_age_section] = -1; + statistics[s_stat_character_age_001day] = 0; + statistics[s_stat_character_age_002day] = 0; + statistics[s_stat_character_age_003day] = 0; + statistics[s_stat_character_age_004day] = 0; + statistics[s_stat_character_age_005day] = 0; + statistics[s_stat_character_age_006day] = 0; + statistics[s_stat_character_age_007day] = 0; + statistics[s_stat_character_age_014day] = 0; + statistics[s_stat_character_age_021day] = 0; + statistics[s_stat_character_age_030day] = 0; + statistics[s_stat_character_age_060day] = 0; + statistics[s_stat_character_age_090day] = 0; + statistics[s_stat_character_age_180day] = 0; + statistics[s_stat_character_age_270day] = 0; + statistics[s_stat_character_age_1year] = 0; + statistics[s_stat_character_age_2year] = 0; + statistics[s_stat_character_age_3year] = 0; + } + + // character create time + static std::map > createTimeStatistics; + if (createTimeStatistics.empty()) + { + createTimeStatistics[(60 * 60 * 24 * 1)] = std::make_pair(s_stat_character_create_time_001day, 0); + createTimeStatistics[(60 * 60 * 24 * 2)] = std::make_pair(s_stat_character_create_time_002day, 0); + createTimeStatistics[(60 * 60 * 24 * 3)] = std::make_pair(s_stat_character_create_time_003day, 0); + createTimeStatistics[(60 * 60 * 24 * 4)] = std::make_pair(s_stat_character_create_time_004day, 0); + createTimeStatistics[(60 * 60 * 24 * 5)] = std::make_pair(s_stat_character_create_time_005day, 0); + createTimeStatistics[(60 * 60 * 24 * 6)] = std::make_pair(s_stat_character_create_time_006day, 0); + createTimeStatistics[(60 * 60 * 24 * 7)] = std::make_pair(s_stat_character_create_time_007day, 0); + createTimeStatistics[(60 * 60 * 24 * 14)] = std::make_pair(s_stat_character_create_time_014day, 0); + createTimeStatistics[(60 * 60 * 24 * 21)] = std::make_pair(s_stat_character_create_time_021day, 0); + createTimeStatistics[(60 * 60 * 24 * 30)] = std::make_pair(s_stat_character_create_time_030day, 0); + createTimeStatistics[(60 * 60 * 24 * 60)] = std::make_pair(s_stat_character_create_time_060day, 0); + createTimeStatistics[(60 * 60 * 24 * 90)] = std::make_pair(s_stat_character_create_time_090day, 0); + createTimeStatistics[(60 * 60 * 24 * 180)] = std::make_pair(s_stat_character_create_time_180day, 0); + createTimeStatistics[(60 * 60 * 24 * 270)] = std::make_pair(s_stat_character_create_time_270day, 0); + createTimeStatistics[(60 * 60 * 24 * 365)] = std::make_pair(s_stat_character_create_time_1year, 0); + createTimeStatistics[(60 * 60 * 24 * 730)] = std::make_pair(s_stat_character_create_time_2year, 0); + createTimeStatistics[(60 * 60 * 24 * 1095)] = std::make_pair(s_stat_character_create_time_3year, 0); + } + + // character age + static std::map > ageStatistics; + if (ageStatistics.empty()) + { + ageStatistics[1] = std::make_pair(s_stat_character_age_001day, 0); + ageStatistics[2] = std::make_pair(s_stat_character_age_002day, 0); + ageStatistics[3] = std::make_pair(s_stat_character_age_003day, 0); + ageStatistics[4] = std::make_pair(s_stat_character_age_004day, 0); + ageStatistics[5] = std::make_pair(s_stat_character_age_005day, 0); + ageStatistics[6] = std::make_pair(s_stat_character_age_006day, 0); + ageStatistics[7] = std::make_pair(s_stat_character_age_007day, 0); + ageStatistics[14] = std::make_pair(s_stat_character_age_014day, 0); + ageStatistics[21] = std::make_pair(s_stat_character_age_021day, 0); + ageStatistics[30] = std::make_pair(s_stat_character_age_030day, 0); + ageStatistics[60] = std::make_pair(s_stat_character_age_060day, 0); + ageStatistics[90] = std::make_pair(s_stat_character_age_090day, 0); + ageStatistics[180] = std::make_pair(s_stat_character_age_180day, 0); + ageStatistics[270] = std::make_pair(s_stat_character_age_270day, 0); + ageStatistics[365] = std::make_pair(s_stat_character_age_1year, 0); + ageStatistics[730] = std::make_pair(s_stat_character_age_2year, 0); + ageStatistics[1095] = std::make_pair(s_stat_character_age_3year, 0); + } + + // set all statistics count to 0 + { + for (std::map::iterator iter = statistics.begin(); iter != statistics.end(); ++iter) + { + if (iter->second > 0) + iter->second = 0; + } + + for (std::map >::iterator iterCreateTimeStatistics = createTimeStatistics.begin(); iterCreateTimeStatistics != createTimeStatistics.end(); ++iterCreateTimeStatistics) + { + iterCreateTimeStatistics->second.second = 0; + } + + for (std::map >::iterator iterAgeStatistics = ageStatistics.begin(); iterAgeStatistics != ageStatistics.end(); ++iterAgeStatistics) + { + iterAgeStatistics->second.second = 0; + } + } + + int32 const timeNow = static_cast(::time(NULL)); + for (std::map::const_iterator iterLfgData = connectedCharacterLfgData.begin(); iterLfgData != connectedCharacterLfgData.end(); ++iterLfgData) + { + // searchable/anonymous + if (iterLfgData->second.anonymous) + ++(statistics[s_stat_anonymous]); + else + ++(statistics[s_stat_searchable]); + + // active/inactive + if (iterLfgData->second.active) + ++(statistics[s_stat_active]); + else + ++(statistics[s_stat_inactive]); + + // grouped/ungrouped + if (iterLfgData->second.groupId.isValid()) + ++(statistics[s_stat_grouped]); + else + ++(statistics[s_stat_ungrouped]); + + // guilded/unguilded + if (!iterLfgData->second.guildName.empty()) + ++(statistics[s_stat_guilded]); + else + ++(statistics[s_stat_unguilded]); + + // searchableByCtsSourceGalaxy + if (iterLfgData->second.searchableByCtsSourceGalaxy) + ++(statistics[s_stat_searchablebyctssourcegalaxy_yes]); + else + ++(statistics[s_stat_searchablebyctssourcegalaxy_no]); + + // displayLocationInSearchResults + if (iterLfgData->second.displayLocationInSearchResults) + ++(statistics[s_stat_displayLocation]); + else + ++(statistics[s_stat_hideLocation]); + + // gender + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_male]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_female]); + + // faction + if (PvpData::isImperialFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_faction_imperial]); + else if (PvpData::isRebelFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_faction_rebel]); + else if (PvpData::isNeutralFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_faction_neutral]); + + // pilot + if (iterLfgData->second.pilot == LfgCharacterData::Pilot_Imperial) + ++(statistics[s_stat_pilot_imperial]); + else if (iterLfgData->second.pilot == LfgCharacterData::Pilot_Rebel) + ++(statistics[s_stat_pilot_rebel]); + else if (iterLfgData->second.pilot == LfgCharacterData::Pilot_Neutral) + ++(statistics[s_stat_pilot_neutral]); + else if (iterLfgData->second.pilot == LfgCharacterData::Pilot_None) + ++(statistics[s_stat_pilot_none]); + + // species and species by gender + if (iterLfgData->second.species == SharedCreatureObjectTemplate::SP_bothan) + { + ++(statistics[s_stat_bothan]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_bothan_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_bothan_f]); + } + else if (iterLfgData->second.species == SharedCreatureObjectTemplate::SP_human) + { + ++(statistics[s_stat_human]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_human_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_human_f]); + } + else if (iterLfgData->second.species == SharedCreatureObjectTemplate::SP_ithorian) + { + ++(statistics[s_stat_ithorian]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_ithorian_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_ithorian_f]); + } + else if (iterLfgData->second.species == SharedCreatureObjectTemplate::SP_monCalamari) + { + ++(statistics[s_stat_monCalamari]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_monCalamari_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_monCalamari_f]); + } + else if (iterLfgData->second.species == SharedCreatureObjectTemplate::SP_rodian) + { + ++(statistics[s_stat_rodian]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_rodian_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_rodian_f]); + } + else if (iterLfgData->second.species == SharedCreatureObjectTemplate::SP_sullustan) + { + ++(statistics[s_stat_sullustan]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_sullustan_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_sullustan_f]); + } + else if (iterLfgData->second.species == SharedCreatureObjectTemplate::SP_trandoshan) + { + ++(statistics[s_stat_trandoshan]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_trandoshan_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_trandoshan_f]); + } + else if (iterLfgData->second.species == SharedCreatureObjectTemplate::SP_twilek) + { + ++(statistics[s_stat_twilek]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_twilek_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_twilek_f]); + } + else if (iterLfgData->second.species == SharedCreatureObjectTemplate::SP_wookiee) + { + ++(statistics[s_stat_wookiee]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_wookiee_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_wookiee_f]); + } + else if (iterLfgData->second.species == SharedCreatureObjectTemplate::SP_zabrak) + { + ++(statistics[s_stat_zabrak]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_zabrak_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_zabrak_f]); + } + + // profession and profession by gender + if (iterLfgData->second.profession == LfgCharacterData::Prof_Bh) + { + ++(statistics[s_stat_bountyHunter]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_bountyHunter_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_bountyHunter_f]); + } + else if (iterLfgData->second.profession == LfgCharacterData::Prof_Commando) + { + ++(statistics[s_stat_commando]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_commando_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_commando_f]); + } + else if (iterLfgData->second.profession == LfgCharacterData::Prof_Entertainer) + { + ++(statistics[s_stat_entertainer]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_entertainer_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_entertainer_f]); + } + else if (iterLfgData->second.profession == LfgCharacterData::Prof_Jedi) + { + ++(statistics[s_stat_jedi]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_jedi_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_jedi_f]); + } + else if (iterLfgData->second.profession == LfgCharacterData::Prof_Medic) + { + ++(statistics[s_stat_medic]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_medic_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_medic_f]); + } + else if (iterLfgData->second.profession == LfgCharacterData::Prof_Officer) + { + ++(statistics[s_stat_officer]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_officer_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_officer_f]); + } + else if (iterLfgData->second.profession == LfgCharacterData::Prof_Smuggler) + { + ++(statistics[s_stat_smuggler]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_smuggler_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_smuggler_f]); + } + else if (iterLfgData->second.profession == LfgCharacterData::Prof_Spy) + { + ++(statistics[s_stat_spy]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_spy_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_spy_f]); + } + else if (iterLfgData->second.profession == LfgCharacterData::Prof_Trader_Domestics) + { + ++(statistics[s_stat_traderDomestics]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_traderDomestics_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_traderDomestics_f]); + } + else if (iterLfgData->second.profession == LfgCharacterData::Prof_Trader_Engineering) + { + ++(statistics[s_stat_traderEngineering]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_traderEngineering_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_traderEngineering_f]); + } + else if (iterLfgData->second.profession == LfgCharacterData::Prof_Trader_Munitions) + { + ++(statistics[s_stat_traderMunitions]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_traderMunitions_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_traderMunitions_f]); + } + else if (iterLfgData->second.profession == LfgCharacterData::Prof_Trader_Structures) + { + ++(statistics[s_stat_traderStructures]); + + if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_male) + ++(statistics[s_stat_traderStructures_m]); + else if (iterLfgData->second.gender == SharedCreatureObjectTemplate::GE_female) + ++(statistics[s_stat_traderStructures_f]); + } + + // level + if (iterLfgData->second.level <= 10) + { + ++(statistics[s_stat_level_10]); + + // faction + if (PvpData::isImperialFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_10_imperial]); + else if (PvpData::isRebelFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_10_rebel]); + else if (PvpData::isNeutralFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_10_neutral]); + } + else if (iterLfgData->second.level <= 20) + { + ++(statistics[s_stat_level_20]); + + // faction + if (PvpData::isImperialFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_20_imperial]); + else if (PvpData::isRebelFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_20_rebel]); + else if (PvpData::isNeutralFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_20_neutral]); + } + else if (iterLfgData->second.level <= 30) + { + ++(statistics[s_stat_level_30]); + + // faction + if (PvpData::isImperialFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_30_imperial]); + else if (PvpData::isRebelFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_30_rebel]); + else if (PvpData::isNeutralFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_30_neutral]); + } + else if (iterLfgData->second.level <= 40) + { + ++(statistics[s_stat_level_40]); + + // faction + if (PvpData::isImperialFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_40_imperial]); + else if (PvpData::isRebelFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_40_rebel]); + else if (PvpData::isNeutralFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_40_neutral]); + } + else if (iterLfgData->second.level <= 50) + { + ++(statistics[s_stat_level_50]); + + // faction + if (PvpData::isImperialFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_50_imperial]); + else if (PvpData::isRebelFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_50_rebel]); + else if (PvpData::isNeutralFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_50_neutral]); + } + else if (iterLfgData->second.level <= 60) + { + ++(statistics[s_stat_level_60]); + + // faction + if (PvpData::isImperialFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_60_imperial]); + else if (PvpData::isRebelFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_60_rebel]); + else if (PvpData::isNeutralFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_60_neutral]); + } + else if (iterLfgData->second.level <= 70) + { + ++(statistics[s_stat_level_70]); + + // faction + if (PvpData::isImperialFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_70_imperial]); + else if (PvpData::isRebelFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_70_rebel]); + else if (PvpData::isNeutralFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_70_neutral]); + } + else if (iterLfgData->second.level <= 80) + { + ++(statistics[s_stat_level_80]); + + // faction + if (PvpData::isImperialFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_80_imperial]); + else if (PvpData::isRebelFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_80_rebel]); + else if (PvpData::isNeutralFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_80_neutral]); + } + else if (iterLfgData->second.level <= 89) + { + ++(statistics[s_stat_level_89]); + + // faction + if (PvpData::isImperialFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_89_imperial]); + else if (PvpData::isRebelFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_89_rebel]); + else if (PvpData::isNeutralFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_89_neutral]); + } + else + { + ++(statistics[s_stat_level_90]); + + // faction + if (PvpData::isImperialFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_90_imperial]); + else if (PvpData::isRebelFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_90_rebel]); + else if (PvpData::isNeutralFactionId(iterLfgData->second.faction)) + ++(statistics[s_stat_level_90_neutral]); + } + + // location planet + if (!iterLfgData->second.locationPlanet.empty()) + ++(statistics[s_stat_location_section + "." + iterLfgData->second.locationPlanet]); + + // activities + for (std::map::const_iterator iterActivities = s_activities.begin(); iterActivities != s_activities.end(); ++iterActivities) + { + if ((iterLfgData->second.sessionActivity & iterActivities->first) == iterActivities->first) + ++(statistics[iterActivities->second]); + } + + // character create time + if (iterLfgData->second.characterCreateTime > 0) + { + int32 const createTimeSecondsAgo = std::max(static_cast(0), (timeNow - iterLfgData->second.characterCreateTime)); + + std::map >::iterator iterFind = createTimeStatistics.lower_bound(createTimeSecondsAgo); + if (iterFind != createTimeStatistics.end()) + ++(iterFind->second.second); + } + + // character age + { + std::map >::iterator iterFind = ageStatistics.lower_bound(iterLfgData->second.characterAge); + if (iterFind != ageStatistics.end()) + ++(iterFind->second.second); + } + } + + // tabulate character create time statistics + { + std::map >::iterator iter = createTimeStatistics.begin(); + std::map >::iterator previousIter = createTimeStatistics.begin(); + + for (; iter != createTimeStatistics.end(); ++iter) + { + if (iter != previousIter) + iter->second.second += previousIter->second.second; + + previousIter = iter; + } + } + + // report character create time statistics + { + for (std::map >::const_iterator iterCreateTimeStatistics = createTimeStatistics.begin(); iterCreateTimeStatistics != createTimeStatistics.end(); ++iterCreateTimeStatistics) + { + std::map::iterator iterStatistics = statistics.find(iterCreateTimeStatistics->second.first); + if (iterStatistics != statistics.end()) + iterStatistics->second = iterCreateTimeStatistics->second.second; + } + } + + // tabulate character age statistics + { + std::map >::iterator iter = ageStatistics.begin(); + std::map >::iterator previousIter = ageStatistics.begin(); + + for (; iter != ageStatistics.end(); ++iter) + { + if (iter != previousIter) + iter->second.second += previousIter->second.second; + + previousIter = iter; + } + } + + // report character age statistics + { + for (std::map >::const_iterator iterAgeStatistics = ageStatistics.begin(); iterAgeStatistics != ageStatistics.end(); ++iterAgeStatistics) + { + std::map::iterator iterStatistics = statistics.find(iterAgeStatistics->second.first); + if (iterStatistics != statistics.end()) + iterStatistics->second = iterAgeStatistics->second.second; + } + } + + return statistics; +} + +// ====================================================================== + +LfgCharacterSearchResultData::LfgCharacterSearchResultData() : + characterId(), + characterName(), + species(SharedCreatureObjectTemplate::SP_human), + profession(LfgCharacterData::Prof_Unknown), + level(0), + faction(0), + guildName(), + guildAbbrev(), + groupId(), + locationPlanet(), + locationRegion(), + locationPlayerCity(), + ctsSourceGalaxy(), + characterInterests() +{ +} + +// ---------------------------------------------------------------------- + +LfgCharacterSearchResultData::LfgCharacterSearchResultData(const LfgCharacterData & lfgData) : + characterId(lfgData.characterId), + characterName(lfgData.characterName), + species(lfgData.species), + profession(lfgData.profession), + level(lfgData.level), + faction(lfgData.faction), + guildName(lfgData.guildName), + guildAbbrev(lfgData.guildAbbrev), + groupId(lfgData.groupId), + locationPlanet(lfgData.locationPlanet), + locationRegion(lfgData.locationRegion), + locationPlayerCity(lfgData.locationPlayerCity), + ctsSourceGalaxy(lfgData.ctsSourceGalaxy), + characterInterests(lfgData.characterInterests) +{ +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/LfgCharacterData.h b/engine/shared/library/sharedGame/src/shared/core/LfgCharacterData.h new file mode 100644 index 00000000..2357d177 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/LfgCharacterData.h @@ -0,0 +1,131 @@ +// ====================================================================== +// +// LfgCharacterData.h +// Copyright 2008 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#ifndef INCLUDED_LfgCharacterData_H +#define INCLUDED_LfgCharacterData_H + +#include "sharedFoundation/BitArray.h" +#include "sharedFoundation/NetworkId.h" +#include "sharedGame/SharedCreatureObjectTemplate.h" + +// ====================================================================== + +class LfgCharacterData +{ +public: + enum Profession + { + Prof_Unknown = 0, // Prof_Unknown must be first and start at 0, and subsequent ones increment by 1 + Prof_Bh, + Prof_Commando, + Prof_Entertainer, + Prof_Jedi, + Prof_Medic, + Prof_Officer, + Prof_Smuggler, + Prof_Spy, + Prof_Trader_Domestics, + Prof_Trader_Engineering, + Prof_Trader_Munitions, + Prof_Trader_Structures, + Prof_NPC, + Profession_MAX // must be last + }; + + enum Pilot + { + Pilot_None, + Pilot_Neutral, + Pilot_Imperial, + Pilot_Rebel, + }; + + LfgCharacterData(); + + bool operator== (const LfgCharacterData& rhs) const; + bool operator!= (const LfgCharacterData& rhs) const; + + static LfgCharacterData::Profession convertSkillTemplateToProfession(const std::string & skillTemplate); + static std::string getProfessionDebugString(LfgCharacterData::Profession profession); + static Unicode::String const & getProfessionDisplayString(LfgCharacterData::Profession profession); + static stdmap::fwd const & calculateStatistics(stdmap::fwd const & connectedCharacterLfgData); + + std::string getDebugString() const; + + NetworkId characterId; + int32 characterCreateTime; + int characterAge; + Unicode::String characterName; + std::string characterLowercaseFirstName; + SharedCreatureObjectTemplate::Species species; + SharedCreatureObjectTemplate::Gender gender; + LfgCharacterData::Profession profession; + LfgCharacterData::Pilot pilot; + int16 level; + uint32 faction; + std::string guildName; + std::string guildAbbrev; + std::string citizenOfCity; + NetworkId groupId; + std::string locationPlanet; + std::string locationRegion; + std::string locationFactionalPresenceGcwRegion; + int locationFactionalPresenceGridX; // only meaningful if locationFactionalPresenceGcwRegion is not empty and locationPlanet is a ground zone + int locationFactionalPresenceGridZ; // only meaningful if locationFactionalPresenceGcwRegion is not empty and locationPlanet is a ground zone + std::string locationPlayerCity; + std::set ctsSourceGalaxy; + bool searchableByCtsSourceGalaxy; + bool displayLocationInSearchResults; + bool anonymous; + bool active; + BitArray characterInterests; + uint32 sessionActivity; +}; + +// ====================================================================== + +// only return a subset of the LfgCharacterData in search results +class LfgCharacterSearchResultData +{ +public: + LfgCharacterSearchResultData(); + LfgCharacterSearchResultData(const LfgCharacterData & lfgData); + + NetworkId characterId; + Unicode::String characterName; + SharedCreatureObjectTemplate::Species species; + LfgCharacterData::Profession profession; + int16 level; + uint32 faction; + std::string guildName; + std::string guildAbbrev; + NetworkId groupId; + std::string locationPlanet; + std::string locationRegion; + std::string locationPlayerCity; + std::set ctsSourceGalaxy; + BitArray characterInterests; +}; + +// ====================================================================== + +namespace Archive +{ + class ReadIterator; + class ByteStream; + + void get(ReadIterator & source, LfgCharacterData & target); + void put(ByteStream & target, const LfgCharacterData & source); + + void get(ReadIterator & source, LfgCharacterSearchResultData & target); + void put(ByteStream & target, const LfgCharacterSearchResultData & source); +} + +// ====================================================================== + +#endif // INCLUDED_LfgCharacterData_H diff --git a/engine/shared/library/sharedGame/src/shared/core/LfgDataTable.cpp b/engine/shared/library/sharedGame/src/shared/core/LfgDataTable.cpp new file mode 100644 index 00000000..6acce604 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/LfgDataTable.cpp @@ -0,0 +1,921 @@ +// ====================================================================== +// +// LfgDataTable.cpp +// Copyright 2008 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/LfgDataTable.h" + +#include "sharedFoundation/BitArray.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedGame/LfgCharacterData.h" +#include "sharedGame/PvpData.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" + +#include +#include + +// ====================================================================== + +namespace LfgDataTableNamespace +{ + char const * const cs_lfgDataTableName = "datatables/lfg/lfg.iff"; + + std::vector s_topLevelNodes; + std::map s_allNodesByName; + std::map s_allLeafNodesByName; + + void getSetLfgNodeDebugString(LfgDataTable::LfgNode const & lfgNode, std::string & sOutput, std::string sIndention, std::set const & allParentNodesWithSetLeafDescendants, std::map > const & allSetLeafNodes, BitArray const & ba, bool displayAnyOrAllValue) + { + if (lfgNode.isLeafNode()) + { + std::map >::const_iterator iterFind = allSetLeafNodes.find(&lfgNode); + if (iterFind != allSetLeafNodes.end()) + { + sOutput += sIndention; + sOutput += lfgNode.name; + + if (lfgNode.minValue > 0) + { + char buffer[128]; + snprintf(buffer, sizeof(buffer)-1, " (%lu, %lu)", iterFind->second.first, iterFind->second.second); + buffer[sizeof(buffer)-1] = '\0'; + + sOutput += std::string(buffer); + } + + sOutput += "\n"; + } + } + else if (allParentNodesWithSetLeafDescendants.count(&lfgNode) > 0) + { + sOutput += sIndention; + sOutput += lfgNode.name; + + if (displayAnyOrAllValue) + { + if ((lfgNode.defaultMatchCondition == LfgDataTable::DMCT_Any) || (lfgNode.defaultMatchCondition == LfgDataTable::DMCT_All)) + { + if (LfgDataTable::testAnyOrAllBit(lfgNode, ba)) + sOutput += " (All)"; + else + sOutput += " (Any)"; + } + } + + sOutput += "\n"; + + sIndention += " "; + for (std::vector::const_iterator iterNode = lfgNode.children.begin(); iterNode != lfgNode.children.end(); ++iterNode) + { + getSetLfgNodeDebugString(**iterNode, sOutput, sIndention, allParentNodesWithSetLeafDescendants, allSetLeafNodes, ba, displayAnyOrAllValue); + } + } + } + + bool matchFactionImperial(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return PvpData::isImperialFactionId(lfgCharacterData.faction); + } + + bool matchFactionNeutral(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return PvpData::isNeutralFactionId(lfgCharacterData.faction); + } + + bool matchFactionRebel(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return PvpData::isRebelFactionId(lfgCharacterData.faction); + } + + bool matchGenderFemale(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.gender == SharedCreatureObjectTemplate::GE_female); + } + + bool matchGenderMale(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.gender == SharedCreatureObjectTemplate::GE_male); + } + + bool matchLevel(LfgCharacterData const & lfgCharacterData, void const * lowLevel, void const * highLevel, void const *, void const *, void const *) + { + return ((static_cast(lfgCharacterData.level) >= reinterpret_cast(lowLevel)) && (static_cast(lfgCharacterData.level) <= reinterpret_cast(highLevel))); + } + + bool matchFriend(LfgCharacterData const & lfgCharacterData, void const * pFriendList, void const *, void const *, void const *, void const *) + { + // pFriendList points to the lowercase, sorted friend list + if (!pFriendList) + return false; + + std::vector const & friendList = *(reinterpret_cast const *>(pFriendList)); + + return std::binary_search(friendList.begin(), friendList.end(), lfgCharacterData.characterLowercaseFirstName); + } + + bool matchCommonCtsSourceGalaxy(LfgCharacterData const & lfgCharacterData, void const * pCtsSourceGalaxy, void const * pMatchingCtsSourceGalaxy, void const *, void const *, void const *) + { + // pCtsSourceGalaxy points to the list of CTS source galaxies + if (lfgCharacterData.ctsSourceGalaxy.empty() || !lfgCharacterData.searchableByCtsSourceGalaxy || !pCtsSourceGalaxy) + return false; + + std::set const & ctsSourceGalaxy = *(reinterpret_cast const *>(pCtsSourceGalaxy)); + if (ctsSourceGalaxy.empty()) + return false; + + // pMatchingCtsSourceGalaxy, if specified, points to a std::vector that will be populated with the matching CTS source galaxies + static std::vector sMatchingCtsSourceGalaxy; + std::vector * matchingCtsSourceGalaxy = &sMatchingCtsSourceGalaxy; + if (pMatchingCtsSourceGalaxy) + matchingCtsSourceGalaxy = reinterpret_cast *>(const_cast(pMatchingCtsSourceGalaxy)); + + matchingCtsSourceGalaxy->clear(); + IGNORE_RETURN(std::set_intersection(lfgCharacterData.ctsSourceGalaxy.begin(), lfgCharacterData.ctsSourceGalaxy.end(), ctsSourceGalaxy.begin(), ctsSourceGalaxy.end(), std::back_inserter(*matchingCtsSourceGalaxy))); + return (!matchingCtsSourceGalaxy->empty()); + } + + bool matchInSameGuild(LfgCharacterData const & lfgCharacterData, void const * pSearcherGuildAbbrev, void const *, void const *, void const *, void const *) + { + // pSearcherGuildAbbrev points to the guild that the searcher is in + if (lfgCharacterData.guildAbbrev.empty() || !pSearcherGuildAbbrev) + return false; + + std::string const & searcherGuildAbbrev = *(reinterpret_cast(pSearcherGuildAbbrev)); + if (searcherGuildAbbrev.empty()) + return false; + + return (searcherGuildAbbrev == lfgCharacterData.guildAbbrev); + } + + bool matchCitizenOfSameCity(LfgCharacterData const & lfgCharacterData, void const * pSearcherCitizenOfCity, void const *, void const *, void const *, void const *) + { + // pSearcherCitizenOfCity points to the city that the searcher is a citizen of + if (lfgCharacterData.citizenOfCity.empty() || !pSearcherCitizenOfCity) + return false; + + std::string const & searcherCitizenOfCity = *(reinterpret_cast(pSearcherCitizenOfCity)); + if (searcherCitizenOfCity.empty()) + return false; + + return (searcherCitizenOfCity == lfgCharacterData.citizenOfCity); + } + + bool matchPilotNeutral(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.pilot == LfgCharacterData::Pilot_Neutral); + } + + bool matchPilotImperial(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.pilot == LfgCharacterData::Pilot_Imperial); + } + + bool matchPilotRebel(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.pilot == LfgCharacterData::Pilot_Rebel); + } + + bool matchProfBh(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.profession == LfgCharacterData::Prof_Bh); + } + + bool matchProfCommando(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.profession == LfgCharacterData::Prof_Commando); + } + + bool matchProfEntertainer(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.profession == LfgCharacterData::Prof_Entertainer); + } + + bool matchProfJedi(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.profession == LfgCharacterData::Prof_Jedi); + } + + bool matchProfMedic(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.profession == LfgCharacterData::Prof_Medic); + } + + bool matchProfOfficer(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.profession == LfgCharacterData::Prof_Officer); + } + + bool matchProfSmuggler(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.profession == LfgCharacterData::Prof_Smuggler); + } + + bool matchProfSpy(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.profession == LfgCharacterData::Prof_Spy); + } + + bool matchProfTraderDomestics(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.profession == LfgCharacterData::Prof_Trader_Domestics); + } + + bool matchProfTraderEngineering(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.profession == LfgCharacterData::Prof_Trader_Engineering); + } + + bool matchProfTraderMunitions(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.profession == LfgCharacterData::Prof_Trader_Munitions); + } + + bool matchProfTraderStructures(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.profession == LfgCharacterData::Prof_Trader_Structures); + } + + bool matchSpeciesBothan(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.species == SharedCreatureObjectTemplate::SP_bothan); + } + + bool matchSpeciesHuman(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.species == SharedCreatureObjectTemplate::SP_human); + } + + bool matchSpeciesIthorian(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.species == SharedCreatureObjectTemplate::SP_ithorian); + } + + bool matchSpeciesMonCalamari(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.species == SharedCreatureObjectTemplate::SP_monCalamari); + } + + bool matchSpeciesRodian(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.species == SharedCreatureObjectTemplate::SP_rodian); + } + + bool matchSpeciesSullustan(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.species == SharedCreatureObjectTemplate::SP_sullustan); + } + + bool matchSpeciesTrandoshan(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.species == SharedCreatureObjectTemplate::SP_trandoshan); + } + + bool matchSpeciesTwilek(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.species == SharedCreatureObjectTemplate::SP_twilek); + } + + bool matchSpeciesWookiee(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.species == SharedCreatureObjectTemplate::SP_wookiee); + } + + bool matchSpeciesZabrak(LfgCharacterData const & lfgCharacterData, void const *, void const *, void const *, void const *, void const *) + { + return (lfgCharacterData.species == SharedCreatureObjectTemplate::SP_zabrak); + } +} + +using namespace LfgDataTableNamespace; + +// ====================================================================== + +void LfgDataTable::install() +{ + // set up the table containing the "match" function for every + // "internal" attribute defined in the lfg datatable + std::map mapInternalSearchAttributeMatchFunction; + + mapInternalSearchAttributeMatchFunction["imperial"] = matchFactionImperial; + mapInternalSearchAttributeMatchFunction["neutral"] = matchFactionNeutral; + mapInternalSearchAttributeMatchFunction["rebel"] = matchFactionRebel; + mapInternalSearchAttributeMatchFunction["female"] = matchGenderFemale; + mapInternalSearchAttributeMatchFunction["male"] = matchGenderMale; + mapInternalSearchAttributeMatchFunction["level"] = matchLevel; + mapInternalSearchAttributeMatchFunction["friend"] = matchFriend; + mapInternalSearchAttributeMatchFunction["cts_source_galaxy"] = matchCommonCtsSourceGalaxy; + mapInternalSearchAttributeMatchFunction["in_same_guild"] = matchInSameGuild; + mapInternalSearchAttributeMatchFunction["citizen_of_same_city"] = matchCitizenOfSameCity; + mapInternalSearchAttributeMatchFunction["pilot_neutral"] = matchPilotNeutral; + mapInternalSearchAttributeMatchFunction["pilot_imperial"] = matchPilotImperial; + mapInternalSearchAttributeMatchFunction["pilot_rebel"] = matchPilotRebel; + mapInternalSearchAttributeMatchFunction["prof_bh"] = matchProfBh; + mapInternalSearchAttributeMatchFunction["prof_commando"] = matchProfCommando; + mapInternalSearchAttributeMatchFunction["prof_entertainer"] = matchProfEntertainer; + mapInternalSearchAttributeMatchFunction["prof_jedi"] = matchProfJedi; + mapInternalSearchAttributeMatchFunction["prof_medic"] = matchProfMedic; + mapInternalSearchAttributeMatchFunction["prof_officer"] = matchProfOfficer; + mapInternalSearchAttributeMatchFunction["prof_smuggler"] = matchProfSmuggler; + mapInternalSearchAttributeMatchFunction["prof_spy"] = matchProfSpy; + mapInternalSearchAttributeMatchFunction["prof_trader_domestics"] = matchProfTraderDomestics; + mapInternalSearchAttributeMatchFunction["prof_trader_engineering"] = matchProfTraderEngineering; + mapInternalSearchAttributeMatchFunction["prof_trader_munitions"] = matchProfTraderMunitions; + mapInternalSearchAttributeMatchFunction["prof_trader_structures"] = matchProfTraderStructures; + mapInternalSearchAttributeMatchFunction["bothan"] = matchSpeciesBothan; + mapInternalSearchAttributeMatchFunction["human"] = matchSpeciesHuman; + mapInternalSearchAttributeMatchFunction["ithorian"] = matchSpeciesIthorian; + mapInternalSearchAttributeMatchFunction["mon_calamari"] = matchSpeciesMonCalamari; + mapInternalSearchAttributeMatchFunction["rodian"] = matchSpeciesRodian; + mapInternalSearchAttributeMatchFunction["sullustan"] = matchSpeciesSullustan; + mapInternalSearchAttributeMatchFunction["trandoshan"] = matchSpeciesTrandoshan; + mapInternalSearchAttributeMatchFunction["twilek"] = matchSpeciesTwilek; + mapInternalSearchAttributeMatchFunction["wookiee"] = matchSpeciesWookiee; + mapInternalSearchAttributeMatchFunction["zabrak"] = matchSpeciesZabrak; + + DataTable * table = DataTableManager::getTable(cs_lfgDataTableName, true); + if (table) + { + int const columnTier1 = table->findColumnNumber("tier1"); + int const columnTier2 = table->findColumnNumber("tier2"); + int const columnTier3 = table->findColumnNumber("tier3"); + int const columnTier4 = table->findColumnNumber("tier4"); + int const columnInternalAttribute = table->findColumnNumber("internalAttribute"); + int const columnMinValueBeginSlotId = table->findColumnNumber("minValueBeginSlotId"); + int const columnMinValueEndSlotId = table->findColumnNumber("minValueEndSlotId"); + int const columnMaxValueBeginSlotId = table->findColumnNumber("maxValueBeginSlotId"); + int const columnMaxValueEndSlotId = table->findColumnNumber("maxValueEndSlotId"); + int const columnMinValue = table->findColumnNumber("minValue"); + int const columnMaxValue = table->findColumnNumber("maxValue"); + int const columnDefaultMatchCondition = table->findColumnNumber("defaultMatchCondition"); + + FATAL((columnTier1 < 0), ("column \"tier1\" not found in %s", cs_lfgDataTableName)); + FATAL((columnTier2 < 0), ("column \"tier2\" not found in %s", cs_lfgDataTableName)); + FATAL((columnTier3 < 0), ("column \"tier3\" not found in %s", cs_lfgDataTableName)); + FATAL((columnTier4 < 0), ("column \"tier4\" not found in %s", cs_lfgDataTableName)); + FATAL((columnInternalAttribute < 0), ("column \"internalAttribute\" not found in %s", cs_lfgDataTableName)); + FATAL((columnMinValueBeginSlotId < 0), ("column \"minValueBeginSlotId\" not found in %s", cs_lfgDataTableName)); + FATAL((columnMinValueEndSlotId < 0), ("column \"minValueEndSlotId\" not found in %s", cs_lfgDataTableName)); + FATAL((columnMaxValueBeginSlotId < 0), ("column \"maxValueBeginSlotId\" not found in %s", cs_lfgDataTableName)); + FATAL((columnMaxValueEndSlotId < 0), ("column \"maxValueEndSlotId\" not found in %s", cs_lfgDataTableName)); + FATAL((columnMinValue < 0), ("column \"minValue\" not found in %s", cs_lfgDataTableName)); + FATAL((columnMaxValue < 0), ("column \"maxValue\" not found in %s", cs_lfgDataTableName)); + FATAL((columnDefaultMatchCondition < 0), ("column \"defaultMatchCondition\" not found in %s", cs_lfgDataTableName)); + + int const numRows = table->getNumRows(); + + // datatable values + std::string tier1, tier2, tier3, tier4; + bool internalAttribute; + int minValueBeginSlotId, minValueEndSlotId, maxValueBeginSlotId, maxValueEndSlotId, minValue, maxValue; + DefaultMatchConditionType defaultMatchCondition; + + // temps + int tempCount; + unsigned long maxValueForNumBits; + std::map names; + std::map allSlotsById; + LfgNode * lfgNode = NULL; + LfgNode * currentTier1Node = NULL; + LfgNode * currentTier2Node = NULL; + LfgNode * currentTier3Node = NULL; + + for (int i = 0; i < numRows; ++i) + { + tier1 = table->getStringValue(columnTier1, i); + tier2 = table->getStringValue(columnTier2, i); + tier3 = table->getStringValue(columnTier3, i); + tier4 = table->getStringValue(columnTier4, i); + + if (tier1.empty() && tier2.empty() && tier3.empty() && tier4.empty()) + continue; + + // only one of tier1, tier2, tier3, or tier4 can be specified + // and tier1, tier2, tier3, and tier4 must be unique + tempCount = 0; + if (!tier1.empty()) + { + FATAL((names.count(tier1) >= 1), ("%s, row %d: tier1 name %s already used at row %d (either as a tier1, tier2, tier3, or tier4 name)", cs_lfgDataTableName, (i+3), tier1.c_str(), names[tier1])); + names[tier1] = (i+3); + ++tempCount; + } + if (!tier2.empty()) + { + FATAL((names.count(tier2) >= 1), ("%s, row %d: tier2 name %s already used at row %d (either as a tier1, tier2, tier3, or tier4 name)", cs_lfgDataTableName, (i+3), tier2.c_str(), names[tier2])); + names[tier2] = (i+3); + ++tempCount; + } + if (!tier3.empty()) + { + FATAL((names.count(tier3) >= 1), ("%s, row %d: tier3 name %s already used at row %d (either as a tier1, tier2, tier3, or tier4 name)", cs_lfgDataTableName, (i+3), tier3.c_str(), names[tier3])); + names[tier3] = (i+3); + ++tempCount; + } + if (!tier4.empty()) + { + FATAL((names.count(tier4) >= 1), ("%s, row %d: tier4 name %s already used at row %d (either as a tier1, tier2, tier3, or tier4 name)", cs_lfgDataTableName, (i+3), tier4.c_str(), names[tier4])); + names[tier4] = (i+3); + ++tempCount; + } + + FATAL((tempCount != 1), ("%s, row %d: only one of tier1, tier2, tier3, or tier4 can be specified", cs_lfgDataTableName, (i+3))); + + internalAttribute = (table->getIntValue(columnInternalAttribute, i) != 0); + minValueBeginSlotId = table->getIntValue(columnMinValueBeginSlotId, i); + minValueEndSlotId = table->getIntValue(columnMinValueEndSlotId, i); + maxValueBeginSlotId = table->getIntValue(columnMaxValueBeginSlotId, i); + maxValueEndSlotId = table->getIntValue(columnMaxValueEndSlotId, i); + minValue = table->getIntValue(columnMinValue, i); + maxValue = table->getIntValue(columnMaxValue, i); + defaultMatchCondition = static_cast(table->getIntValue(columnDefaultMatchCondition, i)); + + // verify min/max value + FATAL(((minValue != -1) && (minValue <= 0)), ("%s, row %d: minValue must be > 0", cs_lfgDataTableName, (i+3))); + FATAL(((maxValue != -1) && (maxValue <= 0)), ("%s, row %d: maxValue must be > 0", cs_lfgDataTableName, (i+3))); + FATAL(((minValue > 0) && (maxValue <= 0)), ("%s, row %d: maxValue must be specified if minValue is specified", cs_lfgDataTableName, (i+3))); + FATAL(((maxValue > 0) && (minValue <= 0)), ("%s, row %d: minValue must be specified if maxValue is specified", cs_lfgDataTableName, (i+3))); + FATAL(((maxValue > 0) && (maxValue <= minValue)), ("%s, row %d: maxValue must be > minValue", cs_lfgDataTableName, (i+3))); + + // verify slot ids + FATAL(((minValueBeginSlotId != -1) && (minValueBeginSlotId < 0)), ("%s, row %d: minValueBeginSlotId must be >= 0", cs_lfgDataTableName, (i+3))); + FATAL(((minValueEndSlotId != -1) && (minValueEndSlotId < 0)), ("%s, row %d: minValueEndSlotId must be >= 0", cs_lfgDataTableName, (i+3))); + FATAL(((maxValueBeginSlotId != -1) && (maxValueBeginSlotId < 0)), ("%s, row %d: maxValueBeginSlotId must be >= 0", cs_lfgDataTableName, (i+3))); + FATAL(((maxValueEndSlotId != -1) && (maxValueEndSlotId < 0)), ("%s, row %d: maxValueEndSlotId must be >= 0", cs_lfgDataTableName, (i+3))); + + FATAL(((minValueEndSlotId >= 0) && (minValueBeginSlotId < 0)), ("%s, row %d: minValueBeginSlotId must be specified if minValueEndSlotId is specified", cs_lfgDataTableName, (i+3))); + FATAL(((minValueEndSlotId >= 0) && (minValueEndSlotId <= minValueBeginSlotId)), ("%s, row %d: minValueEndSlotId must be > minValueBeginSlotId", cs_lfgDataTableName, (i+3))); + + FATAL(((maxValueBeginSlotId >= 0) && (maxValueEndSlotId < 0)), ("%s, row %d: maxValueEndSlotId must be specified if maxValueBeginSlotId is specified", cs_lfgDataTableName, (i+3))); + FATAL(((maxValueEndSlotId >= 0) && (maxValueBeginSlotId < 0)), ("%s, row %d: maxValueBeginSlotId must be specified if maxValueEndSlotId is specified", cs_lfgDataTableName, (i+3))); + FATAL(((maxValueEndSlotId >= 0) && (maxValueEndSlotId <= maxValueBeginSlotId)), ("%s, row %d: maxValueEndSlotId must be > maxValueBeginSlotId", cs_lfgDataTableName, (i+3))); + + FATAL(((maxValueBeginSlotId >= 0) && (minValueEndSlotId < 0)), ("%s, row %d: minValueBeginSlotId/minValueEndSlotId must be specified if maxValueBeginSlotId/maxValueEndSlotId is specified", cs_lfgDataTableName, (i+3))); + FATAL(((minValueEndSlotId >= 0) && (maxValueBeginSlotId < 0)), ("%s, row %d: maxValueBeginSlotId/maxValueEndSlotId must be specified if minValueBeginSlotId/minValueEndSlotId is specified", cs_lfgDataTableName, (i+3))); + + if (maxValueBeginSlotId >= 0) + { + FATAL(((minValueEndSlotId - minValueBeginSlotId) > 31), ("%s, row %d: minValueBeginSlotId/minValueEndSlotId cannot exceed 32 bits", cs_lfgDataTableName, (i+3))); + FATAL(((maxValueEndSlotId - maxValueBeginSlotId) > 31), ("%s, row %d: maxValueBeginSlotId/maxValueEndSlotId cannot exceed 32 bits", cs_lfgDataTableName, (i+3))); + FATAL(((maxValueEndSlotId - maxValueBeginSlotId) != (minValueEndSlotId - minValueBeginSlotId)), ("%s, row %d: maxValueBeginSlotId/maxValueEndSlotId must use the same number of slots as minValueBeginSlotId/minValueEndSlotId", cs_lfgDataTableName, (i+3))); + FATAL((minValue <= 0), ("%s, row %d: minValue/maxValue must be specified if minValueBeginSlotId/minValueEndSlotId/maxValueBeginSlotId/maxValueEndSlotId is specified", cs_lfgDataTableName, (i+3))); + FATAL((!internalAttribute), ("%s, row %d: internalAttribute must be true if minValueBeginSlotId/minValueEndSlotId/maxValueBeginSlotId/maxValueEndSlotId is specified", cs_lfgDataTableName, (i+3))); + + unsigned long const numBits = static_cast(maxValueEndSlotId - maxValueBeginSlotId + 1); + maxValueForNumBits = (0xffffffff >> (32 - numBits)); + FATAL((maxValueForNumBits < static_cast(maxValue)), ("%s, row %d: minValueBeginSlotId/minValueEndSlotId uses %lu bits, which can only hold a max value of %lu, which is less than the specified max value of %d", cs_lfgDataTableName, (i+3), numBits, maxValueForNumBits, maxValue)); + } + + FATAL(((minValue > 0) && (maxValueBeginSlotId < 0)), ("%s, row %d: minValueBeginSlotId/minValueEndSlotId/maxValueBeginSlotId/maxValueEndSlotId must be specified if minValue/maxValue is specified", cs_lfgDataTableName, (i+3))); + + // create a new node + lfgNode = NULL; + if (!tier1.empty()) + { + lfgNode = new LfgNode(tier1, internalAttribute, minValueBeginSlotId, minValueEndSlotId, maxValueBeginSlotId, maxValueEndSlotId, minValue, maxValue, defaultMatchCondition, NULL); + s_topLevelNodes.push_back(lfgNode); + + currentTier1Node = lfgNode; + currentTier2Node = NULL; + currentTier3Node = NULL; + } + else if (!tier2.empty()) + { + FATAL((!currentTier1Node), ("%s, row %d: tier2 %s specified without a parent tier1", cs_lfgDataTableName, (i+3), tier2.c_str())); + + lfgNode = new LfgNode(tier2, internalAttribute, minValueBeginSlotId, minValueEndSlotId, maxValueBeginSlotId, maxValueEndSlotId, minValue, maxValue, defaultMatchCondition, currentTier1Node); + currentTier1Node->children.push_back(lfgNode); + + currentTier2Node = lfgNode; + currentTier3Node = NULL; + } + else if (!tier3.empty()) + { + FATAL((!currentTier2Node), ("%s, row %d: tier3 %s specified without a parent tier2", cs_lfgDataTableName, (i+3), tier3.c_str())); + + lfgNode = new LfgNode(tier3, internalAttribute, minValueBeginSlotId, minValueEndSlotId, maxValueBeginSlotId, maxValueEndSlotId, minValue, maxValue, defaultMatchCondition, currentTier2Node); + currentTier2Node->children.push_back(lfgNode); + + currentTier3Node = lfgNode; + } + else + { + FATAL((!currentTier3Node), ("%s, row %d: tier4 %s specified without a parent tier3", cs_lfgDataTableName, (i+3), tier4.c_str())); + + lfgNode = new LfgNode(tier4, internalAttribute, minValueBeginSlotId, minValueEndSlotId, maxValueBeginSlotId, maxValueEndSlotId, minValue, maxValue, defaultMatchCondition, currentTier3Node); + currentTier3Node->children.push_back(lfgNode); + } + + s_allNodesByName[lfgNode->name] = lfgNode; + + // verify slot ids are not reused + if (minValueBeginSlotId >= 0) + { + if (minValueEndSlotId >= 0) + { + int j; + for (j = minValueBeginSlotId; j <= minValueEndSlotId; ++j) + { + FATAL((allSlotsById.count(j) >= 1), ("%s, row %d: slot id %d already used by node %s", cs_lfgDataTableName, (i+3), j, allSlotsById[j]->name.c_str())); + allSlotsById[j] = lfgNode; + } + + for (j = maxValueBeginSlotId; j <= maxValueEndSlotId; ++j) + { + FATAL((allSlotsById.count(j) >= 1), ("%s, row %d: slot id %d already used by node %s", cs_lfgDataTableName, (i+3), j, allSlotsById[j]->name.c_str())); + allSlotsById[j] = lfgNode; + } + } + else + { + FATAL((allSlotsById.count(minValueBeginSlotId) >= 1), ("%s, row %d: slot id %d already used by node %s", cs_lfgDataTableName, (i+3), minValueBeginSlotId, allSlotsById[minValueBeginSlotId]->name.c_str())); + allSlotsById[minValueBeginSlotId] = lfgNode; + } + } + } + + // make sure that slot ids start at 0 and there are no "holes" in the slot ids + int firstSlotId = -1; + for (std::map::const_iterator iterSlotId = allSlotsById.begin(); iterSlotId != allSlotsById.end(); ++iterSlotId) + { + if (iterSlotId == allSlotsById.begin()) + { + FATAL((iterSlotId->first != 0), ("%s: slot id assignment must start at 0", cs_lfgDataTableName)); + } + else + { + FATAL(((firstSlotId + 1) != iterSlotId->first), ("%s: slot id assignment must be contiguous (there is a \"hole\" between %d and %d)", cs_lfgDataTableName, firstSlotId, iterSlotId->first)); + } + + firstSlotId = iterSlotId->first; + } + + // check each node to make sure they don't violate any "rules" + for (std::map::const_iterator iterNode = s_allNodesByName.begin(); iterNode != s_allNodesByName.end(); ++iterNode) + { + LfgNode const & node = *(iterNode->second); + + FATAL((node.name != iterNode->first), ("%s: node name mismatch (%s, %s)", node.name.c_str(), iterNode->first.c_str())); + + if (node.isLeafNode()) + { + FATAL((node.defaultMatchCondition != DMCT_NA), ("%s: node %s is a leaf node and must have defaultMatchCondition value of NA", cs_lfgDataTableName, node.name.c_str())); + FATAL((node.minValueBeginSlotId < 0), ("%s: node %s is a leaf node and must be assigned to a slot id for minValueBeginSlotId", cs_lfgDataTableName, node.name.c_str())); + + s_allLeafNodesByName[iterNode->first] = iterNode->second; + + // if the leaf node is an "internal" attribute, set the "matching" + // function that can be used to determine if the character data + // "matches" the "internal" attribute + if (node.internalAttribute) + { + std::map::const_iterator iterMatchFunction = mapInternalSearchAttributeMatchFunction.find(node.name); + FATAL((iterMatchFunction == mapInternalSearchAttributeMatchFunction.end()), ("%s: node %s is an \"internal\" attribute but doesn't have a corresponding \"match\" function defined", cs_lfgDataTableName, node.name.c_str())); + + const_cast(node).internalAttributeMatchFunction = iterMatchFunction->second; + } + + // find out the leaf node's ancestor, if any, that has the Any/All option + LfgNode const * parentNode = node.parent; + bool const hasParent = (parentNode != NULL); + int countParentWithNonNaDefaultMatchCondition = 0; + std::string stringParentWithNonNaDefaultMatchCondition; + while (parentNode) + { + if (node.internalAttribute) + const_cast(parentNode)->hasAnyInternalAttributeLeafNodeDescendants = true; + else + const_cast(parentNode)->hasAnyExternalAttributeLeafNodeDescendants = true; + + if (parentNode->defaultMatchCondition != DMCT_NA) + { + const_cast(node).anyAllGroupingParent = parentNode; + + ++countParentWithNonNaDefaultMatchCondition; + + if (!stringParentWithNonNaDefaultMatchCondition.empty()) + stringParentWithNonNaDefaultMatchCondition += ", "; + + stringParentWithNonNaDefaultMatchCondition += parentNode->name; + } + + parentNode = parentNode->parent; + } + + if (hasParent) + { + FATAL((countParentWithNonNaDefaultMatchCondition > 1), ("%s: node %s is a leaf node and cannot have more than 1 ancestor nodes with a non-NA defaultMatchCondition (currently has %d ancestor nodes (%s) with a non-NA defaultMatchCondition)", cs_lfgDataTableName, node.name.c_str(), countParentWithNonNaDefaultMatchCondition, stringParentWithNonNaDefaultMatchCondition.c_str())); + } + } + else + { + FATAL((node.internalAttribute), ("%s: node %s is a non-leaf node and cannot have a true value for internalAttribute", cs_lfgDataTableName, node.name.c_str())); + FATAL((node.minValueEndSlotId >= 0), ("%s: node %s is a non-leaf node and cannot have a value for minValueEndSlotId", cs_lfgDataTableName, node.name.c_str())); + FATAL((node.maxValueBeginSlotId >= 0), ("%s: node %s is a non-leaf node and cannot have a value for maxValueBeginSlotId", cs_lfgDataTableName, node.name.c_str())); + FATAL((node.maxValueEndSlotId >= 0), ("%s: node %s is a non-leaf node and cannot have a value for maxValueEndSlotId", cs_lfgDataTableName, node.name.c_str())); + FATAL((node.minValue > 0), ("%s: node %s is a non-leaf node and cannot have a value for minValue", cs_lfgDataTableName, node.name.c_str())); + FATAL((node.maxValue > 0), ("%s: node %s is a non-leaf node and cannot have a value for maxValue", cs_lfgDataTableName, node.name.c_str())); + + if ((node.defaultMatchCondition == DMCT_Any) || (node.defaultMatchCondition == DMCT_All)) + { + FATAL((node.minValueBeginSlotId < 0), ("%s: node %s has a defaultMatchCondition of Any/All so must be assigned to a slot id for minValueBeginSlotId", cs_lfgDataTableName, node.name.c_str())); + } + else + { + FATAL((node.minValueBeginSlotId >= 0), ("%s: node %s doesn't have a defaultMatchCondition of Any/All so cannot have a value for minValueBeginSlotId", cs_lfgDataTableName, node.name.c_str())); + } + } + } + } + else + { + FATAL(true, ("lfg datatable %s not found", cs_lfgDataTableName)); + } + + ExitChain::add(remove, "LfgDataTable::remove"); +} + +//---------------------------------------------------------------------- + +void LfgDataTable::remove() +{ + for (std::map::const_iterator iterNode = s_allNodesByName.begin(); iterNode != s_allNodesByName.end(); ++iterNode) + delete iterNode->second; + + s_topLevelNodes.clear(); + s_allNodesByName.clear(); + s_allLeafNodesByName.clear(); +} + +//---------------------------------------------------------------------- + +std::vector const & LfgDataTable::getTopLevelLfgNodes() +{ + return s_topLevelNodes; +} + +//---------------------------------------------------------------------- + +std::map const & LfgDataTable::getAllLfgLeafNodes() +{ + return s_allLeafNodesByName; +} + +//---------------------------------------------------------------------- + +LfgDataTable::LfgNode const * LfgDataTable::getLfgNodeByName(std::string const & lfgNodeName) +{ + std::map::const_iterator iterNode = s_allNodesByName.find(lfgNodeName); + if (iterNode == s_allNodesByName.end()) + return NULL; + + return iterNode->second; +} + +//---------------------------------------------------------------------- + +LfgDataTable::LfgNode const * LfgDataTable::getLfgLeafNodeByName(std::string const & lfgNodeName) +{ + std::map::const_iterator iterNode = s_allLeafNodesByName.find(lfgNodeName); + if (iterNode == s_allLeafNodesByName.end()) + return NULL; + + return iterNode->second; +} + +//---------------------------------------------------------------------- + +void LfgDataTable::setBit(std::string const & lfgNodeName, BitArray & ba) +{ + LfgNode const * lfgNode = getLfgNodeByName(lfgNodeName); + if (lfgNode) + setBit(*lfgNode, ba); +} + +//---------------------------------------------------------------------- + +void LfgDataTable::setBit(LfgNode const & lfgNode, BitArray & ba) +{ + if (lfgNode.isLeafNode() && (lfgNode.minValueBeginSlotId >= 0) && (lfgNode.minValueEndSlotId < 0)) + ba.setBit(lfgNode.minValueBeginSlotId); +} + +//---------------------------------------------------------------------- + +void LfgDataTable::clearBit(std::string const & lfgNodeName, BitArray & ba) +{ + LfgNode const * lfgNode = getLfgNodeByName(lfgNodeName); + if (lfgNode) + clearBit(*lfgNode, ba); +} + +//---------------------------------------------------------------------- + +void LfgDataTable::clearBit(LfgNode const & lfgNode, BitArray & ba) +{ + if (lfgNode.isLeafNode() && (lfgNode.minValueBeginSlotId >= 0) && (lfgNode.minValueEndSlotId < 0)) + ba.clearBit(lfgNode.minValueBeginSlotId); +} + +//---------------------------------------------------------------------- + +bool LfgDataTable::testBit(std::string const & lfgNodeName, BitArray const & ba) +{ + LfgNode const * lfgNode = getLfgNodeByName(lfgNodeName); + if (lfgNode) + return testBit(*lfgNode, ba); + + return false; +} + +//---------------------------------------------------------------------- + +bool LfgDataTable::testBit(LfgNode const & lfgNode, BitArray const & ba) +{ + if (lfgNode.isLeafNode() && (lfgNode.minValueBeginSlotId >= 0) && (lfgNode.minValueEndSlotId < 0)) + return ba.testBit(lfgNode.minValueBeginSlotId); + + return false; +} + +//---------------------------------------------------------------------- + +void LfgDataTable::setAnyOrAllBit(std::string const & lfgNodeName, bool any, BitArray & ba) +{ + // any -> clear bit + // all -> set bit + LfgNode const * lfgNode = getLfgNodeByName(lfgNodeName); + if (lfgNode) + setAnyOrAllBit(*lfgNode, any, ba); +} + +//---------------------------------------------------------------------- + +void LfgDataTable::setAnyOrAllBit(LfgNode const & lfgNode, bool any, BitArray & ba) +{ + // any -> clear bit + // all -> set bit + if (!lfgNode.isLeafNode() && ((lfgNode.defaultMatchCondition == LfgDataTable::DMCT_Any) || (lfgNode.defaultMatchCondition == LfgDataTable::DMCT_All)) && (lfgNode.minValueBeginSlotId >= 0) && (lfgNode.minValueEndSlotId < 0)) + { + if (any) + ba.clearBit(lfgNode.minValueBeginSlotId); + else + ba.setBit(lfgNode.minValueBeginSlotId); + } +} + +//---------------------------------------------------------------------- + +bool LfgDataTable::testAnyOrAllBit(std::string const & lfgNodeName, BitArray const & ba) +{ + // all -> bit is set (returns true) + // any -> bit is not set (returns false) + LfgNode const * lfgNode = getLfgNodeByName(lfgNodeName); + if (lfgNode) + return testAnyOrAllBit(*lfgNode, ba); + + return false; +} + +//---------------------------------------------------------------------- + +bool LfgDataTable::testAnyOrAllBit(LfgNode const & lfgNode, BitArray const & ba) +{ + // all -> bit is set (returns true) + // any -> bit is not set (returns false) + if (!lfgNode.isLeafNode() && ((lfgNode.defaultMatchCondition == LfgDataTable::DMCT_Any) || (lfgNode.defaultMatchCondition == LfgDataTable::DMCT_All)) && (lfgNode.minValueBeginSlotId >= 0) && (lfgNode.minValueEndSlotId < 0)) + return ba.testBit(lfgNode.minValueBeginSlotId); + + return false; +} + +//---------------------------------------------------------------------- + +void LfgDataTable::setLowHighValue(std::string const & lfgNodeName, unsigned long lowValue, unsigned long highValue, BitArray & ba) +{ + LfgNode const * lfgNode = getLfgNodeByName(lfgNodeName); + if (lfgNode) + setLowHighValue(*lfgNode, lowValue, highValue, ba); +} + +//---------------------------------------------------------------------- + +void LfgDataTable::setLowHighValue(LfgNode const & lfgNode, unsigned long lowValue, unsigned long highValue, BitArray & ba) +{ + if ((lfgNode.isLeafNode()) && + (lfgNode.minValueBeginSlotId >= 0) && + (lfgNode.minValueEndSlotId >= 0) && + (lfgNode.minValueBeginSlotId < lfgNode.minValueEndSlotId) && + (lfgNode.maxValueBeginSlotId >= 0) && + (lfgNode.maxValueEndSlotId >= 0) && + (lfgNode.maxValueBeginSlotId < lfgNode.maxValueEndSlotId) && + (lfgNode.minValue > 0) && + (lfgNode.maxValue > 0) && + (lfgNode.minValue < lfgNode.maxValue) && + (lowValue <= highValue) + ) + { + // lowValue and highValue of 0 means "clear" + if ((lowValue == 0) && (highValue == 0)) + { + ba.setValue(lfgNode.minValueBeginSlotId, lfgNode.minValueEndSlotId, 0lu); + ba.setValue(lfgNode.maxValueBeginSlotId, lfgNode.maxValueEndSlotId, 0lu); + } + else if ((lowValue >= static_cast(lfgNode.minValue)) && + (lowValue <= static_cast(lfgNode.maxValue)) && + (highValue >= static_cast(lfgNode.minValue)) && + (highValue <= static_cast(lfgNode.maxValue)) + ) + { + ba.setValue(lfgNode.minValueBeginSlotId, lfgNode.minValueEndSlotId, lowValue); + ba.setValue(lfgNode.maxValueBeginSlotId, lfgNode.maxValueEndSlotId, highValue); + } + } +} + +//---------------------------------------------------------------------- + +void LfgDataTable::getLowHighValue(std::string const & lfgNodeName, unsigned long & lowValue, unsigned long & highValue, BitArray const & ba) +{ + lowValue = 0; + highValue = 0; + + LfgNode const * lfgNode = getLfgNodeByName(lfgNodeName); + if (lfgNode) + getLowHighValue(*lfgNode, lowValue, highValue, ba); +} + +//---------------------------------------------------------------------- + +void LfgDataTable::getLowHighValue(LfgNode const & lfgNode, unsigned long & lowValue, unsigned long & highValue, BitArray const & ba) +{ + lowValue = 0; + highValue = 0; + + if ((lfgNode.isLeafNode()) && + (lfgNode.minValueBeginSlotId >= 0) && + (lfgNode.minValueEndSlotId >= 0) && + (lfgNode.minValueBeginSlotId < lfgNode.minValueEndSlotId) && + (lfgNode.maxValueBeginSlotId >= 0) && + (lfgNode.maxValueEndSlotId >= 0) && + (lfgNode.maxValueBeginSlotId < lfgNode.maxValueEndSlotId) && + (lfgNode.minValue > 0) && + (lfgNode.maxValue > 0) && + (lfgNode.minValue < lfgNode.maxValue) + ) + { + lowValue = ba.getValue(lfgNode.minValueBeginSlotId, lfgNode.minValueEndSlotId); + highValue = ba.getValue(lfgNode.maxValueBeginSlotId, lfgNode.maxValueEndSlotId); + } +} + +//---------------------------------------------------------------------- + +std::string LfgDataTable::getSetLfgNodeDebugString(BitArray const & ba, bool displayAnyOrAllValue/*= true*/) +{ + std::string output; + std::map > allSetLeafNodes; + + unsigned long lowValue, highValue; + for (std::map::const_iterator iterLeafNode = s_allLeafNodesByName.begin(); iterLeafNode != s_allLeafNodesByName.end(); ++iterLeafNode) + { + if (iterLeafNode->second->minValue > 0) + { + getLowHighValue(*iterLeafNode->second, lowValue, highValue, ba); + if ((lowValue > 0) && (highValue > 0)) + { + allSetLeafNodes[iterLeafNode->second] = std::make_pair(lowValue, highValue); + } + } + else + { + if (testBit(*iterLeafNode->second, ba)) + { + allSetLeafNodes[iterLeafNode->second] = std::make_pair(0, 0); + } + } + } + + std::set allParentNodesWithSetLeafDescendants; + for (std::map >::const_iterator iterSetLeafNode = allSetLeafNodes.begin(); iterSetLeafNode != allSetLeafNodes.end(); ++iterSetLeafNode) + { + LfgDataTable::LfgNode const * parent = iterSetLeafNode->first->parent; + while (parent) + { + IGNORE_RETURN(allParentNodesWithSetLeafDescendants.insert(parent)); + parent = parent->parent; + } + } + + for (std::vector::const_iterator iterTopLevelNode = s_topLevelNodes.begin(); iterTopLevelNode != s_topLevelNodes.end(); ++iterTopLevelNode) + { + std::string sTopLevelNode; + LfgDataTableNamespace::getSetLfgNodeDebugString(**iterTopLevelNode, sTopLevelNode, std::string(), allParentNodesWithSetLeafDescendants, allSetLeafNodes, ba, displayAnyOrAllValue); + output += sTopLevelNode; + } + + return output; +} diff --git a/engine/shared/library/sharedGame/src/shared/core/LfgDataTable.h b/engine/shared/library/sharedGame/src/shared/core/LfgDataTable.h new file mode 100644 index 00000000..e95f1e85 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/LfgDataTable.h @@ -0,0 +1,125 @@ +// ====================================================================== +// +// LfgDataTable.h +// Copyright 2006 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#ifndef INCLUDED_LfgDataTable_H +#define INCLUDED_LfgDataTable_H + +#include + +class BitArray; +class LfgCharacterData; + +// ====================================================================== + +class LfgDataTable // static class +{ +public: + static void install(); + static void remove(); + + enum DefaultMatchConditionType + { + DMCT_NA, + DMCT_Any, + DMCT_AnyOnly, + DMCT_All, + DMCT_AllOnly + }; + + // pointer to a function that, given a LfgCharacterData, + // determines if there is an lfg "match"; every LfgNode + // corresponding to an "internal" lfg search criteria + // will contain the corresponding "match" function; + // the 5 void const * params are optional information + // that can be passed in to the "match" function, as + // some "match" function may require additional data + // in order to perform the "matching" and those functions + // will cast the void const * to whatever the function + // is expecting to be in those params + typedef bool (*pf) (LfgCharacterData const &, void const *, void const *, void const *, void const *, void const *); + + class LfgNode + { + public: + LfgNode(std::string const & pName, bool pInternalAttribute, int pMinValueBeginSlotId, int pMinValueEndSlotId, int pMaxValueBeginSlotId, int pMaxValueEndSlotId, int pMinValue, int pMaxValue, DefaultMatchConditionType pDefaultMatchCondition, LfgNode const * pParent) : + name(pName), internalAttribute(pInternalAttribute), minValueBeginSlotId(pMinValueBeginSlotId), minValueEndSlotId(pMinValueEndSlotId), maxValueBeginSlotId(pMaxValueBeginSlotId), maxValueEndSlotId(pMaxValueEndSlotId), minValue(pMinValue), maxValue(pMaxValue), defaultMatchCondition(pDefaultMatchCondition), actualMatchCondition(DMCT_NA), parent(pParent), anyAllGroupingParent(NULL), children(), hasAnyInternalAttributeLeafNodeDescendants(false), hasAnyExternalAttributeLeafNodeDescendants(false), internalAttributeMatchFunction(NULL) {}; + + std::string const name; + bool const internalAttribute; + int const minValueBeginSlotId; + int const minValueEndSlotId; + int const maxValueBeginSlotId; + int const maxValueEndSlotId; + int const minValue; + int const maxValue; + DefaultMatchConditionType const defaultMatchCondition; + + // for convenience, we will use this transient/temporary + // member to store the *ACTUAL* any/all value, + // if applicable, that the user specified for this node; + // ***WARNING*** don't use this value willy nilly because + // it just contains the transient/temporary value from + // the last time it was used; remember, this member + // is used to store a transient/temporary value + DefaultMatchConditionType actualMatchCondition; + + LfgNode const * const parent; + LfgNode const * anyAllGroupingParent; + std::vector children; + bool hasAnyInternalAttributeLeafNodeDescendants; + bool hasAnyExternalAttributeLeafNodeDescendants; + + LfgDataTable::pf internalAttributeMatchFunction; + + inline bool isLeafNode() const {return children.empty();} + inline bool isMinMaxNode() const {return (minValue > 0 && maxValue > 0);} + + private: + LfgNode(); + LfgNode(LfgNode const &); + LfgNode &operator =(LfgNode const &); + }; + + static std::vector const & getTopLevelLfgNodes(); + static stdmap::fwd const & getAllLfgLeafNodes(); + static LfgNode const * getLfgNodeByName(std::string const & lfgNodeName); + static LfgNode const * getLfgLeafNodeByName(std::string const & lfgNodeName); + + static void setBit(std::string const & lfgNodeName, BitArray & ba); + static void setBit(LfgNode const & lfgNode, BitArray & ba); + + static void clearBit(std::string const & lfgNodeName, BitArray & ba); + static void clearBit(LfgNode const & lfgNode, BitArray & ba); + + static bool testBit(std::string const & lfgNodeName, BitArray const & ba); + static bool testBit(LfgNode const & lfgNode, BitArray const & ba); + + static void setAnyOrAllBit(std::string const & lfgNodeName, bool any, BitArray & ba); + static void setAnyOrAllBit(LfgNode const & lfgNode, bool any, BitArray & ba); + + static bool testAnyOrAllBit(std::string const & lfgNodeName, BitArray const & ba); + static bool testAnyOrAllBit(LfgNode const & lfgNode, BitArray const & ba); + + static void setLowHighValue(std::string const & lfgNodeName, unsigned long lowValue, unsigned long highValue, BitArray & ba); + static void setLowHighValue(LfgNode const & lfgNode, unsigned long lowValue, unsigned long highValue, BitArray & ba); + + static void getLowHighValue(std::string const & lfgNodeName, unsigned long & lowValue, unsigned long & highValue, BitArray const & ba); + static void getLowHighValue(LfgNode const & lfgNode, unsigned long & lowValue, unsigned long & highValue, BitArray const & ba); + + static std::string getSetLfgNodeDebugString(BitArray const & ba, bool displayAnyOrAllValue = true); + +private: // disabled + + LfgDataTable(); + LfgDataTable(LfgDataTable const &); + LfgDataTable &operator =(LfgDataTable const &); +}; + +// ====================================================================== + +#endif // INCLUDED_LfgDataTable_H diff --git a/engine/shared/library/sharedGame/src/shared/core/MoodManager.cpp b/engine/shared/library/sharedGame/src/shared/core/MoodManager.cpp new file mode 100644 index 00000000..295bd40d --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/MoodManager.cpp @@ -0,0 +1,159 @@ +//====================================================================== +// +// MoodManager.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/MoodManager.h" + +#include "LocalizationManager.h" +#include "LocalizedStringTable.h" +#include "UnicodeUtils.h" +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/Iff.h" +#include "sharedFoundation/Tag.h" +#include "sharedObject/World.h" + +//====================================================================== + +namespace +{ + typedef stdmap::fwd IntStringMap; + typedef stdmap::fwd StringIntMap; + + IntStringMap s_idToNameMap; + StringIntMap s_nameToIdMap; + + bool s_installed = false; + + const std::string s_filename = "chat/mood_types.iff"; + + namespace Tags + { + const Tag MOOD = TAG (M,O,O,D); + const Tag TYPS = TAG (T,Y,P,S); + } +} + +//----------------------------------------------------------------- + +void MoodManager::install () +{ + InstallTimer const installTimer("MoodManager::install "); + + DEBUG_FATAL (s_installed, ("already installed.\n")); + + s_idToNameMap.clear (); + s_nameToIdMap.clear (); + + s_installed = true; + + load (s_filename); +} + +//----------------------------------------------------------------- + +void MoodManager::remove () +{ + DEBUG_FATAL (!s_installed, ("not installed.\n")); + + s_idToNameMap.clear (); + s_nameToIdMap.clear (); + + s_installed = false; +} + +//---------------------------------------------------------------------- + +uint32 MoodManager::getMoodByCanonicalName (const std::string & canonicalName) +{ + DEBUG_FATAL (!s_installed, ("not installed.\n")); + + const StringIntMap::const_iterator it = s_nameToIdMap.find (canonicalName); + + if (it != s_nameToIdMap.end ()) + return (*it).second; + + return 0; +} + +//---------------------------------------------------------------------- + +bool MoodManager::getCanonicalName (uint32 id, std::string & name) +{ + DEBUG_FATAL (!s_installed, ("not installed.\n")); + + const IntStringMap::const_iterator it = s_idToNameMap.find (id); + + if (it != s_idToNameMap.end ()) + { + name = (*it).second; + return true; + } + + return false; +} + +//---------------------------------------------------------------------- + +void MoodManager::getCanonicalMoods (StringIntMap & sim) +{ + sim = s_nameToIdMap; +} + +//---------------------------------------------------------------------- + +void MoodManager::load (const std::string & filename) +{ + Iff iff; + if (!iff.open (filename.c_str (), true)) + { + WARNING_STRICT_FATAL (true, ("MoodManager No such file: '%s'", filename.c_str ())); + return; + } + + if (!iff.enterForm (Tags::MOOD, true)) + { + WARNING_STRICT_FATAL (true, ("MoodManager file '%s' had no tag MOOD", filename.c_str ())); + return; + } + + if (!iff.enterForm (TAG_0000, true)) + { + WARNING_STRICT_FATAL (true, ("MoodManager file '%s' had no tag 0000", filename.c_str ())); + return; + } + + if (!iff.enterChunk (Tags::TYPS, true)) + { + WARNING_STRICT_FATAL (true, ("MoodManager file '%s' had no tag TYPS", filename.c_str ())); + return; + } + + uint32 count = 0; + + //-- 'none' must be zero + static const std::string s_none = "none"; + s_idToNameMap.insert (std::make_pair (count, s_none)); + s_nameToIdMap.insert (std::make_pair (s_none, count)); + + while (iff.getChunkLengthLeft () > 0) + { + const std::string name = Unicode::toLower (iff.read_stdstring ()); + + ++count; + + s_idToNameMap.insert (std::make_pair (count, name)); + + const std::pair retval = s_nameToIdMap.insert (std::make_pair (name, count)); + + if (!retval.second) + WARNING_STRICT_FATAL (true, ("SpatialChatManager file '%s' duplicate chat type '%s'", filename.c_str (), name.c_str ())); + } + + iff.exitChunk (Tags::TYPS); +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/MoodManager.h b/engine/shared/library/sharedGame/src/shared/core/MoodManager.h new file mode 100644 index 00000000..f41f5d89 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/MoodManager.h @@ -0,0 +1,37 @@ +//====================================================================== +// +// MoodManager.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_MoodManager_H +#define INCLUDED_MoodManager_H + +//====================================================================== + +class LocalizedStringTable; + +//---------------------------------------------------------------------- + +class MoodManager +{ +public: + + typedef stdmap::fwd StringIntMap; + + static void install (); + static void remove (); + + static uint32 getMoodByCanonicalName (const std::string & canonicalName); + static bool getCanonicalName (uint32 id, std::string & name); + + static void getCanonicalMoods (StringIntMap & sim); + +private: + static void load (const std::string & filename); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/NpcConversationData.h b/engine/shared/library/sharedGame/src/shared/core/NpcConversationData.h new file mode 100644 index 00000000..b928e6ac --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/NpcConversationData.h @@ -0,0 +1,29 @@ +//======================================================================== +// +// NpcConversationData.h +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef INCLUDED_NpcConversationData_H +#define INCLUDED_NpcConversationData_H + + +//======================================================================== + +namespace NpcConversationData +{ + enum ConversationStarter + { + CS_Player, + CS_NPC + }; + +} // namespace Crafting + + +//======================================================================== + + +#endif // INCLUDED_NpcConversationData_H diff --git a/engine/shared/library/sharedGame/src/shared/core/OutOfBand.h b/engine/shared/library/sharedGame/src/shared/core/OutOfBand.h new file mode 100644 index 00000000..1ede7436 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/OutOfBand.h @@ -0,0 +1,66 @@ +// OutOfBand.h +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall + +#ifndef _INCLUDED_OutOfBand_H +#define _INCLUDED_OutOfBand_H + +//----------------------------------------------------------------------- + +#include "sharedGame/OutOfBandBase.h" + +//----------------------------------------------------------------------- + +template +class OutOfBand : public OutOfBandBase +{ +public: + OutOfBand(const char typeId, const int position, ValueType * object); + ~OutOfBand(); + + const ValueType * getObject () const; + ValueType * getObject (); + +private: + OutOfBand & operator = (const OutOfBand & rhs); + OutOfBand(const OutOfBand & source); + +private: + ValueType * const object; +}; + +//----------------------------------------------------------------------- + +template +OutOfBand::OutOfBand(const char t, const int i, ValueType * o) : +OutOfBandBase(t, i), +object(o) +{ +} + +//----------------------------------------------------------------------- + +template +OutOfBand::~OutOfBand() +{ +} + +//----------------------------------------------------------------------- + +template +const ValueType * OutOfBand::getObject() const +{ + return object; +} + +//----------------------------------------------------------------------- + +template +ValueType * OutOfBand::getObject() +{ + return object; +} + +//----------------------------------------------------------------------- + +#endif // _INCLUDED_OutOfBand_H diff --git a/engine/shared/library/sharedGame/src/shared/core/OutOfBandBase.cpp b/engine/shared/library/sharedGame/src/shared/core/OutOfBandBase.cpp new file mode 100644 index 00000000..9088ef3a --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/OutOfBandBase.cpp @@ -0,0 +1,39 @@ +// OutOfBandBase.cpp +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall + +//----------------------------------------------------------------------- + +#include "sharedGame/FirstSharedGame.h" +#include "OutOfBandBase.h" + +//----------------------------------------------------------------------- + +OutOfBandBase::OutOfBandBase(const char t, const int p) : +position(p), +typeId(t) +{ +} + +//----------------------------------------------------------------------- + +OutOfBandBase::~OutOfBandBase() +{ +} + +//----------------------------------------------------------------------- + +const int OutOfBandBase::getPosition() const +{ + return position; +} + +//----------------------------------------------------------------------- + +const unsigned char OutOfBandBase::getTypeId() const +{ + return typeId; +} + +//----------------------------------------------------------------------- + diff --git a/engine/shared/library/sharedGame/src/shared/core/OutOfBandBase.h b/engine/shared/library/sharedGame/src/shared/core/OutOfBandBase.h new file mode 100644 index 00000000..ef9b39de --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/OutOfBandBase.h @@ -0,0 +1,31 @@ +// OutOfBandBase.h +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall + +#ifndef _INCLUDED_OutOfBandBase_H +#define _INCLUDED_OutOfBandBase_H + +//----------------------------------------------------------------------- + +class OutOfBandBase +{ +public: + virtual ~OutOfBandBase() = 0; + + const int getPosition () const; + const unsigned char getTypeId () const; + +protected: + OutOfBandBase(const char typeId, const int position); + +private: + OutOfBandBase & operator = (const OutOfBandBase & rhs); + OutOfBandBase(const OutOfBandBase & source); + + int position; + unsigned char typeId; +}; + +//----------------------------------------------------------------------- + +#endif // _INCLUDED_OutOfBandBase_H diff --git a/engine/shared/library/sharedGame/src/shared/core/OutOfBandPackager.cpp b/engine/shared/library/sharedGame/src/shared/core/OutOfBandPackager.cpp new file mode 100644 index 00000000..f621cd7f --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/OutOfBandPackager.cpp @@ -0,0 +1,260 @@ +// OutOfBandPackager.cpp +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall + +//----------------------------------------------------------------------- + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/OutOfBandPackager.h" + +#include "Archive/Archive.h" +#include "Archive/ByteStream.h" +#include "Unicode.h" +#include "UnicodeUtils.h" +#include "localizationArchive/StringIdArchive.h" +#include "sharedGame/AuctionToken.h" +#include "sharedGame/AuctionTokenArchive.h" +#include "sharedGame/OutOfBand.h" +#include "sharedGame/OutOfBandPackager.h" +#include "sharedGame/ProsePackage.h" +#include "sharedGame/ProsePackageArchive.h" +#include "sharedGame/WaypointData.h" +#include "sharedObject/ObjectTemplate.h" +#include "unicodeArchive/UnicodeArchive.h" + +//----------------------------------------------------------------------- + +void OutOfBandPackager::pack(const Archive::ByteStream & source, const unsigned char typeId, const int position, Unicode::String & target) +{ + Archive::ByteStream package; + Archive::put(package, typeId); + Archive::put(package, position); + package.put(source.getBuffer(), source.getSize()); + + //-- pad out the buffer to fit perfectly in a unicode string + const int cbufSize = package.getSize (); + + int skipRemainder = cbufSize % sizeof (Unicode::unicode_char_t); + + for (int i = 0; i < skipRemainder; ++i) + Archive::put(package, static_cast (0)); + + const Unicode::unicode_char_t * const ubuf = reinterpret_cast(package.getBuffer ()); + const int ubufSize = package.getSize () / sizeof (Unicode::unicode_char_t); + + DEBUG_FATAL (ubufSize * sizeof (Unicode::unicode_char_t) != package.getSize (), ("bad packing logic")); + + //-- note the size of the skip remainder padding so the unpacking function can advance over it + target.append (1, static_cast(skipRemainder)); + target.append (ubuf, ubuf + ubufSize); +} + +//---------------------------------------------------------------------- + +void OutOfBandPackager::pack (const AttributeVector & attribs, int position, Unicode::String & targetOob) +{ + Archive::ByteStream bs; + Archive::put (bs, attribs); + OutOfBandPackager::pack(bs, OutOfBandPackager::OT_objectAttributes, position, targetOob); +} + +//---------------------------------------------------------------------- + +void OutOfBandPackager::pack (const AuctionToken & token, int position, Unicode::String & targetOob) +{ + Archive::ByteStream bs; + Archive::put (bs, token); + OutOfBandPackager::pack(bs, OutOfBandPackager::OT_auctionToken, position, targetOob); +} + +//---------------------------------------------------------------------- + +void OutOfBandPackager::pack (const ProsePackage & pp, int position, Unicode::String & targetOob) +{ + Archive::ByteStream bs; + Archive::put(bs, pp); + + OutOfBandPackager::pack(bs, OutOfBandPackager::OT_prosePackage, position, targetOob); +} + +//---------------------------------------------------------------------- + +void OutOfBandPackager::pack (const WaypointDataBase & waypointData, int position, Unicode::String & targetOob) +{ + Archive::ByteStream bs; + Archive::put (bs, waypointData); + OutOfBandPackager::pack(bs, OutOfBandPackager::OT_waypointData, position, targetOob); +} + +//---------------------------------------------------------------------- + +void OutOfBandPackager::pack (const StringId & stringId, int position, Unicode::String & targetOob) +{ + Archive::ByteStream bs; + Archive::put (bs, stringId); + OutOfBandPackager::pack(bs, OutOfBandPackager::OT_stringId, position, targetOob); +} + +//---------------------------------------------------------------------- + +void OutOfBandPackager::pack (const std::string & str, int position, Unicode::String & targetOob) +{ + Archive::ByteStream bs; + Archive::put (bs, str); + OutOfBandPackager::pack(bs, OutOfBandPackager::OT_string, position, targetOob); +} + +//----------------------------------------------------------------------- + +OutOfBandPackager::OutOfBandBaseVector OutOfBandPackager::unpack(const Unicode::String & source, OobTypes type, int count) +{ + if (source.empty ()) + return OutOfBandBaseVector (); + + std::vector result; + + const unsigned char * const buf = reinterpret_cast(source.data()); + const uint32 buflen = source.size () * sizeof (Unicode::unicode_char_t); + + Archive::ByteStream bs(buf, buflen); + Archive::ReadIterator ri(bs); + + std::string templateName; + unsigned char typeId = 0; + int position = 0; + int numUnpacked = 0; + + try + { + while(ri.getSize()) + { + if (count > 0 && numUnpacked >= count) + break; + + unsigned short skipRemainder = 0; + + Archive::get(ri, skipRemainder); + Archive::get(ri, typeId); + Archive::get(ri, position); + + switch(typeId) + { + case OT_object: + { + /* + Archive::get(ri, templateName); + if(templateName.length()) + { + Object * const obj = ObjectTemplate::createObject(templateName.c_str()); + if(obj) + { + OutOfBand * const entry = new OutOfBand(typeId, position, obj); + result.push_back(entry); + } + } + */ + } + break; + case OT_prosePackage: + { + ProsePackage * const pp = new ProsePackage; + Archive::get (ri, *pp); + + if (type != OT_numTypes && type != typeId) + delete pp; + else + { + OutOfBand * const entry = new OutOfBand(typeId, position, pp); + result.push_back (entry); + } + } + break; + case OT_auctionToken: + { + AuctionToken * const token = new AuctionToken; + Archive::get (ri, *token); + if (type != OT_numTypes && type != typeId) + delete token; + else + { + OutOfBand * const entry = new OutOfBand(typeId, position, token); + result.push_back (entry); + } + } + break; + + case OT_string: + { + std::string * const str = new std::string; + Archive::get (ri, *str); + if (type != OT_numTypes && type != typeId) + delete str; + else + { + OutOfBand * const entry = new OutOfBand(typeId, position, str); + result.push_back (entry); + } + } + break; + + case OT_objectAttributes: + { + AttributeVector * const av = new AttributeVector; + Archive::get (ri, *av); + if (type != OT_numTypes && type != typeId) + delete av; + else + { + OutOfBand * const entry = new OutOfBand(typeId, position, av); + result.push_back (entry); + } + } + break; + + case OT_waypointData: + { + WaypointDataBase * const waypointData = new WaypointDataBase; + Archive::get (ri, *waypointData); + if (type != OT_numTypes && type != typeId) + delete waypointData; + else + { + OutOfBand * const entry = new OutOfBand(typeId, position, waypointData); + result.push_back (entry); + } + } + break; + + default: + WARNING (true, ("OutOfBandPackager recieved unknown type [%d]", typeId)); + break; + } + + ++numUnpacked; + + //- advance over padding space + if (skipRemainder) + ri.advance (skipRemainder); + } + } + catch (const Archive::ReadException & readException) + { + WARNING (true, ("Archive read error (%s) unpacking OOB type [%d] at position [%d]", readException.what(), typeId, position)); + } + + return result; +} + +//---------------------------------------------------------------------- + +OutOfBandBase * OutOfBandPackager::unpackOne (const Unicode::String & source, OobTypes type) +{ + const OutOfBandBaseVector & v = unpack (source, type, 1); + if (!v.empty ()) + return v.front (); + + return 0; +} + +//----------------------------------------------------------------------- + diff --git a/engine/shared/library/sharedGame/src/shared/core/OutOfBandPackager.h b/engine/shared/library/sharedGame/src/shared/core/OutOfBandPackager.h new file mode 100644 index 00000000..f36e4a14 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/OutOfBandPackager.h @@ -0,0 +1,66 @@ +// OutOfBandPackager.h +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall + +#ifndef _INCLUDED_OutOfBandPackager_H +#define _INCLUDED_OutOfBandPackager_H + +//----------------------------------------------------------------------- + +namespace Archive +{ + class ByteStream; +} + +//----------------------------------------------------------------------- + +class OutOfBandBase; +class ProsePackage; +class AuctionToken; +class WaypointDataBase; + +//----------------------------------------------------------------------- + +class OutOfBandPackager +{ +public: + + typedef stdvector::fwd OutOfBandBaseVector; + typedef stdvector >::fwd AttributeVector; + + enum OobTypes + { + OT_object, + OT_prosePackage, + OT_auctionToken, + OT_objectAttributes, + OT_waypointData, + OT_stringId, + OT_string, + OT_numTypes + }; + + ~OutOfBandPackager(); + + static void pack (const AttributeVector & attribs, int position, Unicode::String & targetOob); + static void pack (const AuctionToken & token, int position, Unicode::String & targetOob); + static void pack (const ProsePackage & pp, int position, Unicode::String & targetOob); + static void pack (const WaypointDataBase & waypointData, int position, Unicode::String & targetOob); + static void pack (const StringId & stringId, int position, Unicode::String & targetOob); + static void pack (const std::string & str, int position, Unicode::String & targetOob); + + static void pack (const Archive::ByteStream & source, const unsigned char typeId, const int position, Unicode::String & target); + + static OutOfBandBaseVector unpack (const Unicode::String & source, OobTypes type = OT_numTypes, int count = -1); + + static OutOfBandBase * unpackOne (const Unicode::String & source, OobTypes type = OT_numTypes); + +private: + OutOfBandPackager(); + OutOfBandPackager(const OutOfBandPackager &); + OutOfBandPackager & operator = (const OutOfBandPackager &); +}; + +//----------------------------------------------------------------------- + +#endif // _INCLUDED_OutOfBandPackager_H diff --git a/engine/shared/library/sharedGame/src/shared/core/PlanetMapManager.cpp b/engine/shared/library/sharedGame/src/shared/core/PlanetMapManager.cpp new file mode 100644 index 00000000..c05674c5 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/PlanetMapManager.cpp @@ -0,0 +1,276 @@ +//====================================================================== +// +// PlanetMapManager.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/PlanetMapManager.h" + +#include "UnicodeUtils.h" +#include "sharedFile/Iff.h" +#include "sharedFile/TreeFile.h" +#include "sharedMath/Vector.h" +#include "sharedUtility/DataTable.h" +#include +#include "sharedNetworkMessages/MapLocation.h" +#include "sharedFoundation/Crc.h" + +//====================================================================== + +namespace PlanetMapManagerNamespace +{ + typedef stdmap::fwd TypeNameMap; + typedef stdmap::fwd NameTypeMap; + typedef stdmap::fwd TypeStringIdMap; + + typedef std::pair FactionAndVisibility; + typedef stdmap::fwd TypeFactionMap; + + TypeNameMap s_typeNameMap; + NameTypeMap s_nameTypeMap; + TypeStringIdMap s_typeStringMap; + TypeFactionMap s_typeFactionMap; + + bool s_installed = false; + + uint8 s_cityCategory = 0; + uint8 s_waypointCategory = 0; + uint8 s_poiCategory = 0; + uint8 s_gcwRegionCategory = 0; + + enum DtCols + { + DC_name, + DC_index, + DC_isCategory, + DC_isSubCategory, + DC_canBeActive, + DC_faction, + DC_factionVisibleOnly + }; + + void install () + { + if (s_installed) + return; + + s_installed = true; + + { + static const char * const filename = "datatables/player/planet_map_cat.iff"; + Iff iff; + + if (!iff.open (filename, true)) + WARNING (true, ("Data file %s not available.", filename)); + else + { + DataTable dt; + dt.load (iff); + iff.close (); + + const int numRows = dt.getNumRows (); + + static const std::string table = "map_loc_cat_n"; + + for (int i = 0; i < numRows; ++i) + { + const std::string & name = dt.getStringValue (DC_name, i); + const uint8 index = static_cast(dt.getIntValue (DC_index, i)); + const StringId & str = StringId (table, name); + + const std::string & faction = dt.getStringValue (DC_faction, i); + + s_typeNameMap.insert (std::make_pair (index, name)); + s_nameTypeMap.insert (std::make_pair (name, index)); + s_typeStringMap.insert (std::make_pair (index, str)); + + if (name == "city") + s_cityCategory = index; + else if (name == "waypoint") + s_waypointCategory = index; + else if (name == "poi") + s_poiCategory = index; + else if (name == "gcw_region") + s_gcwRegionCategory = index; + + if (!faction.empty ()) + { + const bool factionVisibleOnly = dt.getIntValue (DC_factionVisibleOnly, i) != 0; + s_typeFactionMap.insert (std::make_pair (index, FactionAndVisibility (Crc::normalizeAndCalculate (faction.c_str ()), factionVisibleOnly))); + } + } + } + + DEBUG_FATAL (!s_cityCategory, ("PlanetMapManager has no city category")); + DEBUG_FATAL (!s_waypointCategory, ("PlanetMapManager has no waypoint category")); + } + } +} + +using namespace PlanetMapManagerNamespace; + +//---------------------------------------------------------------------- + +bool PlanetMapManager::checkCategoryFaction (uint8 category, uint32 & faction, bool & factionVisibilityOnly) +{ + if (!s_installed) + install (); + + const TypeFactionMap::const_iterator it = s_typeFactionMap.find (category); + if (it != s_typeFactionMap.end ()) + { + const FactionAndVisibility & fav = (*it).second; + faction = fav.first; + factionVisibilityOnly = fav.second; + return true; + } + + return false; +} + +//---------------------------------------------------------------------- + +Vector PlanetMapManager::convertPositionToFictional (const std::string & sceneId, const Vector & pos_w) +{ + if (!s_installed) + install (); + + UNREF (sceneId); + return pos_w; +} + +//---------------------------------------------------------------------- + +Vector PlanetMapManager::convertPositionFromFictional (const std::string & sceneId, const Vector & fictionalPos_w) +{ + if (!s_installed) + install (); + + UNREF (sceneId); + return fictionalPos_w; +} + +//---------------------------------------------------------------------- + +const std::string & PlanetMapManager::findCategoryName (uint8 category) +{ + if (!s_installed) + install (); + + const TypeNameMap::const_iterator it = s_typeNameMap.find (category); + if (it != s_typeNameMap.end ()) + return (*it).second; + + static const std::string emptyString; + return emptyString; +} + +//---------------------------------------------------------------------- + +const StringId & PlanetMapManager::findCategoryStringId (uint8 category) +{ + if (!s_installed) + install (); + + const TypeStringIdMap::const_iterator it = s_typeStringMap.find (category); + if (it != s_typeStringMap.end ()) + return (*it).second; + + return StringId::cms_invalid; +} + +//---------------------------------------------------------------------- + +uint8 PlanetMapManager::findCategory (const std::string & name, bool warn) +{ + if (!s_installed) + install (); + + if (name.empty ()) + return 0; + + const NameTypeMap::const_iterator it = s_nameTypeMap.find (name); + if (it != s_nameTypeMap.end ()) + return (*it).second; + + UNREF(warn); + DEBUG_WARNING (warn, ("MapLocation category [%s] invalid", name.c_str ())); + + return 0; +} + +//---------------------------------------------------------------------- + +MapLocation PlanetMapManager::makeMapLocation (const NetworkId &locationId, const Unicode::String &locationName, const Vector2d &location, const std::string &categoryName, const std::string &subCategoryName, int flags, bool & result) +{ + const uint8 category = PlanetMapManager::findCategory (categoryName); + const uint8 subCategory = PlanetMapManager::findCategory (subCategoryName); + + result = category && (subCategory || subCategoryName.empty ()); + + WARNING (!result, ("PlanetMapManager::makeMapLocation failed for id=[%s], name=[%s], cat=[%s], subcat=[%s], flags=[%d]", + locationId.getValueString ().c_str (), Unicode::wideToNarrow (locationName).c_str (), categoryName.c_str (), subCategoryName.c_str (), flags)); + + return MapLocation (locationId, locationName, location, category, subCategory, static_cast(flags)); +} + +//---------------------------------------------------------------------- + +uint8 PlanetMapManager::getCityCategory () +{ + if (!s_installed) + install (); + + return s_cityCategory; +} + +//---------------------------------------------------------------------- + +uint8 PlanetMapManager::getWaypointCategory () +{ + if (!s_installed) + install (); + + return s_waypointCategory; +} + +//---------------------------------------------------------------------- + +uint8 PlanetMapManager::getPoiCategory () +{ + if (!s_installed) + install (); + + return s_poiCategory; +} + +//---------------------------------------------------------------------- + +uint8 PlanetMapManager::getGCWRegionCategory () +{ + if (!s_installed) + install (); + + return s_gcwRegionCategory; +} + +//---------------------------------------------------------------------- + +bool PlanetMapManager::sceneHasSupermap(std::string const & sceneId) +{ + return (sceneId.find("kashyyyk") != sceneId.npos); +} + +//---------------------------------------------------------------------- + +std::string PlanetMapManager::getSceneSupermap(std::string const & sceneId) +{ + if(sceneId.find("kashyyyk") != sceneId.npos) + return "kashyyyk_planet"; + else + return ""; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/PlanetMapManager.h b/engine/shared/library/sharedGame/src/shared/core/PlanetMapManager.h new file mode 100644 index 00000000..8ed7f686 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/PlanetMapManager.h @@ -0,0 +1,54 @@ +//====================================================================== +// +// PlanetMapManager.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_PlanetMapManager_H +#define INCLUDED_PlanetMapManager_H + +//====================================================================== + +class Vector; +class MapLocation; +class NetworkId; +class Vector2d; + +//---------------------------------------------------------------------- + +class PlanetMapManager +{ +public: + + enum MapLocationType + { + MLT_static, + MLT_dynamic, + MLT_persist, + MLT_numTypes + }; + + static Vector convertPositionToFictional (const std::string & sceneId, const Vector & pos_w); + static Vector convertPositionFromFictional (const std::string & sceneId, const Vector & fictionalPos_w); + + static const std::string & findCategoryName (uint8 category); + static const StringId & findCategoryStringId (uint8 category); + static uint8 findCategory (const std::string & name, bool warn = true); + + static uint8 getCityCategory (); + static uint8 getWaypointCategory (); + static uint8 getPoiCategory (); + static uint8 getGCWRegionCategory (); + + static MapLocation makeMapLocation (const NetworkId &locationId, const Unicode::String &locationName, const Vector2d &location, const std::string &categoryName, const std::string &subCategoryName, int flags, bool & result); + + static bool checkCategoryFaction (uint8 category, uint32 & faction, bool & factionVisibilityOnly); + + static bool sceneHasSupermap(std::string const & sceneId); + static std::string getSceneSupermap(std::string const & sceneId); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/PlatformFeatureBits.cpp b/engine/shared/library/sharedGame/src/shared/core/PlatformFeatureBits.cpp new file mode 100644 index 00000000..f2dbd76b --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/PlatformFeatureBits.cpp @@ -0,0 +1,14 @@ +// ====================================================================== +// +// PlatformFeatureBits.cpp +// +// Copyright 2004 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/PlatformFeatureBits.h" + +// ====================================================================== + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/PlatformFeatureBits.h b/engine/shared/library/sharedGame/src/shared/core/PlatformFeatureBits.h new file mode 100644 index 00000000..0004aae9 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/PlatformFeatureBits.h @@ -0,0 +1,172 @@ +//====================================================================== +// +// PlatformFeatureBits.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_PlatformFeatureBits_H +#define INCLUDED_PlatformFeatureBits_H + +#include +#include + +//These define the bits used by the Platform group (SessionAPI) to distinguish customers +//Ep3 bits specified by Taylor Steil of Platform + +namespace ClientGameFeature +{ + int const Base = BINARY8(0000,0000,0000,0000,0000,0000,0000,0001); // 0 (1) + int const CollectorsEdition = BINARY8(0000,0000,0000,0000,0000,0000,0000,0010); // 1 (2) + int const SpaceExpansionBeta = BINARY8(0000,0000,0000,0000,0000,0000,0000,0100); // 2 (4) + int const SpaceExpansionPreOrder = BINARY8(0000,0000,0000,0000,0000,0000,0000,1000); // 3 (8) + int const SpaceExpansionRetail = BINARY8(0000,0000,0000,0000,0000,0000,0001,0000); // 4 (16) + int const SWGRetail = BINARY8(0000,0000,0000,0000,0000,0000,0010,0000); // 5 (32) + int const SpaceExpansionPromotion = BINARY8(0000,0000,0000,0000,0000,0000,0100,0000); // 6 (64) + int const JapaneseRetail = BINARY8(0000,0000,0000,0000,0000,0000,1000,0000); // 7 (128) + int const JapaneseCollectors = BINARY8(0000,0000,0000,0000,0000,0001,0000,0000); // 8 (256) + int const Episode3ExpansionRetail = BINARY8(0000,0000,0000,0000,0000,0010,0000,0000); // 9 (512) + int const CombatUpgrade = BINARY8(0000,0000,0000,0000,0000,0100,0000,0000); // 10 (1024) + int const Episode3PreorderDownload = BINARY8(0000,0000,0000,0000,0000,1000,0000,0000); // 11 (2048) + int const TrialsOfObiwanBeta = BINARY8(0000,0000,0000,0000,0001,0000,0000,0000); // 12 (4096) + int const JapaneseRecapture = BINARY8(0000,0000,0000,0000,0010,0000,0000,0000); // 13 (8192) + int const TrialsOfObiwanPreorder = BINARY8(0000,0000,0000,0000,0100,0000,0000,0000); // 14 (16384) + int const TrialsOfObiwanRetail = BINARY8(0000,0000,0000,0000,1000,0000,0000,0000); // 15 (32768) + int const StarterKit = BINARY8(0000,0000,0000,0001,0000,0000,0000,0000); // 16 (65536) + int const April2006Roadshow = BINARY8(0000,0000,0000,0010,0000,0000,0000,0000); // 17 (131072) + int const FreeTrial2 = BINARY8(0000,0000,0000,0100,0000,0000,0000,0000); // 18 (262144) + int const CompleteOnlineAdventures = BINARY8(0000,0000,0000,1000,0000,0000,0000,0000); // 19 (524288) + int const Episode3PreorderDownloadReward = BINARY8(0000,0000,0001,0000,0000,0000,0000,0000); // 20 (1048576) + int const Episode3ExpansionRetailReward = BINARY8(0000,0000,0010,0000,0000,0000,0000,0000); // 21 (2097152) + int const TrialsOfObiwanRetailReward = BINARY8(0000,0000,0100,0000,0000,0000,0000,0000); // 22 (4194304) + int const HousePackupReward = BINARY8(0000,0000,1000,0000,0000,0000,0000,0000); // 23 (8388608) + int const Summit2007Reward = BINARY8(0000,0001,0000,0000,0000,0000,0000,0000); // 24 (16777216) + int const CoaDigitalDownloadReward = BINARY8(0000,0010,0000,0000,0000,0000,0000,0000); // 25 (33554432) + int const BuddyProgramReward = BINARY8(0000,0100,0000,0000,0000,0000,0000,0000); // 26 (67108864) + int const GalacticGatheringReward = BINARY8(0000,1000,0000,0000,0000,0000,0000,0000); // 27 (134217728) + + inline std::string const getDescription(int features) + { + std::string result; + if (features & Base) + result += "Base "; + if (features & CollectorsEdition) + result += "CollectorsEdition "; + if (features & SpaceExpansionBeta) + result += "SpaceExpansionBeta "; + if (features & SpaceExpansionPreOrder) + result += "SpaceExpansionPreOrder "; + if (features & SpaceExpansionRetail) + result += "SpaceExpansionRetail "; + if (features & SWGRetail) + result += "SWGRetail "; + if (features & SpaceExpansionPromotion) + result += "SpaceExpansionPromotion "; + if (features & JapaneseRetail) + result += "JapaneseRetail "; + if (features & JapaneseCollectors) + result += "JapaneseCollectors "; + if (features & Episode3ExpansionRetail) + result += "Episode3ExpansionRetail "; + if (features & CombatUpgrade) + result += "CombatUpgrade "; + if (features & Episode3PreorderDownload) + result += "Episode3PreorderDownload "; + if (features & TrialsOfObiwanBeta) + result += "TrialsOfObiwanBeta "; + if (features & JapaneseRecapture) + result += "JapaneseRecapture "; + if (features & TrialsOfObiwanRetail) + result += "TrialsOfObiwanRetail "; + if (features & TrialsOfObiwanPreorder) + result += "TrialsOfObiwanPreorder "; + if (features & StarterKit) + result += "StarterKit "; + if (features & April2006Roadshow) + result += "April2006Roadshow "; + if (features & FreeTrial2) + result += "FreeTrial2 "; + if (features & CompleteOnlineAdventures) + result += "CompleteOnlineAdventures "; + if (features & Episode3PreorderDownloadReward) + result += "Episode3PreorderDownloadReward "; + if (features & Episode3ExpansionRetailReward) + result += "Episode3ExpansionRetailReward "; + if (features & TrialsOfObiwanRetailReward) + result += "TrialsOfObiwanRetailReward "; + if (features & HousePackupReward) + result += "HousePackupReward "; + if (features & Summit2007Reward) + result += "Summit2007Reward "; + if (features & CoaDigitalDownloadReward) + result += "CoaDigitalDownloadReward "; + if (features & BuddyProgramReward) + result += "BuddyProgramReward "; + if (features & GalacticGatheringReward) + result += "GalacticGatheringReward "; + + return result; + } +} + +// ---------------------------------------------------------------------- + +namespace ClientSubscriptionFeature +{ + const int Base = BINARY1(0001); // 0 (1) + const int FreeTrial = BINARY1(0010); // 1 (2) + const int CombatBalanceAccess = BINARY1(0100); // 2 (4) + const int NPENagForTrial = BINARY1(1000); // 3 (8) + const int NPENagForRental = BINARY2(0001, 0000); // 4 (16) + const int FreeTrial2 = BINARY2(0010, 0000); // 5 (32) + + inline std::string const getDescription(int features) + { + std::string result; + if (features & Base) + result += "Base "; + if (features & FreeTrial) + result += "FreeTrial "; + if (features & CombatBalanceAccess) + result += "CombatBalanceAccess "; + if (features & NPENagForTrial) + result += "NPENagForTrial "; + if (features & NPENagForRental) + result += "NPENagForRental "; + if (features & FreeTrial2) + result += "FreeTrial2 "; + + return result; + } +} + +// ---------------------------------------------------------------------- + +namespace PlatformGameCode +{ + const unsigned SWG = 4; + const unsigned SWGTCG = 38; + + const std::pair _gamecodeName[] = + { + std::pair(SWG, "SWG"), + std::pair(SWGTCG, "SWGTCG") + }; + + const std::map gamecodeName((const std::map::value_type *)&_gamecodeName[0],(const std::map::value_type *)&_gamecodeName[sizeof(_gamecodeName)/sizeof(_gamecodeName[0])]); + + inline std::string const & getGamecodeName(unsigned gameCode) + { + static const std::string empty; + + std::map::const_iterator iter = gamecodeName.find(gameCode); + if (iter != gamecodeName.end()) + return iter->second; + + return empty; + } +} + +//======================================================================== + +#endif // INCLUDED_PlatformFeatureBits_H diff --git a/engine/shared/library/sharedGame/src/shared/core/PlayerCreationManager.cpp b/engine/shared/library/sharedGame/src/shared/core/PlayerCreationManager.cpp new file mode 100644 index 00000000..24efe09a --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/PlayerCreationManager.cpp @@ -0,0 +1,652 @@ +//====================================================================== +// +// PlayerCreationManager.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/PlayerCreationManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFoundation/Tag.h" +#include "sharedFile/Iff.h" +#include "sharedSkillSystem/SkillManager.h" +#include "sharedSkillSystem/SkillObject.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" +#include "swgSharedUtility/Attributes.def" + +#include +#include + +//===================================================================== + +std::map > PlayerCreationManager::m_racialModifiers; +std::map > PlayerCreationManager::m_professionModifiers; +std::map > > PlayerCreationManager::m_racialMinMaxes; +std::map PlayerCreationManager::m_racialTotals; + +//===================================================================== + +namespace PlayerCreationManagerNamespace +{ + bool s_installed = false; + bool s_useServerTemplates = false; + + //---------------------------------------------------------------------- + + namespace Tags + { + const Tag PFDT = TAG(P,F,D,T); + const Tag PRFI = TAG(P,R,F,I); + const Tag SKLS = TAG(S,K,L,S); + const Tag SKIL = TAG(S,K,I,L); + const Tag PTMP = TAG(P,T,M,P); + const Tag ITEM = TAG(I,T,E,M); + } + + //---------------------------------------------------------------------- + + struct ProfessionInfo + { + typedef PlayerCreationManager::EqInfo EqInfo; + typedef PlayerCreationManager::SkillVector SkillVector; + typedef PlayerCreationManager::EqVector EqVector; + + typedef std::map EqMap; + + SkillVector skills; + EqMap eq; + + const EqVector * getEqVector (const std::string & sharedTemplateName) const + { + const EqMap::const_iterator it = eq.find (sharedTemplateName); + return it == eq.end () ? 0 : &(*it).second; + } + + bool load (const std::string & filename); + }; + + //---------------------------------------------------------------------- + + bool ProfessionInfo::load (const std::string & filename) + { + Iff iff; + if (!iff.open (filename.c_str (), true)) + { + WARNING_STRICT_FATAL (true, ("Specified PlayerCreationManager file '%s' could not be opened.", filename.c_str ())); + return false; + } + + if (!iff.enterForm (Tags::PRFI, true)) + { + WARNING_STRICT_FATAL (true, ("PlayerCreationManager '%s' no PRFI form found.", filename.c_str ())); + return false; + } + + if (!iff.enterForm (TAG_0000, true)) + { + WARNING_STRICT_FATAL (true, ("PlayerCreationManager '%s' no 0000 form found.", filename.c_str ())); + return false; + } + + //---------------------------------------------------------------------- + //-- load the skills + + if (!iff.enterForm (Tags::SKLS, true)) + { + WARNING_STRICT_FATAL (true, ("PlayerCreationManager '%s' no 0000 form found.", filename.c_str ())); + return false; + } + + { + skills.clear (); + skills.reserve (iff.getNumberOfBlocksLeft ()); + while (iff.enterChunk (Tags::SKIL, true)) + { + skills.push_back (iff.read_stdstring ()); + iff.exitChunk (Tags::SKIL); + } + + iff.exitForm (Tags::SKLS); + } + + //---------------------------------------------------------------------- + //-- load the equipment + + int ptmp_count = 0; + eq.clear (); + + + for (; iff.enterForm (Tags::PTMP, true); ++ptmp_count) + { +#if 1 + std::string playerTemplateStr; + if (iff.enterChunk (TAG_NAME, true)) + { + playerTemplateStr = iff.read_stdstring (); + iff.exitChunk (); + } + + if (playerTemplateStr.empty ()) + { + WARNING_STRICT_FATAL (true, ("PlayerCreationManager '%s' empty player template string in PTMP form %d.", filename.c_str (), ptmp_count)); + return false; + } + + EqVector v; + v.reserve (iff.getNumberOfBlocksLeft ()); + while (iff.enterChunk (Tags::ITEM, true)) + { + const int32 arrangement = iff.read_int32 (); + std::string itemShared = iff.read_stdstring (); + std::string itemServer = iff.read_stdstring (); + + v.push_back (EqInfo (arrangement, itemShared, itemServer)); + iff.exitChunk (); + } + + eq.insert (std::make_pair (playerTemplateStr, v)); +#endif + iff.exitForm (true); + } + + if (ptmp_count == 0) + { + WARNING (true, ("PlayerCreationManager file '%s' contained no PTMP forms.", filename.c_str ())); + return false; + } + + return true; + } + + //---------------------------------------------------------------------- + + typedef std::pair ProfessionInfoPair; + typedef std::vector ProfessionVector; + ProfessionVector * s_profVector; + + //---------------------------------------------------------------------- + + const ProfessionInfo * getProfessionInfo (const std::string & profession) + { + if (!s_profVector) + return 0; + + for (ProfessionVector::const_iterator it = s_profVector->begin (); it != s_profVector->end (); ++it) + { + if (!_stricmp (profession.c_str (), (*it).first.c_str ())) + return &(*it).second; + } + + return 0; + } + + //---------------------------------------------------------------------- + + bool sanityCheckPath (std::string & path) + { + size_t pos = 0; + bool found = false; + while ((pos = path.find ('\\', pos)) != path.npos) + { + found = true; + path [pos] = '/'; + } + + return found; + } + + std::string sharedTemplatePre = "object/creature/player/shared_"; + std::string sharedTemplatePost = ".iff"; + + std::string s_racialModsIffName = "datatables/creation/racial_mods.iff"; + std::string s_professionModsIffName = "datatables/creation/profession_mods.iff"; + + int s_magicBaseAttribNumber = 300; + unsigned int s_numberOfAttributes = Attributes::NumberOfAttributes; +} + +using namespace PlayerCreationManagerNamespace; + +//---------------------------------------------------------------------- + +PlayerCreationManager::EqInfo::EqInfo (int32 i, const std::string & a, const std::string & b) : +arrangement (i), +sharedTemplateName (a), +serverTemplateName (s_useServerTemplates ? b : "") +{ + if (sanityCheckPath (sharedTemplateName)) + WARNING (true, ("Bad shared template path: %s", a.c_str ())); + + if (s_useServerTemplates && b.empty ()) + { + serverTemplateName = sharedTemplateName; + + //-- convert shared template names to server template names + static const std::string shared_str ("/shared_"); + static const std::string shared_str_replacement ("/"); + + const size_t sharedPos = serverTemplateName.find (shared_str); + + if (sharedPos != serverTemplateName.npos) + serverTemplateName.replace (sharedPos, shared_str.size(), shared_str_replacement); + } + else + { + if (sanityCheckPath (serverTemplateName)) + WARNING (true, ("Bad server template path: %s", b.c_str ())); + } +} + +//---------------------------------------------------------------------- + +std::string PlayerCreationManager::ms_filename ("creation/profession_defaults.iff"); + +//---------------------------------------------------------------------- + +bool PlayerCreationManager::isInstalled () +{ + return s_installed; +} + +//---------------------------------------------------------------------- + +void PlayerCreationManager::install (bool useServerTemplates) +{ + InstallTimer const installTimer("PlayerCreationManager::install "); + + DEBUG_FATAL (s_installed, ("already installed.\n")); + s_installed = true; + s_useServerTemplates = useServerTemplates; + + init (); +} + +//---------------------------------------------------------------------- + +void PlayerCreationManager::remove () +{ + clear(); + DEBUG_FATAL (!s_installed, ("not installed.\n")); + s_installed = false; +} + +//---------------------------------------------------------------------- + +void PlayerCreationManager::clear () +{ + DEBUG_FATAL (!s_installed, ("not installed.\n")); + + m_racialModifiers.clear(); + m_racialMinMaxes.clear(); + m_racialTotals.clear(); + m_professionModifiers.clear(); + + delete s_profVector; + s_profVector = 0; +} + +//---------------------------------------------------------------------- + +void PlayerCreationManager::init () +{ + DEBUG_FATAL (!s_installed, ("not installed.\n")); + + initializeProfMap (ms_filename); + + loadRacialModifiers(); + loadProfessionModifiers(); + //we can only build the mins and maxes once we have all the data from the datatables for the above 2 functions + buildRacialMinsMaxes(); +} + +//---------------------------------------------------------------------- + +bool PlayerCreationManager::initializeProfMap (const std::string & filename) +{ + DEBUG_FATAL (!s_installed, ("not installed.\n")); + + Iff iff; + if (!iff.open (filename.c_str (), true)) + { + WARNING_STRICT_FATAL (true, ("Specified PlayerCreationManager file '%s' could not be opened.", filename.c_str ())); + return false; + } + + if (!iff.enterForm (Tags::PFDT, true)) + { + WARNING_STRICT_FATAL (true, ("PlayerCreationManager '%s' no PFDT form found.", filename.c_str ())); + return false; + } + + if (!iff.enterForm (TAG_0000, true)) + { + WARNING_STRICT_FATAL (true, ("PlayerCreationManager '%s' no 0000 form found.", filename.c_str ())); + return false; + } + + if (s_profVector) + s_profVector->clear (); + else + s_profVector = new ProfessionVector; + + int dataCount = 0; + while (iff.enterChunk (TAG_DATA, true)) + { + const std::string profession = iff.read_stdstring (); + const std::string profFilename = iff.read_stdstring (); + + ProfessionInfo pinfo; + + if (pinfo.load(profFilename)) + s_profVector->push_back (std::make_pair(profession, pinfo)); + else + WARNING (true, ("Unable to load PlayerCreationManager file for profession %s: %s", profession.c_str (), profFilename.c_str ())); + + iff.exitChunk (); + ++dataCount; + } + + if (!dataCount) + WARNING (true, ("No DATA items found in %s", filename.c_str ())); + + return true; +} + +//---------------------------------------------------------------------- + +/** +* The output values of attribs, skills, and eq are only guaranteed valid until +* a subsequent method call on PlayerCreationManager occurs. Think std::string::c_str() +* +*/ + +bool PlayerCreationManager::getDefaults(const std::string & sharedTemplateName, const std::string & profession, AttribVector & attribs, const SkillVector *& skills, const EqVector *& eq) +{ + DEBUG_FATAL (!s_installed, ("not installed.\n")); + + const ProfessionInfo * const pinfo = getProfessionInfo (profession); + + if (!pinfo) + { + WARNING (true, ("Unable to load PlayerCreationManager for profession %s", profession.c_str ())); + return false; + } + + getAttribsForRaceProfession(sharedTemplateName, profession, attribs); + + skills = &pinfo->skills; + + std::string actualTemplateName = sharedTemplateName; + + if (sanityCheckPath (actualTemplateName)) + WARNING (true, ("Bad shared template path: %s", sharedTemplateName.c_str ())); + + eq = pinfo->getEqVector(actualTemplateName); + + return true; +} + +//---------------------------------------------------------------------- + +void PlayerCreationManager::getAttribsForRaceProfession(const std::string & sharedTemplateName, const std::string & profession, AttribVector & attribs) +{ + DEBUG_FATAL (!s_installed, ("not installed.\n")); + attribs.clear(); + + std::map >::iterator raceIt = m_racialModifiers.find(sharedTemplateName); + if(raceIt == m_racialModifiers.end()) + return; + + std::map >::iterator profIt = m_professionModifiers.find(profession); + if(profIt == m_professionModifiers.end()) + return; + + DEBUG_FATAL(raceIt->second.size() != s_numberOfAttributes, ("Bad number of attribs")); + DEBUG_FATAL(profIt->second.size() != s_numberOfAttributes, ("Bad number of attribs")); + int val = 0; + for(unsigned int i = 0; i < s_numberOfAttributes; ++i) + { + val = raceIt->second[i] + profIt->second[i]; + attribs.push_back(val); + } +} + +//---------------------------------------------------------------------- + +void PlayerCreationManager::loadRacialModifiers() +{ + DEBUG_FATAL (!s_installed, ("not installed.\n")); + std::vector modifiers; + modifiers.clear(); + + DataTable dataTable; + Iff racialModsIff(s_racialModsIffName.c_str()); + dataTable.load(racialModsIff); + + for (int row = 0; row < dataTable.getNumRows(); ++row) + { + std::string const &maleTemplate = dataTable.getStringValue("male_template", row); + std::string const &femaleTemplate = dataTable.getStringValue("female_template", row); + int health = dataTable.getIntValue("health", row); + int constitution = dataTable.getIntValue("constitution", row); + int action = dataTable.getIntValue("action", row); + int stamina = dataTable.getIntValue("stamina", row); + int mind = dataTable.getIntValue("mind", row); + int willpower = dataTable.getIntValue("willpower", row); + + modifiers.push_back(health); + modifiers.push_back(constitution); + modifiers.push_back(action); + modifiers.push_back(stamina); + modifiers.push_back(mind); + modifiers.push_back(willpower); + + std::string fullMaleTemplate = sharedTemplatePre + maleTemplate + sharedTemplatePost; + std::string fullFemaleTemplate = sharedTemplatePre + femaleTemplate + sharedTemplatePost; + + DEBUG_FATAL(modifiers.size() != s_numberOfAttributes, ("Bad number of racial modifiers")); + m_racialModifiers[fullMaleTemplate] = modifiers; + m_racialModifiers[fullFemaleTemplate] = modifiers; + modifiers.clear(); + } +} + +//---------------------------------------------------------------------- + +void PlayerCreationManager::loadProfessionModifiers() +{ + DEBUG_FATAL (!s_installed, ("not installed.\n")); + std::vector modifiers; + modifiers.clear(); + + DataTable dataTable; + Iff racialModsIff(s_professionModsIffName.c_str()); + dataTable.load(racialModsIff); + + int max_health = 0; + int max_constitution = 0; + int max_action = 0; + int max_stamina = 0; + int max_mind = 0; + int max_willpower = 0; + + for (int row = 0; row < dataTable.getNumRows(); ++row) + { + std::string const &profession = dataTable.getStringValue("profession", row); + int health = dataTable.getIntValue ("health", row); + int constitution = dataTable.getIntValue ("constitution", row); + int action = dataTable.getIntValue ("action", row); + int stamina = dataTable.getIntValue ("stamina", row); + int mind = dataTable.getIntValue ("mind", row); + int willpower = dataTable.getIntValue ("willpower", row); + + //the maximum allowed value for a stat is the maximum of the profession-maxes. + + //don't figure jedi stats into the profession maxes + //TODO if the acceptable stat window for jedi is different than other professions (and it may be), + //then we will need additional code to address that new window size + if(profession != "jedi") + { + //store off the maxes of these values, used as a factor of racial maximums + if(health > max_health) + max_health = health; + if(constitution > max_constitution) + max_constitution = constitution; + if(action > max_action) + max_action = action; + if(stamina > max_stamina) + max_stamina = stamina; + if(mind > max_mind) + max_mind = mind; + if(willpower > max_willpower) + max_willpower = willpower; + } + + modifiers.push_back(health); + modifiers.push_back(constitution); + modifiers.push_back(action); + modifiers.push_back(stamina); + modifiers.push_back(mind); + modifiers.push_back(willpower); + + DEBUG_FATAL(modifiers.size() != s_numberOfAttributes, ("Bad number of profession modifiers")); + m_professionModifiers[profession] = modifiers; + modifiers.clear(); + } +} + +//---------------------------------------------------------------------- + +/** + * + */ +void PlayerCreationManager::buildRacialMinsMaxes() +{ + DEBUG_FATAL (!s_installed, ("not installed.\n")); + std::vector > raceMinMaxes; + + const DataTable * dt = DataTableManager::getTable( + "datatables/creation/attribute_limits.iff", true); + WARNING_STRICT_FATAL(dt == NULL, ("Unable to read the " + "attribute_limits datatable")); + if (dt == NULL) + return; + + int numAttribs = dt->getNumColumns() - 1; + for (int row = 0; row < dt->getNumRows(); ++row) + { + const std::string & maleTemplate = dt->getStringValue(0, row); + const std::string & femaleTemplate = dt->getStringValue(1, row); + raceMinMaxes.clear(); + int i; + for (i = 2; i < numAttribs; i += 2) + { + raceMinMaxes.push_back(std::make_pair( + dt->getIntValue(i, row), + dt->getIntValue(i + 1, row) + )); + } + m_racialMinMaxes[sharedTemplatePre + maleTemplate + sharedTemplatePost] = raceMinMaxes; + m_racialMinMaxes[sharedTemplatePre + femaleTemplate + sharedTemplatePost] = raceMinMaxes; + m_racialTotals[sharedTemplatePre + maleTemplate + sharedTemplatePost] = dt->getIntValue(i, row); + m_racialTotals[sharedTemplatePre + femaleTemplate + sharedTemplatePost] = dt->getIntValue(i, row); + } +} + +//---------------------------------------------------------------------- + +bool PlayerCreationManager::getRacialModifiers(const std::string& sharedTemplateName, std::vector & /*OUT*/ modifiers) +{ + DEBUG_FATAL(!s_installed, ("PlayerCreationManager not installed")); + if(m_racialModifiers[sharedTemplateName].size() != s_numberOfAttributes) + return false; + modifiers = m_racialModifiers[sharedTemplateName]; + return true; +} + +//---------------------------------------------------------------------- + +bool PlayerCreationManager::getProfessionModifiers(const std::string& profession, std::vector & /*OUT*/ modifiers) +{ + DEBUG_FATAL(!s_installed, ("PlayerCreationManager not installed")); + if(m_professionModifiers[profession].size() != s_numberOfAttributes) + return false; + modifiers = m_professionModifiers[profession]; + return true; +} + +//---------------------------------------------------------------------- + +bool PlayerCreationManager::getRacialMinMaxes(const std::string& sharedTemplateName, std::vector >& /*OUT*/ minMaxes) +{ + DEBUG_FATAL(!s_installed, ("PlayerCreationManager not installed")); + if(m_racialMinMaxes[sharedTemplateName].size() != s_numberOfAttributes) + return false; + minMaxes = m_racialMinMaxes[sharedTemplateName]; + return true; +} + +//---------------------------------------------------------------------- + +bool PlayerCreationManager::getRacialTotal(const std::string & sharedTemplateName, int & /*OUT*/ total) +{ + DEBUG_FATAL(!s_installed, ("PlayerCreationManager not installed")); + if(m_racialMinMaxes[sharedTemplateName].size() != s_numberOfAttributes) + return false; + total = m_racialTotals[sharedTemplateName]; + return true; +} + +//---------------------------------------------------------------------- + +bool PlayerCreationManager::test (std::string & result, const stdvector::fwd & templateNames) +{ + DEBUG_FATAL (!s_installed, ("not installed.\n")); + UNREF (result); + + clear (); + + init (); + + UNREF (templateNames); + + return false; +} + +//---------------------------------------------------------------------- + +void PlayerCreationManager::getProfessionVector (StringVector & sv, const std::string & categoryName) +{ + DEBUG_FATAL (!s_installed, ("not installed.\n")); + + sv.clear (); + + if (s_profVector) + { + sv.reserve (s_profVector->size ()); + + for (ProfessionVector::const_iterator it = s_profVector->begin (); it != s_profVector->end (); ++it) + { + const std::string & skillName = (*it).first; + const SkillObject * const skill = SkillManager::getInstance ().getSkill (skillName); + + if (skill) + { + const SkillObject * const category = skill->findCategory (); + + if (category && (categoryName.empty () || category->getSkillName () == categoryName)) + { + sv.push_back (skillName); + } + } + else + WARNING (true, ("Invalid profession name in PlayerCreationManager: %s", skillName.c_str ())); + } + } +} + +//====================================================================== + diff --git a/engine/shared/library/sharedGame/src/shared/core/PlayerCreationManager.h b/engine/shared/library/sharedGame/src/shared/core/PlayerCreationManager.h new file mode 100644 index 00000000..a7335cb4 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/PlayerCreationManager.h @@ -0,0 +1,71 @@ +//====================================================================== +// +// PlayerCreationManager.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_PlayerCreationManager_H +#define INCLUDED_PlayerCreationManager_H + +//====================================================================== + +class PlayerCreationManager +{ +public: + static void install (bool useServerTemplate); + static void remove (); + static bool isInstalled (); + + struct EqInfo + { + int32 arrangement; + std::string sharedTemplateName; + std::string serverTemplateName; + + EqInfo (int32 i, const std::string & a, const std::string & b); + }; + + typedef stdvector::fwd SkillVector; + typedef stdvector::fwd EqVector; + typedef stdvector::fwd StringVector; + typedef stdvector::fwd AttribVector; + typedef stdmap::fwd ProfessionAttribMap; + + static void clear (); + static void init (); + + static bool test (std::string & result, const stdvector::fwd & templateNames); + + static void getProfessionVector (StringVector & sv, const std::string & categoryName); + + static bool getRacialModifiers (const std::string& sharedTemplateName, stdvector::fwd & /*OUT*/ modifiers); + static bool getProfessionModifiers (const std::string& profession, stdvector::fwd & /*OUT*/modifiers); + static bool getRacialMinMaxes (const std::string& sharedTemplateName, stdvector >::fwd & /*OUT*/ minMaxes); + static bool getRacialTotal (const std::string& sharedTemplateName, int & /*OUT*/ total); + +protected: + + static bool getDefaults(const std::string & sharedTemplateName, const std::string & profession, AttribVector & attribs, const SkillVector *& skills, const EqVector *& eq); + static void getAttribsForRaceProfession(const std::string & sharedTemplateName, const std::string & profession, AttribVector & attribs); + virtual ~PlayerCreationManager () {} + +private: + static std::string ms_filename; + + static bool initializeProfMap (const std::string & filename); + + static void loadRacialModifiers (); + static void loadProfessionModifiers(); + static void buildRacialMinsMaxes (); + +private: + static stdmap::fwd >::fwd m_racialModifiers; + static stdmap::fwd >::fwd m_professionModifiers; + static stdmap >::fwd >::fwd m_racialMinMaxes; + static stdmap::fwd m_racialTotals; +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/PlayerData.h b/engine/shared/library/sharedGame/src/shared/core/PlayerData.h new file mode 100644 index 00000000..dae238a9 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/PlayerData.h @@ -0,0 +1,29 @@ +//======================================================================== +// +// PlayerData.h +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef INCLUDED_PlayerData_H +#define INCLUDED_PlayerData_H + +namespace PlayerDataPriviledgedTitle +{ + // DO NOT DELETE OR CHANGE THE ORDER OF THESE ENUMS, + // BECAUSE THEY ARE PERSISTED IN THE DB; ADD NEW ONES + // AT THE BOTTOM + enum + { + NormalPlayer = 0, + CustomerServiceRepresentative = 1, + Developer = 2, + Warden = 3, + QualityAssurance = 4, + }; +} // namespace PlayerDataPriviledgedTitle + +//======================================================================== + +#endif // INCLUDED_PlayerData_H diff --git a/engine/shared/library/sharedGame/src/shared/core/ProsePackage.cpp b/engine/shared/library/sharedGame/src/shared/core/ProsePackage.cpp new file mode 100644 index 00000000..aebc633f --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/ProsePackage.cpp @@ -0,0 +1,24 @@ +//====================================================================== +// +// ProsePackage.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ProsePackage.h" + +//====================================================================== + +ProsePackage::ProsePackage (bool _complexGrammar) : +stringId (), +actor (), +target (), +other (), +digitInteger (0), +digitFloat (0.0f), +complexGrammar (_complexGrammar) +{ +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/ProsePackage.h b/engine/shared/library/sharedGame/src/shared/core/ProsePackage.h new file mode 100644 index 00000000..f4304d9f --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/ProsePackage.h @@ -0,0 +1,67 @@ +//====================================================================== +// +// ProsePackage.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ProsePackage_H +#define INCLUDED_ProsePackage_H + +#include "StringId.h" +#include "sharedGame/ProsePackageParticipant.h" + +class ProsePackageParticipant; + +//====================================================================== + +// See CuiStringVariables.h for %flags + +class ProsePackage +{ +public: + + typedef ProsePackageParticipant Participant; + + StringId stringId; + + Participant actor; + Participant target; + Participant other; + + int digitInteger; + float digitFloat; + + bool complexGrammar; + + explicit ProsePackage (bool _complexGrammar = false); + + bool isValid () const; + + bool operator == (const ProsePackage & rhs) const; +}; + +//---------------------------------------------------------------------- + +inline bool ProsePackage::isValid () const +{ + return !stringId.isInvalid (); +} + +//---------------------------------------------------------------------- + +inline bool ProsePackage::operator == (const ProsePackage & rhs) const +{ + return + stringId == rhs.stringId && + actor == rhs.actor && + target == rhs.target && + other == rhs.other && + digitInteger == rhs.digitInteger && + digitFloat == rhs.digitFloat && + complexGrammar == rhs.complexGrammar; +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/ProsePackageArchive.cpp b/engine/shared/library/sharedGame/src/shared/core/ProsePackageArchive.cpp new file mode 100644 index 00000000..db71d0f8 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/ProsePackageArchive.cpp @@ -0,0 +1,55 @@ +//====================================================================== +// +// ProsePackageArchive.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ProsePackageArchive.h" + +#include "Archive/Archive.h" +#include "localizationArchive/StringIdArchive.h" +#include "sharedFoundation/NetworkIdArchive.h" +#include "sharedGame/ProsePackage.h" +#include "sharedGame/ProsePackageParticipantArchive.h" +#include "unicodeArchive/UnicodeArchive.h" + +//====================================================================== + +namespace Archive +{ + //---------------------------------------------------------------------- + + void get (Archive::ReadIterator & source, ProsePackage & target) + { + get (source, target.stringId); + + get (source, target.actor); + get (source, target.target); + get (source, target.other); + + get (source, target.digitInteger); + get (source, target.digitFloat); + + get (source, target.complexGrammar); + } + + //---------------------------------------------------------------------- + + void put (ByteStream & target, const ProsePackage & source) + { + put (target, source.stringId); + + put (target, source.actor); + put (target, source.target); + put (target, source.other); + + put (target, source.digitInteger); + put (target, source.digitFloat); + + put (target, source.complexGrammar); + } +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/ProsePackageArchive.h b/engine/shared/library/sharedGame/src/shared/core/ProsePackageArchive.h new file mode 100644 index 00000000..5abaa64e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/ProsePackageArchive.h @@ -0,0 +1,26 @@ +//====================================================================== +// +// ProsePackageArchive.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ProsePackageArchive_H +#define INCLUDED_ProsePackageArchive_H + +//====================================================================== + +class ProsePackage; + +namespace Archive +{ + class ReadIterator; + class ByteStream; + + void get (Archive::ReadIterator & source, ProsePackage & target); + void put (ByteStream & target, const ProsePackage & source); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/ProsePackageParticipant.cpp b/engine/shared/library/sharedGame/src/shared/core/ProsePackageParticipant.cpp new file mode 100644 index 00000000..a3ce7adb --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/ProsePackageParticipant.cpp @@ -0,0 +1,20 @@ +//====================================================================== +// +// ProsePackageParticipant.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ProsePackageParticipant.h" + +//====================================================================== + +ProsePackageParticipant::ProsePackageParticipant () : +id (), +stringId (), +str () +{ +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/ProsePackageParticipant.h b/engine/shared/library/sharedGame/src/shared/core/ProsePackageParticipant.h new file mode 100644 index 00000000..59921fd9 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/ProsePackageParticipant.h @@ -0,0 +1,46 @@ +//====================================================================== +// +// ProsePackageParticipant.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ProsePackageParticipant_H +#define INCLUDED_ProsePackageParticipant_H + +#include "sharedFoundation/NetworkId.h" + +//====================================================================== + +class ProsePackageParticipant +{ +public: + NetworkId id; + StringId stringId; + Unicode::String str; + + bool isValid () const; + + ProsePackageParticipant (); + + bool operator== (const ProsePackageParticipant & rhs) const; +}; + +//---------------------------------------------------------------------- + +inline bool ProsePackageParticipant::isValid () const +{ + return id.isValid () || !stringId.isInvalid () || !str.empty (); +} + +//---------------------------------------------------------------------- + +inline bool ProsePackageParticipant::operator== (const ProsePackageParticipant & rhs) const +{ + return id == rhs.id && stringId == rhs.stringId && str == rhs.str; +} + + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/ProsePackageParticipantArchive.cpp b/engine/shared/library/sharedGame/src/shared/core/ProsePackageParticipantArchive.cpp new file mode 100644 index 00000000..debad5c5 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/ProsePackageParticipantArchive.cpp @@ -0,0 +1,40 @@ +//====================================================================== +// +// ProsePackageParticipantArchive.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ProsePackageParticipantArchive.h" +#include "sharedGame/ProsePackageParticipant.h" + +#include "Archive/Archive.h" +#include "localizationArchive/StringIdArchive.h" +#include "sharedFoundation/NetworkIdArchive.h" +#include "unicodeArchive/UnicodeArchive.h" + +//====================================================================== + +namespace Archive +{ + //---------------------------------------------------------------------- + + void get (Archive::ReadIterator & source, ProsePackageParticipant & target) + { + get (source, target.id); + get (source, target.stringId); + get (source, target.str); + } + + //---------------------------------------------------------------------- + + void put (ByteStream & target, const ProsePackageParticipant & source) + { + put (target, source.id); + put (target, source.stringId); + put (target, source.str); + } +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/ProsePackageParticipantArchive.h b/engine/shared/library/sharedGame/src/shared/core/ProsePackageParticipantArchive.h new file mode 100644 index 00000000..2b00c280 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/ProsePackageParticipantArchive.h @@ -0,0 +1,26 @@ +//====================================================================== +// +// ProsePackageParticipantArchive.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ProsePackageParticipantArchive_H +#define INCLUDED_ProsePackageParticipantArchive_H + +//====================================================================== + +class ProsePackageParticipant; + +namespace Archive +{ + class ReadIterator; + class ByteStream; + + void get (Archive::ReadIterator & source, ProsePackageParticipant & target); + void put (ByteStream & target, const ProsePackageParticipant & source); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/PvpData.h b/engine/shared/library/sharedGame/src/shared/core/PvpData.h new file mode 100644 index 00000000..cf1b17d7 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/PvpData.h @@ -0,0 +1,75 @@ +//======================================================================== +// +// PvpData.h +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef INCLUDED_PvpData_H +#define INCLUDED_PvpData_H + +namespace PvpStatusFlags +{ + enum + { + YouCanAttack = (1<<0), + CanAttackYou = (1<<1), + Declared = (1<<2), + HasEnemies = (1<<3), + IsPlayer = (1<<4), + IsEnemy = (1<<5), + WillBeDeclared = (1<<6), + WasDeclared = (1<<7), + YouCanHelp = (1<<8) + }; +} // namespace PvpStatusFlags + +namespace PvpData +{ + // for optimization, these crc are hard coded here (rather + // than using a crc string object to calculate the crc value); + // the words "imperial", "rebel", and "neutral" are intentionally + // put here so that someone searching for these words will end + // up here and use these methods rather than writing their own + inline uint32 getImperialFactionId() + { + return 3679112276lu; // "imperial" + } + + inline bool isImperialFactionId(uint32 crc) + { + return crc == 3679112276lu; // "imperial" + } + + inline uint32 getRebelFactionId() + { + return 370444368lu; // "rebel" + } + + inline bool isRebelFactionId(uint32 crc) + { + return crc == 370444368lu; // "rebel" + } + + inline uint32 getNeutralFactionId() + { + return 0lu; // "neutral" + } + + inline bool isNeutralFactionId(uint32 crc) + { + return crc == 0lu; // "neutral" + } + + // factional presence tracking grid size + inline int getGcwFactionalPresenceGridSize() + { + return 500; + } +} + +//======================================================================== + +#endif // INCLUDED_PvpData_H + diff --git a/engine/shared/library/sharedGame/src/shared/core/RadialMenuManager.cpp b/engine/shared/library/sharedGame/src/shared/core/RadialMenuManager.cpp new file mode 100644 index 00000000..aa61c817 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/RadialMenuManager.cpp @@ -0,0 +1,219 @@ +//====================================================================== +// +// RadialMenuManager.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/RadialMenuManager.h" + +#include "sharedFile/Iff.h" +#include "sharedFile/TreeFile.h" +#include "sharedUtility/DataTable.h" +#include "sharedNetworkMessages/ObjectMenuRequestData.h" +#include + +//====================================================================== + +namespace +{ + struct RadialMenuInfo + { + float range; + std::string commandName; + bool useRadialTarget; + }; + + typedef stdmap::fwd RangeMap; + RangeMap s_ranges; + + typedef stdmap::fwd NameMap; + NameMap s_names; + + bool s_installed = false; + + enum DtCols + { + DC_caption, + DC_range, + DC_commandName, + DC_useRadialTarget + }; + + void install () + { + DEBUG_FATAL (s_installed, ("Already installed")); + + s_installed = true; + + static const char * const filename = "datatables/player/radial_menu.iff"; + + Iff iff; + + if (!iff.open (filename, true)) + WARNING (true, ("Data file %s not available.", filename)); + else + { + + DataTable dt; + dt.load (iff); + iff.close (); + + const int numRows = dt.getNumRows (); + + for (int i = 0; i < numRows; ++i) + { + RadialMenuInfo rmi; + rmi.range = dt.getFloatValue (DC_range, i); + rmi.commandName = dt.getStringValue (DC_commandName, i), + rmi.useRadialTarget = dt.getIntValue (DC_useRadialTarget, i) != 0; + + s_ranges.insert (std::make_pair (i, rmi)); + + const std::string & caption = dt.getStringValue (DC_caption, i); + s_names.insert (std::make_pair (caption, i)); + } + } + } +} + +//---------------------------------------------------------------------- + +bool RadialMenuManager::getRangeForMenuType (int menuType, float &range) +{ + if (!s_installed) + install (); + + const RangeMap::const_iterator it = s_ranges.find (menuType); + + if (it != s_ranges.end ()) + { + const RadialMenuInfo & rmi = (*it).second; + range = rmi.range; + return true; + } + + return false; +} + +//---------------------------------------------------------------------- + +bool RadialMenuManager::getCommandForMenuType (int menuType, std::string & commandName, bool & useRadialTarget) +{ + if (!s_installed) + install (); + + const RangeMap::const_iterator it = s_ranges.find (menuType); + + if (it != s_ranges.end ()) + { + const RadialMenuInfo & rmi = (*it).second; + commandName = rmi.commandName; + useRadialTarget = rmi.useRadialTarget; + return true; + } + + return false; +} + +//---------------------------------------------------------------------- + +int RadialMenuManager::getMenuTypeByName (const std::string & name) +{ + if (!s_installed) + install (); + + const NameMap::const_iterator it = s_names.find (name); + if (it != s_names.end ()) + { + return (*it).second; + } + + return 0; +} + +//---------------------------------------------------------------------- + +int RadialMenuManager::addRootMenu (DataVector & dv, int menuType, const Unicode::String & label, bool serverNotify) +{ + if (menuType == 0) + return 0; + + const ObjectMenuRequestData * const data = findMenuByType (dv, menuType); + + if (data) + return 0; + + const uint8 id = findNextId (dv); + dv.push_back (ObjectMenuRequestData (id, 0, static_cast(menuType), label, true, serverNotify)); + + return id; +} + +//---------------------------------------------------------------------- + +int RadialMenuManager::addSubMenu (DataVector & dv, int parent, int menuType, const Unicode::String & label, bool serverNotify) +{ + if (menuType == 0 || parent == 0) + return 0; + + const ObjectMenuRequestData * const data = findMenuByType (dv, menuType); + + if (data) + return 0; + + const ObjectMenuRequestData * const root = findMenuById (dv, parent); + + if (!root) + return 0; + + const uint8 id = findNextId (dv); + dv.push_back (ObjectMenuRequestData (id, static_cast(parent), static_cast(menuType), label, true, serverNotify)); + + return id; +} + +//---------------------------------------------------------------------- + +const ObjectMenuRequestData * RadialMenuManager::findMenuByType (const DataVector & dv, int menuType) +{ + for (DataVector::const_iterator it = dv.begin (); it != dv.end (); ++it) + { + const ObjectMenuRequestData & data = *it; + if (data.m_menuItemType == menuType) + return &data; + } + + return 0; +} + +//---------------------------------------------------------------------- + +const ObjectMenuRequestData * RadialMenuManager::findMenuById (const DataVector & dv, int id) +{ + for (DataVector::const_iterator it = dv.begin (); it != dv.end (); ++it) + { + const ObjectMenuRequestData & data = *it; + if (data.m_id == id) + return &data; + } + + return 0; +} + +//---------------------------------------------------------------------- + +uint8 RadialMenuManager::findNextId (const DataVector & dv) +{ + uint8 id = 1; + for (DataVector::const_iterator it = dv.begin (); it != dv.end (); ++it) + { + const ObjectMenuRequestData & data = *it; + id = std::max (id, static_cast(data.m_id + 1)); + } + + return id; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/RadialMenuManager.h b/engine/shared/library/sharedGame/src/shared/core/RadialMenuManager.h new file mode 100644 index 00000000..3392afe8 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/RadialMenuManager.h @@ -0,0 +1,36 @@ +//====================================================================== +// +// RadialMenuManager.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_RadialMenuManager_H +#define INCLUDED_RadialMenuManager_H + +//====================================================================== + +struct ObjectMenuRequestData; + +//---------------------------------------------------------------------- + +class RadialMenuManager +{ +public: + + typedef stdvector::fwd DataVector; + + static int getMenuTypeByName (const std::string & name); + static bool getRangeForMenuType (int menuType, float &range); + static bool getCommandForMenuType (int menuType, std::string & commandName, bool & useRadialTarget); + + static int addRootMenu (DataVector & dv, int menuType, const Unicode::String & label, bool serverNotify); + static int addSubMenu (DataVector & dv, int parent, int menuType, const Unicode::String & label, bool serverNotify); + static const ObjectMenuRequestData * findMenuByType (const DataVector & dv, int menuType); + static const ObjectMenuRequestData * findMenuById (const DataVector & dv, int id); + static uint8 findNextId (const DataVector & dv); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/SetupSharedGame.cpp b/engine/shared/library/sharedGame/src/shared/core/SetupSharedGame.cpp new file mode 100644 index 00000000..92135375 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SetupSharedGame.cpp @@ -0,0 +1,219 @@ +// ====================================================================== +// +// SetupSharedGame.cpp +// Copyright 2002-2003 Sony Online Entertainment, Inc. +// All Rights Reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SetupSharedGame.h" + +#include "LocalizationManager.h" +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/TreeFile.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedGame/AppearanceManager.h" +#include "sharedGame/AssetCustomizationManager.h" +#include "sharedGame/AsteroidGenerationManager.h" +#include "sharedGame/CitizenRankDataTable.h" +#include "sharedGame/ClientCombatManagerSupport.h" +#include "sharedGame/CollectionsDataTable.h" +#include "sharedGame/CombatDataTable.h" +#include "sharedGame/ConfigSharedGame.h" +#include "sharedGame/CustomizationManager.h" +#include "sharedGame/GameLanguageManager.h" +#include "sharedGame/GameScheduler.h" +#include "sharedGame/GroundZoneManager.h" +#include "sharedGame/GuildRankDataTable.h" +#include "sharedGame/HyperspaceManager.h" +#include "sharedGame/LfgDataTable.h" +#include "sharedGame/MoodManager.h" +#include "sharedGame/MountValidScaleRangeTable.h" +#include "sharedGame/NebulaManager.h" +#include "sharedGame/ObjectUsabilityManager.h" +#include "sharedGame/PlayerFormationManager.h" +#include "sharedGame/SharedBuffBuilderManager.h" +#include "sharedGame/SharedBuildoutAreaManager.h" +#include "sharedGame/SharedImageDesignerManager.h" +#include "sharedGame/SharedSaddleManager.h" +#include "sharedGame/ShipChassis.h" +#include "sharedGame/ShipComponentAttachmentManager.h" +#include "sharedGame/ShipComponentDescriptor.h" +#include "sharedGame/ShipComponentWeaponManager.h" +#include "sharedGame/ShipSlotIdManager.h" +#include "sharedGame/ShipTurretManager.h" +#include "sharedGame/SpatialChatManager.h" +#include "sharedGame/TextManager.h" +#include "sharedGame/TravelManager.h" +#include "sharedGame/Waypoint.h" +#include "sharedGame/WearableAppearanceMap.h" + +// ====================================================================== + +namespace SetupSharedGameNamespace +{ + bool ms_installed; + + void remove (); +} + +using namespace SetupSharedGameNamespace; + +// ====================================================================== +// PUBLIC SetupSharedGame::Data +// ====================================================================== + +SetupSharedGame::Data::Data () : +m_debugBadStringsFunc (0), +m_useGameScheduler (false), +m_useMountValidScaleRangeTable (false), +m_useWearableAppearanceMap (true), +m_useClientCombatManagerSupport (false) +{ +} + +// ---------------------------------------------------------------------- + +void SetupSharedGame::Data::setUseMountValidScaleRangeTable (bool useIt) +{ + m_useMountValidScaleRangeTable = useIt; +} + +// ---------------------------------------------------------------------- + +bool SetupSharedGame::Data::getUseMountValidScaleRangeTable () const +{ + return m_useMountValidScaleRangeTable; +} + +// ---------------------------------------------------------------------- + +void SetupSharedGame::Data::setUseGameScheduler (bool useIt) +{ + m_useGameScheduler = useIt; +} + +// ---------------------------------------------------------------------- + +bool SetupSharedGame::Data::getUseGameScheduler () const +{ + return m_useGameScheduler; +} + +// ---------------------------------------------------------------------- + +void SetupSharedGame::Data::setUseWearableAppearanceMap (bool useIt) +{ + m_useWearableAppearanceMap = useIt; +} + +// ---------------------------------------------------------------------- + +bool SetupSharedGame::Data::getUseWearableAppearanceMap () const +{ + return m_useWearableAppearanceMap; +} + +// ---------------------------------------------------------------------- + +void SetupSharedGame::Data::setUseClientCombatManagerSupport(bool useIt) +{ + m_useClientCombatManagerSupport = useIt; +} + +// ---------------------------------------------------------------------- + +bool SetupSharedGame::Data::getUseClientCombatManagerSupport() const +{ + return m_useClientCombatManagerSupport; +} + +// ====================================================================== +// STATIC PUBLIC SetupSharedGame +// ====================================================================== + +void SetupSharedGame::install (const SetupSharedGame::Data& data) +{ + InstallTimer const installTimer("SetupSharedGame::install"); + + DEBUG_FATAL (ms_installed, ("SetupSharedGame::install already installed")); + ms_installed = true; + + ConfigSharedGame::install(); + + //-- TODO: add to ExitChain in install functions + SpatialChatManager::install(); + ExitChain::add(SpatialChatManager::remove, "SpatialChatManager::remove"); + + MoodManager::install(); + ExitChain::add(MoodManager::remove, "MoodManager::remove"); + + const bool displayBadStringIds = ConfigSharedGame::getDisplayBadStringIds (); + const bool debugStringIds = ConfigSharedGame::getDebugStringIds (); + Unicode::NarrowString defaultLocale(ConfigSharedGame::getDefaultLocale ()); + Unicode::UnicodeNarrowStringVector localeVector; + localeVector.push_back(defaultLocale); + + LocalizationManager::install (new TreeFile::TreeFileFactory, localeVector, debugStringIds, data.m_debugBadStringsFunc, displayBadStringIds); + ExitChain::add(LocalizationManager::remove, "LocalizationManager::remove"); + + TravelManager::install (); + + if (data.getUseGameScheduler ()) + GameScheduler::install (); + + AppearanceManager::install(); + CustomizationManager::install(); + SharedBuffBuilderManager::install(); + SharedImageDesignerManager::install(); + TextManager::install(); + GameLanguageManager::install(); + ShipChassis::install (); + ShipComponentDescriptor::install (); + ShipComponentWeaponManager::install (); + ShipComponentAttachmentManager::install (); + ShipSlotIdManager::install (); + ShipTurretManager::install (); + ObjectUsabilityManager::install(); + + AssetCustomizationManager::install ("customization/asset_customization_manager.iff"); + + if (data.getUseMountValidScaleRangeTable ()) + MountValidScaleRangeTable::install ("datatables/mount/valid_scale_range.iff"); + + if (data.getUseWearableAppearanceMap ()) + WearableAppearanceMap::install ("datatables/appearance/wearable_appearance_map.iff"); + + if (data.getUseClientCombatManagerSupport ()) + ClientCombatManagerSupport::install ("combat/combat_manager.iff"); + + AsteroidGenerationManager::install(); + NebulaManager::install(); + HyperspaceManager::install(); + PlayerFormationManager::install(); + CollectionsDataTable::install(); + LfgDataTable::install(); + GuildRankDataTable::install(); + CitizenRankDataTable::install(); + SharedBuildoutAreaManager::install(); + GroundZoneManager::install(); + + Waypoint::install(); + + SharedSaddleManager::install(); + CombatDataTable::install(); + ExitChain::add (SetupSharedGameNamespace::remove, "SetupSharedGameNamespace::remove"); +} + +// ====================================================================== +// STATIC PRIVATE SetupSharedGame +// ====================================================================== + +void SetupSharedGameNamespace::remove () +{ + DEBUG_FATAL (!ms_installed, ("SetupSharedGameNamespace::remove not installed")); + ms_installed = false; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/SetupSharedGame.h b/engine/shared/library/sharedGame/src/shared/core/SetupSharedGame.h new file mode 100644 index 00000000..dad74cf4 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SetupSharedGame.h @@ -0,0 +1,64 @@ +// ====================================================================== +// +// SetupSharedGame.h +// asommers +// +// copyright 2002, sony online entertainment +// +// ====================================================================== + +#ifndef INCLUDED_SetupSharedGame_H +#define INCLUDED_SetupSharedGame_H + +class StringId; + +// ====================================================================== + +class SetupSharedGame +{ +public: + + typedef void (*DebugBadStringsFunc) (const StringId &, bool); + + class Data + { + public: + + Data (); + + void setUseGameScheduler (bool useIt); + bool getUseGameScheduler () const; + + void setUseMountValidScaleRangeTable (bool useIt); + bool getUseMountValidScaleRangeTable () const; + + void setUseWearableAppearanceMap(bool useIt); + bool getUseWearableAppearanceMap() const; + + void setUseClientCombatManagerSupport(bool useIt); + bool getUseClientCombatManagerSupport() const; + + DebugBadStringsFunc m_debugBadStringsFunc; + + private: + + bool m_useGameScheduler; + bool m_useMountValidScaleRangeTable; + bool m_useWearableAppearanceMap; + bool m_useClientCombatManagerSupport; + }; + +public: + + static void install (const Data& data); + +private: + + SetupSharedGame (); + SetupSharedGame (const SetupSharedGame&); + SetupSharedGame& operator= (const SetupSharedGame&); +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/SharedBuffBuilderManager.cpp b/engine/shared/library/sharedGame/src/shared/core/SharedBuffBuilderManager.cpp new file mode 100644 index 00000000..5e3a6ee3 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SharedBuffBuilderManager.cpp @@ -0,0 +1,559 @@ +// ====================================================================== +// +// SharedBuffBuilderManager.cpp +// copyright (c) 2006 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SharedBuffBuilderManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/Os.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" + +#include "UnicodeUtils.h" + +#include + +// ====================================================================== + +namespace SharedBuffBuilderManagerNamespace +{ + std::map ms_sessions; + bool ms_installed = false; + const std::string ms_invalidString("invalid"); + const std::string ms_reactiveSecondChanceComponentName = "reactive_second_chance"; +} + +SharedBuffBuilderManager::BuffBuilderDataType * SharedBuffBuilderManager::ms_buffBuilderData=NULL; +using namespace SharedBuffBuilderManagerNamespace; + +// ====================================================================== + +SharedBuffBuilderManagerSession::SharedBuffBuilderManagerSession() +: bufferId(), + recipientId(), + startingTime(0), + bufferRequiredCredits(0), + accepted(false), + buffComponents() +{ +} + +//---------------------------------------------------------------------- + +SharedBuffBuilderManagerSession::SharedBuffBuilderManagerSession(BuffBuilderChangeMessage const & message) +: bufferId(message.getBufferId()), + recipientId(message.getRecipientId()), + startingTime(message.getStartingTime()), + bufferRequiredCredits(message.getBufferRequiredCredits()), + accepted(message.getAccepted()), + buffComponents(message.getBuffComponents()) +{ +} + +bool SharedBuffBuilderManagerSession::addBuffComponent(std::string const& name, int expertiseModifier) +{ + const int maxValue = SharedBuffBuilderManager::getMaxTimesAppliedForRecordName(name); + int value = 1; + + if(buffComponents.find(name) != buffComponents.end()) + { + if(buffComponents[name].first < maxValue) + { + value = buffComponents[name].first + 1; + } + else + { + return false; + } + } + + buffComponents[name].first = value; + buffComponents[name].second = expertiseModifier; + return true; +} + +void SharedBuffBuilderManagerSession::removeBuffComponent(std::string const& name) +{ + std::map >::iterator pos; + pos = buffComponents.find(name); + if(pos != buffComponents.end()) + { + if(pos->second.first > 1) + { + buffComponents[name].first = pos->second.first - 1; + } + else + { + buffComponents.erase(pos); + } + } +} + +void SharedBuffBuilderManagerSession::clearBuffComponents() +{ + buffComponents.clear(); +} + +int SharedBuffBuilderManagerSession::getBuffComponentValue(std::string const& name) +{ + if(buffComponents.find(name) != buffComponents.end()) + { + return buffComponents[name].first; + } + + return 0; +} + +// ====================================================================== + +void SharedBuffBuilderManager::install () +{ + InstallTimer const installTimer("SharedBuffBuilderManager::install "); + + DEBUG_FATAL(ms_installed, ("SharedBuffBuilderManager::install - Already Installed")); + ms_installed = true; + + ExitChain::add(SharedBuffBuilderManager::remove, "SharedBuffBuilderManager::remove", 0, false); + + ms_buffBuilderData = new BuffBuilderDataType; + + { + DataTable const * const buffBuilderDataTable = DataTableManager::getTable("datatables/buff/buff_builder.iff", true); + FATAL(!buffBuilderDataTable,("buff_builder data table could not be opened.")); + int const numRows = buffBuilderDataTable->getNumRows(); + for (int row=0; rowgetStringValue("NAME",row)); + data.m_category = Unicode::getTrim(buffBuilderDataTable->getStringValue("CATEGORY",row)); + data.m_affects = Unicode::getTrim(buffBuilderDataTable->getStringValue("AFFECTS",row)); + data.m_maxTimesApplied = buffBuilderDataTable->getIntValue("MAX_TIMES_APPLIED",row); + data.m_cost = buffBuilderDataTable->getIntValue("COST",row); + data.m_affectAmount = buffBuilderDataTable->getIntValue("AFFECT_AMOUNT",row); + data.m_requiredExpertise = Unicode::getTrim(buffBuilderDataTable->getStringValue("REQUIRED_EXPERTISE",row)); + + (*ms_buffBuilderData)[data.m_name] = data; + } + DataTableManager::close("datatables/buff/buff_builder.iff"); + } +} + +//---------------------------------------------------------------------- + +void SharedBuffBuilderManager::remove () +{ + DEBUG_FATAL(!ms_installed, ("SharedImageDesignerManager::remove - Not Installed")); + delete ms_buffBuilderData; + ms_buffBuilderData = 0; + ms_installed = false; +} + +//---------------------------------------------------------------------- + +void SharedBuffBuilderManager::startSession(SharedBuffBuilderManager::Session const & session) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::startSession SharedBuffBuilderManager not installed")); + return; + } + + NetworkId const & bufferId = session.bufferId; + if(isCurrentlyBuffing(bufferId)) + { + endSession(bufferId); + } + ms_sessions[bufferId] = session; +} + +//---------------------------------------------------------------------- + +void SharedBuffBuilderManager::updateSession(SharedBuffBuilderManager::Session const & session) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::updateSession - SharedBuffBuilderManager not installed")); + return; + } + + ms_sessions[session.bufferId] = session; +} + +//---------------------------------------------------------------------- + +bool SharedBuffBuilderManager::getSession(NetworkId const & bufferId, SharedBuffBuilderManager::Session & /*OUT*/ session) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::getSession - SharedBuffBuilderManager not installed")); + return false; + } + + std::map::const_iterator i = ms_sessions.find(bufferId); + if(i != ms_sessions.end()) + { + session = i->second; + return true; + } + else + return false; +} + +//---------------------------------------------------------------------- + +bool SharedBuffBuilderManager::isCurrentlyBuffing(NetworkId const & bufferId) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::isCurrentlyBuffing - SharedBuffBuilderManager not installed")); + return false; + } + + std::map::const_iterator i = ms_sessions.find(bufferId); + return i != ms_sessions.end(); +} + +//---------------------------------------------------------------------- + +bool SharedBuffBuilderManager::isCurrentlyBeingBuffed(NetworkId const & recipientId) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::isCurrentlyBeingBuffed - SharedBuffBuilderManager not installed")); + return false; + } + + for(std::map::const_iterator i = ms_sessions.begin(); i != ms_sessions.end(); ++i) + { + if(i->second.recipientId == recipientId) + return true; + } + return false; +} + +//---------------------------------------------------------------------- + +void SharedBuffBuilderManager::endSession(NetworkId const & bufferId) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::endSession - SharedBuffBuilderManager not installed")); + return; + } + + if(!isCurrentlyBuffing(bufferId)) + return; + + IGNORE_RETURN(ms_sessions.erase(bufferId)); +} + +//---------------------------------------------------------------------- + +time_t SharedBuffBuilderManager::getTimeRemaining(NetworkId const & bufferId) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::getTimeRemaining - SharedBuffBuilderManager not installed")); + return 0; + } + + if(!isCurrentlyBuffing(bufferId)) + return 0; + + Session session; + bool const result = getSession(bufferId, session); + if(!result) + return 0; + + if(session.startingTime == 0) + return 0; + + time_t const elapsedTime = Os::getRealSystemTime() - session.startingTime; + + time_t endTime = 0; + + time_t timeLeft = (endTime - session.startingTime) - elapsedTime; + if(timeLeft < 0) + timeLeft = 0; + return timeLeft; +} + +//---------------------------------------------------------------------- + +bool SharedBuffBuilderManager::isSessionValid(SharedBuffBuilderManager::Session const & session /*, SharedBuffBuilderManager::SkillMods const & designerSkills, std::string const & recipientSpeciesGender, CustomizationData * const customizationDataCreature, CustomizationData * const customizationDataHair*/) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::isSessionValid - SharedBuffBuilderManager not installed")); + return false; + } + + //check time left + time_t const timeLeft = getTimeRemaining(session.bufferId); + if(timeLeft > 0) + { + DEBUG_REPORT_LOG(true /* ju_todo: add a config option */, ("ImageDesigner: Designer[%s] can't change Recipient[%s], not enough time has elapsed", session.bufferId.getValueString().c_str(), session.recipientId.getValueString().c_str())); + return false; + } + + return true; +} + +//---------------------------------------------------------------------- + +void SharedBuffBuilderManager::populateChangeMessage(SharedBuffBuilderManager::Session const & session, BuffBuilderChangeMessage & /*OUT*/ msg) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::populateChangeMessage - SharedBuffBuilderManager not installed")); + return; + } + + msg.setBufferId(session.bufferId); + msg.setRecipientId(session.recipientId); + msg.setStartingTime(session.startingTime); + msg.setOrigin(BuffBuilderChangeMessage::O_BUFFER); + msg.setBufferRequiredCredits(session.bufferRequiredCredits); + msg.setAccepted(session.accepted); + msg.setBuffComponents(session.buffComponents); +} + +//---------------------------------------------------------------------- + +int SharedBuffBuilderManager::computeAdjustedAffectAmount(const std::string& recordName,int affectAmount,int expertiseModifier) +{ + int value = affectAmount; + + const std::string& categoryName = SharedBuffBuilderManager::getCategoryNameForRecordName(recordName); + + if(categoryName == "attributes" + || categoryName == "resistances" + || categoryName == "trade" + ) + { + value += ((value * expertiseModifier)/100); + } + else if(categoryName == "combat") + { + value += expertiseModifier; + } + else if(recordName == ms_reactiveSecondChanceComponentName) + { + value += expertiseModifier; + } + + return value; +} + +//---------------------------------------------------------------------- + +// datatable stuff + +SharedBuffBuilderManager::BuffBuilderDataTypeRecord::BuffBuilderDataTypeRecord() : +m_name(), +m_category(), +m_affects(), +m_maxTimesApplied(0), +m_cost(0), +m_affectAmount(0), +m_requiredExpertise() +{ +} + +//---------------------------------------------------------------------- + +const std::string& SharedBuffBuilderManager::getCategoryNameForRecordName(const std::string& recordName) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::getCategoryNameForRecordName - SharedBuffBuilderManager not installed")); + return ms_invalidString; + } + + if(ms_installed && ms_buffBuilderData) + { + BuffBuilderDataType::const_iterator const i = ms_buffBuilderData->find(recordName); + if(i != ms_buffBuilderData->end()) + { + BuffBuilderDataTypeRecord const &data = i->second; + return data.m_category; + } + } + + return ms_invalidString; +} + +//---------------------------------------------------------------------- + +const std::string& SharedBuffBuilderManager::getAffectsNameForRecordName(const std::string& recordName) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::getAffectsNameForRecordName - SharedBuffBuilderManager not installed")); + return ms_invalidString; + } + + if(ms_installed && ms_buffBuilderData) + { + BuffBuilderDataType::const_iterator const i = ms_buffBuilderData->find(recordName); + if(i != ms_buffBuilderData->end()) + { + BuffBuilderDataTypeRecord const &data = i->second; + return data.m_affects; + } + } + + return ms_invalidString; +} + +//---------------------------------------------------------------------- + +int SharedBuffBuilderManager::getMaxTimesAppliedForRecordName(const std::string& recordName) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::getMaxTimesAppliedForRecordName - SharedBuffBuilderManager not installed")); + return 0; + } + + if(ms_installed && ms_buffBuilderData) + { + BuffBuilderDataType::const_iterator const i = ms_buffBuilderData->find(recordName); + if(i != ms_buffBuilderData->end()) + { + BuffBuilderDataTypeRecord const &data = i->second; + return data.m_maxTimesApplied; + } + } + + return 0; +} + +//---------------------------------------------------------------------- + +int SharedBuffBuilderManager::getCostForRecordName(const std::string& recordName) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::getCostForRecordName - SharedBuffBuilderManager not installed")); + return 0; + } + + if(ms_installed && ms_buffBuilderData) + { + BuffBuilderDataType::const_iterator const i = ms_buffBuilderData->find(recordName); + if(i != ms_buffBuilderData->end()) + { + BuffBuilderDataTypeRecord const &data = i->second; + return data.m_cost; + } + } + + return 0; +} + +//---------------------------------------------------------------------- + +int SharedBuffBuilderManager::getAffectAmountForRecordName(const std::string& recordName) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::getAffectAmountForRecordName - SharedBuffBuilderManager not installed")); + return 0; + } + + if(ms_installed && ms_buffBuilderData) + { + BuffBuilderDataType::const_iterator const i = ms_buffBuilderData->find(recordName); + if(i != ms_buffBuilderData->end()) + { + BuffBuilderDataTypeRecord const &data = i->second; + return data.m_affectAmount; + } + } + + return 0; +} + +//---------------------------------------------------------------------- + +const std::string& SharedBuffBuilderManager::getRequiredExpertiseNameForRecordName(const std::string& recordName) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::getRequiredExpertiseNameForRecordName - SharedBuffBuilderManager not installed")); + return ms_invalidString; + } + + if(ms_installed && ms_buffBuilderData) + { + BuffBuilderDataType::const_iterator const i = ms_buffBuilderData->find(recordName); + if(i != ms_buffBuilderData->end()) + { + BuffBuilderDataTypeRecord const &data = i->second; + return data.m_requiredExpertise; + } + } + + return ms_invalidString; +} + +//---------------------------------------------------------------------- + +void SharedBuffBuilderManager::getRecordNames(std::vector& recordNames) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::getRecordNames - SharedBuffBuilderManager not installed")); + return; + } + + if(ms_installed && ms_buffBuilderData) + { + BuffBuilderDataType::iterator i; + for(i = ms_buffBuilderData->begin(); i != ms_buffBuilderData->end(); ++i) + { + BuffBuilderDataTypeRecord const &data = i->second; + recordNames.push_back(data.m_name); + } + } + + return; +} + +//---------------------------------------------------------------------- + +void SharedBuffBuilderManager::getCategoryNames(std::vector& categoryNames) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedBuffBuilderManager::getCategoryNames - SharedBuffBuilderManager not installed")); + return; + } + + if(ms_installed && ms_buffBuilderData) + { + BuffBuilderDataType::iterator i; + std::vector::iterator j; + for(i = ms_buffBuilderData->begin(); i != ms_buffBuilderData->end(); ++i) + { + BuffBuilderDataTypeRecord const &data = i->second; + j = find(categoryNames.begin(),categoryNames.end(),data.m_category); + if(j == categoryNames.end()) + { + categoryNames.push_back(data.m_category); + } + } + } + + return; +} + +//---------------------------------------------------------------------- + diff --git a/engine/shared/library/sharedGame/src/shared/core/SharedBuffBuilderManager.h b/engine/shared/library/sharedGame/src/shared/core/SharedBuffBuilderManager.h new file mode 100644 index 00000000..c373f4c9 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SharedBuffBuilderManager.h @@ -0,0 +1,102 @@ +// ====================================================================== +// +// SharedBuffBuilderManager.h +// copyright (c) 2006 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_SharedBuffBuilderManager_H +#define INCLUDED_SharedBuffBuilderManager_H + +// ====================================================================== + +#include "sharedFoundation/NetworkId.h" +#include "sharedNetworkMessages/BuffBuilderChangeMessage.h" + +#include + +//----------------------------------------------------------------------- + +class SharedBuffBuilderManagerSession +{ +public: + NetworkId bufferId; + NetworkId recipientId; + time_t startingTime; + int bufferRequiredCredits; + bool accepted; + std::map > buffComponents; // "buff_type", + + SharedBuffBuilderManagerSession(); + SharedBuffBuilderManagerSession(BuffBuilderChangeMessage const & message); + + bool addBuffComponent(std::string const& name, int expertiseModifier); + void removeBuffComponent(std::string const& name); + void clearBuffComponents(); + int getBuffComponentValue(std::string const& name); +}; + +class SharedBuffBuilderManager +{ +public: + + typedef SharedBuffBuilderManagerSession Session; + + struct BuffBuilderDataTypeRecord + { + + public: + BuffBuilderDataTypeRecord(); + + public: + std::string m_name; + std::string m_category; + std::string m_affects; + int m_maxTimesApplied; + int m_cost; + int m_affectAmount; + std::string m_requiredExpertise; + }; + + typedef stdmap::fwd BuffBuilderDataType; + static BuffBuilderDataType* ms_buffBuilderData; + +public: + static void install(); + static void startSession(Session const & session); + static void updateSession(Session const & session); + static void endSession(NetworkId const & designerId); + static bool getSession(NetworkId const & designerId, Session & /*OUT*/ session); + static bool isCurrentlyBuffing(NetworkId const & designerId); + static bool isCurrentlyBeingBuffed(NetworkId const & recipientId); + static time_t getTimeRemaining(NetworkId const & designerId); + static bool isSessionValid(Session const & session); + static void populateChangeMessage(Session const & session, BuffBuilderChangeMessage & /*OUT*/ msg); + static int computeAdjustedAffectAmount(const std::string& recordName,int affectAmount,int expertiseModifier); + + //--- + // ms_buffBuilderData accessors + //--- + + // via recordName + static const std::string& getCategoryNameForRecordName(const std::string& recordName); + static const std::string& getAffectsNameForRecordName(const std::string& recordName); + static int getMaxTimesAppliedForRecordName(const std::string& recordName); + static int getCostForRecordName(const std::string& recordName); + static int getAffectAmountForRecordName(const std::string& recordName); + static const std::string& getRequiredExpertiseNameForRecordName(const std::string& recordName); + + static void getRecordNames(std::vector& recordNames); + static void getCategoryNames(std::vector& categoryNames); +private: + //disabled + SharedBuffBuilderManager (SharedBuffBuilderManager const & rhs); + SharedBuffBuilderManager & operator= (SharedBuffBuilderManager const & rhs); + +private: + static void remove(); +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/SharedBuildoutAreaManager.cpp b/engine/shared/library/sharedGame/src/shared/core/SharedBuildoutAreaManager.cpp new file mode 100644 index 00000000..792cf3c2 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SharedBuildoutAreaManager.cpp @@ -0,0 +1,653 @@ +// ====================================================================== +// +// SharedBuildoutAreaManager.cpp +// +// Copyright 2005 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SharedBuildoutAreaManager.h" + +#include "Archive/Archive.h" +#include "sharedFile/Iff.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedMathArchive/QuaternionArchive.h" +#include "sharedMathArchive/VectorArchive.h" +#include "sharedTerrain/ProceduralTerrainAppearance.h" +#include "sharedTerrain/TerrainObject.h" +#include "sharedUtility/DataTable.h" + +// ====================================================================== + +namespace SharedBuildoutAreaManagerNamespace +{ + // ---------------------------------------------------------------------- + + static bool s_installed = false; + + // ---------------------------------------------------------------------- + typedef std::map > BuildoutAreaNameMap; + typedef std::map BoolNameMap; + + static std::vector s_buildoutScenes; + static BoolNameMap s_adjustMapCoordinates; + static BuildoutAreaNameMap s_buildoutAreas; + + static std::string s_currentScene; + static const std::vector *s_buildoutAreasForCurrentScene; + static const std::vector s_emptyBuildoutAreas; + + static std::string cms_sceneAndAreaDelimeter("__"); + + // ---------------------------------------------------------------------- + + static float getPlanetEdgeSize() + { + TerrainObject const * const terrain = TerrainObject::getInstance (); + if (terrain) + { + ProceduralTerrainAppearance const * const pta = dynamic_cast(terrain->getAppearance ()); + if (pta) + return pta->getMapWidthInMeters(); + } + //return default planet size + return 16384.0f; + } + + // ---------------------------------------------------------------------- +} +using namespace SharedBuildoutAreaManagerNamespace; + +// ====================================================================== + +int BuildoutArea::getSharedBaseId() const +{ + return -(areaIndex+1)*30000; +} + +// ---------------------------------------------------------------------- + +int BuildoutArea::getSharedTopId() const +{ + return getSharedBaseId()+29999; +} + +// ---------------------------------------------------------------------- + +int BuildoutArea::getServerBaseId() const +{ + return -(areaIndex+1)*30000-1000000; +} + +// ---------------------------------------------------------------------- + +int BuildoutArea::getServerTopId() const +{ + return getServerBaseId()+29999; +} + +// ---------------------------------------------------------------------- + +bool BuildoutArea::isLocationInside(float x, float z) const +{ + return rect.isWithin(x, z); +} + +// ---------------------------------------------------------------------- + +float BuildoutArea::getXCenterPoint(bool allowComposite) const +{ + if (allowComposite && getUseComposite()) + return compositeRect.x0 + ((compositeRect.x1 - compositeRect.x0) * 0.5f); + + return rect.x0 + ((rect.x1 - rect.x0) * 0.5f); +} + +// ---------------------------------------------------------------------- + +float BuildoutArea::getZCenterPoint(bool allowComposite) const +{ + if (allowComposite && getUseComposite()) + return compositeRect.y0 + ((compositeRect.y1 - compositeRect.y0) * 0.5f); + + return rect.y0 + ((rect.y1 - rect.y0) * 0.5f); +} + +//---------------------------------------------------------------------- + +Rectangle2d const & BuildoutArea::getRectangle(bool allowComposite) const +{ + if (allowComposite && getUseComposite()) + return compositeRect; + return rect; +} + +//---------------------------------------------------------------------- + +Vector2d BuildoutArea::getSize(bool allowComposite) const +{ + Rectangle2d const & r = getRectangle(allowComposite); + return Vector2d(r.getWidth(), r.getHeight()); +} + +//---------------------------------------------------------------------- + +bool BuildoutArea::getUseComposite() const +{ + return !compositeName.empty(); +} + +//---------------------------------------------------------------------- + +Vector BuildoutArea::getRelativePosition(Vector const & pos_w, bool allowComposite) const +{ + Vector resultPos; + + resultPos.x = pos_w.x - getXCenterPoint(allowComposite); + resultPos.y = pos_w.y; + resultPos.z = pos_w.z - getZCenterPoint(allowComposite); + + return resultPos; +} + +//---------------------------------------------------------------------- + +std::string const & BuildoutArea::getRequiredEventName() const +{ + return requiredEventName; +} + +// ====================================================================== + +bool SharedBuildoutAreaManager::isBuildoutScene(std::string const & sceneName) +{ + for (int i = 0; i < static_cast(s_buildoutScenes.size()); ++i) + { + if (s_buildoutScenes[i] == sceneName) + { + return true; + } + } + + return false; +} + +//---------------------------------------------------------------------- + +void SharedBuildoutAreaManager::install() +{ + s_installed = true; + + s_buildoutScenes.clear(); + s_adjustMapCoordinates.clear(); + + s_buildoutAreasForCurrentScene=&s_emptyBuildoutAreas; + s_buildoutAreas.clear(); + + Iff iff; + if (iff.open("datatables/buildout/buildout_scenes.iff", true)) + { + DataTable buildoutScenesTable; + buildoutScenesTable.load(iff); + + int const sceneCount = buildoutScenesTable.getNumRows(); + for (int sceneRow = 0; sceneRow < sceneCount; ++sceneRow) + { + const std::string &sceneNameTemp = buildoutScenesTable.getStringValue("sceneName", sceneRow); + s_buildoutScenes.push_back(sceneNameTemp); + const std::string &sceneName = s_buildoutScenes.back(); + + const int adjustMapCoordinates = buildoutScenesTable.getIntValue("adjust_map_coordinates", sceneRow); + + s_adjustMapCoordinates.insert(std::make_pair(sceneName, adjustMapCoordinates!=0)); + } + } + + const int numBuildoutScenes = static_cast(s_buildoutScenes.size()); + for (int i = 0; i < numBuildoutScenes; ++i) + { + char filename[256]; + std::string const & buildoutScene = s_buildoutScenes[i]; + + IGNORE_RETURN(snprintf(filename, sizeof(filename)-1, "datatables/buildout/areas_%s.iff", buildoutScene.c_str())); + + Iff iff; + if (iff.open(filename, true)) + { + DataTable areaListTable; + areaListTable.load(iff); + + std::vector areasForScene; + + int const areaCount = areaListTable.getNumRows(); + for (int areaRow = 0; areaRow < areaCount; ++areaRow) + { + areasForScene.push_back(); + BuildoutArea &buildoutArea = areasForScene.back(); + buildoutArea.areaIndex = i*100+areaRow; + buildoutArea.areaName = areaListTable.getStringValue("area", areaRow); + buildoutArea.rect.x0 = areaListTable.getFloatValue("x1", areaRow); + buildoutArea.rect.y0 = areaListTable.getFloatValue("z1", areaRow); + buildoutArea.rect.x1 = areaListTable.getFloatValue("x2", areaRow); + buildoutArea.rect.y1 = areaListTable.getFloatValue("z2", areaRow); + buildoutArea.useClipRect = areaListTable.getIntValue("useClipRect", areaRow) != 0; + buildoutArea.clipRect.x0 = areaListTable.getFloatValue("clipRectX1", areaRow); + buildoutArea.clipRect.y0 = areaListTable.getFloatValue("clipRectZ1", areaRow); + buildoutArea.clipRect.x1 = areaListTable.getFloatValue("clipRectX2", areaRow); + buildoutArea.clipRect.y1 = areaListTable.getFloatValue("clipRectZ2", areaRow); + + if (buildoutArea.useClipRect) + { + //-- if a zero clip rect was supplied, just use the buildout rect + if (buildoutArea.clipRect.getWidth() <= 0.0f || buildoutArea.clipRect.getHeight() <= 0.0f) + buildoutArea.clipRect = buildoutArea.rect; + } + + buildoutArea.clipEnvironmentFlags = areaListTable.getIntValue("envFlags", areaRow); + buildoutArea.clipEnvironmentFlags &= ~areaListTable.getIntValue("envFlagsExclude", areaRow); + + buildoutArea.compositeName = areaListTable.getStringValue("compositeName", areaRow); + if (!buildoutArea.compositeName.empty()) + { + buildoutArea.compositeRect.x0 = areaListTable.getFloatValue("compositeX1", areaRow); + buildoutArea.compositeRect.y0 = areaListTable.getFloatValue("compositeZ1", areaRow); + buildoutArea.compositeRect.x1 = areaListTable.getFloatValue("compositeX2", areaRow); + buildoutArea.compositeRect.y1 = areaListTable.getFloatValue("compositeZ2", areaRow); + } + + buildoutArea.isolated = areaListTable.getIntValue("isolated", areaRow) != 0; + buildoutArea.allowMap = areaListTable.getIntValue("allowMap", areaRow) != 0; + buildoutArea.allowRadarTerrain = areaListTable.getIntValue("allowRadarTerrain", areaRow) != 0; + + buildoutArea.internalBuildoutArea = areaListTable.getIntValue("internal", areaRow) != 0; + + buildoutArea.requiredEventName = areaListTable.getStringValue("eventRequired", areaRow); + } + + s_buildoutAreas[buildoutScene] = areasForScene; + } + else + { + WARNING(true, ("SharedBuildoutAreaManager unable to load areas file [%s]", filename)); + } + } + + ExitChain::add(remove, "SharedBuildoutAreaManager::remove"); +} + + +//---------------------------------------------------------------------- + +void SharedBuildoutAreaManager::remove() +{ + s_buildoutScenes.clear(); + s_adjustMapCoordinates.clear(); + s_buildoutAreasForCurrentScene=&s_emptyBuildoutAreas; + s_buildoutAreas.clear(); +} + +//---------------------------------------------------------------------- + +void SharedBuildoutAreaManager::load(std::string const & sceneName) +{ + if (sceneName == s_currentScene) + return; + + s_currentScene = sceneName; + + BuildoutAreaNameMap::const_iterator const it = s_buildoutAreas.find(sceneName); + + if (it != s_buildoutAreas.end()) + { + s_buildoutAreasForCurrentScene = &(it->second); + } + else + { + s_buildoutAreasForCurrentScene=&s_emptyBuildoutAreas; + } +} + +// ---------------------------------------------------------------------- + +std::vector const &SharedBuildoutAreaManager::getBuildoutAreasForCurrentScene() +{ + return *s_buildoutAreasForCurrentScene; +} + +// ---------------------------------------------------------------------- + +std::string SharedBuildoutAreaManager::getBuildoutNameForPosition(std::string const & sceneName, Vector const & location_w, bool ignoreInternal, bool ignoreNonActiveEvents) +{ + BuildoutArea const * const ba = findBuildoutAreaAtPosition(sceneName, location_w.x, location_w.z, ignoreInternal, ignoreNonActiveEvents); + + if (NULL != ba) + return sceneName + cms_sceneAndAreaDelimeter + ba->areaName; + + return sceneName; +} + +// ---------------------------------------------------------------------- + +Vector SharedBuildoutAreaManager::getRelativePositionInArea(std::string const & buildoutName, Vector const & location_w, bool ignoreInternal, bool ignoreNonActiveEvents) +{ + Vector resultPos = location_w; + std::pair const & sceneAndArea = parseEncodedBuildoutName(buildoutName); + if (!sceneAndArea.second.empty()) + { + if (s_buildoutAreas.find(sceneAndArea.first) != s_buildoutAreas.end()) + { + std::vector const & areas = s_buildoutAreas[sceneAndArea.first]; + for(std::vector::const_iterator i = areas.begin(); i != areas.end(); ++i) + { + BuildoutArea const & boa = *i; + + if (ignoreInternal && boa.internalBuildoutArea) + continue; + + if(ignoreNonActiveEvents && !boa.requiredEventName.empty()) // Eventually this needs to query the scheduler system and see if the event is currently active. + continue; + + if(boa.isLocationInside(location_w.x, location_w.z) && boa.areaName == sceneAndArea.second) + { + return boa.getRelativePosition(location_w, true); + } + } + } + } + + + return resultPos; +} + +// ---------------------------------------------------------------------- + +Vector SharedBuildoutAreaManager::getCenterPositionInArea(const char *buildoutName, Vector const & location_w) +{ + Vector resultPos(Vector::zero); + if (buildoutName && *buildoutName) + { + std::pair sceneAndArea = parseEncodedBuildoutName(buildoutName); + if (!sceneAndArea.second.empty()) + { + if (s_buildoutAreas.find(sceneAndArea.first.c_str()) != s_buildoutAreas.end()) + { + std::vector const & areas = s_buildoutAreas[sceneAndArea.first.c_str()]; + for(std::vector::const_iterator i = areas.begin(); i != areas.end(); ++i) + { + if (i->isLocationInside(location_w.x, location_w.z) && i->areaName == sceneAndArea.second) + { + resultPos.x = i->getXCenterPoint(false); + resultPos.y = 0.0f; + resultPos.z = i->getZCenterPoint(false); + break; + } + } + } + } + } + + return resultPos; +} + +// ---------------------------------------------------------------------- + +//Vector SharedBuildoutAreaManager::getRelativePositionFromWorldSpaceToPlayerSpace(std::string const & zoneName, Vector const & playerPosition_w, Vector const & worldPosition_w) +//{ +// Vector localPosition(getRelativePositionInArea(zoneName, worldPosition_w)); +// localPosition += getCenterPositionInArea(zoneName, playerPosition_w); + +// return localPosition; +//} + +// ---------------------------------------------------------------------- + +SharedBuildoutAreaManager::StringPair SharedBuildoutAreaManager::parseEncodedBuildoutName(std::string const & encodedBuildoutName) +{ + const size_t underscore_pos = encodedBuildoutName.find(cms_sceneAndAreaDelimeter); + if(underscore_pos == encodedBuildoutName.npos) + { + //we're on a regular planet, return (planet_name, "") + return std::make_pair(encodedBuildoutName, std::string()); + } + + std::string const & sceneName = encodedBuildoutName.substr (0, underscore_pos); + std::string const & areaName = encodedBuildoutName.substr (underscore_pos + cms_sceneAndAreaDelimeter.size()); + return std::make_pair(sceneName, areaName); +} + +// ---------------------------------------------------------------------- + +std::string SharedBuildoutAreaManager::createEncodedBuildoutName(std::string const & sceneName, std::string const & zoneName) +{ + if (!zoneName.empty()) + return sceneName + cms_sceneAndAreaDelimeter + zoneName; + + return sceneName; +} + +// ---------------------------------------------------------------------- + +Vector2d SharedBuildoutAreaManager::getBuildoutAreaSize(std::string const & encodedBuildoutName, bool allowComposite) +{ + float const planetEdgeSize = getPlanetEdgeSize(); + std::pair sceneAndArea = parseEncodedBuildoutName(encodedBuildoutName); + if(sceneAndArea.second.empty()) + { + return Vector2d(planetEdgeSize, planetEdgeSize); + } + else + { + if (s_buildoutAreas.find(sceneAndArea.first) != s_buildoutAreas.end()) + { + std::vector const & areas = s_buildoutAreas[sceneAndArea.first]; + for(std::vector::const_iterator i = areas.begin(); i != areas.end(); ++i) + { + BuildoutArea const & b = *i; + + //return the size of the named area + if(b.areaName == sceneAndArea.second) + { + return b.getSize(allowComposite); + } + } + } + } + + //failure case, return whole planet size + return Vector2d(planetEdgeSize, planetEdgeSize); +} + +// ---------------------------------------------------------------------- + +bool SharedBuildoutAreaManager::adjustMapCoordinatesForScene(std::string const & sceneName) +{ + BoolNameMap::const_iterator const i = s_adjustMapCoordinates.find(sceneName); + if(i != s_adjustMapCoordinates.end()) + return i->second; + else + return false; +} + +// ====================================================================== + +void Archive::get(Archive::ReadIterator &source, ServerBuildoutAreaRow &target) +{ + Archive::get(source, target.id); + Archive::get(source, target.container); + Archive::get(source, target.serverTemplateCrc); + Archive::get(source, target.cellIndex); + Archive::get(source, target.position); + Archive::get(source, target.orientation); + Archive::get(source, target.scripts); + Archive::get(source, target.objvars); +} + +// ---------------------------------------------------------------------- + +void Archive::put(Archive::ByteStream &target, ServerBuildoutAreaRow const &source) +{ + Archive::put(target, source.id); + Archive::put(target, source.container); + Archive::put(target, source.serverTemplateCrc); + Archive::put(target, source.cellIndex); + Archive::put(target, source.position); + Archive::put(target, source.orientation); + Archive::put(target, source.scripts); + Archive::put(target, source.objvars); +} + +// ---------------------------------------------------------------------- + +void Archive::get(Archive::ReadIterator &source, ClientBuildoutAreaRow &target) +{ + Archive::get(source, target.id); + Archive::get(source, target.container); + Archive::get(source, target.type); + Archive::get(source, target.sharedTemplateCrc); + Archive::get(source, target.cellIndex); + Archive::get(source, target.position); + Archive::get(source, target.orientation); + Archive::get(source, target.radius); + Archive::get(source, target.portalLayoutCrc); +} + +// ---------------------------------------------------------------------- + +void Archive::put(Archive::ByteStream &target, ClientBuildoutAreaRow const &source) +{ + Archive::put(target, source.id); + Archive::put(target, source.container); + Archive::put(target, source.type); + Archive::put(target, source.sharedTemplateCrc); + Archive::put(target, source.cellIndex); + Archive::put(target, source.position); + Archive::put(target, source.orientation); + Archive::put(target, source.radius); + Archive::put(target, source.portalLayoutCrc); +} + +//---------------------------------------------------------------------- + +SharedBuildoutAreaManager::BuildoutAreaVector const * SharedBuildoutAreaManager::findBuildoutAreasForScene(std::string const & sceneName) +{ + BuildoutAreaNameMap::const_iterator const it = s_buildoutAreas.find(sceneName); + + if (it != s_buildoutAreas.end()) + { + return &it->second; + } + return NULL; +} + +//---------------------------------------------------------------------- + +BuildoutArea const * SharedBuildoutAreaManager::findBuildoutAreaAtPosition(std::string const & sceneId, float x, float z, bool ignoreInternal, bool ignoreNonActiveEvents) +{ + BuildoutAreaVector const * const bav = findBuildoutAreasForScene(sceneId); + + if (NULL == bav) + return NULL; + + for (BuildoutAreaVector::const_iterator it = bav->begin(); it != bav->end(); ++it) + { + BuildoutArea const & buildoutArea = *it; + + if (ignoreInternal && buildoutArea.internalBuildoutArea) + { + continue; + } + + if(ignoreNonActiveEvents && !buildoutArea.requiredEventName.empty()) + continue; + + if (buildoutArea.isLocationInside(x, z)) + { + return &buildoutArea; + } + } + + return NULL; +} +//---------------------------------------------------------------------- + +BuildoutArea const * SharedBuildoutAreaManager::findBuildoutAreaAtPosition(float x, float z, bool ignoreInternal,bool ignoreNonActiveEvents) +{ + for (std::vector::const_iterator it = s_buildoutAreasForCurrentScene->begin(); it != s_buildoutAreasForCurrentScene->end(); ++it) + { + BuildoutArea const & buildoutArea = *it; + + if (ignoreInternal && buildoutArea.internalBuildoutArea) + { + return NULL; + } + + if(ignoreNonActiveEvents && !buildoutArea.requiredEventName.empty()) + return NULL; + + if (buildoutArea.isLocationInside(x, z)) + { + return &buildoutArea; + } + } + + return NULL; +} + +//---------------------------------------------------------------------- + +std::string const & BuildoutArea::getReferenceDisplayName() const +{ + if (getUseComposite()) + { + return compositeName; + } + + return areaName; +} + +//---------------------------------------------------------------------- + +bool SharedBuildoutAreaManager::isTraversable(std::string const & sceneName, Vector const & location_w1, Vector const & location_w2) +{ + if (!isBuildoutScene(sceneName)) + return true; + + BuildoutArea const * const ba1 = findBuildoutAreaAtPosition(sceneName, location_w1.x, location_w1.z, true); + BuildoutArea const * const ba2 = findBuildoutAreaAtPosition(sceneName, location_w2.x, location_w2.z, true); + + //-- check if the second location is isolated from the first non-buildout location + if (!ba1) + { + if (ba2 && ba2->isolated) + return false; + + return true; + } + + //-- check if the first location is isolated from the second non-buildout location + if (!ba2) + { + if (ba1 && ba1->isolated) + return false; + + return true; + } + + //-- actual same areas (pointer comparison) + if (ba1 == ba2) + return true; + + //-- same area names + if (ba1->areaName == ba2->areaName) + return true; + + //-- is either location isolated + if (!ba1->isolated && !ba2->isolated) + return true; + + //-- otherwise, non-traversable + return false; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/SharedBuildoutAreaManager.h b/engine/shared/library/sharedGame/src/shared/core/SharedBuildoutAreaManager.h new file mode 100644 index 00000000..521ac2f8 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SharedBuildoutAreaManager.h @@ -0,0 +1,149 @@ +// ====================================================================== +// +// SharedBuildoutAreaManager.h +// +// Copyright 2005 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_SharedBuildoutAreaManager_H +#define INCLUDED_SharedBuildoutAreaManager_H + +// ====================================================================== + +#include "sharedMath/Quaternion.h" +#include "sharedMath/Vector.h" +#include "sharedMath/Vector2d.h" +#include "sharedMath/Rectangle2d.h" + +// ====================================================================== + +class BuildoutArea +{ +public: + int getSharedBaseId() const; + int getSharedTopId() const; + int getServerBaseId() const; + int getServerTopId() const; + bool isLocationInside(float x, float z) const; + float getXCenterPoint(bool allowComposite) const; + float getZCenterPoint(bool allowComposite) const; + Rectangle2d const & getRectangle(bool allowComposite) const; + Vector2d getSize(bool allowComposite) const; + + std::string const & getReferenceDisplayName() const; + + bool getUseComposite() const; + + Vector getRelativePosition(Vector const & pos_w, bool allowComposite) const; + + std::string const & getRequiredEventName() const; + + int areaIndex; + std::string areaName; + Rectangle2d rect; + bool useClipRect; + Rectangle2d clipRect; + int clipEnvironmentFlags; + + std::string compositeName; + Rectangle2d compositeRect; + + //-- if a buildout area is isolated, it means you can't walk from it into another one. + //-- or, if you can it means that waypoints in the previous one will shutdown when you walk into the new area + bool isolated; + + bool allowMap; + + //-- if the buildout area is internal, it is not revealed to the player + + bool internalBuildoutArea; + + bool allowRadarTerrain; + + // Required Event name for a particular buildout + std::string requiredEventName; +}; + +// ---------------------------------------------------------------------- + +struct ServerBuildoutAreaRow +{ + int id; + int container; + uint32 serverTemplateCrc; + int cellIndex; + Vector position; + Quaternion orientation; + std::string scripts; + std::string objvars; +}; + +// ---------------------------------------------------------------------- + +struct ClientBuildoutAreaRow +{ + int id; + int container; + uint32 type; + uint32 sharedTemplateCrc; + int cellIndex; + Vector position; + Quaternion orientation; + float radius; + uint32 portalLayoutCrc; +}; + +// ---------------------------------------------------------------------- + +class SharedBuildoutAreaManager +{ +public: + + typedef stdvector::fwd BuildoutAreaVector; + typedef std::pair StringPair; + + static bool isBuildoutScene(std::string const & sceneName); + static void install(); + static void remove(); + static void load(std::string const & sceneName); + static BuildoutAreaVector const &getBuildoutAreasForCurrentScene(); + static std::string getBuildoutNameForPosition(std::string const & sceneName, Vector const & location_w, bool ignoreInternal, bool ignoreNonActiveEvents = true); + static Vector getRelativePositionInArea(std::string const & buildoutName, Vector const & location_w, bool ignoreInternal, bool ignoreNonActiveEvents = true); + static StringPair parseEncodedBuildoutName(std::string const & encodedBuildoutName); + static std::string createEncodedBuildoutName(std::string const & sceneName, std::string const & zoneName); + static Vector2d getBuildoutAreaSize(std::string const & encodedBuildoutName, bool allowComposite); + static bool adjustMapCoordinatesForScene(std::string const & sceneName); + static Vector getCenterPositionInArea(const char *buildoutName, Vector const & location_w); + static Vector getRelativePositionFromWorldSpaceToPlayerSpace(const char *zoneName, Vector const & playerPosition, Vector const & worldPosition); + static BuildoutArea const * findBuildoutAreaAtPosition(float x, float z, bool ignoreInternal, bool ignoreNonActiveEvents = true); + static BuildoutArea const * findBuildoutAreaAtPosition(std::string const & sceneName, float x, float z, bool ignoreInternal, bool ignoreNonActiveEvents = true); + static BuildoutArea const * findBuildoutAreaAtPosition(Vector const & pos, bool ignoreInternal, bool ignoreNonActiveEvents = true); + static BuildoutAreaVector const * findBuildoutAreasForScene(std::string const & sceneName); + static bool isTraversable(std::string const & sceneName, Vector const & location_w1, Vector const & location_w2); +}; + +// ---------------------------------------------------------------------- + +namespace Archive +{ + class ReadIterator; + class ByteStream; + + void get(ReadIterator &source, ServerBuildoutAreaRow &target); + void put(ByteStream &target, ServerBuildoutAreaRow const &source); + void get(ReadIterator &source, ClientBuildoutAreaRow &target); + void put(ByteStream &target, ClientBuildoutAreaRow const &source); +} + +//---------------------------------------------------------------------- + +inline BuildoutArea const * SharedBuildoutAreaManager::findBuildoutAreaAtPosition(Vector const & pos, bool ignoreInternal, bool ignoreNonActiveEvents) +{ + return SharedBuildoutAreaManager::findBuildoutAreaAtPosition(pos.x, pos.z, ignoreInternal, ignoreNonActiveEvents); +} + +// ====================================================================== + +#endif // INCLUDED_SharedBuildoutAreaManager_H + diff --git a/engine/shared/library/sharedGame/src/shared/core/SharedHyperspaceStringIds.cpp b/engine/shared/library/sharedGame/src/shared/core/SharedHyperspaceStringIds.cpp new file mode 100644 index 00000000..491ee102 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SharedHyperspaceStringIds.cpp @@ -0,0 +1,13 @@ +//====================================================================== +// +// SharedHyperspaceStringIds.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SharedHyperspaceStringIds.h" + +//====================================================================== + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/SharedHyperspaceStringIds.h b/engine/shared/library/sharedGame/src/shared/core/SharedHyperspaceStringIds.h new file mode 100644 index 00000000..c3883c1b --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SharedHyperspaceStringIds.h @@ -0,0 +1,31 @@ +//====================================================================== +// +// SharedHyperspaceStringIds.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_SharedHyperspaceStringIds_H +#define INCLUDED_SharedHyperspaceStringIds_H + +//====================================================================== + +#include "StringId.h" + +//====================================================================== + +#define MAKE_STRING_ID(a, b) const StringId b(#a,#b); + +//---------------------------------------------------------------------- + +namespace SharedHyperspaceStringIds +{ + MAKE_STRING_ID(shared_hyperspace, not_cleared_for_point); + MAKE_STRING_ID(shared_hyperspace, zone_too_full); + MAKE_STRING_ID(shared_hyperspace, already_at_point); +} + +//====================================================================== + +#endif + diff --git a/engine/shared/library/sharedGame/src/shared/core/SharedImageDesignerManager.cpp b/engine/shared/library/sharedGame/src/shared/core/SharedImageDesignerManager.cpp new file mode 100644 index 00000000..62e46247 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SharedImageDesignerManager.cpp @@ -0,0 +1,711 @@ +// ====================================================================== +// +// SharedImageDesignerManager.cpp +// copyright (c) 2004 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SharedImageDesignerManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/Os.h" +#include "sharedGame/ConfigSharedGame.h" +#include "sharedGame/CustomizationManager.h" +#include "sharedObject/PaletteColorCustomizationVariable.h" + + +// ====================================================================== + +std::string const SharedImageDesignerManager::cms_bodySkillModName = "body"; +std::string const SharedImageDesignerManager::cms_faceSkillModName = "face"; +std::string const SharedImageDesignerManager::cms_markingsSkillModName = "markings"; +std::string const SharedImageDesignerManager::cms_hairSkillModName = "hair"; + +// ====================================================================== + +namespace SharedImageDesignerManagerNamespace +{ + std::map ms_sessions; + bool ms_installed = false; + + const char * const cms_physicalType = "physical"; +} + +using namespace SharedImageDesignerManagerNamespace; + +// ====================================================================== + +SharedImageDesignerManager::SkillMods::SkillMods() +: faceSkillMod(0), + bodySkillMod(0), + markingsSkillMod(0), + hairSkillMod(0) +{ +} + +//---------------------------------------------------------------------- + +SharedImageDesignerManager::SkillMods::SkillMods(int const bodySkillMod, int const faceSkillMod, int const markingsSkillMod, int const hairSkillMod) +: faceSkillMod(faceSkillMod), + bodySkillMod(bodySkillMod), + markingsSkillMod(markingsSkillMod), + hairSkillMod(hairSkillMod) +{ +} + +//---------------------------------------------------------------------- + +int SharedImageDesignerManager::SkillMods::getSkillMod(std::string const & skillModName) const +{ + if(skillModName == cms_bodySkillModName) + return bodySkillMod; + else if(skillModName == cms_faceSkillModName) + return faceSkillMod; + else if(skillModName == cms_markingsSkillModName) + return markingsSkillMod; + else if(skillModName == cms_hairSkillModName) + return hairSkillMod; + else + { + DEBUG_REPORT_PRINT(ConfigSharedGame::getImageDesignerVerboseOutput(), ("Unknown skill mod [%s]", skillModName.c_str())); + return -1; + } +} + +// ====================================================================== + +SharedImageDesignerManagerSession::SharedImageDesignerManagerSession() +: designerId(), + recipientId(), + terminalId(), + startingTime(0), + designType(ImageDesignChangeMessage::DT_COSMETIC), + newHairSet(false), + newHairAsset(), + hairCustomizationData(), + designerRequiredCredits(0), + recipientPaidCredits(0), + accepted(false), + morphChanges(), + indexChanges(), + holoEmote(), + bodySkillMod(0), + faceSkillMod(0), + markingsSkillMod(0), + hairSkillMod(0) +{ +} + +//---------------------------------------------------------------------- + +SharedImageDesignerManagerSession::SharedImageDesignerManagerSession(ImageDesignChangeMessage const & message) +: designerId(message.getDesignerId()), + recipientId(message.getRecipientId()), + terminalId(message.getTerminalId()), + startingTime(message.getStartingTime()), + designType(message.getDesignType()), + newHairSet(message.getNewHairSet()), + newHairAsset(message.getNewHairAsset()), + hairCustomizationData(message.getHairCustomizationData()), + designerRequiredCredits(message.getDesignerRequiredCredits()), + recipientPaidCredits(message.getRecipientPaidCredits()), + accepted(message.getAccepted()), + morphChanges(message.getMorphParameterChanges()), + indexChanges(message.getIndexParameterChanges()), + holoEmote(message.getHoloEmote()), + bodySkillMod(message.getBodySkillMod()), + faceSkillMod(message.getFaceSkillMod()), + markingsSkillMod(message.getMarkingsSkillMod()), + hairSkillMod(message.getHairSkillMod()) +{ +} + +// ====================================================================== + +void SharedImageDesignerManager::install () +{ + InstallTimer const installTimer("SharedImageDesignerManager::install "); + + DEBUG_FATAL(ms_installed, ("Already Installed")); + ms_installed = true; + + ExitChain::add(SharedImageDesignerManager::remove, "SharedImageDesignerManager::remove", 0, false); +} + +//---------------------------------------------------------------------- + +void SharedImageDesignerManager::remove () +{ + DEBUG_FATAL(!ms_installed, ("Not Installed")); + + ms_installed = false; +} + +//---------------------------------------------------------------------- + +void SharedImageDesignerManager::startSession(SharedImageDesignerManager::Session const & session) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedImageDesignerManager not installed")); + return; //lint !e527 unreachable (reachable in release) + } + + NetworkId const & designerId = session.designerId; + if(isCurrentlyDesigning(designerId)) + { + endSession(designerId); + } + ms_sessions[designerId] = session; +} + +//---------------------------------------------------------------------- + +void SharedImageDesignerManager::updateSession(SharedImageDesignerManager::Session const & session) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedImageDesignerManager not installed")); + return; //lint !e527 unreachable (reachable in release) + } + + ms_sessions[session.designerId] = session; +} + +//---------------------------------------------------------------------- + +bool SharedImageDesignerManager::getSession(NetworkId const & designerId, SharedImageDesignerManager::Session & /*OUT*/ session) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedImageDesignerManager not installed")); + return false; //lint !e527 unreachable (reachable in release) + } + + std::map::const_iterator i = ms_sessions.find(designerId); + if(i != ms_sessions.end()) + { + session = i->second; + return true; + } + else + return false; +} + +//---------------------------------------------------------------------- + +bool SharedImageDesignerManager::isCurrentlyDesigning(NetworkId const & designerId) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedImageDesignerManager not installed")); + return false; //lint !e527 unreachable (reachable in release) + } + + std::map::const_iterator i = ms_sessions.find(designerId); + return i != ms_sessions.end(); +} + +//---------------------------------------------------------------------- + +bool SharedImageDesignerManager::isCurrentlyBeingDesigned(NetworkId const & recipientId) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedImageDesignerManager not installed")); + return false; //lint !e527 unreachable (reachable in release) + } + + for(std::map::const_iterator i = ms_sessions.begin(); i != ms_sessions.end(); ++i) + { + if(i->second.recipientId == recipientId) + return true; + } + return false; +} + +//---------------------------------------------------------------------- + +void SharedImageDesignerManager::endSession(NetworkId const & designerId) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedImageDesignerManager not installed")); + return; //lint !e527 unreachable (reachable in release) + } + + if(!isCurrentlyDesigning(designerId)) + return; + + IGNORE_RETURN(ms_sessions.erase(designerId)); +} + +//---------------------------------------------------------------------- + +time_t SharedImageDesignerManager::getTimeRemaining(NetworkId const & designerId) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedImageDesignerManager not installed")); + return 0; //lint !e527 unreachable (reachable in release) + } + + if(!isCurrentlyDesigning(designerId)) + return 0; + + Session session; + bool const result = getSession(designerId, session); + if(!result) + return 0; + + if(session.startingTime == 0) + return 0; + + SkillMods const skillMods(session.bodySkillMod, session.faceSkillMod, session.markingsSkillMod, session.hairSkillMod); + ImageDesignerPaletteLevel const designerLevel = getAvailablePaletteLevels(skillMods); + + time_t const elapsedTime = Os::getRealSystemTime() - session.startingTime; + + time_t endTime = 0; + if(session.designType == ImageDesignChangeMessage::DT_COSMETIC) + { + int minimumCosmeticTime = ConfigSharedGame::getImageDesignerCosmeticSessionTimeSeconds(); + //cut time in half if we have a terminal + if(session.terminalId != NetworkId::cms_invalid || designerLevel == IDPL_MASTER) + { + minimumCosmeticTime /= 2; + } + if(session.terminalId != NetworkId::cms_invalid && designerLevel == IDPL_MASTER) + { + minimumCosmeticTime = 0; + } + + endTime = session.startingTime + minimumCosmeticTime; + } + else if(session.designType == ImageDesignChangeMessage::DT_PHYSICAL) + { + int minimumPhysicalTime = ConfigSharedGame::getImageDesignerPhysicalSessionTimeSeconds(); + //cut time in half if we have a terminal + if(session.terminalId != NetworkId::cms_invalid || designerLevel == IDPL_MASTER) + { + minimumPhysicalTime /= 2; + } + if(session.terminalId != NetworkId::cms_invalid && designerLevel == IDPL_MASTER) + { + minimumPhysicalTime = 0; + } + + endTime = session.startingTime + minimumPhysicalTime; + } + else + { + //this was for stat migration, and shouldn't be called anymore + endTime = session.startingTime; + } + + time_t timeLeft = (endTime - session.startingTime) - elapsedTime; + if(timeLeft < 0) + timeLeft = 0; + return timeLeft; +} + +//---------------------------------------------------------------------- + +bool SharedImageDesignerManager::isSessionValid(SharedImageDesignerManager::Session const & session, SharedImageDesignerManager::SkillMods const & designerSkills, std::string const & recipientSpeciesGender, CustomizationData * const customizationDataCreature, CustomizationData * const customizationDataHair) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedImageDesignerManager not installed")); + return false; //lint !e527 unreachable (reachable in release) + } + + if(!customizationDataCreature) + return false; + + //check time left + time_t const timeLeft = getTimeRemaining(session.designerId); + if(timeLeft > 0) + { + DEBUG_REPORT_PRINT(ConfigSharedGame::getImageDesignerVerboseOutput(), ("ImageDesigner: Designer[%s] can't change Recipient[%s], not enough time has elapsed", session.designerId.getValueString().c_str(), session.recipientId.getValueString().c_str())); + return false; + } + + CustomizationManager::Customization customization; + + //check morph changes + for(std::map::const_iterator i = session.morphChanges.begin(); i != session.morphChanges.end(); ++i) + { + if(!isMorphChangeValid(i->first, i->second, designerSkills, recipientSpeciesGender)) + { + DEBUG_REPORT_PRINT(ConfigSharedGame::getImageDesignerVerboseOutput(), ("ImageDesigner: Designer[%s] can't change Recipient[%s]'s [%s] to [%f] as requested", session.designerId.getValueString().c_str(), session.recipientId.getValueString().c_str(), i->first.c_str(), i->second)); + return false; + } + } + + //check index changes + for(std::map::const_iterator j = session.indexChanges.begin(); j != session.indexChanges.end(); ++j) + { + bool const result = CustomizationManager::getCustomization(recipientSpeciesGender, j->first, customization); + if(!result) + return false; + + //check against the hair customization data if necessary + CustomizationData * customizationDataForThisCustomization = customizationDataCreature; + if(customization.isVarHairColor) + { + if(customizationDataHair) + customizationDataForThisCustomization = customizationDataHair; + else + customizationDataForThisCustomization = NULL; + } + + if(customizationDataForThisCustomization) + { + if(!isIndexChangeValid(j->first, j->second, designerSkills, recipientSpeciesGender, customizationDataForThisCustomization) && !customization.isVarHairColor) + { + DEBUG_REPORT_PRINT(ConfigSharedGame::getImageDesignerVerboseOutput(), ("ImageDesigner: Designer[%s] can't change Recipient[%s]'s [%s] to [%d] as requested", session.designerId.getValueString().c_str(), session.recipientId.getValueString().c_str(), j->first.c_str(), j->second)); + return false; + } + } + } + + //check hair change + if(session.newHairSet) + { + //if bald, see if that's alright for this avatar + if(session.newHairAsset.empty()) + { + //bald doens't have a skill level, if bald is ok for the recipient, then the designer can do it + bool const baldOk = CustomizationManager::getAllowBald(recipientSpeciesGender); + if(!baldOk) + { + DEBUG_REPORT_PRINT(ConfigSharedGame::getImageDesignerVerboseOutput(), ("ImageDesigner: Designer[%s] can't change Recipient[%s]'s hair to bald, bald is not okay for that species/gender", session.designerId.getValueString().c_str(), session.recipientId.getValueString().c_str())); + return false; + } + //TODO check that the recipient hair 1)can go on that species_gender, and 2)the designer has the skill to make the change + } + } + + //check holoemote + if(!session.holoEmote.empty()) + { + bool const result = hasSkillForHoloemote(session.holoEmote, designerSkills); + if(!result) + { + DEBUG_REPORT_PRINT(ConfigSharedGame::getImageDesignerVerboseOutput(), ("ImageDesigner: Designer[%s] can't give Recipient[%s] the [%s] holoemote, they don't have the skill", session.designerId.getValueString().c_str(), session.recipientId.getValueString().c_str(), session.holoEmote.c_str())); + return false; + } + } + + return true; +} + +//---------------------------------------------------------------------- + +bool SharedImageDesignerManager::isMorphChangeValid(std::string const & customizationName, float const newValue, SharedImageDesignerManager::SkillMods const & designerSkills, std::string const & recipientSpeciesGender) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedImageDesignerManager not installed")); + return false; //lint !e527 unreachable (reachable in release) + } + + UNREF(newValue); + std::string requiredSkillModName; + int requiredSkillModValue = 0; + int designerSkillModValue = 0; + CustomizationManager::Customization customization; + //check that the morph change 1)is a valid customization variable for the recipient, 2)the designer has the skill + bool const result = CustomizationManager::getCustomization(recipientSpeciesGender, customizationName, customization); + if(!result) + { + //unknown customization name, fail + DEBUG_REPORT_PRINT(ConfigSharedGame::getImageDesignerVerboseOutput(), ("ImageDesigner: Unknown customization [%s] for [%s]", customizationName.c_str(), recipientSpeciesGender.c_str())); + return false; + } + requiredSkillModName = customization.skillMod; + if(!isASkillModName(requiredSkillModName)) + { + //unknown skill modname, fail + DEBUG_REPORT_PRINT(ConfigSharedGame::getImageDesignerVerboseOutput(), ("ImageDesigner: Unknown skill mod name [%s]", requiredSkillModName.c_str())); + return false; + } + + requiredSkillModValue = customization.skillModValue; + designerSkillModValue = designerSkills.getSkillMod(requiredSkillModName); + if(designerSkillModValue < requiredSkillModValue) + { + //designer doesn't have enough skill, fail + return false; + } + return true; +} + +//---------------------------------------------------------------------- + +bool SharedImageDesignerManager::isIndexChangeValid(std::string const & customizationName, int const newValue, SharedImageDesignerManager::SkillMods const & designerSkills, std::string const & recipientSpeciesGender, CustomizationData * const customizationData) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedImageDesignerManager not installed")); + return false; //lint !e527 unreachable (reachable in release) + } + + if(newValue < 0) + return false; + + if(!customizationData) + return false; + + std::string requiredSkillModName; + int requiredSkillModValue = 0; + int designerSkillModValue = 0; + CustomizationManager::Customization customization; + //check that the index change 1)is a valid customization variable for the recipient, 2)the designer has the skill, + //and 3)is within the right area of the palette for the designer's skill + bool const result = CustomizationManager::getCustomization(recipientSpeciesGender, customizationName, customization); + if(!result) + { + //unknown customization name, fail + DEBUG_REPORT_PRINT(ConfigSharedGame::getImageDesignerVerboseOutput(), ("ImageDesigner: Unknown customization [%s] for [%s]", customizationName.c_str(), recipientSpeciesGender.c_str())); + return false; + } + requiredSkillModName = customization.skillMod; + if(!isASkillModName(requiredSkillModName)) + { + //unknown skill modname, fail + DEBUG_REPORT_PRINT(ConfigSharedGame::getImageDesignerVerboseOutput(), ("ImageDesigner: Unknown skill mod name [%s]", requiredSkillModName.c_str())); + return false; + } + + requiredSkillModValue = customization.skillModValue; + designerSkillModValue = designerSkills.getSkillMod(requiredSkillModName); + if(designerSkillModValue < requiredSkillModValue) + { + //designer doesn't have enough skill, fail + return false; + } + + CustomizationVariable * const cv = CustomizationManager::findVariable (*customizationData, customization.variables); + PaletteColorCustomizationVariable * const paletteVariable = dynamic_cast(cv); + if(!paletteVariable) + return false; + PaletteArgb const * const palette = paletteVariable->fetchPalette(); + if(!palette) + return false; + else + { + PaletteValues const values = getPaletteValuesForPaletteAndSkillMods(palette, designerSkills); + palette->release(); + //if the requested palette value is outside the range the designer can use, fail + if(values.maxIndex < newValue) + return false; + } + return true; +} + +//---------------------------------------------------------------------- + +bool SharedImageDesignerManager::isASkillModName(std::string const & skillModName) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedImageDesignerManager not installed")); + return false; //lint !e527 unreachable (reachable in release) + } + + return skillModName == cms_bodySkillModName || + skillModName == cms_faceSkillModName || + skillModName == cms_markingsSkillModName || + skillModName == cms_hairSkillModName; +} + +//---------------------------------------------------------------------- + +void SharedImageDesignerManager::populateChangeMessage(SharedImageDesignerManager::Session const & session, ImageDesignChangeMessage & /*OUT*/ msg) +{ + if(!ms_installed) + { + DEBUG_FATAL(true, ("SharedImageDesignerManager not installed")); + return; //lint !e527 unreachable (reachable in release) + } + + msg.setDesignerId(session.designerId); + msg.setRecipientId(session.recipientId); + msg.setTerminalId(session.terminalId); + msg.setStartingTime(session.startingTime); + msg.setDesignType(session.designType); + msg.setNewHairSet(session.newHairSet); + msg.setOrigin(ImageDesignChangeMessage::O_DESIGNER); + msg.setNewHairAsset(session.newHairAsset); + msg.setHairCustomizationData(session.hairCustomizationData); + msg.setDesignerRequiredCredits(session.designerRequiredCredits); + msg.setRecipientPaidCredits(session.recipientPaidCredits); + msg.setAccepted(session.accepted); + msg.setMorphParameterChanges(session.morphChanges); + msg.setIndexParameterChanges(session.indexChanges); + msg.setHoloEmote(session.holoEmote); + msg.setBodySkillMod(session.bodySkillMod); + msg.setFaceSkillMod(session.faceSkillMod); + msg.setMarkingsSkillMod(session.markingsSkillMod); + msg.setHairSkillMod(session.hairSkillMod); +} + +//---------------------------------------------------------------------- + +SharedImageDesignerManager::ImageDesignerPaletteLevel SharedImageDesignerManager::getAvailablePaletteLevels(SharedImageDesignerManager::SkillMods const & designerSkills) +{ + ImageDesignerPaletteLevel maxLevel = IDPL_NOT_A_DESIGNER; + if(designerSkills.faceSkillMod >= 4 || designerSkills.bodySkillMod >= 1 || designerSkills.hairSkillMod >= 5 || designerSkills.markingsSkillMod >= 2) + maxLevel = IDPL_NOVICE; + if(designerSkills.faceSkillMod >= 5 || designerSkills.bodySkillMod >= 2 || designerSkills.hairSkillMod >= 6 || designerSkills.markingsSkillMod >= 2) + maxLevel = IDPL_LEVEL1; + if(designerSkills.faceSkillMod >= 6 || designerSkills.bodySkillMod >= 3 || designerSkills.hairSkillMod >= 8 || designerSkills.markingsSkillMod >= 3) + maxLevel = IDPL_LEVEL2; + if(designerSkills.faceSkillMod >= 8 || designerSkills.bodySkillMod >= 5 || designerSkills.hairSkillMod >= 10 || designerSkills.markingsSkillMod >= 5) + maxLevel = IDPL_LEVEL3; + if(designerSkills.faceSkillMod >= 10 || designerSkills.bodySkillMod >= 7 || designerSkills.hairSkillMod >= 12 || designerSkills.markingsSkillMod >= 7) + maxLevel = IDPL_LEVEL4; + if(designerSkills.faceSkillMod >= 12 || designerSkills.bodySkillMod >= 9 || designerSkills.hairSkillMod >= 13 || designerSkills.markingsSkillMod >= 9) + maxLevel = IDPL_MASTER; + return maxLevel; +} + +//---------------------------------------------------------------------- + +SharedImageDesignerManager::PaletteValues SharedImageDesignerManager::getPaletteValuesForPaletteAndSkillMods(PaletteArgb const * const palette, SharedImageDesignerManager::SkillMods const & designerSkills) +{ + SharedImageDesignerManager::ImageDesignerPaletteLevel const level = SharedImageDesignerManager::getAvailablePaletteLevels(designerSkills); + return getPaletteValuesForPaletteAndLevel(palette, level); +} + +//---------------------------------------------------------------------- + +SharedImageDesignerManager::PaletteValues SharedImageDesignerManager::getPaletteValuesForPaletteAndLevel(PaletteArgb const * const palette, SharedImageDesignerManager::ImageDesignerPaletteLevel const & level) +{ + PaletteValues paletteValues; + paletteValues.columns = 0; + paletteValues.maxIndex = 10000; + + if(palette) + { + CrcString const & paletteNameCrc = palette->getName(); + char const * const paletteName = paletteNameCrc.getString(); + CustomizationManager::PaletteColumns const paletteColumnData = CustomizationManager::getPaletteColumnDataLongName(paletteName); + if(level == SharedImageDesignerManager::IDPL_NOT_A_DESIGNER) + { + paletteValues.columns = paletteColumnData.creationColumns; + paletteValues.maxIndex = paletteColumnData.creationIndexes; + } + else if(level == SharedImageDesignerManager::IDPL_NOVICE) + { + paletteValues.columns = paletteColumnData.noviceColumns; + paletteValues.maxIndex = paletteColumnData.noviceIndexes; + } + else if(level == SharedImageDesignerManager::IDPL_LEVEL1) + { + paletteValues.columns = paletteColumnData.level1Columns; + paletteValues.maxIndex = paletteColumnData.level1Indexes; + } + else if(level == SharedImageDesignerManager::IDPL_LEVEL2) + { + paletteValues.columns = paletteColumnData.level2Columns; + paletteValues.maxIndex = paletteColumnData.level2Indexes; + } + else if(level == SharedImageDesignerManager::IDPL_LEVEL3) + { + paletteValues.columns = paletteColumnData.level3Columns; + paletteValues.maxIndex = paletteColumnData.level3Indexes; + } + else if(level == SharedImageDesignerManager::IDPL_LEVEL4) + { + paletteValues.columns = paletteColumnData.level4Columns; + paletteValues.maxIndex = paletteColumnData.level4Indexes; + } + else if(level == SharedImageDesignerManager::IDPL_MASTER) + { + paletteValues.columns = paletteColumnData.masterColumns; + paletteValues.maxIndex = paletteColumnData.masterIndexes; + } + else + { + DEBUG_FATAL(true, ("Unknown SharedImageDesignerManager::ImageDesignerPaletteLevel type %d found", level)); + } + } + return paletteValues; +} + +//---------------------------------------------------------------------- + +bool SharedImageDesignerManager::hasSkillForHoloemote(std::string const & holoemoteName, SharedImageDesignerManager::SkillMods const & designerSkills) +{ + if(!CustomizationManager::isHoloemoteName(holoemoteName)) + return false; + int const requiredHairSkill = CustomizationManager::getRequiredHairSkillForHoloemote(holoemoteName); + if(designerSkills.hairSkillMod >= requiredHairSkill) + return true; + else + return false; +} + +//---------------------------------------------------------------------- + +/** Look through each customization change. + If any of the changes are "physical", the session's overall change type is "physical". + If stat migration is set, then the type is "stta migration" +*/ +void SharedImageDesignerManager::updateDesignType(SharedImageDesignerManager::Session & /*IN OUT*/ session, std::string const & recipientSpeciesGender) +{ + CustomizationManager::Customization customization; + bool result = false; + + session.designType = ImageDesignChangeMessage::DT_COSMETIC; + + for(std::map::iterator i = session.morphChanges.begin(); i != session.morphChanges.end(); ++i) + { + result = CustomizationManager::getCustomization(recipientSpeciesGender, i->first, customization); + if(result) + { + if(customization.modificationType == cms_physicalType) + { + session.designType = ImageDesignChangeMessage::DT_PHYSICAL; + return; + } + } + } + + for(std::map::iterator j = session.indexChanges.begin(); j != session.indexChanges.end(); ++j) + { + result = CustomizationManager::getCustomization(recipientSpeciesGender, j->first, customization); + if(result) + { + if(customization.modificationType == cms_physicalType) + { + session.designType = ImageDesignChangeMessage::DT_PHYSICAL; + return; + } + } + } +} + +//---------------------------------------------------------------------- + +bool SharedImageDesignerManager::hasSkillForCustomization(std::string const & customizationName, std::string const & recipientSpeciesGender, SkillMods const & designerSkills) +{ + CustomizationManager::Customization customization; + bool const result = CustomizationManager::getCustomization(recipientSpeciesGender, customizationName, customization); + if(result) + { + int const requiredSkillModValue = customization.skillModValue; + int const designerSkillModValue = designerSkills.getSkillMod(customization.skillMod); + if(designerSkillModValue >= requiredSkillModValue) + { + return true; + } + } + return false; +} + +// ===================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/SharedImageDesignerManager.h b/engine/shared/library/sharedGame/src/shared/core/SharedImageDesignerManager.h new file mode 100644 index 00000000..4f382886 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SharedImageDesignerManager.h @@ -0,0 +1,126 @@ +// ====================================================================== +// +// SharedImageDesignerManager.h +// copyright (c) 2004 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_SharedImageDesignerManager_H +#define INCLUDED_SharedImageDesignerManager_H + + +// ====================================================================== + +#include "sharedFoundation/NetworkId.h" + +#include "sharedMath/PaletteArgb.h" +#include "sharedNetworkMessages/ImageDesignChangeMessage.h" + +#include + +//----------------------------------------------------------------------- + +class CustomizationData; + + +//----------------------------------------------------------------------- + +//for forward declaration purposed +class SharedImageDesignerManagerSession +{ +public: + NetworkId designerId; + NetworkId recipientId; + NetworkId terminalId; + time_t startingTime; + ImageDesignChangeMessage::DesignType designType; + bool newHairSet; + std::string newHairAsset; + std::string hairCustomizationData; + int designerRequiredCredits; + int recipientPaidCredits; + bool accepted; + std::map morphChanges; + std::map indexChanges; + std::string holoEmote; + int bodySkillMod; + int faceSkillMod; + int markingsSkillMod; + int hairSkillMod; + + SharedImageDesignerManagerSession(); + SharedImageDesignerManagerSession(ImageDesignChangeMessage const & message); +}; + +class SharedImageDesignerManager +{ +public: + static std::string const cms_bodySkillModName; + static std::string const cms_faceSkillModName; + static std::string const cms_markingsSkillModName; + static std::string const cms_hairSkillModName; + + typedef SharedImageDesignerManagerSession Session; + + struct SkillMods + { + int faceSkillMod; + int bodySkillMod; + int markingsSkillMod; + int hairSkillMod; + + int getSkillMod(std::string const & skillModName) const; + SkillMods(); + SkillMods(int bodySkillMod, int faceSkillMod, int markingsSkillMod, int hairSkillMod); + }; + + enum ImageDesignerPaletteLevel + { + IDPL_NOT_A_DESIGNER, + IDPL_NOVICE, + IDPL_LEVEL1, + IDPL_LEVEL2, + IDPL_LEVEL3, + IDPL_LEVEL4, + IDPL_MASTER + }; + + struct PaletteValues + { + int columns; + int maxIndex; + }; + +public: + static void install(); + static void startSession(Session const & session); + static void updateSession(Session const & session); + static void endSession(NetworkId const & designerId); + static bool getSession(NetworkId const & designerId, Session & /*OUT*/ session); + static bool isCurrentlyDesigning(NetworkId const & designerId); + static bool isCurrentlyBeingDesigned(NetworkId const & recipientId); + static time_t getTimeRemaining(NetworkId const & designerId); + static bool isSessionValid(Session const & session, SkillMods const & designerSkills, std::string const & recipientSpeciesGender, CustomizationData * customizationDataCreature, CustomizationData * customizationDataHair); + static bool isMorphChangeValid(std::string const & customizationName, float const newValue, SkillMods const & designerSkills, std::string const & recipientSpeciesGender); + static bool isIndexChangeValid(std::string const & customizationName, int const newValue, SkillMods const & designerSkills, std::string const & recipientSpeciesGender, CustomizationData * customizationData); + static bool isASkillModName(std::string const & skillModName); + static void populateChangeMessage(Session const & session, ImageDesignChangeMessage & /*OUT*/ msg); + static ImageDesignerPaletteLevel getAvailablePaletteLevels(SkillMods const & designerSkills); + static PaletteValues getPaletteValuesForPaletteAndSkillMods(PaletteArgb const * palette, SkillMods const & designerSkills); + static PaletteValues getPaletteValuesForPaletteAndLevel(PaletteArgb const * const palette, ImageDesignerPaletteLevel const & level); + static bool hasSkillForHoloemote(std::string const & holoemoteName, SkillMods const & designerSkills); + static void updateDesignType(Session & session, std::string const & recipientSpeciesGender); + static bool hasSkillForCustomization(std::string const & customizationName, std::string const & recipientSpeciesGender, SkillMods const & designerSkills); + +private: + //disabled + SharedImageDesignerManager (SharedImageDesignerManager const & rhs); + SharedImageDesignerManager & operator= (SharedImageDesignerManager const & rhs); + +private: + static void remove(); +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/SharedObjectAttributes.cpp b/engine/shared/library/sharedGame/src/shared/core/SharedObjectAttributes.cpp new file mode 100644 index 00000000..e0cedbea --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SharedObjectAttributes.cpp @@ -0,0 +1,13 @@ +//====================================================================== +// +// SharedObjectAttributes.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SharedObjectAttributes.h" + +//====================================================================== + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/SharedObjectAttributes.h b/engine/shared/library/sharedGame/src/shared/core/SharedObjectAttributes.h new file mode 100644 index 00000000..04f7b531 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SharedObjectAttributes.h @@ -0,0 +1,190 @@ +//====================================================================== +// +// SharedObjectAttributes.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_SharedObjectAttributes_H +#define INCLUDED_SharedObjectAttributes_H + +//====================================================================== + +#include + +//---------------------------------------------------------------------- + +namespace SharedObjectAttributes +{ + namespace StringTables + { + const std::string Name = "obj_attr_n"; + const std::string Desc = "obj_attr_d"; + } + +#define MAKE_ATTRIB(a) const std::string a = #a + + MAKE_ATTRIB (craft_tool_status); + MAKE_ATTRIB (craft_tool_time); + MAKE_ATTRIB (serial_number); + MAKE_ATTRIB (crafter); + MAKE_ATTRIB (craft_tool_effectiveness); + + MAKE_ATTRIB (armorRating); + MAKE_ATTRIB (baseEffectiveness); + MAKE_ATTRIB (baseIntegrity); + + MAKE_ATTRIB (volume); + MAKE_ATTRIB (data_volume); + MAKE_ATTRIB (condition); + MAKE_ATTRIB (contents); + MAKE_ATTRIB (data_contents); + MAKE_ATTRIB (resource_contents); + MAKE_ATTRIB (resource_name); + MAKE_ATTRIB (resource_class); + MAKE_ATTRIB (waypoint_planet); + MAKE_ATTRIB (waypoint_region); + MAKE_ATTRIB (waypoint_position); + MAKE_ATTRIB (waypoint_active); + + MAKE_ATTRIB (counter_uses_remaining); + MAKE_ATTRIB (counter_charges_remaining); + + MAKE_ATTRIB (cat_wpn_attack_cost); + MAKE_ATTRIB (cat_pup_attack_cost); + + MAKE_ATTRIB (attr_health); + MAKE_ATTRIB (attr_strength); + MAKE_ATTRIB (attr_constitution); + + MAKE_ATTRIB (attr_action); + MAKE_ATTRIB (attr_quickness); + MAKE_ATTRIB (attr_stamina); + + MAKE_ATTRIB (attr_mind); + MAKE_ATTRIB (attr_focus); + MAKE_ATTRIB (attr_willpower); + + MAKE_ATTRIB (wpn_accuracy); + MAKE_ATTRIB (wpn_attack_speed); + MAKE_ATTRIB (wpn_damage); + MAKE_ATTRIB (wpn_damage_max); + MAKE_ATTRIB (wpn_damage_min); + MAKE_ATTRIB (wpn_damage_radius); + MAKE_ATTRIB (wpn_damage_type); + MAKE_ATTRIB (wpn_elemental_type); + MAKE_ATTRIB (wpn_elemental_value); + MAKE_ATTRIB (wpn_range_max); + MAKE_ATTRIB (wpn_range_min); + MAKE_ATTRIB (wpn_wound_chance); + MAKE_ATTRIB (wpn_armor_pierce_rating); + + MAKE_ATTRIB (armor_pierce_); + + MAKE_ATTRIB (complexity); + + MAKE_ATTRIB (manufacture_schematic_volume); + MAKE_ATTRIB (sockets); + + MAKE_ATTRIB (travel_arrival_planet); + MAKE_ATTRIB (travel_arrival_point); + MAKE_ATTRIB (travel_departure_planet); + MAKE_ATTRIB (travel_departure_point); + + // link to player + MAKE_ATTRIB (bio_link); + MAKE_ATTRIB (no_trade); + MAKE_ATTRIB (no_trade_shared); + + MAKE_ATTRIB (unique); + + //-- + //-- categories + //-- + MAKE_ATTRIB (cat_attrib_mod_bonus); + MAKE_ATTRIB (cat_manf_schem_ing_resource); + MAKE_ATTRIB (cat_manf_schem_ing_component); + MAKE_ATTRIB (manf_limit); + MAKE_ATTRIB (manf_attribs); + + MAKE_ATTRIB (cat_armor_encumbrance); + MAKE_ATTRIB (cat_armor_effectiveness); + MAKE_ATTRIB (armor_eff_); + MAKE_ATTRIB (armor_eff_base); + MAKE_ATTRIB (cat_armor_special_protection); + MAKE_ATTRIB (cat_armor_vulnerability); + + MAKE_ATTRIB (cat_wpn_damage); + + MAKE_ATTRIB (cat_skill_mod_bonus); + MAKE_ATTRIB (weapon_cert_status); + + MAKE_ATTRIB (original_name); + MAKE_ATTRIB (original_name_creature); + + MAKE_ATTRIB (factory_count); + MAKE_ATTRIB (factory_attribs); + + MAKE_ATTRIB (manufacture_object); + MAKE_ATTRIB (manufacture_time); + MAKE_ATTRIB (manufacture_count); + + MAKE_ATTRIB (object_type); + + MAKE_ATTRIB (consider); + + MAKE_ATTRIB (ship_component_armor); + MAKE_ATTRIB (ship_component_hitpoints); + MAKE_ATTRIB (ship_component_efficiency_general); + MAKE_ATTRIB (ship_component_efficiency_energy); + MAKE_ATTRIB (ship_component_energy_required); + MAKE_ATTRIB (ship_component_mass); + MAKE_ATTRIB (ship_component_flags); + + MAKE_ATTRIB (ship_component_booster_energy); + MAKE_ATTRIB (ship_component_booster_energy_recharge_rate); + MAKE_ATTRIB (ship_component_booster_energy_consumption_rate); + MAKE_ATTRIB (ship_component_booster_acceleration); + MAKE_ATTRIB (ship_component_booster_speed_maximum); + + MAKE_ATTRIB (ship_component_capacitor_energy); + MAKE_ATTRIB (ship_component_capacitor_energy_recharge_rate); + + MAKE_ATTRIB (ship_component_droidinterface_speed); + + MAKE_ATTRIB (ship_component_engine_acceleration_rate); + MAKE_ATTRIB (ship_component_engine_deceleration_rate); + MAKE_ATTRIB (ship_component_engine_pitch_acceleration_rate); + MAKE_ATTRIB (ship_component_engine_yaw_acceleration_rate); + MAKE_ATTRIB (ship_component_engine_roll_acceleration_rate); + MAKE_ATTRIB (ship_component_engine_pitch_rate_maximum); + MAKE_ATTRIB (ship_component_engine_yaw_rate_maximum); + MAKE_ATTRIB (ship_component_engine_roll_rate_maximum); + MAKE_ATTRIB (ship_component_engine_speed_maximum); + + MAKE_ATTRIB (ship_component_reactor_generation_rate); + + MAKE_ATTRIB (ship_component_shield_hitpoints_front); + MAKE_ATTRIB (ship_component_shield_hitpoints_back); + MAKE_ATTRIB (ship_component_shield_recharge_rate); + + MAKE_ATTRIB (ship_component_weapon_damage); + MAKE_ATTRIB (ship_component_weapon_effectiveness_shields); + MAKE_ATTRIB (ship_component_weapon_effectiveness_armor); + MAKE_ATTRIB (ship_component_weapon_energy_per_shot); + MAKE_ATTRIB (ship_component_weapon_refire_rate); + MAKE_ATTRIB (ship_component_weapon_ammo); + + MAKE_ATTRIB (ship_component_cargo_hold_contents_max); + + MAKE_ATTRIB (tooltip); + + MAKE_ATTRIB (tier); + +#undef MAKE_ATTRIB + +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/SharedStringIds.cpp b/engine/shared/library/sharedGame/src/shared/core/SharedStringIds.cpp new file mode 100644 index 00000000..5d08e32c --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SharedStringIds.cpp @@ -0,0 +1,13 @@ +//====================================================================== +// +// SharedStringIds.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SharedStringIds.h" + +//====================================================================== + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/SharedStringIds.h b/engine/shared/library/sharedGame/src/shared/core/SharedStringIds.h new file mode 100644 index 00000000..8f7bcaa0 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SharedStringIds.h @@ -0,0 +1,102 @@ +//====================================================================== +// +// SharedStringIds.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_SharedStringIds_H +#define INCLUDED_SharedStringIds_H + +//====================================================================== + +#include "StringId.h" + +//====================================================================== + +#define MAKE_STRING_ID(a, b) const StringId b(#a,#b); + +//---------------------------------------------------------------------- + +namespace SharedStringIds +{ + MAKE_STRING_ID(shared, rsp_object_deleted_prose); + MAKE_STRING_ID(ui, no); + MAKE_STRING_ID(ui, no_sitting_in_water); + MAKE_STRING_ID(ui, yes); + MAKE_STRING_ID(game_language, basic); + MAKE_STRING_ID(cmd_err, unstick_in_progress); + MAKE_STRING_ID(cmd_err, unstick_request_complete); + MAKE_STRING_ID(cmd_err, unstick_request_cancelled); + MAKE_STRING_ID(shared, revoke_dependant_skill); + MAKE_STRING_ID(shared, no_waypoint_datapad_full); + +// MAKE_STRING_ID(shared, player_sit_on_chair_prose); +// MAKE_STRING_ID(shared, player_sit); +// MAKE_STRING_ID(shared, player_stand); +// MAKE_STRING_ID(shared, player_prone); +// MAKE_STRING_ID(shared, player_kneel); + + MAKE_STRING_ID(shared, harvester_no_power); + MAKE_STRING_ID(shared, harvester_no_maint_1); + MAKE_STRING_ID(shared, harvester_no_maint_2); + MAKE_STRING_ID(shared, harvester_no_maint_3); + MAKE_STRING_ID(shared, harvester_no_maint_4); + MAKE_STRING_ID(shared, harvester_hopper_full); + MAKE_STRING_ID(shared, harvester_resource_depleted); + MAKE_STRING_ID(shared, harvester_no_resource); + + MAKE_STRING_ID(shared, gem_inserted); + MAKE_STRING_ID(shared, gem_not_inserted); + MAKE_STRING_ID(shared, gem_not_in_inventory); + + MAKE_STRING_ID(shared, vehicle_disabled_name_prose); + MAKE_STRING_ID(shared, vehicle_destroyed_name_prose); + + MAKE_STRING_ID(shared, imagedesigner_designer_success); + MAKE_STRING_ID(shared, imagedesigner_recipient_success); + MAKE_STRING_ID(shared, imagedesigner_session_not_valid); + MAKE_STRING_ID(shared, imagedesigner_not_enough_time_passed); + MAKE_STRING_ID(shared, imagedesigner_failed_to_send_money); + MAKE_STRING_ID(shared, imagedesigner_not_paying_enough); + MAKE_STRING_ID(shared, imagedesigner_hair_not_valid); + MAKE_STRING_ID(shared, imagedesigner_bald_not_valid); + MAKE_STRING_ID(shared, imagedesigner_recip_paid); + MAKE_STRING_ID(shared, imagedesigner_designer_was_paid); + MAKE_STRING_ID(shared, imagedesigner_canceled_by_recip); + MAKE_STRING_ID(shared, imagedesigner_wounded_can_not_migrate_stats); + MAKE_STRING_ID(shared, waypoint_on_other_planet); + MAKE_STRING_ID(shared, waypoint_in_other_space_zone); + MAKE_STRING_ID(shared, mission_on_other_planet); + + MAKE_STRING_ID(space/space_interaction, no_destroy_in_flight); + MAKE_STRING_ID(space/space_interaction, no_booster); + MAKE_STRING_ID(space/space_interaction, booster_disabled); + MAKE_STRING_ID(space/space_interaction, booster_low_energy); + MAKE_STRING_ID(space/space_interaction, booster_energy_depleted); + MAKE_STRING_ID(space/space_interaction, booster_pilot_only); + MAKE_STRING_ID(space/space_interaction, booster_not_ready); + MAKE_STRING_ID(space/space_interaction, not_group_leader_for_formation); + + MAKE_STRING_ID(ui_weapongroupassignment, not_a_pilot); + + MAKE_STRING_ID(shared, shipcomponentinstall_noinventory); + MAKE_STRING_ID(shared, shipcomponentinstall_noinventorycontainer); + MAKE_STRING_ID(shared, shipcomponentinstall_inventoryfull); + + MAKE_STRING_ID(base_player, too_many_waypoints); + + MAKE_STRING_ID(obj_attr_n, bio_link_pending); + MAKE_STRING_ID(obj_attr_n, bio_link_unknown); + + MAKE_STRING_ID(ui, quest_journal_is_full); + + MAKE_STRING_ID(shared, buffbuilder_canceled_by_recip); + MAKE_STRING_ID(shared, buffbuilder_canceled_by_buffer); + MAKE_STRING_ID(shared, buffbuilder_no_target); + MAKE_STRING_ID(shared, buffbuilder_session_not_valid); +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/SocialsManager.cpp b/engine/shared/library/sharedGame/src/shared/core/SocialsManager.cpp new file mode 100644 index 00000000..3fff1513 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SocialsManager.cpp @@ -0,0 +1,155 @@ +//====================================================================== +// +// SocialsManager.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SocialsManager.h" + +#include "UnicodeUtils.h" +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/Iff.h" +#include "sharedFoundation/Crc.h" +#include "sharedUtility/DataTable.h" + +#include + +//====================================================================== + +namespace +{ + typedef stdmap::fwd IntStringMap; + typedef stdmap::fwd StringIntMap; + + IntStringMap s_idToNameMap; + StringIntMap s_nameToIdMap; + IntStringMap s_crcToNameMap; + + bool s_installed = false; + + const std::string s_filename = "datatables/chat/social_types.iff"; + + enum DtCols + { + DC_name + }; +} + +//---------------------------------------------------------------------- + +void SocialsManager::install () +{ + InstallTimer const installTimer("SocialsManager::install "); + + DEBUG_FATAL (s_installed, ("already installed")); + load (s_filename); + s_installed = true; +} + +//---------------------------------------------------------------------- + +void SocialsManager::remove () +{ + DEBUG_FATAL (!s_installed, ("not installed")); + + s_idToNameMap.clear (); + s_nameToIdMap.clear (); + s_crcToNameMap.clear(); + s_installed = false; +} + +//---------------------------------------------------------------------- + +uint32 SocialsManager::getSocialTypeByName (const std::string & name) +{ + if (!s_installed) + install (); + + const StringIntMap::const_iterator it = s_nameToIdMap.find (name); + + if (it != s_nameToIdMap.end ()) + return (*it).second; + + return 0; +} + +//---------------------------------------------------------------------- + +bool SocialsManager::getSocialNameByType (uint32 type, std::string & name) +{ + if (!s_installed) + install (); + + const IntStringMap::const_iterator it = s_idToNameMap.find (type); + + if (it != s_idToNameMap.end ()) + { + name = (*it).second; + return true; + } + + return false; +} + +//---------------------------------------------------------------------- + +bool SocialsManager::getSocialNameByCrc(const uint32 crc, std::string & name) +{ + if (!s_installed) + install (); + + const IntStringMap::const_iterator it = s_crcToNameMap.find (crc); + + if (it != s_crcToNameMap.end ()) + { + name = (*it).second; + return true; + } + + return false; +} + +//---------------------------------------------------------------------- + +void SocialsManager::load (const std::string & filename) +{ + Iff iff; + + if (!iff.open (filename.c_str (), true)) + WARNING (true, ("Data file %s not available.", filename.c_str ())); + else + { + DataTable dt; + dt.load (iff); + iff.close (); + + const int numRows = dt.getNumRows (); + + uint32 count = 0; + for (int i = 0; i < numRows; ++i) + { + const std::string & name = Unicode::toLower (dt.getStringValue (DC_name, i)); + ++count; + + s_idToNameMap.insert (std::make_pair (count, name)); + s_crcToNameMap.insert (std::make_pair (Crc::calculate(name.c_str()), name)); + + const std::pair retval = s_nameToIdMap.insert (std::make_pair (name, count)); + + if (!retval.second) + WARNING_STRICT_FATAL (true, ("SocialsManager file '%s' duplicate social type '%s'", filename.c_str (), name.c_str ())); + } + } +} + +//---------------------------------------------------------------------- + +void SocialsManager::getCanonicalSocials (StringIntMap & sim) +{ + sim = s_nameToIdMap; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/SocialsManager.h b/engine/shared/library/sharedGame/src/shared/core/SocialsManager.h new file mode 100644 index 00000000..e89d20f1 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SocialsManager.h @@ -0,0 +1,35 @@ +//====================================================================== +// +// SocialsManager.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_SocialsManager_H +#define INCLUDED_SocialsManager_H + +//====================================================================== + +class SocialsManager +{ +public: + + typedef stdmap::fwd StringIntMap; + + static void install (); + static void remove (); + + static uint32 getSocialTypeByName (const std::string & name); + static bool getSocialNameByType (const uint32, std::string & name); + static bool getSocialNameByCrc (const uint32, std::string & name); + + static void getCanonicalSocials (StringIntMap & sim); + +private: + + static void load (const std::string & filename); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/SpaceStringIds.cpp b/engine/shared/library/sharedGame/src/shared/core/SpaceStringIds.cpp new file mode 100644 index 00000000..0ac63975 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SpaceStringIds.cpp @@ -0,0 +1,13 @@ +//====================================================================== +// +// SpaceStringIds.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SpaceStringIds.h" + +//====================================================================== + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/SpaceStringIds.h b/engine/shared/library/sharedGame/src/shared/core/SpaceStringIds.h new file mode 100644 index 00000000..137c45e6 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SpaceStringIds.h @@ -0,0 +1,36 @@ +//====================================================================== +// +// SpaceStringIds.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_SpaceStringIds_H +#define INCLUDED_SpaceStringIds_H + +//====================================================================== + +#include "StringId.h" + +//====================================================================== + +#define MAKE_STRING_ID(a, b) const StringId b(#a,#b); + +//---------------------------------------------------------------------- + +namespace SpaceStringIds +{ + MAKE_STRING_ID(space/space_interaction, wpn_fire_fail_disabled); + MAKE_STRING_ID(space/space_interaction, wpn_fire_fail_missile_acquire); + MAKE_STRING_ID(space/space_interaction, wpn_fire_fail_missile_range); + MAKE_STRING_ID(space/space_interaction, wpn_fire_fail_missile_self); + MAKE_STRING_ID(space/space_interaction, wpn_fire_fail_missile_target); + MAKE_STRING_ID(space/space_interaction, wpn_fire_fail_power); + MAKE_STRING_ID(space/space_interaction, wpn_fire_fail_ammo); + MAKE_STRING_ID(space/space_interaction, autopilot_engaged); + MAKE_STRING_ID(space/space_interaction, autopilot_disengaged); +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/SpatialChatManager.cpp b/engine/shared/library/sharedGame/src/shared/core/SpatialChatManager.cpp new file mode 100644 index 00000000..7e502210 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SpatialChatManager.cpp @@ -0,0 +1,287 @@ +//====================================================================== +// +// SpatialChatManager.cpp +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SpatialChatManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFoundation/Tag.h" +#include "sharedFile/Iff.h" +#include "UnicodeUtils.h" + +#include +#include +#include + +//====================================================================== + +namespace SpatialChatManagerNamespace +{ + typedef stdmap::fwd IntStringMap; + typedef stdmap::fwd StringIntMap; + typedef stdmap::fwd IntShortMap; + typedef stdset::fwd IntSet; + typedef stdmap >::fwd IntStringVectorMap; + + IntStringMap s_idToNameMap; + StringIntMap s_nameToIdMap; + IntShortMap s_idToVolumeMap; + IntSet s_privateIds; + IntStringVectorMap s_skillsProviding; + + uint16 s_defaultVolume = 1024; + std::vector s_defaultSkills; + + bool s_installed = false; + + const std::string s_filename = "chat/spatial_chat_types.iff"; + + namespace Tags + { + const Tag SPCT = TAG (S,P,C,T); + const Tag TYPS = TAG (T,Y,P,S); + const Tag VOLT = TAG (V,O,L,T); + const Tag PRVT = TAG (P,R,V,T); + const Tag SKCT = TAG (S,K,C,T); + const Tag VOLS = TAG (V,O,L,S); + const Tag PRIV = TAG (P,R,I,V); + const Tag SKCS = TAG (S,K,C,S); + } +} +using namespace SpatialChatManagerNamespace; + +//---------------------------------------------------------------------- + +uint32 SpatialChatManager::ms_defaultChatType; + +//---------------------------------------------------------------------- + +void SpatialChatManager::install () +{ + InstallTimer const installTimer("SpatialChatManager::install"); + + DEBUG_FATAL (s_installed, ("installed")); + + s_idToNameMap.clear (); + s_nameToIdMap.clear (); + s_idToVolumeMap.clear (); + s_privateIds.clear (); + s_skillsProviding.clear (); + + ms_defaultChatType = 1; + + s_installed = true; + + load (s_filename); +} + +//---------------------------------------------------------------------- + +void SpatialChatManager::remove () +{ + DEBUG_FATAL (!s_installed, ("not installed")); + + s_idToNameMap.clear (); + s_nameToIdMap.clear (); + s_idToVolumeMap.clear (); + s_privateIds.clear (); + s_skillsProviding.clear (); + + s_installed = false; +} + +//---------------------------------------------------------------------- + +/** +* @param name must be lowercase canonical name +*/ + +uint32 SpatialChatManager::getChatTypeByName (const std::string & name) +{ + DEBUG_FATAL (!s_installed, ("not installed")); + + const StringIntMap::const_iterator it = s_nameToIdMap.find (name); + + if (it != s_nameToIdMap.end ()) + return (*it).second; + + return 0; +} + +//---------------------------------------------------------------------- + +bool SpatialChatManager::getChatNameByType (uint32 type, std::string & name) +{ + DEBUG_FATAL (!s_installed, ("not installed")); + + const IntStringMap::const_iterator it = s_idToNameMap.find (type); + + if (it != s_idToNameMap.end ()) + { + name = (*it).second; + return true; + } + + return false; +} + +//---------------------------------------------------------------------- + +bool SpatialChatManager::isPrivate (uint32 type) +{ + return s_privateIds.find (type) != s_privateIds.end (); +} + +//---------------------------------------------------------------------- + +uint16 SpatialChatManager::getVolume (uint32 type) +{ + const IntShortMap::const_iterator it = s_idToVolumeMap.find (type); + + if (it != s_idToVolumeMap.end ()) + return (*it).second; + + return s_defaultVolume; +} + +//---------------------------------------------------------------------- + +const stdvector::fwd &SpatialChatManager::getSkillsProviding(uint32 type) +{ + const IntStringVectorMap::const_iterator it = s_skillsProviding.find(type); + if (it != s_skillsProviding.end()) + return (*it).second; + return s_defaultSkills; +} + +//---------------------------------------------------------------------- + +void SpatialChatManager::load (const std::string & filename) +{ + Iff iff; + if (!iff.open (filename.c_str (), true)) + { + WARNING_STRICT_FATAL (true, ("SpatialChatManager No such file: '%s'", filename.c_str ())); + return; + } + + if (!iff.enterForm (Tags::SPCT, true)) + { + WARNING_STRICT_FATAL (true, ("SpatialChatManager file '%s' had no tag SPCT", filename.c_str ())); + return; + } + + if (!iff.enterForm (TAG_0000, true)) + { + WARNING_STRICT_FATAL (true, ("SpatialChatManager file '%s' had no tag 0000", filename.c_str ())); + return; + } + + if (!iff.enterChunk (Tags::TYPS, true)) + { + WARNING_STRICT_FATAL (true, ("SpatialChatManager file '%s' had no tag TYPS", filename.c_str ())); + return; + } + + uint32 count = 0; + while (iff.getChunkLengthLeft () > 0) + { + const std::string name = Unicode::toLower (iff.read_stdstring ()); + + ++count; + + s_idToNameMap.insert (std::make_pair (count, name)); + + const std::pair retval = s_nameToIdMap.insert (std::make_pair (name, count)); + + if (!retval.second) + WARNING_STRICT_FATAL (true, ("SpatialChatManager file '%s' duplicate chat type '%s'", filename.c_str (), name.c_str ())); + } + + iff.exitChunk (Tags::TYPS); + + if (!iff.enterForm (Tags::VOLS, true)) + { + WARNING_STRICT_FATAL (true, ("SpatialChatManager file '%s' had no tag VOLS", filename.c_str ())); + return; + } + + while (iff.enterChunk (Tags::VOLT, true)) + { + const std::string name = Unicode::toLower (iff.read_stdstring ()); + const uint16 volume = iff.read_uint16 (); + + if (name.empty ()) + { + s_defaultVolume = volume; + } + else + { + const uint32 id = getChatTypeByName (name); + + if (id) + s_idToVolumeMap.insert (std::make_pair (id, volume)); + else + WARNING_STRICT_FATAL (true, ("SpatialChatManager file '%s' invalid chat type '%s' for volume", filename.c_str (), name.c_str ())); + } + + iff.exitChunk (Tags::VOLT); + } + + iff.exitForm (Tags::VOLS); + + if (!iff.enterForm (Tags::PRIV, true)) + { + WARNING_STRICT_FATAL (true, ("SpatialChatManager file '%s' had no tag PRIV", filename.c_str ())); + return; + } + + while (iff.enterChunk (Tags::PRVT, true)) + { + const std::string name = iff.read_stdstring (); + + uint32 id = getChatTypeByName (name); + + if (id) + s_privateIds.insert (id); + else + { + WARNING_STRICT_FATAL (true, ("SpatialChatManager file '%s' invalid chat type '%s' for private", filename.c_str (), name.c_str ())); + } + + iff.exitChunk (Tags::PRVT); + } + + iff.exitForm (Tags::PRIV); + + if (!iff.enterForm (Tags::SKCS, true)) + { + WARNING_STRICT_FATAL (true, ("SpatialChatManager file '%s' had no tag SKCS", filename.c_str ())); + return; + } + + while (iff.enterChunk (Tags::SKCT, true)) + { + const std::string typeName = iff.read_stdstring (); + const std::string skillName = iff.read_stdstring (); + + uint32 id = getChatTypeByName (typeName); + if (id) + s_skillsProviding[id].push_back(skillName); + else + { + WARNING_STRICT_FATAL (true, ("SpatialChatManager file '%s' invalid chat type '%s' for skill", filename.c_str (), typeName.c_str ())); + } + + iff.exitChunk (Tags::SKCT); + } + + iff.exitForm (Tags::SKCS); + +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/SpatialChatManager.h b/engine/shared/library/sharedGame/src/shared/core/SpatialChatManager.h new file mode 100644 index 00000000..2bfb722d --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/SpatialChatManager.h @@ -0,0 +1,43 @@ +//====================================================================== +// +// SpatialChatManager.h +// copyright (c) 2002 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_SpatialChatManager_H +#define INCLUDED_SpatialChatManager_H + +//====================================================================== + +class SpatialChatManager +{ +public: + static void install (); + static void remove (); + + static uint32 getChatTypeByName (const std::string & name); + static uint32 getDefaultChatType (); + static bool getChatNameByType (uint32 type, std::string & name); + static const stdvector::fwd & getSkillsProviding (uint32 type); + + static bool isPrivate (uint32 type); + static uint16 getVolume (uint32 type); + +private: + + static void load (const std::string & filename); + + static uint32 ms_defaultChatType; +}; + +//---------------------------------------------------------------------- + +inline uint32 SpatialChatManager::getDefaultChatType () +{ + return ms_defaultChatType; +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/TextIterator.cpp b/engine/shared/library/sharedGame/src/shared/core/TextIterator.cpp new file mode 100644 index 00000000..6dde1022 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/TextIterator.cpp @@ -0,0 +1,288 @@ +// ============================================================================ +// +// TextIterator.cpp +// Copyright Sony Online Entertainment +// +// ============================================================================ + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/TextIterator.h" + +#include "UnicodeUtils.h" + +// ============================================================================ +// +// TextIterator +// +// ============================================================================ + +//----------------------------------------------------------------------------- +TextIterator::TextIterator(Unicode::String const &text) + : m_rawText(text) + , m_currentColorCode() + , m_rawIndex(0) + , m_iterPrintableIndex(m_rawText.begin()) +{ +} + +//----------------------------------------------------------------------------- +void TextIterator::setRawText(Unicode::String const &text) +{ + m_rawText = text; +} + +//----------------------------------------------------------------------------- +Unicode::String const &TextIterator::getRawText() const +{ + return m_rawText; +} + +//----------------------------------------------------------------------------- +void TextIterator::skipUnPrintable() +{ + DEBUG_FATAL((m_iterPrintableIndex == m_rawText.begin()) && (m_rawIndex != 0), ("Index should be reset to zero: %d", m_rawIndex)); + + for (; m_iterPrintableIndex != m_rawText.end();) + { + if ((*m_iterPrintableIndex) == '\\') + { + ++m_iterPrintableIndex; + ++m_rawIndex; + + if ((*m_iterPrintableIndex) == '#') + { + ++m_iterPrintableIndex; + ++m_rawIndex; + + if (m_iterPrintableIndex != m_rawText.end()) + { + if ((*m_iterPrintableIndex) == '.') + { + // Color escape sequence: \#. set to default color + + ++m_iterPrintableIndex; + ++m_rawIndex; + } + else if ((*m_iterPrintableIndex) == 'p') + { + // Color escape sequence: \#p + + ++m_iterPrintableIndex; + ++m_rawIndex; + + for (; m_iterPrintableIndex != m_rawText.end();) + { + ++m_iterPrintableIndex; + ++m_rawIndex; + + if ((*m_iterPrintableIndex) == ' ') + { + break; + } + } + } + else + { + // Color code + + int count = 0; + m_currentColorCode = Unicode::narrowToWide("\\#"); + + for (; m_iterPrintableIndex != m_rawText.end();) + { + m_currentColorCode += (*m_iterPrintableIndex); + + ++m_iterPrintableIndex; + ++m_rawIndex; + + if (++count == 6) + { + break; + } + } + } + } + } + else if ((*m_iterPrintableIndex) == '>') + { + // Indentation setting escape sequence \>xxx + + ++m_iterPrintableIndex; + ++m_rawIndex; + + int count = 0; + + for (; m_iterPrintableIndex != m_rawText.end();) + { + ++m_iterPrintableIndex; + ++m_rawIndex; + + if (++count == 3) + { + break; + } + } + } + else if ((*m_iterPrintableIndex) == '@') + { + // Tab setting escape sequence \@xx + + ++m_iterPrintableIndex; + ++m_rawIndex; + + int count = 0; + + for (; m_iterPrintableIndex != m_rawText.end();) + { + ++m_iterPrintableIndex; + ++m_rawIndex; + + if (++count == 2) + { + break; + } + } + } + } + else + { + break; + } + } +} + +//----------------------------------------------------------------------------- +Unicode::String TextIterator::getPrintableText() +{ + Unicode::String result; + + // Set the search to start at the beginning of the text + + m_iterPrintableIndex = m_rawText.begin(); + m_rawIndex = 0; + + // Move through the text keeping on printable text + + while (m_iterPrintableIndex != m_rawText.end()) + { + skipUnPrintable(); + + if (m_iterPrintableIndex != m_rawText.end()) + { + result += (*m_iterPrintableIndex); + ++m_iterPrintableIndex; + ++m_rawIndex; + } + } + + return result; +} + +//----------------------------------------------------------------------------- +void TextIterator::insertTextAtFirstPrintablePosition(Unicode::String const &text) +{ + // Set the search to start at the beginning of the text + + m_iterPrintableIndex = m_rawText.begin(); + m_rawIndex = 0; + + // Move to the first non-coded position + + skipUnPrintable(); + + // Insert the text + + m_rawText.insert(m_rawIndex, text); +} + +//----------------------------------------------------------------------------- +void TextIterator::insertTextAtPrintablePosition(int const position, Unicode::String const &text) +{ + // Set the search to start at the beginning of the text + + m_iterPrintableIndex = m_rawText.begin(); + m_rawIndex = 0; + + // Search for the specified printable position + + if ((position >= 0) && + (position < static_cast(m_rawText.size()))) + { + int index = 0; + + skipUnPrintable(); + + while (index != position) + { + if (m_iterPrintableIndex != m_rawText.end()) + { + ++m_iterPrintableIndex; + ++m_rawIndex; + ++index; + + skipUnPrintable(); + } + else + { + break; + } + } + + // Insert the text + + if (m_iterPrintableIndex != m_rawText.end()) + { + m_rawText.insert(m_rawIndex, text); + } + } +} + +//----------------------------------------------------------------------------- +void TextIterator::insertCurrentColorCodeAtPrintablePosition(int const position) +{ + // Set the search to start at the beginning of the text + + m_iterPrintableIndex = m_rawText.begin(); + m_rawIndex = 0; + + // Search for the specified printable position + + if ((position >= 0) && + (position < static_cast(m_rawText.size()))) + { + int index = 0; + + skipUnPrintable(); + + while (index != position) + { + if (m_iterPrintableIndex != m_rawText.end()) + { + ++m_iterPrintableIndex; + ++m_rawIndex; + ++index; + + skipUnPrintable(); + } + else + { + break; + } + } + + // Insert the current color code + + if (m_iterPrintableIndex != m_rawText.end()) + { + m_rawText.insert(m_rawIndex, m_currentColorCode); + } + } +} + +//----------------------------------------------------------------------------- +void TextIterator::appendText(Unicode::String const &text) +{ + m_rawText += text; +} + +// ============================================================================ diff --git a/engine/shared/library/sharedGame/src/shared/core/TextIterator.h b/engine/shared/library/sharedGame/src/shared/core/TextIterator.h new file mode 100644 index 00000000..c1099bb9 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/TextIterator.h @@ -0,0 +1,47 @@ +// ============================================================================ +// +// TextIterator.h +// Copyright Sony Online Entertainment +// +// ============================================================================ + +#ifndef INCLUDED_TextIterator_H +#define INCLUDED_TextIterator_H + +#include "sharedMath/PackedRgb.h" + +// ---------------------------------------------------------------------------- +class TextIterator +{ +public: + + TextIterator(Unicode::String const &text); + + void setRawText(Unicode::String const &text); + + Unicode::String const &getRawText() const; + Unicode::String getPrintableText(); + + void insertTextAtFirstPrintablePosition(Unicode::String const &text); + void insertTextAtPrintablePosition(int const position, Unicode::String const &text); + void insertCurrentColorCodeAtPrintablePosition(int const position); + void appendText(Unicode::String const &text); + +private: + + void skipUnPrintable(); + + Unicode::String m_rawText; + Unicode::String m_currentColorCode; + int m_rawIndex; + Unicode::String::const_iterator m_iterPrintableIndex; + + // Disabled + + TextIterator(); + TextIterator &operator =(TextIterator const &); +}; + +// ============================================================================ + +#endif // INCLUDED_TextIterator_H diff --git a/engine/shared/library/sharedGame/src/shared/core/TextManager.cpp b/engine/shared/library/sharedGame/src/shared/core/TextManager.cpp new file mode 100644 index 00000000..741f494e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/TextManager.cpp @@ -0,0 +1,409 @@ +// ============================================================================ +// +// TextManager.cpp +// Copyright Sony Online Entertainment +// +// ============================================================================ + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/TextManager.h" + +#include "LocalizationManager.h" +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/Iff.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/NetworkId.h" +#include "sharedGame/TextIterator.h" +#include "sharedMath/PackedRgb.h" +#include "sharedUtility/DataTable.h" +#include "UnicodeUtils.h" +#include "utf8.h" + +#include +#include + +// ============================================================================ +// +// TextManagerNamespace +// +// ============================================================================ + +// ---------------------------------------------------------------------------- +namespace TextManagerNamespace +{ + typedef std::map CussWords; // string/allow sub-string match + typedef std::vector UnicodeStringVector; + + bool s_installed = false; + CussWords s_cussWords; + + void getAppropriateWord(Unicode::String &text); + void tokenize(const Unicode::String &source, UnicodeStringVector &target); + void getFilterLetter(Unicode::String &filterLetter); + bool isExactMatch(Unicode::String const &text); + bool isAlpha(Unicode::unicode_char_t const character); + void checkText(Unicode::String &text, int const startIndex, int const endIndex); +} + +using namespace TextManagerNamespace; + +// ---------------------------------------------------------------------------- +bool TextManagerNamespace::isExactMatch(Unicode::String const &text) +{ + bool result = false; + Unicode::String lowerText(Unicode::toLower(text)); + CussWords::iterator iterCussWords = s_cussWords.find(lowerText); + + if (iterCussWords != s_cussWords.end()) + { + result = true; + } + + return result; +} + +// ---------------------------------------------------------------------------- +void TextManagerNamespace::getAppropriateWord(Unicode::String &text) +{ + if (isExactMatch(text)) + { + // An exact word match was found, plug the bad word with symbols + + unsigned int const letterCount = text.size(); + Unicode::String filterLetter; + + // Found a bad word, replace the word + + for (unsigned int i = 0; i < letterCount; ++i) + { + getFilterLetter(filterLetter); + + text[i] = filterLetter[0]; + } + } + else + { + // See if we can find a non-exact match, but a match by removing + // all non-alphabet letters and condensing the result into a word + + Unicode::String alphabetString; + alphabetString.reserve(text.size()); + int index = 0; + + for (unsigned int i = 0; i < text.size(); ++i) + { + if (isAlpha(text[i])) + { + alphabetString.push_back(text[i]); + ++index; + } + } + + if (isExactMatch(alphabetString)) + { + // Now we found an exact match so plug all the alpha letters + + Unicode::String filterLetter; + + for (unsigned int i = 0; i < text.size(); ++i) + { + if (isAlpha(text[i])) + { + getFilterLetter(filterLetter); + + text[i] = filterLetter[0]; + } + } + } + else + { + // Sub-string search time for words that are listed for sub-string searches + + Unicode::String lowerText(Unicode::toLower(text)); + unsigned int findStartPosition = 0; + + for (;;) + { + bool done = true; + CussWords::iterator iterCussWords = s_cussWords.begin(); + + for (; iterCussWords != s_cussWords.end(); ++iterCussWords) + { + Unicode::String const &cussWord = iterCussWords->first; + bool const allowSubStringSearch = iterCussWords->second; + + if (!allowSubStringSearch) + { + continue; + } + + unsigned int index = lowerText.find(cussWord, findStartPosition); + + if (index != Unicode::String::npos) + { + findStartPosition = index; + + // Found a bad word, replace the word + + unsigned int const letterCount = cussWord.size(); + Unicode::String filterLetter; + + for (unsigned int i = 0; i < letterCount; ++i) + { + getFilterLetter(filterLetter); + + text[index + i] = filterLetter[0]; + ++findStartPosition; + } + + // We are not done with a clean run so start over in case + // there are multiple cuss words in the same string + + done = false; + break; + } + } + + if (done) + { + break; + } + } + } + } +} + +// ---------------------------------------------------------------------------- +void TextManagerNamespace::getFilterLetter(Unicode::String &filterLetter) +{ + int number = rand() % 7; + + switch (number) + { + default: + case 1: { filterLetter = Unicode::narrowToWide("@"); } break; + case 2: { filterLetter = Unicode::narrowToWide("#"); } break; + case 3: { filterLetter = Unicode::narrowToWide("$"); } break; + case 4: { filterLetter = Unicode::narrowToWide("%"); } break; + case 5: { filterLetter = Unicode::narrowToWide("&"); } break; + case 6: { filterLetter = Unicode::narrowToWide("*"); } break; + } +} + +// ---------------------------------------------------------------------------- +void TextManagerNamespace::tokenize(const Unicode::String &source, UnicodeStringVector &target) +{ + UnicodeStringVector unicodeStringVector; + + IGNORE_RETURN(Unicode::tokenize(source, unicodeStringVector)); + + target = unicodeStringVector; +} + +// ---------------------------------------------------------------------------- +bool TextManagerNamespace::isAlpha(Unicode::unicode_char_t const character) +{ + bool result = false; + + if ( (character <= 255) + && isalpha(character)) + { + result = true; + } + + return result; +} + +// ---------------------------------------------------------------------------- +void TextManagerNamespace::checkText(Unicode::String &text, int const startIndex, int const endIndex) +{ + int const length = endIndex - startIndex; + Unicode::String subString(text.substr(startIndex, length)); + + getAppropriateWord(subString); + + // Put the fixed text back into the string + + for (int index = 0; index < (endIndex - startIndex); ++index) + { + text[startIndex + index] = subString[index]; + } +} + +// ============================================================================ +// +// TextManager +// +// ============================================================================ + +// ---------------------------------------------------------------------------- +void TextManager::install() +{ + InstallTimer const installTimer("TextManager::install"); + + DEBUG_FATAL(s_installed,("TextManager already installed.\n")); + + // Cuss words + + char const profanityFile[] = "datatables/chat/profanity_filter.iff"; + Iff profanityFilterIff; + + if (profanityFilterIff.open(profanityFile, true)) + { + DataTable dataTable; + + dataTable.load(profanityFilterIff); + + int const rowCount = dataTable.getNumRows(); + + s_cussWords.clear(); + + // Add all the words to the list in lowercase + + for (int index = 0; index < rowCount; ++index) + { + std::string const &word = dataTable.getStringValue(0, index); + bool const allowSubStringMatch = (dataTable.getIntValue(1, index) != 0); + + Unicode::UTF16 wordBuf[50]; + + Unicode::UTF8_convertToUTF16(const_cast(word.c_str()), wordBuf, sizeof(wordBuf)/sizeof(wordBuf[0])); + + Unicode::String const &unicodeWord = Unicode::String(wordBuf); + + s_cussWords.insert(std::make_pair(Unicode::toLower(unicodeWord), allowSubStringMatch)); + } + } + else + { + DEBUG_WARNING(true, ("Unable to load the profanity filter data table: %s", profanityFile)); + } + + ExitChain::add(remove,"TextManager::remove"); + s_installed = true; +} + +// ---------------------------------------------------------------------------- +void TextManager::remove() +{ + s_cussWords.clear(); + + s_installed = false; +} + +// Filter the text for any profanity. +// ---------------------------------------------------------------------------- +Unicode::String TextManager::filterText(Unicode::String const &text) +{ + Unicode::String result(text); + Unicode::String::const_iterator iterText = text.begin(); + int startIndex = Unicode::String::npos; + int currentIndex = 0; + + { + // Walk through the text finding sections of alpha characters. + // Each set of alpha characters is checked for cuss words, all + // non-alphabet is skipped and preserved. + + for (; iterText != text.end(); ++iterText) + { + Unicode::unicode_char_t const character = (*iterText); + + if ( (static_cast(startIndex) == Unicode::String::npos) + && isAlpha(character)) + { + startIndex = currentIndex; + } + else if ( (static_cast(startIndex) != Unicode::String::npos) + && !isAlpha(character)) + { + checkText(result, startIndex, currentIndex); + + startIndex = Unicode::String::npos; + } + + ++currentIndex; + } + + // Possibly check the last word + + if (static_cast(startIndex) != Unicode::String::npos) + { + checkText(result, startIndex, currentIndex); + } + } + + { + // Walk through the text finding sections between spaces. + // Each set of text between spaces is checked for cuss words, + // all non-alphabet is skipped and preserved. + + iterText = text.begin(); + startIndex = Unicode::String::npos; + currentIndex = 0; + + for (; iterText != text.end(); ++iterText) + { + Unicode::unicode_char_t const character = (*iterText); + + if ( (static_cast(startIndex) == Unicode::String::npos) + && character != static_cast(' ')) + { + startIndex = currentIndex; + } + else if ( (static_cast(startIndex) != Unicode::String::npos) + && character == static_cast(' ')) + { + checkText(result, startIndex, currentIndex); + + startIndex = Unicode::String::npos; + } + + ++currentIndex; + } + + // Possibly check the last word + + if (static_cast(startIndex) != Unicode::String::npos) + { + checkText(result, startIndex, currentIndex); + } + } + + return result; +} + +// ---------------------------------------------------------------------------- +bool TextManager::isAppropriateText(Unicode::String const &text) +{ + bool result = false; + Unicode::String filteredText(filterText(text)); + + // If the text looks clean so far, check the text again with color + // codes removed. + + if (filteredText == text) + { + result = true; + + TextIterator textIterator(filteredText); + Unicode::String colorCodeRemovedText(textIterator.getPrintableText()); + + // Make sure there was some color codes removed before we waste time + // trying to filter it + + if (filteredText.size() != colorCodeRemovedText.size()) + { + Unicode::String colorCodeRemovedFilteredText(filterText(colorCodeRemovedText)); + + if (colorCodeRemovedText != colorCodeRemovedFilteredText) + { + result = false; + } + } + } + + return result; +} + +// ============================================================================ diff --git a/engine/shared/library/sharedGame/src/shared/core/TextManager.h b/engine/shared/library/sharedGame/src/shared/core/TextManager.h new file mode 100644 index 00000000..996debdc --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/TextManager.h @@ -0,0 +1,36 @@ +// ============================================================================ +// +// TextManager.h +// Copyright Sony Online Entertainment +// +// ============================================================================ + +#ifndef INCLUDED_TextManager_H +#define INCLUDED_TextManager_H + +class PackedRgb; +class RegexList; + +// ---------------------------------------------------------------------------- +class TextManager +{ +public: + + static void install(); + +public: + + static Unicode::String filterText(Unicode::String const &text); + static bool isAppropriateText(Unicode::String const &text); + +private: + + static void remove(); + + TextManager(); + ~TextManager(); +}; + +// ============================================================================ + +#endif // INCLUDED_TextManager_H diff --git a/engine/shared/library/sharedGame/src/shared/core/Universe.cpp b/engine/shared/library/sharedGame/src/shared/core/Universe.cpp new file mode 100644 index 00000000..5d5186d4 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/Universe.cpp @@ -0,0 +1,134 @@ +//=================================================================== +// +// Universe.cpp +// +// copyright 2002, sony online entertainment +// +//=================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/Universe.h" + +#include "sharedFoundation/Crc.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedGame/ResourceClassObject.h" + +#include + +// ====================================================================== + +Universe * Universe::ms_theInstance = NULL; +bool Universe::ms_installed = false; + +//=================================================================== + +void Universe::installDerived(Universe *derivedInstance) +{ + DEBUG_FATAL(ms_installed || ms_theInstance!=NULL,("Installed Universe twice.\n")); + ms_theInstance = derivedInstance; + ms_installed = true; + + ExitChain::add(&remove, "Universe::remove"); +} + +// ---------------------------------------------------------------------- + +void Universe::remove() +{ + DEBUG_FATAL(!ms_installed,("Universe was not installed.\n")); + delete ms_theInstance; + ms_theInstance = 0; +} + +Universe::Universe() : + m_resourceClassNameMap (new ResourceClassNameMap), + m_resourceClassNameCrcMap (new ResourceClassNameCrcMap), + m_resourceTreeRoot (NULL) +{ + ResourceClassObject::install(); // sets up some static strings used by the import process +} + +// ---------------------------------------------------------------------- + +Universe::~Universe() +{ + for (ResourceClassNameMap::iterator i=m_resourceClassNameMap->begin(); i!=m_resourceClassNameMap->end(); ++i) + { + delete i->second; + } + delete m_resourceClassNameMap; + delete m_resourceClassNameCrcMap; + + m_resourceClassNameMap = 0; + m_resourceClassNameCrcMap = 0; + m_resourceTreeRoot = 0; +} + +// ---------------------------------------------------------------------- + +ResourceClassObject *Universe::getResourceClassByName(const std::string &name) const +{ + ResourceClassNameMap::iterator i=m_resourceClassNameMap->find(name); + if (i!=m_resourceClassNameMap->end()) + return (*i).second; + else + return 0; +} + +// ---------------------------------------------------------------------- + +ResourceClassObject *Universe::getResourceClassByNameCrc(uint32 nameCrc) const +{ + ResourceClassNameCrcMap::iterator i=m_resourceClassNameCrcMap->find(nameCrc); + if (i!=m_resourceClassNameCrcMap->end()) + return (*i).second; + else + return 0; +} + +// ---------------------------------------------------------------------- + +/** + * Registers a new ResourceClassObject + * Puts the object into a map of name->object, so that it can be found later. + */ + +void Universe::registerResourceClassObject (ResourceClassObject &newResourceClass) +{ + if (newResourceClass.isRoot()) + m_resourceTreeRoot=&newResourceClass; + ResourceClassNameMap::iterator i=m_resourceClassNameMap->find(newResourceClass.getResourceClassName()); + if (i!=m_resourceClassNameMap->end()) + DEBUG_WARNING(true,("RESOURCE TREE ERROR: Resource class %s appears multiple times in the hierarchy. Probably there is a problem with the resource data table. This may cause new pools to get spawned when they shouldn't.\n",newResourceClass.getResourceClassName().c_str())); + else + { + (*m_resourceClassNameMap)[newResourceClass.getResourceClassName()]=&newResourceClass; + (*m_resourceClassNameCrcMap)[Crc::calculate(newResourceClass.getResourceClassName().c_str())]=&newResourceClass; + } +} + +//---------------------------------------------------------------------- + +bool Universe::derivesFromResource (const std::string & base, const std::string & leaf) const +{ + const ResourceClassObject * const baseClass = getResourceClassByName (base); + const ResourceClassObject * leafClass = getResourceClassByName (leaf); + + WARNING (!baseClass, ("Universe::derivesFromResource base class [%s] unknown", base.c_str ())); + WARNING (!leafClass, ("Universe::derivesFromResource leaf class [%s] unknown", leaf.c_str ())); + + if (!baseClass || !leafClass) + return false; + + while (leafClass != 0) + { + if (leafClass == baseClass) + return true; + + leafClass = leafClass->getParent (); + } + + return false; +} + +//=================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/Universe.h b/engine/shared/library/sharedGame/src/shared/core/Universe.h new file mode 100644 index 00000000..32cad7ea --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/Universe.h @@ -0,0 +1,78 @@ +// ====================================================================== +// +// Universe.h +// +// Copyright 2002 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_Universe_H +#define INCLUDED_Universe_H + +class ResourceClassObject; + +// ====================================================================== + +/** + * Singleton that manages Universe objects and functions that are global + * to the entire game universe. Client and Server should both derive + * specific versions of this for their own purposes. + */ +class Universe +{ + public: + static Universe & getInstance (); + + public: + ResourceClassObject * getResourceTreeRoot () const; + ResourceClassObject * getResourceClassByName (const std::string &name) const; + ResourceClassObject * getResourceClassByNameCrc (uint32 nameCrc) const; + void registerResourceClassObject (ResourceClassObject &newClass); + virtual void resourceClassTreeLoaded (stdmap::fwd &resourceClasses) = 0; + virtual ResourceClassObject * makeResourceClassObject () = 0; + + bool derivesFromResource (const std::string & base, const std::string & leaf) const; + + protected: + // + // Resource Class Objects + // + typedef stdmap::fwd ResourceClassNameMap; + typedef stdmap::fwd ResourceClassNameCrcMap; + ResourceClassNameMap * m_resourceClassNameMap; + ResourceClassNameCrcMap * m_resourceClassNameCrcMap; + ResourceClassObject * m_resourceTreeRoot; + + protected: + static void installDerived (Universe *derivedInstance); + static void remove (); + + Universe(); + virtual ~Universe(); + + static Universe *ms_theInstance; + static bool ms_installed; +}; + +// ====================================================================== + +/** +* Get the root node of the resource hierarchy +*/ + +inline ResourceClassObject *Universe::getResourceTreeRoot() const +{ + return m_resourceTreeRoot; +} + +// ---------------------------------------------------------------------- + +inline Universe &Universe::getInstance() +{ + DEBUG_FATAL(!ms_theInstance,("Called Universe::getInstance() before Universe::install()\n")); + return *ms_theInstance; +} + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/core/WearableEntry.cpp b/engine/shared/library/sharedGame/src/shared/core/WearableEntry.cpp new file mode 100644 index 00000000..767c20f4 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/WearableEntry.cpp @@ -0,0 +1,116 @@ +// ====================================================================== +// +// WearableEntry.cpp +// copyright (c) 2001 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/WearableEntry.h" + +#include "sharedFoundation/NetworkIdArchive.h" + + +// ====================================================================== + +WearableEntry::WearableEntry(const std::string& appearance, int arrangement, const NetworkId& id, int sharedTemplate) : + m_appearanceString(appearance), + m_arrangement(arrangement), + m_networkId(id), + m_objectTemplate(sharedTemplate), + m_weaponSharedBaselines(), + m_weaponSharedNpBaselines() +{ + +} + +//------------------------------------------------------------------------------------------ + +WearableEntry::WearableEntry(const std::string& appearance, int arrangement, const NetworkId& id, int sharedTemplate, const BaselinesMessage * weaponSharedBaselines, const BaselinesMessage * weaponSharedNpBaselines) : + m_appearanceString(appearance), + m_arrangement(arrangement), + m_networkId(id), + m_objectTemplate(sharedTemplate), + m_weaponSharedBaselines(weaponSharedBaselines), + m_weaponSharedNpBaselines(weaponSharedNpBaselines) +{ +} + +//------------------------------------------------------------------------------------------ + +WearableEntry::WearableEntry() : + m_appearanceString(""), + m_arrangement(-1), + m_networkId(NetworkId::cms_invalid), + m_objectTemplate(0), + m_weaponSharedBaselines(), + m_weaponSharedNpBaselines() +{ + +} + +//------------------------------------------------------------------------------------------ + +WearableEntry::WearableEntry(const WearableEntry& rhs) : + m_appearanceString(rhs.m_appearanceString), + m_arrangement(rhs.m_arrangement), + m_networkId(rhs.m_networkId), + m_objectTemplate(rhs.m_objectTemplate), + m_weaponSharedBaselines(rhs.m_weaponSharedBaselines), + m_weaponSharedNpBaselines(rhs.m_weaponSharedNpBaselines) +{ + +} + +//------------------------------------------------------------------------------------------ + +WearableEntry& WearableEntry::operator=(const WearableEntry& rhs) +{ + m_appearanceString = rhs.m_appearanceString; + m_arrangement = rhs.m_arrangement; + m_networkId = rhs.m_networkId; + m_objectTemplate = rhs.m_objectTemplate; + m_weaponSharedBaselines = rhs.m_weaponSharedBaselines; + m_weaponSharedNpBaselines = rhs.m_weaponSharedNpBaselines; + + return *this; +} + +//------------------------------------------------------------------------------------------ + +namespace Archive +{ + void get(ReadIterator & source, WearableEntry & target) + { + get(source, target.m_appearanceString); + get(source, target.m_arrangement); + get(source, target.m_networkId); + get(source, target.m_objectTemplate); + + bool isWeapon; + get(source, isWeapon); + if (isWeapon) + { + target.m_weaponSharedBaselines = boost::shared_ptr(new BaselinesMessage(source)); + target.m_weaponSharedNpBaselines = boost::shared_ptr(new BaselinesMessage(source)); + } + } + + void put(ByteStream & target, const WearableEntry & source) + { + put(target, source.m_appearanceString); + put(target, source.m_arrangement); + put(target, source.m_networkId); + put(target, source.m_objectTemplate); + + bool isWeapon = (source.m_weaponSharedBaselines.get() != NULL); + put(target, isWeapon); + if (isWeapon) + { + source.m_weaponSharedBaselines->pack(target); + source.m_weaponSharedNpBaselines->pack(target); + } + } +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/core/WearableEntry.h b/engine/shared/library/sharedGame/src/shared/core/WearableEntry.h new file mode 100644 index 00000000..6af2afdb --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/core/WearableEntry.h @@ -0,0 +1,64 @@ +// ====================================================================== +// +// WearableEntry.h +// copyright (c) 2001 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_WearableEntry_H +#define INCLUDED_WearableEntry_H + +// ====================================================================== + +#include "Archive/AutoByteStream.h" +#include "sharedFoundation/NetworkId.h" +#include "sharedNetworkMessages/BaselinesMessage.h" +#include "boost/smart_ptr.hpp" + + +class WearableEntry; + +namespace Archive +{ + void get(ReadIterator & source, WearableEntry & target); + void put(ByteStream & target, const WearableEntry & source); +} + +// ====================================================================== + +class WearableEntry +{ + friend void Archive::get(ReadIterator & source, WearableEntry & target); + friend void Archive::put(ByteStream & target, const WearableEntry & source); + + public: + WearableEntry(const std::string&, int, const NetworkId&, int); + WearableEntry(const std::string&, int, const NetworkId&, int, const BaselinesMessage *, const BaselinesMessage *); + WearableEntry(); + WearableEntry(const WearableEntry&); + WearableEntry& operator=(const WearableEntry&); + + std::string m_appearanceString; + int m_arrangement; + NetworkId m_networkId; + int m_objectTemplate; + boost::shared_ptr m_weaponSharedBaselines; + boost::shared_ptr m_weaponSharedNpBaselines; + + bool operator==(const WearableEntry&) const; + +private: + void clearWeaponBaseLines(); +}; + +//------------------------------------------------------------------------------------------ + + +inline bool WearableEntry::operator==(const WearableEntry & rhs) const +{ + return this == &rhs || (m_networkId == rhs.m_networkId); +} + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/dynamics/ShipDynamicsModel.cpp b/engine/shared/library/sharedGame/src/shared/dynamics/ShipDynamicsModel.cpp new file mode 100644 index 00000000..ab3572a5 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/dynamics/ShipDynamicsModel.cpp @@ -0,0 +1,290 @@ +// ====================================================================== +// +// ShipDynamicsModel.cpp +// asommers +// +// copyright 2004, sony online entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipDynamicsModel.h" + +#include "sharedGame/ShipObjectInterface.h" +#include "sharedTerrain/TerrainObject.h" + +// ====================================================================== +// ShipDynamicsModelNamespace +// ====================================================================== + +namespace ShipDynamicsModelNamespace +{ + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + bool s_clampMovementToZoneVolume = true; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + void updateAxis(float & currentRate, float const controlPosition, float const maximumRate, float const acceleration, float const deceleration, float const elapsedTime) + { + float const desiredRate = controlPosition * maximumRate; + + if (currentRate < desiredRate) + { + currentRate += acceleration * elapsedTime; + + if (currentRate > desiredRate) + currentRate = desiredRate; + } + else + if (currentRate > desiredRate) + { + currentRate -= deceleration * elapsedTime; + + if (currentRate < desiredRate) + currentRate = desiredRate; + } + } + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + void model(Transform & transform, Vector & velocity, float const elapsedTime, float const yawRate, float const pitchRate, float const rollRate, float const speed, float const slideDampener) + { + //-- Model yaw + { + transform.yaw_l(yawRate * elapsedTime); + } + + //-- Model pitch + { + transform.pitch_l(pitchRate * elapsedTime); + } + + //-- Model roll + { + transform.roll_l(rollRate * elapsedTime); + } + + //-- Model speed + { + if (slideDampener == 0.0f) + { + // 0.0f means no sliding at all + velocity = transform.getLocalFrameK_p() * speed; + } + else + { + velocity += transform.getLocalFrameK_p() * speed * slideDampener * elapsedTime; + + float const magnitudeSquared = velocity.magnitudeSquared(); + if (magnitudeSquared > sqr(speed)) + { + IGNORE_RETURN(velocity.normalize()); + velocity *= speed; + } + } + + Vector newPosition = transform.getPosition_p() + velocity * elapsedTime; + if (s_clampMovementToZoneVolume) + { + float const halfMapWidth = TerrainObject::getConstInstance()->getMapWidthInMeters() * 0.5f; + float const boundary = 32.f; + float const coordMinimum = -halfMapWidth + boundary; + float const coordMaximum = halfMapWidth - boundary; + + newPosition.x = clamp(coordMinimum, newPosition.x, coordMaximum); + newPosition.y = clamp(coordMinimum, newPosition.y, coordMaximum); + newPosition.z = clamp(coordMinimum, newPosition.z, coordMaximum); + } + + transform.setPosition_p(newPosition.x, newPosition.y, newPosition.z); + } + } + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +} + +using namespace ShipDynamicsModelNamespace; + +// ====================================================================== +// PUBLIC ShipDynamicsModel +// ====================================================================== + +ShipDynamicsModel::ShipDynamicsModel() : + m_yawRate(0.f), + m_pitchRate(0.f), + m_rollRate(0.f), + m_speed(0.f), + m_velocity(), + m_transform() +{ +} + +// ---------------------------------------------------------------------- + +ShipDynamicsModel::~ShipDynamicsModel() +{ +} + +// ---------------------------------------------------------------------- + +bool ShipDynamicsModel::getClampMovementToZoneVolume() +{ + return s_clampMovementToZoneVolume; +} + +// ---------------------------------------------------------------------- + +void ShipDynamicsModel::setClampMovementToZoneVolume(bool const clampMovement) +{ + s_clampMovementToZoneVolume = clampMovement; +} + +// ---------------------------------------------------------------------- + +void ShipDynamicsModel::makeStationary() +{ + m_yawRate = 0.f; + m_pitchRate = 0.f; + m_rollRate = 0.f; + m_speed = 0.f; + m_velocity.makeZero(); +} + +// ---------------------------------------------------------------------- + +void ShipDynamicsModel::stop() +{ + m_speed = 0.f; + m_velocity.makeZero(); +} + +// ---------------------------------------------------------------------- + +void ShipDynamicsModel::model(float const elapsedTime, float const yawPosition, float const pitchPosition, float const rollPosition, float const throttlePosition, ShipObjectInterface const & shipObjectInterface) +{ + if (elapsedTime <= 0.f) + return; + + VALIDATE_RANGE_INCLUSIVE_INCLUSIVE(-1.f, yawPosition, 1.f); + VALIDATE_RANGE_INCLUSIVE_INCLUSIVE(-1.f, pitchPosition, 1.f); + VALIDATE_RANGE_INCLUSIVE_INCLUSIVE(-1.f, rollPosition, 1.f); + VALIDATE_RANGE_INCLUSIVE_INCLUSIVE(0.f, throttlePosition, 1.f); + + updateAxis(m_yawRate, yawPosition, shipObjectInterface.getMaximumYaw(), shipObjectInterface.getYawAcceleration(), shipObjectInterface.getYawAcceleration(), elapsedTime); + updateAxis(m_pitchRate, pitchPosition, shipObjectInterface.getMaximumPitch(), shipObjectInterface.getPitchAcceleration(), shipObjectInterface.getPitchAcceleration(), elapsedTime); + updateAxis(m_rollRate, rollPosition, shipObjectInterface.getMaximumRoll(), shipObjectInterface.getRollAcceleration(), shipObjectInterface.getRollAcceleration(), elapsedTime); + updateAxis(m_speed, throttlePosition, shipObjectInterface.getMaximumSpeed(), shipObjectInterface.getSpeedAcceleration(), shipObjectInterface.getSpeedDeceleration(), elapsedTime); + + //-- Modeling is the same as prediction with specified inputs + predict(elapsedTime, shipObjectInterface); +} + +// ---------------------------------------------------------------------- + +void ShipDynamicsModel::predict(float const elapsedTime, ShipObjectInterface const & shipObjectInterface) +{ + if (elapsedTime <= 0.f) + return; + + ShipDynamicsModelNamespace::model(m_transform, m_velocity, elapsedTime, m_yawRate, m_pitchRate, m_rollRate, m_speed, shipObjectInterface.getSlideDampener()); +} + +// ---------------------------------------------------------------------- + +Transform const & ShipDynamicsModel::getTransform() const +{ + return m_transform; +} + +// ---------------------------------------------------------------------- + +void ShipDynamicsModel::setTransform(Transform const & transform) +{ + m_transform = transform; +} + +// ---------------------------------------------------------------------- + +Vector const & ShipDynamicsModel::getVelocity() const +{ + return m_velocity; +} + +// ---------------------------------------------------------------------- + +float ShipDynamicsModel::getSpeed() const +{ + return m_speed; +} + +// ---------------------------------------------------------------------- + +void ShipDynamicsModel::setVelocity(Vector const & velocity) +{ + m_velocity = velocity; + m_speed = m_velocity.magnitude(); +} + +// ---------------------------------------------------------------------- + +float ShipDynamicsModel::getYawRate() const +{ + return m_yawRate; +} + +// ---------------------------------------------------------------------- + +void ShipDynamicsModel::setYawRate(float const yawRate) +{ + m_yawRate = yawRate; +} + +// ---------------------------------------------------------------------- + +float ShipDynamicsModel::getPitchRate() const +{ + return m_pitchRate; +} + +// ---------------------------------------------------------------------- + +void ShipDynamicsModel::setPitchRate(float const pitchRate) +{ + m_pitchRate = pitchRate; +} + +// ---------------------------------------------------------------------- + +float ShipDynamicsModel::getRollRate() const +{ + return m_rollRate; +} + +// ---------------------------------------------------------------------- + +void ShipDynamicsModel::setRollRate(float const rollRate) +{ + m_rollRate = rollRate; +} + +// ---------------------------------------------------------------------- + +void ShipDynamicsModel::getApproximateFutureTransform(Transform & transform, Vector & velocity, float const elapsedTime, ShipObjectInterface const & shipObjectInterface) const +{ + transform = m_transform; + velocity = m_velocity; + + float const timeSlice = 0.1f; + + float remainingTime = elapsedTime; + while (remainingTime > 0.f) + { + float const slicedTime = (remainingTime < timeSlice) ? remainingTime : timeSlice; + ShipDynamicsModelNamespace::model(transform, velocity, slicedTime, m_yawRate, m_pitchRate, m_rollRate, m_speed, shipObjectInterface.getSlideDampener()); + + remainingTime -= slicedTime; + } +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/dynamics/ShipDynamicsModel.h b/engine/shared/library/sharedGame/src/shared/dynamics/ShipDynamicsModel.h new file mode 100644 index 00000000..cc974788 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/dynamics/ShipDynamicsModel.h @@ -0,0 +1,74 @@ +// ====================================================================== +// +// ShipDynamicsModel.h +// asommers +// +// copyright 2004, sony online entertainment +// +// ====================================================================== + +#ifndef INCLUDED_ShipDynamicsModel_H +#define INCLUDED_ShipDynamicsModel_H + +// ====================================================================== + +#include "sharedMath/Transform.h" + +class ShipObjectInterface; + +// ====================================================================== + +class ShipDynamicsModel +{ +public: + + ShipDynamicsModel(); + ~ShipDynamicsModel(); + + static bool getClampMovementToZoneVolume(); + static void setClampMovementToZoneVolume(bool const clampMovement); + + void makeStationary(); + void stop(); + + //-- Modeling + void model(float elapsedTime, float yawPosition, float pitchPosition, float rollPosition, float throttlePosition, ShipObjectInterface const & shipObjectInterface); + + //-- Prediction + void predict(float elapsedTime, ShipObjectInterface const & shipObjectInterface); + + Transform const & getTransform() const; + void setTransform(Transform const & transform); + + Vector const & getVelocity() const; + float getSpeed() const; + void setVelocity(Vector const & velocity); + + float getYawRate() const; + void setYawRate(float yawRate); + float getPitchRate() const; + void setPitchRate(float pitchRate); + float getRollRate() const; + void setRollRate(float rollRate); + + //-- Query where this transform would be with no changes to any inputs if elapsedTime passed + void getApproximateFutureTransform(Transform & transform, Vector & velocity, float elapsedTime, ShipObjectInterface const & shipObjectInterface) const; + +private: + + ShipDynamicsModel(ShipDynamicsModel const &); + ShipDynamicsModel & operator=(ShipDynamicsModel const &); + +private: + + float m_yawRate; + float m_pitchRate; + float m_rollRate; + float m_speed; + Vector m_velocity; + Transform m_transform; +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/mount/MountValidScaleRangeTable.cpp b/engine/shared/library/sharedGame/src/shared/mount/MountValidScaleRangeTable.cpp new file mode 100644 index 00000000..0bdc106c --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/mount/MountValidScaleRangeTable.cpp @@ -0,0 +1,418 @@ +// ====================================================================== +// +// MountValidScaleRangeTable.cpp +// Copyright 2003 Sony Online Entertainment, Inc. +// All Rights Reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/MountValidScaleRangeTable.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFoundation/CrcString.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/LessPointerComparator.h" +#include "sharedFoundation/PersistentCrcString.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedFoundation/TemporaryCrcString.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" + +#include +#include +#include + +// ====================================================================== + +namespace MountValidScaleRangeTableNamespace +{ + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class Saddle + { + public: + + Saddle(int seatingCapacity, float appearanceScaleMin, float appearanceScaleMax); + + int getSeatingCapacity() const; + float getAppearanceScaleMin() const; + float getAppearanceScaleMax() const; + + private: + + // Disabled. + Saddle(); + Saddle &operator =(Saddle const&); + + private: + + int const m_seatingCapacity; + float const m_appearanceScaleMin; + float const m_appearanceScaleMax; + + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + typedef std::vector SaddleVector; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class MountableCreature + { + public: + + explicit MountableCreature(CrcString const &creatureAppearanceName); + ~MountableCreature(); + + void addValidScaleRangeForSaddleCapacity(int saddleCapacity, float validScaleMin, float validScaleMax); + + CrcString const &getCreatureAppearanceName() const; + + int getNumberOfSeatConfigurations() const; + void getSaddleCapacityAndRangeForSeatConfigurationIndex(int seatConfigurationIndex, int &saddleCapacity, float &validScaleMin, float &validScaleMax) const; + + private: + + // Disabled. + MountableCreature(); + MountableCreature &operator =(MountableCreature const&); + + private: + + PersistentCrcString const m_creatureAppearanceName; + SaddleVector m_saddles; + + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + typedef std::map MountableCreatureTable; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + void remove(); + int getRequiredColumnNumberFromNamedTable(char const *filename, DataTable const *table, char const *columnName); + void loadTableData(char const *filename); + MountableCreature const *findMountableCreatureFromAppearanceName(CrcString const &creatureAppearanceName); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + bool s_installed; + MountableCreatureTable s_mountableCreatureTable; +} + +using namespace MountValidScaleRangeTableNamespace; + +// ====================================================================== +// class MountValidScaleRangeTableNamespace::Saddle +// ====================================================================== + +MountValidScaleRangeTableNamespace::Saddle::Saddle(int seatingCapacity, float appearanceScaleMin, float appearanceScaleMax) : + m_seatingCapacity(seatingCapacity), + m_appearanceScaleMin(appearanceScaleMin), + m_appearanceScaleMax(appearanceScaleMax) +{ +} + +// ---------------------------------------------------------------------- + +int MountValidScaleRangeTableNamespace::Saddle::getSeatingCapacity() const +{ + return m_seatingCapacity; +} + +// ---------------------------------------------------------------------- + +float MountValidScaleRangeTableNamespace::Saddle::getAppearanceScaleMin() const +{ + return m_appearanceScaleMin; +} + +// ---------------------------------------------------------------------- + +float MountValidScaleRangeTableNamespace::Saddle::getAppearanceScaleMax() const +{ + return m_appearanceScaleMax; +} + +// ====================================================================== +// class MountValidScaleRangeTableNamespace::MountableCreature +// ====================================================================== + +MountValidScaleRangeTableNamespace::MountableCreature::MountableCreature(CrcString const &creatureAppearanceName) : + m_creatureAppearanceName(creatureAppearanceName), + m_saddles() +{ +} + +// ---------------------------------------------------------------------- + +MountValidScaleRangeTableNamespace::MountableCreature::~MountableCreature() +{ + std::for_each(m_saddles.begin(), m_saddles.end(), PointerDeleter()); +} + +// ---------------------------------------------------------------------- + +void MountValidScaleRangeTableNamespace::MountableCreature::addValidScaleRangeForSaddleCapacity(int saddleCapacity, float validScaleMin, float validScaleMax) +{ +#ifdef _DEBUG + //-- FATAL if we already have an entry for the given saddle capacity. + SaddleVector::iterator const endIt = m_saddles.end(); + for (SaddleVector::iterator it = m_saddles.begin(); it != endIt; ++it) + { + NOT_NULL(*it); + DEBUG_FATAL((*it)->getSeatingCapacity() == saddleCapacity, ("MountValidScaleRangeTable: data for mount appearance [%s] has multiple entries for saddle capacity [%d], please fix data by removing the duplicate entry.", getCreatureAppearanceName().getString(), saddleCapacity)); + } +#endif + + m_saddles.push_back(new Saddle(saddleCapacity, validScaleMin, validScaleMax)); +} + +// ---------------------------------------------------------------------- + +CrcString const &MountValidScaleRangeTableNamespace::MountableCreature::getCreatureAppearanceName() const +{ + return m_creatureAppearanceName; +} + +// ---------------------------------------------------------------------- + +int MountValidScaleRangeTableNamespace::MountableCreature::getNumberOfSeatConfigurations() const +{ + return static_cast(m_saddles.size()); +} + +// ---------------------------------------------------------------------- + +void MountValidScaleRangeTableNamespace::MountableCreature::getSaddleCapacityAndRangeForSeatConfigurationIndex(int seatConfigurationIndex, int &saddleCapacity, float &validScaleMin, float &validScaleMax) const +{ + VALIDATE_RANGE_INCLUSIVE_EXCLUSIVE(0, seatConfigurationIndex, getNumberOfSeatConfigurations()); + + Saddle const *const saddle = m_saddles[static_cast(seatConfigurationIndex)]; + NOT_NULL(saddle); + + saddleCapacity = saddle->getSeatingCapacity(); + validScaleMin = saddle->getAppearanceScaleMin(); + validScaleMax = saddle->getAppearanceScaleMax(); +} + +// ====================================================================== +// namespace MountValidScaleRangeTable +// ====================================================================== + +void MountValidScaleRangeTableNamespace::remove() +{ + std::for_each(s_mountableCreatureTable.begin(), s_mountableCreatureTable.end(), PointerDeleterPairSecond()); + s_mountableCreatureTable.clear(); + + s_installed = false; +} + +// ---------------------------------------------------------------------- + +int MountValidScaleRangeTableNamespace::getRequiredColumnNumberFromNamedTable(char const *filename, DataTable const *table, char const *columnName) +{ + NOT_NULL(columnName); + + int const columnNumber = table->findColumnNumber(columnName); + FATAL(columnNumber < 0, ("failed to find column name [%s] in MountValidScaleRangeTable file [%s].", columnName, filename)); + + return columnNumber; +} + +// ---------------------------------------------------------------------- + +void MountValidScaleRangeTableNamespace::loadTableData(char const *filename) +{ + NOT_NULL(filename); + + //-- Load the data table. + DataTable *const table = DataTableManager::getTable(filename, true); + FATAL(!table, ("MountValidScaleRangeTable data file [%s] failed to open.", filename)); + + //-- Find required data column numbers. + int const appearanceNameColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "appearance_name"); + int const saddleCapacityColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "saddle_capacity"); + int const validScaleMinColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "valid_scale_min"); + int const validScaleMaxColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "valid_scale_max"); + + //-- Loop through data, constructing entries as necessary. + int const rowCount = table->getNumRows(); + for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex) + { + //-- Get creature appearance name. + std::string const &mountableCreatureAppearanceName = table->getStringValue(appearanceNameColumnNumber, rowIndex); + TemporaryCrcString const mountableCreatureAppearanceNameCrc(mountableCreatureAppearanceName.c_str(), true); + + //-- Find or create new MountableCreature instance for this creature name. + MountableCreature *mountableCreature = NULL; + + MountableCreatureTable::iterator lowerBoundIt = s_mountableCreatureTable.lower_bound(&mountableCreatureAppearanceNameCrc); + bool const mountableCreatureEntryExists = ((lowerBoundIt != s_mountableCreatureTable.end()) && !s_mountableCreatureTable.key_comp()(static_cast(&mountableCreatureAppearanceNameCrc), lowerBoundIt->first)); + + if (mountableCreatureEntryExists) + mountableCreature = lowerBoundIt->second; + else + { + mountableCreature = new MountableCreature(mountableCreatureAppearanceNameCrc); + MountableCreatureTable::iterator insertedIterator = s_mountableCreatureTable.insert(lowerBoundIt, MountableCreatureTable::value_type(&mountableCreature->getCreatureAppearanceName(), mountableCreature)); + UNREF(insertedIterator); + DEBUG_FATAL(insertedIterator == s_mountableCreatureTable.end(), ("inserting new MountableCreature with appearance name [%s] failed, return iterator == map.end().", mountableCreatureAppearanceNameCrc.getString())); + } + NOT_NULL(mountableCreature); + + //-- Get seating configuration and valid appearance scale range for the configuration. + int const saddleCapacity = table->getIntValue(saddleCapacityColumnNumber, rowIndex); + DEBUG_FATAL(saddleCapacity < 1, ("invalid saddle capacity [%d] for creature appearance [%s] in file [%s].", saddleCapacity, mountableCreatureAppearanceName.c_str(), filename)); + + float const appearanceScaleMin = table->getFloatValue(validScaleMinColumnNumber, rowIndex); + float const appearanceScaleMax = table->getFloatValue(validScaleMaxColumnNumber, rowIndex); + DEBUG_FATAL(appearanceScaleMin < 0.0f, ("invalid appearance scale min [%g] for creature appearance [%s] in file [%s].", appearanceScaleMin, mountableCreatureAppearanceName.c_str(), filename)); + DEBUG_FATAL(appearanceScaleMax < appearanceScaleMin, ("invalid appearance scale max [%g] given scale min [%g] for creature appearance [%s] in file [%s].", appearanceScaleMax, appearanceScaleMin, mountableCreatureAppearanceName.c_str(), filename)); + + mountableCreature->addValidScaleRangeForSaddleCapacity(saddleCapacity, appearanceScaleMin, appearanceScaleMax); + } + + DataTableManager::close(filename); +} + +// ---------------------------------------------------------------------- + +MountValidScaleRangeTableNamespace::MountableCreature const *MountValidScaleRangeTableNamespace::findMountableCreatureFromAppearanceName(CrcString const &creatureAppearanceName) +{ + MountableCreatureTable::iterator const findIt = s_mountableCreatureTable.find(&creatureAppearanceName); + if (findIt != s_mountableCreatureTable.end()) + return findIt->second; + else + { + DEBUG_WARNING(true, ("'datatables/mount/valid_scale_range.iff' missing entry for creature appearance name '%s'", creatureAppearanceName.getString())); + return NULL; + } +} + +// ====================================================================== +// class MountValidScaleRangeTable: PUBLIC STATIC +// ====================================================================== + +void MountValidScaleRangeTable::install(char const *const filename) +{ + InstallTimer const installTimer("MountValidScaleRangeTable::install"); + + DEBUG_FATAL(s_installed, ("MountValidScaleRangeTable is already installed.")); + + loadTableData(filename); + + s_installed = true; + ExitChain::add(MountValidScaleRangeTableNamespace::remove, "MountValidScaleRangeTable"); +} + +// ---------------------------------------------------------------------- + +MountValidScaleRangeTable::MountabilityStatus MountValidScaleRangeTable::doesCreatureSupportScaleAndSaddleCapacity(CrcString const &creatureAppearanceName, float creatureScale, int saddleCapacity) +{ + DEBUG_FATAL(!s_installed, ("MountValidScaleRangeTable not installed.")); + + //-- Find MountableCreature entry for specified creature. + MountableCreature const *const mountableCreature = findMountableCreatureFromAppearanceName(creatureAppearanceName); + if (!mountableCreature) + { + // No entries for specified creature appearance. This implies the specified creature appearance name is not mountable. + return MS_speciesUnmountable; + } + + //-- Find mountable creature's valid scale range for the given seat count. + int entrySaddleCapacity = 0; + float entryScaleMin = 0.0f; + float entryScaleMax = 0.0f; + + int const seatConfigurationCount = mountableCreature->getNumberOfSeatConfigurations(); + for (int seatConfigurationIndex = 0; seatConfigurationIndex < seatConfigurationCount; ++seatConfigurationIndex) + { + //-- Retrieve seat configuration data. + mountableCreature->getSaddleCapacityAndRangeForSeatConfigurationIndex(seatConfigurationIndex, entrySaddleCapacity, entryScaleMin, entryScaleMax); + + //-- Validate seat configuration data. + DEBUG_FATAL(entrySaddleCapacity < 1, ("invalid seat count [%d] retrieved from mountable creature data for appearance [%s].", entrySaddleCapacity, creatureAppearanceName.getString())); + DEBUG_FATAL(entryScaleMin < 0.0f, ("invalid minimum appearance scale [%g] retrieved from mountable creature data for appearance [%s].", entryScaleMin, creatureAppearanceName.getString())); + DEBUG_FATAL(entryScaleMax < entryScaleMin, ("invalid maximum appearance scale [%g], less than minimum appearance scale [%g], retrieved from mountable creature data for appearance [%s].", entryScaleMax, entryScaleMin, creatureAppearanceName.getString())); + + if (entrySaddleCapacity == saddleCapacity) + { + // Found a range specification for the seat count specified by the caller. Validate that the creature scale is within range. + bool const scaleAndSeatCountSupported = (entryScaleMin <= creatureScale) && (entryScaleMax >= creatureScale); + return scaleAndSeatCountSupported ? MS_creatureMountable: MS_speciesMountableScaleOutOfRange; + } + } + + //-- The specified saddle capacity was not supported. + return MS_speciesMountableSeatingCapacityUnsupported; +} + +// ---------------------------------------------------------------------- + +int MountValidScaleRangeTable::getCreatureCount() +{ + return static_cast(s_mountableCreatureTable.size()); +} + +// ---------------------------------------------------------------------- + +CrcString const &MountValidScaleRangeTable::getCreatureName(int index) +{ + VALIDATE_RANGE_INCLUSIVE_EXCLUSIVE(0, index, getCreatureCount()); + + MountableCreatureTable::const_iterator it = s_mountableCreatureTable.begin(); + std::advance(it, index); + + MountableCreature const *const mountableCreature = it->second; + if (mountableCreature) + return mountableCreature->getCreatureAppearanceName(); + else + return PersistentCrcString::empty; +} + +// ---------------------------------------------------------------------- + +bool MountValidScaleRangeTable::getScaleRangeForCreatureAndSaddleCapacity(CrcString const &creatureAppearanceName, int saddleCapacity, float &minimumScale, float &maximumScale) +{ + //-- Find MountableCreature entry for specified creature. + MountableCreature const *const mountableCreature = findMountableCreatureFromAppearanceName(creatureAppearanceName); + if (!mountableCreature) + { + // No entries for specified creature appearance. This implies the specified creature appearance name is not mountable. + return false; + } + + //-- Find mountable creature's valid scale range for the given seat count. + int entrySaddleCapacity = 0; + float entryScaleMin = 0.0f; + float entryScaleMax = 0.0f; + + int const seatConfigurationCount = mountableCreature->getNumberOfSeatConfigurations(); + for (int seatConfigurationIndex = 0; seatConfigurationIndex < seatConfigurationCount; ++seatConfigurationIndex) + { + //-- Retrieve seat configuration data. + mountableCreature->getSaddleCapacityAndRangeForSeatConfigurationIndex(seatConfigurationIndex, entrySaddleCapacity, entryScaleMin, entryScaleMax); + + //-- Validate seat configuration data. + DEBUG_FATAL(entrySaddleCapacity < 1, ("invalid seat count [%d] retrieved from mountable creature data for appearance [%s].", entrySaddleCapacity, creatureAppearanceName.getString())); + DEBUG_FATAL(entryScaleMin < 0.0f, ("invalid minimum appearance scale [%g] retrieved from mountable creature data for appearance [%s].", entryScaleMin, creatureAppearanceName.getString())); + DEBUG_FATAL(entryScaleMax < entryScaleMin, ("invalid maximum appearance scale [%g], less than minimum appearance scale [%g], retrieved from mountable creature data for appearance [%s].", entryScaleMax, entryScaleMin, creatureAppearanceName.getString())); + + if (entrySaddleCapacity == saddleCapacity) + { + // Found a range specification for the seat count specified by the caller. + minimumScale = entryScaleMin; + maximumScale = entryScaleMax; + return true; + } + } + + //-- The specified saddle capacity was not supported. + return false; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/mount/MountValidScaleRangeTable.h b/engine/shared/library/sharedGame/src/shared/mount/MountValidScaleRangeTable.h new file mode 100644 index 00000000..94445ed3 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/mount/MountValidScaleRangeTable.h @@ -0,0 +1,53 @@ +// ====================================================================== +// +// MountValidScaleRangeTable.h +// Copyright 2003 Sony Online Entertainment, Inc. +// All Rights Reserved. +// +// ====================================================================== + +#ifndef INCLUDED_MountValidScaleRangeTable_H +#define INCLUDED_MountValidScaleRangeTable_H + +// ====================================================================== + +class CrcString; + +// ====================================================================== + +class MountValidScaleRangeTable +{ +public: + + enum MountabilityStatus + { + MS_creatureMountable = 0, + MS_speciesUnmountable, + MS_speciesMountableSeatingCapacityUnsupported, + MS_speciesMountableScaleOutOfRange, + MS_speciesMountableMissingRiderSlot + }; + +public: + + static void install(char const *const filename); + + static MountabilityStatus doesCreatureSupportScaleAndSaddleCapacity(CrcString const &creatureAppearanceName, float creatureScale, int saddleCapacity); + + static int getCreatureCount(); + static CrcString const &getCreatureName(int index); + + static bool getScaleRangeForCreatureAndSaddleCapacity(CrcString const &creatureAppearanceName, int saddleCapacity, float &minimumScale, float &maximumScale); + +private: + + // Disabled. + MountValidScaleRangeTable(); + MountValidScaleRangeTable(MountValidScaleRangeTable const&); + MountValidScaleRangeTable &operator =(MountValidScaleRangeTable const&); + +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/mount/SharedSaddleManager.cpp b/engine/shared/library/sharedGame/src/shared/mount/SharedSaddleManager.cpp new file mode 100644 index 00000000..5c2de639 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/mount/SharedSaddleManager.cpp @@ -0,0 +1,680 @@ +// ====================================================================== +// +// SharedSaddleManager.cpp +// Copyright 2003 Sony Online Entertainment, Inc. +// All Rights Reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SharedSaddleManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFoundation/ConstCharCrcString.h" +#include "sharedFoundation/CrcLowerString.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/PersistentCrcString.h" +#include "sharedGame/GameObjectTypes.h" +#include "sharedGame/SharedObjectTemplate.h" +#include "sharedObject/Appearance.h" +#include "sharedObject/AppearanceTemplate.h" +#include "sharedObject/AppearanceTemplateList.h" +#include "sharedObject/Object.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" + +#include +#include +#include +#include + +#ifdef _DEBUG +#include "sharedDebug/DebugFlags.h" +#endif + +// ====================================================================== + +namespace SharedSaddleManagerNamespace +{ + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + char const * const cs_logicalSaddleNameMapFile = "datatables/mount/logical_saddle_name_map.iff"; + char const * const cs_saddleAppearanceMapFile = "datatables/mount/saddle_appearance_map.iff"; + char const * const cs_riderPoseMapFile = "datatables/mount/rider_pose_map.iff"; + + class LogicalSaddleMapEntry + { + public: + + virtual ~LogicalSaddleMapEntry(); + + virtual CrcString const &getAppearanceTemplateName() const = 0; + virtual CrcString const *getLogicalSaddleName() const = 0; + + protected: + + LogicalSaddleMapEntry(); + + private: + + // Disabled. + LogicalSaddleMapEntry(LogicalSaddleMapEntry const&); //lint -esym(754, LogicalSaddleMapEntry::LogicalSaddleMapEntry) // unreferenced local member // defensive hiding + LogicalSaddleMapEntry & operator=(LogicalSaddleMapEntry const&); + + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class PersistentLogicalSaddleMapEntry: public LogicalSaddleMapEntry + { + public: + + PersistentLogicalSaddleMapEntry(char const *mountAppearanceTemplateName, char const *logicalSaddleName); + + virtual CrcString const &getAppearanceTemplateName() const; + virtual CrcString const *getLogicalSaddleName() const; + + private: + + // Disabled. + PersistentLogicalSaddleMapEntry(); + PersistentLogicalSaddleMapEntry(PersistentLogicalSaddleMapEntry const&); //lint -esym(754, PersistentLogicalSaddleMapEntry::PersistentLogicalSaddleMapEntry) // unreferenced local member // defensive hiding + PersistentLogicalSaddleMapEntry &operator =(PersistentLogicalSaddleMapEntry const&); + + private: + + PersistentCrcString const m_mountAppearanceTemplateName; + PersistentCrcString const m_logicalSaddleName; + + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class SaddleAppearanceMapEntry + { + public: + + virtual ~SaddleAppearanceMapEntry(); + + virtual CrcString const &getLogicalSaddleName() const = 0; + virtual int getSeatingCapacity() const = 0; + virtual CrcString const *getSaddleAppearanceName() const = 0; + virtual CrcString const *getClientDataFilename () const = 0; + + protected: + + SaddleAppearanceMapEntry(); + + private: + + // Disabled. + SaddleAppearanceMapEntry(SaddleAppearanceMapEntry const&); //lint -esym(754, SaddleAppearanceMapEntry::SaddleAppearanceMapEntry) // unrefereced local member // defensive hiding + SaddleAppearanceMapEntry &operator =(SaddleAppearanceMapEntry const&); + + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class PersistentSaddleAppearanceMapEntry: public SaddleAppearanceMapEntry + { + public: + + PersistentSaddleAppearanceMapEntry(char const *logicalSaddleName, int seatingCapacity, char const *saddleAppearanceName, const char * clientDataFilename); + + virtual CrcString const &getLogicalSaddleName() const; + virtual int getSeatingCapacity() const; + virtual CrcString const *getSaddleAppearanceName() const; + virtual CrcString const *getClientDataFilename () const; + + private: + + // Disabled. + PersistentSaddleAppearanceMapEntry(); + PersistentSaddleAppearanceMapEntry(PersistentSaddleAppearanceMapEntry const&); //lint -esym(754, PersistentSaddleAppearanceMapEntry::PersistentSaddleAppearanceMapEntry) // unrefereced local member // defensive hiding + PersistentSaddleAppearanceMapEntry &operator =(PersistentSaddleAppearanceMapEntry const&); + + private: + + PersistentCrcString const m_logicalSaddleName; + int const m_seatingCapacity; + PersistentCrcString const m_saddleAppearanceName; + PersistentCrcString const m_clientDataFilename; + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class RiderPoseMapEntry + { + public: + + virtual ~RiderPoseMapEntry(); + + virtual CrcString const &getSaddleAppearanceName() const = 0; + virtual int getRiderSeatIndex() const = 0; + virtual CrcString const *getRiderPoseName() const = 0; + + protected: + + RiderPoseMapEntry(); + + private: + + RiderPoseMapEntry(RiderPoseMapEntry const&); //lint -esym(754, RiderPoseMapEntry::RiderPoseMapEntry) // local member not referenced // defensive hiding + RiderPoseMapEntry &operator =(RiderPoseMapEntry const&); + + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class PersistentRiderPoseMapEntry : public RiderPoseMapEntry + { + public: + + PersistentRiderPoseMapEntry(char const *saddleAppearanceName, int riderSeatIndex, char const *riderPoseName); + + virtual CrcString const &getSaddleAppearanceName() const; + virtual int getRiderSeatIndex() const; + virtual CrcString const *getRiderPoseName() const; + + private: + + // Disabled. + PersistentRiderPoseMapEntry(); + PersistentRiderPoseMapEntry(PersistentRiderPoseMapEntry const&); //lint -esym(754, PersistentRiderPoseMapEntry::PersistentRiderPoseMapEntry) // local member not referenced // defensive hiding + PersistentRiderPoseMapEntry &operator =(PersistentRiderPoseMapEntry const&); + + private: + + PersistentCrcString const m_saddleAppearanceName; + int const m_riderSeatIndex; + PersistentCrcString const m_riderPoseName; + + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class TemporaryRiderPoseMapEntry: public RiderPoseMapEntry + { + public: + + TemporaryRiderPoseMapEntry(CrcString const &saddleAppearanceName, int riderSeatIndex); + + virtual CrcString const &getSaddleAppearanceName() const; + virtual int getRiderSeatIndex() const; + virtual CrcString const *getRiderPoseName() const; + + private: + + // Disabled. + TemporaryRiderPoseMapEntry(); + TemporaryRiderPoseMapEntry(TemporaryRiderPoseMapEntry const&); //lint -esym(754, TemporaryRiderPoseMapEntry::TemporaryRiderPoseMapEntry) // local member not referenced // defensive hiding + TemporaryRiderPoseMapEntry &operator =(TemporaryRiderPoseMapEntry const&); + + private: + + CrcString const &m_saddleAppearanceName; + int const m_riderSeatIndex; + + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + typedef PersistentCrcString const Key; + typedef std::map LogicalSaddleMapEntryVector; + typedef std::map SaddleAppearanceMapEntryVector; + typedef std::multimap RiderPoseMapEntryVector; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + void remove(); + + int getRequiredColumnNumberFromNamedTable(char const *filename, DataTable const *table, char const *columnName); + void loadLogicalSaddleNameMapTableData(char const *filename); + void loadSaddleAppearanceMapTableData(char const *filename); + void loadRiderPoseMapTableData(char const *filename); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + ConstCharCrcString const cs_defaultCoveringLogicalAppearanceName("lookup/mnt_wr_default_covering"); + ConstCharCrcString const cs_saddleHardpointName("saddle"); + char const * const cs_driverHardpointName = "player"; + char const * const cs_passengerHardpointName = "passenger"; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + bool s_installed; + LogicalSaddleMapEntryVector s_logicalSaddleMapTable; + SaddleAppearanceMapEntryVector s_saddleAppearanceMapTable; + RiderPoseMapEntryVector s_riderPoseMapTable; + + template void clearMap(theMapType & map) + { + typename theMapType::iterator ii = map.begin(); + typename theMapType::iterator iiEnd = map.end(); + + for (; ii != iiEnd; ++ii) + { + delete ii->second; + } + + map.clear(); + } +} + +using namespace SharedSaddleManagerNamespace; + +// ====================================================================== +// class SharedSaddleManagerNamespace::LogicalSaddleMapEntry +// ====================================================================== + +SharedSaddleManagerNamespace::LogicalSaddleMapEntry::~LogicalSaddleMapEntry() +{ +} + +// ====================================================================== + +SharedSaddleManagerNamespace::LogicalSaddleMapEntry::LogicalSaddleMapEntry() +{ +} + +// ====================================================================== +// class SharedSaddleManagerNamespace::PersistentLogicalSaddleMapEntry +// ====================================================================== + +SharedSaddleManagerNamespace::PersistentLogicalSaddleMapEntry::PersistentLogicalSaddleMapEntry(char const * const mountAppearanceTemplateName, char const * const logicalSaddleName) : + LogicalSaddleMapEntry(), + m_mountAppearanceTemplateName(mountAppearanceTemplateName, true), + m_logicalSaddleName(logicalSaddleName, true) +{ +} + +// ---------------------------------------------------------------------- + +CrcString const &SharedSaddleManagerNamespace::PersistentLogicalSaddleMapEntry::getAppearanceTemplateName() const +{ + return m_mountAppearanceTemplateName; +} + +// ---------------------------------------------------------------------- + +CrcString const *SharedSaddleManagerNamespace::PersistentLogicalSaddleMapEntry::getLogicalSaddleName() const +{ + return &m_logicalSaddleName; +} + +// ====================================================================== +// class SharedSaddleManagerNamespace::SaddleAppearanceMapEntry +// ====================================================================== + +SharedSaddleManagerNamespace::SaddleAppearanceMapEntry::~SaddleAppearanceMapEntry() +{ +} + +// ====================================================================== + +SharedSaddleManagerNamespace::SaddleAppearanceMapEntry::SaddleAppearanceMapEntry() +{ +} + +// ====================================================================== +// class SharedSaddleManagerNamespace::PersistentSaddleAppearanceMapEntry +// ====================================================================== + +SharedSaddleManagerNamespace::PersistentSaddleAppearanceMapEntry::PersistentSaddleAppearanceMapEntry(char const *logicalSaddleName, int seatingCapacity, char const *saddleAppearanceName, const char * clientDataFilename) : + SaddleAppearanceMapEntry(), + m_logicalSaddleName(logicalSaddleName, true), + m_seatingCapacity(seatingCapacity), + m_saddleAppearanceName(saddleAppearanceName, true), + m_clientDataFilename (clientDataFilename, true) +{ +} + +// ---------------------------------------------------------------------- + +CrcString const &SharedSaddleManagerNamespace::PersistentSaddleAppearanceMapEntry::getLogicalSaddleName() const +{ + return m_logicalSaddleName; +} + +// ---------------------------------------------------------------------- + +int SharedSaddleManagerNamespace::PersistentSaddleAppearanceMapEntry::getSeatingCapacity() const +{ + return m_seatingCapacity; +} + +// ---------------------------------------------------------------------- + +CrcString const *SharedSaddleManagerNamespace::PersistentSaddleAppearanceMapEntry::getSaddleAppearanceName() const +{ + return &m_saddleAppearanceName; +} + +// ---------------------------------------------------------------------- + +CrcString const *SharedSaddleManagerNamespace::PersistentSaddleAppearanceMapEntry::getClientDataFilename() const +{ + return &m_clientDataFilename; +} + +// ====================================================================== +// class SharedSaddleManagerNamespace::RiderPoseMapEntry +// ====================================================================== + +SharedSaddleManagerNamespace::RiderPoseMapEntry::~RiderPoseMapEntry() +{ +} + +// ====================================================================== + +SharedSaddleManagerNamespace::RiderPoseMapEntry::RiderPoseMapEntry() +{ +} + +// ====================================================================== +// class SharedSaddleManagerNamespace::PersistentRiderPoseMapEntry +// ====================================================================== + +SharedSaddleManagerNamespace::PersistentRiderPoseMapEntry::PersistentRiderPoseMapEntry(char const *saddleAppearanceName, int riderSeatIndex, char const *riderPoseName) : + RiderPoseMapEntry(), + m_saddleAppearanceName(saddleAppearanceName, true), + m_riderSeatIndex(riderSeatIndex), + m_riderPoseName(riderPoseName, true) +{ +} + +// ---------------------------------------------------------------------- + +CrcString const &SharedSaddleManagerNamespace::PersistentRiderPoseMapEntry::getSaddleAppearanceName() const +{ + return m_saddleAppearanceName; +} + +// ---------------------------------------------------------------------- + +int SharedSaddleManagerNamespace::PersistentRiderPoseMapEntry::getRiderSeatIndex() const +{ + return m_riderSeatIndex; +} + +// ---------------------------------------------------------------------- + +CrcString const *SharedSaddleManagerNamespace::PersistentRiderPoseMapEntry::getRiderPoseName() const +{ + return &m_riderPoseName; +} + +// ====================================================================== +// class SharedSaddleManagerNamespace::TemporaryRiderPoseMapEntry +// ====================================================================== + +SharedSaddleManagerNamespace::TemporaryRiderPoseMapEntry::TemporaryRiderPoseMapEntry(CrcString const &saddleAppearanceName, int riderSeatIndex) : + RiderPoseMapEntry(), + m_saddleAppearanceName(saddleAppearanceName), + m_riderSeatIndex(riderSeatIndex) +{ +} + +// ---------------------------------------------------------------------- + +CrcString const &SharedSaddleManagerNamespace::TemporaryRiderPoseMapEntry::getSaddleAppearanceName() const +{ + return m_saddleAppearanceName; +} + +// ---------------------------------------------------------------------- + +int SharedSaddleManagerNamespace::TemporaryRiderPoseMapEntry::getRiderSeatIndex() const +{ + return m_riderSeatIndex; +} + +// ---------------------------------------------------------------------- + +CrcString const *SharedSaddleManagerNamespace::TemporaryRiderPoseMapEntry::getRiderPoseName() const +{ + return NULL; +} + +// ====================================================================== +// namespace SharedSaddleManagerNamespace +// ====================================================================== + +void SharedSaddleManagerNamespace::remove() +{ + DEBUG_FATAL(!s_installed, ("SharedSaddleManager not installed.")); + s_installed = false; + + SharedSaddleManagerNamespace::clearMap(s_logicalSaddleMapTable); + SharedSaddleManagerNamespace::clearMap(s_saddleAppearanceMapTable); + SharedSaddleManagerNamespace::clearMap(s_riderPoseMapTable); +} + +// ---------------------------------------------------------------------- + +int SharedSaddleManagerNamespace::getRequiredColumnNumberFromNamedTable(char const *filename, DataTable const *table, char const *columnName) +{ + NOT_NULL(columnName); + + int const columnNumber = table->findColumnNumber(columnName); + FATAL(columnNumber < 0, ("failed to find column name [%s] in file [%s].", columnName, filename)); + + return columnNumber; +} + +// ---------------------------------------------------------------------- + +void SharedSaddleManagerNamespace::loadLogicalSaddleNameMapTableData(char const *filename) +{ + NOT_NULL(filename); + + //-- Load the data table. + DataTable *const table = DataTableManager::getTable(filename, true); + FATAL(!table, ("SharedSaddleManager: failed to open data file [%s].", filename)); + + //-- Find required data column numbers. + int const appearanceTemplateNameColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "sat_name"); + int const logicalSaddleNameColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "logical_saddle_name"); + + //-- Loop through data, constructing entries as necessary. + int const rowCount = table->getNumRows(); + + for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex) + { + //-- Get entry data. + std::string const & appearanceTemplateName = table->getStringValue(appearanceTemplateNameColumnNumber, rowIndex); + std::string const & logicalSaddleName = table->getStringValue(logicalSaddleNameColumnNumber, rowIndex); + + //-- Create map entry, add to vector. + + PersistentLogicalSaddleMapEntry * const entry = new PersistentLogicalSaddleMapEntry(appearanceTemplateName.c_str(), logicalSaddleName.c_str()); + Key const key(appearanceTemplateName.c_str(), true); + s_logicalSaddleMapTable[key] = entry; + } + + DataTableManager::close(filename); +} + +// ---------------------------------------------------------------------- + +void SharedSaddleManagerNamespace::loadSaddleAppearanceMapTableData(char const *filename) +{ + NOT_NULL(filename); + + //-- Load the data table. + DataTable *const table = DataTableManager::getTable(filename, true); + FATAL(!table, ("SharedSaddleManager: failed to open data file [%s].", filename)); + + //-- Find required data column numbers. + int const logicalSaddleNameColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "logical_saddle_name"); + int const seatingCapacityColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "saddle_capacity"); + int const saddleAppearanceNameColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "saddle_appearance_name"); + int const clientDataFilenameColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "client_data_filename"); + + //-- Loop through data, constructing entries as necessary. + int const rowCount = table->getNumRows(); + + for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex) + { + //-- Get entry data. + std::string const &logicalSaddleName = table->getStringValue(logicalSaddleNameColumnNumber, rowIndex); + int const seatingCapacity = table->getIntValue(seatingCapacityColumnNumber, rowIndex); + std::string const &saddleAppearanceName = table->getStringValue(saddleAppearanceNameColumnNumber, rowIndex); + std::string const &clientDataFilename = table->getStringValue(clientDataFilenameColumnNumber, rowIndex); + + //-- Create map entry, add to vector. + PersistentSaddleAppearanceMapEntry * const entry = new PersistentSaddleAppearanceMapEntry(logicalSaddleName.c_str(), seatingCapacity, saddleAppearanceName.c_str(), clientDataFilename.c_str ()); + Key const key(logicalSaddleName.c_str(), true); + s_saddleAppearanceMapTable[key] = entry; + } + + DataTableManager::close(filename); +} + +// ---------------------------------------------------------------------- + +void SharedSaddleManagerNamespace::loadRiderPoseMapTableData(char const * const filename) +{ + NOT_NULL(filename); + + //-- Load the data table. + DataTable *const table = DataTableManager::getTable(filename, true); + FATAL(!table, ("SharedSaddleManager: failed to open data file [%s].", filename)); + + //-- Find required data column numbers. + int const saddleAppearanceNameColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "saddle_appearance_name"); + int const riderSeatIndexColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "seat_index"); + int const riderPoseNameColumnNumber = getRequiredColumnNumberFromNamedTable(filename, table, "rider_pose"); + + //-- Loop through data, constructing entries as necessary. + int const rowCount = table->getNumRows(); + + for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex) + { + //-- Get entry data. + std::string const &saddleAppearanceName = table->getStringValue(saddleAppearanceNameColumnNumber, rowIndex); + int const riderSeatIndex = table->getIntValue(riderSeatIndexColumnNumber, rowIndex); + std::string const &riderPoseName = table->getStringValue(riderPoseNameColumnNumber, rowIndex); + + //-- Create map entry, add to vector. + PersistentRiderPoseMapEntry * const entry = new PersistentRiderPoseMapEntry(saddleAppearanceName.c_str(), riderSeatIndex, riderPoseName.c_str()); + Key const key(saddleAppearanceName.c_str(), true); + s_riderPoseMapTable.insert(std::pair(key, entry)); + } + + DataTableManager::close(filename); +} + +// ====================================================================== +// class SharedSaddleManager: PUBLIC STATIC +// ====================================================================== + +void SharedSaddleManager::install() +{ + InstallTimer const installTimer("SharedSaddleManager::install"); + + DEBUG_FATAL(s_installed, ("SharedSaddleManager already installed.")); + + loadLogicalSaddleNameMapTableData(cs_logicalSaddleNameMapFile); + loadSaddleAppearanceMapTableData(cs_saddleAppearanceMapFile); + loadRiderPoseMapTableData(cs_riderPoseMapFile); + + s_installed = true; + ExitChain::add(SharedSaddleManagerNamespace::remove, "SharedSaddleManager"); +} + +// ---------------------------------------------------------------------- + +CrcString const * SharedSaddleManager::getLogicalSaddleNameForMountAppearance(CrcString const & mountAppearanceTemplateName) +{ + DEBUG_FATAL(!s_installed, ("SharedSaddleManager not installed.")); + + LogicalSaddleMapEntryVector::const_iterator ii = s_logicalSaddleMapTable.find(Key(mountAppearanceTemplateName)); + if (ii != s_logicalSaddleMapTable.end()) + { + LogicalSaddleMapEntry const * const entry = ii->second; + NOT_NULL(entry); + return entry->getLogicalSaddleName(); + } + + return 0; +} + +// ---------------------------------------------------------------------- + +CrcString const *SharedSaddleManager::getSaddleAppearanceForLogicalSaddleName(CrcString const & logicalSaddleName) +{ + DEBUG_FATAL(!s_installed, ("SharedSaddleManager not installed.")); + + SaddleAppearanceMapEntryVector::const_iterator ii = s_saddleAppearanceMapTable.find(Key(logicalSaddleName)); + if (ii != s_saddleAppearanceMapTable.end()) + { + SaddleAppearanceMapEntry const * const entry = ii->second; + NOT_NULL(entry); + return entry->getSaddleAppearanceName(); + } + + return 0; +} + +// ---------------------------------------------------------------------- + +int SharedSaddleManager::getSaddleSeatingCapacityForLogicalSaddleName(CrcString const & logicalSaddleName) +{ + DEBUG_FATAL(!s_installed, ("SharedSaddleManager not installed.")); + + SaddleAppearanceMapEntryVector::const_iterator ii = s_saddleAppearanceMapTable.find(Key(logicalSaddleName)); + if (ii != s_saddleAppearanceMapTable.end()) + { + SaddleAppearanceMapEntry const * const entry = ii->second; + NOT_NULL(entry); + return entry->getSeatingCapacity(); + } + + return 0; +} + +// ---------------------------------------------------------------------- + +CrcString const *SharedSaddleManager::getClientDataFilenameForLogicalSaddleName(CrcString const &logicalSaddleName) +{ + DEBUG_FATAL(!s_installed, ("SharedSaddleManager not installed.")); + + SaddleAppearanceMapEntryVector::const_iterator ii = s_saddleAppearanceMapTable.find(Key(logicalSaddleName)); + if (ii != s_saddleAppearanceMapTable.end()) + { + SaddleAppearanceMapEntry const * const entry = ii->second; + NOT_NULL(entry); + return entry->getClientDataFilename(); + } + + return 0; +} + +// ---------------------------------------------------------------------- + +CrcString const *SharedSaddleManager::getRiderPoseForSaddleAppearanceNameAndRiderSeatIndex(CrcString const &saddleAppearanceName, int riderSeatIndex) +{ + DEBUG_FATAL(!s_installed, ("SharedSaddleManager not installed.")); + + typedef std::pair Range; + + Range const range = s_riderPoseMapTable.equal_range(Key(saddleAppearanceName)); + + RiderPoseMapEntryVector::const_iterator ii = range.first; + + for (; ii != range.second; ++ii) + { + RiderPoseMapEntry const * const entry = ii->second; + NOT_NULL(entry); + + if (entry->getRiderSeatIndex() == riderSeatIndex) + { + return entry->getRiderPoseName(); + } + } + + return 0; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/mount/SharedSaddleManager.h b/engine/shared/library/sharedGame/src/shared/mount/SharedSaddleManager.h new file mode 100644 index 00000000..2bf62840 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/mount/SharedSaddleManager.h @@ -0,0 +1,43 @@ +// ====================================================================== +// +// SaddleManager.h +// Copyright 2003 Sony Online Entertainment, Inc. +// All Rights Reserved. +// +// ====================================================================== + +#ifndef INCLUDED_SharedSaddleManager_H +#define INCLUDED_SharedSaddleManager_H + +// ====================================================================== + +class CrcString; +class CreatureObject; +class HardpointObject; +class Object; + +// ====================================================================== + +class SharedSaddleManager +{ +public: + + static void install(); + + static CrcString const * getLogicalSaddleNameForMountAppearance(CrcString const & mountObjectTemplateName); + static CrcString const * getSaddleAppearanceForLogicalSaddleName(CrcString const & logicalSaddleName); + static CrcString const * getClientDataFilenameForLogicalSaddleName(CrcString const & logicalSaddleName); + static CrcString const * getRiderPoseForSaddleAppearanceNameAndRiderSeatIndex(CrcString const & saddleAppearanceName, int riderSeatIndex); + + static int getSaddleSeatingCapacityForLogicalSaddleName(CrcString const & logicalSaddleName); + +private: + SharedSaddleManager(); + SharedSaddleManager(SharedSaddleManager const & copy); + SharedSaddleManager & operator=(SharedSaddleManager const & copy); + +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/object/AppearanceManager.cpp b/engine/shared/library/sharedGame/src/shared/object/AppearanceManager.cpp new file mode 100644 index 00000000..092cf327 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/AppearanceManager.cpp @@ -0,0 +1,208 @@ +// ====================================================================== +// +// AppearanceManager.cpp +// Copyright Sony Online Entertainment, Inc. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/AppearanceManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/Iff.h" +#include "sharedFile/TreeFile.h" +#include "sharedFoundation/ConfigFile.h" +#include "sharedFoundation/PersistentCrcString.h" +#include "sharedFoundation/TemporaryCrcString.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/LessPointerComparator.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedUtility/DataTable.h" + +#include +#include +#include +#include + +// ====================================================================== + +namespace AppearanceManagerNamespace +{ + typedef std::set AppearanceTemplateNameSet; + AppearanceTemplateNameSet ms_appearanceTemplateNameSet; + + typedef std::vector CrcStringVector; + typedef std::map ObjectTemplateAppearanceTemplateMap; + ObjectTemplateAppearanceTemplateMap ms_objectTemplateAppearanceTemplateMap; + + bool ms_installed; + bool ms_verboseWarnings; + + void remove(); + +#ifdef _DEBUG + void regressionTest(); +#endif + + class PointerDeleterPair + { + public: + + template + void operator()(std::pair &pairArgument) const + { + delete pairArgument.first; + delete pairArgument.second; + } + }; +} + +using namespace AppearanceManagerNamespace; + +// ====================================================================== + +void AppearanceManager::install() +{ + InstallTimer const installTimer("AppearanceManager::install"); + + DEBUG_FATAL(ms_installed, ("AppearanceManagerNamespace::install: already installed")); + ms_installed = true; + + ms_verboseWarnings = ConfigFile::getKeyBool("SharedGame/AppearanceManager", "verboseWarnings", false); + + char const * const appearanceTableFileName = "datatables/appearance/appearance_table.iff"; + + Iff iff; + if (iff.open(appearanceTableFileName)) + { + DataTable dataTable; + dataTable.load(iff); + + int const numberOfColumns = dataTable.getNumColumns(); + + int const numberOfRows = dataTable.getNumRows(); + for (int row = 0; row < numberOfRows; ++row) + { + std::string const & sourceName = dataTable.getStringValue(0, row); + TemporaryCrcString const crcSourceName(sourceName.c_str(), true); + + //-- Look up the source name + CrcStringVector * crcStringVector = 0; + { + ObjectTemplateAppearanceTemplateMap::iterator iter = ms_objectTemplateAppearanceTemplateMap.find(&crcSourceName); + if (iter != ms_objectTemplateAppearanceTemplateMap.end()) + { + DEBUG_WARNING(true, ("AppearanceManager::install(%s): duplicate entry found for %s", appearanceTableFileName, crcSourceName.getString())); + continue; + } + else + { + crcStringVector = new CrcStringVector(); + crcStringVector->reserve(static_cast(numberOfColumns)); + + ms_objectTemplateAppearanceTemplateMap.insert(std::make_pair(new PersistentCrcString(crcSourceName), crcStringVector)); + } + } + + //-- Read in the column data + for (int column = 1; column < numberOfColumns; ++column) + { + std::string const & fileName = dataTable.getStringValue(column, row); + +#ifdef _DEBUG + if (strstr(fileName.c_str(), ".sat") != 0 || strstr(fileName.c_str(), ".apt") != 0) + DEBUG_WARNING(ms_verboseWarnings && !TreeFile::exists(fileName.c_str()), ("AppearanceManager::install(%s): [%s] is not a valid entry for row %d column %s because the file does not exist", appearanceTableFileName, fileName.c_str(), row, dataTable.getColumnName(column).c_str())); + else + DEBUG_WARNING(!(fileName.empty() || fileName == ":block" || fileName == ":default" || fileName == ":hide" ), ("AppearanceManager::install(%s): [%s] is not a valid entry for row %d column %s", appearanceTableFileName, fileName.c_str(), row, dataTable.getColumnName(column).c_str())); +#endif + + TemporaryCrcString const crcFileName(fileName.c_str(), true); + + CrcString const * appearanceTemplateName = 0; + AppearanceTemplateNameSet::iterator iter = ms_appearanceTemplateNameSet.find(static_cast(&crcFileName)); + if (iter != ms_appearanceTemplateNameSet.end()) + appearanceTemplateName = *iter; + else + { + appearanceTemplateName = new PersistentCrcString(crcFileName); + + ms_appearanceTemplateNameSet.insert(appearanceTemplateName); + } + + crcStringVector->push_back(appearanceTemplateName); + } + } + } + +#ifdef _DEBUG + regressionTest(); +#endif + + ExitChain::add(AppearanceManagerNamespace::remove, "AppearanceManagerNamespace::remove"); +} + +// ---------------------------------------------------------------------- + +void AppearanceManagerNamespace::remove() +{ + DEBUG_FATAL(!ms_installed, ("AppearanceManagerNamespace::remove: not installed")); + ms_installed = false; + + std::for_each(ms_appearanceTemplateNameSet.begin(), ms_appearanceTemplateNameSet.end(), PointerDeleter()); + ms_appearanceTemplateNameSet.clear(); + + std::for_each(ms_objectTemplateAppearanceTemplateMap.begin(), ms_objectTemplateAppearanceTemplateMap.end(), PointerDeleterPair()); + ms_objectTemplateAppearanceTemplateMap.clear(); +} + +// ---------------------------------------------------------------------- + +//bool AppearanceManager::exists(CrcString const & sourceName) +bool AppearanceManager::isAppearanceManaged(std::string const &fileName) +{ + TemporaryCrcString const crcFileName(fileName.c_str(), true); + return ms_objectTemplateAppearanceTemplateMap.find(&crcFileName) != ms_objectTemplateAppearanceTemplateMap.end(); +} + +// ---------------------------------------------------------------------- + +//bool AppearanceManager::getAppearanceName(CrcString const & sourceName, int const column, CrcString const * & fileName) +bool AppearanceManager::getAppearanceName(std::string &targetName, std::string const &sourceName, int const sourceColumn) +{ + TemporaryCrcString const crcSourceName(sourceName.c_str(), true); + + //-- Look up the source name + ObjectTemplateAppearanceTemplateMap::iterator iter = ms_objectTemplateAppearanceTemplateMap.find(&crcSourceName); + if (iter == ms_objectTemplateAppearanceTemplateMap.end()) + return false; + + //-- Source name exists, so the column must exist + CrcStringVector const & crcStringVector = *iter->second; + int const column = sourceColumn - 1; + int const numberOfColumns = static_cast(crcStringVector.size()); + if (column < 0 || column >= numberOfColumns) + { + DEBUG_FATAL(true, ("AppearanceManager::getAppearanceName(%s): invalid column %d/%d", sourceName.c_str(), column, numberOfColumns)); + return false; + } + + targetName = crcStringVector[static_cast(column)]->getString(); + + return true; +} + +// ---------------------------------------------------------------------- + +#ifdef _DEBUG + +void AppearanceManagerNamespace::regressionTest() +{ + DEBUG_FATAL(!AppearanceManager::isAppearanceManaged("shared_aakuan_belt"), ("AppearanceManagerNamespace::regressionTest: FAILED - shared_aakuan_belt not found")); + + std::string targetName; + DEBUG_FATAL(!AppearanceManager::getAppearanceName(targetName, "shared_aakuan_belt", 1) || targetName != std::string("appearance/belt_s05_m.sat"), ("AppearanceManagerNamespace::regressionTest: shared_aakuan_belt Male Human appearance is supposed to be appearance/belt_s05_m.sat, but is %s", targetName.c_str())); +} + +#endif + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/object/AppearanceManager.h b/engine/shared/library/sharedGame/src/shared/object/AppearanceManager.h new file mode 100644 index 00000000..82d32553 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/AppearanceManager.h @@ -0,0 +1,28 @@ +// ============================================================================ +// +// AppearanceManager.cpp +// Copyright Sony Online Entertainment, Inc. +// +// ============================================================================ + +#ifndef INCLUDED_AppearanceManager_H +#define INCLUDED_AppearanceManager_H + +//----------------------------------------------------------------------------- +class AppearanceManager +{ +public: + + static void install(); + + static bool isAppearanceManaged(std::string const &fileName); + static bool getAppearanceName(std::string &targetName, std::string const &sourceName, int const column); + +private: + + static void remove(); +}; + +// ============================================================================ + +#endif // INCLUDED_AppearanceManager_H diff --git a/engine/shared/library/sharedGame/src/shared/object/AttribMod.cpp b/engine/shared/library/sharedGame/src/shared/object/AttribMod.cpp new file mode 100644 index 00000000..bbecb72e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/AttribMod.cpp @@ -0,0 +1,22 @@ +//======================================================================== +// +// AttribMod.cpp +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/AttribMod.h" + + +bool operator!=(const AttribMod::AttribMod & a, const AttribMod::AttribMod & b) +{ + // we are assuming that two mods with the same tag are equal, if the tags + // aren't 0 + if (a.tag != 0 || b.tag != 0) + return a.tag != b.tag; + else + return memcmp(&a, &b, sizeof(AttribMod::AttribMod)) != 0; +} + diff --git a/engine/shared/library/sharedGame/src/shared/object/AttribMod.h b/engine/shared/library/sharedGame/src/shared/object/AttribMod.h new file mode 100644 index 00000000..508bbb0e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/AttribMod.h @@ -0,0 +1,82 @@ +//======================================================================== +// +// AttribMod.h +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + + +#ifndef _INCLUDED_AttribMod_H +#define _INCLUDED_AttribMod_H + + +namespace AttribMod +{ + +struct AttribMod +{ + uint32 tag; // crc value to identify the mod + union + { + int attrib; // which attribute the mod affects + uint32 skill; // which skill the mod affects + }; + int value; // how much the mod changes the attribute + float attack; // time to go from 0 to value + float sustain; // time to stay at value + float decay; // time to go from value to 0 + int flags; // flag to define how the mod operates +}; + +// If decay is negative, it means on of these special conditions +enum AttribModDecaySpecial +{ + AMDS_pool = -1, // use the attribute pool recovery rate (normal recovery) + AMDS_wound = -2, // can only be healed by skill/item use, heal difficulty adjusted by shock wound value + AMDS_antidote = -3, // flag to remove attrib mods that affect the target attribute + AttribModDecaySpecial_Last = AMDS_antidote +}; + +// AttribMod flag values +enum AttribModFlags +{ + AMF_changeMax = 0x00000001, // the mod affects the max attrib value + AMF_attackCurrent = 0x00000002, // the mod attack/sustain affects the current attrib value + AMF_decayCurrent = 0x00000004, // the mod decay affects the current attrib value + AMF_triggerOnDone = 0x00000008, // cause a trigger to go off when the mod ends + AMF_visible = 0x00000010, // the attrib mod info should be sent to the player + AMF_skillMod = 0x00000020, // this mod affects skill mods, not attribs + AMF_directDamage = 0x00000040, // the mod is direct damage that should be applied to the creature +}; + +//----------------------------------------------------------------------- + +inline bool isAttribMod(const AttribMod & mod) +{ + return (mod.flags & (AMF_skillMod | AMF_directDamage)) == 0; +} + +inline bool isSkillMod(const AttribMod & mod) +{ + return (mod.flags & AMF_skillMod) != 0; +} + +inline bool isDirectDamage(const AttribMod & mod) +{ + return (mod.flags & AMF_directDamage) != 0; +} + +}; + +//----------------------------------------------------------------------- + +bool operator!=(const AttribMod::AttribMod & a, const AttribMod::AttribMod & b); +inline bool operator==(const AttribMod::AttribMod & a, const AttribMod::AttribMod & b) +{ + return !(a != b); +} + + +#endif // _INCLUDED_AttribMod_H + diff --git a/engine/shared/library/sharedGame/src/shared/object/AttribModArchive.cpp b/engine/shared/library/sharedGame/src/shared/object/AttribModArchive.cpp new file mode 100644 index 00000000..95cd917d --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/AttribModArchive.cpp @@ -0,0 +1,45 @@ +//======================================================================== +// +// AttribModArchive.cpp +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/AttribModArchive.h" +#include "sharedGame/AttribMod.h" + + +namespace Archive +{ + void put(Archive::ByteStream &target, const AttribMod::AttribMod &mod) + { + put(target, mod.tag); + put(target, mod.flags); + if (AttribMod::isSkillMod(mod)) + put(target, mod.skill); + else + put(target, mod.attrib); + put(target, mod.value); + put(target, mod.attack); + put(target, mod.sustain); + put(target, mod.decay); + } + void get(Archive::ReadIterator &source, AttribMod::AttribMod &mod) + { + get(source, mod.tag); + get(source, mod.flags); + if (AttribMod::isSkillMod(mod)) + get(source, mod.skill); + else + get(source, mod.attrib); + get(source, mod.value); + get(source, mod.attack); + get(source, mod.sustain); + get(source, mod.decay); + } +} + + + diff --git a/engine/shared/library/sharedGame/src/shared/object/AttribModArchive.h b/engine/shared/library/sharedGame/src/shared/object/AttribModArchive.h new file mode 100644 index 00000000..0dea19bb --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/AttribModArchive.h @@ -0,0 +1,28 @@ +//======================================================================== +// +// AttribModArchive.h +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + + +#ifndef _INCLUDED_AttribModArchive_H +#define _INCLUDED_AttribModArchive_H + +#include "Archive/AutoByteStream.h" + +namespace AttribMod +{ +struct AttribMod; +}; + + +namespace Archive +{ + void put(Archive::ByteStream &target, const AttribMod::AttribMod &mod); + void get(Archive::ReadIterator &source, AttribMod::AttribMod &mod); +} + +#endif // _INCLUDED_AttribModArchive_H + diff --git a/engine/shared/library/sharedGame/src/shared/object/Buff.cpp b/engine/shared/library/sharedGame/src/shared/object/Buff.cpp new file mode 100644 index 00000000..a3b97550 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/Buff.cpp @@ -0,0 +1,162 @@ +// ====================================================================== +// +// Buff.cpp +// +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Adam Hunter +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/Buff.h" + +#include "Archive/Archive.h" +#include "sharedFoundation/Crc.h" +#include "sharedFoundation/NetworkIdArchive.h" +// ====================================================================== + +Buff::Buff() : +m_name(), +m_nameCrc(0), +m_timestamp(0), +m_value(0), +m_duration(0), +m_caster(NetworkId::cms_invalid), +m_stackCount(1) +{ +} + +Buff::Buff(std::string const &buffName, Buff::PackedBuff buffValues) : +m_name(buffName), +m_nameCrc(0), +m_timestamp(buffValues.endtime), +m_value(buffValues.value), +m_duration(buffValues.duration), +m_caster(buffValues.caster), +m_stackCount(buffValues.stackCount) +{ + m_nameCrc = Crc::calculate(buffName.c_str()); +} + +// ====================================================================== + +Buff::Buff(std::string const &buffName, uint32 timestamp, float value, uint32 duration, NetworkId caster, uint32 stackCount) : +m_name(buffName), +m_nameCrc(0), +m_timestamp(timestamp), +m_value(value), +m_duration(duration), +m_caster(caster), +m_stackCount(stackCount) +{ + m_nameCrc = Crc::calculate(buffName.c_str()); +} + +// ====================================================================== + +Buff::Buff(uint32 buffNameCrc, Buff::PackedBuff buffValues) : +m_name(""), +m_nameCrc(buffNameCrc), +m_timestamp(buffValues.endtime), +m_value(buffValues.value), +m_duration(buffValues.duration), +m_caster(buffValues.caster), +m_stackCount(buffValues.stackCount) +{ +} + +// ====================================================================== + +Buff::Buff(uint32 buffNameCrc, uint32 timestamp, float value, uint32 duration, NetworkId caster, uint32 stackCount) : +m_name(""), +m_nameCrc(buffNameCrc), +m_timestamp(timestamp), +m_value(value), +m_duration(duration), +m_caster(caster), +m_stackCount(stackCount) +{ +} + +// ====================================================================== + +Buff::~Buff() +{ +} + +// ====================================================================== + +Buff &Buff::operator=(Buff const &rhs) +{ + if (this != (&rhs)) + { + m_name = rhs.m_name; + m_nameCrc = rhs.m_nameCrc; + m_timestamp = rhs.m_timestamp; + m_value = rhs.m_value; + m_duration = rhs.m_duration; + m_caster = rhs.m_caster; + m_stackCount = rhs.m_stackCount; + } + return *this; +} + +// ====================================================================== + +Buff::PackedBuff Buff::getPackedBuffValue() +{ + PackedBuff result; + result.endtime = m_timestamp; + result.duration = m_duration; + result.value = m_value; + result.caster = m_caster; + result.stackCount = m_stackCount; + return result; +} + +void Buff::set(uint32 buffNameCrc, Buff::PackedBuff buffValues) +{ + m_name = ""; + m_nameCrc = buffNameCrc; + m_timestamp = buffValues.endtime; + m_value = buffValues.value; + m_duration = buffValues.duration; + m_caster = buffValues.caster; + m_stackCount = buffValues.stackCount; +} +// ====================================================================== + +namespace Archive +{ + void get (ReadIterator &source, Buff::PackedBuff &target) + { + get(source, target.endtime); + get(source, target.value); + get(source, target.duration); + get(source, target.caster); + get(source, target.stackCount); + } + void put (ByteStream &target, const Buff::PackedBuff &source) + { + put(target, source.endtime); + put(target, source.value); + put(target, source.duration); + put(target, source.caster); + put(target, source.stackCount); + } +} + +Buff::PackedBuff Buff::makePackedBuff(uint64 oldSchoolPackedBuff) +{ + PackedBuff result; + + DEBUG_FATAL(sizeof(float) != sizeof(uint32), ("This buff struct won't work if float isn't 32 bits")); + result.endtime = static_cast(oldSchoolPackedBuff >> 32); + uint32 tmp = static_cast(oldSchoolPackedBuff & 0x00000000FFFFFFFF); + // Yes, this really is taking 32 bits of memory and turning them into a float. -- ARH + result.value = *(reinterpret_cast(&tmp)); + result.duration = 0; + result.caster = NetworkId::cms_invalid; + result.stackCount = 1; + + return result; +} diff --git a/engine/shared/library/sharedGame/src/shared/object/Buff.h b/engine/shared/library/sharedGame/src/shared/object/Buff.h new file mode 100644 index 00000000..f189e461 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/Buff.h @@ -0,0 +1,81 @@ +// ====================================================================== +// +// Buff.h +// +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Adam Hunter +// ====================================================================== + +#ifndef _INCLUDED_Buff_H +#define _INCLUDED_Buff_H + +// ====================================================================== + +#include "sharedFoundation/NetworkId.h" + +class Buff +{ +public: + + struct PackedBuff + { + uint32 endtime; + float value; + uint32 duration; + NetworkId caster; + uint32 stackCount; + + inline bool operator != (const Buff::PackedBuff& rhs) const; + inline bool operator == (const Buff::PackedBuff& rhs) const; + }; + + Buff(); + Buff(std::string const &buffName, PackedBuff buffValues); + Buff(std::string const &buffName, uint32 timestamp, float value, uint32 duration, NetworkId caster, uint32 stackCount); + Buff(uint32 buffNameCrc, PackedBuff buffValues); + Buff(uint32 buffNameCrc, uint32 timestamp, float value, uint32 duration, NetworkId caster = NetworkId::cms_invalid, uint32 stackCount = 1); + ~Buff(); + + Buff &operator=(Buff const &rhs); + + PackedBuff getPackedBuffValue(); + static PackedBuff makePackedBuff(uint64 oldSchoolPackedBuff); + + void set(uint32 buffNameCrc, PackedBuff buffValues); + + std::string m_name; + uint32 m_nameCrc; + uint32 m_timestamp; + float m_value; + uint32 m_duration; + NetworkId m_caster; + uint32 m_stackCount; + +}; + +namespace Archive +{ + class ReadIterator; + class ByteStream; + + void get (ReadIterator &source, Buff::PackedBuff &target); + void put (ByteStream &target, const Buff::PackedBuff &source); +} + + +inline bool Buff::PackedBuff::operator != (const Buff::PackedBuff& rhs) const +{ + return (endtime != rhs.endtime || value != rhs.value || duration != rhs.duration || caster != rhs.caster || stackCount != rhs.stackCount); +} + +inline bool Buff::PackedBuff::operator == (const Buff::PackedBuff& rhs) const +{ + return !(rhs != *this); +} + + + +// ====================================================================== + +#endif // _INCLUDED_Buff_H + diff --git a/engine/shared/library/sharedGame/src/shared/object/GroupPickupPoint.cpp b/engine/shared/library/sharedGame/src/shared/object/GroupPickupPoint.cpp new file mode 100644 index 00000000..29052821 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/GroupPickupPoint.cpp @@ -0,0 +1,85 @@ +// ====================================================================== +// +// GroupPickupPoint.cpp +// Copyright 2008 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/GroupPickupPoint.h" + +#include "sharedGame/TravelManager.h" +#include "sharedMath/Vector.h" +#include "sharedObject/Object.h" + +#include + +// ====================================================================== + +bool GroupPickupPoint::isGroupPickupAllowedAtLocation(std::string const & planetName, Object const & object) +{ + Vector const objectWorldLocation = object.findPosition_w(); + return isGroupPickupAllowedAtLocation(planetName, static_cast(objectWorldLocation.x), static_cast(objectWorldLocation.z)); +} + +// ---------------------------------------------------------------------- + +bool GroupPickupPoint::isGroupPickupAllowedAtLocation(std::string const & planetName, int x, int z) +{ + static std::map, std::pair > > s_groupPickupAllowedLocation; + if (s_groupPickupAllowedLocation.empty()) + { + s_groupPickupAllowedLocation["tatooine"] = std::make_pair(std::make_pair(0, 0), std::make_pair(0, 0)); + s_groupPickupAllowedLocation["naboo"] = std::make_pair(std::make_pair(0, 0), std::make_pair(0, 0)); + s_groupPickupAllowedLocation["corellia"] = std::make_pair(std::make_pair(0, 0), std::make_pair(0, 0)); + s_groupPickupAllowedLocation["rori"] = std::make_pair(std::make_pair(0, 0), std::make_pair(0, 0)); + s_groupPickupAllowedLocation["talus"] = std::make_pair(std::make_pair(0, 0), std::make_pair(0, 0)); + s_groupPickupAllowedLocation["yavin4"] = std::make_pair(std::make_pair(0, 0), std::make_pair(0, 0)); + s_groupPickupAllowedLocation["endor"] = std::make_pair(std::make_pair(0, 0), std::make_pair(0, 0)); + s_groupPickupAllowedLocation["lok"] = std::make_pair(std::make_pair(0, 0), std::make_pair(0, 0)); + s_groupPickupAllowedLocation["dantooine"] = std::make_pair(std::make_pair(0, 0), std::make_pair(0, 0)); + s_groupPickupAllowedLocation["dathomir"] = std::make_pair(std::make_pair(0, 0), std::make_pair(0, 0)); + s_groupPickupAllowedLocation["kashyyyk_main"] = std::make_pair(std::make_pair(0, 0), std::make_pair(0, 0)); + s_groupPickupAllowedLocation["kashyyyk_hunting"] = std::make_pair(std::make_pair(0, 0), std::make_pair(0, 0)); + s_groupPickupAllowedLocation["kashyyyk_dead_forest"] = std::make_pair(std::make_pair(0, 0), std::make_pair(0, 0)); + s_groupPickupAllowedLocation["mustafar"] = std::make_pair(std::make_pair(-6880, -1024), std::make_pair(1120, 6976)); // the "public" area of mustafar, from areas_mustafar.tab + } + + std::map, std::pair > >::const_iterator iterFind = s_groupPickupAllowedLocation.find(planetName); + if (iterFind != s_groupPickupAllowedLocation.end()) + { + if ((iterFind->second.first.first == 0) && (iterFind->second.first.second == 0) && (iterFind->second.second.first == 0) && (iterFind->second.second.second == 0)) + return true; + + if ((x >= iterFind->second.first.first) && (x <= iterFind->second.second.first) && (z >= iterFind->second.first.second) && (z <= iterFind->second.second.second)) + return true; + } + + return false; +} + +// ---------------------------------------------------------------------- + +bool GroupPickupPoint::getGroupPickupTravelCost(const std::string& sourcePlanet, const std::string& targetPlanet, int& cost) +{ + // none of the other kashyyyk zones have starport, so use kashyyyk_main for them + std::string source = sourcePlanet; + std::string target = targetPlanet; + + if (source.find("kashyyyk") == 0) + source = "kashyyyk_main"; + + if (target.find("kashyyyk") == 0) + target = "kashyyyk_main"; + + if (source == target) + { + cost = 200; + return true; + } + + return TravelManager::getPlanetAnyHopLeastCost(source, target, cost); +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/object/GroupPickupPoint.h b/engine/shared/library/sharedGame/src/shared/object/GroupPickupPoint.h new file mode 100644 index 00000000..af353d96 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/GroupPickupPoint.h @@ -0,0 +1,33 @@ +// ====================================================================== +// +// GroupPickupPoint.h +// Copyright 2006 Sony Online Entertainment LLC (SOE) +// All rights reserved. +// +// ====================================================================== + +#ifndef INCLUDED_GroupPickupPoint_H +#define INCLUDED_GroupPickupPoint_H + +class Object; + +// ====================================================================== + +class GroupPickupPoint // static class +{ +public: + + static bool isGroupPickupAllowedAtLocation(std::string const & planetName, Object const & object); + static bool isGroupPickupAllowedAtLocation(std::string const & planetName, int x, int z); + static bool getGroupPickupTravelCost(const std::string& sourcePlanet, const std::string& targetPlanet, int& cost); + +private: // disabled + + GroupPickupPoint(); + GroupPickupPoint(GroupPickupPoint const &); + GroupPickupPoint &operator =(GroupPickupPoint const &); +}; + +// ====================================================================== + +#endif // INCLUDED_GroupPickupPoint_H diff --git a/engine/shared/library/sharedGame/src/shared/object/LotManagerNotification.cpp b/engine/shared/library/sharedGame/src/shared/object/LotManagerNotification.cpp new file mode 100644 index 00000000..1224bc9a --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/LotManagerNotification.cpp @@ -0,0 +1,105 @@ +//=================================================================== +// +// LotManagerNotification.cpp +// asommers +// +// copyright 2001, sony online entertainment +// +//=================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/LotManagerNotification.h" + +#include "sharedGame/SharedTangibleObjectTemplate.h" +#include "sharedObject/LotManager.h" +#include "sharedObject/World.h" +#include "sharedTerrain/TerrainObject.h" + +//=================================================================== +// PUBLIC LotManagerNotification +//=================================================================== + +LotManagerNotification::LotManagerNotification () : + ObjectNotification () +{ +} + +//------------------------------------------------------------------- + +LotManagerNotification::~LotManagerNotification () +{ +} + +//------------------------------------------------------------------- + +void LotManagerNotification::removeFromWorld (Object& object) const +{ + LotManager* const lotManager = World::getLotManager (); + NOT_NULL (lotManager); + + lotManager->removeStructureFootprintEntry (object); +} + +//------------------------------------------------------------------- + +bool LotManagerNotification::positionChanged (Object& object, bool /*dueToParentChange*/, const Vector& /*oldPosition*/) const +{ + rotationChanged (object, false); + + return true; +} + +//------------------------------------------------------------------- + +void LotManagerNotification::rotationChanged (Object& object, bool /*dueToParentChange*/) const +{ + if (object.isInWorld ()) + { + removeFromWorld (object); + addToWorld (object); + } +} + +//------------------------------------------------------------------- + +bool LotManagerNotification::positionAndRotationChanged (Object& object, bool /*dueToParentChange*/, const Vector& /*oldPosition*/) const +{ + rotationChanged (object, false); + + return true; +} + +//=================================================================== +// PROTECTED LotManagerNotification +//=================================================================== + +void LotManagerNotification::addToWorld (Object& object, const StructureFootprint& structureFootprint) const +{ + const Vector k = object.getObjectFrameK_w (); + + RotationType rotationType = RT_0; + if (k.x > 0.95) + rotationType = RT_90; + else + if (k.z < -0.95) + rotationType = RT_180; + else + if (k.x < -0.95) + rotationType = RT_270; + + const TerrainObject* const terrainObject = TerrainObject::getConstInstance (); + NOT_NULL (terrainObject); + + const Vector createLocation = object.getPosition_w (); + const int x = terrainObject->calculateChunkX (createLocation); + const int z = terrainObject->calculateChunkZ (createLocation); + + LotManager* const lotManager = World::getLotManager (); + NOT_NULL (lotManager); + + lotManager->addStructureFootprintEntry (object, structureFootprint, x, z, rotationType); +} + +//=================================================================== + + diff --git a/engine/shared/library/sharedGame/src/shared/object/LotManagerNotification.h b/engine/shared/library/sharedGame/src/shared/object/LotManagerNotification.h new file mode 100644 index 00000000..1dac7fb3 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/LotManagerNotification.h @@ -0,0 +1,47 @@ +//=================================================================== +// +// LotManagerNotification.h +// asommers +// +// copyright 2001, sony online entertainment +// +//=================================================================== + +#ifndef INCLUDED_LotManagerNotification_H +#define INCLUDED_LotManagerNotification_H + +//=================================================================== + +#include "sharedObject/ObjectNotification.h" + +class StructureFootprint; + +//=================================================================== + +class LotManagerNotification : public ObjectNotification +{ +public: + + LotManagerNotification (); + virtual ~LotManagerNotification (); + + virtual void addToWorld (Object& object) const=0; + virtual void removeFromWorld (Object& object) const; + + virtual bool positionChanged (Object& object, bool dueToParentChange, const Vector& oldPosition) const; + virtual void rotationChanged (Object& object, bool dueToParentChange) const; + virtual bool positionAndRotationChanged (Object& object, bool dueToParentChange, const Vector& oldPosition) const; + +protected: + + virtual void addToWorld (Object& object, const StructureFootprint& structureFootprint) const; + +private: + + LotManagerNotification (const LotManagerNotification&); + LotManagerNotification& operator= (const LotManagerNotification&); +}; + +//=================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterPreferenceId.cpp b/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterPreferenceId.cpp new file mode 100644 index 00000000..23777558 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterPreferenceId.cpp @@ -0,0 +1,123 @@ +// ============================================================================ +// +// MatchMakingCharacterPreferenceId.cpp +// Copyright Sony Online Entertainment +// +// ============================================================================ + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/MatchMakingCharacterPreferenceId.h" + +// ============================================================================ +// +// Archive +// +// ============================================================================ + +//----------------------------------------------------------------------------- + +void Archive::get(ReadIterator &source, MatchMakingCharacterPreferenceId &target) +{ + // Search Attribute + get(source, target.getSearchAttribute()); + + // Sub-string + std::string subString; + get(source, subString); + target.setSubString(subString); +} + +//----------------------------------------------------------------------------- + +void Archive::put(ByteStream &target, const MatchMakingCharacterPreferenceId &source) +{ + // Search Attribute + put(target, source.getSearchAttribute()); + + // Sub-string + put(target, source.getSubString()); +} + +// ============================================================================ +// +// MatchMakingCharacterPreferenceId +// +// ============================================================================ + +//----------------------------------------------------------------------------- + +MatchMakingCharacterPreferenceId::MatchMakingCharacterPreferenceId() + : m_searchAttribute() + , m_subString() +{ +} + +//----------------------------------------------------------------------------- + +bool MatchMakingCharacterPreferenceId::operator ==(MatchMakingCharacterPreferenceId const &rhs) const +{ + return (m_searchAttribute == rhs.m_searchAttribute); +} + +//----------------------------------------------------------------------------- + +bool MatchMakingCharacterPreferenceId::operator !=(MatchMakingCharacterPreferenceId const &rhs) const +{ + return !(*this == rhs); +} + +//----------------------------------------------------------------------------- + +MatchMakingCharacterPreferenceId &MatchMakingCharacterPreferenceId::operator =(MatchMakingCharacterPreferenceId const &rhs) +{ + if (this != &rhs) + { + m_searchAttribute = rhs.getSearchAttribute(); + m_subString = rhs.getSubString(); + } + + return *this; +} + +//----------------------------------------------------------------------------- + +void MatchMakingCharacterPreferenceId::packString(std::string &value) const +{ + m_searchAttribute.getAsDbTextString(value); + if (value.empty()) + value = "NONE"; + + if (!m_subString.empty()) + { + value += " "; + value += m_subString; + } +} + +//----------------------------------------------------------------------------- + +void MatchMakingCharacterPreferenceId::unPackString(std::string const &value) +{ + size_t const separator = value.find(' '); + if (separator == std::string::npos) + { + m_subString.clear(); + + if (value.empty() || (value == std::string("NONE"))) + m_searchAttribute.clear(); + else + m_searchAttribute.setFromDbTextString(value.c_str()); + } + else + { + std::string const ba = value.substr(0, separator); + m_subString = value.substr(separator + 1); + + if (ba.empty() || (ba == std::string("NONE"))) + m_searchAttribute.clear(); + else + m_searchAttribute.setFromDbTextString(ba.c_str()); + } +} + +// ============================================================================ diff --git a/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterPreferenceId.h b/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterPreferenceId.h new file mode 100644 index 00000000..c3c1bf9d --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterPreferenceId.h @@ -0,0 +1,78 @@ +// ============================================================================ +// +// MatchMakingCharacterPreferenceId.h +// Copyright Sony Online Entertainment +// +// ============================================================================ + +#ifndef INCLUDED_MatchMakingCharacterPreferenceId_H +#define INCLUDED_MatchMakingCharacterPreferenceId_H + +#include "Archive/AutoByteStream.h" +#include "sharedFoundation/BitArray.h" + +//----------------------------------------------------------------------------- +class MatchMakingCharacterPreferenceId +{ +public: + + MatchMakingCharacterPreferenceId(); + + void setSubString(std::string const &subString); + std::string const & getSubString() const; + + BitArray const & getSearchAttribute() const; + BitArray & getSearchAttribute(); + + void packString(std::string &value) const; + void unPackString(std::string const &value); + + bool operator ==(MatchMakingCharacterPreferenceId const &rhs) const; + bool operator !=(MatchMakingCharacterPreferenceId const &rhs) const; + MatchMakingCharacterPreferenceId &operator =(MatchMakingCharacterPreferenceId const &rhs); + +private: + + BitArray m_searchAttribute; + std::string m_subString; +}; + +//----------------------------------------------------------------------------- + +namespace Archive +{ + void get(ReadIterator &source, MatchMakingCharacterPreferenceId &target); + void put(ByteStream &target, const MatchMakingCharacterPreferenceId &source); +} + +//----------------------------------------------------------------------------- + +inline void MatchMakingCharacterPreferenceId::setSubString(std::string const &subString) +{ + m_subString = subString; +} + +//----------------------------------------------------------------------------- + +inline std::string const & MatchMakingCharacterPreferenceId::getSubString() const +{ + return m_subString; +} + +//----------------------------------------------------------------------------- + +inline BitArray const & MatchMakingCharacterPreferenceId::getSearchAttribute() const +{ + return m_searchAttribute; +} + +//----------------------------------------------------------------------------- + +inline BitArray & MatchMakingCharacterPreferenceId::getSearchAttribute() +{ + return m_searchAttribute; +} + +// ============================================================================ + +#endif // INCLUDED_MatchMakingCharacterPreferenceId_H diff --git a/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterProfileId.cpp b/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterProfileId.cpp new file mode 100644 index 00000000..ce7a5efa --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterProfileId.cpp @@ -0,0 +1,96 @@ +// ============================================================================ +// +// MatchMakingCharacterProfileId.cpp +// Copyright Sony Online Entertainment +// +// ============================================================================ + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/MatchMakingCharacterProfileId.h" + +// ============================================================================ +// +// Archive +// +// ============================================================================ + +//----------------------------------------------------------------------------- +void Archive::get(ReadIterator &source, MatchMakingCharacterProfileId &target) +{ + // Match making id + + MatchMakingId::IntVector ints; + get(source, ints); + MatchMakingId matchMakingId; + matchMakingId.setBits(ints); + target.setMatchMakingId(matchMakingId); +} + +//----------------------------------------------------------------------------- +void Archive::put(ByteStream &target, const MatchMakingCharacterProfileId &source) +{ + // Match making id + + put(target, source.getMatchMakingId().getInts()); +} + +// ============================================================================ +// +// MatchMakingCharacterProfileId +// +// ============================================================================ + +//----------------------------------------------------------------------------- +MatchMakingCharacterProfileId::MatchMakingCharacterProfileId() + : m_matchMakingId() +{ +} + +//----------------------------------------------------------------------------- +void MatchMakingCharacterProfileId::setMatchMakingId(MatchMakingId const &matchMakindId) +{ + m_matchMakingId = matchMakindId; +} + +//----------------------------------------------------------------------------- +MatchMakingId const &MatchMakingCharacterProfileId::getMatchMakingId() const +{ + return m_matchMakingId; +} + +//----------------------------------------------------------------------------- +void MatchMakingCharacterProfileId::unpackFromString(std::string &value) +{ + UNREF(value); +} + +//----------------------------------------------------------------------------- +void MatchMakingCharacterProfileId::packToString(std::string &value) +{ + UNREF(value); +} + +//----------------------------------------------------------------------------- +bool MatchMakingCharacterProfileId::operator ==(MatchMakingCharacterProfileId const &rhs) const +{ + return (m_matchMakingId == rhs.m_matchMakingId); +} + +//----------------------------------------------------------------------------- +bool MatchMakingCharacterProfileId::operator !=(MatchMakingCharacterProfileId const &rhs) const +{ + return !(*this == rhs); +} + +//----------------------------------------------------------------------------- +MatchMakingCharacterProfileId &MatchMakingCharacterProfileId::operator =(MatchMakingCharacterProfileId const &rhs) +{ + if (this != &rhs) + { + m_matchMakingId = rhs.m_matchMakingId; + } + + return *this; +} + +// ============================================================================ diff --git a/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterProfileId.h b/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterProfileId.h new file mode 100644 index 00000000..87503c95 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterProfileId.h @@ -0,0 +1,45 @@ +// ============================================================================ +// +// MatchMakingCharacterProfileId.h +// Copyright Sony Online Entertainment +// +// ============================================================================ + +#ifndef INCLUDED_MatchMakingCharacterProfileId_H +#define INCLUDED_MatchMakingCharacterProfileId_H + +#include "Archive/AutoByteStream.h" +#include "sharedGame/MatchMakingId.h" + +//----------------------------------------------------------------------------- +class MatchMakingCharacterProfileId +{ +public: + + MatchMakingCharacterProfileId(); + + void setMatchMakingId(MatchMakingId const &matchMakindId); + MatchMakingId const &getMatchMakingId() const; + + void unpackFromString(std::string &value); + void packToString(std::string &value); + + bool operator ==(MatchMakingCharacterProfileId const &rhs) const; + bool operator !=(MatchMakingCharacterProfileId const &rhs) const; + MatchMakingCharacterProfileId &operator =(MatchMakingCharacterProfileId const &rhs); + +private: + + MatchMakingId m_matchMakingId; +}; + +//----------------------------------------------------------------------------- +namespace Archive +{ + void get(ReadIterator &source, MatchMakingCharacterProfileId &target); + void put(ByteStream &target, const MatchMakingCharacterProfileId &source); +} + +// ============================================================================ + +#endif // INCLUDED_MatchMakingCharacterProfileId_H diff --git a/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterResult.cpp b/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterResult.cpp new file mode 100644 index 00000000..8aa64b8e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterResult.cpp @@ -0,0 +1,76 @@ +// ============================================================================ +// +// MatchMakingCharacterResult.cpp +// Copyright Sony Online Entertainment +// +// ============================================================================ + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/MatchMakingCharacterResult.h" + +#include "sharedFoundation/NetworkIdArchive.h" +#include "unicodeArchive/UnicodeArchive.h" + +// ============================================================================ + +MatchMakingCharacterResult::MatchMakingCharacterResult() : + m_matchingCharacterData(), + m_matchingCharacterBiography(), + m_matchingCharacterGroup(), + m_hasMoreMatches(false) +{ +} + +//----------------------------------------------------------------------------- + +MatchMakingCharacterResult::~MatchMakingCharacterResult() +{ +} + +// ============================================================================ +// +// Archive +// +// ============================================================================ + +//----------------------------------------------------------------------------- + +void Archive::get(ReadIterator &source, MatchMakingCharacterResult::MatchMakingCharacterGroupMemberInfo &target) +{ + get(source, target.groupMemberId); + get(source, target.groupMemberName); + get(source, target.groupMemberLevel); + get(source, target.groupMemberProfession); +} + +//----------------------------------------------------------------------------- + +void Archive::put(ByteStream &target, const MatchMakingCharacterResult::MatchMakingCharacterGroupMemberInfo &source) +{ + put(target, source.groupMemberId); + put(target, source.groupMemberName); + put(target, source.groupMemberLevel); + put(target, source.groupMemberProfession); +} + +//----------------------------------------------------------------------------- + +void Archive::get(ReadIterator &source, MatchMakingCharacterResult &target) +{ + get(source, target.m_matchingCharacterData); + get(source, target.m_matchingCharacterBiography); + get(source, target.m_matchingCharacterGroup); + get(source, target.m_hasMoreMatches); +} + +//----------------------------------------------------------------------------- + +void Archive::put(ByteStream &target, const MatchMakingCharacterResult &source) +{ + put(target, source.m_matchingCharacterData); + put(target, source.m_matchingCharacterBiography); + put(target, source.m_matchingCharacterGroup); + put(target, source.m_hasMoreMatches); +} + +// ============================================================================ diff --git a/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterResult.h b/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterResult.h new file mode 100644 index 00000000..0dd3046e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/MatchMakingCharacterResult.h @@ -0,0 +1,50 @@ +// ============================================================================ +// +// MatchMakingCharacterResult.h +// Copyright Sony Online Entertainment +// +// ============================================================================ + +#ifndef INCLUDED_MatchMakingCharacterResult_H +#define INCLUDED_MatchMakingCharacterResult_H + +#include "sharedGame/LfgCharacterData.h" + +//----------------------------------------------------------------------------- +struct MatchMakingCharacterResult +{ + MatchMakingCharacterResult(); + ~MatchMakingCharacterResult(); + + std::vector m_matchingCharacterData; + std::map m_matchingCharacterBiography; + + struct MatchMakingCharacterGroupMemberInfo + { + NetworkId groupMemberId; + std::string groupMemberName; + int groupMemberLevel; + uint8 groupMemberProfession; + }; + + std::map > m_matchingCharacterGroup; + bool m_hasMoreMatches; +}; + +//----------------------------------------------------------------------------- + +namespace Archive +{ + class ReadIterator; + class ByteStream; + + void get(ReadIterator &source, MatchMakingCharacterResult &target); + void put(ByteStream &target, const MatchMakingCharacterResult &source); + + void get(ReadIterator &source, MatchMakingCharacterResult::MatchMakingCharacterGroupMemberInfo &target); + void put(ByteStream &target, const MatchMakingCharacterResult::MatchMakingCharacterGroupMemberInfo &source); +} + +// ============================================================================ + +#endif // INCLUDED_MatchMakingCharacterResult_H diff --git a/engine/shared/library/sharedGame/src/shared/object/MatchMakingId.cpp b/engine/shared/library/sharedGame/src/shared/object/MatchMakingId.cpp new file mode 100644 index 00000000..81f0ba62 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/MatchMakingId.cpp @@ -0,0 +1,404 @@ +// ============================================================================ +// +// MatchMakingId.cpp +// Copyright Sony Online Entertainment +// +// ============================================================================ + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/MatchMakingId.h" + +#include +#include +#include "UnicodeUtils.h" + +// ============================================================================ +// +// Archive +// +// ============================================================================ + +//----------------------------------------------------------------------------- +void Archive::get(ReadIterator &source, MatchMakingId &target) +{ + // Get the packed vector + + MatchMakingId::IntVector ints; + + get(source, ints); + + // Set the id from the vector + + target.setBits(ints); + + //DEBUG_REPORT_LOG(true, ("MatchMakingId::Archive::get() %s\n", target.getDebugIntString().c_str())); +} + +//----------------------------------------------------------------------------- +void Archive::put(ByteStream &target, const MatchMakingId &source) +{ + //DEBUG_REPORT_LOG(true, ("MatchMakingId::Archive::put() %s\n", source.getDebugIntString().c_str())); + + // Pack the vector + + MatchMakingId::IntVector ints(source.getInts()); + + put(target, ints); +} + +// ============================================================================ +// +// MatchMakingId +// +// ============================================================================ + +//----------------------------------------------------------------------------- +MatchMakingId::MatchMakingId() + : m_id() +{ + reset(); +} + +//----------------------------------------------------------------------------- +void MatchMakingId::resetBit(Bit const bit) +{ + DEBUG_FATAL((static_cast(bit) >= static_cast(m_id.size())), ("Out of range bit for match making id: %d", static_cast(bit))); + + if (static_cast(bit) < static_cast(m_id.size())) + { + IGNORE_RETURN(m_id.reset(static_cast(bit))); + } +} + +//----------------------------------------------------------------------------- +bool MatchMakingId::isBitSet(Bit const bit) const +{ + bool result = false; + + if (static_cast(bit) < static_cast(m_id.size())) + { + result = m_id.test(static_cast(bit)); + } + + return result; +} + +//----------------------------------------------------------------------------- +std::string MatchMakingId::getDebugIntString() const +{ + IntVector ints(getInts()); + + std::string result; + + for (int bit = 0; bit < getBitCount(); ++bit) + { + if (isBitSet(static_cast(bit))) + { + char text[34]; + _itoa(bit, text, 10); + result += text; + result += " "; + } + } + + return result; +} + +//----------------------------------------------------------------------------- +bool MatchMakingId::operator ==(MatchMakingId const &rhs) const +{ + //DEBUG_REPORT_LOG(true, ("MatchMakingId::operator ==() %s %s\n", getDebugIntString().c_str(), rhs.getDebugIntString().c_str())); + + return (m_id == rhs.m_id); +} + +//----------------------------------------------------------------------------- +bool MatchMakingId::operator !=(MatchMakingId const &rhs) const +{ + return !(*this == rhs); +} + +//----------------------------------------------------------------------------- +MatchMakingId &MatchMakingId::operator =(MatchMakingId const &rhs) +{ + //DEBUG_REPORT_LOG(true, ("MatchMakingId::operator ==() %s %s\n", getDebugIntString().c_str(), rhs.getDebugIntString().c_str())); + + if (this != &rhs) + { + m_id = rhs.m_id; + } + + return *this; +} + +//----------------------------------------------------------------------------- +void MatchMakingId::reset() +{ + IGNORE_RETURN(m_id.reset()); +} + +//----------------------------------------------------------------------------- +MatchMakingId::IntVector MatchMakingId::getInts() const +{ + MatchMakingId::IntVector ints; + + ints.push_back(0); + + { + int counter = 0; + + for (int i = 0; i < static_cast(m_id.size()); ++i) + { + if (counter >= 32) + { + counter = 0; + ints.push_back(0); + } + + if (isBitSet(static_cast(i))) + { + int const intsIndex = (ints.size() == 0) ? 0 : (static_cast(ints.size()) - 1); + + ints[static_cast(intsIndex)] |= (0x00000001 << counter); + } + + ++counter; + } + } + + DEBUG_FATAL((ints.size() > 4), ("Too many ints: %d", ints.size())); + + return ints; +} + +//----------------------------------------------------------------------------- +void MatchMakingId::setBits(IntVector const &ints) +{ + reset(); + + int const intsSize = static_cast(ints.size()); + int const bitCount = intsSize * 32; + unsigned int intsIndex = 0; + int counter = 0; + + for (int i = 0; i < bitCount; ++i) + { + if (counter >= 32) + { + counter = 0; + ++intsIndex; + } + + int const value = ints[intsIndex]; + + if (value & (0x00000001 << counter)) + { + setBit(static_cast(i)); + } + + ++counter; + } +} + +//----------------------------------------------------------------------------- +void MatchMakingId::toggleBit(Bit const bit) +{ + if (isBitSet(bit)) + { + resetBit(bit); + } + else + { + setBit(bit); + } +} + +//----------------------------------------------------------------------------- +int MatchMakingId::getBitCount() const +{ + return static_cast(m_id.size()); +} + +//----------------------------------------------------------------------------- +void MatchMakingId::setBit(Bit const bit) +{ + DEBUG_FATAL((static_cast(bit) >= static_cast(m_id.size())), ("Out of range bit for match making id: %d", static_cast(bit))); + + if (static_cast(bit) < static_cast(m_id.size())) + { + IGNORE_RETURN(m_id.set(static_cast(bit))); + } +} + +//----------------------------------------------------------------------------- +float MatchMakingId::getMatchPercent(MatchMakingId const &id) const +{ + float result = 0.0f; + int usedBits = 0; + int matchBits = 0; + bool const anonymous = id.isBitSet(B_anonymous); + + if (!anonymous) + { + for (int i = 0; i < static_cast(B_maxLoadedBits); ++i) + { + if (isBitSet(static_cast(i))) + { + ++usedBits; + + if (id.isBitSet(static_cast(i))) + { + ++matchBits; + } + } + } + } + + if (usedBits > 0) + { + result = static_cast(matchBits) / static_cast(usedBits); + } + + return result; +} + +//----------------------------------------------------------------------------- +int MatchMakingId::getSetBitCount() const +{ + // This sucks. I should be able to call m_id.count(), but it does not compile + // in both debug/release for bitsets. + + int result = 0; + + for (int i = 0; i < static_cast(B_maxLoadedBits); ++i) + { + if (isBitSet(static_cast(i))) + { + ++result; + } + } + + return result; +} + +//----------------------------------------------------------------------------- +void MatchMakingId::unPackBitString(std::string const &value) +{ + if (value.empty()) + { + reset(); + } + else if ((static_cast(value.size()) != getBitCount())) + { + // String size is invalid + + DEBUG_WARNING(true, ("Invalid MatchMakingId size during unpack (%d) expecting (%d)...aborting unpack", static_cast(value.size()), getBitCount())); + + reset(); + } + else + { + // String size looks good + + for (unsigned int i = 0; i < value.size(); ++i) + { + if (value[i] == '1') + { + setBit(static_cast(i)); + } + } + } +} + +//----------------------------------------------------------------------------- +void MatchMakingId::packBitString(std::string &value) const +{ + // Build a binary string representation of the match making id + + value.reserve(static_cast(getBitCount())); + value.clear(); + + for (int i = 0; i < getBitCount(); ++i) + { + value.push_back(isBitSet(static_cast(i)) ? '1' : '0'); + } +} + +// Unpacks a series of ints +//----------------------------------------------------------------------------- +void MatchMakingId::unPackIntString(std::string const &value) +{ + Unicode::String unicodeValue(Unicode::narrowToWide(value)); + + Unicode::UnicodeStringVector result; + IGNORE_RETURN(Unicode::tokenize(unicodeValue, result)); + + unsigned int resultSize = result.size(); + + if (resultSize > 1) + { + unsigned int const intCount = Unicode::toInt(result[0]); + + if (intCount != static_cast(getBitCount() / 32)) + { + // Int count is wrong + + DEBUG_WARNING(true, ("Invalid MatchMakingId size during unpack (%d) expecting (%d)...aborting unpack", static_cast(intCount), getBitCount() / 32)); + + reset(); + } + else + { + // Int count looks good + + IntVector ints; + ints.reserve(intCount); + + for (unsigned int i = 1; i <= intCount; ++i) + { + ints.push_back(Unicode::toInt(result[i])); + } + + setBits(ints); + } + } +} + +// Packs all the bits into a series of ints to conserve string space +//----------------------------------------------------------------------------- +void MatchMakingId::packIntString(std::string &value) const +{ + IntVector ints(getInts()); + + std::string result; + + { + char text[256]; + + // Put the size of the vector + + sprintf(text, "%d ", ints.size()); + result += text; + + // Put each int value from the vector + + int const intsSize = static_cast(ints.size()); + + for (int i = 0; i < intsSize; ++i) + { + int const value = ints[static_cast(i)]; + + sprintf(text, "%d", value); + result += text; + + if (i < intsSize - 1) + { + result += " "; + } + } + } + + value = result; +} + +// ============================================================================ diff --git a/engine/shared/library/sharedGame/src/shared/object/MatchMakingId.h b/engine/shared/library/sharedGame/src/shared/object/MatchMakingId.h new file mode 100644 index 00000000..2bdb4eef --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/MatchMakingId.h @@ -0,0 +1,95 @@ +// ============================================================================ +// +// MatchMakingId.h +// Copyright Sony Online Entertainment +// +// ============================================================================ + +#ifndef INCLUDED_MatchMakingId_H +#define INCLUDED_MatchMakingId_H + +#include "Archive/AutoByteStream.h" +#include + +//----------------------------------------------------------------------------- +class MatchMakingId +{ +public: + + // Please do not change the numbers on these items, the data is saved in the + // database + + enum Bit + { + B_lookingForGroup = 0, + B_helper = 1, + B_rolePlay = 2, + B_faction = 3, + B_species = 4, + B_title = 5, + B_friend = 6, + B_awayFromKeyBoard = 7, + B_linkDead = 8, + B_displayingFactionRank = 9, + B_displayLocationInSearchResults = 10, + B_outOfCharacter = 11, // Out of Character for Roleplayers + B_searchableByCtsSourceGalaxy = 12, + B_lookingForWork = 13, + + B_maxLoadedBits = 126, // The max bits that can be loaded from a file + B_anonymous = 127 + }; + + typedef stdvector::fwd IntVector; + + MatchMakingId(); + + void setBit(Bit const bit); // set to 1 + void setBits(IntVector const &ints); + + void toggleBit(Bit const bit); // set to 1 + + void resetBit(Bit const bit); // set to 0 + void reset(); // set all bits to 0 + + bool isBitSet(Bit const bit) const; // is a bit 1 + + int getSetBitCount() const; // number of bits set to 1 + int getBitCount() const; + + IntVector getInts() const; + float getMatchPercent(MatchMakingId const &id) const; + +#ifdef _DEBUG + std::string getDebugIntString() const; +#endif // _DEBUG + + void unPackBitString(std::string const &value); + void packBitString(std::string &value) const; + + void unPackIntString(std::string const &value); + void packIntString(std::string &value) const; + + bool operator ==(MatchMakingId const &rhs) const; + bool operator !=(MatchMakingId const &rhs) const; + MatchMakingId &operator =(MatchMakingId const &rhs); + +private: + +#ifndef _DEBUG + std::string getDebugIntString() const; +#endif // _DEBUG + + std::bitset<128> m_id; +}; + +//----------------------------------------------------------------------------- +namespace Archive +{ + void get(ReadIterator &source, MatchMakingId &target); + void put(ByteStream &target, const MatchMakingId &source); +} + +// ============================================================================ + +#endif // INCLUDED_MatchMakingId_H diff --git a/engine/shared/library/sharedGame/src/shared/object/NoBuildNotification.cpp b/engine/shared/library/sharedGame/src/shared/object/NoBuildNotification.cpp new file mode 100644 index 00000000..de786f31 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/NoBuildNotification.cpp @@ -0,0 +1,85 @@ +//=================================================================== +// +// NoBuildNotification.cpp +// asommers +// +// copyright 2001, sony online entertainment +// +//=================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/NoBuildNotification.h" + +#include "sharedObject/LotManager.h" +#include "sharedObject/Object.h" +#include "sharedObject/World.h" + +//=================================================================== +// PUBLIC NoBuildNotification +//=================================================================== + +NoBuildNotification::NoBuildNotification () : + ObjectNotification () +{ +} + +//------------------------------------------------------------------- + +NoBuildNotification::~NoBuildNotification () +{ +} + +//------------------------------------------------------------------- + +void NoBuildNotification::removeFromWorld (Object& object) const +{ + LotManager* const lotManager = World::getLotManager (); + NOT_NULL (lotManager); + + lotManager->removeNoBuildEntry (object); +} + +//------------------------------------------------------------------- + +bool NoBuildNotification::positionChanged (Object& object, bool /*dueToParentChange*/, const Vector& /*oldPosition*/) const +{ + rotationChanged (object, false); + + return true; +} + +//------------------------------------------------------------------- + +void NoBuildNotification::rotationChanged (Object& object, bool /*dueToParentChange*/) const +{ + if (object.isInWorld ()) + { + removeFromWorld (object); + addToWorld (object); + } +} + +//------------------------------------------------------------------- + +bool NoBuildNotification::positionAndRotationChanged (Object& object, bool /*dueToParentChange*/, const Vector& /*oldPosition*/) const +{ + rotationChanged (object, false); + + return true; +} + +//=================================================================== +// PROTECTED NoBuildNotification +//=================================================================== + +void NoBuildNotification::addToWorld (Object& object, const float noBuildRadius) const +{ + LotManager* const lotManager = World::getLotManager (); + NOT_NULL (lotManager); + + lotManager->addNoBuildEntry (object, noBuildRadius); +} + +//=================================================================== + + diff --git a/engine/shared/library/sharedGame/src/shared/object/NoBuildNotification.h b/engine/shared/library/sharedGame/src/shared/object/NoBuildNotification.h new file mode 100644 index 00000000..70404454 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/NoBuildNotification.h @@ -0,0 +1,47 @@ +//=================================================================== +// +// NoBuildNotification.h +// asommers +// +// copyright 2001, sony online entertainment +// +//=================================================================== + +#ifndef INCLUDED_NoBuildNotification_H +#define INCLUDED_NoBuildNotification_H + +//=================================================================== + +#include "sharedObject/ObjectNotification.h" + +class StructureFootprint; + +//=================================================================== + +class NoBuildNotification : public ObjectNotification +{ +public: + + NoBuildNotification (); + virtual ~NoBuildNotification (); + + virtual void addToWorld (Object& object) const=0; + virtual void removeFromWorld (Object& object) const; + + virtual bool positionChanged (Object& object, bool dueToParentChange, const Vector& oldPosition) const; + virtual void rotationChanged (Object& object, bool dueToParentChange) const; + virtual bool positionAndRotationChanged (Object& object, bool dueToParentChange, const Vector& oldPosition) const; + +protected: + + void addToWorld (Object& object, float noBuildRadius) const; + +protected: + + NoBuildNotification (const NoBuildNotification&); + NoBuildNotification& operator= (const NoBuildNotification&); +}; + +//=================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/object/ObjectUsabilityManager.cpp b/engine/shared/library/sharedGame/src/shared/object/ObjectUsabilityManager.cpp new file mode 100644 index 00000000..c884aed1 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/ObjectUsabilityManager.cpp @@ -0,0 +1,205 @@ +// ====================================================================== +// +// ObjectUsabilityManager.cpp +// Copyright Sony Online Entertainment, Inc. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ObjectUsabilityManager.h" + +// ====================================================================== + +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/Iff.h" +#include "sharedFoundation/PersistentCrcString.h" +#include "sharedFoundation/TemporaryCrcString.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedUtility/DataTable.h" + +#include +#include +#include +#include + +// ---------------------------------------------------------------------- + +namespace ObjectUsabilityManagerNamespace +{ + bool ms_installed = false; + + // + const std::string s_sharedPrefix("shared_"); + + // + typedef std::set WearableObjectPermissionSet; + WearableObjectPermissionSet s_wearableCrcSet; // can you wear an item? + + std::set s_isWearableCrcSet; + + // + struct SpecieGenderColumnInformation + { + SpecieGenderColumnInformation() : + m_species(0), + m_gender(0) + { + } + + SpecieGenderColumnInformation(SharedCreatureObjectTemplate::Species const species, SharedCreatureObjectTemplate::Gender const gender) : + m_species(static_cast(species)), + m_gender(static_cast(gender)) + { + } + + uint16 m_species; + uint16 m_gender; + + uint32 getKeyValue() const + { + uint32 const keyUpper = static_cast(m_species) << 16; + uint32 const keyLower = static_cast(m_gender); + return keyUpper | keyLower; + } + }; + + // + typedef std::map SpeciesGenderMap; + SpeciesGenderMap s_speciesGenderMap; +} + +using namespace ObjectUsabilityManagerNamespace; + +// ---------------------------------------------------------------------- + +void ObjectUsabilityManager::install() +{ + InstallTimer const installTimer("ObjectUsabilityManager::install"); + + DEBUG_FATAL(ms_installed, ("ObjectUsabilityManagerNamespace::install: already installed")); + ms_installed = true; + + ExitChain::add(ObjectUsabilityManager::remove, "ObjectUsabilityManagerNamespace::remove"); + + //-- Appearance info + { + char const * const appearanceInfoFileName = "datatables/appearance/appearance_info_table.iff"; + Iff iffInfo; + if (iffInfo.open(appearanceInfoFileName, true)) + { + DataTable appearanceInfoDataTable; + appearanceInfoDataTable.load(iffInfo); + + int const numberOfRows = appearanceInfoDataTable.getNumRows(); + + for (int row = 0; row < numberOfRows; ++row) + { + // Read the template name crc. + std::string const & speciesName = appearanceInfoDataTable.getStringValue(0, row); + TemporaryCrcString const tmpCrcSpeciesName(speciesName.c_str(), true); + uint32 const crcSpeciesName = tmpCrcSpeciesName.getCrc(); + + // Get the species value. + SharedCreatureObjectTemplate::Species const species = static_cast(appearanceInfoDataTable.getIntValue(1, row)); + + // Get the gender value. + SharedCreatureObjectTemplate::Gender const gender = static_cast(appearanceInfoDataTable.getIntValue(2, row)); + + s_speciesGenderMap[crcSpeciesName] = SpecieGenderColumnInformation(species, gender); + } + } + else + { + WARNING(true, ("ObjectUsabilityManager table missing [%s]", appearanceInfoFileName)); + return; + } + } + + //-- Appearance table + { + char const * const appearanceTableFileName = "datatables/appearance/appearance_table.iff"; + Iff iffAppearance; + if (iffAppearance.open(appearanceTableFileName, true)) + { + DataTable appearanceDataTable; + appearanceDataTable.load(iffAppearance); + + int const numberOfColumns = appearanceDataTable.getNumColumns(); + int const numberOfRows = appearanceDataTable.getNumRows(); + + for (int row = 0; row < numberOfRows; ++row) + { + // Read the template name crc. + std::string const & sourceName = appearanceDataTable.getStringValue(0, row); + TemporaryCrcString const crcSourceName(sourceName.c_str(), true); + uint32 const crcValue = crcSourceName.getCrc(); + uint64 const keyValue = static_cast(crcValue) << static_cast(32); + + IGNORE_RETURN(s_isWearableCrcSet.insert(crcValue)); + + // Read the species info. + for (int column = 1; column < numberOfColumns; ++column) + { + std::string const & speciesName = appearanceDataTable.getColumnName(column); + TemporaryCrcString const tmpCrcSpeciesName(speciesName.c_str(), true); + uint32 const crcSpeciesName = tmpCrcSpeciesName.getCrc(); + + std::string const & fileName = appearanceDataTable.getStringValue(column, row); + if (fileName != ":block") // :block means "you can't use this item" in the appearance.tab + { + { + SpeciesGenderMap::iterator const it = s_speciesGenderMap.find(crcSpeciesName); + DEBUG_FATAL(it == s_speciesGenderMap.end(), ("ObjectUsabilityManager::install() species (%s) in appearance_table does not have a appearance_info.iff entry.", speciesName.c_str())); + UNREF(it); + } + + SpecieGenderColumnInformation const & speciesInfo = s_speciesGenderMap[crcSpeciesName]; + IGNORE_RETURN(s_wearableCrcSet.insert(keyValue | speciesInfo.getKeyValue())); + } + } + } + } + else + WARNING(true, ("ObjectUsabilityManager table missing [%s]", appearanceTableFileName)); + + } +} + +// ---------------------------------------------------------------------- + +void ObjectUsabilityManager::remove() +{ + DEBUG_FATAL(!ms_installed, ("ObjectUsabilityManagerNamespace::remove: not installed")); + ms_installed = false; + + s_wearableCrcSet.clear(); + s_isWearableCrcSet.clear(); + s_speciesGenderMap.clear(); +} + +// ---------------------------------------------------------------------- + +bool ObjectUsabilityManager::canWear(uint32 const wearableSharedTemplateCrc, SharedCreatureObjectTemplate::Species const species, SharedCreatureObjectTemplate::Gender const gender) +{ + SpecieGenderColumnInformation const info(species, gender); + uint64 const wearableKeyValue = static_cast(wearableSharedTemplateCrc) << static_cast(32); + uint64 const keyValue = wearableKeyValue | info.getKeyValue(); + return s_wearableCrcSet.find(keyValue) != s_wearableCrcSet.end(); +} + +// ---------------------------------------------------------------------- + +bool ObjectUsabilityManager::canWear(uint32 const wearableSharedTemplateCrc, int const species, int const gender) +{ + return canWear(wearableSharedTemplateCrc, static_cast(species), static_cast(gender)); +} + +// ---------------------------------------------------------------------- + +bool ObjectUsabilityManager::isWearable(uint32 const wearableSharedTemplateCrc) +{ + return s_isWearableCrcSet.find(wearableSharedTemplateCrc) != s_isWearableCrcSet.end(); +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/object/ObjectUsabilityManager.h b/engine/shared/library/sharedGame/src/shared/object/ObjectUsabilityManager.h new file mode 100644 index 00000000..2de65d0f --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/ObjectUsabilityManager.h @@ -0,0 +1,38 @@ +// ============================================================================ +// +// ObjectUsabilityManager.h +// Copyright Sony Online Entertainment, Inc. +// +// ============================================================================ + +#ifndef INCLUDED_ObjectUsabilityManager_H +#define INCLUDED_ObjectUsabilityManager_H + +// ============================================================================ + +#include "sharedGame/SharedCreatureObjectTemplate.h" + +// ============================================================================ + +class CrcString; + +//----------------------------------------------------------------------------- + +class ObjectUsabilityManager +{ +public: + + static void install(); + + static bool isWearable(uint32 const wearableSharedTemplateCrc); + static bool canWear(uint32 const wearableSharedTemplateCrc, SharedCreatureObjectTemplate::Species const species, SharedCreatureObjectTemplate::Gender const gender); + static bool canWear(uint32 const wearableSharedTemplateCrc, int const species, int const gender); + +private: + + static void remove(); +}; + +// ============================================================================ + +#endif // INCLUDED_ObjectUsabilityManager_H diff --git a/engine/shared/library/sharedGame/src/shared/object/ResourceClassObject.cpp b/engine/shared/library/sharedGame/src/shared/object/ResourceClassObject.cpp new file mode 100644 index 00000000..37be318d --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/ResourceClassObject.cpp @@ -0,0 +1,531 @@ +//======================================================================== +// +// ResourceClassObject.cpp +// +// copyright 2002 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ResourceClassObject.h" + +#include "UnicodeUtils.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedFoundation/DynamicVariableList.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedGame/Universe.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" + +#include +#include + + +// ====================================================================== + +std::string *ResourceClassObject::ms_attNameHeader = 0; +std::string *ResourceClassObject::ms_attMaxHeader = 0; +std::string *ResourceClassObject::ms_attMinHeader = 0; + +namespace ResourceClassObjectNamespace +{ + std::string ms_resourceNameStringFile = "resource/resource_names"; + std::set ms_classesExcludedFromCommodities; +} + +using namespace ResourceClassObjectNamespace; + +// ====================================================================== + +ResourceClassObject::ResourceClassObject() : + m_resourceClassName(), + m_parentClass(NULL), + m_friendlyName(NULL), + m_minTypes(0), + m_maxTypes(0), + m_minPools(0), + m_maxPools(0), + m_crateTemplate(), + m_nameTable(), + m_recycled(false), + m_permanent(false), + m_recycledVersion(NULL), + m_resourceAttributeRanges(new ResourceAttributeRangesType()), + m_children(new ClassList) +{ +} + +//----------------------------------------------------------------------- + +ResourceClassObject::~ResourceClassObject() +{ + delete m_children; + m_children = NULL; + + delete m_resourceAttributeRanges; + m_resourceAttributeRanges = NULL; + + m_parentClass = NULL; + m_recycledVersion = NULL; + + if (m_friendlyName != NULL) + { + delete m_friendlyName; + m_friendlyName = NULL; + } +} + +// ---------------------------------------------------------------------- + +void ResourceClassObject::install() +{ + ExitChain::add(&remove, "ResourceClassObject::remove"); + + ms_attNameHeader = new std::string[11]; + ms_attNameHeader[0]="Attribute 1"; + ms_attNameHeader[1]="Attribute 2"; + ms_attNameHeader[2]="Attribute 3"; + ms_attNameHeader[3]="Attribute 4"; + ms_attNameHeader[4]="Attribute 5"; + ms_attNameHeader[5]="Attribute 6"; + ms_attNameHeader[6]="Attribute 7"; + ms_attNameHeader[7]="Attribute 8"; + ms_attNameHeader[8]="Attribute 9"; + ms_attNameHeader[9]="Attribute 10"; + ms_attNameHeader[10]="Attribute 11"; + + ms_attMaxHeader = new std::string[11]; + ms_attMaxHeader[0]="Att 1 max"; + ms_attMaxHeader[1]="Att 2 max"; + ms_attMaxHeader[2]="Att 3 max"; + ms_attMaxHeader[3]="Att 4 max"; + ms_attMaxHeader[4]="Att 5 max"; + ms_attMaxHeader[5]="Att 6 max"; + ms_attMaxHeader[6]="Att 7 max"; + ms_attMaxHeader[7]="Att 8 max"; + ms_attMaxHeader[8]="Att 9 max"; + ms_attMaxHeader[9]="Att 10 max"; + ms_attMaxHeader[10]="Att 11 max"; + + ms_attMinHeader = new std::string[11]; + ms_attMinHeader[0]="Att 1 min"; + ms_attMinHeader[1]="Att 2 min"; + ms_attMinHeader[2]="Att 3 min"; + ms_attMinHeader[3]="Att 4 min"; + ms_attMinHeader[4]="Att 5 min"; + ms_attMinHeader[5]="Att 6 min"; + ms_attMinHeader[6]="Att 7 min"; + ms_attMinHeader[7]="Att 8 min"; + ms_attMinHeader[8]="Att 9 min"; + ms_attMinHeader[9]="Att 10 min"; + ms_attMinHeader[10]="Att 11 min"; +} + +// ---------------------------------------------------------------------- + +void ResourceClassObject::remove() +{ + delete[] ms_attMaxHeader; + delete[] ms_attMinHeader; + delete[] ms_attNameHeader; + ms_attMaxHeader = 0; + ms_attMinHeader = 0; + ms_attNameHeader = 0; +} + +// ---------------------------------------------------------------------- + +/** + * Build a string out of the ResourceClass tree, for debugging. + */ +void ResourceClassObject::debugOutput(std::string &output, int numSpaces) const +{ + for (int i=0; ibegin(); j!=m_children->end(); ++j) + { + (*j)->debugOutput(output,numSpaces+1); + } +} + +// ---------------------------------------------------------------------- + +void ResourceClassObject::setupUniverse() +{ + Universe::getInstance().registerResourceClassObject(*this); + ResourceClassObject *parent = getParent(); + if (parent) + parent->addChildClass(*this); +} + +// ---------------------------------------------------------------------- + +void ResourceClassObject::addChildClass(ResourceClassObject &child) +{ + m_children->push_back(&child); +} //lint !e1764 // child needs to be non-const because the vector holds non-const pointers + +// ---------------------------------------------------------------------- + +/** + * Return true if this class is derived from (or is equal to) the class + * specfied. + */ + +bool ResourceClassObject::isDerivedFrom(const ResourceClassObject &masterClass) const +{ + if (this == &masterClass) + return true; + else + { + const ResourceClassObject *parentClass = getParent(); + if (parentClass) + return parentClass->isDerivedFrom(masterClass); + else + return false; + } +} + +// ---------------------------------------------------------------------- + +/** + * Return the template of the kind of crate that can hold this resource. + */ +void ResourceClassObject::getCrateTemplate(std::string &buffer) const +{ + if (m_crateTemplate.length() > 0) + buffer=m_crateTemplate; + else + { + const ResourceClassObject *parentClass = getParent(); + if (parentClass) + parentClass->getCrateTemplate(buffer); + else + buffer=getDefaultResourceCrate(); + } +} + +// ---------------------------------------------------------------------- + +/** + * Get the name of the table to use when generating names for ResourceTypes + * derived from this class. + */ + +void ResourceClassObject::getNameTable(std::string &buffer) const +{ + if (m_nameTable.length() > 0) + buffer=m_nameTable; + else + { + ResourceClassObject *parentClass = getParent(); + if (parentClass) + parentClass->getNameTable(buffer); + else + buffer=getDefaultResourceNameTable(); + } +} + +// ---------------------------------------------------------------------- + +/** + * Get the name of the table to use when generating names for ResourceTypes + * derived from this class. + */ +std::string ResourceClassObject::getNameTable() const +{ + std::string buffer; + getNameTable(buffer); + return buffer; +} + +// ---------------------------------------------------------------------- + +ResourceClassObject::ResourceAttributeRangesType const & ResourceClassObject::getResourceAttributeRanges() const +{ +static const ResourceAttributeRangesType emptyRanges; + + if (m_resourceAttributeRanges != NULL) + return *m_resourceAttributeRanges; + return emptyRanges; +} + +// ---------------------------------------------------------------------- + +void ResourceClassObject::setAttributesFromDataTable(DataTable &table, int row) +{ + for (int attNumber = 0; attNumber < 11; ++attNumber) + { + const std::string &attName = table.getStringValue (ms_attNameHeader[attNumber],row); + if (attName.size() > 0) + { + IGNORE_RETURN(m_resourceAttributeRanges->insert( + std::make_pair(attName, + std::make_pair(table.getIntValue(ms_attMinHeader[attNumber],row), + table.getIntValue(ms_attMaxHeader[attNumber],row))))); + } + } +} + +// ---------------------------------------------------------------------- + +/** + * Parse the resource spreadsheet and build ResourceClassObjects from it. + * The spreadsheet is formatted to be easy for a human to edit, so it + * is a little awkward to parse in C++. + */ + +void ResourceClassObject::loadTreeFromIff() +{ + DataTable * resourceDataTable = DataTableManager::getTable("datatables/resource/resource_tree.iff", true); + if (resourceDataTable) + { + // These strings are easier to hard-code than to snprintf + std::string classHeader[8]; + classHeader[0]= "CLASS 1"; + classHeader[1]= "CLASS 2"; + classHeader[2]= "CLASS 3"; + classHeader[3]= "CLASS 4"; + classHeader[4]= "CLASS 5"; + classHeader[5]= "CLASS 6"; + classHeader[6]= "CLASS 7"; + classHeader[7]= "CLASS 8"; + + std::map resourceClasses; + int numRows = resourceDataTable->getNumRows(); + ResourceClassObject * parents[8]; + for (int i=0; i<8; ++i) + parents[i]=NULL; + + static const std::string colName_resourceClassName = "ENUM"; + static const std::string colName_maxTypes = "Maximum # types"; + static const std::string colName_minTypes = "Minimum # types"; + static const std::string colName_maxPools = "Maximum # Pools"; + static const std::string colName_minPools = "Minimum # Pools"; + static const std::string colName_crateTemplate = "Resource Container Type"; + static const std::string colName_nameTable = "Random Name Class"; + static const std::string colName_index = "INDEX"; + static const std::string colName_recycled = "Recycled"; + static const std::string colName_permanent = "Permanent"; + + for (int row=0; rowgetIntValue(colName_index,row)<=0) + { + DEBUG_WARNING(true,("Designer bug: Resource data table has a suspicious row %i (the value in the index column is missing or wrong)",row)); + } + else + { + ResourceClassObject *newClass = Universe::getInstance().makeResourceClassObject(); + + // in the spreadsheet, the name is indented to indicate what derives from what + for (int wheresTheName=0; wheresTheName < 8; ++wheresTheName) + { + const std::string &possibleName = resourceDataTable->getStringValue(classHeader[wheresTheName],row); + if (possibleName.size()!=0) + { + if (wheresTheName==0) + newClass->m_parentClass = NULL; + else + { + newClass->m_parentClass = parents[wheresTheName-1]; + DEBUG_FATAL(!newClass->m_parentClass,("Can't determine parent class for ResourceClass %s. Probably a problem in the resource data table\n", + possibleName.c_str())); + } + parents[wheresTheName]=newClass; + break; + } + } + + newClass->m_resourceClassName = resourceDataTable->getStringValue (colName_resourceClassName, row); + newClass->m_friendlyName = new StringId(ms_resourceNameStringFile, newClass->m_resourceClassName); + newClass->m_maxTypes = resourceDataTable->getIntValue (colName_maxTypes, row); + newClass->m_minTypes = resourceDataTable->getIntValue (colName_minTypes, row); + newClass->m_maxPools = resourceDataTable->getIntValue (colName_maxPools, row); + newClass->m_minPools = resourceDataTable->getIntValue (colName_minPools, row); + newClass->m_crateTemplate = resourceDataTable->getStringValue (colName_crateTemplate, row); + newClass->m_nameTable = resourceDataTable->getStringValue (colName_nameTable, row); + newClass->m_recycled = (resourceDataTable->getIntValue (colName_recycled, row) != 0); + newClass->m_permanent = (resourceDataTable->getIntValue (colName_permanent, row) != 0); + + newClass->setupUniverse(); + + newClass->setAttributesFromDataTable(*resourceDataTable, row); + + if (newClass->m_recycled) + { + newClass->m_parentClass->m_recycledVersion = newClass; + } + + resourceClasses[resourceDataTable->getIntValue(colName_index,row)]=newClass; // used to match up with fractal parameters + } + } + + Universe::getInstance().resourceClassTreeLoaded(resourceClasses); + } // if (resourceDataTable) + else + DEBUG_WARNING(true,("Unable to open resource data table.\n")); + + DataTableManager::close("datatables/resource/resource_tree.iff"); + + // read in the list of resource classes that are excluded from the commodities system + DataTable * resourceClassExclusionDataTable = DataTableManager::getTable("datatables/commodity/resource_class_exclusion.iff", true); + if (resourceClassExclusionDataTable) + { + int const classColumn = resourceClassExclusionDataTable->findColumnNumber("class"); + if (classColumn < 0) + { + DEBUG_WARNING(true, ("Could not find column \"class\" in resource commodities exclusion data table datatables/commodity/resource_class_exclusion.iff.\n")); + } + else + { + unsigned int const numRows = static_cast(resourceClassExclusionDataTable->getNumRows()); + if (numRows == 0) + { + DEBUG_WARNING(true, ("Resource commodities exclusion data table datatables/commodity/resource_class_exclusion.iff is empty.\n")); + } + else + { + std::string className; + for (unsigned int i = 0; i < numRows; ++i) + { + className = resourceClassExclusionDataTable->getStringValue(classColumn, i); + if (Universe::getInstance().getResourceClassByName(className)) + IGNORE_RETURN(ms_classesExcludedFromCommodities.insert(className)); + else + DEBUG_WARNING(true, ("Resource commodities exclusion data table datatables/commodity/resource_class_exclusion.iff contains invalid resource class name (%s).\n", className.c_str())); + } + } + } + } + else + { + DEBUG_WARNING(true,("Unable to open resource commodities exclusion data table datatables/commodity/resource_class_exclusion.iff.\n")); + } + + DataTableManager::close("datatables/commodity/resource_class_exclusion.iff"); +} + +// ---------------------------------------------------------------------- + +const std::string &ResourceClassObject::getDefaultResourceCrate() const +{ + static std::string nothing; + return nothing; +} + +// ---------------------------------------------------------------------- + +const std::string &ResourceClassObject::getDefaultResourceNameTable() const +{ + static std::string nothing; + return nothing; +} + +// ---------------------------------------------------------------------- + +bool ResourceClassObject::isLeaf() const +{ + return m_children->empty(); +} + +//---------------------------------------------------------------------- + +void ResourceClassObject::getChildren(std::vector & children, bool recurse) const +{ + if (m_children == NULL) + return; + + for (ClassList::const_iterator i = m_children->begin(); i != m_children->end(); ++i) + { + if (*i != NULL) + { + children.push_back(*i); + if (recurse) + (*i)->getChildren(children, recurse); + } + } +} + +//---------------------------------------------------------------------- + +void ResourceClassObject::getLeafChildren(std::vector & children) const +{ + if (m_children == NULL) + return; + + for (ClassList::const_iterator i = m_children->begin(); i != m_children->end(); ++i) + { + if (*i != NULL) + { + if ((*i)->isLeaf()) + children.push_back(*i); + else + (*i)->getLeafChildren(children); + } + } +} + +// ---------------------------------------------------------------------- + +int ResourceClassObject::getMinPools() const +{ + return m_minPools; +} + +// ---------------------------------------------------------------------- + +int ResourceClassObject::getMaxPools() const +{ + return m_maxPools; +} + +// ---------------------------------------------------------------------- + +ResourceClassObject const * ResourceClassObject::getRecycledVersion() const +{ + if (m_recycledVersion) + return m_recycledVersion; + else if (m_parentClass) + return m_parentClass->getRecycledVersion(); + else return NULL; +} + +// ---------------------------------------------------------------------- + +bool ResourceClassObject::isRecycled() const +{ + return m_recycled; +} + +//---------------------------------------------------------------------- + +bool ResourceClassObject::isPermanent() const +{ + return m_permanent; +} + +//---------------------------------------------------------------------- + +bool ResourceClassObject::isClassExcludedFromCommodities(std::string const & className) +{ + return (ms_classesExcludedFromCommodities.count(className) > 0); +} + +//---------------------------------------------------------------------- + +std::set const & ResourceClassObject::getClassesExcludedFromCommodities() +{ + return ms_classesExcludedFromCommodities; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/object/ResourceClassObject.h b/engine/shared/library/sharedGame/src/shared/object/ResourceClassObject.h new file mode 100644 index 00000000..16de81e8 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/ResourceClassObject.h @@ -0,0 +1,147 @@ +//======================================================================== +// +// ResourceClassObject.h +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef INCLUDED_ResourceClassObject_H +#define INCLUDED_ResourceClassObject_H + +class DataTable; +class StringId; + +// ====================================================================== + +/** +* Represents a resource class, i.e. a non-leaf node in the resource +* tree. The resource class hierarchy is static at runtime, and is read +* in from a datatable. +*/ + +class ResourceClassObject +{ +public: + typedef stdmap >::fwd ResourceAttributeRangesType; + +public: + ResourceClassObject(); + virtual ~ResourceClassObject(); + + static void install(); + static void remove(); + static bool isClassExcludedFromCommodities(std::string const & className); + static stdset::fwd const & getClassesExcludedFromCommodities(); + +public: + // getter functions + virtual void debugOutput (std::string &output, int numSpaces=0) const; + bool isRoot () const; + bool isLeaf () const; + const std::string & getResourceClassName () const; + const StringId & getFriendlyName () const; + ResourceClassObject * getParent () const; + ResourceClassObject const * getRecycledVersion() const; + void getNameTable (std::string &buffer) const; + std::string getNameTable () const; + bool isDerivedFrom (const ResourceClassObject &masterClass) const; + void getCrateTemplate (std::string &buffer) const; + int getMinTypes () const; + int getMaxTypes () const; + void getChildren (stdvector::fwd & children, bool recurse) const; + void getLeafChildren (stdvector::fwd & children) const; + int getMinPools () const; + int getMaxPools () const; + bool isRecycled () const; + bool isPermanent() const; + + ResourceAttributeRangesType const & getResourceAttributeRanges() const; + +public: + // Universe system functions (rebuild data structures on load) + virtual void setupUniverse (); + void addChildClass (ResourceClassObject &child); + +public: + static void loadTreeFromIff(); + +protected: + std::string m_resourceClassName; ///< The (abbreviated) name of the resource class. + ResourceClassObject * m_parentClass; + StringId * m_friendlyName; ///< The string id of the printable name for this resource class + int m_minTypes; ///< The minimum number of non-depleted types that should be derived from this class or its children. Used to decide when to spawn a new type + int m_maxTypes; ///< The maximum number of non-depleted types that should be derived from this class or its children. Used to decide when a new type must be spawned elsewhere in the tree + int m_minPools; + int m_maxPools; + std::string m_crateTemplate; ///< The kind of crate to use for this class + std::string m_nameTable; ///< The name table to use when generating names for ResourceTypes derived from class + bool m_recycled; ///< The resource is designated as "recycled" (influences how it is spawned and used) + bool m_permanent; ///< resource never expires + ResourceClassObject * m_recycledVersion; ///< Pointer to the class representing the recycled version of this resource + ResourceAttributeRangesType * m_resourceAttributeRanges; + +protected: + typedef stdvector::fwd ClassList; + ClassList * m_children; + +private: + virtual const std::string & getDefaultResourceCrate () const; + virtual const std::string & getDefaultResourceNameTable () const; + void setAttributesFromDataTable (DataTable &table, int row); + +private: + ResourceClassObject(const ResourceClassObject& rhs); + ResourceClassObject& operator=(const ResourceClassObject& rhs); + +private: + static std::string *ms_attNameHeader; + static std::string *ms_attMaxHeader; + static std::string *ms_attMinHeader; +}; + +// ---------------------------------------------------------------------- + +inline const std::string & ResourceClassObject::getResourceClassName () const +{ + return m_resourceClassName; +} + +// ---------------------------------------------------------------------- + +inline const StringId & ResourceClassObject::getFriendlyName () const +{ + return *NON_NULL(m_friendlyName); +} + +// ---------------------------------------------------------------------- + +inline bool ResourceClassObject::isRoot() const +{ + return (m_parentClass == NULL); +} + +// ---------------------------------------------------------------------- + +inline ResourceClassObject *ResourceClassObject::getParent() const +{ + return m_parentClass; +} + +// ---------------------------------------------------------------------- + +inline int ResourceClassObject::getMinTypes() const +{ + return m_minTypes; +} + +// ---------------------------------------------------------------------- + +inline int ResourceClassObject::getMaxTypes() const +{ + return m_maxTypes; +} + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/object/ShipObjectInterface.cpp b/engine/shared/library/sharedGame/src/shared/object/ShipObjectInterface.cpp new file mode 100644 index 00000000..6d83eaa7 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/ShipObjectInterface.cpp @@ -0,0 +1,27 @@ +// ====================================================================== +// +// ShipObjectInterface.cpp +// asommers +// +// copyright 2004, sony online entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipObjectInterface.h" + +// ====================================================================== +// PUBLIC ShipObjectInterface +// ====================================================================== + +ShipObjectInterface::ShipObjectInterface() +{ +} + +// ---------------------------------------------------------------------- + +ShipObjectInterface::~ShipObjectInterface() +{ +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/object/ShipObjectInterface.h b/engine/shared/library/sharedGame/src/shared/object/ShipObjectInterface.h new file mode 100644 index 00000000..05ef7e0c --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/ShipObjectInterface.h @@ -0,0 +1,38 @@ +// ====================================================================== +// +// ShipObjectInterface.h +// asommers +// +// copyright 2004, sony online entertainment +// +// ====================================================================== + +#ifndef INCLUDED_ShipObjectInterface_H +#define INCLUDED_ShipObjectInterface_H + +// ====================================================================== + +class ShipObjectInterface +{ +public: + + virtual float getMaximumSpeed() const = 0; + virtual float getSpeedAcceleration() const = 0; + virtual float getSpeedDeceleration() const = 0; + virtual float getSlideDampener() const = 0; + virtual float getMaximumYaw() const = 0; + virtual float getYawAcceleration() const = 0; + virtual float getMaximumPitch() const = 0; + virtual float getPitchAcceleration() const = 0; + virtual float getMaximumRoll() const = 0; + virtual float getRollAcceleration() const = 0; + +protected: + + ShipObjectInterface(); + virtual ~ShipObjectInterface() = 0; +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/object/SlopeEffectProperty.cpp b/engine/shared/library/sharedGame/src/shared/object/SlopeEffectProperty.cpp new file mode 100644 index 00000000..4c8b8f5d --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/SlopeEffectProperty.cpp @@ -0,0 +1,43 @@ +// ====================================================================== +// +// SlopeEffectProperty.cpp +// Copyright 2004 Sony Online Entertainment Inc. +// All Rights Reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SlopeEffectProperty.h" + + +// ====================================================================== + +PropertyId SlopeEffectProperty::getClassPropertyId() +{ +// PropertyId id = LabelHash::hashLabel( "Property", "SlopeEffect" ); +// return id; + return PROPERTY_HASH(SlopeEffect, 0xc8fd989a); +} + +// ====================================================================== + +SlopeEffectProperty::SlopeEffectProperty(Object& thisObject) : +Property(getClassPropertyId(), thisObject), +m_normals() +{ +} + +//------------------------------------------------------------------------- + +SlopeEffectProperty::~SlopeEffectProperty() +{ +} + +//------------------------------------------------------------------------- + +void SlopeEffectProperty::addNormal(const Vector & normal) +{ + m_normals.push_back(normal); +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/object/SlopeEffectProperty.h b/engine/shared/library/sharedGame/src/shared/object/SlopeEffectProperty.h new file mode 100644 index 00000000..4ba6df6d --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/SlopeEffectProperty.h @@ -0,0 +1,59 @@ +// ====================================================================== +// +// SlopeEffectProperty.h +// Copyright 2004 Sony Online Entertainment Inc. +// All Rights Reserved. +// +// ====================================================================== + +#ifndef INCLUDED_SlopeEffectProperty_H +#define INCLUDED_SlopeEffectProperty_H + +// ====================================================================== + +#include "sharedObject/Property.h" +#include "sharedMath/Vector.h" +#include + +// ====================================================================== + +/** + * This property is used to keep track of any induced slope effects that a creature has. + * A slope effect acts as an artificial "hill" that the creature is climbing. + */ +class SlopeEffectProperty : public Property +{ +public: + + static PropertyId getClassPropertyId(); + +public: + SlopeEffectProperty(Object& thisObject); + ~SlopeEffectProperty(); + + const std::vector & getNormals() const; + void addNormal(const Vector & normal); + +private: + std::vector m_normals; + +private: + SlopeEffectProperty(); + SlopeEffectProperty(const SlopeEffectProperty&); + SlopeEffectProperty& operator= (const SlopeEffectProperty&); +}; + + +// ====================================================================== + +inline const stdvector::fwd & SlopeEffectProperty::getNormals() const +{ + return m_normals; +} + + +// ====================================================================== + + +#endif + diff --git a/engine/shared/library/sharedGame/src/shared/object/SlowDownProperty.cpp b/engine/shared/library/sharedGame/src/shared/object/SlowDownProperty.cpp new file mode 100644 index 00000000..b08e1fd1 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/SlowDownProperty.cpp @@ -0,0 +1,41 @@ +// ====================================================================== +// +// SlowDownProperty.cpp +// Copyright 2004 Sony Online Entertainment Inc. +// All Rights Reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SlowDownProperty.h" + + +// ====================================================================== + +PropertyId SlowDownProperty::getClassPropertyId() +{ +// PropertyId id = LabelHash::hashLabel( "Property", "SlowDown" ); +// WARNING(true, ("PROPERTY SLOWDOWN HASH = %x", id)); +// return id; + return PROPERTY_HASH(SlowDown, 0x1faf8ccb); +} + +// ====================================================================== + +SlowDownProperty::SlowDownProperty(Object& thisObject, const CachedNetworkId & target, float coneLength, float coneAngle, float slopeAngle, unsigned long expireTime) : +Property(getClassPropertyId(), thisObject), +m_target(target), +m_coneLength(coneLength), +m_coneAngle(coneAngle), +m_slopeAngle(slopeAngle), +m_expireTime(expireTime) +{ +} + +//------------------------------------------------------------------------- + +SlowDownProperty::~SlowDownProperty() +{ +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/object/SlowDownProperty.h b/engine/shared/library/sharedGame/src/shared/object/SlowDownProperty.h new file mode 100644 index 00000000..aafe3ae3 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/SlowDownProperty.h @@ -0,0 +1,86 @@ +// ====================================================================== +// +// SlowDownProperty.h +// Copyright 2004 Sony Online Entertainment Inc. +// All Rights Reserved. +// +// ====================================================================== + +#ifndef INCLUDED_SlowDownProperty_H +#define INCLUDED_SlowDownProperty_H + +// ====================================================================== + +#include "sharedObject/CachedNetworkId.h" +#include "sharedObject/Property.h" + + +// ====================================================================== + +/** + * This property is used to keep track of data needed by a creature doing + * a slow down effect. + */ +class SlowDownProperty : public Property +{ +public: + + static PropertyId getClassPropertyId(); + +public: + SlowDownProperty(Object& thisObject, const CachedNetworkId & target, float coneLength, float coneAngle, float slopeAngle, unsigned long expireTime); + ~SlowDownProperty(); + + const CachedNetworkId & getTarget() const; + float getConeLength() const; + float getConeAngle() const; + float getSlopeAngle() const; + unsigned long getExpireTime() const; + +private: + CachedNetworkId m_target; + float m_coneLength; + float m_coneAngle; + float m_slopeAngle; + unsigned long m_expireTime; + +private: + SlowDownProperty(); + SlowDownProperty(const SlowDownProperty&); + SlowDownProperty& operator= (const SlowDownProperty&); +}; + + +// ====================================================================== + +inline const CachedNetworkId & SlowDownProperty::getTarget() const +{ + return m_target; +} + +inline float SlowDownProperty::getConeLength() const +{ + return m_coneLength; +} + +inline float SlowDownProperty::getConeAngle() const +{ + return m_coneAngle; +} + +inline float SlowDownProperty::getSlopeAngle() const +{ + return m_slopeAngle; +} + +inline unsigned long SlowDownProperty::getExpireTime() const +{ + return m_expireTime; +} + + +// ====================================================================== + + +#endif + diff --git a/engine/shared/library/sharedGame/src/shared/object/VehicleHoverDynamics.cpp b/engine/shared/library/sharedGame/src/shared/object/VehicleHoverDynamics.cpp new file mode 100644 index 00000000..16c68c7d --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/VehicleHoverDynamics.cpp @@ -0,0 +1,668 @@ +//====================================================================== +// +// VehicleHoverDynamics.cpp +// copyright (c) 2003 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/VehicleHoverDynamics.h" + +#include "sharedDebug/DebugFlags.h" +#include "sharedGame/HoverPlaneHelper.h" +#include "sharedMath/AxialBox.h" +#include "sharedObject/AlterResult.h" +#include "sharedObject/RangedIntCustomizationVariable.h" +#include "sharedObject/CustomizationDataProperty.h" +#include "sharedObject/CustomizationData.h" +#include "sharedTerrain/TerrainObject.h" + +//====================================================================== + +namespace +{ + bool ms_useDamping = true; + bool ms_useFlattening = true; + bool ms_showDebugVehicleBoxes = false; + bool ms_useLookAhead = true; + bool ms_lockLookAhead = false; + bool ms_showCrumbs = false; + + const float ms_lookAheadTime = 0.5f; + + void customizationDataModifiedCallback (const CustomizationData &cd, const void *context) + { + reinterpret_cast(context)->onCustomizationDataModified (cd); + } + + //---------------------------------------------------------------------- + + class CdVariableData + { + public: + std::string path; + float conversionFactor; + + CdVariableData (const std::string & _path, float _conversionFactor) : + path (_path), + conversionFactor (_conversionFactor) + { + } + }; + + //---------------------------------------------------------------------- + + namespace CdVariables + { + const CdVariableData speedMin ("/private/index_speed_min", RECIP (10.0f)); + const CdVariableData speedMax ("/private/index_speed_max", RECIP (10.0f)); + const CdVariableData turnRateMin ("/private/index_turn_rate_min", RECIP (1.0f) * PI_OVER_180); // comes down in degrees, must convert to radians + const CdVariableData turnRateMax ("/private/index_turn_rate_max", RECIP (1.0f) * PI_OVER_180); // comes down in degrees, must convert to radians + const CdVariableData accelMin ("/private/index_accel_min", RECIP (10.0f)); + const CdVariableData accelMax ("/private/index_accel_max", RECIP (10.0f)); + const CdVariableData decel ("/private/index_decel", RECIP (10.0f)); + const CdVariableData slopeMod ("/private/index_slope_mod", RECIP (10.0f)); + const CdVariableData dampRoll ("/private/index_damp_roll", RECIP (10.0f)); + const CdVariableData dampPitch ("/private/index_damp_pitch", RECIP (10.0f)); + const CdVariableData dampHeight ("/private/index_damp_height", RECIP (10.0f)); + const CdVariableData glide ("/private/index_glide", RECIP (10.0f)); + const CdVariableData banking ("/private/index_banking", RECIP (1.0f) * PI_OVER_180); // comes down in degrees, must convert to radians + const CdVariableData hoverHeight ("/private/index_hover_height", RECIP (10.0f)); + const CdVariableData autoLevel ("/private/index_auto_level", RECIP (100.0f)); + const CdVariableData strafe ("/private/index_strafe", RECIP (1.0f)); + } + + //---------------------------------------------------------------------- + + class CdLookupData + { + public: + mutable float * val; + CdVariableData variableData; + + CdLookupData (float * _val, const CdVariableData & _variableData) : + val (_val), + variableData (_variableData) + { + } + }; + + //---------------------------------------------------------------------- +} + +//---------------------------------------------------------------------- + +VehicleHoverDynamics::VehicleHoverDynamics (Object* newOwner, float yaw, float hoverHeight) : +Dynamics (newOwner), +m_currentSpeed (0.0f), +m_speedMin (0.0f), +m_speedMax (0.0f), +m_turnRateMin (0.0f), +m_turnRateMax (0.0f), +m_accelMax (0.0f), +m_accelMin (0.0f), +m_canStrafe (false), +m_dampFactorRoll (2.0f), +m_dampFactorPitch (3.0f), +m_dampFactorGlide (4.0f), +m_glideFactorMoving (2.5f), +m_pitchFactorAccel (0.0f), +m_pitchFactorDecel (0.0f), +m_rollFactorTurn (PI_OVER_4), +m_targetRoll (0.0f), +m_targetPitch (0.0f), +m_roll (0.0f), +m_pitch (0.0f), +m_targetY_w (0.0f), +m_lastY_w (0.0f), +m_lastFrameK_w (), +m_hoverHeight (hoverHeight), +m_hoverHeightStopped (0.1f), +m_baseTransform_o2p (), +m_autoLevellingForce (0.50f), +m_lastTurnDeltaRoll (0.0f), +m_lastAccelDeltaPitch (0.0f), +m_customizationData (0), +m_hasAlteredCount (0), +m_customizationDataChanged (0), +m_turnRatePercentLastFrame (0.0f) +{ + Object * const parent = newOwner->getParent (); + if (parent) + { + CustomizationDataProperty * const cdprop = safe_cast(parent->getProperty (CustomizationDataProperty::getClassPropertyId())); + if (cdprop) + { + m_customizationData = cdprop->fetchCustomizationData (); + + if (m_customizationData) + m_customizationData->registerModificationListener (&customizationDataModifiedCallback, this); + } + } + + WARNING (!m_customizationData, ("VehicleHoverDynamics parent customization data not found, physics will be borked")); + + static bool installed = false; + if (!installed) + { + installed = true; + DebugFlags::registerFlag (ms_showDebugVehicleBoxes, "VehicleHoverDynamics", "debugBoxes"); + DebugFlags::registerFlag (ms_useLookAhead, "VehicleHoverDynamics", "lookAhead"); + DebugFlags::registerFlag (ms_lockLookAhead, "VehicleHoverDynamics", "lockLookAhead"); + DebugFlags::registerFlag (ms_useDamping, "VehicleHoverDynamics", "damping"); + DebugFlags::registerFlag (ms_useFlattening, "VehicleHoverDynamics", "flattening"); + DebugFlags::registerFlag (ms_showCrumbs, "VehicleHoverDynamics", "showCrumbs"); + } + + m_baseTransform_o2p = Transform::identity; + m_baseTransform_o2p.yaw_l (yaw); +} + +//---------------------------------------------------------------------- + +VehicleHoverDynamics::~VehicleHoverDynamics () +{ + if (m_customizationData) + { + m_customizationData->deregisterModificationListener (&customizationDataModifiedCallback, this); + m_customizationData->release (); + } +} + +//---------------------------------------------------------------------- + +float VehicleHoverDynamics::alter(float elapsedTime) +{ + if (elapsedTime <= 0.0f) + return AlterResult::cms_keepNoAlter; + + if (m_hasAlteredCount++ == 2) + m_customizationDataChanged = true; + + if (m_customizationDataChanged) + { + readParamsFromCustomizationData (); + } + + if (m_speedMax <= 0.0f || m_speedMax - m_speedMin <= 0.0f) + return AlterResult::cms_keepNoAlter; + + const Object * const motorObject = getOwner ()->getParent (); + Object * const vehicleObject = getOwner (); + const Vector & motorFrameK_w = motorObject->getObjectFrameK_w (); + + const float speedPercent = std::max(0.0f, std::min (1.0f, (m_currentSpeed - m_speedMin) / (m_speedMax - m_speedMin))); + + //-- speed glide factor + //-- 1.0 at motionless + //-- 0.1 at full speed + const float speedGlideFactor = 1.0f / (1.0f + (speedPercent * m_glideFactorMoving)); + + //-- change in heading increases roll/pitch/glide interpolation rates + const float frameKDot = motorFrameK_w.dot (m_lastFrameK_w); +// const float deltaHeading = ((1.0f - frameKDot) * 0.5f) * PI; //approximate angle to avoid calling acos() + const float deltaHeading = (frameKDot >= 1.0f) ? 0.0f : ((frameKDot <= -1.0f) ? PI : acos (frameKDot)); + const float turnRateLastFrame = deltaHeading / elapsedTime; + + const float maximumTurnRate = getTurnRateForSpeedRadians (m_currentSpeed); + m_turnRatePercentLastFrame = maximumTurnRate > 0.0f ? (turnRateLastFrame / maximumTurnRate) : 0.0f; + const float headingChangeFactor = 1.0f;// + m_turnRatePercentLastFrame; + + const float timeFactorRoll = std::min (1.0f, elapsedTime * m_dampFactorRoll * headingChangeFactor); + const float timeFactorPitchUp = std::min (1.0f, elapsedTime * m_dampFactorPitch * headingChangeFactor * 2.0f); + const float timeFactorPitchDown = std::min (1.0f, elapsedTime * m_dampFactorPitch * headingChangeFactor); + const float timeFactorGlide = std::min (1.0f, elapsedTime * m_dampFactorGlide * speedGlideFactor); + + //-- compute acceleration to pitch the vehicle appropriately + float accelDeltaPitch = 0.0f; + const float maximumAccel = getAccelForSpeed (m_currentSpeed); + if (maximumAccel > 0.0f) + { + const float accel = (m_currentSpeed - m_lastSpeed) / elapsedTime; + + if (accel != 0.0f) + { + const float accelPercent = std::min (1.0f, accel / maximumAccel); + + if (accel > 0.0f) + accelDeltaPitch = accelPercent * m_pitchFactorAccel * (1.0f - m_turnRatePercentLastFrame) * (1.0f - speedPercent); + else + accelDeltaPitch = -accelPercent * m_pitchFactorDecel * (1.0f - m_turnRatePercentLastFrame) * speedPercent; + } + } + + const float targetAccelDeltaPitch = accelDeltaPitch; + accelDeltaPitch = linearInterpolate (m_lastAccelDeltaPitch, accelDeltaPitch, std::min (1.0f, timeFactorPitchDown * 2.0f)); + m_lastAccelDeltaPitch = targetAccelDeltaPitch; + if (accelDeltaPitch > 0.0f && accelDeltaPitch > m_targetPitch) + m_targetPitch = std::max (-PI_OVER_2, std::min (PI_OVER_2, std::min (m_targetPitch + accelDeltaPitch, accelDeltaPitch))); + else if (accelDeltaPitch < 0.0f && accelDeltaPitch < m_targetPitch) + m_targetPitch = std::max (-PI_OVER_2, std::min (PI_OVER_2, std::max (m_targetPitch + accelDeltaPitch, accelDeltaPitch))); + + //-- compute turn rate to roll the vehicle appropriately + float turnDeltaRoll = 0.0f; + if (m_turnRatePercentLastFrame > 0.0f && maximumTurnRate > 0.0f) + { + const Vector frameKCross = motorFrameK_w.cross (m_lastFrameK_w); + turnDeltaRoll = m_turnRatePercentLastFrame * m_rollFactorTurn; + + //-- turning right + if (frameKCross.y < 0.0f) + { + m_turnRatePercentLastFrame = -m_turnRatePercentLastFrame; + turnDeltaRoll = -turnDeltaRoll; + } + + //-- banking is damped to 25% when not moving + turnDeltaRoll *= 0.25f + (speedPercent * 0.75f); + } + + const float targetTurnDeltaRoll = turnDeltaRoll; + turnDeltaRoll = linearInterpolate (m_lastTurnDeltaRoll, turnDeltaRoll, std::min (1.0f, timeFactorRoll * 2.0f)); + m_lastTurnDeltaRoll = targetTurnDeltaRoll; + m_targetRoll = std::max (-PI_OVER_2, std::min (PI_OVER_2, m_targetRoll + turnDeltaRoll)); + + m_distancePopupThisFrame = 0.0f; + + //-- interpolate the roll, pitch, and glide height + if (ms_useDamping) + { + m_roll = m_roll + (m_targetRoll - m_roll) * timeFactorRoll; + + if (m_targetPitch < m_pitch) + m_pitch = m_pitch + (m_targetPitch - m_pitch) * timeFactorPitchUp; + else + m_pitch = m_pitch + (m_targetPitch - m_pitch) * timeFactorPitchDown; + + //const float desiredHoverHeight = linearInterpolate (m_hoverHeightStopped, m_hoverHeight, speedPercent); + const float desiredHoverHeight = m_hoverHeight; + const float vehicle_y_w = m_lastY_w; + m_distancePopupThisFrame = m_targetY_w - vehicle_y_w; + float y = std::max (vehicle_y_w, m_targetY_w); + const float localTargetY = m_targetY_w + desiredHoverHeight; + y = y + (localTargetY - y) * timeFactorGlide; + vehicleObject->move_p (Vector::unitY * (y - vehicleObject->getPosition_w ().y)); + m_lastY_w = y; + } + + vehicleObject->resetRotateTranslate_o2p (); + vehicleObject->setTransform_o2p (m_baseTransform_o2p); + vehicleObject->move_p (Vector::unitY * (m_lastY_w - vehicleObject->getPosition_w ().y)); + + float lookAheadDistance = ms_useLookAhead ? m_currentSpeed * ms_lookAheadTime: 0.0f; + if (ms_lockLookAhead) + lookAheadDistance = m_speedMax * ms_lookAheadTime; + + const Vector lookAhead = motorFrameK_w * lookAheadDistance; + + float deltaRoll = 0.0f; + float deltaPitch = 0.0f; + + //-- + //-- compute the desired change in roll & pitch + //-- + + if (HoverPlaneHelper::findMinimumHoverPlane (*vehicleObject, deltaRoll, deltaPitch, lookAhead)) + { + m_targetRoll = deltaRoll; + m_targetPitch = deltaPitch; + + if (ms_showDebugVehicleBoxes && ms_useLookAhead) + showDebugBoxHoverPlane (lookAhead); + + const float vehicle_y_w = m_lastY_w; + + vehicleObject->resetRotateTranslate_o2p (); + vehicleObject->setTransform_o2p (m_baseTransform_o2p); + + //-- auto-flatten the roll & pitch if we are moving slowly or stopped + if (ms_useFlattening) + { + m_targetRoll = linearInterpolate (m_targetRoll, 0.0f, sqr (sqr(1.0f - speedPercent)) * m_autoLevellingForce); + m_targetPitch = linearInterpolate (m_targetPitch, 0.0f, sqr (sqr(1.0f - speedPercent)) * m_autoLevellingForce); + } + + if (!ms_useDamping) + { + m_roll = m_targetRoll; + m_pitch = m_targetPitch; + } + + vehicleObject->pitch_o (m_pitch); + vehicleObject->roll_o (m_roll); + vehicleObject->move_p (Vector::unitY * (m_lastY_w - vehicleObject->getPosition_w ().y)); + + const Vector & vehicleFrameK_w = vehicleObject->getObjectFrameK_w (); + Vector lookAheadVehicle = vehicleFrameK_w * lookAheadDistance; + lookAheadVehicle = m_baseTransform_o2p.rotateTranslate_p2l (lookAheadVehicle); + + //-- + //-- determine the hover height target + //-- + + if (HoverPlaneHelper::findMinimumHoverHeight (*vehicleObject, m_targetY_w, lookAheadVehicle)) + { + if (ms_showDebugVehicleBoxes && ms_useLookAhead) + showDebugBoxHeight (lookAheadVehicle); + + m_distancePopupThisFrame += m_targetY_w - vehicle_y_w; + + float y = std::max (vehicle_y_w, m_targetY_w); + + if (!ms_useDamping) + { + const float desiredHoverHeight = m_hoverHeight; +// const float desiredHoverHeight = linearInterpolate (m_hoverHeightStopped, m_hoverHeight, speedPercent); + m_targetY_w += desiredHoverHeight; + y = m_targetY_w ; + } + + const float deltaY = (y - vehicleObject->getPosition_w ().y); + vehicleObject->move_p (Vector::unitY * deltaY); + m_lastY_w = y; + + m_vehicleMotorOffsetY = m_lastY_w - motorObject->getPosition_w ().y; + } + } + + if (ms_showCrumbs) + updateCrumbTrail (); + + m_lastFrameK_w = motorFrameK_w; + m_lastSpeed = m_currentSpeed; + + return AlterResult::cms_keepNoAlter; +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::showDebugBoxHoverPlane (const Vector & ) const +{ +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::showDebugBoxHeight (const Vector & ) const +{ +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::updateCrumbTrail () const +{ +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::setDampRoll (float f) +{ + m_dampFactorRoll = f; +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::setDampPitch (float f) +{ + m_dampFactorPitch = f; +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::setDampHeight (float f) +{ + m_dampFactorGlide = f; +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::setGlide (float f) +{ + m_glideFactorMoving = f; +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::setPitchAccel (float f) +{ + m_pitchFactorAccel = f; +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::setPitchDecel (float f) +{ + m_pitchFactorDecel = f; +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::setRollTurn (float f) +{ + m_rollFactorTurn = f; +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::setAutoLevel (float f) +{ + m_autoLevellingForce = f; +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::setHoverHeight (float f) +{ + m_hoverHeight = f; +} + +//---------------------------------------------------------------------- + +float VehicleHoverDynamics::getTurnRateForSpeedRadians (float currentSpeed) const +{ + if (m_speedMax <= 0.0f || m_speedMax - m_speedMin <= 0.0f) + return 0.0f; + + const float speedPercent = std::max (0.0f, std::min (1.0f, (currentSpeed - m_speedMin) / (m_speedMax - m_speedMin))); + + return m_turnRateMin + (m_turnRateMax - m_turnRateMin) * speedPercent; +} + +//---------------------------------------------------------------------- + +float VehicleHoverDynamics::getTurnRateForSpeedDegrees (float currentSpeed) const +{ + return convertRadiansToDegrees (getTurnRateForSpeedRadians (currentSpeed)); +} + +//---------------------------------------------------------------------- + +float VehicleHoverDynamics::getAccelForSpeed (float currentSpeed) const +{ + if (m_speedMax <= 0.0f || m_speedMax - m_speedMin <= 0.0f) + return 0.0f; + + const float speedPercent = std::max (0.0f, std::min (1.0f, (currentSpeed - m_speedMin) / (m_speedMax - m_speedMin))); + + return m_accelMin + (m_accelMax - m_accelMin) * speedPercent; +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::readParamsFromCustomizationData (const CustomizationData & cd, + float & speedMin, + float & speedMax, + float & turnRateMin, + float & turnRateMax, + float & accelMin, + float & accelMax) +{ + float dummy = 0.0f; + bool dumbool = false; + + readParamsFromCustomizationData (cd, + speedMin, + speedMax, + turnRateMin, + turnRateMax, + accelMin, + accelMax, + dummy, + dummy, + dummy, + dummy, + dummy, + dummy, + dummy, + dummy, + dummy, + dumbool); +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::readParamsFromCustomizationData (const CustomizationData & cd, + float & speedMin, + float & speedMax, + float & turnRateMin, + float & turnRateMax, + float & accelMin, + float & accelMax, + float & decel, + float & slopeMod, + float & dampFactorRoll, + float & dampFactorPitch, + float & dampFactorGlide, + float & glideFactorMoving, + float & rollFactorTurn, + float & hoverHeight, + float & autoLevellingForce, + bool & strafe) +{ + float tempStrafe = 0.0f; + const CdLookupData s_data [] = + { + CdLookupData (&speedMin, CdVariables::speedMin), + CdLookupData (&speedMax, CdVariables::speedMax), + CdLookupData (&turnRateMin, CdVariables::turnRateMin), + CdLookupData (&turnRateMax, CdVariables::turnRateMax), + CdLookupData (&accelMin, CdVariables::accelMin), + CdLookupData (&accelMax, CdVariables::accelMax), + CdLookupData (&decel, CdVariables::decel), + CdLookupData (&slopeMod, CdVariables::slopeMod), + CdLookupData (&dampFactorRoll, CdVariables::dampRoll), + CdLookupData (&dampFactorPitch, CdVariables::dampPitch), + CdLookupData (&dampFactorGlide, CdVariables::dampHeight), + CdLookupData (&glideFactorMoving, CdVariables::glide), + CdLookupData (&rollFactorTurn, CdVariables::banking), + CdLookupData (&hoverHeight, CdVariables::hoverHeight), + CdLookupData (&autoLevellingForce, CdVariables::autoLevel), + CdLookupData (&tempStrafe, CdVariables::strafe) + }; + + const int s_data_len = sizeof (s_data) / sizeof (s_data [0]); + + for (int i = 0; i < s_data_len; ++i) + { + const CdLookupData & cld = s_data [i]; + const CdVariableData & cvd = cld.variableData; + + const RangedIntCustomizationVariable * const ricv = dynamic_cast(cd.findConstVariable(cvd.path)); + if (ricv) + { + const int val = ricv->getValue (); + const float fval = val * cvd.conversionFactor; + *cld.val = fval; + } + else + WARNING (true, ("VehicleHoverDynamics customization param [%s] not found", cvd.path.c_str ())); + } + + strafe = tempStrafe > 0.0f; +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::readParamsFromCustomizationData () +{ + if (!m_customizationData) + return; + + m_customizationDataChanged = false; + + float m_decel = 0.0f; + float m_slopeMod = 0.0f; + + readParamsFromCustomizationData (*m_customizationData, + m_speedMin, + m_speedMax, + m_turnRateMin, + m_turnRateMax, + m_accelMin, + m_accelMax, + m_decel, + m_slopeMod, + m_dampFactorRoll, + m_dampFactorPitch, + m_dampFactorGlide, + m_glideFactorMoving, + m_rollFactorTurn, + m_hoverHeight, + m_autoLevellingForce, + m_canStrafe); +} + +//---------------------------------------------------------------------- + +void VehicleHoverDynamics::onCustomizationDataModified (const CustomizationData & cd) const +{ + if (&cd == m_customizationData) + m_customizationDataChanged = true; +} + +//---------------------------------------------------------------------- + +/** +* turn rates are passed into this function in degrees +*/ + +void VehicleHoverDynamics::setInitialParams (CustomizationData & cd, + float speedMin, + float speedMax, + float turnRateMin, + float turnRateMax, + float accelMin, + float accelMax) +{ + turnRateMin = convertDegreesToRadians (turnRateMin); + turnRateMax = convertDegreesToRadians (turnRateMax); + + const CdLookupData s_data [] = + { + CdLookupData (&speedMin, CdVariables::speedMin), + CdLookupData (&speedMax, CdVariables::speedMax), + CdLookupData (&turnRateMin, CdVariables::turnRateMin), + CdLookupData (&turnRateMax, CdVariables::turnRateMax), + CdLookupData (&accelMin, CdVariables::accelMin), + CdLookupData (&accelMax, CdVariables::accelMax) + }; + + const int s_data_len = sizeof (s_data) / sizeof (s_data [0]); + + for (int i = 0; i < s_data_len; ++i) + { + const CdLookupData & cld = s_data [i]; + const CdVariableData & cvd = cld.variableData; + + RangedIntCustomizationVariable * const ricv = dynamic_cast(cd.findVariable(cvd.path)); + if (ricv) + { + const float fval = *cld.val; + const int ival = static_cast(fval / cvd.conversionFactor); + ricv->setValue (ival); + } + else + WARNING (true, ("VehicleHoverDynamics customization param [%s] not found", cvd.path.c_str ())); + } +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/object/VehicleHoverDynamics.h b/engine/shared/library/sharedGame/src/shared/object/VehicleHoverDynamics.h new file mode 100644 index 00000000..24cf797d --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/VehicleHoverDynamics.h @@ -0,0 +1,296 @@ +// ====================================================================== +// +// VehicleHoverDynamics.h +// copyright 2003, sony online entertainment +// +// +// ====================================================================== + +#ifndef INCLUDED_VehicleHoverDynamics_H +#define INCLUDED_VehicleHoverDynamics_H + +// ====================================================================== + +#include "sharedObject/Dynamics.h" +#include "sharedMath/Vector.h" +#include "sharedMath/Transform.h" + +class CustomizationData; + +// ====================================================================== +// Abstract VehicleHoverDynamics entity for an object + +class VehicleHoverDynamics : public Dynamics +{ +public: + + explicit VehicleHoverDynamics (Object* newOwner, float yaw, float hoverHeight); + virtual ~VehicleHoverDynamics () = 0; + + virtual float alter(float time); + + void setDampRoll (float f); + void setDampPitch (float f); + void setDampHeight (float f); + void setGlide (float f); + void setPitchAccel (float f); + void setPitchDecel (float f); + void setRollTurn (float f); + void setAutoLevel (float f); + void setHoverHeight (float f); + void setNumType (float f); + + float getDampRoll () const; + float getDampPitch () const; + float getDampHeight () const; + float getGlide () const; + float getPitchAccel () const; + float getPitchDecel () const; + float getRollTurn () const; + float getAutoLevel () const; + float getHoverHeight () const; + float getNumTypes () const; + + float getSpeedMin () const; + float getSpeedMax () const; + float getTurnRateMin () const; + float getTurnRateMax () const; + float getTurnRateForSpeedRadians (float currentSpeed) const; + float getTurnRateForSpeedDegrees (float currentSpeed) const; + float getAccelMin () const; + float getAccelMax () const; + float getAccelForSpeed (float currentSpeed) const; + + bool getCanStrafe () const; + + void onCustomizationDataModified (const CustomizationData & cd) const; + + static void setInitialParams (CustomizationData & cd, + float speedMin, + float speedMax, + float turnRateMin, + float turnRateMax, + float accelMin, + float accelMax); + + static void readParamsFromCustomizationData (const CustomizationData & cd, + float & speedMin, + float & speedMax, + float & turnRateMin, + float & turnRateMax, + float & accelMin, + float & accelMax, + float & decel, + float & slopeMod, + float & dampFactorRoll, + float & dampFactorPitch, + float & dampFactorGlide, + float & glideFactorMoving, + float & rollFactorTurn, + float & hoverHeight, + float & autoLevellingForce, + bool & strafe); + + static void readParamsFromCustomizationData (const CustomizationData & cd, + float & speedMin, + float & speedMax, + float & turnRateMin, + float & turnRateMax, + float & accelMin, + float & accelMax); + +protected: + + float m_currentSpeed; + float m_speedMin; + float m_speedMax; + float m_turnRateMin; + float m_turnRateMax; + float m_accelMax; + float m_accelMin; + +// float m_maximumAccel; +// float m_maximumTurnRate; + float m_vehicleMotorOffsetY; + float m_distancePopupThisFrame; + bool m_canStrafe; + + virtual void showDebugBoxHoverPlane (const Vector & lookAhead) const; + virtual void showDebugBoxHeight (const Vector & lookAhead) const; + virtual void updateCrumbTrail () const; + + float getTurnRatePercentLastFrame () const; + +private: + + // disable these + VehicleHoverDynamics (); + VehicleHoverDynamics (const VehicleHoverDynamics&); + VehicleHoverDynamics& operator= (const VehicleHoverDynamics&); + + void readParamsFromCustomizationData (); + +private: + + float m_dampFactorRoll; + float m_dampFactorPitch; + float m_dampFactorGlide; + float m_glideFactorMoving; + float m_pitchFactorAccel; + float m_pitchFactorDecel; + float m_rollFactorTurn; + + float m_targetRoll; + float m_targetPitch; + + float m_roll; + float m_pitch; + + float m_targetY_w; + float m_lastY_w; + + Vector m_lastFrameK_w; + + float m_hoverHeight; + float m_hoverHeightStopped; + + Transform m_baseTransform_o2p; + + float m_autoLevellingForce; + + float m_lastSpeed; + + float m_lastTurnDeltaRoll; + float m_lastAccelDeltaPitch; + + CustomizationData * m_customizationData; + + int m_hasAlteredCount; + mutable bool m_customizationDataChanged; + + float m_turnRatePercentLastFrame; +}; + + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getDampRoll () const +{ + return m_dampFactorRoll; +} + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getDampPitch () const +{ + return m_dampFactorPitch; +} + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getDampHeight () const +{ + return m_dampFactorGlide; +} + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getGlide () const +{ + return m_glideFactorMoving; +} + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getPitchAccel () const +{ + return m_pitchFactorAccel; +} + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getPitchDecel () const +{ + return m_pitchFactorDecel; +} + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getRollTurn () const +{ + return m_rollFactorTurn; +} + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getAutoLevel () const +{ + return m_autoLevellingForce; +} + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getHoverHeight () const +{ + return m_hoverHeight; +} + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getSpeedMin () const +{ + return m_speedMin; +} + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getSpeedMax () const +{ + return m_speedMax; +} + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getTurnRateMin () const +{ + return m_turnRateMin; +} + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getTurnRateMax () const +{ + return m_turnRateMax; +} + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getAccelMin () const +{ + return m_accelMin; +} + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getAccelMax () const +{ + return m_accelMax; +} + +//---------------------------------------------------------------------- + +inline float VehicleHoverDynamics::getTurnRatePercentLastFrame () const +{ + return m_turnRatePercentLastFrame; +} + +//---------------------------------------------------------------------- + +inline bool VehicleHoverDynamics::getCanStrafe () const +{ + return m_canStrafe; +} + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/object/Waypoint.cpp b/engine/shared/library/sharedGame/src/shared/object/Waypoint.cpp new file mode 100644 index 00000000..a0a4a71b --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/Waypoint.cpp @@ -0,0 +1,508 @@ +// ====================================================================== +// +// Waypoint.cpp +// +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/Waypoint.h" + +#include "Archive/Archive.h" +#include "sharedFoundation/NetworkId.h" +#include "sharedFoundation/NetworkIdArchive.h" +#include "sharedUtility/LocationArchive.h" +#include "sharedUtility/Location.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedGame/WaypointData.h" +#include "sharedMessageDispatch/Transceiver.h" +#include "unicodeArchive/UnicodeArchive.h" +#include "UnicodeUtils.h" +#include + +// ====================================================================== + +namespace WaypointNamespace +{ + typedef std::hash_map WaypointMapById; + WaypointMapById s_waypointMapById; + bool s_installed; + + const std::string ColorNames [static_cast(Waypoint::NumColors)] = + { + "invisible", + "blue", + "green", + "orange", + "yellow", + "purple", + "white", + "space", + "small", + "entrance" + }; + + void remove(); +} + +using namespace WaypointNamespace; + +// ====================================================================== + +void releaseDataAccessor(Waypoint &target, WaypointData *data) +{ + target.releaseData(data); +} + +// ====================================================================== + +namespace Archive +{ + + // ---------------------------------------------------------------------- + + void get(Archive::ReadIterator &source, WaypointDataBase &target) + { + get(source, target.m_appearanceNameCrc); + get(source, target.m_location); + get(source, target.m_name); + NetworkId hackNetworkId; + get(source, hackNetworkId); // preserve format of old persisted bytestreams + get(source, target.m_color); + get(source, target.m_active); + } + + // ---------------------------------------------------------------------- + + void put(Archive::ByteStream &target, WaypointDataBase const &source) + { + put(target, source.m_appearanceNameCrc); + put(target, source.m_location); + put(target, source.m_name); + put(target, NetworkId::cms_invalid); // preserve format of old persisted bytestreams + put(target, source.m_color); + put(target, source.m_active); + } + + // ---------------------------------------------------------------------- + + void get(Archive::ReadIterator &source, Waypoint &target) + { + unsigned int appearanceNameCrc; + Location location; + Unicode::String name; + NetworkId networkId; + uint8 color; + bool active; + + get(source, appearanceNameCrc); + get(source, location); + get(source, name); + get(source, networkId); + get(source, color); + get(source, active); + + if (networkId.isValid()) + { + WaypointData *data = 0; + std::hash_map::iterator f = s_waypointMapById.find(networkId); + if (f == s_waypointMapById.end()) + data = new WaypointData(networkId); + else + data = f->second; + + releaseDataAccessor(target, data); + target.setAppearanceNameCrc(appearanceNameCrc); + target.setLocation(location); + target.setName(name); + target.setColor(color); + target.setActive(active); + } + else + { + DEBUG_FATAL(true, ("Trying to unpack an invalid waypoint. The caller should probably be using WaypointDataBase instead.")); + + // We're unpacking a waypoint without a valid networkId, so just point it at the invalid waypoint + releaseDataAccessor(target, &WaypointData::getInvalidWaypoint()); + } + } + + // ---------------------------------------------------------------------- + + void put(Archive::ByteStream &target, Waypoint const &source) + { + put(target, source.getAppearanceNameCrc()); + put(target, source.getLocation()); + put(target, source.getName()); + put(target, source.getNetworkId()); + put(target, source.getColor()); + put(target, source.isActive()); + } + + // ---------------------------------------------------------------------- + +} + +// ====================================================================== + +WaypointDataBase::WaypointDataBase() : + m_appearanceNameCrc(0), + m_location(), + m_name(), + m_color(Waypoint::Blue), + m_active(false) +{ +} + +// ---------------------------------------------------------------------- + +void WaypointDataBase::setName(Unicode::String const &name) +{ + //This magical number (250) is chosen because the waypoint datatable has VARCHAR2(512) in this column, + //and we're assuming 2 bytes per char (which is not quite true actually) plus an extra one for null plus + //a few extra for good measure and because nobody needs 251-character waypoint names. + if (name.length() > 250) + { + WARNING(true, ("Warning: truncating waypoint name, not valid if string id: %s", Unicode::wideToUTF8(name).c_str())); + m_name = name.substr(0, 250); + } + else + { + m_name = name; + } +} + +// ====================================================================== + +WaypointData::WaypointData() : + WaypointDataBase(), + m_changeNotification(new ChangeNotification), + m_refCount(0), + m_networkId() +{ +} + +// ---------------------------------------------------------------------- + +WaypointData::WaypointData(NetworkId const &networkId) : + WaypointDataBase(), + m_changeNotification(new ChangeNotification), + m_refCount(0), + m_networkId(networkId) +{ + if (m_networkId != NetworkId::cms_invalid) + s_waypointMapById[m_networkId] = this; +} + +// ---------------------------------------------------------------------- + +WaypointData::~WaypointData() +{ + if (this != &getInvalidWaypoint()) + { + DEBUG_FATAL(m_refCount > 0, ("WaypointData deleted while it still has references!")); + + IGNORE_RETURN(s_waypointMapById.erase(m_networkId)); + } + + delete m_changeNotification; + m_changeNotification = 0; +} + +// ---------------------------------------------------------------------- + +WaypointData & WaypointData::getInvalidWaypoint() +{ + // we have a static function to return a static rather + // than have a static member because we want to prevent + // another static from referencing this static before + // it has been created (i.e. the problem with ordering + // when statics are initialized) + static WaypointData invalidWaypoint; + + return invalidWaypoint; +} + +// ====================================================================== + +void Waypoint::install() +{ + s_installed = true; + + // prevent anyone from deleting + WaypointData::getInvalidWaypoint().m_refCount++; + + ExitChain::add(remove, "Waypoint::remove"); +} + +void WaypointNamespace::remove() +{ + DEBUG_FATAL(!s_installed, ("s_installed is false")); + + s_installed = false; +} + +Waypoint::Waypoint() : + m_data(0), + m_loadNotification() +{ + DEBUG_FATAL(!s_installed, ("Waypoint::install not called")); + + m_data = &WaypointData::getInvalidWaypoint(); + m_data->m_refCount++; +} + +// ---------------------------------------------------------------------- + +Waypoint::Waypoint(NetworkId const &id) : + m_data(0), + m_loadNotification() +{ + DEBUG_FATAL(!s_installed, ("Waypoint::install not called")); + + if (id == NetworkId::cms_invalid) + { + m_data = &WaypointData::getInvalidWaypoint(); + } + else + { + m_data = new WaypointData(id); + } + m_data->m_refCount++; +} + +// ---------------------------------------------------------------------- + +Waypoint::Waypoint(Waypoint const &rhs) : + m_data(rhs.m_data), + m_loadNotification() +{ + m_data->m_refCount++; +} + +// ---------------------------------------------------------------------- + +Waypoint::~Waypoint() +{ + releaseData(0); +} + +// ---------------------------------------------------------------------- + +Waypoint &Waypoint::operator=(Waypoint const &rhs) +{ + if (&rhs != this) + releaseData(rhs.m_data); + return *this; +} + +// ---------------------------------------------------------------------- + +bool Waypoint::operator!=(Waypoint const &) const +{ + return true; // force deltas +} + +// ---------------------------------------------------------------------- + +uint8 Waypoint::getColorIdByName(std::string const &colorName) // static +{ + for (int i = 0; i < static_cast(NumColors); ++i) + if (colorName == ColorNames[i]) + return static_cast(i); + + return static_cast(Invisible); +} + +// ---------------------------------------------------------------------- + +std::string const &Waypoint::getColorNameById(uint8 id) // static +{ + if (id < static_cast(NumColors)) + return ColorNames[static_cast(id)]; + + static const std::string empty; + return empty; +} + +// ---------------------------------------------------------------------- + +Waypoint const Waypoint::getWaypointById(NetworkId const &id) // static +{ + Waypoint result; + std::hash_map::iterator f = s_waypointMapById.find(id); + if (f != s_waypointMapById.end()) + result.releaseData(f->second); + return result; +} + +// ---------------------------------------------------------------------- + +unsigned int Waypoint::getAppearanceNameCrc() const +{ + return m_data->m_appearanceNameCrc; +} + +// ---------------------------------------------------------------------- + +Waypoint::ChangeNotification &Waypoint::getChangeNotification() +{ + return *m_data->m_changeNotification; +} + +// ---------------------------------------------------------------------- + +Waypoint::LoadNotification &Waypoint::getLoadNotification() +{ + return m_loadNotification; +} + +// ---------------------------------------------------------------------- + +Location const &Waypoint::getLocation() const +{ + return m_data->m_location; +} + +// ---------------------------------------------------------------------- + +Unicode::String const &Waypoint::getName() const +{ + return m_data->m_name; +} + +// ---------------------------------------------------------------------- + +NetworkId const &Waypoint::getNetworkId() const +{ + return m_data->m_networkId; +} + +// ---------------------------------------------------------------------- + +uint8 Waypoint::getColor() const +{ + return m_data->m_color; +} + +// ---------------------------------------------------------------------- + +bool Waypoint::isActive() const +{ + return m_data->m_active; +} + +// ---------------------------------------------------------------------- + +bool Waypoint::isValid() const +{ + return m_data->m_networkId != NetworkId::cms_invalid; +} + +// ---------------------------------------------------------------------- + +bool Waypoint::isVisible() const +{ + return m_data->m_color != Waypoint::Invisible; +} + +// ---------------------------------------------------------------------- + +WaypointDataBase const &Waypoint::getWaypointDataBase() const +{ + NOT_NULL(m_data); + return *m_data; +} + +// ---------------------------------------------------------------------- + +void Waypoint::set(WaypointDataBase const &wd) +{ + DEBUG_FATAL(!isValid(), ("Programmer bug: Attempted to change data on an invalid waypoint")); + + m_data->m_appearanceNameCrc = wd.m_appearanceNameCrc; + m_data->m_location = wd.m_location; + m_data->setName(wd.m_name); + m_data->m_color = std::min(wd.m_color, static_cast(NumColors-1)); + m_data->m_active = wd.m_active; + + m_data->m_changeNotification->emitMessage(*this); +} + +// ---------------------------------------------------------------------- + +void Waypoint::setAppearanceNameCrc(unsigned int appearanceNameCrc) +{ + DEBUG_FATAL(!isValid(), ("Programmer bug: Attempted to change data on an invalid waypoint")); + + m_data->m_appearanceNameCrc = appearanceNameCrc; + m_data->m_changeNotification->emitMessage(*this); +} + +// ---------------------------------------------------------------------- + +void Waypoint::setLocation(Location const &location) +{ + DEBUG_FATAL(!isValid(), ("Programmer bug: Attempted to change data on an invalid waypoint")); + + m_data->m_location = location; + m_data->m_changeNotification->emitMessage(*this); +} + +// ---------------------------------------------------------------------- + +void Waypoint::setName(Unicode::String const &name) +{ + DEBUG_FATAL(!isValid(), ("Programmer bug: Attempted to change data on an invalid waypoint")); + + m_data->setName(name); + + m_data->m_changeNotification->emitMessage(*this); +} + +// ---------------------------------------------------------------------- + +void Waypoint::setColor(uint8 color) +{ + DEBUG_FATAL(!isValid(), ("Programmer bug: Attempted to change data on an invalid waypoint")); + + m_data->m_color = std::min(color, static_cast(NumColors-1)); + m_data->m_changeNotification->emitMessage(*this); +} + +// ---------------------------------------------------------------------- + +void Waypoint::setActive(bool active) +{ + DEBUG_FATAL(!isValid(), ("Programmer bug: Attempted to change data on an invalid waypoint")); + + m_data->m_active = active; + m_data->m_changeNotification->emitMessage(*this); +} + +// ---------------------------------------------------------------------- + +void Waypoint::releaseData(WaypointData *replacement) +{ + if (replacement != m_data) + { + if (replacement) + { + m_loadNotification.emitMessage(*replacement->m_changeNotification); + replacement->m_refCount++; + } + + m_data->m_refCount--; + if (m_data->m_refCount < 1) + { + if (m_data != &WaypointData::getInvalidWaypoint()) + delete m_data; + } + + m_data = replacement; + } +} + +// ====================================================================== + diff --git a/engine/shared/library/sharedGame/src/shared/object/Waypoint.h b/engine/shared/library/sharedGame/src/shared/object/Waypoint.h new file mode 100644 index 00000000..c160cb8f --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/Waypoint.h @@ -0,0 +1,104 @@ +// ====================================================================== +// +// Waypoint.h +// +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall +// ====================================================================== + +#ifndef _INCLUDED_Waypoint_H +#define _INCLUDED_Waypoint_H + +// ====================================================================== + +#include "sharedMessageDispatch/Transceiver.h" + +namespace MessageDispatch +{ + template class Transceiver; +} + +class WaypointData; +class WaypointDataBase; +class Location; +class NetworkId; + +// ====================================================================== + +class Waypoint +{ +public: + enum + { + Invisible, + Blue, + Green, + Orange, + Yellow, + Purple, + White, + Space, + Small, + Entrance, + NumColors + }; + + typedef MessageDispatch::Transceiver ChangeNotification; + typedef MessageDispatch::Transceiver LoadNotification; + + static void install(); + + Waypoint(); + Waypoint(Waypoint const &source); + Waypoint(NetworkId const &); + ~Waypoint(); + + Waypoint &operator=(Waypoint const &rhs); + bool operator!=(Waypoint const &rhs) const; + + static uint8 getColorIdByName (std::string const &colorName); + static std::string const & getColorNameById (uint8 color); + static Waypoint const getWaypointById (NetworkId const &id); + + unsigned int getAppearanceNameCrc () const; + ChangeNotification & getChangeNotification (); + LoadNotification & getLoadNotification (); + Location const & getLocation () const; + Unicode::String const & getName () const; + NetworkId const & getNetworkId () const; + uint8 getColor () const; + bool isActive () const; + bool isValid () const; + bool isVisible () const; + WaypointDataBase const & getWaypointDataBase () const; + + void set (WaypointDataBase const &wd); + void setAppearanceNameCrc (unsigned int crc); + void setLocation (Location const &location); + void setName (Unicode::String const &name); + void setColor (uint8 color); + void setActive (bool active); + +private: + friend void releaseDataAccessor(Waypoint &target, WaypointData *data); + void releaseData(WaypointData *replacementData); + + WaypointData * m_data; + LoadNotification m_loadNotification; +}; + +// ====================================================================== + +namespace Archive +{ + class ReadIterator; + class ByteStream; + + void get(Archive::ReadIterator &source, Waypoint &target); + void put(Archive::ByteStream &target, Waypoint const &source); +} + +// ====================================================================== + +#endif // _INCLUDED_Waypoint_H + diff --git a/engine/shared/library/sharedGame/src/shared/object/WaypointData.cpp b/engine/shared/library/sharedGame/src/shared/object/WaypointData.cpp new file mode 100644 index 00000000..54026c11 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/WaypointData.cpp @@ -0,0 +1,14 @@ +//====================================================================== +// +// WaypointData.cpp +// copyright (c) 2003 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/WaypointData.h" + +//====================================================================== + + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/object/WaypointData.h b/engine/shared/library/sharedGame/src/shared/object/WaypointData.h new file mode 100644 index 00000000..3df00f67 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/object/WaypointData.h @@ -0,0 +1,75 @@ +//====================================================================== +// +// WaypointData.h +// copyright (c) 2003 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_WaypointData_H +#define INCLUDED_WaypointData_H + +//====================================================================== + +#include "sharedFoundation/NetworkId.h" +#include "sharedUtility/Location.h" +#include "Unicode.h" + +class Waypoint; + +namespace MessageDispatch +{ + template class Transceiver; + class Callback; +} + +//---------------------------------------------------------------------- + +class WaypointDataBase +{ +public: + WaypointDataBase(); + virtual ~WaypointDataBase() {}; + + void setName(Unicode::String const &name); + + unsigned int m_appearanceNameCrc; + Location m_location; + Unicode::String m_name; + uint8 m_color; + bool m_active; +}; + +//---------------------------------------------------------------------- + +namespace Archive +{ + class ByteStream; + class ReadIterator; + + void get(Archive::ReadIterator &source, WaypointDataBase &target); + void put(Archive::ByteStream &target, WaypointDataBase const &source); +}; + +//---------------------------------------------------------------------- + +class WaypointData: public WaypointDataBase +{ +public: + typedef MessageDispatch::Transceiver ChangeNotification; + + WaypointData (); + WaypointData (const NetworkId & networkId); + ~WaypointData (); + WaypointData (const WaypointData &); + WaypointData & operator = (const WaypointData &); + + static WaypointData & getInvalidWaypoint(); + + ChangeNotification * m_changeNotification; + int m_refCount; + NetworkId m_networkId; +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedBattlefieldMarkerObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedBattlefieldMarkerObjectTemplate.cpp new file mode 100644 index 00000000..23867f84 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedBattlefieldMarkerObjectTemplate.cpp @@ -0,0 +1,572 @@ +//======================================================================== +// +// SharedBattlefieldMarkerObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedBattlefieldMarkerObjectTemplate.h" +#include "sharedDebug/DataLint.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedBattlefieldMarkerObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedBattlefieldMarkerObjectTemplate::SharedBattlefieldMarkerObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedTangibleObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedBattlefieldMarkerObjectTemplate::SharedBattlefieldMarkerObjectTemplate + +/** + * Class destructor. + */ +SharedBattlefieldMarkerObjectTemplate::~SharedBattlefieldMarkerObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedBattlefieldMarkerObjectTemplate::~SharedBattlefieldMarkerObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedBattlefieldMarkerObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedBattlefieldMarkerObjectTemplate_tag, create); +} // SharedBattlefieldMarkerObjectTemplate::registerMe + +/** + * Creates a SharedBattlefieldMarkerObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedBattlefieldMarkerObjectTemplate::create(const std::string & filename) +{ + return new SharedBattlefieldMarkerObjectTemplate(filename); +} // SharedBattlefieldMarkerObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedBattlefieldMarkerObjectTemplate::getId(void) const +{ + return SharedBattlefieldMarkerObjectTemplate_tag; +} // SharedBattlefieldMarkerObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedBattlefieldMarkerObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedBattlefieldMarkerObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedBattlefieldMarkerObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedBattlefieldMarkerObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedBattlefieldMarkerObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +int SharedBattlefieldMarkerObjectTemplate::getNumberOfPoles(bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedBattlefieldMarkerObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getNumberOfPoles(true); +#endif + } + + if (!m_numberOfPoles.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter numberOfPoles in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter numberOfPoles has not been defined in template %s!", DataResource::getName())); + return base->getNumberOfPoles(); + } + } + + int value = m_numberOfPoles.getValue(); + char delta = m_numberOfPoles.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getNumberOfPoles(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedBattlefieldMarkerObjectTemplate::getNumberOfPoles + +int SharedBattlefieldMarkerObjectTemplate::getNumberOfPolesMin(bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedBattlefieldMarkerObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getNumberOfPolesMin(true); +#endif + } + + if (!m_numberOfPoles.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter numberOfPoles in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter numberOfPoles has not been defined in template %s!", DataResource::getName())); + return base->getNumberOfPolesMin(); + } + } + + int value = m_numberOfPoles.getMinValue(); + char delta = m_numberOfPoles.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getNumberOfPolesMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedBattlefieldMarkerObjectTemplate::getNumberOfPolesMin + +int SharedBattlefieldMarkerObjectTemplate::getNumberOfPolesMax(bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedBattlefieldMarkerObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getNumberOfPolesMax(true); +#endif + } + + if (!m_numberOfPoles.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter numberOfPoles in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter numberOfPoles has not been defined in template %s!", DataResource::getName())); + return base->getNumberOfPolesMax(); + } + } + + int value = m_numberOfPoles.getMaxValue(); + char delta = m_numberOfPoles.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getNumberOfPolesMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedBattlefieldMarkerObjectTemplate::getNumberOfPolesMax + +float SharedBattlefieldMarkerObjectTemplate::getRadius(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedBattlefieldMarkerObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getRadius(true); +#endif + } + + if (!m_radius.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter radius in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter radius has not been defined in template %s!", DataResource::getName())); + return base->getRadius(); + } + } + + float value = m_radius.getValue(); + char delta = m_radius.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getRadius(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedBattlefieldMarkerObjectTemplate::getRadius + +float SharedBattlefieldMarkerObjectTemplate::getRadiusMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedBattlefieldMarkerObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getRadiusMin(true); +#endif + } + + if (!m_radius.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter radius in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter radius has not been defined in template %s!", DataResource::getName())); + return base->getRadiusMin(); + } + } + + float value = m_radius.getMinValue(); + char delta = m_radius.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getRadiusMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedBattlefieldMarkerObjectTemplate::getRadiusMin + +float SharedBattlefieldMarkerObjectTemplate::getRadiusMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedBattlefieldMarkerObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getRadiusMax(true); +#endif + } + + if (!m_radius.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter radius in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter radius has not been defined in template %s!", DataResource::getName())); + return base->getRadiusMax(); + } + } + + float value = m_radius.getMaxValue(); + char delta = m_radius.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getRadiusMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedBattlefieldMarkerObjectTemplate::getRadiusMax + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedBattlefieldMarkerObjectTemplate::testValues(void) const +{ + IGNORE_RETURN(getNumberOfPolesMin(true)); + IGNORE_RETURN(getNumberOfPolesMax(true)); + IGNORE_RETURN(getRadiusMin(true)); + IGNORE_RETURN(getRadiusMax(true)); + SharedTangibleObjectTemplate::testValues(); +} // SharedBattlefieldMarkerObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedBattlefieldMarkerObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedBattlefieldMarkerObjectTemplate_tag) + { + SharedTangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,1)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "numberOfPoles") == 0) + m_numberOfPoles.loadFromIff(file); + else if (strcmp(paramName, "radius") == 0) + m_radius.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + SharedTangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedBattlefieldMarkerObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedBattlefieldMarkerObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedBattlefieldMarkerObjectTemplate.h new file mode 100644 index 00000000..29672636 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedBattlefieldMarkerObjectTemplate.h @@ -0,0 +1,91 @@ +//======================================================================== +// +// SharedBattlefieldMarkerObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedBattlefieldMarkerObjectTemplate_H +#define _INCLUDED_SharedBattlefieldMarkerObjectTemplate_H + +#include "SharedTangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedBattlefieldMarkerObjectTemplate : public SharedTangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedBattlefieldMarkerObjectTemplate_tag = TAG(S,B,M,K) + }; +//@END TFD ID +public: + SharedBattlefieldMarkerObjectTemplate(const std::string & filename); + virtual ~SharedBattlefieldMarkerObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + int getNumberOfPoles(bool testData = false) const; + int getNumberOfPolesMin(bool testData = false) const; + int getNumberOfPolesMax(bool testData = false) const; + float getRadius(bool testData = false) const; + float getRadiusMin(bool testData = false) const; + float getRadiusMax(bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + IntegerParam m_numberOfPoles; // // number of child object poles + FloatParam m_radius; // // radius in meters +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedBattlefieldMarkerObjectTemplate(const SharedBattlefieldMarkerObjectTemplate &); + SharedBattlefieldMarkerObjectTemplate & operator =(const SharedBattlefieldMarkerObjectTemplate &); +}; + + +inline void SharedBattlefieldMarkerObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedBattlefieldMarkerObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedBattlefieldMarkerObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedBuildingObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedBuildingObjectTemplate.cpp new file mode 100644 index 00000000..3886ce42 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedBuildingObjectTemplate.cpp @@ -0,0 +1,269 @@ +//======================================================================== +// +// SharedBuildingObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedBuildingObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedBuildingObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedBuildingObjectTemplate::SharedBuildingObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedTangibleObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedBuildingObjectTemplate::SharedBuildingObjectTemplate + +/** + * Class destructor. + */ +SharedBuildingObjectTemplate::~SharedBuildingObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedBuildingObjectTemplate::~SharedBuildingObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedBuildingObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedBuildingObjectTemplate_tag, create); +} // SharedBuildingObjectTemplate::registerMe + +/** + * Creates a SharedBuildingObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedBuildingObjectTemplate::create(const std::string & filename) +{ + return new SharedBuildingObjectTemplate(filename); +} // SharedBuildingObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedBuildingObjectTemplate::getId(void) const +{ + return SharedBuildingObjectTemplate_tag; +} // SharedBuildingObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedBuildingObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedBuildingObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedBuildingObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedBuildingObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedBuildingObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +const std::string & SharedBuildingObjectTemplate::getTerrainModificationFileName(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedBuildingObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getTerrainModificationFileName(true); +#endif + } + + if (!m_terrainModificationFileName.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter terrainModificationFileName in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter terrainModificationFileName has not been defined in template %s!", DataResource::getName())); + return base->getTerrainModificationFileName(); + } + } + + const std::string & value = m_terrainModificationFileName.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedBuildingObjectTemplate::getTerrainModificationFileName + +const std::string & SharedBuildingObjectTemplate::getInteriorLayoutFileName(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedBuildingObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getInteriorLayoutFileName(true); +#endif + } + + if (!m_interiorLayoutFileName.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter interiorLayoutFileName in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter interiorLayoutFileName has not been defined in template %s!", DataResource::getName())); + return base->getInteriorLayoutFileName(); + } + } + + const std::string & value = m_interiorLayoutFileName.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedBuildingObjectTemplate::getInteriorLayoutFileName + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedBuildingObjectTemplate::testValues(void) const +{ + IGNORE_RETURN(getTerrainModificationFileName(true)); + IGNORE_RETURN(getInteriorLayoutFileName(true)); + SharedTangibleObjectTemplate::testValues(); +} // SharedBuildingObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedBuildingObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedBuildingObjectTemplate_tag) + { + SharedTangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,1)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "terrainModificationFileName") == 0) + m_terrainModificationFileName.loadFromIff(file); + else if (strcmp(paramName, "interiorLayoutFileName") == 0) + m_interiorLayoutFileName.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + SharedTangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedBuildingObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedBuildingObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedBuildingObjectTemplate.h new file mode 100644 index 00000000..1c37d84e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedBuildingObjectTemplate.h @@ -0,0 +1,87 @@ +//======================================================================== +// +// SharedBuildingObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedBuildingObjectTemplate_H +#define _INCLUDED_SharedBuildingObjectTemplate_H + +#include "SharedTangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedBuildingObjectTemplate : public SharedTangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedBuildingObjectTemplate_tag = TAG(S,B,O,T) + }; +//@END TFD ID +public: + SharedBuildingObjectTemplate(const std::string & filename); + virtual ~SharedBuildingObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + const std::string & getTerrainModificationFileName(bool testData = false) const; + const std::string & getInteriorLayoutFileName(bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + StringParam m_terrainModificationFileName; + StringParam m_interiorLayoutFileName; +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedBuildingObjectTemplate(const SharedBuildingObjectTemplate &); + SharedBuildingObjectTemplate & operator =(const SharedBuildingObjectTemplate &); +}; + + +inline void SharedBuildingObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedBuildingObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedBuildingObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedCellObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedCellObjectTemplate.cpp new file mode 100644 index 00000000..c68ebeb3 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedCellObjectTemplate.cpp @@ -0,0 +1,175 @@ +//======================================================================== +// +// SharedCellObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedCellObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedCellObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedCellObjectTemplate::SharedCellObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedCellObjectTemplate::SharedCellObjectTemplate + +/** + * Class destructor. + */ +SharedCellObjectTemplate::~SharedCellObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedCellObjectTemplate::~SharedCellObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedCellObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedCellObjectTemplate_tag, create); +} // SharedCellObjectTemplate::registerMe + +/** + * Creates a SharedCellObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedCellObjectTemplate::create(const std::string & filename) +{ + return new SharedCellObjectTemplate(filename); +} // SharedCellObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedCellObjectTemplate::getId(void) const +{ + return SharedCellObjectTemplate_tag; +} // SharedCellObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedCellObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedCellObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedCellObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedCellObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedCellObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedCellObjectTemplate::testValues(void) const +{ + SharedObjectTemplate::testValues(); +} // SharedCellObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedCellObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedCellObjectTemplate_tag) + { + SharedObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedCellObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedCellObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedCellObjectTemplate.h new file mode 100644 index 00000000..01c05587 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedCellObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedCellObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedCellObjectTemplate_H +#define _INCLUDED_SharedCellObjectTemplate_H + +#include "SharedObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedCellObjectTemplate : public SharedObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedCellObjectTemplate_tag = TAG(C,C,L,T) + }; +//@END TFD ID +public: + SharedCellObjectTemplate(const std::string & filename); + virtual ~SharedCellObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedCellObjectTemplate(const SharedCellObjectTemplate &); + SharedCellObjectTemplate & operator =(const SharedCellObjectTemplate &); +}; + + +inline void SharedCellObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedCellObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedCellObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedConstructionContractObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedConstructionContractObjectTemplate.cpp new file mode 100644 index 00000000..ebb5f9ee --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedConstructionContractObjectTemplate.cpp @@ -0,0 +1,175 @@ +//======================================================================== +// +// SharedConstructionContractObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedConstructionContractObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedConstructionContractObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedConstructionContractObjectTemplate::SharedConstructionContractObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedIntangibleObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedConstructionContractObjectTemplate::SharedConstructionContractObjectTemplate + +/** + * Class destructor. + */ +SharedConstructionContractObjectTemplate::~SharedConstructionContractObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedConstructionContractObjectTemplate::~SharedConstructionContractObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedConstructionContractObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedConstructionContractObjectTemplate_tag, create); +} // SharedConstructionContractObjectTemplate::registerMe + +/** + * Creates a SharedConstructionContractObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedConstructionContractObjectTemplate::create(const std::string & filename) +{ + return new SharedConstructionContractObjectTemplate(filename); +} // SharedConstructionContractObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedConstructionContractObjectTemplate::getId(void) const +{ + return SharedConstructionContractObjectTemplate_tag; +} // SharedConstructionContractObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedConstructionContractObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedConstructionContractObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedConstructionContractObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedConstructionContractObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedConstructionContractObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedConstructionContractObjectTemplate::testValues(void) const +{ + SharedIntangibleObjectTemplate::testValues(); +} // SharedConstructionContractObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedConstructionContractObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedConstructionContractObjectTemplate_tag) + { + SharedIntangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedIntangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedConstructionContractObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedConstructionContractObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedConstructionContractObjectTemplate.h new file mode 100644 index 00000000..20804df0 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedConstructionContractObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedConstructionContractObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedConstructionContractObjectTemplate_H +#define _INCLUDED_SharedConstructionContractObjectTemplate_H + +#include "SharedIntangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedConstructionContractObjectTemplate : public SharedIntangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedConstructionContractObjectTemplate_tag = TAG(S,C,N,C) + }; +//@END TFD ID +public: + SharedConstructionContractObjectTemplate(const std::string & filename); + virtual ~SharedConstructionContractObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedConstructionContractObjectTemplate(const SharedConstructionContractObjectTemplate &); + SharedConstructionContractObjectTemplate & operator =(const SharedConstructionContractObjectTemplate &); +}; + + +inline void SharedConstructionContractObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedConstructionContractObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedConstructionContractObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedCreatureObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedCreatureObjectTemplate.cpp new file mode 100644 index 00000000..83eca1e7 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedCreatureObjectTemplate.cpp @@ -0,0 +1,3390 @@ +//======================================================================== +// +// SharedCreatureObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedCreatureObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedGame/AssetCustomizationManager.h" +#include "sharedMath/Vector.h" +#include "sharedObject/CustomizationData.h" +#include "sharedObject/CustomizationDataProperty.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/MovementTable.h" +#include "sharedObject/Object.h" +#include "sharedObject/ObjectTemplateList.h" +#include "sharedObject/BasicRangedIntCustomizationVariable.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedCreatureObjectTemplate::ms_allowDefaultTemplateParams = true; + +typedef ::RangedIntCustomizationVariable GlobalRangedIntCustomizationVariableType; + +/** + * Class constructor. + */ +SharedCreatureObjectTemplate::SharedCreatureObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedTangibleObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ + m_movementTable = 0; +} // SharedCreatureObjectTemplate::SharedCreatureObjectTemplate + +/** + * Class destructor. + */ +SharedCreatureObjectTemplate::~SharedCreatureObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP + delete m_movementTable; + m_movementTable = 0; +} // SharedCreatureObjectTemplate::~SharedCreatureObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedCreatureObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedCreatureObjectTemplate_tag, create); +} // SharedCreatureObjectTemplate::registerMe + +/** + * Creates a SharedCreatureObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedCreatureObjectTemplate::create(const std::string & filename) +{ + return new SharedCreatureObjectTemplate(filename); +} // SharedCreatureObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedCreatureObjectTemplate::getId(void) const +{ + return SharedCreatureObjectTemplate_tag; +} // SharedCreatureObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedCreatureObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedCreatureObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedCreatureObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedCreatureObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedCreatureObjectTemplate::getHighestTemplateVersion + +void SharedCreatureObjectTemplate::postLoad() +{ + SharedTangibleObjectTemplate::postLoad(); + m_movementTable = new MovementTable(getMovementDatatable(), DataResource::getName()); +} + +// ---------------------------------------------------------------------- + +void SharedCreatureObjectTemplate::createCustomizationDataPropertyAsNeeded(Object &object, bool /* forceCreation */) const +{ + //-- Properties cannot be added while an object is in the world. Some callers may be in the world, + // so temporarily remove the object from the world if necessary. + bool shouldBeInWorld = object.isInWorld(); + if (shouldBeInWorld) + object.removeFromWorld(); + + //-- Create the CustomizationDataProperty, add to Object property collection + CustomizationDataProperty *const cdProperty = new CustomizationDataProperty(object); + object.addProperty(*cdProperty); + + //-- Put object back in world if it was originally there. + if (shouldBeInWorld) + object.addToWorld(); + + //-- Fetch the CustomizationData instance + CustomizationData *const customizationData = cdProperty->fetchCustomizationData(); + if (customizationData) + { + //-- Create customization variables associated with this appearance. Don't skip /shared_owner/ + // variables since we are a creature. The SharedTangibleObjectTemplate version of + // this function sets it to true. + bool const skipSharedOwnerVariables = false; + AssetCustomizationManager::addCustomizationVariablesForAsset(TemporaryCrcString(getAppearanceFilename().c_str(), true), *customizationData, skipSharedOwnerVariables); + + //-- set up mappings for any variables which need dependent mappings + int numVariableMappings = getCustomizationVariableMappingCount(); + for (int i = 0; i < numVariableMappings; ++i) + { + CustomizationVariableMapping localVariableMapping; + getCustomizationVariableMapping(localVariableMapping, i); + GlobalRangedIntCustomizationVariableType *source = safe_cast(customizationData->findVariable(localVariableMapping.sourceVariable)); + if(source) + { + source->setDependentVariable(localVariableMapping.dependentVariable); + } + } + + //-- release local reference to the CustomizationData instance + customizationData->release(); + } +} + +// ---------------------------------------------------------------------- + +//@BEGIN TFD +SharedCreatureObjectTemplate::Gender SharedCreatureObjectTemplate::getGender(bool testData) const +{ +#ifdef _DEBUG +SharedCreatureObjectTemplate::Gender testDataValue = static_cast(0); +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getGender(true); +#endif + } + + if (!m_gender.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter gender in template %s", DataResource::getName())); + return static_cast(0); + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter gender has not been defined in template %s!", DataResource::getName())); + return base->getGender(); + } + } + + Gender value = static_cast(m_gender.getValue()); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getGender + +SharedCreatureObjectTemplate::Niche SharedCreatureObjectTemplate::getNiche(bool testData) const +{ +#ifdef _DEBUG +SharedCreatureObjectTemplate::Niche testDataValue = static_cast(0); +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getNiche(true); +#endif + } + + if (!m_niche.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter niche in template %s", DataResource::getName())); + return static_cast(0); + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter niche has not been defined in template %s!", DataResource::getName())); + return base->getNiche(); + } + } + + Niche value = static_cast(m_niche.getValue()); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getNiche + +SharedCreatureObjectTemplate::Species SharedCreatureObjectTemplate::getSpecies(bool testData) const +{ +#ifdef _DEBUG +SharedCreatureObjectTemplate::Species testDataValue = static_cast(0); +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSpecies(true); +#endif + } + + if (!m_species.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter species in template %s", DataResource::getName())); + return static_cast(0); + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter species has not been defined in template %s!", DataResource::getName())); + return base->getSpecies(); + } + } + + Species value = static_cast(m_species.getValue()); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getSpecies + +SharedCreatureObjectTemplate::Race SharedCreatureObjectTemplate::getRace(bool testData) const +{ +#ifdef _DEBUG +SharedCreatureObjectTemplate::Race testDataValue = static_cast(0); +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getRace(true); +#endif + } + + if (!m_race.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter race in template %s", DataResource::getName())); + return static_cast(0); + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter race has not been defined in template %s!", DataResource::getName())); + return base->getRace(); + } + } + + Race value = static_cast(m_race.getValue()); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getRace + +float SharedCreatureObjectTemplate::getAcceleration(MovementTypes index) const +{ + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + DEBUG_FATAL(index < 0 || index >= 2, ("template param index out of range")); + if (!m_acceleration[index].isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter acceleration in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter acceleration has not been defined in template %s!", DataResource::getName())); + return base->getAcceleration(index); + } + } + + float value = m_acceleration[index].getValue(); + char delta = m_acceleration[index].getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getAcceleration(index); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } + return value; +} // SharedCreatureObjectTemplate::getAcceleration + +float SharedCreatureObjectTemplate::getAccelerationMin(MovementTypes index) const +{ + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + DEBUG_FATAL(index < 0 || index >= 2, ("template param index out of range")); + if (!m_acceleration[index].isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter acceleration in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter acceleration has not been defined in template %s!", DataResource::getName())); + return base->getAccelerationMin(index); + } + } + + float value = m_acceleration[index].getMinValue(); + char delta = m_acceleration[index].getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getAccelerationMin(index); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } + return value; +} // SharedCreatureObjectTemplate::getAccelerationMin + +float SharedCreatureObjectTemplate::getAccelerationMax(MovementTypes index) const +{ + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + DEBUG_FATAL(index < 0 || index >= 2, ("template param index out of range")); + if (!m_acceleration[index].isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter acceleration in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter acceleration has not been defined in template %s!", DataResource::getName())); + return base->getAccelerationMax(index); + } + } + + float value = m_acceleration[index].getMaxValue(); + char delta = m_acceleration[index].getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getAccelerationMax(index); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } + return value; +} // SharedCreatureObjectTemplate::getAccelerationMax + +float SharedCreatureObjectTemplate::getSpeed(MovementTypes index) const +{ + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + DEBUG_FATAL(index < 0 || index >= 2, ("template param index out of range")); + if (!m_speed[index].isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter speed in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter speed has not been defined in template %s!", DataResource::getName())); + return base->getSpeed(index); + } + } + + float value = m_speed[index].getValue(); + char delta = m_speed[index].getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSpeed(index); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } + return value; +} // SharedCreatureObjectTemplate::getSpeed + +float SharedCreatureObjectTemplate::getSpeedMin(MovementTypes index) const +{ + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + DEBUG_FATAL(index < 0 || index >= 2, ("template param index out of range")); + if (!m_speed[index].isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter speed in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter speed has not been defined in template %s!", DataResource::getName())); + return base->getSpeedMin(index); + } + } + + float value = m_speed[index].getMinValue(); + char delta = m_speed[index].getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSpeedMin(index); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } + return value; +} // SharedCreatureObjectTemplate::getSpeedMin + +float SharedCreatureObjectTemplate::getSpeedMax(MovementTypes index) const +{ + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + DEBUG_FATAL(index < 0 || index >= 2, ("template param index out of range")); + if (!m_speed[index].isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter speed in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter speed has not been defined in template %s!", DataResource::getName())); + return base->getSpeedMax(index); + } + } + + float value = m_speed[index].getMaxValue(); + char delta = m_speed[index].getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSpeedMax(index); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } + return value; +} // SharedCreatureObjectTemplate::getSpeedMax + +float SharedCreatureObjectTemplate::getTurnRate(MovementTypes index) const +{ + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + DEBUG_FATAL(index < 0 || index >= 2, ("template param index out of range")); + if (!m_turnRate[index].isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter turnRate in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter turnRate has not been defined in template %s!", DataResource::getName())); + return base->getTurnRate(index); + } + } + + float value = m_turnRate[index].getValue(); + char delta = m_turnRate[index].getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getTurnRate(index); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } + return value; +} // SharedCreatureObjectTemplate::getTurnRate + +float SharedCreatureObjectTemplate::getTurnRateMin(MovementTypes index) const +{ + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + DEBUG_FATAL(index < 0 || index >= 2, ("template param index out of range")); + if (!m_turnRate[index].isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter turnRate in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter turnRate has not been defined in template %s!", DataResource::getName())); + return base->getTurnRateMin(index); + } + } + + float value = m_turnRate[index].getMinValue(); + char delta = m_turnRate[index].getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getTurnRateMin(index); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } + return value; +} // SharedCreatureObjectTemplate::getTurnRateMin + +float SharedCreatureObjectTemplate::getTurnRateMax(MovementTypes index) const +{ + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + DEBUG_FATAL(index < 0 || index >= 2, ("template param index out of range")); + if (!m_turnRate[index].isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter turnRate in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter turnRate has not been defined in template %s!", DataResource::getName())); + return base->getTurnRateMax(index); + } + } + + float value = m_turnRate[index].getMaxValue(); + char delta = m_turnRate[index].getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getTurnRateMax(index); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } + return value; +} // SharedCreatureObjectTemplate::getTurnRateMax + +const std::string & SharedCreatureObjectTemplate::getAnimationMapFilename(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getAnimationMapFilename(true); +#endif + } + + if (!m_animationMapFilename.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter animationMapFilename in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter animationMapFilename has not been defined in template %s!", DataResource::getName())); + return base->getAnimationMapFilename(); + } + } + + const std::string & value = m_animationMapFilename.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getAnimationMapFilename + +float SharedCreatureObjectTemplate::getSlopeModAngle(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSlopeModAngle(true); +#endif + } + + if (!m_slopeModAngle.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter slopeModAngle in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter slopeModAngle has not been defined in template %s!", DataResource::getName())); + return base->getSlopeModAngle(); + } + } + + float value = m_slopeModAngle.getValue(); + char delta = m_slopeModAngle.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSlopeModAngle(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getSlopeModAngle + +float SharedCreatureObjectTemplate::getSlopeModAngleMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSlopeModAngleMin(true); +#endif + } + + if (!m_slopeModAngle.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter slopeModAngle in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter slopeModAngle has not been defined in template %s!", DataResource::getName())); + return base->getSlopeModAngleMin(); + } + } + + float value = m_slopeModAngle.getMinValue(); + char delta = m_slopeModAngle.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSlopeModAngleMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getSlopeModAngleMin + +float SharedCreatureObjectTemplate::getSlopeModAngleMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSlopeModAngleMax(true); +#endif + } + + if (!m_slopeModAngle.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter slopeModAngle in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter slopeModAngle has not been defined in template %s!", DataResource::getName())); + return base->getSlopeModAngleMax(); + } + } + + float value = m_slopeModAngle.getMaxValue(); + char delta = m_slopeModAngle.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSlopeModAngleMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getSlopeModAngleMax + +float SharedCreatureObjectTemplate::getSlopeModPercent(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSlopeModPercent(true); +#endif + } + + if (!m_slopeModPercent.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter slopeModPercent in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter slopeModPercent has not been defined in template %s!", DataResource::getName())); + return base->getSlopeModPercent(); + } + } + + float value = m_slopeModPercent.getValue(); + char delta = m_slopeModPercent.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSlopeModPercent(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getSlopeModPercent + +float SharedCreatureObjectTemplate::getSlopeModPercentMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSlopeModPercentMin(true); +#endif + } + + if (!m_slopeModPercent.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter slopeModPercent in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter slopeModPercent has not been defined in template %s!", DataResource::getName())); + return base->getSlopeModPercentMin(); + } + } + + float value = m_slopeModPercent.getMinValue(); + char delta = m_slopeModPercent.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSlopeModPercentMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getSlopeModPercentMin + +float SharedCreatureObjectTemplate::getSlopeModPercentMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSlopeModPercentMax(true); +#endif + } + + if (!m_slopeModPercent.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter slopeModPercent in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter slopeModPercent has not been defined in template %s!", DataResource::getName())); + return base->getSlopeModPercentMax(); + } + } + + float value = m_slopeModPercent.getMaxValue(); + char delta = m_slopeModPercent.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSlopeModPercentMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getSlopeModPercentMax + +float SharedCreatureObjectTemplate::getWaterModPercent(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getWaterModPercent(true); +#endif + } + + if (!m_waterModPercent.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter waterModPercent in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter waterModPercent has not been defined in template %s!", DataResource::getName())); + return base->getWaterModPercent(); + } + } + + float value = m_waterModPercent.getValue(); + char delta = m_waterModPercent.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getWaterModPercent(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getWaterModPercent + +float SharedCreatureObjectTemplate::getWaterModPercentMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getWaterModPercentMin(true); +#endif + } + + if (!m_waterModPercent.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter waterModPercent in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter waterModPercent has not been defined in template %s!", DataResource::getName())); + return base->getWaterModPercentMin(); + } + } + + float value = m_waterModPercent.getMinValue(); + char delta = m_waterModPercent.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getWaterModPercentMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getWaterModPercentMin + +float SharedCreatureObjectTemplate::getWaterModPercentMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getWaterModPercentMax(true); +#endif + } + + if (!m_waterModPercent.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter waterModPercent in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter waterModPercent has not been defined in template %s!", DataResource::getName())); + return base->getWaterModPercentMax(); + } + } + + float value = m_waterModPercent.getMaxValue(); + char delta = m_waterModPercent.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getWaterModPercentMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getWaterModPercentMax + +float SharedCreatureObjectTemplate::getStepHeight(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getStepHeight(true); +#endif + } + + if (!m_stepHeight.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter stepHeight in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter stepHeight has not been defined in template %s!", DataResource::getName())); + return base->getStepHeight(); + } + } + + float value = m_stepHeight.getValue(); + char delta = m_stepHeight.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getStepHeight(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getStepHeight + +float SharedCreatureObjectTemplate::getStepHeightMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getStepHeightMin(true); +#endif + } + + if (!m_stepHeight.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter stepHeight in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter stepHeight has not been defined in template %s!", DataResource::getName())); + return base->getStepHeightMin(); + } + } + + float value = m_stepHeight.getMinValue(); + char delta = m_stepHeight.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getStepHeightMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getStepHeightMin + +float SharedCreatureObjectTemplate::getStepHeightMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getStepHeightMax(true); +#endif + } + + if (!m_stepHeight.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter stepHeight in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter stepHeight has not been defined in template %s!", DataResource::getName())); + return base->getStepHeightMax(); + } + } + + float value = m_stepHeight.getMaxValue(); + char delta = m_stepHeight.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getStepHeightMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getStepHeightMax + +float SharedCreatureObjectTemplate::getCollisionHeight(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCollisionHeight(true); +#endif + } + + if (!m_collisionHeight.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter collisionHeight in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter collisionHeight has not been defined in template %s!", DataResource::getName())); + return base->getCollisionHeight(); + } + } + + float value = m_collisionHeight.getValue(); + char delta = m_collisionHeight.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCollisionHeight(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCollisionHeight + +float SharedCreatureObjectTemplate::getCollisionHeightMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCollisionHeightMin(true); +#endif + } + + if (!m_collisionHeight.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter collisionHeight in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter collisionHeight has not been defined in template %s!", DataResource::getName())); + return base->getCollisionHeightMin(); + } + } + + float value = m_collisionHeight.getMinValue(); + char delta = m_collisionHeight.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCollisionHeightMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCollisionHeightMin + +float SharedCreatureObjectTemplate::getCollisionHeightMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCollisionHeightMax(true); +#endif + } + + if (!m_collisionHeight.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter collisionHeight in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter collisionHeight has not been defined in template %s!", DataResource::getName())); + return base->getCollisionHeightMax(); + } + } + + float value = m_collisionHeight.getMaxValue(); + char delta = m_collisionHeight.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCollisionHeightMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCollisionHeightMax + +float SharedCreatureObjectTemplate::getCollisionRadius(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCollisionRadius(true); +#endif + } + + if (!m_collisionRadius.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter collisionRadius in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter collisionRadius has not been defined in template %s!", DataResource::getName())); + return base->getCollisionRadius(); + } + } + + float value = m_collisionRadius.getValue(); + char delta = m_collisionRadius.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCollisionRadius(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCollisionRadius + +float SharedCreatureObjectTemplate::getCollisionRadiusMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCollisionRadiusMin(true); +#endif + } + + if (!m_collisionRadius.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter collisionRadius in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter collisionRadius has not been defined in template %s!", DataResource::getName())); + return base->getCollisionRadiusMin(); + } + } + + float value = m_collisionRadius.getMinValue(); + char delta = m_collisionRadius.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCollisionRadiusMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCollisionRadiusMin + +float SharedCreatureObjectTemplate::getCollisionRadiusMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCollisionRadiusMax(true); +#endif + } + + if (!m_collisionRadius.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter collisionRadius in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter collisionRadius has not been defined in template %s!", DataResource::getName())); + return base->getCollisionRadiusMax(); + } + } + + float value = m_collisionRadius.getMaxValue(); + char delta = m_collisionRadius.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCollisionRadiusMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCollisionRadiusMax + +const std::string & SharedCreatureObjectTemplate::getMovementDatatable(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getMovementDatatable(true); +#endif + } + + if (!m_movementDatatable.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter movementDatatable in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter movementDatatable has not been defined in template %s!", DataResource::getName())); + return base->getMovementDatatable(); + } + } + + const std::string & value = m_movementDatatable.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getMovementDatatable + +bool SharedCreatureObjectTemplate::getPostureAlignToTerrain(Postures index) const +{ + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + DEBUG_FATAL(index < 0 || index >= 15, ("template param index out of range")); + if (!m_postureAlignToTerrain[index].isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter postureAlignToTerrain in template %s", DataResource::getName())); + return false; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter postureAlignToTerrain has not been defined in template %s!", DataResource::getName())); + return base->getPostureAlignToTerrain(index); + } + } + + bool value = m_postureAlignToTerrain[index].getValue(); + return value; +} // SharedCreatureObjectTemplate::getPostureAlignToTerrain + +float SharedCreatureObjectTemplate::getSwimHeight(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSwimHeight(true); +#endif + } + + if (!m_swimHeight.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter swimHeight in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter swimHeight has not been defined in template %s!", DataResource::getName())); + return base->getSwimHeight(); + } + } + + float value = m_swimHeight.getValue(); + char delta = m_swimHeight.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSwimHeight(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getSwimHeight + +float SharedCreatureObjectTemplate::getSwimHeightMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSwimHeightMin(true); +#endif + } + + if (!m_swimHeight.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter swimHeight in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter swimHeight has not been defined in template %s!", DataResource::getName())); + return base->getSwimHeightMin(); + } + } + + float value = m_swimHeight.getMinValue(); + char delta = m_swimHeight.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSwimHeightMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getSwimHeightMin + +float SharedCreatureObjectTemplate::getSwimHeightMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSwimHeightMax(true); +#endif + } + + if (!m_swimHeight.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter swimHeight in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter swimHeight has not been defined in template %s!", DataResource::getName())); + return base->getSwimHeightMax(); + } + } + + float value = m_swimHeight.getMaxValue(); + char delta = m_swimHeight.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSwimHeightMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getSwimHeightMax + +float SharedCreatureObjectTemplate::getWarpTolerance(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getWarpTolerance(true); +#endif + } + + if (!m_warpTolerance.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter warpTolerance in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter warpTolerance has not been defined in template %s!", DataResource::getName())); + return base->getWarpTolerance(); + } + } + + float value = m_warpTolerance.getValue(); + char delta = m_warpTolerance.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getWarpTolerance(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getWarpTolerance + +float SharedCreatureObjectTemplate::getWarpToleranceMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getWarpToleranceMin(true); +#endif + } + + if (!m_warpTolerance.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter warpTolerance in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter warpTolerance has not been defined in template %s!", DataResource::getName())); + return base->getWarpToleranceMin(); + } + } + + float value = m_warpTolerance.getMinValue(); + char delta = m_warpTolerance.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getWarpToleranceMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getWarpToleranceMin + +float SharedCreatureObjectTemplate::getWarpToleranceMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getWarpToleranceMax(true); +#endif + } + + if (!m_warpTolerance.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter warpTolerance in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter warpTolerance has not been defined in template %s!", DataResource::getName())); + return base->getWarpToleranceMax(); + } + } + + float value = m_warpTolerance.getMaxValue(); + char delta = m_warpTolerance.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getWarpToleranceMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getWarpToleranceMax + +float SharedCreatureObjectTemplate::getCollisionOffsetX(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCollisionOffsetX(true); +#endif + } + + if (!m_collisionOffsetX.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter collisionOffsetX in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter collisionOffsetX has not been defined in template %s!", DataResource::getName())); + return base->getCollisionOffsetX(); + } + } + + float value = m_collisionOffsetX.getValue(); + char delta = m_collisionOffsetX.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCollisionOffsetX(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCollisionOffsetX + +float SharedCreatureObjectTemplate::getCollisionOffsetXMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCollisionOffsetXMin(true); +#endif + } + + if (!m_collisionOffsetX.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter collisionOffsetX in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter collisionOffsetX has not been defined in template %s!", DataResource::getName())); + return base->getCollisionOffsetXMin(); + } + } + + float value = m_collisionOffsetX.getMinValue(); + char delta = m_collisionOffsetX.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCollisionOffsetXMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCollisionOffsetXMin + +float SharedCreatureObjectTemplate::getCollisionOffsetXMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCollisionOffsetXMax(true); +#endif + } + + if (!m_collisionOffsetX.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter collisionOffsetX in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter collisionOffsetX has not been defined in template %s!", DataResource::getName())); + return base->getCollisionOffsetXMax(); + } + } + + float value = m_collisionOffsetX.getMaxValue(); + char delta = m_collisionOffsetX.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCollisionOffsetXMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCollisionOffsetXMax + +float SharedCreatureObjectTemplate::getCollisionOffsetZ(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCollisionOffsetZ(true); +#endif + } + + if (!m_collisionOffsetZ.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter collisionOffsetZ in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter collisionOffsetZ has not been defined in template %s!", DataResource::getName())); + return base->getCollisionOffsetZ(); + } + } + + float value = m_collisionOffsetZ.getValue(); + char delta = m_collisionOffsetZ.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCollisionOffsetZ(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCollisionOffsetZ + +float SharedCreatureObjectTemplate::getCollisionOffsetZMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCollisionOffsetZMin(true); +#endif + } + + if (!m_collisionOffsetZ.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter collisionOffsetZ in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter collisionOffsetZ has not been defined in template %s!", DataResource::getName())); + return base->getCollisionOffsetZMin(); + } + } + + float value = m_collisionOffsetZ.getMinValue(); + char delta = m_collisionOffsetZ.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCollisionOffsetZMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCollisionOffsetZMin + +float SharedCreatureObjectTemplate::getCollisionOffsetZMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCollisionOffsetZMax(true); +#endif + } + + if (!m_collisionOffsetZ.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter collisionOffsetZ in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter collisionOffsetZ has not been defined in template %s!", DataResource::getName())); + return base->getCollisionOffsetZMax(); + } + } + + float value = m_collisionOffsetZ.getMaxValue(); + char delta = m_collisionOffsetZ.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCollisionOffsetZMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCollisionOffsetZMax + +float SharedCreatureObjectTemplate::getCollisionLength(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCollisionLength(true); +#endif + } + + if (!m_collisionLength.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter collisionLength in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter collisionLength has not been defined in template %s!", DataResource::getName())); + return base->getCollisionLength(); + } + } + + float value = m_collisionLength.getValue(); + char delta = m_collisionLength.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCollisionLength(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCollisionLength + +float SharedCreatureObjectTemplate::getCollisionLengthMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCollisionLengthMin(true); +#endif + } + + if (!m_collisionLength.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter collisionLength in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter collisionLength has not been defined in template %s!", DataResource::getName())); + return base->getCollisionLengthMin(); + } + } + + float value = m_collisionLength.getMinValue(); + char delta = m_collisionLength.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCollisionLengthMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCollisionLengthMin + +float SharedCreatureObjectTemplate::getCollisionLengthMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCollisionLengthMax(true); +#endif + } + + if (!m_collisionLength.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter collisionLength in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter collisionLength has not been defined in template %s!", DataResource::getName())); + return base->getCollisionLengthMax(); + } + } + + float value = m_collisionLength.getMaxValue(); + char delta = m_collisionLength.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCollisionLengthMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCollisionLengthMax + +float SharedCreatureObjectTemplate::getCameraHeight(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCameraHeight(true); +#endif + } + + if (!m_cameraHeight.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter cameraHeight in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter cameraHeight has not been defined in template %s!", DataResource::getName())); + return base->getCameraHeight(); + } + } + + float value = m_cameraHeight.getValue(); + char delta = m_cameraHeight.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCameraHeight(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCameraHeight + +float SharedCreatureObjectTemplate::getCameraHeightMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCameraHeightMin(true); +#endif + } + + if (!m_cameraHeight.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter cameraHeight in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter cameraHeight has not been defined in template %s!", DataResource::getName())); + return base->getCameraHeightMin(); + } + } + + float value = m_cameraHeight.getMinValue(); + char delta = m_cameraHeight.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCameraHeightMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCameraHeightMin + +float SharedCreatureObjectTemplate::getCameraHeightMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedCreatureObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCameraHeightMax(true); +#endif + } + + if (!m_cameraHeight.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter cameraHeight in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter cameraHeight has not been defined in template %s!", DataResource::getName())); + return base->getCameraHeightMax(); + } + } + + float value = m_cameraHeight.getMaxValue(); + char delta = m_cameraHeight.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCameraHeightMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedCreatureObjectTemplate::getCameraHeightMax + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedCreatureObjectTemplate::testValues(void) const +{ + IGNORE_RETURN(getGender(true)); + IGNORE_RETURN(getNiche(true)); + IGNORE_RETURN(getSpecies(true)); + IGNORE_RETURN(getRace(true)); + IGNORE_RETURN(getAnimationMapFilename(true)); + IGNORE_RETURN(getSlopeModAngleMin(true)); + IGNORE_RETURN(getSlopeModAngleMax(true)); + IGNORE_RETURN(getSlopeModPercentMin(true)); + IGNORE_RETURN(getSlopeModPercentMax(true)); + IGNORE_RETURN(getWaterModPercentMin(true)); + IGNORE_RETURN(getWaterModPercentMax(true)); + IGNORE_RETURN(getStepHeightMin(true)); + IGNORE_RETURN(getStepHeightMax(true)); + IGNORE_RETURN(getCollisionHeightMin(true)); + IGNORE_RETURN(getCollisionHeightMax(true)); + IGNORE_RETURN(getCollisionRadiusMin(true)); + IGNORE_RETURN(getCollisionRadiusMax(true)); + IGNORE_RETURN(getMovementDatatable(true)); + IGNORE_RETURN(getSwimHeightMin(true)); + IGNORE_RETURN(getSwimHeightMax(true)); + IGNORE_RETURN(getWarpToleranceMin(true)); + IGNORE_RETURN(getWarpToleranceMax(true)); + IGNORE_RETURN(getCollisionOffsetXMin(true)); + IGNORE_RETURN(getCollisionOffsetXMax(true)); + IGNORE_RETURN(getCollisionOffsetZMin(true)); + IGNORE_RETURN(getCollisionOffsetZMax(true)); + IGNORE_RETURN(getCollisionLengthMin(true)); + IGNORE_RETURN(getCollisionLengthMax(true)); + IGNORE_RETURN(getCameraHeightMin(true)); + IGNORE_RETURN(getCameraHeightMax(true)); + SharedTangibleObjectTemplate::testValues(); +} // SharedCreatureObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedCreatureObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedCreatureObjectTemplate_tag) + { + SharedTangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,1,3)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "gender") == 0) + m_gender.loadFromIff(file); + else if (strcmp(paramName, "niche") == 0) + m_niche.loadFromIff(file); + else if (strcmp(paramName, "species") == 0) + m_species.loadFromIff(file); + else if (strcmp(paramName, "race") == 0) + m_race.loadFromIff(file); + else if (strcmp(paramName, "acceleration") == 0) + { + int listCount = file.read_int32(); + DEBUG_WARNING(listCount != 2, ("Template %s: read array size of %d for array \"acceleration\" of size 2, reading values anyway", file.getFileName(), listCount)); + int j; + for (j = 0; j < 2 && j < listCount; ++j) + m_acceleration[j].loadFromIff(file); + // if there are more params for acceleration read and dump them + for (; j < listCount; ++j) + { + FloatParam dummy; + dummy.loadFromIff(file); + } + } + else if (strcmp(paramName, "speed") == 0) + { + int listCount = file.read_int32(); + DEBUG_WARNING(listCount != 2, ("Template %s: read array size of %d for array \"speed\" of size 2, reading values anyway", file.getFileName(), listCount)); + int j; + for (j = 0; j < 2 && j < listCount; ++j) + m_speed[j].loadFromIff(file); + // if there are more params for speed read and dump them + for (; j < listCount; ++j) + { + FloatParam dummy; + dummy.loadFromIff(file); + } + } + else if (strcmp(paramName, "turnRate") == 0) + { + int listCount = file.read_int32(); + DEBUG_WARNING(listCount != 2, ("Template %s: read array size of %d for array \"turnRate\" of size 2, reading values anyway", file.getFileName(), listCount)); + int j; + for (j = 0; j < 2 && j < listCount; ++j) + m_turnRate[j].loadFromIff(file); + // if there are more params for turnRate read and dump them + for (; j < listCount; ++j) + { + FloatParam dummy; + dummy.loadFromIff(file); + } + } + else if (strcmp(paramName, "animationMapFilename") == 0) + m_animationMapFilename.loadFromIff(file); + else if (strcmp(paramName, "slopeModAngle") == 0) + m_slopeModAngle.loadFromIff(file); + else if (strcmp(paramName, "slopeModPercent") == 0) + m_slopeModPercent.loadFromIff(file); + else if (strcmp(paramName, "waterModPercent") == 0) + m_waterModPercent.loadFromIff(file); + else if (strcmp(paramName, "stepHeight") == 0) + m_stepHeight.loadFromIff(file); + else if (strcmp(paramName, "collisionHeight") == 0) + m_collisionHeight.loadFromIff(file); + else if (strcmp(paramName, "collisionRadius") == 0) + m_collisionRadius.loadFromIff(file); + else if (strcmp(paramName, "movementDatatable") == 0) + m_movementDatatable.loadFromIff(file); + else if (strcmp(paramName, "postureAlignToTerrain") == 0) + { + int listCount = file.read_int32(); + DEBUG_WARNING(listCount != 15, ("Template %s: read array size of %d for array \"postureAlignToTerrain\" of size 15, reading values anyway", file.getFileName(), listCount)); + int j; + for (j = 0; j < 15 && j < listCount; ++j) + m_postureAlignToTerrain[j].loadFromIff(file); + // if there are more params for postureAlignToTerrain read and dump them + for (; j < listCount; ++j) + { + BoolParam dummy; + dummy.loadFromIff(file); + } + } + else if (strcmp(paramName, "swimHeight") == 0) + m_swimHeight.loadFromIff(file); + else if (strcmp(paramName, "warpTolerance") == 0) + m_warpTolerance.loadFromIff(file); + else if (strcmp(paramName, "collisionOffsetX") == 0) + m_collisionOffsetX.loadFromIff(file); + else if (strcmp(paramName, "collisionOffsetZ") == 0) + m_collisionOffsetZ.loadFromIff(file); + else if (strcmp(paramName, "collisionLength") == 0) + m_collisionLength.loadFromIff(file); + else if (strcmp(paramName, "cameraHeight") == 0) + m_cameraHeight.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + SharedTangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedCreatureObjectTemplate::load + +//@END TFD + diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedCreatureObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedCreatureObjectTemplate.h new file mode 100644 index 00000000..53645aa7 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedCreatureObjectTemplate.h @@ -0,0 +1,479 @@ +//======================================================================== +// +// SharedCreatureObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedCreatureObjectTemplate_H +#define _INCLUDED_SharedCreatureObjectTemplate_H + +#include "SharedTangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +class MovementTable; + +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedCreatureObjectTemplate : public SharedTangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedCreatureObjectTemplate_tag = TAG(S,C,O,T) + }; +//@END TFD ID +public: + SharedCreatureObjectTemplate(const std::string & filename); + virtual ~SharedCreatureObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + + void postLoad(); + virtual void createCustomizationDataPropertyAsNeeded(Object &object, bool forceCreation = false) const; + + const MovementTable * getMovementTable() const; + +//@BEGIN TFD +public: + enum Gender + { + GE_male, + GE_female, + GE_other, + Gender_Last = GE_other, + }; + + enum MovementTypes + { + MT_run, + MT_walk, + MovementTypes_Last = MT_walk, + }; + + enum Niche + { + NI_none = 0, + NI_pc = 1, + NI_ai = 2, + NI_droid = 3, + NI_vehicle = 4, + NI_npc = 5, + NI_monster = 6, + NI_herbivore = 7, + NI_carnivore = 8, + NI_predator = 9, + NI_android = 10, + Niche_Last = NI_android, + }; + + enum Postures + { + Upright = 0, + Crouched = 1, + Prone = 2, + Sneaking = 3, + Blocking = 4, + Climbing = 5, + Flying = 6, + LyingDown = 7, + Sitting = 8, + SkillAnimating = 9, + DrivingVehicle = 10, + RidingCreature = 11, + KnockedDown = 12, + Incapacitated = 13, + Dead = 14, + Postures_Last = Dead, + }; + + enum Race + { + RA_none, + RA_aqualish_quara = 1, + RA_aqualish_aquala = 2, + RA_ewok_ewok = 1, // // plae, green, black, white (subject to change, pending information request to LucasArts) + RA_ewok_dulok = 2, // // blue skin; "Orn Free Taa", "Ann Gella" & "Tann", Sebulba's personal entourage. + RA_ewok_jinda = 3, // // red skin; "Pampy" & "Supi", consorts of Orn Free Taa. + RA_gungan_ankura = 1, // // Boss Nass + RA_gungan_otolla = 2, // // Jar Jar + RA_nikto_red = 1, // // Kajain'sa'Nikto + RA_nikto_green = 2, // // Kadas'sa'Nikto + RA_nikto_mountain = 3, // // Esral'sa'Nikto + RA_nikto_pale = 4, // // Gluss'sa'Nikto + RA_nikto_southern = 5, // // M'shento'su'Nikto + RA_krayt_canyon = 1, + RA_krayt_greater = 2, + RA_R2 = 0, + RA_R3 = 1, + RA_R4 = 2, + RA_R5 = 3, + Race_Last = RA_R5, + }; + + enum Species + { + SP_human = 0, + SP_rodian = 1, + SP_trandoshan = 2, + SP_monCalamari = 3, + SP_wookiee = 4, + SP_bothan = 5, + SP_twilek = 6, + SP_zabrak = 7, + SP_abyssin = 8, + SP_aqualish = 9, + SP_arcona = 10, + SP_askajian = 11, + SP_bith = 12, + SP_bomarrMonk = 13, + SP_chadraFan = 14, + SP_chevin = 15, + SP_dantari = 16, + SP_devaronian = 17, + SP_drall = 18, + SP_dug = 19, + SP_duros = 20, + SP_elomin = 21, + SP_ewok = 22, + SP_feeorin = 23, + SP_frogDog = 24, + SP_gamorrean = 25, + SP_gorax = 26, + SP_gotal = 27, + SP_gran = 28, + SP_gungan = 29, + SP_gupin = 30, + SP_hutt = 31, + SP_ishiTib = 32, + SP_ithorian = 33, + SP_jawa = 34, + SP_kiffu = 35, + SP_kitonak = 36, + SP_klatooinian = 37, + SP_kowakianMonkeyLizard = 38, + SP_kubaz = 39, + SP_marauder = 40, + SP_massassiWarrior = 41, + SP_nikto = 42, + SP_ortolan = 43, + SP_palowick = 44, + SP_phlog = 45, + SP_quarren = 46, + SP_selonian = 47, + SP_shistavanen = 48, + SP_sullustan = 49, + SP_talz = 50, + SP_teek = 51, + SP_tulgah = 52, + SP_toydarian = 53, + SP_tuskenRaider = 54, + SP_weequay = 55, + SP_whiffid = 56, + SP_wistie = 57, + SP_yuzzum = 58, + SP_angler = 60, + SP_bageraset = 61, + SP_bantha = 62, + SP_barkMite = 63, + SP_bazNitch = 64, + SP_beardedJax = 65, + SP_blackfish = 66, + SP_blistmok = 67, + SP_bluefish = 68, + SP_blurrg = 69, + SP_boarWolf = 70, + SP_bocatt = 71, + SP_bol = 72, + SP_bolleBol = 73, + SP_bolma = 74, + SP_bordok = 75, + SP_borgle = 76, + SP_brackaset = 77, + SP_capperSpineflap = 78, + SP_carrionSpat = 79, + SP_choku = 80, + SP_chuba = 81, + SP_coloClawFish = 82, + SP_condorDragon = 83, + SP_corellianSandPanther = 84, + SP_corellianSliceHound = 85, + SP_crownedRasp = 86, + SP_crystalSnake = 87, + SP_cuPa = 88, + SP_dalyrake = 89, + SP_dewback = 90, + SP_duneLizard = 91, + SP_durni = 92, + SP_dwarfNuna = 93, + SP_eopie = 94, + SP_faa = 95, + SP_falumpaset = 96, + SP_fambaa = 97, + SP_fannedRawl = 98, + SP_flewt = 99, + SP_flit = 100, + SP_fliteRasp = 101, + SP_fynock = 102, + SP_gackleBat = 103, + SP_gapingSpider = 104, + SP_gekk = 105, + SP_gnort = 106, + SP_graul = 107, + SP_greatGrassPlainsTuskCat = 108, + SP_gronda = 109, + SP_gualama = 110, + SP_gubbur = 111, + SP_gufDrolg = 112, + SP_gulginaw = 113, + SP_gurk = 114, + SP_gurnaset = 115, + SP_gurrek = 116, + SP_hanadak = 117, + SP_hermitSpider = 118, + SP_hornedKrevol = 119, + SP_hornedRasp = 120, + SP_hufDun = 121, + SP_huurton = 122, + SP_ikopi = 123, + SP_jellyfish = 124, + SP_kaadu = 125, + SP_kaitok = 126, + SP_kima = 127, + SP_kimogila = 128, + SP_kittle = 129, + SP_kliknik = 130, + SP_krahbu = 131, + SP_kraytDragon = 132, + SP_kupernug = 133, + SP_kusak = 134, + SP_kwi = 135, + SP_laa = 136, + SP_langlatch = 137, + SP_lanternBird = 138, + SP_malkloc = 139, + SP_mamien = 140, + SP_mawgax = 141, + SP_merek = 142, + SP_mott = 143, + SP_murra = 144, + SP_mynock = 145, + SP_narglatch = 146, + SP_nerf = 147, + SP_nuna = 148, + SP_opeeSeaKiller = 149, + SP_predatorialButterfly = 150, + SP_pekoPeko = 151, + SP_perlek = 152, + SP_pharple = 153, + SP_piket = 154, + SP_plumedRasp = 155, + SP_pufferfish = 156, + SP_pugoriss = 157, + SP_purbole = 158, + SP_quenker = 159, + SP_qurvel = 160, + SP_rancor = 161, + SP_ray = 162, + SP_remmer = 163, + SP_reptilianFlyer = 164, + SP_roba = 165, + SP_rockMite = 166, + SP_ronto = 167, + SP_saltMynock = 168, + SP_sarlacc = 169, + SP_scurrier = 170, + SP_sharnaff = 171, + SP_shaupaut = 172, + SP_shearMite = 173, + SP_skreeg = 174, + SP_snorbal = 175, + SP_spinedPuc = 176, + SP_spinedSnake = 177, + SP_squall = 178, + SP_squill = 179, + SP_stintaril = 180, + SP_stripedFish = 181, + SP_swirlProng = 182, + SP_tancMite = 183, + SP_taunTaun = 184, + SP_tesselatedArborealBinjinphant = 185, + SP_thune = 186, + SP_torton = 187, + SP_tybis = 188, + SP_veermok = 189, + SP_verne = 190, + SP_vesp = 191, + SP_virVur = 192, + SP_vlutore = 193, + SP_vogEel = 194, + SP_voritorLizard = 195, + SP_vynock = 196, + SP_whisperBird = 197, + SP_wingedOrnith = 198, + SP_wompRat = 199, + SP_woolamander = 200, + SP_worrt = 201, + SP_zuccaBoar = 202, + SP_assassinDroid = 203, + SP_astromech = 204, + SP_bartenderDroid = 205, + SP_bugDroid = 206, + SP_darktrooper = 207, + SP_demolitionmech = 208, + SP_doorDroid = 209, + SP_droideka = 210, + SP_interrogator = 211, + SP_jediTrainer = 212, + SP_loadLifter = 213, + SP_mouseDroid = 214, + SP_powerDroid = 215, + SP_probot = 216, + SP_protocolDroid = 217, + SP_repairDroid = 218, + SP_spiderDroid = 219, + SP_surgicalDroid = 220, + SP_tattletaleDroid = 221, + SP_trackerDroid = 222, + SP_treadwell = 223, + SP_ev9d9 = 224, + SP_maulProbeDroid = 225, + SP_atst = 226, + SP_atat = 227, + SP_geonosian = 228, + SP_veractyle = 229, + Species_Last = SP_veractyle, + }; + +public: + Gender getGender(bool testData = false) const; + Niche getNiche(bool testData = false) const; + Species getSpecies(bool testData = false) const; + Race getRace(bool testData = false) const; + float getAcceleration(MovementTypes index) const; + float getAccelerationMin(MovementTypes index) const; + float getAccelerationMax(MovementTypes index) const; + float getSpeed(MovementTypes index) const; + float getSpeedMin(MovementTypes index) const; + float getSpeedMax(MovementTypes index) const; + float getTurnRate(MovementTypes index) const; + float getTurnRateMin(MovementTypes index) const; + float getTurnRateMax(MovementTypes index) const; + const std::string & getAnimationMapFilename(bool testData = false) const; + float getSlopeModAngle(bool testData = false) const; + float getSlopeModAngleMin(bool testData = false) const; + float getSlopeModAngleMax(bool testData = false) const; + float getSlopeModPercent(bool testData = false) const; + float getSlopeModPercentMin(bool testData = false) const; + float getSlopeModPercentMax(bool testData = false) const; + float getWaterModPercent(bool testData = false) const; + float getWaterModPercentMin(bool testData = false) const; + float getWaterModPercentMax(bool testData = false) const; + float getStepHeight(bool testData = false) const; + float getStepHeightMin(bool testData = false) const; + float getStepHeightMax(bool testData = false) const; + float getCollisionHeight(bool testData = false) const; + float getCollisionHeightMin(bool testData = false) const; + float getCollisionHeightMax(bool testData = false) const; + float getCollisionRadius(bool testData = false) const; + float getCollisionRadiusMin(bool testData = false) const; + float getCollisionRadiusMax(bool testData = false) const; + const std::string & getMovementDatatable(bool testData = false) const; + bool getPostureAlignToTerrain(Postures index) const; + float getSwimHeight(bool testData = false) const; + float getSwimHeightMin(bool testData = false) const; + float getSwimHeightMax(bool testData = false) const; + float getWarpTolerance(bool testData = false) const; + float getWarpToleranceMin(bool testData = false) const; + float getWarpToleranceMax(bool testData = false) const; + float getCollisionOffsetX(bool testData = false) const; + float getCollisionOffsetXMin(bool testData = false) const; + float getCollisionOffsetXMax(bool testData = false) const; + float getCollisionOffsetZ(bool testData = false) const; + float getCollisionOffsetZMin(bool testData = false) const; + float getCollisionOffsetZMax(bool testData = false) const; + float getCollisionLength(bool testData = false) const; + float getCollisionLengthMin(bool testData = false) const; + float getCollisionLengthMax(bool testData = false) const; + float getCameraHeight(bool testData = false) const; + float getCameraHeightMin(bool testData = false) const; + float getCameraHeightMax(bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + IntegerParam m_gender; // //creature gender + IntegerParam m_niche; // //creature niche + IntegerParam m_species; // //creature species + IntegerParam m_race; // //creature subspecies + FloatParam m_acceleration[2]; // //how fast the creature accelerates in m/s/s + FloatParam m_speed[2]; // //how fast the creature moves in m/s + FloatParam m_turnRate[2]; // //how fast the creature turns in deg/s + StringParam m_animationMapFilename; // //info on how to animate the creature + FloatParam m_slopeModAngle; // //the maximum slope (in degrees) the creature will scale + FloatParam m_slopeModPercent; // //the relative speed the creature travels up a vertical slope + FloatParam m_waterModPercent; // //the relative speed the creature travels in water + FloatParam m_stepHeight; // //The maximum vertical step distance for the creature + FloatParam m_collisionHeight; // //The height of the creature's collision cylinder + FloatParam m_collisionRadius; // //The radius of the creature's collision cylinder + StringParam m_movementDatatable; // //The datatable to use for creature movement + BoolParam m_postureAlignToTerrain[15]; // //align to terrain flags per posture + FloatParam m_swimHeight; // //Height below the water where the creature decides to swim + FloatParam m_warpTolerance; + FloatParam m_collisionOffsetX; // // X offset of the collision sphere + FloatParam m_collisionOffsetZ; // // Z offset of the collision sphere + FloatParam m_collisionLength; // // Length of the creature, in meters + FloatParam m_cameraHeight; +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + MovementTable * m_movementTable; + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedCreatureObjectTemplate(const SharedCreatureObjectTemplate &); + SharedCreatureObjectTemplate & operator =(const SharedCreatureObjectTemplate &); +}; + + +inline void SharedCreatureObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedCreatureObjectTemplate::registerMe(); +//@END TFD INSTALL +} + +inline const MovementTable * SharedCreatureObjectTemplate::getMovementTable() const +{ + return m_movementTable; +} + +#endif // _INCLUDED_SharedCreatureObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedDraftSchematicObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedDraftSchematicObjectTemplate.cpp new file mode 100644 index 00000000..590422aa --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedDraftSchematicObjectTemplate.cpp @@ -0,0 +1,1231 @@ +//======================================================================== +// +// SharedDraftSchematicObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedDraftSchematicObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedDraftSchematicObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedDraftSchematicObjectTemplate::SharedDraftSchematicObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedIntangibleObjectTemplate(filename) + ,m_slotsLoaded(false) + ,m_slotsAppend(false) + ,m_attributesLoaded(false) + ,m_attributesAppend(false) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedDraftSchematicObjectTemplate::SharedDraftSchematicObjectTemplate + +/** + * Class destructor. + */ +SharedDraftSchematicObjectTemplate::~SharedDraftSchematicObjectTemplate() +{ +//@BEGIN TFD CLEANUP + { + std::vector::iterator iter; + for (iter = m_slots.begin(); iter != m_slots.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_slots.clear(); + } + { + std::vector::iterator iter; + for (iter = m_attributes.begin(); iter != m_attributes.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_attributes.clear(); + } +//@END TFD CLEANUP +} // SharedDraftSchematicObjectTemplate::~SharedDraftSchematicObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedDraftSchematicObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedDraftSchematicObjectTemplate_tag, create); +} // SharedDraftSchematicObjectTemplate::registerMe + +/** + * Creates a SharedDraftSchematicObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedDraftSchematicObjectTemplate::create(const std::string & filename) +{ + return new SharedDraftSchematicObjectTemplate(filename); +} // SharedDraftSchematicObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedDraftSchematicObjectTemplate::getId(void) const +{ + return SharedDraftSchematicObjectTemplate_tag; +} // SharedDraftSchematicObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedDraftSchematicObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedDraftSchematicObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedDraftSchematicObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedDraftSchematicObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedDraftSchematicObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +void SharedDraftSchematicObjectTemplate::getSlots(IngredientSlot &data, int index) const +{ + const SharedDraftSchematicObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_slotsLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter slots in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter slots has not been defined in template %s!", DataResource::getName())); + base->getSlots(data, index); + return; + } + } + + if (m_slotsAppend && base != NULL) + { + int baseCount = base->getSlotsCount(); + if (index < baseCount) + { + base->getSlots(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_slots.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_slots[index]).getValue(); + NOT_NULL(structTemplate); + const _IngredientSlot *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.name = param->getName(m_versionOk); + data.hardpoint = param->getHardpoint(m_versionOk); +} // SharedDraftSchematicObjectTemplate::getSlots + +void SharedDraftSchematicObjectTemplate::getSlotsMin(IngredientSlot &data, int index) const +{ + const SharedDraftSchematicObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_slotsLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter slots in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter slots has not been defined in template %s!", DataResource::getName())); + base->getSlotsMin(data, index); + return; + } + } + + if (m_slotsAppend && base != NULL) + { + int baseCount = base->getSlotsCount(); + if (index < baseCount) + { + base->getSlotsMin(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_slots.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_slots[index]).getValue(); + NOT_NULL(structTemplate); + const _IngredientSlot *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.name = param->getName(m_versionOk); + data.hardpoint = param->getHardpoint(m_versionOk); +} // SharedDraftSchematicObjectTemplate::getSlotsMin + +void SharedDraftSchematicObjectTemplate::getSlotsMax(IngredientSlot &data, int index) const +{ + const SharedDraftSchematicObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_slotsLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter slots in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter slots has not been defined in template %s!", DataResource::getName())); + base->getSlotsMax(data, index); + return; + } + } + + if (m_slotsAppend && base != NULL) + { + int baseCount = base->getSlotsCount(); + if (index < baseCount) + { + base->getSlotsMax(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_slots.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_slots[index]).getValue(); + NOT_NULL(structTemplate); + const _IngredientSlot *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.name = param->getName(m_versionOk); + data.hardpoint = param->getHardpoint(m_versionOk); +} // SharedDraftSchematicObjectTemplate::getSlotsMax + +size_t SharedDraftSchematicObjectTemplate::getSlotsCount(void) const +{ + if (!m_slotsLoaded) + { + if (m_baseData == NULL) + return 0; + const SharedDraftSchematicObjectTemplate * base = dynamic_cast(m_baseData); + DEBUG_FATAL(base == NULL, ("base template wrong type")); + return base->getSlotsCount(); + } + + size_t count = m_slots.size(); + + // if we are extending our base template, add it's count + if (m_slotsAppend && m_baseData != NULL) + { + const SharedDraftSchematicObjectTemplate * base = dynamic_cast(m_baseData); + if (base != NULL) + count += base->getSlotsCount(); + } + + return count; +} // SharedDraftSchematicObjectTemplate::getSlotsCount + +void SharedDraftSchematicObjectTemplate::getAttributes(SchematicAttribute &data, int index) const +{ + const SharedDraftSchematicObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_attributesLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter attributes in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter attributes has not been defined in template %s!", DataResource::getName())); + base->getAttributes(data, index); + return; + } + } + + if (m_attributesAppend && base != NULL) + { + int baseCount = base->getAttributesCount(); + if (index < baseCount) + { + base->getAttributes(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_attributes.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_attributes[index]).getValue(); + NOT_NULL(structTemplate); + const _SchematicAttribute *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.name = param->getName(m_versionOk); + data.experiment = param->getExperiment(m_versionOk); + data.value = param->getValue(m_versionOk); +} // SharedDraftSchematicObjectTemplate::getAttributes + +void SharedDraftSchematicObjectTemplate::getAttributesMin(SchematicAttribute &data, int index) const +{ + const SharedDraftSchematicObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_attributesLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter attributes in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter attributes has not been defined in template %s!", DataResource::getName())); + base->getAttributesMin(data, index); + return; + } + } + + if (m_attributesAppend && base != NULL) + { + int baseCount = base->getAttributesCount(); + if (index < baseCount) + { + base->getAttributesMin(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_attributes.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_attributes[index]).getValue(); + NOT_NULL(structTemplate); + const _SchematicAttribute *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.name = param->getName(m_versionOk); + data.experiment = param->getExperiment(m_versionOk); + data.value = param->getValueMin(m_versionOk); +} // SharedDraftSchematicObjectTemplate::getAttributesMin + +void SharedDraftSchematicObjectTemplate::getAttributesMax(SchematicAttribute &data, int index) const +{ + const SharedDraftSchematicObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_attributesLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter attributes in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter attributes has not been defined in template %s!", DataResource::getName())); + base->getAttributesMax(data, index); + return; + } + } + + if (m_attributesAppend && base != NULL) + { + int baseCount = base->getAttributesCount(); + if (index < baseCount) + { + base->getAttributesMax(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_attributes.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_attributes[index]).getValue(); + NOT_NULL(structTemplate); + const _SchematicAttribute *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.name = param->getName(m_versionOk); + data.experiment = param->getExperiment(m_versionOk); + data.value = param->getValueMax(m_versionOk); +} // SharedDraftSchematicObjectTemplate::getAttributesMax + +size_t SharedDraftSchematicObjectTemplate::getAttributesCount(void) const +{ + if (!m_attributesLoaded) + { + if (m_baseData == NULL) + return 0; + const SharedDraftSchematicObjectTemplate * base = dynamic_cast(m_baseData); + DEBUG_FATAL(base == NULL, ("base template wrong type")); + return base->getAttributesCount(); + } + + size_t count = m_attributes.size(); + + // if we are extending our base template, add it's count + if (m_attributesAppend && m_baseData != NULL) + { + const SharedDraftSchematicObjectTemplate * base = dynamic_cast(m_baseData); + if (base != NULL) + count += base->getAttributesCount(); + } + + return count; +} // SharedDraftSchematicObjectTemplate::getAttributesCount + +const std::string & SharedDraftSchematicObjectTemplate::getCraftedSharedTemplate(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedDraftSchematicObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCraftedSharedTemplate(true); +#endif + } + + if (!m_craftedSharedTemplate.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter craftedSharedTemplate in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter craftedSharedTemplate has not been defined in template %s!", DataResource::getName())); + return base->getCraftedSharedTemplate(); + } + } + + const std::string & value = m_craftedSharedTemplate.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedDraftSchematicObjectTemplate::getCraftedSharedTemplate + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedDraftSchematicObjectTemplate::testValues(void) const +{ + IGNORE_RETURN(getCraftedSharedTemplate(true)); + SharedIntangibleObjectTemplate::testValues(); +} // SharedDraftSchematicObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedDraftSchematicObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedDraftSchematicObjectTemplate_tag) + { + SharedIntangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,3)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "slots") == 0) + { + std::vector::iterator iter; + for (iter = m_slots.begin(); iter != m_slots.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_slots.clear(); + m_slotsAppend = file.read_bool8(); + int listCount = file.read_int32(); + for (int j = 0; j < listCount; ++j) + { + StructParamOT * newData = new StructParamOT; + newData->loadFromIff(file); + m_slots.push_back(newData); + } + m_slotsLoaded = true; + } + else if (strcmp(paramName, "attributes") == 0) + { + std::vector::iterator iter; + for (iter = m_attributes.begin(); iter != m_attributes.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_attributes.clear(); + m_attributesAppend = file.read_bool8(); + int listCount = file.read_int32(); + for (int j = 0; j < listCount; ++j) + { + StructParamOT * newData = new StructParamOT; + newData->loadFromIff(file); + m_attributes.push_back(newData); + } + m_attributesLoaded = true; + } + else if (strcmp(paramName, "craftedSharedTemplate") == 0) + m_craftedSharedTemplate.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + SharedIntangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedDraftSchematicObjectTemplate::load + + +//============================================================================= +// class SharedDraftSchematicObjectTemplate::_IngredientSlot + +/** + * Class constructor. + */ +SharedDraftSchematicObjectTemplate::_IngredientSlot::_IngredientSlot(const std::string & filename) + : ObjectTemplate(filename) +{ +} // SharedDraftSchematicObjectTemplate::_IngredientSlot::_IngredientSlot + +/** + * Class destructor. + */ +SharedDraftSchematicObjectTemplate::_IngredientSlot::~_IngredientSlot() +{ +} // SharedDraftSchematicObjectTemplate::_IngredientSlot::~_IngredientSlot + +/** + * Static function used to register this template. + */ +void SharedDraftSchematicObjectTemplate::_IngredientSlot::registerMe(void) +{ + ObjectTemplateList::registerTemplate(_IngredientSlot_tag, create); +} // SharedDraftSchematicObjectTemplate::_IngredientSlot::registerMe + +/** + * Creates a SharedDraftSchematicObjectTemplate::_IngredientSlot template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedDraftSchematicObjectTemplate::_IngredientSlot::create(const std::string & filename) +{ + return new SharedDraftSchematicObjectTemplate::_IngredientSlot(filename); +} // SharedDraftSchematicObjectTemplate::_IngredientSlot::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedDraftSchematicObjectTemplate::_IngredientSlot::getId(void) const +{ + return _IngredientSlot_tag; +} // SharedDraftSchematicObjectTemplate::_IngredientSlot::getId + +const StringId SharedDraftSchematicObjectTemplate::_IngredientSlot::getName(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +StringId testDataValue = DefaultStringId; +#else +UNREF(testData); +#endif + + const SharedDraftSchematicObjectTemplate::_IngredientSlot * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getName(true); +#endif + } + + if (!m_name.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter name in template %s", DataResource::getName())); + return DefaultStringId; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter name has not been defined in template %s!", DataResource::getName())); + return base->getName(versionOk); + } + } + + const StringId value = m_name.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedDraftSchematicObjectTemplate::_IngredientSlot::getName + +const std::string & SharedDraftSchematicObjectTemplate::_IngredientSlot::getHardpoint(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedDraftSchematicObjectTemplate::_IngredientSlot * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getHardpoint(true); +#endif + } + + if (!m_hardpoint.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter hardpoint in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter hardpoint has not been defined in template %s!", DataResource::getName())); + return base->getHardpoint(versionOk); + } + } + + const std::string & value = m_hardpoint.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedDraftSchematicObjectTemplate::_IngredientSlot::getHardpoint + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedDraftSchematicObjectTemplate::_IngredientSlot::testValues(void) const +{ + IGNORE_RETURN(getName(true)); + IGNORE_RETURN(getHardpoint(true)); +} // SharedDraftSchematicObjectTemplate::_IngredientSlot::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedDraftSchematicObjectTemplate::_IngredientSlot::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "name") == 0) + m_name.loadFromIff(file); + else if (strcmp(paramName, "hardpoint") == 0) + m_hardpoint.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + UNREF(file); +} // SharedDraftSchematicObjectTemplate::_IngredientSlot::load + + +//============================================================================= +// class SharedDraftSchematicObjectTemplate::_SchematicAttribute + +/** + * Class constructor. + */ +SharedDraftSchematicObjectTemplate::_SchematicAttribute::_SchematicAttribute(const std::string & filename) + : ObjectTemplate(filename) +{ +} // SharedDraftSchematicObjectTemplate::_SchematicAttribute::_SchematicAttribute + +/** + * Class destructor. + */ +SharedDraftSchematicObjectTemplate::_SchematicAttribute::~_SchematicAttribute() +{ +} // SharedDraftSchematicObjectTemplate::_SchematicAttribute::~_SchematicAttribute + +/** + * Static function used to register this template. + */ +void SharedDraftSchematicObjectTemplate::_SchematicAttribute::registerMe(void) +{ + ObjectTemplateList::registerTemplate(_SchematicAttribute_tag, create); +} // SharedDraftSchematicObjectTemplate::_SchematicAttribute::registerMe + +/** + * Creates a SharedDraftSchematicObjectTemplate::_SchematicAttribute template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedDraftSchematicObjectTemplate::_SchematicAttribute::create(const std::string & filename) +{ + return new SharedDraftSchematicObjectTemplate::_SchematicAttribute(filename); +} // SharedDraftSchematicObjectTemplate::_SchematicAttribute::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedDraftSchematicObjectTemplate::_SchematicAttribute::getId(void) const +{ + return _SchematicAttribute_tag; +} // SharedDraftSchematicObjectTemplate::_SchematicAttribute::getId + +const StringId SharedDraftSchematicObjectTemplate::_SchematicAttribute::getName(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +StringId testDataValue = DefaultStringId; +#else +UNREF(testData); +#endif + + const SharedDraftSchematicObjectTemplate::_SchematicAttribute * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getName(true); +#endif + } + + if (!m_name.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter name in template %s", DataResource::getName())); + return DefaultStringId; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter name has not been defined in template %s!", DataResource::getName())); + return base->getName(versionOk); + } + } + + const StringId value = m_name.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedDraftSchematicObjectTemplate::_SchematicAttribute::getName + +const StringId SharedDraftSchematicObjectTemplate::_SchematicAttribute::getExperiment(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +StringId testDataValue = DefaultStringId; +#else +UNREF(testData); +#endif + + const SharedDraftSchematicObjectTemplate::_SchematicAttribute * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getExperiment(true); +#endif + } + + if (!m_experiment.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter experiment in template %s", DataResource::getName())); + return DefaultStringId; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter experiment has not been defined in template %s!", DataResource::getName())); + return base->getExperiment(versionOk); + } + } + + const StringId value = m_experiment.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedDraftSchematicObjectTemplate::_SchematicAttribute::getExperiment + +int SharedDraftSchematicObjectTemplate::_SchematicAttribute::getValue(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedDraftSchematicObjectTemplate::_SchematicAttribute * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getValue(true); +#endif + } + + if (!m_value.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter value in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter value has not been defined in template %s!", DataResource::getName())); + return base->getValue(versionOk); + } + } + + int value = m_value.getValue(); + char delta = m_value.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getValue(versionOk); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedDraftSchematicObjectTemplate::_SchematicAttribute::getValue + +int SharedDraftSchematicObjectTemplate::_SchematicAttribute::getValueMin(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedDraftSchematicObjectTemplate::_SchematicAttribute * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getValueMin(true); +#endif + } + + if (!m_value.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter value in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter value has not been defined in template %s!", DataResource::getName())); + return base->getValueMin(versionOk); + } + } + + int value = m_value.getMinValue(); + char delta = m_value.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getValueMin(versionOk); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedDraftSchematicObjectTemplate::_SchematicAttribute::getValueMin + +int SharedDraftSchematicObjectTemplate::_SchematicAttribute::getValueMax(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedDraftSchematicObjectTemplate::_SchematicAttribute * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getValueMax(true); +#endif + } + + if (!m_value.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter value in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter value has not been defined in template %s!", DataResource::getName())); + return base->getValueMax(versionOk); + } + } + + int value = m_value.getMaxValue(); + char delta = m_value.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getValueMax(versionOk); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedDraftSchematicObjectTemplate::_SchematicAttribute::getValueMax + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedDraftSchematicObjectTemplate::_SchematicAttribute::testValues(void) const +{ + IGNORE_RETURN(getName(true)); + IGNORE_RETURN(getExperiment(true)); + IGNORE_RETURN(getValueMin(true)); + IGNORE_RETURN(getValueMax(true)); +} // SharedDraftSchematicObjectTemplate::_SchematicAttribute::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedDraftSchematicObjectTemplate::_SchematicAttribute::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "name") == 0) + m_name.loadFromIff(file); + else if (strcmp(paramName, "experiment") == 0) + m_experiment.loadFromIff(file); + else if (strcmp(paramName, "value") == 0) + m_value.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + UNREF(file); +} // SharedDraftSchematicObjectTemplate::_SchematicAttribute::load + +//@END TFD + +//---------------------------------------------------------------------- + +const StringId SharedDraftSchematicObjectTemplate::getCraftedName () const +{ + StringId sid = getObjectName (); + + if (sid.isInvalid ()) + { + const SharedObjectTemplate * const sot = fetchCraftedSharedObjectTemplate (); + if (sot) + { + sid = sot->getObjectName (); + sot->releaseReference (); + } + } + + return sid; +} + +//---------------------------------------------------------------------- + +const StringId SharedDraftSchematicObjectTemplate::getCraftedDetailedDescription () const +{ + StringId sid = getDetailedDescription (); + + if (sid.isInvalid ()) + { + const SharedObjectTemplate * const sot = fetchCraftedSharedObjectTemplate (); + if (sot) + { + sid = sot->getDetailedDescription (); + sot->releaseReference (); + } + } + + return sid; +} + +//---------------------------------------------------------------------- + +const StringId SharedDraftSchematicObjectTemplate::getCraftedLookAtText () const +{ + StringId sid = getLookAtText (); + + if (sid.isInvalid ()) + { + const SharedObjectTemplate * const sot = fetchCraftedSharedObjectTemplate (); + if (sot) + { + sid = sot->getLookAtText (); + sot->releaseReference (); + } + } + + return sid; +} + +//---------------------------------------------------------------------- + +const std::string SharedDraftSchematicObjectTemplate::getCraftedAppearanceFilename () const +{ + const std::string & app = getAppearanceFilename (); + + if (app.empty ()) + { + const SharedObjectTemplate * const sot = fetchCraftedSharedObjectTemplate (); + if (sot) + { + const std::string capp = sot->getAppearanceFilename (); + sot->releaseReference (); + return capp; + } + } + + return app; +} + +//---------------------------------------------------------------------- + +const SharedObjectTemplate * SharedDraftSchematicObjectTemplate::fetchCraftedSharedObjectTemplate () const +{ + const std::string & sotName = getCraftedSharedTemplate (); + const SharedObjectTemplate * const sot = safe_cast(ObjectTemplateList::fetch (sotName.c_str ())); + + if (!sot) + { + const char * const draftName = this->DataResource::getName (); + WARNING (true, ("SharedDraftSchematicObjectTemplate [%s] could not load craftedSharedTemplate [%s]", draftName ? draftName : "", sotName.c_str ())); + } + + return sot; +} + +//---------------------------------------------------------------------- + diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedDraftSchematicObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedDraftSchematicObjectTemplate.h new file mode 100644 index 00000000..e84be62c --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedDraftSchematicObjectTemplate.h @@ -0,0 +1,237 @@ +//======================================================================== +// +// SharedDraftSchematicObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedDraftSchematicObjectTemplate_H +#define _INCLUDED_SharedDraftSchematicObjectTemplate_H + +#include "SharedIntangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedDraftSchematicObjectTemplate : public SharedIntangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedDraftSchematicObjectTemplate_tag = TAG(S,D,S,C) + }; +//@END TFD ID +public: + SharedDraftSchematicObjectTemplate(const std::string & filename); + virtual ~SharedDraftSchematicObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + + const StringId getCraftedName () const; + const StringId getCraftedDetailedDescription () const; + const StringId getCraftedLookAtText () const; + const std::string getCraftedAppearanceFilename () const; + const SharedObjectTemplate * fetchCraftedSharedObjectTemplate () const; + +//@BEGIN TFD +public: + enum ArmorRating + { + AR_armorNone, + AR_armorLight, + AR_armorMedium, + AR_armorHeavy, + ArmorRating_Last = AR_armorHeavy, + }; + + enum DamageType + { + DT_none = 0x00000000, + DT_kinetic = 0x00000001, + DT_energy = 0x00000002, + DT_blast = 0x00000004, + DT_stun = 0x00000008, + DT_restraint = 0x00000010, + DT_elemental_heat = 0x00000020, + DT_elemental_cold = 0x00000040, + DT_elemental_acid = 0x00000080, + DT_elemental_electrical = 0x00000100, + DT_environmental_heat = 0x00000200, + DT_environmental_cold = 0x00000400, + DT_environmental_acid = 0x00000800, + DT_environmental_electrical = 0x00001000, + DamageType_Last = DT_environmental_electrical, + }; + +public: + struct IngredientSlot + { + StringId name; + std::string hardpoint; + }; + + struct SchematicAttribute + { + StringId name; + StringId experiment; + int value; + }; + +protected: + class _IngredientSlot : public ObjectTemplate + { + friend class SharedDraftSchematicObjectTemplate; + public: + enum + { + _IngredientSlot_tag = TAG(S,I,S,S) + }; + + public: + _IngredientSlot(const std::string & filename); + virtual ~_IngredientSlot(); + + virtual Tag getId(void) const; + +public: + const StringId getName(bool versionOk, bool testData = false) const; + const std::string & getHardpoint(bool versionOk, bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + StringIdParam m_name; // slot name + StringParam m_hardpoint; // UI hardpoint for this slot + private: + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + private: + _IngredientSlot(const _IngredientSlot &); + _IngredientSlot & operator =(const _IngredientSlot &); + }; + friend class SharedDraftSchematicObjectTemplate::_IngredientSlot; + + class _SchematicAttribute : public ObjectTemplate + { + friend class SharedDraftSchematicObjectTemplate; + public: + enum + { + _SchematicAttribute_tag = TAG(D,S,S,A) + }; + + public: + _SchematicAttribute(const std::string & filename); + virtual ~_SchematicAttribute(); + + virtual Tag getId(void) const; + +public: + const StringId getName(bool versionOk, bool testData = false) const; + const StringId getExperiment(bool versionOk, bool testData = false) const; + int getValue(bool versionOk, bool testData = false) const; + int getValueMin(bool versionOk, bool testData = false) const; + int getValueMax(bool versionOk, bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + StringIdParam m_name; // name of the attribute + StringIdParam m_experiment; // name of the experimental attribute associated with the attribute + IntegerParam m_value; // value of the attribute - a range for draft schematics and a single value for manufacture schematics + private: + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + private: + _SchematicAttribute(const _SchematicAttribute &); + _SchematicAttribute & operator =(const _SchematicAttribute &); + }; + friend class SharedDraftSchematicObjectTemplate::_SchematicAttribute; + +public: + void getSlots(IngredientSlot &data, int index) const; + void getSlotsMin(IngredientSlot &data, int index) const; + void getSlotsMax(IngredientSlot &data, int index) const; + size_t getSlotsCount(void) const; + void getAttributes(SchematicAttribute &data, int index) const; + void getAttributesMin(SchematicAttribute &data, int index) const; + void getAttributesMax(SchematicAttribute &data, int index) const; + size_t getAttributesCount(void) const; + const std::string & getCraftedSharedTemplate(bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + // this enum is also defined in the server object_template.tdf file + // this enum is also defined in the server object_template.tdf file + stdvector::fwd m_slots; // ingredient slots + bool m_slotsLoaded; + bool m_slotsAppend; + stdvector::fwd m_attributes; // what attributes the schematic can affect + bool m_attributesLoaded; + bool m_attributesAppend; + StringParam m_craftedSharedTemplate; +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedDraftSchematicObjectTemplate(const SharedDraftSchematicObjectTemplate &); + SharedDraftSchematicObjectTemplate & operator =(const SharedDraftSchematicObjectTemplate &); +}; + + +inline void SharedDraftSchematicObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedDraftSchematicObjectTemplate::registerMe(); + SharedDraftSchematicObjectTemplate::_IngredientSlot::registerMe(); + SharedDraftSchematicObjectTemplate::_SchematicAttribute::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedDraftSchematicObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedFactoryObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedFactoryObjectTemplate.cpp new file mode 100644 index 00000000..cf7c46fb --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedFactoryObjectTemplate.cpp @@ -0,0 +1,175 @@ +//======================================================================== +// +// SharedFactoryObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedFactoryObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedFactoryObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedFactoryObjectTemplate::SharedFactoryObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedTangibleObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedFactoryObjectTemplate::SharedFactoryObjectTemplate + +/** + * Class destructor. + */ +SharedFactoryObjectTemplate::~SharedFactoryObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedFactoryObjectTemplate::~SharedFactoryObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedFactoryObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedFactoryObjectTemplate_tag, create); +} // SharedFactoryObjectTemplate::registerMe + +/** + * Creates a SharedFactoryObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedFactoryObjectTemplate::create(const std::string & filename) +{ + return new SharedFactoryObjectTemplate(filename); +} // SharedFactoryObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedFactoryObjectTemplate::getId(void) const +{ + return SharedFactoryObjectTemplate_tag; +} // SharedFactoryObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedFactoryObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedFactoryObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedFactoryObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedFactoryObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedFactoryObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedFactoryObjectTemplate::testValues(void) const +{ + SharedTangibleObjectTemplate::testValues(); +} // SharedFactoryObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedFactoryObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedFactoryObjectTemplate_tag) + { + SharedTangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedTangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedFactoryObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedFactoryObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedFactoryObjectTemplate.h new file mode 100644 index 00000000..3bab50b6 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedFactoryObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedFactoryObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedFactoryObjectTemplate_H +#define _INCLUDED_SharedFactoryObjectTemplate_H + +#include "SharedTangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedFactoryObjectTemplate : public SharedTangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedFactoryObjectTemplate_tag = TAG(S,F,O,T) + }; +//@END TFD ID +public: + SharedFactoryObjectTemplate(const std::string & filename); + virtual ~SharedFactoryObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedFactoryObjectTemplate(const SharedFactoryObjectTemplate &); + SharedFactoryObjectTemplate & operator =(const SharedFactoryObjectTemplate &); +}; + + +inline void SharedFactoryObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedFactoryObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedFactoryObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedGroupObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedGroupObjectTemplate.cpp new file mode 100644 index 00000000..a6e77be1 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedGroupObjectTemplate.cpp @@ -0,0 +1,175 @@ +//======================================================================== +// +// SharedGroupObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedGroupObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedGroupObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedGroupObjectTemplate::SharedGroupObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedUniverseObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedGroupObjectTemplate::SharedGroupObjectTemplate + +/** + * Class destructor. + */ +SharedGroupObjectTemplate::~SharedGroupObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedGroupObjectTemplate::~SharedGroupObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedGroupObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedGroupObjectTemplate_tag, create); +} // SharedGroupObjectTemplate::registerMe + +/** + * Creates a SharedGroupObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedGroupObjectTemplate::create(const std::string & filename) +{ + return new SharedGroupObjectTemplate(filename); +} // SharedGroupObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedGroupObjectTemplate::getId(void) const +{ + return SharedGroupObjectTemplate_tag; +} // SharedGroupObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedGroupObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedGroupObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedGroupObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedGroupObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedGroupObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedGroupObjectTemplate::testValues(void) const +{ + SharedUniverseObjectTemplate::testValues(); +} // SharedGroupObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedGroupObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedGroupObjectTemplate_tag) + { + SharedUniverseObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedUniverseObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedGroupObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedGroupObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedGroupObjectTemplate.h new file mode 100644 index 00000000..a114b920 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedGroupObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedGroupObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedGroupObjectTemplate_H +#define _INCLUDED_SharedGroupObjectTemplate_H + +#include "SharedUniverseObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedGroupObjectTemplate : public SharedUniverseObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedGroupObjectTemplate_tag = TAG(S,G,R,P) + }; +//@END TFD ID +public: + SharedGroupObjectTemplate(const std::string & filename); + virtual ~SharedGroupObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedGroupObjectTemplate(const SharedGroupObjectTemplate &); + SharedGroupObjectTemplate & operator =(const SharedGroupObjectTemplate &); +}; + + +inline void SharedGroupObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedGroupObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedGroupObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedGuildObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedGuildObjectTemplate.cpp new file mode 100644 index 00000000..03f2c443 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedGuildObjectTemplate.cpp @@ -0,0 +1,175 @@ +//======================================================================== +// +// SharedGuildObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedGuildObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedGuildObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedGuildObjectTemplate::SharedGuildObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedUniverseObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedGuildObjectTemplate::SharedGuildObjectTemplate + +/** + * Class destructor. + */ +SharedGuildObjectTemplate::~SharedGuildObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedGuildObjectTemplate::~SharedGuildObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedGuildObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedGuildObjectTemplate_tag, create); +} // SharedGuildObjectTemplate::registerMe + +/** + * Creates a SharedGuildObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedGuildObjectTemplate::create(const std::string & filename) +{ + return new SharedGuildObjectTemplate(filename); +} // SharedGuildObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedGuildObjectTemplate::getId(void) const +{ + return SharedGuildObjectTemplate_tag; +} // SharedGuildObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedGuildObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedGuildObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedGuildObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedGuildObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedGuildObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedGuildObjectTemplate::testValues(void) const +{ + SharedUniverseObjectTemplate::testValues(); +} // SharedGuildObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedGuildObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedGuildObjectTemplate_tag) + { + SharedUniverseObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedUniverseObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedGuildObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedGuildObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedGuildObjectTemplate.h new file mode 100644 index 00000000..43a7c2d3 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedGuildObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedGuildObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedGuildObjectTemplate_H +#define _INCLUDED_SharedGuildObjectTemplate_H + +#include "SharedUniverseObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedGuildObjectTemplate : public SharedUniverseObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedGuildObjectTemplate_tag = TAG(S,G,L,D) + }; +//@END TFD ID +public: + SharedGuildObjectTemplate(const std::string & filename); + virtual ~SharedGuildObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedGuildObjectTemplate(const SharedGuildObjectTemplate &); + SharedGuildObjectTemplate & operator =(const SharedGuildObjectTemplate &); +}; + + +inline void SharedGuildObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedGuildObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedGuildObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedInstallationObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedInstallationObjectTemplate.cpp new file mode 100644 index 00000000..1613d830 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedInstallationObjectTemplate.cpp @@ -0,0 +1,175 @@ +//======================================================================== +// +// SharedInstallationObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedInstallationObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedInstallationObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedInstallationObjectTemplate::SharedInstallationObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedTangibleObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedInstallationObjectTemplate::SharedInstallationObjectTemplate + +/** + * Class destructor. + */ +SharedInstallationObjectTemplate::~SharedInstallationObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedInstallationObjectTemplate::~SharedInstallationObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedInstallationObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedInstallationObjectTemplate_tag, create); +} // SharedInstallationObjectTemplate::registerMe + +/** + * Creates a SharedInstallationObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedInstallationObjectTemplate::create(const std::string & filename) +{ + return new SharedInstallationObjectTemplate(filename); +} // SharedInstallationObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedInstallationObjectTemplate::getId(void) const +{ + return SharedInstallationObjectTemplate_tag; +} // SharedInstallationObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedInstallationObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedInstallationObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedInstallationObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedInstallationObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedInstallationObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedInstallationObjectTemplate::testValues(void) const +{ + SharedTangibleObjectTemplate::testValues(); +} // SharedInstallationObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedInstallationObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedInstallationObjectTemplate_tag) + { + SharedTangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedTangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedInstallationObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedInstallationObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedInstallationObjectTemplate.h new file mode 100644 index 00000000..36e3aabe --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedInstallationObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedInstallationObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedInstallationObjectTemplate_H +#define _INCLUDED_SharedInstallationObjectTemplate_H + +#include "SharedTangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedInstallationObjectTemplate : public SharedTangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedInstallationObjectTemplate_tag = TAG(S,I,O,T) + }; +//@END TFD ID +public: + SharedInstallationObjectTemplate(const std::string & filename); + virtual ~SharedInstallationObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedInstallationObjectTemplate(const SharedInstallationObjectTemplate &); + SharedInstallationObjectTemplate & operator =(const SharedInstallationObjectTemplate &); +}; + + +inline void SharedInstallationObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedInstallationObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedInstallationObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedIntangibleObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedIntangibleObjectTemplate.cpp new file mode 100644 index 00000000..909749fa --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedIntangibleObjectTemplate.cpp @@ -0,0 +1,175 @@ +//======================================================================== +// +// SharedIntangibleObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedIntangibleObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedIntangibleObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedIntangibleObjectTemplate::SharedIntangibleObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedIntangibleObjectTemplate::SharedIntangibleObjectTemplate + +/** + * Class destructor. + */ +SharedIntangibleObjectTemplate::~SharedIntangibleObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedIntangibleObjectTemplate::~SharedIntangibleObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedIntangibleObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedIntangibleObjectTemplate_tag, create); +} // SharedIntangibleObjectTemplate::registerMe + +/** + * Creates a SharedIntangibleObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedIntangibleObjectTemplate::create(const std::string & filename) +{ + return new SharedIntangibleObjectTemplate(filename); +} // SharedIntangibleObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedIntangibleObjectTemplate::getId(void) const +{ + return SharedIntangibleObjectTemplate_tag; +} // SharedIntangibleObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedIntangibleObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedIntangibleObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedIntangibleObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedIntangibleObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedIntangibleObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedIntangibleObjectTemplate::testValues(void) const +{ + SharedObjectTemplate::testValues(); +} // SharedIntangibleObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedIntangibleObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedIntangibleObjectTemplate_tag) + { + SharedObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedIntangibleObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedIntangibleObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedIntangibleObjectTemplate.h new file mode 100644 index 00000000..bf0ae9d3 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedIntangibleObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedIntangibleObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedIntangibleObjectTemplate_H +#define _INCLUDED_SharedIntangibleObjectTemplate_H + +#include "SharedObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedIntangibleObjectTemplate : public SharedObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedIntangibleObjectTemplate_tag = TAG(S,I,T,N) + }; +//@END TFD ID +public: + SharedIntangibleObjectTemplate(const std::string & filename); + virtual ~SharedIntangibleObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedIntangibleObjectTemplate(const SharedIntangibleObjectTemplate &); + SharedIntangibleObjectTemplate & operator =(const SharedIntangibleObjectTemplate &); +}; + + +inline void SharedIntangibleObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedIntangibleObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedIntangibleObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedJediManagerObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedJediManagerObjectTemplate.cpp new file mode 100644 index 00000000..f87a92f0 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedJediManagerObjectTemplate.cpp @@ -0,0 +1,176 @@ +//======================================================================== +// +// SharedJediManagerObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedJediManagerObjectTemplate.h" +#include "sharedDebug/DataLint.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedJediManagerObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedJediManagerObjectTemplate::SharedJediManagerObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedUniverseObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedJediManagerObjectTemplate::SharedJediManagerObjectTemplate + +/** + * Class destructor. + */ +SharedJediManagerObjectTemplate::~SharedJediManagerObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedJediManagerObjectTemplate::~SharedJediManagerObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedJediManagerObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedJediManagerObjectTemplate_tag, create); +} // SharedJediManagerObjectTemplate::registerMe + +/** + * Creates a SharedJediManagerObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedJediManagerObjectTemplate::create(const std::string & filename) +{ + return new SharedJediManagerObjectTemplate(filename); +} // SharedJediManagerObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedJediManagerObjectTemplate::getId(void) const +{ + return SharedJediManagerObjectTemplate_tag; +} // SharedJediManagerObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedJediManagerObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedJediManagerObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedJediManagerObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedJediManagerObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedJediManagerObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedJediManagerObjectTemplate::testValues(void) const +{ + SharedUniverseObjectTemplate::testValues(); +} // SharedJediManagerObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedJediManagerObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedJediManagerObjectTemplate_tag) + { + SharedUniverseObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedUniverseObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedJediManagerObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedJediManagerObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedJediManagerObjectTemplate.h new file mode 100644 index 00000000..b2be5b14 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedJediManagerObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedJediManagerObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedJediManagerObjectTemplate_H +#define _INCLUDED_SharedJediManagerObjectTemplate_H + +#include "SharedUniverseObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedJediManagerObjectTemplate : public SharedUniverseObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedJediManagerObjectTemplate_tag = TAG(S,J,E,D) + }; +//@END TFD ID +public: + SharedJediManagerObjectTemplate(const std::string & filename); + virtual ~SharedJediManagerObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedJediManagerObjectTemplate(const SharedJediManagerObjectTemplate &); + SharedJediManagerObjectTemplate & operator =(const SharedJediManagerObjectTemplate &); +}; + + +inline void SharedJediManagerObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedJediManagerObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedJediManagerObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedManufactureSchematicObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedManufactureSchematicObjectTemplate.cpp new file mode 100644 index 00000000..a5d97f52 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedManufactureSchematicObjectTemplate.cpp @@ -0,0 +1,175 @@ +//======================================================================== +// +// SharedManufactureSchematicObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedManufactureSchematicObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedManufactureSchematicObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedManufactureSchematicObjectTemplate::SharedManufactureSchematicObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedIntangibleObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedManufactureSchematicObjectTemplate::SharedManufactureSchematicObjectTemplate + +/** + * Class destructor. + */ +SharedManufactureSchematicObjectTemplate::~SharedManufactureSchematicObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedManufactureSchematicObjectTemplate::~SharedManufactureSchematicObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedManufactureSchematicObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedManufactureSchematicObjectTemplate_tag, create); +} // SharedManufactureSchematicObjectTemplate::registerMe + +/** + * Creates a SharedManufactureSchematicObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedManufactureSchematicObjectTemplate::create(const std::string & filename) +{ + return new SharedManufactureSchematicObjectTemplate(filename); +} // SharedManufactureSchematicObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedManufactureSchematicObjectTemplate::getId(void) const +{ + return SharedManufactureSchematicObjectTemplate_tag; +} // SharedManufactureSchematicObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedManufactureSchematicObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedManufactureSchematicObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedManufactureSchematicObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedManufactureSchematicObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedManufactureSchematicObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedManufactureSchematicObjectTemplate::testValues(void) const +{ + SharedIntangibleObjectTemplate::testValues(); +} // SharedManufactureSchematicObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedManufactureSchematicObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedManufactureSchematicObjectTemplate_tag) + { + SharedIntangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedIntangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedManufactureSchematicObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedManufactureSchematicObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedManufactureSchematicObjectTemplate.h new file mode 100644 index 00000000..71a6c26e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedManufactureSchematicObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedManufactureSchematicObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedManufactureSchematicObjectTemplate_H +#define _INCLUDED_SharedManufactureSchematicObjectTemplate_H + +#include "SharedIntangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedManufactureSchematicObjectTemplate : public SharedIntangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedManufactureSchematicObjectTemplate_tag = TAG(S,M,S,C) + }; +//@END TFD ID +public: + SharedManufactureSchematicObjectTemplate(const std::string & filename); + virtual ~SharedManufactureSchematicObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedManufactureSchematicObjectTemplate(const SharedManufactureSchematicObjectTemplate &); + SharedManufactureSchematicObjectTemplate & operator =(const SharedManufactureSchematicObjectTemplate &); +}; + + +inline void SharedManufactureSchematicObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedManufactureSchematicObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedManufactureSchematicObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedMissionObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedMissionObjectTemplate.cpp new file mode 100644 index 00000000..4b48b068 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedMissionObjectTemplate.cpp @@ -0,0 +1,175 @@ +//======================================================================== +// +// SharedMissionObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedMissionObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedMissionObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedMissionObjectTemplate::SharedMissionObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedIntangibleObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedMissionObjectTemplate::SharedMissionObjectTemplate + +/** + * Class destructor. + */ +SharedMissionObjectTemplate::~SharedMissionObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedMissionObjectTemplate::~SharedMissionObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedMissionObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedMissionObjectTemplate_tag, create); +} // SharedMissionObjectTemplate::registerMe + +/** + * Creates a SharedMissionObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedMissionObjectTemplate::create(const std::string & filename) +{ + return new SharedMissionObjectTemplate(filename); +} // SharedMissionObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedMissionObjectTemplate::getId(void) const +{ + return SharedMissionObjectTemplate_tag; +} // SharedMissionObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedMissionObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedMissionObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedMissionObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedMissionObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedMissionObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedMissionObjectTemplate::testValues(void) const +{ + SharedIntangibleObjectTemplate::testValues(); +} // SharedMissionObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedMissionObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedMissionObjectTemplate_tag) + { + SharedIntangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedIntangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedMissionObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedMissionObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedMissionObjectTemplate.h new file mode 100644 index 00000000..7830dc89 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedMissionObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedMissionObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedMissionObjectTemplate_H +#define _INCLUDED_SharedMissionObjectTemplate_H + +#include "SharedIntangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedMissionObjectTemplate : public SharedIntangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedMissionObjectTemplate_tag = TAG(S,M,S,O) + }; +//@END TFD ID +public: + SharedMissionObjectTemplate(const std::string & filename); + virtual ~SharedMissionObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedMissionObjectTemplate(const SharedMissionObjectTemplate &); + SharedMissionObjectTemplate & operator =(const SharedMissionObjectTemplate &); +}; + + +inline void SharedMissionObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedMissionObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedMissionObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplate.cpp new file mode 100644 index 00000000..1d2abd82 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplate.cpp @@ -0,0 +1,2260 @@ +//======================================================================== +// +// SharedObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SharedObjectTemplate.h" + +#include "sharedFile/Iff.h" +#include "sharedGame/SharedObjectTemplateClientData.h" +#include "sharedMath/Vector.h" +#include "sharedObject/AppearanceTemplate.h" +#include "sharedObject/AppearanceTemplateList.h" +#include "sharedObject/ArrangementDescriptor.h" +#include "sharedObject/ArrangementDescriptorList.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +#include "sharedObject/PortalPropertyTemplate.h" +#include "sharedObject/PortalPropertyTemplateList.h" +#include "sharedObject/SlotDescriptor.h" +#include "sharedObject/SlotDescriptorList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedObjectTemplate::ms_allowDefaultTemplateParams = true; + +// ====================================================================== +// SharedObjectTemplate::PreloadManager +// ====================================================================== + +class SharedObjectTemplate::PreloadManager +{ +public: + + explicit PreloadManager (const SharedObjectTemplate* sharedObjectTemplate); + ~PreloadManager (); + +private: + + PreloadManager (); + PreloadManager (const PreloadManager&); + PreloadManager& operator= (const PreloadManager&); + +private: + + const AppearanceTemplate* m_preloadAppearanceTemplate; + const PortalPropertyTemplate* m_preloadPortalPropertyTemplate; +}; + +// ---------------------------------------------------------------------- + +SharedObjectTemplate::PreloadManager::PreloadManager (const SharedObjectTemplate* const sharedObjectTemplate) : +m_preloadAppearanceTemplate (0), +m_preloadPortalPropertyTemplate (0) +{ + NOT_NULL(sharedObjectTemplate); + const std::string& appearanceFileName = sharedObjectTemplate->getAppearanceFilename (); + if (!appearanceFileName.empty ()) + { + bool found = false; + m_preloadAppearanceTemplate = AppearanceTemplateList::fetch (appearanceFileName.c_str (), found); + WARNING(!found, ("SharedObjectTemplate [%s] unable to load appearance [%s]", sharedObjectTemplate->getName(), appearanceFileName.c_str())); + m_preloadAppearanceTemplate->preloadAssets (); + } + + const std::string& portalLayoutFilename = sharedObjectTemplate->getPortalLayoutFilename (); + if (!portalLayoutFilename.empty ()) + { + m_preloadPortalPropertyTemplate = PortalPropertyTemplateList::fetch (TemporaryCrcString (portalLayoutFilename.c_str (), true)); + m_preloadPortalPropertyTemplate->preloadAssets (); + } + + if (sharedObjectTemplate->m_clientData) + sharedObjectTemplate->m_clientData->preloadAssets (); +} + +// ---------------------------------------------------------------------- + +SharedObjectTemplate::PreloadManager::~PreloadManager () +{ + if (m_preloadAppearanceTemplate) + AppearanceTemplateList::release (m_preloadAppearanceTemplate); + + if (m_preloadPortalPropertyTemplate) + m_preloadPortalPropertyTemplate->release (); +} + +// ====================================================================== + +/** + * Class constructor. + */ +SharedObjectTemplate::SharedObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : ObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT + , m_slotDescriptor(NULL) + , m_arrangementDescriptor(NULL) + , m_clientData (0) + , m_preloadManager (0) +{ +} // SharedObjectTemplate::SharedObjectTemplate + +/** + * Class destructor. + */ +SharedObjectTemplate::~SharedObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP + + //-- Release ArrangementDescriptor resource. + if (m_arrangementDescriptor) + { + m_arrangementDescriptor->release(); + m_arrangementDescriptor = 0; + } + + //-- Release SlotDescriptor resource. + if (m_slotDescriptor) + { + m_slotDescriptor->release(); + m_slotDescriptor = 0; + } + + //-- delete client data + if (m_clientData) + m_clientData->releaseReference (); + + //-- delete preloadmanager + if (m_preloadManager) + { + delete m_preloadManager; + m_preloadManager = 0; + } +} // SharedObjectTemplate::~SharedObjectTemplate + +// ---------------------------------------------------------------------- + +SharedObjectTemplate * SharedObjectTemplate::asSharedObjectTemplate() +{ + return this; +} + +// ---------------------------------------------------------------------- + +SharedObjectTemplate const * SharedObjectTemplate::asSharedObjectTemplate() const +{ + return this; +} + +// ---------------------------------------------------------------------- + +/** + * Static function used to register this template. + */ +void SharedObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedObjectTemplate_tag, create); +} // SharedObjectTemplate::registerMe + +/** + * Creates a SharedObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedObjectTemplate::create(const std::string & filename) +{ + return new SharedObjectTemplate(filename); +} // SharedObjectTemplate::create + + +void SharedObjectTemplate::preloadAssets () const +{ + ObjectTemplate::preloadAssets (); + + if (!m_preloadManager) + m_preloadManager = new PreloadManager (this); +} + +void SharedObjectTemplate::garbageCollect () const +{ + ObjectTemplate::garbageCollect (); + + if (m_preloadManager) + { + delete m_preloadManager; + m_preloadManager = 0; + } +} + + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedObjectTemplate::getId(void) const +{ + return SharedObjectTemplate_tag; +} // SharedObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedObjectTemplate::getHighestTemplateVersion + +/** + * Handle any post-load processing for the instance. + */ +void SharedObjectTemplate::postLoad(void) +{ + //-- fetch the SlotDescriptor if specified + const std::string &slotFilename = getSlotDescriptorFilename(); + if (!slotFilename.empty()) + m_slotDescriptor = SlotDescriptorList::fetch(slotFilename); + + //-- fetch the ArrangementDescriptor if specified + const std::string &arrangementFilename = getArrangementDescriptorFilename(); + if (!arrangementFilename.empty()) + m_arrangementDescriptor = ArrangementDescriptorList::fetch(arrangementFilename); + + //-- load the client data file + if (ms_createClientDataFunction) + { + const std::string& clientDataFile = getClientDataFile (); + + if (!clientDataFile.empty ()) + m_clientData = ms_createClientDataFunction (clientDataFile.c_str ()); + } +} // SharedObjectTemplate::postLoad + +//@BEGIN TFD +const StringId SharedObjectTemplate::getObjectName(bool testData) const +{ +#ifdef _DEBUG +StringId testDataValue = DefaultStringId; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getObjectName(true); +#endif + } + + if (!m_objectName.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter objectName in template %s", DataResource::getName())); + return DefaultStringId; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter objectName has not been defined in template %s!", DataResource::getName())); + return base->getObjectName(); + } + } + + const StringId value = m_objectName.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getObjectName + +const StringId SharedObjectTemplate::getDetailedDescription(bool testData) const +{ +#ifdef _DEBUG +StringId testDataValue = DefaultStringId; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getDetailedDescription(true); +#endif + } + + if (!m_detailedDescription.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter detailedDescription in template %s", DataResource::getName())); + return DefaultStringId; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter detailedDescription has not been defined in template %s!", DataResource::getName())); + return base->getDetailedDescription(); + } + } + + const StringId value = m_detailedDescription.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getDetailedDescription + +const StringId SharedObjectTemplate::getLookAtText(bool testData) const +{ +#ifdef _DEBUG +StringId testDataValue = DefaultStringId; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getLookAtText(true); +#endif + } + + if (!m_lookAtText.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter lookAtText in template %s", DataResource::getName())); + return DefaultStringId; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter lookAtText has not been defined in template %s!", DataResource::getName())); + return base->getLookAtText(); + } + } + + const StringId value = m_lookAtText.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getLookAtText + +bool SharedObjectTemplate::getSnapToTerrain(bool testData) const +{ +#ifdef _DEBUG +bool testDataValue = false; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSnapToTerrain(true); +#endif + } + + if (!m_snapToTerrain.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter snapToTerrain in template %s", DataResource::getName())); + return false; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter snapToTerrain has not been defined in template %s!", DataResource::getName())); + return base->getSnapToTerrain(); + } + } + + bool value = m_snapToTerrain.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getSnapToTerrain + +SharedObjectTemplate::ContainerType SharedObjectTemplate::getContainerType(bool testData) const +{ +#ifdef _DEBUG +SharedObjectTemplate::ContainerType testDataValue = static_cast(0); +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getContainerType(true); +#endif + } + + if (!m_containerType.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter containerType in template %s", DataResource::getName())); + return static_cast(0); + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter containerType has not been defined in template %s!", DataResource::getName())); + return base->getContainerType(); + } + } + + ContainerType value = static_cast(m_containerType.getValue()); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getContainerType + +int SharedObjectTemplate::getContainerVolumeLimit(bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getContainerVolumeLimit(true); +#endif + } + + if (!m_containerVolumeLimit.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter containerVolumeLimit in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter containerVolumeLimit has not been defined in template %s!", DataResource::getName())); + return base->getContainerVolumeLimit(); + } + } + + int value = m_containerVolumeLimit.getValue(); + char delta = m_containerVolumeLimit.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getContainerVolumeLimit(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getContainerVolumeLimit + +int SharedObjectTemplate::getContainerVolumeLimitMin(bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getContainerVolumeLimitMin(true); +#endif + } + + if (!m_containerVolumeLimit.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter containerVolumeLimit in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter containerVolumeLimit has not been defined in template %s!", DataResource::getName())); + return base->getContainerVolumeLimitMin(); + } + } + + int value = m_containerVolumeLimit.getMinValue(); + char delta = m_containerVolumeLimit.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getContainerVolumeLimitMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getContainerVolumeLimitMin + +int SharedObjectTemplate::getContainerVolumeLimitMax(bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getContainerVolumeLimitMax(true); +#endif + } + + if (!m_containerVolumeLimit.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter containerVolumeLimit in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter containerVolumeLimit has not been defined in template %s!", DataResource::getName())); + return base->getContainerVolumeLimitMax(); + } + } + + int value = m_containerVolumeLimit.getMaxValue(); + char delta = m_containerVolumeLimit.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getContainerVolumeLimitMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getContainerVolumeLimitMax + +const std::string & SharedObjectTemplate::getTintPalette(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getTintPalette(true); +#endif + } + + if (!m_tintPalette.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter tintPalette in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter tintPalette has not been defined in template %s!", DataResource::getName())); + return base->getTintPalette(); + } + } + + const std::string & value = m_tintPalette.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getTintPalette + +const std::string & SharedObjectTemplate::getSlotDescriptorFilename(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSlotDescriptorFilename(true); +#endif + } + + if (!m_slotDescriptorFilename.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter slotDescriptorFilename in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter slotDescriptorFilename has not been defined in template %s!", DataResource::getName())); + return base->getSlotDescriptorFilename(); + } + } + + const std::string & value = m_slotDescriptorFilename.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getSlotDescriptorFilename + +const std::string & SharedObjectTemplate::getArrangementDescriptorFilename(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getArrangementDescriptorFilename(true); +#endif + } + + if (!m_arrangementDescriptorFilename.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter arrangementDescriptorFilename in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter arrangementDescriptorFilename has not been defined in template %s!", DataResource::getName())); + return base->getArrangementDescriptorFilename(); + } + } + + const std::string & value = m_arrangementDescriptorFilename.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getArrangementDescriptorFilename + +const std::string & SharedObjectTemplate::getAppearanceFilename(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getAppearanceFilename(true); +#endif + } + + if (!m_appearanceFilename.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter appearanceFilename in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter appearanceFilename has not been defined in template %s!", DataResource::getName())); + return base->getAppearanceFilename(); + } + } + + const std::string & value = m_appearanceFilename.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getAppearanceFilename + +const std::string & SharedObjectTemplate::getPortalLayoutFilename(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getPortalLayoutFilename(true); +#endif + } + + if (!m_portalLayoutFilename.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter portalLayoutFilename in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter portalLayoutFilename has not been defined in template %s!", DataResource::getName())); + return base->getPortalLayoutFilename(); + } + } + + const std::string & value = m_portalLayoutFilename.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getPortalLayoutFilename + +const std::string & SharedObjectTemplate::getClientDataFile(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getClientDataFile(true); +#endif + } + + if (!m_clientDataFile.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter clientDataFile in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter clientDataFile has not been defined in template %s!", DataResource::getName())); + return base->getClientDataFile(); + } + } + + const std::string & value = m_clientDataFile.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getClientDataFile + +float SharedObjectTemplate::getScale(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getScale(true); +#endif + } + + if (!m_scale.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter scale in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter scale has not been defined in template %s!", DataResource::getName())); + return base->getScale(); + } + } + + float value = m_scale.getValue(); + char delta = m_scale.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getScale(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getScale + +float SharedObjectTemplate::getScaleMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getScaleMin(true); +#endif + } + + if (!m_scale.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter scale in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter scale has not been defined in template %s!", DataResource::getName())); + return base->getScaleMin(); + } + } + + float value = m_scale.getMinValue(); + char delta = m_scale.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getScaleMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getScaleMin + +float SharedObjectTemplate::getScaleMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getScaleMax(true); +#endif + } + + if (!m_scale.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter scale in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter scale has not been defined in template %s!", DataResource::getName())); + return base->getScaleMax(); + } + } + + float value = m_scale.getMaxValue(); + char delta = m_scale.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getScaleMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getScaleMax + +SharedObjectTemplate::GameObjectType SharedObjectTemplate::getGameObjectType(bool testData) const +{ +#ifdef _DEBUG +SharedObjectTemplate::GameObjectType testDataValue = static_cast(0); +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getGameObjectType(true); +#endif + } + + if (!m_gameObjectType.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter gameObjectType in template %s", DataResource::getName())); + return static_cast(0); + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter gameObjectType has not been defined in template %s!", DataResource::getName())); + return base->getGameObjectType(); + } + } + + GameObjectType value = static_cast(m_gameObjectType.getValue()); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getGameObjectType + +bool SharedObjectTemplate::getSendToClient(bool testData) const +{ +#ifdef _DEBUG +bool testDataValue = false; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSendToClient(true); +#endif + } + + if (!m_sendToClient.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter sendToClient in template %s", DataResource::getName())); + return false; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter sendToClient has not been defined in template %s!", DataResource::getName())); + return base->getSendToClient(); + } + } + + bool value = m_sendToClient.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getSendToClient + +float SharedObjectTemplate::getScaleThresholdBeforeExtentTest(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getScaleThresholdBeforeExtentTest(true); +#endif + } + + if (!m_scaleThresholdBeforeExtentTest.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter scaleThresholdBeforeExtentTest in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter scaleThresholdBeforeExtentTest has not been defined in template %s!", DataResource::getName())); + return base->getScaleThresholdBeforeExtentTest(); + } + } + + float value = m_scaleThresholdBeforeExtentTest.getValue(); + char delta = m_scaleThresholdBeforeExtentTest.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getScaleThresholdBeforeExtentTest(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getScaleThresholdBeforeExtentTest + +float SharedObjectTemplate::getScaleThresholdBeforeExtentTestMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getScaleThresholdBeforeExtentTestMin(true); +#endif + } + + if (!m_scaleThresholdBeforeExtentTest.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter scaleThresholdBeforeExtentTest in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter scaleThresholdBeforeExtentTest has not been defined in template %s!", DataResource::getName())); + return base->getScaleThresholdBeforeExtentTestMin(); + } + } + + float value = m_scaleThresholdBeforeExtentTest.getMinValue(); + char delta = m_scaleThresholdBeforeExtentTest.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getScaleThresholdBeforeExtentTestMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getScaleThresholdBeforeExtentTestMin + +float SharedObjectTemplate::getScaleThresholdBeforeExtentTestMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getScaleThresholdBeforeExtentTestMax(true); +#endif + } + + if (!m_scaleThresholdBeforeExtentTest.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter scaleThresholdBeforeExtentTest in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter scaleThresholdBeforeExtentTest has not been defined in template %s!", DataResource::getName())); + return base->getScaleThresholdBeforeExtentTestMax(); + } + } + + float value = m_scaleThresholdBeforeExtentTest.getMaxValue(); + char delta = m_scaleThresholdBeforeExtentTest.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getScaleThresholdBeforeExtentTestMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getScaleThresholdBeforeExtentTestMax + +float SharedObjectTemplate::getClearFloraRadius(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getClearFloraRadius(true); +#endif + } + + if (!m_clearFloraRadius.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter clearFloraRadius in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter clearFloraRadius has not been defined in template %s!", DataResource::getName())); + return base->getClearFloraRadius(); + } + } + + float value = m_clearFloraRadius.getValue(); + char delta = m_clearFloraRadius.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getClearFloraRadius(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getClearFloraRadius + +float SharedObjectTemplate::getClearFloraRadiusMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getClearFloraRadiusMin(true); +#endif + } + + if (!m_clearFloraRadius.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter clearFloraRadius in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter clearFloraRadius has not been defined in template %s!", DataResource::getName())); + return base->getClearFloraRadiusMin(); + } + } + + float value = m_clearFloraRadius.getMinValue(); + char delta = m_clearFloraRadius.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getClearFloraRadiusMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getClearFloraRadiusMin + +float SharedObjectTemplate::getClearFloraRadiusMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getClearFloraRadiusMax(true); +#endif + } + + if (!m_clearFloraRadius.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter clearFloraRadius in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter clearFloraRadius has not been defined in template %s!", DataResource::getName())); + return base->getClearFloraRadiusMax(); + } + } + + float value = m_clearFloraRadius.getMaxValue(); + char delta = m_clearFloraRadius.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getClearFloraRadiusMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getClearFloraRadiusMax + +SharedObjectTemplate::SurfaceType SharedObjectTemplate::getSurfaceType(bool testData) const +{ +#ifdef _DEBUG +SharedObjectTemplate::SurfaceType testDataValue = static_cast(0); +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSurfaceType(true); +#endif + } + + if (!m_surfaceType.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter surfaceType in template %s", DataResource::getName())); + return static_cast(0); + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter surfaceType has not been defined in template %s!", DataResource::getName())); + return base->getSurfaceType(); + } + } + + SurfaceType value = static_cast(m_surfaceType.getValue()); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getSurfaceType + +float SharedObjectTemplate::getNoBuildRadius(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getNoBuildRadius(true); +#endif + } + + if (!m_noBuildRadius.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter noBuildRadius in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter noBuildRadius has not been defined in template %s!", DataResource::getName())); + return base->getNoBuildRadius(); + } + } + + float value = m_noBuildRadius.getValue(); + char delta = m_noBuildRadius.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getNoBuildRadius(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getNoBuildRadius + +float SharedObjectTemplate::getNoBuildRadiusMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getNoBuildRadiusMin(true); +#endif + } + + if (!m_noBuildRadius.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter noBuildRadius in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter noBuildRadius has not been defined in template %s!", DataResource::getName())); + return base->getNoBuildRadiusMin(); + } + } + + float value = m_noBuildRadius.getMinValue(); + char delta = m_noBuildRadius.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getNoBuildRadiusMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getNoBuildRadiusMin + +float SharedObjectTemplate::getNoBuildRadiusMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getNoBuildRadiusMax(true); +#endif + } + + if (!m_noBuildRadius.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter noBuildRadius in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter noBuildRadius has not been defined in template %s!", DataResource::getName())); + return base->getNoBuildRadiusMax(); + } + } + + float value = m_noBuildRadius.getMaxValue(); + char delta = m_noBuildRadius.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getNoBuildRadiusMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getNoBuildRadiusMax + +bool SharedObjectTemplate::getOnlyVisibleInTools(bool testData) const +{ +#ifdef _DEBUG +bool testDataValue = false; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getOnlyVisibleInTools(true); +#endif + } + + if (!m_onlyVisibleInTools.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter onlyVisibleInTools in template %s", DataResource::getName())); + return false; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter onlyVisibleInTools has not been defined in template %s!", DataResource::getName())); + return base->getOnlyVisibleInTools(); + } + } + + bool value = m_onlyVisibleInTools.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getOnlyVisibleInTools + +float SharedObjectTemplate::getLocationReservationRadius(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getLocationReservationRadius(true); +#endif + } + + if (!m_locationReservationRadius.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter locationReservationRadius in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter locationReservationRadius has not been defined in template %s!", DataResource::getName())); + return base->getLocationReservationRadius(); + } + } + + float value = m_locationReservationRadius.getValue(); + char delta = m_locationReservationRadius.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getLocationReservationRadius(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getLocationReservationRadius + +float SharedObjectTemplate::getLocationReservationRadiusMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getLocationReservationRadiusMin(true); +#endif + } + + if (!m_locationReservationRadius.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter locationReservationRadius in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter locationReservationRadius has not been defined in template %s!", DataResource::getName())); + return base->getLocationReservationRadiusMin(); + } + } + + float value = m_locationReservationRadius.getMinValue(); + char delta = m_locationReservationRadius.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getLocationReservationRadiusMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getLocationReservationRadiusMin + +float SharedObjectTemplate::getLocationReservationRadiusMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getLocationReservationRadiusMax(true); +#endif + } + + if (!m_locationReservationRadius.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter locationReservationRadius in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter locationReservationRadius has not been defined in template %s!", DataResource::getName())); + return base->getLocationReservationRadiusMax(); + } + } + + float value = m_locationReservationRadius.getMaxValue(); + char delta = m_locationReservationRadius.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getLocationReservationRadiusMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getLocationReservationRadiusMax + +bool SharedObjectTemplate::getForceNoCollision(bool testData) const +{ +#ifdef _DEBUG +bool testDataValue = false; +#else +UNREF(testData); +#endif + + const SharedObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getForceNoCollision(true); +#endif + } + + if (!m_forceNoCollision.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter forceNoCollision in template %s", DataResource::getName())); + return false; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter forceNoCollision has not been defined in template %s!", DataResource::getName())); + return base->getForceNoCollision(); + } + } + + bool value = m_forceNoCollision.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedObjectTemplate::getForceNoCollision + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedObjectTemplate::testValues(void) const +{ + IGNORE_RETURN(getObjectName(true)); + IGNORE_RETURN(getDetailedDescription(true)); + IGNORE_RETURN(getLookAtText(true)); + IGNORE_RETURN(getSnapToTerrain(true)); + IGNORE_RETURN(getContainerType(true)); + IGNORE_RETURN(getContainerVolumeLimitMin(true)); + IGNORE_RETURN(getContainerVolumeLimitMax(true)); + IGNORE_RETURN(getTintPalette(true)); + IGNORE_RETURN(getSlotDescriptorFilename(true)); + IGNORE_RETURN(getArrangementDescriptorFilename(true)); + IGNORE_RETURN(getAppearanceFilename(true)); + IGNORE_RETURN(getPortalLayoutFilename(true)); + IGNORE_RETURN(getClientDataFile(true)); + IGNORE_RETURN(getScaleMin(true)); + IGNORE_RETURN(getScaleMax(true)); + IGNORE_RETURN(getGameObjectType(true)); + IGNORE_RETURN(getSendToClient(true)); + IGNORE_RETURN(getScaleThresholdBeforeExtentTestMin(true)); + IGNORE_RETURN(getScaleThresholdBeforeExtentTestMax(true)); + IGNORE_RETURN(getClearFloraRadiusMin(true)); + IGNORE_RETURN(getClearFloraRadiusMax(true)); + IGNORE_RETURN(getSurfaceType(true)); + IGNORE_RETURN(getNoBuildRadiusMin(true)); + IGNORE_RETURN(getNoBuildRadiusMax(true)); + IGNORE_RETURN(getOnlyVisibleInTools(true)); + IGNORE_RETURN(getLocationReservationRadiusMin(true)); + IGNORE_RETURN(getLocationReservationRadiusMax(true)); + IGNORE_RETURN(getForceNoCollision(true)); +} // SharedObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedObjectTemplate_tag) + { + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,1,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "objectName") == 0) + m_objectName.loadFromIff(file); + else if (strcmp(paramName, "detailedDescription") == 0) + m_detailedDescription.loadFromIff(file); + else if (strcmp(paramName, "lookAtText") == 0) + m_lookAtText.loadFromIff(file); + else if (strcmp(paramName, "snapToTerrain") == 0) + m_snapToTerrain.loadFromIff(file); + else if (strcmp(paramName, "containerType") == 0) + m_containerType.loadFromIff(file); + else if (strcmp(paramName, "containerVolumeLimit") == 0) + m_containerVolumeLimit.loadFromIff(file); + else if (strcmp(paramName, "tintPalette") == 0) + m_tintPalette.loadFromIff(file); + else if (strcmp(paramName, "slotDescriptorFilename") == 0) + m_slotDescriptorFilename.loadFromIff(file); + else if (strcmp(paramName, "arrangementDescriptorFilename") == 0) + m_arrangementDescriptorFilename.loadFromIff(file); + else if (strcmp(paramName, "appearanceFilename") == 0) + m_appearanceFilename.loadFromIff(file); + else if (strcmp(paramName, "portalLayoutFilename") == 0) + m_portalLayoutFilename.loadFromIff(file); + else if (strcmp(paramName, "clientDataFile") == 0) + m_clientDataFile.loadFromIff(file); + else if (strcmp(paramName, "scale") == 0) + m_scale.loadFromIff(file); + else if (strcmp(paramName, "gameObjectType") == 0) + m_gameObjectType.loadFromIff(file); + else if (strcmp(paramName, "sendToClient") == 0) + m_sendToClient.loadFromIff(file); + else if (strcmp(paramName, "scaleThresholdBeforeExtentTest") == 0) + m_scaleThresholdBeforeExtentTest.loadFromIff(file); + else if (strcmp(paramName, "clearFloraRadius") == 0) + m_clearFloraRadius.loadFromIff(file); + else if (strcmp(paramName, "surfaceType") == 0) + m_surfaceType.loadFromIff(file); + else if (strcmp(paramName, "noBuildRadius") == 0) + m_noBuildRadius.loadFromIff(file); + else if (strcmp(paramName, "onlyVisibleInTools") == 0) + m_onlyVisibleInTools.loadFromIff(file); + else if (strcmp(paramName, "locationReservationRadius") == 0) + m_locationReservationRadius.loadFromIff(file); + else if (strcmp(paramName, "forceNoCollision") == 0) + m_forceNoCollision.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + return; +} // SharedObjectTemplate::load + +//@END TFD + +//=================================================================== +// PUBLIC STATIC SharedObjectTemplate +//=================================================================== + +void SharedObjectTemplate::setCreateClientDataFunction (SharedObjectTemplate::CreateClientDataFunction createClientDataFunction) +{ + ms_createClientDataFunction = createClientDataFunction; +} + +//=================================================================== +// PUBLIC SharedObjectTemplate +//=================================================================== + +const SharedObjectTemplateClientData* SharedObjectTemplate::getClientData () const +{ + return m_clientData; +} + +//=================================================================== +// PRIVATE STATIC SharedObjectTemplate +//=================================================================== + +SharedObjectTemplate::CreateClientDataFunction SharedObjectTemplate::ms_createClientDataFunction; + +//=================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplate.h new file mode 100644 index 00000000..5fc7686f --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplate.h @@ -0,0 +1,484 @@ +//======================================================================== +// +// SharedObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedObjectTemplate_H +#define _INCLUDED_SharedObjectTemplate_H + +#include "sharedObject/ObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class ArrangementDescriptor; +class SharedObjectTemplateClientData; +class SlotDescriptor; +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + +class SharedObjectTemplate : public ObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedObjectTemplate_tag = TAG(S,H,O,T) + }; +//@END TFD ID +public: + SharedObjectTemplate(const std::string & filename); + virtual ~SharedObjectTemplate(); + + virtual SharedObjectTemplate * asSharedObjectTemplate(); + virtual SharedObjectTemplate const * asSharedObjectTemplate() const; + + virtual void preloadAssets () const; + virtual void garbageCollect () const; + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + enum ContainerType + { + CT_none, + CT_slotted, + CT_volume, // //This kind of container can hold tangible objects + CT_volumeIntangible, // //This kind of container can hold intangible objects + CT_volumeGeneric, // //This kind of container can hold any object tangible or not. + CT_ridable, // //This should be used for vehicles and mounts only: provides a slotted container with contents visible to the world + ContainerType_Last = CT_ridable, + }; + + enum GameObjectType + { + GOT_none = 0x00000000, + GOT_corpse, + GOT_group, + GOT_guild, + GOT_lair, + GOT_static, + GOT_camp, + GOT_vendor, + GOT_loadbeacon, + GOT_armor = 0x00000100, // //if you add armor types, please add them to the GOT_powerups as well + GOT_armor_body, + GOT_armor_head, + GOT_armor_misc, + GOT_armor_leg, + GOT_armor_arm, + GOT_armor_hand, + GOT_armor_foot, + GOT_armor_shield, + GOT_armor_layer, + GOT_armor_segment, + GOT_armor_core, + GOT_armor_psg, + GOT_building = 0x00000200, + GOT_building_municipal, + GOT_building_player, + GOT_building_factional, + GOT_creature = 0x00000400, + GOT_creature_character, + GOT_creature_droid, + GOT_creature_droid_probe, + GOT_creature_monster, + GOT_data = 0x00000800, + GOT_data_draft_schematic, + GOT_data_manufacturing_schematic, + GOT_data_mission_object, + GOT_data_token, + GOT_data_waypoint, + GOT_data_fictional, + GOT_data_pet_control_device, + GOT_data_vehicle_control_device, + GOT_data_draft_schematic_read_only, + GOT_data_ship_control_device, + GOT_data_droid_control_device, + GOT_data_house_control_device, + GOT_data_vendor_control_device, + GOT_data_player_quest_object, + GOT_installation = 0x00001000, + GOT_installation_factory, + GOT_installation_generator, + GOT_installation_harvester, + GOT_installation_turret, + GOT_installation_minefield, + GOT_misc = 0x00002000, + GOT_misc_ammunition, + GOT_misc_chemical, + GOT_misc_clothing_DUMMY, // // when you remove this, please recompile all the shared object templates + GOT_misc_component_DUMMY, // // when you remove this, please recompile all the shared object templates + GOT_misc_container, + GOT_misc_crafting_station, + GOT_misc_deed_DUMMY, + GOT_misc_electronics, + GOT_misc_flora, + GOT_misc_food, + GOT_misc_furniture, + GOT_misc_instrument, + GOT_misc_pharmaceutical, + GOT_misc_resource_container_DUMMY, // // when you remove this, please recompile all the shared object templates + GOT_misc_sign, + GOT_misc_counter, + GOT_misc_factory_crate, + GOT_misc_ticket_travel, + GOT_misc_item, // // generic 'usable' item + GOT_misc_trap, + GOT_misc_container_wearable, + GOT_misc_fishing_pole, + GOT_misc_fishing_bait, + GOT_misc_drink, + GOT_misc_firework, + GOT_misc_item_usable, + GOT_misc_petmed, + GOT_misc_firework_show, + GOT_misc_clothing_attachment, + GOT_misc_live_sample, + GOT_misc_armor_attachment, + GOT_misc_community_crafting_project, + GOT_misc_force_crystal, + GOT_misc_droid_programming_chip, + GOT_misc_asteroid, + GOT_misc_pob_ship_pilot_chair, + GOT_misc_operations_chair, + GOT_misc_turret_access_ladder, + GOT_misc_container_ship_loot, + GOT_misc_armor_noequip, + GOT_misc_enzyme, + GOT_misc_food_pet, + GOT_misc_collection, + GOT_misc_container_public, + GOT_misc_ground_target, + GOT_misc_blueprint, + GOT_misc_enzyme_isomerase, + GOT_misc_enzyme_lyase, + GOT_misc_enzyme_hydrolase, + GOT_misc_tcg_card, + GOT_misc_appearance_only, + GOT_misc_appearance_only_invisible, + GOT_terminal = 0x00004000, + GOT_terminal_bank, + GOT_terminal_bazaar, + GOT_terminal_cloning, + GOT_terminal_insurance, + GOT_terminal_manage, + GOT_terminal_mission, + GOT_terminal_permissions, + GOT_terminal_player_structure, + GOT_terminal_shipping, + GOT_terminal_travel, + GOT_terminal_space, + GOT_terminal_misc, + GOT_terminal_space_npe, + GOT_tool = 0x00008000, + GOT_tool_crafting, + GOT_tool_survey, + GOT_tool_repair, + GOT_tool_camp_kit, + GOT_tool_ship_component_repair, + GOT_vehicle = 0x00010000, + GOT_vehicle_hover, + GOT_vehicle_hover_ai, + GOT_weapon = 0x00020000, // //if you add weapon types, please add them to the GOT_powerups as well + GOT_weapon_melee_misc, + GOT_weapon_ranged_misc, + GOT_weapon_ranged_thrown, + GOT_weapon_heavy_misc, + GOT_weapon_heavy_mine, + GOT_weapon_heavy_special, + GOT_weapon_melee_1h, + GOT_weapon_melee_2h, + GOT_weapon_melee_polearm, + GOT_weapon_ranged_pistol, + GOT_weapon_ranged_carbine, + GOT_weapon_ranged_rifle, + GOT_component = 0x00040000, + GOT_component_armor, + GOT_component_chemistry, + GOT_component_clothing, + GOT_component_droid, + GOT_component_electronics, + GOT_component_munition, + GOT_component_structure, + GOT_component_weapon_melee, + GOT_component_weapon_ranged, + GOT_component_tissue, + GOT_component_genetic, + GOT_component_saber_crystal, + GOT_component_community_crafting, + GOT_component_new_armor, + GOT_powerup_weapon = 0x00080000, + GOT_powerup_weapon_melee, + GOT_powerup_weapon_ranged, + GOT_powerup_weapon_thrown, + GOT_powerup_weapon_heavy, + GOT_powerup_weapon_mine, + GOT_powerup_weapon_heavy_special, + GOT_powerup_armor = 0x00100000, + GOT_powerup_armor_body, + GOT_powerup_armor_head, + GOT_powerup_armor_misc, + GOT_powerup_armor_leg, + GOT_powerup_armor_arm, + GOT_powerup_armor_hand, + GOT_powerup_armor_foot, + GOT_powerup_armor_layer, + GOT_powerup_armor_segment, + GOT_powerup_armor_core, + GOT_jewelry = 0x00200000, + GOT_jewelry_ring, + GOT_jewelry_bracelet, + GOT_jewelry_necklace, + GOT_jewelry_earring, + GOT_resource_container = 0x00400000, + GOT_resource_container_energy_gas, + GOT_resource_container_energy_liquid, + GOT_resource_container_energy_radioactive, + GOT_resource_container_energy_solid, + GOT_resource_container_inorganic_chemicals, + GOT_resource_container_inorganic_gas, + GOT_resource_container_inorganic_minerals, + GOT_resource_container_inorganic_water, + GOT_resource_container_organic_food, + GOT_resource_container_organic_hide, + GOT_resource_container_organic_structure, + GOT_resource_container_pseudo, + GOT_resource_container_space, + GOT_deed = 0x00800000, + GOT_deed_building, + GOT_deed_installation, + GOT_deed_pet, + GOT_deed_droid, + GOT_deed_vehicle, + GOT_clothing = 0x01000000, + GOT_clothing_bandolier, + GOT_clothing_belt, + GOT_clothing_bodysuit, + GOT_clothing_cape, + GOT_clothing_cloak, + GOT_clothing_foot, + GOT_clothing_dress, + GOT_clothing_hand, + GOT_clothing_eye, + GOT_clothing_head, + GOT_clothing_jacket, + GOT_clothing_pants, + GOT_clothing_robe, + GOT_clothing_shirt, + GOT_clothing_vest, + GOT_clothing_wookiee, + GOT_clothing_misc, + GOT_clothing_skirt, + GOT_ship_component = 0x40000000, // //add space-specific GOTS at the "end" to make merging easier + GOT_ship_component_reactor, + GOT_ship_component_engine, + GOT_ship_component_shield, + GOT_ship_component_armor, + GOT_ship_component_weapon, + GOT_ship_component_capacitor, + GOT_ship_component_booster, + GOT_ship_component_droid_interface, + GOT_ship_component_hangar, + GOT_ship_component_targeting_station, + GOT_ship_component_bridge, + GOT_ship_component_chassis, + GOT_ship_component_missilepack, + GOT_ship_component_countermeasurepack, + GOT_ship_component_missilelauncher, + GOT_ship_component_countermeasurelauncher, + GOT_ship_component_cargo_hold, + GOT_ship_component_modification, + GOT_ship = 0x20000000, + GOT_ship_fighter, + GOT_ship_capital, + GOT_ship_station, + GOT_ship_transport, + GOT_ship_mining_asteroid_static, + GOT_ship_mining_asteroid_dynamic, + GOT_cybernetic = 0x20000100, + GOT_cybernetic_arm, + GOT_cybernetic_legs, + GOT_cybernetic_torso, + GOT_cybernetic_forearm, + GOT_cybernetic_hand, + GOT_cybernetic_component, + GOT_chronicles = 0x00001100, + GOT_chronicles_relic, + GOT_chronicles_chronicle, + GOT_chronicles_quest_holocron, + GOT_chronicles_quest_holocron_recipe, + GOT_chronicles_relic_fragment, + GameObjectType_Last = GOT_chronicles_relic_fragment, + }; + + enum SurfaceType + { + ST_other, + ST_metal, + ST_stone, + ST_wood, + ST_acid, + ST_ice, + ST_molten, + ST_obsidian, + SurfaceType_Last = ST_obsidian, + }; + +public: + const StringId getObjectName(bool testData = false) const; + const StringId getDetailedDescription(bool testData = false) const; + const StringId getLookAtText(bool testData = false) const; + bool getSnapToTerrain(bool testData = false) const; + ContainerType getContainerType(bool testData = false) const; + int getContainerVolumeLimit(bool testData = false) const; + int getContainerVolumeLimitMin(bool testData = false) const; + int getContainerVolumeLimitMax(bool testData = false) const; + const std::string & getTintPalette(bool testData = false) const; + const std::string & getSlotDescriptorFilename(bool testData = false) const; + const std::string & getArrangementDescriptorFilename(bool testData = false) const; + const std::string & getAppearanceFilename(bool testData = false) const; + const std::string & getPortalLayoutFilename(bool testData = false) const; + const std::string & getClientDataFile(bool testData = false) const; + float getScale(bool testData = false) const; + float getScaleMin(bool testData = false) const; + float getScaleMax(bool testData = false) const; + GameObjectType getGameObjectType(bool testData = false) const; + bool getSendToClient(bool testData = false) const; + float getScaleThresholdBeforeExtentTest(bool testData = false) const; + float getScaleThresholdBeforeExtentTestMin(bool testData = false) const; + float getScaleThresholdBeforeExtentTestMax(bool testData = false) const; + float getClearFloraRadius(bool testData = false) const; + float getClearFloraRadiusMin(bool testData = false) const; + float getClearFloraRadiusMax(bool testData = false) const; + SurfaceType getSurfaceType(bool testData = false) const; + float getNoBuildRadius(bool testData = false) const; + float getNoBuildRadiusMin(bool testData = false) const; + float getNoBuildRadiusMax(bool testData = false) const; + bool getOnlyVisibleInTools(bool testData = false) const; + float getLocationReservationRadius(bool testData = false) const; + float getLocationReservationRadiusMin(bool testData = false) const; + float getLocationReservationRadiusMax(bool testData = false) const; + bool getForceNoCollision(bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + StringIdParam m_objectName; // //the default name of this object + StringIdParam m_detailedDescription; // //long description of the object + StringIdParam m_lookAtText; // //? does this differ from detailedDescription ? + BoolParam m_snapToTerrain; // //flag that the object is snapped to terrain on addition to the world + IntegerParam m_containerType; // //if this is a container, what kind + IntegerParam m_containerVolumeLimit; // //if this object has a volume container, this say how much it can hold. + StringParam m_tintPalette; // //what tints are available to the object + StringParam m_slotDescriptorFilename; // //what slots are available for this object + StringParam m_arrangementDescriptorFilename; // //what slots this object can be put into + StringParam m_appearanceFilename; // //? + StringParam m_portalLayoutFilename; // //? + StringParam m_clientDataFile; // //client-specific data + FloatParam m_scale; // //modification to object's size + IntegerParam m_gameObjectType; // // game object type + BoolParam m_sendToClient; // //specifies whether or not the object using this template should is sent to the client + FloatParam m_scaleThresholdBeforeExtentTest; // //specifies the scale at which the object will use box extents for collision + FloatParam m_clearFloraRadius; // // distance to clear collidable flora around this object + IntegerParam m_surfaceType; + FloatParam m_noBuildRadius; // // distance to not allow structure placement around this object + BoolParam m_onlyVisibleInTools; + FloatParam m_locationReservationRadius; + BoolParam m_forceNoCollision; +//@END TFD + +public: + + // user functions + virtual void postLoad(void); + const SlotDescriptor * getSlotDescriptor() const; + const ArrangementDescriptor * getArrangementDescriptor() const; + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedObjectTemplate(const SharedObjectTemplate &); + SharedObjectTemplate & operator =(const SharedObjectTemplate &); + +private: + // user data + const SlotDescriptor * m_slotDescriptor; + const ArrangementDescriptor * m_arrangementDescriptor; + +public: + + typedef const SharedObjectTemplateClientData* (*CreateClientDataFunction) (const char* fileName); + +public: + + static void setCreateClientDataFunction (CreateClientDataFunction createClientDataFunction); + +public: + + const SharedObjectTemplateClientData* getClientData () const; + +private: + + static CreateClientDataFunction ms_createClientDataFunction; + +private: + + const SharedObjectTemplateClientData* m_clientData; + + class PreloadManager; + friend class PreloadManager; + mutable PreloadManager* m_preloadManager; +}; + + +inline void SharedObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedObjectTemplate::registerMe(); +//@END TFD INSTALL +} + +// ---------------------------------------------------------------------- + +inline const SlotDescriptor *SharedObjectTemplate::getSlotDescriptor() const +{ + return m_slotDescriptor; +} + +// ---------------------------------------------------------------------- + +inline const ArrangementDescriptor *SharedObjectTemplate::getArrangementDescriptor() const +{ + return m_arrangementDescriptor; +} + + +#endif // _INCLUDED_SharedObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplateClientData.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplateClientData.cpp new file mode 100644 index 00000000..19775c95 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplateClientData.cpp @@ -0,0 +1,28 @@ +//=================================================================== +// +// SharedObjectTemplateClientData.cpp +// asommers +// +// copyright 2002, sony online entertainment +// +//=================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SharedObjectTemplateClientData.h" + +//=================================================================== +// PUBLIC SharedObjectTemplateClientData +//=================================================================== + +SharedObjectTemplateClientData::SharedObjectTemplateClientData (const char* filename) : + DataResource (filename) +{ +} + +//------------------------------------------------------------------- + +SharedObjectTemplateClientData::~SharedObjectTemplateClientData () +{ +} + +//=================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplateClientData.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplateClientData.h new file mode 100644 index 00000000..d5f8d966 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplateClientData.h @@ -0,0 +1,35 @@ +//=================================================================== +// +// SharedObjectTemplateClientData.h +// asommers +// +// copyright 2002, sony online entertainment +// +//=================================================================== + +#ifndef INCLUDED_SharedObjectTemplateClientData_H +#define INCLUDED_SharedObjectTemplateClientData_H + +//=================================================================== + +#include "sharedFoundation/DataResource.h" + +//=================================================================== + +class SharedObjectTemplateClientData : public DataResource +{ +public: + + explicit SharedObjectTemplateClientData (const char* filename); + virtual ~SharedObjectTemplateClientData () = 0; + +private: + + SharedObjectTemplateClientData (); + SharedObjectTemplateClientData (const SharedObjectTemplateClientData&); + SharedObjectTemplateClientData& operator= (const SharedObjectTemplateClientData&); +}; + +//=================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplateInterface.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplateInterface.cpp new file mode 100644 index 00000000..12a5d1a3 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplateInterface.cpp @@ -0,0 +1,18 @@ +//====================================================================== +// +// SharedObjectTemplateInterface.cpp +// copyright (c) 2004 Sony Online Entertainment +// tford +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SharedObjectTemplateInterface.h" + +SharedObjectTemplateInterface::SharedObjectTemplateInterface() +{ +} + +SharedObjectTemplateInterface::~SharedObjectTemplateInterface() +{ +} diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplateInterface.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplateInterface.h new file mode 100644 index 00000000..8cbfc237 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedObjectTemplateInterface.h @@ -0,0 +1,37 @@ +//====================================================================== +// +// SharedObjectTemplateInterface.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_SharedObjectTemplateInterface_H +#define INCLUDED_SharedObjectTemplateInterface_H + +//====================================================================== + +class Object; +class SharedObjectTemplate; + +//---------------------------------------------------------------------- + +class SharedObjectTemplateInterface +{ +public: + SharedObjectTemplateInterface(); + virtual ~SharedObjectTemplateInterface(); + + virtual SharedObjectTemplate const * getSharedTemplate(Object const * object) const = 0; + virtual bool isShipObject(Object const * object) const = 0; + virtual uint32 getShipChassisType(Object const * object) const = 0; + virtual uint32 getShipComponentCrc(Object const * object, int chassisSlot) const = 0; + +private: + + SharedObjectTemplateInterface(SharedObjectTemplateInterface const & copy); + SharedObjectTemplateInterface & operator=(SharedObjectTemplateInterface const & copy); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedPlayerObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedPlayerObjectTemplate.cpp new file mode 100644 index 00000000..50ec4bcd --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedPlayerObjectTemplate.cpp @@ -0,0 +1,176 @@ +//======================================================================== +// +// SharedPlayerObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedPlayerObjectTemplate.h" +#include "sharedDebug/DataLint.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedPlayerObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedPlayerObjectTemplate::SharedPlayerObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedIntangibleObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedPlayerObjectTemplate::SharedPlayerObjectTemplate + +/** + * Class destructor. + */ +SharedPlayerObjectTemplate::~SharedPlayerObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedPlayerObjectTemplate::~SharedPlayerObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedPlayerObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedPlayerObjectTemplate_tag, create); +} // SharedPlayerObjectTemplate::registerMe + +/** + * Creates a SharedPlayerObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedPlayerObjectTemplate::create(const std::string & filename) +{ + return new SharedPlayerObjectTemplate(filename); +} // SharedPlayerObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedPlayerObjectTemplate::getId(void) const +{ + return SharedPlayerObjectTemplate_tag; +} // SharedPlayerObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedPlayerObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedPlayerObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedPlayerObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedPlayerObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedPlayerObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedPlayerObjectTemplate::testValues(void) const +{ + SharedIntangibleObjectTemplate::testValues(); +} // SharedPlayerObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedPlayerObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedPlayerObjectTemplate_tag) + { + SharedIntangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedIntangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedPlayerObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedPlayerObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedPlayerObjectTemplate.h new file mode 100644 index 00000000..5b64f2f8 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedPlayerObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedPlayerObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedPlayerObjectTemplate_H +#define _INCLUDED_SharedPlayerObjectTemplate_H + +#include "SharedIntangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedPlayerObjectTemplate : public SharedIntangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedPlayerObjectTemplate_tag = TAG(S,P,L,Y) + }; +//@END TFD ID +public: + SharedPlayerObjectTemplate(const std::string & filename); + virtual ~SharedPlayerObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedPlayerObjectTemplate(const SharedPlayerObjectTemplate &); + SharedPlayerObjectTemplate & operator =(const SharedPlayerObjectTemplate &); +}; + + +inline void SharedPlayerObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedPlayerObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedPlayerObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedPlayerQuestObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedPlayerQuestObjectTemplate.cpp new file mode 100644 index 00000000..cb3f6f77 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedPlayerQuestObjectTemplate.cpp @@ -0,0 +1,176 @@ +//======================================================================== +// +// SharedPlayerQuestObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedPlayerQuestObjectTemplate.h" +#include "sharedDebug/DataLint.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedPlayerQuestObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedPlayerQuestObjectTemplate::SharedPlayerQuestObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedTangibleObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedPlayerQuestObjectTemplate::SharedPlayerQuestObjectTemplate + +/** + * Class destructor. + */ +SharedPlayerQuestObjectTemplate::~SharedPlayerQuestObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedPlayerQuestObjectTemplate::~SharedPlayerQuestObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedPlayerQuestObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedPlayerQuestObjectTemplate_tag, create); +} // SharedPlayerQuestObjectTemplate::registerMe + +/** + * Creates a SharedPlayerQuestObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedPlayerQuestObjectTemplate::create(const std::string & filename) +{ + return new SharedPlayerQuestObjectTemplate(filename); +} // SharedPlayerQuestObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedPlayerQuestObjectTemplate::getId(void) const +{ + return SharedPlayerQuestObjectTemplate_tag; +} // SharedPlayerQuestObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedPlayerQuestObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedPlayerQuestObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedPlayerQuestObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedPlayerQuestObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedPlayerQuestObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedPlayerQuestObjectTemplate::testValues(void) const +{ + SharedTangibleObjectTemplate::testValues(); +} // SharedPlayerQuestObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedPlayerQuestObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedPlayerQuestObjectTemplate_tag) + { + SharedTangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedTangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedPlayerQuestObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedPlayerQuestObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedPlayerQuestObjectTemplate.h new file mode 100644 index 00000000..e5c9260c --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedPlayerQuestObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedPlayerQuestObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedPlayerQuestObjectTemplate_H +#define _INCLUDED_SharedPlayerQuestObjectTemplate_H + +#include "SharedTangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedPlayerQuestObjectTemplate : public SharedTangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedPlayerQuestObjectTemplate_tag = TAG(S,P,Q,O) + }; +//@END TFD ID +public: + SharedPlayerQuestObjectTemplate(const std::string & filename); + virtual ~SharedPlayerQuestObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedPlayerQuestObjectTemplate(const SharedPlayerQuestObjectTemplate &); + SharedPlayerQuestObjectTemplate & operator =(const SharedPlayerQuestObjectTemplate &); +}; + + +inline void SharedPlayerQuestObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedPlayerQuestObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedPlayerQuestObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedResourceContainerObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedResourceContainerObjectTemplate.cpp new file mode 100644 index 00000000..8f9dfe89 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedResourceContainerObjectTemplate.cpp @@ -0,0 +1,175 @@ +//======================================================================== +// +// SharedResourceContainerObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedResourceContainerObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedResourceContainerObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedResourceContainerObjectTemplate::SharedResourceContainerObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedTangibleObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedResourceContainerObjectTemplate::SharedResourceContainerObjectTemplate + +/** + * Class destructor. + */ +SharedResourceContainerObjectTemplate::~SharedResourceContainerObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedResourceContainerObjectTemplate::~SharedResourceContainerObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedResourceContainerObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedResourceContainerObjectTemplate_tag, create); +} // SharedResourceContainerObjectTemplate::registerMe + +/** + * Creates a SharedResourceContainerObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedResourceContainerObjectTemplate::create(const std::string & filename) +{ + return new SharedResourceContainerObjectTemplate(filename); +} // SharedResourceContainerObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedResourceContainerObjectTemplate::getId(void) const +{ + return SharedResourceContainerObjectTemplate_tag; +} // SharedResourceContainerObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedResourceContainerObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedResourceContainerObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedResourceContainerObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedResourceContainerObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedResourceContainerObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedResourceContainerObjectTemplate::testValues(void) const +{ + SharedTangibleObjectTemplate::testValues(); +} // SharedResourceContainerObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedResourceContainerObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedResourceContainerObjectTemplate_tag) + { + SharedTangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedTangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedResourceContainerObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedResourceContainerObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedResourceContainerObjectTemplate.h new file mode 100644 index 00000000..86067879 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedResourceContainerObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedResourceContainerObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedResourceContainerObjectTemplate_H +#define _INCLUDED_SharedResourceContainerObjectTemplate_H + +#include "SharedTangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedResourceContainerObjectTemplate : public SharedTangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedResourceContainerObjectTemplate_tag = TAG(R,C,C,T) + }; +//@END TFD ID +public: + SharedResourceContainerObjectTemplate(const std::string & filename); + virtual ~SharedResourceContainerObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedResourceContainerObjectTemplate(const SharedResourceContainerObjectTemplate &); + SharedResourceContainerObjectTemplate & operator =(const SharedResourceContainerObjectTemplate &); +}; + + +inline void SharedResourceContainerObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedResourceContainerObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedResourceContainerObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedShipObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedShipObjectTemplate.cpp new file mode 100644 index 00000000..cbea91d7 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedShipObjectTemplate.cpp @@ -0,0 +1,403 @@ +//======================================================================== +// +// SharedShipObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SharedShipObjectTemplate.h" + +#include "sharedDebug/DataLint.h" +#include "sharedFile/Iff.h" +#include "sharedGame/AssetCustomizationManager.h" +#include "sharedMath/Vector.h" +#include "sharedObject/CustomizationData.h" +#include "sharedObject/CustomizationDataProperty.h" +#include "sharedObject/Object.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" + +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedShipObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedShipObjectTemplate::SharedShipObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedTangibleObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedShipObjectTemplate::SharedShipObjectTemplate + +/** + * Class destructor. + */ +SharedShipObjectTemplate::~SharedShipObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedShipObjectTemplate::~SharedShipObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedShipObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedShipObjectTemplate_tag, create); +} // SharedShipObjectTemplate::registerMe + +/** + * Creates a SharedShipObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedShipObjectTemplate::create(const std::string & filename) +{ + return new SharedShipObjectTemplate(filename); +} // SharedShipObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedShipObjectTemplate::getId(void) const +{ + return SharedShipObjectTemplate_tag; +} // SharedShipObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedShipObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedShipObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedShipObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedShipObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedShipObjectTemplate::getHighestTemplateVersion + +//---------------------------------------------------------------------- + +/** +* createCustomizationDataPropertyAsNeeded +*/ + +void SharedShipObjectTemplate::createCustomizationDataPropertyAsNeeded(Object &object, bool /* forceCreation */) const +{ + //-- Create the CustomizationDataProperty, add to Object property collection + CustomizationDataProperty *const cdProperty = new CustomizationDataProperty(object); + object.addProperty(*cdProperty); + + //-- Fetch the CustomizationData instance + CustomizationData *const customizationData = cdProperty->fetchCustomizationData(); + if (customizationData) + { + //-- Create customization variables associated with this appearance. Don't skip /shared_owner/ + // variables since we are a creature. The SharedTangibleObjectTemplate version of + // this function sets it to true. + bool const skipSharedOwnerVariables = false; + const std::string & appearanceFilename = getAppearanceFilename(); + if(!appearanceFilename.empty()) + { + AssetCustomizationManager::addCustomizationVariablesForAsset(TemporaryCrcString(appearanceFilename.c_str(), true), *customizationData, skipSharedOwnerVariables); + } + else + { + //Perhaps it's a POB ship, check the portalLayoutFilename + const std::string & portalLayoutFilename = getPortalLayoutFilename(); + AssetCustomizationManager::addCustomizationVariablesForAsset(TemporaryCrcString(portalLayoutFilename.c_str(), true), *customizationData, skipSharedOwnerVariables); + } + + //-- release local reference to the CustomizationData instance + customizationData->release(); + } +} + +//@BEGIN TFD +const std::string & SharedShipObjectTemplate::getCockpitFilename(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedShipObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCockpitFilename(true); +#endif + } + + if (!m_cockpitFilename.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter cockpitFilename in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter cockpitFilename has not been defined in template %s!", DataResource::getName())); + return base->getCockpitFilename(); + } + } + + const std::string & value = m_cockpitFilename.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedShipObjectTemplate::getCockpitFilename + +bool SharedShipObjectTemplate::getHasWings(bool testData) const +{ +#ifdef _DEBUG +bool testDataValue = false; +#else +UNREF(testData); +#endif + + const SharedShipObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getHasWings(true); +#endif + } + + if (!m_hasWings.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter hasWings in template %s", DataResource::getName())); + return false; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter hasWings has not been defined in template %s!", DataResource::getName())); + return base->getHasWings(); + } + } + + bool value = m_hasWings.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedShipObjectTemplate::getHasWings + +bool SharedShipObjectTemplate::getPlayerControlled(bool testData) const +{ +#ifdef _DEBUG +bool testDataValue = false; +#else +UNREF(testData); +#endif + + const SharedShipObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getPlayerControlled(true); +#endif + } + + if (!m_playerControlled.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter playerControlled in template %s", DataResource::getName())); + return false; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter playerControlled has not been defined in template %s!", DataResource::getName())); + return base->getPlayerControlled(); + } + } + + bool value = m_playerControlled.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedShipObjectTemplate::getPlayerControlled + +const std::string & SharedShipObjectTemplate::getInteriorLayoutFileName(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedShipObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getInteriorLayoutFileName(true); +#endif + } + + if (!m_interiorLayoutFileName.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter interiorLayoutFileName in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter interiorLayoutFileName has not been defined in template %s!", DataResource::getName())); + return base->getInteriorLayoutFileName(); + } + } + + const std::string & value = m_interiorLayoutFileName.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedShipObjectTemplate::getInteriorLayoutFileName + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedShipObjectTemplate::testValues(void) const +{ + IGNORE_RETURN(getCockpitFilename(true)); + IGNORE_RETURN(getHasWings(true)); + IGNORE_RETURN(getPlayerControlled(true)); + IGNORE_RETURN(getInteriorLayoutFileName(true)); + SharedTangibleObjectTemplate::testValues(); +} // SharedShipObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedShipObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedShipObjectTemplate_tag) + { + SharedTangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,4)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "cockpitFilename") == 0) + m_cockpitFilename.loadFromIff(file); + else if (strcmp(paramName, "hasWings") == 0) + m_hasWings.loadFromIff(file); + else if (strcmp(paramName, "playerControlled") == 0) + m_playerControlled.loadFromIff(file); + else if (strcmp(paramName, "interiorLayoutFileName") == 0) + m_interiorLayoutFileName.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + SharedTangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedShipObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedShipObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedShipObjectTemplate.h new file mode 100644 index 00000000..abbdb08e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedShipObjectTemplate.h @@ -0,0 +1,92 @@ +//======================================================================== +// +// SharedShipObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedShipObjectTemplate_H +#define _INCLUDED_SharedShipObjectTemplate_H + +#include "SharedTangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedShipObjectTemplate : public SharedTangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedShipObjectTemplate_tag = TAG(S,S,H,P) + }; +//@END TFD ID +public: + SharedShipObjectTemplate(const std::string & filename); + virtual ~SharedShipObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + virtual void createCustomizationDataPropertyAsNeeded(Object &object, bool forceCreation) const; + +//@BEGIN TFD +public: + const std::string & getCockpitFilename(bool testData = false) const; + bool getHasWings(bool testData = false) const; + bool getPlayerControlled(bool testData = false) const; + const std::string & getInteriorLayoutFileName(bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + StringParam m_cockpitFilename; + BoolParam m_hasWings; + BoolParam m_playerControlled; + StringParam m_interiorLayoutFileName; +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedShipObjectTemplate(const SharedShipObjectTemplate &); + SharedShipObjectTemplate & operator =(const SharedShipObjectTemplate &); +}; + + +inline void SharedShipObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedShipObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedShipObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedStaticObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedStaticObjectTemplate.cpp new file mode 100644 index 00000000..65ee046b --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedStaticObjectTemplate.cpp @@ -0,0 +1,175 @@ +//======================================================================== +// +// SharedStaticObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedStaticObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedStaticObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedStaticObjectTemplate::SharedStaticObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedStaticObjectTemplate::SharedStaticObjectTemplate + +/** + * Class destructor. + */ +SharedStaticObjectTemplate::~SharedStaticObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedStaticObjectTemplate::~SharedStaticObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedStaticObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedStaticObjectTemplate_tag, create); +} // SharedStaticObjectTemplate::registerMe + +/** + * Creates a SharedStaticObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedStaticObjectTemplate::create(const std::string & filename) +{ + return new SharedStaticObjectTemplate(filename); +} // SharedStaticObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedStaticObjectTemplate::getId(void) const +{ + return SharedStaticObjectTemplate_tag; +} // SharedStaticObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedStaticObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedStaticObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedStaticObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedStaticObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedStaticObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedStaticObjectTemplate::testValues(void) const +{ + SharedObjectTemplate::testValues(); +} // SharedStaticObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedStaticObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedStaticObjectTemplate_tag) + { + SharedObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedStaticObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedStaticObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedStaticObjectTemplate.h new file mode 100644 index 00000000..cc22dc7e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedStaticObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedStaticObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedStaticObjectTemplate_H +#define _INCLUDED_SharedStaticObjectTemplate_H + +#include "SharedObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedStaticObjectTemplate : public SharedObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedStaticObjectTemplate_tag = TAG(S,T,A,T) + }; +//@END TFD ID +public: + SharedStaticObjectTemplate(const std::string & filename); + virtual ~SharedStaticObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedStaticObjectTemplate(const SharedStaticObjectTemplate &); + SharedStaticObjectTemplate & operator =(const SharedStaticObjectTemplate &); +}; + + +inline void SharedStaticObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedStaticObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedStaticObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedTangibleObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedTangibleObjectTemplate.cpp new file mode 100644 index 00000000..da8dccd0 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedTangibleObjectTemplate.cpp @@ -0,0 +1,2892 @@ +//======================================================================== +// +// SharedTangibleObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedTangibleObjectTemplate.h" +#include "sharedFoundation/TemporaryCrcString.h" +#include "sharedFile/Iff.h" +#include "sharedGame/AssetCustomizationManager.h" +#include "sharedMath/PaletteArgb.h" +#include "sharedMath/PaletteArgbList.h" +#include "sharedObject/BasicRangedIntCustomizationVariable.h" +#include "sharedObject/CustomizationData.h" +#include "sharedObject/CustomizationDataProperty.h" +#include "sharedObject/Object.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/PaletteColorCustomizationVariable.h" +#include "sharedObject/StructureFootprint.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedTangibleObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedTangibleObjectTemplate::SharedTangibleObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedObjectTemplate(filename) + ,m_paletteColorCustomizationVariablesLoaded(false) + ,m_paletteColorCustomizationVariablesAppend(false) + ,m_rangedIntCustomizationVariablesLoaded(false) + ,m_rangedIntCustomizationVariablesAppend(false) + ,m_constStringCustomizationVariablesLoaded(false) + ,m_constStringCustomizationVariablesAppend(false) + ,m_socketDestinationsLoaded(false) + ,m_socketDestinationsAppend(false) + ,m_certificationsRequiredLoaded(false) + ,m_certificationsRequiredAppend(false) + ,m_customizationVariableMappingLoaded(false) + ,m_customizationVariableMappingAppend(false) + ,m_versionOk(true) +//@END TFD INIT + ,m_structureFootprint (0) +{ +} // SharedTangibleObjectTemplate::SharedTangibleObjectTemplate + +/** + * Class destructor. + */ +SharedTangibleObjectTemplate::~SharedTangibleObjectTemplate() +{ +//@BEGIN TFD CLEANUP + { + std::vector::iterator iter; + for (iter = m_paletteColorCustomizationVariables.begin(); iter != m_paletteColorCustomizationVariables.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_paletteColorCustomizationVariables.clear(); + } + { + std::vector::iterator iter; + for (iter = m_rangedIntCustomizationVariables.begin(); iter != m_rangedIntCustomizationVariables.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_rangedIntCustomizationVariables.clear(); + } + { + std::vector::iterator iter; + for (iter = m_constStringCustomizationVariables.begin(); iter != m_constStringCustomizationVariables.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_constStringCustomizationVariables.clear(); + } + { + std::vector::iterator iter; + for (iter = m_socketDestinations.begin(); iter != m_socketDestinations.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_socketDestinations.clear(); + } + { + std::vector::iterator iter; + for (iter = m_certificationsRequired.begin(); iter != m_certificationsRequired.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_certificationsRequired.clear(); + } + { + std::vector::iterator iter; + for (iter = m_customizationVariableMapping.begin(); iter != m_customizationVariableMapping.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_customizationVariableMapping.clear(); + } +//@END TFD CLEANUP + + if (m_structureFootprint) + { + delete m_structureFootprint; + m_structureFootprint = 0; + } +} // SharedTangibleObjectTemplate::~SharedTangibleObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedTangibleObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedTangibleObjectTemplate_tag, create); +} // SharedTangibleObjectTemplate::registerMe + +/** + * Creates a SharedTangibleObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedTangibleObjectTemplate::create(const std::string & filename) +{ + return new SharedTangibleObjectTemplate(filename); +} // SharedTangibleObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedTangibleObjectTemplate::getId(void) const +{ + return SharedTangibleObjectTemplate_tag; +} // SharedTangibleObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedTangibleObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedTangibleObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedTangibleObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedTangibleObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedTangibleObjectTemplate::getHighestTemplateVersion + +/** + * Perform any post load initialization on the object + */ +void SharedTangibleObjectTemplate::postLoad() +{ + SharedObjectTemplate::postLoad (); + + //-- load the structure footprint + if (getStructureFootprintFileName ().length () != 0) + { + m_structureFootprint = new StructureFootprint (); + m_structureFootprint->load (getStructureFootprintFileName ().c_str ()); + } +} + +/** + * Returns the structure footprint + * + * @return the structure footprint + */ +const StructureFootprint* SharedTangibleObjectTemplate::getStructureFootprint () const +{ + return m_structureFootprint; +} + +/** + * Create a CustomizationDataProperty and associate it with the specified Object. + * + * This function will not add a CustomizationDataProperty if there are no + * customization variables associated with the template or its base data template. + * + * The CustomizationData within the property will be filled with + * the variable and its default for each customization variable + * exported by this ObjectTemplate instance. + * + * The implementation makes use of the append-style base data class + * mechanism for the customization variable lists. + * + * The forceCreation feature is added to allow the caller to insist that a CustomizationData + * property be added to the Object. The client needs this functionality for wearables --- + * even if the wearable doesn't own any customization variables, it most likely needs to + * link and inherit customization data from its owner (the Object on which the wearable is + * worn). + * + * @param object the Object instance with which to create and associate the + * CustomizationDataProperty. + * @param forceCreation if true, will force a CustomizationData property to + * be created even if there are no customization variable + * declarations. + */ +void SharedTangibleObjectTemplate::createCustomizationDataPropertyAsNeeded(Object &object, bool /* forceCreation */) const +{ +#if 1 + //-- Properties cannot be added while an object is in the world. Some callers may be in the world, + // so temporarily remove the object from the world if necessary. + bool shouldBeInWorld = object.isInWorld(); + if (shouldBeInWorld) + object.removeFromWorld(); + + //-- create the CustomizationDataProperty, add to Object property collection + CustomizationDataProperty *const cdProperty = new CustomizationDataProperty(object); + object.addProperty(*cdProperty); + + //-- Put object back in world if it was originally there. + if (shouldBeInWorld) + object.addToWorld(); + + //-- fetch the CustomizationData instance + CustomizationData *const customizationData = cdProperty->fetchCustomizationData(); + if (customizationData) + { + //-- Create customization variables associated with this appearance. Skip /shared_owner/ + // variables since we're not a creature. The SharedCreatureObjectTemplate overrides + // this function and sets it to false. + bool const skipSharedOwnerVariables = true; + AssetCustomizationManager::addCustomizationVariablesForAsset(TemporaryCrcString(getAppearanceFilename().c_str(), true), *customizationData, skipSharedOwnerVariables); + + +#ifdef _DEBUG + //-- set up mappings for any variables which need dependent mappings + int numVariableMappings = getCustomizationVariableMappingCount(); + if(numVariableMappings != 0) + { + //If the object is a wearable, then the dependent variable, which is probably shared, will not exist at the moment the dependency + //is set up. For this reason, make sure that you're really doing what you want. + DEBUG_WARNING(true, ("Generally, CustomizationVariableMapping should not be set on Wearables or other non-Creature tangibles.")); + } +#endif + + //-- release local reference to the CustomizationData instance + customizationData->release(); + } + +#else + // @todo -TRF- remove this code as soon as asset customization manager is working properly. + const size_t paletteColorCount = getPaletteColorCustomizationVariablesCount(); + const size_t rangedIntCount = getRangedIntCustomizationVariablesCount(); + + //-- Return if caller isn't forcing customization data creation and no customization variables are declared for the ObjectTemplate. + const bool makeCustomizationData = forceCreation || (paletteColorCount > 0) || (rangedIntCount > 0); + if (!makeCustomizationData) + return; + + //-- Properties cannot be added while an object is in the world. Some callers may be in the world, + // so temporarily remove the object from the world if necessary. + bool shouldBeInWorld = object.isInWorld(); + if (shouldBeInWorld) + object.removeFromWorld(); + + //-- create the CustomizationDataProperty, add to Object property collection + CustomizationDataProperty *const cdProperty = new CustomizationDataProperty(object); + object.addProperty(*cdProperty); + + //-- Put object back in world if it was originally there. + if (shouldBeInWorld) + object.addToWorld(); + + //-- fetch the CustomizationData instance + CustomizationData *const customizationData = cdProperty->fetchCustomizationData(); + + //-- create PaletteColorCustomizationVariable variables as specified + { + SharedTangibleObjectTemplate::PaletteColorCustomizationVariable variableData; + + for (int i = 0; i < static_cast(paletteColorCount); ++i) + { + //-- get the palette variable data + getPaletteColorCustomizationVariables(variableData, i); + + //-- fetch the palette + const PaletteArgb *const palette = PaletteArgbList::fetch(TemporaryCrcString(variableData.palettePathName.c_str(), true)); + if (!palette) + { + DEBUG_WARNING(true, ("failed to retrieve color palette [%s] for [%s], skipping variable [%s].\n", variableData.palettePathName.c_str(), getName (), variableData.variableName.c_str())); + continue; + } + + //-- create the variable, add to CustomizationData + ::PaletteColorCustomizationVariable * const palColorVar = new ::PaletteColorCustomizationVariable(palette, variableData.defaultPaletteIndex); + + if (variableData.defaultPaletteIndex != palColorVar->getValue ()) + DEBUG_WARNING (true, ("Error loading PaletteColorCustomizationVariable [%s] for [%s]", variableData.variableName.c_str(), getName ())); + + customizationData->addVariableTakeOwnership(variableData.variableName, palColorVar); + + //-- release local palette reference + palette->release(); + } + } + + //-- create BasicRangedIntCustomizationVariable variables as specified + { + SharedTangibleObjectTemplate::RangedIntCustomizationVariable variableData; + + for (int i = 0; i < static_cast(rangedIntCount); ++i) + { + //-- get the palette variable data + getRangedIntCustomizationVariables(variableData, i); + + //-- create the variable, add to CustomizationData + customizationData->addVariableTakeOwnership(variableData.variableName, new ::BasicRangedIntCustomizationVariable(variableData.minValueInclusive, variableData.defaultValue, variableData.maxValueExclusive)); + } + } + //-- release local reference to the CustomizationData instance + customizationData->release(); +#endif +} + +//@BEGIN TFD +void SharedTangibleObjectTemplate::getPaletteColorCustomizationVariables(PaletteColorCustomizationVariable &data, int index) const +{ + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_paletteColorCustomizationVariablesLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter paletteColorCustomizationVariables in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter paletteColorCustomizationVariables has not been defined in template %s!", DataResource::getName())); + base->getPaletteColorCustomizationVariables(data, index); + return; + } + } + + if (m_paletteColorCustomizationVariablesAppend && base != NULL) + { + int baseCount = base->getPaletteColorCustomizationVariablesCount(); + if (index < baseCount) + { + base->getPaletteColorCustomizationVariables(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_paletteColorCustomizationVariables.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_paletteColorCustomizationVariables[index]).getValue(); + NOT_NULL(structTemplate); + const _PaletteColorCustomizationVariable *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.variableName = param->getVariableName(m_versionOk); + data.palettePathName = param->getPalettePathName(m_versionOk); + data.defaultPaletteIndex = param->getDefaultPaletteIndex(m_versionOk); +} // SharedTangibleObjectTemplate::getPaletteColorCustomizationVariables + +void SharedTangibleObjectTemplate::getPaletteColorCustomizationVariablesMin(PaletteColorCustomizationVariable &data, int index) const +{ + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_paletteColorCustomizationVariablesLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter paletteColorCustomizationVariables in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter paletteColorCustomizationVariables has not been defined in template %s!", DataResource::getName())); + base->getPaletteColorCustomizationVariablesMin(data, index); + return; + } + } + + if (m_paletteColorCustomizationVariablesAppend && base != NULL) + { + int baseCount = base->getPaletteColorCustomizationVariablesCount(); + if (index < baseCount) + { + base->getPaletteColorCustomizationVariablesMin(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_paletteColorCustomizationVariables.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_paletteColorCustomizationVariables[index]).getValue(); + NOT_NULL(structTemplate); + const _PaletteColorCustomizationVariable *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.variableName = param->getVariableName(m_versionOk); + data.palettePathName = param->getPalettePathName(m_versionOk); + data.defaultPaletteIndex = param->getDefaultPaletteIndexMin(m_versionOk); +} // SharedTangibleObjectTemplate::getPaletteColorCustomizationVariablesMin + +void SharedTangibleObjectTemplate::getPaletteColorCustomizationVariablesMax(PaletteColorCustomizationVariable &data, int index) const +{ + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_paletteColorCustomizationVariablesLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter paletteColorCustomizationVariables in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter paletteColorCustomizationVariables has not been defined in template %s!", DataResource::getName())); + base->getPaletteColorCustomizationVariablesMax(data, index); + return; + } + } + + if (m_paletteColorCustomizationVariablesAppend && base != NULL) + { + int baseCount = base->getPaletteColorCustomizationVariablesCount(); + if (index < baseCount) + { + base->getPaletteColorCustomizationVariablesMax(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_paletteColorCustomizationVariables.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_paletteColorCustomizationVariables[index]).getValue(); + NOT_NULL(structTemplate); + const _PaletteColorCustomizationVariable *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.variableName = param->getVariableName(m_versionOk); + data.palettePathName = param->getPalettePathName(m_versionOk); + data.defaultPaletteIndex = param->getDefaultPaletteIndexMax(m_versionOk); +} // SharedTangibleObjectTemplate::getPaletteColorCustomizationVariablesMax + +size_t SharedTangibleObjectTemplate::getPaletteColorCustomizationVariablesCount(void) const +{ + if (!m_paletteColorCustomizationVariablesLoaded) + { + if (m_baseData == NULL) + return 0; + const SharedTangibleObjectTemplate * base = dynamic_cast(m_baseData); + DEBUG_FATAL(base == NULL, ("base template wrong type")); + return base->getPaletteColorCustomizationVariablesCount(); + } + + size_t count = m_paletteColorCustomizationVariables.size(); + + // if we are extending our base template, add it's count + if (m_paletteColorCustomizationVariablesAppend && m_baseData != NULL) + { + const SharedTangibleObjectTemplate * base = dynamic_cast(m_baseData); + if (base != NULL) + count += base->getPaletteColorCustomizationVariablesCount(); + } + + return count; +} // SharedTangibleObjectTemplate::getPaletteColorCustomizationVariablesCount + +void SharedTangibleObjectTemplate::getRangedIntCustomizationVariables(RangedIntCustomizationVariable &data, int index) const +{ + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_rangedIntCustomizationVariablesLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter rangedIntCustomizationVariables in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter rangedIntCustomizationVariables has not been defined in template %s!", DataResource::getName())); + base->getRangedIntCustomizationVariables(data, index); + return; + } + } + + if (m_rangedIntCustomizationVariablesAppend && base != NULL) + { + int baseCount = base->getRangedIntCustomizationVariablesCount(); + if (index < baseCount) + { + base->getRangedIntCustomizationVariables(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_rangedIntCustomizationVariables.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_rangedIntCustomizationVariables[index]).getValue(); + NOT_NULL(structTemplate); + const _RangedIntCustomizationVariable *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.variableName = param->getVariableName(m_versionOk); + data.minValueInclusive = param->getMinValueInclusive(m_versionOk); + data.defaultValue = param->getDefaultValue(m_versionOk); + data.maxValueExclusive = param->getMaxValueExclusive(m_versionOk); +} // SharedTangibleObjectTemplate::getRangedIntCustomizationVariables + +void SharedTangibleObjectTemplate::getRangedIntCustomizationVariablesMin(RangedIntCustomizationVariable &data, int index) const +{ + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_rangedIntCustomizationVariablesLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter rangedIntCustomizationVariables in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter rangedIntCustomizationVariables has not been defined in template %s!", DataResource::getName())); + base->getRangedIntCustomizationVariablesMin(data, index); + return; + } + } + + if (m_rangedIntCustomizationVariablesAppend && base != NULL) + { + int baseCount = base->getRangedIntCustomizationVariablesCount(); + if (index < baseCount) + { + base->getRangedIntCustomizationVariablesMin(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_rangedIntCustomizationVariables.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_rangedIntCustomizationVariables[index]).getValue(); + NOT_NULL(structTemplate); + const _RangedIntCustomizationVariable *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.variableName = param->getVariableName(m_versionOk); + data.minValueInclusive = param->getMinValueInclusiveMin(m_versionOk); + data.defaultValue = param->getDefaultValueMin(m_versionOk); + data.maxValueExclusive = param->getMaxValueExclusiveMin(m_versionOk); +} // SharedTangibleObjectTemplate::getRangedIntCustomizationVariablesMin + +void SharedTangibleObjectTemplate::getRangedIntCustomizationVariablesMax(RangedIntCustomizationVariable &data, int index) const +{ + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_rangedIntCustomizationVariablesLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter rangedIntCustomizationVariables in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter rangedIntCustomizationVariables has not been defined in template %s!", DataResource::getName())); + base->getRangedIntCustomizationVariablesMax(data, index); + return; + } + } + + if (m_rangedIntCustomizationVariablesAppend && base != NULL) + { + int baseCount = base->getRangedIntCustomizationVariablesCount(); + if (index < baseCount) + { + base->getRangedIntCustomizationVariablesMax(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_rangedIntCustomizationVariables.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_rangedIntCustomizationVariables[index]).getValue(); + NOT_NULL(structTemplate); + const _RangedIntCustomizationVariable *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.variableName = param->getVariableName(m_versionOk); + data.minValueInclusive = param->getMinValueInclusiveMax(m_versionOk); + data.defaultValue = param->getDefaultValueMax(m_versionOk); + data.maxValueExclusive = param->getMaxValueExclusiveMax(m_versionOk); +} // SharedTangibleObjectTemplate::getRangedIntCustomizationVariablesMax + +size_t SharedTangibleObjectTemplate::getRangedIntCustomizationVariablesCount(void) const +{ + if (!m_rangedIntCustomizationVariablesLoaded) + { + if (m_baseData == NULL) + return 0; + const SharedTangibleObjectTemplate * base = dynamic_cast(m_baseData); + DEBUG_FATAL(base == NULL, ("base template wrong type")); + return base->getRangedIntCustomizationVariablesCount(); + } + + size_t count = m_rangedIntCustomizationVariables.size(); + + // if we are extending our base template, add it's count + if (m_rangedIntCustomizationVariablesAppend && m_baseData != NULL) + { + const SharedTangibleObjectTemplate * base = dynamic_cast(m_baseData); + if (base != NULL) + count += base->getRangedIntCustomizationVariablesCount(); + } + + return count; +} // SharedTangibleObjectTemplate::getRangedIntCustomizationVariablesCount + +void SharedTangibleObjectTemplate::getConstStringCustomizationVariables(ConstStringCustomizationVariable &data, int index) const +{ + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_constStringCustomizationVariablesLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter constStringCustomizationVariables in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter constStringCustomizationVariables has not been defined in template %s!", DataResource::getName())); + base->getConstStringCustomizationVariables(data, index); + return; + } + } + + if (m_constStringCustomizationVariablesAppend && base != NULL) + { + int baseCount = base->getConstStringCustomizationVariablesCount(); + if (index < baseCount) + { + base->getConstStringCustomizationVariables(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_constStringCustomizationVariables.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_constStringCustomizationVariables[index]).getValue(); + NOT_NULL(structTemplate); + const _ConstStringCustomizationVariable *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.variableName = param->getVariableName(m_versionOk); + data.constValue = param->getConstValue(m_versionOk); +} // SharedTangibleObjectTemplate::getConstStringCustomizationVariables + +void SharedTangibleObjectTemplate::getConstStringCustomizationVariablesMin(ConstStringCustomizationVariable &data, int index) const +{ + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_constStringCustomizationVariablesLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter constStringCustomizationVariables in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter constStringCustomizationVariables has not been defined in template %s!", DataResource::getName())); + base->getConstStringCustomizationVariablesMin(data, index); + return; + } + } + + if (m_constStringCustomizationVariablesAppend && base != NULL) + { + int baseCount = base->getConstStringCustomizationVariablesCount(); + if (index < baseCount) + { + base->getConstStringCustomizationVariablesMin(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_constStringCustomizationVariables.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_constStringCustomizationVariables[index]).getValue(); + NOT_NULL(structTemplate); + const _ConstStringCustomizationVariable *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.variableName = param->getVariableName(m_versionOk); + data.constValue = param->getConstValue(m_versionOk); +} // SharedTangibleObjectTemplate::getConstStringCustomizationVariablesMin + +void SharedTangibleObjectTemplate::getConstStringCustomizationVariablesMax(ConstStringCustomizationVariable &data, int index) const +{ + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_constStringCustomizationVariablesLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter constStringCustomizationVariables in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter constStringCustomizationVariables has not been defined in template %s!", DataResource::getName())); + base->getConstStringCustomizationVariablesMax(data, index); + return; + } + } + + if (m_constStringCustomizationVariablesAppend && base != NULL) + { + int baseCount = base->getConstStringCustomizationVariablesCount(); + if (index < baseCount) + { + base->getConstStringCustomizationVariablesMax(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_constStringCustomizationVariables.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_constStringCustomizationVariables[index]).getValue(); + NOT_NULL(structTemplate); + const _ConstStringCustomizationVariable *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.variableName = param->getVariableName(m_versionOk); + data.constValue = param->getConstValue(m_versionOk); +} // SharedTangibleObjectTemplate::getConstStringCustomizationVariablesMax + +size_t SharedTangibleObjectTemplate::getConstStringCustomizationVariablesCount(void) const +{ + if (!m_constStringCustomizationVariablesLoaded) + { + if (m_baseData == NULL) + return 0; + const SharedTangibleObjectTemplate * base = dynamic_cast(m_baseData); + DEBUG_FATAL(base == NULL, ("base template wrong type")); + return base->getConstStringCustomizationVariablesCount(); + } + + size_t count = m_constStringCustomizationVariables.size(); + + // if we are extending our base template, add it's count + if (m_constStringCustomizationVariablesAppend && m_baseData != NULL) + { + const SharedTangibleObjectTemplate * base = dynamic_cast(m_baseData); + if (base != NULL) + count += base->getConstStringCustomizationVariablesCount(); + } + + return count; +} // SharedTangibleObjectTemplate::getConstStringCustomizationVariablesCount + +SharedTangibleObjectTemplate::GameObjectType SharedTangibleObjectTemplate::getSocketDestinations(int index) const +{ + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_socketDestinationsLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter socketDestinations in template %s", DataResource::getName())); + return static_cast(0); + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter socketDestinations has not been defined in template %s!", DataResource::getName())); + return base->getSocketDestinations(index); + } + } + + if (m_socketDestinationsAppend && base != NULL) + { + int baseCount = base->getSocketDestinationsCount(); + if (index < baseCount) + return base->getSocketDestinations(index); + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_socketDestinations.size(), ("template param index out of range")); + return static_cast(m_socketDestinations[index]->getValue()); +} // SharedTangibleObjectTemplate::getSocketDestinations + +size_t SharedTangibleObjectTemplate::getSocketDestinationsCount(void) const +{ + if (!m_socketDestinationsLoaded) + { + if (m_baseData == NULL) + return 0; + const SharedTangibleObjectTemplate * base = dynamic_cast(m_baseData); + DEBUG_FATAL(base == NULL, ("base template wrong type")); + return base->getSocketDestinationsCount(); + } + + size_t count = m_socketDestinations.size(); + + // if we are extending our base template, add it's count + if (m_socketDestinationsAppend && m_baseData != NULL) + { + const SharedTangibleObjectTemplate * base = dynamic_cast(m_baseData); + if (base != NULL) + count += base->getSocketDestinationsCount(); + } + + return count; +} // SharedTangibleObjectTemplate::getSocketDestinationsCount + +const std::string & SharedTangibleObjectTemplate::getStructureFootprintFileName(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getStructureFootprintFileName(true); +#endif + } + + if (!m_structureFootprintFileName.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter structureFootprintFileName in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter structureFootprintFileName has not been defined in template %s!", DataResource::getName())); + return base->getStructureFootprintFileName(); + } + } + + const std::string & value = m_structureFootprintFileName.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::getStructureFootprintFileName + +bool SharedTangibleObjectTemplate::getUseStructureFootprintOutline(bool testData) const +{ +#ifdef _DEBUG +bool testDataValue = false; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getUseStructureFootprintOutline(true); +#endif + } + + if (!m_useStructureFootprintOutline.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter useStructureFootprintOutline in template %s", DataResource::getName())); + return false; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter useStructureFootprintOutline has not been defined in template %s!", DataResource::getName())); + return base->getUseStructureFootprintOutline(); + } + } + + bool value = m_useStructureFootprintOutline.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::getUseStructureFootprintOutline + +bool SharedTangibleObjectTemplate::getTargetable(bool testData) const +{ +#ifdef _DEBUG +bool testDataValue = false; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getTargetable(true); +#endif + } + + if (!m_targetable.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter targetable in template %s", DataResource::getName())); + return false; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter targetable has not been defined in template %s!", DataResource::getName())); + return base->getTargetable(); + } + } + + bool value = m_targetable.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::getTargetable + +const std::string & SharedTangibleObjectTemplate::getCertificationsRequired(int index) const +{ + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_certificationsRequiredLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter certificationsRequired in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter certificationsRequired has not been defined in template %s!", DataResource::getName())); + return base->getCertificationsRequired(index); + } + } + + if (m_certificationsRequiredAppend && base != NULL) + { + int baseCount = base->getCertificationsRequiredCount(); + if (index < baseCount) + return base->getCertificationsRequired(index); + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_certificationsRequired.size(), ("template param index out of range")); + const std::string & value = m_certificationsRequired[index]->getValue(); + return value; +} // SharedTangibleObjectTemplate::getCertificationsRequired + +size_t SharedTangibleObjectTemplate::getCertificationsRequiredCount(void) const +{ + if (!m_certificationsRequiredLoaded) + { + if (m_baseData == NULL) + return 0; + const SharedTangibleObjectTemplate * base = dynamic_cast(m_baseData); + DEBUG_FATAL(base == NULL, ("base template wrong type")); + return base->getCertificationsRequiredCount(); + } + + size_t count = m_certificationsRequired.size(); + + // if we are extending our base template, add it's count + if (m_certificationsRequiredAppend && m_baseData != NULL) + { + const SharedTangibleObjectTemplate * base = dynamic_cast(m_baseData); + if (base != NULL) + count += base->getCertificationsRequiredCount(); + } + + return count; +} // SharedTangibleObjectTemplate::getCertificationsRequiredCount + +void SharedTangibleObjectTemplate::getCustomizationVariableMapping(CustomizationVariableMapping &data, int index) const +{ + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_customizationVariableMappingLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter customizationVariableMapping in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter customizationVariableMapping has not been defined in template %s!", DataResource::getName())); + base->getCustomizationVariableMapping(data, index); + return; + } + } + + if (m_customizationVariableMappingAppend && base != NULL) + { + int baseCount = base->getCustomizationVariableMappingCount(); + if (index < baseCount) + { + base->getCustomizationVariableMapping(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_customizationVariableMapping.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_customizationVariableMapping[index]).getValue(); + NOT_NULL(structTemplate); + const _CustomizationVariableMapping *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.sourceVariable = param->getSourceVariable(m_versionOk); + data.dependentVariable = param->getDependentVariable(m_versionOk); +} // SharedTangibleObjectTemplate::getCustomizationVariableMapping + +void SharedTangibleObjectTemplate::getCustomizationVariableMappingMin(CustomizationVariableMapping &data, int index) const +{ + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_customizationVariableMappingLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter customizationVariableMapping in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter customizationVariableMapping has not been defined in template %s!", DataResource::getName())); + base->getCustomizationVariableMappingMin(data, index); + return; + } + } + + if (m_customizationVariableMappingAppend && base != NULL) + { + int baseCount = base->getCustomizationVariableMappingCount(); + if (index < baseCount) + { + base->getCustomizationVariableMappingMin(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_customizationVariableMapping.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_customizationVariableMapping[index]).getValue(); + NOT_NULL(structTemplate); + const _CustomizationVariableMapping *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.sourceVariable = param->getSourceVariable(m_versionOk); + data.dependentVariable = param->getDependentVariable(m_versionOk); +} // SharedTangibleObjectTemplate::getCustomizationVariableMappingMin + +void SharedTangibleObjectTemplate::getCustomizationVariableMappingMax(CustomizationVariableMapping &data, int index) const +{ + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + if (!m_customizationVariableMappingLoaded) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter customizationVariableMapping in template %s", DataResource::getName())); + return ; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter customizationVariableMapping has not been defined in template %s!", DataResource::getName())); + base->getCustomizationVariableMappingMax(data, index); + return; + } + } + + if (m_customizationVariableMappingAppend && base != NULL) + { + int baseCount = base->getCustomizationVariableMappingCount(); + if (index < baseCount) + { + base->getCustomizationVariableMappingMax(data, index); + return; + } + index -= baseCount; + } + + DEBUG_FATAL(index < 0 || static_cast(index) >= m_customizationVariableMapping.size(), ("template param index out of range")); + const ObjectTemplate * structTemplate = (*m_customizationVariableMapping[index]).getValue(); + NOT_NULL(structTemplate); + const _CustomizationVariableMapping *param = dynamic_cast(structTemplate); + NOT_NULL(param); + data.sourceVariable = param->getSourceVariable(m_versionOk); + data.dependentVariable = param->getDependentVariable(m_versionOk); +} // SharedTangibleObjectTemplate::getCustomizationVariableMappingMax + +size_t SharedTangibleObjectTemplate::getCustomizationVariableMappingCount(void) const +{ + if (!m_customizationVariableMappingLoaded) + { + if (m_baseData == NULL) + return 0; + const SharedTangibleObjectTemplate * base = dynamic_cast(m_baseData); + DEBUG_FATAL(base == NULL, ("base template wrong type")); + return base->getCustomizationVariableMappingCount(); + } + + size_t count = m_customizationVariableMapping.size(); + + // if we are extending our base template, add it's count + if (m_customizationVariableMappingAppend && m_baseData != NULL) + { + const SharedTangibleObjectTemplate * base = dynamic_cast(m_baseData); + if (base != NULL) + count += base->getCustomizationVariableMappingCount(); + } + + return count; +} // SharedTangibleObjectTemplate::getCustomizationVariableMappingCount + +SharedTangibleObjectTemplate::ClientVisabilityFlags SharedTangibleObjectTemplate::getClientVisabilityFlag(bool testData) const +{ +#ifdef _DEBUG +SharedTangibleObjectTemplate::ClientVisabilityFlags testDataValue = static_cast(0); +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getClientVisabilityFlag(true); +#endif + } + + if (!m_clientVisabilityFlag.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter clientVisabilityFlag in template %s", DataResource::getName())); + return static_cast(0); + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter clientVisabilityFlag has not been defined in template %s!", DataResource::getName())); + return base->getClientVisabilityFlag(); + } + } + + ClientVisabilityFlags value = static_cast(m_clientVisabilityFlag.getValue()); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::getClientVisabilityFlag + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedTangibleObjectTemplate::testValues(void) const +{ + IGNORE_RETURN(getStructureFootprintFileName(true)); + IGNORE_RETURN(getUseStructureFootprintOutline(true)); + IGNORE_RETURN(getTargetable(true)); + IGNORE_RETURN(getClientVisabilityFlag(true)); + SharedObjectTemplate::testValues(); +} // SharedTangibleObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedTangibleObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedTangibleObjectTemplate_tag) + { + SharedObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,1,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "paletteColorCustomizationVariables") == 0) + { + std::vector::iterator iter; + for (iter = m_paletteColorCustomizationVariables.begin(); iter != m_paletteColorCustomizationVariables.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_paletteColorCustomizationVariables.clear(); + m_paletteColorCustomizationVariablesAppend = file.read_bool8(); + int listCount = file.read_int32(); + for (int j = 0; j < listCount; ++j) + { + StructParamOT * newData = new StructParamOT; + newData->loadFromIff(file); + m_paletteColorCustomizationVariables.push_back(newData); + } + m_paletteColorCustomizationVariablesLoaded = true; + } + else if (strcmp(paramName, "rangedIntCustomizationVariables") == 0) + { + std::vector::iterator iter; + for (iter = m_rangedIntCustomizationVariables.begin(); iter != m_rangedIntCustomizationVariables.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_rangedIntCustomizationVariables.clear(); + m_rangedIntCustomizationVariablesAppend = file.read_bool8(); + int listCount = file.read_int32(); + for (int j = 0; j < listCount; ++j) + { + StructParamOT * newData = new StructParamOT; + newData->loadFromIff(file); + m_rangedIntCustomizationVariables.push_back(newData); + } + m_rangedIntCustomizationVariablesLoaded = true; + } + else if (strcmp(paramName, "constStringCustomizationVariables") == 0) + { + std::vector::iterator iter; + for (iter = m_constStringCustomizationVariables.begin(); iter != m_constStringCustomizationVariables.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_constStringCustomizationVariables.clear(); + m_constStringCustomizationVariablesAppend = file.read_bool8(); + int listCount = file.read_int32(); + for (int j = 0; j < listCount; ++j) + { + StructParamOT * newData = new StructParamOT; + newData->loadFromIff(file); + m_constStringCustomizationVariables.push_back(newData); + } + m_constStringCustomizationVariablesLoaded = true; + } + else if (strcmp(paramName, "socketDestinations") == 0) + { + std::vector::iterator iter; + for (iter = m_socketDestinations.begin(); iter != m_socketDestinations.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_socketDestinations.clear(); + m_socketDestinationsAppend = file.read_bool8(); + int listCount = file.read_int32(); + for (int j = 0; j < listCount; ++j) + { + IntegerParam * newData = new IntegerParam; + newData->loadFromIff(file); + m_socketDestinations.push_back(newData); + } + m_socketDestinationsLoaded = true; + } + else if (strcmp(paramName, "structureFootprintFileName") == 0) + m_structureFootprintFileName.loadFromIff(file); + else if (strcmp(paramName, "useStructureFootprintOutline") == 0) + m_useStructureFootprintOutline.loadFromIff(file); + else if (strcmp(paramName, "targetable") == 0) + m_targetable.loadFromIff(file); + else if (strcmp(paramName, "certificationsRequired") == 0) + { + std::vector::iterator iter; + for (iter = m_certificationsRequired.begin(); iter != m_certificationsRequired.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_certificationsRequired.clear(); + m_certificationsRequiredAppend = file.read_bool8(); + int listCount = file.read_int32(); + for (int j = 0; j < listCount; ++j) + { + StringParam * newData = new StringParam; + newData->loadFromIff(file); + m_certificationsRequired.push_back(newData); + } + m_certificationsRequiredLoaded = true; + } + else if (strcmp(paramName, "customizationVariableMapping") == 0) + { + std::vector::iterator iter; + for (iter = m_customizationVariableMapping.begin(); iter != m_customizationVariableMapping.end(); ++iter) + { + delete *iter; + *iter = NULL; + } + m_customizationVariableMapping.clear(); + m_customizationVariableMappingAppend = file.read_bool8(); + int listCount = file.read_int32(); + for (int j = 0; j < listCount; ++j) + { + StructParamOT * newData = new StructParamOT; + newData->loadFromIff(file); + m_customizationVariableMapping.push_back(newData); + } + m_customizationVariableMappingLoaded = true; + } + else if (strcmp(paramName, "clientVisabilityFlag") == 0) + m_clientVisabilityFlag.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + SharedObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedTangibleObjectTemplate::load + + +//============================================================================= +// class SharedTangibleObjectTemplate::_ConstStringCustomizationVariable + +/** + * Class constructor. + */ +SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::_ConstStringCustomizationVariable(const std::string & filename) + : ObjectTemplate(filename) +{ +} // SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::_ConstStringCustomizationVariable + +/** + * Class destructor. + */ +SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::~_ConstStringCustomizationVariable() +{ +} // SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::~_ConstStringCustomizationVariable + +/** + * Static function used to register this template. + */ +void SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::registerMe(void) +{ + ObjectTemplateList::registerTemplate(_ConstStringCustomizationVariable_tag, create); +} // SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::registerMe + +/** + * Creates a SharedTangibleObjectTemplate::_ConstStringCustomizationVariable template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::create(const std::string & filename) +{ + return new SharedTangibleObjectTemplate::_ConstStringCustomizationVariable(filename); +} // SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::getId(void) const +{ + return _ConstStringCustomizationVariable_tag; +} // SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::getId + +const std::string & SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::getVariableName(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_ConstStringCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getVariableName(true); +#endif + } + + if (!m_variableName.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter variableName in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter variableName has not been defined in template %s!", DataResource::getName())); + return base->getVariableName(versionOk); + } + } + + const std::string & value = m_variableName.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::getVariableName + +const std::string & SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::getConstValue(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_ConstStringCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getConstValue(true); +#endif + } + + if (!m_constValue.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter constValue in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter constValue has not been defined in template %s!", DataResource::getName())); + return base->getConstValue(versionOk); + } + } + + const std::string & value = m_constValue.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::getConstValue + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::testValues(void) const +{ + IGNORE_RETURN(getVariableName(true)); + IGNORE_RETURN(getConstValue(true)); +} // SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "variableName") == 0) + m_variableName.loadFromIff(file); + else if (strcmp(paramName, "constValue") == 0) + m_constValue.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + UNREF(file); +} // SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::load + + +//============================================================================= +// class SharedTangibleObjectTemplate::_CustomizationVariableMapping + +/** + * Class constructor. + */ +SharedTangibleObjectTemplate::_CustomizationVariableMapping::_CustomizationVariableMapping(const std::string & filename) + : ObjectTemplate(filename) +{ +} // SharedTangibleObjectTemplate::_CustomizationVariableMapping::_CustomizationVariableMapping + +/** + * Class destructor. + */ +SharedTangibleObjectTemplate::_CustomizationVariableMapping::~_CustomizationVariableMapping() +{ +} // SharedTangibleObjectTemplate::_CustomizationVariableMapping::~_CustomizationVariableMapping + +/** + * Static function used to register this template. + */ +void SharedTangibleObjectTemplate::_CustomizationVariableMapping::registerMe(void) +{ + ObjectTemplateList::registerTemplate(_CustomizationVariableMapping_tag, create); +} // SharedTangibleObjectTemplate::_CustomizationVariableMapping::registerMe + +/** + * Creates a SharedTangibleObjectTemplate::_CustomizationVariableMapping template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedTangibleObjectTemplate::_CustomizationVariableMapping::create(const std::string & filename) +{ + return new SharedTangibleObjectTemplate::_CustomizationVariableMapping(filename); +} // SharedTangibleObjectTemplate::_CustomizationVariableMapping::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedTangibleObjectTemplate::_CustomizationVariableMapping::getId(void) const +{ + return _CustomizationVariableMapping_tag; +} // SharedTangibleObjectTemplate::_CustomizationVariableMapping::getId + +const std::string & SharedTangibleObjectTemplate::_CustomizationVariableMapping::getSourceVariable(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_CustomizationVariableMapping * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSourceVariable(true); +#endif + } + + if (!m_sourceVariable.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter sourceVariable in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter sourceVariable has not been defined in template %s!", DataResource::getName())); + return base->getSourceVariable(versionOk); + } + } + + const std::string & value = m_sourceVariable.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_CustomizationVariableMapping::getSourceVariable + +const std::string & SharedTangibleObjectTemplate::_CustomizationVariableMapping::getDependentVariable(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_CustomizationVariableMapping * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getDependentVariable(true); +#endif + } + + if (!m_dependentVariable.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter dependentVariable in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter dependentVariable has not been defined in template %s!", DataResource::getName())); + return base->getDependentVariable(versionOk); + } + } + + const std::string & value = m_dependentVariable.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_CustomizationVariableMapping::getDependentVariable + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedTangibleObjectTemplate::_CustomizationVariableMapping::testValues(void) const +{ + IGNORE_RETURN(getSourceVariable(true)); + IGNORE_RETURN(getDependentVariable(true)); +} // SharedTangibleObjectTemplate::_CustomizationVariableMapping::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedTangibleObjectTemplate::_CustomizationVariableMapping::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "sourceVariable") == 0) + m_sourceVariable.loadFromIff(file); + else if (strcmp(paramName, "dependentVariable") == 0) + m_dependentVariable.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + UNREF(file); +} // SharedTangibleObjectTemplate::_CustomizationVariableMapping::load + + +//============================================================================= +// class SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable + +/** + * Class constructor. + */ +SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::_PaletteColorCustomizationVariable(const std::string & filename) + : ObjectTemplate(filename) +{ +} // SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::_PaletteColorCustomizationVariable + +/** + * Class destructor. + */ +SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::~_PaletteColorCustomizationVariable() +{ +} // SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::~_PaletteColorCustomizationVariable + +/** + * Static function used to register this template. + */ +void SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::registerMe(void) +{ + ObjectTemplateList::registerTemplate(_PaletteColorCustomizationVariable_tag, create); +} // SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::registerMe + +/** + * Creates a SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::create(const std::string & filename) +{ + return new SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable(filename); +} // SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::getId(void) const +{ + return _PaletteColorCustomizationVariable_tag; +} // SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::getId + +const std::string & SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::getVariableName(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getVariableName(true); +#endif + } + + if (!m_variableName.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter variableName in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter variableName has not been defined in template %s!", DataResource::getName())); + return base->getVariableName(versionOk); + } + } + + const std::string & value = m_variableName.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::getVariableName + +const std::string & SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::getPalettePathName(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getPalettePathName(true); +#endif + } + + if (!m_palettePathName.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter palettePathName in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter palettePathName has not been defined in template %s!", DataResource::getName())); + return base->getPalettePathName(versionOk); + } + } + + const std::string & value = m_palettePathName.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::getPalettePathName + +int SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::getDefaultPaletteIndex(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getDefaultPaletteIndex(true); +#endif + } + + if (!m_defaultPaletteIndex.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter defaultPaletteIndex in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter defaultPaletteIndex has not been defined in template %s!", DataResource::getName())); + return base->getDefaultPaletteIndex(versionOk); + } + } + + int value = m_defaultPaletteIndex.getValue(); + char delta = m_defaultPaletteIndex.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getDefaultPaletteIndex(versionOk); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::getDefaultPaletteIndex + +int SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::getDefaultPaletteIndexMin(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getDefaultPaletteIndexMin(true); +#endif + } + + if (!m_defaultPaletteIndex.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter defaultPaletteIndex in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter defaultPaletteIndex has not been defined in template %s!", DataResource::getName())); + return base->getDefaultPaletteIndexMin(versionOk); + } + } + + int value = m_defaultPaletteIndex.getMinValue(); + char delta = m_defaultPaletteIndex.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getDefaultPaletteIndexMin(versionOk); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::getDefaultPaletteIndexMin + +int SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::getDefaultPaletteIndexMax(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getDefaultPaletteIndexMax(true); +#endif + } + + if (!m_defaultPaletteIndex.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter defaultPaletteIndex in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter defaultPaletteIndex has not been defined in template %s!", DataResource::getName())); + return base->getDefaultPaletteIndexMax(versionOk); + } + } + + int value = m_defaultPaletteIndex.getMaxValue(); + char delta = m_defaultPaletteIndex.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getDefaultPaletteIndexMax(versionOk); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::getDefaultPaletteIndexMax + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::testValues(void) const +{ + IGNORE_RETURN(getVariableName(true)); + IGNORE_RETURN(getPalettePathName(true)); + IGNORE_RETURN(getDefaultPaletteIndexMin(true)); + IGNORE_RETURN(getDefaultPaletteIndexMax(true)); +} // SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "variableName") == 0) + m_variableName.loadFromIff(file); + else if (strcmp(paramName, "palettePathName") == 0) + m_palettePathName.loadFromIff(file); + else if (strcmp(paramName, "defaultPaletteIndex") == 0) + m_defaultPaletteIndex.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + UNREF(file); +} // SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::load + + +//============================================================================= +// class SharedTangibleObjectTemplate::_RangedIntCustomizationVariable + +/** + * Class constructor. + */ +SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::_RangedIntCustomizationVariable(const std::string & filename) + : ObjectTemplate(filename) +{ +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::_RangedIntCustomizationVariable + +/** + * Class destructor. + */ +SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::~_RangedIntCustomizationVariable() +{ +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::~_RangedIntCustomizationVariable + +/** + * Static function used to register this template. + */ +void SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::registerMe(void) +{ + ObjectTemplateList::registerTemplate(_RangedIntCustomizationVariable_tag, create); +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::registerMe + +/** + * Creates a SharedTangibleObjectTemplate::_RangedIntCustomizationVariable template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::create(const std::string & filename) +{ + return new SharedTangibleObjectTemplate::_RangedIntCustomizationVariable(filename); +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getId(void) const +{ + return _RangedIntCustomizationVariable_tag; +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getId + +const std::string & SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getVariableName(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_RangedIntCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getVariableName(true); +#endif + } + + if (!m_variableName.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter variableName in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter variableName has not been defined in template %s!", DataResource::getName())); + return base->getVariableName(versionOk); + } + } + + const std::string & value = m_variableName.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getVariableName + +int SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getMinValueInclusive(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_RangedIntCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getMinValueInclusive(true); +#endif + } + + if (!m_minValueInclusive.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter minValueInclusive in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter minValueInclusive has not been defined in template %s!", DataResource::getName())); + return base->getMinValueInclusive(versionOk); + } + } + + int value = m_minValueInclusive.getValue(); + char delta = m_minValueInclusive.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getMinValueInclusive(versionOk); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getMinValueInclusive + +int SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getMinValueInclusiveMin(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_RangedIntCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getMinValueInclusiveMin(true); +#endif + } + + if (!m_minValueInclusive.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter minValueInclusive in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter minValueInclusive has not been defined in template %s!", DataResource::getName())); + return base->getMinValueInclusiveMin(versionOk); + } + } + + int value = m_minValueInclusive.getMinValue(); + char delta = m_minValueInclusive.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getMinValueInclusiveMin(versionOk); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getMinValueInclusiveMin + +int SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getMinValueInclusiveMax(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_RangedIntCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getMinValueInclusiveMax(true); +#endif + } + + if (!m_minValueInclusive.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter minValueInclusive in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter minValueInclusive has not been defined in template %s!", DataResource::getName())); + return base->getMinValueInclusiveMax(versionOk); + } + } + + int value = m_minValueInclusive.getMaxValue(); + char delta = m_minValueInclusive.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getMinValueInclusiveMax(versionOk); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getMinValueInclusiveMax + +int SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getDefaultValue(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_RangedIntCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getDefaultValue(true); +#endif + } + + if (!m_defaultValue.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter defaultValue in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter defaultValue has not been defined in template %s!", DataResource::getName())); + return base->getDefaultValue(versionOk); + } + } + + int value = m_defaultValue.getValue(); + char delta = m_defaultValue.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getDefaultValue(versionOk); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getDefaultValue + +int SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getDefaultValueMin(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_RangedIntCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getDefaultValueMin(true); +#endif + } + + if (!m_defaultValue.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter defaultValue in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter defaultValue has not been defined in template %s!", DataResource::getName())); + return base->getDefaultValueMin(versionOk); + } + } + + int value = m_defaultValue.getMinValue(); + char delta = m_defaultValue.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getDefaultValueMin(versionOk); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getDefaultValueMin + +int SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getDefaultValueMax(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_RangedIntCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getDefaultValueMax(true); +#endif + } + + if (!m_defaultValue.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter defaultValue in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter defaultValue has not been defined in template %s!", DataResource::getName())); + return base->getDefaultValueMax(versionOk); + } + } + + int value = m_defaultValue.getMaxValue(); + char delta = m_defaultValue.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getDefaultValueMax(versionOk); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getDefaultValueMax + +int SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getMaxValueExclusive(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_RangedIntCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getMaxValueExclusive(true); +#endif + } + + if (!m_maxValueExclusive.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter maxValueExclusive in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter maxValueExclusive has not been defined in template %s!", DataResource::getName())); + return base->getMaxValueExclusive(versionOk); + } + } + + int value = m_maxValueExclusive.getValue(); + char delta = m_maxValueExclusive.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getMaxValueExclusive(versionOk); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getMaxValueExclusive + +int SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getMaxValueExclusiveMin(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_RangedIntCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getMaxValueExclusiveMin(true); +#endif + } + + if (!m_maxValueExclusive.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter maxValueExclusive in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter maxValueExclusive has not been defined in template %s!", DataResource::getName())); + return base->getMaxValueExclusiveMin(versionOk); + } + } + + int value = m_maxValueExclusive.getMinValue(); + char delta = m_maxValueExclusive.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getMaxValueExclusiveMin(versionOk); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getMaxValueExclusiveMin + +int SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getMaxValueExclusiveMax(bool versionOk, bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedTangibleObjectTemplate::_RangedIntCustomizationVariable * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getMaxValueExclusiveMax(true); +#endif + } + + if (!m_maxValueExclusive.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter maxValueExclusive in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter maxValueExclusive has not been defined in template %s!", DataResource::getName())); + return base->getMaxValueExclusiveMax(versionOk); + } + } + + int value = m_maxValueExclusive.getMaxValue(); + char delta = m_maxValueExclusive.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getMaxValueExclusiveMax(versionOk); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::getMaxValueExclusiveMax + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::testValues(void) const +{ + IGNORE_RETURN(getVariableName(true)); + IGNORE_RETURN(getMinValueInclusiveMin(true)); + IGNORE_RETURN(getMinValueInclusiveMax(true)); + IGNORE_RETURN(getDefaultValueMin(true)); + IGNORE_RETURN(getDefaultValueMax(true)); + IGNORE_RETURN(getMaxValueExclusiveMin(true)); + IGNORE_RETURN(getMaxValueExclusiveMax(true)); +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "variableName") == 0) + m_variableName.loadFromIff(file); + else if (strcmp(paramName, "minValueInclusive") == 0) + m_minValueInclusive.loadFromIff(file); + else if (strcmp(paramName, "defaultValue") == 0) + m_defaultValue.loadFromIff(file); + else if (strcmp(paramName, "maxValueExclusive") == 0) + m_maxValueExclusive.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + UNREF(file); +} // SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedTangibleObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedTangibleObjectTemplate.h new file mode 100644 index 00000000..7cd54f53 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedTangibleObjectTemplate.h @@ -0,0 +1,355 @@ +//======================================================================== +// +// SharedTangibleObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedTangibleObjectTemplate_H +#define _INCLUDED_SharedTangibleObjectTemplate_H + +#include "SharedObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class StructureFootprint; +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedTangibleObjectTemplate : public SharedObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedTangibleObjectTemplate_tag = TAG(S,T,O,T) + }; +//@END TFD ID +public: + SharedTangibleObjectTemplate(const std::string & filename); + virtual ~SharedTangibleObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + enum ClientVisabilityFlags + { + CVF_always, + CVF_gm_only, + ClientVisabilityFlags_Last = CVF_gm_only, + }; + +public: + struct RangedIntCustomizationVariable + { + std::string variableName; + int minValueInclusive; + int defaultValue; + int maxValueExclusive; + }; + + struct PaletteColorCustomizationVariable + { + std::string variableName; + std::string palettePathName; + int defaultPaletteIndex; + }; + + struct ConstStringCustomizationVariable + { + std::string variableName; + std::string constValue; + }; + + struct CustomizationVariableMapping + { + std::string sourceVariable; + std::string dependentVariable; + }; + +protected: + class _RangedIntCustomizationVariable : public ObjectTemplate + { + friend class SharedTangibleObjectTemplate; + public: + enum + { + _RangedIntCustomizationVariable_tag = TAG(R,I,C,V) + }; + + public: + _RangedIntCustomizationVariable(const std::string & filename); + virtual ~_RangedIntCustomizationVariable(); + + virtual Tag getId(void) const; + +public: + const std::string & getVariableName(bool versionOk, bool testData = false) const; + int getMinValueInclusive(bool versionOk, bool testData = false) const; + int getMinValueInclusiveMin(bool versionOk, bool testData = false) const; + int getMinValueInclusiveMax(bool versionOk, bool testData = false) const; + int getDefaultValue(bool versionOk, bool testData = false) const; + int getDefaultValueMin(bool versionOk, bool testData = false) const; + int getDefaultValueMax(bool versionOk, bool testData = false) const; + int getMaxValueExclusive(bool versionOk, bool testData = false) const; + int getMaxValueExclusiveMin(bool versionOk, bool testData = false) const; + int getMaxValueExclusiveMax(bool versionOk, bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + StringParam m_variableName; + IntegerParam m_minValueInclusive; + IntegerParam m_defaultValue; + IntegerParam m_maxValueExclusive; + private: + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + private: + _RangedIntCustomizationVariable(const _RangedIntCustomizationVariable &); + _RangedIntCustomizationVariable & operator =(const _RangedIntCustomizationVariable &); + }; + friend class SharedTangibleObjectTemplate::_RangedIntCustomizationVariable; + + class _PaletteColorCustomizationVariable : public ObjectTemplate + { + friend class SharedTangibleObjectTemplate; + public: + enum + { + _PaletteColorCustomizationVariable_tag = TAG(P,C,C,V) + }; + + public: + _PaletteColorCustomizationVariable(const std::string & filename); + virtual ~_PaletteColorCustomizationVariable(); + + virtual Tag getId(void) const; + +public: + const std::string & getVariableName(bool versionOk, bool testData = false) const; + const std::string & getPalettePathName(bool versionOk, bool testData = false) const; + int getDefaultPaletteIndex(bool versionOk, bool testData = false) const; + int getDefaultPaletteIndexMin(bool versionOk, bool testData = false) const; + int getDefaultPaletteIndexMax(bool versionOk, bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + StringParam m_variableName; + StringParam m_palettePathName; + IntegerParam m_defaultPaletteIndex; + private: + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + private: + _PaletteColorCustomizationVariable(const _PaletteColorCustomizationVariable &); + _PaletteColorCustomizationVariable & operator =(const _PaletteColorCustomizationVariable &); + }; + friend class SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable; + + class _ConstStringCustomizationVariable : public ObjectTemplate + { + friend class SharedTangibleObjectTemplate; + public: + enum + { + _ConstStringCustomizationVariable_tag = TAG(C,S,C,V) + }; + + public: + _ConstStringCustomizationVariable(const std::string & filename); + virtual ~_ConstStringCustomizationVariable(); + + virtual Tag getId(void) const; + +public: + const std::string & getVariableName(bool versionOk, bool testData = false) const; + const std::string & getConstValue(bool versionOk, bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + StringParam m_variableName; + StringParam m_constValue; + private: + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + private: + _ConstStringCustomizationVariable(const _ConstStringCustomizationVariable &); + _ConstStringCustomizationVariable & operator =(const _ConstStringCustomizationVariable &); + }; + friend class SharedTangibleObjectTemplate::_ConstStringCustomizationVariable; + + class _CustomizationVariableMapping : public ObjectTemplate + { + friend class SharedTangibleObjectTemplate; + public: + enum + { + _CustomizationVariableMapping_tag = TAG(C,V,M,M) + }; + + public: + _CustomizationVariableMapping(const std::string & filename); + virtual ~_CustomizationVariableMapping(); + + virtual Tag getId(void) const; + +public: + const std::string & getSourceVariable(bool versionOk, bool testData = false) const; + const std::string & getDependentVariable(bool versionOk, bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + StringParam m_sourceVariable; + StringParam m_dependentVariable; + private: + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + private: + _CustomizationVariableMapping(const _CustomizationVariableMapping &); + _CustomizationVariableMapping & operator =(const _CustomizationVariableMapping &); + }; + friend class SharedTangibleObjectTemplate::_CustomizationVariableMapping; + +public: + void getPaletteColorCustomizationVariables(PaletteColorCustomizationVariable &data, int index) const; + void getPaletteColorCustomizationVariablesMin(PaletteColorCustomizationVariable &data, int index) const; + void getPaletteColorCustomizationVariablesMax(PaletteColorCustomizationVariable &data, int index) const; + size_t getPaletteColorCustomizationVariablesCount(void) const; + void getRangedIntCustomizationVariables(RangedIntCustomizationVariable &data, int index) const; + void getRangedIntCustomizationVariablesMin(RangedIntCustomizationVariable &data, int index) const; + void getRangedIntCustomizationVariablesMax(RangedIntCustomizationVariable &data, int index) const; + size_t getRangedIntCustomizationVariablesCount(void) const; + void getConstStringCustomizationVariables(ConstStringCustomizationVariable &data, int index) const; + void getConstStringCustomizationVariablesMin(ConstStringCustomizationVariable &data, int index) const; + void getConstStringCustomizationVariablesMax(ConstStringCustomizationVariable &data, int index) const; + size_t getConstStringCustomizationVariablesCount(void) const; + GameObjectType getSocketDestinations(int index) const; + size_t getSocketDestinationsCount(void) const; + const std::string & getStructureFootprintFileName(bool testData = false) const; + bool getUseStructureFootprintOutline(bool testData = false) const; + bool getTargetable(bool testData = false) const; + const std::string & getCertificationsRequired(int index) const; + size_t getCertificationsRequiredCount(void) const; + void getCustomizationVariableMapping(CustomizationVariableMapping &data, int index) const; + void getCustomizationVariableMappingMin(CustomizationVariableMapping &data, int index) const; + void getCustomizationVariableMappingMax(CustomizationVariableMapping &data, int index) const; + size_t getCustomizationVariableMappingCount(void) const; + ClientVisabilityFlags getClientVisabilityFlag(bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + stdvector::fwd m_paletteColorCustomizationVariables; // // all palette color customization variables exposed by an Object created with this template + bool m_paletteColorCustomizationVariablesLoaded; + bool m_paletteColorCustomizationVariablesAppend; + stdvector::fwd m_rangedIntCustomizationVariables; // // all ranged-int style customization variables exposed by an Object created with this template + bool m_rangedIntCustomizationVariablesLoaded; + bool m_rangedIntCustomizationVariablesAppend; + stdvector::fwd m_constStringCustomizationVariables; // // constant string values added to the Object's customization data, not persisted in the DB + bool m_constStringCustomizationVariablesLoaded; + bool m_constStringCustomizationVariablesAppend; + stdvector::fwd m_socketDestinations; // // GOTs that this object can be socketed into + bool m_socketDestinationsLoaded; + bool m_socketDestinationsAppend; + StringParam m_structureFootprintFileName; + BoolParam m_useStructureFootprintOutline; + BoolParam m_targetable; // // can the object be targetted by the client + stdvector::fwd m_certificationsRequired; // // List of the certifications required to use this item (used in x1 only) + bool m_certificationsRequiredLoaded; + bool m_certificationsRequiredAppend; + stdvector::fwd m_customizationVariableMapping; // // Allows remapping of variables when needed + bool m_customizationVariableMappingLoaded; + bool m_customizationVariableMappingAppend; + IntegerParam m_clientVisabilityFlag; // // can the object be viewed on the client +//@END TFD + +public: + // user functions + virtual void postLoad(void); + virtual void createCustomizationDataPropertyAsNeeded(Object &object, bool forceCreation = false) const; + const StructureFootprint* getStructureFootprint () const; + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedTangibleObjectTemplate(const SharedTangibleObjectTemplate &); + SharedTangibleObjectTemplate & operator =(const SharedTangibleObjectTemplate &); + +private: + // user data + StructureFootprint* m_structureFootprint; +}; + + +inline void SharedTangibleObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedTangibleObjectTemplate::registerMe(); + SharedTangibleObjectTemplate::_ConstStringCustomizationVariable::registerMe(); + SharedTangibleObjectTemplate::_CustomizationVariableMapping::registerMe(); + SharedTangibleObjectTemplate::_PaletteColorCustomizationVariable::registerMe(); + SharedTangibleObjectTemplate::_RangedIntCustomizationVariable::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedTangibleObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedTerrainSurfaceObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedTerrainSurfaceObjectTemplate.cpp new file mode 100644 index 00000000..b45b93c1 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedTerrainSurfaceObjectTemplate.cpp @@ -0,0 +1,424 @@ +//======================================================================== +// +// SharedTerrainSurfaceObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedTerrainSurfaceObjectTemplate.h" +#include "sharedDebug/DataLint.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedTerrainSurfaceObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedTerrainSurfaceObjectTemplate::SharedTerrainSurfaceObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : ObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedTerrainSurfaceObjectTemplate::SharedTerrainSurfaceObjectTemplate + +/** + * Class destructor. + */ +SharedTerrainSurfaceObjectTemplate::~SharedTerrainSurfaceObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedTerrainSurfaceObjectTemplate::~SharedTerrainSurfaceObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedTerrainSurfaceObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedTerrainSurfaceObjectTemplate_tag, create); +} // SharedTerrainSurfaceObjectTemplate::registerMe + +/** + * Creates a SharedTerrainSurfaceObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedTerrainSurfaceObjectTemplate::create(const std::string & filename) +{ + return new SharedTerrainSurfaceObjectTemplate(filename); +} // SharedTerrainSurfaceObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedTerrainSurfaceObjectTemplate::getId(void) const +{ + return SharedTerrainSurfaceObjectTemplate_tag; +} // SharedTerrainSurfaceObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedTerrainSurfaceObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedTerrainSurfaceObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedTerrainSurfaceObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedTerrainSurfaceObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedTerrainSurfaceObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +float SharedTerrainSurfaceObjectTemplate::getCover(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedTerrainSurfaceObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCover(true); +#endif + } + + if (!m_cover.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter cover in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter cover has not been defined in template %s!", DataResource::getName())); + return base->getCover(); + } + } + + float value = m_cover.getValue(); + char delta = m_cover.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCover(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + if (testDataValue == value) + DEBUG_WARNING(true, ("Template %s, parameter cover is returning same value as base template.", DataResource::getName())); + } +#endif + + return value; +} // SharedTerrainSurfaceObjectTemplate::getCover + +float SharedTerrainSurfaceObjectTemplate::getCoverMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedTerrainSurfaceObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCoverMin(true); +#endif + } + + if (!m_cover.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter cover in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter cover has not been defined in template %s!", DataResource::getName())); + return base->getCoverMin(); + } + } + + float value = m_cover.getMinValue(); + char delta = m_cover.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCoverMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + if (testDataValue == value) + DEBUG_WARNING(true, ("Template %s, parameter cover is returning same value as base template.", DataResource::getName())); + } +#endif + + return value; +} // SharedTerrainSurfaceObjectTemplate::getCoverMin + +float SharedTerrainSurfaceObjectTemplate::getCoverMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedTerrainSurfaceObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getCoverMax(true); +#endif + } + + if (!m_cover.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter cover in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter cover has not been defined in template %s!", DataResource::getName())); + return base->getCoverMax(); + } + } + + float value = m_cover.getMaxValue(); + char delta = m_cover.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getCoverMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + if (testDataValue == value) + DEBUG_WARNING(true, ("Template %s, parameter cover is returning same value as base template.", DataResource::getName())); + } +#endif + + return value; +} // SharedTerrainSurfaceObjectTemplate::getCoverMax + +const std::string & SharedTerrainSurfaceObjectTemplate::getSurfaceType(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedTerrainSurfaceObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSurfaceType(true); +#endif + } + + if (!m_surfaceType.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter surfaceType in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter surfaceType has not been defined in template %s!", DataResource::getName())); + return base->getSurfaceType(); + } + } + + const std::string & value = m_surfaceType.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + if (testDataValue == value) + DEBUG_WARNING(true, ("Template %s, parameter surfaceType is returning same value as base template.", DataResource::getName())); + } +#endif + + return value; +} // SharedTerrainSurfaceObjectTemplate::getSurfaceType + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedTerrainSurfaceObjectTemplate::testValues(void) const +{ + IGNORE_RETURN(getCoverMin(true)); + IGNORE_RETURN(getCoverMax(true)); + IGNORE_RETURN(getSurfaceType(true)); +} // SharedTerrainSurfaceObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedTerrainSurfaceObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedTerrainSurfaceObjectTemplate_tag) + { + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "cover") == 0) + m_cover.loadFromIff(file); + else if (strcmp(paramName, "surfaceType") == 0) + m_surfaceType.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + return; +} // SharedTerrainSurfaceObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedTerrainSurfaceObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedTerrainSurfaceObjectTemplate.h new file mode 100644 index 00000000..bf5265e7 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedTerrainSurfaceObjectTemplate.h @@ -0,0 +1,89 @@ +//======================================================================== +// +// SharedTerrainSurfaceObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedTerrainSurfaceObjectTemplate_H +#define _INCLUDED_SharedTerrainSurfaceObjectTemplate_H + +#include "sharedObject/ObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedTerrainSurfaceObjectTemplate : public ObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedTerrainSurfaceObjectTemplate_tag = TAG(S,T,E,R) + }; +//@END TFD ID +public: + SharedTerrainSurfaceObjectTemplate(const std::string & filename); + virtual ~SharedTerrainSurfaceObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + float getCover(bool testData = false) const; + float getCoverMin(bool testData = false) const; + float getCoverMax(bool testData = false) const; + const std::string & getSurfaceType(bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + FloatParam m_cover; + StringParam m_surfaceType; +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedTerrainSurfaceObjectTemplate(const SharedTerrainSurfaceObjectTemplate &); + SharedTerrainSurfaceObjectTemplate & operator =(const SharedTerrainSurfaceObjectTemplate &); +}; + + +inline void SharedTerrainSurfaceObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedTerrainSurfaceObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedTerrainSurfaceObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedUniverseObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedUniverseObjectTemplate.cpp new file mode 100644 index 00000000..893c4aa6 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedUniverseObjectTemplate.cpp @@ -0,0 +1,176 @@ +//======================================================================== +// +// SharedUniverseObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedUniverseObjectTemplate.h" +#include "sharedDebug/DataLint.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedUniverseObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedUniverseObjectTemplate::SharedUniverseObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedUniverseObjectTemplate::SharedUniverseObjectTemplate + +/** + * Class destructor. + */ +SharedUniverseObjectTemplate::~SharedUniverseObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedUniverseObjectTemplate::~SharedUniverseObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedUniverseObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedUniverseObjectTemplate_tag, create); +} // SharedUniverseObjectTemplate::registerMe + +/** + * Creates a SharedUniverseObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedUniverseObjectTemplate::create(const std::string & filename) +{ + return new SharedUniverseObjectTemplate(filename); +} // SharedUniverseObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedUniverseObjectTemplate::getId(void) const +{ + return SharedUniverseObjectTemplate_tag; +} // SharedUniverseObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedUniverseObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedUniverseObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedUniverseObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedUniverseObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedUniverseObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedUniverseObjectTemplate::testValues(void) const +{ + SharedObjectTemplate::testValues(); +} // SharedUniverseObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedUniverseObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedUniverseObjectTemplate_tag) + { + SharedObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedUniverseObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedUniverseObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedUniverseObjectTemplate.h new file mode 100644 index 00000000..1968e4eb --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedUniverseObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedUniverseObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedUniverseObjectTemplate_H +#define _INCLUDED_SharedUniverseObjectTemplate_H + +#include "SharedObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedUniverseObjectTemplate : public SharedObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedUniverseObjectTemplate_tag = TAG(S,U,N,I) + }; +//@END TFD ID +public: + SharedUniverseObjectTemplate(const std::string & filename); + virtual ~SharedUniverseObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedUniverseObjectTemplate(const SharedUniverseObjectTemplate &); + SharedUniverseObjectTemplate & operator =(const SharedUniverseObjectTemplate &); +}; + + +inline void SharedUniverseObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedUniverseObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedUniverseObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedVehicleObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedVehicleObjectTemplate.cpp new file mode 100644 index 00000000..8ebac887 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedVehicleObjectTemplate.cpp @@ -0,0 +1,1516 @@ +//======================================================================== +// +// SharedVehicleObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedVehicleObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedVehicleObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedVehicleObjectTemplate::SharedVehicleObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedTangibleObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedVehicleObjectTemplate::SharedVehicleObjectTemplate + +/** + * Class destructor. + */ +SharedVehicleObjectTemplate::~SharedVehicleObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedVehicleObjectTemplate::~SharedVehicleObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedVehicleObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedVehicleObjectTemplate_tag, create); +} // SharedVehicleObjectTemplate::registerMe + +/** + * Creates a SharedVehicleObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedVehicleObjectTemplate::create(const std::string & filename) +{ + return new SharedVehicleObjectTemplate(filename); +} // SharedVehicleObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedVehicleObjectTemplate::getId(void) const +{ + return SharedVehicleObjectTemplate_tag; +} // SharedVehicleObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedVehicleObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedVehicleObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedVehicleObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedVehicleObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedVehicleObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +float SharedVehicleObjectTemplate::getSpeed(MovementTypes index) const +{ + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + DEBUG_FATAL(index < 0 || index >= 5, ("template param index out of range")); + if (!m_speed[index].isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter speed in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter speed has not been defined in template %s!", DataResource::getName())); + return base->getSpeed(index); + } + } + + float value = m_speed[index].getValue(); + char delta = m_speed[index].getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSpeed(index); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } + return value; +} // SharedVehicleObjectTemplate::getSpeed + +float SharedVehicleObjectTemplate::getSpeedMin(MovementTypes index) const +{ + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + DEBUG_FATAL(index < 0 || index >= 5, ("template param index out of range")); + if (!m_speed[index].isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter speed in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter speed has not been defined in template %s!", DataResource::getName())); + return base->getSpeedMin(index); + } + } + + float value = m_speed[index].getMinValue(); + char delta = m_speed[index].getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSpeedMin(index); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } + return value; +} // SharedVehicleObjectTemplate::getSpeedMin + +float SharedVehicleObjectTemplate::getSpeedMax(MovementTypes index) const +{ + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); + } + + DEBUG_FATAL(index < 0 || index >= 5, ("template param index out of range")); + if (!m_speed[index].isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter speed in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter speed has not been defined in template %s!", DataResource::getName())); + return base->getSpeedMax(index); + } + } + + float value = m_speed[index].getMaxValue(); + char delta = m_speed[index].getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSpeedMax(index); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } + return value; +} // SharedVehicleObjectTemplate::getSpeedMax + +float SharedVehicleObjectTemplate::getSlopeAversion(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSlopeAversion(true); +#endif + } + + if (!m_slopeAversion.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter slopeAversion in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter slopeAversion has not been defined in template %s!", DataResource::getName())); + return base->getSlopeAversion(); + } + } + + float value = m_slopeAversion.getValue(); + char delta = m_slopeAversion.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSlopeAversion(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getSlopeAversion + +float SharedVehicleObjectTemplate::getSlopeAversionMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSlopeAversionMin(true); +#endif + } + + if (!m_slopeAversion.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter slopeAversion in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter slopeAversion has not been defined in template %s!", DataResource::getName())); + return base->getSlopeAversionMin(); + } + } + + float value = m_slopeAversion.getMinValue(); + char delta = m_slopeAversion.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSlopeAversionMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getSlopeAversionMin + +float SharedVehicleObjectTemplate::getSlopeAversionMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getSlopeAversionMax(true); +#endif + } + + if (!m_slopeAversion.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter slopeAversion in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter slopeAversion has not been defined in template %s!", DataResource::getName())); + return base->getSlopeAversionMax(); + } + } + + float value = m_slopeAversion.getMaxValue(); + char delta = m_slopeAversion.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getSlopeAversionMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getSlopeAversionMax + +float SharedVehicleObjectTemplate::getHoverValue(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getHoverValue(true); +#endif + } + + if (!m_hoverValue.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter hoverValue in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter hoverValue has not been defined in template %s!", DataResource::getName())); + return base->getHoverValue(); + } + } + + float value = m_hoverValue.getValue(); + char delta = m_hoverValue.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getHoverValue(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getHoverValue + +float SharedVehicleObjectTemplate::getHoverValueMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getHoverValueMin(true); +#endif + } + + if (!m_hoverValue.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter hoverValue in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter hoverValue has not been defined in template %s!", DataResource::getName())); + return base->getHoverValueMin(); + } + } + + float value = m_hoverValue.getMinValue(); + char delta = m_hoverValue.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getHoverValueMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getHoverValueMin + +float SharedVehicleObjectTemplate::getHoverValueMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getHoverValueMax(true); +#endif + } + + if (!m_hoverValue.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter hoverValue in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter hoverValue has not been defined in template %s!", DataResource::getName())); + return base->getHoverValueMax(); + } + } + + float value = m_hoverValue.getMaxValue(); + char delta = m_hoverValue.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getHoverValueMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getHoverValueMax + +float SharedVehicleObjectTemplate::getTurnRate(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getTurnRate(true); +#endif + } + + if (!m_turnRate.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter turnRate in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter turnRate has not been defined in template %s!", DataResource::getName())); + return base->getTurnRate(); + } + } + + float value = m_turnRate.getValue(); + char delta = m_turnRate.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getTurnRate(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getTurnRate + +float SharedVehicleObjectTemplate::getTurnRateMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getTurnRateMin(true); +#endif + } + + if (!m_turnRate.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter turnRate in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter turnRate has not been defined in template %s!", DataResource::getName())); + return base->getTurnRateMin(); + } + } + + float value = m_turnRate.getMinValue(); + char delta = m_turnRate.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getTurnRateMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getTurnRateMin + +float SharedVehicleObjectTemplate::getTurnRateMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getTurnRateMax(true); +#endif + } + + if (!m_turnRate.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter turnRate in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter turnRate has not been defined in template %s!", DataResource::getName())); + return base->getTurnRateMax(); + } + } + + float value = m_turnRate.getMaxValue(); + char delta = m_turnRate.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getTurnRateMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getTurnRateMax + +float SharedVehicleObjectTemplate::getMaxVelocity(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getMaxVelocity(true); +#endif + } + + if (!m_maxVelocity.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter maxVelocity in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter maxVelocity has not been defined in template %s!", DataResource::getName())); + return base->getMaxVelocity(); + } + } + + float value = m_maxVelocity.getValue(); + char delta = m_maxVelocity.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getMaxVelocity(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getMaxVelocity + +float SharedVehicleObjectTemplate::getMaxVelocityMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getMaxVelocityMin(true); +#endif + } + + if (!m_maxVelocity.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter maxVelocity in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter maxVelocity has not been defined in template %s!", DataResource::getName())); + return base->getMaxVelocityMin(); + } + } + + float value = m_maxVelocity.getMinValue(); + char delta = m_maxVelocity.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getMaxVelocityMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getMaxVelocityMin + +float SharedVehicleObjectTemplate::getMaxVelocityMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getMaxVelocityMax(true); +#endif + } + + if (!m_maxVelocity.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter maxVelocity in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter maxVelocity has not been defined in template %s!", DataResource::getName())); + return base->getMaxVelocityMax(); + } + } + + float value = m_maxVelocity.getMaxValue(); + char delta = m_maxVelocity.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getMaxVelocityMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getMaxVelocityMax + +float SharedVehicleObjectTemplate::getAcceleration(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getAcceleration(true); +#endif + } + + if (!m_acceleration.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter acceleration in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter acceleration has not been defined in template %s!", DataResource::getName())); + return base->getAcceleration(); + } + } + + float value = m_acceleration.getValue(); + char delta = m_acceleration.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getAcceleration(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getAcceleration + +float SharedVehicleObjectTemplate::getAccelerationMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getAccelerationMin(true); +#endif + } + + if (!m_acceleration.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter acceleration in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter acceleration has not been defined in template %s!", DataResource::getName())); + return base->getAccelerationMin(); + } + } + + float value = m_acceleration.getMinValue(); + char delta = m_acceleration.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getAccelerationMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getAccelerationMin + +float SharedVehicleObjectTemplate::getAccelerationMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getAccelerationMax(true); +#endif + } + + if (!m_acceleration.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter acceleration in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter acceleration has not been defined in template %s!", DataResource::getName())); + return base->getAccelerationMax(); + } + } + + float value = m_acceleration.getMaxValue(); + char delta = m_acceleration.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getAccelerationMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getAccelerationMax + +float SharedVehicleObjectTemplate::getBraking(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getBraking(true); +#endif + } + + if (!m_braking.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter braking in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter braking has not been defined in template %s!", DataResource::getName())); + return base->getBraking(); + } + } + + float value = m_braking.getValue(); + char delta = m_braking.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getBraking(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getBraking + +float SharedVehicleObjectTemplate::getBrakingMin(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getBrakingMin(true); +#endif + } + + if (!m_braking.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter braking in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter braking has not been defined in template %s!", DataResource::getName())); + return base->getBrakingMin(); + } + } + + float value = m_braking.getMinValue(); + char delta = m_braking.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getBrakingMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getBrakingMin + +float SharedVehicleObjectTemplate::getBrakingMax(bool testData) const +{ +#ifdef _DEBUG +float testDataValue = 0.0f; +#else +UNREF(testData); +#endif + + const SharedVehicleObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getBrakingMax(true); +#endif + } + + if (!m_braking.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter braking in template %s", DataResource::getName())); + return 0.0f; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter braking has not been defined in template %s!", DataResource::getName())); + return base->getBrakingMax(); + } + } + + float value = m_braking.getMaxValue(); + char delta = m_braking.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + float baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getBrakingMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedVehicleObjectTemplate::getBrakingMax + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedVehicleObjectTemplate::testValues(void) const +{ + IGNORE_RETURN(getSlopeAversionMin(true)); + IGNORE_RETURN(getSlopeAversionMax(true)); + IGNORE_RETURN(getHoverValueMin(true)); + IGNORE_RETURN(getHoverValueMax(true)); + IGNORE_RETURN(getTurnRateMin(true)); + IGNORE_RETURN(getTurnRateMax(true)); + IGNORE_RETURN(getMaxVelocityMin(true)); + IGNORE_RETURN(getMaxVelocityMax(true)); + IGNORE_RETURN(getAccelerationMin(true)); + IGNORE_RETURN(getAccelerationMax(true)); + IGNORE_RETURN(getBrakingMin(true)); + IGNORE_RETURN(getBrakingMax(true)); + SharedTangibleObjectTemplate::testValues(); +} // SharedVehicleObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedVehicleObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedVehicleObjectTemplate_tag) + { + SharedTangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "speed") == 0) + { + int listCount = file.read_int32(); + DEBUG_WARNING(listCount != 5, ("Template %s: read array size of %d for array \"speed\" of size 5, reading values anyway", file.getFileName(), listCount)); + int j; + for (j = 0; j < 5 && j < listCount; ++j) + m_speed[j].loadFromIff(file); + // if there are more params for speed read and dump them + for (; j < listCount; ++j) + { + FloatParam dummy; + dummy.loadFromIff(file); + } + } + else if (strcmp(paramName, "slopeAversion") == 0) + m_slopeAversion.loadFromIff(file); + else if (strcmp(paramName, "hoverValue") == 0) + m_hoverValue.loadFromIff(file); + else if (strcmp(paramName, "turnRate") == 0) + m_turnRate.loadFromIff(file); + else if (strcmp(paramName, "maxVelocity") == 0) + m_maxVelocity.loadFromIff(file); + else if (strcmp(paramName, "acceleration") == 0) + m_acceleration.loadFromIff(file); + else if (strcmp(paramName, "braking") == 0) + m_braking.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + SharedTangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedVehicleObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedVehicleObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedVehicleObjectTemplate.h new file mode 100644 index 00000000..4da4d4c1 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedVehicleObjectTemplate.h @@ -0,0 +1,122 @@ +//======================================================================== +// +// SharedVehicleObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedVehicleObjectTemplate_H +#define _INCLUDED_SharedVehicleObjectTemplate_H + +#include "SharedTangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedVehicleObjectTemplate : public SharedTangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedVehicleObjectTemplate_tag = TAG(S,V,O,T) + }; +//@END TFD ID +public: + SharedVehicleObjectTemplate(const std::string & filename); + virtual ~SharedVehicleObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + enum MovementTypes + { + MT_hover, + MT_underwater, + MT_ground, + MT_swim, + MT_walker, + MovementTypes_Last = MT_walker, + }; + +public: + float getSpeed(MovementTypes index) const; + float getSpeedMin(MovementTypes index) const; + float getSpeedMax(MovementTypes index) const; + float getSlopeAversion(bool testData = false) const; + float getSlopeAversionMin(bool testData = false) const; + float getSlopeAversionMax(bool testData = false) const; + float getHoverValue(bool testData = false) const; + float getHoverValueMin(bool testData = false) const; + float getHoverValueMax(bool testData = false) const; + float getTurnRate(bool testData = false) const; + float getTurnRateMin(bool testData = false) const; + float getTurnRateMax(bool testData = false) const; + float getMaxVelocity(bool testData = false) const; + float getMaxVelocityMin(bool testData = false) const; + float getMaxVelocityMax(bool testData = false) const; + float getAcceleration(bool testData = false) const; + float getAccelerationMin(bool testData = false) const; + float getAccelerationMax(bool testData = false) const; + float getBraking(bool testData = false) const; + float getBrakingMin(bool testData = false) const; + float getBrakingMax(bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + FloatParam m_speed[5]; // how fast the vehicle moves + FloatParam m_slopeAversion; // ? + FloatParam m_hoverValue; // height vehicle hovers at + FloatParam m_turnRate; // how tight the vehicle turns (?) + FloatParam m_maxVelocity; // max speed the vehicle can move + FloatParam m_acceleration; // vehicle acceleration + FloatParam m_braking; // vehicle braking +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedVehicleObjectTemplate(const SharedVehicleObjectTemplate &); + SharedVehicleObjectTemplate & operator =(const SharedVehicleObjectTemplate &); +}; + + +inline void SharedVehicleObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedVehicleObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedVehicleObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedWaypointObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedWaypointObjectTemplate.cpp new file mode 100644 index 00000000..70d98cd2 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedWaypointObjectTemplate.cpp @@ -0,0 +1,175 @@ +//======================================================================== +// +// SharedWaypointObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedWaypointObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedWaypointObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedWaypointObjectTemplate::SharedWaypointObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedIntangibleObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedWaypointObjectTemplate::SharedWaypointObjectTemplate + +/** + * Class destructor. + */ +SharedWaypointObjectTemplate::~SharedWaypointObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedWaypointObjectTemplate::~SharedWaypointObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedWaypointObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedWaypointObjectTemplate_tag, create); +} // SharedWaypointObjectTemplate::registerMe + +/** + * Creates a SharedWaypointObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedWaypointObjectTemplate::create(const std::string & filename) +{ + return new SharedWaypointObjectTemplate(filename); +} // SharedWaypointObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedWaypointObjectTemplate::getId(void) const +{ + return SharedWaypointObjectTemplate_tag; +} // SharedWaypointObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedWaypointObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedWaypointObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedWaypointObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedWaypointObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedWaypointObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedWaypointObjectTemplate::testValues(void) const +{ + SharedIntangibleObjectTemplate::testValues(); +} // SharedWaypointObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedWaypointObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedWaypointObjectTemplate_tag) + { + SharedIntangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,0)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + UNREF(paramName); + UNREF(paramCount); + + file.exitForm(); + SharedIntangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedWaypointObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedWaypointObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedWaypointObjectTemplate.h new file mode 100644 index 00000000..4fb31a6b --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedWaypointObjectTemplate.h @@ -0,0 +1,83 @@ +//======================================================================== +// +// SharedWaypointObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedWaypointObjectTemplate_H +#define _INCLUDED_SharedWaypointObjectTemplate_H + +#include "SharedIntangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedWaypointObjectTemplate : public SharedIntangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedWaypointObjectTemplate_tag = TAG(S,W,A,Y) + }; +//@END TFD ID +public: + SharedWaypointObjectTemplate(const std::string & filename); + virtual ~SharedWaypointObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedWaypointObjectTemplate(const SharedWaypointObjectTemplate &); + SharedWaypointObjectTemplate & operator =(const SharedWaypointObjectTemplate &); +}; + + +inline void SharedWaypointObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedWaypointObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedWaypointObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedWeaponObjectTemplate.cpp b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedWeaponObjectTemplate.cpp new file mode 100644 index 00000000..1630d557 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedWeaponObjectTemplate.cpp @@ -0,0 +1,465 @@ +//======================================================================== +// +// SharedWeaponObjectTemplate.cpp +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "SharedWeaponObjectTemplate.h" +#include "sharedFile/Iff.h" +#include "sharedMath/Vector.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS +#include + +const std::string DefaultString(""); +const StringId DefaultStringId("", 0); +const Vector DefaultVector(0,0,0); +const TriggerVolumeData DefaultTriggerVolumeData; + +bool SharedWeaponObjectTemplate::ms_allowDefaultTemplateParams = true; + + +/** + * Class constructor. + */ +SharedWeaponObjectTemplate::SharedWeaponObjectTemplate(const std::string & filename) +//@BEGIN TFD INIT + : SharedTangibleObjectTemplate(filename) + ,m_versionOk(true) +//@END TFD INIT +{ +} // SharedWeaponObjectTemplate::SharedWeaponObjectTemplate + +/** + * Class destructor. + */ +SharedWeaponObjectTemplate::~SharedWeaponObjectTemplate() +{ +//@BEGIN TFD CLEANUP +//@END TFD CLEANUP +} // SharedWeaponObjectTemplate::~SharedWeaponObjectTemplate + +/** + * Static function used to register this template. + */ +void SharedWeaponObjectTemplate::registerMe(void) +{ + ObjectTemplateList::registerTemplate(SharedWeaponObjectTemplate_tag, create); +} // SharedWeaponObjectTemplate::registerMe + +/** + * Creates a SharedWeaponObjectTemplate template. + * + * @return a new instance of the template + */ +ObjectTemplate * SharedWeaponObjectTemplate::create(const std::string & filename) +{ + return new SharedWeaponObjectTemplate(filename); +} // SharedWeaponObjectTemplate::create + +/** + * Returns the template id. + * + * @return the template id + */ +Tag SharedWeaponObjectTemplate::getId(void) const +{ + return SharedWeaponObjectTemplate_tag; +} // SharedWeaponObjectTemplate::getId + +/** + * Returns this template's version. + * + * @return the version + */ +Tag SharedWeaponObjectTemplate::getTemplateVersion(void) const +{ + return m_templateVersion; +} // SharedWeaponObjectTemplate::getTemplateVersion + +/** + * Returns the highest version of this template or it's base templates. + * + * @return the highest version + */ +Tag SharedWeaponObjectTemplate::getHighestTemplateVersion(void) const +{ + if (m_baseData == NULL) + return m_templateVersion; + const SharedWeaponObjectTemplate * base = dynamic_cast(m_baseData); + if (base == NULL) + return m_templateVersion; + return std::max(m_templateVersion, base->getHighestTemplateVersion()); +} // SharedWeaponObjectTemplate::getHighestTemplateVersion + +//@BEGIN TFD +const std::string & SharedWeaponObjectTemplate::getWeaponEffect(bool testData) const +{ +#ifdef _DEBUG +std::string testDataValue = DefaultString; +#else +UNREF(testData); +#endif + + const SharedWeaponObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getWeaponEffect(true); +#endif + } + + if (!m_weaponEffect.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter weaponEffect in template %s", DataResource::getName())); + return DefaultString; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter weaponEffect has not been defined in template %s!", DataResource::getName())); + return base->getWeaponEffect(); + } + } + + const std::string & value = m_weaponEffect.getValue(); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedWeaponObjectTemplate::getWeaponEffect + +int SharedWeaponObjectTemplate::getWeaponEffectIndex(bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedWeaponObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getWeaponEffectIndex(true); +#endif + } + + if (!m_weaponEffectIndex.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter weaponEffectIndex in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter weaponEffectIndex has not been defined in template %s!", DataResource::getName())); + return base->getWeaponEffectIndex(); + } + } + + int value = m_weaponEffectIndex.getValue(); + char delta = m_weaponEffectIndex.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getWeaponEffectIndex(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedWeaponObjectTemplate::getWeaponEffectIndex + +int SharedWeaponObjectTemplate::getWeaponEffectIndexMin(bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedWeaponObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getWeaponEffectIndexMin(true); +#endif + } + + if (!m_weaponEffectIndex.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter weaponEffectIndex in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter weaponEffectIndex has not been defined in template %s!", DataResource::getName())); + return base->getWeaponEffectIndexMin(); + } + } + + int value = m_weaponEffectIndex.getMinValue(); + char delta = m_weaponEffectIndex.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getWeaponEffectIndexMin(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedWeaponObjectTemplate::getWeaponEffectIndexMin + +int SharedWeaponObjectTemplate::getWeaponEffectIndexMax(bool testData) const +{ +#ifdef _DEBUG +int testDataValue = 0; +#else +UNREF(testData); +#endif + + const SharedWeaponObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getWeaponEffectIndexMax(true); +#endif + } + + if (!m_weaponEffectIndex.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter weaponEffectIndex in template %s", DataResource::getName())); + return 0; + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter weaponEffectIndex has not been defined in template %s!", DataResource::getName())); + return base->getWeaponEffectIndexMax(); + } + } + + int value = m_weaponEffectIndex.getMaxValue(); + char delta = m_weaponEffectIndex.getDeltaType(); + if (delta == '+' || delta == '-' || delta == '_' || delta == '=') + { + int baseValue = 0; + if (m_baseData != NULL) + { + if (base != NULL) + baseValue = base->getWeaponEffectIndexMax(); + else if (ms_allowDefaultTemplateParams) + DEBUG_WARNING(true, ("No base template for delta, using 0")); + else + NOT_NULL(base); + } + if (delta == '+') + value = baseValue + value; + else if (delta == '-') + value = baseValue - value; + else if (delta == '=') + value = baseValue + static_cast(baseValue * (value / 100.0f)); + else if (delta == '_') + value = baseValue - static_cast(baseValue * (value / 100.0f)); + } +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedWeaponObjectTemplate::getWeaponEffectIndexMax + +SharedWeaponObjectTemplate::AttackType SharedWeaponObjectTemplate::getAttackType(bool testData) const +{ +#ifdef _DEBUG +SharedWeaponObjectTemplate::AttackType testDataValue = static_cast(0); +#else +UNREF(testData); +#endif + + const SharedWeaponObjectTemplate * base = NULL; + if (m_baseData != NULL) + { + base = dynamic_cast(m_baseData); +#ifdef _DEBUG + if (testData && base != NULL) + testDataValue = base->getAttackType(true); +#endif + } + + if (!m_attackType.isLoaded()) + { + if (ms_allowDefaultTemplateParams && /*!m_versionOk &&*/ base == NULL) + { + DEBUG_WARNING(true, ("Returning default value for missing parameter attackType in template %s", DataResource::getName())); + return static_cast(0); + } + else + { + DEBUG_FATAL(base == NULL, ("Template parameter attackType has not been defined in template %s!", DataResource::getName())); + return base->getAttackType(); + } + } + + AttackType value = static_cast(m_attackType.getValue()); +#ifdef _DEBUG + if (testData && base != NULL) + { + } +#endif + + return value; +} // SharedWeaponObjectTemplate::getAttackType + +#ifdef _DEBUG +/** + * Special function used by datalint. Checks for duplicate values in base and derived templates. + */ +void SharedWeaponObjectTemplate::testValues(void) const +{ + IGNORE_RETURN(getWeaponEffect(true)); + IGNORE_RETURN(getWeaponEffectIndexMin(true)); + IGNORE_RETURN(getWeaponEffectIndexMax(true)); + IGNORE_RETURN(getAttackType(true)); + SharedTangibleObjectTemplate::testValues(); +} // SharedWeaponObjectTemplate::testValues +#endif + +/** + * Loads the template data from an iff file. We should already be in the form + * for this template. + * + * @param file file to load from + */ +void SharedWeaponObjectTemplate::load(Iff &file) +{ +static const int MAX_NAME_SIZE = 256; +char paramName[MAX_NAME_SIZE]; + + if (file.getCurrentName() != SharedWeaponObjectTemplate_tag) + { + SharedTangibleObjectTemplate::load(file); + return; + } + + file.enterForm(); + m_templateVersion = file.getCurrentName(); + if (m_templateVersion == TAG(D,E,R,V)) + { + file.enterForm(); + file.enterChunk(); + std::string baseFilename; + file.read_string(baseFilename); + file.exitChunk(); + const ObjectTemplate *base = ObjectTemplateList::fetch(baseFilename); + DEBUG_WARNING(base == NULL, ("was unable to load base template %s", baseFilename.c_str())); + if (m_baseData == base && base != NULL) + base->releaseReference(); + else + { + if (m_baseData != NULL) + m_baseData->releaseReference(); + m_baseData = base; + } + file.exitForm(); + m_templateVersion = file.getCurrentName(); + } + if (getHighestTemplateVersion() != TAG(0,0,0,4)) + { + if (DataLint::isEnabled()) + DEBUG_WARNING(true, ("template %s version out of date", file.getFileName())); + m_versionOk = false; + } + + file.enterForm(); + + file.enterChunk(); + int paramCount = file.read_int32(); + file.exitChunk(); + for (int i = 0; i < paramCount; ++i) + { + file.enterChunk(); + file.read_string(paramName, MAX_NAME_SIZE); + if (strcmp(paramName, "weaponEffect") == 0) + m_weaponEffect.loadFromIff(file); + else if (strcmp(paramName, "weaponEffectIndex") == 0) + m_weaponEffectIndex.loadFromIff(file); + else if (strcmp(paramName, "attackType") == 0) + m_attackType.loadFromIff(file); + file.exitChunk(true); + } + + file.exitForm(); + SharedTangibleObjectTemplate::load(file); + file.exitForm(); + return; +} // SharedWeaponObjectTemplate::load + +//@END TFD diff --git a/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedWeaponObjectTemplate.h b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedWeaponObjectTemplate.h new file mode 100644 index 00000000..ba4d771c --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/objectTemplate/SharedWeaponObjectTemplate.h @@ -0,0 +1,101 @@ +//======================================================================== +// +// SharedWeaponObjectTemplate.h +// +//IMPORTANT: Any code between //@BEGIN TFD... and //@END TFD... will be +//overwritten the next time the template definition is compiled. Do not +//make changes to code inside these blocks. +// +// copyright 2001 Sony Online Entertainment +// +//======================================================================== + +#ifndef _INCLUDED_SharedWeaponObjectTemplate_H +#define _INCLUDED_SharedWeaponObjectTemplate_H + +#include "SharedTangibleObjectTemplate.h" +#include "sharedFoundation/DynamicVariable.h" +#include "sharedUtility/TemplateParameter.h" + + +class Vector; +typedef StructParam StructParamOT; +//@BEGIN TFD TEMPLATE REFS +//@END TFD TEMPLATE REFS + + +class SharedWeaponObjectTemplate : public SharedTangibleObjectTemplate +{ +public: +//@BEGIN TFD ID + enum + { + SharedWeaponObjectTemplate_tag = TAG(S,W,O,T) + }; +//@END TFD ID +public: + SharedWeaponObjectTemplate(const std::string & filename); + virtual ~SharedWeaponObjectTemplate(); + + virtual Tag getId(void) const; + virtual Tag getTemplateVersion(void) const; + virtual Tag getHighestTemplateVersion(void) const; + static void install(bool allowDefaultTemplateParams = true); + +//@BEGIN TFD +public: + enum AttackType + { + AT_melee, + AT_ranged, + AT_thrown, + AT_ammo, + AttackType_Last = AT_ammo, + }; + +public: + const std::string & getWeaponEffect(bool testData = false) const; + int getWeaponEffectIndex(bool testData = false) const; + int getWeaponEffectIndexMin(bool testData = false) const; + int getWeaponEffectIndexMax(bool testData = false) const; + AttackType getAttackType(bool testData = false) const; + +#ifdef _DEBUG +public: + // special code used by datalint + virtual void testValues(void) const; +#endif + +protected: + virtual void load(Iff &file); + +private: + StringParam m_weaponEffect; // The id lookup into the weapon data table for the bolt and combat effects. + IntegerParam m_weaponEffectIndex; // The index 0-4 for a specific weaponEffect in the weapon data table. + IntegerParam m_attackType; // Type of attack this weapon is used with. +//@END TFD + +private: + Tag m_templateVersion; // the template version + bool m_versionOk; // flag that the template version loaded is the one we expect + static bool ms_allowDefaultTemplateParams; // flag to allow defaut params instead of fataling + + static void registerMe(void); + static ObjectTemplate * create(const std::string & filename); + + // no copying + SharedWeaponObjectTemplate(const SharedWeaponObjectTemplate &); + SharedWeaponObjectTemplate & operator =(const SharedWeaponObjectTemplate &); +}; + + +inline void SharedWeaponObjectTemplate::install(bool allowDefaultTemplateParams) +{ + ms_allowDefaultTemplateParams = allowDefaultTemplateParams; +//@BEGIN TFD INSTALL + SharedWeaponObjectTemplate::registerMe(); +//@END TFD INSTALL +} + + +#endif // _INCLUDED_SharedWeaponObjectTemplate_H diff --git a/engine/shared/library/sharedGame/src/shared/quest/PlayerQuestData.cpp b/engine/shared/library/sharedGame/src/shared/quest/PlayerQuestData.cpp new file mode 100644 index 00000000..e944ed62 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/quest/PlayerQuestData.cpp @@ -0,0 +1,367 @@ +// ====================================================================== +// +// PlayerQuestData.cpp +// copyright (c) 2004 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/PlayerQuestData.h" + +#include "Archive/Archive.h" +#include "Archive/AutoDeltaPackedMap.h" +#include "sharedFoundation/NetworkIdArchive.h" + +#include + +// ====================================================================== + +uint32 PlayerQuestData::ms_lastRelativeAgeIndex = 0; + +// ====================================================================== + +PlayerQuestData::PlayerQuestData () : + m_questGiver(NetworkId::cms_invalid), + m_completed(false), + m_activeTasks(0), + m_completedTasks(0), + m_relativeAgeIndex(++ms_lastRelativeAgeIndex), + m_hasReceivedReward(false) +{ +} + +// ---------------------------------------------------------------------- + +PlayerQuestData::PlayerQuestData(bool const completed, bool const receivedReward) : + m_questGiver(NetworkId::cms_invalid), + m_completed(completed), + m_activeTasks(0), + m_completedTasks(0), + m_relativeAgeIndex(++ms_lastRelativeAgeIndex), + m_hasReceivedReward(receivedReward) +{ +} + +// ---------------------------------------------------------------------- + +PlayerQuestData::PlayerQuestData(NetworkId const & questGiver) : + m_questGiver(questGiver), + m_completed(false), + m_activeTasks(0), + m_completedTasks(0), + m_relativeAgeIndex(++ms_lastRelativeAgeIndex), + m_hasReceivedReward(false) +{ +} + +// ---------------------------------------------------------------------- + +PlayerQuestData::PlayerQuestData(NetworkId const & questGiver, uint16 const activeTasks, uint16 const completedTasks, bool receivedReward) : + m_questGiver(questGiver), + m_completed(false), + m_activeTasks(activeTasks), + m_completedTasks(completedTasks), + m_relativeAgeIndex(++ms_lastRelativeAgeIndex), + m_hasReceivedReward(receivedReward) +{ +} + +// ---------------------------------------------------------------------- + +PlayerQuestData::~PlayerQuestData() +{ +} + +// ---------------------------------------------------------------------- + +bool PlayerQuestData::operator!=(PlayerQuestData const & rhs) const +{ + return (m_questGiver != rhs.m_questGiver) || + (m_activeTasks != rhs.m_activeTasks) || + (m_completedTasks != rhs.m_completedTasks) || + (m_completed != rhs.m_completed) || + (m_hasReceivedReward != rhs.m_hasReceivedReward); +} + +// ---------------------------------------------------------------------- + +NetworkId const & PlayerQuestData::getQuestGiver() const +{ + return m_questGiver; +} + +// ---------------------------------------------------------------------- + +uint16 PlayerQuestData::getActiveTasks() const +{ + return m_activeTasks; +} + +// ---------------------------------------------------------------------- + +uint16 PlayerQuestData::getCompletedTasks() const +{ + return m_completedTasks; +} + +// ---------------------------------------------------------------------- + +bool PlayerQuestData::hasReceivedReward() const +{ + return m_hasReceivedReward; +} + +// ---------------------------------------------------------------------- + +void PlayerQuestData::setHasReceivedReward(bool const hasReceivedReward) +{ + m_hasReceivedReward = hasReceivedReward; +} + +// ---------------------------------------------------------------------- + +bool PlayerQuestData::isTaskActive(int const taskId) const +{ + return (!m_completed && ((m_activeTasks & getTaskMask(taskId)) != 0)); +} + +// ---------------------------------------------------------------------- + +bool PlayerQuestData::isTaskCompleted(int const taskId) const +{ + return (m_completed || ((m_completedTasks & getTaskMask(taskId)) != 0)); +} + +// ---------------------------------------------------------------------- + +void PlayerQuestData::activateTask(int const taskId) +{ + m_completedTasks &= ~getTaskMask(taskId); + m_activeTasks |= getTaskMask(taskId); + + // Refresh the relative age of this quest since its data has changed + m_relativeAgeIndex = (++ms_lastRelativeAgeIndex); +} + +// ---------------------------------------------------------------------- + +void PlayerQuestData::completeTask(int const taskId) +{ + m_activeTasks &= ~getTaskMask(taskId); + m_completedTasks |= getTaskMask(taskId); + + // Refresh the relative age of this quest since its data has changed + m_relativeAgeIndex = (++ms_lastRelativeAgeIndex); +} + +// ---------------------------------------------------------------------- + +void PlayerQuestData::clearTask(int const taskId) +{ + m_activeTasks &= ~getTaskMask(taskId); + m_completedTasks &= ~getTaskMask(taskId); + + // Refresh the relative age of this quest since its data has changed + m_relativeAgeIndex = (++ms_lastRelativeAgeIndex); +} + +// ---------------------------------------------------------------------- + +uint16 PlayerQuestData::getTaskMask(int const taskId) const +{ + DEBUG_FATAL(taskId < 0 || taskId > static_cast(sizeof(m_activeTasks) * 8),("PlayerQuestData::getTaskMask called with task id %i, which is not in the valid range for a task id.", taskId)); + return static_cast(1 << taskId); +} + +// ---------------------------------------------------------------------- + +void PlayerQuestData::complete() +{ + m_completed=true; + + // Refresh the relative age of this quest since its data has changed + m_relativeAgeIndex = (++ms_lastRelativeAgeIndex); +} + +// ---------------------------------------------------------------------- + +bool PlayerQuestData::isCompleted() const +{ + return m_completed; +} + +// ---------------------------------------------------------------------- + +uint32 PlayerQuestData::getRelativeAgeIndex() const +{ + return m_relativeAgeIndex; +} + +// ====================================================================== + +namespace Archive +{ + // Class to help us sort quest data by age + class QuestDataToSort + { + public: + QuestDataToSort() : + m_key(0) + {} + + QuestDataToSort( uint32 key, PlayerQuestData const& questData ) : + m_key(key), + m_questData(questData) + {} + + bool operator<(QuestDataToSort const & rhs) const + { + return (m_questData.getRelativeAgeIndex() < rhs.m_questData.getRelativeAgeIndex()); + } + + uint32 GetPlayerQuestDataKey() const { return m_key; } + PlayerQuestData const& GetPlayerQuestData() const { return m_questData; } + + private: + uint32 m_key; + PlayerQuestData m_questData; + }; + + typedef std::list SortableQuestList; + + //---------------------------------------------------------------------- + + class ByteStream; + class ReadIterator; + void get(ReadIterator & source, PlayerQuestData & target) + { + get(source,target.m_questGiver); + get(source,target.m_activeTasks); + get(source,target.m_completedTasks); + get(source,target.m_completed); + get(source,target.m_relativeAgeIndex); + get(source,target.m_hasReceivedReward); + } + + void put(ByteStream & target, const PlayerQuestData & source) + { + put(target,source.m_questGiver); + put(target,source.m_activeTasks); + put(target,source.m_completedTasks); + put(target,source.m_completed); + put(target,source.m_relativeAgeIndex); + put(target,source.m_hasReceivedReward); + } + + void Archive::AutoDeltaPackedMap::unpack(ReadIterator & source, std::string & buffer) + { + char temp[200]; + + Command c; + size_t commandCount; + size_t baselineCommandCount; //lint !e578 hides a symbol elsewhere + + Archive::get(source, commandCount); + Archive::get(source, baselineCommandCount); + + if (commandCount==0) + { + buffer=' '; // An empty map is represented as a single space, because a completely empty string is used to mean "no change" + } + else + { + // We need to sort the quests by age + SortableQuestList sortedQuests; + + for (size_t i = 0; i < commandCount; ++i) + { + Archive::get(source, c.cmd); + Archive::get(source, c.key); + Archive::get(source, c.value); + + sortedQuests.push_back(QuestDataToSort(c.key, c.value)); + } + + // Sort the quests + sortedQuests.sort(); + + // Output the quests as strings + for ( SortableQuestList::const_iterator j = sortedQuests.begin(); j != sortedQuests.end(); ++j ) + { + QuestDataToSort const& questDataToSort = (*j); + uint32 const playerQuestDataKey = questDataToSort.GetPlayerQuestDataKey(); + PlayerQuestData const& playerQuestData = questDataToSort.GetPlayerQuestData(); + + if (playerQuestData.isCompleted()) + { + IGNORE_RETURN(snprintf(temp, sizeof(temp)-1, "%lu %hi:", playerQuestDataKey, playerQuestData.hasReceivedReward() ? static_cast(1) : static_cast(0))); + } + else + { + IGNORE_RETURN(snprintf(temp, sizeof(temp)-1, "%lu %hi %hi %s:", playerQuestDataKey, playerQuestData.getActiveTasks(), playerQuestData.getCompletedTasks(), playerQuestData.getQuestGiver().getValueString().c_str())); + } + + temp[sizeof(temp)-1]='\0'; + buffer+=temp; + } + } + } + + void Archive::AutoDeltaPackedMap::pack(ByteStream & target, std::string const & buffer) + { + char temp[200]; + AutoDeltaMap::Command c; + + Archive::put(target, countCharacter(buffer,':')); + Archive::put(target, static_cast(0)); // baselineCommandCount + + int tempPos = 0; + for (std::string::const_iterator i=buffer.begin(); i!=buffer.end(); ++i) + { + if (*i==':') + { + uint16 activeTasks = 0; + uint16 completedTasks = 0; + char giver[100]; + temp[tempPos]='\0'; + int const numScanned = sscanf(temp,"%lu %hi %hi %s", &c.key, &activeTasks, &completedTasks, giver); + //active quests + if (numScanned == 4) + { + // in-progress quest + Archive::put(target, static_cast(Command::ADD)); + Archive::put(target, c.key); + Archive::put(target, PlayerQuestData(NetworkId(giver), activeTasks, completedTasks, false)); + } + //"old-style" completed quests, which don't store extra flags + else if (numScanned==1) + { + // completed quest + Archive::put(target, static_cast(Command::ADD)); + Archive::put(target, c.key); + Archive::put(target, PlayerQuestData(true, true)); + } + //completed quests with store flags + else if (numScanned==2) + { + // completed quest + Archive::put(target, static_cast(Command::ADD)); + Archive::put(target, c.key); + //this is really a flags field + uint16 const flags = activeTasks; + bool const hasReceivedReward = (flags != 0); + Archive::put(target, PlayerQuestData(true, hasReceivedReward)); + } + else + FATAL(true,("Could not parse packed quest data %s,",temp)); + tempPos=0; + } + else + { + temp[tempPos++]=*i; + } + } + } +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/quest/PlayerQuestData.h b/engine/shared/library/sharedGame/src/shared/quest/PlayerQuestData.h new file mode 100644 index 00000000..6cd7e769 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/quest/PlayerQuestData.h @@ -0,0 +1,83 @@ +// ====================================================================== +// +// PlayerQuestData.h +// copyright (c) 2004 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_PlayerQuestData_H +#define INCLUDED_PlayerQuestData_H + +// ====================================================================== + +#include "sharedFoundation/NetworkId.h" + +// ====================================================================== + +class PlayerQuestData; + +namespace Archive +{ + class ByteStream; + class ReadIterator; + void get(ReadIterator & source, PlayerQuestData & target); + void put(ByteStream & target, const PlayerQuestData & source); +} + +// ====================================================================== + +/** + * A class that tracks an active quest for a player + */ +class PlayerQuestData +{ + public: + PlayerQuestData (); + explicit PlayerQuestData (NetworkId const & questGiver); + PlayerQuestData (NetworkId const & questGiver, uint16 activeTasks, uint16 completedTasks, bool hasReceivedReward); + PlayerQuestData (bool completed, bool receivedReward); + ~PlayerQuestData(); + + bool operator!=(PlayerQuestData const & rhs) const; + void packToString(std::string & buffer) const; + void unpackFromString(std::string const & buffer); + + NetworkId const & getQuestGiver() const; + uint16 getActiveTasks() const; + uint16 getCompletedTasks() const; + bool hasReceivedReward() const; + void setHasReceivedReward(bool hasReceivedReward); + + bool isCompleted() const; + + bool isTaskActive(int taskId) const; + bool isTaskCompleted(int taskId) const; + + void complete(); + void activateTask(int taskId); + void completeTask(int taskId); + void clearTask(int taskId); + + uint32 getRelativeAgeIndex() const; + + private: + uint16 getTaskMask(int taskId) const; + + private: + // We need to keep track of the relative age of Quest data + static uint32 ms_lastRelativeAgeIndex; + + NetworkId m_questGiver; + bool m_completed; + uint16 m_activeTasks; + uint16 m_completedTasks; + uint32 m_relativeAgeIndex; // This is not meant to be persisted + bool m_hasReceivedReward; + + friend void Archive::get(ReadIterator & source, PlayerQuestData & target); + friend void Archive::put(ByteStream & target, const PlayerQuestData & source); +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/quest/Quest.cpp b/engine/shared/library/sharedGame/src/shared/quest/Quest.cpp new file mode 100644 index 00000000..7cfaccef --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/quest/Quest.cpp @@ -0,0 +1,557 @@ + // ====================================================================== +// +// Quest.cpp +// copyright (c) 2004 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/Quest.h" + +#include "sharedFile/Iff.h" +#include "sharedFoundation/Crc.h" +#include "sharedFoundation/FormattedString.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedGame/QuestTask.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" +#include +#include + +// ====================================================================== + +namespace Quest_Namespace +{ + std::string const cs_summaryTablePrefix("datatables/questlist/"); + std::string const cs_taskTablePrefix("datatables/questtask/"); + std::string const cs_journalEntryTitleColumn("JOURNAL_ENTRY_TITLE"); + std::string const cs_journalEntryDescriptionColumn("JOURNAL_ENTRY_DESCRIPTION"); + std::string const cs_prerequisiteQuestsColumn("PREREQUISITE_QUESTS"); + std::string const cs_exclusionQuestsColumn("EXCLUSION_QUESTS"); + std::string const cs_allowRepeatsColumn("ALLOW_REPEATS"); + std::string const cs_visibleColumn("VISIBLE"); + std::string const cs_categoryColumn("CATEGORY"); + std::string const cs_completeQuestWhenTasksCompleteColumn("COMPLETE_WHEN_TASKS_COMPLETE"); + std::string const cs_levelColumn("LEVEL"); + std::string const cs_tierColumn("TIER"); + std::string const cs_typeColumn("TYPE"); + std::string const cs_experienceRewardTypeColumn("QUEST_REWARD_EXPERIENCE_TYPE"); + std::string const cs_experienceRewardAmountColumn("QUEST_REWARD_EXPERIENCE_AMOUNT"); + std::string const cs_factionRewardTypeColumn("QUEST_REWARD_FACTION_NAME"); + std::string const cs_factionRewardAmountColumn("QUEST_REWARD_FACTION_AMOUNT"); + std::string const cs_moneyRewardCreditsColumn("QUEST_REWARD_BANK_CREDITS"); + std::string const cs_journalEntryCompetionSummaryColumn("JOURNAL_ENTRY_COMPLETION_SUMMARY"); + std::string const cs_inclusiveLootNameColumn("QUEST_REWARD_LOOT_NAME"); + std::string const cs_inclusiveLootCountColumn("QUEST_REWARD_LOOT_COUNT"); + std::string const cs_inclusiveLootNameColumn2("QUEST_REWARD_LOOT_NAME_2"); + std::string const cs_inclusiveLootCountColumn2("QUEST_REWARD_LOOT_COUNT_2"); + std::string const cs_inclusiveLootNameColumn3("QUEST_REWARD_LOOT_NAME_3"); + std::string const cs_inclusiveLootCountColumn3("QUEST_REWARD_LOOT_COUNT_3"); + std::string const cs_exclusiveLootNameColumn("QUEST_REWARD_EXCLUSIVE_LOOT_NAME"); + std::string const cs_exclusiveLootCountColumn("QUEST_REWARD_EXCLUSIVE_LOOT_COUNT"); + std::string const cs_exclusiveLootNameColumn2("QUEST_REWARD_EXCLUSIVE_LOOT_NAME_2"); + std::string const cs_exclusiveLootCountColumn2("QUEST_REWARD_EXCLUSIVE_LOOT_COUNT_2"); + std::string const cs_exclusiveLootNameColumn3("QUEST_REWARD_EXCLUSIVE_LOOT_NAME_3"); + std::string const cs_exclusiveLootCountColumn3("QUEST_REWARD_EXCLUSIVE_LOOT_COUNT_3"); + std::string const cs_exclusiveLootNameColumn4("QUEST_REWARD_EXCLUSIVE_LOOT_NAME_4"); + std::string const cs_exclusiveLootCountColumn4("QUEST_REWARD_EXCLUSIVE_LOOT_COUNT_4"); + std::string const cs_exclusiveLootNameColumn5("QUEST_REWARD_EXCLUSIVE_LOOT_NAME_5"); + std::string const cs_exclusiveLootCountColumn5("QUEST_REWARD_EXCLUSIVE_LOOT_COUNT_5"); + std::string const cs_exclusiveLootNameColumn6("QUEST_REWARD_EXCLUSIVE_LOOT_NAME_6"); + std::string const cs_exclusiveLootCountColumn6("QUEST_REWARD_EXCLUSIVE_LOOT_COUNT_6"); + std::string const cs_exclusiveLootNameColumn7("QUEST_REWARD_EXCLUSIVE_LOOT_NAME_7"); + std::string const cs_exclusiveLootCountColumn7("QUEST_REWARD_EXCLUSIVE_LOOT_COUNT_7"); + std::string const cs_exclusiveLootNameColumn8("QUEST_REWARD_EXCLUSIVE_LOOT_NAME_8"); + std::string const cs_exclusiveLootCountColumn8("QUEST_REWARD_EXCLUSIVE_LOOT_COUNT_8"); + std::string const cs_exclusiveLootNameColumn9("QUEST_REWARD_EXCLUSIVE_LOOT_NAME_9"); + std::string const cs_exclusiveLootCountColumn9("QUEST_REWARD_EXCLUSIVE_LOOT_COUNT_9"); + std::string const cs_exclusiveLootNameColumn10("QUEST_REWARD_EXCLUSIVE_LOOT_NAME_10"); + std::string const cs_exclusiveLootCountColumn10("QUEST_REWARD_EXCLUSIVE_LOOT_COUNT_10"); + + char const * const cs_questExperienceDataTableFile = "datatables/quest/quest_experience.iff"; + char const * const cs_questExperienceDataTableLevelColumn = "LEVEL"; + char const * const cs_questExperienceDataTableTierColumns[] = + { + "TIER_1_EXPERIENCE", + "TIER_2_EXPERIENCE", + "TIER_3_EXPERIENCE", + "TIER_4_EXPERIENCE", + "TIER_5_EXPERIENCE", + "TIER_6_EXPERIENCE" + }; + + int const cs_minTierValue = -1; + int const cs_maxTierValue = 6; + + void getCrcVector(std::string const &source, std::vector & crcs); +} + +using namespace Quest_Namespace; + +// ====================================================================== + +Quest::Quest(CrcString const & name) : + m_name(name), + m_journalEntryTitle(), + m_journalEntryDescription(), + m_journalEntryCompetionSummary(), + m_prerequisiteQuests(new std::vector), + m_exclusionQuests(new std::vector), + m_tasks(new std::vector), + m_allowRepeats(false), + m_visible(true), + m_category(), + m_completeQuestWhenTasksComplete(false), + m_experienceRewardType(), + m_experienceRewardAmount(0), + m_factionRewardType(), + m_factionRewardAmount(0), + m_moneyRewardCredits(0), + m_inclusiveLootItemNames(), + m_inclusiveLootItemCounts(), + m_exclusiveLootItemNames(), + m_exclusiveLootItemCounts() +{ + //-- Summary Data + + Iff tableIff; + if (tableIff.open((cs_summaryTablePrefix + m_name.getString() + ".iff").c_str(), true)) + { + DataTable summaryTable; + summaryTable.load(tableIff); + DEBUG_FATAL(summaryTable.getNumRows()!=1,("Data bug: Data table %s had %i rows, expected it to have 1.", (cs_summaryTablePrefix + m_name.getString()).c_str(), summaryTable.getNumRows())); + m_journalEntryTitle = StringId(summaryTable.getStringValue(cs_journalEntryTitleColumn,0)); + m_journalEntryDescription = StringId(summaryTable.getStringValue(cs_journalEntryDescriptionColumn,0)); + getCrcVector(summaryTable.getStringValue(cs_prerequisiteQuestsColumn,0), *m_prerequisiteQuests); + getCrcVector(summaryTable.getStringValue(cs_exclusionQuestsColumn,0), *m_exclusionQuests); + m_allowRepeats = (summaryTable.getIntValue(cs_allowRepeatsColumn,0) != 0); + m_category = StringId(summaryTable.getStringValue(cs_categoryColumn,0)); + + if(summaryTable.doesColumnExist(cs_levelColumn)) + m_level = summaryTable.getIntValue(cs_levelColumn,0); + else + m_level = 0; + + if(summaryTable.doesColumnExist(cs_tierColumn)) + { + m_tier = summaryTable.getIntValue(cs_tierColumn,0); + clamp(cs_minTierValue, m_tier, cs_maxTierValue); + } + else + m_tier = -1; + + if(summaryTable.doesColumnExist(cs_typeColumn)) + m_type = summaryTable.getStringValue(cs_typeColumn,0); + else + m_type.clear(); + + if(summaryTable.doesColumnExist(cs_visibleColumn)) + m_visible = (summaryTable.getIntValue(cs_visibleColumn,0) != 0); + else + m_visible = true; + + if(summaryTable.doesColumnExist(cs_experienceRewardTypeColumn)) + m_experienceRewardType = summaryTable.getStringValue(cs_experienceRewardTypeColumn,0); + + if(summaryTable.doesColumnExist(cs_experienceRewardAmountColumn)) + m_experienceRewardAmount = summaryTable.getIntValue(cs_experienceRewardAmountColumn,0); + + if(summaryTable.doesColumnExist(cs_factionRewardTypeColumn)) + m_factionRewardType = summaryTable.getStringValue(cs_factionRewardTypeColumn,0); + + if(summaryTable.doesColumnExist(cs_factionRewardAmountColumn)) + m_factionRewardAmount = summaryTable.getIntValue(cs_factionRewardAmountColumn,0); + + if(summaryTable.doesColumnExist(cs_moneyRewardCreditsColumn)) + m_moneyRewardCredits = summaryTable.getIntValue(cs_moneyRewardCreditsColumn,0); + + if(summaryTable.doesColumnExist(cs_completeQuestWhenTasksCompleteColumn)) + m_completeQuestWhenTasksComplete = (summaryTable.getIntValue(cs_completeQuestWhenTasksCompleteColumn,0) != 0); + + if(summaryTable.doesColumnExist(cs_journalEntryCompetionSummaryColumn)) + m_journalEntryCompetionSummary = StringId(summaryTable.getStringValue(cs_journalEntryCompetionSummaryColumn,0)); + + std::string s; + if(summaryTable.doesColumnExist(cs_inclusiveLootNameColumn) && summaryTable.doesColumnExist(cs_inclusiveLootCountColumn)) + { + s = summaryTable.getStringValue(cs_inclusiveLootNameColumn,0); + if(!s.empty()) + { + m_inclusiveLootItemNames.push_back(s); + m_inclusiveLootItemCounts.push_back(summaryTable.getIntValue(cs_inclusiveLootCountColumn,0)); + } + } + if(summaryTable.doesColumnExist(cs_inclusiveLootNameColumn2) && summaryTable.doesColumnExist(cs_inclusiveLootCountColumn2)) + { + s = summaryTable.getStringValue(cs_inclusiveLootNameColumn2,0); + if(!s.empty()) + { + m_inclusiveLootItemNames.push_back(s); + m_inclusiveLootItemCounts.push_back(summaryTable.getIntValue(cs_inclusiveLootCountColumn2,0)); + } + } + if(summaryTable.doesColumnExist(cs_inclusiveLootNameColumn3) && summaryTable.doesColumnExist(cs_inclusiveLootCountColumn3)) + { + s = summaryTable.getStringValue(cs_inclusiveLootNameColumn3,0); + if(!s.empty()) + { + m_inclusiveLootItemNames.push_back(s); + m_inclusiveLootItemCounts.push_back(summaryTable.getIntValue(cs_inclusiveLootCountColumn3,0)); + } + } + + if(summaryTable.doesColumnExist(cs_exclusiveLootNameColumn) && summaryTable.doesColumnExist(cs_exclusiveLootCountColumn)) + { + s = summaryTable.getStringValue(cs_exclusiveLootNameColumn,0); + if(!s.empty()) + { + m_exclusiveLootItemNames.push_back(s); + m_exclusiveLootItemCounts.push_back(summaryTable.getIntValue(cs_exclusiveLootCountColumn,0)); + } + } + if(summaryTable.doesColumnExist(cs_exclusiveLootNameColumn2) && summaryTable.doesColumnExist(cs_exclusiveLootCountColumn2)) + { + s = summaryTable.getStringValue(cs_exclusiveLootNameColumn2,0); + if(!s.empty()) + { + m_exclusiveLootItemNames.push_back(s); + m_exclusiveLootItemCounts.push_back(summaryTable.getIntValue(cs_exclusiveLootCountColumn2,0)); + } + } + if(summaryTable.doesColumnExist(cs_exclusiveLootNameColumn3) && summaryTable.doesColumnExist(cs_exclusiveLootCountColumn3)) + { + s = summaryTable.getStringValue(cs_exclusiveLootNameColumn3,0); + if(!s.empty()) + { + m_exclusiveLootItemNames.push_back(s); + m_exclusiveLootItemCounts.push_back(summaryTable.getIntValue(cs_exclusiveLootCountColumn3,0)); + } + } + if(summaryTable.doesColumnExist(cs_exclusiveLootNameColumn4) && summaryTable.doesColumnExist(cs_exclusiveLootCountColumn4)) + { + s = summaryTable.getStringValue(cs_exclusiveLootNameColumn4,0); + if(!s.empty()) + { + m_exclusiveLootItemNames.push_back(s); + m_exclusiveLootItemCounts.push_back(summaryTable.getIntValue(cs_exclusiveLootCountColumn4,0)); + } + } + if(summaryTable.doesColumnExist(cs_exclusiveLootNameColumn5) && summaryTable.doesColumnExist(cs_exclusiveLootCountColumn5)) + { + s = summaryTable.getStringValue(cs_exclusiveLootNameColumn5,0); + if(!s.empty()) + { + m_exclusiveLootItemNames.push_back(s); + m_exclusiveLootItemCounts.push_back(summaryTable.getIntValue(cs_exclusiveLootCountColumn5,0)); + } + } + if(summaryTable.doesColumnExist(cs_exclusiveLootNameColumn6) && summaryTable.doesColumnExist(cs_exclusiveLootCountColumn6)) + { + s = summaryTable.getStringValue(cs_exclusiveLootNameColumn6,0); + if(!s.empty()) + { + m_exclusiveLootItemNames.push_back(s); + m_exclusiveLootItemCounts.push_back(summaryTable.getIntValue(cs_exclusiveLootCountColumn6,0)); + } + } + if(summaryTable.doesColumnExist(cs_exclusiveLootNameColumn7) && summaryTable.doesColumnExist(cs_exclusiveLootCountColumn7)) + { + s = summaryTable.getStringValue(cs_exclusiveLootNameColumn7,0); + if(!s.empty()) + { + m_exclusiveLootItemNames.push_back(s); + m_exclusiveLootItemCounts.push_back(summaryTable.getIntValue(cs_exclusiveLootCountColumn7,0)); + } + } + if(summaryTable.doesColumnExist(cs_exclusiveLootNameColumn8) && summaryTable.doesColumnExist(cs_exclusiveLootCountColumn8)) + { + s = summaryTable.getStringValue(cs_exclusiveLootNameColumn8,0); + if(!s.empty()) + { + m_exclusiveLootItemNames.push_back(s); + m_exclusiveLootItemCounts.push_back(summaryTable.getIntValue(cs_exclusiveLootCountColumn8,0)); + } + } + if(summaryTable.doesColumnExist(cs_exclusiveLootNameColumn9) && summaryTable.doesColumnExist(cs_exclusiveLootCountColumn9)) + { + s = summaryTable.getStringValue(cs_exclusiveLootNameColumn9,0); + if(!s.empty()) + { + m_exclusiveLootItemNames.push_back(s); + m_exclusiveLootItemCounts.push_back(summaryTable.getIntValue(cs_exclusiveLootCountColumn9,0)); + } + } + if(summaryTable.doesColumnExist(cs_exclusiveLootNameColumn10) && summaryTable.doesColumnExist(cs_exclusiveLootCountColumn10)) + { + s = summaryTable.getStringValue(cs_exclusiveLootNameColumn10,0); + if(!s.empty()) + { + m_exclusiveLootItemNames.push_back(s); + m_exclusiveLootItemCounts.push_back(summaryTable.getIntValue(cs_exclusiveLootCountColumn10,0)); + } + } + + //-- Task list + + Iff taskIff((cs_taskTablePrefix + m_name.getString() + ".iff").c_str()); + DataTable taskList; + taskList.load(taskIff); + + int const numRows = taskList.getNumRows(); + for (int i=0; ipush_back(task); + } + } + else + DEBUG_WARNING(true,("Data tables for quest %s were not found", m_name.getString())); +} + +// ---------------------------------------------------------------------- + +Quest::~Quest() +{ + delete m_prerequisiteQuests; + delete m_exclusionQuests; + std::for_each(m_tasks->begin(), m_tasks->end(), PointerDeleter()); + delete m_tasks; +} + +// ---------------------------------------------------------------------- + +std::vector const & Quest::getPrerequisiteQuests() const +{ + return *m_prerequisiteQuests; +} + +// ---------------------------------------------------------------------- + +std::vector const & Quest::getExclusionQuests() const +{ + return *m_exclusionQuests; +} + +// ---------------------------------------------------------------------- + +bool Quest::isRepeatable() const +{ + return m_allowRepeats; +} + +// ---------------------------------------------------------------------- + +bool Quest::isVisible() const +{ + return m_visible; +} + +// ---------------------------------------------------------------------- + +int Quest::getNumberOfTasks() const +{ + return static_cast(m_tasks->size()); +} + +// ---------------------------------------------------------------------- + +QuestTask const * Quest::getTask(int const taskId) const +{ + if (taskId < 0 || taskId >= getNumberOfTasks()) + return NULL; + return (*m_tasks)[static_cast(taskId)]; +} + +// ---------------------------------------------------------------------- + +CrcString const & Quest::getName() const +{ + return m_name; +} + +// ---------------------------------------------------------------------- + +uint32 Quest::getId() const +{ + return m_name.getCrc(); +} + +// ---------------------------------------------------------------------- + +StringId const & Quest::getCategory() const +{ + return m_category; +} + +// ---------------------------------------------------------------------- + +StringId const & Quest::getJournalEntryTitle() const +{ + return m_journalEntryTitle; +} + +// ---------------------------------------------------------------------- + +StringId const & Quest::getJournalEntryDescription() const +{ + return m_journalEntryDescription; +} + +// ---------------------------------------------------------------------- + +StringId const & Quest::getJournalEntryCompetionSummary() const +{ + return m_journalEntryCompetionSummary; +} + +// ---------------------------------------------------------------------- + +bool Quest::getCompleteQuestWhenTasksComplete() const +{ + return m_completeQuestWhenTasksComplete; +} + +// ---------------------------------------------------------------------- + +int Quest::getLevel() const +{ + return m_level; +} + +// ---------------------------------------------------------------------- + +int Quest::getTier() const +{ + return m_tier; +} + +// ---------------------------------------------------------------------- + +std::string const & Quest::getType() const +{ + return m_type; +} + +// ---------------------------------------------------------------------- + +std::string const & Quest::getExperienceRewardType() const +{ + return m_experienceRewardType; +} + +// ---------------------------------------------------------------------- + +int Quest::getExperienceRewardAmount() const +{ + //-- NOTE: Any changes to this function must also be made to the script code used + //-- to calculate the reward experience given to the player. + //-- See groundquests.getQuestExperienceReward in script/library. + + DataTable * questExperienceDataTable = DataTableManager::getTable(cs_questExperienceDataTableFile, true); + + if (getLevel() < 1 || getTier() < 0) + return m_experienceRewardAmount; + + if (getTier() == 0) + return 0; + + int levelColumn = questExperienceDataTable->findColumnNumber(cs_questExperienceDataTableLevelColumn); + int levelRow = questExperienceDataTable->searchColumnString(levelColumn, + FormattedString<32>().sprintf("%d", getLevel())); + + return questExperienceDataTable->getIntValue(cs_questExperienceDataTableTierColumns[getTier()-1], levelRow); +} + +// ---------------------------------------------------------------------- + +std::string const & Quest::getFactionRewardType() const +{ + return m_factionRewardType; +} + +// ---------------------------------------------------------------------- + +int Quest::getFactionRewardAmount() const +{ + return m_factionRewardAmount; +} + +// ---------------------------------------------------------------------- + +int Quest::getMoneyRewardCredits() const +{ + return m_moneyRewardCredits; +} + +// ---------------------------------------------------------------------- + +#if 0 +std::vector const & Quest::getTasks() const +{ + return *m_tasks; +} +#endif + +// ---------------------------------------------------------------------- + +/** + * Conversts a comma-delimited list of strings into a vector or the CRCs + * of those strings. + */ +void Quest_Namespace::getCrcVector(std::string const &source, std::vector & crcs) +{ + size_t pos = 0; + size_t commaPos = source.find(',', pos); + while (commaPos != std::string::npos) + { + crcs.push_back(Crc::calculate(source.c_str()+pos, static_cast(commaPos-pos-1))); //lint !e834 a-b-c is NOT confusing + pos = commaPos+1; + commaPos = source.find(',', pos); + } + if (pos < source.size()) + crcs.push_back(Crc::calculate(source.c_str()+pos)); +} + +// ---------------------------------------------------------------------- + +std::vector const & Quest::getInclusiveStaticLootItemNames() const +{ + return m_inclusiveLootItemNames; +} + +// ---------------------------------------------------------------------- + +std::vector const & Quest::getInclusiveStaticLootItemCounts() const +{ + return m_inclusiveLootItemCounts; +} + +// ---------------------------------------------------------------------- + +std::vector const & Quest::getExclusiveStaticLootItemNames() const +{ + return m_exclusiveLootItemNames; +} + +// ---------------------------------------------------------------------- + +std::vector const & Quest::getExclusiveStaticLootItemCounts() const +{ + return m_exclusiveLootItemCounts; +} + +// ---------------------------------------------------------------------- + +bool Quest::isAnInclusiveStaticLootReward(std::string const & item) const +{ + return std::find(m_inclusiveLootItemNames.begin(), m_inclusiveLootItemNames.end(), item) != m_inclusiveLootItemNames.end(); +} + +// ---------------------------------------------------------------------- + +bool Quest::isAnExclusiveStaticLootReward(std::string const & item) const +{ + return std::find(m_exclusiveLootItemNames.begin(), m_exclusiveLootItemNames.end(), item) != m_exclusiveLootItemNames.end(); +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/quest/Quest.h b/engine/shared/library/sharedGame/src/shared/quest/Quest.h new file mode 100644 index 00000000..44f7ad7b --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/quest/Quest.h @@ -0,0 +1,95 @@ +// ====================================================================== +// +// Quest.h +// copyright (c) 2004 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_Quest_H +#define INCLUDED_Quest_H + +// ====================================================================== + +#include "sharedFoundation/PersistentCrcString.h" +#include "StringId.h" + +class QuestTask; + +// ====================================================================== + +#include + +// ====================================================================== + +/** + * Data associated with a quest. + */ +class Quest +{ +public: + explicit Quest(CrcString const & name); + ~Quest(); + +public: + bool isRepeatable() const; + bool isVisible() const; + stdvector::fwd const & getPrerequisiteQuests() const; + stdvector::fwd const & getExclusionQuests() const; + int getNumberOfTasks() const; + QuestTask const * getTask(int taskId) const; + CrcString const & getName() const; + StringId const & getJournalEntryTitle() const; + StringId const & getJournalEntryDescription() const; + StringId const & getJournalEntryCompetionSummary() const; + uint32 getId() const; + StringId const & getCategory() const; + bool getCompleteQuestWhenTasksComplete() const; + int getLevel() const; + int getTier() const; + std::string const & getType() const; + std::string const & getExperienceRewardType() const; + int getExperienceRewardAmount() const; + std::string const & getFactionRewardType() const; + int getFactionRewardAmount() const; + int getMoneyRewardCredits() const; + std::vector const & getInclusiveStaticLootItemNames() const; + std::vector const & getInclusiveStaticLootItemCounts() const; + std::vector const & getExclusiveStaticLootItemNames() const; + std::vector const & getExclusiveStaticLootItemCounts() const; + bool isAnInclusiveStaticLootReward(std::string const & item) const; + bool isAnExclusiveStaticLootReward(std::string const & item) const; + +private: + PersistentCrcString const m_name; + StringId m_journalEntryTitle; + StringId m_journalEntryDescription; + StringId m_journalEntryCompetionSummary; + stdvector::fwd * const m_prerequisiteQuests; + stdvector::fwd * const m_exclusionQuests; + stdvector::fwd * const m_tasks; + bool m_allowRepeats; + bool m_visible; + StringId m_category; + bool m_completeQuestWhenTasksComplete; + int m_level; + int m_tier; + std::string m_type; + std::string m_experienceRewardType; + int m_experienceRewardAmount; + std::string m_factionRewardType; + int m_factionRewardAmount; + int m_moneyRewardCredits; + std::vector m_inclusiveLootItemNames; + std::vector m_inclusiveLootItemCounts; + std::vector m_exclusiveLootItemNames; + std::vector m_exclusiveLootItemCounts; + +private: + Quest(); + Quest(Quest const &); + Quest & operator=(Quest const &); //disable +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/quest/QuestManager.cpp b/engine/shared/library/sharedGame/src/shared/quest/QuestManager.cpp new file mode 100644 index 00000000..ef210b43 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/quest/QuestManager.cpp @@ -0,0 +1,342 @@ +// ====================================================================== +// +// QuestManager.cpp +// copyright (c) 2004 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/QuestManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/Iff.h" +#include "sharedFile/TreeFile.h" +#include "sharedFoundation/ConstCharCrcString.h" +#include "sharedFoundation/Crc.h" +#include "sharedFoundation/CrcStringTable.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/LessPointerComparator.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedFoundation/TemporaryCrcString.h" +#include "sharedGame/Quest.h" +#include "sharedUtility/FileName.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" + +#include +#include +#include +#include +#include + +// ====================================================================== + +namespace QuestManagerNamespace +{ + std::string const s_questListFileName("misc/quest_crc_string_table.iff"); + std::string const cs_summaryTablePrefix("datatables/questlist/"); + std::string const cs_taskTablePrefix("datatables/questtask/"); + + std::string const cs_unabandonableQuestFileName("datatables/quest/unabandonable_quests.iff"); + std::string const cs_unacceptableQuestFileName("datatables/quest/unaccepted_quests.iff"); + std::string const s_forceAcceptQuestsFileName("datatables/quest/force_accept_quests.iff"); + + typedef std::map QuestMap; + QuestMap s_quests; + + typedef std::map QuestNameMap; + QuestNameMap s_questNames; + + + std::set s_unabandonableQuests; + std::set s_unacceptableQuests; + std::set s_forceAcceptQuests; + + bool ms_installed = false; + bool ms_debugging = false; + + //currently turned off + int const cms_maximumNumberOfQuestsPerPlayer = -1; + +#ifdef _DEBUG + void regressionTest(); +#endif +} + +using namespace QuestManagerNamespace; + +// ====================================================================== + +void QuestManager::install() +{ + InstallTimer const installTimer("QuestManager::install"); + + DEBUG_FATAL(ms_installed, ("QuestManager::install: already installed")); + ms_installed = true; + + loadQuests(); + + //load up the list of unabandonable quests (ones that would break if players abandoned them at the wrong place, or quests that just haven't been tested with abandonment + s_unabandonableQuests.clear(); + Iff unabandonableQuestsTableIff; + if(unabandonableQuestsTableIff.open(cs_unabandonableQuestFileName.c_str(), true)) + { + DataTable unabandonableQuestsTable; + unabandonableQuestsTable.load(unabandonableQuestsTableIff); + int const rowCount = unabandonableQuestsTable.getNumRows(); + int const questNameColumn = unabandonableQuestsTable.findColumnNumber("NAME"); + for(int row = 0; row < rowCount; ++row) + { + s_unabandonableQuests.insert(unabandonableQuestsTable.getStringValue(questNameColumn, row)); + } + } + + //load up the list of unabandonable quests (ones that would break if players abandoned them at the wrong place, or quests that just haven't been tested with abandonment + s_unacceptableQuests.clear(); + Iff unacceptableQuestsTableIff; + if(unacceptableQuestsTableIff.open(cs_unacceptableQuestFileName.c_str(), true)) + { + DataTable unacceptableQuestsTable; + unacceptableQuestsTable.load(unacceptableQuestsTableIff); + int const rowCount = unacceptableQuestsTable.getNumRows(); + int const questNameColumn = unacceptableQuestsTable.findColumnNumber("NAME"); + for(int row = 0; row < rowCount; ++row) + { + s_unacceptableQuests.insert(unacceptableQuestsTable.getStringValue(questNameColumn, row)); + } + } + + //load up the list of unabandonable quests (ones that would break if players abandoned them at the wrong place, or quests that just haven't been tested with abandonment + s_forceAcceptQuests.clear(); + Iff forceAcceptQuestsTableIff; + if(forceAcceptQuestsTableIff.open(s_forceAcceptQuestsFileName.c_str(), true)) + { + DataTable forceAcceptQuestsTable; + forceAcceptQuestsTable.load(forceAcceptQuestsTableIff); + int const rowCount = forceAcceptQuestsTable.getNumRows(); + int const questNameColumn = forceAcceptQuestsTable.findColumnNumber("NAME"); + for(int row = 0; row < rowCount; ++row) + { + s_forceAcceptQuests.insert(forceAcceptQuestsTable.getStringValue(questNameColumn, row)); + //force accept quests are also unacceptable quests (so they don't show the completionUI) + s_unacceptableQuests.insert(forceAcceptQuestsTable.getStringValue(questNameColumn, row)); + } + } + + ExitChain::add(QuestManager::remove, "QuestManager::install"); +} + +// ---------------------------------------------------------------------- + +void QuestManager::loadQuests() +{ + CrcStringTable questList(s_questListFileName.c_str()); + + std::vector strings; + questList.getAllStrings(strings); + for (std::vector::const_iterator i=strings.begin(); i!=strings.end(); ++i) + { + std::string const & questName = *i; + s_questNames[Crc::calculate(questName.c_str())] = questName; + } + +#ifdef _DEBUG + { + InstallTimer const installTimer("QuestManager::install: quest validation"); + + for (int i = 0; i < questList.getNumberOfStrings(); ++i) + { + FileName const fileName("datatables/questlist", questList.getString(i).getString(), "iff"); + DEBUG_WARNING(!TreeFile::exists(fileName.getString()), ("Data tables for quest %s were not found", fileName.getString())); + } + + } + + regressionTest(); +#endif +} + +// ---------------------------------------------------------------------- + +void QuestManager::unloadQuests() +{ + std::for_each(s_quests.begin(), s_quests.end(), PointerDeleterPairSecond()); + s_quests.clear(); + s_questNames.clear(); +} + +// ---------------------------------------------------------------------- + +void QuestManager::reloadQuests() +{ + unloadQuests(); + loadQuests(); +} + +// ---------------------------------------------------------------------- + +void QuestManager::remove() +{ + unloadQuests(); + + s_unabandonableQuests.clear(); + s_unacceptableQuests.clear(); + s_forceAcceptQuests.clear(); + + DEBUG_FATAL(!ms_installed, ("QuestManager::remove: not installed")); + ms_installed = false; +} + +// ---------------------------------------------------------------------- + +Quest const * QuestManager::getQuest(CrcString const & fileName) +{ + Quest const * const quest = getQuest(fileName.getCrc()); + DEBUG_WARNING(quest == NULL, ("QuestManager::getQuest(%s): FAILED - testquest not found", fileName.getString())); + return quest; +} + +// ---------------------------------------------------------------------- + +Quest const * QuestManager::getQuest(uint32 const questCrc) +{ + Quest * quest = NULL; + + //-- Look for the quest in the quest map + QuestMap::iterator const iter = s_quests.find(questCrc); + if (iter != s_quests.end()) + quest = iter->second; + + if (!quest) + { + // -- Didn't find it in the map? Create it. + QuestNameMap::iterator const itQuestName = s_questNames.find(questCrc); + if (itQuestName != s_questNames.end()) + { + std::string const & questName = itQuestName->second; + + DataTableManager::reloadIfOpen(cs_summaryTablePrefix + questName + ".iff"); + DataTableManager::reloadIfOpen(cs_taskTablePrefix + questName + ".iff"); + + quest = new Quest(ConstCharCrcString(questName.c_str())); + s_quests[questCrc] = quest; + } + } + + DEBUG_WARNING(quest == NULL, ("QuestManager::getQuest: FAILED - testquest not found")); + + return quest; +} + +// ---------------------------------------------------------------------- + +Quest const * QuestManager::getQuest(std::string const & questName) +{ + TemporaryCrcString const fileName(questName.c_str(), true); + Quest const * const quest = getQuest(fileName); + DEBUG_WARNING(quest == NULL, ("QuestManager::getQuest(%s): FAILED - testquest not found", questName.c_str())); + return quest; +} + +// ---------------------------------------------------------------------- + +std::string QuestManager::getQuestName(uint32 const questCrc) +{ + Quest const * const q = getQuest(questCrc); + + if(!q) + return ""; + else + return q->getName().getString(); +} + +// ---------------------------------------------------------------------- + +void QuestManager::setDebugging(bool debugging) +{ + ms_debugging = debugging; +} + +// ---------------------------------------------------------------------- + +bool QuestManager::getDebugging() +{ + return ms_debugging; +} + +// ---------------------------------------------------------------------- + +bool QuestManager::isValidTaskId(int const taskId) +{ + return (taskId >= 0 && taskId < 16); +} + +// ---------------------------------------------------------------------- + +bool QuestManager::isQuestAbandonable(std::string const & questName) +{ + //can't abandon empty quest name + if(questName.empty()) + return false; + + //can't abandon a quest with a colon in it (used for quest:taskid) + if(questName.find(":") != questName.npos) + return false; + + return s_unabandonableQuests.find(questName) == s_unabandonableQuests.end(); +} + +// ---------------------------------------------------------------------- + +bool QuestManager::isQuestAcceptable(std::string const & questName) +{ + //can't accept and empty quest name + if(questName.empty()) + return false; + + //can't accept invalid quest names + Quest const * const q = getQuest(questName); + if(!q) + return false; + + //can't accept invisible quests + if(!q->isVisible()) + return false; + + //can't accept a quest with a colon in it (used for quest:taskid) + if(questName.find(":") != questName.npos) + return false; + + return s_unacceptableQuests.find(questName) == s_unacceptableQuests.end(); +} + +// ---------------------------------------------------------------------- + +bool QuestManager::isQuestForceAccepted(std::string const & questName) +{ + //can't force accept a quest with a colon in it (used for quest:taskid) + if(questName.find(":") != questName.npos) + return false; + + return s_forceAcceptQuests.find(questName) != s_forceAcceptQuests.end(); +} + +// ---------------------------------------------------------------------- + +int QuestManager::getMaximumNumberOfQuestsPerPlayer() +{ + return cms_maximumNumberOfQuestsPerPlayer; +} + +// ---------------------------------------------------------------------- + +#ifdef _DEBUG + +void QuestManagerNamespace::regressionTest() +{ + DEBUG_FATAL(QuestManager::getQuest("testquest") == 0, ("QuestManagerNamespace::regressionTest: FAILED - testquest not found")); +} + +#endif + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/quest/QuestManager.h b/engine/shared/library/sharedGame/src/shared/quest/QuestManager.h new file mode 100644 index 00000000..151ce234 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/quest/QuestManager.h @@ -0,0 +1,48 @@ +// ====================================================================== +// +// QuestManager.h +// copyright (c) 2004 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_QuestManager_H +#define INCLUDED_QuestManager_H + +// ====================================================================== + +class Quest; +class CrcString; + +// ====================================================================== + +/** +* Singleton for managing the list of quests +*/ +class QuestManager +{ +public: + static void install(); + static void reloadQuests(); + static void setDebugging(bool debugging); + static bool getDebugging(); + static bool isValidTaskId(int taskId); + static bool isQuestAbandonable(std::string const & questName); + static bool isQuestAcceptable(std::string const & questName); + static int getMaximumNumberOfQuestsPerPlayer(); + static bool isQuestForceAccepted(std::string const & questName); + +public: + static Quest const * getQuest(uint32 questCrc); + static Quest const * getQuest(std::string const & questName); + static Quest const * getQuest(CrcString const & fileName); + static std::string getQuestName(uint32 questCrc); + +private: + static void remove(); + static void loadQuests(); + static void unloadQuests(); +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/quest/QuestTask.cpp b/engine/shared/library/sharedGame/src/shared/quest/QuestTask.cpp new file mode 100644 index 00000000..6a6b9c3b --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/quest/QuestTask.cpp @@ -0,0 +1,322 @@ +// ====================================================================== +// +// QuestTask.cpp +// copyright (c) 2004 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/QuestTask.h" + +#include "sharedUtility/DataTable.h" +#include "sharedGame/Quest.h" + +// ====================================================================== + +namespace QuestTask_namespace +{ + std::string const cs_prerequisiteTasksColumn("PREREQUISITE_TASKS"); + std::string const cs_exclusionTasksColumn("EXCLUSION_TASKS"); + std::string const cs_attachScriptColumn("ATTACH_SCRIPT"); + std::string const cs_journalEntryTitleColumn("JOURNAL_ENTRY_TITLE"); + std::string const cs_journalEntryDescriptionColumn("JOURNAL_ENTRY_DESCRIPTION"); + std::string const cs_tasksOnCompleteColumn("TASKS_ON_COMPLETE"); + std::string const cs_tasksOnFailColumn("TASKS_ON_FAIL"); + std::string const cs_targetColumn("TARGET"); + std::string const cs_parameterColumn("PARAMETER"); + std::string const cs_visibleColumn("IS_VISIBLE"); + std::string const cs_showSystemMessagesColumn("SHOW_SYSTEM_MESSAGES"); + std::string const cs_allowRepeatsColumn("ALLOW_REPEATS"); + std::string const cs_musicOnActivateColumn("MUSIC_ON_ACTIVATE"); + std::string const cs_systemMessageOnActivateColumn("SYSTEM_MESSAGE_ON_ACTIVATE"); + std::string const cs_createWaypointColumn("CREATE_WAYPOINT"); + std::string const cs_planetNameColumn("PLANET_NAME"); + std::string const cs_locationXColumn("LOCATION_X"); + std::string const cs_locationYColumn("LOCATION_Y"); + std::string const cs_locationZColumn("LOCATION_Z"); + std::string const cs_waypointBuildingCellName("WAYPOINT_BUILDING_CELL_NAME"); + std::string const cs_entranceCreateWaypointColumn("CREATE_ENTRANCE_WAYPOINT"); + std::string const cs_entranceLocationXColumn("ENTRANCE_LOCATION_X"); + std::string const cs_entranceLocationYColumn("ENTRANCE_LOCATION_Y"); + std::string const cs_entranceLocationZColumn("ENTRANCE_LOCATION_Z"); + std::string const cs_chanceToActivate("CHANCE_TO_ACTIVATE"); + std::string const cs_questControlOnTaskCompletion("QUEST_CONTROL_ON_TASK_COMPLETION"); + std::string const cs_questControlOnTaskFailure("QUEST_CONTROL_ON_TASK_FAILURE"); + + std::vector * createIntVector(std::string const &source); +} + +using namespace QuestTask_namespace; + +// ====================================================================== + +QuestTask::QuestTask(Quest const & owner, DataTable const &sourceTable, int row) : + m_owner(owner), + m_id(row), + m_prerequisiteTasks(createIntVector(sourceTable.getStringValue(cs_prerequisiteTasksColumn, row))), + m_exclusionTasks(createIntVector(sourceTable.getStringValue(cs_exclusionTasksColumn, row))), + m_attachScript(sourceTable.getStringValue(cs_attachScriptColumn, row)), + m_journalEntryTitle(sourceTable.getStringValue(cs_journalEntryTitleColumn, row)), + m_journalEntryDescription(sourceTable.getStringValue(cs_journalEntryDescriptionColumn, row)), + m_tasksOnComplete(createIntVector(sourceTable.getStringValue(cs_tasksOnCompleteColumn, row))), + m_tasksOnFail(createIntVector(sourceTable.getStringValue(cs_tasksOnFailColumn, row))), + m_target(sourceTable.getStringValue(cs_targetColumn, row)), + m_parameter(sourceTable.getStringValue(cs_parameterColumn, row)), + m_visible(sourceTable.getIntValue(cs_visibleColumn, row) != 0), + m_showSystemMessages(sourceTable.getIntValue(cs_showSystemMessagesColumn, row) != 0), + m_allowRepeats(sourceTable.getIntValue(cs_allowRepeatsColumn, row) != 0), + m_musicOnActivate(), + m_systemMessageOnActivate(), + m_createWaypoint(false), + m_waypointPlanetName(), + m_waypointLocation(), + m_waypointBuildingCellName(), + m_isInteriorWaypoint(false), + m_entranceCreateWaypoint(false), + m_waypointEntranceLocation(), + m_chanceToActivate(0), + m_questControlOnTaskCompletion(QC_none), + m_questControlOnTaskFailure(QC_none) +{ + if(sourceTable.doesColumnExist(cs_musicOnActivateColumn)) + { + m_musicOnActivate = sourceTable.getStringValue(cs_musicOnActivateColumn, row); + } + if(sourceTable.doesColumnExist(cs_systemMessageOnActivateColumn)) + { + m_systemMessageOnActivate = StringId(sourceTable.getStringValue(cs_systemMessageOnActivateColumn, row)); + } + if(sourceTable.doesColumnExist(cs_createWaypointColumn)) + { + m_createWaypoint = sourceTable.getIntValue(cs_createWaypointColumn, row) != 0; + } + if(sourceTable.doesColumnExist(cs_planetNameColumn)) + { + m_waypointPlanetName = sourceTable.getStringValue(cs_planetNameColumn, row); + } + if(sourceTable.doesColumnExist(cs_locationXColumn) && sourceTable.doesColumnExist(cs_locationYColumn) && sourceTable.doesColumnExist(cs_locationZColumn)) + { + float const x = static_cast(atof(sourceTable.getStringValue(cs_locationXColumn, row))); + float const y = static_cast(atof(sourceTable.getStringValue(cs_locationYColumn, row))); + float const z = static_cast(atof(sourceTable.getStringValue(cs_locationZColumn, row))); + m_waypointLocation.set(x, y, z); + } + if(sourceTable.doesColumnExist(cs_waypointBuildingCellName)) + { + m_waypointBuildingCellName = sourceTable.getStringValue(cs_waypointBuildingCellName, row); + } + m_isInteriorWaypoint = !m_waypointBuildingCellName.empty(); + + if(sourceTable.doesColumnExist(cs_entranceCreateWaypointColumn)) + { + m_entranceCreateWaypoint = sourceTable.getIntValue(cs_entranceCreateWaypointColumn, row) != 0; + } + if(sourceTable.doesColumnExist(cs_entranceLocationXColumn) && sourceTable.doesColumnExist(cs_entranceLocationYColumn) && sourceTable.doesColumnExist(cs_entranceLocationZColumn)) + { + float const x = static_cast(atof(sourceTable.getStringValue(cs_entranceLocationXColumn, row))); + float const y = static_cast(atof(sourceTable.getStringValue(cs_entranceLocationYColumn, row))); + float const z = static_cast(atof(sourceTable.getStringValue(cs_entranceLocationZColumn, row))); + m_waypointEntranceLocation.set(x, y, z); + } + if (sourceTable.doesColumnExist(cs_chanceToActivate)) + { + m_chanceToActivate = sourceTable.getIntValue(cs_chanceToActivate, row); + } + if (sourceTable.doesColumnExist(cs_questControlOnTaskCompletion)) + { + m_questControlOnTaskCompletion = static_cast(sourceTable.getIntValue(cs_questControlOnTaskCompletion, row)); + } + if (sourceTable.doesColumnExist(cs_questControlOnTaskFailure)) + { + m_questControlOnTaskFailure = static_cast(sourceTable.getIntValue(cs_questControlOnTaskFailure, row)); + } +#if _DEBUG + // Test for bad waypoints. + if (m_isInteriorWaypoint) + { + // Is an interior waypoint set at 0.0f? + if (static_cast(m_waypointLocation.y) == 0) + { + // The designer is using cell space and not world space for this location. + DEBUG_REPORT_LOG(true, ("The waypoint for quest %s, task id %d, planet %s, location %4.2f, %4.2f, %4.2f is in an invalid location.\n", owner.getName().getString(), m_id, m_waypointPlanetName.c_str(), m_waypointLocation.x, m_waypointLocation.y, m_waypointLocation.z)); + } + } +#endif +} + +// ---------------------------------------------------------------------- + +QuestTask::~QuestTask() +{ + delete m_prerequisiteTasks; + delete m_exclusionTasks; + delete m_tasksOnComplete; + delete m_tasksOnFail; +} + +// ---------------------------------------------------------------------- + +bool QuestTask::isRepeatable() const +{ + return m_allowRepeats; +} + +// ---------------------------------------------------------------------- + +QuestTask::TaskIdList const & QuestTask::getPrerequisiteTasks() const +{ + return *m_prerequisiteTasks; +} + +// ---------------------------------------------------------------------- + +QuestTask::TaskIdList const & QuestTask::getExclusionTasks() const +{ + return *m_exclusionTasks; +} + +// ---------------------------------------------------------------------- + +QuestTask::TaskIdList const & QuestTask::getTasksOnComplete() const +{ + return *m_tasksOnComplete; +} + +// ---------------------------------------------------------------------- + +QuestTask::TaskIdList const & QuestTask::getTasksOnFail() const +{ + return *m_tasksOnFail; +} + +// ---------------------------------------------------------------------- + +int QuestTask::getId() const +{ + return m_id; +} + +// ---------------------------------------------------------------------- + +Quest const & QuestTask::getQuest() const +{ + return m_owner; +} + +// ---------------------------------------------------------------------- + +StringId const & QuestTask::getJournalEntryTitle() const +{ + return m_journalEntryTitle; +} + +// ---------------------------------------------------------------------- + +StringId const & QuestTask::getJournalEntryDescription() const +{ + return m_journalEntryDescription; +} + +// ---------------------------------------------------------------------- + +const std::string & QuestTask::getAttachScript() const +{ + return m_attachScript; +} + +// ---------------------------------------------------------------------- + +std::string const & QuestTask::getMusicOnActivate() const +{ + return m_musicOnActivate; +} + +// ---------------------------------------------------------------------- + +StringId const & QuestTask::getSystemMessageOnActivate() const +{ + return m_systemMessageOnActivate; +} + +// ---------------------------------------------------------------------- + +bool QuestTask::isVisible() const +{ + return m_visible; +} + +// ---------------------------------------------------------------------- + +Location QuestTask::getWaypointLocation() const +{ + int sceneCrc = Location::getCrcBySceneName(m_waypointPlanetName.c_str()); + return Location(m_waypointLocation, NetworkId::cms_invalid, sceneCrc); +} + +// ---------------------------------------------------------------------- + +Location QuestTask::getWaypointEntranceLocation() const +{ + int sceneCrc = Location::getCrcBySceneName(m_waypointPlanetName.c_str()); + return Location(m_waypointEntranceLocation, NetworkId::cms_invalid, sceneCrc); +} + +// ---------------------------------------------------------------------- + +int QuestTask::getChanceToActivate() const +{ + return m_chanceToActivate; +} + +// ---------------------------------------------------------------------- + +bool QuestTask::questCompletesOnTaskCompletion() const +{ + return m_questControlOnTaskCompletion == QC_complete; +} + +// ---------------------------------------------------------------------- + +bool QuestTask::questClearsOnTaskCompletion() const +{ + return m_questControlOnTaskCompletion == QC_clear; +} + +// ---------------------------------------------------------------------- + +bool QuestTask::questCompletesOnTaskFailure() const +{ + return m_questControlOnTaskFailure == QC_complete; +} + +// ---------------------------------------------------------------------- + +bool QuestTask::questClearsOnTaskFailure() const +{ + return m_questControlOnTaskFailure == QC_clear; +} + +// ====================================================================== + +/** + * Given a comma-separated list of numbers (in ASCII), allocate a new vector of those numbers + */ +std::vector * QuestTask_namespace::createIntVector(std::string const &source) +{ + std::vector * result = new std::vector; + + size_t pos = 0; + size_t commaPos = source.find(',', pos); + while (commaPos != std::string::npos) + { + result->push_back(atoi(source.c_str()+pos)); + pos = commaPos+1; + commaPos = source.find(',', pos); + } + if (pos < source.size()) + result->push_back(atoi(source.c_str()+pos)); + + return result; +} +// ====================================================================== + diff --git a/engine/shared/library/sharedGame/src/shared/quest/QuestTask.h b/engine/shared/library/sharedGame/src/shared/quest/QuestTask.h new file mode 100644 index 00000000..3fd3844f --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/quest/QuestTask.h @@ -0,0 +1,128 @@ +// ====================================================================== +// +// QuestTask.h +// copyright (c) 2004 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_QuestTask_H +#define INCLUDED_QuestTask_H + +// ====================================================================== + +#include "StringId.h" +#include "sharedUtility/Location.h" + +class DataTable; +class Quest; + +// ====================================================================== + +/** + * A subtask that is part of a quest + */ +class QuestTask +{ +public: + typedef stdvector::fwd TaskIdList; + + enum QuestControl + { + QC_none = 0, + QC_complete = 1, + QC_clear = 2 + }; + +public: + QuestTask(Quest const & owner, DataTable const &sourceTable, int row); + ~QuestTask(); + bool isRepeatable() const; + TaskIdList const & getPrerequisiteTasks() const; + TaskIdList const & getExclusionTasks() const; + TaskIdList const & getTasksOnComplete() const; + TaskIdList const & getTasksOnFail() const; + Quest const & getQuest() const; + StringId const & getJournalEntryTitle() const; + StringId const & getJournalEntryDescription() const; + const std::string & getAttachScript() const; + int getId() const; + std::string const & getMusicOnActivate() const; + StringId const & getSystemMessageOnActivate() const; + bool isVisible() const; + Location getWaypointLocation() const; + bool hasWaypoint() const; + bool hasEntranceWaypoint() const; + bool isInteriorWaypoint() const; + std::string const & getWaypointBuildingCellName() const; + Location getWaypointEntranceLocation() const; + int getChanceToActivate() const; + bool questCompletesOnTaskCompletion() const; + bool questClearsOnTaskCompletion() const; + bool questCompletesOnTaskFailure() const; + bool questClearsOnTaskFailure() const; + + private: + Quest const & m_owner; + int const m_id; + TaskIdList * const m_prerequisiteTasks; + TaskIdList * const m_exclusionTasks; + std::string const m_attachScript; + StringId const m_journalEntryTitle; + StringId const m_journalEntryDescription; + TaskIdList * const m_tasksOnComplete; + TaskIdList * const m_tasksOnFail; + std::string const m_target; + std::string const m_parameter; + bool const m_visible; + bool const m_showSystemMessages; + bool const m_allowRepeats; + std::string m_musicOnActivate; + StringId m_systemMessageOnActivate; + bool m_createWaypoint; + std::string m_waypointPlanetName; + Vector m_waypointLocation; + std::string m_waypointBuildingCellName; + bool m_isInteriorWaypoint; + bool m_entranceCreateWaypoint; + Vector m_waypointEntranceLocation; + int m_chanceToActivate; + QuestControl m_questControlOnTaskCompletion; + QuestControl m_questControlOnTaskFailure; + + private: + QuestTask(); + QuestTask(QuestTask const &); + QuestTask & operator=(QuestTask const &); +}; + +// ---------------------------------------------------------------------- + +inline bool QuestTask::hasWaypoint() const +{ + return m_createWaypoint; +} + +// ---------------------------------------------------------------------- + +inline bool QuestTask::hasEntranceWaypoint() const +{ + return m_entranceCreateWaypoint; +} + +// ---------------------------------------------------------------------- +inline bool QuestTask::isInteriorWaypoint() const +{ + return m_isInteriorWaypoint; +} + +// ---------------------------------------------------------------------- + +inline std::string const & QuestTask::getWaypointBuildingCellName() const +{ + return m_waypointBuildingCellName; +} + +// ====================================================================== + +#endif + diff --git a/engine/shared/library/sharedGame/src/shared/space/AsteroidGenerationManager.cpp b/engine/shared/library/sharedGame/src/shared/space/AsteroidGenerationManager.cpp new file mode 100644 index 00000000..26b912b2 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/AsteroidGenerationManager.cpp @@ -0,0 +1,572 @@ +//====================================================================== +// +// AsteroidGenerationManager.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/AsteroidGenerationManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/TreeFile.h" +#include "sharedFoundation/Crc.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedGame/ConfigSharedGame.h" +#include "sharedMath/SpatialSubdivision.h" +#include "sharedMath/WaveForm3D.h" +#include "sharedRandom/RandomGenerator.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" + +#include +#include +#include + +//====================================================================== + +std::map > AsteroidGenerationManager::ms_staticFieldData; +SphereTree AsteroidGenerationManager::ms_collisionSphereTree; +std::vector AsteroidGenerationManager::ms_objectsInSphereTree; +AsteroidGenerationManager::GetExtentRadiusFunction AsteroidGenerationManager::ms_getRadiusFunction; + +//====================================================================== + +namespace AsteroidGenerationManagerNamespace +{ + bool s_installed = false; + + const std::string s_baseDir ("datatables/space/asteroidfield/"); + const std::string s_filenameExt (".iff"); + + //this will be reseeded before use + RandomGenerator s_randomGenerator(0); +} + +using namespace AsteroidGenerationManagerNamespace; + +//====================================================================== + +Sphere const AsteroidGenerationManager::AsteroidDataSphereExtentAccessor::getExtent(Sphere const * const sphere) +{ + return *sphere; +} + +//------------------------------------------------------------------- + +char const *AsteroidGenerationManager::AsteroidDataSphereExtentAccessor::getDebugName(Sphere *) +{ + return 0; +} + +//====================================================================== + +void AsteroidGenerationManager::AsteroidData::clear() +{ + position.makeZero(); + orientation.makeZero(); + scale = 0.0f; + rotationVector.makeZero(); +} + +//====================================================================== + +void AsteroidGenerationManager::install() +{ + InstallTimer const installTimer("AsteroidGenerationManager::install"); + + DEBUG_FATAL(s_installed, ("AsteroidGenerationManager already installed")); + s_installed = true; + + ms_getRadiusFunction = NULL; + + ExitChain::add(AsteroidGenerationManager::remove, "AsteroidGenerationManager::remove"); +} + +//---------------------------------------------------------------------- + +void AsteroidGenerationManager::remove() +{ + ms_getRadiusFunction = NULL; + + clearStaticFieldData(); + clearInstantiatedData(); + + s_installed = false; +} + +//---------------------------------------------------------------------- + +void AsteroidGenerationManager::registerGetExtentRadiusFunction(AsteroidGenerationManager::GetExtentRadiusFunction getRadiusFunction) +{ + ms_getRadiusFunction = getRadiusFunction; +} + +//---------------------------------------------------------------------- + +/** Load up the asteroid data for a given planet. This does NOT create the actual field (client/server specific code must do this). +*/ +void AsteroidGenerationManager::loadStaticFieldDataForScene(std::string const & sceneName, bool server) +{ + if(!s_installed) + { + DEBUG_FATAL (true, ("AsteroidGenerationManager not installed")); + return; //lint !e527 unreachable (reachable in release) + } + + if (!AsteroidGenerationManager::hasDataForScene(sceneName)) + { + //-- skip non-space scenes + if (strncmp(sceneName.c_str(), "space_", 6)) + return; + + std::string tableName = s_baseDir + sceneName + s_filenameExt; + if(!TreeFile::exists(tableName.c_str())) + { + DEBUG_WARNING(true, ("Static asteroid field data not defined for %s", sceneName.c_str())); + return; + } + + std::set seeds; + + DataTable* table = DataTableManager::getTable(tableName, true); + if(table) + { + const int numRows = table->getNumRows (); + + for (int i = 0; i < numRows; ++i) + { + AsteroidFieldData newData; + + newData.templateCrcsAndLikelihood.clear(); + + switch (table->getIntValue("Type", i)) + { + case 1: + newData.fieldType = AsteroidFieldData::FT_cube; + break; + case 2: + newData.fieldType = AsteroidFieldData::FT_spline; + break; + default: + DEBUG_FATAL(true, ("Row %i in asteroid field table for %s specifies invalid field type %i", i, sceneName.c_str(), table->getIntValue("Type", i))); + } + newData.centerPosition.x = table->getFloatValue("CenterLocationX", i); + newData.centerPosition.y = table->getFloatValue("CenterLocationY", i); + newData.centerPosition.z = table->getFloatValue("CenterLocationZ", i); + newData.radius = table->getFloatValue("Radius", i); + newData.flattenDepth = table->getFloatValue("FlattenDepth", i); + newData.count = table->getIntValue("NumAsteroids", i); + newData.seed = static_cast(table->getIntValue("RandomSeed", i)); + newData.scaleMin = table->getFloatValue("ScaleMin", i); + newData.scaleMax = table->getFloatValue("ScaleMax", i); + newData.rotationMin = table->getFloatValue("RotationMin", i); + newData.rotationMax = table->getFloatValue("RotationMax", i); + std::string const & fieldStyleTableName = table->getStringValue("FieldStyleTable", i); + std::string const & radialStyleTableName = table->getStringValue("RadialStyleTable", i); + newData.radialCount = table->getIntValue("NumRadialAsteroids", i); + newData.radialLikelihoodSum = 0; + newData.maxViewableDistance = table->getFloatValue("MaxViewableDistance", i); + newData.viewAllDistance = table->getFloatValue("ViewAllDistance", i); + newData.soundEffect = table->getStringValue("SoundEffect", i); + + // read spline control points + newData.splineControlPoints.clear(); + if (newData.fieldType == AsteroidFieldData::FT_spline) + { + std::string pointsAsString(table->getStringValue("SplineControlPoints", i)); + pointsAsString += ":"; + size_t pos = 0; + bool done=false; + while (!done) + { + size_t nextColon = pointsAsString.find(':',pos); + if (nextColon != static_cast(std::string::npos)) + { + Vector onePoint; + std::string const onePointAsString(pointsAsString,pos,nextColon-pos); + sscanf(onePointAsString.c_str(),"%f,%f,%f", &onePoint.x, &onePoint.y, &onePoint.z); + newData.splineControlPoints.push_back(onePoint); + pos = nextColon+1; + } + else + done = true; + } + + DEBUG_FATAL(newData.splineControlPoints.size() < 2,("Row %i in asteroid file table for %s specified < 2 spline control points. At least 2 are required.", i, sceneName.c_str())); + + std::string const facingAsString(table->getStringValue("FaceTowards",i)); + sscanf(facingAsString.c_str(),"%f,%f,%f", &newData.faceTowards.x, &newData.faceTowards.y, &newData.faceTowards.z); + } + + if(seeds.find(newData.seed) != seeds.end()) + { + DEBUG_FATAL(true, ("Each static asteroid field must have a seed unique to the scene, seed [%d] seed > once for %s", newData.seed, sceneName.c_str())); + continue; //lint !e527 unreachable (reachable in release) + } + IGNORE_RETURN(seeds.insert(newData.seed)); + + if(!TreeFile::exists(fieldStyleTableName.c_str())) + { + DEBUG_WARNING(true, ("Could not find asteroid field style table %s", fieldStyleTableName.c_str())); + continue; //lint !e527 unreachable (reachable in release) + } + + //now read the rest of the data from the field style table + + DataTable* fieldStyleTable = DataTableManager::getTable(fieldStyleTableName, true); + if(fieldStyleTable) + { + const int fieldStyleNumRows = fieldStyleTable->getNumRows (); + uint32 crc = Crc::crcNull; + float likelihood = 0.0f; + for (int j = 0; j < fieldStyleNumRows; ++j) + { + if(server) + crc = Crc::calculate(fieldStyleTable->getStringValue("ServerTemplate", j)); + else + crc = Crc::calculate(fieldStyleTable->getStringValue("SharedTemplate", j)); + likelihood = fieldStyleTable->getFloatValue("Likelihood", j); + if(likelihood <= 0.0f) + { + continue; + } + newData.templateCrcsAndLikelihood.push_back(std::make_pair(crc, likelihood)); + } + } + + //read the radial data from the radial style table + + if (!server) + { + DataTable* radialStyleTable = DataTableManager::getTable(radialStyleTableName, true); + if(radialStyleTable) + { + const int radialStyleNumRows = radialStyleTable->getNumRows (); + //uint32 crc = Crc::crcNull; + //float likelihood = 0.0f; + for (int j = 0; j < radialStyleNumRows; ++j) + { + RadialAsteroidData rad; + rad.appearance = radialStyleTable->getStringValue("Appearance", j); + rad.likelihood = radialStyleTable->getFloatValue ("Likelihood", j); + rad.scaleMin = radialStyleTable->getFloatValue ("ScaleMin", j); + rad.scaleMax = radialStyleTable->getFloatValue ("ScaleMax", j); + rad.spawnRange = radialStyleTable->getFloatValue ("SpawnRange", j); + rad.deleteRange = radialStyleTable->getFloatValue ("DeleteRange", j); + rad.hitEffectName = radialStyleTable->getStringValue ("HitEffect", j); + + newData.radialLikelihoodSum += rad.likelihood; + + newData.radialData.push_back(rad); + } + } + } + + ms_staticFieldData[sceneName].push_back(newData); + } + } + } +} + +//---------------------------------------------------------------------- + +void AsteroidGenerationManager::clearStaticFieldData() +{ + typedef std::map > StaticFieldData; + + StaticFieldData::iterator ii = ms_staticFieldData.begin(); + StaticFieldData::iterator iiEnd = ms_staticFieldData.end(); + + for (; ii != iiEnd; ++ii) + { + ii->second.clear(); + } +} + +//---------------------------------------------------------------------- + +void AsteroidGenerationManager::clearInstantiatedData() +{ + if(!s_installed) + { + DEBUG_FATAL (true, ("AsteroidGenerationManager not installed")); + return; //lint !e527 unreachable (reachable in release) + } + + SpatialSubdivisionHandle* handle; + + std::vector > spheres; + ms_collisionSphereTree.dumpSphereTreeObjs (spheres); + for(std::vector >::iterator i = spheres.begin(); i != spheres.end(); ++i) + { + delete i->first; + } + + for(std::vector::iterator i2 = ms_objectsInSphereTree.begin(); i2 != ms_objectsInSphereTree.end(); ++i2) + { + handle = *i2; + if(handle) + { + ms_collisionSphereTree.removeObject(handle); + } + } + ms_objectsInSphereTree.clear(); +} + +//---------------------------------------------------------------------- + +/** Get the static asteroid field data for the current planet +*/ +std::vector const & AsteroidGenerationManager::getDataForScene(std::string const & sceneName) +{ + return ms_staticFieldData[sceneName]; +} + +//---------------------------------------------------------------------- + +bool AsteroidGenerationManager::hasDataForScene(std::string const & sceneName) +{ + typedef std::map > StaticFieldData; + + StaticFieldData::const_iterator ii = ms_staticFieldData.find(sceneName); + return ii != ms_staticFieldData.end(); +} + +//---------------------------------------------------------------------- + +/** Generate the DATA (NOT the objects) for a asteroid field given seed data. + The same seed data will always generate the same asteroid field. + The field will have randomly even distribution of position, orientation, rotation range, scale range, and template selection based on the ratios given in the fields style table +*/ +bool AsteroidGenerationManager::generateField(AsteroidFieldData const & fieldData, stdvector::fwd & result) +{ + if(!s_installed) + { + DEBUG_FATAL (true, ("AsteroidGenerationManager not installed")); + return false; //lint !e527 unreachable (reachable in release) + } + + if(fieldData.rotationMin > fieldData.rotationMax) + { + DEBUG_FATAL(true, ("AsteroidGenerationManager::generateField rotationMin > rotationMax")); + return false; //lint !e527 unreachable (reachable in release) + } + + if(fieldData.scaleMin > fieldData.scaleMax) + { + DEBUG_FATAL(true, ("AsteroidGenerationManager::generateField scaleMin > scaleMax")); + return false; //lint !e527 unreachable (reachable in release) + } + + clearInstantiatedData(); + + std::vector > templateCrcsAndLikelihoodWeighted; + + float sum = 0.0f; + { + for(std::vector >::const_iterator i = fieldData.templateCrcsAndLikelihood.begin(); i != fieldData.templateCrcsAndLikelihood.end(); ++i) + { + sum += i->second; + } + } + if(sum <= 0.0f) + sum = 1.0f; + + for(std::vector >::const_iterator it = fieldData.templateCrcsAndLikelihood.begin(); it != fieldData.templateCrcsAndLikelihood.end(); ++it) + { + templateCrcsAndLikelihoodWeighted.push_back(std::make_pair(it->first, it->second / sum)); + } + + s_randomGenerator.setSeed(fieldData.seed); + + WaveForm3D * splineWaveform = NULL; + if (fieldData.fieldType == AsteroidFieldData::FT_spline) + { + splineWaveform = new WaveForm3D; + + size_t numPoints = fieldData.splineControlPoints.size(); + size_t count = 0; + for (std::vector::const_iterator i = fieldData.splineControlPoints.begin(); i!=fieldData.splineControlPoints.end(); ++i) + { + splineWaveform->insert(static_cast(count) / static_cast(numPoints - 1), *i); + ++count; + } + } + + result.clear(); + + AsteroidData newAsteroid; + + for(int i2 = 0; i2 < fieldData.count; ++i2) + { + bool valid = false; + std::vector collisionResult; + Sphere * s = NULL; + while(!valid) + { + //create asteroid locations until we find one that doesn't penetrate any existing objects + collisionResult.clear(); + switch (fieldData.fieldType) + { + case AsteroidFieldData::FT_cube: + newAsteroid = generateAsteroidDataCube(fieldData.centerPosition, fieldData.radius, fieldData.scaleMin, fieldData.scaleMax, fieldData.rotationMin, fieldData.rotationMax, templateCrcsAndLikelihoodWeighted); + break; + + case AsteroidFieldData::FT_spline: + newAsteroid = generateAsteroidDataSpline(*NON_NULL(splineWaveform), fieldData.radius, fieldData.flattenDepth, fieldData.faceTowards,fieldData.scaleMin, fieldData.scaleMax, fieldData.rotationMin, fieldData.rotationMax, templateCrcsAndLikelihoodWeighted); + break; + } + + s = new Sphere; + s->setCenter(newAsteroid.position); + s->setRadius(1.0f); + + if(ms_getRadiusFunction) + { + typedef std::map RadiusMapType; + static RadiusMapType radiusMap; + RadiusMapType::const_iterator i=radiusMap.find(newAsteroid.templateCrc); + if (i==radiusMap.end()) + i=radiusMap.insert(std::make_pair(newAsteroid.templateCrc,ms_getRadiusFunction(newAsteroid.templateCrc))).first; + + s->setRadius(i->second * newAsteroid.scale); + } + + ms_collisionSphereTree.findInRange (newAsteroid.position, s->getRadius(), collisionResult); + if(collisionResult.empty()) + { + DEBUG_REPORT_LOG_PRINT(ConfigSharedGame::getSpamAsteroidGenerationData(), ("Added Asteroid at [%f, %f, %f], radius [%f].\n", newAsteroid.position.x, newAsteroid.position.y, newAsteroid.position.z, s->getRadius())); + valid = true; + } + else + { + DEBUG_REPORT_LOG_PRINT(ConfigSharedGame::getSpamAsteroidGenerationData(), ("Asteroid creation collision at [%f, %f, %f], radius [%f], trying again...\n", newAsteroid.position.x, newAsteroid.position.y, newAsteroid.position.z, s->getRadius())); + delete s; + s = NULL; + } + } + + NOT_NULL(s); //lint !e644 // s could be uninitialized (not true -- initialized to NULL above, should be set to a value during the while loop) + + SpatialSubdivisionHandle* handle = ms_collisionSphereTree.addObject(s); + if(handle) + ms_objectsInSphereTree.push_back(handle); + + result.push_back(newAsteroid); + } //lint !e429 // not leaking s because it is stored in the sphere tree + + delete splineWaveform; + + return true; +} + +//---------------------------------------------------------------------- + +AsteroidGenerationManager::AsteroidData AsteroidGenerationManager::generateAsteroidDataCube(Vector const & centerPosition, float radius, float scaleMin, float scaleMax, float rotationMin, float rotationMax, std::vector > templateCrcsAndLikelihoodWeighted) +{ + float randomNum = 0.0f; + float sum = 0.0f; + AsteroidData newAsteroid; + + //position + randomNum = s_randomGenerator.randomReal(-1.0f, 1.0f); + newAsteroid.position.x = centerPosition.x + (radius * randomNum); + randomNum = s_randomGenerator.randomReal(-1.0f, 1.0f); + newAsteroid.position.y = centerPosition.y + (radius * randomNum); + randomNum = s_randomGenerator.randomReal(-1.0f, 1.0f); + newAsteroid.position.z = centerPosition.z + (radius * randomNum); + + //orientation + newAsteroid.orientation.set(s_randomGenerator.randomReal(0.0f, PI_TIMES_2), s_randomGenerator.randomReal(0.0f, PI_TIMES_2), s_randomGenerator.randomReal(0.0f, PI_TIMES_2)); + + //rotation speed + newAsteroid.rotationVector.set(s_randomGenerator.randomReal(rotationMin, rotationMax), s_randomGenerator.randomReal(rotationMin, rotationMax), s_randomGenerator.randomReal(rotationMin, rotationMax)); + + //scale + newAsteroid.scale = s_randomGenerator.randomReal(scaleMin, scaleMax); + + //template selection + randomNum = s_randomGenerator.randomReal(); + std::vector >::const_iterator it = templateCrcsAndLikelihoodWeighted.begin(); + sum = it->second; + while(sum < randomNum && it != templateCrcsAndLikelihoodWeighted.end()) + { + ++it; + sum += it->second; + } + + newAsteroid.templateCrc = it->first; + + return newAsteroid; +} + +//---------------------------------------------------------------------- + +AsteroidGenerationManager::AsteroidData AsteroidGenerationManager::generateAsteroidDataSpline(WaveForm3D & waveform, float radius, float flattenDepth, Vector const & faceTowards, float scaleMin, float scaleMax, float rotationMin, float rotationMax, std::vector > templateCrcsAndLikelihoodWeighted) +{ + float sum = 0.0f; + float const t = s_randomGenerator.randomReal(0.0f,1.0f); + float const tForPoint2 = (t<0.9f) ? t + 0.1f : t - 0.1f; + Vector wavePoint; + waveform.getValue(t,wavePoint,true); + Vector wavePoint2; // another point along the spine, to figure out which direction the spline is going + waveform.getValue(tForPoint2,wavePoint2,true); + Vector alongSpline = wavePoint2 - wavePoint; + + AsteroidData newAsteroid; + + //position + if (flattenDepth >= 0.0f) + { + // ribbon-shaped field. Cross-section is a rectangle + Vector planeX = wavePoint - faceTowards; // flat direction of the plane, which points towards the "faceTowards" point + if (!planeX.normalize()) + FATAL(true,("Data bug: Asteroid field specified facing towards point (%f,%f,%f), which is in (or very close to) the field itself.",faceTowards.x,faceTowards.y,faceTowards.z)); + Vector planeY = planeX.cross(alongSpline); // wide direction of the plane + IGNORE_RETURN(planeY.normalize()); + planeX *= s_randomGenerator.randomReal(-flattenDepth, flattenDepth); + planeY *= s_randomGenerator.randomReal(-radius, radius); + + newAsteroid.position = wavePoint + planeX + planeY; + + } + else + { + // standard field. Cross-section is a square + Vector planeX = Vector::perpendicular(alongSpline); + Vector planeY = planeX.cross(alongSpline); + IGNORE_RETURN(planeX.normalize()); + IGNORE_RETURN(planeY.normalize()); + planeX *= s_randomGenerator.randomReal(-radius, radius); + planeY *= s_randomGenerator.randomReal(-radius, radius); + + newAsteroid.position = wavePoint + planeX + planeY; + } + + //orientation + newAsteroid.orientation.set(s_randomGenerator.randomReal(0.0f, PI_TIMES_2), s_randomGenerator.randomReal(0.0f, PI_TIMES_2), s_randomGenerator.randomReal(0.0f, PI_TIMES_2)); + + //rotation speed + newAsteroid.rotationVector.set(s_randomGenerator.randomReal(rotationMin, rotationMax), s_randomGenerator.randomReal(rotationMin, rotationMax), s_randomGenerator.randomReal(rotationMin, rotationMax)); + + //scale + newAsteroid.scale = s_randomGenerator.randomReal(scaleMin, scaleMax); + + //template selection + float const randomNum = s_randomGenerator.randomReal(); + std::vector >::const_iterator it = templateCrcsAndLikelihoodWeighted.begin(); + sum = it->second; + while(sum < randomNum && it != templateCrcsAndLikelihoodWeighted.end()) + { + ++it; + sum += it->second; + } + + newAsteroid.templateCrc = it->first; + + return newAsteroid; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/AsteroidGenerationManager.h b/engine/shared/library/sharedGame/src/shared/space/AsteroidGenerationManager.h new file mode 100644 index 00000000..a299e1c2 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/AsteroidGenerationManager.h @@ -0,0 +1,116 @@ +//====================================================================== +// +// AsteroidGenerationManager.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_AsteroidGenerationManager_H +#define INCLUDED_AsteroidGenerationManager_H + +//====================================================================== + +#include "sharedMath/SphereTree.h" +#include "sharedMath/Vector.h" +#include + +//====================================================================== + +class SpatialSubdivisionHandle; +class Sphere; +class WaveForm3D; + +//====================================================================== + +class AsteroidGenerationManager +{ +public: + struct AsteroidData + { + Vector position; + Vector orientation; + uint32 templateCrc; + float scale; + Vector rotationVector; + + void clear(); + }; + + struct RadialAsteroidData + { + std::string appearance; + float likelihood; + float scaleMin; + float scaleMax; + float spawnRange; + float deleteRange; + std::string hitEffectName; + }; + + struct AsteroidFieldData + { + enum FieldType {FT_cube, FT_spline}; + + FieldType fieldType; + Vector centerPosition; + float radius; + std::vector splineControlPoints; + int count; + uint32 seed; + float flattenDepth; + Vector faceTowards; + float scaleMin; + float scaleMax; + float rotationMin; + float rotationMax; + std::vector > templateCrcsAndLikelihood; + std::vector radialData; + int radialCount; + float radialLikelihoodSum; + float maxViewableDistance; + float viewAllDistance; + std::string soundEffect; + }; + + typedef float (*GetExtentRadiusFunction)(uint32 crc); + +public: + static void install(); + static bool generateField(AsteroidFieldData const & fieldData, stdvector::fwd & result); + static bool generateField(Vector const & centerPosition, float radius, int count, uint32 seed, float scaleMin, float scaleMax, float rotationMin, float rotationMax, stdvector >::fwd const & templateCrcsAndLikelihood, stdvector::fwd & asteroidDatas); + static void loadStaticFieldDataForScene(std::string const & sceneName, bool server); + static void clearStaticFieldData(); + static void clearInstantiatedData(); + static bool hasDataForScene(std::string const & sceneName); + static stdvector::fwd const & getDataForScene(std::string const & sceneName); + static void registerGetExtentRadiusFunction(GetExtentRadiusFunction); + +private: + class AsteroidDataSphereExtentAccessor: public BaseSphereTreeAccessor + { + public: + static Sphere const getExtent(Sphere const * const sphere); + static char const *getDebugName(Sphere * sphere); + }; + + static void remove(); + static AsteroidData generateAsteroidDataCube(Vector const & centerPosition, float radius, float scaleMin, float scaleMax, float rotationMin, float rotationMax, std::vector > templateCrcsAndLikelihoodWeighted); + static AsteroidData generateAsteroidDataSpline(WaveForm3D & waveform, float radius, float flattenDepth, Vector const & faceTowards, float scaleMin, float scaleMax, float rotationMin, float rotationMax, std::vector > templateCrcsAndLikelihoodWeighted); + +private: + typedef std::string SceneNameKey; + static stdmap::fwd>::fwd ms_staticFieldData; + static SphereTree ms_collisionSphereTree; + static std::vector ms_objectsInSphereTree; + static GetExtentRadiusFunction ms_getRadiusFunction; + + //disabled + AsteroidGenerationManager(); + ~AsteroidGenerationManager(); + AsteroidGenerationManager(AsteroidGenerationManager const &); + AsteroidGenerationManager &operator =(AsteroidGenerationManager const &); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/Nebula.cpp b/engine/shared/library/sharedGame/src/shared/space/Nebula.cpp new file mode 100644 index 00000000..beab18e1 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/Nebula.cpp @@ -0,0 +1,184 @@ +//====================================================================== +// +// Nebula.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/Nebula.h" + +#include "sharedMath/Vector.h" + +//====================================================================== + +int const Nebula::ms_numStyleWeightings = 16; + +//---------------------------------------------------------------------- + +Nebula::Nebula(int id, std::string const & name) : +m_id(id), +m_name(name), +m_sphere(), +m_density(1.0f), +m_colorFacing(), +m_colorOriented(), +m_colorRampFacing(), +m_colorRampOriented(), +m_facingPercent(0.0f), +m_ambientSound(), +m_ambientSoundVolume(1.0f), +m_effectReactor(0.0f), +m_effectEngine(0.0f), +m_effectShields(0.0f), +m_lightningFrequency(0.0f), +m_lightningDamageMin(0.0f), +m_lightningDamageMax(0.0f), +m_lightningDurationMax(0.0f), +m_lightningAppearance(), +m_lightningColor(), +m_lightningColorRamp(), +m_lightningSound(), +m_lightningSoundLoop(), +m_lightningClientEffectHitClient(), +m_lightningClientEffectHitServer(), +m_environmentalDamageFrequency(0.0f), +m_environmentalDamage(0.0f), +m_environmentalDamageClientEffect(), +m_cameraJitterAngle(0.0f), +m_shaderIndex(0), +m_spatialSubdivisionHandle(0) +{ +} + +//---------------------------------------------------------------------- + +Nebula::~Nebula() +{ +} + +//---------------------------------------------------------------------- + +void Nebula::setColor(VectorArgb const & colorFacing, VectorArgb const & colorRampFacing, VectorArgb const & colorOriented, VectorArgb const & colorRampOriented) +{ + m_colorFacing = colorFacing; + m_colorOriented = colorOriented; + m_colorRampFacing = colorRampFacing; + m_colorRampOriented = colorRampOriented; +} + +//---------------------------------------------------------------------- + +void Nebula::setExtent(Vector const & pos_w, float const radius) +{ + m_sphere.set(pos_w, radius); +} + +//---------------------------------------------------------------------- + +void Nebula::setShipEffects(float const effectReactor, float const effectEngine, float const effectShields) +{ + m_effectReactor = effectReactor; + m_effectEngine = effectEngine; + m_effectShields = effectShields; +} + +//---------------------------------------------------------------------- + +void Nebula::setLightningEffects(float const lightningFrequency, float const lightningDurationMax, std::string const & lightningAppearance, VectorArgb const & lightningColor, VectorArgb const & lightningColorRamp, std::string const & lightningSound, std::string const & lightningSoundLoop, std::string const & lightningClientEffectHitClient, std::string const & lightningClientEffectHitServer) +{ + m_lightningFrequency = lightningFrequency; + m_lightningDurationMax = lightningDurationMax; + m_lightningAppearance = lightningAppearance; + + m_lightningColor = lightningColor; + m_lightningColorRamp = lightningColorRamp; + + m_lightningSound = lightningSound; + m_lightningSoundLoop = lightningSoundLoop; + m_lightningClientEffectHitClient = lightningClientEffectHitClient; + m_lightningClientEffectHitServer = lightningClientEffectHitServer; +} + +//---------------------------------------------------------------------- + +void Nebula::setEnvironmentalDamage(float const environmentalDamageFrequency, float const environmentalDamage, std::string const & environmentalDamageClientEffect) +{ + m_environmentalDamageFrequency = environmentalDamageFrequency; + m_environmentalDamage = environmentalDamage; + m_environmentalDamageClientEffect = environmentalDamageClientEffect; +} + +//---------------------------------------------------------------------- + +void Nebula::setDensity(float const density) +{ + m_density = density; +} + +//---------------------------------------------------------------------- + +void Nebula::setAmbientSound(std::string const & ambientSound, float ambientSoundVolume) +{ + m_ambientSound = ambientSound; + m_ambientSoundVolume = ambientSoundVolume; +} + +//---------------------------------------------------------------------- + +void Nebula::setCameraJitterAngle(float const cameraJitterAngle) +{ + m_cameraJitterAngle = cameraJitterAngle; +} + +//---------------------------------------------------------------------- + +void Nebula::setLightningDamage(float const lightningDamageMin, float const lightningDamageMax) +{ + m_lightningDamageMin = lightningDamageMin; + m_lightningDamageMax = lightningDamageMax; +} + +//---------------------------------------------------------------------- + +int Nebula::getShaderIndex() const +{ + return m_shaderIndex; +} + +//---------------------------------------------------------------------- + +void Nebula::setShaderInfo(int shaderIndex, float const * styleWeightings, float facingPercent) +{ + m_shaderIndex = shaderIndex; + for (int i = 0; i < ms_numStyleWeightings; ++i) + { + m_styleWeightings[i] = styleWeightings[i]; + } + + m_facingPercent = facingPercent; + +} + +//---------------------------------------------------------------------- + +std::string const & Nebula::getName() const +{ + return m_name; +} + +//---------------------------------------------------------------------- + +SpatialSubdivisionHandle * Nebula::getSpatialSubdivisionHandle() const +{ + return m_spatialSubdivisionHandle; +} + +//---------------------------------------------------------------------- + +void Nebula::setSpatialSubdivisionHandle (SpatialSubdivisionHandle * const spatialSubdivisionHandle) const +{ + m_spatialSubdivisionHandle = spatialSubdivisionHandle; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/Nebula.h b/engine/shared/library/sharedGame/src/shared/space/Nebula.h new file mode 100644 index 00000000..5f2e074f --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/Nebula.h @@ -0,0 +1,341 @@ +//====================================================================== +// +// Nebula.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_Nebula_H +#define INCLUDED_Nebula_H + +//====================================================================== + +#include "sharedMath/Sphere.h" +#include "sharedMath/VectorArgb.h" + +class SpatialSubdivisionHandle; +class Vector; + +//---------------------------------------------------------------------- + +class Nebula +{ +public: + + static int const ms_numStyleWeightings; + +public: + + Nebula(int id, std::string const & name); + ~Nebula(); + + void setColor(VectorArgb const & colorFacing, VectorArgb const & colorRampFacing, VectorArgb const & colorOriented, VectorArgb const & colorRampOriented); + void setExtent(Vector const & pos_w, float radius); + void setDensity(float density); + void setShipEffects(float effectReactor, float effectEngine, float effectShields); + void setLightningEffects(float lightningFrequency, float lightningDurationMax, std::string const & lightningAppearance, VectorArgb const & colorLightning, VectorArgb const & colorRampLightning, std::string const & lightningSound, std::string const & lightningSoundLoop, std::string const & lightningClientEffectHitClient, std::string const & lightningClientEffectHitServer); + void setLightningDamage(float lightningDamageMin, float lightningDamageMax); + void setEnvironmentalDamage(float environmentalDamageFrequency, float environmentalDamage, std::string const & environmentalDamageClientEffect); + void setAmbientSound(std::string const & ambientSound, float ambientSoundVolume); + void setCameraJitterAngle(float cameraJitterAngle); + void setShaderInfo(int shaderIndex, float const * styleWeightings, float facingPercent); + + Sphere const & getSphere() const; + float getDensity() const; + VectorArgb const & getColor() const; + VectorArgb const & getColorFacing() const; + VectorArgb const & getColorOriented() const; + VectorArgb const & getColorRampFacing() const; + VectorArgb const & getColorRampOriented() const; + float getFacingPercent() const; + int getId() const; + std::string const & getAmbientSound() const; + float getAmbientSoundVolume() const; + std::string const & getLightningAppearance() const; + VectorArgb const & getLightningColor() const; + VectorArgb const & getLightningColorRamp() const; + std::string const & getLightningSound() const; + std::string const & getLightningSoundLoop() const; + std::string const & getLightningClientEffectHitClient() const; + std::string const & getLightningClientEffectHitServer() const; + float getLightningFrequency() const; + float getLightningDamageMin() const; + float getLightningDamageMax() const; + float getLightningDurationMax() const; + float getEffectEngine() const; + float getEffectReactor() const; + float getEffectShields() const; + float getCameraJitterAngle() const; + float getEnvironmentalDamageFrequency() const; + float getEnvironmentalDamage() const; + std::string const & getEnvironmentalDamageClientEffect() const; + int getShaderIndex() const; + std::string const & getName() const; + + SpatialSubdivisionHandle * getSpatialSubdivisionHandle() const; + void setSpatialSubdivisionHandle(SpatialSubdivisionHandle * spatialSubdivisionHandle) const; + +private: + + Nebula & operator=(Nebula const & rhs); + Nebula(Nebula const & rhs); + +private: + + int m_id; + std::string m_name; + Sphere m_sphere; + float m_density; + VectorArgb m_colorFacing; + VectorArgb m_colorOriented; + VectorArgb m_colorRampFacing; + VectorArgb m_colorRampOriented; + float m_facingPercent; + std::string m_ambientSound; + float m_ambientSoundVolume; + + float m_effectReactor; + float m_effectEngine; + float m_effectShields; + + float m_lightningFrequency; + float m_lightningDamageMin; + float m_lightningDamageMax; + + float m_lightningDurationMax; + + std::string m_lightningAppearance; + + VectorArgb m_lightningColor; + VectorArgb m_lightningColorRamp; + + std::string m_lightningSound; + std::string m_lightningSoundLoop; + std::string m_lightningClientEffectHitClient; + std::string m_lightningClientEffectHitServer; + + float m_environmentalDamageFrequency; + float m_environmentalDamage; + + std::string m_environmentalDamageClientEffect; + + float m_cameraJitterAngle; + int m_shaderIndex; + + float m_styleWeightings[16]; + + mutable SpatialSubdivisionHandle * m_spatialSubdivisionHandle; + + // light + // fog params + // flashes + // shifting clouds + // etc... +}; + +//---------------------------------------------------------------------- + +inline int Nebula::getId() const +{ + return m_id; +} + +//---------------------------------------------------------------------- + +inline Sphere const & Nebula::getSphere() const +{ + return m_sphere; +} + +//---------------------------------------------------------------------- + +inline VectorArgb const & Nebula::getColor() const +{ + return m_colorFacing; +} + +//---------------------------------------------------------------------- + +inline std::string const & Nebula::getAmbientSound() const +{ + return m_ambientSound; +} + +//---------------------------------------------------------------------- + +inline float Nebula::getAmbientSoundVolume() const +{ + return m_ambientSoundVolume; +} + +//---------------------------------------------------------------------- + +inline std::string const & Nebula::getLightningAppearance() const +{ + return m_lightningAppearance; +} + +//---------------------------------------------------------------------- + +inline float Nebula::getLightningFrequency() const +{ + return m_lightningFrequency; +} + +//---------------------------------------------------------------------- + +inline std::string const & Nebula::getLightningSound() const +{ + return m_lightningSound; +} + +//---------------------------------------------------------------------- + +inline std::string const & Nebula::getLightningSoundLoop() const +{ + return m_lightningSoundLoop; +} + +//---------------------------------------------------------------------- + +inline std::string const & Nebula::getLightningClientEffectHitClient() const +{ + return m_lightningClientEffectHitClient; +} + +//---------------------------------------------------------------------- + +inline std::string const & Nebula::getLightningClientEffectHitServer() const +{ + return m_lightningClientEffectHitServer; +} + +//---------------------------------------------------------------------- + +inline float Nebula::getEffectEngine() const +{ + return m_effectEngine; +} + +//---------------------------------------------------------------------- + +inline float Nebula::getEffectReactor() const +{ + return m_effectReactor; +} + +//---------------------------------------------------------------------- + +inline float Nebula::getEffectShields() const +{ + return m_effectShields; +} + +//---------------------------------------------------------------------- + +inline float Nebula::getCameraJitterAngle() const +{ + return m_cameraJitterAngle; +} + +//---------------------------------------------------------------------- + +inline float Nebula::getLightningDamageMin() const +{ + return m_lightningDamageMin; +} + +//---------------------------------------------------------------------- + +inline float Nebula::getLightningDamageMax() const +{ + return m_lightningDamageMax; +} + +//---------------------------------------------------------------------- + +inline float Nebula::getLightningDurationMax() const +{ + return m_lightningDurationMax; +} + +//---------------------------------------------------------------------- + +inline float Nebula::getEnvironmentalDamageFrequency() const +{ + return m_environmentalDamageFrequency; +} + +//---------------------------------------------------------------------- + +inline float Nebula::getEnvironmentalDamage() const +{ + return m_environmentalDamage; +} + +//---------------------------------------------------------------------- + +inline std::string const & Nebula::getEnvironmentalDamageClientEffect() const +{ + return m_environmentalDamageClientEffect; +} + +//---------------------------------------------------------------------- + +inline float Nebula::getDensity() const +{ + return m_density; +} + +//---------------------------------------------------------------------- + +inline VectorArgb const & Nebula::getColorFacing() const +{ + return m_colorFacing; +} + +//---------------------------------------------------------------------- + +inline VectorArgb const & Nebula::getColorOriented() const +{ + return m_colorOriented; +} + +//---------------------------------------------------------------------- + +inline VectorArgb const & Nebula::getColorRampFacing() const +{ + return m_colorRampFacing; +} + +//---------------------------------------------------------------------- + +inline VectorArgb const & Nebula::getColorRampOriented() const +{ + return m_colorRampOriented; +} + +//---------------------------------------------------------------------- + +inline float Nebula::getFacingPercent() const +{ + return m_facingPercent; +} + +//---------------------------------------------------------------------- + +inline VectorArgb const & Nebula::getLightningColor() const +{ + return m_lightningColor; +} + +//---------------------------------------------------------------------- + +inline VectorArgb const & Nebula::getLightningColorRamp() const +{ + return m_lightningColorRamp; +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/NebulaManager.cpp b/engine/shared/library/sharedGame/src/shared/space/NebulaManager.cpp new file mode 100644 index 00000000..b5035cb7 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/NebulaManager.cpp @@ -0,0 +1,363 @@ +//====================================================================== +// +// NebulaManager.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/NebulaManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedGame/Nebula.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedMath/SphereTree.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" + +#include +#include + +//====================================================================== + +namespace NebulaManagerNamespace +{ + typedef NebulaManager::NebulaVector NebulaVector; + typedef stdmap::fwd NebulaMap; + typedef std::map NebulasByScene; + + //-- nebula vector OWNS the nebulas + NebulasByScene s_nebulasByScene; + NebulaMap s_nebulaMap; + std::string s_currentSceneId; + + class NebulaSphereAccessor: public BaseSphereTreeAccessor + { + public: + + static Sphere const getExtent(Nebula const *nebula) + { + return NON_NULL(nebula)->getSphere(); + } + + //------------------------------------------------------------------- + + static char const *getDebugName(Nebula const *) + { + return 0; + } + + }; + + typedef SphereTree NebulaSphereTree; + NebulaSphereTree * s_collisionSphereTree = NULL; + + enum DatatableColumns + { + DC_name, + DC_x, + DC_y, + DC_z, + DC_radius, + DC_density, + DC_facingPercent, + DC_facingA, + DC_facingR, + DC_facingG, + DC_facingB, + DC_facingRampA, + DC_facingRampR, + DC_facingRampG, + DC_facingRampB, + DC_orientedA, + DC_orientedR, + DC_orientedG, + DC_orientedB, + DC_orientedRampA, + DC_orientedRampR, + DC_orientedRampG, + DC_orientedRampB, + DC_ambientSound, + DC_ambientSoundVolume, + DC_cameraJitterAngle, + DC_effectReactor, + DC_effectEngine, + DC_effectShields, + DC_lightningFrequency, + DC_lightningDurationMax, + DC_lightningDamageMin, + DC_lightningDamageMax, + DC_lightningAppearance, + DC_lightningA, + DC_lightningR, + DC_lightningG, + DC_lightningB, + DC_lightningRampA, + DC_lightningRampR, + DC_lightningRampG, + DC_lightningRampB, + DC_lightningSound, + DC_lightningSoundLoop, + DC_lightningHitEffectClient, + DC_lightningHitEffectServer, + DC_environmentalDamageFrequency, + DC_environmentalDamage, + DC_environmentalDamageEffect, + DC_shaderIndex + }; + + //---------------------------------------------------------------------- + + NebulaManager::ImplementationClearFunction s_clearFunction = NULL; +} + +using namespace NebulaManagerNamespace; + +//---------------------------------------------------------------------- + +void NebulaManager::install() +{ + InstallTimer const installTimer("NebulaManager::install"); + + ExitChain::add(NebulaManager::remove, "NebulaManager::remove"); +} + +//---------------------------------------------------------------------- + +void NebulaManager::remove() +{ + clear(); + + NebulasByScene::iterator ii = s_nebulasByScene.begin(); + NebulasByScene::iterator iiEnd = s_nebulasByScene.end(); + for (; ii != iiEnd; ++ii) + { + NebulaVector & nebulaVector = ii->second; + + std::for_each(nebulaVector.begin(), nebulaVector.end(), PointerDeleter()); + nebulaVector.clear(); + } + + s_nebulasByScene.clear(); +} + +//---------------------------------------------------------------------- + +void NebulaManager::clear() +{ + //-- Remove nebulas from the collision sphere tree and delete the sphere tree + { + for (NebulaMap::iterator iter = s_nebulaMap.begin(); iter != s_nebulaMap.end(); ++iter) + { + Nebula const * const nebula = iter->second; + s_collisionSphereTree->removeObject(nebula->getSpatialSubdivisionHandle()); + } + } + + s_nebulaMap.clear(); + + if (s_collisionSphereTree != NULL) + { + delete s_collisionSphereTree; + s_collisionSphereTree = NULL; + } + + //-- Remove nebulas for the current scene from the scene map + { + NebulasByScene::iterator iter = s_nebulasByScene.find(s_currentSceneId); + if (iter != s_nebulasByScene.end()) + { + NebulaVector & nebulaVector = iter->second; + + std::for_each(nebulaVector.begin(), nebulaVector.end(), PointerDeleter()); + nebulaVector.clear(); + } + } + + s_currentSceneId = ""; + + if (s_clearFunction != NULL) + s_clearFunction(); +} + +//---------------------------------------------------------------------- + +void NebulaManager::loadSceneData(std::string const & sceneId) +{ + if (sceneId.empty()) + return; + + // already loaded this data + if (hasSceneData(sceneId)) + return; + + std::string const & filename = "datatables/space/nebula/" + sceneId + ".iff"; + + DataTable * const dt = DataTableManager::getTable(filename, true); + + if (dt == NULL) + { + //-- apparently not a space scene + // @todo: need better way to detect this + if (!strncmp(sceneId.c_str(), "space_", 6) != 0) + WARNING(true, ("NebulaManager no such datatable [%s]", filename.c_str())); + return; + } + + float styleWeightings[16] = {0}; + + const int numRows = dt->getNumRows(); + + //lint -e641 //enums to int + + for (int row = 0; row < numRows; ++row) + { + Nebula * const nebula = new Nebula(row + 1, dt->getStringValue(DC_name, row)); + Vector const pos(dt->getFloatValue(DC_x, row), dt->getFloatValue(DC_y, row), dt->getFloatValue(DC_z, row)); + nebula->setExtent(pos, dt->getFloatValue(DC_radius, row)); + nebula->setDensity(dt->getFloatValue(DC_density, row)); + VectorArgb const colorFacing (dt->getFloatValue(DC_facingA, row), dt->getFloatValue(DC_facingR, row), dt->getFloatValue(DC_facingG, row), dt->getFloatValue(DC_facingB, row)); + VectorArgb const colorRampFacing (dt->getFloatValue(DC_facingRampA, row), dt->getFloatValue(DC_facingRampR, row), dt->getFloatValue(DC_facingRampG, row), dt->getFloatValue(DC_facingRampB, row)); + VectorArgb const colorOriented (dt->getFloatValue(DC_orientedA, row), dt->getFloatValue(DC_orientedR, row), dt->getFloatValue(DC_orientedG, row), dt->getFloatValue(DC_orientedB, row)); + VectorArgb const colorRampOriented (dt->getFloatValue(DC_orientedRampA, row), dt->getFloatValue(DC_orientedRampR, row), dt->getFloatValue(DC_orientedRampG, row), dt->getFloatValue(DC_orientedRampB, row)); + nebula->setColor(colorFacing, colorRampFacing, colorOriented, colorRampOriented); + + nebula->setAmbientSound(dt->getStringValue(DC_ambientSound, row), dt->getFloatValue(DC_ambientSoundVolume, row)); + nebula->setCameraJitterAngle(convertDegreesToRadians(dt->getFloatValue(DC_cameraJitterAngle, row))); + nebula->setShipEffects(dt->getFloatValue(DC_effectReactor, row), dt->getFloatValue(DC_effectEngine, row), dt->getFloatValue(DC_effectShields, row)); + + VectorArgb const colorLightning (dt->getFloatValue(DC_lightningA, row), dt->getFloatValue(DC_lightningR, row), dt->getFloatValue(DC_lightningG, row), dt->getFloatValue(DC_lightningB, row)); + VectorArgb const colorRampLightning (dt->getFloatValue(DC_lightningRampA, row), dt->getFloatValue(DC_lightningRampR, row), dt->getFloatValue(DC_lightningRampG, row), dt->getFloatValue(DC_lightningRampB, row)); + + nebula->setLightningEffects(dt->getFloatValue(DC_lightningFrequency, row), + dt->getFloatValue(DC_lightningDurationMax, row), + dt->getStringValue(DC_lightningAppearance, row), + colorLightning, colorRampLightning, + dt->getStringValue(DC_lightningSound, row), dt->getStringValue(DC_lightningSoundLoop, row), + dt->getStringValue(DC_lightningHitEffectClient, row), dt->getStringValue(DC_lightningHitEffectServer, row)); + nebula->setLightningDamage(dt->getFloatValue(DC_lightningDamageMin, row), dt->getFloatValue(DC_lightningDamageMax, row)); + nebula->setEnvironmentalDamage(dt->getFloatValue(DC_environmentalDamageFrequency, row), dt->getFloatValue(DC_environmentalDamage, row), dt->getStringValue(DC_environmentalDamageEffect, row)); + + int const shaderIndex = dt->getIntValue(DC_shaderIndex, row); + float const facingPercent = dt->getFloatValue(DC_facingPercent, row); + + nebula->setShaderInfo(shaderIndex, styleWeightings, facingPercent); + + s_nebulasByScene[sceneId].push_back (nebula); + } //lint !e429 //nebula owned + + DataTableManager::close(filename); +} + +//---------------------------------------------------------------------- + +bool NebulaManager::hasSceneData(std::string const & sceneId) +{ + NebulasByScene::const_iterator ii = s_nebulasByScene.find(sceneId); + + if (ii != s_nebulasByScene.end()) + { + NebulaVector const & currentNebulaVector = ii->second; + return !currentNebulaVector.empty(); + } + + return false; +} + +//---------------------------------------------------------------------- + +void NebulaManager::loadScene(std::string const & sceneId) +{ + clear(); + + s_collisionSphereTree = new NebulaSphereTree; + + loadSceneData(sceneId); + + NebulasByScene::iterator ii = s_nebulasByScene.find(sceneId); + if (ii != s_nebulasByScene.end()) + { + s_currentSceneId = sceneId; + + NebulaVector & currentNebulaVector = ii->second; + + NebulaVector::iterator jj = currentNebulaVector.begin(); + NebulaVector::iterator jjEnd = currentNebulaVector.end(); + + for (; jj != jjEnd; ++jj) + { + Nebula const * const nebula = *jj; + addNebula(*nebula); + } + } +} + +//---------------------------------------------------------------------- + +void NebulaManager::addNebula(Nebula const & nebula) +{ + IGNORE_RETURN(s_nebulaMap.insert(std::make_pair(nebula.getId(), &nebula))); + nebula.setSpatialSubdivisionHandle(s_collisionSphereTree->addObject(&nebula)); +} + +//---------------------------------------------------------------------- + +void NebulaManager::getNebulasAtPosition(Vector const & pos, NebulaVector & nebulaVector) +{ + NON_NULL(s_collisionSphereTree)->findAtPoint(pos, nebulaVector); +} + +//---------------------------------------------------------------------- + +void NebulaManager::getNebulasInSphere(Vector const & pos, float const radius, NebulaVector & nebulaVector) +{ + NON_NULL(s_collisionSphereTree)->findInRange(pos, radius, nebulaVector); +} + +//---------------------------------------------------------------------- + +Nebula const * NebulaManager::getClosestNebula(Vector const & pos, float const maxDistance, float & outMinDistance, float & outMaxDistance) +{ + Nebula const * nebula = NULL; + if (NON_NULL(s_collisionSphereTree)->findClosest(pos, maxDistance, nebula, outMinDistance, outMaxDistance)) + return nebula; + + return NULL; +} + +//---------------------------------------------------------------------- + +Nebula const * NebulaManager::getNebulaById(int const id) +{ + NebulaMap::const_iterator const it = s_nebulaMap.find(id); + if (it != s_nebulaMap.end()) + return (*it).second; + + return NULL; +} + +//---------------------------------------------------------------------- + +NebulaVector const & NebulaManager::getNebulaVector(std::string const & sceneId) +{ + return s_nebulasByScene[sceneId]; +} + +//---------------------------------------------------------------------- + +NebulaVector const & NebulaManager::getNebulaVector() +{ + // this will create an empty nebula vector that + // will be returned if this is the ground game + return s_nebulasByScene[s_currentSceneId]; +} + +//---------------------------------------------------------------------- + +void NebulaManager::setClearFunction(ImplementationClearFunction func) +{ + s_clearFunction = func; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/NebulaManager.h b/engine/shared/library/sharedGame/src/shared/space/NebulaManager.h new file mode 100644 index 00000000..07f53385 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/NebulaManager.h @@ -0,0 +1,53 @@ +//====================================================================== +// +// NebulaManager.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_NebulaManager_H +#define INCLUDED_NebulaManager_H + +//====================================================================== + +class Nebula; +class Vector; + +//---------------------------------------------------------------------- + +class NebulaManager +{ +public: + + typedef void (*ImplementationClearFunction) (void); + + typedef stdvector::fwd NebulaVector; + + static void install(); + static void remove(); + static void setClearFunction(ImplementationClearFunction func); + + static void clear(); + static void loadSceneData(std::string const & sceneId); + static bool hasSceneData(std::string const & sceneId); + static void loadScene(std::string const & sceneId); + + static NebulaVector const & getNebulaVector(std::string const & sceneId); + static NebulaVector const & getNebulaVector(); + + static void getNebulasAtPosition(Vector const & pos, NebulaVector & nebulaVector); + static void getNebulasInSphere(Vector const & pos, float radius, NebulaVector & nebulaVector); + static Nebula const * getClosestNebula(Vector const & pos, float maxDistance, float & outMinDistance, float & outMaxDistance); + static Nebula const * getNebulaById(int id); + +private: + + NebulaManager(NebulaManager const & rhs); + NebulaManager & operator=(NebulaManager const & rhs); + + static void addNebula(Nebula const & nebula); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/PlayerFormationManager.cpp b/engine/shared/library/sharedGame/src/shared/space/PlayerFormationManager.cpp new file mode 100644 index 00000000..6fb7260a --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/PlayerFormationManager.cpp @@ -0,0 +1,283 @@ +//====================================================================== +// +// PlayerFormationManager.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/PlayerFormationManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/TreeFile.h" +#include "sharedFoundation/Crc.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedMath/Vector.h" +#include "sharedMath/Vector2d.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" + +#include +#include + +//====================================================================== + +namespace PlayerFormationManagerNamespace +{ + typedef std::vector FormationData; + + namespace FileListColumnNames + { + char const * const filename = "FILENAME"; + } + + namespace FormationTableColumnNames + { + char const * const x = "X"; + char const * const y = "Y"; + char const * const z = "Z"; + char const * const x2D = "X2D"; + char const * const z2D = "Z2D"; + } + + char const * const cms_filelistTableName = "datatables/space/formation/filelist.iff"; + char const * const cms_formationTableNamePre = "datatables/space/formation/"; + char const * const cms_formationTableNamePost = ".iff"; + int const cms_maxGroupMembers = 20; + + std::map ms_formations; + std::map ms_crcToFormationName; +} + +//====================================================================== + +struct PlayerFormationManager::FormationLocation +{ + bool operator==(FormationLocation const & rhs) const; + bool operator!=(FormationLocation const & rhs) const; + + Vector m_3d; + Vector2d m_2d; +}; + +using namespace PlayerFormationManagerNamespace; + +//====================================================================== + +bool PlayerFormationManager::FormationLocation::operator==(PlayerFormationManager::FormationLocation const & rhs) const +{ + return (m_3d == rhs.m_3d) && (m_2d == rhs.m_2d); +} + +bool PlayerFormationManager::FormationLocation::operator!=(PlayerFormationManager::FormationLocation const & rhs) const +{ + return !operator== (rhs); +} + +//---------------------------------------------------------------------- + +void PlayerFormationManager::install() +{ + InstallTimer const installTimer("PlayerFormationManager::install"); + + ExitChain::add(PlayerFormationManager::remove, "PlayerFormationManager::remove"); + loadTables(); +} + +//---------------------------------------------------------------------- + +void PlayerFormationManager::remove() +{ + clear(); +} + +//---------------------------------------------------------------------- + +void PlayerFormationManager::loadTables() +{ + clear(); + + if(!TreeFile::exists(cms_filelistTableName)) + { + DEBUG_FATAL(true, ("Datatable [%s] not found to build the formation file list", cms_filelistTableName)); + return; + } + + DataTable const * const filelistTableName = DataTableManager::getTable(cms_filelistTableName, true); + std::string formationFileName; + if(filelistTableName) + { + for(int i = 0; i < filelistTableName->getNumRows(); ++i) + { + formationFileName = filelistTableName->getStringValue(FileListColumnNames::filename, i); + loadFormationFile(formationFileName); + } + } +} + +//---------------------------------------------------------------------- + +void PlayerFormationManager::clear() +{ + ms_formations.clear(); + ms_crcToFormationName.clear(); +} + +//---------------------------------------------------------------------- + +void PlayerFormationManager::loadFormationFile(std::string const & formationFileName) +{ + std::string const fullformationFilename = cms_formationTableNamePre + formationFileName + cms_formationTableNamePost; + + //ensure the full filename exists + if(!TreeFile::exists(fullformationFilename.c_str())) + { + DEBUG_FATAL(true, ("Datatable [%s] not found to build the formation", fullformationFilename.c_str())); + return; + } + + DataTable const * const formationDataTable = DataTableManager::getTable(fullformationFilename, true); + if(formationDataTable) + { + //ensure the table has the right number of rows + if(formationDataTable->getNumRows() != cms_maxGroupMembers) + { + DEBUG_FATAL(true, ("Formation data table [%s] does not have the required number of slots [20] defined", fullformationFilename.c_str())); + return; + } + + PlayerFormationManager::FormationLocation formationLocation; + FormationData formationData; + for(int i = 0; i < formationDataTable->getNumRows(); ++i) + { + formationLocation.m_3d.x = formationDataTable->getFloatValue(FormationTableColumnNames::x, i); + formationLocation.m_3d.y = formationDataTable->getFloatValue(FormationTableColumnNames::y, i); + formationLocation.m_3d.z = formationDataTable->getFloatValue(FormationTableColumnNames::z, i); + + formationLocation.m_2d.x = formationDataTable->getFloatValue(FormationTableColumnNames::x2D, i); + formationLocation.m_2d.y = formationDataTable->getFloatValue(FormationTableColumnNames::z2D, i); + + //ensure point wasn't already defined + for(FormationData::const_iterator j = formationData.begin(); j != formationData.end(); ++j) + { + PlayerFormationManager::FormationLocation const & test = *j; + if(test == formationLocation) + { + DEBUG_FATAL(true, ("When building formation data for [%s], 3d position [%.2f, %.2f, %.2f] and 2d position [%.2f, %.2f] defined twice, each position must be unique", fullformationFilename.c_str(), formationLocation.m_3d.x, formationLocation.m_3d.y, formationLocation.m_3d.z, formationLocation.m_2d.x, formationLocation.m_2d.y)); + return; + } + } + + formationData.push_back(formationLocation); + } + + //ensure we could build all the slots (so we can always assume the vector is the right size) + if(formationData.size() != static_cast(cms_maxGroupMembers)) + { + DEBUG_FATAL(true, ("When building formation data for [%s], could not build the required number of slots [%d]", fullformationFilename.c_str(), cms_maxGroupMembers)); + return; + } + + //ensure this formation wasn't already loaded + std::map::const_iterator k = ms_formations.find(formationFileName); + if(k != ms_formations.end()) + { + DEBUG_FATAL(true, ("Formation data table [%s], defined twice", formationFileName.c_str())); + return; + } + + ms_formations[formationFileName] = formationData; + ms_crcToFormationName[Crc::normalizeAndCalculate(formationFileName.c_str())] = formationFileName; + } +} + +//---------------------------------------------------------------------- + +void PlayerFormationManager::getFormationNames(PlayerFormationManager::FormationNameList & formationNames) +{ + formationNames.reserve(ms_formations.size()); + + std::map::const_iterator ii = ms_formations.begin(); + std::map::const_iterator iiEnd = ms_formations.end(); + + for (; ii != iiEnd; ++ii) + { + formationNames.push_back(ii->first); + } +} + +//---------------------------------------------------------------------- + +bool PlayerFormationManager::isValidFormationName(std::string const & formationName) +{ + std::map::const_iterator const & i = ms_formations.find(formationName); + return (i != ms_formations.end()); +} + +//---------------------------------------------------------------------- + +int PlayerFormationManager::getMaximumFormationGroupMembers() +{ + return cms_maxGroupMembers; +} + +//---------------------------------------------------------------------- + +bool PlayerFormationManager::getPositionOffsetFormationLocation(uint32 const formationCrc, int const index, FormationLocation & formationLocation) +{ + if(index < 0 || index > cms_maxGroupMembers) + { + DEBUG_WARNING(true, ("getPositionOffsetFormationLocation, index is [%d], out of range of [0, %d]", index, cms_maxGroupMembers)); + return false; + } + + std::map::const_iterator const & it = ms_crcToFormationName.find(formationCrc); + if(it != ms_crcToFormationName.end()) + { + std::map::const_iterator const & it2 = ms_formations.find(it->second); + if(it2 != ms_formations.end()) + { + if(it2->second.size() <= static_cast(index)) + { + DEBUG_WARNING(true, ("getPositionOffsetFormationLocation, index is [%d], out of range of [0, %d)", index, it2->second.size())); + return false; + } + formationLocation = it2->second[static_cast(index)]; + return true; + } + } + return false; +} + +//---------------------------------------------------------------------- + +bool PlayerFormationManager::getPositionOffset(uint32 const formationCrc, int const index, Vector & /*OUT*/ offset) +{ + offset.makeZero(); + + FormationLocation formationLocation; + if (getPositionOffsetFormationLocation(formationCrc, index, formationLocation)) + { + offset = formationLocation.m_3d; + return true; + } + return false; +} + +//---------------------------------------------------------------------- + +bool PlayerFormationManager::getPositionOffset(uint32 formationCrc, int index, Vector2d & /*OUT*/ offset) +{ + offset.makeZero(); + + FormationLocation formationLocation; + if (getPositionOffsetFormationLocation(formationCrc, index, formationLocation)) + { + offset = formationLocation.m_2d; + return true; + } + return false; +} + + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/PlayerFormationManager.h b/engine/shared/library/sharedGame/src/shared/space/PlayerFormationManager.h new file mode 100644 index 00000000..8c77d464 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/PlayerFormationManager.h @@ -0,0 +1,46 @@ +//====================================================================== +// +// PlayerFormationManager.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_PlayerFormationManager_H +#define INCLUDED_PlayerFormationManager_H + +//====================================================================== + +class Vector; +class Vector2d; + +//---------------------------------------------------------------------- + +class PlayerFormationManager +{ +public: + + typedef stdvector::fwd FormationNameList; + struct FormationLocation; + +public: + static void install(); + static void remove(); + static void loadTables(); + static void getFormationNames(FormationNameList & formationNames); + static bool isValidFormationName(std::string const & formationName); + static int getMaximumFormationGroupMembers(); + static bool getPositionOffset(uint32 formationCrc, int index, Vector & /*OUT*/ offset); + static bool getPositionOffset(uint32 formationCrc, int index, Vector2d & /*OUT*/ offset); + +private: + PlayerFormationManager(PlayerFormationManager const & rhs); + PlayerFormationManager & operator=(PlayerFormationManager const & rhs); + + static void clear(); + static void loadFormationFile(std::string const & formationFileName); + static bool getPositionOffsetFormationLocation(uint32 const formationCrc, int const index, FormationLocation & formationLocation); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipChassis.cpp b/engine/shared/library/sharedGame/src/shared/space/ShipChassis.cpp new file mode 100644 index 00000000..ab3b0672 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipChassis.cpp @@ -0,0 +1,710 @@ +//====================================================================== +// +// ShipChassis.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipChassis.h" + +#include "fileInterface/StdioFile.h" +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/Iff.h" +#include "sharedFoundation/ConstCharCrcString.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/LessPointerComparator.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedFoundation/TemporaryCrcString.h" +#include "sharedGame/ShipChassisSlot.h" +#include "sharedGame/ShipChassisWritable.h" +#include "sharedGame/ShipComponentAttachmentManager.h" +#include "sharedUtility/DataTable.h" +#include +#include + +//====================================================================== + +namespace ShipChassisNamespace +{ + + typedef stdmap::fwd NameChassisMap; + typedef stdmap::fwd CrcChassisMap; + + typedef ShipChassis::PersistentCrcStringVector PersistentCrcStringVector; + PersistentCrcStringVector * s_shipChassisNameVector; + + //-- the s_nameChassisMap owns the Chassis objects + NameChassisMap * s_nameChassisMap; + + //-- the s_nameChassisMap DOES NOT own the Chassis objects + CrcChassisMap s_crcChassisMap; + + bool s_useWritableChassis = false; + + bool s_installed = false; + + const char * const s_filename = "datatables/space/ship_chassis.iff"; +} + +using namespace ShipChassisNamespace; + +//---------------------------------------------------------------------- + +void ShipChassis::install () +{ + InstallTimer const installTimer("ShipChassis::install "); + + if (s_installed) + return; + + s_nameChassisMap = new NameChassisMap; + s_shipChassisNameVector = new PersistentCrcStringVector; + + s_installed = true; + + load(); + + ExitChain::add(ShipChassis::remove, "ShipChassis::remove"); +} + +//---------------------------------------------------------------------- + +void ShipChassis::load() +{ + Iff iff; + if (!iff.open (s_filename, true)) + { + WARNING (true, ("Data file %s not available.", s_filename)); + return; + } + + DataTable dt; + dt.load (iff); + iff.close (); + + std::string const & s_colnameName = "name"; + std::string const & s_colnameSuffix_hitweight = "_hitweight"; + std::string const & s_colnameSuffix_targetable = "_targetable"; + std::string const & s_colnameFlyBySound = "flyby_sound"; + std::string const & s_colnameWingOpenSpeedFactor = "wing_open_speed_factor"; + std::string const & s_colnameHitSoundGroup = "hit_sound_group"; + + const int numRows = dt.getNumRows (); + + for (int row = 0; row < numRows; ++row) + { + ShipChassis * const chassis = s_useWritableChassis ? new ShipChassisWritable : new ShipChassis; + + TemporaryCrcString const nameString (dt.getStringValue (s_colnameName, row), true); + IGNORE_RETURN(chassis->setName(nameString)); + + chassis->setFlyBySound(dt.getStringValue (s_colnameFlyBySound, row)); + + float const wingOpenSpeedFactor = dt.getFloatValue(s_colnameWingOpenSpeedFactor, row); + + chassis->setWingOpenSpeedFactor(wingOpenSpeedFactor); + + std::string const & hitSoundGroup = dt.getStringValue(s_colnameHitSoundGroup, row); + + chassis->setHitSoundGroup(hitSoundGroup); + + for (int shipChassisSlotType = 0; shipChassisSlotType < static_cast(ShipChassisSlotType::SCST_num_explicit_types); ++shipChassisSlotType) + { + std::string const & colnameSlotName = ShipChassisSlotType::getNameFromType (static_cast(shipChassisSlotType)); + std::string const & colnameCompatibilities = colnameSlotName; + + int const colNumber = dt.findColumnNumber(colnameCompatibilities); + if (colNumber >= 0) + { + std::string const & compatibilities = dt.getStringValue(colNumber, row); + + if (!compatibilities.empty()) + { + std::string const & colnameHitWeight = colnameSlotName + s_colnameSuffix_hitweight; + std::string const & colnameTargetable = colnameSlotName + s_colnameSuffix_targetable; + int const hitWeight = dt.getIntValue(colnameHitWeight, row); + bool const targetable = (dt.getIntValue(colnameTargetable, row) == 1) ? true : false; + + ShipChassisSlot const slot(static_cast(shipChassisSlotType), compatibilities, hitWeight, targetable); + chassis->addSlot (slot); + + if (targetable) + { + chassis->setSlotTargetable(slot.getSlotType(), true); + } + } + } + } + + IGNORE_RETURN(chassis->addChassis(false)); + } //lint !e429 //custodial chassis + + std::sort (s_shipChassisNameVector->begin(), s_shipChassisNameVector->end(), LessPointerComparator()); +} + +//---------------------------------------------------------------------- + +bool ShipChassis::save(std::string const & filename) +{ + //-- fill this string with the text contents of the tab file + std::string tabStr; + + //-- TAB HEADER COLNAMES + tabStr += "name\t"; + tabStr += "flyby_sound\t"; + tabStr += "hit_sound_group\t"; + tabStr += "wing_open_speed_factor"; + + { + for (int chassisSlotType = 0; chassisSlotType < static_cast(ShipChassisSlotType::SCST_num_explicit_types); ++chassisSlotType) + { + tabStr.push_back('\t'); + std::string const & slotTypeName = ShipChassisSlotType::getNameFromType(static_cast(chassisSlotType)); + tabStr += slotTypeName + "\t"; + tabStr += slotTypeName + "_hitweight\t"; + tabStr += slotTypeName + "_targetable"; + } + } + + //-- TAB HEADER COLTYPES + tabStr.push_back('\n'); + tabStr += "s\t"; + tabStr += "s\t"; + tabStr += "s\t"; + tabStr += "f[1.0]"; + + { + for (int chassisSlotType = 0; chassisSlotType < static_cast(ShipChassisSlotType::SCST_num_explicit_types); ++chassisSlotType) + { + tabStr.push_back('\t'); + tabStr += "s\t"; + tabStr += "i[10]\t"; + tabStr += "b[0]"; + } + } + + //-- TAB DATA ROWS + { + + char buf[128]; + size_t const buf_size = sizeof(buf); + + StringVector chassisNames; + IGNORE_RETURN(getSortedNameList(chassisNames)); + + for (StringVector::const_iterator it = chassisNames.begin(); it != chassisNames.end(); ++it) + { + std::string const & chassisName = *it; + ShipChassis const * const shipChassis = NON_NULL(findShipChassisByName(ConstCharCrcString(chassisName.c_str()))); + + tabStr.push_back('\n'); + tabStr += chassisName + "\t"; + tabStr += shipChassis->getFlyBySound() + "\t"; + tabStr += shipChassis->getHitSoundGroup() + "\t"; + IGNORE_RETURN(snprintf(buf, buf_size, "%2.2f", shipChassis->getWingOpenSpeedFactor())); + tabStr += buf; + + for (int chassisSlotType = 0; chassisSlotType < static_cast(ShipChassisSlotType::SCST_num_explicit_types); ++chassisSlotType) + { + tabStr.push_back('\t'); + + ShipChassisSlot const * const chassisSlot = shipChassis->getSlot(static_cast(chassisSlotType)); + + if (NULL == chassisSlot) + { + tabStr += "\t\t"; + continue; + } + + //-- compatibilities are canonically space separated + bool firstCompat = true; + ShipChassisSlot::CompatibilityVector const & cv = chassisSlot->getCompatibilities(); + for (ShipChassisSlot::CompatibilityVector::const_iterator cit = cv.begin(); cit != cv.end(); ++cit) + { + if (!firstCompat) + tabStr.push_back(' '); + + firstCompat = false; + + CrcString const * const cs = NON_NULL(*cit); + tabStr += std::string(cs->getString()); + } + + tabStr.push_back('\t'); + + if (10 != chassisSlot->getHitWeight()) + tabStr += 10; + tabStr.push_back('\t'); + + if (chassisSlot->isTargetable()) + tabStr += "1"; + } + } + } + + tabStr.push_back('\n'); + + bool retval = false; + + StdioFileFactory sff; + AbstractFile * const af = sff.createFile(filename.c_str(), "wb"); + if (NULL != af && af->isOpen()) + { + int const bytesWritten = af->write(static_cast(tabStr.size()), tabStr.c_str()); + retval = (bytesWritten == static_cast(tabStr.size())); + } + else + { + WARNING(true, ("ShipChassis failed to write file [%s]", filename.c_str())); + } + + delete af; + return retval; +} + +//---------------------------------------------------------------------- + +void ShipChassis::remove () +{ + for (NameChassisMap::iterator it = s_nameChassisMap->begin (); it != s_nameChassisMap->end (); ++it) + delete (*it).second; + + s_nameChassisMap->clear (); + delete s_nameChassisMap; + s_nameChassisMap = 0; + + s_crcChassisMap.clear (); + + std::for_each(s_shipChassisNameVector->begin (), s_shipChassisNameVector->end (), PointerDeleter ()); + s_shipChassisNameVector->clear (); + delete s_shipChassisNameVector; + s_shipChassisNameVector = 0; + + s_installed = false; +} + +//---------------------------------------------------------------------- + +ShipChassis::ShipChassis () : +m_name (), +m_slots (new SlotVector), +m_targetableSlots (new IntVector), +m_flybySound (), +m_wingOpenSpeedFactor(1.0f), +m_hitSoundGroup() +{ + +} + +//---------------------------------------------------------------------- + +ShipChassis::~ShipChassis () +{ + delete m_slots; + m_slots = 0; + delete m_targetableSlots; + m_targetableSlots = 0; +} + +//---------------------------------------------------------------------- + +ShipChassis const * ShipChassis::findShipChassisByName (CrcString const & chassisName) +{ + DEBUG_FATAL (!s_installed, ("not installed")); + + const NameChassisMap::const_iterator it = s_nameChassisMap->find (PersistentCrcString(chassisName)); + if (it != s_nameChassisMap->end ()) + return (*it).second; + + return NULL; +} + +//---------------------------------------------------------------------- + +ShipChassis const * ShipChassis::findShipChassisByCrc (uint32 chassisCrc) +{ + DEBUG_FATAL (!s_installed, ("not installed")); + + const CrcChassisMap::const_iterator it = s_crcChassisMap.find (chassisCrc); + if (it != s_crcChassisMap.end ()) + return (*it).second; + + return NULL; +} + +//---------------------------------------------------------------------- + +void ShipChassis::addSlot (ShipChassisSlot const & slot) +{ + m_slots->push_back (slot); +} + +//---------------------------------------------------------------------- + +void ShipChassis::removeSlot(int chassisSlotType) +{ + { + for (SlotVector::iterator it = m_slots->begin (); it != m_slots->end (); ++it) + { + ShipChassisSlot const & slot = *it; + if (slot.getSlotType() == chassisSlotType) + { + IGNORE_RETURN(m_slots->erase(it)); + break; + } + } + } + + setSlotTargetable(chassisSlotType, false); +} + +//---------------------------------------------------------------------- + +void ShipChassis::setSlotTargetable(int const chassisSlotType, bool targetable) +{ + if (targetable) + { + if (NULL == getSlot(static_cast(chassisSlotType))) + { + WARNING(true, ("ShipChassis cannot set non existant slot [%d] targetable", chassisSlotType)); + return; + } + + if (std::find(m_targetableSlots->begin(), m_targetableSlots->end(), chassisSlotType) == m_targetableSlots->end()) + m_targetableSlots->push_back(chassisSlotType); + } + else + { + IGNORE_RETURN(m_targetableSlots->erase(std::remove(m_targetableSlots->begin(), m_targetableSlots->end(), chassisSlotType), m_targetableSlots->end())); + } +} + +//---------------------------------------------------------------------- + +ShipChassisSlot const * ShipChassis::getSlot(ShipChassisSlotType::Type shipChassisSlotType) const +{ + return const_cast(this)->getSlot(shipChassisSlotType); +} + +//---------------------------------------------------------------------- + +ShipChassisSlot * ShipChassis::getSlot(ShipChassisSlotType::Type shipChassisSlotType) +{ + for (SlotVector::iterator it = m_slots->begin (); it != m_slots->end (); ++it) + { + ShipChassisSlot & slot = *it; + if (slot.getSlotType () == shipChassisSlotType) + return &slot; + } + + return NULL; +} + +//---------------------------------------------------------------------- + +ShipChassisSlotType::Type ShipChassis::getPreviousTargetableSlot (uint32 chassisCrc, ShipChassisSlotType::Type shipChassisSlotType) +{ + ShipChassis const * const chassis = findShipChassisByCrc(chassisCrc); + if (chassis) + return chassis->getPreviousTargetableSlot(shipChassisSlotType); + + return ShipChassisSlotType::SCST_num_types; +} + +//---------------------------------------------------------------------- + +ShipChassisSlotType::Type ShipChassis::getPreviousTargetableSlot (ShipChassisSlotType::Type currentlyTargetedSlotType) const +{ + if (m_targetableSlots->empty()) + return ShipChassisSlotType::SCST_num_types; + + //if we're given a "none" slot, return the last targetable slot + if (currentlyTargetedSlotType == ShipChassisSlotType::SCST_num_types) + return static_cast(m_targetableSlots->back()); + + //if we're given the first slot, return the none slot + if (m_targetableSlots->front() == currentlyTargetedSlotType) + return ShipChassisSlotType::SCST_num_types; + + //otherwise, find the given slot, and return the previous one + for (IntVector::const_iterator it = m_targetableSlots->begin (); it != m_targetableSlots->end (); ++it) + { + int const slotType = *it; + + //we found the currently targeted slot, return the previous one + if (slotType == currentlyTargetedSlotType) + return static_cast(*(--it)); + } + + return ShipChassisSlotType::SCST_num_types; +} + +//---------------------------------------------------------------------- + +ShipChassisSlotType::Type ShipChassis::getNextTargetableSlot (uint32 chassisCrc, ShipChassisSlotType::Type shipChassisSlotType) +{ + int result = ShipChassisSlotType::SCST_num_types; + ShipChassis const * const chassis = findShipChassisByCrc(chassisCrc); + if(chassis && !chassis->m_targetableSlots->empty()) + { + //if we're given a "none" slot, return the first targetable slot + if(shipChassisSlotType == ShipChassisSlotType::SCST_num_types) + { + IntVector::const_iterator it = chassis->m_targetableSlots->begin(); + return static_cast(*it); + } + + //otherwise, take the given slot, find it, then return the next slot + IntVector::const_iterator const firstIt = chassis->m_targetableSlots->begin (); + int const firstSlotType = *firstIt; + result = firstSlotType; + + for (IntVector::const_iterator it = chassis->m_targetableSlots->begin (); it != chassis->m_targetableSlots->end (); ++it) + { + int const slotType = *it; + //we found the currently targeted slot, return the next one + if (slotType == shipChassisSlotType) + { + //grab the next item + if(++it != chassis->m_targetableSlots->end ()) + { + return static_cast(slotType); + } + else + { + //if we're at the end, we'll return a "none" target + return ShipChassisSlotType::SCST_num_types; + } + } + } + } + + return static_cast(result); +} + +//---------------------------------------------------------------------- + +ShipChassisSlotType::Type ShipChassis::getNextTargetableSlot (ShipChassisSlotType::Type currentlyTargetedSlotType) const +{ + if (m_targetableSlots->empty()) + return ShipChassisSlotType::SCST_num_types; + + //if we're given a "none" slot, return the first targetable slot + if (currentlyTargetedSlotType == ShipChassisSlotType::SCST_num_types) + return static_cast(m_targetableSlots->front()); + + //if we're given the last slot, return the none slot + if (m_targetableSlots->back() == currentlyTargetedSlotType) + return ShipChassisSlotType::SCST_num_types; + + //otherwise, find the given slot, and return the previous one + for (IntVector::reverse_iterator it = m_targetableSlots->rbegin (); it != m_targetableSlots->rend (); ++it) + { + int const slotType = *it; + + //we found the currently targeted slot, return the previous (next) one + if (slotType == currentlyTargetedSlotType) + return static_cast(*(--it)); + } + + return ShipChassisSlotType::SCST_num_types; +} + +//---------------------------------------------------------------------- + +bool ShipChassis::isSlotTargetable(int chassisSlotType) const +{ + return std::find(m_targetableSlots->begin(), m_targetableSlots->end(), chassisSlotType) != m_targetableSlots->end(); +} + +//---------------------------------------------------------------------- + +bool ShipChassis::isSlotTargetable (uint32 chassisCrc, ShipChassisSlotType::Type shipChassisSlotType) +{ + ShipChassis const * const chassis = findShipChassisByCrc(chassisCrc); + if(chassis) + { + return chassis->isSlotTargetable(shipChassisSlotType); + } + return false; +} + +//---------------------------------------------------------------------- + +ShipChassisSlotType::Type ShipChassis::getSlotPowerPriority (int slotIndex) const +{ + if (slotIndex < static_cast(ShipChassisSlotType::SCST_first) || + slotIndex >= static_cast(ShipChassisSlotType::SCST_num_types)) + return ShipChassisSlotType::SCST_num_types; + + //@todo: data drive this + return static_cast(slotIndex); +} + +//---------------------------------------------------------------------- + +ShipChassis::PersistentCrcStringVector const & ShipChassis::getShipChassisCrcVector () +{ + DEBUG_FATAL (!s_installed, ("not installed")); + return *NON_NULL(s_shipChassisNameVector); +} + +//---------------------------------------------------------------------- + +ShipChassis::ShipChassis(ShipChassis const & rhs) : +m_name(rhs.m_name), +m_slots(new SlotVector(*rhs.m_slots)), +m_targetableSlots(new IntVector(*rhs.m_targetableSlots)), +m_flybySound(rhs.m_flybySound), +m_wingOpenSpeedFactor(rhs.m_wingOpenSpeedFactor), +m_hitSoundGroup(rhs.m_hitSoundGroup) +{ +} + +//---------------------------------------------------------------------- + +void ShipChassis::setFlybySound(std::string const & flybySound) +{ + m_flybySound = flybySound; +} + +//---------------------------------------------------------------------- + +void ShipChassis::setUseWritableChassis(bool onlyUseThisForTools) +{ + DEBUG_FATAL (s_installed, ("already installed, setUseWritableChassis must be called prior to installation")); + + s_useWritableChassis = onlyUseThisForTools; +} + +//---------------------------------------------------------------------- + +bool ShipChassis::addChassis(bool doSort) +{ + if (doSort && NULL != findShipChassisByCrc(getCrc())) + { + WARNING(true, ("ShipChassis attempt to add multiple [%s] chassis", getName().getString())); + return false; + } + + IGNORE_RETURN (s_nameChassisMap->insert (std::make_pair (m_name, this))); + IGNORE_RETURN (s_crcChassisMap.insert (std::make_pair (getCrc (), this))); + s_shipChassisNameVector->push_back (new PersistentCrcString(getName())); + + if (doSort) + { + std::sort (s_shipChassisNameVector->begin(), s_shipChassisNameVector->end(), LessPointerComparator()); + } + + return true; +} + +//---------------------------------------------------------------------- + +bool ShipChassis::removeChassis() +{ + if (s_nameChassisMap->find(m_name) == s_nameChassisMap->end() || s_crcChassisMap.find(getCrc()) == s_crcChassisMap.end()) + return false; + + IGNORE_RETURN(s_nameChassisMap->erase(m_name)); + IGNORE_RETURN(s_crcChassisMap.erase(getCrc())); + + for (PersistentCrcStringVector::iterator it = s_shipChassisNameVector->begin(); it != s_shipChassisNameVector->end(); ++it) + { + PersistentCrcString const * const pcs = *it; + if (pcs->getCrc() == getCrc()) + { + IGNORE_RETURN(s_shipChassisNameVector->erase(it)); + break; + } + } + + return true; +} + +//---------------------------------------------------------------------- + +bool ShipChassis::setName(CrcString const & name) +{ + ShipChassis const * const dupeNameShipChassis = findShipChassisByName(name); + if (NULL != dupeNameShipChassis) + { + WARNING(true, ("ShipChassis attempt to set name [%s] already exists", name.getString())); + return false; + } + + ShipChassis const * const chassisInList = findShipChassisByCrc(getCrc()); + + if (this == chassisInList) + { + ShipComponentAttachmentManager::udpateChassisCrc(m_name.getCrc(), name.getCrc()); + + if (!removeChassis()) + return false; + + m_name.CrcString::set(name); + + if (!addChassis(true)) + return false; + } + else + { + m_name.CrcString::set(name); + } + + return true; +} + +//---------------------------------------------------------------------- + +ShipChassis::StringVector & ShipChassis::getSortedNameList(StringVector & chassisNames) +{ + ShipChassis::PersistentCrcStringVector const & shipChassisNameVector = ShipChassis::getShipChassisCrcVector(); + chassisNames.reserve(shipChassisNameVector.size()); + for (ShipChassis::PersistentCrcStringVector::const_iterator it = shipChassisNameVector.begin(); it != shipChassisNameVector.end(); ++it) + { + PersistentCrcString const * const pcs = *it; + chassisNames.push_back(pcs->getString()); + } + + std::sort(chassisNames.begin(), chassisNames.end()); + return chassisNames; +} + +//---------------------------------------------------------------------- + +char const * const ShipChassis::getFilename() +{ + return s_filename; +} + +//---------------------------------------------------------------------- + +float ShipChassis::getWingOpenSpeedFactor() const +{ + return m_wingOpenSpeedFactor; +} + +//---------------------------------------------------------------------- + +std::string const & ShipChassis::getHitSoundGroup() const +{ + return m_hitSoundGroup; +} + +//---------------------------------------------------------------------- + +void ShipChassis::setWingOpenSpeedFactor(float const wingOpenSpeedFactor) +{ + m_wingOpenSpeedFactor = wingOpenSpeedFactor; +} + +//---------------------------------------------------------------------- + +void ShipChassis::setHitSoundGroup(std::string const & hitSoundGroup) +{ + m_hitSoundGroup = hitSoundGroup; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipChassis.h b/engine/shared/library/sharedGame/src/shared/space/ShipChassis.h new file mode 100644 index 00000000..2ff80838 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipChassis.h @@ -0,0 +1,136 @@ +//====================================================================== +// +// ShipChassis.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ShipChassis_H +#define INCLUDED_ShipChassis_H + +//====================================================================== + +#include "sharedGame/ShipChassisSlotType.h" +#include "sharedFoundation/PersistentCrcString.h" + +class ShipChassisSlot; + +//---------------------------------------------------------------------- + +class ShipChassis +{ +public: + + typedef stdvector::fwd SlotVector; + typedef stdset::fwd SlotSet; + typedef stdvector::fwd IntVector; + typedef stdvector::fwd StringVector; + + static void install (); + static void remove (); + + static void load(); + static bool save(std::string const & filename); + + static void setUseWritableChassis(bool onlyUseThisForTools); + + typedef stdvector::fwd PersistentCrcStringVector; + + static PersistentCrcStringVector const & getShipChassisCrcVector (); + + static StringVector & getSortedNameList(StringVector & chassisNames); + static char const * const getFilename(); + + static ShipChassis const * findShipChassisByName (CrcString const & chassisName); + static ShipChassis const * findShipChassisByCrc (uint32 chassisCrc); + static bool isSlotTargetable (uint32 chassisCrc, ShipChassisSlotType::Type shipChassisSlotType); + static ShipChassisSlotType::Type getPreviousTargetableSlot (uint32 chassisCrc, ShipChassisSlotType::Type currentlyTargetedSlotType); + static ShipChassisSlotType::Type getNextTargetableSlot (uint32 chassisCrc, ShipChassisSlotType::Type currentlyTargetedSlotType); + + CrcString const & getName () const; + uint32 getCrc () const; + + SlotVector const & getSlots () const; + ShipChassisSlot const * getSlot (ShipChassisSlotType::Type shipChassisSlotType) const; + + ShipChassisSlotType::Type getSlotPowerPriority (int slotIndex) const; + std::string const & getFlyBySound () const; + void setFlyBySound (std::string const & flyBySound); + bool isSlotTargetable(int chassisSlotType) const; + + ShipChassisSlotType::Type getPreviousTargetableSlot (ShipChassisSlotType::Type currentlyTargetedSlotType) const; + ShipChassisSlotType::Type getNextTargetableSlot (ShipChassisSlotType::Type currentlyTargetedSlotType) const; + + float getWingOpenSpeedFactor() const; + + std::string const & getHitSoundGroup() const; + +protected: + + ShipChassis (); + ShipChassis(ShipChassis const & rhs); + virtual ~ShipChassis (); + + virtual bool setName (CrcString const & name); + virtual void addSlot (ShipChassisSlot const & slot); + virtual void setSlotTargetable (int chassisSlotType, bool targetable); + virtual void removeSlot(int chassisSlotType); + virtual void setFlybySound(std::string const & flybySound); + ShipChassisSlot * getSlot(ShipChassisSlotType::Type shipChassisSlotType); + virtual bool addChassis(bool doSort); + virtual bool removeChassis(); + virtual void setWingOpenSpeedFactor(float wingOpenSpeedFactor); + virtual void setHitSoundGroup(std::string const & hitSoundGroup); + +private: + + ShipChassis & operator= (const ShipChassis & rhs); + +private: + + PersistentCrcString m_name; + SlotVector * m_slots; + IntVector * m_targetableSlots; + std::string m_flybySound; + float m_wingOpenSpeedFactor; + std::string m_hitSoundGroup; +}; + +//---------------------------------------------------------------------- + +inline CrcString const & ShipChassis::getName () const +{ + return m_name; +} + +//---------------------------------------------------------------------- + +inline uint32 ShipChassis::getCrc () const +{ + return m_name.getCrc (); +} + +//---------------------------------------------------------------------- + +inline ShipChassis::SlotVector const & ShipChassis::getSlots () const +{ + return *m_slots; +} + +//---------------------------------------------------------------------- + +inline std::string const & ShipChassis::getFlyBySound() const +{ + return m_flybySound; +} + +//---------------------------------------------------------------------- + +inline void ShipChassis::setFlyBySound(std::string const & flyBySound) +{ + m_flybySound = flyBySound; +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipChassisSlot.cpp b/engine/shared/library/sharedGame/src/shared/space/ShipChassisSlot.cpp new file mode 100644 index 00000000..dec4fd3e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipChassisSlot.cpp @@ -0,0 +1,324 @@ +//====================================================================== +// +// ShipChassisSlot.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipChassisSlot.h" +#include "sharedGame/ShipComponentType.h" + +#include "UnicodeUtils.h" +#include "sharedFoundation/ConstCharCrcString.h" +#include "sharedFoundation/LessPointerComparator.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedGame/ShipComponentDescriptor.h" +#include +#include + +//====================================================================== + +namespace ShipChassisSlotNamespace +{ + bool s_installed = false; + + void install () + { + if (s_installed) + return; + } + + //---------------------------------------------------------------------- + + typedef stdvector::fwd CompatibilityVector; + + //---------------------------------------------------------------------- + + void copyCompatibilities(CompatibilityVector const & src, CompatibilityVector & dst) + { + std::for_each(dst.begin(), dst.end(), PointerDeleter()); + dst.clear(); + dst.reserve(src.size()); + for (CompatibilityVector::const_iterator it = src.begin(); it != src.end(); ++it) + { + CrcString const * const str = *it; + dst.push_back(new PersistentCrcString(*str)); + } + } +} + +using namespace ShipChassisSlotNamespace; + +//---------------------------------------------------------------------- + +ShipChassisSlot::ShipChassisSlot () : +m_slotType (ShipChassisSlotType::SCST_num_types), +m_compatibilities (new CompatibilityVector), +m_hitWeight (1), +m_targetable (false) +{ +} + +//---------------------------------------------------------------------- + +ShipChassisSlot::ShipChassisSlot (ShipChassisSlotType::Type slotType, std::string const & compatibilities, int hitWeight, bool targetable) : +m_slotType (slotType), +m_compatibilities (new CompatibilityVector), +m_hitWeight (hitWeight), +m_targetable (targetable) +{ + unpackCompatibilities (compatibilities); +} + +//---------------------------------------------------------------------- + +ShipChassisSlot::~ShipChassisSlot () +{ + std::for_each(m_compatibilities->begin(), m_compatibilities->end(), PointerDeleter()); + m_compatibilities->clear(); + delete m_compatibilities; + m_compatibilities = NULL; +} + +//---------------------------------------------------------------------- + +ShipChassisSlot::ShipChassisSlot (const ShipChassisSlot & rhs) : +m_slotType (rhs.m_slotType), +m_compatibilities (new CompatibilityVector), +m_hitWeight (rhs.m_hitWeight), +m_targetable (rhs.m_targetable) +{ + copyCompatibilities(*rhs.m_compatibilities, *m_compatibilities); +} + +//---------------------------------------------------------------------- + +ShipChassisSlot & ShipChassisSlot::operator= (const ShipChassisSlot & rhs) +{ + if (this != &rhs) + { + m_slotType = rhs.m_slotType; + copyCompatibilities(*rhs.m_compatibilities, *m_compatibilities); + m_hitWeight = rhs.m_hitWeight; + m_targetable = rhs.m_targetable; + } + + return *this; +} //lint !e1539 // m_compatibilities is assigned + +//---------------------------------------------------------------------- + +bool ShipChassisSlot::canAcceptComponent (ShipComponentDescriptor const & shipComponentDescriptor) const +{ + if (canAcceptComponentType (shipComponentDescriptor.getComponentType ())) + { + if (canAcceptCompatibility (shipComponentDescriptor.getCompatibility ())) + return true; + } + + return false; +} + +//---------------------------------------------------------------------- + +std::string const ShipChassisSlot::getMatchingCompatibilityString(ShipComponentDescriptor const & shipComponentDescriptor) const +{ + if (canAcceptComponent (shipComponentDescriptor)) + { + return std::string(shipComponentDescriptor.getCompatibility().getString()); + } + return std::string(); +} + +//---------------------------------------------------------------------- + +bool ShipChassisSlot::canAcceptComponentType (int shipComponentType) const +{ + if (shipComponentType >= static_cast(ShipComponentType::SCT_num_types)) + return false; + + return ShipChassisSlotType::getComponentTypeForSlot (m_slotType) == shipComponentType; +} + +//---------------------------------------------------------------------- + +bool ShipChassisSlot::canAcceptCompatibility (CrcString const & compatibility) const +{ + //-- null compatibility components are universally accepted + if (compatibility.isEmpty ()) + return true; + + //-- m_compatibilities must be maintained in sorted order + return std::binary_search (m_compatibilities->begin (), m_compatibilities->end (), &compatibility, &LessPointerComparatorStatic::compare); +} + +//---------------------------------------------------------------------- + +void ShipChassisSlot::unpackCompatibilities (std::string const & compatibilities) +{ + std::for_each(m_compatibilities->begin(), m_compatibilities->end(), PointerDeleter()); + m_compatibilities->clear(); + + size_t pos = 0; + + std::string token; + while (Unicode::getFirstToken (compatibilities, pos, pos, token, ", \n\r\t")) + { + m_compatibilities->push_back (new PersistentCrcString (token.c_str (), true)); + + if (pos != std::string::npos) //lint !e650 !e737 // stupid msvc + ++pos; + else + break; + } + + std::sort(m_compatibilities->begin(), m_compatibilities->end(), LessPointerComparator()); +} + +//---------------------------------------------------------------------- + +std::string const ShipChassisSlot::getCompatibilityString() const +{ + static std::string result; + result.clear(); + + for (ShipChassisSlot::CompatibilityVector::const_iterator cit = m_compatibilities->begin (); cit != m_compatibilities->end (); ++cit) + { + CrcString const & compatibility = *NON_NULL(*cit); + result += compatibility.getString (); + result.push_back (' '); + } + + return result; +} + +//---------------------------------------------------------------------- + +void ShipChassisSlot::setTargetable(bool targetable) +{ + m_targetable = targetable; +} + +//---------------------------------------------------------------------- + +void ShipChassisSlot::setHitWeight(int hitWeight) +{ + m_hitWeight = hitWeight; +} + +//---------------------------------------------------------------------- + +void ShipChassisSlot::setCompatibilities(std::string const & compatibilities) +{ + unpackCompatibilities(compatibilities); +} + +//---------------------------------------------------------------------- + +void ShipChassisSlot::removeCompatibility(std::string const & compat) +{ + ConstCharCrcString const cccs(compat.c_str()); + for (CompatibilityVector::iterator it = m_compatibilities->begin(); it != m_compatibilities->end(); ++it) + { + CrcString * const existingCompat = NON_NULL(*it); + if (*existingCompat == cccs) + { + IGNORE_RETURN(m_compatibilities->erase(it)); + return; + } + } +} + +//---------------------------------------------------------------------- + +void ShipChassisSlot::addCompatibility(std::string const & compat) +{ + ConstCharCrcString const cccs(compat.c_str()); + if (std::binary_search (m_compatibilities->begin (), m_compatibilities->end (), &cccs, &LessPointerComparatorStatic::compare)) + { + WARNING(true, ("ShipChassisSlot::addCompatibility attempt to add exising compatibility")); + return; + } + + m_compatibilities->push_back(new PersistentCrcString(cccs.getString(), cccs.getCrc())); + std::sort(m_compatibilities->begin(), m_compatibilities->end(), LessPointerComparator()); +} + +//---------------------------------------------------------------------- + +Unicode::String ShipChassisSlot::getLocalizedSlotName () const +{ + return getLocalizedSlotInformation("ship_slot_n", "ship_slot_compatabilities_n", true, "/"); +} + +//---------------------------------------------------------------------- + +Unicode::String ShipChassisSlot::getLocalizedSlotDescription () const +{ + return getLocalizedSlotInformation("ship_slot_d", "ship_slot_compatabilities_d", true, " "); +} + +//---------------------------------------------------------------------- + +Unicode::String ShipChassisSlot::getLocalizedSlotInformation (std::string const & stringTableGeneral, std::string const & stringTableSpecific, + bool allowCompoundInfo, std::string const & compoundSeperator) const +{ + CompatibilityVector const & compatibilities = getCompatibilities(); + if(compatibilities.empty()) + return Unicode::emptyString; + + //if it can take multiple types, try to build a compound name + //otherwise just use the generic name + bool useSlotName = false; + + //special case armor, use general information to prevent confusion + if(m_slotType == ShipChassisSlotType::SCST_armor_0 || m_slotType == ShipChassisSlotType::SCST_armor_1) + useSlotName = true; + + int numCompatibilities = static_cast(compatibilities.size()); + if(!useSlotName && numCompatibilities > 1) + { + //try to build a compound name + if(allowCompoundInfo) + { + Unicode::String compoundName; + Unicode::String compatibilityName; + for(int i = 0; i < numCompatibilities; ++i) + { + CrcString * slotNameCrcString = compatibilities[i]; + StringId sid(stringTableSpecific, slotNameCrcString->getString()); + + if(sid.localize(compatibilityName)) + { + if(!compoundName.empty()) + { + compoundName += Unicode::narrowToWide(compoundSeperator); + } + compoundName += compatibilityName; + } + } + + if(!compoundName.empty()) + { + return compoundName; + } + } + + //fall back to using the slot name + useSlotName = true; + } + + if(useSlotName) + { + StringId sid(stringTableGeneral, ShipChassisSlotType::getNameFromType(m_slotType)); + return sid.localize(); + } + + //else, find the more specific name for it + CrcString * slotNameCrcString = compatibilities[0]; + StringId sid(stringTableSpecific, slotNameCrcString->getString()); + return sid.localize(); +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipChassisSlot.h b/engine/shared/library/sharedGame/src/shared/space/ShipChassisSlot.h new file mode 100644 index 00000000..9642ef34 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipChassisSlot.h @@ -0,0 +1,103 @@ +//====================================================================== +// +// ShipChassisSlot.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ShipChassisSlot_H +#define INCLUDED_ShipChassisSlot_H + +//====================================================================== + +#include "sharedGame/ShipChassisSlotType.h" +#include "sharedFoundation/PersistentCrcString.h" + +class ShipComponentDescriptor; + +//---------------------------------------------------------------------- + +class ShipChassisSlot +{ +public: + typedef stdvector::fwd CompatibilityVector; + + ShipChassisSlot (ShipChassisSlotType::Type slotType, std::string const & compatibilities, int hitWeight, bool targetable); + ShipChassisSlot (); + ~ShipChassisSlot (); + + ShipChassisSlotType::Type getSlotType () const; + CompatibilityVector const & getCompatibilities () const; + std::string const getCompatibilityString () const; + + bool canAcceptComponent (ShipComponentDescriptor const & shipComponentDescriptor) const; + bool canAcceptComponentType (int shipComponentType) const; + bool canAcceptCompatibility (CrcString const & compatibility) const; + int getHitWeight () const; + bool isTargetable () const; + + Unicode::String getLocalizedSlotName () const; + Unicode::String getLocalizedSlotDescription () const; + + ShipChassisSlot (const ShipChassisSlot & rhs); + ShipChassisSlot & operator= (const ShipChassisSlot & rhs); + + std::string const getMatchingCompatibilityString(ShipComponentDescriptor const & shipComponentDescriptor) const; + +public: + + /** + * The following methods are for editor use only + */ + + void setTargetable(bool targetable); + void setHitWeight(int hitWeight); + void setCompatibilities(std::string const & compatibilities); + void removeCompatibility(std::string const & compat); + void addCompatibility(std::string const & compat); + +private: + + void unpackCompatibilities (std::string const & compatibilities); + Unicode::String getLocalizedSlotInformation (std::string const & stringTableGeneral, std::string const & stringTableSpecific, + bool allowCompoundInfo = false, const std::string & compoundSeperator = "") const; + +private: + + ShipChassisSlotType::Type m_slotType; + CompatibilityVector * m_compatibilities; + int m_hitWeight; + bool m_targetable; +}; + +//---------------------------------------------------------------------- + +inline ShipChassisSlotType::Type ShipChassisSlot::getSlotType () const +{ + return m_slotType; +} + +//---------------------------------------------------------------------- + +inline ShipChassisSlot::CompatibilityVector const & ShipChassisSlot::getCompatibilities () const +{ + return *m_compatibilities; +} + +//---------------------------------------------------------------------- + +inline int ShipChassisSlot::getHitWeight () const +{ + return m_hitWeight; +} + +//---------------------------------------------------------------------- + +inline bool ShipChassisSlot::isTargetable () const +{ + return m_targetable; +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipChassisSlotType.cpp b/engine/shared/library/sharedGame/src/shared/space/ShipChassisSlotType.cpp new file mode 100644 index 00000000..ab0bd1b8 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipChassisSlotType.cpp @@ -0,0 +1,379 @@ +//====================================================================== +// +// ShipChassisSlotType.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipChassisSlotType.h" + +#include "sharedGame/ShipComponentType.h" + +#include "Unicode.h" + +#include + +//====================================================================== + +namespace ShipChassisSlotTypeNamespace +{ + // The following must be kept in sync: + // scst_short_n.stf + // ShipChassisSlotType::Type (ShipChassisSlotType.h) + // ShipChassisSlotTypeNamespace::s_slotTypeNames (ShipChassisSlotType.cpp) + // ShipChassisSlotTypeNamespace::s_slotTypeComponentTypeMapping (ShipChassisSlotType.cpp) + // ship_chassis_slot_type (base_class.java) + // ship_chassis_slot_type::names (base_class.java) + const std::string s_slotTypeNames [ShipChassisSlotType::SCST_num_types + 1] = + { + "reactor", + "engine", + "shield_0", + "shield_1", + "armor_0", + "armor_1", + "capacitor", + "booster", + "droid_interface", + "bridge", + "hangar", + "targeting_station", + "cargo_hold", + "modification_0", + "modification_1", + "weapon_0", + "weapon_1", + "weapon_2", + "weapon_3", + "weapon_4", + "weapon_5", + "weapon_6", + "weapon_7", + "weapon_8", + "weapon_9", + "weapon_10", + "weapon_11", + "weapon_12", + "weapon_13", + "weapon_14", + "weapon_15", + "weapon_16", + "weapon_17", + "weapon_18", + "weapon_19", + "weapon_20", + "weapon_21", + "weapon_22", + "weapon_23", + "weapon_24", + "weapon_25", + "weapon_26", + "weapon_27", + "weapon_28", + "weapon_29", + "weapon_30", + "weapon_31", + "weapon_32", + "weapon_33", + "weapon_34", + "weapon_35", + "weapon_36", + "weapon_37", + "weapon_38", + "weapon_39", + "weapon_40", + "weapon_41", + "weapon_42", + "weapon_43", + "weapon_44", + "weapon_45", + "weapon_46", + "weapon_47", + "weapon_48", + "weapon_49", + "weapon_50", + "weapon_51", + "weapon_52", + "weapon_53", + "weapon_54", + "weapon_55", + "weapon_56", + "weapon_57", + "weapon_58", + "weapon_59", + "weapon_60", + "weapon_61", + "weapon_62", + "weapon_63", + "weapon_64", + "weapon_65", + "weapon_66", + "weapon_67", + "weapon_68", + "weapon_69", + "weapon_70", + "weapon_71", + "weapon_72", + "weapon_73", + "weapon_74", + "weapon_75", + "weapon_76", + "weapon_77", + "weapon_78", + "weapon_79", + "weapon_80", + "weapon_81", + "weapon_82", + "weapon_83", + "weapon_84", + "weapon_85", + "weapon_86", + "weapon_87", + "weapon_88", + "weapon_89", + "weapon_90", + "weapon_91", + "weapon_92", + "weapon_93", + "weapon_94", + "weapon_95", + "weapon_96", + "weapon_97", + "weapon_98", + "weapon_99", + "none", + }; + + Unicode::String s_slotTypeShortNames [ShipChassisSlotType::SCST_num_types]; + + // The following must be kept in sync: + // scst_short_n.stf + // ShipChassisSlotType::Type (ShipChassisSlotType.h) + // ShipChassisSlotTypeNamespace::s_slotTypeNames (ShipChassisSlotType.cpp) + // ShipChassisSlotTypeNamespace::s_slotTypeComponentTypeMapping (ShipChassisSlotType.cpp) + // ship_chassis_slot_type (base_class.java) + // ship_chassis_slot_type::names (base_class.java) + const int s_slotTypeComponentTypeMapping [static_cast(ShipChassisSlotType::SCST_num_types)] = + { + static_cast(ShipComponentType::SCT_reactor), // SCST_reactor + static_cast(ShipComponentType::SCT_engine), // SCST_engine + static_cast(ShipComponentType::SCT_shield), // SCST_shield_0 + static_cast(ShipComponentType::SCT_shield), // SCST_shield_1 + static_cast(ShipComponentType::SCT_armor), // SCST_armor_0 + static_cast(ShipComponentType::SCT_armor), // SCST_armor_1 + static_cast(ShipComponentType::SCT_capacitor), // SCST_capacitor + static_cast(ShipComponentType::SCT_booster), // SCST_booster + static_cast(ShipComponentType::SCT_droid_interface), // SCST_droid_interface + static_cast(ShipComponentType::SCT_bridge), // SCST_bridge + static_cast(ShipComponentType::SCT_hangar), // SCST_hangar + static_cast(ShipComponentType::SCT_targeting_station),// SCST_targeting_station + static_cast(ShipComponentType::SCT_cargo_hold), // SCST_cargo_hold + static_cast(ShipComponentType::SCT_modification), // SCST_modification_0 + static_cast(ShipComponentType::SCT_modification), // SCST_modification_1 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_0 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_1 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_2 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_3 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_4 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_5 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_6 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_7 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_8 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_9 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_10 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_11 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_12 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_13 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_14 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_15 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_16 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_17 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_18 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_19 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_20 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_21 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_22 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_23 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_24 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_25 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_26 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_27 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_28 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_29 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_30 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_31 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_32 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_33 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_34 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_35 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_36 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_37 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_38 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_39 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_40 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_41 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_42 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_43 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_44 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_45 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_46 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_47 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_48 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_49 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_50 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_51 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_52 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_53 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_54 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_55 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_56 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_57 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_58 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_59 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_60 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_61 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_62 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_63 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_64 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_65 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_66 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_67 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_68 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_69 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_70 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_71 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_72 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_73 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_74 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_75 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_76 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_77 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_78 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_79 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_80 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_81 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_82 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_83 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_84 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_85 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_86 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_87 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_88 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_89 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_90 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_91 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_92 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_93 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_94 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_95 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_96 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_97 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_98 + static_cast(ShipComponentType::SCT_weapon), // SCST_weapon_99 + }; + + typedef stdhash_map::fwd SlotNameTypeMap; + SlotNameTypeMap s_slotNameTypeMap; + + bool s_installed = false; + + void install () + { + if (s_installed) + return; + + s_installed = true; + + for (int i = 0; i < static_cast(ShipChassisSlotType::SCST_num_types); ++i) + { + IGNORE_RETURN (s_slotNameTypeMap.insert (std::make_pair (s_slotTypeNames [i], static_cast(i)))); + + s_slotTypeShortNames [i] = StringId("space/scst_short_n", s_slotTypeNames [i]).localize(); + } + } +} + +using namespace ShipChassisSlotTypeNamespace; + +//---------------------------------------------------------------------- + +std::string const & ShipChassisSlotType::getNameFromType (Type type) +{ //lint !e1929 // ref + if (!s_installed) + install (); + + const int i_type = static_cast(type); + + if (i_type < SCST_first || i_type > SCST_num_types) + { + static const std::string empty; + return empty; + } + + return s_slotTypeNames [i_type]; +} + +//---------------------------------------------------------------------- + +ShipChassisSlotType::Type ShipChassisSlotType::getTypeFromName (std::string const & name) +{ + if (!s_installed) + install (); + + const SlotNameTypeMap::const_iterator it = s_slotNameTypeMap.find (name); + if (it != s_slotNameTypeMap.end ()) + return (*it).second; + + return SCST_num_types; +} + +//---------------------------------------------------------------------- + +int ShipChassisSlotType::getComponentTypeForSlot (ShipChassisSlotType::Type slotType) +{ + if (slotType == static_cast(ShipChassisSlotType::SCST_num_types)) + return static_cast(ShipChassisSlotType::SCST_num_types); + + return static_cast(s_slotTypeComponentTypeMapping [static_cast(slotType)]); +} + +//---------------------------------------------------------------------- + +Unicode::String const & ShipChassisSlotType::getShortNameFromType (Type type) +{ + if (!s_installed) + install (); + + if (type < SCST_first || type >= SCST_num_types) + { + return Unicode::emptyString; + } + + return s_slotTypeShortNames[type]; +} + +//---------------------------------------------------------------------- + +bool ShipChassisSlotType::isWeaponChassisSlot(Type const type) +{ + return ((type >= ShipChassisSlotType::SCST_weapon_first) && (type <= ShipChassisSlotType::SCST_weapon_last)); +} + +//---------------------------------------------------------------------- + +int ShipChassisSlotType::getWeaponIndex(Type const type) +{ + DEBUG_FATAL(!isWeaponChassisSlot(type), ("Non-weapon chassis slot specified(%s)", getNameFromType(type).c_str())); + + return static_cast(type - ShipChassisSlotType::SCST_weapon_first); +} + +//---------------------------------------------------------------------- + +bool ShipChassisSlotType::isWeaponIndex(int const index) +{ + return (index >= 0) && (index < cms_numWeaponIndices); +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipChassisSlotType.h b/engine/shared/library/sharedGame/src/shared/space/ShipChassisSlotType.h new file mode 100644 index 00000000..2f6f67cc --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipChassisSlotType.h @@ -0,0 +1,161 @@ +//====================================================================== +// +// ShipChassisSlotType.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ShipChassisSlotType_H +#define INCLUDED_ShipChassisSlotType_H + +//====================================================================== + +namespace ShipChassisSlotType +{ + // The following must be kept in sync: + // scst_short_n.stf + // ShipChassisSlotType::Type (ShipChassisSlotType.h) + // ShipChassisSlotTypeNamespace::s_slotTypeNames (ShipChassisSlotType.cpp) + // ShipChassisSlotTypeNamespace::s_slotTypeComponentTypeMapping (ShipChassisSlotType.cpp) + // ship_chassis_slot_type (base_class.java) + // ship_chassis_slot_type::names (base_class.java) + enum Type + { + SCST_first, + SCST_reactor = SCST_first, + SCST_engine, + SCST_shield_0, + SCST_shield_1, + SCST_armor_0, + SCST_armor_1, + SCST_capacitor, + SCST_booster, + SCST_droid_interface, + SCST_bridge, + SCST_hangar, + SCST_targeting_station, + SCST_cargo_hold, + SCST_modification_0, + SCST_modification_1, + SCST_weapon_first, + SCST_weapon_0 = SCST_weapon_first, + SCST_weapon_1, + SCST_weapon_2, + SCST_weapon_3, + SCST_weapon_4, + SCST_weapon_5, + SCST_weapon_6, + SCST_weapon_7, + SCST_num_explicit_types, + SCST_weapon_8 = SCST_num_explicit_types, + SCST_weapon_9, + SCST_weapon_10, + SCST_weapon_11, + SCST_weapon_12, + SCST_weapon_13, + SCST_weapon_14, + SCST_weapon_15, + SCST_weapon_16, + SCST_weapon_17, + SCST_weapon_18, + SCST_weapon_19, + SCST_weapon_20, + SCST_weapon_21, + SCST_weapon_22, + SCST_weapon_23, + SCST_weapon_24, + SCST_weapon_25, + SCST_weapon_26, + SCST_weapon_27, + SCST_weapon_28, + SCST_weapon_29, + SCST_weapon_30, + SCST_weapon_31, + SCST_weapon_32, + SCST_weapon_33, + SCST_weapon_34, + SCST_weapon_35, + SCST_weapon_36, + SCST_weapon_37, + SCST_weapon_38, + SCST_weapon_39, + SCST_weapon_40, + SCST_weapon_41, + SCST_weapon_42, + SCST_weapon_43, + SCST_weapon_44, + SCST_weapon_45, + SCST_weapon_46, + SCST_weapon_47, + SCST_weapon_48, + SCST_weapon_49, + SCST_weapon_50, + SCST_weapon_51, + SCST_weapon_52, + SCST_weapon_53, + SCST_weapon_54, + SCST_weapon_55, + SCST_weapon_56, + SCST_weapon_57, + SCST_weapon_58, + SCST_weapon_59, + SCST_weapon_60, + SCST_weapon_61, + SCST_weapon_62, + SCST_weapon_63, + SCST_weapon_64, + SCST_weapon_65, + SCST_weapon_66, + SCST_weapon_67, + SCST_weapon_68, + SCST_weapon_69, + SCST_weapon_70, + SCST_weapon_71, + SCST_weapon_72, + SCST_weapon_73, + SCST_weapon_74, + SCST_weapon_75, + SCST_weapon_76, + SCST_weapon_77, + SCST_weapon_78, + SCST_weapon_79, + SCST_weapon_80, + SCST_weapon_81, + SCST_weapon_82, + SCST_weapon_83, + SCST_weapon_84, + SCST_weapon_85, + SCST_weapon_86, + SCST_weapon_87, + SCST_weapon_88, + SCST_weapon_89, + SCST_weapon_90, + SCST_weapon_91, + SCST_weapon_92, + SCST_weapon_93, + SCST_weapon_94, + SCST_weapon_95, + SCST_weapon_96, + SCST_weapon_97, + SCST_weapon_98, + SCST_weapon_99, + SCST_weapon_last = SCST_weapon_99, + SCST_num_types, + SCST_invalid = SCST_num_types + }; + + int const cms_numWeaponIndices = (static_cast(SCST_weapon_last) - static_cast(SCST_weapon_0)) + 1; + int const cms_numExplicitWeaponIndices = (static_cast(SCST_num_explicit_types) - static_cast(SCST_weapon_0)) + 1; + + std::string const & getNameFromType (Type type); + Unicode::String const & getShortNameFromType (Type type); + Type getTypeFromName (std::string const & name); + int getComponentTypeForSlot (Type slotType); + bool isWeaponChassisSlot(Type const type); + bool isWeaponIndex(int const index); + int getWeaponIndex(Type const type); +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipChassisWritable.cpp b/engine/shared/library/sharedGame/src/shared/space/ShipChassisWritable.cpp new file mode 100644 index 00000000..cfc58a90 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipChassisWritable.cpp @@ -0,0 +1,166 @@ +//====================================================================== +// +// ShipChassisWritable.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipChassisWritable.h" + +#include "sharedGame/ShipChassisSlot.h" +#include "sharedMessageDispatch/Transceiver.h" + +//====================================================================== + +namespace ShipChassisWritableNamespace +{ + namespace Transceivers + { + MessageDispatch::Transceiver chassisListChanged; + MessageDispatch::Transceiver chassisChanged; + } +} + +using namespace ShipChassisWritableNamespace; + +//---------------------------------------------------------------------- + +ShipChassisWritable::ShipChassisWritable() : +ShipChassis() +{ +} + +//---------------------------------------------------------------------- + +ShipChassisWritable::ShipChassisWritable(ShipChassis const & rhs, std::string const & name) : +ShipChassis(rhs) +{ + IGNORE_RETURN(ShipChassis::setName(PersistentCrcString(name.c_str(), true))); +} + +//---------------------------------------------------------------------- + +ShipChassisWritable::~ShipChassisWritable() +{ +} + +//---------------------------------------------------------------------- + +bool ShipChassisWritable::setName(CrcString const & name) +{ + if (ShipChassis::setName(name)) + { + if (NULL != findShipChassisByCrc(name.getCrc())) + Transceivers::chassisListChanged.emitMessage(true); + return true; + } + return false; +} + +//---------------------------------------------------------------------- + +void ShipChassisWritable::addSlot(ShipChassisSlot const & slot) +{ + ShipChassis::addSlot(slot); + notifyChanged(); +} + +//---------------------------------------------------------------------- + +void ShipChassisWritable::setSlotTargetable(int chassisSlotType, bool targetable) +{ + ShipChassisSlot * const chassisSlot = getSlot(static_cast(chassisSlotType)); + + if (NULL == chassisSlot) + { + WARNING(true, ("ShipChassisWritable::setSlotTargetable() invalid slot")); + } + else + chassisSlot->setTargetable(targetable); + + ShipChassis::setSlotTargetable(chassisSlotType, targetable); + notifyChanged(); +} + +//---------------------------------------------------------------------- + +void ShipChassisWritable::setFlybySound(std::string const & flybySound) +{ + ShipChassis::setFlybySound(flybySound); + notifyChanged(); +} + +//---------------------------------------------------------------------- + +ShipChassisSlot * ShipChassisWritable::getSlot(ShipChassisSlotType::Type shipChassisSlotType) +{ + return ShipChassis::getSlot(shipChassisSlotType); +} + +//---------------------------------------------------------------------- + +bool ShipChassisWritable::addChassis(bool doSort) +{ + if (ShipChassis::addChassis(doSort)) + { + Transceivers::chassisListChanged.emitMessage(true); + return true; + } + + return false; +} + +//---------------------------------------------------------------------- + +bool ShipChassisWritable::removeChassis() +{ + if (ShipChassis::removeChassis()) + { + Transceivers::chassisListChanged.emitMessage(true); + return true; + } + return false; +} + +//---------------------------------------------------------------------- + +bool ShipChassisWritable::canAcceptComponent(ShipComponentDescriptor const & shipComponentDescriptor) const +{ + SlotVector const & sv = getSlots(); + + for (SlotVector::const_iterator it = sv.begin(); it != sv.end(); ++it) + { + ShipChassisSlot const & shipSlot = *it; + + if (shipSlot.canAcceptComponent(shipComponentDescriptor)) + return true; + } + + return false; +} + +//---------------------------------------------------------------------- + +void ShipChassisWritable::notifyChanged() const +{ + Transceivers::chassisChanged.emitMessage(*this); +} + +//---------------------------------------------------------------------- + +void ShipChassisWritable::setWingOpenSpeedFactor(float const wingOpenSpeedFactor) +{ + ShipChassis::setWingOpenSpeedFactor(wingOpenSpeedFactor); + notifyChanged(); +} + +//---------------------------------------------------------------------- + +void ShipChassisWritable::setHitSoundGroup(std::string const & hitSoundGroup) +{ + ShipChassis::setHitSoundGroup(hitSoundGroup); + notifyChanged(); +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipChassisWritable.h b/engine/shared/library/sharedGame/src/shared/space/ShipChassisWritable.h new file mode 100644 index 00000000..140b71b9 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipChassisWritable.h @@ -0,0 +1,58 @@ +//====================================================================== +// +// ShipChassisWritable.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ShipChassisWritable_H +#define INCLUDED_ShipChassisWritable_H + +#include "sharedGame/ShipChassis.h" + +class ShipComponentDescriptor; + +//====================================================================== + +class ShipChassisWritable : public ShipChassis +{ +public: + + class Messages + { + public: + struct ChassisListChanged; + struct ChassisChanged + { + typedef ShipChassisWritable Payload; + }; + }; + + ShipChassisWritable(); + ShipChassisWritable(ShipChassis const & rhs, std::string const & name); + + virtual ~ShipChassisWritable(); + + virtual bool setName(CrcString const & name); + virtual void addSlot(ShipChassisSlot const & slot); + virtual void setSlotTargetable(int chassisSlot, bool targetable); + virtual void setFlybySound(std::string const & flybySound); + virtual void setWingOpenSpeedFactor(float wingOpenSpeedFactor); + ShipChassisSlot * getSlot(ShipChassisSlotType::Type shipChassisSlotType); + + virtual bool addChassis(bool doSort); + virtual bool removeChassis(); + + bool canAcceptComponent(ShipComponentDescriptor const & shipComponentDescriptor) const; + void notifyChanged() const; + void setHitSoundGroup(std::string const & hitSoundGroup); + +private: + + ShipChassisWritable(ShipChassisWritable const & rhs); + ShipChassisWritable& operator=(ShipChassisWritable const & rhs); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipComponentAttachmentManager.cpp b/engine/shared/library/sharedGame/src/shared/space/ShipComponentAttachmentManager.cpp new file mode 100644 index 00000000..14897909 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipComponentAttachmentManager.cpp @@ -0,0 +1,704 @@ +//====================================================================== +// +// ShipComponentAttachmentManager.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipComponentAttachmentManager.h" + +#include "UnicodeUtils.h" +#include "sharedDebug/InstallTimer.h" +#include "fileInterface/StdioFile.h" +#include "sharedFile/Iff.h" +#include "sharedFoundation/ConstCharCrcString.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/PersistentCrcString.h" +#include "sharedFoundation/TemporaryCrcString.h" +#include "sharedGame/ShipChassis.h" +#include "sharedGame/ShipChassisSlotType.h" +#include "sharedGame/ShipComponentDescriptor.h" +#include "sharedMessageDispatch/Transceiver.h" +#include "sharedObject/ObjectTemplateList.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableWriter.h" +#include +#include + +//lint -e1925 //public data member + +//====================================================================== + +namespace ShipComponentAttachmentManagerNamespace +{ + namespace Transceivers + { + MessageDispatch::Transceiver attachmentsChanged; + } + + typedef ShipComponentAttachmentManager::TemplateHardpointPairVector TemplateHardpointPairVector; + typedef ShipComponentAttachmentManager::HardpointVector HardpointVector; + + class AttachmentKey + { + public: + uint32 chassisCrc; + uint32 componentCrc; + int chassisSlotType; + + AttachmentKey () : + chassisCrc (0), + componentCrc (0), + chassisSlotType (0) + { + } + + AttachmentKey (uint32 _chassisCrc, uint32 _componentCrc, int _chassisSlotType) : + chassisCrc (_chassisCrc), + componentCrc (_componentCrc), + chassisSlotType (_chassisSlotType) + { + } + + bool operator< (AttachmentKey const & other) const + { + if (chassisCrc < other.chassisCrc) + return true; + + if (chassisCrc == other.chassisCrc) + { + if (componentCrc < other.componentCrc) + return true; + + if (componentCrc == other.componentCrc) + return chassisSlotType < other.chassisSlotType; + } + + return false; + } + }; + + typedef stdmap::fwd AttachmentMap; + AttachmentMap * s_attachmentMap; + + typedef std::map ComponentHitRangeMap; + ComponentHitRangeMap * s_componentHitRangeMap; + + typedef std::map ExtraHardpointsMap; + ExtraHardpointsMap * s_extraHardpointsMap; + + std::string s_attachmentTemplatePrefix = "object/tangible/ship/attachment/"; + bool s_installed = false; +} + +using namespace ShipComponentAttachmentManagerNamespace; + +//---------------------------------------------------------------------- + +void ShipComponentAttachmentManager::install () +{ + InstallTimer const installTimer("ShipComponentAttachmentManager::install "); + + DEBUG_FATAL (s_installed, ("already installed")); + if (s_installed) + return; + + s_attachmentMap = new AttachmentMap; + s_componentHitRangeMap = new ComponentHitRangeMap; + s_extraHardpointsMap = new ExtraHardpointsMap; + + load(); + + ExitChain::add (ShipComponentAttachmentManager::remove, "ShipComponentAttachmentManager::remove"); + s_installed = true; +} + +//---------------------------------------------------------------------- + +void ShipComponentAttachmentManager::remove () +{ + DEBUG_FATAL (!s_installed, ("not installed")); + + delete s_attachmentMap; + s_attachmentMap = 0; + + delete s_componentHitRangeMap; + s_componentHitRangeMap = 0; + + delete s_extraHardpointsMap; + s_extraHardpointsMap = 0; + + s_installed = false; +} + +//---------------------------------------------------------------------- + +void ShipComponentAttachmentManager::load() +{ + ShipChassis::PersistentCrcStringVector const & shipChassisNames = ShipChassis::getShipChassisCrcVector (); + + for (ShipChassis::PersistentCrcStringVector::const_iterator it = shipChassisNames.begin (); it != shipChassisNames.end (); ++it) + { + PersistentCrcString const & name = *(*it); + + std::string const & chassis_filename = std::string ("datatables/space/ship_chassis_") + std::string (name.getString ()) + std::string (".iff"); + + Iff iff; + + if (!iff.open (chassis_filename.c_str (), true)) + continue; + + DataTable dt; + dt.load (iff); + iff.close (); + + const int numRows = dt.getNumRows (); + + for (int row = 0; row < numRows; ++row) + { + std::string const & componentName = dt.getStringValue (0, row); + if (componentName.empty()) + continue; + + ShipComponentDescriptor const * const shipComponentDescriptor = + ShipComponentDescriptor::findShipComponentDescriptorByName (TemporaryCrcString (componentName.c_str (), true)); + + if (shipComponentDescriptor == NULL) + { + WARNING (true, ("ShipComponentAttachmentManager chassis [%s] specified invalid component [%s] at row [%d] in file [%s]", name.getString (), componentName.c_str (), row, chassis_filename.c_str())); + continue; + } + + for (int slotTypeIndex = 0; slotTypeIndex < static_cast(ShipChassisSlotType::SCST_num_types); ++slotTypeIndex) + { + std::string const & slotName = ShipChassisSlotType::getNameFromType (static_cast(slotTypeIndex)); + if (!dt.doesColumnExist (slotName)) + continue; + + std::string const & attachments = dt.getStringValue (slotName, row); + if (attachments.empty ()) + continue; + + ShipComponentType::Type const componentType = + static_cast(ShipChassisSlotType::getComponentTypeForSlot (static_cast(slotTypeIndex))); + std::string const & componentTypeName = ShipComponentType::getNameFromType (componentType); + + TemplateHardpointPairVector thpv; + HardpointVector extraHardpoints; + + size_t pos = 0; + std::string attachmentToken; + while (pos != std::string::npos && Unicode::getFirstToken (attachments, pos, pos, attachmentToken, ",")) //lint !e650 !e737 //stupid msvc + { + Unicode::trim (attachmentToken); + + if (pos != std::string::npos) //lint !e650 !e737 //stupid msvc + ++pos; + + if (attachmentToken.empty ()) + continue; + + size_t colonPos = attachmentToken.find (':'); + + if (colonPos == std::string::npos) //lint !e650 !e737 //stupid msvc + { + // Component specifies a hardpoint that will be used for targetting only, but no object to attach + extraHardpoints.push_back(PersistentCrcString(attachmentToken.c_str(), true)); + } + else + { + std::string const & objectTemplateName = + s_attachmentTemplatePrefix + componentTypeName + std::string ("/shared_") + attachmentToken.substr (0, colonPos) + std::string (".iff"); + CrcString const & objectTemplateCrcString = ObjectTemplateList::lookUp(objectTemplateName.c_str ()); + if (objectTemplateCrcString.getCrc () == 0) + { + WARNING (true, ("ShipComponentAttachmentManager chassis [%s] specified invalid object template [%s (%s)] for component [%s] slot [%s]", + name.getString (), objectTemplateName.c_str (), attachmentToken.c_str (), componentName.c_str (), slotName.c_str ())); + } + + std::string const & hardpointName = attachmentToken.substr (colonPos + 1); + + TemplateHardpointPair const thp (objectTemplateCrcString.getCrc (), PersistentCrcString (hardpointName.c_str (), true)); + thpv.push_back (thp); + } + } + + AttachmentKey const attachmentKey (name.getCrc (), shipComponentDescriptor->getCrc (), slotTypeIndex); + IGNORE_RETURN (s_attachmentMap->insert (std::make_pair (attachmentKey, thpv))); + if (!extraHardpoints.empty()) + IGNORE_RETURN (s_extraHardpointsMap->insert (std::make_pair (attachmentKey, extraHardpoints))); + + if (dt.doesColumnExist("hit_range")) + { + float hitRange = dt.getFloatValue("hit_range",row); + if (hitRange != 0) + IGNORE_RETURN(s_componentHitRangeMap->insert(std::make_pair (attachmentKey, hitRange))); + } + } + } + } +} + +//---------------------------------------------------------------------- + +bool ShipComponentAttachmentManager::save(std::string const & dsrcPath, std::string const & dataPath) +{ + bool retval = true; + + ShipChassis::PersistentCrcStringVector const & shipChassisNames = ShipChassis::getShipChassisCrcVector (); + + for (ShipChassis::PersistentCrcStringVector::const_iterator it = shipChassisNames.begin (); it != shipChassisNames.end (); ++it) + { + PersistentCrcString const & chassisName = *(*it); + + std::string const & chassisFilenameTab = dsrcPath + "/datatables/space/ship_chassis_" + chassisName.getString () + ".tab"; + std::string const & chassisFilenameIff = dataPath + "/datatables/space/ship_chassis_" + chassisName.getString () + ".iff"; + + retval = saveChassisInfo(chassisName.getString(), chassisFilenameTab, chassisFilenameIff) && retval; + } + + return retval; +} + +//---------------------------------------------------------------------- + +bool ShipComponentAttachmentManager::saveChassisInfo(std::string const & chassisName, std::string const & filenameTab, std::string const & filenameIff) +{ + ShipChassis const * const chassis = ShipChassis::findShipChassisByName(ConstCharCrcString(chassisName.c_str())); + if (NULL == chassis) + return false; + + uint32 const chassisCrc = chassis->getCrc(); + ShipComponentDescriptor::StringVector const & componentNames = ShipComponentDescriptor::getComponentDescriptorNames(); + + bool columnPresent[ShipChassisSlotType::SCST_num_types]; + + { + for (int chassisSlotType = 0; chassisSlotType < static_cast(ShipChassisSlotType::SCST_num_types); ++chassisSlotType) + columnPresent[chassisSlotType] = false; + + for (ShipComponentDescriptor::StringVector::const_iterator it = componentNames.begin(); it != componentNames.end(); ++it) + { + std::string const & componentName = *it; + ShipComponentDescriptor const * const shipComponentDescriptor = ShipComponentDescriptor::findShipComponentDescriptorByName(ConstCharCrcString(componentName.c_str())); + + if (NULL == shipComponentDescriptor) + return false; + + uint32 const componentCrc = shipComponentDescriptor->getCrc(); + + for (int chassisSlotType = 0; chassisSlotType < static_cast(ShipChassisSlotType::SCST_num_types); ++chassisSlotType) + if (!ShipComponentAttachmentManager::getAttachmentsForShip(chassisCrc, componentCrc, chassisSlotType).empty()) + columnPresent[chassisSlotType] = true; + } + } + + //-- TAB HEADER COLNAMES + std::string tabStr("component"); + + { + for (int chassisSlotType = 0; chassisSlotType < static_cast(ShipChassisSlotType::SCST_num_types); ++chassisSlotType) + { + if (columnPresent[chassisSlotType]) + { + std::string const & slotName = ShipChassisSlotType::getNameFromType(static_cast(chassisSlotType)); + tabStr.push_back('\t'); + tabStr += slotName; + } + } + } + + tabStr.push_back('\n'); + + //-- TAB HEADER COLTYPES + tabStr += "s"; + + { + for (int chassisSlotType = 0; chassisSlotType < static_cast(ShipChassisSlotType::SCST_num_types); ++chassisSlotType) + { + if (columnPresent[chassisSlotType]) + { + tabStr += "\ts"; + } + } + } + + tabStr.push_back('\n'); + + //-- TAB DATA ROWS + + for (ShipComponentDescriptor::StringVector::const_iterator it = componentNames.begin(); it != componentNames.end(); ++it) + { + std::string const & componentName = *it; + ShipComponentDescriptor const * const shipComponentDescriptor = ShipComponentDescriptor::findShipComponentDescriptorByName(ConstCharCrcString(componentName.c_str())); + + if (NULL == shipComponentDescriptor) + return false; + + uint32 const componentCrc = shipComponentDescriptor->getCrc(); + + bool showThisRow = false; + + { + for (int chassisSlotType = 0; chassisSlotType < static_cast(ShipChassisSlotType::SCST_num_types); ++chassisSlotType) + { + TemplateHardpointPairVector const & thpv = ShipComponentAttachmentManager::getAttachmentsForShip (chassisCrc, componentCrc, chassisSlotType); + if (!thpv.empty()) + { + showThisRow = true; + break; + } + } + } + + if (!showThisRow) + continue; + + tabStr += shipComponentDescriptor->getName().getString(); + + for (int chassisSlotType = 0; chassisSlotType < static_cast(ShipChassisSlotType::SCST_num_types); ++chassisSlotType) + { + if (!columnPresent[chassisSlotType]) + continue; + + TemplateHardpointPairVector const & thpv = ShipComponentAttachmentManager::getAttachmentsForShip (chassisCrc, componentCrc, chassisSlotType); + + tabStr.push_back('\t'); + + bool firstThp = true; + for (TemplateHardpointPairVector::const_iterator tit = thpv.begin(); tit != thpv.end(); ++tit) + { + TemplateHardpointPair const & thp = *tit; + uint32 const templateCrc = thp.first; + PersistentCrcString const & hardpointName = thp.second; + + if (!firstThp) + tabStr.push_back(','); + + CrcString const & templateName = ObjectTemplateList::lookUp(templateCrc); + + std::string templateNameStr(templateName.getString()); + + if (templateNameStr.empty()) + { + WARNING(true, ("ShipComponentAttachmentManager::save could not resolve template crc [%d]", static_cast(templateCrc))); + continue; + } + + firstThp = false; + + std::string const & componentTypeName = + ShipComponentType::getNameFromType( + static_cast( + ShipChassisSlotType::getComponentTypeForSlot( + static_cast(chassisSlotType)))); + + std::string const & attachmentTemplatePrefix = s_attachmentTemplatePrefix + componentTypeName + std::string ("/shared_"); + + if (0 != templateNameStr.find(attachmentTemplatePrefix)) + { + WARNING(true, ("Malformed template [%s], should start with [%s]", templateNameStr.c_str(), attachmentTemplatePrefix.c_str())); + return false; + } + + IGNORE_RETURN(templateNameStr.erase(0, attachmentTemplatePrefix.size())); + + if (templateNameStr.size() <= 4 || (templateNameStr.find(".iff") != templateNameStr.size() - 4)) + { + WARNING(true, ("Malformed template [%s], should end with [.iff]", templateNameStr.c_str())); + return false; + } + + IGNORE_RETURN(templateNameStr.erase(templateNameStr.size() - 4, 4)); + + tabStr += templateNameStr.c_str(); + tabStr.push_back(':'); + tabStr += hardpointName.getString(); + } + } + + tabStr.push_back('\n'); + } + + tabStr.push_back('\n'); + + bool retval = false; + + StdioFileFactory sff; + AbstractFile * const af = sff.createFile(filenameTab.c_str(), "wb"); + if (NULL != af && af->isOpen()) + { + int const bytesWritten = af->write(static_cast(tabStr.size()), tabStr.c_str()); + retval = (bytesWritten == static_cast(tabStr.size())); + } + else + { + WARNING(true, ("ShipComponentDescriptor failed to write file [%s]", filenameTab.c_str())); + } + delete af; + + if (!retval) + return false; + + DataTableWriter dtw; + dtw.loadFromSpreadsheet(filenameTab.c_str()); + if (!dtw.save(filenameIff.c_str(), true)) + { + WARNING(true, ("ShipComponentAttachmentManager failed to compile file [%s] to [%s]", filenameIff.c_str())); + return false; + } + + return true; +} + +//---------------------------------------------------------------------- + +ShipComponentAttachmentManager::TemplateHardpointPairVector const & ShipComponentAttachmentManager::getAttachmentsForShip(uint32 chassisCrc, uint32 componentCrc, int chassisSlotType) +{ + DEBUG_FATAL (!s_installed, ("not installed")); + + AttachmentMap::const_iterator const it = s_attachmentMap->find (AttachmentKey (chassisCrc, componentCrc, chassisSlotType)); + if (it != s_attachmentMap->end ()) + return (*it).second; + + AttachmentKey const emptyAttachmentKey (0, 0, 0); + return (*s_attachmentMap) [emptyAttachmentKey]; +} + +//---------------------------------------------------------------------- + +/** +* @param thpVectors is an array of length ShipChassisSlotType::SCST_num_types +*/ + +bool ShipComponentAttachmentManager::getAttachmentsForShip(uint32 chassisCrc, uint32 componentCrc, TemplateHardpointPairVector const ** thpVectors) +{ + bool found = false; + + for (int i = 0; i < static_cast(ShipChassisSlotType::SCST_num_types); ++i) + { + AttachmentMap::const_iterator const it = s_attachmentMap->find (AttachmentKey (chassisCrc, componentCrc, i)); + if (it != s_attachmentMap->end ()) + { + TemplateHardpointPairVector const & thpv = (*it).second; + if (thpv.empty()) + { + thpVectors[i] = NULL; + } + else + { + thpVectors[i] = &thpv; + found = true; + } + } + else + thpVectors[i] = NULL; + } + + return found; +} + +// ---------------------------------------------------------------------- + +/** + * Given the a ship, component, and chassis slot type, find any "extra" + * hardpoints for that component. An extra hardpoint is a hardpoint that + * has no object attached to it, but represents the location of that component. + * It is used for figuring out which component to damage based on collision + * location, etc. + */ +ShipComponentAttachmentManager::HardpointVector const & ShipComponentAttachmentManager::getExtraHardpointsForComponent (uint32 const chassisCrc, uint32 const componentCrc, int const chassisSlotType) +{ + DEBUG_FATAL (!s_installed, ("not installed")); + + static const HardpointVector emptyHardpointVector; + + ExtraHardpointsMap::const_iterator const it = s_extraHardpointsMap->find (AttachmentKey (chassisCrc, componentCrc, chassisSlotType)); + if (it != s_extraHardpointsMap->end()) + return (*it).second; + else + return emptyHardpointVector; +} + +// ---------------------------------------------------------------------- + +float ShipComponentAttachmentManager::getComponentHitRange (uint32 chassisCrc, uint32 componentCrc, int chassisSlotType) +{ + DEBUG_FATAL (!s_installed, ("not installed")); + + ComponentHitRangeMap::const_iterator const it = s_componentHitRangeMap->find (AttachmentKey (chassisCrc, componentCrc, chassisSlotType)); + if (it != s_componentHitRangeMap->end ()) + return (*it).second; + + return -1.0f; +} + +//---------------------------------------------------------------------- +//-- EDITOR methods +//---------------------------------------------------------------------- + +void ShipComponentAttachmentManager::setAttachmentsForShip(uint32 chassisCrc, uint32 componentCrc, int chassisSlotType, TemplateHardpointPairVector const & attachments) +{ + AttachmentKey const key(chassisCrc, componentCrc, chassisSlotType); + IGNORE_RETURN(s_attachmentMap->erase(key)); + if (!attachments.empty()) + IGNORE_RETURN(s_attachmentMap->insert(std::make_pair(key, attachments))); + + Transceivers::attachmentsChanged.emitMessage(Messages::AttachmentsChanged::Payload(chassisCrc, std::make_pair(componentCrc, chassisSlotType))); +} + +//---------------------------------------------------------------------- + +std::string const & ShipComponentAttachmentManager::getAttachmentTemplatePrefix() +{ + return s_attachmentTemplatePrefix; +} + +//---------------------------------------------------------------------- + +/** +* @param newChassisCrc zero to delete a component +*/ + +void ShipComponentAttachmentManager::udpateComponentCrc(uint32 const oldComponentCrc, uint32 const newComponentCrc) +{ + if (oldComponentCrc == newComponentCrc) + return; + + for (AttachmentMap::iterator it = s_attachmentMap->begin(); it != s_attachmentMap->end(); ) + { + //-- keep a copy of this for later + AttachmentKey const oldKey = (*it).first; + + if (oldKey.componentCrc == oldComponentCrc) + { + //-- change the key by replacing it + AttachmentKey const newKey(oldKey.chassisCrc, newComponentCrc, oldKey.chassisSlotType); + + //-- change to zero crc is a deletion of this component + if (0 != newKey.componentCrc) + (*s_attachmentMap)[newKey] = (*it).second; + + s_attachmentMap->erase(it++); + + Transceivers::attachmentsChanged.emitMessage(Messages::AttachmentsChanged::Payload(newKey.chassisCrc, std::make_pair(oldKey.componentCrc, newKey.chassisSlotType))); + + if (0 != newKey.componentCrc) + Transceivers::attachmentsChanged.emitMessage(Messages::AttachmentsChanged::Payload(newKey.chassisCrc, std::make_pair(newKey.componentCrc, newKey.chassisSlotType))); + + continue; + } + + ++it; + } +} + +//---------------------------------------------------------------------- + +/** +* @param newChassisCrc zero to delete a chassis +*/ + +void ShipComponentAttachmentManager::udpateChassisCrc(uint32 const oldChassisCrc, uint32 const newChassisCrc) +{ + if (oldChassisCrc == newChassisCrc) + return; + + for (AttachmentMap::iterator it = s_attachmentMap->begin(); it != s_attachmentMap->end(); ) + { + //-- keep a copy of this for later + AttachmentKey const oldKey = (*it).first; + + if (oldKey.chassisCrc == oldChassisCrc) + { + //-- change the key by replacing it + AttachmentKey const newKey(newChassisCrc, oldKey.componentCrc, oldKey.chassisSlotType); + + //-- change to zero crc is a deletion of this chassis + if (0 != newKey.chassisCrc) + (*s_attachmentMap)[newKey] = (*it).second; + + s_attachmentMap->erase(it++); + + Transceivers::attachmentsChanged.emitMessage(Messages::AttachmentsChanged::Payload(oldKey.chassisCrc, std::make_pair(newKey.componentCrc, newKey.chassisSlotType))); + + if (0 != newKey.chassisCrc) + Transceivers::attachmentsChanged.emitMessage(Messages::AttachmentsChanged::Payload(newKey.chassisCrc, std::make_pair(newKey.componentCrc, newKey.chassisSlotType))); + + continue; + } + + ++it; + } +} + +//---------------------------------------------------------------------- + +void ShipComponentAttachmentManager::copyAttachmentsForComponent(uint32 const oldComponentCrc, uint32 const newComponentCrc) +{ + if (oldComponentCrc == newComponentCrc) + { + WARNING(true, ("ShipComponentAttachmentManager::copyAttachmentsForComponent() cannot copy from self")); + return; + } + + if (0 == oldComponentCrc || 0 == newComponentCrc) + { + WARNING(true, ("ShipComponentAttachmentManager::copyAttachmentsForComponent() cannot copy from/to zero")); + return; + } + + for (AttachmentMap::iterator it = s_attachmentMap->begin(); it != s_attachmentMap->end(); ++it) + { + //-- keep a copy of this for later + AttachmentKey const oldKey = (*it).first; + + if (oldKey.componentCrc == oldComponentCrc) + { + //-- change the key by replacing it + AttachmentKey const newKey(oldKey.chassisCrc, newComponentCrc, oldKey.chassisSlotType); + + //-- copy the attachment info into the new entry, + (*s_attachmentMap)[newKey] = (*it).second; + + Transceivers::attachmentsChanged.emitMessage(Messages::AttachmentsChanged::Payload(newKey.chassisCrc, std::make_pair(newKey.componentCrc, newKey.chassisSlotType))); + } + } +} + + +//---------------------------------------------------------------------- + +void ShipComponentAttachmentManager::copyAttachmentsForChassis(uint32 const oldChassisCrc, uint32 const newChassisCrc) +{ + if (oldChassisCrc == newChassisCrc) + { + WARNING(true, ("ShipComponentAttachmentManager::copyAttachmentsForChassis() cannot copy from self")); + return; + } + + if (0 == oldChassisCrc || 0 == newChassisCrc) + { + WARNING(true, ("ShipComponentAttachmentManager::copyAttachmentsForChassis() cannot copy from/to zero")); + return; + } + + for (AttachmentMap::iterator it = s_attachmentMap->begin(); it != s_attachmentMap->end(); ++it) + { + //-- keep a copy of this for later + AttachmentKey const oldKey = (*it).first; + + if (oldKey.chassisCrc == oldChassisCrc) + { + //-- change the key by replacing it + AttachmentKey const newKey(newChassisCrc, oldKey.componentCrc, oldKey.chassisSlotType); + + //-- copy the attachment info into the new entry, + (*s_attachmentMap)[newKey] = (*it).second; + + Transceivers::attachmentsChanged.emitMessage(Messages::AttachmentsChanged::Payload(newKey.chassisCrc, std::make_pair(newKey.componentCrc, newKey.chassisSlotType))); + } + } +} +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipComponentAttachmentManager.h b/engine/shared/library/sharedGame/src/shared/space/ShipComponentAttachmentManager.h new file mode 100644 index 00000000..0ca935dd --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipComponentAttachmentManager.h @@ -0,0 +1,59 @@ +//====================================================================== +// +// ShipComponentAttachmentManager.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ShipComponentAttachmentManager_H +#define INCLUDED_ShipComponentAttachmentManager_H + +//====================================================================== + +class PersistentCrcString; + +class ShipComponentAttachmentManager +{ +public: + + class Messages + { + public: + struct AttachmentsChanged + { + //-- chassisCrc, componentCrc, chassisSlotType + typedef std::pair > Payload; + }; + }; + + static void install (); + static void remove (); + + static void load(); + static bool save(std::string const & dsrcPath, std::string const & dataPath); + static bool saveChassisInfo(std::string const & chassisName, std::string const & chassisFilenameTab, std::string const & chassisFilenameIff); + + typedef std::pair TemplateHardpointPair; + typedef stdvector::fwd TemplateHardpointPairVector; + typedef stdvector::fwd HardpointVector; + + static TemplateHardpointPairVector const & getAttachmentsForShip (uint32 chassisCrc, uint32 componentCrc, int chassisSlotType); + static bool getAttachmentsForShip(uint32 chassisCrc, uint32 componentCrc, TemplateHardpointPairVector const ** thpVectors); + static float getComponentHitRange (uint32 chassisCrc, uint32 componentCrc, int chassisSlotType); + static HardpointVector const & getExtraHardpointsForComponent (uint32 chassisCrc, uint32 componentCrc, int chassisSlotType); + +public: + + //-- these methods are for editor use only + + static void setAttachmentsForShip(uint32 chassisCrc, uint32 componentCrc, int chassisSlotType, TemplateHardpointPairVector const & attachments); + static std::string const & getAttachmentTemplatePrefix(); + static void udpateComponentCrc(uint32 const oldComponentCrc, uint32 const newComponentCrc); + static void udpateChassisCrc(uint32 const oldChassisCrc, uint32 const newChassisCrc); + static void copyAttachmentsForComponent(uint32 const oldComponentCrc, uint32 const newComponentCrc); + static void copyAttachmentsForChassis(uint32 const oldChassisCrc, uint32 const newChassisCrc); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipComponentData.cpp b/engine/shared/library/sharedGame/src/shared/space/ShipComponentData.cpp new file mode 100644 index 00000000..78a26512 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipComponentData.cpp @@ -0,0 +1,145 @@ +//====================================================================== +// +// ShipComponentData.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipComponentData.h" + +#include "UnicodeUtils.h" +#include "sharedFoundation/DynamicVariableList.h" +#include "sharedGame/SharedObjectAttributes.h" +#include "sharedGame/ShipComponentDescriptor.h" +#include "sharedGame/ShipComponentFlags.h" +#include "sharedObject/ObjectTemplate.h" + +//====================================================================== + +namespace ShipComponentDataNamespace +{ +} + +using namespace ShipComponentDataNamespace; + +//---------------------------------------------------------------------- + +ShipComponentData::ShipComponentData (ShipComponentDescriptor const & shipComponentDescriptor) : +m_descriptor (&shipComponentDescriptor), +cm_slash (Unicode::narrowToWide("/")), +cm_shipComponentCategory ("ship_component."), +m_armorHitpointsCurrent (50.0f), +m_armorHitpointsMaximum (50.0f), +m_efficiencyGeneral (1.0f), +m_efficiencyEnergy (1.0f), +m_energyMaintenanceRequirement (0.0f), +m_mass (0.0f), +m_hitpointsCurrent (100.0f), +m_hitpointsMaximum (100.0f), +m_flags (ShipComponentFlags::F_lowPower), +m_name () +{ +} + +//---------------------------------------------------------------------- + +ShipComponentData::~ShipComponentData () +{ + m_descriptor = 0; +} + +//---------------------------------------------------------------------- + +void ShipComponentData::printDebugString (Unicode::String & result, Unicode::String const & padding) const +{ + if (m_descriptor == NULL) + return; + + char buf [2048]; + const size_t buf_size = sizeof (buf); + + std::string const & nPad = Unicode::wideToNarrow (padding); + + float oo_efficiencyEnergy = m_efficiencyEnergy; + if (oo_efficiencyEnergy > 0.0f) + oo_efficiencyEnergy = RECIP (oo_efficiencyEnergy); + + snprintf (buf, buf_size, + "%s\\#pcontrast2 Descriptor:\\#.\n" + "%s Name: %s (%s), (%s) compat:[%s]\n" + "%sArmor: %f/%f, Hitpoints: %f/%f\n" + "%sEfficiency: gen: %f, energy: %f\n" + "%sEnergy Req: %f (%f)\n" + "%sMass: %f\n" + "%sFlags: %d\n" + "%s----------\n", + nPad.c_str (), + nPad.c_str (), m_descriptor->getName ().getString (), Unicode::wideToNarrow(m_name).c_str(), + ShipComponentType::getNameFromType (m_descriptor->getComponentType ()).c_str (), + m_descriptor->getCompatibility ().getString (), + nPad.c_str (), m_armorHitpointsCurrent, m_armorHitpointsMaximum, + m_hitpointsCurrent, m_hitpointsMaximum, + nPad.c_str (), m_efficiencyGeneral, m_efficiencyEnergy, + nPad.c_str (), m_energyMaintenanceRequirement, m_energyMaintenanceRequirement * oo_efficiencyEnergy, + nPad.c_str (), m_mass, + nPad.c_str (), m_flags, + nPad.c_str ()); + + result += Unicode::narrowToWide (buf); +} + +//---------------------------------------------------------------------- + +void ShipComponentData::getAttributes(AttributeVector & data) const +{ + Unicode::String attrib; + static char buffer[128]; + static const size_t buffer_size = sizeof (buffer); + + //armor + snprintf(buffer, buffer_size, "%.1f", m_armorHitpointsCurrent); + attrib = Unicode::narrowToWide(buffer); + attrib += cm_slash; + snprintf(buffer, buffer_size, "%.1f", m_armorHitpointsMaximum); + attrib += Unicode::narrowToWide(buffer); + data.push_back(std::make_pair(cm_shipComponentCategory + SharedObjectAttributes::ship_component_armor, attrib)); + + //hitpoints + snprintf(buffer, buffer_size, "%.1f", m_hitpointsCurrent); + attrib = Unicode::narrowToWide(buffer); + attrib += cm_slash; + snprintf(buffer, buffer_size, "%.1f", m_hitpointsMaximum); + attrib += Unicode::narrowToWide(buffer); + data.push_back(std::make_pair(cm_shipComponentCategory + SharedObjectAttributes::ship_component_hitpoints, attrib)); + + //general efficiency + if(m_efficiencyGeneral < 1.0f) + { + snprintf(buffer, buffer_size, "%.1f", m_efficiencyGeneral); + attrib = Unicode::narrowToWide(buffer); + data.push_back(std::make_pair(cm_shipComponentCategory + SharedObjectAttributes::ship_component_efficiency_general, attrib)); + } + + //energy efficiency + if(m_efficiencyEnergy < 1.0f) + { + snprintf(buffer, buffer_size, "%.1f", m_efficiencyEnergy); + attrib = Unicode::narrowToWide(buffer); + data.push_back(std::make_pair(cm_shipComponentCategory + SharedObjectAttributes::ship_component_efficiency_energy, attrib)); + } + + //energy maintenance requirement + if(m_energyMaintenanceRequirement > 0.0f) + { + snprintf(buffer, buffer_size, "%.1f", m_energyMaintenanceRequirement); + attrib = Unicode::narrowToWide(buffer); + data.push_back(std::make_pair(cm_shipComponentCategory + SharedObjectAttributes::ship_component_energy_required, attrib)); + } + + //mass + snprintf(buffer, buffer_size, "%.1f", m_mass); + attrib = Unicode::narrowToWide(buffer); + data.push_back(std::make_pair(cm_shipComponentCategory + SharedObjectAttributes::ship_component_mass, attrib)); +} +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipComponentData.h b/engine/shared/library/sharedGame/src/shared/space/ShipComponentData.h new file mode 100644 index 00000000..87ee4c48 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipComponentData.h @@ -0,0 +1,76 @@ +//====================================================================== +// +// ShipComponentData.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ShipComponentData_H +#define INCLUDED_ShipComponentData_H + +//====================================================================== + +#include "sharedFoundation/NetworkId.h" + +// ====================================================================== + +class ShipComponentDescriptor; +class ShipObject; +class TangibleObject; + +//---------------------------------------------------------------------- + +class ShipComponentData +{ +public: + + typedef std::pair AttributePair; + typedef stdvector::fwd AttributeVector; + + explicit ShipComponentData (ShipComponentDescriptor const & shipComponentDescriptor); + virtual ~ShipComponentData () = 0; + + virtual bool readDataFromShip (int chassisSlot, ShipObject const & ship) = 0; + virtual void writeDataToShip (int chassisSlot, ShipObject & ship) const = 0; + virtual bool readDataFromComponent (TangibleObject const & component) = 0; + virtual void writeDataToComponent (TangibleObject & component) const = 0; + + virtual void printDebugString (Unicode::String & result, Unicode::String const & padding) const; + + virtual void getAttributes (AttributeVector & data) const; + + ShipComponentDescriptor const & getDescriptor () const; + +private: + ShipComponentData (const ShipComponentData & rhs); + ShipComponentData & operator= (const ShipComponentData & rhs); + +protected: + ShipComponentDescriptor const * m_descriptor; + Unicode::String const cm_slash; + std::string const cm_shipComponentCategory; + +public: + float m_armorHitpointsCurrent; + float m_armorHitpointsMaximum; + float m_efficiencyGeneral; + float m_efficiencyEnergy; + float m_energyMaintenanceRequirement; + float m_mass; + float m_hitpointsCurrent; + float m_hitpointsMaximum; + int m_flags; + Unicode::String m_name; + NetworkId m_creator; +}; + +//---------------------------------------------------------------------- + +inline ShipComponentDescriptor const & ShipComponentData::getDescriptor () const +{ + return *NON_NULL (m_descriptor); +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipComponentDescriptor.cpp b/engine/shared/library/sharedGame/src/shared/space/ShipComponentDescriptor.cpp new file mode 100644 index 00000000..5c3560f0 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipComponentDescriptor.cpp @@ -0,0 +1,532 @@ +//====================================================================== +// +// ShipComponentDescriptor.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipComponentDescriptor.h" + +#include "fileInterface/StdioFile.h" +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/Iff.h" +#include "sharedFoundation/ConstCharCrcString.h" +#include "sharedFoundation/Crc.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/PersistentCrcString.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedFoundation/TemporaryCrcString.h" +#include "sharedGame/ShipComponentAttachmentManager.h" +#include "sharedGame/ShipComponentDescriptorWritable.h" +#include "sharedObject/ObjectTemplate.h" +#include "sharedObject/ObjectTemplateList.h" +#include "sharedUtility/DataTable.h" +#include +#include + +//====================================================================== + +namespace ShipComponentDescriptorNamespace +{ + typedef stdmap::fwd NameComponentMap; + typedef stdmap::fwd CrcComponentMap; + typedef stdmap::fwd ObjectTemplateCrcComponentMap; + + //-- the s_nameComponentMap owns the ShipComponentDescriptor objects + NameComponentMap * s_nameComponentMap; + + //-- the s_crcComponentMap DOES NOT own the ShipComponentDescriptor objects + CrcComponentMap s_crcComponentMap; + ObjectTemplateCrcComponentMap s_objectTemplateCrcComponentMap; + ObjectTemplateCrcComponentMap s_sharedObjectTemplateCrcComponentMap; + + bool s_installed = false; + + bool s_useWritableComponentDescriptor = false; + + static const char * const s_filename = "datatables/space/ship_components.iff"; +} + +using namespace ShipComponentDescriptorNamespace; + +//---------------------------------------------------------------------- + +void ShipComponentDescriptor::install () +{ + InstallTimer const installTimer("ShipComponentDescriptor::install "); + + if (s_installed) + return; + + s_nameComponentMap = new NameComponentMap; + + s_installed = true; + + load(); + + ExitChain::add(ShipComponentDescriptor::remove, "ShipComponentDescriptor::remove"); +} + +//---------------------------------------------------------------------- + +void ShipComponentDescriptor::fetchSharedObjectTemplates() +{ + for (NameComponentMap::iterator it = s_nameComponentMap->begin (); it != s_nameComponentMap->end (); ++it) + it->second->fetchSharedObjectTemplate(); +} + +//---------------------------------------------------------------------- + +void ShipComponentDescriptor::load() +{ + Iff iff; + + if (!iff.open (s_filename, true)) + { + WARNING (true, ("Data file %s not available.", s_filename)); + return; + } + + DataTable dt; + dt.load (iff); + iff.close (); + + std::string const & s_colnameName = "name"; + std::string const & s_colnameShipComponentType = "component_type"; + std::string const & s_colnameCompatibility = "compatibility"; + std::string const & s_colnameObjectTemplate = "object_template"; + std::string const & s_colnameSharedObjectTemplate = "shared_object_template"; + + const int numRows = dt.getNumRows (); + + for (int row = 0; row < numRows; ++row) + { + std::string const & name = dt.getStringValue (s_colnameName, row); + ShipComponentType::Type const type = ShipComponentType::getTypeFromName (dt.getStringValue (s_colnameShipComponentType, row)); + std::string const & compatibility = dt.getStringValue (s_colnameCompatibility, row); + std::string const & serverObjectTemplateName = dt.getStringValue (s_colnameObjectTemplate, row); + uint32 const serverObjectTemplateCrc = Crc::normalizeAndCalculate (serverObjectTemplateName.c_str()); + std::string const & sharedTemplateName = dt.getStringValue (s_colnameSharedObjectTemplate, row); + uint32 const sharedObjectTemplateCrc = Crc::normalizeAndCalculate (sharedTemplateName.c_str ()); + +#ifdef _DEBUG + ConstCharCrcString const & sharedCrcString = ObjectTemplateList::lookUp(sharedObjectTemplateCrc); + DEBUG_WARNING(!sharedTemplateName.empty() && sharedCrcString.isEmpty(), ("Data error: in ship_components.tab - Component [%s] Shared template [%s] not found for row [%d]", name.c_str(), sharedTemplateName.c_str(), row)); +#endif + + ShipComponentDescriptor * componentDescriptor = NULL; + + if (s_useWritableComponentDescriptor) + componentDescriptor = new ShipComponentDescriptorWritable (TemporaryCrcString (name.c_str (), true), type, TemporaryCrcString (compatibility.c_str (), true), serverObjectTemplateName, sharedTemplateName); + else + componentDescriptor = new ShipComponentDescriptor (TemporaryCrcString (name.c_str (), true), type, TemporaryCrcString (compatibility.c_str (), true), serverObjectTemplateCrc, sharedObjectTemplateCrc); + + if (!componentDescriptor->addShipComponentDescriptor(true, false)) + { + WARNING(true, ("ShipComponentDescriptor error adding [%s]", name.c_str())); + } + } //lint !e429 //custodial componentDescriptor +} + +//---------------------------------------------------------------------- + +bool ShipComponentDescriptor::save(std::string const & filename) +{ + //-- fill this string with the text contents of the tab file + std::string tabStr; + + //-- TAB HEADER COLNAMES + tabStr += + "name\t" + "object_template\t" + "shared_object_template\t" + "component_type\t" + "compatibility\n"; + + //-- TAB HEADER COLTYPES + tabStr += + "s\t" + "s\t" + "s\t" + "s\t" + "s\n"; + + //-- TAB DATA ROWS + { + StringVector const & componentNames = ShipComponentDescriptor::getComponentDescriptorNames(); + + for (StringVector::const_iterator it = componentNames.begin(); it != componentNames.end(); ++it) + { + std::string const & componentName = *it; + ShipComponentDescriptor const * const shipComponentDescriptor = NON_NULL(findShipComponentDescriptorByName(ConstCharCrcString(componentName.c_str()))); + + tabStr += componentName + "\t"; + tabStr += shipComponentDescriptor->getObjectTemplateName() + "\t"; + tabStr += shipComponentDescriptor->getSharedTemplateName() + "\t"; + tabStr += ShipComponentType::getNameFromType(static_cast(shipComponentDescriptor->getComponentType())) + "\t"; + tabStr += std::string(shipComponentDescriptor->getCompatibility().getString()); + tabStr.push_back('\n'); + } + } + + bool retval = false; + + StdioFileFactory sff; + AbstractFile * const af = sff.createFile(filename.c_str(), "wb"); + if (NULL != af && af->isOpen()) + { + int const bytesWritten = af->write(static_cast(tabStr.size()), tabStr.c_str()); + retval = (bytesWritten == static_cast(tabStr.size())); + } + else + { + WARNING(true, ("ShipComponentDescriptor failed to write file [%s]", filename.c_str())); + } + + delete af; + return retval; +} + +//---------------------------------------------------------------------- + +void ShipComponentDescriptor::remove () +{ + for (NameComponentMap::iterator it = s_nameComponentMap->begin (); it != s_nameComponentMap->end (); ++it) + delete (*it).second; + + s_nameComponentMap->clear (); + delete s_nameComponentMap; + s_nameComponentMap = 0; + + s_crcComponentMap.clear (); + s_objectTemplateCrcComponentMap.clear (); + s_sharedObjectTemplateCrcComponentMap.clear (); + + s_installed = false; +} + +//---------------------------------------------------------------------- + +void ShipComponentDescriptor::setUseWritableComponentDescriptor(bool onlyUseThisForTools) +{ + DEBUG_FATAL (s_installed, ("already installed, setUseWritableComponentDescriptor must be called prior to installation")); + + s_useWritableComponentDescriptor = onlyUseThisForTools; +} + +//---------------------------------------------------------------------- + +ShipComponentDescriptor::ShipComponentDescriptor () : +m_name (), +m_componentType (ShipComponentType::SCT_num_types), +m_compatibility (), +m_objectTemplateCrc (0), +m_sharedObjectTemplateCrc (0), +m_sharedObjectTemplate(0) +{ +} + +//---------------------------------------------------------------------- + +ShipComponentDescriptor::ShipComponentDescriptor (CrcString const & name, ShipComponentType::Type type, CrcString const & compatibility, uint32 objectTemplateCrc, uint32 sharedObjectTemplateCrc) : +m_name (name), +m_componentType (type), +m_compatibility (compatibility), +m_objectTemplateCrc (objectTemplateCrc), +m_sharedObjectTemplateCrc (sharedObjectTemplateCrc), +m_sharedObjectTemplate(0) +{ +} + +//---------------------------------------------------------------------- + +ShipComponentDescriptor::ShipComponentDescriptor(CrcString const & name, ShipComponentType::Type type, CrcString const & compatibility, std::string const & objectTemplateName, std::string const & sharedTemplateName) : +m_name (name), +m_componentType (type), +m_compatibility (compatibility), +m_objectTemplateCrc (Crc::normalizeAndCalculate(objectTemplateName.c_str())), +m_sharedObjectTemplateCrc (Crc::normalizeAndCalculate(sharedTemplateName.c_str())), +m_sharedObjectTemplate(0) +{ +} + +//---------------------------------------------------------------------- + +ShipComponentDescriptor::~ShipComponentDescriptor () +{ + if (m_sharedObjectTemplate) + { + m_sharedObjectTemplate->releaseReference(); + m_sharedObjectTemplate = 0; + } +} + +//---------------------------------------------------------------------- + +void ShipComponentDescriptor::fetchSharedObjectTemplate() +{ + if (m_sharedObjectTemplate) + { + m_sharedObjectTemplate->releaseReference(); + m_sharedObjectTemplate = 0; + } + + if (m_sharedObjectTemplateCrc != 0) + m_sharedObjectTemplate = ObjectTemplateList::fetch(m_sharedObjectTemplateCrc); +} + +//---------------------------------------------------------------------- + +ShipComponentDescriptor const * ShipComponentDescriptor::findShipComponentDescriptorByCrc (uint32 componentCrc) +{ + DEBUG_FATAL (!s_installed, ("not installed")); + const CrcComponentMap::const_iterator it = s_crcComponentMap.find (componentCrc); + if (it != s_crcComponentMap.end ()) + return (*it).second; + + return NULL; +} + +//---------------------------------------------------------------------- + +ShipComponentDescriptor const * ShipComponentDescriptor::findShipComponentDescriptorByName (CrcString const & componentName) +{ + DEBUG_FATAL (!s_installed, ("not installed")); + const NameComponentMap::const_iterator it = s_nameComponentMap->find (PersistentCrcString(componentName)); + if (it != s_nameComponentMap->end ()) + return (*it).second; + + return NULL; +} + +//---------------------------------------------------------------------- + +ShipComponentDescriptor const * ShipComponentDescriptor::findShipComponentDescriptorByObjectTemplate (uint32 objectTemplateCrc) +{ + DEBUG_FATAL (!s_installed, ("not installed")); + const ObjectTemplateCrcComponentMap::const_iterator it = s_objectTemplateCrcComponentMap.find (objectTemplateCrc); + if (it != s_objectTemplateCrcComponentMap.end ()) + return (*it).second; + + return NULL; +} + +//---------------------------------------------------------------------- + +ShipComponentDescriptor const * ShipComponentDescriptor::findShipComponentDescriptorBySharedObjectTemplate (uint32 sharedObjectTemplateCrc) +{ + DEBUG_FATAL (!s_installed, ("not installed")); + const ObjectTemplateCrcComponentMap::const_iterator it = s_sharedObjectTemplateCrcComponentMap.find (sharedObjectTemplateCrc); + if (it != s_sharedObjectTemplateCrcComponentMap.end ()) + return (*it).second; + + return NULL; +} + +//---------------------------------------------------------------------- + +ShipComponentDescriptor::StringVector ShipComponentDescriptor::getComponentDescriptorNames() +{ + StringVector sv; + sv.reserve(s_nameComponentMap->size()); + + { + for (NameComponentMap::const_iterator it = s_nameComponentMap->begin(); it != s_nameComponentMap->end(); ++it) + { + std::string const componentName((*it).first.getString()); + sv.push_back(componentName); + } + } + + std::sort(sv.begin(), sv.end()); + return sv; +} + +//---------------------------------------------------------------------- + +bool ShipComponentDescriptor::setName(std::string const & name) +{ + ShipComponentDescriptor const * const dupeNameShipComponentDescriptor = findShipComponentDescriptorByName(ConstCharCrcString(name.c_str())); + if (NULL != dupeNameShipComponentDescriptor) + { + WARNING(true, ("ShipComponentDescriptor attempt to set name [%s] already exists", name.c_str())); + return false; + } + + ShipComponentDescriptor const * const shipComponentDescriptorInList = findShipComponentDescriptorByCrc(getCrc()); + + if (this == shipComponentDescriptorInList) + { + uint32 const newCrc = Crc::normalizeAndCalculate(name.c_str()); + ShipComponentAttachmentManager::udpateComponentCrc(getCrc(), newCrc); + removeShipComponentDescriptor(); + m_name.set(name.c_str(), true); + + if (!addShipComponentDescriptor(true, true)) + return false; + } + else + { + m_name.set(name.c_str(), true); + } + + return true; +} + +//---------------------------------------------------------------------- + +bool ShipComponentDescriptor::setObjectTemplateCrcs(uint32 crc, uint32 sharedCrc) +{ + ShipComponentDescriptor const * const dupeTemplateShipComponentDescriptor = findShipComponentDescriptorByObjectTemplate(crc); + if (NULL != dupeTemplateShipComponentDescriptor && this != dupeTemplateShipComponentDescriptor) + { + WARNING(true, ("ShipComponentDescriptor attempt to set ot crc [%s] already exists", dupeTemplateShipComponentDescriptor->getName().getString())); + return false; + } + + ShipComponentDescriptor const * const dupeSharedTemplateShipComponentDescriptor = findShipComponentDescriptorBySharedObjectTemplate(crc); + if (NULL != dupeSharedTemplateShipComponentDescriptor && this != dupeSharedTemplateShipComponentDescriptor) + { + WARNING(true, ("ShipComponentDescriptor attempt to set shared ot crc [%s] already exists", dupeSharedTemplateShipComponentDescriptor->getName().getString())); + return false; + } + + ShipComponentDescriptor const * const shipComponentDescriptorInList = findShipComponentDescriptorByCrc(getCrc()); + + if (this == shipComponentDescriptorInList) + { + removeShipComponentDescriptor(); + m_objectTemplateCrc = crc; + m_sharedObjectTemplateCrc = sharedCrc; + + if (!addShipComponentDescriptor(true, false)) + return false; + } + else + { + m_objectTemplateCrc = crc; + m_sharedObjectTemplateCrc = sharedCrc; + } + + fetchSharedObjectTemplate(); + + return true; +} + +//---------------------------------------------------------------------- + +void ShipComponentDescriptor::removeShipComponentDescriptor() +{ + IGNORE_RETURN(s_nameComponentMap->erase(m_name)); + IGNORE_RETURN(s_crcComponentMap.erase(getCrc())); + IGNORE_RETURN(s_objectTemplateCrcComponentMap.erase(getObjectTemplateCrc())); + IGNORE_RETURN(s_sharedObjectTemplateCrcComponentMap.erase(getSharedObjectTemplateCrc())); +} + +//---------------------------------------------------------------------- + +bool ShipComponentDescriptor::addShipComponentDescriptor(bool checkValidity, bool strict) +{ + if (checkValidity) + { + { + ShipComponentDescriptor const * const shipComponentDescriptor = findShipComponentDescriptorByName(m_name); + if (NULL != shipComponentDescriptor) + { + WARNING(true, ("ShipComponentDescriptor::addShipComponentDescriptor name [%s] is already in map", m_name.getString())); + return false; + } + } + + { + ShipComponentDescriptor const * const shipComponentDescriptor = findShipComponentDescriptorByCrc(getCrc()); + if (NULL != shipComponentDescriptor) + { + WARNING(true, ("ShipComponentDescriptor::addShipComponentDescriptor [%s] crc [0x%x] is already in map via [%s]", m_name.getString(), static_cast(getCrc()), shipComponentDescriptor->getName().getString())); + return false; + } + } + + { + uint32 const objectTemplateCrc = getObjectTemplateCrc(); + if (0 != objectTemplateCrc) + { + ShipComponentDescriptor const * const shipComponentDescriptor = findShipComponentDescriptorByObjectTemplate(objectTemplateCrc); + if (NULL != shipComponentDescriptor) + { + WARNING(true, ("ShipComponentDescriptor::addShipComponentDescriptor [%s] server template [%s] [0x%x] is already in map via [%s]", m_name.getString(), getObjectTemplateName().c_str(), static_cast(getObjectTemplateCrc()), shipComponentDescriptor->getName().getString())); + if (strict) + return false; + } + } + } + + { + uint32 const sharedObjectTemplateCrc = getSharedObjectTemplateCrc(); + if (0 != sharedObjectTemplateCrc) + { + ShipComponentDescriptor const * const shipComponentDescriptor = findShipComponentDescriptorBySharedObjectTemplate(sharedObjectTemplateCrc); + if (NULL != shipComponentDescriptor) + { + WARNING(true, ("ShipComponentDescriptor::addShipComponentDescriptor [%s] shared template [%s] [0x%x] is already in map via [%s]", m_name.getString(), getSharedTemplateName().c_str(), static_cast(getSharedObjectTemplateCrc()), shipComponentDescriptor->getName().getString())); + if (strict) + return false; + } + } + } + } + + IGNORE_RETURN (s_nameComponentMap->insert (std::make_pair (m_name, this))); + IGNORE_RETURN (s_crcComponentMap.insert (std::make_pair (getCrc(), this))); + IGNORE_RETURN (s_objectTemplateCrcComponentMap.insert (std::make_pair (getObjectTemplateCrc(), this))); + IGNORE_RETURN (s_sharedObjectTemplateCrcComponentMap.insert (std::make_pair (getSharedObjectTemplateCrc(), this))); + + return true; +} + +//---------------------------------------------------------------------- + +std::string const & ShipComponentDescriptor::getObjectTemplateName() const +{ + static const std::string empty; + return empty; +} + +//---------------------------------------------------------------------- + +std::string const & ShipComponentDescriptor::getSharedTemplateName() const +{ + static const std::string empty; + return empty; +} + +//---------------------------------------------------------------------- + +ShipComponentDescriptor::NameComponentMap const & ShipComponentDescriptor::getNameComponentMap() +{ + return *NON_NULL(s_nameComponentMap); +} + +//---------------------------------------------------------------------- + +void ShipComponentDescriptor::setComponentType(ShipComponentType::Type type) +{ + m_componentType = type; +} + +//---------------------------------------------------------------------- + +void ShipComponentDescriptor::setCompatibility(std::string const & compat) +{ + m_compatibility.set(compat.c_str(), true); +} + +//---------------------------------------------------------------------- + +char const * ShipComponentDescriptor::getFilename() +{ + return s_filename; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipComponentDescriptor.h b/engine/shared/library/sharedGame/src/shared/space/ShipComponentDescriptor.h new file mode 100644 index 00000000..f2792969 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipComponentDescriptor.h @@ -0,0 +1,138 @@ +//====================================================================== +// +// ShipComponentDescriptor.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ShipComponentDescriptor_H +#define INCLUDED_ShipComponentDescriptor_H + +//====================================================================== + +#include "sharedGame/ShipComponentType.h" +#include "sharedFoundation/PersistentCrcString.h" + +class ObjectTemplate; + +//---------------------------------------------------------------------- + +class ShipComponentDescriptor +{ +public: + + typedef stdvector::fwd StringVector; + typedef stdmap::fwd NameComponentMap; + + static void install (); + static void fetchSharedObjectTemplates(); + static void remove (); + static void load(); + static bool save(std::string const & filename); + + static char const * getFilename(); + + static void setUseWritableComponentDescriptor(bool onlyUseThisForTools); + + static ShipComponentDescriptor const * findShipComponentDescriptorByCrc (uint32 componentCrc); + static ShipComponentDescriptor const * findShipComponentDescriptorByName (CrcString const & componentName); + static ShipComponentDescriptor const * findShipComponentDescriptorByObjectTemplate (uint32 objectTemplateCrc); + static ShipComponentDescriptor const * findShipComponentDescriptorBySharedObjectTemplate (uint32 sharedObjectTemplateCrc); + + CrcString const & getName () const; + uint32 getCrc () const; + ShipComponentType::Type getComponentType () const; + CrcString const & getCompatibility () const; + uint32 getObjectTemplateCrc () const; + uint32 getSharedObjectTemplateCrc () const; + ObjectTemplate const * getSharedObjectTemplate() const; + + static StringVector getComponentDescriptorNames(); + static NameComponentMap const & getNameComponentMap(); + +protected: + ShipComponentDescriptor (CrcString const & name, ShipComponentType::Type type, CrcString const & compatibility, std::string const & objectTemplateName, std::string const & sharedTemplateName); + virtual ~ShipComponentDescriptor (); + + virtual bool setName(std::string const & name); + virtual void removeShipComponentDescriptor(); + virtual bool addShipComponentDescriptor(bool checkValidity, bool strict); + + virtual std::string const & getObjectTemplateName() const; + virtual std::string const & getSharedTemplateName() const; + virtual void setCompatibility(std::string const & compat); + virtual void setComponentType(ShipComponentType::Type type); + + bool setObjectTemplateCrcs(uint32 crc, uint32 sharedCrc); + +private: + ShipComponentDescriptor (CrcString const & name, ShipComponentType::Type type, CrcString const & compatibility, uint32 objectTemplateCrc, uint32 sharedObjectTemplateCrc); + ShipComponentDescriptor (); + + ShipComponentDescriptor (const ShipComponentDescriptor & rhs); + ShipComponentDescriptor & operator= (const ShipComponentDescriptor & rhs); + + void fetchSharedObjectTemplate(); + +private: + + PersistentCrcString m_name; + ShipComponentType::Type m_componentType; + PersistentCrcString m_compatibility; + uint32 m_objectTemplateCrc; + uint32 m_sharedObjectTemplateCrc; + ObjectTemplate const * m_sharedObjectTemplate; +}; + +//---------------------------------------------------------------------- + +inline CrcString const & ShipComponentDescriptor::getName () const +{ + return m_name; +} + +//---------------------------------------------------------------------- + +inline ShipComponentType::Type ShipComponentDescriptor::getComponentType () const +{ + return m_componentType; +} + +//---------------------------------------------------------------------- + +inline CrcString const & ShipComponentDescriptor::getCompatibility () const +{ + return m_compatibility; +} + +//---------------------------------------------------------------------- + +inline uint32 ShipComponentDescriptor::getObjectTemplateCrc () const +{ + return m_objectTemplateCrc; +} + +//---------------------------------------------------------------------- + +inline uint32 ShipComponentDescriptor::getSharedObjectTemplateCrc () const +{ + return m_sharedObjectTemplateCrc; +} + +//---------------------------------------------------------------------- + +inline ObjectTemplate const * ShipComponentDescriptor::getSharedObjectTemplate() const +{ + return m_sharedObjectTemplate; +} + +//---------------------------------------------------------------------- + +inline uint32 ShipComponentDescriptor::getCrc () const +{ + return m_name.getCrc (); +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipComponentDescriptorWritable.cpp b/engine/shared/library/sharedGame/src/shared/space/ShipComponentDescriptorWritable.cpp new file mode 100644 index 00000000..8e3cf0fb --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipComponentDescriptorWritable.cpp @@ -0,0 +1,142 @@ +//====================================================================== +// +// ShipComponentDescriptorWritable.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipComponentDescriptorWritable.h" + +#include "sharedFoundation/Crc.h" +#include "sharedMessageDispatch/Transceiver.h" + +//====================================================================== + +namespace ShipComponentDescriptorWritableNamespace +{ + namespace Transceivers + { + MessageDispatch::Transceiver componentListChanged; + MessageDispatch::Transceiver componentChanged; + } +} + +using namespace ShipComponentDescriptorWritableNamespace; + +//---------------------------------------------------------------------- + +ShipComponentDescriptorWritable::ShipComponentDescriptorWritable (CrcString const & name, ShipComponentType::Type type, CrcString const & compatibility, std::string const & objectTemplateName, std::string const & sharedTemplateName) : +ShipComponentDescriptor(name, type, compatibility, objectTemplateName, sharedTemplateName), +m_objectTemplateName(objectTemplateName), +m_sharedTemplateName(sharedTemplateName) +{ +} + +//---------------------------------------------------------------------- + +ShipComponentDescriptorWritable::~ShipComponentDescriptorWritable () +{ +} + +//---------------------------------------------------------------------- + +std::string const & ShipComponentDescriptorWritable::getObjectTemplateName() const +{ + return m_objectTemplateName; +} + +//---------------------------------------------------------------------- + +std::string const & ShipComponentDescriptorWritable::getSharedTemplateName() const +{ + return m_sharedTemplateName; +} + +//---------------------------------------------------------------------- + +bool ShipComponentDescriptorWritable::setObjectTemplateByName(std::string const & objectTemplateName, std::string const & sharedObjectTemplateName) +{ + uint32 const crc = Crc::normalizeAndCalculate(objectTemplateName.c_str()); + uint32 const sharedCrc = Crc::normalizeAndCalculate(sharedObjectTemplateName.c_str()); + + if (setObjectTemplateCrcs(crc, sharedCrc)) + { + m_objectTemplateName = objectTemplateName; + m_sharedTemplateName = sharedObjectTemplateName; + notifyChanged(); + return true; + } + + return false; +} + +/* +//---------------------------------------------------------------------- + +void ShipComponentDescriptorWritable::setSharedTemplateName(std::string const & sharedTemplateName) +{ + m_sharedTemplateName = sharedTemplateName; +} +*/ +//---------------------------------------------------------------------- + +bool ShipComponentDescriptorWritable::setName(std::string const & name) +{ + if (ShipComponentDescriptor::setName(name)) + { + if (NULL != ShipComponentDescriptor::findShipComponentDescriptorByCrc(Crc::normalizeAndCalculate(name.c_str()))) + { + notifyChanged(); + Transceivers::componentListChanged.emitMessage(true); + } + + return true; + } + return false; +} + +//---------------------------------------------------------------------- + +void ShipComponentDescriptorWritable::setCompatibility(std::string const & compat) +{ + ShipComponentDescriptor::setCompatibility(compat); + notifyChanged(); +} + +//---------------------------------------------------------------------- + +void ShipComponentDescriptorWritable::notifyChanged() +{ + Transceivers::componentChanged.emitMessage(*this); +} + +//---------------------------------------------------------------------- + +void ShipComponentDescriptorWritable::removeShipComponentDescriptor() +{ + ShipComponentDescriptor::removeShipComponentDescriptor(); + Transceivers::componentListChanged.emitMessage(true); +} + +//---------------------------------------------------------------------- + +bool ShipComponentDescriptorWritable::addShipComponentDescriptor(bool checkValidity, bool strict) +{ + if (ShipComponentDescriptor::addShipComponentDescriptor(checkValidity, strict)) + { + Transceivers::componentListChanged.emitMessage(true); + return true; + } + return false; +} + +//---------------------------------------------------------------------- + +void ShipComponentDescriptorWritable::setComponentType(ShipComponentType::Type type) +{ + ShipComponentDescriptor::setComponentType(type); + Transceivers::componentListChanged.emitMessage(true); +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipComponentDescriptorWritable.h b/engine/shared/library/sharedGame/src/shared/space/ShipComponentDescriptorWritable.h new file mode 100644 index 00000000..154f32a8 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipComponentDescriptorWritable.h @@ -0,0 +1,60 @@ +//====================================================================== +// +// ShipComponentDescriptorWritable.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ShipComponentDescriptorWritable_H +#define INCLUDED_ShipComponentDescriptorWritable_H + +//====================================================================== + +#include "sharedGame/ShipComponentDescriptor.h" + +class ShipComponentDescriptorWritable : public ShipComponentDescriptor +{ +public: + + class Messages + { + public: + struct ComponentListChanged; + struct ComponentChanged + { + typedef ShipComponentDescriptorWritable Payload; + }; + }; + +public: + ShipComponentDescriptorWritable (CrcString const & name, ShipComponentType::Type type, CrcString const & compatibility, std::string const & objectTemplateName, std::string const & sharedTemplateName); + ~ShipComponentDescriptorWritable (); + + virtual std::string const & getObjectTemplateName() const; + virtual std::string const & getSharedTemplateName() const; + + bool setObjectTemplateByName(std::string const & objectTemplateName, std::string const & sharedObjectTemplateName); +// void setSharedTemplateName(std::string const & sharedTemplateName); + + virtual bool setName(std::string const & name); + virtual void setCompatibility(std::string const & compat); + virtual void removeShipComponentDescriptor(); + virtual bool addShipComponentDescriptor(bool checkValidity, bool strict); + virtual void setComponentType(ShipComponentType::Type type); + + void notifyChanged(); + +private: + + ShipComponentDescriptorWritable(ShipComponentDescriptorWritable const & rhs); + ShipComponentDescriptorWritable & operator=(ShipComponentDescriptorWritable const & rhs); + +private: + + std::string m_objectTemplateName; + std::string m_sharedTemplateName; +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipComponentFlags.cpp b/engine/shared/library/sharedGame/src/shared/space/ShipComponentFlags.cpp new file mode 100644 index 00000000..b1d97483 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipComponentFlags.cpp @@ -0,0 +1,13 @@ +//====================================================================== +// +// ShipComponentFlags.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipComponentFlags.h" + +//====================================================================== + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipComponentFlags.h b/engine/shared/library/sharedGame/src/shared/space/ShipComponentFlags.h new file mode 100644 index 00000000..0c0d8a18 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipComponentFlags.h @@ -0,0 +1,30 @@ +//====================================================================== +// +// ShipComponentFlags.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ShipComponentFlags_H +#define INCLUDED_ShipComponentFlags_H + +//====================================================================== + +namespace ShipComponentFlags +{ + enum Flags + { + F_disabled = 0x0001, + F_lowPower = 0x0002, //this flag is transient and is overriden at runtime + F_active = 0x0004, + F_demolished = 0x0008, + F_reverse_engineered = 0x0010, + F_shieldsFront = 0x0020, //this flag is transient and is overriden at runtime + F_shieldsBack = 0x0040, //this flag is transient and is overriden at runtime + F_disabledNeedsPower = 0x0080 + }; +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipComponentType.cpp b/engine/shared/library/sharedGame/src/shared/space/ShipComponentType.cpp new file mode 100644 index 00000000..04e92f3e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipComponentType.cpp @@ -0,0 +1,127 @@ +//====================================================================== +// +// ShipComponentType.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipComponentType.h" + +#include + +//====================================================================== + +namespace ShipComponentTypeNamespace +{ + const std::string s_componentTypeNames [ShipComponentType::SCT_num_types] = + { + "reactor", + "engine", + "shield", + "armor", + "weapon", + "capacitor", + "booster", + "droid_interface", + "bridge", + "hangar", + "targeting_station", + "cargo_hold", + "modification" + }; + + const std::string s_componentTypePrefixes[ShipComponentType::SCT_num_types] = + { + "rct_", + "eng_", + "shd_", + "arm_", + "wpn_", + "cap_", + "bst_", + "ddi_", + "bdg_", + "hgr_", + "tst_", + "crg_", + "mod_" + }; + + typedef stdhash_map::fwd ComponentNameTypeMap; + ComponentNameTypeMap s_componentNameTypeMap; + + bool s_installed = false; + + void install () + { + if (s_installed) + return; + + s_installed = true; + + for (int i = 0; i < static_cast(ShipComponentType::SCT_num_types); ++i) + s_componentNameTypeMap.insert (std::make_pair (s_componentTypeNames [i], static_cast(i))); + } +} + +using namespace ShipComponentTypeNamespace; + +//---------------------------------------------------------------------- + +std::string const & ShipComponentType::getNameFromType (Type type) +{ + const int i_type = static_cast(type); + + if (i_type < SCT_reactor || i_type >= SCT_num_types) + { + static const std::string empty; + return empty; + } + + return s_componentTypeNames [i_type]; +} + +//---------------------------------------------------------------------- + +ShipComponentType::Type ShipComponentType::getTypeFromName (std::string const & name) +{ + if (!s_installed) + install (); + + const ComponentNameTypeMap::const_iterator it = s_componentNameTypeMap.find (name); + if (it != s_componentNameTypeMap.end ()) + return (*it).second; + + return SCT_num_types; +} + +//---------------------------------------------------------------------- + +std::string const & ShipComponentType::getCanonicalPrefixForType(Type type) +{ + const int i_type = static_cast(type); + + if (i_type < SCT_reactor || i_type >= SCT_num_types) + { + static const std::string empty; + return empty; + } + + return s_componentTypePrefixes [i_type]; +} + +//---------------------------------------------------------------------- + +bool ShipComponentType::isCanonicalPrefix(std::string const & prefix) +{ + for (int i = 0; i < SCT_num_types; ++i) + { + if (s_componentTypePrefixes[i] == prefix) + return true; + } + + return false; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipComponentType.h b/engine/shared/library/sharedGame/src/shared/space/ShipComponentType.h new file mode 100644 index 00000000..3cefdb50 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipComponentType.h @@ -0,0 +1,42 @@ +//====================================================================== +// +// ShipComponentType.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ShipComponentType_H +#define INCLUDED_ShipComponentType_H + +//====================================================================== + +namespace ShipComponentType +{ + enum Type + { + SCT_reactor, + SCT_engine, + SCT_shield, + SCT_armor, + SCT_weapon, + SCT_capacitor, + SCT_booster, + SCT_droid_interface, + SCT_bridge, + SCT_hangar, + SCT_targeting_station, + SCT_cargo_hold, + SCT_modification, + SCT_num_types + }; + + std::string const & getNameFromType (Type type); + Type getTypeFromName (std::string const & name); + std::string const & getCanonicalPrefixForType(Type type); + bool isCanonicalPrefix(std::string const &); + +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipComponentWeaponManager.cpp b/engine/shared/library/sharedGame/src/shared/space/ShipComponentWeaponManager.cpp new file mode 100644 index 00000000..4e6559c7 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipComponentWeaponManager.cpp @@ -0,0 +1,215 @@ +//====================================================================== +// +// ShipComponentWeaponManager.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipComponentWeaponManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFoundation/TemporaryCrcString.h" +#include "sharedGame/ShipComponentDescriptor.h" +#include "sharedGame/ShipComponentType.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" +#include "sharedFoundation/ExitChain.h" + +#include + +//====================================================================== + +namespace ShipComponentWeaponManagerNamespace +{ + enum DatatableColumns + { + DC_componentName, + DC_projectileIndex, + DC_range, + DC_speed, + DC_ammoConsuming, + DC_missile, + DC_countermeasure, + DC_mining, + DC_tractor, + DC_beam + }; + + class Data + { + public: + + //lint -e1925 + int projectileIndex; + int8 flags; + float range; + float speed; + + Data() : + projectileIndex(0), + flags(0), + range(0.0f), + speed(0.0f) + { + } + }; + + typedef stdmap::fwd CrcIntMap; + CrcIntMap s_dataMap; + + bool s_installed = false; +} + +using namespace ShipComponentWeaponManagerNamespace; + +//---------------------------------------------------------------------- + +void ShipComponentWeaponManager::install() +{ + InstallTimer const installTimer("ShipComponentWeaponManager::install"); + + DEBUG_FATAL(s_installed, ("ShipComponentWeaponManager already installed")); + s_installed = true; + + std::string const & filename = "datatables/space/ship_weapon_components.iff"; + + DataTable * const dt = DataTableManager::getTable(filename, true); + + if (dt == NULL) + { + WARNING(true, ("ShipComponentWeaponManager no such datatable [%s]", filename.c_str())); + return; + } + + const int numRows = dt->getNumRows(); + + for (int row = 0; row < numRows; ++row) + { + std::string const & componentName = dt->getStringValue(static_cast(DC_componentName), row); + ShipComponentDescriptor const * const shipComponentDescriptor = + ShipComponentDescriptor::findShipComponentDescriptorByName(TemporaryCrcString(componentName.c_str(), true)); + + if (shipComponentDescriptor == NULL) + { + WARNING(true, ("getComponentType datatable specified invalid component [%s]", componentName.c_str())); + continue; + } + + if (shipComponentDescriptor->getComponentType() != ShipComponentType::SCT_weapon) + { + WARNING(true, ("ShipComponentWeaponManager specified non-weapon component [%s]", componentName.c_str())); + continue; + } + + Data data; + data.projectileIndex = dt->getIntValue(static_cast(DC_projectileIndex), row); + data.flags |= (dt->getIntValue(static_cast(DC_ammoConsuming), row) != 0) ? F_ammoConsuming : 0; + data.flags |= (dt->getIntValue(static_cast(DC_missile), row) != 0) ? F_missile : 0; + data.flags |= (dt->getIntValue(static_cast(DC_countermeasure), row) != 0) ? F_countermeasure : 0; + data.flags |= (dt->getIntValue(static_cast(DC_mining), row) != 0) ? F_mining : 0; + data.flags |= (dt->getIntValue(static_cast(DC_tractor), row) != 0) ? F_tractor : 0; + data.flags |= (dt->getIntValue(static_cast(DC_beam), row) != 0) ? F_beam : 0; + + data.range = dt->getFloatValue(static_cast(DC_range), row); + data.speed = dt->getFloatValue(static_cast(DC_speed), row); + + + DEBUG_FATAL((data.flags & (F_countermeasure | F_missile)) == (F_countermeasure | F_missile), + ("Data bug: weapon %i in ship_weapon_components is both a missile and a countermeasure. This is not supported.",row)); + + IGNORE_RETURN(s_dataMap.insert(std::make_pair(shipComponentDescriptor->getCrc(), data))); + } + + ExitChain::add(ShipComponentWeaponManager::remove, "ShipComponentWeaponManager::remove"); +} + +//---------------------------------------------------------------------- + +void ShipComponentWeaponManager::remove() +{ + s_installed = false; + s_dataMap.clear (); +} + +//---------------------------------------------------------------------- + +int ShipComponentWeaponManager::getProjectileIndex(uint32 componentCrc) +{ + CrcIntMap::const_iterator const it = s_dataMap.find(componentCrc); + if (it != s_dataMap.end()) + return (*it).second.projectileIndex; + + return -1; +} + +//---------------------------------------------------------------------- + +bool ShipComponentWeaponManager::isAmmoConsuming(uint32 componentCrc) +{ + return hasFlags(componentCrc, F_ammoConsuming); +} + +//---------------------------------------------------------------------- + +bool ShipComponentWeaponManager::isMissile(uint32 componentCrc) +{ + return hasFlags(componentCrc, F_missile); +} + +//---------------------------------------------------------------------- + +bool ShipComponentWeaponManager::isCountermeasure(uint32 componentCrc) +{ + return hasFlags(componentCrc, F_countermeasure); +} + +//---------------------------------------------------------------------- + +bool ShipComponentWeaponManager::isMining(uint32 componentCrc) +{ + return hasFlags(componentCrc, F_mining); +} + +//---------------------------------------------------------------------- + +bool ShipComponentWeaponManager::isTractor(uint32 componentCrc) +{ + return hasFlags(componentCrc, F_tractor); +} + +//---------------------------------------------------------------------- + +float ShipComponentWeaponManager::getRange(uint32 componentCrc) +{ + CrcIntMap::const_iterator const it = s_dataMap.find(componentCrc); + if (it != s_dataMap.end()) + return (*it).second.range; + + return false; +} + +//---------------------------------------------------------------------- + +float ShipComponentWeaponManager::getProjectileSpeed(uint32 componentCrc) +{ + CrcIntMap::const_iterator const it = s_dataMap.find(componentCrc); + if (it != s_dataMap.end()) + return (*it).second.speed; + + return false; +} + +//---------------------------------------------------------------------- + +bool ShipComponentWeaponManager::hasFlags(uint32 componentCrc, int flags) +{ + CrcIntMap::const_iterator const it = s_dataMap.find(componentCrc); + if (it != s_dataMap.end()) + return ((*it).second.flags & flags) == flags; + + return false; +} + +//====================================================================== + diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipComponentWeaponManager.h b/engine/shared/library/sharedGame/src/shared/space/ShipComponentWeaponManager.h new file mode 100644 index 00000000..a99c3156 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipComponentWeaponManager.h @@ -0,0 +1,45 @@ +//====================================================================== +// +// ShipComponentWeaponManager.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ShipComponentWeaponManager_H +#define INCLUDED_ShipComponentWeaponManager_H + +//====================================================================== + +class ShipComponentWeaponManager +{ +public: + + enum Flags + { + F_ammoConsuming = 0x01, + F_missile = 0x02, + F_countermeasure = 0x04, + F_mining = 0x08, + F_tractor = 0x10, + F_beam = 0x20 + }; + + static void install(); + static void remove(); + + static int getProjectileIndex(uint32 componentCrc); + static bool isAmmoConsuming(uint32 componentCrc); + static bool isMissile(uint32 componentCrc); + static bool isCountermeasure(uint32 componentCrc); + static bool isMining(uint32 componentCrc); + static bool isTractor(uint32 componentCrc); + + static bool hasFlags(uint32 componentCrc, int flags); + + static float getRange(uint32 componentCrc); + static float getProjectileSpeed(uint32 componentCrc); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipHitEffectsManager.cpp b/engine/shared/library/sharedGame/src/shared/space/ShipHitEffectsManager.cpp new file mode 100644 index 00000000..5e1a439a --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipHitEffectsManager.cpp @@ -0,0 +1,13 @@ +//====================================================================== +// +// ShipHitEffectsManager.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipHitEffectsManager.h" + +//====================================================================== + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipHitEffectsManager.h b/engine/shared/library/sharedGame/src/shared/space/ShipHitEffectsManager.h new file mode 100644 index 00000000..6c1c311d --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipHitEffectsManager.h @@ -0,0 +1,40 @@ +//====================================================================== +// +// ShipHitEffectsManager.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ShipHitEffectsManager_H +#define INCLUDED_ShipHitEffectsManager_H + +//====================================================================== + +class ShipHitEffectsManager +{ +public: + + /** + * These must be kept in sync with: + * base_class.java + * space/ship_hit_effects.tab + * space/ship_hit_sounds.tab + */ + enum HitType + { + HT_shield, + HT_armor, + HT_component, + HT_chassis, + HT_numTypes + }; + +private: + ShipHitEffectsManager (); + ShipHitEffectsManager (const ShipHitEffectsManager & rhs); + ShipHitEffectsManager & operator= (const ShipHitEffectsManager & rhs); +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipSlotIdManager.cpp b/engine/shared/library/sharedGame/src/shared/space/ShipSlotIdManager.cpp new file mode 100644 index 00000000..b3a9049f --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipSlotIdManager.cpp @@ -0,0 +1,144 @@ +// ====================================================================== +// +// ShipSlotIdManager.cpp +// +// Copyright 2004 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipSlotIdManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFoundation/ConstCharCrcLowerString.h" +#include "sharedGame/ShipChassisSlotType.h" +#include "sharedObject/SlotId.h" +#include "sharedObject/SlotIdManager.h" + +// ====================================================================== + +namespace ShipSlotIdManagerNamespace +{ + + SlotId s_shipPilotSlotId; + SlotId s_pobShipPilotSlotId; + SlotId s_shipOperationsSlotId; + SlotId s_pobShipOperationsSlotId; + SlotId s_shipGunnerSlotIds[ShipChassisSlotType::cms_numWeaponIndices]; + SlotId s_pobShipGunnerSlotIds[ShipChassisSlotType::cms_numWeaponIndices]; + SlotId s_shipDroidSlotId; + + bool s_installed = false; + +} + +using namespace ShipSlotIdManagerNamespace; + +// ====================================================================== + +void ShipSlotIdManager::install() +{ + InstallTimer const installTimer("ShipSlotIdManager::install"); + + if (SlotIdManager::isInstalled()) + { + s_shipPilotSlotId = SlotIdManager::findSlotId(ConstCharCrcLowerString("ship_pilot")); + s_pobShipPilotSlotId = SlotIdManager::findSlotId(ConstCharCrcLowerString("ship_pilot_pob")); + s_shipOperationsSlotId = SlotIdManager::findSlotId(ConstCharCrcLowerString("ship_operations")); + s_pobShipOperationsSlotId = SlotIdManager::findSlotId(ConstCharCrcLowerString("ship_operations_pob")); + + for (int i = 0; i < ShipChassisSlotType::cms_numWeaponIndices; ++i) + { + char buf[32]; + IGNORE_RETURN(snprintf(buf, sizeof(buf)-1, "ship_gunner%d", i)); + buf[sizeof(buf)-1] = '\0'; + s_shipGunnerSlotIds[i] = SlotIdManager::findSlotId(ConstCharCrcLowerString(buf)); + IGNORE_RETURN(snprintf(buf, sizeof(buf)-1, "ship_gunner%d_pob", i)); + buf[sizeof(buf)-1] = '\0'; + s_pobShipGunnerSlotIds[i] = SlotIdManager::findSlotId(ConstCharCrcLowerString(buf)); + } + + s_shipDroidSlotId = SlotIdManager::findSlotId(ConstCharCrcLowerString("ship_droid")); + + s_installed = true; + } +} + +// ---------------------------------------------------------------------- + +SlotId const &ShipSlotIdManager::getShipPilotSlotId() +{ + DEBUG_FATAL(!s_installed, ("ShipSlotIdManager was not installed, or sharedGame was installed before SharedObject")); + return s_shipPilotSlotId; +} + +// ---------------------------------------------------------------------- + +SlotId const &ShipSlotIdManager::getPobShipPilotSlotId() +{ + DEBUG_FATAL(!s_installed, ("ShipSlotIdManager was not installed, or sharedGame was installed before SharedObject")); + return s_pobShipPilotSlotId; +} + +// ---------------------------------------------------------------------- + +SlotId const &ShipSlotIdManager::getShipOperationsSlotId() +{ + DEBUG_FATAL(!s_installed, ("ShipSlotIdManager was not installed, or sharedGame was installed before SharedObject")); + return s_shipOperationsSlotId; +} + +// ---------------------------------------------------------------------- + +SlotId const &ShipSlotIdManager::getPobShipOperationsSlotId() +{ + DEBUG_FATAL(!s_installed, ("ShipSlotIdManager was not installed, or sharedGame was installed before SharedObject")); + return s_pobShipOperationsSlotId; +} + +// ---------------------------------------------------------------------- + +SlotId const &ShipSlotIdManager::getShipDroidSlotId() +{ + DEBUG_FATAL(!s_installed, ("ShipSlotIdManager was not installed, or sharedGame was installed before SharedObject")); + return s_shipDroidSlotId; +} + +// ---------------------------------------------------------------------- + +SlotId const &ShipSlotIdManager::getShipGunnerSlotId(int weaponIndex) +{ + DEBUG_FATAL(!s_installed, ("ShipSlotIdManager was not installed, or sharedGame was installed before SharedObject")); + FATAL(weaponIndex < 0 || weaponIndex >= ShipChassisSlotType::cms_numWeaponIndices, ("tried to get gunner slot id for invalid weaponIndex")); + return s_shipGunnerSlotIds[weaponIndex]; +} + +// ---------------------------------------------------------------------- + +SlotId const &ShipSlotIdManager::getPobShipGunnerSlotId(int weaponIndex) +{ + DEBUG_FATAL(!s_installed, ("ShipSlotIdManager was not installed, or sharedGame was installed before SharedObject")); + FATAL(weaponIndex < 0 || weaponIndex >= ShipChassisSlotType::cms_numWeaponIndices, ("tried to get gunner slot id for invalid weaponIndex")); + return s_pobShipGunnerSlotIds[weaponIndex]; +} + +// ---------------------------------------------------------------------- + +int ShipSlotIdManager::getGunnerSlotWeaponIndex(SlotId const &slotId) +{ + DEBUG_FATAL(!s_installed, ("ShipSlotIdManager was not installed, or sharedGame was installed before SharedObject")); + for (int i = 0; i < ShipChassisSlotType::cms_numWeaponIndices; ++i) + if (s_shipGunnerSlotIds[i] == slotId || s_pobShipGunnerSlotIds[i] == slotId) + return i; + return -1; +} + +// ---------------------------------------------------------------------- + +bool ShipSlotIdManager::isGunnerSlot(SlotId const &slotId) +{ + return getGunnerSlotWeaponIndex(slotId) != -1; +} + +// ====================================================================== + diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipSlotIdManager.h b/engine/shared/library/sharedGame/src/shared/space/ShipSlotIdManager.h new file mode 100644 index 00000000..8c8e425a --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipSlotIdManager.h @@ -0,0 +1,37 @@ +// ====================================================================== +// +// ShipSlotIdManager.h +// +// Copyright 2004 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_ShipSlotIdManager_H +#define INCLUDED_ShipSlotIdManager_H + +// ====================================================================== + +class SlotId; + +// ====================================================================== + +class ShipSlotIdManager +{ +public: + static void install(); + + static SlotId const &getShipPilotSlotId(); + static SlotId const &getPobShipPilotSlotId(); + static SlotId const &getShipOperationsSlotId(); + static SlotId const &getPobShipOperationsSlotId(); + static SlotId const &getShipDroidSlotId(); + static SlotId const &getShipGunnerSlotId(int weaponIndex); + static SlotId const &getPobShipGunnerSlotId(int weaponIndex); + static bool isGunnerSlot(SlotId const &slotId); + static int getGunnerSlotWeaponIndex(SlotId const &slotId); +}; + +// ====================================================================== + +#endif // INCLUDED_ShipSlotIdManager_H + diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipTargeting.cpp b/engine/shared/library/sharedGame/src/shared/space/ShipTargeting.cpp new file mode 100644 index 00000000..ebcc9184 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipTargeting.cpp @@ -0,0 +1,712 @@ +//======================================================================= +// +// ShipTargeting.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//======================================================================= + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipTargeting.h" + +#include "sharedCollision/CollisionProperty.h" +#include "sharedCollision/CollisionWorld.h" +#include "sharedGame/SharedObjectTemplateInterface.h" +#include "sharedGame/SharedObjectTemplate.h" +#include "sharedGame/SharedShipObjectTemplate.h" +#include "sharedGame/ShipChassisSlotType.h" +#include "sharedGame/ShipComponentAttachmentManager.h" +#include "sharedObject/Appearance.h" +#include "sharedObject/CellProperty.h" +#include "sharedObject/Object.h" +#include "sharedObject/World.h" + +#include +#include + +//======================================================================= + +namespace ShipTargetingNamespace +{ + float const cs_maximumSweepTargetingDistance = 2000.0f; + float const cs_maximumTargetingWidth = 1000.0f; + + void sweepForCloseShips(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject, ShipTargeting::ObjectVector & closeObjects); + void allShipsInWorld(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject, ShipTargeting::ObjectVector & resultObjects); + + void getAllAttachmentHardpoints(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * object, ShipComponentAttachmentManager::HardpointVector & hardpoints); + float smallestDistanceToObject(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * object, Vector const & targetingObject_w); + float smallestDotToObject(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * object, Vector const & targetingObject_w, Vector const & targetingObjectFramek_w); +} + +// ---------------------------------------------------------------------- + +void ShipTargetingNamespace::sweepForCloseShips(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject, ShipTargeting::ObjectVector & closeObjects) +{ + NOT_NULL(targetingObject); + if (targetingObject == 0) //lint !e774 // previous debug test interupts flow + return; + + Vector const center_w(targetingObject->getPosition_w()); + Vector const targetingObjectFramek_w(targetingObject->getObjectFrameK_w()); + Capsule const capsule_w(Sphere(center_w, cs_maximumTargetingWidth), targetingObjectFramek_w * cs_maximumSweepTargetingDistance); + + ColliderList colliderList; + int const queryMask = static_cast(SpatialDatabase::Q_Physicals); + CollisionWorld::getDatabase()->queryFor(queryMask, CellProperty::getWorldCellProperty(), true, capsule_w, colliderList); + + closeObjects.reserve(colliderList.size()); + ColliderList::const_iterator ii = colliderList.begin(); + ColliderList::const_iterator iiEnd = colliderList.end(); + for (; ii != iiEnd; ++ii) + { + CollisionProperty * const closeObjectCollisionProperty = *ii; + + if (closeObjectCollisionProperty != 0) + { + Object * const object = &closeObjectCollisionProperty->getOwner(); + if (sharedObjectTemplateInterface.isShipObject(object)) + { + if (object != targetingObject->getRootParent()) + { + closeObjects.push_back(object); + } + } + } + } + + std::sort(closeObjects.begin(), closeObjects.end()); +} + +// ---------------------------------------------------------------------- + +void ShipTargetingNamespace::allShipsInWorld(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject, ShipTargeting::ObjectVector & resultObjects) +{ + int const tangibleListIndex = static_cast(WOL_Tangible); + int const numberOfTangibles = World::getNumberOfObjects(tangibleListIndex); + resultObjects.reserve(static_cast(numberOfTangibles)); + + for (int i = 0; i < numberOfTangibles; ++i) + { + Object * const object = World::getObject(tangibleListIndex, i); + if (object != 0) + { + if (sharedObjectTemplateInterface.isShipObject(object)) + { + if (object != targetingObject->getRootParent()) + { + resultObjects.push_back(object); + } + } + } + } + + std::sort(resultObjects.begin(), resultObjects.end()); +} + +// ---------------------------------------------------------------------- + +void ShipTargetingNamespace::getAllAttachmentHardpoints(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const object, ShipComponentAttachmentManager::HardpointVector & hardpoints) +{ + if (sharedObjectTemplateInterface.isShipObject(object)) + { + for (int i = static_cast(ShipChassisSlotType::SCST_first); i != static_cast(ShipChassisSlotType::SCST_num_types); ++i) + { + ShipChassisSlotType::Type chassisSlot = static_cast(i); + + uint32 const chassisType = sharedObjectTemplateInterface.getShipChassisType(object); + uint32 const componentCrc = sharedObjectTemplateInterface.getShipComponentCrc(object, chassisSlot); + + ShipComponentAttachmentManager::TemplateHardpointPairVector const & hardPointPairs = + ShipComponentAttachmentManager::getAttachmentsForShip (chassisType, componentCrc, chassisSlot); + + ShipComponentAttachmentManager::HardpointVector const & extraHardpoints = ShipComponentAttachmentManager::getExtraHardpointsForComponent(chassisType, componentCrc, chassisSlot); + + int const numberOfHardpointsToAdd = static_cast(hardpoints.size() + hardPointPairs.size() + extraHardpoints.size()); + hardpoints.reserve(static_cast(numberOfHardpointsToAdd)); + + ShipComponentAttachmentManager::TemplateHardpointPairVector::const_iterator ii = hardPointPairs.begin(); + ShipComponentAttachmentManager::TemplateHardpointPairVector::const_iterator iiEnd = hardPointPairs.end(); + + for (; ii != iiEnd; ++ii) + { + hardpoints.push_back(ii->second); + } + + hardpoints.insert(hardpoints.end(), extraHardpoints.begin(), extraHardpoints.end()); + } + } +} + +// ---------------------------------------------------------------------- + +float ShipTargetingNamespace::smallestDistanceToObject(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const object, Vector const & targetingObject_w) +{ + NOT_NULL(object); + + float bestDistanceSqr = FLT_MAX; + + { + // check against the root first + Vector const shipToTest_w(object->getPosition_w()); + bestDistanceSqr = (shipToTest_w - targetingObject_w).magnitudeSquared(); + } + + if (ShipTargeting::isCapShipOrSpaceStation(sharedObjectTemplateInterface, object)) + { + // check against the attachments + Appearance const * const appearance = object->getAppearance(); + + if (appearance != 0) + { + ShipComponentAttachmentManager::HardpointVector hardpoints; + + ShipTargetingNamespace::getAllAttachmentHardpoints(sharedObjectTemplateInterface, object, hardpoints); + + if (!hardpoints.empty()) + { + ShipComponentAttachmentManager::HardpointVector::const_iterator ii = hardpoints.begin(); + ShipComponentAttachmentManager::HardpointVector::const_iterator iiEnd = hardpoints.end(); + + for (; ii != iiEnd; ++ii) + { + PersistentCrcString const & hardpointName = *ii; + + Transform transform; + + if (appearance->findHardpoint(hardpointName, transform)) + { + Vector const attachment_w(object->rotateTranslate_o2w(transform.getPosition_p())); + float const testDistanceSqr = (targetingObject_w - attachment_w).magnitudeSquared(); + + if (testDistanceSqr < bestDistanceSqr) + { + bestDistanceSqr = testDistanceSqr; + } + } + } + } + } + } + return bestDistanceSqr; +} + +// ---------------------------------------------------------------------- + +float ShipTargetingNamespace::smallestDotToObject(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const object, Vector const & targetingObject_w, Vector const & targetingObjectFramek_w) +{ + NOT_NULL(object); + + float bestDot = -1.0f; + + { + // check against the root first + Vector const shipToTest_w(object->getPosition_w()); + Vector shipToTestDirection(shipToTest_w - targetingObject_w); + if (shipToTestDirection.normalize()) + { + bestDot = targetingObjectFramek_w.dot(shipToTestDirection); + } + } + + if (ShipTargeting::isCapShipOrSpaceStation(sharedObjectTemplateInterface, object)) + { + // check against the attachments + Appearance const * const appearance = object->getAppearance(); + + if (appearance != 0) + { + ShipComponentAttachmentManager::HardpointVector hardpoints; + + ShipTargetingNamespace::getAllAttachmentHardpoints(sharedObjectTemplateInterface, object, hardpoints); + + if (!hardpoints.empty()) + { + ShipComponentAttachmentManager::HardpointVector::const_iterator ii = hardpoints.begin(); + ShipComponentAttachmentManager::HardpointVector::const_iterator iiEnd = hardpoints.end(); + + for (; ii != iiEnd; ++ii) + { + PersistentCrcString const & hardpointName = *ii; + + Transform transform; + + if (appearance->findHardpoint(hardpointName, transform)) + { + Vector const attachment_w(object->rotateTranslate_o2w(transform.getPosition_p())); + Vector shipToTestDirection(attachment_w - targetingObject_w); + if (shipToTestDirection.normalize()) + { + float const testDot = targetingObjectFramek_w.dot(shipToTestDirection); + + if (testDot > bestDot) + { + bestDot = testDot; + } + } + } + } + } + } + } + + return bestDot; +} + +//======================================================================= + +using namespace ShipTargetingNamespace; + +//======================================================================= + +bool ShipTargeting::isPlayerShip(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const object) +{ + NOT_NULL(object); + + SharedObjectTemplate const * const sharedObjectTemplate = sharedObjectTemplateInterface.getSharedTemplate(object); + + NOT_NULL(sharedObjectTemplate); + + SharedShipObjectTemplate const * const sharedShipObjectTemplate = safe_cast(sharedObjectTemplate); + if (sharedShipObjectTemplate != 0) + { + return (sharedShipObjectTemplate->getPlayerControlled()); + } + + return false; +} + +// ---------------------------------------------------------------------- + +bool ShipTargeting::isNPCShip(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const object) +{ + return !isPlayerShip(sharedObjectTemplateInterface, object); +} + +// ---------------------------------------------------------------------- + +bool ShipTargeting::isCapShipOrSpaceStation(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const object) +{ + NOT_NULL(object); + + SharedObjectTemplate const * const sharedObjectTemplate = sharedObjectTemplateInterface.getSharedTemplate(object); + + NOT_NULL(sharedObjectTemplate); + + SharedObjectTemplate::GameObjectType const GOT = sharedObjectTemplate->getGameObjectType(); + + return (GOT == SharedObjectTemplate::GOT_ship_capital) || (GOT == SharedObjectTemplate::GOT_ship_station); +} + +// ---------------------------------------------------------------------- + +Object * ShipTargeting::closestObjectFromListMeetingCriteria(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject, ShipTargeting::ObjectVector & toTestAgainst, ShipTargeting::TestObjectCriteriaFunction testFunction) +{ + NOT_NULL(targetingObject); + if (targetingObject == 0) //lint !e774 // previous debug test interupts flow + return 0; + + Vector const targetingObject_w(targetingObject->getPosition_w()); + float bestDistanceSqr = FLT_MAX; + Object * bestTarget = 0; + + ObjectVector::const_iterator ii = toTestAgainst.begin(); + ObjectVector::const_iterator iiEnd = toTestAgainst.end(); + for (; ii != iiEnd; ++ii) + { + Object * const objectToTest = *ii; + + if (objectToTest != 0) + { + if ((testFunction != 0) && (!testFunction(sharedObjectTemplateInterface, objectToTest))) + { + continue; + } + + float const testDistanceSqr = smallestDistanceToObject(sharedObjectTemplateInterface, + objectToTest, + targetingObject_w); + + if (testDistanceSqr < bestDistanceSqr) + { + bestDistanceSqr = testDistanceSqr; + bestTarget = objectToTest; + } + } + } + + return bestTarget; +} + +// ---------------------------------------------------------------------- + +Object * ShipTargeting::sweepForClosestShip(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject) +{ + NOT_NULL(targetingObject); + if (targetingObject == 0) //lint !e774 // previous debug test interupts flow + return 0; + + ObjectVector closeObjects; + sweepForCloseShips(sharedObjectTemplateInterface, targetingObject, closeObjects); + return closestObjectFromListMeetingCriteria(sharedObjectTemplateInterface, targetingObject, closeObjects); +} + +// ---------------------------------------------------------------------- + +Object * ShipTargeting::sweepForClosestCapShip(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject) +{ + NOT_NULL(targetingObject); + if (targetingObject == 0) //lint !e774 // previous debug test interupts flow + return 0; + + ObjectVector closeObjects; + sweepForCloseShips(sharedObjectTemplateInterface, targetingObject, closeObjects); + return closestObjectFromListMeetingCriteria(sharedObjectTemplateInterface, targetingObject, closeObjects, isCapShipOrSpaceStation); +} + +// ---------------------------------------------------------------------- + +Object * ShipTargeting::sweepForClosestUnderReticle(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject) +{ + NOT_NULL(targetingObject); + if (targetingObject == 0) //lint !e774 // previous debug test interupts flow + return 0; + + ObjectVector closeObjects; + sweepForCloseShips(sharedObjectTemplateInterface, targetingObject, closeObjects); + + Vector const targetingObject_w(targetingObject->getPosition_w()); + Vector const targetingObjectFramek_w(targetingObject->getObjectFrameK_w()); + float bestDot = -1.0f; + Object * bestTarget = 0; + + ObjectVector::const_iterator ii = closeObjects.begin(); + ObjectVector::const_iterator iiEnd = closeObjects.end(); + for (; ii != iiEnd; ++ii) + { + Object * const objectToTest = *ii; + + if ((objectToTest != 0) && (objectToTest != targetingObject->getRootParent())) + { + float const testDot = smallestDotToObject(sharedObjectTemplateInterface, + objectToTest, + targetingObject_w, + targetingObjectFramek_w); + if (testDot > bestDot) + { + bestTarget = objectToTest; + bestDot = testDot; + } + } + } + + return bestTarget; +} + +// ---------------------------------------------------------------------- + +Object * ShipTargeting::sweepForClosestPlayer(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject) +{ + ObjectVector closeObjects; + sweepForCloseShips(sharedObjectTemplateInterface, targetingObject, closeObjects); + return closestObjectFromListMeetingCriteria(sharedObjectTemplateInterface, targetingObject, closeObjects, isPlayerShip); +} + +// ---------------------------------------------------------------------- + +Object * ShipTargeting::sweepForClosestNPC(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject) +{ + ObjectVector closeObjects; + sweepForCloseShips(sharedObjectTemplateInterface, targetingObject, closeObjects); + return closestObjectFromListMeetingCriteria(sharedObjectTemplateInterface, targetingObject, closeObjects, isNPCShip); +} + +// ---------------------------------------------------------------------- + +Object * ShipTargeting::sweepForClosestShipWithRelationShip(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject, ActorAndTargetHaveReletionship function) +{ + ObjectVector resultObjects; + sweepForShipsWithRelationship(sharedObjectTemplateInterface, targetingObject, function, resultObjects); + return closestObjectFromListMeetingCriteria(sharedObjectTemplateInterface, targetingObject, resultObjects); +} + +// ---------------------------------------------------------------------- + +Object * ShipTargeting::closestShipInWorld(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject) +{ + NOT_NULL(targetingObject); + if (targetingObject == 0) //lint !e774 // previous debug test interupts flow + return 0; + + ObjectVector closeObjects; + allShipsInWorld(sharedObjectTemplateInterface, targetingObject, closeObjects); + return closestObjectFromListMeetingCriteria(sharedObjectTemplateInterface, targetingObject, closeObjects); +} + +// ---------------------------------------------------------------------- + +Object * ShipTargeting::closestCapShipInWorld(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject) +{ + NOT_NULL(targetingObject); + if (targetingObject == 0) //lint !e774 // previous debug test interupts flow + return 0; + + ObjectVector closeObjects; + allShipsInWorld(sharedObjectTemplateInterface, targetingObject, closeObjects); + return closestObjectFromListMeetingCriteria(sharedObjectTemplateInterface, targetingObject, closeObjects, isCapShipOrSpaceStation); +} + +// ---------------------------------------------------------------------- + +Object * ShipTargeting::closestUnderReticleInWorld(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject) +{ + NOT_NULL(targetingObject); + if (targetingObject == 0) //lint !e774 // previous debug test interupts flow + return 0; + + ObjectVector closeObjects; + allShipsInWorld(sharedObjectTemplateInterface, targetingObject, closeObjects); + + Vector const targetingObject_w(targetingObject->getPosition_w()); + Vector const targetingObjectFramek_w(targetingObject->getObjectFrameK_w()); + float bestDot = -1.0f; + Object * bestTarget = 0; + + ObjectVector::const_iterator ii = closeObjects.begin(); + ObjectVector::const_iterator iiEnd = closeObjects.end(); + for (; ii != iiEnd; ++ii) + { + Object * const objectToTest = *ii; + + if ((objectToTest != 0) && (objectToTest != targetingObject->getRootParent())) + { + float const testDot = smallestDotToObject(sharedObjectTemplateInterface, + objectToTest, + targetingObject_w, + targetingObjectFramek_w); + if (testDot > bestDot) + { + bestTarget = objectToTest; + bestDot = testDot; + } + } + } + + return bestTarget; +} + +// ---------------------------------------------------------------------- + +Object * ShipTargeting::closestPlayerInWorld(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject) +{ + ObjectVector closeObjects; + allShipsInWorld(sharedObjectTemplateInterface, targetingObject, closeObjects); + return closestObjectFromListMeetingCriteria(sharedObjectTemplateInterface, targetingObject, closeObjects, isPlayerShip); +} + +// ---------------------------------------------------------------------- + +Object * ShipTargeting::closestNPCInWorld(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject) +{ + ObjectVector closeObjects; + allShipsInWorld(sharedObjectTemplateInterface, targetingObject, closeObjects); + return closestObjectFromListMeetingCriteria(sharedObjectTemplateInterface, targetingObject, closeObjects, isNPCShip); +} + +// ---------------------------------------------------------------------- + +Object * ShipTargeting::closestShipInWorldWithRelationShip(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject, ActorAndTargetHaveReletionship function) +{ + ObjectVector resultObjects; + allShipsWithRelationshipInWorld(sharedObjectTemplateInterface, targetingObject, function, resultObjects); + return closestObjectFromListMeetingCriteria(sharedObjectTemplateInterface, targetingObject, resultObjects); +} + +// ---------------------------------------------------------------------- + +void ShipTargeting::sweepForShipsWithRelationship(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject, ActorAndTargetHaveReletionship function, ObjectVector & resultObjects) +{ + NOT_NULL(targetingObject); + NOT_NULL(function); + + ObjectVector closeObjects; + sweepForCloseShips(sharedObjectTemplateInterface, targetingObject, closeObjects); + + resultObjects.reserve(closeObjects.size()); + + ObjectVector::const_iterator ii = closeObjects.begin(); + ObjectVector::const_iterator iiEnd = closeObjects.end(); + for (; ii != iiEnd; ++ii) + { + Object * const objectToTest = *ii; + if (objectToTest != 0) + { + if (function(targetingObject, objectToTest)) + { + resultObjects.push_back(objectToTest); + } + } + } + std::sort(resultObjects.begin(), resultObjects.end()); +} + +// ---------------------------------------------------------------------- + +void ShipTargeting::sweepForShipsUnderDefinedReticle(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject, float targetingFov, ObjectVector & resultObjects) +{ + ObjectVector closeObjects; + sweepForCloseShips(sharedObjectTemplateInterface, targetingObject, closeObjects); + + Vector const targetingObject_w(targetingObject->getPosition_w()); + Vector const targetingObjectFramek_w(targetingObject->getObjectFrameK_w()); + float const halfOnScreenTargetFov = targetingFov * 0.5f; + + ObjectVector::const_iterator ii = closeObjects.begin(); + ObjectVector::const_iterator iiEnd = closeObjects.end(); + for (; ii != iiEnd; ++ii) + { + Object * const objectToTest = *ii; + if ((objectToTest != 0) && (objectToTest != targetingObject->getRootParent())) + { + float const testDot = smallestDotToObject(sharedObjectTemplateInterface, + objectToTest, + targetingObject_w, + targetingObjectFramek_w); + float const angle = acos(testDot); + if (angle < halfOnScreenTargetFov) + { + resultObjects.push_back(objectToTest); + } + } + } + std::sort(resultObjects.begin(), resultObjects.end()); +} + +// ---------------------------------------------------------------------- + +void ShipTargeting::allShipsWithRelationshipInWorld(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject, ActorAndTargetHaveReletionship function, ObjectVector & resultObjects) +{ + NOT_NULL(targetingObject); + NOT_NULL(function); + + int const tangibleListIndex = static_cast(WOL_Tangible); + int const numberOfTangibles = World::getNumberOfObjects(tangibleListIndex); + resultObjects.reserve(static_cast(numberOfTangibles)); + + for (int i = 0; i < numberOfTangibles; ++i) + { + Object * const objectToTest = World::getObject(tangibleListIndex, i); + if (objectToTest != 0) + { + if (sharedObjectTemplateInterface.isShipObject(objectToTest)) + { + if (objectToTest != targetingObject->getRootParent()) + { + if (function(targetingObject, objectToTest)) + { + resultObjects.push_back(objectToTest); + } + } + } + } + } + + std::sort(resultObjects.begin(), resultObjects.end()); +} + + +// ---------------------------------------------------------------------- + +void ShipTargeting::allShipsInWorldUnderDefinedReticle(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * const targetingObject, float targetingFov, ObjectVector & resultObjects) +{ + Vector const targetingObject_w(targetingObject->getPosition_w()); + Vector const targetingObjectFramek_w(targetingObject->getObjectFrameK_w()); + float const halfOnScreenTargetFov = targetingFov * 0.5f; + + int const tangibleListIndex = static_cast(WOL_Tangible); + int const numberOfTangibles = World::getNumberOfObjects(tangibleListIndex); + resultObjects.reserve(static_cast(numberOfTangibles)); + + for (int i = 0; i < numberOfTangibles; ++i) + { + Object * const objectToTest = World::getObject(tangibleListIndex, i); + if ((objectToTest != 0) && (objectToTest != targetingObject->getRootParent())) + { + if (sharedObjectTemplateInterface.isShipObject(objectToTest)) + { + float const testDot = smallestDotToObject(sharedObjectTemplateInterface, + objectToTest, + targetingObject_w, + targetingObjectFramek_w); + float const angle = acos(testDot); + if (angle < halfOnScreenTargetFov) + { + resultObjects.push_back(objectToTest); + } + } + } + } + + std::sort(resultObjects.begin(), resultObjects.end()); +} + +// ---------------------------------------------------------------------- + +Object * ShipTargeting::getNextTarget(ObjectVector const & objectList, Object const * const currentTarget) +{ + if (!objectList.empty()) + { + WARNING_DEBUG_FATAL(!std::is_sorted(objectList.begin(), objectList.end()), ("ShipTargeting::getNextTarget: objectList must be sorted")); + ObjectVector::const_iterator ii = std::lower_bound(objectList.begin(), objectList.end(), currentTarget); + + if (ii == objectList.end()) + { + // we didn't find the current target in the list. + // just return the first object in the list + return *(objectList.begin()); + } + else + { + // advance the iterator by one and wrap if necessary + ++ii; + if (ii == objectList.end()) + { + ii = objectList.begin(); + } + return *ii; + } + } + + return 0; +} + +// ---------------------------------------------------------------------- + +Object * ShipTargeting::getPreviousTarget(ObjectVector const & objectList, Object const * const currentTarget) +{ + if (!objectList.empty()) + { + WARNING_DEBUG_FATAL(!std::is_sorted(objectList.begin(), objectList.end()), ("ShipTargeting::getNextTarget: objectList must be sorted")); + ObjectVector::const_iterator ii = std::lower_bound(objectList.begin(), objectList.end(), currentTarget); + + if (ii == objectList.end()) + { + // we didn't find the current target in the list. + // just return the first object in the list + return *(objectList.begin()); + } + else + { + // advance the iterator by one and wrap if necessary + if (ii == objectList.begin()) + { + ii = objectList.end(); + } + --ii; + return *ii; + } + } + return 0; +} + + +//======================================================================= diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipTargeting.h b/engine/shared/library/sharedGame/src/shared/space/ShipTargeting.h new file mode 100644 index 00000000..189a1f1d --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipTargeting.h @@ -0,0 +1,70 @@ +//====================================================================== +// +// ShipTargeting.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_ShipTargeting_H +#define INCLUDED_ShipTargeting_H + +//====================================================================== + +class Object; +class SharedObjectTemplateInterface; + +//---------------------------------------------------------------------- + +class ShipTargeting +{ +public: + + typedef stdvector::fwd ObjectVector; + + typedef bool (*ActorAndTargetHaveReletionship)(Object const * actor, Object const * target); + + static bool isPlayerShip(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * object); + static bool isNPCShip(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * object); + static bool isCapShipOrSpaceStation(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * object); +protected: + + // TestObjectCriteriaFunction must return true if the object passes the test + typedef bool (*TestObjectCriteriaFunction)(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * object); + static Object * closestObjectFromListMeetingCriteria(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject, ShipTargeting::ObjectVector & toTestAgainst, TestObjectCriteriaFunction = 0); + + static Object * sweepForClosestShip(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject); + static Object * sweepForClosestCapShip(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject); + static Object * sweepForClosestUnderReticle(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject); + static Object * sweepForClosestPlayer(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject); + static Object * sweepForClosestNPC(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject); + static Object * sweepForClosestShipWithRelationShip(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject, ActorAndTargetHaveReletionship function); + + static Object * closestShipInWorld(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject); + static Object * closestCapShipInWorld(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject); + static Object * closestUnderReticleInWorld(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject); + static Object * closestPlayerInWorld(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject); + static Object * closestNPCInWorld(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject); + static Object * closestShipInWorldWithRelationShip(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject, ActorAndTargetHaveReletionship function); + + static void sweepForShipsWithRelationship(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject, ActorAndTargetHaveReletionship function, ObjectVector & resultObjects); + static void sweepForShipsUnderDefinedReticle(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject, float targetingFov, ObjectVector & resultObjects); + + static void allShipsWithRelationshipInWorld(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject, ActorAndTargetHaveReletionship function, ObjectVector & resultObjects); + static void allShipsInWorldUnderDefinedReticle(SharedObjectTemplateInterface const & sharedObjectTemplateInterface, Object const * targetingObject, float targetingFov, ObjectVector & resultObjects); + + static Object * getNextTarget(ObjectVector const & objectList, Object const * currentTarget); + static Object * getPreviousTarget(ObjectVector const & objectList, Object const * currentTarget); + +private: + + ShipTargeting(); + ShipTargeting(ShipTargeting const & copy); + ShipTargeting & operator=(ShipTargeting const & copy); + +}; + +//lint -esym(1512, ShipTargeting) // No virtual destructor (because there are no data members at all) + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipTurretManager.cpp b/engine/shared/library/sharedGame/src/shared/space/ShipTurretManager.cpp new file mode 100644 index 00000000..5535f8c2 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipTurretManager.cpp @@ -0,0 +1,131 @@ +// ====================================================================== +// +// ShipTurretManager.cpp +// +// Copyright 2004 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/ShipTurretManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/Iff.h" +#include "sharedGame/ShipChassis.h" +#include "sharedFoundation/TemporaryCrcString.h" +#include "sharedUtility/DataTable.h" +#include + +// ====================================================================== + +namespace ShipTurretManagerNamespace +{ + + struct ShipTurretData + { + float minYaw; + float maxYaw; + float minPitch; + float maxPitch; + }; + + std::map > s_shipTurretData; + +} + +using namespace ShipTurretManagerNamespace; + +// ====================================================================== + +void ShipTurretManager::install() // static +{ + InstallTimer const installTimer("ShipTurretManager::install"); + + Iff iff; + if (iff.open("datatables/space/ship_turret.iff", true)) + { + DataTable dataTable; + dataTable.load(iff); + int numberOfRows = dataTable.getNumRows(); + for (int row = 0; row < numberOfRows; ++row) + { + std::string const chassisName(dataTable.getStringValue("chassis", row)); + ShipChassis const * const chassis = ShipChassis::findShipChassisByName(TemporaryCrcString(chassisName.c_str(), false)); + FATAL(!chassis, ("ShipTurretManager::install: no such chassis '%s'", chassisName.c_str())); + int const weaponIndex = dataTable.getIntValue("weaponIndex", row); + ShipTurretData &shipTurretData = s_shipTurretData[chassis->getCrc()][weaponIndex]; + shipTurretData.minYaw = dataTable.getFloatValue("minYaw", row) * PI_OVER_180; + shipTurretData.maxYaw = dataTable.getFloatValue("maxYaw", row) * PI_OVER_180; + shipTurretData.minPitch = dataTable.getFloatValue("minPitch", row) * PI_OVER_180; + shipTurretData.maxPitch = dataTable.getFloatValue("maxPitch", row) * PI_OVER_180; + } + } +} + +// ---------------------------------------------------------------------- + +bool ShipTurretManager::isTurret(uint32 chassisCrc, int weaponIndex) +{ + std::map >::const_iterator i = s_shipTurretData.find(chassisCrc); + if (i == s_shipTurretData.end()) + return false; + return (*i).second.count(weaponIndex) > 0; +} + +// ---------------------------------------------------------------------- + +float ShipTurretManager::getTurretMinYaw(uint32 chassisCrc, int weaponIndex) +{ + std::map >::const_iterator i = s_shipTurretData.find(chassisCrc); + if (i != s_shipTurretData.end()) + { + std::map::const_iterator j = (*i).second.find(weaponIndex); + if (j != (*i).second.end()) + return (*j).second.minYaw; + } + return 0.f; +} + +// ---------------------------------------------------------------------- + +float ShipTurretManager::getTurretMaxYaw(uint32 chassisCrc, int weaponIndex) +{ + std::map >::const_iterator i = s_shipTurretData.find(chassisCrc); + if (i != s_shipTurretData.end()) + { + std::map::const_iterator j = (*i).second.find(weaponIndex); + if (j != (*i).second.end()) + return (*j).second.maxYaw; + } + return 0.f; +} + +// ---------------------------------------------------------------------- + +float ShipTurretManager::getTurretMinPitch(uint32 chassisCrc, int weaponIndex) +{ + std::map >::const_iterator i = s_shipTurretData.find(chassisCrc); + if (i != s_shipTurretData.end()) + { + std::map::const_iterator j = (*i).second.find(weaponIndex); + if (j != (*i).second.end()) + return (*j).second.minPitch; + } + return 0.f; +} + +// ---------------------------------------------------------------------- + +float ShipTurretManager::getTurretMaxPitch(uint32 chassisCrc, int weaponIndex) +{ + std::map >::const_iterator i = s_shipTurretData.find(chassisCrc); + if (i != s_shipTurretData.end()) + { + std::map::const_iterator j = (*i).second.find(weaponIndex); + if (j != (*i).second.end()) + return (*j).second.maxPitch; + } + return 0.f; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/space/ShipTurretManager.h b/engine/shared/library/sharedGame/src/shared/space/ShipTurretManager.h new file mode 100644 index 00000000..6920d3ff --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/space/ShipTurretManager.h @@ -0,0 +1,28 @@ +// ====================================================================== +// +// ShipTurretManager.h +// +// Copyright 2004 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_ShipTurretManager_H +#define INCLUDED_ShipTurretManager_H + +// ====================================================================== + +class ShipTurretManager +{ +public: + static void install(); + + static bool isTurret(uint32 chassisCrc, int weaponIndex); + static float getTurretMinYaw(uint32 chassisCrc, int weaponIndex); + static float getTurretMaxYaw(uint32 chassisCrc, int weaponIndex); + static float getTurretMinPitch(uint32 chassisCrc, int weaponIndex); + static float getTurretMaxPitch(uint32 chassisCrc, int weaponIndex); +}; + +// ====================================================================== + +#endif // INCLUDED_ShipTurretManager_H diff --git a/engine/shared/library/sharedGame/src/shared/sui/SuiCommand.cpp b/engine/shared/library/sharedGame/src/shared/sui/SuiCommand.cpp new file mode 100644 index 00000000..0a279a9f --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/sui/SuiCommand.cpp @@ -0,0 +1,338 @@ +//====================================================================== +// +// SuiCommand.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SuiCommand.h" + +#include "Archive/Archive.h" +#include "sharedGame/SuiWidgetProperty.h" +#include "sharedGame/SuiWidgetProperty.h" +#include "unicodeArchive/UnicodeArchive.h" + +//====================================================================== + +namespace +{ + size_t const parameterNarrowSizes[] = + { + 0, // SCT_none + 1, // SCT_clearDataSource + 3, // SCT_addChildWidget + 2, // SCT_setProperty + 2, // SCT_addDataItem + 3, // SCT_subscribeToEvent // possibly more pairs of parameters + 2, // SCT_addDataSourceContainer + 1, // SCT_clearDataSourceContainer + 2 // SCT_addDataSource + }; + + size_t const parameterWideSizes[] = + { + 0, // SCT_none + 0, // SCT_clearDataSource + 0, // SCT_addChildWidget + 1, // SCT_setProperty + 1, // SCT_addDataItem + 0, // SCT_subscribeToEvent // possibly more pairs of parameters + 1, // SCT_addDataSourceContainer + 0, // SCT_clearDataSourceContainer + 1, // SCT_addDataSource + }; + + int const numParameterSizes = sizeof(parameterWideSizes) / sizeof(parameterWideSizes[0]); +} + +//---------------------------------------------------------------------- + +SuiCommand::SuiCommand() : +m_type(SCT_none), +m_parametersWide(), +m_parametersNarrow() +{ +} + +//---------------------------------------------------------------------- + +SuiCommand::SuiCommand(Type type, std::string const & targetWidget) : +m_type(type), +m_parametersWide(), +m_parametersNarrow() +{ + int const typeIndex = static_cast(type); + VALIDATE_RANGE_INCLUSIVE_EXCLUSIVE(0, typeIndex, numParameterSizes); + + if (parameterNarrowSizes[typeIndex] > 0) + m_parametersNarrow.reserve(parameterNarrowSizes[static_cast(typeIndex)]); + + if (parameterWideSizes[typeIndex] > 0) + m_parametersWide.reserve(parameterWideSizes[static_cast(typeIndex)]); + + m_parametersNarrow.push_back(targetWidget); +} + +//---------------------------------------------------------------------- + +void SuiCommand::initAddChildWidget(std::string const & widgetType, std::string const & widgetName) +{ + DEBUG_FATAL(m_type != SCT_addChildWidget, ("SuiCommand invalid command type")); + + m_parametersNarrow.push_back(widgetType); + m_parametersNarrow.push_back(widgetName); +} + +//---------------------------------------------------------------------- + +void SuiCommand::initSetProperty(std::string const & propertyName, Unicode::String const & propertyValue) +{ + DEBUG_FATAL(m_type != SCT_setProperty, ("SuiCommand invalid command type")); + + m_parametersNarrow.push_back(propertyName); + m_parametersWide.push_back(propertyValue); +} + +//---------------------------------------------------------------------- + +void SuiCommand::initAddDataItem(std::string const & dataItemName, Unicode::String const & dataItemValue) +{ + DEBUG_FATAL(m_type != SCT_addDataItem, ("SuiCommand invalid command type")); + + m_parametersNarrow.push_back(dataItemName); + m_parametersWide.push_back(dataItemValue); +} + +//---------------------------------------------------------------------- + +void SuiCommand::initAddDataSourceContainer(std::string const & dataSourceContainerName, Unicode::String const & dataSourceContainerValue) +{ + DEBUG_FATAL(m_type != SCT_addDataSourceContainer, ("SuiCommand invalid command type")); + + m_parametersNarrow.push_back(dataSourceContainerName); + m_parametersWide.push_back(dataSourceContainerValue); +} + +//---------------------------------------------------------------------- + +void SuiCommand::initAddDataSource(std::string const & dataSourceName, Unicode::String const & dataSourceValue) +{ + DEBUG_FATAL(m_type != SCT_addDataSource, ("SuiCommand invalid command type")); + + m_parametersNarrow.push_back(dataSourceName); + m_parametersWide.push_back(dataSourceValue); +} + + +//---------------------------------------------------------------------- + +/** +* @param callback this param is not used on the client +*/ +void SuiCommand::initSubscribeToEvent(int eventType, std::string const & callback) +{ + DEBUG_FATAL(m_type != SCT_subscribeToEvent, ("SuiCommand invalid command type")); + + static std::string typeString; + typeString.clear(); + typeString.push_back(static_cast(eventType)); + + m_parametersNarrow.push_back(typeString); + m_parametersNarrow.push_back(callback); +} + +//---------------------------------------------------------------------- + +void SuiCommand::modifyEventCallback(std::string const & callback) +{ + if (m_parametersNarrow.size() < 3) + { + WARNING(true, ("SuiCommand::modifyEventCallback on uninitialized callback for widget [%s]", getTargetWidget().c_str())); + return; + } + + m_parametersNarrow[2] = callback; +} + +//---------------------------------------------------------------------- + +void SuiCommand::addPropertySubscriptionToEvent(std::string const & widgetName, std::string const & propertyName) +{ + DEBUG_FATAL(m_type != SCT_subscribeToEvent, ("SuiCommand invalid command type")); + + m_parametersNarrow.reserve(m_parametersNarrow.size() + 2); + m_parametersNarrow.push_back(widgetName); + m_parametersNarrow.push_back(propertyName); +} + +//---------------------------------------------------------------------- + +void SuiCommand::getAddChildWidget(std::string & widgetType, std::string & widgetName) const +{ + DEBUG_FATAL(m_type != SCT_addChildWidget, ("SuiCommand invalid command type")); + + if (m_parametersNarrow.size() < 3) + WARNING(true, ("SuiCommand::getAddChildWidget() invalid number of narrow parameters [%d] for type [%d]", static_cast(m_parametersNarrow.size()), static_cast(m_type))); + else + { + widgetType = m_parametersNarrow[1]; + widgetName = m_parametersNarrow[2]; + } +} + +//---------------------------------------------------------------------- + +void SuiCommand::getSetProperty(std::string & propertyName, Unicode::String & propertyValue) const +{ + DEBUG_FATAL(m_type != SCT_setProperty, ("SuiCommand invalid command type")); + + if (m_parametersNarrow.size() < 2) + WARNING(true, ("SuiCommand::getSetProperty() invalid number of narrow parameters [%d] for type [%d]", static_cast(m_parametersNarrow.size()), static_cast(m_type))); + else if (m_parametersWide.size() < 1) + WARNING(true, ("SuiCommand::getSetProperty() invalid number of wide parameters [%d] for type [%d]", static_cast(m_parametersWide.size()), static_cast(m_type))); + else + { + propertyName = m_parametersNarrow[1]; + propertyValue = m_parametersWide[0]; + } +} + +//---------------------------------------------------------------------- + +void SuiCommand::getAddDataItem(std::string & dataItemName, Unicode::String & dataItemValue) const +{ + DEBUG_FATAL(m_type != SCT_addDataItem, ("SuiCommand invalid command type")); + + if (m_parametersNarrow.size() < 2) + WARNING(true, ("SuiCommand::getAddDataItem() invalid number of narrow parameters [%d] for type [%d]", static_cast(m_parametersNarrow.size()), static_cast(m_type))); + else if (m_parametersWide.size() < 1) + WARNING(true, ("SuiCommand::getAddDataItem() invalid number of wide parameters [%d] for type [%d]", static_cast(m_parametersWide.size()), static_cast(m_type))); + else + { + dataItemName = m_parametersNarrow[1]; + dataItemValue = m_parametersWide[0]; + } +} + +//---------------------------------------------------------------------- + +void SuiCommand::getAddDataSourceContainer(std::string & dataSourceContainerName, Unicode::String & dataSourceContainerValue) const +{ + DEBUG_FATAL(m_type != SCT_addDataSourceContainer, ("SuiCommand invalid command type")); + + if (m_parametersNarrow.size() < 2) + WARNING(true, ("SuiCommand::getAddDataSourceContainer() invalid number of narrow parameters [%d] for type [%d]", static_cast(m_parametersNarrow.size()), static_cast(m_type))); + else if (m_parametersWide.size() < 1) + WARNING(true, ("SuiCommand::getAddDataSourceContainer() invalid number of wide parameters [%d] for type [%d]", static_cast(m_parametersWide.size()), static_cast(m_type))); + else + { + dataSourceContainerName = m_parametersNarrow[1]; + dataSourceContainerValue = m_parametersWide[0]; + } +} + +//---------------------------------------------------------------------- + +void SuiCommand::getAddDataSource(std::string & dataSourceName, Unicode::String & dataSourceValue) const +{ + DEBUG_FATAL(m_type != SCT_addDataSource, ("SuiCommand invalid command type")); + + if (m_parametersNarrow.size() < 2) + WARNING(true, ("SuiCommand::getAddDataSource() invalid number of narrow parameters [%d] for type [%d]", static_cast(m_parametersNarrow.size()), static_cast(m_type))); + else if (m_parametersWide.size() < 1) + WARNING(true, ("SuiCommand::getAddDataSource() invalid number of wide parameters [%d] for type [%d]", static_cast(m_parametersWide.size()), static_cast(m_type))); + else + { + dataSourceName = m_parametersNarrow[1]; + dataSourceValue = m_parametersWide[0]; + } +} + +//---------------------------------------------------------------------- + +/** +* @param callback this param is not used on the client +*/ + +void SuiCommand::getSubscribeToEventCallback(int & eventType, std::string & callback) const +{ + DEBUG_FATAL(m_type != SCT_subscribeToEvent, ("SuiCommand invalid command type")); + + if (m_parametersNarrow.size() < 3) + WARNING(true, ("SuiCommand::getSubscribeToEventCallback() invalid number of narrow parameters [%d] for type [%d]", static_cast(m_parametersNarrow.size()), static_cast(m_type))); + else + { + if (m_parametersNarrow[1].empty()) + WARNING(true, ("SuiCommand empty event type for subscription")); + else + eventType = m_parametersNarrow[1][0]; + + callback = m_parametersNarrow[2]; + } +} + +//---------------------------------------------------------------------- + +void SuiCommand::getPropertySubscriptionsForEvent(WidgetPropertyVector & widgetProperties) const +{ + DEBUG_FATAL(m_type != SCT_subscribeToEvent, ("SuiCommand invalid command type")); + + int const paramCount = static_cast(m_parametersNarrow.size()); + + if (m_parametersNarrow.size() < 3) + WARNING(true, ("SuiCommand::getPropertySubscriptionsForEvent() invalid number of narrow parameters [%d] for type [%d]", static_cast(m_parametersNarrow.size()), static_cast(m_type))); + else + { + widgetProperties.reserve(static_cast((paramCount - 3) / 2)); + for (int i = 3; i < paramCount; ) + { + SuiWidgetProperty prop; + prop.widgetName = m_parametersNarrow[static_cast(i++)]; + prop.propertyName = m_parametersNarrow[static_cast(i++)]; + widgetProperties.push_back(prop); + } + } +} + +//---------------------------------------------------------------------- + +std::string const & SuiCommand::getTargetWidget() const +{ + if (m_parametersNarrow.size() == 0) + WARNING(true, ("SuiCommand::getTargetWidget() invalid number of parameters [%d] for type [%d]", static_cast(m_parametersNarrow.size()), static_cast(m_type))); + + return m_parametersNarrow[0]; +} + +//---------------------------------------------------------------------- + +void SuiCommand::get(Archive::ReadIterator & source) +{ + uint8 type; + Archive::get(source, type); + m_type = static_cast(type); + Archive::get(source, m_parametersWide); + Archive::get(source, m_parametersNarrow); +} + +//---------------------------------------------------------------------- + +void SuiCommand::put(Archive::ByteStream & target) const +{ + Archive::put(target, static_cast(m_type)); + Archive::put(target, m_parametersWide); + Archive::put(target, m_parametersNarrow); +} + +//---------------------------------------------------------------------- + +bool SuiCommand::operator==(SuiCommand const & rhs) const +{ + return + m_type == rhs.m_type && + m_parametersWide == rhs.m_parametersWide && + m_parametersNarrow == rhs.m_parametersNarrow; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/sui/SuiCommand.h b/engine/shared/library/sharedGame/src/shared/sui/SuiCommand.h new file mode 100644 index 00000000..25b4f1aa --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/sui/SuiCommand.h @@ -0,0 +1,122 @@ +//====================================================================== +// +// SuiCommand.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_SuiCommand_H +#define INCLUDED_SuiCommand_H + +//====================================================================== + +class SuiWidgetProperty; + +#include + +namespace Archive +{ + class ReadIterator; + class ByteStream; +} + +//---------------------------------------------------------------------- + +class SuiCommand +{ +public: + enum Type + { + SCT_none, + SCT_clearDataSource, + SCT_addChildWidget, + SCT_setProperty, + SCT_addDataItem, + SCT_subscribeToEvent, + SCT_addDataSourceContainer, + SCT_clearDataSourceContainer, + SCT_addDataSource, + }; + + typedef stdvector::fwd UnicodeStringVector; + typedef stdvector::fwd StringVector; + typedef stdvector::fwd WidgetPropertyVector; + +public: + + SuiCommand(); + SuiCommand(Type type, std::string const & targetWidget); + + void initAddChildWidget(std::string const & widgetType, std::string const & widgetName); + void initSetProperty(std::string const & propertyName, Unicode::String const & propertyValue); + void initAddDataItem(std::string const & dataItemName, Unicode::String const & dataItemValue); + void initAddDataSourceContainer(std::string const & dataSourceContainerName, Unicode::String const & dataSourceContainerValue); + void initAddDataSource(std::string const & dataSourceName, Unicode::String const & dataSourceValue); + void initSubscribeToEvent(int eventType, std::string const & callback); + + void addPropertySubscriptionToEvent(std::string const & widgetName, std::string const & propertyName); + void modifyEventCallback(std::string const & callback); + + void getAddChildWidget(std::string & widgetType, std::string & widgetName) const; + void getSetProperty(std::string & propertyName, Unicode::String & propertyValue) const; + void getAddDataItem(std::string & dataItemName, Unicode::String & dataItemValue) const; + void getAddDataSourceContainer(std::string & dataSourceContainerName, Unicode::String & dataSourceContainerValue) const; + void getAddDataSource(std::string & dataSourceName, Unicode::String & dataSourceValue) const; + void getSubscribeToEventCallback(int & eventType, std::string & callback) const; + + void getPropertySubscriptionsForEvent(WidgetPropertyVector & widgetProperties) const; + + Type getType() const; + std::string const & getTargetWidget() const; + bool isSubscriptionToEvent(int eventType, std::string const & widgetName); + + bool operator==(SuiCommand const & rhs) const; + bool operator!=(SuiCommand const & rhs) const; + +public: + + void get(Archive::ReadIterator & source); + void put(Archive::ByteStream & target) const; + +private: + + Type m_type; + UnicodeStringVector m_parametersWide; + StringVector m_parametersNarrow; +}; + +//---------------------------------------------------------------------- + +inline SuiCommand::Type SuiCommand::getType() const +{ + return m_type; +} + +//---------------------------------------------------------------------- + +inline bool SuiCommand::isSubscriptionToEvent(int eventType, std::string const & widgetName) +{ + if (getType() == SCT_subscribeToEvent) + { + if (widgetName == getTargetWidget()) + { + int myEventType = 0; + std::string callback; + getSubscribeToEventCallback(myEventType, callback); + return myEventType == eventType; + } + } + + return false; +} + +//---------------------------------------------------------------------- + +inline bool SuiCommand::operator!=(SuiCommand const & rhs) const +{ + return !(*this == rhs); +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/sui/SuiCommandArchive.cpp b/engine/shared/library/sharedGame/src/shared/sui/SuiCommandArchive.cpp new file mode 100644 index 00000000..47c9ed11 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/sui/SuiCommandArchive.cpp @@ -0,0 +1,29 @@ +//====================================================================== +// +// SuiCommandArchive.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SuiCommandArchive.h" + +#include "sharedGame/SuiCommand.h" + +//====================================================================== + +namespace Archive +{ + void get(ReadIterator & source, SuiCommand & target) + { + target.get(source); + } + + + void put(ByteStream & target, const SuiCommand & source) + { + source.put(target); + } +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/sui/SuiCommandArchive.h b/engine/shared/library/sharedGame/src/shared/sui/SuiCommandArchive.h new file mode 100644 index 00000000..a8089696 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/sui/SuiCommandArchive.h @@ -0,0 +1,28 @@ +//====================================================================== +// +// SuiCommandArchive.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_SuiCommandArchive_H +#define INCLUDED_SuiCommandArchive_H + +//====================================================================== + +class SuiCommand; + +//---------------------------------------------------------------------- + +namespace Archive +{ + class ReadIterator; + class ByteStream; + + void get(ReadIterator & source, SuiCommand & target); + void put(ByteStream & target, const SuiCommand & source); +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/sui/SuiEventSubscription.cpp b/engine/shared/library/sharedGame/src/shared/sui/SuiEventSubscription.cpp new file mode 100644 index 00000000..a226d10d --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/sui/SuiEventSubscription.cpp @@ -0,0 +1,29 @@ +//====================================================================== +// +// SuiEventSubscription.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SuiEventSubscription.h" + +#include "sharedGame/SuiEventType.h" + +//====================================================================== + +SuiEventSubscription::SuiEventSubscription() : +m_suiEventType(SuiEventType::SET_none), +m_eventWidgetName() +{ +} + +//---------------------------------------------------------------------- + +SuiEventSubscription::SuiEventSubscription(int suiEventType, std::string const & eventWidgetName) : +m_suiEventType(suiEventType), +m_eventWidgetName(eventWidgetName) +{ +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/sui/SuiEventSubscription.h b/engine/shared/library/sharedGame/src/shared/sui/SuiEventSubscription.h new file mode 100644 index 00000000..ea1ff92a --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/sui/SuiEventSubscription.h @@ -0,0 +1,57 @@ +//====================================================================== +// +// SuiEventSubscription.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_SuiEventSubscription_H +#define INCLUDED_SuiEventSubscription_H + +//====================================================================== + +class SuiEventSubscription +{ +public: + SuiEventSubscription(); + SuiEventSubscription(int suiEventType, std::string const & eventWidgetName); + + bool operator<(SuiEventSubscription const & rhs) const; + + int getSuiEventType() const; + std::string const & getEventWidgetName() const; + +private: + int m_suiEventType; + std::string m_eventWidgetName; +}; + +//---------------------------------------------------------------------- + +inline bool SuiEventSubscription::operator<(SuiEventSubscription const & rhs) const +{ + if (m_suiEventType < rhs.m_suiEventType) + return true; + if (m_suiEventType == rhs.m_suiEventType) + return m_eventWidgetName < rhs.m_eventWidgetName; + + return false; +} + +//---------------------------------------------------------------------- + +inline int SuiEventSubscription::getSuiEventType() const +{ + return m_suiEventType; +} + +//---------------------------------------------------------------------- + +inline std::string const & SuiEventSubscription::getEventWidgetName() const +{ + return m_eventWidgetName; +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/sui/SuiEventType.cpp b/engine/shared/library/sharedGame/src/shared/sui/SuiEventType.cpp new file mode 100644 index 00000000..94d7f342 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/sui/SuiEventType.cpp @@ -0,0 +1,41 @@ +//====================================================================== +// +// SuiEventType.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SuiEventType.h" + +//====================================================================== + +namespace SuiEventTypeNamespace +{ + std::string const names[] = + { + "none", //SET_none, + "onButton", //SET_onButton, + "onCheckbox", //SET_onCheckbox, + "onEnabledChanged", //SET_onEnabledChanged, + "onGenericSelection", //SET_onGenericSelection, + "onSliderbar", //SET_onSliderbar, + "onTabbedPane", //SET_onTabbedPane, + "onTextbox", //SET_onTextbox, + "onVisibilityChanged", //SET_onVisibilityChanged, + "onClosedOk", //SET_onClosedOk, + "onClosedCancel", //SET_onClosedCancel + }; +} + +using namespace SuiEventTypeNamespace; + +//---------------------------------------------------------------------- + +std::string const & SuiEventType::getNameForType(int eventType) +{ //lint !e1929 //returning a reference + VALIDATE_RANGE_INCLUSIVE_EXCLUSIVE(SET_none, static_cast(eventType), SET_numEventTypes); + return names[static_cast(eventType)]; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/sui/SuiEventType.h b/engine/shared/library/sharedGame/src/shared/sui/SuiEventType.h new file mode 100644 index 00000000..358a28ef --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/sui/SuiEventType.h @@ -0,0 +1,36 @@ +//====================================================================== +// +// SuiEventType.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_SuiEventType_H +#define INCLUDED_SuiEventType_H + +//====================================================================== + +namespace SuiEventType +{ + enum Type + { + SET_none, + SET_onButton, + SET_onCheckbox, + SET_onEnabledChanged, + SET_onGenericSelection, + SET_onSliderbar, + SET_onTabbedPane, + SET_onTextbox, + SET_onVisibilityChanged, + SET_onClosedOk, + SET_onClosedCancel, + SET_numEventTypes + }; + + std::string const & getNameForType(int eventType); +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/sui/SuiPageData.cpp b/engine/shared/library/sharedGame/src/shared/sui/SuiPageData.cpp new file mode 100644 index 00000000..c0941d98 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/sui/SuiPageData.cpp @@ -0,0 +1,275 @@ +//====================================================================== +// +// SuiPageData.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SuiPageData.h" + +#include "Archive/Archive.h" +#include "sharedFoundation/NetworkIdArchive.h" +#include "sharedGame/SuiCommand.h" +#include "sharedGame/SuiCommandArchive.h" +#include "sharedMathArchive/VectorArchive.h" + +//lint -e766 //header + +//====================================================================== + +SuiPageData::SuiPageData() : +m_pageId(0), +m_pageName(), +m_commands(), +m_associatedObjectId(), +m_associatedLocation(Vector::maxXYZ), // "unset" value is Vector::maxXYZ +m_maxRangeFromObject(0.0f) +{ +} + +//---------------------------------------------------------------------- + +SuiPageData::SuiPageData(int pageId, std::string const & pageName) : +m_pageId(pageId), +m_pageName(pageName), +m_commands(), +m_associatedObjectId(), +m_associatedLocation(Vector::maxXYZ), // "unset" value is Vector::maxXYZ +m_maxRangeFromObject(0.0f) +{ +} + +//---------------------------------------------------------------------- + +std::string const & SuiPageData::getPageName() const +{ + return m_pageName; +} + +//---------------------------------------------------------------------- + +NetworkId const & SuiPageData::getAssociatedObjectId() const +{ + return m_associatedObjectId; +} + +//---------------------------------------------------------------------- + +Vector const & SuiPageData::getAssociatedLocation() const +{ + return m_associatedLocation; +} + +//---------------------------------------------------------------------- + +float const SuiPageData::getMaxRangeFromObject() const +{ + return m_maxRangeFromObject; +} + +//---------------------------------------------------------------------- + +SuiPageData::SuiCommandVector const & SuiPageData::getCommands() const +{ + return m_commands; +} + +//---------------------------------------------------------------------- + +/** +* This method does not attempt to merge identical subscription commands' property subscription lists +* @todo: make the merging work +*/ + +bool SuiPageData::addCommand(SuiCommand const & command) +{ + if (command.getType() == SuiCommand::SCT_subscribeToEvent) + { + int eventType = 0; + std::string callback; + command.getSubscribeToEventCallback(eventType, callback); + std::string const & targetWidget = command.getTargetWidget(); + + SuiCommand const * const oldCommand = findSubscribeToEventCommand(eventType, targetWidget); + + if (oldCommand != NULL) + { + WARNING(true, ("SuiPageData::addCommand attempt to add duplicate SCT_subscribeToEvent command. Type=[%d], target=[%s]", eventType, targetWidget.c_str())); + return false; + } + } + + m_commands.push_back(command); + return true; +} + +//---------------------------------------------------------------------- + +void SuiPageData::setAssociatedObjectIdWithMaxRange(NetworkId const & associatedObjectId, float const maxRange) +{ + m_associatedObjectId = associatedObjectId; + m_maxRangeFromObject = maxRange; +} + +//---------------------------------------------------------------------- + +void SuiPageData::setAssociatedLocationWithMaxRange(Vector const & associatedLocation, float maxRange) +{ + m_associatedLocation = associatedLocation; + m_maxRangeFromObject = maxRange; +} + +//---------------------------------------------------------------------- + +/** +* This method call must be accompanied at some point by a call to subscribeToEvent() +*/ + +void SuiPageData::subscribeToPropertyForEvent(int eventType, std::string const & eventWidgetName, std::string const & propertyWidgetName, std::string const & propertyName) +{ + SuiCommand * const command = findSubscribeToEventCommand(eventType, eventWidgetName); + + if (command == NULL) + { + SuiCommand newCommand(SuiCommand::SCT_subscribeToEvent, eventWidgetName); + newCommand.initSubscribeToEvent(eventType, std::string()); + newCommand.addPropertySubscriptionToEvent(propertyWidgetName, propertyName); + if (!addCommand(newCommand)) + WARNING(true, ("SuiPageData::subscribeToPropertyForEvent() failed to addCommand()")); + } + else + command->addPropertySubscriptionToEvent(propertyWidgetName, propertyName); +} + +//---------------------------------------------------------------------- + +bool SuiPageData::subscribeToEvent(int eventType, std::string const & eventWidgetName, std::string const & callback) +{ + SuiCommand * const command = findSubscribeToEventCommand(eventType, eventWidgetName); + + if (command == NULL) + { + SuiCommand newCommand(SuiCommand::SCT_subscribeToEvent, eventWidgetName); + newCommand.initSubscribeToEvent(eventType, callback); + if (!addCommand(newCommand)) + WARNING(true, ("SuiPageData::subscribeToEvent() failed to addCommand()")); + return true; + } + else + { + command->modifyEventCallback(callback); + return false; + } +} + +//---------------------------------------------------------------------- + +SuiCommand * SuiPageData::findSubscribeToEventCommand(int const eventType, std::string const & eventWidgetName) +{ + for (SuiCommandVector::iterator it = m_commands.begin(); it != m_commands.end(); ++it) + { + SuiCommand & command = *it; + if (command.getType() == SuiCommand::SCT_subscribeToEvent) + { + int existingEventType = 0; + std::string callback; + command.getSubscribeToEventCallback(existingEventType, callback); + std::string const & existingTargetWidget = command.getTargetWidget(); + + if (eventType == existingEventType && eventWidgetName == existingTargetWidget) + return &command; + } + } + + return NULL; +} + +//---------------------------------------------------------------------- + +SuiCommand * SuiPageData::findSubscribeToEventCommandByIndex(int const index) +{ + int currentIndex = 0; + + for (SuiCommandVector::iterator it = m_commands.begin(); it != m_commands.end(); ++it) + { + SuiCommand & command = *it; + if (command.getType() == SuiCommand::SCT_subscribeToEvent) + { + if (currentIndex == index) + return &command; + + ++currentIndex; + } + } + + return NULL; +} + +//---------------------------------------------------------------------- + +void SuiPageData::get(Archive::ReadIterator & source) +{ + Archive::get(source, m_pageId); + Archive::get(source, m_pageName); + Archive::get(source, m_commands); + Archive::get(source, m_associatedObjectId); + Archive::get(source, m_associatedLocation); + Archive::get(source, m_maxRangeFromObject); +} + +//---------------------------------------------------------------------- + +void SuiPageData::put(Archive::ByteStream & target) const +{ + Archive::put(target, m_pageId); + Archive::put(target, m_pageName); + Archive::put(target, m_commands); + Archive::put(target, m_associatedObjectId); + Archive::put(target, m_associatedLocation); + Archive::put(target, m_maxRangeFromObject); +} + +//---------------------------------------------------------------------- + +bool SuiPageData::operator==(SuiPageData const & rhs) const +{ + return + m_pageId == rhs.m_pageId && + m_pageName == rhs.m_pageName && + m_commands == rhs.m_commands && + m_associatedObjectId == rhs.m_associatedObjectId && + m_associatedLocation == rhs.m_associatedLocation && + m_maxRangeFromObject == rhs.m_maxRangeFromObject; //lint !e777 //testing floats +} + +//---------------------------------------------------------------------- + +bool SuiPageData::getPageUpdate(int commandIndex, SuiPageData & pageData) const +{ + if (commandIndex < 0 || commandIndex >= static_cast(m_commands.size())) + return false; + + pageData.m_pageId = m_pageId; + pageData.m_pageName = m_pageName; + pageData.m_associatedObjectId = m_associatedObjectId; + pageData.m_associatedLocation = m_associatedLocation; + pageData.m_maxRangeFromObject = m_maxRangeFromObject; + + pageData.m_commands.clear(); + + SuiCommandVector::const_iterator it = m_commands.begin(); + + std::advance(it, commandIndex); + + for (; it != m_commands.end(); ++it) + { + SuiCommand const & command = *it; + if (command.getType() != SuiCommand::SCT_subscribeToEvent) + pageData.m_commands.push_back(command); + } + + return true; +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/sui/SuiPageData.h b/engine/shared/library/sharedGame/src/shared/sui/SuiPageData.h new file mode 100644 index 00000000..d29703a7 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/sui/SuiPageData.h @@ -0,0 +1,109 @@ +//====================================================================== +// +// SuiPageData.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_SuiPageData_H +#define INCLUDED_SuiPageData_H + +//====================================================================== + +#include "sharedFoundation/NetworkId.h" +#include "sharedGame/SuiCommand.h" +#include "sharedMath/Vector.h" +#include + +class SuiCommand; + +namespace Archive +{ + class ReadIterator; + class ByteStream; +} + +//---------------------------------------------------------------------- + +class SuiPageData +{ +public: + + typedef stdvector::fwd SuiCommandVector; + +public: + + SuiPageData(); + SuiPageData(int pageId, std::string const & pageName); + + int getPageId() const; + std::string const & getPageName() const; + NetworkId const & getAssociatedObjectId() const; + Vector const & getAssociatedLocation() const; + float const getMaxRangeFromObject() const; + SuiCommandVector const & getCommands() const; + + bool addCommand(SuiCommand const & command); + void setAssociatedObjectIdWithMaxRange(NetworkId const & associatedObjectId, float maxRange); + void setAssociatedLocationWithMaxRange(Vector const & associatedLocation, float maxRange); + + void subscribeToPropertyForEvent(int eventType, std::string const & eventWidgetName, std::string const & propertyWidgetName, std::string const & propertyName); + + bool subscribeToEvent(int eventType, std::string const & eventWidgetName, std::string const & callback); + + SuiCommand const * findSubscribeToEventCommand(int eventType, std::string const & eventWidgetName) const; + SuiCommand * findSubscribeToEventCommand(int eventType, std::string const & eventWidgetName); + + SuiCommand const * findSubscribeToEventCommandByIndex(int index) const; + SuiCommand * findSubscribeToEventCommandByIndex(int index); + + bool operator==(SuiPageData const & rhs) const; + bool operator!=(SuiPageData const & rhs) const; + bool getPageUpdate(int commandIndex, SuiPageData & pageData) const; + +public: + + void get(Archive::ReadIterator & source); + void put(Archive::ByteStream & target) const; + +private: + + int m_pageId; + std::string m_pageName; + SuiCommandVector m_commands; + NetworkId m_associatedObjectId; + Vector m_associatedLocation; + float m_maxRangeFromObject; +}; + +//---------------------------------------------------------------------- + +inline int SuiPageData::getPageId() const +{ + return m_pageId; +} + +//---------------------------------------------------------------------- + +inline SuiCommand const * SuiPageData::findSubscribeToEventCommand(int eventType, std::string const & eventWidgetName) const +{ + return const_cast(this)->findSubscribeToEventCommand(eventType, eventWidgetName); +} + +//---------------------------------------------------------------------- + +inline SuiCommand const * SuiPageData::findSubscribeToEventCommandByIndex(int index) const +{ + return const_cast(this)->findSubscribeToEventCommandByIndex(index); +} + +//---------------------------------------------------------------------- + +inline bool SuiPageData::operator!=(SuiPageData const & rhs) const +{ + return !(*this==rhs); +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/sui/SuiPageDataArchive.cpp b/engine/shared/library/sharedGame/src/shared/sui/SuiPageDataArchive.cpp new file mode 100644 index 00000000..c0bd0a3c --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/sui/SuiPageDataArchive.cpp @@ -0,0 +1,29 @@ +//====================================================================== +// +// SuiPageDataArchive.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SuiPageDataArchive.h" + +#include "sharedGame/SuiPageData.h" + +//====================================================================== + +namespace Archive +{ + void get(ReadIterator & source, SuiPageData & target) + { + target.get(source); + } + + + void put(ByteStream & target, const SuiPageData & source) + { + source.put(target); + } +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/sui/SuiPageDataArchive.h b/engine/shared/library/sharedGame/src/shared/sui/SuiPageDataArchive.h new file mode 100644 index 00000000..61dff580 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/sui/SuiPageDataArchive.h @@ -0,0 +1,28 @@ +//====================================================================== +// +// SuiPageDataArchive.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_SuiPageDataArchive_H +#define INCLUDED_SuiPageDataArchive_H + +//====================================================================== + +class SuiPageData; + +//---------------------------------------------------------------------- + +namespace Archive +{ + class ReadIterator; + class ByteStream; + + void get(ReadIterator & source, SuiPageData & target); + void put(ByteStream & target, const SuiPageData & source); +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/sui/SuiWidgetProperty.cpp b/engine/shared/library/sharedGame/src/shared/sui/SuiWidgetProperty.cpp new file mode 100644 index 00000000..9c56b581 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/sui/SuiWidgetProperty.cpp @@ -0,0 +1,27 @@ +//====================================================================== +// +// SuiWidgetProperty.cpp +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/SuiWidgetProperty.h" + +//====================================================================== + +SuiWidgetProperty::SuiWidgetProperty() : +widgetName(), +propertyName() +{ +} + +//---------------------------------------------------------------------- + +SuiWidgetProperty::SuiWidgetProperty(std::string const & _widgetName, std::string const & _propertyName) : +widgetName(_widgetName), +propertyName(_propertyName) +{ +} + +//====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/sui/SuiWidgetProperty.h b/engine/shared/library/sharedGame/src/shared/sui/SuiWidgetProperty.h new file mode 100644 index 00000000..a100d526 --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/sui/SuiWidgetProperty.h @@ -0,0 +1,26 @@ +//====================================================================== +// +// SuiWidgetProperty.h +// copyright (c) 2004 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_SuiWidgetProperty_H +#define INCLUDED_SuiWidgetProperty_H + +//====================================================================== + +class SuiWidgetProperty +{ +public: + + SuiWidgetProperty(); + SuiWidgetProperty(std::string const & _widgetName, std::string const & propertyName); + + std::string widgetName; + std::string propertyName; +}; + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/travel/TravelManager.cpp b/engine/shared/library/sharedGame/src/shared/travel/TravelManager.cpp new file mode 100644 index 00000000..aceea77e --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/travel/TravelManager.cpp @@ -0,0 +1,387 @@ +// ====================================================================== +// +// TravelManager.cpp +// asommers +// +// copyright 2002, sony online entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/TravelManager.h" + +#include "sharedDebug/DebugFlags.h" +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/Iff.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedUtility/DataTable.h" + +#include +#include +#include + +// ====================================================================== + +namespace TravelManagerNamespace +{ + //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + typedef std::vector PlanetNameList; + typedef std::map PlanetNameToPlanetIndexMap; + typedef std::map, int> SingleHopRouteList; // <, cost> (planet1 ***IS ALWAYS <=*** planet2) + typedef std::map, std::pair > > AnyHopLeastCostRouteList; // <, >> (planet1 ***IS ALWAYS <=*** planet2) + + //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + void remove (); + void load (const char* fileName); + bool getPlanetIndex (const std::string& planetName, int& planetIndex); + bool getPlanetSingleHopCost(int planetIndex1, int planetIndex2, int& planetCost); + bool getPlanetAnyHopLeastCost(int planetIndex1, int planetIndex2, int& planetCost); + + //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + bool ms_installed; + bool ms_debugReport; + PlanetNameList ms_planetNameList; + PlanetNameToPlanetIndexMap ms_planetNameToPlanetIndexList; + SingleHopRouteList ms_singleHopRouteList; + AnyHopLeastCostRouteList ms_anyHopLeastCostRouteList; + + //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +} + +using namespace TravelManagerNamespace; + +// ====================================================================== +// STATIC PUBLIC TravelManager +// ====================================================================== + +void TravelManager::install () +{ + InstallTimer const installTimer("TravelManager::install "); + + DEBUG_FATAL (ms_installed, ("TravelManager::install: already installed")); + ms_installed = true; + + load ("datatables/travel/travel.iff"); + + DebugFlags::registerFlag (ms_debugReport, "SharedGame", "reportTravelManager"); + ExitChain::add (TravelManagerNamespace::remove, "TravelManagerNamespace::remove"); +} + +// ---------------------------------------------------------------------- + +int TravelManager::getNumberOfPlanets () +{ + return static_cast (ms_planetNameToPlanetIndexList.size ()); +} + +// ---------------------------------------------------------------------- + +bool TravelManager::getPlanetName (int planetIndex, std::string& planetName) +{ + if (planetIndex < 0 || planetIndex >= getNumberOfPlanets ()) + { + DEBUG_WARNING (true, ("TravelManager::getPlanetName: planetIndex out of range %i >= %i\n", planetIndex, getNumberOfPlanets ())); + return false; + } + + planetName = ms_planetNameList [static_cast (planetIndex)]; + return true; +} + +// ---------------------------------------------------------------------- + +bool TravelManager::getPlanetSingleHopCost (const std::string& planetName1, const std::string& planetName2, int& planetCost) +{ + int planetIndex1(0); + if (!getPlanetIndex (planetName1, planetIndex1)) + { + DEBUG_WARNING (true, ("TravelManager::getPlanetSingleHopCost: planet %s does not exist\n", planetName1.c_str ())); + return false; + } + + int planetIndex2(0); + if (!getPlanetIndex (planetName2, planetIndex2)) + { + DEBUG_WARNING (true, ("TravelManager::getPlanetSingleHopCost: planet %s does not exist\n", planetName2.c_str ())); + return false; + } + + return TravelManagerNamespace::getPlanetSingleHopCost(planetIndex1, planetIndex2, planetCost); +} + +// ---------------------------------------------------------------------- + +bool TravelManager::getPlanetAnyHopLeastCost (const std::string& planetName1, const std::string& planetName2, int& planetCost) +{ + int planetIndex1(0); + if (!getPlanetIndex (planetName1, planetIndex1)) + { + DEBUG_WARNING (true, ("TravelManager::getPlanetAnyHopLeastCost: planet %s does not exist\n", planetName1.c_str ())); + return false; + } + + int planetIndex2(0); + if (!getPlanetIndex (planetName2, planetIndex2)) + { + DEBUG_WARNING (true, ("TravelManager::getPlanetAnyHopLeastCost: planet %s does not exist\n", planetName2.c_str ())); + return false; + } + + return TravelManagerNamespace::getPlanetAnyHopLeastCost(planetIndex1, planetIndex2, planetCost); +} + +// ---------------------------------------------------------------------- + +bool TravelManager::getAdjacentPlanets (const std::string& planetName, std::set& planetList) +{ + int planetIndex(0); + if (!getPlanetIndex (planetName, planetIndex)) + { + DEBUG_WARNING (true, ("TravelManager::getAdjacentPlanets: planet %s does not exist\n", planetName.c_str ())); + return false; + } + + planetList.clear (); + planetList.insert (planetName); + + SingleHopRouteList::const_iterator iter = ms_singleHopRouteList.begin (); + for (; iter != ms_singleHopRouteList.end (); ++iter) + { + if (iter->first.first == planetIndex) + planetList.insert (ms_planetNameList [static_cast (iter->first.second)]); + else if (iter->first.second == planetIndex) + planetList.insert (ms_planetNameList [static_cast (iter->first.first)]); + } + + return true; +} + +// ====================================================================== +// STATIC PRIVATE TravelManager +// ====================================================================== + +void TravelManagerNamespace::remove () +{ + DEBUG_FATAL (!ms_installed, ("TravelManager::install: not installed")); + ms_installed = false; + + DebugFlags::unregisterFlag (ms_debugReport); +} + +// ---------------------------------------------------------------------- + +void TravelManagerNamespace::load (const char* fileName) +{ + ms_planetNameList.clear (); + ms_planetNameToPlanetIndexList.clear (); + ms_singleHopRouteList.clear (); + ms_anyHopLeastCostRouteList.clear (); + + Iff iff; + if (iff.open (fileName, true)) + { + DataTable dataTable; + dataTable.load (iff); + + //-- setup planet names + const int numberOfColumns = dataTable.getNumColumns (); + int column(0); + for (column = 1; column < numberOfColumns; ++column) + { + std::string const & planetName = dataTable.getColumnName (column); + FATAL ((ms_planetNameToPlanetIndexList.count(planetName) > 0), ("TravelManagerNamespace::load: duplicate planet %s in column %i", planetName.c_str (), column)); + + ms_planetNameToPlanetIndexList[planetName] = ms_planetNameList.size(); + ms_planetNameList.push_back (planetName); + } + + //-- setup "single hop" routes + const int numberOfRows = dataTable.getNumRows (); + int row(0); + for (row = 0; row < numberOfRows; ++row) + { + const std::string planetName1 = dataTable.getStringValue (0, row); + int planetIndex1(0); + if (!getPlanetIndex (planetName1, planetIndex1)) + DEBUG_FATAL (true, ("TravelManagerNamespace::load: planet %s could not be found for row %i", planetName1.c_str (), planetIndex1)); + + const int numberOfColumns = dataTable.getNumColumns (); + int column(0); + for (column = 1; column < numberOfColumns; ++column) + { + const int cost = dataTable.getIntValue (column, row); + if (cost != 0) + { + const std::string planetName2 = dataTable.getColumnName (column); + int planetIndex2(0); + if (!getPlanetIndex (planetName2, planetIndex2)) + DEBUG_FATAL (true, ("TravelManagerNamespace::load: planet %s could not be found for row %i", planetName2.c_str (), planetIndex2)); + + int dummy(0); + if (!TravelManager::getPlanetSingleHopCost (planetName1, planetName2, dummy)) + { + if (planetIndex2 < planetIndex1) + std::swap (planetIndex1, planetIndex2); + + ms_singleHopRouteList[std::make_pair(planetIndex1, planetIndex2)] = cost; + + DEBUG_REPORT_LOG (ms_debugReport, ("Added single hop travel route %s <--> %s costing %i\n", planetName1.c_str (), planetName2.c_str (), cost)); + } + } + } + } + + // setup "least cost" routes, some of which may involve multiple hops + int routeCost; + int const numberOfPlanets = ms_planetNameToPlanetIndexList.size(); + int indexPlanet1, indexPlanet2; + for (indexPlanet1 = 0; indexPlanet1 < numberOfPlanets; ++indexPlanet1) + { + for (indexPlanet2 = indexPlanet1; indexPlanet2 < numberOfPlanets; ++indexPlanet2) + { + std::multimap > > aStarSearchTree; + + // initialize A* search tree with all single hops from indexPlanet1 + for (int i = 0; i < numberOfPlanets; ++i) + { + if (getPlanetSingleHopCost(i, indexPlanet1, routeCost)) + { + std::vector > route; + route.push_back(std::make_pair(indexPlanet1, i)); + + aStarSearchTree.insert(std::make_pair(routeCost, route)); + } + } + + // now process the A* search tree + bool found = false; + int infiniteLoopSentinel = 0; + while (true) + { + if (aStarSearchTree.empty()) + break; + + if (++infiniteLoopSentinel == 10000) + break; + + // get the current best route + std::multimap > >::iterator begin = aStarSearchTree.begin(); + + // we are done if the current best route ends at the destination + if (begin->second[begin->second.size() - 1].second == indexPlanet2) + { + std::vector routeList; + for (std::vector >::const_iterator iter = begin->second.begin(); iter != begin->second.end(); ++iter) + { + if (iter != begin->second.begin()) + routeList.push_back(iter->first); + } + + ms_anyHopLeastCostRouteList[std::make_pair(indexPlanet1, indexPlanet2)] = std::make_pair(begin->first, routeList); + + std::string route = ms_planetNameList[indexPlanet1]; + for (std::vector::const_iterator iter2 = routeList.begin(); iter2 != routeList.end(); ++iter2) + { + route += " <--> "; + route += ms_planetNameList[*iter2]; + } + + route += " <--> "; + route += ms_planetNameList[indexPlanet2]; + + DEBUG_REPORT_LOG (ms_debugReport, ("Added least cost travel route %s costing %i\n", route.c_str (), begin->first)); + + if (getPlanetSingleHopCost(indexPlanet1, indexPlanet2, routeCost) && (routeCost > begin->first)) + { + DEBUG_REPORT_LOG (ms_debugReport, ("Single hop travel route %s <--> %s (%i) cost ***MORE*** than least cost travel route %s (%i)\n", ms_planetNameList[indexPlanet1].c_str(), ms_planetNameList[indexPlanet2].c_str(), routeCost, route.c_str (), begin->first)); + } + + found = true; + break; + } + + // otherwise add on new routes that can be reached from the current best route + int const currentBestRouteCost = begin->first; + std::vector > const currentBestRoute = begin->second; + + aStarSearchTree.erase(begin); + + for (int i = 0; i < numberOfPlanets; ++i) + { + if ((i != currentBestRoute[currentBestRoute.size() - 1].second) && (getPlanetSingleHopCost(i, currentBestRoute[currentBestRoute.size() - 1].second, routeCost))) + { + std::vector > route = currentBestRoute; + route.push_back(std::make_pair(currentBestRoute[currentBestRoute.size() - 1].second, i)); + + aStarSearchTree.insert(std::make_pair((currentBestRouteCost + routeCost), route)); + } + } + } + + if (!found) + FATAL (true, ("TravelManagerNamespace::load: couldn't find least cost travel route from %s to %s", ms_planetNameList[indexPlanet1].c_str(), ms_planetNameList[indexPlanet2].c_str())); + } + } + + // sanity check to make sure all planets have routes to each other + for (indexPlanet1 = 0; indexPlanet1 < numberOfPlanets; ++indexPlanet1) + { + for (indexPlanet2 = 0; indexPlanet2 < numberOfPlanets; ++indexPlanet2) + { + FATAL (!TravelManager::getPlanetAnyHopLeastCost(ms_planetNameList[indexPlanet1], ms_planetNameList[indexPlanet2], routeCost), ("TravelManagerNamespace::load: couldn't find least cost travel route from %s to %s", ms_planetNameList[indexPlanet1].c_str(), ms_planetNameList[indexPlanet2].c_str())); + FATAL (!getPlanetAnyHopLeastCost(indexPlanet1, indexPlanet2, routeCost), ("TravelManagerNamespace::load: couldn't find least cost travel route from %s to %s", ms_planetNameList[indexPlanet1].c_str(), ms_planetNameList[indexPlanet2].c_str())); + } + } + } +} + +// ---------------------------------------------------------------------- + +bool TravelManagerNamespace::getPlanetIndex (const std::string& planetName, int& planetIndex) +{ + PlanetNameToPlanetIndexMap::const_iterator iterFind = ms_planetNameToPlanetIndexList.find(planetName); + if (iterFind == ms_planetNameToPlanetIndexList.end()) + return false; + + planetIndex = iterFind->second; + return true; +} + +// ---------------------------------------------------------------------- + +bool TravelManagerNamespace::getPlanetSingleHopCost(int planetIndex1, int planetIndex2, int& planetCost) +{ + if (planetIndex2 < planetIndex1) + std::swap (planetIndex1, planetIndex2); + + SingleHopRouteList::const_iterator iterFind = ms_singleHopRouteList.find(std::make_pair(planetIndex1, planetIndex2)); + if (iterFind != ms_singleHopRouteList.end()) + { + planetCost = iterFind->second; + return true; + } + + return false; +} + +// ---------------------------------------------------------------------- + +bool TravelManagerNamespace::getPlanetAnyHopLeastCost(int planetIndex1, int planetIndex2, int& planetCost) +{ + if (planetIndex2 < planetIndex1) + std::swap (planetIndex1, planetIndex2); + + AnyHopLeastCostRouteList::const_iterator iterFind = ms_anyHopLeastCostRouteList.find(std::make_pair(planetIndex1, planetIndex2)); + if (iterFind != ms_anyHopLeastCostRouteList.end()) + { + planetCost = iterFind->second.first; + return true; + } + + return false; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/travel/TravelManager.h b/engine/shared/library/sharedGame/src/shared/travel/TravelManager.h new file mode 100644 index 00000000..01415b1c --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/travel/TravelManager.h @@ -0,0 +1,30 @@ +// ====================================================================== +// +// TravelManager.h +// asommers +// +// copyright 2002, sony online entertainment +// +// ====================================================================== + +#ifndef INCLUDED_TravelManager_H +#define INCLUDED_TravelManager_H + +// ====================================================================== + +class TravelManager +{ +public: + + static void install (); + + static int getNumberOfPlanets (); + static bool getPlanetName (int planetIndex, std::string& planetName); + static bool getPlanetSingleHopCost (const std::string& planetName1, const std::string& planetName2, int& planetCost); + static bool getPlanetAnyHopLeastCost (const std::string& planetName1, const std::string& planetName2, int& planetCost); + static bool getAdjacentPlanets (const std::string& planetName, stdset::fwd& planetSet); +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/shared/travel/TravelPoint.cpp b/engine/shared/library/sharedGame/src/shared/travel/TravelPoint.cpp new file mode 100644 index 00000000..42f9d19c --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/travel/TravelPoint.cpp @@ -0,0 +1,120 @@ +// ====================================================================== +// +// TravelPoint.cpp +// asommers +// +// copyright 2002, sony online entertainment +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" +#include "sharedGame/TravelPoint.h" + +#include "Archive/Archive.h" +#include "Archive/ByteStream.h" +#include "sharedFoundation/NetworkIdArchive.h" +#include "sharedMathArchive/VectorArchive.h" + +// ====================================================================== +// PUBLIC TravelPoint +// ====================================================================== + +TravelPoint::TravelPoint () : + m_name (), + m_gcwContestedRegion (), + m_position_w (), + m_cost (0), + m_interplanetary (false), + m_type (TPT_Unknown) +{ +} + +// ---------------------------------------------------------------------- + +TravelPoint::TravelPoint (const std::string& name, const std::string& gcwContestedRegion, const Vector& position_w, const int cost, const bool interplanetary, const TravelPointType type) : + m_name (name), + m_gcwContestedRegion (gcwContestedRegion), + m_position_w (position_w), + m_cost (cost), + m_interplanetary (interplanetary), + m_type (type) +{ +} + +// ---------------------------------------------------------------------- + +TravelPoint::TravelPoint (const TravelPoint& rhs) : + m_name (rhs.m_name), + m_gcwContestedRegion (rhs.m_gcwContestedRegion), + m_position_w (rhs.m_position_w), + m_cost (rhs.m_cost), + m_interplanetary (rhs.m_interplanetary), + m_type (rhs.m_type) +{ +} + +// ---------------------------------------------------------------------- + +TravelPoint& TravelPoint::operator= (const TravelPoint& rhs) +{ + if (this != &rhs) + { + m_name = rhs.m_name; + m_gcwContestedRegion = rhs.m_gcwContestedRegion; + m_position_w = rhs.m_position_w; + m_cost = rhs.m_cost; + m_interplanetary = rhs.m_interplanetary; + m_type = rhs.m_type; + } + + return *this; +} + +// ---------------------------------------------------------------------- + +TravelPoint::~TravelPoint () +{ +} + +// ---------------------------------------------------------------------- + +bool TravelPoint::operator== (const TravelPoint& rhs) const +{ + return + m_name == rhs.m_name && + m_gcwContestedRegion == rhs.m_gcwContestedRegion && + m_position_w == rhs.m_position_w && + m_cost == rhs.m_cost && + m_interplanetary == rhs.m_interplanetary && + m_type == rhs.m_type; +} + +// ====================================================================== + +namespace Archive +{ + void get(ReadIterator& source, TravelPoint& target) + { + Archive::get (source, target.m_name); + Archive::get (source, target.m_gcwContestedRegion); + Archive::get (source, target.m_position_w); + Archive::get (source, target.m_cost); + Archive::get (source, target.m_interplanetary); + + uint32 type = 0; + Archive::get (source, type); + target.m_type = (static_cast(type)); + } + + void put(ByteStream& target, const TravelPoint& source) + { + Archive::put (target, source.m_name); + Archive::put (target, source.m_gcwContestedRegion); + Archive::put (target, source.m_position_w); + Archive::put (target, source.m_cost); + Archive::put (target, source.m_interplanetary); + Archive::put (target, static_cast(source.m_type)); + } +} + +// ====================================================================== diff --git a/engine/shared/library/sharedGame/src/shared/travel/TravelPoint.h b/engine/shared/library/sharedGame/src/shared/travel/TravelPoint.h new file mode 100644 index 00000000..e90538dc --- /dev/null +++ b/engine/shared/library/sharedGame/src/shared/travel/TravelPoint.h @@ -0,0 +1,121 @@ +// ====================================================================== +// +// TravelPoint.h +// asommers +// +// copyright 2002, sony online entertainment +// +// ====================================================================== + +#ifndef INCLUDED_TravelPoint_H +#define INCLUDED_TravelPoint_H + +// ====================================================================== + +#include "sharedMath/Vector.h" + +class TravelPoint; + +// ====================================================================== + +namespace Archive +{ + class ReadIterator; + void get(ReadIterator& source, TravelPoint& target); + + class ByteStream; + void put(ByteStream& target, const TravelPoint& source); +} + +// ====================================================================== + +class TravelPoint +{ + friend void Archive::get(ReadIterator& source, TravelPoint& target); + friend void Archive::put(ByteStream& target, const TravelPoint& source); + +public: + + // *****WARNING***** + // this must be kept in sync with the corresponding definitions in base_class.java + // *****WARNING***** + enum TravelPointType + { + TPT_Unknown = 0x00000000, + TPT_NPC_Starport = 0x00000001, + TPT_NPC_Shuttleport = 0x00000002, + TPT_NPC_StaticBaseBeacon = 0x00000004, + TPT_PC_Shuttleport = 0x00000008, + TPT_PC_CampShuttleBeacon = 0x00000010, + }; + + TravelPoint (); + TravelPoint (const std::string& name, const std::string& gcwContestedRegion, const Vector& position_w, int cost, bool interplanetary, TravelPointType type); + TravelPoint (const TravelPoint& rhs); + TravelPoint& operator= (const TravelPoint& rhs); + ~TravelPoint (); + + bool operator== (const TravelPoint& rhs) const; + + const std::string& getName () const; + const std::string& getGcwContestedRegion () const; + const Vector& getPosition_w () const; + int getCost () const; + bool getInterplanetary () const; + TravelPointType getType () const; + +private: + + std::string m_name; + std::string m_gcwContestedRegion; + Vector m_position_w; + int m_cost; + bool m_interplanetary; + TravelPointType m_type; +}; + +// ---------------------------------------------------------------------- + +inline const std::string& TravelPoint::getName () const +{ + return m_name; +} + +// ---------------------------------------------------------------------- + +inline const std::string& TravelPoint::getGcwContestedRegion () const +{ + return m_gcwContestedRegion; +} + +// ---------------------------------------------------------------------- + +inline const Vector& TravelPoint::getPosition_w () const +{ + return m_position_w; +} + +// ---------------------------------------------------------------------- + +inline int TravelPoint::getCost () const +{ + return m_cost; +} + +// ---------------------------------------------------------------------- + +inline bool TravelPoint::getInterplanetary () const +{ + return m_interplanetary; +} + +// ---------------------------------------------------------------------- + +inline TravelPoint::TravelPointType TravelPoint::getType () const +{ + return m_type; +} + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedGame/src/win32/FirstSharedGame.cpp b/engine/shared/library/sharedGame/src/win32/FirstSharedGame.cpp new file mode 100644 index 00000000..b95c88bf --- /dev/null +++ b/engine/shared/library/sharedGame/src/win32/FirstSharedGame.cpp @@ -0,0 +1,9 @@ +// ====================================================================== +// +// FirstSharedGame.cpp +// Copyright 2002-2003 Sony Online Entertainment, Inc. +// All Rights Reserved. +// +// ====================================================================== + +#include "sharedGame/FirstSharedGame.h" diff --git a/engine/shared/library/sharedMathArchive/CMakeLists.txt b/engine/shared/library/sharedMathArchive/CMakeLists.txt new file mode 100644 index 00000000..9e1fc43c --- /dev/null +++ b/engine/shared/library/sharedMathArchive/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 2.8) + +project(sharedMathArchive) + +if(WIN32) + add_definitions(/D_CRT_SECURE_NO_WARNINGS) +endif() + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/public) + +add_subdirectory(src) diff --git a/engine/shared/library/sharedMathArchive/include/public/sharedMathArchive/FirstSharedMathArchive.h b/engine/shared/library/sharedMathArchive/include/public/sharedMathArchive/FirstSharedMathArchive.h new file mode 100644 index 00000000..f9424107 --- /dev/null +++ b/engine/shared/library/sharedMathArchive/include/public/sharedMathArchive/FirstSharedMathArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/FirstSharedMathArchive.h" diff --git a/engine/shared/library/sharedMathArchive/include/public/sharedMathArchive/QuaternionArchive.h b/engine/shared/library/sharedMathArchive/include/public/sharedMathArchive/QuaternionArchive.h new file mode 100644 index 00000000..c9706076 --- /dev/null +++ b/engine/shared/library/sharedMathArchive/include/public/sharedMathArchive/QuaternionArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/QuaternionArchive.h" diff --git a/engine/shared/library/sharedMathArchive/include/public/sharedMathArchive/SphereArchive.h b/engine/shared/library/sharedMathArchive/include/public/sharedMathArchive/SphereArchive.h new file mode 100644 index 00000000..07bd8d8f --- /dev/null +++ b/engine/shared/library/sharedMathArchive/include/public/sharedMathArchive/SphereArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/SphereArchive.h" diff --git a/engine/shared/library/sharedMathArchive/include/public/sharedMathArchive/TransformArchive.h b/engine/shared/library/sharedMathArchive/include/public/sharedMathArchive/TransformArchive.h new file mode 100644 index 00000000..e0520503 --- /dev/null +++ b/engine/shared/library/sharedMathArchive/include/public/sharedMathArchive/TransformArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/TransformArchive.h" diff --git a/engine/shared/library/sharedMathArchive/include/public/sharedMathArchive/VectorArchive.h b/engine/shared/library/sharedMathArchive/include/public/sharedMathArchive/VectorArchive.h new file mode 100644 index 00000000..2448efd7 --- /dev/null +++ b/engine/shared/library/sharedMathArchive/include/public/sharedMathArchive/VectorArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/VectorArchive.h" diff --git a/engine/shared/library/sharedMathArchive/src/CMakeLists.txt b/engine/shared/library/sharedMathArchive/src/CMakeLists.txt new file mode 100644 index 00000000..04d07f7e --- /dev/null +++ b/engine/shared/library/sharedMathArchive/src/CMakeLists.txt @@ -0,0 +1,28 @@ + +set(SHARED_SOURCES + shared/FirstSharedMathArchive.h + shared/QuaternionArchive.h + shared/SphereArchive.h + shared/TransformArchive.h + shared/VectorArchive.h +) + +if(WIN32) + set(EXCLUDE_PROJECT "") +else() + set(EXCLUDE_PROJECT "EXCLUDE_FROM_ALL") +endif() + +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR}/shared + #${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedDebug/include/public + #${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedFoundation/include/public + #${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedFoundationTypes/include/public + #${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedMemoryManager/include/public +) + +add_library(sharedMathArchive STATIC ${EXCLUDE_PROJECT} + ${SHARED_SOURCES} +) + +set_target_properties(sharedMathArchive PROPERTIES LINKER_LANGUAGE CXX) diff --git a/engine/shared/library/sharedMathArchive/src/shared/FirstSharedMathArchive.h b/engine/shared/library/sharedMathArchive/src/shared/FirstSharedMathArchive.h new file mode 100644 index 00000000..8e338aa1 --- /dev/null +++ b/engine/shared/library/sharedMathArchive/src/shared/FirstSharedMathArchive.h @@ -0,0 +1,17 @@ +// ====================================================================== +// +// FirstMathArchive.h +// copyright (c) 2001 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_FirstMathArchive_H +#define INCLUDED_FirstMathArchive_H + +// ====================================================================== + +#include "sharedFoundation/FirstSharedFoundation.h" + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedMathArchive/src/shared/QuaternionArchive.h b/engine/shared/library/sharedMathArchive/src/shared/QuaternionArchive.h new file mode 100644 index 00000000..e8fbb32f --- /dev/null +++ b/engine/shared/library/sharedMathArchive/src/shared/QuaternionArchive.h @@ -0,0 +1,91 @@ +// QuaternionArchive.h +// copyright 2001 Verant Interactive +// Author: Justin Randall + +#ifndef _INCLUDED_QuaternionArchive_H +#define _INCLUDED_QuaternionArchive_H + +//----------------------------------------------------------------------- + +#include "Archive/Archive.h" +#include "Archive/ByteStream.h" +#include "sharedMath/Quaternion.h" + +//----------------------------------------------------------------------- + +namespace Archive +{ + +//----------------------------------------------------------------------- +/** + @brief get a Quaternion from a source Archive::ByteStream + + Rertrieves a quaternion's x, y, z and w values from the + Archive::ByteStream object's current read position. + + @param source The Archive::ByteStream object containing the + quaternion x, y, z and w members at the current + read position. + @param target A Quaternion object that will receive the + x, y z and w components from the + Archive::ByteStream + + @see Archive + @see Archive::ByteStream + @see Vector + + @author Justin Randall +*/ +inline void get(ReadIterator & source, Quaternion & target) +{ + Archive::get(source, target.x); + Archive::get(source, target.y); + Archive::get(source, target.z); + Archive::get(source, target.w); + +#ifdef _WIN32 + if (_isnan(static_cast(target.w)) || _isnan(static_cast(target.x)) || _isnan(static_cast(target.y)) || _isnan(static_cast(target.z))) +#else + if (isnan(target.w) || isnan(target.x) || isnan(target.y) || isnan(target.z)) +#endif + { + target.w = 1.0f; + target.x = 0.0f; + target.y = 0.0f; + target.z = 0.0f; + } +} + +//----------------------------------------------------------------------- +/** + @brief put a Quaternion into an Archive::ByteStream + + Puts the Quaternion into the Archive::ByteStream at its current + write position. + + @param target The ByteStream object that will receive the data + at its current write position. + @param source A Quaternion containing the x, y, z and w + components that will be written to the ByteStream + + @see Archive + @see Archive::ByteStream + @see Quaternion + + @author Justin Randall +*/ +inline void put(ByteStream & target, const Quaternion & source) +{ + Archive::put(target, source.x); + Archive::put(target, source.y); + Archive::put(target, source.z); + Archive::put(target, source.w); +} + +//----------------------------------------------------------------------- + +}//namespace Archive + +//----------------------------------------------------------------------- + +#endif // _INCLUDED_QuaternionArchive_H diff --git a/engine/shared/library/sharedMathArchive/src/shared/SphereArchive.h b/engine/shared/library/sharedMathArchive/src/shared/SphereArchive.h new file mode 100644 index 00000000..3c8884db --- /dev/null +++ b/engine/shared/library/sharedMathArchive/src/shared/SphereArchive.h @@ -0,0 +1,40 @@ +// SphereArchive.h +// copyright 2004 Sony Online Entertainment + +#ifndef _INCLUDED_SphereArchive_H +#define _INCLUDED_SphereArchive_H + +//----------------------------------------------------------------------- + +#include "Archive/Archive.h" +#include "Archive/ByteStream.h" +#include "sharedMath/Sphere.h" +#include "sharedMathArchive/VectorArchive.h" + +//----------------------------------------------------------------------- +namespace Archive +{ + +inline void get(ReadIterator & source, Sphere & target) +{ + Vector v; + float f; + Archive::get(source, v); + Archive::get(source, f); + target.setCenter(v); + target.setRadius(f); +} + +//----------------------------------------------------------------------- + +inline void put(ByteStream & target, const Sphere & source) +{ + Archive::put(target, source.getCenter()); + Archive::put(target, static_cast(source.getRadius())); +} + +}//namespace Archive + +//----------------------------------------------------------------------- + +#endif // _INCLUDED_SphereArchive_H diff --git a/engine/shared/library/sharedMathArchive/src/shared/TransformArchive.h b/engine/shared/library/sharedMathArchive/src/shared/TransformArchive.h new file mode 100644 index 00000000..633a8dd6 --- /dev/null +++ b/engine/shared/library/sharedMathArchive/src/shared/TransformArchive.h @@ -0,0 +1,102 @@ +// TransformArchive.h +// copyright 2001 Verant Interactive +// Author: Justin Randall + +#ifndef _INCLUDED_TransformArchive_H +#define _INCLUDED_TransformArchive_H + +//----------------------------------------------------------------------- + +#include "Archive/Archive.h" +#include "Archive/ByteStream.h" +#include "sharedMathArchive/QuaternionArchive.h" +#include "sharedMath/Transform.h" +#include "sharedMathArchive/VectorArchive.h" + +//----------------------------------------------------------------------- +namespace Archive +{ + +//----------------------------------------------------------------------- +/** + @brief Get a Transform from a ByteStream object + + Reads a Quaternion and a Vector from the source + ByteStream object at it's current read position, then + sets the Transform data using the Quaternion and Vector + values. + + @param source The ByteStream object containing the Quaternion + and Vector data at it's current read position. + @param target A Transform object that will receive values from + the Quaternion and Vector. + + @see Archive + @see Archive::ByteStream + @see Transform + @see Quaternion + @see Vector + @see Archive::get(const ByteStream & source, Quaternion & target) + @see Archive::get(const ByteStream & source, Vector & target) + + @author Justin Randall +*/ +inline void get(ReadIterator & source, Transform & target) +{ + Quaternion q; + Vector v; + Archive::get(source, q); + Archive::get(source, v); + q.getTransform(&target); +#ifdef _DEBUG + target.validate(); +#endif + target.setPosition_p(v); +} + +//----------------------------------------------------------------------- +/** + @brief Put a Transform into a ByteStream object + + Extracts a Quaternion and Vector from the supplied Transform, then + puts the Quaternion followed by the Vector into the ByteStream + at its current write position. + + @param target The ByteStream that will receive the Quaternion + and Vector derived from the Transform. The + Quaternion and Vector data is committed at the + ByteStream obect's current write position. + @param source A transform that will be used to extract + Quaternion and Vector data, which is then + put into the target ByteStream object. + + @see Archive + @see Archive::ByteStream + @see Transform + @see Quaternion + @see Vector + @see Archive::put(ByteStream & target, const Vector & source) + @see Archive::put(ByteStream & target, const Quaternion & source) + + @author Justin Randall +*/ +inline void put(ByteStream & target, const Transform & source) +{ +#ifdef _DEBUG + source.validate(); +#endif + + Quaternion q(source); + + Vector v = source.getPosition_p(); + Archive::put(target, q); + Archive::put(target, v); +} + +//----------------------------------------------------------------------- + +}//namespace Archive + +//----------------------------------------------------------------------- + +#endif // _INCLUDED_TransformArchive_H diff --git a/engine/shared/library/sharedMathArchive/src/shared/VectorArchive.h b/engine/shared/library/sharedMathArchive/src/shared/VectorArchive.h new file mode 100644 index 00000000..6b599b0b --- /dev/null +++ b/engine/shared/library/sharedMathArchive/src/shared/VectorArchive.h @@ -0,0 +1,123 @@ +// VectorArchive.h +// copyright 2001 Verant Interactive +// Author: Justin Randall + +#ifndef _INCLUDED_VectorArchive_H +#define _INCLUDED_VectorArchive_H + +//----------------------------------------------------------------------- + +#include "Archive/Archive.h" +#include "Archive/ByteStream.h" +#include "sharedMath/Vector.h" + +//----------------------------------------------------------------------- + +namespace Archive +{ +void get(const ByteStream & source, Vector & target); +void put(ByteStream & target, const Vector & source); + +//----------------------------------------------------------------------- +/** + @brief get a Vector from an Archive::ByteStream object + + This get's the vector data as 3 floats: x, y, and z + + @param source The Archive::ByteStream object containing the Vector + data at it's current read position. + @param target A Vector object that will have it's values set from + the Archive::ByteStream data + + @see Archive + @see Archive::ByteStream + @see Vector + + @author Justin Randall +*/ +inline void get(ReadIterator & source, Vector & target) +{ + Archive::get(source, target.x); + Archive::get(source, target.y); + Archive::get(source, target.z); +} + +//----------------------------------------------------------------------- +/** + @brief put a Vector into an Archive::ByteStream object + + This puts the Vector object's data into the Archive::ByteStream + at it's current write position as x, y and z respectively. + + @param target The Archive::ByteStream object receiving the + Vector object's values at its current write + position. + @param source A Vector object containing the data to be written + to the Archive::ByteStream + + @see Archive + @see Archive::ByteStream + @see Vector + + @author Justin Randall +*/ +inline void put(ByteStream & target, const Vector & source) +{ + Archive::put(target, source.x); + Archive::put(target, source.y); + Archive::put(target, source.z); +} + +//----------------------------------------------------------------------- + +/** + @brief get a Vector from an Archive::ByteStream object + + This get's the vector data as 3 floats: x, y, and z + + @param source The Archive::ByteStream object containing the Vector + data at it's current read position. + @param target A Vector object that will have it's values set from + the Archive::ByteStream data + + @see Archive + @see Archive::ByteStream + @see Vector +*/ +inline void get(ReadIterator & source, Vector * target) +{ + Archive::get(source, target->x); + Archive::get(source, target->y); + Archive::get(source, target->z); +} + +//----------------------------------------------------------------------- + +/** + @brief put a Vector into an Archive::ByteStream object + + This puts the Vector object's data into the Archive::ByteStream + at it's current write position as x, y and z respectively. + + @param target The Archive::ByteStream object receiving the + Vector object's values at its current write + position. + @param source A Vector object containing the data to be written + to the Archive::ByteStream + + @see Archive + @see Archive::ByteStream + @see Vector +*/ +inline void put(ByteStream & target, const Vector * source) +{ + Archive::put(target, source->x); + Archive::put(target, source->y); + Archive::put(target, source->z); +} + +//----------------------------------------------------------------------- + +}//namespace Archive + +#endif // _INCLUDED_VectorArchive_H diff --git a/engine/shared/library/sharedNetworkMessages/src/CMakeLists.txt b/engine/shared/library/sharedNetworkMessages/src/CMakeLists.txt index df969209..9c3ca964 100644 --- a/engine/shared/library/sharedNetworkMessages/src/CMakeLists.txt +++ b/engine/shared/library/sharedNetworkMessages/src/CMakeLists.txt @@ -709,8 +709,12 @@ include_directories( ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedDebug/include/public ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedFoundation/include/public ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedFoundationTypes/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedGame/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedMath/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedNetwork/include/public ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedMemoryManager/include/public ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedMessageDispatch/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedUtility/include/public ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/archive/include ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/localization/include ${SWG_EXTERNALS_SOURCE_DIR}/ours/library/localizationArchive/include/public diff --git a/engine/shared/library/sharedUtility/CMakeLists.txt b/engine/shared/library/sharedUtility/CMakeLists.txt new file mode 100644 index 00000000..72836386 --- /dev/null +++ b/engine/shared/library/sharedUtility/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 2.8) + +project(sharedUtility) + +if(WIN32) + add_definitions(/D_CRT_SECURE_NO_WARNINGS) +endif() + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include/public) + +add_subdirectory(src) diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/BakedTerrain.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/BakedTerrain.h new file mode 100644 index 00000000..b8564bed --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/BakedTerrain.h @@ -0,0 +1 @@ +#include "../../src/shared/BakedTerrain.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/BakedTerrainReader.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/BakedTerrainReader.h new file mode 100644 index 00000000..506371ac --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/BakedTerrainReader.h @@ -0,0 +1 @@ +#include "../../src/shared/BakedTerrainReader.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/CachedFileManager.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/CachedFileManager.h new file mode 100644 index 00000000..5fdd6744 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/CachedFileManager.h @@ -0,0 +1 @@ +#include "../../src/shared/CachedFileManager.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/Callback.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/Callback.h new file mode 100644 index 00000000..22c86c22 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/Callback.h @@ -0,0 +1 @@ +#include "../../src/shared/Callback.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/CallbackReceiver.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/CallbackReceiver.h new file mode 100644 index 00000000..9ca36d7d --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/CallbackReceiver.h @@ -0,0 +1 @@ +#include "../../src/shared/CallbackReceiver.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/ConfigSharedUtility.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/ConfigSharedUtility.h new file mode 100644 index 00000000..99632b0b --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/ConfigSharedUtility.h @@ -0,0 +1 @@ +#include "../../src/shared/ConfigSharedUtility.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/CurrentUserOptionManager.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/CurrentUserOptionManager.h new file mode 100644 index 00000000..0e3f69d4 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/CurrentUserOptionManager.h @@ -0,0 +1 @@ +#include "../../src/shared/CurrentUserOptionManager.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/DataTable.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/DataTable.h new file mode 100644 index 00000000..bc4e46e4 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/DataTable.h @@ -0,0 +1 @@ +#include "../../src/shared/DataTable.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/DataTableCell.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/DataTableCell.h new file mode 100644 index 00000000..cf7307c4 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/DataTableCell.h @@ -0,0 +1 @@ +#include "../../src/shared/DataTableCell.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/DataTableColumnType.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/DataTableColumnType.h new file mode 100644 index 00000000..d55019c6 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/DataTableColumnType.h @@ -0,0 +1 @@ +#include "../../src/shared/DataTableColumnType.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/DataTableManager.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/DataTableManager.h new file mode 100644 index 00000000..2e9abed0 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/DataTableManager.h @@ -0,0 +1 @@ +#include "../../src/shared/DataTableManager.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/DataTableWriter.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/DataTableWriter.h new file mode 100644 index 00000000..204ab465 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/DataTableWriter.h @@ -0,0 +1 @@ +#include "../../src/shared/DataTableWriter.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/FileName.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/FileName.h new file mode 100644 index 00000000..971de30f --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/FileName.h @@ -0,0 +1 @@ +#include "../../src/shared/FileName.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/FirstSharedUtility.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/FirstSharedUtility.h new file mode 100644 index 00000000..2e47658e --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/FirstSharedUtility.h @@ -0,0 +1 @@ +#include "../../src/shared/FirstSharedUtility.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/HttpGetEncoder.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/HttpGetEncoder.h new file mode 100644 index 00000000..7fe74fbd --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/HttpGetEncoder.h @@ -0,0 +1 @@ +#include "../../src/shared/HttpGetEncoder.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/IndexedCache.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/IndexedCache.h new file mode 100644 index 00000000..1cab4bd1 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/IndexedCache.h @@ -0,0 +1 @@ +#include "../../src/shared/IndexedCache.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/InstallationResourceData.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/InstallationResourceData.h new file mode 100644 index 00000000..97cbdf03 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/InstallationResourceData.h @@ -0,0 +1 @@ +#include "../../src/shared/InstallationResourceData.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/InstallationResourceDataArchive.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/InstallationResourceDataArchive.h new file mode 100644 index 00000000..fb7839d2 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/InstallationResourceDataArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/InstallationResourceDataArchive.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/InteriorLayoutReaderWriter.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/InteriorLayoutReaderWriter.h new file mode 100644 index 00000000..13167af3 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/InteriorLayoutReaderWriter.h @@ -0,0 +1 @@ +#include "../../src/shared/InteriorLayoutReaderWriter.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/LocalMachineOptionManager.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/LocalMachineOptionManager.h new file mode 100644 index 00000000..0827d973 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/LocalMachineOptionManager.h @@ -0,0 +1 @@ +#include "../../src/shared/LocalMachineOptionManager.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/Location.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/Location.h new file mode 100644 index 00000000..64b8215d --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/Location.h @@ -0,0 +1 @@ +#include "../../src/shared/Location.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/LocationArchive.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/LocationArchive.h new file mode 100644 index 00000000..1113b031 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/LocationArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/LocationArchive.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/LocationManager.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/LocationManager.h new file mode 100644 index 00000000..4bb83e90 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/LocationManager.h @@ -0,0 +1 @@ +#include "../../src/shared/LocationManager.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/NameGenerator.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/NameGenerator.h new file mode 100644 index 00000000..5980b743 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/NameGenerator.h @@ -0,0 +1 @@ +#include "../../src/shared/NameGenerator.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/NetworkIdAutoDeltaPackedMap.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/NetworkIdAutoDeltaPackedMap.h new file mode 100644 index 00000000..780a0fde --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/NetworkIdAutoDeltaPackedMap.h @@ -0,0 +1 @@ +#include "../../src/shared/NetworkIdAutoDeltaPackedMap.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/OptionManager.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/OptionManager.h new file mode 100644 index 00000000..7829e360 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/OptionManager.h @@ -0,0 +1 @@ +#include "../../src/shared/OptionManager.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedFixedPointMap.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedFixedPointMap.h new file mode 100644 index 00000000..0cfcc7be --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedFixedPointMap.h @@ -0,0 +1 @@ +#include "../../src/shared/PackedFixedPointMap.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedIntegerMap.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedIntegerMap.h new file mode 100644 index 00000000..2fb9efac --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedIntegerMap.h @@ -0,0 +1 @@ +#include "../../src/shared/PackedIntegerMap.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedPosition.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedPosition.h new file mode 100644 index 00000000..b18820aa --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedPosition.h @@ -0,0 +1,2 @@ +#include "../../src/shared/PackedPosition.h" + diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedQuaternion.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedQuaternion.h new file mode 100644 index 00000000..b326886b --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedQuaternion.h @@ -0,0 +1,2 @@ +#include "../../src/shared/PackedQuaternion.h" + diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedRotationRate.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedRotationRate.h new file mode 100644 index 00000000..0c8157cd --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedRotationRate.h @@ -0,0 +1,2 @@ +#include "../../src/shared/PackedRotationRate.h" + diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedTransform.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedTransform.h new file mode 100644 index 00000000..67419fab --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedTransform.h @@ -0,0 +1,2 @@ +#include "../../src/shared/PackedTransform.h" + diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedUnitVector.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedUnitVector.h new file mode 100644 index 00000000..6d212521 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedUnitVector.h @@ -0,0 +1,2 @@ +#include "../../src/shared/PackedUnitVector.h" + diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedVelocity.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedVelocity.h new file mode 100644 index 00000000..b250f93e --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/PackedVelocity.h @@ -0,0 +1,2 @@ +#include "../../src/shared/PackedVelocity.h" + diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/PooledString.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/PooledString.h new file mode 100644 index 00000000..998356a9 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/PooledString.h @@ -0,0 +1,2 @@ +#include "../../src/shared/PooledString.h" + diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/RotaryCache.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/RotaryCache.h new file mode 100644 index 00000000..af4a0c99 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/RotaryCache.h @@ -0,0 +1 @@ +#include "../../src/shared/RotaryCache.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/SetupSharedUtility.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/SetupSharedUtility.h new file mode 100644 index 00000000..8fbae3c2 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/SetupSharedUtility.h @@ -0,0 +1 @@ +#include "../../src/shared/SetupSharedUtility.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/StartingLocationData.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/StartingLocationData.h new file mode 100644 index 00000000..f7c20580 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/StartingLocationData.h @@ -0,0 +1 @@ +#include "../../src/shared/StartingLocationData.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/StartingLocationDataArchive.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/StartingLocationDataArchive.h new file mode 100644 index 00000000..ecfd63f5 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/StartingLocationDataArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/StartingLocationDataArchive.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/StartingLocationManager.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/StartingLocationManager.h new file mode 100644 index 00000000..0550f783 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/StartingLocationManager.h @@ -0,0 +1 @@ +#include "../../src/shared/StartingLocationManager.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/SynchronizedWeatherGenerator.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/SynchronizedWeatherGenerator.h new file mode 100644 index 00000000..68c0acf3 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/SynchronizedWeatherGenerator.h @@ -0,0 +1 @@ +#include "../../src/shared/SynchronizedWeatherGenerator.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/TemplateParameter.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/TemplateParameter.h new file mode 100644 index 00000000..3851d929 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/TemplateParameter.h @@ -0,0 +1 @@ +#include "../../src/shared/TemplateParameter.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/UniqueNameList.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/UniqueNameList.h new file mode 100644 index 00000000..1bc599e7 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/UniqueNameList.h @@ -0,0 +1 @@ +#include "../../src/shared/UniqueNameList.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueDictionary.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueDictionary.h new file mode 100644 index 00000000..ea2638d8 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueDictionary.h @@ -0,0 +1 @@ +#include "../../src/shared/ValueDictionary.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueDictionaryArchive.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueDictionaryArchive.h new file mode 100644 index 00000000..dd2744f8 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueDictionaryArchive.h @@ -0,0 +1 @@ +#include "../../src/shared/ValueDictionaryArchive.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeBase.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeBase.h new file mode 100644 index 00000000..c0a560c6 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeBase.h @@ -0,0 +1 @@ +#include "../../src/shared/ValueTypeBase.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeBool.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeBool.h new file mode 100644 index 00000000..4dab0b15 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeBool.h @@ -0,0 +1 @@ +#include "../../src/shared/ValueTypeBool.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeFloat.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeFloat.h new file mode 100644 index 00000000..a59890ed --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeFloat.h @@ -0,0 +1 @@ +#include "../../src/shared/ValueTypeFloat.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeObjId.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeObjId.h new file mode 100644 index 00000000..611cfcb0 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeObjId.h @@ -0,0 +1 @@ +#include "../../src/shared/ValueTypeObjId.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeSignedInt.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeSignedInt.h new file mode 100644 index 00000000..5667e5a3 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeSignedInt.h @@ -0,0 +1 @@ +#include "../../src/shared/ValueTypeSignedInt.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeString.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeString.h new file mode 100644 index 00000000..d939dfe3 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/ValueTypeString.h @@ -0,0 +1 @@ +#include "../../src/shared/ValueTypeString.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/WeatherData.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/WeatherData.h new file mode 100644 index 00000000..57f1a473 --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/WeatherData.h @@ -0,0 +1 @@ +#include "../../src/shared/WeatherData.h" diff --git a/engine/shared/library/sharedUtility/include/public/sharedUtility/WorldSnapshotReaderWriter.h b/engine/shared/library/sharedUtility/include/public/sharedUtility/WorldSnapshotReaderWriter.h new file mode 100644 index 00000000..036323ba --- /dev/null +++ b/engine/shared/library/sharedUtility/include/public/sharedUtility/WorldSnapshotReaderWriter.h @@ -0,0 +1 @@ +#include "../../src/shared/WorldSnapshotReaderWriter.h" diff --git a/engine/shared/library/sharedUtility/src/CMakeLists.txt b/engine/shared/library/sharedUtility/src/CMakeLists.txt new file mode 100644 index 00000000..4e8a58f0 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/CMakeLists.txt @@ -0,0 +1,122 @@ + +set(SHARED_SOURCES + shared/BakedTerrain.cpp + shared/BakedTerrain.h + shared/BakedTerrainReader.cpp + shared/BakedTerrainReader.h + shared/CachedFileManager.cpp + shared/CachedFileManager.h + shared/Callback.cpp + shared/Callback.h + shared/CallbackReceiver.h + shared/ConfigSharedUtility.cpp + shared/ConfigSharedUtility.h + shared/CurrentUserOptionManager.cpp + shared/CurrentUserOptionManager.h + shared/DataTable.cpp + shared/DataTable.h + shared/DataTableCell.cpp + shared/DataTableCell.h + shared/DataTableColumnType.cpp + shared/DataTableColumnType.h + shared/DataTableManager.cpp + shared/DataTableManager.h + shared/DataTableWriter.cpp + shared/DataTableWriter.h + shared/FileName.cpp + shared/FileName.h + shared/FirstSharedUtility.h + shared/HttpGetEncoder.cpp + shared/HttpGetEncoder.h + shared/IndexedCache.cpp + shared/IndexedCache.h + shared/InstallationResourceData.h + shared/InstallationResourceDataArchive.h + shared/InteriorLayoutReaderWriter.cpp + shared/InteriorLayoutReaderWriter.h + shared/Location.cpp + shared/Location.h + shared/LocationArchive.cpp + shared/LocationArchive.h + shared/LocalMachineOptionManager.cpp + shared/LocalMachineOptionManager.h + shared/LocationManager.cpp + shared/LocationManager.h + shared/NameGenerator.cpp + shared/NameGenerator.h + shared/NetworkIdAutoDeltaPackedMap.cpp + shared/NetworkIdAutoDeltaPackedMap.h + shared/OptionManager.cpp + shared/OptionManager.h + shared/PackedIntegerMap.cpp + shared/PackedIntegerMap.h + shared/PackedFixedPointMap.cpp + shared/PackedFixedPointMap.h + shared/PackedPosition.h + shared/PackedQuaternion.h + shared/PackedRotationRate.h + shared/PackedTransform.h + shared/PackedUnitVector.h + shared/PackedVelocity.h + shared/PooledString.cpp + shared/PooledString.h + shared/RotaryCache.cpp + shared/RotaryCache.h + shared/SetupSharedUtility.cpp + shared/SetupSharedUtility.h + shared/StartingLocationData.cpp + shared/StartingLocationData.h + shared/StartingLocationDataArchive.cpp + shared/StartingLocationDataArchive.h + shared/StartingLocationManager.cpp + shared/StartingLocationManager.h + shared/SynchronizedWeatherGenerator.cpp + shared/SynchronizedWeatherGenerator.h + shared/TemplateParameter.cpp + shared/TemplateParameter.h + shared/UniqueNameList.cpp + shared/UniqueNameList.h + shared/ValueDictionary.cpp + shared/ValueDictionary.h + shared/ValueDictionaryArchive.cpp + shared/ValueDictionaryArchive.h + shared/ValueTypeBase.cpp + shared/ValueTypeBase.h + shared/ValueTypeBool.cpp + shared/ValueTypeBool.h + shared/ValueTypeFloat.cpp + shared/ValueTypeFloat.h + shared/ValueTypeObjId.cpp + shared/ValueTypeObjId.h + shared/ValueTypeSignedInt.cpp + shared/ValueTypeSignedInt.h + shared/ValueTypeString.cpp + shared/ValueTypeString.h + shared/WeatherData.cpp + shared/WeatherData.h + shared/WorldSnapshotReaderWriter.cpp + shared/WorldSnapshotReaderWriter.h +) + +if(WIN32) + set(PLATFORM_SOURCES + win32/FirstSharedUtility.cpp + ) + + include_directories(${CMAKE_CURRENT_SOURCE_DIR}/win32) +else() + set(PLATFORM_SOURCES "") +endif() + +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR}/shared + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedDebug/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedFoundation/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedFoundationTypes/include/public + ${SWG_ENGINE_SOURCE_DIR}/shared/library/sharedMemoryManager/include/public +) + +add_library(sharedUtility STATIC + ${SHARED_SOURCES} + ${PLATFORM_SOURCES} +) diff --git a/engine/shared/library/sharedUtility/src/shared/BakedTerrain.cpp b/engine/shared/library/sharedUtility/src/shared/BakedTerrain.cpp new file mode 100644 index 00000000..74e9d65f --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/BakedTerrain.cpp @@ -0,0 +1,361 @@ +//=================================================================== +// +// BakedTerrain.cpp +// asommers +// +// copyright 2002, sony online entertainment +// +//=================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/BakedTerrain.h" + +#include "sharedFile/Iff.h" +#include "sharedMath/Rectangle2d.h" +#include "sharedMath/Vector2d.h" + +#include + +//=================================================================== + +namespace +{ + const Tag TAG_WMAP = TAG (W,M,A,P); + const Tag TAG_SMAP = TAG (S,M,A,P); +} + +//=================================================================== +// PUBLIC BakedTerrain +//=================================================================== + +BakedTerrain::BakedTerrain () : + m_mapWidthInMeters (0.f), + m_chunkWidthInMeters (0.f), + m_width (0), + m_height (0), + m_waterMap (0), + m_slopeMap (0) +{ +} + +//------------------------------------------------------------------- + +BakedTerrain::~BakedTerrain () +{ + destroy (); + + m_waterMap = 0; + m_slopeMap = 0; +} + +//------------------------------------------------------------------- + +void BakedTerrain::load (Iff& iff) +{ + destroy (); + + switch (iff.getCurrentName ()) + { + case TAG_0000: + load_0000 (iff); + break; + + case TAG_0001: + load_0001 (iff); + break; + + default: + { + char tagBuffer [5]; + ConvertTagToString (iff.getCurrentName (), tagBuffer); + + char buffer [128]; + iff.formatLocation (buffer, sizeof (buffer)); + DEBUG_FATAL (true, ("invalid BakedTerrain version %s/%s", buffer, tagBuffer)); + } + break; + } +} + +//------------------------------------------------------------------- + +void BakedTerrain::save (Iff& iff) const +{ + iff.insertForm (TAG_0001); + + iff.insertChunk (TAG_DATA); + iff.insertChunkData (m_mapWidthInMeters); + iff.insertChunkData (m_chunkWidthInMeters); + iff.insertChunkData (m_width); + iff.insertChunkData (m_height); + iff.exitChunk (TAG_DATA); + + iff.insertChunk (TAG_WMAP); + iff.insertChunkData (m_waterMap, m_width * m_height); + iff.exitChunk (TAG_WMAP); + + iff.insertChunk (TAG_SMAP); + iff.insertChunkData (m_slopeMap, m_width * m_height); + iff.exitChunk (TAG_SMAP); + + iff.exitForm (TAG_0001); +} + +//------------------------------------------------------------------- + +float BakedTerrain::getMapWidthInMeters () const +{ + return m_mapWidthInMeters; +} + +//------------------------------------------------------------------- + +float BakedTerrain::getChunkWidthInMeters () const +{ + return m_chunkWidthInMeters; +} + +//------------------------------------------------------------------- + +bool BakedTerrain::getWater (const int chunkX, const int chunkY) const +{ + if (!m_waterMap) + return false; + + const int x = chunkX + static_cast ((m_mapWidthInMeters / m_chunkWidthInMeters) * 0.5f); + const int y = chunkY + static_cast ((m_mapWidthInMeters / m_chunkWidthInMeters) * 0.5f); + + return getBool (m_waterMap, x, y); +} + +//------------------------------------------------------------------- + +bool BakedTerrain::getSlope (const int chunkX, const int chunkY) const +{ + if (!m_slopeMap) + return false; + + const int x = chunkX + static_cast ((m_mapWidthInMeters / m_chunkWidthInMeters) * 0.5f); + const int y = chunkY + static_cast ((m_mapWidthInMeters / m_chunkWidthInMeters) * 0.5f); + + return getBool (m_slopeMap, x, y); +} + +//------------------------------------------------------------------- + +bool BakedTerrain::getWater (const Vector2d& position) const +{ + if (!m_waterMap) + return false; + + int x; + int y; + calculateMapXy (position, x, y); + + return getBool (m_waterMap, x, y); +} + +//------------------------------------------------------------------- + +bool BakedTerrain::getSlope (const Vector2d& position) const +{ + if (!m_slopeMap) + return false; + + int x; + int y; + calculateMapXy (position, x, y); + + return getBool (m_slopeMap, x, y); +} + +//------------------------------------------------------------------- + +bool BakedTerrain::getWater (const Rectangle2d& rectangle) const +{ + return getMap (m_waterMap, rectangle); +} + +//------------------------------------------------------------------- + +bool BakedTerrain::getSlope (const Rectangle2d& rectangle) const +{ + return getMap (m_slopeMap, rectangle); +} + +//------------------------------------------------------------------- + +void BakedTerrain::setMap (const float mapWidthInMeters, const float chunkWidthInMeters) +{ + destroy (); + + m_mapWidthInMeters = mapWidthInMeters; + m_chunkWidthInMeters = chunkWidthInMeters; + m_width = static_cast (m_mapWidthInMeters / m_chunkWidthInMeters) / 8; + m_height = static_cast (m_mapWidthInMeters / m_chunkWidthInMeters); + const int size = m_width * m_height; + m_waterMap = new uint8 [size]; + memset (m_waterMap, 0, size); + m_slopeMap = new uint8 [size]; + memset (m_slopeMap, 0, size); +} + +//------------------------------------------------------------------- + +void BakedTerrain::setWater (int chunkX, int chunkY, bool water) +{ + if (!m_waterMap) + return; + + const int x = chunkX + static_cast ((m_mapWidthInMeters / m_chunkWidthInMeters) * 0.5f); + const int y = chunkY + static_cast ((m_mapWidthInMeters / m_chunkWidthInMeters) * 0.5f); + + setBool (m_waterMap, x, y, water); +} + +//------------------------------------------------------------------- + +void BakedTerrain::setSlope (int chunkX, int chunkY, bool slope) +{ + if (!m_slopeMap) + return; + + const int x = chunkX + static_cast ((m_mapWidthInMeters / m_chunkWidthInMeters) * 0.5f); + const int y = chunkY + static_cast ((m_mapWidthInMeters / m_chunkWidthInMeters) * 0.5f); + + setBool (m_slopeMap, x, y, slope); +} + +//=================================================================== +// PRIVATE BakedTerrain +//=================================================================== + +void BakedTerrain::destroy () +{ + delete [] m_waterMap; + m_waterMap = 0; + + delete [] m_slopeMap; + m_slopeMap = 0; +} + +//------------------------------------------------------------------- + +int BakedTerrain::calculateChunkX (const Vector2d& position) const +{ + const int chunkX = static_cast ((position.x >= 0.f) ? floorf (position.x / m_chunkWidthInMeters) : ceilf (position.x / m_chunkWidthInMeters)); + + return (position.x < 0.f) ? chunkX - 1 : chunkX; +} + +//------------------------------------------------------------------- + +int BakedTerrain::calculateChunkY (const Vector2d& position) const +{ + const int chunkY = static_cast ((position.y >= 0.f) ? floorf (position.y / m_chunkWidthInMeters) : ceilf (position.y / m_chunkWidthInMeters)); + + return (position.y < 0.f) ? chunkY - 1 : chunkY; +} + +//------------------------------------------------------------------- + +void BakedTerrain::calculateMapXy (const Vector2d& position, int& x, int& y) const +{ + x = calculateChunkX (position) + static_cast ((m_mapWidthInMeters / m_chunkWidthInMeters) * 0.5f); + y = calculateChunkY (position) + static_cast ((m_mapWidthInMeters / m_chunkWidthInMeters) * 0.5f); +} + +//------------------------------------------------------------------- + +bool BakedTerrain::getBool (const uint8* const map, const int mapX, const int mapY) const +{ + const int index = mapX >> 3; + const int offset = mapX % 8; + + if (index < 0 || index >= m_width || mapY < 0 || mapY >= m_height) + return false; + + return (map [mapY * m_width + index] & (1 << offset)) != 0; +} + +//------------------------------------------------------------------- + +bool BakedTerrain::getMap (const uint8* const map, const Rectangle2d& rectangle) const +{ + if (!map) + return false; + + int x0; + int y0; + calculateMapXy (Vector2d (rectangle.x0, rectangle.y0), x0, y0); + + int x1; + int y1; + calculateMapXy (Vector2d (rectangle.x1, rectangle.y1), x1, y1); + + if (x0 > x1) + std::swap (x0, x1); + + if (y0 > y1) + std::swap (y0, y1); + + int x; + int y; + for (y = y0; y <= y1; ++y) + for (x = x0; x <= x1; ++x) + if (getBool (map, x, y)) + return true; + + return false; +} + +//------------------------------------------------------------------- + +void BakedTerrain::setBool (uint8* const map, const int mapX, const int mapY, const bool value) +{ + const int index = mapX >> 3; + const int offset = mapX % 8; + + VALIDATE_RANGE_INCLUSIVE_EXCLUSIVE (0, index, m_width); + VALIDATE_RANGE_INCLUSIVE_EXCLUSIVE (0, mapY, m_height); + + if (value) + map [mapY * m_width + index] |= (1 << offset); + else + map [mapY * m_width + index] &= ~(1 << offset); +} + +//------------------------------------------------------------------- + +void BakedTerrain::load_0000 (Iff& iff) +{ + iff.enterForm (TAG_0000); + iff.exitForm (TAG_0000, true); +} + +//------------------------------------------------------------------- + +void BakedTerrain::load_0001 (Iff& iff) +{ + iff.enterForm (TAG_0001); + + iff.enterChunk (TAG_DATA); + m_mapWidthInMeters = iff.read_float (); + m_chunkWidthInMeters = iff.read_float (); + m_width = iff.read_int32 (); + m_height = iff.read_int32 (); + iff.exitChunk (TAG_DATA); + + iff.enterChunk (TAG_WMAP); + m_waterMap = iff.readRest_uint8 (); + iff.exitChunk (TAG_WMAP); + + iff.enterChunk (TAG_SMAP); + m_slopeMap = iff.readRest_uint8 (); + iff.exitChunk (TAG_SMAP); + + iff.exitForm (TAG_0001); +} + +//=================================================================== + diff --git a/engine/shared/library/sharedUtility/src/shared/BakedTerrain.h b/engine/shared/library/sharedUtility/src/shared/BakedTerrain.h new file mode 100644 index 00000000..449c5f1f --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/BakedTerrain.h @@ -0,0 +1,79 @@ +//=================================================================== +// +// BakedTerrain.h +// asommers +// +// copyright 2002, sony online entertainment +// +//=================================================================== + +#ifndef INCLUDED_BakedTerrain_H +#define INCLUDED_BakedTerrain_H + +//=================================================================== + +class Iff; +class Rectangle2d; +class Vector2d; + +//=================================================================== + +class BakedTerrain +{ + friend class TerrainEditorDoc; + +public: + + BakedTerrain (); + ~BakedTerrain (); + + void load (Iff& iff); + void save (Iff& iff) const; + + float getMapWidthInMeters () const; + float getChunkWidthInMeters () const; + bool getWater (int chunkX, int chunkY) const; + bool getSlope (int chunkX, int chunkY) const; + bool getWater (const Vector2d& position) const; + bool getSlope (const Vector2d& position) const; + bool getWater (const Rectangle2d& rectangle) const; + bool getSlope (const Rectangle2d& rectangle) const; + + //-- tool use only + void setMap (float mapWidthInMeters, float chunkWidthInMeters); + void setWater (int chunkX, int chunkY, bool water); + void setSlope (int chunkX, int chunkY, bool slope); + +private: + + void destroy (); + + int calculateChunkX (const Vector2d& position) const; + int calculateChunkY (const Vector2d& position) const; + void calculateMapXy (const Vector2d& position, int& x, int& y) const; + bool getBool (const uint8* map, int mapX, int mapY) const; + bool getMap (const uint8* map, const Rectangle2d& rectangle) const; + void setBool (uint8* map, int mapX, int mapY, bool value); + + void load_0000 (Iff& iff); + void load_0001 (Iff& iff); + +private: + + BakedTerrain (const BakedTerrain&); + BakedTerrain& operator= (const BakedTerrain&); + +private: + + float m_mapWidthInMeters; + float m_chunkWidthInMeters; + int m_width; + int m_height; + uint8* m_waterMap; + uint8* m_slopeMap; +}; + +//=================================================================== + +#endif + diff --git a/engine/shared/library/sharedUtility/src/shared/BakedTerrainReader.cpp b/engine/shared/library/sharedUtility/src/shared/BakedTerrainReader.cpp new file mode 100644 index 00000000..5bd40fe6 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/BakedTerrainReader.cpp @@ -0,0 +1,73 @@ +// ====================================================================== +// +// BakedTerrainReader.cpp +// asommers +// +// copyright 2003, sony online entertainment +// +// ====================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/BakedTerrainReader.h" + +#include "sharedFile/Iff.h" +#include "sharedUtility/BakedTerrain.h" + +// ====================================================================== +// BakedTerrainReaderNamespace +// ====================================================================== + +namespace BakedTerrainReaderNamespace +{ + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + Tag const TAG_MPTA = TAG (M,P,T,A); + Tag const TAG_PTAT = TAG (P,T,A,T); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + BakedTerrain * load (Iff & iff) + { + if (iff.getCurrentName () != TAG_MPTA && iff.getCurrentName () != TAG_PTAT) + return 0; + + iff.enterForm (); + + iff.enterForm (); + + iff.enterChunk (); + iff.exitChunk (true); + + iff.enterForm (); + iff.exitForm (true); + + BakedTerrain * const bakedTerrain = new BakedTerrain (); + bakedTerrain->load (iff); + + iff.exitForm (true); + + iff.exitForm (true); + + DEBUG_REPORT_LOG (true, ("BakedTerrainReader: loaded terrain for %s\n", iff.getFileName ())); + return bakedTerrain; + } + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +} + +using namespace BakedTerrainReaderNamespace; + +// ====================================================================== +// STATIC BakedTerrainReader +// ====================================================================== + +BakedTerrain * BakedTerrainReader::create (char const * const fileName) +{ + Iff iff; + if (iff.open (fileName, true)) + return load (iff); + + return 0; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedUtility/src/shared/BakedTerrainReader.h b/engine/shared/library/sharedUtility/src/shared/BakedTerrainReader.h new file mode 100644 index 00000000..bfda139f --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/BakedTerrainReader.h @@ -0,0 +1,29 @@ +// ====================================================================== +// +// BakedTerrainReader.h +// asommers +// +// copyright 2003, sony online entertainment +// +// ====================================================================== + +#ifndef INCLUDED_BakedTerrainReader_H +#define INCLUDED_BakedTerrainReader_H + +// ====================================================================== + +class BakedTerrain; + +// ====================================================================== + +class BakedTerrainReader +{ +public: + + static BakedTerrain * create (char const * fileName); +}; + +// ====================================================================== + +#endif + diff --git a/engine/shared/library/sharedUtility/src/shared/CachedFileManager.cpp b/engine/shared/library/sharedUtility/src/shared/CachedFileManager.cpp new file mode 100644 index 00000000..255bef4b --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/CachedFileManager.cpp @@ -0,0 +1,282 @@ +// ====================================================================== +// +// CachedFileManager.cpp +// asommers +// +// copyright 2003, sony online entertainment +// +// ====================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/CachedFileManager.h" + +#include "sharedDebug/InstallTimer.h" +#include "sharedFile/Iff.h" +#include "sharedFile/TreeFile.h" +#include "sharedFoundation/Clock.h" +#include "sharedFoundation/ConstCharCrcString.h" +#include "sharedFoundation/CrcString.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/LessPointerComparator.h" +#include "sharedFoundation/Os.h" +#include "sharedFoundation/PersistentCrcString.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedFoundation/Production.h" +#include "sharedFoundation/VoidMemberFunction.h" +#include "sharedUtility/ConfigSharedUtility.h" + +#include +#include +#include + +// ====================================================================== + +namespace CachedFileManagerNamespace +{ +#if PRODUCTION == 0 + + class CachedFileInfo + { + public: + + explicit CachedFileInfo (char const * extension); + ~CachedFileInfo (); + + CrcString const * getExtension () const; + int getSize () const; + void addFile (int size); + void report () const; + + private: + + CachedFileInfo (); + CachedFileInfo (CachedFileInfo const &); + CachedFileInfo & operator= (CachedFileInfo const &); + + private: + + PersistentCrcString const m_extension; + int m_numberOfFiles; + int m_size; + }; + + typedef std::map ExtensionMap; + ExtensionMap ms_extensionMap; + + int ms_totalAllocatedBytes; + +#endif + + Tag const TAG_CACH = TAG (C,A,C,H); + + char * ms_filenames = NULL; + size_t ms_filenamesLength = 0; + size_t ms_filenamesCurrentPos = 0; + unsigned long ms_totalTime; + size_t ms_numberOfFilesLoaded; + + std::string ms_cacheFileName; + + void remove (); +} + +using namespace CachedFileManagerNamespace; + +// ====================================================================== + +#if PRODUCTION == 0 + +CachedFileInfo::CachedFileInfo (char const * const extension) : + m_extension (extension, false), + m_numberOfFiles (0), + m_size (0) +{ +} + +// ---------------------------------------------------------------------- + +CachedFileInfo::~CachedFileInfo () +{ +} + +// ---------------------------------------------------------------------- + +CrcString const * CachedFileInfo::getExtension () const +{ + return &m_extension; +} + +// ---------------------------------------------------------------------- + +int CachedFileInfo::getSize () const +{ + return m_size; +} + +// ---------------------------------------------------------------------- + +void CachedFileInfo::addFile (int const size) +{ + ++m_numberOfFiles; + m_size += size; +} + +// ---------------------------------------------------------------------- + +void CachedFileInfo::report () const +{ + REPORT_LOG (true, ("| type=%s, count=%5d, size=%9d\n", m_extension.getString (), m_numberOfFiles, m_size)); +} + +#endif + +// ====================================================================== + +void CachedFileManager::install(bool const allowFileCaching) +{ + InstallTimer const installTimer("CachedFileManager::install"); + + if (!allowFileCaching || ConfigSharedUtility::getDisableFileCaching()) + return; + + char const * const result = ConfigSharedUtility::getUseCacheFile(); + if (result) + { + ms_cacheFileName = result; + + Iff iff; + if (iff.open (result, true)) + { + iff.enterForm (TAG_CACH); + iff.enterChunk (TAG_0000); + + //-- the entire chunk is filled with null terminated strings + ms_filenamesLength = iff.getChunkLengthLeft(); + ms_filenames = iff.readRest_char(); + + iff.exitChunk (TAG_0000); + + iff.exitForm (TAG_CACH); + } + } + + ExitChain::add (CachedFileManagerNamespace::remove, "CachedFileManagerNamespace::remove"); +} + +// ---------------------------------------------------------------------- + +void CachedFileManagerNamespace::remove () +{ + delete[] ms_filenames; + ms_filenames = NULL; + ms_filenamesCurrentPos = 0; + ms_filenamesLength = 0; + +#if PRODUCTION == 0 + std::for_each (ms_extensionMap.begin (), ms_extensionMap.end (), PointerDeleterPairSecond ()); + ms_extensionMap.clear(); +#endif +} + +// ---------------------------------------------------------------------- + +void CachedFileManager::preloadSomeAssets () +{ + if (!donePreloading ()) + { + unsigned long const startTime = Clock::timeMs (); + +#if PRODUCTION == 0 + unsigned long const bytesBefore = MemoryManager::getCurrentNumberOfBytesAllocated(); +#endif + + //-- preloading occurs in one second slices + while (ms_filenamesCurrentPos < ms_filenamesLength && Clock::timeMs () - startTime < 1000) + { + char const * const fileName = ms_filenames + ms_filenamesCurrentPos; + + if (TreeFile::exists(fileName)) + { +#if PRODUCTION == 0 + int const fileSize = TreeFile::cacheFile (fileName); + + //-- record cached file information per extension + char const * const possibleExtension = strrchr (fileName, '.'); + if (possibleExtension) + { + ConstCharCrcString const extension (possibleExtension + 1); + ExtensionMap::iterator iter = ms_extensionMap.find (&extension); + if (iter == ms_extensionMap.end ()) + { + CachedFileInfo * const info = new CachedFileInfo (extension.getString ()); + std::pair result = ms_extensionMap.insert (ExtensionMap::value_type (info->getExtension (), info)); + DEBUG_FATAL (!result.second, ("insert failed")); + iter = result.first; + } + + iter->second->addFile (fileSize); + } + + ++ms_numberOfFilesLoaded; +#else + IGNORE_RETURN(TreeFile::cacheFile (fileName)); +#endif + } + + ms_filenamesCurrentPos += strlen(fileName) + 1; + } + +#if PRODUCTION == 0 + unsigned long const stopTime = Clock::timeMs (); + ms_totalTime += stopTime - startTime; + + ms_totalAllocatedBytes += MemoryManager::getCurrentNumberOfBytesAllocated() - bytesBefore; +#endif + + if (donePreloading ()) + { +#if PRODUCTION == 0 + REPORT_LOG (true, ("CachedFileManager [%s]: Caching took [%.2f] seconds for [%d] files and increased memory usage by [%.2f] MB.\n", ms_cacheFileName.c_str (), static_cast (ms_totalTime) / 1000.f, ms_numberOfFilesLoaded, static_cast (ms_totalAllocatedBytes) / (1024.0f * 1024.0f))); + + int size = 0; + while (!ms_extensionMap.empty ()) + { + ExtensionMap::iterator iter = ms_extensionMap.begin (); + iter->second->report (); + size += iter->second->getSize (); + delete iter->second; + + ms_extensionMap.erase (iter); + } + + std::for_each(ms_extensionMap.begin (), ms_extensionMap.end (), PointerDeleterPairSecond ()); + ms_extensionMap.clear(); + REPORT_LOG (true, ("+ Total cached data size = %.2f MB.\n", static_cast (size) / (1024.0f * 1024.0f))); +#endif + + delete[] ms_filenames; + ms_filenames = NULL; + ms_filenamesCurrentPos = 0; + ms_filenamesLength = 0; + } + } +} + +// ---------------------------------------------------------------------- + +bool CachedFileManager::donePreloading () +{ + return ms_filenames == NULL || (ms_filenamesCurrentPos >= ms_filenamesLength); +} + +// ---------------------------------------------------------------------- + +int CachedFileManager::getLoadingPercent () +{ + if (ms_filenamesLength == 0) + return 100; + + return (ms_filenamesCurrentPos * 100) / ms_filenamesLength; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedUtility/src/shared/CachedFileManager.h b/engine/shared/library/sharedUtility/src/shared/CachedFileManager.h new file mode 100644 index 00000000..8b548a71 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/CachedFileManager.h @@ -0,0 +1,28 @@ +// ====================================================================== +// +// CachedFileManager.h +// asommers +// +// copyright 2003, sony online entertainment +// +// ====================================================================== + +#ifndef INCLUDED_CachedFileManager_H +#define INCLUDED_CachedFileManager_H + +// ====================================================================== + +class CachedFileManager +{ +public: + + static void install(bool allowFileCaching); + + static void preloadSomeAssets (); + static bool donePreloading (); + static int getLoadingPercent (); +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/Callback.cpp b/engine/shared/library/sharedUtility/src/shared/Callback.cpp new file mode 100644 index 00000000..66bf4425 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/Callback.cpp @@ -0,0 +1,109 @@ +// ====================================================================== +// +// Callback.cpp +// copyright 2001 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/Callback.h" + +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/MemoryBlockManager.h" +#include "sharedUtility/CallbackReceiver.h" +#include + +// ====================================================================== + +MEMORY_BLOCK_MANAGER_IMPLEMENTATION_WITH_INSTALL (Callback, true, 0, 0, 0); + +// ====================================================================== + +Callback::Callback() +: m_referenceCount(0), + m_receivers(), + m_inPerformCallback (false) +{ +} + +// ---------------------------------------------------------------------- + +Callback::~Callback() +{ + DEBUG_FATAL(m_referenceCount, ("Callback deleted with non-zero reference count")); + m_receivers.clear (); +} + +// ---------------------------------------------------------------------- + +void Callback::attachReceiver(CallbackReceiver &receiver) +{ + DEBUG_FATAL (m_inPerformCallback, ("Callback cannot attach receivers while receiving callbacks")); + //-- pre-reserve the space to prevent the vector from agressively allocating more space + m_receivers.reserve (m_receivers.size () + 1); + m_receivers.push_back (&receiver); +} + +// ---------------------------------------------------------------------- + +void Callback::detachReceiver(CallbackReceiver &receiver) +{ + DEBUG_FATAL (m_inPerformCallback, ("Callback cannot detach receivers while receiving callbacks")); + const CallbackReceiverVector::iterator remove_begin = std::remove (m_receivers.begin (), m_receivers.end (), &receiver); + + if (remove_begin == m_receivers.end ()) + { + DEBUG_FATAL (true, ("Callback attempted to detach unattached receeiver.")); + return; + } + + m_receivers.erase (remove_begin, m_receivers.end ()); +} + +// ---------------------------------------------------------------------- + +bool Callback::hasAnyReceivers() const +{ + return !m_receivers.empty (); +} + +// ---------------------------------------------------------------------- + +void Callback::performCallback() +{ + m_inPerformCallback = true; + const CallbackReceiverVector::const_iterator end = m_receivers.end (); + for (CallbackReceiverVector::const_iterator it = m_receivers.begin (); it != end; ++it) + { + CallbackReceiver * const receiver = *it; + NOT_NULL (receiver); + if (receiver) + receiver->performCallback(); + } + m_inPerformCallback = false; +} + +// ---------------------------------------------------------------------- + +void Callback::fetch() +{ + ++m_referenceCount; + + // sanity check + DEBUG_FATAL(m_referenceCount < 1, ("invalid reference count %d after fetch()", m_referenceCount)); +} + +// ---------------------------------------------------------------------- + +void Callback::release() +{ + --m_referenceCount; + + if (m_referenceCount < 1) + { + DEBUG_FATAL(m_referenceCount < 0, ("bad reference count handling [%d]", m_referenceCount)); + delete this; + } +} + +// ====================================================================== diff --git a/engine/shared/library/sharedUtility/src/shared/Callback.h b/engine/shared/library/sharedUtility/src/shared/Callback.h new file mode 100644 index 00000000..1fc75b58 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/Callback.h @@ -0,0 +1,61 @@ +// ====================================================================== +// +// Callback.h +// copyright 2001 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_Callback_H +#define INCLUDED_Callback_H + +// ====================================================================== + +class CallbackReceiver; +class MemoryBlockManager; + +#include +#include "sharedFoundation/MemoryBlockManagerMacros.h" + +// ====================================================================== + +class Callback +{ +public: + + MEMORY_BLOCK_MANAGER_INTERFACE_WITH_INSTALL; + +public: + + Callback(); + + void attachReceiver(CallbackReceiver &receiver); + void detachReceiver(CallbackReceiver &receiver); + + bool hasAnyReceivers() const; + + void performCallback(); + + void fetch(); + void release(); + +private: + + ~Callback(); + +private: + + typedef stdvector::fwd CallbackReceiverVector; + + int m_referenceCount; + CallbackReceiverVector m_receivers; + bool m_inPerformCallback; + +private: + // disabled + Callback(const Callback&); + Callback &operator =(const Callback&); +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/CallbackReceiver.h b/engine/shared/library/sharedUtility/src/shared/CallbackReceiver.h new file mode 100644 index 00000000..84ac59b6 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/CallbackReceiver.h @@ -0,0 +1,28 @@ +// ====================================================================== +// +// CallbackReceiver.h +// copyright 2001 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_CallbackReceiver_H +#define INCLUDED_CallbackReceiver_H + +// ====================================================================== + +class CallbackReceiver +{ +public: + + virtual void performCallback() = 0; + +protected: + + CallbackReceiver() {} + virtual ~CallbackReceiver() {} + +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/ConfigSharedUtility.cpp b/engine/shared/library/sharedUtility/src/shared/ConfigSharedUtility.cpp new file mode 100644 index 00000000..7bb36be5 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/ConfigSharedUtility.cpp @@ -0,0 +1,69 @@ +// ====================================================================== +// +// ConfigSharedUtility.cpp +// copyright 2004 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/ConfigSharedUtility.h" + +#include "sharedFoundation/ConfigFile.h" + +// ====================================================================== + +#define KEY_BOOL(a,b) (ms_ ## a = ConfigFile::getKeyBool("SharedUtility", #a, (b))) +#define KEY_INT(a,b) (ms_ ## a = ConfigFile::getKeyInt("SharedUtility", #a, (b))) +#define KEY_STRING(a,b) (ms_ ## a = ConfigFile::getKeyString("SharedUtility", #a, (b))) + +// ====================================================================== + +namespace ConfigSharedUtilityNamespace +{ + bool ms_disableFileCaching; + char const * ms_useCacheFile; + int ms_chunkSize; + bool ms_logOptionManager; +} + +using namespace ConfigSharedUtilityNamespace; + +// ====================================================================== + +void ConfigSharedUtility::install() +{ + KEY_BOOL(disableFileCaching, false); + KEY_STRING(useCacheFile, ""); + KEY_INT(chunkSize, 32); + KEY_BOOL(logOptionManager, false); +} + +// ---------------------------------------------------------------------- + +bool ConfigSharedUtility::getDisableFileCaching() +{ + return ms_disableFileCaching; +} + +// ---------------------------------------------------------------------- + +char const * ConfigSharedUtility::getUseCacheFile() +{ + return ms_useCacheFile; +} + +// ---------------------------------------------------------------------- + +int ConfigSharedUtility::getChunkSize() +{ + return ms_chunkSize; +} + +// ---------------------------------------------------------------------- + +bool ConfigSharedUtility::getLogOptionManager() +{ + return ms_logOptionManager; +} + +// ====================================================================== diff --git a/engine/shared/library/sharedUtility/src/shared/ConfigSharedUtility.h b/engine/shared/library/sharedUtility/src/shared/ConfigSharedUtility.h new file mode 100644 index 00000000..d0f91bcf --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/ConfigSharedUtility.h @@ -0,0 +1,28 @@ +// ====================================================================== +// +// ConfigSharedUtility.h +// Copyright 2004, Sony Online Entertainment Inc. +// All Rights Reserved. +// +// ====================================================================== + +#ifndef INCLUDED_ConfigSharedUtility_H +#define INCLUDED_ConfigSharedUtility_H + +// ====================================================================== + +class ConfigSharedUtility +{ +public: + + static void install(); + + static bool getDisableFileCaching(); + static char const * getUseCacheFile(); + static int getChunkSize(); + static bool getLogOptionManager(); +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/CurrentUserOptionManager.cpp b/engine/shared/library/sharedUtility/src/shared/CurrentUserOptionManager.cpp new file mode 100644 index 00000000..626c7fcb --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/CurrentUserOptionManager.cpp @@ -0,0 +1,128 @@ +// ====================================================================== +// +// CurrentUserOptionManager.cpp +// asommers +// +// copyright 2003, sony online entertainment +// +// ====================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/CurrentUserOptionManager.h" + +#include "sharedDebug/DebugFlags.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedUtility/OptionManager.h" +#include + +// ====================================================================== +// CurrentUserOptionManagerNamespace +// ====================================================================== + +namespace CurrentUserOptionManagerNamespace +{ + bool ms_installed; + OptionManager * ms_optionManager; + std::string ms_userName; + + bool s_verbose = false; +} + +using namespace CurrentUserOptionManagerNamespace; + +// ====================================================================== +// STATIC PUBLIC CurrentUserOptionManager +// ====================================================================== + +void CurrentUserOptionManager::install () +{ + DEBUG_FATAL (ms_installed, ("CurrentUserOptionManager::install: already installed")); + ms_installed = true; + + ms_optionManager = new OptionManager; + + ExitChain::add (remove, "CurrentUserOptionManager::remove"); + + DebugFlags::registerFlag(s_verbose, "sharedUtility/CurrentUserOptionManager", "verbose"); +} + +// ---------------------------------------------------------------------- + +void CurrentUserOptionManager::remove () +{ + DEBUG_FATAL (!ms_installed, ("CurrentUserOptionManager::remove: not installed")); + ms_installed = false; + + delete ms_optionManager; + ms_optionManager = 0; +} + +// ---------------------------------------------------------------------- + +void CurrentUserOptionManager::load (char const * const userName) +{ + if (userName && *userName) + { + ms_userName = userName; + + DEBUG_REPORT_LOG (s_verbose, ("CurrentUserOptionManager::load: user name set to %s, loading %s\n", userName, ms_userName.c_str ())); + + ms_optionManager->load (ms_userName.c_str ()); + } + else + DEBUG_WARNING (true, ("CurrentUserOptionManager::load: userName is null")); +} + +// ---------------------------------------------------------------------- + +void CurrentUserOptionManager::save () +{ + DEBUG_FATAL (!ms_installed, ("CurrentUserOptionManager::save: not installed")); + + if (!ms_userName.empty ()) + ms_optionManager->save (ms_userName.c_str ()); + else + DEBUG_REPORT_LOG (s_verbose, ("CurrentUserOptionManager::save: userName is null\n")); +} + +// ---------------------------------------------------------------------- + +void CurrentUserOptionManager::registerOption (bool & variable, char const * const section, char const * const name, const int version) +{ + DEBUG_FATAL (!ms_installed, ("CurrentUserOptionManager::registerOption: not installed")); + ms_optionManager->registerOption (variable, section, name, version); +} + +// ---------------------------------------------------------------------- + +void CurrentUserOptionManager::registerOption (float & variable, char const * const section, char const * const name, const int version) +{ + DEBUG_FATAL (!ms_installed, ("CurrentUserOptionManager::registerOption: not installed")); + ms_optionManager->registerOption (variable, section, name, version); +} + +// ---------------------------------------------------------------------- + +void CurrentUserOptionManager::registerOption (int & variable, char const * const section, char const * const name, const int version) +{ + DEBUG_FATAL (!ms_installed, ("CurrentUserOptionManager::registerOption: not installed")); + ms_optionManager->registerOption (variable, section, name, version); +} + +// ---------------------------------------------------------------------- + +void CurrentUserOptionManager::registerOption (std::string & variable, char const * const section, char const * const name, const int version) +{ + DEBUG_FATAL (!ms_installed, ("CurrentUserOptionManager::registerOption: not installed")); + ms_optionManager->registerOption (variable, section, name, version); +} + +// ---------------------------------------------------------------------- + +void CurrentUserOptionManager::registerOption (Unicode::String & variable, char const * const section, char const * const name, const int version) +{ + DEBUG_FATAL (!ms_installed, ("CurrentUserOptionManager::registerOption: not installed")); + ms_optionManager->registerOption (variable, section, name, version); +} + +// ====================================================================== diff --git a/engine/shared/library/sharedUtility/src/shared/CurrentUserOptionManager.h b/engine/shared/library/sharedUtility/src/shared/CurrentUserOptionManager.h new file mode 100644 index 00000000..821cd8c1 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/CurrentUserOptionManager.h @@ -0,0 +1,41 @@ +// ====================================================================== +// +// CurrentUserOptionManager.h +// asommers +// +// copyright 2003, sony online entertainment +// +// ====================================================================== + +#ifndef INCLUDED_CurrentUserOptionManager_H +#define INCLUDED_CurrentUserOptionManager_H + +// ====================================================================== + +class CurrentUserOptionManager +{ +public: + + static void install (); + static void remove (); + + static void load (char const * userName); + static void save (); + + static void registerOption (bool & variable, char const * section, char const * name, const int version = 0); + static void registerOption (float & variable, char const * section, char const * name, const int version = 0); + static void registerOption (int & variable, char const * section, char const * name, const int version = 0); + static void registerOption (std::string & variable, char const * section, char const * name, const int version = 0); + static void registerOption (Unicode::String & variable, char const * section, char const * name, const int version = 0); + +private: + + CurrentUserOptionManager (); + ~CurrentUserOptionManager (); + CurrentUserOptionManager (CurrentUserOptionManager const &); + CurrentUserOptionManager & operator= (CurrentUserOptionManager const &); +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/DataTable.cpp b/engine/shared/library/sharedUtility/src/shared/DataTable.cpp new file mode 100644 index 00000000..c0bf3ef0 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/DataTable.cpp @@ -0,0 +1,763 @@ +// ====================================================================== +// +// DataTable.cpp +// +// copyright 2002 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/DataTable.h" + +#include "sharedFile/Iff.h" +#include "sharedUtility/DataTableCell.h" + +#include +#include + +//---------------------------------------------------------------------------- + +const Tag DataTable::m_dataTableIffId = TAG(D,T,I,I); + +//---------------------------------------------------------------------------- + +DataTable::DataTable() : +m_numRows(0), +m_numCols(0), +m_cells(0), +m_columns(), +m_index(), +m_types(), +m_columnIndexMap(new ColumnIndexMap(17)), +m_name() +{ +} + +//---------------------------------------------------------------------------- + +DataTable::~DataTable() +{ + std::vector::iterator k = m_index.begin(); + int count = 0; + for (; k != m_index.end(); ++k, ++count) + { + DataTableColumnType::DataType dt = m_types[static_cast(count)]->getBasicType(); + + switch (dt) + { + case DataTableColumnType::DT_Int: + { + if (*k) + { + delete static_cast *>(*k); + *k = NULL; + } + } + break; + case DataTableColumnType::DT_Float: + { + if (*k) + { + delete static_cast *>(*k); + *k = NULL; + } + + } + break; + case DataTableColumnType::DT_String: + { + if (*k) + { + delete static_cast, std::multimap > *>(*k); + *k = NULL; + } + + } + break; + case DataTableColumnType::DT_HashString: + case DataTableColumnType::DT_Enum: + case DataTableColumnType::DT_Bool: + case DataTableColumnType::DT_BitVector: + case DataTableColumnType::DT_Unknown: + case DataTableColumnType::DT_Comment: + case DataTableColumnType::DT_PackedObjVars: + default: + { + WARNING_STRICT_FATAL((*k) != NULL, ("Bad column Index %d. Unsupported datatype. This may leak memory.", count)); + } + break; + } + } + + if (m_cells) + { + for (int row=0;rowempty(), ("DataTable(%x) [%s]: Column index map is empty.\n", this, m_name.c_str())); + + return m_columnIndexMap->find(column) != m_columnIndexMap->end(); +} + +//---------------------------------------------------------------------------- + +int DataTable::findColumnNumber(const std::string & column) const +{ + DEBUG_FATAL(m_columnIndexMap->empty(), ("DataTable(%x) [%s]: Column index map is empty.\n", this, m_name.c_str())); + + int count = -1; + ColumnIndexMap::const_iterator const it = m_columnIndexMap->find(column); + + if (it != m_columnIndexMap->end()) + { + count = it->second; + } + + return count; +} + +//---------------------------------------------------------------------------- +const std::string & DataTable::getColumnName(int column) const +{ + DEBUG_FATAL(column < 0 || column >= getNumColumns(), ("DataTable [%s] getColumnName(): Invalid col number [%d]. Cols=[%d]\n", m_name.c_str(), column, getNumColumns())); + return m_columns[static_cast(column)]; +} + + +//---------------------------------------------------------------------------- + +DataTableColumnType DataTable::getDataType(const std::string & type) +{ + return DataTableColumnType(type); +} + +//---------------------------------------------------------------------------- + +DataTableColumnType const &DataTable::getDataTypeForColumn(const std::string& column) const +{ + int const columnIndex = findColumnNumber(column); + DEBUG_FATAL(columnIndex < 0 || columnIndex >= getNumColumns(), ("DataTable [%s] getDataTypeForColumn(): Column name [%s] is invalid\n", m_name.c_str(), column.c_str())); + + return getDataTypeForColumn(columnIndex); +} + +//---------------------------------------------------------------------------- + +DataTableColumnType const &DataTable::getDataTypeForColumn(int column) const +{ + DEBUG_FATAL(column < 0 || column >= getNumColumns(), ("DataTable [%s] getDataTypeForColumn(): Invalid col number [%d]. Cols=[%d]\n", m_name.c_str(), column, getNumColumns())); + return *m_types[static_cast(column)]; +} + +//---------------------------------------------------------------------------- + +int DataTable::getIntValue(const std::string & column, int row) const +{ + int const columnIndex = findColumnNumber(column); + DEBUG_FATAL(columnIndex < 0 || columnIndex >= getNumColumns(), ("DataTable [%s] getIntValue(): Column name [%s] is invalid\n", m_name.c_str(), column.c_str())); + return getIntValue(columnIndex, row); +} + +//---------------------------------------------------------------------------- + +int DataTable::getIntValue(int column, int row) const +{ + DEBUG_FATAL(row < 0 || row >= getNumRows(), ("DataTable [%s] getIntValue(): Invalid row number [%d]. Rows=[%d]\n", m_name.c_str(), row, getNumRows())); + DEBUG_FATAL(column < 0 || column >= getNumColumns(), ("DataTable [%s] getIntValue(): Invalid col number [%d]. Cols=[%d]\n", m_name.c_str(), column, getNumColumns())); + + // we can return the value of an int column or the crc value of a string column + if (m_types[static_cast(column)]->getBasicType() == DataTableColumnType::DT_Int) + { + const DataTableCell *cell = getDataTableCell(column, row); + DEBUG_FATAL(cell->getType()!=DataTableCell::CT_int, ("Could not convert row %d column %d to int value", row, column)); + return cell->getIntValue(); + } + else if (m_types[static_cast(column)]->getBasicType() == DataTableColumnType::DT_String) + { + const DataTableCell *cell = getDataTableCell(column, row); + DEBUG_FATAL(cell->getType()!=DataTableCell::CT_string, ("Could not convert row %d column %d to string value", row, column)); + return cell->getStringValueCrc(); + } + + DEBUG_FATAL(true, ("DataTable [%s] getIntValue(): Wrong data type [%d] for col [%d].\n", m_name.c_str(), m_types[static_cast(column)]->getBasicType(), column)); + return 0; +} + +//---------------------------------------------------------------------------- + +int DataTable::getIntDefaultForColumn(const std::string & column) const +{ + int const columnIndex = findColumnNumber(column); + DEBUG_FATAL(columnIndex < 0 || columnIndex >= getNumColumns(), ("DataTable [%s] getIntDefaultForColumn(): Invalid col number [%d]. Cols=[%d]\n", m_name.c_str(), columnIndex, getNumColumns())); + return getIntDefaultForColumn(columnIndex); +} + +//---------------------------------------------------------------------------- + +int DataTable::getIntDefaultForColumn(int column) const +{ + DEBUG_FATAL(column < 0 || column >= getNumColumns(), ("DataTable [%s] getIntDefaultForColumn(): Invalid col number [%d]. Cols=[%d]\n", m_name.c_str(), column, getNumColumns())); + DEBUG_FATAL(m_types[static_cast(column)]->getBasicType() != DataTableColumnType::DT_Int, ("Wrong data type for column %d.", column)); + std::string value; + IGNORE_RETURN( getDataTypeForColumn(column).mangleValue(value) ); + return atoi(value.c_str()); +} + +//---------------------------------------------------------------------------- + +float DataTable::getFloatValue(const std::string & column, int row) const +{ + int const columnIndex = findColumnNumber(column); + DEBUG_FATAL(columnIndex < 0 || columnIndex >= getNumColumns(), ("DataTable Column [%s] is invalid", column.c_str())); + return getFloatValue(columnIndex, row); +} + +//---------------------------------------------------------------------------- + +float DataTable::getFloatValue(int column, int row) const +{ + DEBUG_FATAL(row < 0 || row >= getNumRows(), ("Row is invalid.")); + DEBUG_FATAL(column < 0 || column >= getNumColumns(), ("DataTable [%s] getFloatValue(): Invalid col number [%d]. Cols=[%d]\n", m_name.c_str(), column, getNumColumns())); + DEBUG_FATAL(m_types[static_cast(column)]->getBasicType() != DataTableColumnType::DT_Float, ("Wrong data type for column %d.", column)); + + const DataTableCell *cell = getDataTableCell(column, row); + DEBUG_FATAL(cell->getType()!=DataTableCell::CT_float, ("Could not convert row %d column %d to float value", row, column)); + return cell->getFloatValue(); + +} + +//---------------------------------------------------------------------------- + +float DataTable::getFloatDefaultForColumn(const std::string & column) const +{ + int const columnIndex = findColumnNumber(column); + DEBUG_FATAL(columnIndex < 0 || columnIndex >= getNumColumns(), ("DataTable Column [%s] is invalid", column.c_str())); + return getFloatDefaultForColumn(columnIndex); +} + +//---------------------------------------------------------------------------- + +float DataTable::getFloatDefaultForColumn(int column) const +{ + DEBUG_FATAL(column < 0 || column >= getNumColumns(), ("DataTable [%s] getFloatDefaultForColumn(): Invalid col number [%d]. Cols=[%d]\n", m_name.c_str(), column, getNumColumns())); + DEBUG_FATAL(m_types[static_cast(column)]->getBasicType() != DataTableColumnType::DT_Float, ("Wrong data type for column %d.", column)); + std::string value; + IGNORE_RETURN ( getDataTypeForColumn(column).mangleValue(value) ); + return static_cast(atof(value.c_str())); +} + +//---------------------------------------------------------------------------- + +const char *DataTable::getStringValue(const std::string & column, int row) const +{ + int const columnIndex = findColumnNumber(column); + DEBUG_FATAL(columnIndex < 0 || columnIndex >= getNumColumns(), ("DataTable Column [%s] is invalid", column.c_str())); + return getStringValue(columnIndex, row); +} + +//---------------------------------------------------------------------------- + +const char *DataTable::getStringValue(int column, int row) const +{ + DEBUG_FATAL(row < 0 || row >= getNumRows(), ("Row [%d] is invalid.", row)); + DEBUG_FATAL(column < 0 || column >= getNumColumns(), ("Column [%d] is invalid.", column)); + DEBUG_FATAL(m_types[static_cast(column)]->getBasicType() != DataTableColumnType::DT_String, ("Wrong data type for column %s (%d). Current data type is %s", getColumnName(column).c_str(), column, getDataTypeForColumn(column).getTypeSpecString().c_str())); + + const DataTableCell * const cell = getDataTableCell(column, row); + DEBUG_FATAL(cell->getType()!=DataTableCell::CT_string, ("Could not convert row %d column %d to string value", row, column)); + return cell->getStringValue(); + +} + +//---------------------------------------------------------------------------- + +std::string DataTable::getStringDefaultForColumn(const std::string & column) const +{ + int const columnIndex = findColumnNumber(column); + DEBUG_FATAL(columnIndex < 0 || columnIndex >= getNumColumns(), ("DataTable Column [%s] is invalid", column.c_str())); + return getStringDefaultForColumn(columnIndex); +} + +//---------------------------------------------------------------------------- + +std::string DataTable::getStringDefaultForColumn(int column) const +{ + DEBUG_FATAL(column < 0 || column >= getNumColumns(), ("DataTable [%s] getStringDefaultForColumn(): Invalid col number [%d]. Cols=[%d]\n", m_name.c_str(), column, getNumColumns())); + + DEBUG_FATAL(m_types[static_cast(column)]->getBasicType() != DataTableColumnType::DT_String, ("Wrong data type for column %d.", column)); + std::string value; + IGNORE_RETURN( getDataTypeForColumn(column).mangleValue(value) ); + return value; +} + +//---------------------------------------------------------------------------- + +void DataTable::getIntColumn(const std::string& column, std::vector& returnVector) const +{ + int const columnIndex = findColumnNumber(column); + DEBUG_FATAL(columnIndex < 0 || columnIndex >= getNumColumns(), ("DataTable Column [%s] is invalid", column.c_str())); + getIntColumn(columnIndex, returnVector); +} + +//---------------------------------------------------------------------------- + +void DataTable::getIntColumn(const std::string& column, std::vector& returnVector) const +{ + int const columnIndex = findColumnNumber(column); + DEBUG_FATAL(columnIndex < 0 || columnIndex >= getNumColumns(), ("DataTable Column [%s] is invalid", column.c_str())); + getIntColumn(columnIndex, returnVector); +} + +//---------------------------------------------------------------------------- + +void DataTable::getFloatColumn(const std::string& column, std::vector& returnVector) const +{ + int const columnIndex = findColumnNumber(column); + DEBUG_FATAL(columnIndex < 0 || columnIndex >= getNumColumns(), ("DataTable Column [%s] is invalid", column.c_str())); + getFloatColumn(columnIndex, returnVector); +} + +//---------------------------------------------------------------------------- + +void DataTable::getStringColumn(const std::string& column, std::vector& returnVector) const +{ + int const columnIndex = findColumnNumber(column); + DEBUG_FATAL(columnIndex < 0 || columnIndex >= getNumColumns(), ("DataTable Column [%s] is invalid", column.c_str())); + getStringColumn(columnIndex, returnVector); +} + +//---------------------------------------------------------------------------- + +void DataTable::getIntColumn(int column, std::vector& returnVector) const +{ + returnVector.clear(); + for (int i = 0; i < getNumRows(); ++i) + { + returnVector.push_back(getIntValue(column, i)); + } +} + +//---------------------------------------------------------------------------- + +void DataTable::getIntColumn(int column, std::vector& returnVector) const +{ + returnVector.clear(); + for (int i = 0; i < getNumRows(); ++i) + { + returnVector.push_back(getIntValue(column, i)); + } +} + +//---------------------------------------------------------------------------- + +void DataTable::getFloatColumn(int column, std::vector& returnVector) const +{ + returnVector.clear(); + for (int i = 0; i < getNumRows(); ++i) + { + returnVector.push_back(getFloatValue(column, i)); + } +} + +//---------------------------------------------------------------------------- + +void DataTable::getStringColumn(int column, std::vector& returnVector) const +{ + returnVector.clear(); + for (int i = 0; i < getNumRows(); ++i) + { + returnVector.push_back(getStringValue(column, i)); + } +} + +//---------------------------------------------------------------------------- + +void DataTable::_readCell(Iff & iff, int column, int row) +{ + DataTableCell *cell = const_cast(getDataTableCell(column, row)); + const DataTableColumnType &typeCol = *m_types[static_cast(column)]; + switch (typeCol.getBasicType()) + { + case DataTableColumnType::DT_Int: + { + int tmp = iff.read_int32(); + new (cell) DataTableCell(tmp); + + break; + } + case DataTableColumnType::DT_Float: + { + float tmp = iff.read_float(); + new (cell) DataTableCell(tmp); + break; + } + case DataTableColumnType::DT_String: + { + const int maxLen = 16384; + char buffer[maxLen]; + buffer[0]=0; + iff.read_string(buffer, maxLen-1); + buffer[maxLen-1]=0; + new (cell) DataTableCell(buffer); + break; + } + case DataTableColumnType::DT_Unknown: + case DataTableColumnType::DT_HashString: + case DataTableColumnType::DT_Enum: + case DataTableColumnType::DT_Bool: + case DataTableColumnType::DT_BitVector: + case DataTableColumnType::DT_Comment: + case DataTableColumnType::DT_PackedObjVars: + default: + DEBUG_FATAL(true, ("bad case")); + break; + } +} + +//---------------------------------------------------------------------------- + +void DataTable::load(Iff & iff) +{ + IGNORE_RETURN ( iff.enterForm(m_dataTableIffId, false) ); + + const Tag version = iff.getCurrentName(); + if (version == TAG_0000) + load_0000(iff); + else if (version == TAG_0001) + load_0001(iff); + else + { + char buffer[5]; + + ConvertTagToString(version, buffer); + FATAL(true, ("unknown DataTable file format [%s]", buffer)); + } + + iff.exitForm(m_dataTableIffId, false); + + int count = getNumColumns(); + for (int i = 0; i < count; ++i) + { + //initialize the table index used for searching. + m_index.push_back(NULL); + } + + buildColumnIndexMap(); + + if (NULL != iff.getFileName()) + m_name = iff.getFileName(); + else + m_name.clear(); +} + +//---------------------------------------------------------------------------- + +void DataTable::load_0000(Iff & iff) +{ + IGNORE_RETURN ( iff.enterForm(TAG_0000, false) ); + + //load columns + iff.enterChunk(TAG(C,O,L,S)); + m_numCols = iff.read_int32(); + int i = 0; + m_columns.reserve(m_numCols); + std::string tmpString; + for (i = 0; i < m_numCols; ++i) + { + iff.read_string(tmpString); + m_columns.push_back(tmpString); + tmpString.clear(); + } + + iff.exitChunk(TAG(C,O,L,S)); + //load type info + iff.enterChunk(TAG(T,Y,P,E)); + for (i = 0; i < m_numCols; ++i) + { + DataTableColumnType::DataType dt = static_cast(iff.read_int32()); + // version 0000 has only Int, Float, String, and no other format information + switch (dt) + { + case DataTableColumnType::DT_Int: + { + m_types.push_back(new DataTableColumnType("i")); + } + break; + case DataTableColumnType::DT_Float: + { + m_types.push_back(new DataTableColumnType("f")); + } + break; + case DataTableColumnType::DT_String: + { + m_types.push_back(new DataTableColumnType("s")); + } + break; + case DataTableColumnType::DT_Unknown: + case DataTableColumnType::DT_HashString: + case DataTableColumnType::DT_Enum: + case DataTableColumnType::DT_Bool: + case DataTableColumnType::DT_BitVector: + case DataTableColumnType::DT_Comment: + case DataTableColumnType::DT_PackedObjVars: + + default: + { + FATAL(true, ("unknown column type loaded from version 0000")); + } + break; + } + } + iff.exitChunk(TAG(T,Y,P,E)); + + //load rows + iff.enterChunk(TAG(R,O,W,S)); + m_numRows = iff.read_int32(); + + const size_t cellSize = m_numRows * m_numCols * sizeof(DataTableCell); + void *cellMemory = malloc(cellSize); + m_cells = (DataTableCell *)cellMemory; + for (i = 0; i < m_numRows; ++i) + { + for (int j = 0; j < m_numCols; ++j) + { + _readCell(iff, j, i); + } + } + + iff.exitChunk(TAG(R,O,W,S)); + iff.exitForm(TAG_0000, false); +} + +//---------------------------------------------------------------------------- + +void DataTable::load_0001(Iff & iff) +{ + IGNORE_RETURN( iff.enterForm(TAG_0001, false) ); + + //load columns + iff.enterChunk(TAG(C,O,L,S)); + m_numCols = iff.read_int32(); + int i = 0; + m_columns.reserve(m_numCols); + std::string tmpString; + for (i = 0; i < m_numCols; ++i) + { + iff.read_string(tmpString); + m_columns.push_back(tmpString); + tmpString.clear(); + } + + iff.exitChunk(TAG(C,O,L,S)); + //load type info + iff.enterChunk(TAG(T,Y,P,E)); + for (i = 0; i < m_numCols; ++i) + { + // version 0001 has a format string for the type + m_types.push_back(new DataTableColumnType(iff.read_stdstring())); + } + iff.exitChunk(TAG(T,Y,P,E)); + + //load rows + iff.enterChunk(TAG(R,O,W,S)); + m_numRows = iff.read_int32(); + + const size_t cellSize = m_numRows * m_numCols * sizeof(DataTableCell); + void *cellMemory = malloc(cellSize); + m_cells = (DataTableCell *)cellMemory; + for (i = 0; i < m_numRows; ++i) + { + for (int j = 0; j < m_numCols; ++j) + { + _readCell(iff, j, i); + } + } + + iff.exitChunk(TAG(R,O,W,S)); + iff.exitForm(TAG_0001, false); +} + +// ---------------------------------------------------------------------- + +int DataTable::searchColumnString( int column, const std::string & searchValue ) const +{ + DEBUG_FATAL(column < 0 || column >= getNumColumns(), ("DataTable [%s] searchColumnString(): Invalid col number [%d]. Cols=[%d]\n", m_name.c_str(), column, getNumColumns())); + + int retval = -1; + + void * voidIndex = m_index[ static_cast(column) ]; + if (!voidIndex) + { + std::pair, std::multimap > * indexPair = new std::pair, std::multimap >; + NOT_NULL(indexPair); + + m_index[static_cast(column)] = static_cast(indexPair); + + //no index has been built yet for this column + int rowCount = getNumRows(); + for (int i = 0; i < rowCount; ++i) + { + const std::string & valueString = getStringValue(column,i); + IGNORE_RETURN ( indexPair->first.insert(std::pair(valueString, i)) ); + int valueCrc = getIntValue(column,i); + IGNORE_RETURN ( indexPair->second.insert(std::pair(valueCrc, i)) ); + if (retval == -1 && valueString == searchValue) + retval = i; + } + } + else + { + std::pair, std::multimap > * indexPair = static_cast, std::multimap > *>(voidIndex); + std::multimap::iterator iter = indexPair->first.find(searchValue); + if (iter != indexPair->first.end()) + retval = iter->second; + } + + return retval; +} + +// ---------- + +int DataTable::searchColumnFloat( int column, float searchValue ) const +{ + DEBUG_FATAL(column < 0 || column >= getNumColumns(), ("DataTable [%s] searchColumnFloat(): Invalid col number [%d]. Cols=[%d]\n", m_name.c_str(), column, getNumColumns())); + + int retval = -1; + + void * voidIndex = m_index[ static_cast(column) ]; + if (!voidIndex) + { + std::multimap * index = new std::multimap; + NOT_NULL(index); + + m_index[static_cast(column)] = static_cast(index); + + //no index has been built yet for this column + for (int i = 0; i < getNumRows(); ++i) + { + float rowValue = getFloatValue(column,i); + IGNORE_RETURN ( index->insert(std::pair(rowValue, i)) ); + if (retval == -1 && rowValue == searchValue) //lint !e777 //ok to compare floats + retval = i; + } + } + else + { + std::multimap * index = static_cast *>(voidIndex); + std::multimap::iterator iter = index->find(searchValue); + if (iter != index->end()) + retval = iter->second; + } + + return retval; +} + +// ---------- + +int DataTable::searchColumnInt( int column, int searchValue ) const +{ + DEBUG_FATAL(column < 0 || column >= getNumColumns(), ("DataTable [%s] searchColumnInt(): Invalid col number [%d]. Cols=[%d]\n", m_name.c_str(), column, getNumColumns())); + + int retval = -1; + DataTableColumnType::DataType columnType = m_types[static_cast(column)]->getBasicType(); + + void * voidIndex = m_index[ static_cast(column) ]; + if (!voidIndex) + { + if (columnType == DataTableColumnType::DT_Int) + { + std::multimap * index = new std::multimap; + NOT_NULL(index); + + m_index[static_cast(column)] = static_cast(index); + + //no index has been built yet for this column + int rowCount = getNumRows(); + for (int i = 0; i < rowCount; ++i) + { + int rowValue = getIntValue(column,i); + IGNORE_RETURN ( index->insert(std::pair(rowValue, i)) ); + if (retval == -1 && rowValue == searchValue) + retval = i; + } + } + else if (columnType == DataTableColumnType::DT_String) + { + std::pair, std::multimap > * indexPair = new std::pair, std::multimap >; + NOT_NULL(indexPair); + + m_index[static_cast(column)] = static_cast(indexPair); + + //no index has been built yet for this column + int rowCount = getNumRows(); + for (int i = 0; i < rowCount; ++i) + { + const std::string & valueString = getStringValue(column,i); + IGNORE_RETURN ( indexPair->first.insert(std::pair(valueString, i)) ); + int valueCrc = getIntValue(column,i); + IGNORE_RETURN ( indexPair->second.insert(std::pair(valueCrc, i)) ); + if (retval == -1 && valueCrc == searchValue) + retval = i; + } + } + } + else + { + if (columnType == DataTableColumnType::DT_Int) + { + std::multimap * index = static_cast *>(voidIndex); + std::multimap::iterator iter = index->find(searchValue); + if (iter != index->end()) + retval = iter->second; + } + else if (columnType == DataTableColumnType::DT_String) + { + std::pair, std::multimap > * indexPair = static_cast, std::multimap > *>(voidIndex); + std::multimap::iterator iter = indexPair->second.find(searchValue); + if (iter != indexPair->second.end()) + retval = iter->second; + } + } + + return retval; + +} + +// ---------- + +void DataTable::buildColumnIndexMap() +{ + std::vector::const_iterator i = m_columns.begin(); + for (int columnIndex = 0; i != m_columns.end(); ++i, ++columnIndex) + { + (*m_columnIndexMap)[*i] = columnIndex; + } +} + +//---------------------------------------------------------------------------- + diff --git a/engine/shared/library/sharedUtility/src/shared/DataTable.h b/engine/shared/library/sharedUtility/src/shared/DataTable.h new file mode 100644 index 00000000..eb986091 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/DataTable.h @@ -0,0 +1,127 @@ +// ====================================================================== +// +// DataTable.h +// +// copyright 2002 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_DataTable_H +#define INCLUDED_DataTable_H + +#include "sharedFoundation/Tag.h" +#include "DataTableCell.h" +#include "DataTableColumnType.h" + +#include +#include + +class Iff; + +class DataTable +{ +public: + DataTable(); + virtual ~DataTable(); + + bool doesColumnExist(const std::string &) const; + const std::string & getColumnName(int column) const; + int findColumnNumber(const std::string & column) const; + DataTableColumnType const &getDataTypeForColumn(const std::string& column) const; + DataTableColumnType const &getDataTypeForColumn(int column) const; + + int getIntValue(const std::string & column, int row) const; + int getIntValue(int column, int row) const; + int getIntDefaultForColumn(const std::string & column) const; + int getIntDefaultForColumn(int column) const; + float getFloatValue(const std::string & column, int row) const; + float getFloatValue(int column, int row) const; + float getFloatDefaultForColumn(const std::string & column) const; + float getFloatDefaultForColumn(int column) const; + const char * getStringValue(const std::string & column, int row) const; + const char * getStringValue(int column, int row) const; + std::string getStringDefaultForColumn(const std::string & column) const; + std::string getStringDefaultForColumn(int column) const; + + void getIntColumn(const std::string& column, std::vector& returnVector) const; + void getIntColumn(const std::string& column, std::vector& returnVector) const; + void getFloatColumn(const std::string& column, std::vector& returnVector) const; + void getStringColumn(const std::string& column, std::vector& returnVector) const; + void getIntColumn(int column, std::vector& returnVector) const; + void getIntColumn(int column, std::vector& returnVector) const; + void getFloatColumn(int column, std::vector& returnVector) const; + void getStringColumn(int column, std::vector& returnVector) const; + + int getNumColumns() const; + int getNumRows() const; + + void load(Iff &); + + // Search a column of the table for a given value and return the index of the first + // matching row. Warning - this is a linear search, so it can be slow. + + int searchColumnString(int column, const std::string & searchValue) const; + int searchColumnFloat(int column, float searchValue) const; + int searchColumnInt(int column, int searchValue) const; + + std::string const & getName() const; + + static Tag getDataTableIffId() { return m_dataTableIffId; } + +protected: + + const std::vector &_columns() const { return m_columns; } + +private: + + const DataTableCell * getDataTableCell(int column, int row) const; + void _readCell(Iff & iff, int column, int row); + + static DataTableColumnType getDataType(const std::string &type); + void load_0000(Iff &); + void load_0001(Iff &); + void buildColumnIndexMap(); + + typedef std::vector DataTableColumnTypeVector; + typedef stdhash_map::fwd ColumnIndexMap; + + int m_numRows; + int m_numCols; + DataTableCell const * m_cells; + std::vector m_columns; + mutable std::vector m_index; + DataTableColumnTypeVector m_types; + ColumnIndexMap * m_columnIndexMap; + std::string m_name; + + static const Tag m_dataTableIffId; + +private: + + DataTable(DataTable const &); + DataTable & operator=(DataTable const &); +}; + +inline int DataTable::getNumColumns() const +{ + return static_cast(m_columns.size()); +} + +inline int DataTable::getNumRows() const +{ + return m_numRows; +} + +inline const DataTableCell * DataTable::getDataTableCell(int column, int row) const +{ + return m_cells + (row * m_numCols + column); +} + +//---------------------------------------------------------------------- + +inline std::string const & DataTable::getName() const +{ + return m_name; +} + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/DataTableCell.cpp b/engine/shared/library/sharedUtility/src/shared/DataTableCell.cpp new file mode 100644 index 00000000..62573069 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/DataTableCell.cpp @@ -0,0 +1,108 @@ +// ====================================================================== +// +// DataTableCell.cpp +// +// copyright 2002 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/DataTableCell.h" + +#include "sharedFoundation/Crc.h" +#include "sharedFoundation/CrcString.h" +#include "sharedFoundation/MemoryBlockManager.h" + + +// ====================================================================== + +MemoryBlockManager *DataTableCell::ms_memoryBlockManager; + +// ---------------------------------------------------------------------- + +void DataTableCell::install() +{ + DEBUG_FATAL(ms_memoryBlockManager, ("DataTableCell is not installed")); + ms_memoryBlockManager = new MemoryBlockManager("DataTableCell::ms_memoryBlockManager", true, sizeof(DataTableCell), 0, 0, 0); +} + +// ---------------------------------------------------------------------- + +void DataTableCell::remove() +{ + DEBUG_FATAL(!ms_memoryBlockManager,("DataTableCell is not installed")); + delete ms_memoryBlockManager; + ms_memoryBlockManager = 0; +} + +// ---------------------------------------------------------------------- + +void *DataTableCell::operator new(size_t size) +{ + UNREF(size); + DEBUG_FATAL(!ms_memoryBlockManager,("DataTableCell is not installed")); + DEBUG_FATAL(size != sizeof(DataTableCell),("bad size")); + return ms_memoryBlockManager->allocate(); +} + +// ---------------------------------------------------------------------- + +void DataTableCell::operator delete(void *pointer) +{ + DEBUG_FATAL(!ms_memoryBlockManager,("DataTableCell is not installed")); + ms_memoryBlockManager->free(pointer); +} + +// ---------------------------------------------------------------------- + +DataTableCell::DataTableCell(int value) +: m_type(CT_int) +{ + m_value.m_i=value; +} + +// ---------------------------------------------------------------------- + +DataTableCell::DataTableCell(float value) +: m_type(CT_float) +{ + m_value.m_f = value; +} + +// ---------------------------------------------------------------------- + +DataTableCell::DataTableCell(const char *value) +: m_type(CT_string) +{ + if (!value || !*value) + { + m_value.m_s.m_sz = 0; + m_value.m_s.m_crc = 0; + } + else + { + int len = strlen(value) + 1; + char *s = new char[len]; + + // normalize copies the output into s, so we can get the crc + CrcString::normalize(s, value); + m_value.m_s.m_crc = Crc::calculate(s); + + // copy the correct (unnormalized) string into s (this saves us the allocation of a tmp string) + strcpy(s, value); + m_value.m_s.m_sz = s; + } +} + +// ---------------------------------------------------------------------- + +DataTableCell::~DataTableCell() +{ + if (m_type==CT_string && m_value.m_s.m_sz!=0) + { + delete [] const_cast(m_value.m_s.m_sz); + #ifdef _DEBUG + m_value.m_s.m_sz=0; + #endif + } +} diff --git a/engine/shared/library/sharedUtility/src/shared/DataTableCell.h b/engine/shared/library/sharedUtility/src/shared/DataTableCell.h new file mode 100644 index 00000000..5021b5f8 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/DataTableCell.h @@ -0,0 +1,81 @@ +// ====================================================================== +// +// DataTableCell.h +// +// copyright 2002 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_DataTableCell_H +#define INCLUDED_DataTableCell_H + +// ====================================================================== + +class MemoryBlockManager; + +// ====================================================================== + +class DataTableCell +{ +public: + + static void install(); + static void remove(); + static void *operator new(size_t size, void *p) { UNREF(size); return p; } + static void *operator new(size_t size); + static void operator delete(void *pointer); + + enum CellType { + CT_string + ,CT_int + ,CT_float + }; + + explicit DataTableCell(int value); + explicit DataTableCell(float value); + explicit DataTableCell(const char *value); + ~DataTableCell(); + + CellType getType() const { return m_type; } + int getIntValue() const { return m_value.m_i; } + float getFloatValue() const { return m_value.m_f; } + const char *getStringValue() const; + int getStringValueCrc() const { return m_value.m_s.m_crc; } + +private: + const CellType m_type; + struct + { + union + { + int m_i; + float m_f; + struct + { + const char *m_sz; + int m_crc; + } m_s; + }; + } m_value; + + + DataTableCell &operator=(const DataTableCell &); + + static MemoryBlockManager *ms_memoryBlockManager; +}; + +inline const char *DataTableCell::getStringValue() const +{ + if (m_value.m_s.m_sz) + { + return m_value.m_s.m_sz; + } + else + { + return ""; + } +} + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/DataTableColumnType.cpp b/engine/shared/library/sharedUtility/src/shared/DataTableColumnType.cpp new file mode 100644 index 00000000..e0ac3cf4 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/DataTableColumnType.cpp @@ -0,0 +1,483 @@ +// ====================================================================== +// +// DataTableColumnType.cpp +// +// copyright 2002 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/DataTableColumnType.h" + +#include "UnicodeUtils.h" +#include "sharedFoundation/Crc.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" +#include +#include + +// ---------------------------------------------------------------------- + +static std::string chomp(std::string const &str) +{ + std::string result = str; + while(!result.empty() && result[0] == ' ') + result.erase(0, 1); + while(!result.empty() && result[result.size() - 1] == ' ') + result.erase(result.size() - 1, 1); + return result; +} + +static std::string getDelimStr(std::string const &str, char left, char right) +{ + std::string::size_type lPos = str.find(left); + std::string::size_type rPos = str.rfind(right); + + if (lPos == std::string::npos || rPos == std::string::npos) + return ""; + + return str.substr(lPos+1, rPos-lPos-1); +} + +// ---------------------------------------------------------------------- + +bool consumePackedObjVarIntField(char const *&s) +{ + while (*s) + { + char const c = *s; + ++s; + if (c == '|') + return true; + else if ( c != '-' && !isdigit(c)) + break; + } + return false; +} + +// ---------------------------------------------------------------------- + +bool consumePackedObjVarStringField(char const *& s) +{ + while (*s) + { + char const c = *s++; + if (c == '|') + return true; + } + return false; +} + +// ---------------------------------------------------------------------- + +DataTableColumnType::~DataTableColumnType () +{ + delete m_enumMap; + m_enumMap = 0; + + delete m_defaultCell; + m_defaultCell = 0; +} + +// ---------------------------------------------------------------------- + +DataTableColumnType::DataTableColumnType(std::string const &desc) : + m_typeSpecString(desc), + m_type(DT_Unknown), + m_basicType(DT_Unknown), + m_defaultValue(), + m_enumMap(0), + m_defaultCell(0) +{ + // desc may only look like: + // {ifshbep}[def] or e(x=0,y=1,z=2,...)[def] + + // first, split into type and default value + int type = tolower(desc[0]); + m_defaultValue = getDelimStr(desc, '[', ']'); + + if (type == 'i') + { + m_type = m_basicType = DT_Int; + if (m_defaultValue.length() == 0) + m_defaultValue = "0"; + } + else if (type == 'f') + { + m_type = m_basicType = DT_Float; + if (m_defaultValue.length() == 0) + m_defaultValue = "0"; + } + else if (type == 's') + { + m_type = m_basicType = DT_String; + } + else if (type == 'c') + { + m_type = m_basicType = DT_Comment; + } + else if (type == 'h') + { + m_type = DT_HashString; + m_basicType = DT_Int; + } + else if (type == 'p') + { + m_type = DT_PackedObjVars; + m_basicType = DT_String; + } + else if (type == 'b') + { + m_type = DT_Bool; + m_basicType = DT_Int; + if (m_defaultValue != "1") + m_defaultValue = "0"; + } + else if (type == 'e') + { + m_enumMap = new StringIntMap; + m_type = DT_Enum; + m_basicType = DT_Int; + // build the enumeration map + std::string enumList = getDelimStr(desc, '(', ')'); + enumList += ","; + // enumList looks like "foo=0,bar=1,life=42," + std::string::size_type eqPos; + while ((eqPos = enumList.find('=')) != std::string::npos) + { + std::string::size_type endPos = enumList.find(','); + std::string label = enumList.substr(0, eqPos); + std::string val = enumList.substr(eqPos+1, endPos-eqPos-1); + (*m_enumMap)[label] = static_cast(strtol(val.c_str(), NULL, 0)); + enumList.erase(0, endPos+1); + } + // assure the default is a member of the enumeration + if (m_enumMap->find(m_defaultValue) == m_enumMap->end()) + { + WARNING(true, ("Default value [%s] is not a member of enumeration", m_defaultValue.c_str())); + m_basicType = DT_Unknown; + } + } + else if (type == 'v') + { + m_enumMap = new StringIntMap; + m_type = DT_BitVector; + m_basicType = DT_Int; + // build the enumeration map + std::string enumList = getDelimStr(desc, '(', ')'); + enumList += ","; + // enumList looks like "foo=0,bar=1,life=42," + std::string::size_type eqPos; + while ((eqPos = enumList.find('=')) != std::string::npos) + { + std::string::size_type endPos = enumList.find(','); + std::string label = enumList.substr(0, eqPos); + std::string val = enumList.substr(eqPos+1, endPos-eqPos-1); + int bit = static_cast(strtol(val.c_str(), NULL, 0)); + if((bit < 1) || (bit > 32)) + { + WARNING(true, ("Flags value [%s] is not a whole number from 1 to 32", label.c_str())); + m_basicType = DT_Unknown; + } + (*m_enumMap)[label] = 1 << (bit - 1); + enumList.erase(0, endPos+1); + } + // assure the default is a member of the enumeration + if(strcmp(m_defaultValue.c_str(), "NONE") != 0) + { + if (m_enumMap->find(m_defaultValue) == m_enumMap->end()) + { + WARNING(true, ("Default value [%s] is not a member of enumeration", m_defaultValue.c_str())); + m_basicType = DT_Unknown; + } + } + } + else if (type == 'z') + { + m_enumMap = new StringIntMap; + m_type = DT_Enum; + m_basicType = DT_Int; + // get the filename + std::string fileName = getDelimStr(desc, '(', ')'); + + DataTable * enumTable = DataTableManager::getTable(fileName, true); + if (!enumTable) + { + m_basicType = DT_Unknown; + return; + } + int enumCount = enumTable->getNumRows(); + int x; + std::string firstKey; + for (x=0; xgetStringValue(0, x); + Unicode::trim(key); + int value = enumTable->getIntValue(1,x); + if (x==0) + firstKey = key; + (*m_enumMap)[key] = value; + } + + // assure the default is a member of the enumeration + if (m_enumMap->find(m_defaultValue) == m_enumMap->end()) + { + m_defaultValue = firstKey; + } + } + else + m_basicType = DT_Unknown; + + createDefaultCell(); +} + +// ---------------------------------------------------------------------- + +void DataTableColumnType::createDefaultCell() +{ + std::string value; + + IS_NULL(m_defaultCell); + + // If mangleValue does not update the input value string, + // then the default cell will have a value of 0 for floats and ints + // and a value of empty string for strings. + IGNORE_RETURN(mangleValue(value)); + + switch(m_basicType) + { + case DT_Int: + m_defaultCell = new DataTableCell(static_cast(strtol(value.c_str(), NULL, 0))); + break; + case DT_Float: + m_defaultCell = new DataTableCell(static_cast(atof(value.c_str()))); + break; + case DT_String: + case DT_Comment: + case DT_Unknown: + default: + m_defaultCell = new DataTableCell(value.c_str()); + break; + } +} + +// ---------------------------------------------------------------------- + +DataTableColumnType::DataTableColumnType(DataTableColumnType const &rhs) : + m_typeSpecString(rhs.m_typeSpecString), + m_type(rhs.m_type), + m_basicType(rhs.m_basicType), + m_defaultValue(rhs.m_defaultValue), + m_enumMap(rhs.m_enumMap ? new StringIntMap (*rhs.m_enumMap) : 0), + m_defaultCell(0) +{ + createDefaultCell(); +} + +// ---------------------------------------------------------------------- + +DataTableColumnType& DataTableColumnType::operator=(DataTableColumnType const &rhs) +{ + if (&rhs != this) + { + m_typeSpecString = rhs.m_typeSpecString; + m_type = rhs.m_type; + m_basicType = rhs.m_basicType; + m_defaultValue = rhs.m_defaultValue; + + if(rhs.m_enumMap) + { + if(!m_enumMap) + m_enumMap = new StringIntMap; + *m_enumMap = *rhs.m_enumMap; + } + else + { + delete m_enumMap; + m_enumMap = 0; + } + + delete m_defaultCell; + m_defaultCell = 0; + + createDefaultCell(); + } + return *this; +} + +// ---------------------------------------------------------------------- + +std::string const &DataTableColumnType::getTypeSpecString() const +{ + return m_typeSpecString; +} + +// ---------------------------------------------------------------------- + +DataTableColumnType::DataType DataTableColumnType::getType() const +{ + return m_type; +} + +// ---------------------------------------------------------------------- + +DataTableColumnType::DataType DataTableColumnType::getBasicType() const +{ + return m_basicType; +} + +// ---------------------------------------------------------------------- + +bool DataTableColumnType::lookupEnum(std::string const &label, int &result) const +{ + NOT_NULL(m_enumMap); + + std::string localLabel = chomp(label); + + const StringIntMap::const_iterator i = m_enumMap->find(localLabel); + if (i != m_enumMap->end()) + { + result = (*i).second; + return true; + } + return false; +} + +// ---------------------------------------------------------------------- + +bool DataTableColumnType::lookupBitVector(std::string const &label, int &result) const +{ + std::string localLabel = label; + if(strcmp(label.c_str(), "NONE") == 0) + { + result = 0; + return true; + } + bool foundAny = false; + localLabel += ","; + // enumList looks like "foo,bar,life," + std::string::size_type eqPos; + while ((eqPos = localLabel.find(',')) != std::string::npos) + { + std::string::size_type endPos = localLabel.find(','); + std::string subLabel = chomp(localLabel.substr(0, eqPos)); + int subResult; + if(lookupEnum(subLabel, subResult)) + { + foundAny = true; + result |= subResult; + } + else + { + DEBUG_WARNING(true, ("DataTableColumnType::lookupEnumExtended found invalid enum value '%s'", subLabel.c_str())); + } + localLabel.erase(0, endPos+1); + } + + return foundAny; +} + +// ---------------------------------------------------------------------- + +bool DataTableColumnType::mangleValue(std::string &value) const +{ + // if the value passed in is empty, we mangle to the default value + if (value.length() == 0) + { + if (m_defaultValue == "required" || m_defaultValue == "unique") + return false; + else + value = m_defaultValue; + } + + // special validation code for packed objvars + if (m_type == DT_PackedObjVars) + { + // packed objvars are of the form: + // nameString|typeInt|valueString|nameString|typeInt|valueString|$| + // where || may be used in the string fields to represent a | + char const *s = value.c_str(); + while (*s) + { + // name + if (s[0] == '$' && s[1] == '|' && s[2] == '\0') + break; + if (!consumePackedObjVarStringField(s)) + return false; + // type + if (!consumePackedObjVarIntField(s)) + return false; + // value + if (!consumePackedObjVarStringField(s)) + return false; + } + } + + // only basic type DT_Int are complex types that use value mangling other + // than default values + if (m_basicType != DT_Int || m_type == DT_Int) + return true; + // complex type which needs mangling + switch (m_type) + { + case DT_Bool: + { + if (value == "0" || value == "1") + return true; + } + break; + case DT_HashString: + { + // conversion to integer crc + int val; + if (value.length()) + val = Crc::normalizeAndCalculate(value.c_str()); + else + val = Crc::crcNull; + char buf[16]; + sprintf(buf, "%d", val); + value = buf; + return true; + } + break; + case DT_Enum: + { + // enumeration lookup + int val = 0; + if (lookupEnum(value, val)) + { + char buf[16]; + sprintf(buf, "%d", val); + value = buf; + return true; + } + } + break; + case DT_BitVector: + { + // enumeration lookup + int val = 0; + if (lookupBitVector(value, val)) + { + char buf[16]; + sprintf(buf, "%d", val); + value = buf; + return true; + } + } + break; + default: + break; + } + return false; +} + +// ---------------------------------------------------------------------- + +bool DataTableColumnType::areUniqueCellsRequired() const +{ + return m_defaultValue == "unique"; +} + +// ====================================================================== + diff --git a/engine/shared/library/sharedUtility/src/shared/DataTableColumnType.h b/engine/shared/library/sharedUtility/src/shared/DataTableColumnType.h new file mode 100644 index 00000000..9f816802 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/DataTableColumnType.h @@ -0,0 +1,70 @@ +// ====================================================================== +// +// DataTableColumnType.h +// +// copyright 2002 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_DataTableColumnType_H +#define INCLUDED_DataTableColumnType_H + +#include + +class DataTableCell; + +class DataTableColumnType +{ +public: + explicit DataTableColumnType(std::string const &desc); + ~DataTableColumnType (); + DataTableColumnType(DataTableColumnType const &rhs); + DataTableColumnType &operator=(DataTableColumnType const &rhs); + + enum DataType + { + DT_Int, + DT_Float, + DT_String, + DT_Unknown, + DT_Comment, + // specializations of DT_Int basic type + DT_HashString, + DT_Enum, + DT_Bool, + // specializations of DT_String basic type + DT_PackedObjVars, + DT_BitVector, + }; + + DataType getType() const; + DataType getBasicType() const; + std::string const &getTypeSpecString() const; + bool mangleValue(std::string &value) const; + DataTableCell const *getDefaultCell() const; + bool areUniqueCellsRequired() const; + +private: + bool lookupEnum(std::string const &label, int &result) const; + bool lookupBitVector(std::string const &label, int &result) const; + +private: + DataTableColumnType(); + void createDefaultCell(); + + std::string m_typeSpecString; + DataType m_type; + DataType m_basicType; + std::string m_defaultValue; + typedef stdmap::fwd StringIntMap; + StringIntMap * m_enumMap; + DataTableCell * m_defaultCell; +}; + +inline const DataTableCell * DataTableColumnType::getDefaultCell() const +{ + return m_defaultCell; +} + +#endif // INCLUDED_DataTableColumnType_H + diff --git a/engine/shared/library/sharedUtility/src/shared/DataTableManager.cpp b/engine/shared/library/sharedUtility/src/shared/DataTableManager.cpp new file mode 100644 index 00000000..87a994da --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/DataTableManager.cpp @@ -0,0 +1,197 @@ +// ====================================================================== +// +// DataTableManager.cpp +// +// copyright 2002 Sony Online Entertainment +// +// ====================================================================== + + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/DataTableManager.h" + +#include "sharedFile/Iff.h" +#include "sharedFile/TreeFile.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableCell.h" +#include + +// ---------------------------------------------------------------------- + +DataTable * DataTableManager::m_cachedTable = 0; +std::string DataTableManager::m_cachedTableName = ""; +bool DataTableManager::m_errorChecking = false; +std::map DataTableManager::m_tables; +bool DataTableManager::m_installed = false; +std::multimap DataTableManager::m_reloadCallbacks; + +// ---------------------------------------------------------------------- + +void DataTableManager::install(bool verboseErrorChecking) +{ + FATAL(m_installed, ("DataTableManager::install: already installed.")); + m_errorChecking = verboseErrorChecking; + ExitChain::add(DataTableManager::remove, "DataTableManager::remove"); + + DataTableCell::install(); + + m_installed = true; +} + +// ---------------------------------------------------------------------- + +void DataTableManager::remove() +{ + FATAL(!m_installed, ("DataTableManager::remove: not installed.")); + m_cachedTable = 0; + m_cachedTableName = ""; + + std::map::iterator i; + for (i=m_tables.begin(); i != m_tables.end(); ++i) + { + DataTable * toDelete = i->second; + delete toDelete; + } + + m_tables.clear(); + m_reloadCallbacks.clear(); + + DataTableCell::remove(); + + m_installed = false; +} + +// ---------------------------------------------------------------------- + +DataTable* DataTableManager::open(const std::string& table) +{ + FATAL(!m_installed, ("DataTableManager::open: not installed.")); + DataTable *retVal = getTable(table, false); + if (retVal) + return retVal; + + if (!TreeFile::exists(table.c_str())) + { + DEBUG_WARNING(true, ("Could not find treefile table for open [%s]", table.c_str())); + return 0; + } + + Iff iff(table.c_str(), false); + retVal = new DataTable; + retVal->load(iff); + + m_cachedTable = retVal; + m_cachedTableName = table; + m_tables[table] = retVal; + + return retVal; +} +// ---------------------------------------------------------------------- + + +void DataTableManager::close(const std::string& table) +{ +// FATAL(!m_installed, ("DataTableManager::close: not installed.")); + std::map::iterator i = m_tables.find(table); + if (i == m_tables.end()) + { + DEBUG_WARNING(true, ("Could not find loaded table for close [%s]", table.c_str())); + return; + } + + if (m_cachedTable == i->second) + { + DEBUG_WARNING(m_cachedTableName != table, ("Cached name got out of sync")); + m_cachedTableName = ""; + m_cachedTable = 0; + } + + DataTable * dt = i->second; + m_tables.erase(i); + delete dt; +} +// ---------------------------------------------------------------------- + + +DataTable * DataTableManager::getTable(const std::string& table, bool openIfNotFound) +{ +// FATAL(!m_installed, ("DataTableManager::getTable: not installed.")); + if (m_cachedTableName == table) + return m_cachedTable; + + std::map::iterator i = m_tables.find(table); + if (i == m_tables.end()) + { + if (openIfNotFound) + { + DataTable * dt = open(table); + if (!dt) + { + DEBUG_WARNING(true, ("Could not find table [%s]", table.c_str())); + return NULL; + } + else + { + m_cachedTableName = table; + m_cachedTable = dt; + return dt; + } + } + else + { + return NULL; + } + } + + m_cachedTableName = table; + m_cachedTable = i->second; + return i->second; +} + +// ---------------------------------------------------------------------- + +DataTable* DataTableManager::reload(const std::string & table) +{ +// FATAL(!m_installed, ("DataTableManager::reload: not installed.")); + close(table); + + DataTable * const dataTable = open(table); + + if (dataTable != NULL) + { + std::multimap::const_iterator i = m_reloadCallbacks.lower_bound(table); + for (; i != m_reloadCallbacks.end() && (*i).first == table; ++i) + (*((*i).second))(*dataTable); + } + + return dataTable; +} + +// ---------------------------------------------------------------------- + +DataTable* DataTableManager::reloadIfOpen(const std::string & table) +{ + if(isOpen(table)) + return reload(table); + else + return NULL; +} + +// ---------------------------------------------------------------------- + +void DataTableManager::addReloadCallback(const std::string& table, DataTableReloadCallback callbackFunction) +{ + IGNORE_RETURN(m_reloadCallbacks.insert(std::make_pair(table, callbackFunction))); +} + +// ---------------------------------------------------------------------- + +bool DataTableManager::isOpen(const std::string& table) +{ + std::map::const_iterator const i = m_tables.find(table); + return i != m_tables.end(); +} + +// ====================================================================== + diff --git a/engine/shared/library/sharedUtility/src/shared/DataTableManager.h b/engine/shared/library/sharedUtility/src/shared/DataTableManager.h new file mode 100644 index 00000000..19b34143 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/DataTableManager.h @@ -0,0 +1,50 @@ +// ====================================================================== +// +// DataTableManager.h +// +// copyright 2002 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_DataTableManager_H +#define INCLUDED_DataTableManager_H + +// ====================================================================== + +class DataTable; + +// ====================================================================== + +typedef void (*DataTableReloadCallback)(DataTable const &); + +class DataTableManager +{ +public: + static void install(bool verboseErrorChecking = true); + + static void close(const std::string& table); + static DataTable * getTable(const std::string& table, bool openIfNotFound = false); + static DataTable * reload(const std::string& table); + static DataTable * reloadIfOpen(const std::string& table); + static void addReloadCallback(const std::string& table, DataTableReloadCallback callbackFunction); + static bool isOpen(const std::string& table); + +private: + static void remove(); + + static DataTable * open(const std::string& table); + + DataTableManager(); + ~DataTableManager(); + + static DataTable* m_cachedTable; + static std::string m_cachedTableName; + static bool m_errorChecking; + static stdmap::fwd m_tables; + static bool m_installed; + static stdmultimap::fwd m_reloadCallbacks; +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/DataTableWriter.cpp b/engine/shared/library/sharedUtility/src/shared/DataTableWriter.cpp new file mode 100644 index 00000000..1a004dd2 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/DataTableWriter.cpp @@ -0,0 +1,1059 @@ +// ====================================================================== +// +// DataTableWriter.cpp +// +// Copyright 2002 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/DataTableWriter.h" + +#include "fileInterface/StdioFile.h" +#include "sharedFile/FileNameUtils.h" +#include "sharedFile/Iff.h" +#include "sharedFoundation/ConstCharCrcString.h" +#include "sharedUtility/DataTable.h" +#include "sharedXml/XmlTreeDocument.h" +#include "sharedXml/XmlTreeDocumentList.h" +#include "sharedXml/XmlTreeNode.h" + +#include + +// ====================================================================== + +#ifdef _DEBUG +namespace DataTableWriterNamespace +{ + int s_debugRow = 0; +}; +#endif + +//---------------------------------------------------------------------------- + +class DataTableWriter::NamedDataTable +{ + friend class DataTableWriter; + +public: + + NamedDataTable(); + ~NamedDataTable(); + + const std::string& getName() const; + void setName(const std::string& name); + + int getNumColumns() const { return static_cast(m_columns.size()); } + + const std::string & getColumnName(int column) const + { + DEBUG_FATAL(column < 0 || column >= static_cast(m_columns.size()), ("DataTable [%s] getColumnName(): Invalid col number [%d]. Cols=[%d]\n", m_Name.c_str(), column, static_cast(m_columns.size()))); + return m_columns[static_cast(column)]; + } + + const DataTableColumnType &getDataTypeForColumn(int column) const + { + DEBUG_FATAL(column < 0 || column >= static_cast(m_columns.size()), ("DataTable [%s] getDataTypeForColumn(): Invalid col number [%d] for possible row [%d]. Cols=[%d]\n", m_Name.c_str(), column, DataTableWriterNamespace::s_debugRow, static_cast(m_columns.size()))); + return *m_types[static_cast(column)]; + } + + int getNumRows() const { return static_cast(m_rows.size()); } + +private: + + typedef std::vector DataTableRow; + typedef std::vector DataTableColumnTypeVector; + + std::string m_Name; + + std::vector m_rows; + std::vector m_columns; + DataTableColumnTypeVector m_types; + +private: + NamedDataTable(NamedDataTable const &); + NamedDataTable & operator=(NamedDataTable const &); +}; + +//---------------------------------------------------------------------------- + +namespace DataTableWriterNamespace +{ + std::string &unquotify(std::string &s); + + std::string getTableNameFromTabFile( const char* fileName ); + +}; + +using namespace DataTableWriterNamespace; + +// ====================================================================== + +DataTableWriter::NamedDataTable::NamedDataTable() +{ +} + +// ---------------------------------------------------------------------- + +DataTableWriter::NamedDataTable::~NamedDataTable() +{ + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + std::vector::iterator i = m_rows.begin(); + for (; i != m_rows.end(); ++i) + { + DataTableColumnTypeVector::iterator k = m_types.begin(); + DataTableRow::iterator j = (*i)->begin(); + for(; j != (*i)->end(); ++j, ++k) + { + // Only delete cells that are different from the default + if(*j != (*k)->getDefaultCell()) + delete *j; + } + delete *i; + } + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + DataTableColumnTypeVector::iterator l = m_types.begin(); + while (l != m_types.end()) + { + delete *l++; + } + m_types.clear(); +} + +// ---------------------------------------------------------------------- + +inline const std::string& DataTableWriter::NamedDataTable::getName() const +{ + return m_Name; +} + +// ---------------------------------------------------------------------- + +inline void DataTableWriter::NamedDataTable::setName(const std::string& name) +{ + m_Name = name; +} + +// ---------------------------------------------------------------------- + +std::string & DataTableWriterNamespace::unquotify(std::string &s) +{ + static const std::string quote = "\""; + + //First strip any beginning end quotes. + if (s.length() >= 2) + { + if (s[0] == '"') + s.erase(0, 1); + if (s[s.length()-1] == '"') + s.erase(s.length()-1, 1); + } + + + //Then deal with imbedded quotes + //iterate through string + //if character is a quote + //if next is a quote erase this one jump past next + //else erase this one + //else next + + for (std::string::iterator i = s.begin(); i != s.end();) + { + if (*i == '"') + { + if ( (i+1) != s.end() && *(i+1) == '"' ) + { + s.erase(i); + ++i; + } + else + { + s.erase(i); + } + } + else + { + ++i; + } + } + return s; + +} + +// ---------------------------------------------------------------------- + +std::string DataTableWriterNamespace::getTableNameFromTabFile( const char* fileName ) +{ + std::string ret(fileName); + + ret.erase(ret.find_last_of('.')); + + // support both types of naming, regardless of what platform you are on. + size_t i = ret.find_last_of("\\/"); + + if (i != std::string::npos) + ret.erase(0, i+1); + + return ret; +} + + +// ---------------------------------------------------------------------- + +DataTableWriter::DataTableWriter() +{ +} + +// ---------------------------------------------------------------------- + +DataTableWriter::~DataTableWriter() +{ + while(!m_tables.empty()) + { + NamedDataTable * ndt = m_tables.front(); + m_tables.pop_front(); + delete ndt; + } +} + +// ---------------------------------------------------------------------- + +bool DataTableWriter::isXmlFile(const char * filename) +{ + NOT_NULL(filename); + + const char * xmlExtString = ".XML"; + const int extLength = sizeof(xmlExtString)/sizeof(xmlExtString[0]); + + int fileLength = strlen(filename); + + if(fileLength <= extLength) + return false; + + // Return false if the extension does not match xmlExtString + return !_strnicmp(filename + fileLength - extLength, xmlExtString, extLength); +} + +// ---------------------------------------------------------------------- + +void DataTableWriter::loadFromSpreadsheet(const char * filename) +{ + NOT_NULL(filename); + + if(!isXmlFile(filename)) + // Original file format + _loadFromSpreadsheetTab(filename); + else + // XML file format + _loadFromSpreadsheetXml(filename); +} + +// ---------------------------------------------------------------------- + +void DataTableWriter::_loadWorksheet(NamedDataTable * ndt, XmlTreeNode nodeWorksheet) +{ + // Table + XmlTreeNode nodeTable = nodeWorksheet.getChildNodeNamed("Table"); + FATAL(nodeTable.isNull(), ("Worksheet %s: Table node not found, worksheet has no data", ndt->getName().c_str())); + + XmlTreeNode nodeRow = nodeTable.getChildNodeNamed("Row"); + FATAL(nodeRow.isNull(), ("Worksheet %s: Missing row node, worksheet has no data", ndt->getName().c_str())); + + XmlTreeNode nodeCell = nodeRow.getChildNodeNamed("Cell"); + FATAL(nodeCell.isNull(), ("Worksheet %s: Missing cell node, worksheet has no data", ndt->getName().c_str())); + + // Read the column names + while(!nodeCell.isNull()) + { + XmlTreeNode nodeText = nodeCell.getTextChildNodeNamed("Data"); + FATAL(nodeText.isNull(), ("Worksheet %s: Column #%d missing a name", ndt->getName().c_str(), ndt->m_columns.size()+1)); + + std::string s = nodeText.getTextValue(); + ndt->m_columns.push_back(s); + nodeCell = nodeCell.getNextSiblingElementNode(); + } + + nodeRow = nodeRow.getNextSiblingElementNode(); + nodeCell = nodeRow.getChildNodeNamed("Cell"); + + // Read the column types + while(!nodeCell.isNull()) + { + XmlTreeNode nodeText = nodeCell.getTextChildNodeNamed("Data"); + FATAL(nodeText.isNull(), ("Worksheet %s: Column #%d missing a type", ndt->getName().c_str(), ndt->m_types.size()+1)); + + std::string s = nodeText.getTextValue(); + ndt->m_types.push_back(new DataTableColumnType(unquotify(s))); + nodeCell = nodeCell.getNextSiblingElementNode(); + } + + FATAL(ndt->m_columns.size() != ndt->m_types.size(), ("Worksheet %s: Number of columns %d does not match number of types %d", + ndt->getName().c_str(), ndt->m_columns.size(), ndt->m_types.size())); + + nodeRow = nodeRow.getNextSiblingElementNode(); + + FATAL(nodeRow.isNull(), ("Worksheet %s: No data rows found.", ndt->getName().c_str())); + + // Read the row data + while(!nodeRow.isNull()) + { + NamedDataTable::DataTableRow * newRow = new NamedDataTable::DataTableRow; + int count = 0; + + nodeCell = nodeRow.getChildNodeNamed("Cell"); + while(!nodeCell.isNull()) + { + const char * c; + XmlTreeNode nodeText = nodeCell.getTextChildNodeNamed("Data"); + + // If the cell has no data node with text, use an empty string + if(nodeText.isNull()) + c = ""; + else + c = nodeText.getTextValue(); + + int nIndex = 0; + + // Get the cell's index attribute if provide + nodeCell.getElementAttributeAsInt("Index", nIndex, true); + + FATAL(nIndex && nIndex <= count, ("Worksheet %s: Row %d has an out of order index number. Expected %d, got %d", + ndt->getName().c_str(), ndt->m_rows.size()+1, count+1, nIndex)); + + int colSize = ndt->m_columns.size(); + FATAL(nIndex > colSize || count >= colSize, ("Worksheet %s: Too many columns in row %d. Expected %d, got %d", + ndt->getName().c_str(), ndt->m_rows.size()+1, colSize, nIndex > colSize ? nIndex : count+1)); + + // Skip cells up to index attribute value + for(; count< (nIndex - 1); ++count) + newRow->push_back(_getNewCell(ndt->getDataTypeForColumn(count), "")); + + newRow->push_back(_getNewCell(ndt->getDataTypeForColumn(count), c)); + + nodeCell = nodeCell.getNextSiblingElementNode(); + count++; + } + + // Fill in the empty columns + int oldSize = newRow->size(); + int colSize = ndt->m_columns.size(); + for (int i = 0; i < colSize - oldSize; ++i) + newRow->push_back(_getNewCell(ndt->getDataTypeForColumn(i+oldSize), "")); + + ndt->m_rows.push_back(newRow); + + // Advance to next row + nodeRow = nodeRow.getNextSiblingElementNode(); + } +} + +// ---------------------------------------------------------------------- + +void DataTableWriter::_loadFromSpreadsheetXml(const char * filename) +{ + NOT_NULL(filename); + + ConstCharCrcString cc(filename); + + // Open the xml file + XmlTreeDocument const *const xmlTreeDocument = XmlTreeDocumentList::fetch(cc); + + // Get the root node + XmlTreeNode rootNode = xmlTreeDocument->getRootTreeNode(); + + // Workbook + FATAL(rootNode.isNull(), ("%s is not a valid XML file. Root node not found.", filename)); + + if (_stricmp(rootNode.getName(), "Workbook") == 0) + { + // Excel Worksheet + XmlTreeNode node = rootNode.getChildNodeNamed("Worksheet"); + FATAL(node.isNull(), ("%s is not a valid Excel XML file. Worksheet node not found.", filename)); + + while(!node.isNull()) + { + std::string strName; + node.getElementAttributeAsString("Name", strName); + + FATAL(!_stricmp(strName.c_str(), "Sheet1"), ("You need to rename the worksheet %s", strName.c_str())); + FATAL(!_stricmp(strName.c_str(), "Sheet2"), ("You need to rename the worksheet %s", strName.c_str())); + FATAL(!_stricmp(strName.c_str(), "Sheet3"), ("You need to rename the worksheet %s", strName.c_str())); + + // Skip worksheets with underscore as first character + if(strName[0] != '_') + { + m_tables.push_back(new NamedDataTable()); + NamedDataTable* ndt = m_tables.back(); + ndt->setName(strName); + _loadWorksheet(ndt, node); + } + + node = node.getNextSiblingElementNode(); + } + } + else // assume this is a dataset + { + // look for a schema node + XmlTreeNode schemaNode = rootNode.getChildNodeNamed("schema"); + XmlTreeNode node(0); + + if (!schemaNode.isNull()) + node = schemaNode.getChildNodeNamed("element"); + + if (!node.isNull()) + node = node.getChildNodeNamed("complexType"); + + if (!node.isNull()) + node = node.getChildNodeNamed("choice"); + + if (!node.isNull()) + node = node.getChildNodeNamed("element"); + + FATAL(node.isNull(), ("%s is not a valid DataSet file. No table definitions found.", filename)); + + std::map< std::string, NamedDataTable* > namedTables; + + while (!node.isNull()) + { + std::string strName; + node.getElementAttributeAsString("Name", strName); + + FATAL( namedTables.find(strName) != namedTables.end(), ("%s is not a valid DataSet file. Duplicate table definition found.", filename)); + + // Skip tables with underscore as first character + if(strName[0] != '_') + { + NamedDataTable* table = new NamedDataTable(); + + namedTables[strName] = table; + table->setName(strName); + + _loadDataTableSchema(table, node); + } + + node = node.getNextSiblingElementNode(); + } + + // fill in the table rows + node = schemaNode.getNextSiblingElementNode(); + + std::map< std::string, NamedDataTable* >::iterator t = namedTables.end(); + while (!node.isNull()) + { + std::string rowName = node.getName(); + + if (t == namedTables.end() || t->first != rowName) + t = namedTables.find( rowName ); + + if (t != namedTables.end() ) + _loadDataTableRow( t->second, node ); + + node = node.getNextSiblingElementNode(); + } + + // fill in the table of tables + for (t = namedTables.begin(); t != namedTables.end(); ++t) + { + m_tables.push_back(t->second); + } + + } + + + // Clean up + xmlTreeDocument->release(); +} + + +// ---------------------------------------------------------------------- + +void DataTableWriter::_loadDataTableSchema(NamedDataTable * ndt, XmlTreeNode parentNode) +{ + XmlTreeNode node(0); + + if (!parentNode.isNull()) + node = parentNode.getChildNodeNamed("complexType"); + + if (!node.isNull()) + node = node.getChildNodeNamed("sequence"); + + if (!node.isNull()) + node = node.getChildNodeNamed("element"); + + // read the column names and typespec properties + while (!node.isNull()) + { + std::string name; + std::string type; + + node.getElementAttributeAsString("name", name); + node.getElementAttributeAsString("typespec", type); + + ndt->m_columns.push_back(name); + ndt->m_types.push_back(new DataTableColumnType( type )); + + node = node.getNextSiblingElementNode(); + } +} + +// ---------------------------------------------------------------------- + +void DataTableWriter::_loadDataTableRow(NamedDataTable * ndt, XmlTreeNode rowNode) +{ + NamedDataTable::DataTableRow * newRow = new NamedDataTable::DataTableRow; + + int index = 0; + + const char * c = 0; + + for (index = 0; index < ndt->getNumColumns(); ++index) + { + XmlTreeNode cellNode = rowNode.getChildElementNodeNamed( ndt->getColumnName(index).c_str() ); + + c = ""; + + if (!cellNode.isNull()) + { + XmlTreeNode textNode = cellNode.getFirstChildTextNode(); + + if (!textNode.isNull()) + c = textNode.getTextValue(); + } + + newRow->push_back( _getNewCell(ndt->getDataTypeForColumn(index), c )); + } + + ndt->m_rows.push_back(newRow); +} + + +// ---------------------------------------------------------------------- + +void DataTableWriter::_loadFromSpreadsheetTab(const char * filename) +{ + NamedDataTable * ndt; + + NOT_NULL(filename); + + StdioFile inputFile(filename,"r"); + FATAL(!inputFile.isOpen(), ("Could not open %s.", filename)); + + int fileLength = inputFile.length(); + int bufferLength = fileLength + 1; + char* buffer = new char[bufferLength]; + memset(buffer, 0, bufferLength); + NOT_NULL(buffer); + + int bytes_read = inputFile.read(buffer, fileLength); + FATAL(!bytes_read, ("Didn't read in any bytes when loading %s.", filename)); + + FATAL(buffer[bytes_read-1] != '\n', ("No newline at end of file when loading %s.", filename)); + + // Terminate the buffer because apparently fread can put garbage in the buffer + // past the end of the file data + buffer[bytes_read] = 0; + + const char* newLine = strchr(buffer, '\n'); + FATAL(!newLine, ("No end of line while looking for column row when loading %s.", filename)); + + FATAL(!m_tables.empty(), ("TAB file does not support multiple tables when loading %s.", filename)); + + m_tables.push_back(new NamedDataTable()); + ndt = m_tables.back(); + ndt->setName(getTableNameFromTabFile(filename).c_str()); + + _loadColumnNames(ndt, buffer); + const char* currentPos = newLine + 1; + + newLine = strchr(currentPos, '\n'); + FATAL(!newLine, ("No end of line while looking for column row when loading %s.", filename)); + + _loadTypes(ndt, currentPos); + currentPos = newLine + 1; + + newLine = strchr(currentPos, '\n'); + + for(int count = 0; newLine; ++count) + { + _loadRow(ndt, currentPos, count); + currentPos = newLine + 1; + + newLine = strchr(currentPos, '\n'); + } + FATAL(ndt->getNumRows() < 1, ("No rows in the table when loading %s.", filename)); + + delete [] buffer; + inputFile.close(); + +} + +// ---------------------------------------------------------------------- + +bool DataTableWriter::save(const char * outputFileName, bool optional) const +{ + if (!outputFileName || strlen(outputFileName) == 0) + { + DEBUG_FATAL(true, ("OutputFileName is NULL or empty.")); + return false; + } + + if (m_tables.size() > 1) + { + DEBUG_FATAL(true, ("OutputFileName not supported on DataTableWriter with multiple tables.")); + return false; + } + + if (m_tables.size() == 0) + { + DEBUG_FATAL(true, ("DataTableWriter is empty.")); + return false; + } + + + return _writeTable( m_tables.front(), outputFileName, optional ); +} + +// ---------------------------------------------------------------------- + +void DataTableWriter::save (Iff & iff) const +{ + FATAL(m_tables.size() == 0, ("No table loaded.")); + FATAL(m_tables.size() > 1, ("Multiple tables not supported.")); + NamedDataTable * ndt = *m_tables.begin(); + + _saveTableToIff(iff, ndt); +} + +// ---------------------------------------------------------------------- + +bool DataTableWriter::_writeTable(NamedDataTable * ndt, const char * outputFile, bool optional) const +{ + Iff iff(512,true,true); + + if (!FileNameUtils::isWritable(outputFile)) + { + FATAL(!optional, ("ERROR: The output file is not available for writing: %s", outputFile)); + WARNING(true, ("ERROR: The output file is not available for writing: %s", outputFile)); + return false; + } + + _saveTableToIff(iff, ndt); + + iff.write(outputFile); + iff.close(); + return true; +} + +// ---------------------------------------------------------------------- + +void DataTableWriter::_saveTableToIff(Iff & iff, NamedDataTable * ndt) const +{ + NOT_NULL(ndt); + + _checkIntegrity(ndt); + iff.insertForm(DataTable::getDataTableIffId()); + iff.insertForm(TAG_0001); + + _saveColumns(ndt, iff); + _saveTypes(ndt, iff); + _saveRows(ndt, iff); + + iff.exitForm(TAG_0001); + iff.exitForm(); +} + +// ---------------------------------------------------------------------- + +void DataTableWriter::_loadColumnNames(NamedDataTable * ndt, const char* row) +{ + const char* currentPos = row; + const char* tab = strchr(currentPos, '\t'); + + // we want endLine to be the first occurrence of a newline or carriage return + const char* endLine = strchr(currentPos, '\n'); + const char* carriageRet = strchr(currentPos, '\r'); + endLine = (carriageRet && carriageRet == endLine - 1) ? carriageRet : endLine; + + while(tab && tab < endLine) + { + FATAL(currentPos == tab, ("Empty cell in column names")); + std::string s(currentPos, tab - currentPos); + ndt->m_columns.push_back(s); + currentPos = tab + 1; + tab = strchr(currentPos, '\t'); + } + //Read last cell in row + FATAL(endLine <= currentPos, ("Empty cell at end of col. names")); + std::string s (currentPos, endLine - currentPos); + ndt->m_columns.push_back(s); + +} + +// ---------------------------------------------------------------------- + +void DataTableWriter::_loadTypes(NamedDataTable * ndt, const char* row) +{ + const char* currentPos = row; + const char* tab = strchr(currentPos, '\t'); + + // we want endLine to be the first occurrence of a newline or carriage return + const char* endLine = strchr(currentPos, '\n'); + const char* carriageRet = strchr(currentPos, '\r'); + endLine = (carriageRet && carriageRet == endLine - 1) ? carriageRet : endLine; + + while(tab && tab < endLine) + { + FATAL(currentPos == tab, ("Empty cell in type names")); + std::string s(currentPos, tab - currentPos); + ndt->m_types.push_back(new DataTableColumnType(unquotify(s))); + currentPos = tab + 1; + tab = strchr(currentPos, '\t'); + } + //Read last cell in row + FATAL(endLine <= currentPos, ("Empty cell at end of type names")); + std::string s (currentPos, endLine - currentPos); + ndt->m_types.push_back(new DataTableColumnType(unquotify(s))); + FATAL(ndt->m_types.size() != ndt->m_columns.size(), ("Types != num columns")); + +} + +// ---------------------------------------------------------------------- + +DataTableCell *DataTableWriter::_getNewCell(DataTableColumnType const &columnType, char const *buf) +{ + std::string value(buf); + if (!columnType.mangleValue(unquotify(value))) + { + FATAL(true, ("tried to create a cell with an invalid value [%s] for its type [%s])", value.c_str(), columnType.getTypeSpecString().c_str())); + } + + switch (columnType.getBasicType()) + { + case DataTableColumnType::DT_Int: + return new DataTableCell(static_cast(strtol(value.c_str(), NULL, 0))); + break; + case DataTableColumnType::DT_Float: + return new DataTableCell(static_cast(atof(value.c_str()))); + break; + case DataTableColumnType::DT_String: + case DataTableColumnType::DT_Comment: + return new DataTableCell(value.c_str()); + break; + default: + FATAL(true, ("Type with unknown basic type specified in the types row.")); + break; + } + return 0; +} + +// ---------------------------------------------------------------------- + +void DataTableWriter::_loadRow(NamedDataTable * ndt, const char* row, int index) +{ +#ifdef _DEBUG + s_debugRow = index + 3; +#endif + + const char* currentPos = row; + const char* tab = strchr(currentPos, '\t'); + + // we want endLine to be the first occurrence of a newline or carriage return + const char* endLine = strchr(currentPos, '\n'); + const char* carriageRet = strchr(currentPos, '\r'); + endLine = (carriageRet && carriageRet == endLine - 1) ? carriageRet : endLine; + + NamedDataTable::DataTableRow * newRow = new NamedDataTable::DataTableRow; + + char buf[16384]; + int count = 0; + for(count = 0; tab && tab < endLine; ++count) + { + FATAL(tab < currentPos, ("Causality has been broken")); + if (tab == currentPos) + { + //empty cell + buf[0] = '\0'; + } + else + { + FATAL(tab - currentPos > isizeof(buf) - 1, ("Cells can only be less than %d bytes", sizeof(buf) - 1)); + strncpy(buf, currentPos, tab - currentPos); + buf[tab - currentPos] = '\0'; + } + + newRow->push_back(_getNewCell(ndt->getDataTypeForColumn(count), buf)); + + currentPos = tab + 1; + tab = strchr(currentPos, '\t'); + } + + //Still need the last cell + { + FATAL(endLine < currentPos, ("Empty cell at end of row %d", index)); + if (endLine == currentPos) + { + //empty cell + buf[0] = '\0'; + } + else + { + FATAL(endLine - currentPos > isizeof(buf) - 1, ("Cells can only be less than %d bytes", sizeof(buf) - 1)); + strncpy(buf, currentPos, endLine - currentPos); + buf[endLine - currentPos] = '\0'; + } + + newRow->push_back(_getNewCell(ndt->getDataTypeForColumn(count), buf)); + } + + //Fill in empty rows: + int oldSize = static_cast(newRow->size()); + buf[0] = '\0'; + for (int i = 0; i < static_cast(ndt->m_columns.size()) - oldSize; ++i) + { + newRow->push_back(_getNewCell(ndt->getDataTypeForColumn(i+oldSize), buf)); + } + ndt->m_rows.push_back(newRow); +} + +// ---------------------------------------------------------------------- + +void DataTableWriter::_saveColumns(NamedDataTable * ndt, Iff& iff) const +{ + iff.insertChunk(TAG(C,O,L,S)); + NamedDataTable::DataTableColumnTypeVector::iterator j; + int numCols = 0; + for (j = ndt->m_types.begin(); j!=ndt->m_types.end(); ++j) + { + if ((*j)->getType() != DataTableColumnType::DT_Comment) + ++numCols; + } + iff.insertChunkData(&numCols, sizeof(int)); + std::vector::iterator i = ndt->m_columns.begin(); + j = ndt->m_types.begin(); + for (; i!= ndt->m_columns.end(); ++i, ++j) + { + if ((*j)->getType() != DataTableColumnType::DT_Comment) + iff.insertChunkString(i->c_str()); + } + iff.exitChunk(TAG(C,O,L,S)); +} + +// ---------------------------------------------------------------------- + +void DataTableWriter::_saveTypes(NamedDataTable * ndt, Iff& iff) const +{ + iff.insertChunk(TAG(T,Y,P,E)); + NamedDataTable::DataTableColumnTypeVector::iterator i = ndt->m_types.begin(); + for (; i!= ndt->m_types.end(); ++i) + { + if ((*i)->getType() != DataTableColumnType::DT_Comment) + iff.insertChunkString((*i)->getTypeSpecString().c_str()); + } + + iff.exitChunk(TAG(T,Y,P,E)); + +} + +// ---------------------------------------------------------------------- + +void DataTableWriter::_saveRows(NamedDataTable * ndt, Iff& iff) const +{ + iff.insertChunk(TAG(R,O,W,S)); + + int numRows = static_cast(ndt->m_rows.size()); + iff.insertChunkData(&numRows, sizeof(int)); + std::vector::iterator i = ndt->m_rows.begin(); + for (; i!= ndt->m_rows.end(); ++i) + { + std::vector::iterator j = (*i)->begin(); + int count = 0; + for (; j != (*i)->end(); ++j) + { + switch (ndt->m_types[count]->getBasicType()) + { + case DataTableColumnType::DT_Int: + { + const DataTableCell * cell = *j; + NOT_NULL(cell); + int tmp = cell->getIntValue(); + iff.insertChunkData(&tmp, sizeof(int)); + break; + } + case DataTableColumnType::DT_Float: + { + const DataTableCell * cell = *j; + NOT_NULL(cell); + float tmp = cell->getFloatValue(); + iff.insertChunkData(&tmp, sizeof(float)); + break; + } + case DataTableColumnType::DT_String: + { + const DataTableCell * cell = *j; + NOT_NULL(cell); + iff.insertChunkString(cell->getStringValue()); + break; + } + case DataTableColumnType::DT_Comment: + { + } + break; + default: + FATAL(true, ("bad case")); + break; + } + ++count; + } + //should we enter a seperator here between rows? + } + + iff.exitChunk(TAG(R,O,W,S)); +} + +// ---------------------------------------------------------------------- + +bool DataTableWriter::_checkIntegrity(const NamedDataTable * ndt) const +{ + FATAL(ndt->m_columns.empty(), ("empty columns")); + FATAL(ndt->m_columns.size() != ndt->m_types.size(), ("size mismatch")); + FATAL(ndt->m_rows.empty(), ("empty rows")); + FATAL(ndt->m_columns.size() != ndt->m_rows[0]->size(), ("size mismatch %d %d", ndt->m_columns.size(), ndt->m_rows[0]->size())); + + // Check unique constraints + int column = 0; + for (NamedDataTable::DataTableColumnTypeVector::const_iterator i = ndt->m_types.begin(); i != ndt->m_types.end(); ++i) + { + if ((*i)->areUniqueCellsRequired()) + { + for (std::vector::const_iterator j = ndt->m_rows.begin(); j != ndt->m_rows.end(); ++j) + { + std::vector::const_iterator k = j; + ++k; + for ( ; k != ndt->m_rows.end(); ++k) + { + switch ((*i)->getBasicType()) + { + case DataTableColumnType::DT_Int: + FATAL( + (**j)[column]->getIntValue() == (**k)[column]->getIntValue(), + ( + "unique constraint not satisfied for column %s, value %d", + ndt->m_columns[column].c_str(), + (**j)[column]->getIntValue() + ) + ); + break; + case DataTableColumnType::DT_Float: + FATAL( + (**j)[column]->getFloatValue() == (**k)[column]->getFloatValue(), + ( + "unique constraint not satisfied for column %s, value %g", + ndt->m_columns[column].c_str(), + static_cast((**j)[column]->getFloatValue()) + ) + ); + break; + case DataTableColumnType::DT_String: + FATAL( + strcmp((**j)[column]->getStringValue(), (**k)[column]->getStringValue())==0, + ( + "unique constraint not satisfied for column %s, value %s", + ndt->m_columns[column].c_str(), + (**j)[column]->getStringValue() + ) + ); + break; + default: + break; + } + } + } + } + ++column; + } + + return true; +} + +// ---------------------------------------------------------------------- + +void DataTableWriter::setOutputPath(const char * path) +{ + m_path = path; +} + +// ---------------------------------------------------------------------- + +void DataTableWriter::getTableNames(std::vector & v) const +{ + NamedDataTableList::const_iterator t = m_tables.begin(); + + for (; t != m_tables.end(); ++t) + { + NamedDataTable const * const ndt = *t; + v.push_back(ndt->getName()); + } +} + +// ---------------------------------------------------------------------- + +bool DataTableWriter::save (bool optional) const +{ + bool retval = true; + + NamedDataTableList::const_iterator i = m_tables.begin(); + for(; i != m_tables.end(); ++i) + { + std::string outputFile; + getTableOutputFileName((*i)->getName().c_str(), outputFile); + retval = _writeTable(*i, outputFile.c_str(), optional) && retval; + } + + return retval; + +} + +// ---------------------------------------------------------------------- + +void DataTableWriter::getTableOutputFileName( const char* tableName, std::string& fileName ) const +{ + if (tableName != 0) + { + fileName = m_path; + fileName.append(tableName); + fileName.append(".iff"); + } +} + +// ---------------------------------------------------------------------- + +bool DataTableWriter::saveTable( const char* tableName, const char* fileName, bool optional ) const +{ + bool ret = true; + + NamedDataTableList::const_iterator i; + for (i = m_tables.begin(); i != m_tables.end(); ++i) + { + if (strcmp((*i)->getName().c_str(), tableName) == 0) + break; + } + + if (i != m_tables.end()) + { + if (!fileName || strlen(fileName) == 0) + { + std::string outputFile; + getTableOutputFileName((*i)->getName().c_str(), outputFile); + + ret = _writeTable(*i, outputFile.c_str(), optional); + } + else + ret = _writeTable(*i, fileName, optional); + } + + return ret; +} + +// ====================================================================== + diff --git a/engine/shared/library/sharedUtility/src/shared/DataTableWriter.h b/engine/shared/library/sharedUtility/src/shared/DataTableWriter.h new file mode 100644 index 00000000..bfe3807f --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/DataTableWriter.h @@ -0,0 +1,77 @@ +// ====================================================================== +// +// DataTableWriter.h +// +// copyright 2002 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_DataTableWriter_H +#define INCLUDED_DataTableWriter_H + +#include "DataTableColumnType.h" +#include +#include +#include + +class Iff; +class XmlTreeNode; + +//---------------------------------------------------------------------- + +class DataTableWriter +{ +public: + + DataTableWriter(); + ~DataTableWriter(); + + void setOutputPath (const char * path); + void loadFromSpreadsheet (const char * filename); + + bool save (const char * outputFileName, bool optional = false) const; + bool save (bool optional = false) const; + void save (Iff & iff) const; + + bool saveTable( const char* tableName, const char* fileName = 0, bool optional = false ) const; + + void getTableNames(std::vector & v) const; + void getTableOutputFileName( const char* tableName, std::string& fileName ) const; + + static bool isXmlFile(const char * filename); + +private: + + class NamedDataTable; + + typedef std::list NamedDataTableList; + + bool _checkIntegrity(const NamedDataTable * ndt) const; + + void _loadFromSpreadsheetTab (const char * filename); + void _loadFromSpreadsheetXml (const char * filename); + void _loadWorksheet (NamedDataTable * ndt, XmlTreeNode nodeWorksheet); + + void _loadDataTableSchema(NamedDataTable * ndt, XmlTreeNode parentNode); + void _loadDataTableRow(NamedDataTable * ndt, XmlTreeNode rowNode); + + void _loadColumnNames(NamedDataTable * ndt, const char* row); + void _loadTypes(NamedDataTable * ndt, const char* row); + void _loadRow(NamedDataTable * ndt, const char* row, int index); + + void _saveColumns(NamedDataTable * ndt, Iff& iff) const; + void _saveTypes(NamedDataTable * ndt, Iff& iff) const; + void _saveRows(NamedDataTable * ndt, Iff& iff) const; + + bool _writeTable(NamedDataTable * ndt, const char * outputFile, bool optional) const; + void _saveTableToIff(Iff & iff, NamedDataTable * ndt) const; + + static DataTableCell *_getNewCell(DataTableColumnType const &columnType, char const *contents); + + NamedDataTableList m_tables; + std::string m_path; +}; + +//---------------------------------------------------------------------- + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/FileName.cpp b/engine/shared/library/sharedUtility/src/shared/FileName.cpp new file mode 100644 index 00000000..aa9fcd90 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/FileName.cpp @@ -0,0 +1,289 @@ +// +// FileName.h +// asommers 5-26-99 +// +// copyright 1999, bootprint entertainment +// + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/FileName.h" + +#include + +//------------------------------------------------------------------- + +FileName::Table FileName::pathTable [P_COUNT] = +{ + {"", "" }, // P_none + {"animationmap/", "map"}, // P_animationMap + {"camera/", "iff"}, // P_camera + {"inputmap/", "iff"}, // P_inputmap + {"appearance/", "" }, // P_appearance + {"animation", "" }, // P_animation + {"music/", "mus"}, // P_music + {"object/", "iff"}, // P_object + {"sample/", "sam"}, // P_sound + {"scene/", "scn"}, // P_scene + {"script/", "iff"}, // P_script + {"shader/", "sht"}, // P_shader + {"effect/", "eft"}, // P_effect + {"terrain/", "" }, // P_terrain + {"texture/", "dds"} // P_texture +}; + +//------------------------------------------------------------------- + +FileName::FileName (const char* const newName) : + fullName (0) +{ + set (newName); +} + +FileName::FileName (FileName::Path path, const char* filename, const char* ext) +: fullName (0) +{ + //-- verify args + DEBUG_FATAL (path < P_none || path >= P_COUNT, ("FileName::FileName - bad path!")); + DEBUG_FATAL (!filename, ("FileName::FileName - filename is 0")); + + //-- make sure we have an extention + if (!ext) + ext = pathTable [path].ext; + + // see if the filename already begins with the path + const char *prePath = pathTable [path].path; + if (prePath != NULL && *prePath != '\0') + { + if (strncmp(filename, prePath, strlen(prePath)) == 0) + prePath = ""; + } + + // see if the filename already ends in the extension + if (ext != NULL && *ext != '\0') + { + int extLen = strlen(ext); + int filenameLen = strlen(filename); + if (filenameLen > extLen + 1) + { + for (--extLen, --filenameLen; extLen >= 0; --extLen, --filenameLen) + { + if (ext[extLen] != filename[filenameLen]) + break; + } + if (extLen == -1 && filename[filenameLen] == '.') + ext = ""; + } + } + + fullName = new char [strlen(prePath) + strlen(filename) + 1 + strlen(ext) + 1]; + sprintf(fullName, "%s%s%s%s", prePath, filename, strlen(ext) ? "." : "", ext); +} + +//------------------------------------------------------------------- + +FileName::FileName (const char* path, const char* filename, const char* ext) : + fullName (0) +{ + NOT_NULL (path); + NOT_NULL (filename); + + fullName = new char [strlen(path) + 1 + strlen(filename) + 1 + (ext ? strlen(ext) : 0) + 1]; + sprintf(fullName, "%s%s%s%s%s", path, strlen (path) ? "/" : "", filename, (ext && strlen (ext)) ? "." : "", ext ? ext : ""); +} + +//------------------------------------------------------------------- + +FileName::~FileName (void) +{ + delete [] fullName; + fullName = 0; +} + +//------------------------------------------------------------------- + +void FileName::set (const char* const newName) +{ + DEBUG_FATAL (!newName, ("FileName::set - newName is 0")); + + if (fullName) + { + delete [] fullName; + fullName = 0; + } + + if (newName) + fullName = DuplicateString (newName); +} + +//------------------------------------------------------------------- + +void FileName::stripPathAndExt (void) +{ + stripPathAndExt (fullName, istrlen (fullName)); +} + +//------------------------------------------------------------------- + +void FileName::stripPath (void) +{ + stripPath (fullName, istrlen (fullName)); +} + +//------------------------------------------------------------------- + +void FileName::stripSpecificPathAndExt (Path path) +{ + stripSpecificPathAndExt (path, fullName, istrlen (fullName)); +} + +//------------------------------------------------------------------- + +void FileName::stripPathAndExt (char* nameBuffer, int nameBufferLength) +{ + NOT_NULL (nameBuffer); + + //-- warning: this function modifies the buffer of the argument + char buffer [1000]; + + int len = istrlen (nameBuffer); + char* start = nameBuffer; + char* end = nameBuffer + len; + char* curr = end; + + //-- start from end of string and search backward for '\' or '/' + while (curr != start && !(*curr == '\\' || *curr == '/')) + curr--; + + //-- start from curr and search to the end for '.' + if (*curr == '\\' || *curr == '/') + curr++; + + start = curr; + while (curr < end && *curr != '.') + curr++; + + //-- copy string + end = curr; + curr = start; + len = end - start; + int i; + for (i = 0; i < len && i < nameBufferLength; i++) + buffer [i] = *curr++; + + buffer [i] = 0; + + strncpy (nameBuffer, buffer, nameBufferLength); +} + +//------------------------------------------------------------------- + +void FileName::stripPath (char* nameBuffer, int nameBufferLength) +{ + NOT_NULL (nameBuffer); + + //-- warning: this function modifies the buffer of the argument + char buffer [1000]; + + int len = istrlen (nameBuffer); + char* start = nameBuffer; + char* end = nameBuffer + len; + char* curr = end; + + //-- start from end of string and search backward for '\' or '/' + while (curr != start && !(*curr == '\\' || *curr == '/')) + curr--; + + if (curr != start && (*curr == '\\' || *curr == '/')) + curr++; + + //-- copy string + start = curr; + len = end - start; + int i; + for (i = 0; i < len && i < nameBufferLength; i++) + buffer [i] = *curr++; + + if (i >= nameBufferLength) + i--; + + DEBUG_FATAL (i < 0, ("i < 0")); + + buffer [i] = 0; + + strncpy (nameBuffer, buffer, nameBufferLength); + nameBuffer [nameBufferLength - 1] = 0; +} + +//------------------------------------------------------------------- + +/* This function strips the path and ext from the nameBuffer that correspond to the given path. + * It will do nothing if the path and ext do not match the one given to it in the path parameter. + */ +void FileName::stripSpecificPathAndExt (Path path, char* nameBuffer, int nameBufferLength) +{ + //-- warning: this function modifies the buffer of the argument + NOT_NULL(nameBuffer); + + int len = istrlen(nameBuffer); + char* start = nameBuffer; + char* end = nameBuffer + len; + char buffer[1000]; + + //string compare nameBuffer to path.path for strlen(path.path)-1 to make sure it is correct. + //-1 because we don't care about the slash (could be back or forward) + //@todo these compares could be debug only. + if (strncmp(nameBuffer, pathTable[path].path, strlen(pathTable[path].path) - 1) != 0) + { + DEBUG_REPORT_LOG(true, ("Error in stripSpecificPathAndExt...nameBuffer does not match path\n")); + return; + } + + //correct path, now check extension. + //first make sure this path has an extension + if (strlen(pathTable[path].ext) > 0) + { + end = strrchr(nameBuffer, '.'); + //make sure to compare strings starting just after the dot + if (!end || strncmp(end + 1, pathTable[path].ext, strlen(pathTable[path].ext)) != 0) + { + DEBUG_REPORT_LOG(true, ("Error in stripSpecificPathAndExt...nameBuffer does not match path\n")); + return; + } + *end = '\0'; //End points to '.' Strip the extension + } + else //We aren't supposed to have an ext. Make sure we don't + { + char* tmp = strrchr(nameBuffer, '.'); + if (tmp) + { + DEBUG_REPORT_LOG(true, ("Error in stripSpecificPathAndExt...nameBuffer does not match path\n")); + return; + } + } + + + //correct extension. End is set to the correct place...just before the dot. + //or in the case of no extension, the last character in the string. + + //advance start to after path. Make sure to skip slashes. + start += strlen(pathTable[path].path); + + while (*start == '\\' || *start == '/') + start++; + + //copy from start to end (which is \0) into tmp buffer + strncpy (buffer, start, 1000); + //move temp buffer into return. + strncpy (nameBuffer, buffer, nameBufferLength); +} + +//------------------------------------------------------------------- + +#if 0 + + DEBUG_REPORT_LOG_PRINT (true, ("%s\n", FileName (FileName::P_none, "test"))); + DEBUG_REPORT_LOG_PRINT (true, ("%s\n", FileName (FileName::P_none, "test", "iff"))); + DEBUG_REPORT_LOG_PRINT (true, ("%s\n", FileName (FileName::P_sound, "test"))); + DEBUG_REPORT_LOG_PRINT (true, ("%s\n", FileName (FileName::P_sound, "test", "iff"))); + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/FileName.h b/engine/shared/library/sharedUtility/src/shared/FileName.h new file mode 100644 index 00000000..da981c2a --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/FileName.h @@ -0,0 +1,99 @@ +// ====================================================================== +// +// FileName.h +// asommers 5-26-99 +// +// copyright 1999, bootprint entertainment +// +// ====================================================================== + +#ifndef INCLUDED_FileName_H +#define INCLUDED_FileName_H + +// ====================================================================== + +class FileName +{ +public: + + enum Path + { + P_none, + + P_animationMap, + P_camera, + P_inputmap, + P_appearance, + P_animation, + P_music, + P_object, + P_sample, + P_scene, + P_script, + P_shader, + P_shaderEffect, + P_terrain, + P_texture, + + P_COUNT + }; + +private: + + struct Table + { + const char* path; + const char* ext; + }; + +private: + + static Table pathTable [P_COUNT]; + +private: + + char* fullName; + +private: + + FileName (); + FileName (const FileName&); + FileName& operator= (const FileName&); + +public: + + explicit FileName (const char* const newName); + FileName (const char* path, const char* filename, const char* ext=0); + FileName (Path path, const char* filename, const char* ext=0); + ~FileName (); + + operator const char* () const; //lint !e1930 //-- conversion operator found + const char* getString () const; + + void set (const char* const newName); + void stripPathAndExt (); + void stripPath (); + void stripSpecificPathAndExt (Path path); + + static void stripPathAndExt (char* nameBuffer, int nameBufferLength); + static void stripPath (char* nameBuffer, int nameBufferLength); + static void stripSpecificPathAndExt (Path path, char* nameBuffer, int nameBufferLength); +}; + +//------------------------------------------------------------------- + +inline FileName::operator const char* () const +{ + return fullName; +} + +//------------------------------------------------------------------- + +inline const char* FileName::getString () const +{ + return fullName; +} + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/FirstSharedUtility.h b/engine/shared/library/sharedUtility/src/shared/FirstSharedUtility.h new file mode 100644 index 00000000..eaac791b --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/FirstSharedUtility.h @@ -0,0 +1,19 @@ +// ====================================================================== +// +// FirstUtility.h +// copyright (c) 2001 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_FirstUtility_H +#define INCLUDED_FirstUtility_H + +// ====================================================================== + +#include "sharedDebug/FirstSharedDebug.h" +#include "sharedFoundation/FirstSharedFoundation.h" + +// ====================================================================== + +#endif + diff --git a/engine/shared/library/sharedUtility/src/shared/HttpGetEncoder.cpp b/engine/shared/library/sharedUtility/src/shared/HttpGetEncoder.cpp new file mode 100644 index 00000000..1fefcce9 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/HttpGetEncoder.cpp @@ -0,0 +1,71 @@ +//====================================================================== +// +// HttpGetEncoder.cpp +// copyright (c) 2006 Sony Online Entertainment +// +//====================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "HttpGetEncoder.h" +//====================================================================== + +namespace HttpGetEncoderNamespace +{ + // note: This is a pretty aggressive encoder. A few more characters + // (such as parens) could be added, however extra encoding is always legal. + std::string encodeString(const std::string & toEncode) + { + char buf[3]; + std::string output; + for(unsigned int i = 0; i < toEncode.length(); ++i) + { + // check to see if the char is valid. + char current = toEncode[i]; + + // if it is, append it. + if((current >= 'a' && current <= 'z') || + (current >='A' && current <= 'Z') || + (current >='0' && current <= '9') || + (current == '-')) + { + output = output + current; + } + + // if it is a space, add a + sign. + else if(current == ' ') + { + output = output + "+"; + } + // if not, append the ascii code. + else + { + output = output + "%"; + snprintf(buf, 3, "%02x", current); + output = output + buf; + } + } + + return output; + } +} + +std::string HttpGetEncoder::getUrl(const std::string & urlBase, const GetParams & params) +{ + std::string outUrl = urlBase; + std::string paramList; + for(GetParams::const_iterator it = params.begin(); it != params.end(); ++it) + { + if(it->first != "" && it->second != "") + paramList = paramList + HttpGetEncoderNamespace::encodeString(it->first) + "=" + + HttpGetEncoderNamespace::encodeString(it->second) + "&"; + } + // trim the trailing & + if(paramList.length() > 0) + { + paramList = paramList.substr(0, paramList.length() - 1); + // if we still have data, append it. + if( paramList.length() > 0) + outUrl = outUrl + "?" + paramList; + } + return outUrl; +} diff --git a/engine/shared/library/sharedUtility/src/shared/HttpGetEncoder.h b/engine/shared/library/sharedUtility/src/shared/HttpGetEncoder.h new file mode 100644 index 00000000..908fc7b0 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/HttpGetEncoder.h @@ -0,0 +1,25 @@ +//=================================================================== +// +// HttpGetEncoder.h +// +// copyright 2006, Sony Online Entertainment +// +//=================================================================== + +#ifndef INCLUDED_HttpGetEncoder_H +#define INCLUDED_HttpGetEncoder_H + +#include +#include + +class HttpGetEncoder +{ +public: + typedef std::map GetParams; + static std::string getUrl( const std::string & UrlBase, const GetParams & params); + +private: + HttpGetEncoder(); +}; + +#endif // INCLUDED_HttpGetEncoder_H diff --git a/engine/shared/library/sharedUtility/src/shared/IndexedCache.cpp b/engine/shared/library/sharedUtility/src/shared/IndexedCache.cpp new file mode 100644 index 00000000..03a4141c --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/IndexedCache.cpp @@ -0,0 +1,265 @@ +// ====================================================================== +// +// IndexedCache.cpp +// copyright (c) 2001 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/IndexedCache.h" + +#include "Archive/Archive.h" +#include "Archive/ByteStream.h" +#include "fileInterface/StdioFile.h" + + +IndexedCache::IndexedCache(const std::string &i_filename, int i_length, int i_version) +: filename(i_filename), length(i_length), version(i_version) +{ + lockExclusive(filename); + file = new StdioFile(filename.c_str(), "r+b"); + if (!file->isOpen()) + { + delete file; + file = new StdioFile(filename.c_str(), "w+b"); + if (!file->isOpen()) + { + delete file; + file = 0; + } + } + if (file) + { + if (file->length() == 0) + { + // Write the header out + initializeFile(i_version); + } + else + { + file->seek(AbstractFile::SeekBegin, 0); + + Header header; + file->read(&header, sizeof(header)); + if (header.elements != i_length || header.version != i_version) + { + initializeFile(i_version); + } + } + } + else + { + length = 0; + } + unlockExclusive(filename); +} + +IndexedCache::IndexedCache(const std::string &i_filename) +: filename(i_filename), length(0), version(0) +{ + file = new StdioFile(filename.c_str(), "r+b"); + if (file->length() > 0) + { + file->seek(AbstractFile::SeekBegin, 0); + + Header header; + file->read(&header, sizeof(header)); + length = header.elements; + version = header.version; + } +} + +IndexedCache::~IndexedCache() +{ + delete file; + file = 0; +} + +void IndexedCache::initializeFile(int i_version) +{ + file->seek(AbstractFile::SeekBegin, 0); + + Header header; + header.elements = length; + header.formatVersion = 1; + header.version = i_version; + file->write(sizeof(header), &header); + + // Write out a bunch of zero entries + int toWrite = length; + const int COUNT = 8192; + Entry * entries = new Entry[COUNT]; + int x; + for (x=0; x 0) + { + file->write(std::min(toWrite, COUNT) * sizeof(Entry), entries); + toWrite -= COUNT; + } + + delete [] entries; + + file->flush(); +} + +/* attempt to get data into the cache. +If there is no data in the cache, returns 0. +If the index is out of range, returns 0 and no error. +*/ +Archive::ByteStream * IndexedCache::getData(int index) const +{ + if (index < 0 || index >= length) + return 0; + + lockForRead(); + + Entry entry; + readEntry(index, entry); + + if (entry.offset == 0) + { + unlock(); + return 0; + } + file->seek(AbstractFile::SeekBegin, entry.offset); + Datum datum; + file->read(&datum, sizeof(datum)); + unsigned char * data = new unsigned char[datum.length]; + file->read(data, datum.length); + Archive::ByteStream * result = new Archive::ByteStream(data, datum.length); + delete [] data; + unlock(); + + return result; +} + +/* Test to see if the data is already in the cache +If there is no data in the cache, returns false. +If the index is out of range, returns true. (The typical +use is to check contains() before creating the bytestream +to write data. This prevents an out-of-range index from +having to generate data) +*/ +bool IndexedCache::contains(int index) const +{ + if (index < 0 || index >= length) + return true; + + lockForRead(); + + Entry entry; + readEntry(index, entry); + + unlock(); + return entry.offset != 0; +} + +/* Set data into the cache. +The new data is appended and the index is updated, even if the data is already in the cache. +Use contains() to test if needed. This can potentially cause duplicate data to +be entered into the cache twice, but this will typicallly not be a problem. +This is also useful to allow partial caching, updating the cached data as more +information becomes available. +*/ +void IndexedCache::setData(int index, Archive::ByteStream const * data) +{ + if (index < 0 || index >= length) + return; + + lockForWrite(); + + Entry entry; + + file->seek(AbstractFile::SeekEnd, 0); + entry.offset = file->tell(); + + Datum datum; + datum.index = index; + datum.length = data->getSize(); + file->write(sizeof(datum), &datum); + file->write(data->getSize(), data->getBuffer()); + + writeEntry(index, entry); + + file->flush(); + + unlock(); +} + +void IndexedCache::readEntry(int index, Entry &o_entry) const +{ + file->seek(AbstractFile::SeekBegin, sizeof(Header) + index * sizeof(Entry)); + file->read(&o_entry, sizeof(o_entry)); +} + +void IndexedCache::writeEntry(int index, Entry const &i_entry) +{ + file->seek(AbstractFile::SeekBegin, sizeof(Header) + index * sizeof(Entry)); + file->write(sizeof(i_entry), &i_entry); +} + +void IndexedCache::lockExclusive(const std::string &filename) +{ + UNREF(filename); +} + +void IndexedCache::unlockExclusive(const std::string &filename) +{ + UNREF(filename); +} + +void IndexedCache::lockForRead() const +{ +} + +void IndexedCache::lockForWrite() +{ +} + +void IndexedCache::unlock() const +{ +} + +/* Repacks and sorts the file by index order. +Returns false if the repack fails for any reason. +Any attempts to access the file during repacking will fail. +Repacking will fail if the file is already opened for use. +*/ +bool IndexedCache::repack(const std::string &filename) +{ + lockExclusive(filename); + + std::string outputFilename(filename + ".repack"); + + { + IndexedCache input(filename); + int size = input.getSize(); + if (size == 0) + { + unlockExclusive(filename); + return false; + } + + IndexedCache output(filename, size, input.getVersion()); + int x; + for (x=0; x + +class AbstractFile; + +namespace Archive +{ + class ByteStream; +}; + +/* +IndexedCache provides a cache of variable-sized data indexed by an integer. + +It is intended to provide a means of storing data which requires a significant amount +of time to produce (on the order of hundreds of milliseconds). Each read requires +at most two seeks; but the index will probably be cached in RAM, and in many cases +the data will as well, especially if the file has been packed. + +It is essentially a very simple append-only filesystem. + +The structure of the file is as follows: +1. A simple header +2. An array of offsets (from the start of file) +3. A sequence of index/length/arbitrary data + +Updates are made by writing the data (never overwriting existing data) and then writing +the index part of the table. Assuming writes commit in order, no incorrect data can +be stored. + +File corruption can still occur, however it does not damage data integrity. Appending +data and then crashing before the index can be updated will leave extra data at the end +of the file. Simply iterating through the data allows us to rebuild the most recent index. + +*/ + +class IndexedCache +{ +public: + // Open the spatial cache. If it is not present or the stored width, height, and version are different, recreate it. + IndexedCache(const std::string &filename, int length, int version); + virtual ~IndexedCache(); + + /* attempt to get data into the cache. + If there is no data in the cache, returns 0. + If the index is out of range, returns 0 and no error. + */ + Archive::ByteStream * getData(int index) const; + + /* Test to see if the data is already in the cache + If there is no data in the cache, returns false. + If the index is out of range, returns true. (The typical + use is to check contains() before creating the bytestream + to write data. This prevents an out-of-range index from + having to generate data) + */ + bool contains(int index) const; + + /* Set data into the cache. + The new data is appended and the index is updated, even if the data is already in the cache. + Use contains() to test if needed. This can potentially cause duplicate data to + be entered into the cache twice, but this will typicallly not be a problem. + This is also useful to allow partial caching, updating the cached data as more + information becomes available. + */ + void setData(int index, Archive::ByteStream const * data); + + /* Repacks and sorts the file by index order. + Returns false if the repack fails for any reason. + Any attempts to access the file during repacking will fail. + Repacking will fail if the file is already opened for use. + */ + static bool repack(const std::string &filename); + + int getSize() { return length; } + int getVersion() { return version; } +private: + IndexedCache(const std::string &filename); + struct Header + { + int elements; + int formatVersion; + int version; + }; + struct Entry + { + int offset; + }; + struct Datum + { + int index; + int length; + // char data[length]; + }; + +private: + std::string filename; + int length; + int version; + mutable AbstractFile * file; + + void initializeFile(int version); + static void lockExclusive(const std::string &filename); // used to open the file for repacking. + static void unlockExclusive(const std::string &filename); + void lockForRead() const; + void lockForWrite(); + void unlock() const; + void readEntry(int index, Entry &o_entry) const; + void writeEntry(int index, Entry const &i_entry); + +}; + +#endif + diff --git a/engine/shared/library/sharedUtility/src/shared/InstallationResourceData.h b/engine/shared/library/sharedUtility/src/shared/InstallationResourceData.h new file mode 100644 index 00000000..f0059736 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/InstallationResourceData.h @@ -0,0 +1,73 @@ +//====================================================================== +// +// InstallationResourceData.h +// copyright (c) 2001 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_InstallationResourceData_H +#define INCLUDED_InstallationResourceData_H + +//====================================================================== + +#include "Unicode.h" +#include "sharedFoundation/NetworkId.h" + +//---------------------------------------------------------------------- + +/** +* InstallationResource contains information of interest to the client, concerning +* a single resource pool +*/ + +struct InstallationResourceData +{ + std::string m_name; + NetworkId m_id; + std::string m_parentName; + uint8 m_efficiency; + + InstallationResourceData (const std::string & name, const NetworkId & id, const std::string& parentName, uint8 efficiency); + InstallationResourceData (); + + bool operator== (const InstallationResourceData & rhs) const; + bool operator!= (const InstallationResourceData & rhs) const; +}; + +//---------------------------------------------------------------------- + +inline InstallationResourceData::InstallationResourceData (const std::string & name, const NetworkId & id, const std::string& parentName, uint8 efficiency) : +m_name (name), +m_id (id), +m_parentName(parentName), +m_efficiency (efficiency) +{ +} + +//---------------------------------------------------------------------- + +inline InstallationResourceData::InstallationResourceData () : +m_name (), +m_id (), +m_parentName(), +m_efficiency (0) +{ +} + +//---------------------------------------------------------------------- + +inline bool InstallationResourceData::operator== (const InstallationResourceData & rhs) const +{ + return m_id == rhs.m_id && m_name == rhs.m_name && m_efficiency == rhs.m_efficiency && m_parentName == rhs.m_parentName; +} + +//---------------------------------------------------------------------- + +inline bool InstallationResourceData::operator!= (const InstallationResourceData & rhs) const +{ + return !(*this == rhs); +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/InstallationResourceDataArchive.h b/engine/shared/library/sharedUtility/src/shared/InstallationResourceDataArchive.h new file mode 100644 index 00000000..b6b09010 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/InstallationResourceDataArchive.h @@ -0,0 +1,44 @@ +//====================================================================== +// +// InstallationResourceDataArchive.h +// copyright (c) 2001 Sony Online Entertainment +// +//====================================================================== + +#ifndef INCLUDED_InstallationResourceDataArchive_H +#define INCLUDED_InstallationResourceDataArchive_H + +//====================================================================== + +#include "sharedFoundation/NetworkIdArchive.h" +#include "sharedUtility/InstallationResourceData.h" +#include "unicodeArchive/UnicodeArchive.h" + +//----------------------------------------------------------------------- + +namespace Archive +{ + //----------------------------------------------------------------------- + + inline void get(ReadIterator & source, InstallationResourceData & target) + { + get(source, target.m_id); + get(source, target.m_name); + get(source, target.m_parentName); + get(source, target.m_efficiency); + } + + //----------------------------------------------------------------------- + + inline void put(ByteStream & target, const InstallationResourceData & source) + { + put(target, source.m_id); + put(target, source.m_name); + put(target, source.m_parentName); + put(target, source.m_efficiency); + } +} + +//====================================================================== + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/InteriorLayoutReaderWriter.cpp b/engine/shared/library/sharedUtility/src/shared/InteriorLayoutReaderWriter.cpp new file mode 100644 index 00000000..7aa78f09 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/InteriorLayoutReaderWriter.cpp @@ -0,0 +1,381 @@ +// ====================================================================== +// +// InteriorLayoutReaderWriter.cpp +// asommers +// +// copyright 2002, sony online entertainment +// +// ====================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/InteriorLayoutReaderWriter.h" + +#include "sharedFile/Iff.h" +#include "sharedFoundation/LessPointerComparator.h" +#include "sharedFoundation/PersistentCrcString.h" +#include "sharedFoundation/TemporaryCrcString.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedMath/Transform.h" + +#include +#include +#include + +// ====================================================================== + +namespace InteriorLayoutReaderWriterNamespace +{ + const Tag TAG_INLY = TAG(I,N,L,Y); + const Tag TAG_NODE = TAG(N,O,D,E); +}; + +using namespace InteriorLayoutReaderWriterNamespace; + +// ====================================================================== +// InteriorLayoutReaderWriter::Node +// ====================================================================== + +class InteriorLayoutReaderWriter::Node +{ +public: + + explicit Node(char const * cellName); + ~Node(); + + CrcString const & getCellName() const; + + int getNumberOfObjects() const; + CrcString const & getObjectTemplateName(int index) const; + Transform const & getTransform_o2p(int index) const; + + void addObject(char const * objectTemplateName, Transform const & transform_o2p); + +private: + + Node(); + Node(const Node&); + Node & operator=(const Node&); + +private: + + PersistentCrcString const m_cellName; + typedef std::vector > ObjectVector; + ObjectVector m_objectVector; +}; + +// ====================================================================== +// PUBLIC InteriorLayoutReaderWriter::Node +// ====================================================================== + +InteriorLayoutReaderWriter::Node::Node(char const * const cellName) : + m_cellName(cellName, true), + m_objectVector() +{ +} + +// ---------------------------------------------------------------------- + +InteriorLayoutReaderWriter::Node::~Node() +{ +} + +// ---------------------------------------------------------------------- + +CrcString const & InteriorLayoutReaderWriter::Node::getCellName() const +{ + return m_cellName; +} + +// ---------------------------------------------------------------------- + +int InteriorLayoutReaderWriter::Node::getNumberOfObjects() const +{ + return static_cast(m_objectVector.size()); +} + +// ---------------------------------------------------------------------- + +CrcString const & InteriorLayoutReaderWriter::Node::getObjectTemplateName(int const index) const +{ + VALIDATE_RANGE_INCLUSIVE_EXCLUSIVE(0, index, getNumberOfObjects()); + + return m_objectVector[static_cast(index)].first; +} + +// ---------------------------------------------------------------------- + +Transform const & InteriorLayoutReaderWriter::Node::getTransform_o2p(int const index) const +{ + VALIDATE_RANGE_INCLUSIVE_EXCLUSIVE(0, index, getNumberOfObjects()); + + return m_objectVector[static_cast(index)].second; +} + +// ---------------------------------------------------------------------- + +void InteriorLayoutReaderWriter::Node::addObject(char const * const objectTemplateName, Transform const & transform_o2p) +{ + FATAL(!objectTemplateName, ("")); + m_objectVector.push_back(std::make_pair(PersistentCrcString(objectTemplateName, true), transform_o2p)); +} + +// ====================================================================== +// PUBLIC InteriorLayoutReaderWriter +// ====================================================================== + +InteriorLayoutReaderWriter::InteriorLayoutReaderWriter() : + m_nodeMap(new NodeMap), + m_numberOfObjects(0) +{ +} + +// ---------------------------------------------------------------------- + +InteriorLayoutReaderWriter::~InteriorLayoutReaderWriter() +{ + clear(); + + delete m_nodeMap; +} + +// ---------------------------------------------------------------------- + +bool InteriorLayoutReaderWriter::load(const char* const fileName) +{ + clear(); + + Iff iff; + if (iff.open(fileName, true)) + { + load(iff); + + return true; + } + + return false; +} + +// ---------------------------------------------------------------------- + +bool InteriorLayoutReaderWriter::save(const char* const fileName) const +{ + Iff iff(1024); + save(iff); + return iff.write(fileName, true); +} + +// ---------------------------------------------------------------------- + +CrcString const & InteriorLayoutReaderWriter::getFileName() const +{ + return m_fileName; +} + +// ---------------------------------------------------------------------- + +int InteriorLayoutReaderWriter::getNumberOfCellNames() const +{ + return static_cast(m_nodeMap->size()); +} + +// ---------------------------------------------------------------------- + +CrcString const & InteriorLayoutReaderWriter::getCellName(int const index) const +{ + VALIDATE_RANGE_INCLUSIVE_EXCLUSIVE(0, index, getNumberOfCellNames()); + + NodeMap::iterator iter = m_nodeMap->begin(); + for (int i = 0; i < index; ++i, ++iter) + ; + + return *iter->first; +} + +// ---------------------------------------------------------------------- + +bool InteriorLayoutReaderWriter::hasCellName(CrcString const & cellName) const +{ + return m_nodeMap->find(&cellName) != m_nodeMap->end(); +} + +// ---------------------------------------------------------------------- + +int InteriorLayoutReaderWriter::getNumberOfObjects(CrcString const & cellName) const +{ + NodeMap::iterator iter = m_nodeMap->find(&cellName); + if (iter != m_nodeMap->end()) + return static_cast(iter->second->getNumberOfObjects()); + + return 0; +} + +// ---------------------------------------------------------------------- + +CrcString const & InteriorLayoutReaderWriter::getObjectTemplateName(CrcString const & cellName, int const index) const +{ + VALIDATE_RANGE_INCLUSIVE_EXCLUSIVE(0, index, getNumberOfObjects(cellName)); + + NodeMap::iterator iter = m_nodeMap->find(&cellName); + if (iter != m_nodeMap->end()) + return iter->second->getObjectTemplateName(index); + + DEBUG_FATAL(true, ("InteriorLayoutReaderWriter::getObjectTemplateName: %s does not have any objects in cells named %s", m_fileName.getString(), cellName.getString())); + return PersistentCrcString::empty; +} + +// ---------------------------------------------------------------------- + +Transform const & InteriorLayoutReaderWriter::getTransform_o2p(CrcString const & cellName, int const index) const +{ + VALIDATE_RANGE_INCLUSIVE_EXCLUSIVE(0, index, getNumberOfObjects(cellName)); + + NodeMap::iterator iter = m_nodeMap->find(&cellName); + if (iter != m_nodeMap->end()) + return iter->second->getTransform_o2p(index); + + DEBUG_FATAL(true, ("InteriorLayoutReaderWriter::getTransform_o2p: %s does not have any objects in cells named %s", m_fileName.getString(), cellName.getString())); + return Transform::identity; +} + +// ---------------------------------------------------------------------- + +int InteriorLayoutReaderWriter::getNumberOfObjects() const +{ + return m_numberOfObjects; +} + +// ---------------------------------------------------------------------- + +void InteriorLayoutReaderWriter::getObjectTemplateNames(CrcStringVector & crcStringVector) +{ + crcStringVector.reserve(static_cast(m_numberOfObjects)); + for (NodeMap::iterator iter = m_nodeMap->begin(); iter != m_nodeMap->end(); ++iter) + { + Node const * const node = iter->second; + for (int i = 0; i < node->getNumberOfObjects(); ++i) + { + CrcString const & objectTemplateName = node->getObjectTemplateName(i); + size_t j = 0; + for (; j < crcStringVector.size(); ++j) + if (*crcStringVector[j] == objectTemplateName) + break; + + if (j == crcStringVector.size()) + crcStringVector.push_back(&objectTemplateName); + } + } +} + +// ---------------------------------------------------------------------- + +void InteriorLayoutReaderWriter::clear() +{ + std::for_each(m_nodeMap->begin(), m_nodeMap->end(), PointerDeleterPairSecond()); + m_nodeMap->clear(); + m_numberOfObjects = 0; +} + +// ---------------------------------------------------------------------- + +void InteriorLayoutReaderWriter::addObject(char const * const cellName, char const * const objectTemplateName, Transform const & transform_o2p) +{ + Node * node = 0; + TemporaryCrcString const cellNameCrcString(cellName, true); + NodeMap::iterator iter = m_nodeMap->find(&cellNameCrcString); + if (iter != m_nodeMap->end()) + node = iter->second; + else + { + node = new Node(cellName); + m_nodeMap->insert(std::make_pair(&node->getCellName(), node)); + } + + NOT_NULL(node); + node->addObject(objectTemplateName, transform_o2p); + + ++m_numberOfObjects; +} + +// ====================================================================== +// PUBLIC InteriorLayoutReaderWriter +// ====================================================================== + +void InteriorLayoutReaderWriter::load(Iff& iff) +{ + if (iff.enterForm(TAG_INLY, true)) + { + switch(iff.getCurrentName()) + { + case TAG_0000: + load_0000(iff); + break; + + default: + { + char tagBuffer [5]; + ConvertTagToString(iff.getCurrentName(), tagBuffer); + + char buffer [128]; + iff.formatLocation(buffer, sizeof(buffer)); + DEBUG_FATAL(true,("InteriorLayoutReaderWriter::load invalid version %s/%s", buffer, tagBuffer)); + } + break; + } + + iff.exitForm(TAG_INLY); + } +} + +// ---------------------------------------------------------------------- + +void InteriorLayoutReaderWriter::load_0000(Iff& iff) +{ + iff.enterForm(TAG_0000); + + char objectTemplateName [512]; + char cellName [512]; + + while (iff.getNumberOfBlocksLeft()) + { + iff.enterChunk(TAG_NODE); + + iff.read_string(objectTemplateName, 512); + iff.read_string(cellName, 512); + Transform const transform_o2p = iff.read_floatTransform(); + + addObject(cellName, objectTemplateName, transform_o2p); + + iff.exitChunk(TAG_NODE); + } + + iff.exitForm(TAG_0000); +} + +// ---------------------------------------------------------------------- + +void InteriorLayoutReaderWriter::save(Iff& iff) const +{ + iff.insertForm(TAG_INLY); + iff.insertForm(TAG_0000); + + for (NodeMap::iterator iter = m_nodeMap->begin(); iter != m_nodeMap->end(); ++iter) + { + Node const * const node = iter->second; + for (int i = 0; i < node->getNumberOfObjects(); ++i) + { + iff.insertChunk(TAG_NODE); + + iff.insertChunkString(node->getObjectTemplateName(i).getString()); + iff.insertChunkString(node->getCellName().getString()); + iff.insertChunkFloatTransform(node->getTransform_o2p(i)); + + iff.exitChunk(TAG_NODE); + } + } + + iff.exitForm(TAG_0000); + iff.exitForm(TAG_INLY); +} + +// ====================================================================== + diff --git a/engine/shared/library/sharedUtility/src/shared/InteriorLayoutReaderWriter.h b/engine/shared/library/sharedUtility/src/shared/InteriorLayoutReaderWriter.h new file mode 100644 index 00000000..cd3747c1 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/InteriorLayoutReaderWriter.h @@ -0,0 +1,76 @@ +// ====================================================================== +// +// InteriorLayoutReaderWriter.h +// asommers +// +// copyright 2002, sony online entertainment +// +// ====================================================================== + +#ifndef INCLUDED_InteriorLayoutReaderWriter_H +#define INCLUDED_InteriorLayoutReaderWriter_H + +// ====================================================================== + +#include "sharedFoundation/PersistentCrcString.h" + +class LessPointerComparator; +class Transform; +class Iff; + +// ====================================================================== + +class InteriorLayoutReaderWriter +{ +public: + + InteriorLayoutReaderWriter (); + ~InteriorLayoutReaderWriter (); + + bool load (const char* fileName); + bool save (const char* fileName) const; + + CrcString const & getFileName() const; + + //-- reader interface + int getNumberOfCellNames() const; + CrcString const & getCellName(int index) const; + bool hasCellName(CrcString const & cellName) const; + int getNumberOfObjects(CrcString const & cellName) const; + CrcString const & getObjectTemplateName(CrcString const & cellName, int index) const; + Transform const & getTransform_o2p(CrcString const & cellName, int index) const; + + //-- preload interface + int getNumberOfObjects() const; + typedef stdvector::fwd CrcStringVector; + void getObjectTemplateNames(CrcStringVector & crcStringVector); + + //-- writer interface + void clear (); + void addObject(char const * cellName, char const * objectTemplateName, Transform const & transform_o2p); + +private: + + void load (Iff& iff); + void load_0000 (Iff& iff); + + void save (Iff& iff) const; + +private: + + InteriorLayoutReaderWriter (const InteriorLayoutReaderWriter&); + InteriorLayoutReaderWriter& operator= (const InteriorLayoutReaderWriter&); + +private: + + PersistentCrcString m_fileName; + + class Node; + typedef stdmap::fwd NodeMap; + NodeMap * const m_nodeMap; + int m_numberOfObjects; +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/LocalMachineOptionManager.cpp b/engine/shared/library/sharedUtility/src/shared/LocalMachineOptionManager.cpp new file mode 100644 index 00000000..13bc19eb --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/LocalMachineOptionManager.cpp @@ -0,0 +1,112 @@ +// ====================================================================== +// +// LocalMachineOptionManager.cpp +// asommers +// +// copyright 2003, sony online entertainment +// +// ====================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/LocalMachineOptionManager.h" + +#include "sharedFoundation/ExitChain.h" +#include "sharedUtility/OptionManager.h" + +// ====================================================================== +// LocalMachineOptionManagerNamespace +// ====================================================================== + +namespace LocalMachineOptionManagerNamespace +{ + char const * const cms_fileName = "local_machine_options.iff"; + + bool ms_installed; + OptionManager * ms_optionManager; +} + +using namespace LocalMachineOptionManagerNamespace; + +// ====================================================================== +// STATIC PUBLIC LocalMachineOptionManager +// ====================================================================== + +void LocalMachineOptionManager::install () +{ + DEBUG_FATAL (ms_installed, ("LocalMachineOptionManager::install: already installed")); + ms_installed = true; + + ms_optionManager = new OptionManager; + ms_optionManager->load (cms_fileName); + + ExitChain::add (remove, "LocalMachineOptionManager::remove"); +} + +// ---------------------------------------------------------------------- + +void LocalMachineOptionManager::remove () +{ + DEBUG_FATAL (!ms_installed, ("LocalMachineOptionManager::remove: not installed")); + ms_installed = false; + + delete ms_optionManager; + ms_optionManager = 0; +} + +// ---------------------------------------------------------------------- + +void LocalMachineOptionManager::save () +{ + DEBUG_FATAL (!ms_installed, ("LocalMachineOptionManager::save: not installed")); + ms_optionManager->save (cms_fileName); +} + +// ---------------------------------------------------------------------- + +void LocalMachineOptionManager::registerOption (bool & variable, char const * const section, char const * const name, const int version) +{ + DEBUG_FATAL (!ms_installed, ("LocalMachineOptionManager::registerOption: not installed")); + ms_optionManager->registerOption (variable, section, name, version); +} + +// ---------------------------------------------------------------------- + +void LocalMachineOptionManager::registerOption (float & variable, char const * const section, char const * const name, const int version) +{ + DEBUG_FATAL (!ms_installed, ("LocalMachineOptionManager::registerOption: not installed")); + ms_optionManager->registerOption (variable, section, name, version); +} + +// ---------------------------------------------------------------------- + +void LocalMachineOptionManager::registerOption (int & variable, char const * const section, char const * const name, const int version) +{ + DEBUG_FATAL (!ms_installed, ("LocalMachineOptionManager::registerOption: not installed")); + ms_optionManager->registerOption (variable, section, name, version); +} + +// ---------------------------------------------------------------------- + +void LocalMachineOptionManager::registerOption (std::string & variable, char const * const section, char const * const name, const int version) +{ + DEBUG_FATAL (!ms_installed, ("LocalMachineOptionManager::registerOption: not installed")); + ms_optionManager->registerOption (variable, section, name, version); +} + +// ---------------------------------------------------------------------- + +void LocalMachineOptionManager::registerOption (Unicode::String & variable, char const * const section, char const * const name, const int version) +{ + DEBUG_FATAL (!ms_installed, ("LocalMachineOptionManager::registerOption: not installed")); + ms_optionManager->registerOption (variable, section, name, version); +} + +// ---------------------------------------------------------------------- + +float LocalMachineOptionManager::findFloat(char const * const section, char const * const name, float const defaultValue) +{ + DEBUG_FATAL (!ms_installed, ("LocalMachineOptionManager::findFloat: not installed")); + return ms_optionManager->findFloat (section, name, defaultValue); +} + +// ====================================================================== diff --git a/engine/shared/library/sharedUtility/src/shared/LocalMachineOptionManager.h b/engine/shared/library/sharedUtility/src/shared/LocalMachineOptionManager.h new file mode 100644 index 00000000..e4971169 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/LocalMachineOptionManager.h @@ -0,0 +1,42 @@ +// ====================================================================== +// +// LocalMachineOptionManager.h +// asommers +// +// copyright 2003, sony online entertainment +// +// ====================================================================== + +#ifndef INCLUDED_LocalMachineOptionManager_H +#define INCLUDED_LocalMachineOptionManager_H + +// ====================================================================== + +class LocalMachineOptionManager +{ +public: + + static void install (); + static void remove (); + + static void save (); + + static void registerOption (bool & variable, char const * section, char const * name, const int version = 0); + static void registerOption (float & variable, char const * section, char const * name, const int version = 0); + static void registerOption (int & variable, char const * section, char const * name, const int version = 0); + static void registerOption (std::string & variable, char const * section, char const * name, const int version = 0); + static void registerOption (Unicode::String & variable, char const * section, char const * name, const int version = 0); + + static float findFloat(char const * section, char const * name, float defaultValue); + +private: + + LocalMachineOptionManager (); + ~LocalMachineOptionManager (); + LocalMachineOptionManager (LocalMachineOptionManager const &); + LocalMachineOptionManager & operator= (LocalMachineOptionManager const &); +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/Location.cpp b/engine/shared/library/sharedUtility/src/shared/Location.cpp new file mode 100644 index 00000000..0a1000a6 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/Location.cpp @@ -0,0 +1,182 @@ +// Location.cpp +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall + +//----------------------------------------------------------------------- + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/Location.h" +#include "sharedFoundation/ConstCharCrcString.h" +#include "sharedFoundation/CrcStringTable.h" +#include + +//----------------------------------------------------------------------- + +namespace LocationNamespace +{ + CrcStringTable * s_planetCrcStringTable = 0; + + struct TableAllocator + { + TableAllocator(); + ~TableAllocator(); + }; + + TableAllocator::TableAllocator() + { + if(! s_planetCrcStringTable) + s_planetCrcStringTable = new CrcStringTable("misc/planet_crc_string_table.iff"); + } + + TableAllocator::~TableAllocator() + { + delete s_planetCrcStringTable; + } +} +using namespace LocationNamespace; + +//----------------------------------------------------------------------- + +Location::Location() : +m_coordinates(), +m_cell(), +m_sceneIdCrc() +{ + static TableAllocator t; +} + +//----------------------------------------------------------------------- + +Location::Location(const Location & source) : +m_coordinates(source.m_coordinates), +m_cell(source.m_cell), +m_sceneIdCrc(source.m_sceneIdCrc) +{ +} + +//----------------------------------------------------------------------- + +Location::Location(const Vector & coordinates, const NetworkId & cell, unsigned int sceneIdCrc) : +m_coordinates(coordinates), +m_cell(cell), +m_sceneIdCrc(sceneIdCrc) +{ +} + +//----------------------------------------------------------------------- + +Location::~Location() +{ +} + + +//----------------------------------------------------------------------- + +Location & Location::operator = (const Location & rhs) +{ + if(&rhs != this) + { + m_coordinates = rhs.m_coordinates; + m_cell = rhs.m_cell; + m_sceneIdCrc = rhs.m_sceneIdCrc; + } + return *this; +} + +//----------------------------------------------------------------------- + +bool Location::operator != (const Location & rhs) const +{ + return (m_coordinates != rhs.m_coordinates || m_cell != rhs.m_cell || m_sceneIdCrc != rhs.m_sceneIdCrc); +} + +//----------------------------------------------------------------------- + +bool Location::operator < (const Location & rhs) const +{ + if (m_sceneIdCrc != rhs.m_sceneIdCrc) + return m_sceneIdCrc < rhs.m_sceneIdCrc; + if (m_cell != rhs.m_cell) + return m_cell < rhs.m_cell; + return m_coordinates.x < rhs.m_coordinates.x; +} + +//----------------------------------------------------------------------- + +const char * const Location::getSceneNameByCrc(unsigned int crc) +{ + return s_planetCrcStringTable->lookUp(crc).getString(); +} + +//----------------------------------------------------------------------- + +unsigned int Location::getCrcBySceneName(const char * const name) +{ + return s_planetCrcStringTable->lookUp(name).getCrc(); +} + +//----------------------------------------------------------------------- + +unsigned int Location::getCrcBySceneName(const std::string & name) +{ + return getCrcBySceneName(name.c_str()); +} + +//----------------------------------------------------------------------- + +const Vector & Location::getCoordinates() const +{ + return m_coordinates; +} + +//----------------------------------------------------------------------- + +const NetworkId & Location::getCell() const +{ + return m_cell; +} + +//----------------------------------------------------------------------- + +unsigned int Location::getSceneIdCrc() const +{ + return m_sceneIdCrc; +} + +//----------------------------------------------------------------------- + +const char * const Location::getSceneId() const +{ + return getSceneNameByCrc(m_sceneIdCrc); +} + +//----------------------------------------------------------------------- + +void Location::setCoordinates(const Vector & coordinates) +{ + m_coordinates = coordinates; +} + +//----------------------------------------------------------------------- + +void Location::setCell(const NetworkId & cell) +{ + m_cell = cell; +} + +//----------------------------------------------------------------------- + +void Location::setSceneIdCrc(unsigned int crc) +{ + m_sceneIdCrc = crc; +} + +//----------------------------------------------------------------------- + +void Location::setSceneId(const char * const name) +{ + m_sceneIdCrc = getCrcBySceneName(name); +} + +//----------------------------------------------------------------------- + diff --git a/engine/shared/library/sharedUtility/src/shared/Location.h b/engine/shared/library/sharedUtility/src/shared/Location.h new file mode 100644 index 00000000..d7958af5 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/Location.h @@ -0,0 +1,52 @@ +// Location.h +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall + +#ifndef _INCLUDED_Location_H +#define _INCLUDED_Location_H + +//----------------------------------------------------------------------- + +#include "sharedMath/Vector.h" +#include "sharedFoundation/NetworkId.h" +#include "sharedUtility/LocationArchive.h" + +//----------------------------------------------------------------------- + +// WARNING: If you edit this class, you must also edit the persistence functions for it (SwgSnapshot.cpp) +class Location +{ +public: + Location(); + Location(const Vector & coordinates, const NetworkId & cell, unsigned int sceneIdCrc); + Location & operator = (const Location & rhs); + Location(const Location & source); + ~Location(); + + bool operator != (const Location & rhs) const; + bool operator < (const Location & rhs) const; + + const Vector & getCoordinates () const; + const NetworkId & getCell () const; + unsigned int getSceneIdCrc () const; + const char * const getSceneId () const; + + static const char * const getSceneNameByCrc (unsigned int crc); + static unsigned int getCrcBySceneName (const char * const name); + static unsigned int getCrcBySceneName (const std::string & name); + + void setCoordinates (const Vector & coordinates); + void setCell (const NetworkId & cell); + void setSceneIdCrc (unsigned int crc); + void setSceneId (const char * const sceneId); + +private: + friend void Archive::get(Archive::ReadIterator &, Location &); + Vector m_coordinates; + NetworkId m_cell; + unsigned int m_sceneIdCrc; +}; + +//----------------------------------------------------------------------- + +#endif // _INCLUDED_Location_H diff --git a/engine/shared/library/sharedUtility/src/shared/LocationArchive.cpp b/engine/shared/library/sharedUtility/src/shared/LocationArchive.cpp new file mode 100644 index 00000000..f45341c8 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/LocationArchive.cpp @@ -0,0 +1,34 @@ +// LocationArchive.cpp +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall + +//----------------------------------------------------------------------- + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/LocationArchive.h" + +#include "Archive/Archive.h" +#include "sharedUtility/Location.h" +#include "sharedMathArchive/VectorArchive.h" +#include "sharedFoundation/NetworkIdArchive.h" + +//----------------------------------------------------------------------- + +namespace Archive +{ + + void get (Archive::ReadIterator & source, Location & target) + { + get(source, target.m_coordinates); + get(source, target.m_cell); + get(source, target.m_sceneIdCrc); + } + + void put (ByteStream & target, const Location & source) + { + put(target, source.getCoordinates()); + put(target, source.getCell()); + put(target, source.getSceneIdCrc()); + } +} + diff --git a/engine/shared/library/sharedUtility/src/shared/LocationArchive.h b/engine/shared/library/sharedUtility/src/shared/LocationArchive.h new file mode 100644 index 00000000..26adceed --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/LocationArchive.h @@ -0,0 +1,23 @@ +// LocationArchive.h +// Copyright 2000-02, Sony Online Entertainment Inc., all rights reserved. +// Author: Justin Randall + +#ifndef _INCLUDED_LocationArchive_H +#define _INCLUDED_LocationArchive_H + +//----------------------------------------------------------------------- + +class Location; + +namespace Archive +{ + class ReadIterator; + class ByteStream; + + void get (Archive::ReadIterator & source, Location & target); + void put (ByteStream & target, const Location & source); +} + +//----------------------------------------------------------------------- + +#endif // _INCLUDED_LocationArchive_H diff --git a/engine/shared/library/sharedUtility/src/shared/LocationManager.cpp b/engine/shared/library/sharedUtility/src/shared/LocationManager.cpp new file mode 100644 index 00000000..3d725623 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/LocationManager.cpp @@ -0,0 +1,366 @@ +// ====================================================================== +// +// LocationManager.cpp +// asommers +// +// copyright 2003, sony online entertainment +// +// ====================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/LocationManager.h" + +#include "sharedFoundation/ConfigFile.h" +#include "sharedFoundation/ExitChain.h" +#include "sharedFoundation/MemoryBlockManager.h" +#include "sharedFoundation/MemoryBlockManagerMacros.h" +#include "sharedFoundation/NetworkId.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedMath/Rectangle2d.h" +#include "sharedMath/SphereTree.h" +#include "sharedMath/Vector2d.h" +#include "sharedUtility/BakedTerrain.h" +#include "sharedUtility/BakedTerrainReader.h" +#include "sharedUtility/ConfigSharedUtility.h" + +#include +#include +#include + +// ====================================================================== +// LocationManagerNamespace +// ====================================================================== + +namespace LocationManagerNamespace +{ + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class Node + { + MEMORY_BLOCK_MANAGER_INTERFACE_WITHOUT_INSTALL; + + public: + + static void install (); + static void remove (); + + public: + + explicit Node (NetworkId const & networkId); + ~Node (); + + Sphere const getSphere () const; + void setSphere (int x, int z, int radius); + + SpatialSubdivisionHandle * getSpatialSubdivisionHandle (); + void setSpatialSubdivisionHandle (SpatialSubdivisionHandle * spatialSubdivisionHandle); + + private: + + Node (); + Node (Node const & rhs); + Node & operator= (Node const & rhs); + + private: + + NetworkId m_networkId; + int m_x; + int m_z; + int m_radius; + SpatialSubdivisionHandle * m_spatialSubdivisionHandle; + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + class NodeSphereExtentAccessor: public BaseSphereTreeAccessor + { + public: + + static Sphere const getExtent (Node const * const node) + { + return node ? node->getSphere () : Sphere::zero; + } + }; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + typedef SphereTree NodeSphereTree; + typedef std::vector NodeVector; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + std::string ms_planetName; + + NodeSphereTree ms_nodeSphereTree; + + typedef std::map NodeMap; + NodeMap ms_nodeMap; + + BakedTerrain * ms_bakedTerrain; + + typedef std::vector > OffsetList; + OffsetList ms_offsetList; + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + void remove (); + bool intersectsObject (float x, float z, float radius); + void clearSphereTree (NodeSphereTree & sphereTree); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +} + +using namespace LocationManagerNamespace; + +// ====================================================================== +// STATIC PUBLIC LocationManager::Node +// ====================================================================== + +MEMORY_BLOCK_MANAGER_IMPLEMENTATION_WITHOUT_INSTALL (Node, true, 0, 0, 0); + +// ---------------------------------------------------------------------- + +void Node::install () +{ + installMemoryBlockManager (); +} + +// ---------------------------------------------------------------------- + +void Node::remove () +{ + removeMemoryBlockManager (); +} + +// ====================================================================== +// PUBLIC LocationManagerNamespace::Node +// ====================================================================== + +Node::Node (NetworkId const & networkId) : + m_networkId (networkId), + m_x (0), + m_z (0), + m_radius (0), + m_spatialSubdivisionHandle (0) +{ +} + +// ---------------------------------------------------------------------- + +Node::~Node () +{ + m_spatialSubdivisionHandle = 0; +} + +// ---------------------------------------------------------------------- + +Sphere const Node::getSphere () const +{ + return Sphere (Vector (static_cast (m_x), 0.f, static_cast (m_z)), static_cast (m_radius)); +} + +// ---------------------------------------------------------------------- + +void Node::setSphere (int const x, int const z, int const radius) +{ + m_x = x; + m_z = z; + m_radius = radius; +} + +// ---------------------------------------------------------------------- + +SpatialSubdivisionHandle * Node::getSpatialSubdivisionHandle () +{ + return m_spatialSubdivisionHandle; +} + +// ---------------------------------------------------------------------- + +void Node::setSpatialSubdivisionHandle (SpatialSubdivisionHandle * const spatialSubdivisionHandle) +{ + m_spatialSubdivisionHandle = spatialSubdivisionHandle; +} + +// ====================================================================== +// STATIC PUBLIC LocationManager +// ====================================================================== + +void LocationManager::install () +{ + Node::install (); + + ExitChain::add (remove, "LocationManager::remove"); +} + +// ---------------------------------------------------------------------- + +void LocationManager::setPlanetName (char const * const planetName) +{ + ms_planetName = planetName; + + char fileName [256]; + sprintf (fileName, "terrain/%s.trn", planetName); + + if (ms_bakedTerrain) + delete ms_bakedTerrain; + + ms_bakedTerrain = BakedTerrainReader::create (fileName); +} + +// ---------------------------------------------------------------------- + +void LocationManager::updateObject (NetworkId const & networkId, int const x, int const z, int const radius) +{ + Node * node = 0; + + NodeMap::iterator iter = ms_nodeMap.find (networkId); + if (iter == ms_nodeMap.end ()) + { + //-- add + node = new Node (networkId); + IGNORE_RETURN (ms_nodeMap.insert (std::make_pair (networkId, node))); + } + else + { + //-- update + node = NON_NULL (iter->second); + ms_nodeSphereTree.removeObject (node->getSpatialSubdivisionHandle ()); + } + + node->setSphere (x, z, radius); + node->setSpatialSubdivisionHandle (ms_nodeSphereTree.addObject (node)); +} + +// ---------------------------------------------------------------------- + +void LocationManager::removeObject (NetworkId const & networkId) +{ + NodeMap::iterator iter = ms_nodeMap.find (networkId); + if (iter != ms_nodeMap.end ()) + { + Node * const node = NON_NULL (iter->second); + ms_nodeSphereTree.removeObject (node->getSpatialSubdivisionHandle ()); + delete node; + + ms_nodeMap.erase (iter); + } +} + +// ---------------------------------------------------------------------- + +bool LocationManager::requestLocation (float const searchX, float const searchZ, float const searchRadius, float const locationRadius, bool const checkWater, bool const checkSlope, float & resultX, float & resultZ) +{ + Rectangle2d const searchArea (searchX - searchRadius, searchZ - searchRadius, searchX + searchRadius, searchZ + searchRadius); + + int const chunkSize = ConfigSharedUtility::getChunkSize(); + + ms_offsetList.clear (); + { + //-- generate the offset list + int const logicalWidth = static_cast (searchArea.getWidth () / chunkSize); + int const logicalHeight = static_cast (searchArea.getHeight () / chunkSize); + int const logicalRadius = static_cast (searchRadius / chunkSize); + int const centerX = logicalWidth / 2; + int const centerZ = logicalHeight / 2; + for (int i = 0; i < logicalWidth; ++i) + for (int j = 0; j < logicalHeight; ++j) + { + int const logicalX = i - centerX; + int const logicalZ = j - centerZ; + if (sqr (logicalX) + sqr (logicalZ) < sqr (logicalRadius)) + ms_offsetList.push_back (std::make_pair (logicalX, logicalZ)); + } + + //-- shuffle offset list to randomize rasterization + std::random_shuffle (ms_offsetList.begin (), ms_offsetList.end ()); + } + + bool found = false; + { + for (OffsetList::iterator iter = ms_offsetList.begin (); iter != ms_offsetList.end (); ++iter) + { + //-- start in the upper left corner of the search area + Rectangle2d currentArea (0.f, 0.f, locationRadius * 2.f, locationRadius * 2.f); + currentArea.translate (static_cast (iter->first * chunkSize) + searchX, static_cast (iter->second * chunkSize) + searchZ); + + //-- check the current area for water + if (checkWater && ms_bakedTerrain && ms_bakedTerrain->getWater (currentArea)) + continue; + + //-- check the current area for slope + if (checkSlope && ms_bakedTerrain && ms_bakedTerrain->getSlope (currentArea)) + continue; + + //-- check the current area for objects + float const x = currentArea.getCenter ().x; + float const z = currentArea.getCenter ().y; + if (intersectsObject (x, z, locationRadius)) + continue; + + //-- we found a location + found = true; + resultX = x; + resultZ = z; + } + } + + return found; +} + +// ====================================================================== +// LocationManagerNamespace +// ====================================================================== + +void LocationManagerNamespace::remove () +{ + //-- delete the baked terrain + if (ms_bakedTerrain) + { + delete ms_bakedTerrain; + ms_bakedTerrain = 0; + } + + //-- clear the sphere tree + clearSphereTree (ms_nodeSphereTree); + + //-- clear the node map + IGNORE_RETURN (std::for_each (ms_nodeMap.begin (), ms_nodeMap.end (), PointerDeleterPairSecond ())); + ms_nodeMap.clear (); + + Node::remove (); +} + +// ---------------------------------------------------------------------- + +bool LocationManagerNamespace::intersectsObject (float const x, float const z, float const radius) +{ + NodeVector result; + ms_nodeSphereTree.findInRange (Vector (x, 0.f, z), radius, result); + return !result.empty (); +} + +// ---------------------------------------------------------------------- + +void LocationManagerNamespace::clearSphereTree (NodeSphereTree & sphereTree) +{ + typedef std::vector > NodeSphereList; + NodeSphereList nodeSphereList; + sphereTree.dumpSphereTreeObjs (nodeSphereList); + + NodeSphereList::const_iterator end = nodeSphereList.end (); + for (NodeSphereList::const_iterator iter = nodeSphereList.begin (); iter != end; ++iter) + { + Node * const node = iter->first; + if (node) + { + sphereTree.removeObject (node->getSpatialSubdivisionHandle ()); + node->setSpatialSubdivisionHandle (0); + + delete node; + } + } +} + +// ====================================================================== + diff --git a/engine/shared/library/sharedUtility/src/shared/LocationManager.h b/engine/shared/library/sharedUtility/src/shared/LocationManager.h new file mode 100644 index 00000000..5143af86 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/LocationManager.h @@ -0,0 +1,35 @@ +// ====================================================================== +// +// LocationManager.h +// asommers +// +// copyright 2003, sony online entertainment +// +// ====================================================================== + +#ifndef INCLUDED_LocationManager_H +#define INCLUDED_LocationManager_H + +// ====================================================================== + +class NetworkId; + +// ====================================================================== + +class LocationManager +{ +public: + + static void install (); + + static void setPlanetName (char const * planetName); + + static void updateObject (NetworkId const & networkId, int x, int z, int radius); + static void removeObject (NetworkId const & networkId); + + static bool requestLocation (float searchX, float searchZ, float searchRadius, float locationRadius, bool checkWater, bool checkSlope, float & resultX, float & resultZ); +}; + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/NameGenerator.cpp b/engine/shared/library/sharedUtility/src/shared/NameGenerator.cpp new file mode 100644 index 00000000..657df359 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/NameGenerator.cpp @@ -0,0 +1,650 @@ +// +// FileName.h +// asommers 5-26-99 +// +// copyright 1999, bootprint entertainment +// + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/NameGenerator.h" + +#include "sharedRandom/Random.h" +#include "sharedUtility/DataTable.h" +#include "sharedUtility/DataTableManager.h" + +#include "UnicodeUtils.h" + +#include +#include +#include + +//==================================================================== + +NameGenerator::NameGenerator(const std::string &i_language, const std::string &directory) +{ + std::string datatablePath("datatables/" + directory + "/"); + m_initialized = false; + + if (i_language.empty()) + return; + + DataTable * vowelTable = DataTableManager::getTable(datatablePath+"vowels.iff", true); + DataTable * consonantTable = DataTableManager::getTable(datatablePath+"consonants.iff", true); + DataTable * specialTable = DataTableManager::getTable(datatablePath+"special.iff", true); + DataTable * professionPatternTable = DataTableManager::getTable(datatablePath+"profession_patterns.iff", true); + DataTable * professionTable = DataTableManager::getTable(datatablePath+"profession.iff", true); + DataTable * ruleTable = DataTableManager::getTable(datatablePath+"rules.iff", true); + + if (!ruleTable || + !professionTable || + !professionPatternTable || + !specialTable || + !consonantTable || + !vowelTable) + { + WARNING_STRICT_FATAL(true, ("Couldn't open a naming data table with path %s language %s\n", datatablePath.c_str(), i_language.c_str())); + return; + } + + int ruleRow = findRow(ruleTable, "id", i_language); + if (ruleRow < 0) + { + WARNING(true, ("Couldn't find language [%s] in rule table path %s\n", i_language.c_str(), datatablePath.c_str())); + return; + } + + pushNameTemplate(ruleTable, ruleRow, "fname_"); + pushNameTemplate(ruleTable, ruleRow, "lname_"); + + loadColumn(m_initialConsonants, consonantTable, i_language, "placement", 'b'); + loadColumn(m_medialConsonants, consonantTable, i_language, "placement", 'm'); + loadColumn(m_finalConsonants, consonantTable, i_language, "placement", 'e'); + + loadColumn(m_vowels, vowelTable, i_language); + loadColumn(m_specialSyllables, specialTable, i_language); + loadColumn(m_professionPatterns, professionPatternTable, i_language); + + // now extract all of the word types from profession patterns + std::vector::iterator ppi; + bool inLiteral = false; + for (ppi = m_professionPatterns.begin(); ppi != m_professionPatterns.end(); ++ppi) + { + const std::string &value = ppi->value; + std::string::const_iterator c; + for (c=value.begin(); c!=value.end(); ++c) + { + if (*c == '\\') // skip literals + { + inLiteral = true; + } + else if (*c == '*') // skip + { + } + else + { + if (!inLiteral) + { + std::map *>::iterator wordIter = m_professions.find(*c); + if (wordIter == m_professions.end()) + { + m_professions[*c] = new std::vector(); + loadColumn(*m_professions[*c], professionTable, i_language, "type", *c); + } + } + inLiteral = false; + } + } + } + + if (!m_nameTemplates.empty()) + { + m_initialized = true; + } +} + +//-------------------------------------------------------------------- + +NameGenerator::~NameGenerator() +{ + std::map * >::iterator i; + for (i=m_professions.begin(); i!=m_professions.end(); ++i) + { + delete i->second; + } + m_professions.clear(); +} + +//-------------------------------------------------------------------- + +Unicode::String NameGenerator::generateRandomName() const +{ + if (!m_initialized) + return Unicode::String(); + + std::vector::const_iterator i; + bool first = true; + std::string result; + for (i=m_nameTemplates.begin(); i!=m_nameTemplates.end(); ++i) + { + if (Random::randomReal() < i->m_odds) + { + if (!first) + { + result += " "; + } + result += generateSingleName(*i); + first = false; + } + } + if (first) + { + result = generateSingleName(m_nameTemplates.front()); + } + return Unicode::narrowToWide(capitalizeName(result)); +} + +//-------------------------------------------------------------------- + +int NameGenerator::findRow(DataTable * table, const std::string &column, const std::string &value) +{ + int i; + for (i=0; igetNumRows(); ++i) + { + if (value == table->getStringValue(column, i)) + { + return i; + } + } + return -1; +} + +//-------------------------------------------------------------------- + +void NameGenerator::pushNameTemplate(DataTable * table, int row, const std::string &prefix) +{ + float odds = table->getIntValue(prefix+"chance", row) / 100.f; // don't convert this to *0.01f, we need to insure that int(100)/100.0f equals exactly 1. + if (odds == 0) + return; + + NameTemplate temp; + temp.m_odds = odds; + temp.m_chanceProfession = table->getIntValue(prefix+"chance_profession", row) * 0.01f; + temp.m_syllablesMin = table->getIntValue(prefix+"syllables_min", row); + temp.m_syllablesMax = table->getIntValue(prefix+"syllables_max", row); + temp.m_charsMin = table->getIntValue(prefix+"chars_min", row); + temp.m_charsMax = table->getIntValue(prefix+"chars_max", row); + temp.m_specialCharChance = table->getIntValue(prefix+"special_char_chance", row) * 0.01f; + temp.m_specialChars = table->getStringValue(prefix+"special_char", row); + temp.m_specialCharMax = table->getIntValue(prefix+"special_char_max", row); + temp.m_chanceBeginsSpecial = table->getIntValue(prefix+"chance_begins_special", row) * 0.01f; + temp.m_chanceMedialSpecial = table->getIntValue(prefix+"chance_medial_special", row) * 0.01f; + temp.m_chanceEndsSpecial = table->getIntValue(prefix+"chance_ends_special", row) * 0.01f; + temp.m_maxSpecialSyllables = table->getIntValue(prefix+"max_special_syllables", row); + + m_nameTemplates.push_back(temp); +} + +//-------------------------------------------------------------------- + +std::string NameGenerator::generateSingleName(const NameTemplate &nt) const +{ + if (Random::randomReal() < nt.m_chanceProfession) + return generateProfessionName(nt); + else + return generateRandomName(nt); +} + +//-------------------------------------------------------------------- + +std::string NameGenerator::generateRandomName(const NameTemplate &nt) const +{ + for (;;) + { + int syllables = nt.m_syllablesMin; + while (syllables < nt.m_syllablesMax) + { + float syllableChance = 0.6f - syllables / (nt.m_syllablesMax*2.0f); + if (Random::randomReal() > syllableChance) + break; + ++syllables; + } + + bool nextSyllableIsFirst = true; + std::string result; + int specialCharCount = 0; + std::set selectedSpecialSyllables; + int i; + for (i=0; i(result.size()); + if (resultSize < nt.m_charsMin) + continue; + else if (resultSize > nt.m_charsMax) + continue; + + // continue if we have a lonely special syllable + if (getFragmentType(result) == kSpecial) + continue; + + // now capitalize + return result; + } +} + + +//-------------------------------------------------------------------- + +std::string NameGenerator::generateProfessionName(const NameTemplate &nt) const +{ + std::string professionPattern = selectProfessionPattern(); + if (professionPattern.empty()) + return std::string(); + + std::set usedRoots; + std::string result; + + std::string::const_iterator i; + bool append = false; + for (i=professionPattern.begin(); i!=professionPattern.end(); ++i) + { + if (*i == '\\') + { + ++i; + if (i != professionPattern.end()) + { + result += *i; + } + } + else if (*i == '*') + { + result = appendSyllable(result, generateRandomName(nt)); + } + else + { + for (;;) + { + std::string profession, root; + profession = selectProfession(*i, &root); + if (!root.empty() && usedRoots.find(root) != usedRoots.end()) + continue; + if (append) + { + result = appendSyllable(result, profession); + append = false; + } + else + { + result += profession; + } + usedRoots.insert(root); + break; + } + } + } + + return result; +} + +//-------------------------------------------------------------------- + +void NameGenerator::balanceOdds(std::vector::iterator begin, std::vector::iterator end) +{ + std::sort(begin, end); + + std::vector::iterator i; + float total = 0; + for (i=begin; i!=end; ++i) + total += i->odds; + + float accum = 0; + for (i=begin; i!=end; ++i) + { + float odds = i->odds / total; + accum += odds; + i->odds = accum; + } + // correct rounding errors + if (end > begin) + (end-1)->odds = 1.0f; +} + +//-------------------------------------------------------------------- + +std::string NameGenerator::selectRandomFrom(std::vector::const_iterator begin, std::vector::const_iterator end, std::string * extra) const +{ + if (begin == end) + { + if (extra) + *extra = std::string(); + return std::string(); + } + + float rr = Random::randomReal(); + FATAL(rr >= 1.0f, ("randomReal returned an invalid random number %g\n", rr)); + + std::vector::const_iterator i = std::lower_bound(begin, end, rr, OddsValue::findFloat()); + /* + std::vector::const_iterator i; + for (i=begin; i!=end; ++i) + { + if (rr < i->odds) + { + if (extra) + *extra = i->extra; + return i->value; + } + rr -= i->odds; + } + // just in case of rounding errors + return (end-1)->value; + */ + if (extra) + *extra = i->extra; + return i->value; +} + +//-------------------------------------------------------------------- + +std::string NameGenerator::capitalizeName(const std::string &result) const +{ + std::string capitalizedResult; + std::string::const_iterator capIter; + bool capNext = true; + for (capIter = result.begin(); capIter != result.end(); ++capIter) + { + if (capNext) + { + capitalizedResult += (char)toupper(*capIter); + } + else + { + capitalizedResult += *capIter; + } + if (*capIter == ' ') + { + capNext = true; + } + else if (*capIter == '\'' || *capIter == '-') + { + capNext = Random::randomReal() > 0.5f; + } + else + { + capNext = false; + } + } + return capitalizedResult; +} + +//-------------------------------------------------------------------- + +void NameGenerator::loadColumn(std::vector &result, DataTable * source, const std::string &i_language) +{ + int rows = source->getNumRows(); + int languageColumnIndex = source->findColumnNumber(i_language); + + int i; + for (i=0; igetStringValue(0, i); + + int odds = source->getIntValue(languageColumnIndex, i); + if (odds == 0) + continue; + + OddsValue temp; + temp.value = value; + temp.odds = (float)odds; + result.push_back(temp); + } + + balanceOdds(result.begin(), result.end()); +} + +//-------------------------------------------------------------------- + +void NameGenerator::loadColumn(std::vector &result, DataTable * source, const std::string &i_language, const std::string &maskColumn, const char maskChar) +{ + int rows = source->getNumRows(); + int maskColumnIndex = source->findColumnNumber(maskColumn); + int languageColumnIndex = source->findColumnNumber(i_language); + + int i; + for (i=0; igetStringValue(0, i); + + int odds = source->getIntValue(languageColumnIndex, i); + if (odds == 0) + continue; + + std::string mask = source->getStringValue(maskColumnIndex, i); + if (mask.find(maskChar) == std::string::npos) + continue; + + OddsValue temp; + temp.value = value; + temp.odds = (float)odds; + if (maskColumnIndex >= 2) + { + temp.extra = source->getStringValue(1, i); + } + result.push_back(temp); + } + + balanceOdds(result.begin(), result.end()); +} + +//-------------------------------------------------------------------- + +std::string NameGenerator::appendSyllable(const std::string &left, const std::string &right) const +{ + if (left.empty()) + return right; + + // now we try to merge/simplify repeated letters. If there are too many repeats, we insert + // a remedial vowel or consonant to try and make the word more pronounceable + + // grab the longest ending vowel or consonant string from left + std::string::const_iterator l = left.end(); + eFragmentType leftFragmentType = kMixed; + std::string leftFragment; + while (l != left.begin()) + { + --l; + std::string leftEnd(l, left.end()); + eFragmentType fragment = getFragmentType(leftEnd); + if (fragment == kMixed || fragment == kSpecial) + break; + leftFragment = leftEnd; + leftFragmentType = fragment; + } + + eFragmentType rightFragmentType = kMixed; + std::string rightFragment; + std::string::const_iterator r = right.begin(); + while (r != right.end()) + { + ++r; + std::string rightBegin(right.begin(), r); + eFragmentType fragment = getFragmentType(rightBegin); + if (fragment == kMixed || fragment == kSpecial) + break; + rightFragment = rightBegin; + rightFragmentType = fragment; + } + + if (leftFragmentType != rightFragmentType) + return left + right; + + if (leftFragment == rightFragment) + return left; + + if (leftFragmentType == kConsonant) + return left + selectVowel() + right; + else + return left + selectMedialConsonant() + right; +} + +//-------------------------------------------------------------------- + +NameGenerator::eFragmentType NameGenerator::getFragmentType(const std::string &test) const +{ + if (hasString(m_vowels, test)) + return kVowel; + if (hasString(m_initialConsonants, test)) + return kConsonant; + if (hasString(m_medialConsonants, test)) + return kConsonant; + if (hasString(m_finalConsonants, test)) + return kConsonant; + if (hasString(m_specialSyllables, test)) + return kSpecial; + return kMixed; +} + +//-------------------------------------------------------------------- + +bool NameGenerator::hasString(const std::vector &array, const std::string &test) const +{ + std::vector::const_iterator i; + i = std::lower_bound(array.begin(), array.end(), test, OddsValue::findString()); + if (i == array.end()) + return false; + if (i->value != test) + return false; + return true; +} + +//-------------------------------------------------------------------- + +bool NameGenerator::verifyName(const Unicode::String &name) const +{ + size_t minNameCount = 0; + std::vector::const_iterator i; + for (i = m_nameTemplates.begin(); i!=m_nameTemplates.end(); ++i) + { + if (i->m_odds >= 1.0f) + { + ++minNameCount; + } + } + + int pos=0; + size_t nameindex = 0; + for (;;) + { + if (nameindex >= m_nameTemplates.size()) + return false; + + int newpos = name.find(' ', pos); + int namelength = newpos - pos; + if (newpos == int(Unicode::String::npos)) + { + namelength = name.size() - pos; + } + if (namelength < m_nameTemplates[nameindex].m_charsMin) + return false; + if (namelength > m_nameTemplates[nameindex].m_charsMax) + return false; + pos = newpos + 1; + ++nameindex; + if (newpos == int(Unicode::String::npos)) + { + if (nameindex < minNameCount) + return false; + else + return true; + } + } + return true; // just in case, should always return from the newpos == npos test +} + +//==================================================================== diff --git a/engine/shared/library/sharedUtility/src/shared/NameGenerator.h b/engine/shared/library/sharedUtility/src/shared/NameGenerator.h new file mode 100644 index 00000000..a5c90fbf --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/NameGenerator.h @@ -0,0 +1,165 @@ +// +// FileName.h +// asommers 5-26-99 +// +// copyright 1999, bootprint entertainment +// + +#ifndef INCLUDED_NameGenerator_H +#define INCLUDED_NameGenerator_H + +#include +#include +#include + +class DataTable; + +//==================================================================== + +class NameGenerator +{ +public: + NameGenerator(const std::string &language, const std::string &directory); + virtual ~NameGenerator(); + + virtual bool verifyName(const Unicode::String &name) const; + virtual Unicode::String generateRandomName() const; + + bool getInitialized() const; +private: + bool m_initialized; + + struct NameTemplate + { + float m_odds; + float m_chanceProfession; + int m_syllablesMin; + int m_syllablesMax; + int m_charsMin; + int m_charsMax; + float m_specialCharChance; + std::string m_specialChars; + int m_specialCharMax; + float m_chanceBeginsSpecial; + float m_chanceMedialSpecial; + float m_chanceEndsSpecial; + int m_maxSpecialSyllables; + }; + std::vector m_nameTemplates; + + struct OddsValue + { + std::string value; + float odds; + std::string extra; + bool operator <(const OddsValue &o) const { return value < o.value; } + struct findFloat { bool operator ()(const OddsValue &o, float f) const { return o.odds < f; } }; + struct findString { bool operator ()(const OddsValue &o, const std::string &f) const { return o.value < f; } }; + }; + + std::vector m_initialConsonants; + std::vector m_medialConsonants; + std::vector m_finalConsonants; + std::vector m_vowels; + std::vector m_specialSyllables; + std::vector m_professionPatterns; + std::map * > m_professions; + + std::string selectInitialConsonant(std::string * extra = 0) const; + std::string selectMedialConsonant(std::string * extra = 0) const; + std::string selectFinalConsonant(std::string * extra = 0) const; + std::string selectVowel(std::string * extra = 0) const; + std::string selectSpecialSyllable(std::string * extra = 0) const; + std::string selectProfessionPattern(std::string * extra = 0) const; + std::string selectProfession(char type, std::string * extra = 0) const; + + std::string generateSingleName(const NameTemplate &nt) const; + std::string generateProfessionName(const NameTemplate &nt) const; + std::string generateRandomName(const NameTemplate &nt) const; + std::string capitalizeName(const std::string &name) const; + + int findRow(DataTable * table, const std::string &column, const std::string &value); + void pushNameTemplate(DataTable * table, int row, const std::string &prefix); + void balanceOdds(std::vector::iterator begin, std::vector::iterator end); + std::string selectRandomFrom(std::vector::const_iterator begin, std::vector::const_iterator end, std::string * extra = 0) const; + void loadColumn(std::vector &result, DataTable * source, const std::string &i_language); + void loadColumn(std::vector &result, DataTable * source, const std::string &i_language, const std::string &filterColumn, const char maskChar); + std::string appendSyllable(const std::string &left, const std::string &right) const; + enum eFragmentType + { + kVowel, + kConsonant, + kSpecial, + kMixed + }; + eFragmentType getFragmentType(const std::string &test) const; + bool hasString(const std::vector &array, const std::string &test) const; + + // disable copying + NameGenerator(const NameGenerator &o); + NameGenerator &operator = (const NameGenerator &o); +}; + +//-------------------------------------------------------------------- + +inline std::string NameGenerator::selectInitialConsonant(std::string * extra) const +{ + return selectRandomFrom(m_initialConsonants.begin(), m_initialConsonants.end(), extra); +} + +//-------------------------------------------------------------------- + +inline std::string NameGenerator::selectMedialConsonant(std::string * extra) const +{ + return selectRandomFrom(m_medialConsonants.begin(), m_medialConsonants.end(), extra); +} + +//-------------------------------------------------------------------- + +inline std::string NameGenerator::selectFinalConsonant(std::string * extra) const +{ + return selectRandomFrom(m_finalConsonants.begin(), m_finalConsonants.end(), extra); +} + +//-------------------------------------------------------------------- + +inline std::string NameGenerator::selectVowel(std::string * extra) const +{ + return selectRandomFrom(m_vowels.begin(), m_vowels.end(), extra); +} + +//-------------------------------------------------------------------- + +inline std::string NameGenerator::selectSpecialSyllable(std::string * extra) const +{ + return selectRandomFrom(m_specialSyllables.begin(), m_specialSyllables.end(), extra); +} + +//-------------------------------------------------------------------- + +inline std::string NameGenerator::selectProfessionPattern(std::string * extra) const +{ + return selectRandomFrom(m_professionPatterns.begin(), m_professionPatterns.end(), extra); +} + +//-------------------------------------------------------------------- + +inline std::string NameGenerator::selectProfession(char type, std::string * extra) const +{ + std::map *>::const_iterator i = m_professions.find(type); + if (i==m_professions.end()) + return std::string(); + + return selectRandomFrom(i->second->begin(), i->second->end(), extra); +} + +//-------------------------------------------------------------------- + +inline bool NameGenerator::getInitialized() const +{ + return m_initialized; +} + +//==================================================================== + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/NetworkIdAutoDeltaPackedMap.cpp b/engine/shared/library/sharedUtility/src/shared/NetworkIdAutoDeltaPackedMap.cpp new file mode 100644 index 00000000..88eafbdf --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/NetworkIdAutoDeltaPackedMap.cpp @@ -0,0 +1,82 @@ +// ====================================================================== +// +// NetworkIdAutoDeltaPackedMap.cpp +// copyright (c) 2004 Sony Online Entertainment +// +// ====================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/NetworkIdAutoDeltaPackedMap.h" + +#include "sharedFoundation/NetworkIdArchive.h" + +// ====================================================================== + +namespace Archive +{ + + void AutoDeltaPackedMap::pack(ByteStream & target, const std::string & buffer) + { + char temp[200]; + char value[200]; + Command c; + + Archive::put(target, countCharacter(buffer,':')); + Archive::put(target, static_cast(0)); // baselineCommandCount + + int tempPos = 0; + for (std::string::const_iterator i=buffer.begin(); i!=buffer.end(); ++i) + { + if (*i==':') + { + temp[tempPos]='\0'; + sscanf(temp,"%i %s",&c.key, value); + c.value=NetworkId(std::string(value)); // because there's no constructor that takes a char* + Archive::put(target, static_cast(Command::ADD)); + Archive::put(target, c.key); + Archive::put(target, c.value); + tempPos=0; + } + else + { + temp[tempPos++]=*i; + } + } + } + + // ====================================================================== + + void AutoDeltaPackedMap::unpack(ReadIterator & source, std::string & buffer) + { + char temp[200]; + + Command c; + size_t commandCount; + size_t baselineCommandCount; + + Archive::get(source, commandCount); + Archive::get(source, baselineCommandCount); + + if (commandCount==0) + { + buffer=' '; // An empty map is represented as a single space, because a completely empty string is used to mean "no change" + } + else + { + for (size_t i = 0; i < commandCount; ++i) + { + Archive::get(source, c.cmd); + Archive::get(source, c.key); + Archive::get(source, c.value); + + snprintf(temp, sizeof(temp)-1, "%i %s:", c.key, c.value.getValueString().c_str()); + + temp[sizeof(temp)-1]='\0'; + buffer+=temp; + } + } + } + +} + +// ====================================================================== diff --git a/engine/shared/library/sharedUtility/src/shared/NetworkIdAutoDeltaPackedMap.h b/engine/shared/library/sharedUtility/src/shared/NetworkIdAutoDeltaPackedMap.h new file mode 100644 index 00000000..85de579d --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/NetworkIdAutoDeltaPackedMap.h @@ -0,0 +1,26 @@ +// ====================================================================== +// +// NetworkIdAutoDeltaPackedMap.h +// copyright (c) 2004 Sony Online Entertainment +// +// ====================================================================== + +#ifndef INCLUDED_NetworkIdAutoDeltaPackedMap_H +#define INCLUDED_NetworkIdAutoDeltaPackedMap_H + +// ====================================================================== + +#include "Archive/AutoDeltaPackedMap.h" +#include "sharedFoundation/NetworkId.h" + +// ====================================================================== + +namespace Archive +{ + template <> void AutoDeltaPackedMap::pack(ByteStream & target, const std::string & buffer); + template <> void AutoDeltaPackedMap::unpack(ReadIterator & source, std::string & buffer); +} + +// ====================================================================== + +#endif diff --git a/engine/shared/library/sharedUtility/src/shared/OptionManager.cpp b/engine/shared/library/sharedUtility/src/shared/OptionManager.cpp new file mode 100644 index 00000000..2ba423ed --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/OptionManager.cpp @@ -0,0 +1,782 @@ +//=================================================================== +// +// OptionManager.cpp +// asommers +// +// copyright 2002, sony online entertainment +// +//=================================================================== + +#include "sharedUtility/FirstSharedUtility.h" +#include "sharedUtility/OptionManager.h" + +#include "sharedFoundation/ConfigFile.h" +#include "sharedFoundation/PointerDeleter.h" +#include "sharedFile/Iff.h" +#include "sharedFile/TreeFile.h" +#include "sharedUtility/ConfigSharedUtility.h" +#include "UnicodeUtils.h" + +#include +#include +#include + +//=================================================================== +// OptionManagerNamespace +//=================================================================== + +namespace OptionManagerNamespace +{ + const Tag TAG_BOOL = TAG (B,O,O,L); + const Tag TAG_FLT = TAG3 (F,L,T); + const Tag TAG_INT = TAG3 (I,N,T); + const Tag TAG_OPTN = TAG (O,P,T,N); + const Tag TAG_STDS = TAG (S,T,D,S); + const Tag TAG_UNIS = TAG (U,N,I,S); + + bool ms_optionManagersEnabled = true; +} + +using namespace OptionManagerNamespace; + +//=================================================================== +// PUBLIC Option +//=================================================================== + +OptionManager::Option::Option (Option::Type const type) : + m_version (0), + m_name (0), + m_section (0), + m_void (0), + m_type (type) +{ +} + +//------------------------------------------------------------------- + +OptionManager::Option::~Option () +{ +} + +//------------------------------------------------------------------- + +OptionManager::Option::Option (Option const & rhs) : + m_version (rhs.m_version), + m_name (rhs.m_name), + m_section (rhs.m_section), + m_void (rhs.m_void), + m_type (rhs.m_type) +{ +} + +//---------------------------------------------------------------------- + +OptionManager::Option & OptionManager::Option::operator= (Option const & rhs) +{ + m_version = rhs.m_version; + m_name = rhs.m_name; + m_section = rhs.m_section; + m_void = rhs.m_void; + m_type = rhs.m_type; + + return *this; +} + +//------------------------------------------------------------------- + +OptionManager::Option::Type OptionManager::Option::getType () const +{ + return m_type; +} + +//------------------------------------------------------------------- + +void OptionManager::Option::debugDump (char const * operation) const +{ + UNREF(operation); + + switch (m_type) + { + case T_bool: + DEBUG_REPORT_LOG (true, ("OptionManager::Option %s (ver %d) [%s] %s=%s\n", operation, m_version, m_section, m_name, *m_bool ? "true" : "false")); + break; + + case T_float: + DEBUG_REPORT_LOG (true, ("OptionManager::Option %s (ver %d) [%s] %s=%1.5f\n", operation, m_version, m_section, m_name, *m_float)); + break; + + case T_int: + DEBUG_REPORT_LOG (true, ("OptionManager::Option %s (ver %d) [%s] %s=%i\n", operation, m_version, m_section, m_name, *m_int)); + break; + + case T_stdString: + DEBUG_REPORT_LOG (true, ("OptionManager::Option %s (ver %d) [%s] %s=%s\n", operation, m_version, m_section, m_name, m_stdString->c_str ())); + break; + + case T_unicodeString: + DEBUG_REPORT_LOG (true, ("OptionManager::Option %s (ver %d) [%s] %s=%s\n", operation, m_version, m_section, m_name, Unicode::wideToNarrow(*m_unicodeString).c_str ())); + break; + + default: + break; + } +} + +//=================================================================== +// STATIC PUBLIC OptionManager +//=================================================================== + +void OptionManager::setOptionManagersEnabled(bool enabled) +{ + ms_optionManagersEnabled = enabled; +} + +//---------------------------------------------------------------------- + + +OptionManager::OptionManager () : + m_registeredOptionList (new OptionList), + m_savedOptionList (new OptionList), + m_stringList (new StringList), + m_boolList (new BoolList), + m_floatList (new FloatList), + m_intList (new IntList), + m_stdStringList (new StdStringList), + m_unicodeStringList (new UnicodeStringList) +{ +} + +//------------------------------------------------------------------- + +OptionManager::~OptionManager () +{ + clearSavedLists (); + + delete m_registeredOptionList; + delete m_savedOptionList; + delete m_stringList; + delete m_boolList; + delete m_floatList; + delete m_intList; + delete m_stdStringList; + delete m_unicodeStringList; +} + +//------------------------------------------------------------------- + +void OptionManager::load (char const * const fileName) +{ + if (!ms_optionManagersEnabled) + return; + + if (TreeFile::exists(fileName)) + { + if (Iff::isValid(fileName)) + { + Iff iff; + if (iff.open (fileName, true)) + { + if (iff.getCurrentName() == TAG_OPTN) + { + load (iff); + } + else + { + REPORT_LOG (true, ("OptionManager::load: %s not a valid options Iff\n", fileName)); + } + } + } + else + { + REPORT_LOG (true, ("OptionManager::load: %s not a valid Iff\n", fileName)); + } + } + else + { + REPORT_LOG (true, ("OptionManager::load: %s not found\n", fileName)); + } + + if (ConfigSharedUtility::getLogOptionManager()) + { + OptionList::iterator iter = m_savedOptionList->begin (); + for (; iter != m_savedOptionList->end (); ++iter) + iter->debugDump ("load"); + } +} + +//------------------------------------------------------------------- + +void OptionManager::save (char const * const fileName) +{ + if (!ms_optionManagersEnabled) + return; + + Iff iff (1024); + save (iff); + if (!iff.write (fileName, true)) + DEBUG_REPORT_LOG (true, ("OptionManager::save: could not write %s\n", fileName)); + + if (ConfigSharedUtility::getLogOptionManager()) + { + OptionList::iterator iter = m_registeredOptionList->begin (); + for (; iter != m_registeredOptionList->end (); ++iter) + iter->debugDump ("save"); + } +} + +//---------------------------------------------------------------------- + +void OptionManager::clearSavedLists () +{ + m_savedOptionList->clear (); + + std::for_each (m_stringList->begin (), m_stringList->end (), ArrayPointerDeleter ()); + m_stringList->clear (); + + std::for_each (m_boolList->begin (), m_boolList->end (), PointerDeleter ()); + m_boolList->clear (); + + std::for_each (m_floatList->begin (), m_floatList->end (), PointerDeleter ()); + m_floatList->clear (); + + std::for_each (m_intList->begin (), m_intList->end (), PointerDeleter ()); + m_intList->clear (); + + std::for_each (m_stdStringList->begin (), m_stdStringList->end (), PointerDeleter ()); + m_stdStringList->clear (); + + std::for_each (m_unicodeStringList->begin (), m_unicodeStringList->end (), PointerDeleter ()); + m_unicodeStringList->clear (); +} + +//------------------------------------------------------------------- + +void OptionManager::registerOption (bool & variable, char const * const section, char const * const name, const int version) +{ + Option option (Option::T_bool); + option.m_bool = &variable; + option.m_section = section; + option.m_name = name; + option.m_version = version; + m_registeredOptionList->push_back (option); + + variable = findBool (section, name, variable, version); +} + +//------------------------------------------------------------------- + +void OptionManager::registerOption (float & variable, char const * const section, char const * const name, const int version) +{ + Option option (Option::T_float); + option.m_float = &variable; + option.m_section = section; + option.m_name = name; + option.m_version = version; + m_registeredOptionList->push_back (option); + + variable = findFloat (section, name, variable, version); +} + +//------------------------------------------------------------------- + +void OptionManager::registerOption (int & variable, char const * const section, char const * const name, const int version) +{ + Option option (Option::T_int); + option.m_int = &variable; + option.m_section = section; + option.m_name = name; + option.m_version = version; + m_registeredOptionList->push_back (option); + + variable = findInt (section, name, variable, version); +} + +//---------------------------------------------------------------------- + +void OptionManager::registerOption (std::string & variable, char const * const section, char const * const name, const int version) +{ + Option option (Option::T_stdString); + option.m_stdString = &variable; + option.m_section = section; + option.m_name = name; + option.m_version = version; + m_registeredOptionList->push_back (option); + + variable = findStdString (section, name, variable, version); +} + + +//---------------------------------------------------------------------- + +void OptionManager::registerOption (Unicode::String & variable, char const * const section, char const * const name, const int version) +{ + Option option (Option::T_unicodeString); + option.m_unicodeString = &variable; + option.m_section = section; + option.m_name = name; + option.m_version = version; + m_registeredOptionList->push_back (option); + + variable = findUnicodeString (section, name, variable, version); +} + +//=================================================================== +// STATIC PRIVATE OptionManager +//=================================================================== + +bool OptionManager::findBool (char const * const section, char const * const name, bool const defaultValue, const int version) +{ + bool value = defaultValue; + + OptionList::iterator iter = m_savedOptionList->begin (); + for (; iter != m_savedOptionList->end (); ++iter) + { + const Option& option = *iter; + if (option.getType () == Option::T_bool && strcmp (section, option.m_section) == 0 && strcmp (name, option.m_name) == 0 && option.m_version == version) + { + value = *option.m_bool; + break; + } + } + + if (section && name && ConfigFile::isInstalled ()) + return ConfigFile::getKeyBool (section, name, value, true); + + return value; +} + +//---------------------------------------------------------------------- + +float OptionManager::findFloat (char const * const section, char const * const name, float const defaultValue, const int version) +{ + float value = defaultValue; + + OptionList::iterator iter = m_savedOptionList->begin (); + for (; iter != m_savedOptionList->end (); ++iter) + { + const Option& option = *iter; + if (option.getType () == Option::T_float && strcmp (section, option.m_section) == 0 && strcmp (name, option.m_name) == 0 && option.m_version == version) + { + value = *option.m_float; + break; + } + } + + if (section && name && ConfigFile::isInstalled ()) + return ConfigFile::getKeyFloat (section, name, value, true); + + return value; +} + +//---------------------------------------------------------------------- + +int OptionManager::findInt (char const * const section, char const * const name, int const defaultValue, const int version) +{ + int value = defaultValue; + + OptionList::iterator iter = m_savedOptionList->begin (); + for (; iter != m_savedOptionList->end (); ++iter) + { + const Option& option = *iter; + if (option.getType () == Option::T_int && strcmp (section, option.m_section) == 0 && strcmp (name, option.m_name) == 0 && option.m_version == version) + { + value = *option.m_int; + break; + } + } + + if (section && name && ConfigFile::isInstalled ()) + return ConfigFile::getKeyInt (section, name, value, true); + + return value; +} + +//---------------------------------------------------------------------- + +std::string OptionManager::findStdString (char const * const section, char const * const name, std::string const & defaultValue, const int version) +{ + std::string value = defaultValue; + + OptionList::iterator iter = m_savedOptionList->begin (); + for (; iter != m_savedOptionList->end (); ++iter) + { + const Option& option = *iter; + if (option.getType () == Option::T_stdString && strcmp (section, option.m_section) == 0 && strcmp (name, option.m_name) == 0 && option.m_version == version) + { + NOT_NULL (option.m_stdString); + value = *option.m_stdString; + break; + } + } + + if (section && name && ConfigFile::isInstalled ()) + { + const char * const str = ConfigFile::getKeyString (section, name, value.c_str (), true); + if (str) + return std::string (str); + } + + return value; +} + +//---------------------------------------------------------------------- + +Unicode::String OptionManager::findUnicodeString (char const * const section, char const * const name, Unicode::String const & defaultValue, const int version) +{ + Unicode::String value = defaultValue; + + OptionList::iterator iter = m_savedOptionList->begin (); + for (; iter != m_savedOptionList->end (); ++iter) + { + const Option& option = *iter; + if (option.getType () == Option::T_unicodeString && strcmp (section, option.m_section) == 0 && strcmp (name, option.m_name) == 0 && option.m_version == version) + { + NOT_NULL (option.m_unicodeString); + value = *option.m_unicodeString; + break; + } + } + + // No config file search for Unicode::String + + return value; +} + +//---------------------------------------------------------------------- + +void OptionManager::load (Iff & iff) +{ + iff.enterForm (TAG_OPTN); + + int version = 0; + + switch (iff.getCurrentName ()) + { + case TAG_0000: + case TAG_0001: + WARNING (true, ("OptionManager::load: detected old version (below 0002), skipping load...")); + break; + + // loading of version 0002 still supported in order to convert to version 0003 on save + case TAG_0002: + version = 2; + break; + + case TAG_0003: + version = 3; + break; + + default: + { + char tagBuffer [5]; + ConvertTagToString (iff.getCurrentName (), tagBuffer); + + char buffer [128]; + iff.formatLocation (buffer, sizeof (buffer)); + DEBUG_FATAL (true, ("OptionManager::load - invalid version %s/%s", buffer, tagBuffer)); + } + break; + } + + if (version >= 2) + { + loadVersion(iff, version); + } + + iff.exitForm (TAG_OPTN, true); +} + +//------------------------------------------------------------------- + +void OptionManager::save (Iff & iff) +{ + iff.insertForm (TAG_OPTN); + + iff.insertForm (TAG_0003); + + OptionList::iterator iter = m_registeredOptionList->begin (); + for (; iter != m_registeredOptionList->end (); ++iter) + { + const Option& option = *iter; + + switch (option.getType ()) + { + case Option::T_bool: + { + iff.insertChunk (TAG_BOOL); + + iff.insertChunkData (static_cast (*option.m_bool ? 1 : 0)); + iff.insertChunkString (option.m_section); + iff.insertChunkString (option.m_name); + iff.insertChunkData (option.m_version); + + iff.exitChunk (TAG_BOOL); + } + break; + + case Option::T_float: + { + iff.insertChunk (TAG_FLT); + + iff.insertChunkData (*option.m_float); + iff.insertChunkString (option.m_section); + iff.insertChunkString (option.m_name); + iff.insertChunkData (option.m_version); + + iff.exitChunk (TAG_FLT); + } + break; + + case Option::T_int: + { + iff.insertChunk (TAG_INT); + + iff.insertChunkData (*option.m_int); + iff.insertChunkString (option.m_section); + iff.insertChunkString (option.m_name); + iff.insertChunkData (option.m_version); + + iff.exitChunk (TAG_INT); + } + break; + + case Option::T_stdString: + { + iff.insertChunk (TAG_STDS); + + iff.insertChunkString (option.m_stdString->c_str ()); + iff.insertChunkString (option.m_section); + iff.insertChunkString (option.m_name); + iff.insertChunkData (option.m_version); + + iff.exitChunk (TAG_STDS); + } + break; + + case Option::T_unicodeString: + { + iff.insertChunk (TAG_UNIS); + + iff.insertChunkString (*option.m_unicodeString); + iff.insertChunkString (option.m_section); + iff.insertChunkString (option.m_name); + iff.insertChunkData (option.m_version); + + iff.exitChunk (TAG_UNIS); + } + break; + + default: + break; + } + } + + iff.exitForm (TAG_0003); + + iff.exitForm (TAG_OPTN); +} + +//------------------------------------------------------------------- + +void OptionManager::loadVersion(Iff & iff, const int version) +{ + clearSavedLists (); + + Tag versionTag = iff.getCurrentName(); + + iff.enterForm (versionTag); + + while (iff.getNumberOfBlocksLeft ()) + { + switch (iff.getCurrentName ()) + { + case TAG_BOOL: + { + iff.enterChunk (TAG_BOOL); + + Option option (Option::T_bool); + option.m_bool = new bool; + *option.m_bool = iff.read_bool8 (); + option.m_section = iff.read_string (); + option.m_name = iff.read_string (); + if (version > 2) + { + option.m_version = iff.read_int32 (); + } + m_savedOptionList->push_back (option); + + //-- save these for deleting later + m_stringList->push_back (const_cast (option.m_section)); + m_stringList->push_back (const_cast (option.m_name)); + m_boolList->push_back (option.m_bool); + + iff.exitChunk (TAG_BOOL); + } + break; + + case TAG_FLT: + { + iff.enterChunk (TAG_FLT); + + Option option (Option::T_float); + option.m_float = new float; + *option.m_float = iff.read_float (); + option.m_section = iff.read_string (); + option.m_name = iff.read_string (); + if (version > 2) + { + option.m_version = iff.read_int32 (); + } + m_savedOptionList->push_back (option); + + //-- save these for deleting later + m_stringList->push_back (const_cast (option.m_section)); + m_stringList->push_back (const_cast (option.m_name)); + m_floatList->push_back (option.m_float); + + iff.exitChunk (TAG_FLT); + } + break; + + case TAG_INT: + { + iff.enterChunk (TAG_INT); + + Option option (Option::T_int); + option.m_int = new int; + *option.m_int = iff.read_int32 (); + option.m_section = iff.read_string (); + option.m_name = iff.read_string (); + if (version > 2) + { + option.m_version = iff.read_int32 (); + } + m_savedOptionList->push_back (option); + + //-- save these for deleting later + m_stringList->push_back (const_cast (option.m_section)); + m_stringList->push_back (const_cast (option.m_name)); + m_intList->push_back (option.m_int); + + iff.exitChunk (TAG_INT); + } + break; + + case TAG_STDS: + { + iff.enterChunk (TAG_STDS); + + Option option (Option::T_stdString); + option.m_stdString = new std::string; + *option.m_stdString = iff.read_stdstring (); + option.m_section = iff.read_string (); + option.m_name = iff.read_string (); + if (version > 2) + { + option.m_version = iff.read_int32 (); + } + m_savedOptionList->push_back (option); + + //-- save these for deleting later + m_stringList->push_back (const_cast (option.m_section)); + m_stringList->push_back (const_cast (option.m_name)); + m_stdStringList->push_back (option.m_stdString); + + iff.exitChunk (TAG_STDS); + } + break; + + case TAG_UNIS: + { + iff.enterChunk (TAG_UNIS); + + Option option (Option::T_unicodeString); + option.m_unicodeString = new Unicode::String; + *option.m_unicodeString = iff.read_unicodeString (); + option.m_section = iff.read_string (); + option.m_name = iff.read_string (); + if (version > 2) + { + option.m_version = iff.read_int32 (); + } + m_savedOptionList->push_back (option); + + //-- save these for deleting later + m_stringList->push_back (const_cast (option.m_section)); + m_stringList->push_back (const_cast (option.m_name)); + m_unicodeStringList->push_back (option.m_unicodeString); + + iff.exitChunk (TAG_UNIS); + } + break; + + default: + { + iff.enterChunk (); + iff.exitChunk (true); + } + } + } + + iff.exitForm (versionTag); + + //-- copy the loaded values into any registered values + + copyOptionListIntersection (*m_savedOptionList, *m_registeredOptionList); +} + +//---------------------------------------------------------------------- + + /* + * Copy the values of options that are shared by both lists. + * The size of dst is unchanged. + */ + + void OptionManager::copyOptionListIntersection (const OptionList & src, OptionList & dst) + { + for (OptionList::const_iterator it = src.begin (); it != src.end (); ++it) + { + const Option & sopt = *it; + + for (OptionList::iterator rit = dst.begin (); rit != dst.end (); ++rit) + { + const Option & dopt = *rit; + + if (dopt.m_name && sopt.m_name && !strcmp (dopt.m_name, sopt.m_name) && + dopt.m_section && sopt.m_section && !strcmp (dopt.m_section, sopt.m_section) && + dopt.m_type == sopt.m_type && + dopt.m_version == sopt.m_version) // default value takes precedence when version changes + { + switch (dopt.m_type) + { + case Option::T_bool: + NOT_NULL (dopt.m_bool); + NOT_NULL (sopt.m_bool); + *dopt.m_bool = *sopt.m_bool; + break; + case Option::T_float: + NOT_NULL (dopt.m_float); + NOT_NULL (sopt.m_float); + *dopt.m_float = *sopt.m_float; + break; + case Option::T_int: + NOT_NULL (dopt.m_int); + NOT_NULL (sopt.m_int); + *dopt.m_int = *sopt.m_int; + break; + case Option::T_stdString: + NOT_NULL (dopt.m_stdString); + NOT_NULL (sopt.m_stdString); + *dopt.m_stdString = *sopt.m_stdString; + break; + case Option::T_unicodeString: + NOT_NULL (dopt.m_unicodeString); + NOT_NULL (sopt.m_unicodeString); + *dopt.m_unicodeString = *sopt.m_unicodeString; + break; + } + } + } + } + } +//=================================================================== diff --git a/engine/shared/library/sharedUtility/src/shared/OptionManager.h b/engine/shared/library/sharedUtility/src/shared/OptionManager.h new file mode 100644 index 00000000..454f6d19 --- /dev/null +++ b/engine/shared/library/sharedUtility/src/shared/OptionManager.h @@ -0,0 +1,138 @@ +//=================================================================== +// +// OptionManager.h +// asommers +// +// copyright 2002, sony online entertainment +// +//=================================================================== + +#ifndef INCLUDED_OptionManager_H +#define INCLUDED_OptionManager_H + +//=================================================================== + +class Iff; + +//=================================================================== + +class OptionManager +{ +public: + + OptionManager (); + ~OptionManager (); + + static void setOptionManagersEnabled(bool enabled); + + void load (char const * fileName); + void save (char const * fileName); + + void registerOption (bool & variable, char const * section, char const * name, const int version = 0); + void registerOption (float & variable, char const * section, char const * name, const int version = 0); + void registerOption (int & variable, char const * section, char const * name, const int version = 0); + void registerOption (std::string & variable, char const * section, char const * name, const int version = 0); + void registerOption (Unicode::String & variable, char const * section, char const * name, const int version = 0); + + float findFloat(char const * section, char const * name, float defaultValue, const int version = 0); + +private: + + class Option + { + friend class OptionManager; + + public: + + enum Type + { + T_bool, + T_float, + T_int, + T_stdString, + T_unicodeString + }; + + public: + + explicit Option (Type type); + ~Option (); + Option (Option const & rhs); + + Type getType () const; + + void debugDump (char const * operation) const; + + Option & operator= (Option const & rhs); + + public: + + int m_version; + char const * m_name; + char const * m_section; + + union + { + bool * m_bool; + float * m_float; + int * m_int; + std::string * m_stdString; + void * m_void; + Unicode::String * m_unicodeString; + }; + + private: + + Option (); + + private: + + Type m_type; + }; + + typedef stdvector