diff --git a/Assets/Engine/Config/engine_core.thread_config b/Assets/Engine/Config/engine_core.thread_config deleted file mode 100644 index f9183d9174..0000000000 --- a/Assets/Engine/Config/engine_core.thread_config +++ /dev/null @@ -1,402 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Assets/Engine/Config/engine_sandbox.thread_config b/Assets/Engine/Config/engine_sandbox.thread_config deleted file mode 100644 index 7c0dc00b71..0000000000 --- a/Assets/Engine/Config/engine_sandbox.thread_config +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake index f9d1e60dda..ffcaf7293a 100644 --- a/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake @@ -10,6 +10,4 @@ # set(GEM_DEPENDENCIES - Gem::Atom_RHI_Metal.Private - Gem::Atom_RHI_Null.Private ) \ No newline at end of file diff --git a/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake index 2e9d450ab8..ffcaf7293a 100644 --- a/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake @@ -10,10 +10,4 @@ # set(GEM_DEPENDENCIES - Gem::Atom_RHI_Null.Private - Gem::Atom_RHI_Null.Builders - Gem::Atom_RHI_Metal.Private - Gem::Atom_RHI_Metal.Builders - Gem::Atom_RHI_Vulkan.Builders - Gem::Atom_RHI_DX12.Builders ) \ No newline at end of file diff --git a/AutomatedTesting/Gem/Code/Platform/Windows/runtime_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Windows/runtime_dependencies.cmake index 0a1541bcfc..ffcaf7293a 100644 --- a/AutomatedTesting/Gem/Code/Platform/Windows/runtime_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/Platform/Windows/runtime_dependencies.cmake @@ -10,7 +10,4 @@ # set(GEM_DEPENDENCIES - Gem::Atom_RHI_Vulkan.Private - Gem::Atom_RHI_DX12.Private - Gem::Atom_RHI_Null.Private ) \ No newline at end of file diff --git a/AutomatedTesting/Gem/Code/Platform/Windows/tool_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Windows/tool_dependencies.cmake index ddd3bfa6a7..933dd7927b 100644 --- a/AutomatedTesting/Gem/Code/Platform/Windows/tool_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/Platform/Windows/tool_dependencies.cmake @@ -11,11 +11,4 @@ set(GEM_DEPENDENCIES Gem::QtForPython.Editor - Gem::Atom_RHI_Vulkan.Private - Gem::Atom_RHI_Vulkan.Builders - Gem::Atom_RHI_DX12.Private - Gem::Atom_RHI_DX12.Builders - Gem::Atom_RHI_Null.Private - Gem::Atom_RHI_Null.Builders - Gem::Atom_RHI_Metal.Builders ) \ No newline at end of file diff --git a/AutomatedTesting/Gem/Code/runtime_dependencies.cmake b/AutomatedTesting/Gem/Code/runtime_dependencies.cmake index 62a6ed7f8c..280c25bcf7 100644 --- a/AutomatedTesting/Gem/Code/runtime_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/runtime_dependencies.cmake @@ -42,17 +42,7 @@ set(GEM_DEPENDENCIES Gem::SurfaceData Gem::GradientSignal Gem::Vegetation - Gem::Atom_RHI.Private - Gem::Atom_RPI.Private - Gem::Atom_Feature_Common - Gem::Atom_Bootstrap - Gem::Atom_Component_DebugCamera - Gem::AtomImGuiTools - Gem::AtomLyIntegration_CommonFeatures - Gem::EMotionFX_Atom - Gem::ImguiAtom Gem::Atom_AtomBridge - Gem::AtomFont Gem::NvCloth Gem::Blast ) diff --git a/AutomatedTesting/Gem/Code/tool_dependencies.cmake b/AutomatedTesting/Gem/Code/tool_dependencies.cmake index a6bbeee350..fc50707c12 100644 --- a/AutomatedTesting/Gem/Code/tool_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/tool_dependencies.cmake @@ -50,24 +50,9 @@ set(GEM_DEPENDENCIES Gem::Vegetation.Editor Gem::GraphModel.Editor Gem::LandscapeCanvas.Editor - Gem::Atom_RHI.Private Gem::EMotionFX.Editor - Gem::Atom_RPI.Builders - Gem::Atom_RPI.Editor - Gem::Atom_Feature_Common.Builders - Gem::Atom_Feature_Common.Editor Gem::ImGui.Editor - Gem::Atom_Bootstrap - Gem::Atom_Asset_Shader.Builders - Gem::Atom_Component_DebugCamera - Gem::AtomImGuiTools - Gem::AtomLyIntegration_CommonFeatures.Editor - Gem::EMotionFX_Atom.Editor - Gem::ImageProcessingAtom.Editor Gem::Atom_AtomBridge.Editor - Gem::ImguiAtom - Gem::AtomFont - Gem::AtomToolsFramework.Editor Gem::NvCloth.Editor Gem::Blast.Editor ) diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py index 1ccfc43585..d0c6fc3c5a 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py @@ -82,42 +82,34 @@ class TestDistanceBetweenFilterComponentOverrides(EditorTestHelper): editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, 'Configuration|Area System Settings|Sector Point Density', 16) - # Add a Vegetation Debugger component to allow area refreshes - hydra.add_level_component("Vegetation Debugger") - # 5) Add a Vegetation Distance Between Filter, toggle overrides on both the component and descriptor, # and verify initial instance counts are accurate spawner_entity.add_component("Vegetation Distance Between Filter") spawner_entity.get_set_test(3, "Configuration|Allow Per-Item Overrides", True) spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Override Enabled", True) - general.run_console('veg_debugClearAllAreas') - self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 2), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 2), 5.0) and \ - self.test_success + num_expected = 16 * 16 + initial_success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + self.test_success = self.test_success and initial_success # 6) Change Radius Min to 1.0, refresh, and verify instance counts are accurate spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Radius Min", 1.0) - general.run_console('veg_debugClearAllAreas') - self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 1), 5.0) and \ - self.test_success + point_a_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) + point_b_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) + point_c_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 1), 5.0) + self.test_success = self.test_success and point_a_success and point_b_success and point_c_success # 7) Change Radius Min to 2.0, refresh, and verify instance counts are accurate spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Radius Min", 2.0) - general.run_console('veg_debugClearAllAreas') - self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 0), 5.0) and \ - self.test_success + point_a_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) + point_b_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) + point_c_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 0), 5.0) + self.test_success = self.test_success and point_a_success and point_b_success and point_c_success # 8) Change Radius Min to 16.0, refresh, and verify instance counts are accurate, only a single instance should plant spawner_entity.get_set_test(2, "Configuration|Embedded Assets|[0]|Distance Between Filter (Radius)|Radius Min", 16.0) - general.run_console('veg_debugClearAllAreas') num_expected_instances = 1 final_check_success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) - self.test_success = final_check_success and self.test_success + self.test_success = self.test_success and final_check_success test = TestDistanceBetweenFilterComponentOverrides() diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py index 09c5fd63cf..d342afd7ca 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py @@ -80,35 +80,29 @@ class TestDistanceBetweenFilterComponent(EditorTestHelper): editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", veg_system_settings_component, 'Configuration|Area System Settings|Sector Point Density', 16) - # Add a Vegetation Debugger component to allow area refreshes - hydra.add_level_component("Vegetation Debugger") - # 5) Add a Vegetation Distance Between Filter and verify initial instance counts are accurate spawner_entity.add_component("Vegetation Distance Between Filter") - self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 2), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 2), 5.0) and \ - self.test_success + num_expected = 16 * 16 + num_expected = 16 * 16 + initial_success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected), 5.0) + self.test_success = self.test_success and initial_success # 6) Change Radius Min to 1.0, refresh, and verify instance counts are accurate spawner_entity.get_set_test(3, "Configuration|Radius Min", 1.0) - general.run_console('veg_debugClearAllAreas') - self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 1), 5.0) and \ - self.test_success + point_a_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) + point_b_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) + point_c_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 1), 5.0) + self.test_success = self.test_success and point_a_success and point_b_success and point_c_success # 7) Change Radius Min to 2.0, refresh, and verify instance counts are accurate spawner_entity.get_set_test(3, "Configuration|Radius Min", 2.0) - general.run_console('veg_debugClearAllAreas') - self.test_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) and \ - self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 0), 5.0) and \ - self.test_success + point_a_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_a, 0.5, 1), 5.0) + point_b_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_b, 0.5, 0), 5.0) + point_c_success = self.wait_for_condition(lambda: dynveg.validate_instance_count(instance_query_point_c, 0.5, 0), 5.0) + self.test_success = self.test_success and point_a_success and point_b_success and point_c_success # 8) Change Radius Min to 16.0, refresh, and verify instance counts are accurate spawner_entity.get_set_test(3, "Configuration|Radius Min", 16.0) - general.run_console('veg_debugClearAllAreas') num_expected_instances = 1 final_check_success = self.wait_for_condition(lambda: dynveg.validate_instance_count_in_entity_shape(spawner_entity.id, num_expected_instances), 5.0) self.test_success = final_check_success and self.test_success diff --git a/AutomatedTesting/Slices/1m_Cube.slice b/AutomatedTesting/Slices/1m_Cube.slice index 5ace34bd10..b31869c7fa 100644 --- a/AutomatedTesting/Slices/1m_Cube.slice +++ b/AutomatedTesting/Slices/1m_Cube.slice @@ -39,6 +39,7 @@ + @@ -61,7 +62,7 @@ - + @@ -122,38 +123,26 @@ - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - + diff --git a/AutomatedTesting/sounds/.gitignore b/AutomatedTesting/sounds/.gitignore new file mode 100644 index 0000000000..80c66daa1c --- /dev/null +++ b/AutomatedTesting/sounds/.gitignore @@ -0,0 +1,8 @@ +.backup/ +.cache/ +*.log +*.akd +*.dat +*.prof +*.validationcache +*.wsettings \ No newline at end of file diff --git a/AutomatedTesting/sounds/wwise/Init.bnk b/AutomatedTesting/sounds/wwise/Init.bnk index 530a7e007f..292288ff26 100644 --- a/AutomatedTesting/sounds/wwise/Init.bnk +++ b/AutomatedTesting/sounds/wwise/Init.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:803ddb37eb27cba666f9320c2f5905219193e1a069d1144a64df92fab0e31878 -size 1243 +oid sha256:c9e6a4ef3d2f33f31827ce2bba2ed8bad87324f3fe86f79389ef2956b304a924 +size 1180 diff --git a/AutomatedTesting/sounds/wwise/Init.txt b/AutomatedTesting/sounds/wwise/Init.txt index 038359ac1a..4b989c4017 100644 --- a/AutomatedTesting/sounds/wwise/Init.txt +++ b/AutomatedTesting/sounds/wwise/Init.txt @@ -21,5 +21,4 @@ Audio Bus ID Name Wwise Object Path Notes Audio Devices ID Name Type Notes 2317455096 No_Output No Output 3859886410 System System - 4230635974 Default_Motion_Device Wwise Motion diff --git a/AutomatedTesting/sounds/wwise/PluginInfo.xml b/AutomatedTesting/sounds/wwise/PluginInfo.xml index 61e689f373..19f3fe9c1b 100644 --- a/AutomatedTesting/sounds/wwise/PluginInfo.xml +++ b/AutomatedTesting/sounds/wwise/PluginInfo.xml @@ -1,9 +1,8 @@ - + - - - - + + + diff --git a/AutomatedTesting/sounds/wwise/SoundbanksInfo.xml b/AutomatedTesting/sounds/wwise/SoundbanksInfo.xml index 22ae71f4dc..d7bfecaa53 100644 --- a/AutomatedTesting/sounds/wwise/SoundbanksInfo.xml +++ b/AutomatedTesting/sounds/wwise/SoundbanksInfo.xml @@ -1,11 +1,11 @@ - + - Q:\audio\dev\AutomatedTesting\sounds\wwise_project\ - Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\ - Q:\audio\dev\AutomatedTesting\sounds\wwise\ + D:\code\o3de\AutomatedTesting\sounds\wwise_project\ + D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\ + D:\code\o3de\AutomatedTesting\sounds\wwise\ - Q:\audio\dev\AutomatedTesting\sounds\wwise_project\GeneratedSoundBanks\Windows + D:\code\o3de\AutomatedTesting\sounds\wwise_project\GeneratedSoundBanks\Windows @@ -28,7 +28,7 @@ - + \SoundBanks\Default Work Unit\test_bank2 test_bank2 test_bank2.bnk @@ -37,7 +37,7 @@ - + \SoundBanks\Default Work Unit\test_bank3 test_bank3 test_bank3.bnk @@ -60,7 +60,7 @@ - + \SoundBanks\Default Work Unit\test_bank1 test_bank1 test_bank1.bnk @@ -83,7 +83,7 @@ - + \SoundBanks\Default Work Unit\test_bank6 test_bank6 test_bank6.bnk @@ -102,7 +102,7 @@ - + \SoundBanks\Default Work Unit\test_bank7 test_bank7 test_bank7.bnk @@ -125,7 +125,7 @@ - + \SoundBanks\Default Work Unit\test_bank4 test_bank4 test_bank4.bnk @@ -136,7 +136,7 @@ - + \SoundBanks\Default Work Unit\test_bank5 test_bank5 test_bank5.bnk @@ -169,7 +169,7 @@ - + Init Init Init.bnk diff --git a/AutomatedTesting/sounds/wwise/test_bank1.bnk b/AutomatedTesting/sounds/wwise/test_bank1.bnk index 9e8f50a98a..bd0e1e66cb 100644 --- a/AutomatedTesting/sounds/wwise/test_bank1.bnk +++ b/AutomatedTesting/sounds/wwise/test_bank1.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:94ea13931c13592deba669bd4920328ff96f17e6f8fce280d03f00251a96327a -size 94122 +oid sha256:3db299d7d823b649ff20a7ffc986dccfce1fa3189f178491e2712d6c00b317af +size 94126 diff --git a/AutomatedTesting/sounds/wwise/test_bank1.txt b/AutomatedTesting/sounds/wwise/test_bank1.txt index a0c6e13621..5ec2e4b96b 100644 --- a/AutomatedTesting/sounds/wwise/test_bank1.txt +++ b/AutomatedTesting/sounds/wwise/test_bank1.txt @@ -3,8 +3,8 @@ Event ID Name Wwise Object Path Notes 865645077 test_event_1_bank1_embedded_target \Default Work Unit\test_event_1_bank1_embedded_target In Memory Audio ID Name Audio source file Wwise Object Path Notes Data Size - 23965881 test_sfx_1_bank1_embedded Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\AMZ_sfx_NME_wpn_plasma_pistol_fire_impact004_56D34C19.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_1_bank1_embedded 93864 + 23965881 test_sfx_1_bank1_embedded D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\AMZ_sfx_NME_wpn_plasma_pistol_fire_impact004_56D34C19.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_1_bank1_embedded 93864 Streamed Audio ID Name Audio source file Generated audio file Wwise Object Path Notes - 499820003 test_sfx_2_bank1_streamed Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\env_door_scanner_scan_success_56D34C19.wem 499820003.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_2_bank1_streamed + 499820003 test_sfx_2_bank1_streamed D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\env_door_scanner_scan_success_56D34C19.wem 499820003.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_2_bank1_streamed diff --git a/AutomatedTesting/sounds/wwise/test_bank2.bnk b/AutomatedTesting/sounds/wwise/test_bank2.bnk index 2e31c359bf..ee96554646 100644 --- a/AutomatedTesting/sounds/wwise/test_bank2.bnk +++ b/AutomatedTesting/sounds/wwise/test_bank2.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:ad73fd0981e47fe3313eff51d2841ea5fd522a99103684d696849e7353277ea9 -size 430 +oid sha256:1bdaed4dc5cc514a8a3ddfaf990f59061514af7962a7a112eb677ad5c45fcb85 +size 434 diff --git a/AutomatedTesting/sounds/wwise/test_bank3.bankdeps b/AutomatedTesting/sounds/wwise/test_bank3.bankdeps index 606dbdbac8..51a952d463 100644 --- a/AutomatedTesting/sounds/wwise/test_bank3.bankdeps +++ b/AutomatedTesting/sounds/wwise/test_bank3.bankdeps @@ -2,9 +2,9 @@ "version": "1.0", "bankName": "test_bank3.bnk", "dependencies": [ - "196049145.wem", + "test_bank4.bnk", "Init.bnk", - "test_bank4.bnk" + "196049145.wem" ], "includedEvents": [ "test_event_5_bank3_embedded_target_bank4", diff --git a/AutomatedTesting/sounds/wwise/test_bank3.bnk b/AutomatedTesting/sounds/wwise/test_bank3.bnk index 32e6161e6c..6b83836c18 100644 --- a/AutomatedTesting/sounds/wwise/test_bank3.bnk +++ b/AutomatedTesting/sounds/wwise/test_bank3.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:33eabaa646e9567017946bee05b1b5a835e91862f63145ebe5a2fbdd9c9f5a49 -size 226 +oid sha256:57c75cf8745b31071a788a20d8de5a60cedbfb8a6155eae1a461b8c6501e5479 +size 230 diff --git a/AutomatedTesting/sounds/wwise/test_bank3.txt b/AutomatedTesting/sounds/wwise/test_bank3.txt index ca6efc6e02..9a843afad7 100644 --- a/AutomatedTesting/sounds/wwise/test_bank3.txt +++ b/AutomatedTesting/sounds/wwise/test_bank3.txt @@ -3,5 +3,5 @@ Event ID Name Wwise Object Path Notes 645979556 test_event_6_bank3_streamed_target_bank4 \Default Work Unit\test_event_6_bank3_streamed_target_bank4 Event that lives in test_bank3. This event targets only one media, which is streamed from test_bank4. Streamed Audio ID Name Audio source file Generated audio file Wwise Object Path Notes - 196049145 test_sfx_6_bank4_streamed Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\AMZ_sfx_NME_wpn_plasma_pistol_fire003_56D34C19.wem 196049145.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_6_bank4_streamed + 196049145 test_sfx_6_bank4_streamed D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\AMZ_sfx_NME_wpn_plasma_pistol_fire003_56D34C19.wem 196049145.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_6_bank4_streamed diff --git a/AutomatedTesting/sounds/wwise/test_bank4.bnk b/AutomatedTesting/sounds/wwise/test_bank4.bnk index e169744d84..5f5883d559 100644 --- a/AutomatedTesting/sounds/wwise/test_bank4.bnk +++ b/AutomatedTesting/sounds/wwise/test_bank4.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:79d308f3c50fece383fd82fd0060e26558e6a2e78a4ecd5d8afe24907489a88f +oid sha256:3a635f7d1ccb256caed90d18ca566cd0fa56d49b491af7c88c0b5da55a3ef4fe size 142234 diff --git a/AutomatedTesting/sounds/wwise/test_bank4.txt b/AutomatedTesting/sounds/wwise/test_bank4.txt index 770cb7f171..7649b0eed5 100644 --- a/AutomatedTesting/sounds/wwise/test_bank4.txt +++ b/AutomatedTesting/sounds/wwise/test_bank4.txt @@ -1,3 +1,3 @@ In Memory Audio ID Name Audio source file Wwise Object Path Notes Data Size - 666825490 test_sfx_5_bank4_embedded Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\AMZN_sfx_env_commsarray_apllyupdate_end_56D34C19.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_5_bank4_embedded 142170 + 666825490 test_sfx_5_bank4_embedded D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\AMZN_sfx_env_commsarray_apllyupdate_end_56D34C19.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_5_bank4_embedded 142170 diff --git a/AutomatedTesting/sounds/wwise/test_bank5.bnk b/AutomatedTesting/sounds/wwise/test_bank5.bnk index b4e629d9a7..168c7c1a4d 100644 --- a/AutomatedTesting/sounds/wwise/test_bank5.bnk +++ b/AutomatedTesting/sounds/wwise/test_bank5.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:80c02f30d439ffcfb479e4a82b0269fe4f479c50019028e51f0fa6e3fea0bfdd -size 290 +oid sha256:fa329eeb83184e88b7ab26fbff2479a98232210bcd130801041b20ccb3bcf16e +size 294 diff --git a/AutomatedTesting/sounds/wwise/test_bank5.txt b/AutomatedTesting/sounds/wwise/test_bank5.txt index 0f66c57f8e..3d560cf9f5 100644 --- a/AutomatedTesting/sounds/wwise/test_bank5.txt +++ b/AutomatedTesting/sounds/wwise/test_bank5.txt @@ -5,5 +5,5 @@ Event ID Name Wwise Object Path Notes 3546419658 test_event_7_bank5_referenced_event_bank1_embedded \Default Work Unit\test_event_7_bank5_referenced_event_bank1_embedded Streamed Audio ID Name Audio source file Generated audio file Wwise Object Path Notes - 499820003 test_sfx_2_bank1_streamed Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\env_door_scanner_scan_success_56D34C19.wem 499820003.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_2_bank1_streamed + 499820003 test_sfx_2_bank1_streamed D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\env_door_scanner_scan_success_56D34C19.wem 499820003.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_2_bank1_streamed diff --git a/AutomatedTesting/sounds/wwise/test_bank6.bnk b/AutomatedTesting/sounds/wwise/test_bank6.bnk index 18ee92b51d..4c942037f0 100644 --- a/AutomatedTesting/sounds/wwise/test_bank6.bnk +++ b/AutomatedTesting/sounds/wwise/test_bank6.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:07d132d54b2c747e2409a56c05a4adca0dfa4407b791ffaa6bb14531f92f89aa -size 494 +oid sha256:80d3014fcfd3a8ff37219515f0c9d67a2a674094002538ac6741702dca07c14d +size 498 diff --git a/AutomatedTesting/sounds/wwise/test_bank7.bankdeps b/AutomatedTesting/sounds/wwise/test_bank7.bankdeps index 02be60a544..56cf29c619 100644 --- a/AutomatedTesting/sounds/wwise/test_bank7.bankdeps +++ b/AutomatedTesting/sounds/wwise/test_bank7.bankdeps @@ -2,9 +2,9 @@ "version": "1.0", "bankName": "test_bank7.bnk", "dependencies": [ + "656567798.wem", "601903616.wem", - "Init.bnk", - "656567798.wem" + "Init.bnk" ], "includedEvents": [ "test_event_11_bank7_streamed_target", diff --git a/AutomatedTesting/sounds/wwise/test_bank7.bnk b/AutomatedTesting/sounds/wwise/test_bank7.bnk index abc398d1f1..c01346fd58 100644 --- a/AutomatedTesting/sounds/wwise/test_bank7.bnk +++ b/AutomatedTesting/sounds/wwise/test_bank7.bnk @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:990538a33c72e79d63cab0c191b4e0f199688b923bb6bdcc8888aab375e7d11d -size 226 +oid sha256:0de33094b9792d7f9ff8042e16b153dd76729e9010d6713e1824d2229c653042 +size 230 diff --git a/AutomatedTesting/sounds/wwise/test_bank7.txt b/AutomatedTesting/sounds/wwise/test_bank7.txt index 033c2ea5b9..3bf2da686b 100644 --- a/AutomatedTesting/sounds/wwise/test_bank7.txt +++ b/AutomatedTesting/sounds/wwise/test_bank7.txt @@ -3,6 +3,6 @@ Event ID Name Wwise Object Path Notes 2110064689 test_event_11_bank7_streamed_target \Default Work Unit\test_event_11_bank7_streamed_target Streamed Audio ID Name Audio source file Generated audio file Wwise Object Path Notes - 601903616 test_sfx_8_bank7_streamed Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\gun_blaster_no_trigger_shot_1_56D34C19.wem 601903616.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_8_bank7_streamed - 656567798 test_sfx_7_bank7_streamed Q:\audio\dev\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\impact_bot_hits_metalelement_56D34C19.wem 656567798.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_7_bank7_streamed + 601903616 test_sfx_8_bank7_streamed D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\gun_blaster_no_trigger_shot_1_56D34C19.wem 601903616.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_8_bank7_streamed + 656567798 test_sfx_7_bank7_streamed D:\code\o3de\AutomatedTesting\sounds\wwise_project\.cache\Windows\SFX\impact_bot_hits_metalelement_56D34C19.wem 656567798.wem \Actor-Mixer Hierarchy\Default Work Unit\test_sfx_7_bank7_streamed diff --git a/AutomatedTesting/sounds/wwise_project/Actor-Mixer Hierarchy/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Actor-Mixer Hierarchy/Default Work Unit.wwu index 8cc6eeecc2..33ac513281 100644 --- a/AutomatedTesting/sounds/wwise_project/Actor-Mixer Hierarchy/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Actor-Mixer Hierarchy/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + @@ -21,6 +21,7 @@ + @@ -50,6 +51,7 @@ + @@ -72,6 +74,7 @@ + @@ -101,6 +104,7 @@ + @@ -130,6 +134,7 @@ + @@ -159,6 +164,7 @@ + @@ -187,6 +193,7 @@ SFX + @@ -215,6 +222,7 @@ SFX + diff --git a/AutomatedTesting/sounds/wwise_project/Attenuations/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Attenuations/Default Work Unit.wwu index 9034f07366..955c7d9e4a 100644 --- a/AutomatedTesting/sounds/wwise_project/Attenuations/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Attenuations/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Audio Devices/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Audio Devices/Default Work Unit.wwu index 472e9b12d1..f56682b0bf 100644 --- a/AutomatedTesting/sounds/wwise_project/Audio Devices/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Audio Devices/Default Work Unit.wwu @@ -1,11 +1,10 @@ - + - diff --git a/AutomatedTesting/sounds/wwise_project/AutomatedTesting.wproj b/AutomatedTesting/sounds/wwise_project/AutomatedTesting.wproj new file mode 100644 index 0000000000..1aead159ad --- /dev/null +++ b/AutomatedTesting/sounds/wwise_project/AutomatedTesting.wproj @@ -0,0 +1,13491 @@ + + + + + + + + + + + + + + + + + + + + + + GeneratedSoundBanks\Windows + + + + + 256 + + + + + + ..\wwise\ + + + + + Copy Streamed Files and Generate Dependency Info + + + + + "$(CopyStreamedFilesExePath)" -info "$(InfoFilePath)" -outputpath "$(SoundBankPath)" -banks "$(SoundBankListAsTextFile)" -languages "$(LanguageList)" +"$(WwiseProjectPath)\..\..\..\python\python.cmd" "$(WwiseProjectPath)\..\..\..\Gems\AudioEngineWwise\Tools\WwiseAuthoringScripts\bank_info_parser.py" "$(InfoFilePath)" "$(SoundBankPath)" + + + + + + + + + + + + + + + -80 + + + + + + + + + + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 8 + + + + + 0 + + + + + -1 + + + + + -1 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + -1 + + + + + -1 + + + + + 0 + + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + 0 + + + + + False + + + + + True + + + + + False + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 2 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + False + + + + + 65535 + + + + + 127 + + + + + 0 + + + + + 1 + + + + + 60 + + + + + 0 + + + + + 127 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 50 + + + + + + + + + 1 + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + 10000 + + + + + 1 + + + + + 400 + + + + + 1 + + + + + 1 + + + + + 0.5 + + + + + 0 + + + + + -96 + + + + + 0 + + + + + True + + + + + False + + + + + 0 + + + + + 0 + + + + + 16 + + + + + -96 + + + + + 0 + + + + + 48000 + + + + + 0 + + + + + + + + + 16 + + + + + False + + + + + 1 + + + + + 75 + + + + + + + + + False + + + + + 512 + + + + + -50 + + + + + -30 + + + + + -40 + + + + + 0 + + + + + 24024 + + + + + 0 + + + + + 8 + + + + + English(US) + + + + + 0 + + + + + 0 + + + + + False + + + + + + + + + + + + + + + 1 + + + + + True + + + + + False + + + + + False + + + + + True + + + + + 256 + + + + + + + + + + 50 + + + + + 100 + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + + + + + + True + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + False + + + + + True + + + + + True + + + + + True + + + + + True + + + + + -80 + + + + + + + + + + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 64 + + + + + 1.5 + + + + + 2 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + 64 + + + + + 64 + + + + + 4 + + + + + 0 + + + + + 0.1 + + + + + 4 + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 20 + + + + + 10000 + + + + + 0.2 + + + + + True + + + + + 80 + + + + + 0.2 + + + + + False + + + + + 200 + + + + + 0.25 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + True + + + + + True + + + + + True + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 4 + + + + + 4 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + True + + + + + 0 + + + + + 100 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 10 + + + + + 1 + + + + + 200 + + + + + 0 + + + + + 0 + + + + + 10 + + + + + 1 + + + + + 200 + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + 40 + + + + + 0 + + + + + 1000 + + + + + 160 + + + + + 0 + + + + + 0.5 + + + + + 0.2 + + + + + 0 + + + + + 0.5 + + + + + 0.2 + + + + + 0 + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 0.2 + + + + + 0 + + + + + 0.2 + + + + + 0.2 + + + + + 3000 + + + + + 0.2 + + + + + 0 + + + + + 6 + + + + + 15000 + + + + + 0 + + + + + 1000 + + + + + 20000 + + + + + 0 + + + + + 0.5 + + + + + 0.2 + + + + + 0 + + + + + 0.5 + + + + + 0.2 + + + + + 0 + + + + + 1 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + 1 + + + + + False + + + + + + + + + 1 + + + + + 0 + + + + + True + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + False + + + + + 3 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + False + + + + + 65535 + + + + + 127 + + + + + 0 + + + + + 1 + + + + + 60 + + + + + 0 + + + + + 127 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + False + + + + + 65535 + + + + + 127 + + + + + 0 + + + + + 1 + + + + + 60 + + + + + 0 + + + + + 127 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 1 + + + + + False + + + + + 2 + + + + + True + + + + + False + + + + + 0 + + + + + 1 + + + + + 1 + + + + + 50 + + + + + False + + + + + -10 + + + + + True + + + + + 1 + + + + + 1 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 1 + + + + + 0 + + + + + 100 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 50 + + + + + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 5 + + + + + 0.5 + + + + + 0 + + + + + True + + + + + 5000 + + + + + 10000 + + + + + False + + + + + + + + + False + + + + + 0 + + + + + 3 + + + + + 9 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + False + + + + + 65535 + + + + + 127 + + + + + 0 + + + + + 1 + + + + + 60 + + + + + 0 + + + + + 127 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + 0 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 50 + + + + + + + + + 1000 + + + + + 5000 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + 96 + + + + + -100 + + + + + -100 + + + + + -100 + + + + + False + + + + + False + + + + + + + + + False + + + + + 0 + + + + + 35 + + + + + 0 + + + + + True + + + + + 0 + + + + + 1 + + + + + 1 + + + + + True + + + + + + + + + 0 + + + + + + + + + False + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 3 + + + + + 9 + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + False + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + False + + + + + False + + + + + + + + + 64 + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 100 + + + + + 0 + + + + + True + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 100 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + -96 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 100 + + + + + 0 + + + + + False + + + + + 0 + + + + + 50 + + + + + 50 + + + + + 50 + + + + + + + + + False + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + 4000 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 1 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + 120 + + + + + 4 + + + + + 4 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 100 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 100 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + False + + + + + 65535 + + + + + 127 + + + + + 0 + + + + + 1 + + + + + 60 + + + + + 0 + + + + + 127 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 50 + + + + + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 1 + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + 0 + + + + + 0 + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + True + + + + + False + + + + + False + + + + + True + + + + + True + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + + + + + + + + + + + 0 + + + + + + + + + + 0 + + + + + + + + + + + + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + + -1 + + + + + 0 + + + + + -1 + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + + + + + + + + 0 + + + + + + + + + + 0 + + + + + + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 1 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + 120 + + + + + 4 + + + + + 4 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + True + + + + + True + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 12 + + + + + False + + + + + 20 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 1 + + + + + 50 + + + + + False + + + + + -10 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 100 + + + + + 120 + + + + + 4 + + + + + 4 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + + + + + 0 + + + + + 1 + + + + + 1 + + + + + False + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 50 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 7 + + + + + + + + + + False + + + + + 1 + + + + + + + + + + False + + + + + True + + + + + True + + + + + True + + + + + True + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + + + + + + 0 + + + + + 1 + + + + + False + + + + + 0 + + + + + + + + + 4 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + -6 + + + + + 0 + + + + + 90 + + + + + 0 + + + + + 245 + + + + + False + + + + + True + + + + + False + + + + + 100 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + False + + + + + 100 + + + + + + + + + True + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + False + + + + + + + + + + + + + + + False + + + + + False + + + + + True + + + + + False + + + + + False + + + + + True + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + + + + + + True + + + + + False + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + False + + + + + True + + + + + + + + + 0 + + + + + False + + + + + + + + + + + + + + + + + + True + + + + + 4 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + + + + + 0 + + + + + False + + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 1 + + + + + 0 + + + + + 1 + + + + + 8 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 100 + + + + + 0 + + + + + True + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 100 + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 100 + + + + + 1 + + + + + 0 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + False + + + + + + + + + 0 + + + + + 50 + + + + + 0.2 + + + + + False + + + + + 0.2 + + + + + 0.5 + + + + + True + + + + + 100 + + + + + 0 + + + + + 1 + + + + + 1 + + + + + False + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + + + + + + 1 + + + + + False + + + + + 0 + + + + + + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + + + + + + 1 + + + + + False + + + + + 0 + + + + + + + + + + 0 + + + + + + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + + + + + 0 + + + + + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + + + + + 0 + + + + + True + + + + + 1 + + + + + 1 + + + + + False + + + + + 1 + + + + + 0 + + + + + 1 + + + + + 1 + + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 4 + + + + + 1 + + + + + 440 + + + + + -12 + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 1 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 4 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 0 + + + + + -12 + + + + + 1 + + + + + False + + + + + 0 + + + + + -12 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + False + + + + + 10 + + + + + 0 + + + + + + + + + 0 + + + + + 4 + + + + + 6 + + + + + 5 + + + + + 100 + + + + + 1000 + + + + + 12000 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + True + + + + + True + + + + + True + + + + + 0 + + + + + False + + + + + True + + + + + 1 + + + + + 1 + + + + + 1 + + + + + + + + + 0 + + + + + 0.5 + + + + + 15 + + + + + True + + + + + True + + + + + 0 + + + + + False + + + + + True + + + + + 25 + + + + + + + + + 0.1 + + + + + True + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + True + + + + + 1.5 + + + + + 0.1 + + + + + 0 + + + + + + + + + 0.1 + + + + + True + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + True + + + + + 3 + + + + + 0.01 + + + + + -40 + + + + + + + + + True + + + + + 0 + + + + + True + + + + + 0.01 + + + + + 0 + + + + + False + + + + + True + + + + + 10 + + + + + 0.1 + + + + + 0 + + + + + + + + + 100 + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + 1 + + + + + 1000 + + + + + 0 + + + + + 0 + + + + + True + + + + + 40 + + + + + 0 + + + + + 0 + + + + + 18000 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + True + + + + + 10 + + + + + 0 + + + + + 100 + + + + + -40 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + True + + + + + 40 + + + + + 18000 + + + + + -96 + + + + + -20 + + + + + 20 + + + + + 0 + + + + + 0 + + + + + False + + + + + True + + + + + 100 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 13.62 + + + + + 26.09 + + + + + 26.55 + + + + + 26.91 + + + + + 28.04 + + + + + 29.09 + + + + + 29.9 + + + + + 30.86 + + + + + 15.66 + + + + + 17.52 + + + + + 19.02 + + + + + 20.83 + + + + + 22.6 + + + + + 24.05 + + + + + 24.78 + + + + + 25.6 + + + + + -96.3 + + + + + 2 + + + + + True + + + + + 8 + + + + + False + + + + + 0 + + + + + True + + + + + 4 + + + + + -35 + + + + + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + True + + + + + 0 + + + + + True + + + + + 100 + + + + + 0 + + + + + False + + + + + -96.3 + + + + + + + + + 0 + + + + + 0 + + + + + 40 + + + + + 1.2 + + + + + 80 + + + + + 50 + + + + + 8 + + + + + 2 + + + + + 100 + + + + + 15 + + + + + 5 + + + + + 66 + + + + + -96.3 + + + + + 0 + + + + + -20 + + + + + 23 + + + + + True + + + + + False + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 3 + + + + + 1 + + + + + 1 + + + + + 1000 + + + + + 0 + + + + + 3 + + + + + 1 + + + + + 2 + + + + + 10000 + + + + + 0 + + + + + 3 + + + + + 1 + + + + + 0 + + + + + 2.25 + + + + + True + + + + + 0 + + + + + -96.3 + + + + + -96.3 + + + + + False + + + + + 25 + + + + + 8 + + + + + 0 + + + + + -20 + + + + + 100 + + + + + 50 + + + + + 100 + + + + + 0.8 + + + + + 0.1 + + + + + 0 + + + + + 180 + + + + + + + + + 1 + + + + + 0 + + + + + False + + + + + 0 + + + + + 1 + + + + + 0 + + + + + False + + + + + 0 + + + + + 10 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0.5 + + + + + False + + + + + 0 + + + + + 10 + + + + + 5 + + + + + 1 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0.25 + + + + + False + + + + + 0 + + + + + 0.5 + + + + + + + + + 1 + + + + + 1 + + + + + True + + + + + 0.5 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0 + + + + + False + + + + + 0 + + + + + 10 + + + + + 0 + + + + + 1 + + + + + 1 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0 + + + + + False + + + + + 10 + + + + + 0.5 + + + + + 0 + + + + + 1 + + + + + + + + + 440 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 10 + + + + + + + + + False + + + + + 440 + + + + + 0 + + + + + 10 + + + + + 1 + + + + + + + + + 0 + + + + + 5 + + + + + 1 + + + + + True + + + + + 0 + + + + + 1 + + + + + True + + + + + 50 + + + + + 1 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + False + + + + + 100 + + + + + + + + + 0 + + + + + 50 + + + + + 50 + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + False + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + False + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + False + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + False + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + False + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + False + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 100 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + -96.3 + + + + + 0 + + + + + 0 + + + + + False + + + + + 4 + + + + + 0 + + + + + 100 + + + + + 0 + + + + + 0 + + + + + -75 + + + + + False + + + + + False + + + + + 6 + + + + + 0 + + + + + 0 + + + + + True + + + + + 100 + + + + + True + + + + + 0 + + + + + -96.3 + + + + + 0 + + + + + -60 + + + + + -96.3 + + + + + False + + + + + 0 + + + + + 0 + + + + + 1024 + + + + + 48000 + + + + + 48000 + + + + + 48000 + + + + + 180 + + + + + 0 + + + + + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 0 + + + + + -48 + + + + + False + + + + + 0.1 + + + + + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + 100 + + + + + 0 + + + + + 2048 + + + + + + + + + 0 + + + + + True + + + + + 100 + + + + + 1 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + True + + + + + True + + + + + + + + + 1 + + + + + False + + + + + Recorder.wav + + + + + -3 + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + + + + + + True + + + + + -96.3 + + + + + False + + + + + -3 + + + + + -3 + + + + + + + + + 0 + + + + + 0 + + + + + False + + + + + False + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + -100 + + + + + True + + + + + -12 + + + + + 0.1 + + + + + -12 + + + + + 0 + + + + + False + + + + + -12 + + + + + 0.1 + + + + + -12 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + 50 + + + + + -96 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + 0 + + + + + False + + + + + False + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + False + + + + + True + + + + + True + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1024 + + + + + + + + + 0 + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + + + + + 1000 + + + + + 0 + + + + + 0 + + + + + -96 + + + + + 0 + + + + + 0 + + + + + False + + + + + -6 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + False + + + + + -6 + + + + + 50 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + + + + + False + + + + + False + + + + + + + + + 1 + + + + + 0 + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 250 + + + + + 100 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + -96 + + + + + 3 + + + + + True + + + + + 1000 + + + + + 0 + + + + + 0 + + + + + False + + + + + 0.5 + + + + + 0 + + + + + 2400 + + + + + 345 + + + + + 0 + + + + + 0 + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 1 + + + + + + + + + False + + + + + True + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + 0 + + + + + 0 + + + + + 32 + + + + + False + + + + + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + False + + + + + True + + + + + False + + + + + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + + + + + False + + + + + False + + + + + False + + + + + False + + + + + False + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 100 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 10 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 20000 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0.707 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1000 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 256 + + + + + False + + + + + 100 + + + + + 100 + + + + + 100 + + + + + 100 + + + + + 1000 + + + + + 1000 + + + + + 1000 + + + + + 1000 + + + + + 20000 + + + + + 20000 + + + + + 20000 + + + + + 20000 + + + + + 1 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 5 + + + + + 5 + + + + + 9 + + + + + 9 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 16641 + + + + + 0 + + + + + 0 + + + + + False + + + + + 10 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 60 + + + + + 1 + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + + 0 + + + + + + + + + + + + + + 0 + + + + + True + + + + + False + + + + + 0.01 + + + + + True + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0.1 + + + + + 0 + + + + + 0.01 + + + + + True + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0.1 + + + + + 0 + + + + + 0.01 + + + + + True + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0.1 + + + + + 0 + + + + + 0.01 + + + + + True + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0.1 + + + + + 0 + + + + + 150 + + + + + 1000 + + + + + 6000 + + + + + 0 + + + + + False + + + + + 0 + + + + + 4 + + + + + 0 + + + + + False + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + True + + + + + True + + + + + True + + + + + True + + + + + True + + + + + 5 + + + + + 100 + + + + + 0 + + + + + 1 + + + + + True + + + + + 3 + + + + + 200 + + + + + 0 + + + + + 1 + + + + + True + + + + + 3 + + + + + 500 + + + + + 0 + + + + + 1 + + + + + True + + + + + 4 + + + + + 1000 + + + + + 0 + + + + + 1 + + + + + False + + + + + 3 + + + + + 3000 + + + + + 0 + + + + + 1 + + + + + False + + + + + 3 + + + + + 6000 + + + + + 0 + + + + + 1 + + + + + 4 + + + + + + + + + -12 + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + False + + + + + + + + + 1 + + + + + 0 + + + + + + + + + 0 + + + + + 0 + + + + + 1 + + + + + 0 + + + + + 1 + + + + + 1 + + + + + 0 + + + + + -12 + + + + + 1 + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 6 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + + + + + 1 + + + + + 1 + + + + + 1 + + + + + 0 + + + + + + + + + + 0 + + + + + 0 + + + + + + + + + 0.6 + + + + + 0.6 + + + + + 0.5 + + + + + 0.3 + + + + + 0.05 + + + + + 0.25 + + + + + 0.02 + + + + + 1.5 + + + + + 0.2 + + + + + 0.3 + + + + + True + + + + + 0.2 + + + + + 8 + + + + + 0.2 + + + + + 12 + + + + + + + + + 20 + + + + + 0.7 + + + + + 100 + + + + + 0.1 + + + + + 1 + + + + + 1 + + + + + True + + + + + 1 + + + + + 0 + + + + + 3 + + + + + 1 + + + + + + + + + 2 + + + + + 0.7 + + + + + 1 + + + + + 0 + + + + + 1 + + + + + 0.9 + + + + + 0.1 + + + + + 3 + + + + + + + + + 0 + + + + + True + + + + + False + + + + + + + + + 0 + + + + + True + + + + + 0 + + + + + False + + + + + + + + + 0 + + + + + False + + + + + False + + + + + True + + + + + 0 + + + + + 0 + + + + + + + + + + 0 + + + + + 0 + + + + + 0 + + + + + 0 + + + + + False + + + + + 2 + + + + + False + + + + + + + + + + + + + + + 1 + + + + + + + + + + + + + + 0 + + + + + + + + + False + + + + + 0 + + + + + 0 + + + + + 1.4 + + + + + -6 + + + + + True + + + + + 0 + + + + + 0 + + + + + False + + + + + True + + + + + 0.5 + + + + + 10000 + + + + + -6 + + + + + 7 + + + + + 1 + + + + + 1 + + + + + 7.25 + + + + + 2.75 + + + + + 3.25 + + + + + 4.25 + + + + + 4.75 + + + + + 3.75 + + + + + + + + + 100 + + + + + 50 + + + + + + + + + + + + + + + + + 0 + 0 + 5 + + + 100 + -200 + 37 + + + + + + + + + + + + + + 0 + 0 + 5 + + + 100 + 100 + 37 + + + + + + + + + + + + + + 0 + 0 + 5 + + + 100 + 100 + 37 + + + + + + + + + + + + + + 0 + 0 + 5 + + + 100 + -200 + 37 + + + + + + + + + + + + + + 0 + 0 + 5 + + + 100 + 100 + 37 + + + + + + + + + + + + + + 0 + 0 + 5 + + + 100 + 100 + 37 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/sounds/wwise_project/Control Surface Sessions/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Control Surface Sessions/Default Work Unit.wwu index 1f7d254b46..4e13dee554 100644 --- a/AutomatedTesting/sounds/wwise_project/Control Surface Sessions/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Control Surface Sessions/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Conversion Settings/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Conversion Settings/Default Work Unit.wwu index ac7c83d1db..236f5765db 100644 --- a/AutomatedTesting/sounds/wwise_project/Conversion Settings/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Conversion Settings/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Conversion Settings/Factory Conversion Settings.wwu b/AutomatedTesting/sounds/wwise_project/Conversion Settings/Factory Conversion Settings.wwu index 9a94d81c32..7873f5135a 100644 --- a/AutomatedTesting/sounds/wwise_project/Conversion Settings/Factory Conversion Settings.wwu +++ b/AutomatedTesting/sounds/wwise_project/Conversion Settings/Factory Conversion Settings.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Dynamic Dialogue/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Dynamic Dialogue/Default Work Unit.wwu index e6e033e251..5411c7d503 100644 --- a/AutomatedTesting/sounds/wwise_project/Dynamic Dialogue/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Dynamic Dialogue/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Effects/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Effects/Default Work Unit.wwu index f938135d6b..ca63005f4b 100644 --- a/AutomatedTesting/sounds/wwise_project/Effects/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Effects/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Effects/Factory Effects.wwu b/AutomatedTesting/sounds/wwise_project/Effects/Factory Effects.wwu index ac716afb97..5a545f5e61 100644 --- a/AutomatedTesting/sounds/wwise_project/Effects/Factory Effects.wwu +++ b/AutomatedTesting/sounds/wwise_project/Effects/Factory Effects.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Effects/Factory Reflect.wwu b/AutomatedTesting/sounds/wwise_project/Effects/Factory Reflect.wwu index f2269dd2dc..2c0ebb6b67 100644 --- a/AutomatedTesting/sounds/wwise_project/Effects/Factory Reflect.wwu +++ b/AutomatedTesting/sounds/wwise_project/Effects/Factory Reflect.wwu @@ -1,10 +1,9 @@ - + - - + @@ -185,8 +184,7 @@ - - + diff --git a/AutomatedTesting/sounds/wwise_project/Events/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Events/Default Work Unit.wwu index c65c8adca1..73c2e8f028 100644 --- a/AutomatedTesting/sounds/wwise_project/Events/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Events/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Game Parameters/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Game Parameters/Default Work Unit.wwu index e373885f46..a939ebe124 100644 --- a/AutomatedTesting/sounds/wwise_project/Game Parameters/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Game Parameters/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory Motion.wwu b/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory Motion.wwu index b06d283012..3989d74308 100644 --- a/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory Motion.wwu +++ b/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory Motion.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory SoundSeed Air Game Syncs.wwu b/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory SoundSeed Air Game Syncs.wwu index 049dacb51e..efe69cb1a8 100644 --- a/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory SoundSeed Air Game Syncs.wwu +++ b/AutomatedTesting/sounds/wwise_project/Game Parameters/Factory SoundSeed Air Game Syncs.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Interactive Music Hierarchy/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Interactive Music Hierarchy/Default Work Unit.wwu index 1086c4511f..e8f4d23bb6 100644 --- a/AutomatedTesting/sounds/wwise_project/Interactive Music Hierarchy/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Interactive Music Hierarchy/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Master-Mixer Hierarchy/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Master-Mixer Hierarchy/Default Work Unit.wwu index a627ce106e..b6c14df7af 100644 --- a/AutomatedTesting/sounds/wwise_project/Master-Mixer Hierarchy/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Master-Mixer Hierarchy/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + @@ -9,13 +9,15 @@ + - + + diff --git a/AutomatedTesting/sounds/wwise_project/Metadata/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Metadata/Default Work Unit.wwu new file mode 100644 index 0000000000..0317c70b7c --- /dev/null +++ b/AutomatedTesting/sounds/wwise_project/Metadata/Default Work Unit.wwu @@ -0,0 +1,6 @@ + + + + + + diff --git a/AutomatedTesting/sounds/wwise_project/Mixing Sessions/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Mixing Sessions/Default Work Unit.wwu index 8c62ef9009..c24440febd 100644 --- a/AutomatedTesting/sounds/wwise_project/Mixing Sessions/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Mixing Sessions/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Modulators/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Modulators/Default Work Unit.wwu index 062f9f80df..dc16200be3 100644 --- a/AutomatedTesting/sounds/wwise_project/Modulators/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Modulators/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Presets/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Presets/Default Work Unit.wwu index 2bed1c6613..07f7565980 100644 --- a/AutomatedTesting/sounds/wwise_project/Presets/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Presets/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Presets/Factory Reflect.wwu b/AutomatedTesting/sounds/wwise_project/Presets/Factory Reflect.wwu index 53f828f459..8138f5bcdd 100644 --- a/AutomatedTesting/sounds/wwise_project/Presets/Factory Reflect.wwu +++ b/AutomatedTesting/sounds/wwise_project/Presets/Factory Reflect.wwu @@ -1,5 +1,5 @@ - + @@ -19,6 +19,7 @@ + diff --git a/AutomatedTesting/sounds/wwise_project/Presets/Factory Spatial Audio.wwu b/AutomatedTesting/sounds/wwise_project/Presets/Factory Spatial Audio.wwu index 5b96bd3b29..d73cf8d8c3 100644 --- a/AutomatedTesting/sounds/wwise_project/Presets/Factory Spatial Audio.wwu +++ b/AutomatedTesting/sounds/wwise_project/Presets/Factory Spatial Audio.wwu @@ -1,5 +1,5 @@ - + @@ -17,6 +17,7 @@ + diff --git a/AutomatedTesting/sounds/wwise_project/Queries/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Queries/Default Work Unit.wwu index f4e9f99aa4..ff80573330 100644 --- a/AutomatedTesting/sounds/wwise_project/Queries/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Queries/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Queries/Factory Queries.wwu b/AutomatedTesting/sounds/wwise_project/Queries/Factory Queries.wwu index 527315de63..813983d789 100644 --- a/AutomatedTesting/sounds/wwise_project/Queries/Factory Queries.wwu +++ b/AutomatedTesting/sounds/wwise_project/Queries/Factory Queries.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/SoundBanks/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/SoundBanks/Default Work Unit.wwu index da8fa90010..c12261ab5b 100644 --- a/AutomatedTesting/sounds/wwise_project/SoundBanks/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/SoundBanks/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Soundcaster Sessions/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Soundcaster Sessions/Default Work Unit.wwu index d6b8329537..379bf37da9 100644 --- a/AutomatedTesting/sounds/wwise_project/Soundcaster Sessions/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Soundcaster Sessions/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/States/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/States/Default Work Unit.wwu index f27a0d0310..b06937baa9 100644 --- a/AutomatedTesting/sounds/wwise_project/States/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/States/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Switches/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Switches/Default Work Unit.wwu index 49c00bc378..37fb0b424c 100644 --- a/AutomatedTesting/sounds/wwise_project/Switches/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Switches/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Triggers/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Triggers/Default Work Unit.wwu index 3b2e2634df..bb2a827d79 100644 --- a/AutomatedTesting/sounds/wwise_project/Triggers/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Triggers/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Default Work Unit.wwu b/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Default Work Unit.wwu index 29c26cbbab..d10d9475dc 100644 --- a/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Default Work Unit.wwu +++ b/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Default Work Unit.wwu @@ -1,5 +1,5 @@ - + diff --git a/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Factory Reflect Acoustic Textures.wwu b/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Factory Reflect Acoustic Textures.wwu index 864f6ba959..ca4a1ae8f2 100644 --- a/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Factory Reflect Acoustic Textures.wwu +++ b/AutomatedTesting/sounds/wwise_project/Virtual Acoustics/Factory Reflect Acoustic Textures.wwu @@ -1,5 +1,5 @@ - + diff --git a/Code/CryEngine/CryCommon/CMakeLists.txt b/Code/CryEngine/CryCommon/CMakeLists.txt index 4725489358..5105ff1a5b 100644 --- a/Code/CryEngine/CryCommon/CMakeLists.txt +++ b/Code/CryEngine/CryCommon/CMakeLists.txt @@ -32,41 +32,6 @@ ly_add_target( AZ::AzFramework ) -ly_add_target( - NAME CryCommon.EngineSettings.Static STATIC - NAMESPACE Legacy - FILES_CMAKE - crycommon_enginesettings_files.cmake - ${pal_dir}/crycommon_enginesettings_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - . - ${pal_dir} - BUILD_DEPENDENCIES - PUBLIC - AZ::AzCore - AZ::AzFramework -) - -ly_add_target( - NAME CryCommon.EngineSettings.RC.Static STATIC - NAMESPACE Legacy - FILES_CMAKE - crycommon_enginesettings_files.cmake - ${pal_dir}/crycommon_enginesettings_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - . - ${pal_dir} - COMPILE_DEFINITIONS - PRIVATE - RESOURCE_COMPILER - BUILD_DEPENDENCIES - PUBLIC - AZ::AzCore - AZ::AzFramework -) - if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) ly_add_target( diff --git a/Code/CryEngine/CryCommon/CryAssert_Android.h b/Code/CryEngine/CryCommon/CryAssert_Android.h index 68f716ec28..6e60df1bb1 100644 --- a/Code/CryEngine/CryCommon/CryAssert_Android.h +++ b/Code/CryEngine/CryCommon/CryAssert_Android.h @@ -31,7 +31,7 @@ void CryAssertTrace(const char* szFormat, ...) return; } - if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting) + if (!gEnv->bIgnoreAllAsserts) { if (szFormat == NULL) { diff --git a/Code/CryEngine/CryCommon/CryAssert_Linux.h b/Code/CryEngine/CryCommon/CryAssert_Linux.h index 7c52f78366..f0acdd79db 100644 --- a/Code/CryEngine/CryCommon/CryAssert_Linux.h +++ b/Code/CryEngine/CryCommon/CryAssert_Linux.h @@ -34,7 +34,7 @@ void CryAssertTrace(const char* szFormat, ...) return; } - if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting) + if (!gEnv->bIgnoreAllAsserts) { if (szFormat == NULL) { diff --git a/Code/CryEngine/CryCommon/CryAssert_Mac.h b/Code/CryEngine/CryCommon/CryAssert_Mac.h index 9502605fea..f7f74c3b58 100644 --- a/Code/CryEngine/CryCommon/CryAssert_Mac.h +++ b/Code/CryEngine/CryCommon/CryAssert_Mac.h @@ -30,7 +30,7 @@ void CryAssertTrace(const char* szFormat, ...) return; } - if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting) + if (!gEnv->bIgnoreAllAsserts) { if (szFormat == NULL) { diff --git a/Code/CryEngine/CryCommon/CryAssert_iOS.h b/Code/CryEngine/CryCommon/CryAssert_iOS.h index ad668fb131..2cb08befff 100644 --- a/Code/CryEngine/CryCommon/CryAssert_iOS.h +++ b/Code/CryEngine/CryCommon/CryAssert_iOS.h @@ -31,7 +31,7 @@ void CryAssertTrace(const char* szFormat, ...) return; } - if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting) + if (!gEnv->bIgnoreAllAsserts) { if (szFormat == NULL) { diff --git a/Code/CryEngine/CryCommon/CryAssert_impl.h b/Code/CryEngine/CryCommon/CryAssert_impl.h index ed55162f1a..edbbb2f0c4 100644 --- a/Code/CryEngine/CryCommon/CryAssert_impl.h +++ b/Code/CryEngine/CryCommon/CryAssert_impl.h @@ -305,7 +305,7 @@ void CryAssertTrace(const char* _pszFormat, ...) { return; } - if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting) + if (!gEnv->bIgnoreAllAsserts) { if (NULL == _pszFormat) { diff --git a/Code/CryEngine/CryCommon/CrySystemBus.h b/Code/CryEngine/CryCommon/CrySystemBus.h index f183de0fa9..def1ce4688 100644 --- a/Code/CryEngine/CryCommon/CrySystemBus.h +++ b/Code/CryEngine/CryCommon/CrySystemBus.h @@ -49,12 +49,6 @@ public: //! ISystem has shut down. virtual void OnCrySystemPostShutdown() {} - //! Engine pre physics update. - virtual void OnCrySystemPrePhysicsUpdate() {} - - //! Engine post physics update. - virtual void OnCrySystemPostPhysicsUpdate() {} - //! Sent when a new level is being created. virtual void OnCryEditorBeginCreate() {} diff --git a/Code/CryEngine/CryCommon/CryThread.h b/Code/CryEngine/CryCommon/CryThread.h index f1e97b2199..9aa7bce128 100644 --- a/Code/CryEngine/CryCommon/CryThread.h +++ b/Code/CryEngine/CryCommon/CryThread.h @@ -37,9 +37,6 @@ enum CryLockType #define CRYLOCK_HAVE_FASTLOCK 1 -void CryThreadSetName(threadID nThreadId, const char* sThreadName); -const char* CryThreadGetName(threadID nThreadId); - ///////////////////////////////////////////////////////////////////////////// // // Primitive locks and conditions. diff --git a/Code/CryEngine/CryCommon/CryThreadImpl.h b/Code/CryEngine/CryCommon/CryThreadImpl.h index b151b3da8a..da9be86dd5 100644 --- a/Code/CryEngine/CryCommon/CryThreadImpl.h +++ b/Code/CryEngine/CryCommon/CryThreadImpl.h @@ -31,22 +31,3 @@ #else // Put other platform specific includes here! #endif - -#include - -void CryThreadSetName(threadID dwThreadId, const char* sThreadName) -{ - if (gEnv && gEnv->pSystem && gEnv->pSystem->GetIThreadTaskManager()) - { - gEnv->pSystem->GetIThreadTaskManager()->SetThreadName(dwThreadId, sThreadName); - } -} - -const char* CryThreadGetName(threadID dwThreadId) -{ - if (gEnv && gEnv->pSystem && gEnv->pSystem->GetIThreadTaskManager()) - { - return gEnv->pSystem->GetIThreadTaskManager()->GetThreadName(dwThreadId); - } - return ""; -} diff --git a/Code/CryEngine/CryCommon/CryThreadImpl_windows.h b/Code/CryEngine/CryCommon/CryThreadImpl_windows.h index 6f37edeea1..3ff28a81be 100644 --- a/Code/CryEngine/CryCommon/CryThreadImpl_windows.h +++ b/Code/CryEngine/CryCommon/CryThreadImpl_windows.h @@ -13,8 +13,6 @@ #pragma once -//#include - #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif diff --git a/Code/CryEngine/CryCommon/CryThread_windows.h b/Code/CryEngine/CryCommon/CryThread_windows.h index 1d9ea6dc31..b70260c7ac 100644 --- a/Code/CryEngine/CryCommon/CryThread_windows.h +++ b/Code/CryEngine/CryCommon/CryThread_windows.h @@ -249,10 +249,6 @@ public: void SetName(const char* Name) { m_name = Name; - if (m_threadId) - { - CryThreadSetName(m_threadId, m_name); - } } const char* GetName() { return m_name; } @@ -289,11 +285,6 @@ private: self->m_bIsStarted = true; self->m_bIsRunning = true; - if (!self->m_name.empty()) - { - CryThreadSetName(-1, self->m_name); - } - self->m_Runnable->Run(); self->m_bIsRunning = false; self->m_bCreatedThread = false; @@ -311,11 +302,6 @@ private: self->m_bIsStarted = true; self->m_bIsRunning = true; - if (!self->m_name.empty()) - { - CryThreadSetName(-1, self->m_name); - } - self->Run(); self->m_bIsRunning = false; self->m_bCreatedThread = false; diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackend.cpp b/Code/CryEngine/CryCommon/EngineSettingsBackend.cpp deleted file mode 100644 index caf7e03f31..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackend.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ - - -#include "EngineSettingsBackend.h" - -#ifdef CRY_ENABLE_RC_HELPER - -CEngineSettingsBackend::CEngineSettingsBackend(CEngineSettingsManager* parent, const wchar_t* moduleName) - : m_parent(parent) - , m_moduleName() -{ - if (moduleName != nullptr) - { - m_moduleName = moduleName; - } -} - -CEngineSettingsBackend::~CEngineSettingsBackend() -{ - -} - -#endif // CRY_ENABLE_RC_HELPER - diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackend.h b/Code/CryEngine/CryCommon/EngineSettingsBackend.h deleted file mode 100644 index fce16517ec..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackend.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ -#ifndef CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKEND_H -#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKEND_H -#pragma once - -#include "ProjectDefines.h" - -#ifdef CRY_ENABLE_RC_HELPER - -#include "SettingsManagerHelpers.h" - -#include - -class CEngineSettingsManager; - -class CEngineSettingsBackend -{ -public: - CEngineSettingsBackend(CEngineSettingsManager* parent, const wchar_t* moduleName = NULL); - virtual ~CEngineSettingsBackend(); - - virtual std::wstring GetModuleFilePath() const = 0; - - virtual bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) = 0; - virtual bool GetModuleSpecificIntEntry(const char* key, int& value) = 0; - virtual bool GetModuleSpecificBoolEntry(const char* key, bool& value) = 0; - - virtual bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) = 0; - virtual bool SetModuleSpecificIntEntry(const char* key, const int& value) = 0; - virtual bool SetModuleSpecificBoolEntry(const char* key, const bool& value) = 0; - - virtual bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) = 0; - - virtual void LoadEngineSettingsFromRegistry() = 0; - virtual bool StoreEngineSettingsToRegistry() = 0; - -protected: - CEngineSettingsManager* parent() const - { - return m_parent; - } - - const std::wstring& moduleName() const - { - return m_moduleName; - } - -private: - std::wstring m_moduleName; - CEngineSettingsManager* m_parent; -}; - -#endif // CRY_ENABLE_RC_HELPER - -#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKEND_H diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackendApple.cpp b/Code/CryEngine/CryCommon/EngineSettingsBackendApple.cpp deleted file mode 100644 index 06f8d532d3..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackendApple.cpp +++ /dev/null @@ -1,486 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ - -#include "EngineSettingsBackendApple.h" - -#ifdef CRY_ENABLE_RC_HELPER - -#include "AzCore/PlatformDef.h" - -#if AZ_TRAIT_OS_PLATFORM_APPLE - -#include "EngineSettingsManager.h" -#include "SettingsManagerHelpers.h" - -#include "platform.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -using namespace SettingsManagerHelpers; - -static const char gDefaultRegistryLocation[] = "/EngineSettings.reg"; - -#define REG_SOFTWARE L"Software\\" -#define REG_COMPANY_NAME L"Amazon\\" -#define REG_PRODUCT_NAME L"Lumberyard\\" -#define REG_SETTING L"Settings\\" -#define REG_BASE_SETTING_KEY REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME REG_SETTING - -////////////////////////////////////////////////////////////////////////// -class SimpleRegistry -{ - typedef std::map< std::wstring, std::wstring > WStringMap; - std::map< std::wstring, WStringMap * > m_modules; - -public: - SimpleRegistry(); - ~SimpleRegistry(); - - void setBoolValue(const std::wstring& module, const std::wstring& key, bool value); - void setIntValue(const std::wstring& module, const std::wstring& key, int value); - void setStrValue(const std::wstring& module, const std::wstring& key, const std::wstring& value); - - bool getBoolValue(const std::wstring& module, const std::wstring& key, bool& value); - bool getIntValue(const std::wstring& module, const std::wstring& key, int& value); - bool getStrValue(const std::wstring& module, const std::wstring& key, std::wstring& value); - - bool loadFromFile(const char* fileName); - bool saveToFile(const char* fileName); - -protected: - void clear(); - -private: - static const wchar_t gSimpleMagic[]; - static const size_t gMetaCharCount; -}; - -const wchar_t SimpleRegistry::gSimpleMagic[] = L"FR0"; -const size_t SimpleRegistry::gMetaCharCount = sizeof(size_t) / sizeof(wchar_t); - -SimpleRegistry::SimpleRegistry() -{ -} - -SimpleRegistry::~SimpleRegistry() -{ - clear(); -} - -void SimpleRegistry::setBoolValue(const std::wstring& module, const std::wstring& key, bool value) -{ - return setStrValue(module, key, value ? L"true" : L"false"); -} - -void SimpleRegistry::setIntValue(const std::wstring& module, const std::wstring& key, int value) -{ - return setStrValue(module, key, std::to_wstring(value)); -} - -void SimpleRegistry::setStrValue(const std::wstring& module, const std::wstring& key, const std::wstring& value) -{ - WStringMap *map = nullptr; - - auto i = m_modules.find(module); - - if (i == m_modules.end()) - { - map = new WStringMap; - m_modules.emplace(module, map); - } - else - { - map = i->second; - } - - assert(map); - - (*map)[key] = value; -} - -bool SimpleRegistry::getBoolValue(const std::wstring& module, const std::wstring& key, bool& value) -{ - std::wstring str; - - if (!getStrValue(module, key, str)) - { - return false; - } - - value = (0 == str.compare(L"true")); - - return true; -} - -bool SimpleRegistry::getIntValue(const std::wstring& module, const std::wstring& key, int& value) -{ - std::wstring str; - - if (!getStrValue(module, key, str)) - { - return false; - } - - value = std::stoi(str); - - return true; -} - -bool SimpleRegistry::getStrValue(const std::wstring& module, const std::wstring& key, std::wstring& value) -{ - WStringMap *map = nullptr; - - auto mi = m_modules.find(module); - if (mi == m_modules.end()) - { - return false; - } - - map = mi->second; - assert(map); - - auto ki = map->find(key); - if (ki == map->end()) - { - return false; - } - - value = ki->second; - - return true; -} - -bool SimpleRegistry::loadFromFile(const char* fileName) -{ - clear(); - - std::wifstream file(fileName, std::ios_base::in|std::ios_base::binary); - file.imbue(std::locale(file.getloc(), new std::codecvt_utf16)); - if (!file.is_open()) - { - AZ_Warning("EngineSettings", false, "Failed to open registry settings file: %s", fileName); - return false; - } - - std::wstring module; - std::wstring key; - std::wstring value; - - wchar_t buffer[512]; - size_t size; - wchar_t meta[gMetaCharCount]; - - /* magic number */ - if(!file.read(buffer, sizeof(gSimpleMagic) / sizeof(wchar_t)) || - wcsncmp(gSimpleMagic, buffer, sizeof(gSimpleMagic) / sizeof(wchar_t)) != 0) - { - file.close(); - AZ_Warning("EngineSettings", false, "Failed to load registry settings from file: %s", fileName); - return false; - } - - while (file.good()) - { - file.read(meta, gMetaCharCount); - if (!file.good()) - { - break; - } - - memcpy(&size, meta, sizeof(size)); - file.read(buffer, size); - buffer[file.gcount()] = L'\0'; - module = buffer; - - file.read(meta, gMetaCharCount); - memcpy(&size, meta, sizeof(size)); - file.read(buffer, size); - buffer[file.gcount()] = L'\0'; - key = buffer; - - file.read(meta, gMetaCharCount); - memcpy(&size, meta, sizeof(size)); - file.read(buffer, size); - buffer[file.gcount()] = L'\0'; - value = buffer; - - setStrValue(module, key, value); - } - - file.close(); - - return true; -} - -bool SimpleRegistry::saveToFile(const char* fileName) -{ - std::wofstream file(fileName, std::ios_base::out|std::ios_base::trunc|std::ios_base::binary); - file.imbue(std::locale(file.getloc(), new std::codecvt_utf16)); - if (!file.is_open()) - { - return false; - } - - std::wstring module; - - size_t size; - wchar_t meta[gMetaCharCount]; - - /* magic number */ - file.write(gSimpleMagic, sizeof(gSimpleMagic) / sizeof(wchar_t)); - - for (auto j : m_modules) - { - module = j.first; - - for (auto i : *j.second) - { - size = module.size(); - memcpy(meta, &size, sizeof(meta)); - file.write(meta, gMetaCharCount); - file.write(module.c_str(), size); - - size = i.first.size(); - memcpy(meta, &size, sizeof(meta)); - file.write(meta, gMetaCharCount); - file.write(i.first.c_str(), size); - - size = i.second.size(); - memcpy(meta, &size, sizeof(meta)); - file.write(meta, gMetaCharCount); - file.write(i.second.c_str(), size); - } - } - - file.close(); - - return true; -} - -void SimpleRegistry::clear() -{ - for (auto pair : m_modules) - { - delete pair.second; - } - - m_modules.clear(); -} -////////////////////////////////////////////////////////////////////////// - -CEngineSettingsBackendApple::CEngineSettingsBackendApple(CEngineSettingsManager* parent, const wchar_t* moduleName) - : CEngineSettingsBackend(parent, moduleName) - , m_registry(new SimpleRegistry) - , m_registryFilePath() -{ - std::string rootValue = gEnv->pFileIO->GetAlias("@root@"); - if (rootValue.empty()) - { - AZ_Warning("EngineSettings", false, "Could not get engine root."); - return; - } - - rootValue.append(gDefaultRegistryLocation); - m_registryFilePath = rootValue; -} - -CEngineSettingsBackendApple::~CEngineSettingsBackendApple() -{ - delete m_registry, m_registry = nullptr; -} - -std::wstring CEngineSettingsBackendApple::GetModuleFilePath() const -{ - std::string path; - - std::wstring_convert> converter; - std::string module = converter.to_bytes(moduleName()); - - void* handle = ::dlopen(module.c_str(), RTLD_LAZY); - if (handle) - { - const int c = _dyld_image_count(); - for (int i = 0; i < c; ++i) - { - const char* image = _dyld_get_image_name(i); - const void* altHandle = dlopen(image, RTLD_LAZY); - if (handle == altHandle) - { - char absImage[PATH_MAX]; - realpath(image, absImage); - char *ext = rindex(absImage, '.'); - if (ext) - { - *ext = '\0'; - } - path.append(absImage); - path.append(".ini"); - break; - } - } - } - - return converter.from_bytes(path); -} - -bool CEngineSettingsBackendApple::GetModuleSpecificStringEntryUtf16(const char* key, CWCharBuffer wbuffer) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - std::wstring str; - if (!m_registry->getStrValue(moduleName(), wkey, str)) - { - return false; - } - - std::wcscpy(wbuffer.getPtr(), str.c_str()); - - return true; -} - -bool CEngineSettingsBackendApple::GetModuleSpecificIntEntry(const char* key, int& value) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - return m_registry->getIntValue(moduleName(), wkey, value); -} - -bool CEngineSettingsBackendApple::GetModuleSpecificBoolEntry(const char* key, bool& value) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - return m_registry->getBoolValue(moduleName(), wkey, value); -} - -bool CEngineSettingsBackendApple::SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - m_registry->setStrValue(moduleName(), wkey, str); - - return true; -} - -bool CEngineSettingsBackendApple::SetModuleSpecificIntEntry(const char* key, const int& value) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - m_registry->setIntValue(moduleName(), wkey, value); - - return true; -} - -bool CEngineSettingsBackendApple::SetModuleSpecificBoolEntry(const char* key, const bool& value) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - m_registry->setBoolValue(moduleName(), wkey, value); - - return true; -} - -bool CEngineSettingsBackendApple::GetInstalledBuildRootPathUtf16(const int index, CWCharBuffer name, CWCharBuffer path) -{ - return false; -} - -bool CEngineSettingsBackendApple::StoreEngineSettingsToRegistry() -{ - bool bRet = true; - wchar_t buffer[1024]; - - // ResourceCompiler Specific - if (parent()->GetValueByRef("RC_ShowWindow", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - m_registry->setBoolValue(REG_BASE_SETTING_KEY, L"RC_ShowWindow", b); - } - - if (parent()->GetValueByRef("RC_HideCustom", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - m_registry->setBoolValue(REG_BASE_SETTING_KEY, L"RC_HideCustom", b); - } - - if (parent()->GetValueByRef("RC_Parameters", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - m_registry->setStrValue(REG_BASE_SETTING_KEY, L"RC_Parameters", buffer); - } - - if (parent()->GetValueByRef("RC_EnableSourceControl", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - m_registry->setBoolValue(REG_BASE_SETTING_KEY, L"RC_EnableSourceControl", b); - } - - bRet &= m_registry->saveToFile(m_registryFilePath.c_str()); - return bRet; -} - -void CEngineSettingsBackendApple::LoadEngineSettingsFromRegistry() -{ - if (!m_registry->loadFromFile(m_registryFilePath.c_str())) - { - return; - } - - std::wstring wStrResult; - bool bResult; - - if (m_registry->getStrValue(REG_BASE_SETTING_KEY, L"RootPath", wStrResult)) - { - parent()->SetKey("ENG_RootPath", wStrResult.c_str()); - } - - // Engine Specific - if (m_registry->getStrValue(REG_BASE_SETTING_KEY, L"ENG_RootPath", wStrResult)) - { - parent()->SetKey("ENG_RootPath", wStrResult.c_str()); - } - - // ResourceCompiler Specific - if (m_registry->getBoolValue(REG_BASE_SETTING_KEY, L"RC_ShowWindow", bResult)) - { - parent()->SetKey("RC_ShowWindow", bResult); - } - if (m_registry->getBoolValue(REG_BASE_SETTING_KEY, L"RC_HideCustom", bResult)) - { - parent()->SetKey("RC_HideCustom", bResult); - } - if (m_registry->getStrValue(REG_BASE_SETTING_KEY, L"RC_Parameters", wStrResult)) - { - parent()->SetKey("RC_Parameters", wStrResult.c_str()); - } - if (m_registry->getBoolValue(REG_BASE_SETTING_KEY, L"RC_EnableSourceControl", bResult)) - { - parent()->SetKey("RC_EnableSourceControl", bResult); - } -} - -#endif // AZ_TRAIT_OS_PLATFORM_APPLE -#endif // CRY_ENABLE_RC_HELPER - diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackendApple.h b/Code/CryEngine/CryCommon/EngineSettingsBackendApple.h deleted file mode 100644 index efc5a12bed..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackendApple.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ -#ifndef CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDAPPLE_H -#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDAPPLE_H -#pragma once - -#include "EngineSettingsBackend.h" - -#ifdef CRY_ENABLE_RC_HELPER - -class CEngineSettingsManager; -class SimpleRegistry; - -class CEngineSettingsBackendApple : public CEngineSettingsBackend -{ -public: - CEngineSettingsBackendApple(CEngineSettingsManager* parent, const wchar_t* moduleName = NULL); - ~CEngineSettingsBackendApple(); - - std::wstring GetModuleFilePath() const override; - - bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) override; - bool GetModuleSpecificIntEntry(const char* key, int& value) override; - bool GetModuleSpecificBoolEntry(const char* key, bool& value) override; - - bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) override; - bool SetModuleSpecificIntEntry(const char* key, const int& value) override; - bool SetModuleSpecificBoolEntry(const char* key, const bool& value) override; - - bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) override; - - void LoadEngineSettingsFromRegistry() override; - bool StoreEngineSettingsToRegistry() override; - -private: - SimpleRegistry *m_registry; - std::string m_registryFilePath; -}; - -#endif // CRY_ENABLE_RC_HELPER - -#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDAPPLE_H diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.cpp b/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.cpp deleted file mode 100644 index c2e9a67d57..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.cpp +++ /dev/null @@ -1,431 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ - - -#include "EngineSettingsBackendWin32.h" - -#ifdef CRY_ENABLE_RC_HELPER - -#include "AzCore/PlatformDef.h" - -#ifdef AZ_PLATFORM_WINDOWS - -#include "EngineSettingsManager.h" - -#include "platform.h" -#include - -#define REG_SOFTWARE L"Software\\" -#define REG_COMPANY_NAME L"Amazon\\" -#define REG_PRODUCT_NAME L"Open 3D Engine\\" -#define REG_SETTING L"Settings\\" -#define REG_BASE_SETTING_KEY REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME REG_SETTING - -EXTERN_C IMAGE_DOS_HEADER __ImageBase; - -using namespace SettingsManagerHelpers; - -static bool g_bWindowQuit; -static CEngineSettingsManager* g_pThis = 0; -static const unsigned int IDC_hEditRootPath = 100; -static const unsigned int IDC_hBtnBrowse = 101; - -namespace -{ - class RegKey - { - public: - RegKey(const wchar_t* key, bool writeable); - ~RegKey(); - void* pKey; - }; - - RegKey::RegKey(const wchar_t* key, bool writeable) - { - HKEY hKey; - LONG result; - if (writeable) - { - result = RegCreateKeyExW(HKEY_CURRENT_USER, key, 0, 0, 0, KEY_WRITE, 0, &hKey, 0); - } - else - { - result = RegOpenKeyExW(HKEY_CURRENT_USER, key, 0, KEY_READ, &hKey); - } - pKey = hKey; - } - - RegKey::~RegKey() - { - RegCloseKey((HKEY)pKey); - } -} - -CEngineSettingsBackendWin32::CEngineSettingsBackendWin32(CEngineSettingsManager* parent, const wchar_t* moduleName) - : CEngineSettingsBackend(parent, moduleName) -{ -} - -std::wstring CEngineSettingsBackendWin32::GetModuleFilePath() const -{ - wchar_t szFilename[_MAX_PATH]; - GetModuleFileNameW((HINSTANCE)&__ImageBase, szFilename, _MAX_PATH); - wchar_t drive[_MAX_DRIVE]; - wchar_t dir[_MAX_DIR]; - wchar_t fname[_MAX_FNAME]; - wchar_t ext[1] = L""; - _wsplitpath_s(szFilename, drive, dir, fname, ext); - _wmakepath_s(szFilename, drive, dir, fname, L"ini"); - return szFilename; -} - -bool CEngineSettingsBackendWin32::GetModuleSpecificStringEntryUtf16(const char* key, CWCharBuffer wbuffer) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), false); - if (!superKey.pKey) - { - wbuffer[0] = 0; - return false; - } - if (!GetRegValue(superKey.pKey, key, wbuffer)) - { - wbuffer[0] = 0; - return false; - } - - return true; -} - -bool CEngineSettingsBackendWin32::GetModuleSpecificIntEntry(const char* key, int& value) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), false); - if (!superKey.pKey) - { - return false; - } - if (!GetRegValue(superKey.pKey, key, value)) - { - value = 0; - return false; - } - - return true; -} - -bool CEngineSettingsBackendWin32::GetModuleSpecificBoolEntry(const char* key, bool& value) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), false); - if (!superKey.pKey) - { - return false; - } - if (!GetRegValue(superKey.pKey, key, value)) - { - value = false; - return false; - } - - return true; -} - -bool CEngineSettingsBackendWin32::SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), true); - if (superKey.pKey) - { - return SetRegValue(superKey.pKey, key, str); - } - return false; -} - -bool CEngineSettingsBackendWin32::SetModuleSpecificIntEntry(const char* key, const int& value) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), true); - if (superKey.pKey) - { - return SetRegValue(superKey.pKey, key, value); - } - return false; -} - -bool CEngineSettingsBackendWin32::SetModuleSpecificBoolEntry(const char* key, const bool& value) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), true); - if (superKey.pKey) - { - return SetRegValue(superKey.pKey, key, value); - } - return false; -} - -bool CEngineSettingsBackendWin32::GetInstalledBuildRootPathUtf16(const int index, CWCharBuffer name, CWCharBuffer path) -{ - RegKey key(REG_BASE_SETTING_KEY L"O3DEExport\\ProjectBuilds", false); - if (key.pKey) - { - DWORD type; - DWORD nameSizeInBytes = DWORD(name.getSizeInBytes()); - DWORD pathSizeInBytes = DWORD(path.getSizeInBytes()); - LONG result = RegEnumValueW((HKEY)key.pKey, index, name.getPtr(), &nameSizeInBytes, NULL, &type, (BYTE*)path.getPtr(), &pathSizeInBytes); - if (result == ERROR_SUCCESS) - { - return true; - } - } - return false; -} - -bool CEngineSettingsBackendWin32::StoreEngineSettingsToRegistry() -{ - // make sure the path in registry exists - { - RegKey key0(REG_SOFTWARE REG_COMPANY_NAME, true); - if (!key0.pKey) - { - RegKey software(REG_SOFTWARE, true); - HKEY hKey; - RegCreateKeyW((HKEY)software.pKey, REG_COMPANY_NAME, &hKey); - if (!hKey) - { - return false; - } - } - - RegKey key1(REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME, true); - if (!key1.pKey) - { - RegKey softwareCompany(REG_SOFTWARE REG_COMPANY_NAME, true); - HKEY hKey; - RegCreateKeyW((HKEY)softwareCompany.pKey, REG_COMPANY_NAME, &hKey); - if (!hKey) - { - return false; - } - } - - RegKey key2(REG_BASE_SETTING_KEY, true); - if (!key2.pKey) - { - RegKey softwareCompanyProduct(REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME, true); - HKEY hKey; - RegCreateKeyW((HKEY)key2.pKey, REG_SETTING, &hKey); - if (!hKey) - { - return false; - } - } - } - - bool bRet = true; - - RegKey key(REG_BASE_SETTING_KEY, true); - if (!key.pKey) - { - bRet = false; - } - else - { - wchar_t buffer[1024]; - - // ResourceCompiler Specific - - if (parent()->GetValueByRef("RC_ShowWindow", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - SetRegValue(key.pKey, "RC_ShowWindow", b); - } - - if (parent()->GetValueByRef("RC_HideCustom", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - SetRegValue(key.pKey, "RC_HideCustom", b); - } - - if (parent()->GetValueByRef("RC_Parameters", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - SetRegValue(key.pKey, "RC_Parameters", buffer); - } - - if (parent()->GetValueByRef("RC_EnableSourceControl", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - SetRegValue(key.pKey, "RC_EnableSourceControl", b); - } - } - - return bRet; -} - -void CEngineSettingsBackendWin32::LoadEngineSettingsFromRegistry() -{ - wchar_t buffer[1024]; - - bool bResult; - - // Engine Specific (Deprecated value) - RegKey key(REG_BASE_SETTING_KEY, false); - if (key.pKey) - { - if (GetRegValue(key.pKey, "RootPath", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - parent()->SetKey("ENG_RootPath", buffer); - } - - // Engine Specific - if (GetRegValue(key.pKey, "ENG_RootPath", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - parent()->SetKey("ENG_RootPath", buffer); - } - - // ResourceCompiler Specific - if (GetRegValue(key.pKey, "RC_ShowWindow", bResult)) - { - parent()->SetKey("RC_ShowWindow", bResult); - } - if (GetRegValue(key.pKey, "RC_HideCustom", bResult)) - { - parent()->SetKey("RC_HideCustom", bResult); - } - if (GetRegValue(key.pKey, "RC_Parameters", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - parent()->SetKey("RC_Parameters", buffer); - } - if (GetRegValue(key.pKey, "RC_EnableSourceControl", bResult)) - { - parent()->SetKey("RC_EnableSourceControl", bResult); - } - } -} - -bool CEngineSettingsBackendWin32::SetRegValue(void* key, const char* valueName, const wchar_t* value) -{ - CFixedString name; - name.appendAscii(valueName); - - size_t const sizeInBytes = (wcslen(value) + 1) * sizeof(value[0]); - return (ERROR_SUCCESS == RegSetValueExW((HKEY)key, name.c_str(), 0, REG_SZ, (BYTE*)value, DWORD(sizeInBytes))); -} - -bool CEngineSettingsBackendWin32::SetRegValue(void* key, const char* valueName, bool value) -{ - CFixedString name; - name.appendAscii(valueName); - - DWORD dwVal = value; - return (ERROR_SUCCESS == RegSetValueExW((HKEY)key, name.c_str(), 0, REG_DWORD, (BYTE*)&dwVal, sizeof(dwVal))); -} - -bool CEngineSettingsBackendWin32::SetRegValue(void* key, const char* valueName, int value) -{ - CFixedString name; - name.appendAscii(valueName); - - DWORD dwVal = value; - return (ERROR_SUCCESS == RegSetValueExW((HKEY)key, name.c_str(), 0, REG_DWORD, (BYTE*)&dwVal, sizeof(dwVal))); -} - -bool CEngineSettingsBackendWin32::GetRegValue(void* key, const char* valueName, CWCharBuffer wbuffer) -{ - if (wbuffer.getSizeInElements() <= 0) - { - return false; - } - - CFixedString name; - name.appendAscii(valueName); - - DWORD type; - DWORD sizeInBytes = DWORD(wbuffer.getSizeInBytes()); - if (ERROR_SUCCESS != RegQueryValueExW((HKEY)key, name.c_str(), NULL, &type, (BYTE*)wbuffer.getPtr(), &sizeInBytes)) - { - wbuffer[0] = 0; - return false; - } - - const size_t sizeInElements = sizeInBytes / sizeof(wbuffer[0]); - if (sizeInElements > wbuffer.getSizeInElements()) // paranoid check - { - wbuffer[0] = 0; - return false; - } - - // According to MSDN documentation for RegQueryValueEx(), strings returned by the function - // are not zero-terminated sometimes, so we need to terminate them by ourselves. - if (wbuffer[sizeInElements - 1] != 0) - { - if (sizeInElements >= wbuffer.getSizeInElements()) - { - // No space left to put terminating zero character - wbuffer[0] = 0; - return false; - } - wbuffer[sizeInElements] = 0; - } - - return true; -} - -bool CEngineSettingsBackendWin32::GetRegValue(void* key, const char* valueName, bool& value) -{ - CFixedString name; - name.appendAscii(valueName); - - // Open the appropriate registry key - DWORD type, dwVal = 0, size = sizeof(dwVal); - bool res = (ERROR_SUCCESS == RegQueryValueExW((HKEY)key, name.c_str(), NULL, &type, (BYTE*)&dwVal, &size)); - if (res) - { - value = (dwVal != 0); - } - else - { - wchar_t buffer[100]; - res = GetRegValue(key, valueName, CWCharBuffer(buffer, sizeof(buffer))); - if (res) - { - value = (wcscmp(buffer, L"true") == 0); - } - } - return res; -} - -bool CEngineSettingsBackendWin32::GetRegValue(void* key, const char* valueName, int& value) -{ - CFixedString name; - name.appendAscii(valueName); - - // Open the appropriate registry key - DWORD type, dwVal = 0, size = sizeof(dwVal); - - bool res = (ERROR_SUCCESS == RegQueryValueExW((HKEY)key, name.c_str(), NULL, &type, (BYTE*)&dwVal, &size)); - if (res) - { - value = dwVal; - } - - return res; -} - -#endif // AZ_PLATFORM_WINDOWS -#endif // CRY_ENABLE_RC_HELPER diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.h b/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.h deleted file mode 100644 index 47b4772ede..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ -#ifndef CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDWIN32_H -#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDWIN32_H -#pragma once - -#include "EngineSettingsBackend.h" - -#ifdef CRY_ENABLE_RC_HELPER - -class CEngineSettingsManager; - -class CEngineSettingsBackendWin32 : public CEngineSettingsBackend -{ -public: - CEngineSettingsBackendWin32(CEngineSettingsManager* parent, const wchar_t* moduleName = NULL); - - std::wstring GetModuleFilePath() const override; - - bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) override; - bool GetModuleSpecificIntEntry(const char* key, int& value) override; - bool GetModuleSpecificBoolEntry(const char* key, bool& value) override; - - bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) override; - bool SetModuleSpecificIntEntry(const char* key, const int& value) override; - bool SetModuleSpecificBoolEntry(const char* key, const bool& value) override; - - bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) override; - - void LoadEngineSettingsFromRegistry() override; - bool StoreEngineSettingsToRegistry() override; - -protected: - bool SetRegValue(void* key, const char* valueName, const wchar_t* value); - bool SetRegValue(void* key, const char* valueName, bool value); - bool SetRegValue(void* key, const char* valueName, int value); - bool GetRegValue(void* key, const char* valueName, SettingsManagerHelpers::CWCharBuffer wbuffer); - bool GetRegValue(void* key, const char* valueName, bool& value); - bool GetRegValue(void* key, const char* valueName, int& value); -}; - -#endif // CRY_ENABLE_RC_HELPER - -#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDWIN32_H diff --git a/Code/CryEngine/CryCommon/EngineSettingsManager.cpp b/Code/CryEngine/CryCommon/EngineSettingsManager.cpp deleted file mode 100644 index 13ad568217..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsManager.cpp +++ /dev/null @@ -1,479 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - - -#include "ProjectDefines.h" -#include "EngineSettingsManager.h" - -#if defined(CRY_ENABLE_RC_HELPER) - -#include // assert() -#include "EngineSettingsBackend.h" - -#include "AzCore/PlatformDef.h" -#include "platform.h" - -#if defined(AZ_PLATFORM_WINDOWS) -#include "EngineSettingsBackendWin32.h" -#include -#elif AZ_TRAIT_OS_PLATFORM_APPLE -#include "EngineSettingsBackendApple.h" -#endif - - -#include -#include - -#define INFOTEXT L"Please specify the directory of your CryENGINE installation (RootPath):" - - -using namespace SettingsManagerHelpers; - - -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -CEngineSettingsManager::CEngineSettingsManager(const wchar_t* moduleName, const wchar_t* iniFileName) - : m_hWndParent(0) - , m_backend(NULL) -{ - m_sModuleName.clear(); - -#if defined(AZ_PLATFORM_WINDOWS) - m_backend = new CEngineSettingsBackendWin32(this, moduleName); -#elif AZ_TRAIT_OS_PLATFORM_APPLE - m_backend = new CEngineSettingsBackendApple(this, moduleName); -#endif - assert(m_backend); - - // std initialization - RestoreDefaults(); - - // try to load content from INI file - if (moduleName != NULL) - { - m_sModuleName = moduleName; - - if (iniFileName == NULL) - { - // find INI filename located in module path - m_sModuleFileName = m_backend->GetModuleFilePath().c_str(); - } - else - { - m_sModuleFileName = iniFileName; - } - - if (LoadValuesFromConfigFile(m_sModuleFileName.c_str())) - { - m_bGetDataFromBackend = false; - return; - } - } - - m_bGetDataFromBackend = true; - - // load basic content from registry - LoadEngineSettingsFromRegistry(); -} - -////////////////////////////////////////////////////////////////////////// -CEngineSettingsManager::~CEngineSettingsManager() -{ - delete m_backend, m_backend = NULL; -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::RestoreDefaults() -{ - // Engine - SetKey("ENG_RootPath", L""); - - // RC - SetKey("RC_ShowWindow", false); - SetKey("RC_HideCustom", false); - SetKey("RC_Parameters", L""); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) -{ - if (wbuffer.getSizeInElements() <= 0) - { - return false; - } - - if (!m_bGetDataFromBackend) - { - if (!HasKey(key)) - { - wbuffer[0] = 0; - return false; - } - if (!GetValueByRef(key, wbuffer)) - { - wbuffer[0] = 0; - return false; - } - } - else - { - assert(m_backend); - return m_backend->GetModuleSpecificStringEntryUtf16(key, wbuffer); - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetModuleSpecificStringEntryUtf8(const char* key, SettingsManagerHelpers::CCharBuffer buffer) -{ - if (buffer.getSizeInElements() <= 0) - { - return false; - } - - wchar_t wBuffer[1024]; - - if (!GetModuleSpecificStringEntryUtf16(key, SettingsManagerHelpers::CWCharBuffer(wBuffer, sizeof(wBuffer)))) - { - buffer[0] = 0; - return false; - } - - SettingsManagerHelpers::ConvertUtf16ToUtf8(wBuffer, buffer); - - return true; -} - - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetModuleSpecificIntEntry(const char* key, int& value) -{ - value = 0; - - if (!m_bGetDataFromBackend) - { - if (!HasKey(key)) - { - return false; - } - if (!GetValueByRef(key, value)) - { - return false; - } - } - else - { - assert(m_backend); - return m_backend->GetModuleSpecificIntEntry(key, value); - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetModuleSpecificBoolEntry(const char* key, bool& value) -{ - value = false; - - if (!m_bGetDataFromBackend) - { - if (!HasKey(key)) - { - return false; - } - if (!GetValueByRef(key, value)) - { - return false; - } - } - else - { - assert(m_backend); - return m_backend->GetModuleSpecificBoolEntry(key, value); - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) -{ - SetKey(key, str); - if (!m_bGetDataFromBackend) - { - return StoreData(); - } - - assert(m_backend); - return m_backend->SetModuleSpecificStringEntryUtf16(key, str); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::SetModuleSpecificIntEntry(const char* key, const int& value) -{ - SetKey(key, value); - if (!m_bGetDataFromBackend) - { - return StoreData(); - } - - assert(m_backend); - return m_backend->SetModuleSpecificIntEntry(key, value); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::SetModuleSpecificBoolEntry(const char* key, const bool& value) -{ - SetKey(key, value); - if (!m_bGetDataFromBackend) - { - return StoreData(); - } - - assert(m_backend); - return m_backend->SetModuleSpecificBoolEntry(key, value); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::SetModuleSpecificStringEntryUtf8(const char* key, const char* str) -{ - wchar_t wbuffer[512]; - SettingsManagerHelpers::ConvertUtf8ToUtf16(str, SettingsManagerHelpers::CWCharBuffer(wbuffer, sizeof(wbuffer))); - - return SetModuleSpecificStringEntryUtf16(key, wbuffer); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::HasKey(const char* key) -{ - return m_keyValueArray.find(key) != 0; -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::SetKey(const char* key, const wchar_t* value) -{ - m_keyValueArray.set(key, value); -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::SetKey(const char* key, bool value) -{ - m_keyValueArray.set(key, (value ? L"true" : L"false")); -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::SetKey(const char* key, int value) -{ - m_keyValueArray.set(key, std::to_wstring(value).c_str()); -} - -bool CEngineSettingsManager::GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) -{ - assert(m_backend); - return m_backend->GetInstalledBuildRootPathUtf16(index, name, path); -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::SetParentDialog(size_t window) -{ - m_hWndParent = window; -} - - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::StoreData() -{ - if (m_bGetDataFromBackend) - { - bool res = StoreEngineSettingsToRegistry(); - - if (!res) - { -#ifdef AZ_PLATFORM_WINDOWS - MessageBoxA(reinterpret_cast(m_hWndParent), "Could not store data to registry.", "Error", MB_OK | MB_ICONERROR); -#endif - } - return res; - } - - // store data to INI file - - FILE* file; -#ifdef AZ_PLATFORM_WINDOWS - _wfopen_s(&file, m_sModuleFileName.c_str(), L"wb"); -#else - char fname[MAX_PATH]; - memset(fname, 0, MAX_PATH); - wcstombs(fname, m_sModuleFileName.c_str(), MAX_PATH); - file = fopen(fname, "wb"); -#endif - if (file == NULL) - { - return false; - } - - char buffer[2048]; - - for (size_t i = 0; i < m_keyValueArray.size(); ++i) - { - const SKeyValue& kv = m_keyValueArray[i]; - - fprintf_s(file, kv.key.c_str()); - fprintf_s(file, " = "); - - if (kv.value.length() > 0) - { - SettingsManagerHelpers::ConvertUtf16ToUtf8(kv.value.c_str(), SettingsManagerHelpers::CCharBuffer(buffer, sizeof(buffer))); - fprintf_s(file, "%s", buffer); - } - - fprintf_s(file, "\r\n"); - } - - fclose(file); - - return true; -} - - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::LoadValuesFromConfigFile(const wchar_t* szFileName) -{ - m_keyValueArray.clear(); - - // read file to memory - - FILE* file; -#ifdef AZ_PLATFORM_WINDOWS - _wfopen_s(&file, szFileName, L"rb"); -#else - char fname[MAX_PATH]; - memset(fname, 0, MAX_PATH); - wcstombs(fname, szFileName, MAX_PATH); - file = fopen(fname, "rb"); -#endif - if (file == NULL) - { - return false; - } - - fseek(file, 0, SEEK_END); - long size = ftell(file); - fseek(file, 0, SEEK_SET); - char* data = new char[size + 1]; - fread_s(data, size, 1, size, file); - fclose(file); - - wchar_t wBuffer[1024]; - - // parse file for root path - - int start = 0, end = 0; - while (end < size) - { - while (end < size && data[end] != '\n') - { - end++; - } - - memcpy(data, &data[start], end - start); - data[end - start] = 0; - start = end = end + 1; - - CFixedString line(data); - size_t equalsOfs; - for (equalsOfs = 0; equalsOfs < line.length(); ++equalsOfs) - { - if (line[equalsOfs] == '=') - { - break; - } - } - if (equalsOfs < line.length()) - { - CFixedString key; - CFixedString value; - - key.appendAscii(line.c_str(), equalsOfs); - key.trim(); - - SettingsManagerHelpers::ConvertUtf8ToUtf16(line.c_str() + equalsOfs + 1, SettingsManagerHelpers::CWCharBuffer(wBuffer, sizeof(wBuffer))); - value.append(wBuffer); - value.trim(); - - m_keyValueArray.set(key.c_str(), value.c_str()); - } - } - delete[] data; - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::StoreEngineSettingsToRegistry() -{ - assert(m_backend); - return m_backend->StoreEngineSettingsToRegistry(); -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::LoadEngineSettingsFromRegistry() -{ - assert(m_backend); - m_backend->LoadEngineSettingsFromRegistry(); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetValueByRef(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) const -{ - if (wbuffer.getSizeInElements() <= 0) - { - return false; - } - - const SKeyValue* p = m_keyValueArray.find(key); - if (!p || (p->value.length() + 1) > wbuffer.getSizeInElements()) - { - wbuffer[0] = 0; - return false; - } - azwcscpy(wbuffer.getPtr(), wbuffer.getSizeInElements(), p->value.c_str()); - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetValueByRef(const char* key, bool& value) const -{ - wchar_t buffer[100]; - if (!GetValueByRef(key, SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - return false; - } - value = (wcscmp(buffer, L"true") == 0); - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetValueByRef(const char* key, int& value) const -{ - wchar_t buffer[100]; - if (!GetValueByRef(key, SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - return false; - } - value = wcstol(buffer, 0, 10); - return true; -} - -#endif //(CRY_ENABLE_RC_HELPER) diff --git a/Code/CryEngine/CryCommon/EngineSettingsManager.h b/Code/CryEngine/CryCommon/EngineSettingsManager.h deleted file mode 100644 index 95216b3bf3..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsManager.h +++ /dev/null @@ -1,89 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_ENGINESETTINGSMANAGER_H -#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSMANAGER_H -#pragma once - -#include "ProjectDefines.h" - -#if defined(CRY_ENABLE_RC_HELPER) - -#include "SettingsManagerHelpers.h" - -class CEngineSettingsBackend; - -////////////////////////////////////////////////////////////////////////// -// Manages storage and loading of all information for tools and CryENGINE, by either registry or an INI file. -// Information can be read and set by key-to-value functions. -// Specific information can be set by a dialog application called by this class. -// If the engine root path is not found, a fall-back dialog is opened. -class CEngineSettingsManager -{ -public: - // prepares CEngineSettingsManager to get requested information either from registry or an INI file, - // if existent as a file with name an directory equal to the module, or from registry. - CEngineSettingsManager(const wchar_t* moduleName = NULL, const wchar_t* iniFileName = NULL); - ~CEngineSettingsManager(); - - void RestoreDefaults(); - - // stores/loads user specific information for modules to/from registry or INI file - bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer); - bool GetModuleSpecificStringEntryUtf8(const char* key, SettingsManagerHelpers::CCharBuffer buffer); - bool GetModuleSpecificIntEntry(const char* key, int& value); - bool GetModuleSpecificBoolEntry(const char* key, bool& value); - - bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str); - bool SetModuleSpecificStringEntryUtf8(const char* key, const char* str); - bool SetModuleSpecificIntEntry(const char* key, const int& value); - bool SetModuleSpecificBoolEntry(const char* key, const bool& value); - - bool GetValueByRef(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) const; - bool GetValueByRef(const char* key, bool& value) const; - bool GetValueByRef(const char* key, int& value) const; - - void SetKey(const char* key, const wchar_t* value); - void SetKey(const char* key, bool value); - void SetKey(const char* key, int value); - - bool StoreData(); - - bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path); - - void SetParentDialog(size_t window); - -private: - bool HasKey(const char* key); - - void LoadEngineSettingsFromRegistry(); - bool StoreEngineSettingsToRegistry(); - - // parses a file and stores all flags in a private key-value-map - bool LoadValuesFromConfigFile(const wchar_t* szFileName); - -private: - CEngineSettingsBackend *m_backend; - - SettingsManagerHelpers::CFixedString m_sModuleName; // name to store key-value pairs of modules in (registry) or to identify INI file - SettingsManagerHelpers::CFixedString m_sModuleFileName; // used in case of data being loaded from INI file - bool m_bGetDataFromBackend; - SettingsManagerHelpers::CKeyValueArray<30> m_keyValueArray; - - void* m_hBtnBrowse; - size_t m_hWndParent; -}; - -#endif // CRY_ENABLE_RC_HELPER - -#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSMANAGER_H diff --git a/Code/CryEngine/CryCommon/IFlares.h b/Code/CryEngine/CryCommon/IFlares.h deleted file mode 100644 index d1626a83d9..0000000000 --- a/Code/CryEngine/CryCommon/IFlares.h +++ /dev/null @@ -1,228 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_IFLARES_H -#define CRYINCLUDE_CRYCOMMON_IFLARES_H -#pragma once - -#include // <> required for Interfuscator -#include // <> required for Interfuscator -#include "smartptr.h" - -struct IShader; -class CCamera; - -class __MFPA -{ -}; -class __MFPB -{ -}; -#define MFP_SIZE_ENFORCE : public __MFPA, public __MFPB - -enum EFlareType -{ - eFT__Base__, - eFT_Root, - eFT_Group, - eFT_Ghost, - eFT_MultiGhosts, - eFT_Glow, - eFT_ChromaticRing, - eFT_IrisShafts, - eFT_CameraOrbs, - eFT_ImageSpaceShafts, - eFT_Streaks, - eFT_Reference, - eFT_Proxy, - eFT_Max -}; - -#define FLARE_LIBS_PATH "libs/flares/" -#define FLARE_EXPORT_FILE "LensFlareList.xml" -#define FLARE_EXPORT_FILE_VERSION "1" - -struct FlareInfo -{ - EFlareType type; - const char* name; -#if defined(FLARES_SUPPORT_EDITING) - const char* imagename; -#endif -}; - -#if defined(FLARES_SUPPORT_EDITING) -# define ADD_FLARE_INFO(type, name, imagename) {type, name, imagename} -#else -# define ADD_FLARE_INFO(type, name, imagename) {type, name} -#endif - -class FlareInfoArray -{ -public: - struct Props - { - const FlareInfo* p; - size_t size; - }; - - static const Props Get() - { - static const FlareInfo flareInfoArray[] = - { - ADD_FLARE_INFO(eFT__Base__, "__Base__", NULL), - ADD_FLARE_INFO(eFT_Root, "Root", NULL), - ADD_FLARE_INFO(eFT_Group, "Group", NULL), - ADD_FLARE_INFO(eFT_Ghost, "Ghost", "EngineAssets/Textures/flares/icons/ghost.dds"), - ADD_FLARE_INFO(eFT_MultiGhosts, "Multi Ghost", "EngineAssets/Textures/flares/icons/multi_ghost.dds"), - ADD_FLARE_INFO(eFT_Glow, "Glow", "EngineAssets/Textures/flares/icons/glow.dds"), - ADD_FLARE_INFO(eFT_ChromaticRing, "ChromaticRing", "EngineAssets/Textures/flares/icons/ring.dds"), - ADD_FLARE_INFO(eFT_IrisShafts, "IrisShafts", "EngineAssets/Textures/flares/icons/iris_shafts.dds"), - ADD_FLARE_INFO(eFT_CameraOrbs, "CameraOrbs", "EngineAssets/Textures/flares/icons/orbs.dds"), - ADD_FLARE_INFO(eFT_ImageSpaceShafts, "Vol Shafts", "EngineAssets/Textures/flares/icons/vol_shafts.dds"), - ADD_FLARE_INFO(eFT_Streaks, "Streaks", "EngineAssets/Textures/flares/icons/iris_shafts.dds") - }; - - Props ret; - ret.p = flareInfoArray; - ret.size = sizeof(flareInfoArray) / sizeof(flareInfoArray[0]); - return ret; - } - -private: - FlareInfoArray(); - ~FlareInfoArray(); -}; - -struct SLensFlareRenderParam -{ - SLensFlareRenderParam() - : pCamera(NULL) - , pShader(NULL) - { - } - ~SLensFlareRenderParam(){} - bool IsValid() const - { - return pCamera && pShader; - } - CCamera* pCamera; - IShader* pShader; -}; - -class ISoftOcclusionQuery -{ -public: - // - virtual ~ISoftOcclusionQuery() {} - - virtual void AddRef() = 0; - virtual void Release() = 0; - // -}; - -class IOpticsElementBase MFP_SIZE_ENFORCE -{ -public: - - IOpticsElementBase() - : m_nRefCount(0) - { - } - void AddRef() - { - CryInterlockedIncrement(&m_nRefCount); - } - void Release() - { - if (CryInterlockedDecrement(&m_nRefCount) <= 0) - { - delete this; - } - } - - // - virtual EFlareType GetType() = 0; - virtual bool IsGroup() const = 0; - virtual string GetName() const = 0; - virtual void SetName(const char* ch_name) = 0; - virtual void Load(IXmlNode* pNode) = 0; - - virtual IOpticsElementBase* GetParent() const = 0; - virtual ~IOpticsElementBase() { - } - - virtual bool IsEnabled() const = 0; - - virtual void AddElement(IOpticsElementBase* pElement) = 0; - virtual void InsertElement(int nPos, IOpticsElementBase* pElement) = 0; - virtual void Remove(int i) = 0; - virtual void RemoveAll() = 0; - virtual int GetElementCount() const = 0; - virtual IOpticsElementBase* GetElementAt(int i) const = 0; - - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - virtual void Invalidate() = 0; - - virtual void Render(SLensFlareRenderParam* pParam, const Vec3& vPos) = 0; - - virtual void SetOpticsReference([[maybe_unused]] IOpticsElementBase* pReference) {} - virtual IOpticsElementBase* GetOpticsReference() const { return NULL; } - // - -#if defined(FLARES_SUPPORT_EDITING) - virtual AZStd::vector GetEditorParamGroups() = 0; -#endif - - ///Basic Setters/////////////////////////////////////////////////////////////// - virtual void SetEnabled(bool enabled) { (void)enabled; } - virtual void SetSize(float size) { (void)size; } - virtual void SetPerspectiveFactor(float perspectiveFactor) { (void)perspectiveFactor; } - virtual void SetDistanceFadingFactor(float distanceFadingFactor) { (void)distanceFadingFactor; } - virtual void SetBrightness(float brightness) { (void)brightness; } - virtual void SetColor(ColorF color) { (void)color; } - virtual void SetMovement(Vec2 movement) { (void)movement; } - virtual void SetTransform(const Matrix33& xform) { (void)xform; } - virtual void SetOccBokehEnabled(bool occBokehEnabled) { (void)occBokehEnabled; } - virtual void SetOrbitAngle(float orbitAngle) { (void)orbitAngle; } - virtual void SetSensorSizeFactor(float sizeFactor) { (void)sizeFactor; } - virtual void SetSensorBrightnessFactor(float brightnessFactor) { (void)brightnessFactor; } - virtual void SetAutoRotation(bool autoRotation) { (void)autoRotation; } - virtual void SetAspectRatioCorrection(bool aspectRatioCorrection) { (void)aspectRatioCorrection; } - //////////////////////////////////////////////////////////////////////////////// - -private: - - volatile int m_nRefCount; -}; - -class IOpticsManager -{ -public: - // - virtual ~IOpticsManager(){} - virtual void Reset() = 0; - virtual IOpticsElementBase* Create(EFlareType type) const = 0; - virtual bool Load(const char* fullFlareName, int& nOutIndex, bool forceReload = false) = 0; - virtual bool Load(XmlNodeRef& rootNode, int& nOutIndex) = 0; - virtual IOpticsElementBase* GetOptics(int nIndex) = 0; - virtual bool AddOptics(IOpticsElementBase* pOptics, const char* name, int& nOutNewIndex, bool allowReplace = false) = 0; - virtual bool Rename(const char* fullFlareName, const char* newFullFlareName) = 0; - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - virtual void Invalidate() = 0; - // -}; - -typedef _smart_ptr IOpticsElementBasePtr; - -#endif // CRYINCLUDE_CRYCOMMON_IFLARES_H diff --git a/Code/CryEngine/CryCommon/IMaterialEffects.h b/Code/CryEngine/CryCommon/IMaterialEffects.h deleted file mode 100644 index 73e03a1d80..0000000000 --- a/Code/CryEngine/CryCommon/IMaterialEffects.h +++ /dev/null @@ -1,504 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Interface to the Material Effects System - - -#ifndef CRYINCLUDE_CRYCOMMON_IMATERIALEFFECTS_H -#define CRYINCLUDE_CRYCOMMON_IMATERIALEFFECTS_H -#pragma once - -#if !defined(_RELEASE) - #define MATERIAL_EFFECTS_DEBUG -#endif - - -#include "CryFixedArray.h" - -struct IRenderNode; -struct ISurfaceType; - -////////////////////////////////////////////////////////////////////////// -enum EMFXPlayFlags -{ - eMFXPF_Disable_Delay = BIT(0), - eMFXPF_Audio = BIT(1), - eMFXPF_Decal = BIT(2), - eMFXPF_Particles = BIT(3), - eMFXPF_Deprecated0 = BIT(4), // formerly eMFXPF_Flowgraph - eMFXPF_ForceFeedback = BIT(5), - eMFXPF_All = (eMFXPF_Audio | eMFXPF_Decal | eMFXPF_Particles | eMFXPF_Deprecated0 | eMFXPF_ForceFeedback), -}; - -#define MFX_INVALID_ANGLE (gf_PI2 + 1) - -////////////////////////////////////////////////////////////////////////// -struct SMFXAudioEffectRtpc -{ - SMFXAudioEffectRtpc() - { - rtpcName = ""; - rtpcValue = 0.0f; - } - const char* rtpcName; - float rtpcValue; -}; - -////////////////////////////////////////////////////////////////////////// -struct SMFXRunTimeEffectParams -{ - static const int MAX_AUDIO_RTPCS = 4; - - SMFXRunTimeEffectParams() - : playSoundFP(false) - , playflags(eMFXPF_All) - , fLastTime(0.0f) - , srcSurfaceId(0) - , trgSurfaceId(0) - , srcRenderNode(0) - , trgRenderNode(0) - , partID(0) - , pos(ZERO) - , decalPos(ZERO) - , normal(0.0f, 0.0f, 1.0f) - , angle(MFX_INVALID_ANGLE) - , scale(1.0f) - , audioComponentOffset(ZERO) - , numAudioRtpcs(0) - , fDecalPlacementTestMaxSize(1000.f) - { - dir[0].Set(0.0f, 0.0f, -1.0f); - dir[1].Set(0.0f, 0.0f, 1.0f); - } - - bool AddAudioRtpc(const char* name, float val) - { - if (numAudioRtpcs < MAX_AUDIO_RTPCS) - { - audioRtpcs[numAudioRtpcs].rtpcName = name; - audioRtpcs[numAudioRtpcs].rtpcValue = val; - ++numAudioRtpcs; - return true; - } - return false; - } - - void ResetAudioRtpcs() - { - numAudioRtpcs = 0; - } - -public: - uint16 playSoundFP; // Sets 1p/3p audio switch - uint16 playflags; // See EMFXPlayFlags - float fLastTime; // Last time this effect was played - float fDecalPlacementTestMaxSize; - - int srcSurfaceId; - int trgSurfaceId; - IRenderNode* srcRenderNode; - IRenderNode* trgRenderNode; - int partID; - - Vec3 pos; - Vec3 decalPos; - Vec3 dir[2]; - Vec3 normal; - float angle; - float scale; - - // audio related - Vec3 audioComponentOffset; // in case of audio component, uses this offset - - SMFXAudioEffectRtpc audioRtpcs[MAX_AUDIO_RTPCS]; - uint32 numAudioRtpcs; -}; - -struct SMFXBreakageParams -{ - enum EBreakageRequestFlags - { - eBRF_Matrix = BIT(0), - eBRF_HitPos = BIT(1), - eBRF_HitImpulse = BIT(2), - eBRF_Velocity = BIT(3), - eBRF_ExplosionImpulse = BIT(4), - eBRF_Mass = BIT(5), - eBFR_Entity = BIT(6), - }; - - SMFXBreakageParams() - : m_flags(0) - , m_worldTM(IDENTITY) - , m_vHitPos(ZERO) - , m_vHitImpulse(IDENTITY) - , m_vVelocity(ZERO) - , m_fExplosionImpulse(1.0f) - , m_fMass(0.0f) - { - } - - - // Matrix - void SetMatrix(const Matrix34& worldTM) - { - m_worldTM = worldTM; - SetFlag(eBRF_Matrix); - } - - const Matrix34& GetMatrix() const - { - return m_worldTM; - } - - // HitPos - void SetHitPos(const Vec3& vHitPos) - { - m_vHitPos = vHitPos; - SetFlag(eBRF_HitPos); - } - - const Vec3& GetHitPos() const - { - return m_vHitPos; - } - - // HitImpulse - void SetHitImpulse(const Vec3& vHitImpulse) - { - m_vHitImpulse = vHitImpulse; - SetFlag(eBRF_HitImpulse); - } - - const Vec3& GetHitImpulse() const - { - return m_vHitImpulse; - } - - // Velocity - void SetVelocity(const Vec3& vVelocity) - { - m_vVelocity = vVelocity; - SetFlag(eBRF_Velocity); - } - - const Vec3& GetVelocity() const - { - return m_vVelocity; - } - - // Explosion Impulse - void SetExplosionImpulse(float fExplosionImpulse) - { - m_fExplosionImpulse = fExplosionImpulse; - SetFlag(eBRF_ExplosionImpulse); - } - - float GetExplosionImpulse() const - { - return m_fExplosionImpulse; - } - - // Mass - void SetMass(float fMass) - { - m_fMass = fMass; - SetFlag(eBRF_Mass); - } - - float GetMass() const - { - return m_fMass; - } - - // Checking for flags - bool CheckFlag(EBreakageRequestFlags flag) const - { - return (m_flags & flag) != 0; - } - -protected: - void SetFlag(EBreakageRequestFlags flag) - { - m_flags |= flag; - } - - void ClearFlag(EBreakageRequestFlags flag) - { - m_flags &= ~flag; - } - - uint32 m_flags; - Matrix34 m_worldTM; - Vec3 m_vHitPos; - Vec3 m_vHitImpulse; - Vec3 m_vVelocity; - float m_fExplosionImpulse; - float m_fMass; -}; - -class IMFXParticleParams -{ -public: - IMFXParticleParams() - : name(NULL) - , userdata(NULL) - , scale(1.0f) - { - } - - const char* name; - const char* userdata; - float scale; -}; - -class SMFXParticleListNode -{ -public: - static SMFXParticleListNode* Create(); - void Destroy(); - static void FreePool(); - - IMFXParticleParams m_particleParams; - SMFXParticleListNode* pNext; - -private: - SMFXParticleListNode() - { - pNext = NULL; - } - ~SMFXParticleListNode() {} -}; - -class IMFXAudioParams -{ - const static uint MAX_SWITCH_DATA_ELEMENTS = 4; - -public: - - struct SSwitchData - { - SSwitchData() - : switchName(NULL) - , switchStateName(NULL) - { - } - - const char* switchName; - const char* switchStateName; - }; - - IMFXAudioParams() - : triggerName(NULL) - { - } - const char* triggerName; - - CryFixedArray triggerSwitches; -}; - -class SMFXAudioListNode -{ -public: - static SMFXAudioListNode* Create(); - void Destroy(); - static void FreePool(); - - IMFXAudioParams m_audioParams; - SMFXAudioListNode* pNext; - -private: - SMFXAudioListNode() - : pNext(NULL) - { - } - - ~SMFXAudioListNode() - { - } -}; - -class IMFXDecalParams -{ -public: - IMFXDecalParams() - { - filename = 0; - material = 0; - minscale = 1.f; - maxscale = 1.f; - rotation = -1.f; - lifetime = 10.0f; - assemble = false; - forceedge = false; - } - const char* filename; - const char* material; - float minscale; - float maxscale; - float rotation; - float lifetime; - bool assemble; - bool forceedge; -}; - -class SMFXDecalListNode -{ -public: - static SMFXDecalListNode* Create(); - void Destroy(); - static void FreePool(); - - IMFXDecalParams m_decalParams; - SMFXDecalListNode* pNext; - -private: - SMFXDecalListNode() - { - pNext = 0; - } - ~SMFXDecalListNode() {} -}; - -class IMFXForceFeedbackParams -{ -public: - IMFXForceFeedbackParams() - : forceFeedbackEventName (NULL) - , intensityFallOffMinDistanceSqr(0.0f) - , intensityFallOffMaxDistanceSqr(0.0f) - { - } - - const char* forceFeedbackEventName; - float intensityFallOffMinDistanceSqr; - float intensityFallOffMaxDistanceSqr; -}; - -class SMFXForceFeedbackListNode -{ -public: - static SMFXForceFeedbackListNode* Create(); - void Destroy(); - static void FreePool(); - - IMFXForceFeedbackParams m_forceFeedbackParams; - SMFXForceFeedbackListNode* pNext; - -private: - SMFXForceFeedbackListNode() - : pNext(NULL) - { - } - ~SMFXForceFeedbackListNode() {} -}; - -struct SMFXResourceList; -typedef _smart_ptr SMFXResourceListPtr; - -struct SMFXResourceList -{ -public: - SMFXParticleListNode* m_particleList; - SMFXAudioListNode* m_audioList; - SMFXDecalListNode* m_decalList; - SMFXForceFeedbackListNode* m_forceFeedbackList; - - void AddRef() { ++m_refs; } - void Release() - { - if (--m_refs <= 0) - { - Destroy(); - } - } - - static SMFXResourceListPtr Create(); - static void FreePool(); - -private: - int m_refs; - - virtual void Destroy(); - - SMFXResourceList() - : m_refs(0) - { - m_particleList = 0; - m_audioList = 0; - m_decalList = 0; - m_forceFeedbackList = 0; - } - virtual ~SMFXResourceList() - { - while (m_particleList != 0) - { - SMFXParticleListNode* next = m_particleList->pNext; - m_particleList->Destroy(); - m_particleList = next; - } - while (m_audioList != 0) - { - SMFXAudioListNode* next = m_audioList->pNext; - m_audioList->Destroy(); - m_audioList = next; - } - while (m_decalList != 0) - { - SMFXDecalListNode* next = m_decalList->pNext; - m_decalList->Destroy(); - m_decalList = next; - } - while (m_forceFeedbackList != 0) - { - SMFXForceFeedbackListNode* next = m_forceFeedbackList->pNext; - m_forceFeedbackList->Destroy(); - m_forceFeedbackList = next; - } - } -}; - -typedef uint16 TMFXEffectId; -static const TMFXEffectId InvalidEffectId = 0; - -struct SMFXCustomParamValue -{ - float fValue; -}; - -////////////////////////////////////////////////////////////////////////// -struct IMaterialEffects -{ - // - virtual ~IMaterialEffects(){} - virtual void LoadFXLibraries() = 0; - virtual void Reset(bool bCleanup) = 0; - virtual void ClearDelayedEffects() = 0; - virtual TMFXEffectId GetEffectIdByName(const char* libName, const char* effectName) = 0; - virtual TMFXEffectId GetEffectId(int surfaceIndex1, int surfaceIndex2) = 0; - virtual TMFXEffectId GetEffectId(const char* customName, int surfaceIndex2) = 0; - virtual SMFXResourceListPtr GetResources(TMFXEffectId effectId) const = 0; - virtual void PreLoadAssets() = 0; - virtual bool ExecuteEffect(TMFXEffectId effectId, SMFXRunTimeEffectParams& runtimeParams) = 0; - virtual int GetDefaultSurfaceIndex() = 0; - virtual int GetDefaultCanopyIndex() = 0; - - virtual bool PlayBreakageEffect(ISurfaceType* pSurfaceType, const char* breakageType, const SMFXBreakageParams& mfxBreakageParams) = 0; - - virtual void SetCustomParameter(TMFXEffectId effectId, const char* customParameter, const SMFXCustomParamValue& customParameterValue) = 0; - - virtual void CompleteInit() = 0; - // -}; - -#endif // CRYINCLUDE_CRYCOMMON_IMATERIALEFFECTS_H diff --git a/Code/CryEngine/CryCommon/INotificationNetwork.h b/Code/CryEngine/CryCommon/INotificationNetwork.h deleted file mode 100644 index 9ad44b24ab..0000000000 --- a/Code/CryEngine/CryCommon/INotificationNetwork.h +++ /dev/null @@ -1,147 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_INOTIFICATIONNETWORK_H -#define CRYINCLUDE_CRYCOMMON_INOTIFICATIONNETWORK_H -#pragma once - - -// Constants - -#define NN_CHANNEL_NAME_LENGTH_MAX 16 - -struct INotificationNetworkClient; - -// User Interfaces - -struct INotificationNetworkListener -{ - // - virtual ~INotificationNetworkListener(){} - // Called upon receiving data from the Channel the Listener is binded to. - virtual void OnNotificationNetworkReceive(const void* pBuffer, size_t length) = 0; - // -}; - -struct INotificationNetworkConnectionCallback -{ - // - virtual ~INotificationNetworkConnectionCallback(){} - virtual void OnConnect(INotificationNetworkClient* pClient, bool bSucceeded) = 0; - virtual void OnDisconnected(INotificationNetworkClient* pClient) = 0; - // -}; - -// Interfaces - -struct INotificationNetworkClient -{ - // - virtual ~INotificationNetworkClient(){} - virtual void Release() = 0; - - // Binds a Listener to the given Notification Channel. - // Each Listener can be binded only to one Channel, calling the method - // again with an already added Listener and a different Channel will rebind it. - // The Channel name cannot exceed NN_CHANNEL_NAME_LENGTH_MAX chars. - virtual bool ListenerBind(const char* channelName, INotificationNetworkListener* pListener) = 0; - - // If it exist, removes the given Listener form the Notification Network. - virtual bool ListenerRemove(INotificationNetworkListener* pListener) = 0; - - // Sends arbitrary data to the Notification Network the Client is connected to. - virtual bool Send(const char* channelName, const void* pBuffer, size_t length) = 0; - - // Checks if the current client is connected. - // Returns true if it is connected, false otherwise. - virtual bool IsConnected() = 0; - - // Checks if the connection attempt failed. - // Returns true if it failed to connect by any reason (such as timeout). - virtual bool IsFailedToConnect() const = 0; - - // Start the connection request for this particular client. - // Parameters: - // address - Is the host name or ipv4 (for now) address string to which - // we want to connect. - // port - Is the TCP port to which we want to connect. - // Remarks: Port 9432 is being used by the live preview already. - virtual bool Connect(const char* address, uint16 port) = 0; - - // Tries to register a callback listener object. - // A callback listener object will receive events from the client element, - // such as connection result information. - // Parameters: - // - pConnectionCallback - Is a pointer to an object implementing interface - // INotificationNetworkConnectionCallback which will be called when - // the events happen, such as connection, disconnection and failed attempt - // to connect. - // Return Value: - // - It will return true if registered the callback object successfully. - // - It will return false when there the callback object is already - // registered. - virtual bool RegisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback) = 0; - - // Tries to unregister a callback listener object. - // A callback listener object will receive events from the client element, - // such as connection result information. - // Parameters: - // - pConnectionCallback - Is a pointer to an object implementing interface - // INotificationNetworkConnectionCallback which will be called when - // the events happen, such as connection, disconnection and failed attempt - // to connect and that we want to unregister. - // Return Value: - // - It will return true if unregistered the callback object successfully. - // - It will return false when no object matching the one requested is found - // int the object. - virtual bool UnregisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback) = 0; - // -}; - -struct INotificationNetwork -{ - // - virtual ~INotificationNetwork(){} - - virtual void Release() = 0; - - // Creates a disconnected client. - virtual INotificationNetworkClient* CreateClient() = 0; - - // Attempts to connect to the Notification Network at the given address, - // returns a Client interface if communication is possible. - virtual INotificationNetworkClient* Connect(const char* address, uint16 port) = 0; - - // Returns the Connection count of the given Channel. If NULL is passed - // instead of a valid Channel name the total count of all Connections is - // returned. - virtual size_t GetConnectionCount(const char* channelName = NULL) = 0; - - // Has to be called from the main thread to process received notifications. - virtual void Update() = 0; - - // Binds a Listener to the given Notification Channel. - // Each Listener can be binded only to one Channel, calling the method - // again with an already added Listener and a different Channel will rebind it. - // The Channel name cannot exceed NN_CHANNEL_NAME_LENGTH_MAX chars. - virtual bool ListenerBind(const char* channelName, INotificationNetworkListener* pListener) = 0; - - // If it exist, removes the given Listener form the Notification Network. - virtual bool ListenerRemove(INotificationNetworkListener* pListener) = 0; - - // Sends arbitrary data to all the Connections listening to the given Channel. - virtual uint32 Send(const char* channel, const void* pBuffer, size_t length) = 0; - // -}; - -#endif // CRYINCLUDE_CRYCOMMON_INOTIFICATIONNETWORK_H diff --git a/Code/CryEngine/CryCommon/IRenderer.h b/Code/CryEngine/CryCommon/IRenderer.h index 94f8772e71..bb8f8fa572 100644 --- a/Code/CryEngine/CryCommon/IRenderer.h +++ b/Code/CryEngine/CryCommon/IRenderer.h @@ -16,12 +16,12 @@ #include "Cry_Geo.h" #include "Cry_Camera.h" #include "ITexture.h" -#include // <> required for Interfuscator +#include // <> required for Interfuscator +#include // <> required for Interfuscator +#include "smartptr.h" #include #include -#include "IResourceCompilerHelper.h" // for IResourceCompilerHelper::ERcCallResult - // forward declarations struct SRenderingPassInfo; struct SRTStack; @@ -95,7 +95,6 @@ struct IFFont; struct IFFont_RenderProxy; struct STextDrawContext; struct IRenderMesh; -class IOpticsManager; struct ShadowFrustumMGPUCache; struct IAsyncTextureCompileListener; struct IClipVolume; @@ -955,25 +954,6 @@ protected: virtual ~ITextureStreamListener() {} }; -#if defined(CRY_ENABLE_RC_HELPER) -//////////////////////////////////////////////////////////////////////////// -// Listener for asynchronous texture compilation. -// Connects the listener to the task-queue of pending compilation requests. -enum ERcExitCode; -struct IAsyncTextureCompileListener -{ -public: - virtual void OnCompilationStarted(const char* source, const char* target, int nPending) = 0; - virtual void OnCompilationFinished(const char* source, const char* target, IResourceCompilerHelper::ERcCallResult nReturnCode) = 0; - - virtual void OnCompilationQueueTriggered(int nPending) = 0; - virtual void OnCompilationQueueDepleted() = 0; - -protected: - virtual ~IAsyncTextureCompileListener() {} -}; -#endif - enum eDolbyVisionMode { eDVM_Disabled, @@ -1869,8 +1849,6 @@ struct IRenderer virtual SDepthTexture* CreateDepthSurface(int nWidth, int nHeight, bool shaderResourceView = false) = 0; virtual void DestroyDepthSurface(SDepthTexture* pDepthSurf) = 0; - virtual IOpticsElementBase* CreateOptics(EFlareType type) const = 0; - // Note: // Used for pausing timer related stuff. // Example: diff --git a/Code/CryEngine/CryCommon/IResourceCompilerHelper.cpp b/Code/CryEngine/CryCommon/IResourceCompilerHelper.cpp deleted file mode 100644 index 380c94e4c7..0000000000 --- a/Code/CryEngine/CryCommon/IResourceCompilerHelper.cpp +++ /dev/null @@ -1,378 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "IResourceCompilerHelper.h" - -#include -// DO NOT USE AZSTD. - -#include // std string used here. -#include -#include - -// the following block is for _mkdir on windows and mkdir on other platforms. -#if defined(_WIN32) -# include -#else -# include -# include -#endif - -namespace RCPathUtil -{ - const char* GetExt(const char* filepath) - { - const char* str = filepath; - size_t len = strlen(filepath); - for (const char* p = str + len - 1; p >= str; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - // we've reached a path separator - it means there's no extension in this name - return ""; - case '.': - // there's an extension in this file name - return p + 1; - } - } - return ""; - } - - const char* GetFile(const char* filepath) - { - const size_t len = strlen(filepath); - for (const char* p = filepath + len - 1; p >= filepath; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - return p + 1; - } - } - return filepath; - } - - - //! Replace extension for given file. - std::string RemoveExtension(const char* filepath) - { - std::string filepathstr = filepath; - const char* str = filepathstr.c_str(); - for (const char* p = str + filepathstr.length() - 1; p >= str; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - // we've reached a path separator - it means there's no extension in this name - return filepathstr; - case '.': - // there's an extension in this file name - filepathstr.erase(p - str); - return filepathstr; - } - } - // it seems the file name is a pure name, without path or extension - return filepathstr; - } - - std::string ReplaceExtension(const char* filepath, const char* ext) - { - std::string str = filepath; - if (ext != 0) - { - str = RemoveExtension(str.c_str()); - if (ext[0] != 0 && ext[0] != '.') - { - str += "."; - } - str += ext; - } - return str; - } - - std::string GetPath(const char* filepath) - { - std::string filepathstr = filepath; - const char* str = filepathstr.c_str(); - for (const char* p = str + filepathstr.length() - 1; p >= str; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - // we've reached a path separator - it means there's no extension in this name - return filepathstr.substr(0, p - str); - } - } - // it seems the file name is a pure name, without path - return ""; - } - - - ////////////////////////////////////////////////////////////////////////// - bool IsRelativePath(const char* p) - { - if (!p || !p[0]) - { - return true; - } - return p[0] != '/' && p[0] != '\\' && !strchr(p, ':'); - } -} - -const char* IResourceCompilerHelper::SourceImageFormatExts[NUM_SOURCE_IMAGE_TYPE] = { "tif", "bmp", "gif", "jpg", "jpeg", "jpe", "tga", "png" }; -const char* IResourceCompilerHelper::SourceImageFormatExtsWithDot[NUM_SOURCE_IMAGE_TYPE] = { ".tif", ".bmp", ".gif", ".jpg", ".jpeg", ".jpe", ".tga", ".png" }; -const char* IResourceCompilerHelper::EngineImageFormatExts[NUM_ENGINE_IMAGE_TYPE] = { "dds" }; -const char* IResourceCompilerHelper::EngineImageFormatExtsWithDot[NUM_ENGINE_IMAGE_TYPE] = { ".dds" }; - - -IResourceCompilerHelper::ERcCallResult IResourceCompilerHelper::ConvertResourceCompilerExitCodeToResultCode(int exitCode) -{ - switch (exitCode) - { - case eRcExitCode_Success: - case eRcExitCode_UserFixing: - return eRcCallResult_success; - - case eRcExitCode_Error: - return eRcCallResult_error; - - case eRcExitCode_FatalError: - return eRcCallResult_error; - case eRcExitCode_Crash: - return eRcCallResult_crash; - } - return eRcCallResult_error; -} - - -////////////////////////////////////////////////////////////////////////// -const char* IResourceCompilerHelper::GetCallResultDescription(IResourceCompilerHelper::ERcCallResult result) -{ - switch (result) - { - case eRcCallResult_success: - return "Success."; - case eRcCallResult_notFound: - return "ResourceCompiler executable was not found."; - case eRcCallResult_error: - return "ResourceCompiler exited with an error."; - case eRcCallResult_crash: - return "ResourceCompiler crashed! Please report this. Include source asset and this log in the report."; - default: - return "Unexpected failure in ResultCompilerHelper."; - } -} - -// Arguments: -// szFilePath - could be source or destination filename -void IResourceCompilerHelper::GetOutputFilename(const char* szFilePath, char* buffer, size_t bufferSizeInBytes) -{ - if (IResourceCompilerHelper::IsSourceImageFormatSupported(szFilePath)) - { - std::string newString = RCPathUtil::ReplaceExtension(szFilePath, "dds"); - azstrncpy(buffer, bufferSizeInBytes, newString.c_str(), bufferSizeInBytes - 1); - return; - } - - azstrncpy(buffer, bufferSizeInBytes, szFilePath, bufferSizeInBytes - 1); -} - -IResourceCompilerHelper::ERcCallResult IResourceCompilerHelper::InvokeResourceCompiler(const char* szSrcFilePath, const char* szDstFilePath, const bool bUserDialog) -{ - - const char* szDstFileName = RCPathUtil::GetFile(szDstFilePath); - std::string pathOnly = RCPathUtil::GetPath(szDstFilePath); - const int maxStringSize = 512; - char szRemoteCmdLine[maxStringSize] = { 0 }; - char szFullPathToSourceFile[maxStringSize] = { 0 }; - - if (RCPathUtil::IsRelativePath(szSrcFilePath)) - { - azstrcat(szFullPathToSourceFile, maxStringSize, "#ENGINEROOT#"); - azstrcat(szFullPathToSourceFile, maxStringSize, "\\"); - } - azstrcat(szFullPathToSourceFile, maxStringSize, szSrcFilePath); - - azstrcat(szRemoteCmdLine, maxStringSize, " /targetroot=\""); - azstrcat(szRemoteCmdLine, maxStringSize, pathOnly.c_str()); - azstrcat(szRemoteCmdLine, maxStringSize, "\""); - - azstrcat(szRemoteCmdLine, maxStringSize, " /overwritefilename=\""); - azstrcat(szRemoteCmdLine, maxStringSize, szDstFileName); - azstrcat(szRemoteCmdLine, maxStringSize, "\""); - - return CallResourceCompiler(szFullPathToSourceFile, szRemoteCmdLine, nullptr, true, false, !bUserDialog); -} - -unsigned int IResourceCompilerHelper::GetNumSourceImageFormats() -{ - return NUM_SOURCE_IMAGE_TYPE; -} - -const char* IResourceCompilerHelper::GetSourceImageFormat(unsigned int index, bool bWithDot) -{ - if (index >= GetNumSourceImageFormats()) - { - return nullptr; - } - - if (bWithDot) - { - return SourceImageFormatExtsWithDot[index]; - } - else - { - return SourceImageFormatExts[index]; - } -} - -unsigned int IResourceCompilerHelper::GetNumEngineImageFormats() -{ - return NUM_ENGINE_IMAGE_TYPE; -} - -const char* IResourceCompilerHelper::GetEngineImageFormat(unsigned int index, bool bWithDot) -{ - if (index >= GetNumEngineImageFormats()) - { - return nullptr; - } - - if (bWithDot) - { - return EngineImageFormatExtsWithDot[index]; - } - else - { - return EngineImageFormatExts[index]; - } -} - -bool IResourceCompilerHelper::IsSourceImageFormatSupported(const char* szFileNameOrExtension) -{ - if (!szFileNameOrExtension) // if this hits, might want to check the call site - { - return false; - } - - //check the string length - size_t len = strlen(szFileNameOrExtension); - if (len < 3)//no point in going on if the smallest valid ext is 3 characters - { - return false; - } - - //find the ext by starting at the last character and moving backward to first he first '.' - const char* szExtension = nullptr; - size_t cur = len - 1; - while (cur && !szExtension) - { - if (szFileNameOrExtension[cur] == '.') - { - szExtension = &szFileNameOrExtension[cur]; - } - cur--; - } - if (len - cur < 3)//no point in going on if the smallest valid ext is 3 characters - { - return false; - } - - //if we didn't find a '.' it could still be valid, they may not have - //passed it in. i.e. "dds" instead of ".dds" which is still valid - if (!szExtension) - { - //with no '.' the largest ext is currently 4 characters - //no point in going on if it is larger - if (len > 4) - { - return false; - } - - szExtension = szFileNameOrExtension; - } - - //loop over all the valid exts and see if it is one of them - for (unsigned int i = 0; i < GetNumSourceImageFormats(); ++i) - { - if (!azstricmp(szExtension, GetSourceImageFormat(i, szExtension[0] == '.'))) - { - return true; - } - } - - return false; -} - -bool IResourceCompilerHelper::IsGameImageFormatSupported(const char* szFileNameOrExtension) -{ - if (!szFileNameOrExtension) // if this hits, might want to check the call site - { - return false; - } - - //check the string length - size_t len = strlen(szFileNameOrExtension); - if (len < 3)//no point in going on if the smallest valid ext is 3 characters - { - return false; - } - - //find the ext by starting at the last character and moving backward to first he first '.' - const char* szExtension = nullptr; - size_t cur = len - 1; - while (cur && !szExtension) - { - if (szFileNameOrExtension[cur] == '.') - { - szExtension = &szFileNameOrExtension[cur]; - } - cur--; - } - if (len - cur < 3)//no point in going on if the smallest valid ext is 3 characters - { - return false; - } - - //if we didn't find a '.' it could still be valid, they may not have - //passed it in. i.e. "dds" instead of ".dds" which is still valid - if (!szExtension) - { - //with no '.' the largest ext is currently 4 characters - //no point in going on if it is larger - if (len > 4) - { - return false; - } - - szExtension = szFileNameOrExtension; - } - - //loop over all the valid exts and see if it is one of them - for (unsigned int i = 0; i < GetNumEngineImageFormats(); ++i) - { - if (!azstricmp(szExtension, GetEngineImageFormat(i, szExtension[0] == '.'))) - { - return true; - } - } - - return false; -} diff --git a/Code/CryEngine/CryCommon/IResourceCompilerHelper.h b/Code/CryEngine/CryCommon/IResourceCompilerHelper.h deleted file mode 100644 index 52f05b0c84..0000000000 --- a/Code/CryEngine/CryCommon/IResourceCompilerHelper.h +++ /dev/null @@ -1,167 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef CRYINCLUDE_CRYCOMMON_IRESOURCECOMPILERHELPER_H -#define CRYINCLUDE_CRYCOMMON_IRESOURCECOMPILERHELPER_H - -#pragma once - -// DO NOT USE AZSTD - -#include - -// IResourceCompilerHelper exists to define an interface that allows -// remote or local compilation of resources through the "resource Compiler" executable -// in most tools it will be implemented as a local execution. However, in the engine -// it will be substituted for a remote RC invocation through the Asset Processor if -// that system is enabled (via con var and define) - -// DO NOT USE CRYSTRING or CRY ALLOCATORS HERE. This is used in maya plugins, that kind of thing. -// the following path utils are special versions of these functions which take pains -// to not use crystring. -// the functions in this interface must be cross platform. -namespace RCPathUtil -{ - // given a full path, return the extension (it will be a pointer into the existing string) - const char* GetExt(const char* filepath); - - // given a full path, return the file only (it will be a pointer into the existing string) - const char* GetFile(const char* filepath); - - // given a filepath, get only the path. - std::string GetPath(const char* filepath); - std::string ReplaceExtension(const char* filepath, const char* ext); - bool IsRelativePath(const char* p); -} - -class IResourceCompilerListener; - -enum ERcExitCode -{ - eRcExitCode_Success = 0, // must be 0 - eRcExitCode_Error = 1, - eRcExitCode_FatalError = 100, - eRcExitCode_Crash = 101, - eRcExitCode_UserFixing = 200, - eRcExitCode_Pending = 666, -}; - -/// A pure virtual interface to the RC Helper system -/// the RC helper system allows you to make requests to a remote process in order to process -/// an asset for you. -class IResourceCompilerHelper -{ -public: - virtual ~IResourceCompilerHelper() {} - - // defines the result of a call via this API to the RC system - enum ERcCallResult - { - eRcCallResult_success, // everything is OK - eRcCallResult_notFound, // the RC executable is not found - eRcCallResult_error, // the RC executable returned an error - eRcCallResult_crash, // the RC executable did not finish - }; - - // - // Arguments: - // szFileName null terminated ABSOLUTE file path or 0 can be used to test for rc.exe existence - // relative path needs to be relative to rc_plugins directory - // szAdditionalSettings - 0 or e.g. "/refresh" or "/refresh /xyz=56" - // - // this is a SYNCHRONOUS, BLOCKING call and will return once the process is complete - virtual ERcCallResult CallResourceCompiler( - const char* szFileName = 0, - const char* szAdditionalSettings = 0, - IResourceCompilerListener* listener = 0, - bool bMayShowWindow = true, - bool bSilent = false, - bool bNoUserDialog = false, - const wchar_t* szWorkingDirectory = 0, - const wchar_t* szRootPath = 0) = 0; - - // InvokeResourceCompiler - a utility that calls the above CallResourceCompiler function - // but generates appropriate settings so you don't have to specify each option. - // This is a BLOCKING call - // the srcFile can be relative to the project root or an absolute path - // the dstFilePath MUST be relative to the same folder as the Src File path - // this will output dstFilePath in the same folder as srcFile. - virtual ERcCallResult InvokeResourceCompiler(const char* szSrcFilePath, const char* szDstFilePath, const bool bUserDialog); - - // --------------------- utility functions --------------------------------- - - // given a RC.EXE process exit code like 101, convert it to the above ERcCallResult - ERcCallResult ConvertResourceCompilerExitCodeToResultCode(int exitCode); - - // given a ERcCallResult, convert it to a simple english string for debugging. - static const char* GetCallResultDescription(ERcCallResult result); - - // given a filename such as "blah.tif" convert it to the appropriate output name "blah.dds" for example - static void GetOutputFilename(const char* szFilePath, char* buffer, size_t bufferSizeInBytes); - - ////////////////////////////////////////////////////////////////////////// - - enum SourceImageTypes - { - SOURCE_IMAGE_TYPE_TIF, - SOURCE_IMAGE_TYPE_BMP, - SOURCE_IMAGE_TYPE_GIF, - SOURCE_IMAGE_TYPE_JPG, - SOURCE_IMAGE_TYPE_JPEG, - SOURCE_IMAGE_TYPE_JPE, - SOURCE_IMAGE_TYPE_TGA, - SOURCE_IMAGE_TYPE_PNG, - NUM_SOURCE_IMAGE_TYPE - }; - - enum EngineImageTypes - { - ENGINE_IMAGE_TYPE_DDS, - NUM_ENGINE_IMAGE_TYPE - }; - -private: - static const char* SourceImageFormatExts[NUM_SOURCE_IMAGE_TYPE]; - static const char* SourceImageFormatExtsWithDot[NUM_SOURCE_IMAGE_TYPE]; - static const char* EngineImageFormatExts[NUM_ENGINE_IMAGE_TYPE]; - static const char* EngineImageFormatExtsWithDot[NUM_ENGINE_IMAGE_TYPE]; - -public: - static unsigned int GetNumSourceImageFormats(); - static const char* GetSourceImageFormat(unsigned int index, bool bWithDot); - - static unsigned int GetNumEngineImageFormats(); - static const char* GetEngineImageFormat(unsigned int index, bool bWithDot); - - static bool IsSourceImageFormatSupported(const char* szExtension); - static bool IsGameImageFormatSupported(const char* szExtension); -}; - -//////////////////////////////////////////////////////////////////////////// -// Listener for synchronous resource-compilation. -// Connects the listener to the output of the RC process. -class IResourceCompilerListener -{ -public: - // FbxImportDialog relies on this enum being in the order from most verbose to least verbose - enum MessageSeverity - { - MessageSeverity_Debug = 0, - MessageSeverity_Info, - MessageSeverity_Warning, - MessageSeverity_Error - }; - - virtual void OnRCMessage(MessageSeverity /*severity*/, const char* /*text*/) {} - virtual ~IResourceCompilerListener() {} -}; - -#endif // CRYINCLUDE_CRYCOMMON_IRESOURCECOMPILERHELPER_H diff --git a/Code/CryEngine/CryCommon/IShader.h b/Code/CryEngine/CryCommon/IShader.h index a87144a8c2..5f5209992e 100644 --- a/Code/CryEngine/CryCommon/IShader.h +++ b/Code/CryEngine/CryCommon/IShader.h @@ -24,7 +24,9 @@ #endif #include "smartptr.h" -#include // <> required for Interfuscator +#include // <> required for Interfuscator +#include // <> required for Interfuscator +#include "smartptr.h" #include "VertexFormats.h" #include #include @@ -2828,7 +2830,6 @@ struct SRenderLight m_ObjMatrix.SetIdentity(); m_BaseObjMatrix.SetIdentity(); m_sName = ""; - m_pSoftOccQuery = NULL; m_pLightAnim = NULL; m_fAreaWidth = 1; m_fAreaHeight = 1; @@ -2884,11 +2885,6 @@ struct SRenderLight return m_pLightImage ? m_pLightImage : NULL; } - IOpticsElementBase* GetLensOpticsElement() const - { - return m_pLensOpticsElement; - } - void SetOpticsParams(const SOpticsInstanceParameters& params) { m_opticsParams = params; @@ -2899,24 +2895,6 @@ struct SRenderLight return m_opticsParams; } - void SetLensOpticsElement(IOpticsElementBase* pOptics) - { - if (m_pLensOpticsElement == pOptics) - { - return; - } - if (pOptics && pOptics->GetType() != eFT_Root) - { - return; - } - SAFE_RELEASE(m_pLensOpticsElement); - m_pLensOpticsElement = pOptics; - if (m_pLensOpticsElement) - { - m_pLensOpticsElement->AddRef(); - } - } - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { /*LATER*/} void AcquireResources() @@ -2937,14 +2915,6 @@ struct SRenderLight { m_pSpecularCubemap->AddRef(); } - if (m_pLensOpticsElement) - { - m_pLensOpticsElement->AddRef(); - } - if (m_pSoftOccQuery) - { - m_pSoftOccQuery->AddRef(); - } if (m_pLightAnim) { m_pLightAnim->AddRef(); @@ -2961,8 +2931,6 @@ struct SRenderLight SAFE_RELEASE(m_pLightImage); SAFE_RELEASE(m_pDiffuseCubemap); SAFE_RELEASE(m_pSpecularCubemap); - SAFE_RELEASE(m_pLensOpticsElement); - SAFE_RELEASE(m_pSoftOccQuery); SAFE_RELEASE(m_pLightAnim); SAFE_RELEASE(m_pLightAttenMap); } @@ -3046,8 +3014,6 @@ struct SRenderLight const char* m_sName; // Optional name of the light source. SShaderItem m_Shader; // Shader item CRenderObject* m_pObject[MAX_RECURSION_LEVELS]; // Object for light coronas and light flares. - IOpticsElementBase* m_pLensOpticsElement; // Optics element for this shader instance - ISoftOcclusionQuery* m_pSoftOccQuery; ILightAnimWrapper* m_pLightAnim; Matrix34 m_BaseObjMatrix; @@ -3146,9 +3112,7 @@ public: m_fShadowSlopeBias = dl.m_fShadowSlopeBias; m_fShadowResolutionScale = dl.m_fShadowResolutionScale; m_fHDRDynamic = dl.m_fHDRDynamic; - m_pLensOpticsElement = dl.m_pLensOpticsElement; m_LensOpticsFrustumAngle = dl.m_LensOpticsFrustumAngle; - m_pSoftOccQuery = dl.m_pSoftOccQuery; m_fLightFrustumAngle = dl.m_fLightFrustumAngle; m_fProjectorNearPlane = dl.m_fProjectorNearPlane; m_Flags = dl.m_Flags; diff --git a/Code/CryEngine/CryCommon/ISoftCodeMgr.h b/Code/CryEngine/CryCommon/ISoftCodeMgr.h deleted file mode 100644 index b3cef7e1f0..0000000000 --- a/Code/CryEngine/CryCommon/ISoftCodeMgr.h +++ /dev/null @@ -1,276 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Interface to manage SoftCode module loading and patching - - -#ifndef CRYINCLUDE_CRYCOMMON_ISOFTCODEMGR_H -#define CRYINCLUDE_CRYCOMMON_ISOFTCODEMGR_H -#pragma once - - -// Provides the generic interface for exchanging member values between SoftCode modules, -struct IExchangeValue -{ - // - virtual ~IExchangeValue() {} - - // Allocates a new IExchangeValue with the underlying type - virtual IExchangeValue* Clone() const = 0; - // Returns the size of the underlying type (to check compatibility) - virtual size_t GetSizeOf() const = 0; - // -}; - -template -struct ExchangeValue - : public IExchangeValue -{ - ExchangeValue(T& value) - : m_value(value) - {} - - virtual IExchangeValue* Clone() const { return new ExchangeValue(*this); } - virtual size_t GetSizeOf() const { return sizeof(m_value); } - - T m_value; -}; - -template -struct ExchangeArray - : public IExchangeValue -{ - ExchangeArray(T* pArr) - { - for (size_t i = 0; i < S; ++i) - { - m_array[i] = pArr[i]; - } - } - - virtual IExchangeValue* Clone() const { return new ExchangeArray(*this); } - virtual size_t GetSizeOf() const { return sizeof(m_array); } - - T m_array[S]; -}; - -/* - This is a non-intrusive support function for types where default construction does no initialization. - SoftCoding relies on default construction to initialize object state correctly. - For most types this works as expected but for some types (typically things like vectors or matrices) - default initialization would be too costly and is therefore not implemented. - This function allows a specialized implementation to be used for such types that will perform - initialization on the newly constructed instance. For example: - - inline void DefaultInitialize(Matrix34& matrix) - { - matrix.SetIdentity(); - } -*/ -template -void DefaultInitialize(T& t) -{ - t = T(); -} - -// Vector support -template -struct Vec2_tpl; -template -struct Vec3_tpl; -template -void DefaultInitialize(Vec2_tpl& vec) { vec.zero(); } -template -void DefaultInitialize(Vec3_tpl& vec) { vec.zero(); } - -// Matrix support -template -struct Matrix33_tpl; -template -struct Matrix34_tpl; -template -struct Matrix44_tpl; - -template -void DefaultInitialize(Matrix33_tpl& matrix) { matrix.SetIdentity(); } -template -void DefaultInitialize(Matrix34_tpl& matrix) { matrix.SetIdentity(); } -template -void DefaultInitialize(Matrix44_tpl& matrix) { matrix.SetIdentity(); } - -// Quat support -template -struct Quat_tpl; -template -void DefaultInitialize(Quat_tpl& quat) { quat.SetIdentity(); } - -// Interface for performing an exchange of instance data -struct IExchanger -{ - // - virtual ~IExchanger() {} - - // True if data is being read from instance members - virtual bool IsLoading() const = 0; - - virtual size_t InstanceCount() const = 0; - - virtual bool BeginInstance(void* pInstance) = 0; - virtual bool SetValue(const char* name, IExchangeValue& value) = 0; - virtual IExchangeValue* GetValue(const char* name, void* pTarget, size_t targetSize) = 0; - // - - template - void Visit(const char* name, T& instance); - - template - void Visit(const char* name, T (&arr)[S]); -}; - -template -void IExchanger::Visit(const char* name, T& value) -{ - if (IsLoading()) - { - IExchangeValue* pValue = GetValue(name, &value, sizeof(value)); - if (pValue) - { - ExchangeValue* pTypedValue = static_cast*>(pValue); - value = pTypedValue->m_value; - } - } - else // Saving - { - // If this member is stored - if (SetValue(name, ExchangeValue(value))) - { - // Set the original value to the default state (to allow safe destruction) - DefaultInitialize(value); - } - } -} - -template -void IExchanger::Visit(const char* name, T (&arr)[S]) -{ - if (IsLoading()) - { - IExchangeValue* pValue = GetValue(name, &arr, sizeof(arr)); - if (pValue) - { - ExchangeArray* pTypedArray = static_cast*>(pValue); - // TODO: Accommodate array resizing? Complex however... - for (size_t i = 0; i < S; ++i) - { - arr[i] = pTypedArray->m_array[i]; - } - } - } - else // Saving - { - // If this member is stored - if (SetValue(name, ExchangeArray(arr))) - { - T defaultValue; - DefaultInitialize(defaultValue); - - // Set the original value to the default value (to allow safe destruction) - for (size_t i = 0; i < S; ++i) - { - arr[i] = defaultValue; - } - } - } -} - -struct InstanceTracker; - -struct ITypeRegistrar -{ - // - virtual ~ITypeRegistrar() {} - - virtual const char* GetName() const = 0; - - // Creates an instance of the type - virtual void* CreateInstance() = 0; - // - -#ifdef SOFTCODE_ENABLED - // How many active instances exist of this type? - virtual size_t InstanceCount() const = 0; - // Used to remove a tracked instance from the Registrar - virtual void RemoveInstance(InstanceTracker* pTracker) = 0; - // Exchanges the instance state with the given exchanger data set - virtual bool ExchangeInstances(IExchanger& exchanger) = 0; - // Destroys all tracked instances of this type - virtual bool DestroyInstances() = 0; - // Returns true if pInstance is of this type (linear search) - virtual bool HasInstance(void* pInstance) const = 0; -#endif -}; - -struct ITypeLibrary -{ - // - virtual ~ITypeLibrary() {} - - virtual const char* GetName() = 0; - virtual void* CreateInstanceVoid(const char* typeName) = 0; - // - -#ifdef SOFTCODE_ENABLED - virtual void SetOverride(ITypeLibrary* pOverrideLib) = 0; - - // Fills in the supplied type list if large enough, and sets count to number of types - virtual size_t GetTypes(ITypeRegistrar** ppRegistrar, size_t& count) const = 0; -#endif -}; - -struct ISoftCodeListener -{ - // - virtual ~ISoftCodeListener() {} - - // Called when an instance is replaced to allow managing systems to fixup pointers - virtual void InstanceReplaced(void* pOldInstance, void* pNewInstance) = 0; - // -}; - -/// Interface for ... -struct ISoftCodeMgr -{ - // - virtual ~ISoftCodeMgr() {} - - // Used to register built-in libraries on first use - virtual void RegisterLibrary(ITypeLibrary* pLib) = 0; - - // Loads any new SoftCode modules - virtual void LoadNewModules() = 0; - - virtual void AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName) = 0; - virtual void RemoveListener(const char* libraryName, ISoftCodeListener* pListener) = 0; - - // To be called regularly to poll for library updates - virtual void PollForNewModules() = 0; - - // Stops thread execution until a new SoftCode instance is available - virtual void* WaitForUpdate(void* pInstance) = 0; - - /// Frees this instance from memory - //virtual void Release() = 0; - // -}; - -#endif // CRYINCLUDE_CRYCOMMON_ISOFTCODEMGR_H diff --git a/Code/CryEngine/CryCommon/IStreamEngine.h b/Code/CryEngine/CryCommon/IStreamEngine.h index f325eec389..0536e1f486 100644 --- a/Code/CryEngine/CryCommon/IStreamEngine.h +++ b/Code/CryEngine/CryCommon/IStreamEngine.h @@ -34,7 +34,6 @@ #include #include "smartptr.h" -#include // <> required for Interfuscator #include "CryThread.h" #include "IStreamEngineDefs.h" diff --git a/Code/CryEngine/CryCommon/ISystem.h b/Code/CryEngine/CryCommon/ISystem.h index 86c2b57464..4c6bd73b61 100644 --- a/Code/CryEngine/CryCommon/ISystem.h +++ b/Code/CryEngine/CryCommon/ISystem.h @@ -49,19 +49,15 @@ #include // <> required for Interfuscator #include "CryVersion.h" #include "smartptr.h" -#include // <> required for Interfuscator #include // shared_ptr #include struct ISystem; struct ILog; -struct IProfileLogSystem; namespace AZ::IO { struct IArchive; } -struct IKeyboard; -struct IMouse; struct IConsole; struct IRemoteConsole; struct IRenderer; @@ -79,29 +75,21 @@ struct SFileVersion; struct INameTable; struct ILevelSystem; struct IViewSystem; -struct IMaterialEffects; -class IOpticsManager; class ICrySizer; class IXMLBinarySerializer; struct IReadWriteXMLSink; -struct IThreadTaskManager; struct IResourceManager; struct ITextModeConsole; struct IAVI_Reader; class CPNoise3; -struct IVisualLog; struct ILocalizationManager; -struct ISoftCodeMgr; struct IZLibCompressor; struct IZLibDecompressor; struct ILZ4Decompressor; class IZStdDecompressor; struct IOutputPrintSink; -struct IThreadManager; struct IWindowMessageHandler; struct IImageHandler; -class IResourceCompilerHelper; -class ILmbrAWS; namespace AZ { @@ -111,12 +99,6 @@ namespace AZ } } -class IResourceCompilerHelper; - -namespace Serialization { - struct IArchiveHost; -} - typedef void* WIN_HWND; class CCamera; @@ -124,39 +106,13 @@ struct CLoadingTimeProfiler; class ICmdLine; -struct INotificationNetwork; class ILyShine; -namespace JobManager { - struct IJobManager; -} - -#define PROC_MENU 1 -#define PROC_3DENGINE 2 - -// Summary: -// IDs for script userdata typing. -// Remarks: -// Maybe they should be moved into the game.dll . -//##@{ -#define USER_DATA_SOUND 1 -#define USER_DATA_TEXTURE 2 -#define USER_DATA_OBJECT 3 -#define USER_DATA_LIGHT 4 -#define USER_DATA_BONEHANDLER 5 -#define USER_DATA_POINTER 6 -//##@} - enum ESystemUpdateFlags { - ESYSUPDATE_IGNORE_PHYSICS = 0x0002, // Summary: // Special update mode for editor. - ESYSUPDATE_EDITOR = 0x0004, - ESYSUPDATE_MULTIPLAYER = 0x0008, - ESYSUPDATE_EDITOR_AI_PHYSICS = 0x0010, - ESYSUPDATE_EDITOR_ONLY = 0x0020, - ESYSUPDATE_UPDATE_VIEW_ONLY = 0x0040 + ESYSUPDATE_EDITOR = 0x0004 }; // Description: @@ -189,29 +145,6 @@ enum ESystemConfigPlatform END_CONFIG_PLATFORM_ENUM, // MUST BE LAST VALUE. USED FOR ERROR CHECKING. }; -enum ESubsystem -{ - ESubsys_3DEngine = 0, - ESubsys_AI = 1, - ESubsys_Physics = 2, - ESubsys_Renderer = 3, - ESubsys_Script = 4 -}; - -// Summary: -// Collates cycles taken per update. -struct sUpdateTimes -{ - uint32 PhysYields; - uint64 SysUpdateTime; - uint64 PhysStepTime; - uint64 RenderTime; - //extended yimes info - uint64 physWaitTime; - uint64 streamingWaitTime; - uint64 animationWaitTime; -}; - enum ESystemGlobalState { ESYSTEM_GLOBAL_STATE_UNKNOWN, @@ -568,33 +501,6 @@ struct IErrorObserver // }; -enum ESystemProtectedFunctions -{ - eProtectedFunc_Save = 0, - eProtectedFunc_Load = 1, - eProtectedFuncsLast = 10, -}; - -struct SCvarsDefault -{ - SCvarsDefault() - { - sz_r_DriverDef = NULL; - } - - const char* sz_r_DriverDef; -}; - -#if defined(CVARS_WHITELIST) -struct ICVarsWhitelist -{ - // - virtual ~ICVarsWhitelist() {}; - virtual bool IsWhiteListed(const string& command, bool silent) = 0; - // -}; -#endif // defined(CVARS_WHITELIST) - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION ISYSTEM_H_SECTION_3 #include AZ_RESTRICTED_FILE(ISystem_h) @@ -616,9 +522,6 @@ struct SSystemInitParams { void* hInstance; // void* hWnd; // - void* hWndForInputSystem; // the HWND for the input devices, distinct from the hWnd, which the rendering system overrides anyways - - bool remoteResourceCompiler; ILog* pLog; // You can specify your own ILog to be used by System. ILogCallback* pLogCallback; // You can specify your own ILogCallback to be added on log creation (used by Editor). @@ -633,33 +536,14 @@ struct SSystemInitParams bool bPreview; // When running in Preview mode (Minimal initialization). bool bTestMode; // When running in Automated testing mode. bool bDedicatedServer; // When running a dedicated server. - bool bExecuteCommandLine; // can be switched of to suppress the feature or do it later during the initialization. - bool bSkipFont; // Don't load CryFont.dll bool bSkipConsole; // Don't create console - bool bSkipNetwork; // Don't create Network - bool bSkipWebsocketServer; // Don't create the WebSocket server - bool bMinimal; // Don't load banks - bool bTesting; // CryUnit - bool bNoRandom; //use fixed generator init/seed bool bUnattendedMode; // When running as part of a build on build-machines: Prevent popping up of any dialog bool bSkipMovie; // Don't load movie - bool bSkipAnimation; // Don't load animation bool bToolMode; // System is running inside a tool. Will not create USER directory or anything else that the game needs to do - bool bSkipPhysics; // Don't initialize CryPhysics. - ISystem* pSystem; // Pointer to existing ISystem interface, it will be reused if not NULL. - typedef void* (*ProtectedFunction)(void* param1, void* param2); - ProtectedFunction pProtectedFunctions[eProtectedFuncsLast]; // Protected functions. - - SCvarsDefault* pCvarsDefault; // to override the default value of some cvar - -#if defined(CVARS_WHITELIST) - ICVarsWhitelist* pCVarsWhitelist; // CVars whitelist callback -#endif // defined(CVARS_WHITELIST) - SharedEnvironmentInstance* pSharedEnvironment; // Summary: @@ -668,16 +552,10 @@ struct SSystemInitParams { hInstance = NULL; hWnd = NULL; - hWndForInputSystem = NULL; - - remoteResourceCompiler = false; pLog = NULL; pLogCallback = NULL; pUserCallback = NULL; -#if defined(CVARS_WHITELIST) - pCVarsWhitelist = NULL; -#endif // defined(CVARS_WHITELIST) sLogFileName = NULL; autoBackupLogs = true; pValidator = NULL; @@ -688,32 +566,13 @@ struct SSystemInitParams bPreview = false; bTestMode = false; bDedicatedServer = false; - bExecuteCommandLine = true; - bExecuteCommandLine = true; - bSkipFont = false; bSkipConsole = false; - bSkipNetwork = false; -#if defined(WIN32) || defined(WIN64) - // create websocket server by default. bear in mind that USE_HTTP_WEBSOCKETS is not defined in release. - bSkipWebsocketServer = false; -#else - // CTCPStreamSocket only seems to fully support Win32 and 64 - bSkipWebsocketServer = true; -#endif - bMinimal = false; - bTesting = false; - bNoRandom = false; bUnattendedMode = false; bSkipMovie = false; - bSkipAnimation = false; bToolMode = false; - bSkipPhysics = false; pSystem = NULL; - memset(pProtectedFunctions, 0, sizeof(pProtectedFunctions)); - pCvarsDefault = NULL; - pSharedEnvironment = nullptr; } }; @@ -782,8 +641,6 @@ struct SSystemGlobalEnvironment { AZ::IO::IArchive* pCryPak; AZ::IO::FileIOBase* pFileIO; - IProfileLogSystem* pProfileLogSystem; - IOpticsManager* pOpticsManager; ITimer* pTimer; ICryFont* pCryFont; ::IConsole* pConsole; @@ -791,81 +648,27 @@ struct SSystemGlobalEnvironment ILog* pLog; IMovieSystem* pMovieSystem; INameTable* pNameTable; - IVisualLog* pVisualLog; IRenderer* pRenderer; - IMaterialEffects* pMaterialEffects; - ISoftCodeMgr* pSoftCodeMgr; ILyShine* pLyShine; - IResourceCompilerHelper* pResourceCompilerHelper; SharedEnvironmentInstance* pSharedEnvironment; - IThreadManager* pThreadManager; #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION ISYSTEM_H_SECTION_4 #include AZ_RESTRICTED_FILE(ISystem_h) #endif - ISystemScheduler* pSystemScheduler; - threadID mMainThreadId; //The main thread ID is used in multiple systems so should be stored globally - ////////////////////////////////////////////////////////////////////////// - uint32 nMainFrameID; - - ////////////////////////////////////////////////////////////////////////// - const char* szCmdLine; // Startup command line. - - ////////////////////////////////////////////////////////////////////////// - // Generic debug string which can be easily updated by any system and output by the debug handler - enum - { - MAX_DEBUG_STRING_LENGTH = 128 - }; - char szDebugStatus[MAX_DEBUG_STRING_LENGTH]; - - ////////////////////////////////////////////////////////////////////////// - // Used to tell if this is a server/multiplayer instance - bool bServer; - bool bMultiplayer; - bool bHostMigrating; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // Indicate Editor status. - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// // Used by CRY_ASSERT bool bIgnoreAllAsserts; bool bNoAssertDialog; - bool bTesting; ////////////////////////////////////////////////////////////////////////// - bool bNoRandomSeed; - - SPlatformInfo pi; - - // Protected functions. - SSystemInitParams::ProtectedFunction pProtectedFunctions[eProtectedFuncsLast]; // Protected functions. - - ////////////////////////////////////////////////////////////////////////// - // Flag to able to print out of memory conditon - bool bIsOutOfMemory; - bool bIsOutOfVideoMemory; - bool bToolMode; int retCode = 0; - ILINE const bool IsClient() const - { -#if defined(CONSOLE) - return true; -#else - return bClient; -#endif - } - ILINE const bool IsDedicated() const { #if defined(CONSOLE) @@ -895,11 +698,6 @@ struct SSystemGlobalEnvironment { bDedicated = isDedicated; } - - ILINE void SetIsClient(bool isClient) - { - bClient = isClient; - } #endif //this way the compiler can strip out code for consoles @@ -939,26 +737,6 @@ struct SSystemGlobalEnvironment #endif } - ILINE const bool IsFMVPlaying() const - { - return m_isFMVPlaying; - } - - ILINE void SetFMVIsPlaying(const bool isPlaying) - { - m_isFMVPlaying = isPlaying; - } - - ILINE const bool IsCutscenePlaying() const - { - return m_isCutscenePlaying; - } - - ILINE void SetCutsceneIsPlaying(const bool isPlaying) - { - m_isCutscenePlaying = isPlaying; - } - ILINE bool IsInToolMode() const { return bToolMode; @@ -969,35 +747,17 @@ struct SSystemGlobalEnvironment bToolMode = bNewToolMode; } - ILINE void SetDynamicMergedMeshGenerationEnabled(bool mmgenEnable) - { - m_bDynamicMergedMeshGenerationEnabled = mmgenEnable; - } - - ILINE const bool IsDynamicMergedMeshGenerationEnabled() const - { - return m_bDynamicMergedMeshGenerationEnabled; - } - #if !defined(CONSOLE) private: - bool bClient; bool bEditor; // Engine is running under editor. bool bEditorGameMode; // Engine is in editor game mode. bool bEditorSimulationMode; // Engine is in editor simulation mode. bool bDedicated; // Engine is in dedicated #endif - bool m_isFMVPlaying; - bool m_isCutscenePlaying; - bool m_bDynamicMergedMeshGenerationEnabled; - public: SSystemGlobalEnvironment() - : pSystemScheduler(nullptr) - , szCmdLine("") - , bToolMode(false) - , m_bDynamicMergedMeshGenerationEnabled(false) + : bToolMode(false) { }; }; @@ -1035,37 +795,11 @@ struct IProfilingSystem // Initialize and dispatch all engine's subsystems. struct ISystem { - struct ILoadingProgressListener - { - // - virtual ~ILoadingProgressListener() {} - virtual void OnLoadingProgress(int steps) = 0; - // - }; - -#ifndef _RELEASE - enum LevelLoadOrigin - { - eLLO_Unknown, - eLLO_NewLevel, - eLLO_Level2Level, - eLLO_Resumed, - eLLO_MapCmd, - }; - - struct ICheckpointData - { - int m_totalLoads; - LevelLoadOrigin m_loadOrigin; - }; -#endif - // virtual ~ISystem() {} // Summary: // Releases ISystem. virtual void Release() = 0; - virtual ILoadConfigurationEntrySink* GetCVarsWhiteListConfigSink() const = 0; // will return NULL if no whitelisting // Summary: // Returns pointer to the global environment structure. @@ -1094,9 +828,6 @@ struct ISystem virtual void DoWorkDuringOcclusionChecks() = 0; virtual bool NeedDoWorkDuringOcclusionChecks() = 0; - //! Update screen and call some important tick functions during loading. - virtual void SynchronousLoadingTick(const char* pFunc, int line) = 0; - // Summary: // Returns the current used memory. virtual uint32 GetUsedMemory() = 0; @@ -1170,7 +901,6 @@ struct ISystem virtual IZLibDecompressor* GetIZLibDecompressor() = 0; virtual ILZ4Decompressor* GetLZ4Decompressor() = 0; virtual IZStdDecompressor* GetZStdDecompressor() = 0; - virtual INotificationNetwork* GetINotificationNetwork() = 0; virtual IViewSystem* GetIViewSystem() = 0; virtual ILevelSystem* GetILevelSystem() = 0; virtual INameTable* GetINameTable() = 0; @@ -1187,24 +917,10 @@ struct ISystem // Returns: // Can be NULL, because it only exists when running through the editor, not in pure game mode. virtual IResourceManager* GetIResourceManager() = 0; - virtual IThreadTaskManager* GetIThreadTaskManager() = 0; virtual IProfilingSystem* GetIProfilingSystem() = 0; virtual ISystemEventDispatcher* GetISystemEventDispatcher() = 0; - virtual IVisualLog* GetIVisualLog() = 0; virtual ITimer* GetITimer() = 0; - virtual IThreadManager* GetIThreadManager() = 0; - - virtual void SetLoadingProgressListener(ILoadingProgressListener* pListener) = 0; - virtual ISystem::ILoadingProgressListener* GetLoadingProgressListener() const = 0; - - // Summary: - // Game is created after System init, so has to be set explicitly. - virtual void SetIMaterialEffects(IMaterialEffects* pMaterialEffects) = 0; - virtual void SetIOpticsManager(IOpticsManager* pOpticsManager) = 0; - virtual void SetIVisualLog(IVisualLog* pVisualLog) = 0; - - //virtual const char *GetGamePath()=0; virtual void DebugStats(bool checkpoint, bool leaks) = 0; virtual void DumpWinHeaps() = 0; @@ -1219,7 +935,6 @@ struct ISystem virtual bool WasInDevMode() const = 0; virtual bool IsDevMode() const = 0; virtual bool IsMODValid(const char* szMODName) const = 0; - virtual bool IsMinimalMode() const = 0; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// @@ -1334,12 +1049,6 @@ struct ISystem // Detects and set optimal spec. virtual void AutoDetectSpec(bool detectResolution) = 0; - // Summary: - // Thread management for subsystems - // Return Value: - // Non-0 if the state was indeed changed, 0 if already in that state. - virtual int SetThreadState(ESubsystem subsys, bool bActive) = 0; - // Summary: // Query if system is now paused. // Pause flag is set when calling system update with pause mode. @@ -1406,14 +1115,6 @@ struct ISystem // Get log index of the currently running Open 3D Engine application. (0 = first instance, 1 = second instance, etc) virtual int GetApplicationLogInstance(const char* logFilePath) = 0; - // Summary: - // Retrieves the current stats for systems to update the respective time taken - virtual sUpdateTimes& GetCurrentUpdateTimeStats() = 0; - - // Summary: - // Retrieves the array of update times and the number of entries - virtual const sUpdateTimes* GetUpdateTimeStats(uint32&, uint32&) = 0; - // Summary: // Clear all currently logged and drawn on screen error messages virtual void ClearErrorMessages() = 0; @@ -1458,17 +1159,6 @@ struct ISystem virtual void AsyncMemcpy(void* dst, const void* src, size_t size, int nFlags, volatile int* sync) = 0; // - -#if defined(CVARS_WHITELIST) - virtual ICVarsWhitelist* GetCVarsWhiteList() const = 0; -#endif // defined(CVARS_WHITELIST) - -#ifndef _RELEASE - virtual void GetCheckpointData(ICheckpointData& data) = 0; - virtual void IncreaseCheckpointLoadCount() = 0; - virtual void SetLoadOrigin(LevelLoadOrigin origin) = 0; -#endif - #if !defined(_RELEASE) virtual bool IsSavingResourceList() const = 0; #endif @@ -1513,11 +1203,6 @@ struct ISystem using CrySystemNotificationBus = AZ::EBus; }; -//JAT - this is a very important function for the dedicated server - it lets us run >1000 players per piece of server hardware -//JAT - this saves us lots of money on the dedicated server hardware -#define SYNCHRONOUS_LOADING_TICK() do { if (gEnv && gEnv->pSystem) {gEnv->pSystem->SynchronousLoadingTick(__FUNC__, __LINE__); } \ -} while (0) - #if defined(USE_DISK_PROFILER) struct DiskOperationInfo @@ -1594,7 +1279,7 @@ typedef ISystem* (*PFNCREATESYSTEMINTERFACE)(SSystemInitParams& initParams); ////////////////////////////////////////////////////////////////////////// // Global environment variable. ////////////////////////////////////////////////////////////////////////// -extern SC_API SSystemGlobalEnvironment* gEnv; +extern SSystemGlobalEnvironment* gEnv; // Summary: @@ -1613,11 +1298,6 @@ inline ISystem* GetISystem() } return systemInterface; }; - -inline ISystemScheduler* GetISystemScheduler(void) -{ - return gEnv->pSystemScheduler; -}; ////////////////////////////////////////////////////////////////////////// // Description: @@ -1640,7 +1320,6 @@ void* GetDetachEnvironmentSymbol(); extern bool g_bProfilerEnabled; -extern int g_iTraceAllocations; // Summary: // Interface of the DLL. diff --git a/Code/CryEngine/CryCommon/ISystemScheduler.h b/Code/CryEngine/CryCommon/ISystemScheduler.h deleted file mode 100644 index 9280eb2ea6..0000000000 --- a/Code/CryEngine/CryCommon/ISystemScheduler.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_ISYSTEMSCHEDULER_H -#define CRYINCLUDE_CRYCOMMON_ISYSTEMSCHEDULER_H -#pragma once - -#if defined(__cplusplus) -#define SLICE_AND_SLEEP() do { if (GetISystemScheduler()) { GetISystemScheduler()->SliceAndSleep(__FUNC__, __LINE__); } \ -} while (0) -#define SLICE_SCOPE_DEFINE() CSliceLoadingMonitor sliceScope -#else -extern void SliceAndSleep(const char* pFunc, int line); -#define SLICE_AND_SLEEP() SliceAndSleep(__FILE__, __LINE__) -#endif - -struct ISystemScheduler -{ - virtual ~ISystemScheduler(){} - - // - // Map load slicing functionality support - virtual void SliceAndSleep(const char* sliceName, int line) = 0; - virtual void SliceLoadingBegin() = 0; - virtual void SliceLoadingEnd() = 0; - - virtual void SchedulingSleepIfNeeded(void) = 0; - // -}; - -ISystemScheduler* GetISystemScheduler(void); - -class CSliceLoadingMonitor -{ -public: - CSliceLoadingMonitor() - { - if (GetISystemScheduler()) - { - GetISystemScheduler()->SliceLoadingBegin(); - } - } - - ~CSliceLoadingMonitor() - { - if (GetISystemScheduler()) - { - GetISystemScheduler()->SliceLoadingEnd(); - } - } -}; - -#endif // CRYINCLUDE_CRYCOMMON_ISYSTEMSCHEDULER_H diff --git a/Code/CryEngine/CryCommon/IThreadManager.h b/Code/CryEngine/CryCommon/IThreadManager.h deleted file mode 100644 index 448e3eec16..0000000000 --- a/Code/CryEngine/CryCommon/IThreadManager.h +++ /dev/null @@ -1,111 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -class IThreadConfigManager; - -enum EJoinMode -{ - eJM_TryJoin, - eJM_Join, -}; - -class IThread -{ -public: - // - virtual ~IThread() - { - } - - //! Entry functions for code executed on thread. - virtual void ThreadEntry() = 0; - // -}; - -enum EFPE_Severity -{ - eFPE_None, //!< No Floating Point Exceptions. - eFPE_Basic, //!< Invalid operation, Div by 0. - eFPE_All, //!< Invalid operation, Div by 0, Denormalized operand, Overflow, Underflow, Inexact. - eFPE_LastEntry -}; - -//temp disable CRY DX12 -//#define SCOPED_ENABLE_FLOAT_EXCEPTIONS(eFPESeverity) CScopedFloatingPointException scopedSetFloatExceptionMask(eFPESeverity) -//#define SCOPED_DISABLE_FLOAT_EXCEPTIONS() CScopedFloatingPointException scopedSetFloatExceptionMask(eFPE_None) - -struct IThreadManager -{ -public: - // - virtual ~IThreadManager() - { - } - - //! Get thread config manager. - virtual IThreadConfigManager* GetThreadConfigManager() = 0; - - //! Spawn a new thread and apply thread config settings at thread beginning. - virtual bool SpawnThread(IThread* pThread, const char* sThreadName, ...) = 0; - - //! Wait on another thread to exit (Blocking). - //! Use eJM_TryJoin if you cannot be sure that the target thread is awake. - //! \retval true if target thread has not been started yet or has already exited. - //! \retval false if target thread is still running and therefore not in a state to exit. - virtual bool JoinThread(IThread* pThreadTask, EJoinMode joinStatus) = 0; - - //! Register 3rd party thread with the thread manager. - //! Applies thread config for thread if found. - //! \param pThreadHandle If NULL, the current thread handle will be used. - virtual bool RegisterThirdPartyThread(void* pThreadHandle, const char* sThreadName, ...) = 0; - - //! Unregister 3rd party thread with the thread manager. - virtual bool UnRegisterThirdPartyThread(const char* sThreadName, ...) = 0; - - //! Get Thread Name. - //! Returns "" if thread not found. - virtual const char* GetThreadName(threadID nThreadId) = 0; - - //! Get ThreadID. - virtual threadID GetThreadId(const char* sThreadName, ...) = 0; - - //! Execute function for each other thread but this one. - typedef void (* ThreadModifFunction)(threadID nThreadId, void* pData); - virtual void ForEachOtherThread(IThreadManager::ThreadModifFunction fpThreadModiFunction, void* pFuncData = 0) = 0; - - virtual void EnableFloatExceptions(EFPE_Severity eFPESeverity, threadID nThreadId = 0) = 0; - virtual void EnableFloatExceptionsForEachOtherThread(EFPE_Severity eFPESeverity) = 0; - - virtual uint GetFloatingPointExceptionMask() = 0; - virtual void SetFloatingPointExceptionMask(uint nMask) = 0; - // -}; -/*TEMP DISABLE CRY DX12 -class CScopedFloatingPointException -{ -public: - CScopedFloatingPointException(EFPE_Severity eFPESeverity) - { - oldMask = gEnv->pThreadManager->GetFloatingPointExceptionMask(); - gEnv->pThreadManager->EnableFloatExceptions(eFPESeverity); - } - ~CScopedFloatingPointException() - { - gEnv->pThreadManager->SetFloatingPointExceptionMask(oldMask); - } -private: - uint oldMask; -}; -*/ diff --git a/Code/CryEngine/CryCommon/IThreadTask.h b/Code/CryEngine/CryCommon/IThreadTask.h deleted file mode 100644 index d4a565fcff..0000000000 --- a/Code/CryEngine/CryCommon/IThreadTask.h +++ /dev/null @@ -1,166 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "BitFiddling.h" - -#ifndef CRYINCLUDE_CRYCOMMON_ITHREADTASK_H -#define CRYINCLUDE_CRYCOMMON_ITHREADTASK_H -#pragma once - -#include - -// forward declarations -struct SThreadTaskInfo; - -enum EThreadTaskFlags -{ - THREAD_TASK_BLOCKING = BIT(0), // Blocking tasks will be allocated on their own thread. - THREAD_TASK_ASSIGN_TO_POOL = BIT(1), // Task can be assigned to any thread in the group of threads -}; - -class IThreadTask_Thread -{ -public: - // - virtual ~IThreadTask_Thread() {}; - virtual void AddTask(SThreadTaskInfo* pTaskInfo) = 0; - virtual void RemoveTask(SThreadTaskInfo* pTaskInfo) = 0; - virtual void RemoveAllTasks() = 0; - virtual void SingleUpdate() = 0; - // -}; - -typedef int ThreadPoolHandle; - -struct SThreadTaskParams -{ - uint32 nFlags; // Task flags. @see ETaskFlags - union - { - int nPreferedThread; // Preferred Thread index (0,1,2,3...) - ThreadPoolHandle nThreadsGroupId; // Id of group of threads(useful only if THREAD_TASK_ASSIGN_TO_POOL is set) - }; - int16 nPriorityOff; // If THREAD_TASK_BLOCKING, this will adjust the priority of the thread - int16 nStackSizeKB; // If THREAD_TASK_BLOCKING, this will adjust the stack size of the thread - const char* name; // Name for this task (thread for the blocking task will be named using this string) - - SThreadTaskParams() - : nFlags(0) - , nPreferedThread(-1) - , nPriorityOff(0) - , name("") - , nStackSizeKB(SIMPLE_THREAD_STACK_SIZE_KB) {} -}; - -////////////////////////////////////////////////////////////////////////// -// Tasks must implement this interface. -////////////////////////////////////////////////////////////////////////// -struct IThreadTask -{ - // - // The function to be called on every update for non bocking tasks. - // Or will be called only once for the blocking threads. - virtual void OnUpdate() = 0; - - // Called to indicate that this task must quit. - // Warning! can be called from different thread then OnUpdate call. - virtual void Stop() = 0; - - // Returns task info - virtual struct SThreadTaskInfo* GetTaskInfo() = 0; - - virtual ~IThreadTask() {} - // -}; - -struct SThreadTaskInfo - : public CMultiThreadRefCount -{ - IThreadTask_Thread* m_pThread; - IThreadTask* m_pTask; - SThreadTaskParams m_params; - - SThreadTaskInfo() - : m_pThread(NULL) - , m_pTask(NULL) { m_params.nFlags = 0; m_params.nPreferedThread = -1; } -}; - -// Might be changed to uint64 etc in the future -typedef uint32 ThreadPoolAffinityMask; -#define INVALID_AFFINITY 0 - -////////////////////////////////////////////////////////////////////////// -// Description of thread pool to create -////////////////////////////////////////////////////////////////////////// -struct ThreadPoolDesc -{ - ThreadPoolAffinityMask AffinityMask; // number of bits means number of threads. affinity overlapping is prohibited - string sPoolName; - int32 nThreadPriority; - int32 nThreadStackSizeKB; - - ThreadPoolDesc() - : AffinityMask(INVALID_AFFINITY) - , sPoolName("UnnamedPool") - , nThreadPriority(-1) - , nThreadStackSizeKB(-1) { } - - ILINE bool CreateThread(ThreadPoolAffinityMask affinityMask) - { - if (this->AffinityMask & affinityMask) - { - return false; - } - - this->AffinityMask |= affinityMask; - return true; - } - - ILINE uint32 GetThreadCount() const - { - return CountBits(AffinityMask); - } -}; - -////////////////////////////////////////////////////////////////////////// -// Task manager. -////////////////////////////////////////////////////////////////////////// -struct IThreadTaskManager -{ - // - virtual ~IThreadTaskManager(){} - // Register new task to the manager. - virtual void RegisterTask(IThreadTask* pTask, const SThreadTaskParams& options) = 0; - virtual void UnregisterTask(IThreadTask* pTask) = 0; - - // Limit number of threads to this amount. - virtual void SetMaxThreadCount(int nMaxThreads) = 0; - - // Create a pool of threads - virtual ThreadPoolHandle CreateThreadsPool(const ThreadPoolDesc& desc) = 0; - virtual const bool DestroyThreadsPool(const ThreadPoolHandle& handle) = 0; - virtual const bool GetThreadsPoolDesc(const ThreadPoolHandle handle, ThreadPoolDesc* pDesc) const = 0; - virtual const bool SetThreadsPoolAffinity(const ThreadPoolHandle handle, const ThreadPoolAffinityMask AffinityMask) = 0; - - virtual void SetThreadName(threadID dwThreadId, const char* sThreadName) = 0; - virtual const char* GetThreadName(threadID dwThreadId) = 0; - - // Return thread handle by thread name - virtual threadID GetThreadByName(const char* sThreadName) = 0; - - // if bMark=true the calling thread will dump its stack during crashes - virtual void MarkThisThreadForDebugging(const char* name, bool bDump) = 0; - // -}; - -#endif // CRYINCLUDE_CRYCOMMON_ITHREADTASK_H diff --git a/Code/CryEngine/CryCommon/Mocks/IRendererMock.h b/Code/CryEngine/CryCommon/Mocks/IRendererMock.h index 7b0b7b76a2..74d072c48c 100644 --- a/Code/CryEngine/CryCommon/Mocks/IRendererMock.h +++ b/Code/CryEngine/CryCommon/Mocks/IRendererMock.h @@ -585,8 +585,6 @@ public: SDepthTexture * (int, int, bool)); MOCK_METHOD1(DestroyDepthSurface, void(SDepthTexture * pDepthSurf)); - MOCK_CONST_METHOD1(CreateOptics, - IOpticsElementBase * (EFlareType type)); MOCK_METHOD1(PauseTimer, void(bool bPause)); MOCK_METHOD0(CreateShaderPublicParams, diff --git a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h index 1e28937764..cfe150c1df 100644 --- a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h +++ b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h @@ -23,8 +23,6 @@ class SystemMock public: MOCK_METHOD0(Release, void()); - MOCK_CONST_METHOD0(GetCVarsWhiteListConfigSink, - ILoadConfigurationEntrySink * ()); MOCK_METHOD0(GetGlobalEnvironment, SSystemGlobalEnvironment * ()); MOCK_METHOD2(UpdatePreTickBus, @@ -37,8 +35,6 @@ public: void()); MOCK_METHOD0(NeedDoWorkDuringOcclusionChecks, bool()); - MOCK_METHOD2(SynchronousLoadingTick, - void(const char* pFunc, int line)); MOCK_METHOD0(RenderStatistics, void()); MOCK_METHOD0(GetUsedMemory, @@ -84,8 +80,6 @@ public: ILZ4Decompressor * ()); MOCK_METHOD0(GetZStdDecompressor, IZStdDecompressor * ()); - MOCK_METHOD0(GetINotificationNetwork, - INotificationNetwork * ()); MOCK_METHOD0(GetIViewSystem, IViewSystem * ()); MOCK_METHOD0(GetILevelSystem, @@ -116,28 +110,12 @@ public: IRemoteConsole * ()); MOCK_METHOD0(GetIResourceManager, IResourceManager * ()); - MOCK_METHOD0(GetIThreadTaskManager, - IThreadTaskManager * ()); MOCK_METHOD0(GetIProfilingSystem, IProfilingSystem * ()); MOCK_METHOD0(GetISystemEventDispatcher, ISystemEventDispatcher * ()); - MOCK_METHOD0(GetIVisualLog, - IVisualLog * ()); MOCK_METHOD0(GetITimer, ITimer * ()); - MOCK_METHOD0(GetIThreadManager, - IThreadManager * ()); - MOCK_METHOD1(SetLoadingProgressListener, - void(ILoadingProgressListener * pListener)); - MOCK_CONST_METHOD0(GetLoadingProgressListener, - ISystem::ILoadingProgressListener * ()); - MOCK_METHOD1(SetIMaterialEffects, - void(IMaterialEffects * pMaterialEffects)); - MOCK_METHOD1(SetIOpticsManager, - void(IOpticsManager * pOpticsManager)); - MOCK_METHOD1(SetIVisualLog, - void(IVisualLog * pVisualLog)); MOCK_METHOD2(DebugStats, void(bool checkpoint, bool leaks)); MOCK_METHOD0(DumpWinHeaps, @@ -154,8 +132,6 @@ public: bool()); MOCK_CONST_METHOD1(IsMODValid, bool(const char* szMODName)); - MOCK_CONST_METHOD0(IsMinimalMode, - bool()); MOCK_METHOD3(CreateXmlNode, XmlNodeRef(const char*, bool, bool)); MOCK_METHOD4(LoadXmlFromBuffer, @@ -209,8 +185,6 @@ public: void(ESystemConfigPlatform platform)); MOCK_METHOD1(AutoDetectSpec, void(bool detectResolution)); - MOCK_METHOD2(SetThreadState, - int(ESubsystem subsys, bool bActive)); MOCK_CONST_METHOD0(IsPaused, bool()); MOCK_METHOD0(GetLocalizationManager, @@ -239,10 +213,6 @@ public: int()); MOCK_METHOD1(GetApplicationLogInstance, int(const char* logFilePath)); - MOCK_METHOD0(GetCurrentUpdateTimeStats, - sUpdateTimes & ()); - MOCK_METHOD2(GetUpdateTimeStats, - const sUpdateTimes * (uint32 &, uint32 &)); MOCK_METHOD0(ClearErrorMessages, void()); MOCK_METHOD2(debug_GetCallStack, @@ -260,20 +230,6 @@ public: MOCK_METHOD5(AsyncMemcpy, void(void* dst, const void* src, size_t size, int nFlags, volatile int* sync)); -#if defined(CVARS_WHITELIST) - MOCK_CONST_METHOD0(GetCVarsWhiteList, - ICVarsWhitelist * ()); -#endif - -#ifndef _RELEASE - MOCK_METHOD1(GetCheckpointData, - void(ICheckpointData & data)); - MOCK_METHOD0(IncreaseCheckpointLoadCount, - void()); - MOCK_METHOD1(SetLoadOrigin, - void(LevelLoadOrigin origin)); -#endif - #if !defined(_RELEASE) MOCK_CONST_METHOD0(IsSavingResourceList, bool()); diff --git a/Code/CryEngine/CryCommon/ProfileLog.h b/Code/CryEngine/CryCommon/ProfileLog.h deleted file mode 100644 index fbde619166..0000000000 --- a/Code/CryEngine/CryCommon/ProfileLog.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_PROFILELOG_H -#define CRYINCLUDE_CRYCOMMON_PROFILELOG_H -#pragma once - - -#include // <> required for Interfuscator -#include // <> required for Interfuscator - -struct ILogElement -{ - virtual ~ILogElement(){} - virtual ILogElement* Log (const char* name, const char* message) = 0; - virtual ILogElement* SetTime (float time) = 0; - virtual void Flush (stack_string& indent) = 0; -}; - -struct IProfileLogSystem -{ - virtual ~IProfileLogSystem(){} - virtual ILogElement* Log (const char* name, const char* msg) = 0; - virtual void SetTime (ILogElement* pElement, float time) = 0; - virtual void Release () = 0; -}; - -struct SHierProfileLogItem -{ - SHierProfileLogItem(const char* name, const char* msg, int inbDoLog) - : m_pLogElement(NULL) - , m_bDoLog(inbDoLog) - { - if (m_bDoLog) - { - m_pLogElement = gEnv->pProfileLogSystem->Log(name, msg); - m_startTime = gEnv->pTimer->GetAsyncTime(); - } - } - ~SHierProfileLogItem() - { - if (m_bDoLog) - { - CTimeValue endTime = gEnv->pTimer->GetAsyncTime(); - gEnv->pProfileLogSystem->SetTime(m_pLogElement, (endTime - m_startTime).GetMilliSeconds()); - } - } - -private: - int m_bDoLog; - CTimeValue m_startTime; - ILogElement* m_pLogElement; -}; - -#define HPROFILE_BEGIN(msg1, msg2, doLog) { SHierProfileLogItem __hier_profile_uniq_var_in_this_scope__(msg1, msg2, doLog); -#define HPROFILE_END() } - -#define HPROFILE(msg1, msg2, doLog) SHierProfileLogItem __hier_profile_uniq_var_in_this_scope__(msg1, msg2, doLog); - -#endif // CRYINCLUDE_CRYCOMMON_PROFILELOG_H diff --git a/Code/CryEngine/CryCommon/ProjectDefines.h b/Code/CryEngine/CryCommon/ProjectDefines.h index f82861d6e0..67ae58a324 100644 --- a/Code/CryEngine/CryCommon/ProjectDefines.h +++ b/Code/CryEngine/CryCommon/ProjectDefines.h @@ -78,9 +78,6 @@ typedef uint32 vtx_idx; #if defined(WIN32) || defined(WIN64) || LOG_CONST_CVAR_ACCESS #define RELEASE_LOGGING -//#if defined(_RELEASE) -//#define CVARS_WHITELIST -//#endif // defined(_RELEASE) #endif #if defined(_RELEASE) && !defined(RELEASE_LOGGING) @@ -181,32 +178,6 @@ typedef uint32 vtx_idx; #define SHADER_REFLECT_TEXTURE_SLOTS 0 #endif -#if (defined(WIN32) || defined(WIN64) || defined(AZ_PLATFORM_MAC)) && (!defined(AZ_MONOLITHIC_BUILD) || defined(RESOURCE_COMPILER)) -#define CRY_ENABLE_RC_HELPER 1 -#endif - -#if !defined(_RELEASE) && PROJECTDEFINES_H_TRAIT_ENABLE_SOFTCODE_SYSTEM - #define SOFTCODE_SYSTEM_ENABLED -#endif - -// Is SoftCoding enabled for this module? Usually set by the SoftCode AddIn in conjunction with a SoftCode.props file. -#ifdef SOFTCODE_ENABLED - -// Is this current compilation unit part of a SOFTCODE build? - #ifdef SOFTCODE -// Import any SC functions from the host module - #define SC_API __declspec(dllimport) - #else -// Export any SC functions from the host module - #define SC_API __declspec(dllexport) - #endif - -#else // SoftCode disabled - - #define SC_API - -#endif - // these enable and disable certain net features to give compatibility between PCs and consoles / profile and performance builds #define PC_CONSOLE_NET_COMPATIBLE 0 #define PROFILE_PERFORMANCE_NET_COMPATIBLE 0 @@ -292,10 +263,6 @@ typedef uint32 vtx_idx; # define ENABLE_LOADING_PROFILER // requires AZ_PROFILE_TELEMETRY to also be defined #endif -#if defined(SOFTCODE_ENABLED) - #error "SoftCode currently relies on CryMemoryManager being enabled. Either build without SoftCode support, or enable CryMemoryManager." -#endif - #if PROJECTDEFINES_H_TRAIT_USE_GPU_PARTICLES && !defined(NULL_RENDERER) #define GPU_PARTICLES 1 #else diff --git a/Code/CryEngine/CryCommon/ResourceCompilerHelper.cpp b/Code/CryEngine/CryCommon/ResourceCompilerHelper.cpp deleted file mode 100644 index 33373f7460..0000000000 --- a/Code/CryEngine/CryCommon/ResourceCompilerHelper.cpp +++ /dev/null @@ -1,639 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - - -#include "ProjectDefines.h" - -#if defined(CRY_ENABLE_RC_HELPER) - -#include "ResourceCompilerHelper.h" -#include "EngineSettingsManager.h" - -// When complining CryTiffPlugin the mayaAssert.h is included that defined -// Assert as _Assert. This wreaks havoc with AZ_Assert since under the covers -// it calls AzCore::Debug::Trace::Assert, which gets transformed bo -// Trace::_Assert, which does not exist. Gotta love macros. Undefine Assert -// before we include semaphore so that it can compile correctly -#if defined(Assert) -#undef Assert -#endif - -#include -#include -#include -#include -#include - -#if defined(AZ_PLATFORM_WINDOWS) -#include -#include // ShellExecuteW() -#endif - -#if AZ_TRAIT_OS_PLATFORM_APPLE -#include "AppleSpecific.h" -#include -#else -#undef RC_EXECUTABLE -#define RC_EXECUTABLE "rc.exe" -#endif - -#include -#include // lawsonn - we use std::string internally -#include - -namespace -{ - class LineStreamBuffer - { - public: - template - LineStreamBuffer(T* object, void (T::* method)(const char* line)) - : m_charCount(0) - , m_bTruncated(false) - { - m_target = new Target(object, method); - } - - ~LineStreamBuffer() - { - Flush(); - delete m_target; - } - - void HandleText(const char* text, int length) - { - const char* pos = text; - while (pos - text < length) - { - const char* start = pos; - - while (pos - text < length && *pos != '\n' && *pos != '\r') - { - ++pos; - } - - size_t n = pos - start; - if (m_charCount + n > kMaxCharCount) - { - n = kMaxCharCount - m_charCount; - m_bTruncated = true; - } - memcpy(&m_buffer[m_charCount], start, n); - m_charCount += n; - - if (pos - text < length) - { - Flush(); - while (pos - text < length && (*pos == '\n' || *pos == '\r')) - { - ++pos; - } - } - } - } - - void Flush() - { - if (m_charCount > 0) - { - m_buffer[m_charCount] = 0; - m_target->Call(m_buffer); - m_charCount = 0; - } - } - - bool IsTruncated() const - { - return m_bTruncated; - } - - private: - struct ITarget - { - virtual ~ITarget() {} - virtual void Call(const char* line) = 0; - }; - template - struct Target - : public ITarget - { - public: - Target(T* object, void (T::* method)(const char* line)) - : object(object) - , method(method) {} - virtual void Call(const char* line) - { - (object->*method)(line); - } - private: - T* object; - void (T::* method)(const char* line); - }; - - ITarget* m_target; - size_t m_charCount; - static const size_t kMaxCharCount = 2047; - char m_buffer[kMaxCharCount + 1]; - bool m_bTruncated; - }; - -#if !defined(AZ_PLATFORM_WINDOWS) - void MessageBoxW(int, const wchar_t* header, const wchar_t* message, unsigned long) - { -#if AZ_TRAIT_OS_PLATFORM_APPLE - CFStringEncoding encoding = (CFByteOrderLittleEndian == CFByteOrderGetCurrent()) ? - kCFStringEncodingUTF32LE : kCFStringEncodingUTF32BE; - CFStringRef header_ref = CFStringCreateWithBytes(nullptr, reinterpret_cast(header), wcslen(header) * sizeof(wchar_t), encoding, false); - CFStringRef message_ref = CFStringCreateWithBytes(nullptr, reinterpret_cast(message), wcslen(message) * sizeof(wchar_t), encoding, false); - - CFOptionFlags result; //result code from the message box - - CFUserNotificationDisplayAlert(0, kCFUserNotificationStopAlertLevel, 0, 0, 0, header_ref, message_ref, 0, 0, 0, &result); - - CFRelease(header_ref); - CFRelease(message_ref); -#endif - } -#endif -} - -namespace -{ - class RcLock - { - public: - RcLock() - : m_cs(0u, 1u) - { - m_cs.release(); - } - ~RcLock() - { - } - - void Lock() - { - m_cs.acquire(); - } - void Unlock() - { - m_cs.release(); - } - - private: - AZStd::semaphore m_cs; - }; - - - template - class RcAutoLock - { - public: - RcAutoLock(LockClass& lock) - : m_lock(lock) - { - m_lock.Lock(); - } - ~RcAutoLock() - { - m_lock.Unlock(); - } - - private: - RcAutoLock(); - RcAutoLock(const RcAutoLock&); - RcAutoLock& operator =(const RcAutoLock&); - - private: - LockClass& m_lock; - }; - - - HANDLE s_rcProcessHandle = 0; - RcLock s_rcProcessHandleLock; -} - -////////////////////////////////////////////////////////////////////////// -static void ShowMessageBoxRcNotFound([[maybe_unused]] const wchar_t* const szCmdLine, [[maybe_unused]] const wchar_t* const szDir) -{ - SettingsManagerHelpers::CFixedString tmp; - - tmp.append(L"The resource compiler (RC.EXE) was not found."); - MessageBoxW(0, tmp.c_str(), L"Error", MB_ICONERROR | MB_OK); -} - - -////////////////////////////////////////////////////////////////////////// -namespace -{ - class ResourceCompilerLineHandler - { - public: - ResourceCompilerLineHandler(IResourceCompilerListener* listener) - : m_listener(listener) - { - } - - void HandleLine(const char* line) - { - if (!m_listener || !line) - { - return; - } - - // check the first three characters to see if it's a warning or error. - bool bHasPrefix; - IResourceCompilerListener::MessageSeverity severity; - if ((line[0] == 'E') && (line[1] == ':') && (line[2] == ' ')) - { - bHasPrefix = true; - severity = IResourceCompilerListener::MessageSeverity_Error; - line += 3; // skip the prefix - } - else if ((line[0] == 'W') && (line[1] == ':') && (line[2] == ' ')) - { - bHasPrefix = true; - severity = IResourceCompilerListener::MessageSeverity_Warning; - line += 3; // skip the prefix - } - else if ((line[0] == ' ') && (line[1] == ' ') && (line[2] == ' ')) - { - bHasPrefix = true; - severity = IResourceCompilerListener::MessageSeverity_Info; - line += 3; // skip the prefix - } - else - { - bHasPrefix = false; - severity = IResourceCompilerListener::MessageSeverity_Info; - } - - if (bHasPrefix) - { - // skip thread info "%d>", if present - { - const char* p = line; - while (*p == ' ') - { - ++p; - } - if (isdigit(*p)) - { - while (isdigit(*p)) - { - ++p; - } - if (*p == '>') - { - line = p + 1; - } - } - } - - // skip time info "%d:%d", if present - { - const char* p = line; - while (*p == ' ') - { - ++p; - } - if (isdigit(*p)) - { - while (isdigit(*p)) - { - ++p; - } - if (*p == ':') - { - ++p; - if (isdigit(*p)) - { - while (isdigit(*p)) - { - ++p; - } - while (*p == ' ') - { - ++p; - } - line = p; - } - } - } - } - } - - m_listener->OnRCMessage(severity, line); - } - - private: - IResourceCompilerListener* m_listener; - }; - - // we now support macros like #ENGINEROOT# in the string: - void replaceAllInStringInPlace(std::string& inOut, const char* findValue, const char* replaceValue) - { - if (!findValue) - { - return; - } - - if (!replaceValue) - { - return; - } - - std::string::size_type pos = std::string::npos; - std::string::size_type replaceLen = strlen(findValue); - - while ((pos = inOut.find(findValue)) != std::string::npos) - { - inOut.replace(pos, replaceLen, replaceValue); - } - } - - // given a string that contains macros (like #ENGINEROOT#), eliminate the macros and replace them with the real data. - // note that in the 'remote' implementation, these macros are sent to the remote RC. It can then expand them for its own environment - // but in a local RC, these macros are expanded by the local environment. - void expandMacros(const char* inputString, char* outputString, std::size_t bufferSize) - { - if (!inputString) - { - return; - } - - if (!outputString) - { - return; - } - - AZStd::string_view rootFolder; - AZ::ComponentApplicationBus::BroadcastResult(rootFolder, &AZ::ComponentApplicationRequests::GetAppRoot); - - std::string finalString(inputString); - const AZStd::string rootFolderStr = rootFolder.data(); - replaceAllInStringInPlace(finalString, "#ENGINEROOT#", rootFolderStr.c_str()); - // put additional replacements here. - - azstrcpy(outputString, bufferSize, finalString.c_str()); - } -} - -////////////////////////////////////////////////////////////////////////// -IResourceCompilerHelper::ERcCallResult CResourceCompilerHelper::CallResourceCompiler( - const char* szFileName, - const char* szAdditionalSettings, - IResourceCompilerListener* listener, - bool bMayShowWindow, - bool bSilent, - bool bNoUserDialog, - const wchar_t* szWorkingDirectory, - [[maybe_unused]] const wchar_t* szRootPath) -{ -#if defined(AZ_PLATFORM_WINDOWS) - HANDLE hChildStdOutRd = INVALID_HANDLE_VALUE, hChildStdOutWr = INVALID_HANDLE_VALUE; - HANDLE hChildStdInRd = INVALID_HANDLE_VALUE, hChildStdInWr = INVALID_HANDLE_VALUE; - PROCESS_INFORMATION pi; -#else - FILE* hChildStdOutRd; -#endif - - { - RcAutoLock lock(s_rcProcessHandleLock); - - // make command for execution - SettingsManagerHelpers::CFixedString wRemoteCmdLine; - - - if (!szAdditionalSettings) - { - szAdditionalSettings = ""; - } - - // expand the additioanl settings. - char szActualFileName[512] = {0}; - char szActualAdditionalSettings[512] = {0}; - - expandMacros(szFileName, szActualFileName, 512); - expandMacros(szAdditionalSettings, szActualAdditionalSettings, 512); - - CSettingsManagerTools smTools = CSettingsManagerTools(); // moved this line to after macro expansion to avoid multiple of these existing at once. - - AZStd::string_view exeFolderName; - AZ::ComponentApplicationBus::BroadcastResult(exeFolderName, &AZ::ComponentApplicationRequests::GetExecutableFolder); - - wchar_t szRegSettingsBuffer[1024]; - smTools.GetEngineSettingsManager()->GetValueByRef("RC_Parameters", SettingsManagerHelpers::CWCharBuffer(szRegSettingsBuffer, sizeof(szRegSettingsBuffer))); - bool enableSourceControl = true; - smTools.GetEngineSettingsManager()->GetValueByRef("RC_EnableSourceControl", enableSourceControl); - - wRemoteCmdLine.appendAscii("\""); - wRemoteCmdLine.appendAscii(exeFolderName.data(), exeFolderName.size()); - wRemoteCmdLine.appendAscii("/"); - wRemoteCmdLine.appendAscii(RC_EXECUTABLE); - wRemoteCmdLine.appendAscii("\""); - - if (!enableSourceControl) - { - wRemoteCmdLine.appendAscii(" -nosourcecontrol "); - } - - if (!szFileName) - { - wRemoteCmdLine.appendAscii(" -userdialog=0 "); - wRemoteCmdLine.appendAscii(szActualAdditionalSettings); - wRemoteCmdLine.appendAscii(" "); - wRemoteCmdLine.append(szRegSettingsBuffer); - } - else - { - wRemoteCmdLine.appendAscii(" \""); - wRemoteCmdLine.appendAscii(szActualFileName); - wRemoteCmdLine.appendAscii("\""); - wRemoteCmdLine.appendAscii(bNoUserDialog ? " -userdialog=0 " : " -userdialog=1 "); - wRemoteCmdLine.appendAscii(szActualAdditionalSettings); - wRemoteCmdLine.appendAscii(" "); - wRemoteCmdLine.append(szRegSettingsBuffer); - } - - // Create a pipe to read the stdout of the RC. - SECURITY_ATTRIBUTES saAttr; - if (listener) - { -#if defined(AZ_PLATFORM_WINDOWS) - ZeroMemory(&saAttr, sizeof(saAttr)); - saAttr.bInheritHandle = TRUE; - saAttr.lpSecurityDescriptor = 0; - CreatePipe(&hChildStdOutRd, &hChildStdOutWr, &saAttr, 0); - SetHandleInformation(hChildStdOutRd, HANDLE_FLAG_INHERIT, 0); // Need to do this according to MSDN - CreatePipe(&hChildStdInRd, &hChildStdInWr, &saAttr, 0); - SetHandleInformation(hChildStdInWr, HANDLE_FLAG_INHERIT, 0); // Need to do this according to MSDN -#endif - } - -#if defined(AZ_PLATFORM_WINDOWS) - STARTUPINFOW si; - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - si.dwX = 100; - si.dwY = 100; - if (listener) - { - si.hStdError = hChildStdOutWr; - si.hStdOutput = hChildStdOutWr; - si.hStdInput = hChildStdInRd; - si.dwFlags = STARTF_USEPOSITION | STARTF_USESTDHANDLES; - } - else - { - si.dwFlags = STARTF_USEPOSITION; - } - - ZeroMemory(&pi, sizeof(pi)); -#endif - - bool bShowWindow; - if (bMayShowWindow) - { - wchar_t buffer[20]; - smTools.GetEngineSettingsManager()->GetValueByRef("ShowWindow", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))); - bShowWindow = (wcscmp(buffer, L"true") == 0); - } - else - { - bShowWindow = false; - } - -#if defined(AZ_PLATFORM_WINDOWS) - const wchar_t* szStartingDirectory = szWorkingDirectory; - if (!szStartingDirectory) - { - char currentDirectory[MAX_PATH]; - AZ::Utils::GetExecutableDirectory(currentDirectory, MAX_PATH); - SettingsManagerHelpers::CFixedString wCurrentDirectory; - wCurrentDirectory.appendAscii(currentDirectory); - szStartingDirectory = wCurrentDirectory.c_str(); - } - - - if (!CreateProcessW( - NULL, // No module name (use command line). - const_cast(wRemoteCmdLine.c_str()), // Command line. - NULL, // Process handle not inheritable. - NULL, // Thread handle not inheritable. - TRUE, // Set handle inheritance to TRUE. - bShowWindow ? 0 : CREATE_NO_WINDOW, // creation flags. - NULL, // Use parent's environment block. - szStartingDirectory, // Set starting directory. - &si, // Pointer to STARTUPINFO structure. - &pi)) // Pointer to PROCESS_INFORMATION structure. - { - // The following code block is commented out instead of being deleted - // because it's good to have at hand for a debugging session. - #if 0 - const size_t charsInMessageBuffer = 32768; // msdn about FormatMessage(): "The output buffer cannot be larger than 64K bytes." - wchar_t szMessageBuffer[charsInMessageBuffer] = L""; - FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, szMessageBuffer, charsInMessageBuffer, NULL); - GetCurrentDirectoryW(charsInMessageBuffer, szMessageBuffer); - #endif - - if (!bSilent) - { - ShowMessageBoxRcNotFound(wRemoteCmdLine.c_str(), szStartingDirectory); - } - - return eRcCallResult_notFound; - } - - s_rcProcessHandle = pi.hProcess; -#else - int fd = open(".", O_RDONLY); - char remoteCmdLineUtf8[MAX_PATH * 8]; - char workingDirectory[MAX_PATH * 8]; - ConvertUtf16ToUtf8(wRemoteCmdLine.c_str(), SettingsManagerHelpers::CCharBuffer(remoteCmdLineUtf8, MAX_PATH * 8)); - if (szWorkingDirectory) - { - ConvertUtf16ToUtf8(szWorkingDirectory, SettingsManagerHelpers::CCharBuffer(workingDirectory, MAX_PATH * 8)); - chdir(workingDirectory); - } - hChildStdOutRd = popen(remoteCmdLineUtf8, "r"); - fchdir(fd); - if (hChildStdOutRd == nullptr) - { - if (!bSilent) - { - ShowMessageBoxRcNotFound(wRemoteCmdLine.c_str(), szWorkingDirectory); - } - return eRcCallResult_notFound; - } -#endif - } - - bool bFailedToReadOutput = false; - - if (listener) - { -#if defined(AZ_PLATFORM_WINDOWS) - // Close the pipe that writes to the child process, since we don't actually have any input for it. - CloseHandle(hChildStdInWr); - - // Read all the output from the child process. - CloseHandle(hChildStdOutWr); -#endif - ResourceCompilerLineHandler lineHandler(listener); - LineStreamBuffer lineBuffer(&lineHandler, &ResourceCompilerLineHandler::HandleLine); - for (;; ) - { - char buffer[2048]; - DWORD bytesRead; -#if defined(AZ_PLATFORM_WINDOWS) - if (!ReadFile(hChildStdOutRd, buffer, sizeof(buffer), &bytesRead, NULL) || (bytesRead == 0)) -#else - if (fgets(buffer, sizeof(buffer), hChildStdOutRd) == nullptr || (bytesRead = strlen(buffer) == 0)) -#endif - { - break; - } - lineBuffer.HandleText(buffer, bytesRead); - } - - bFailedToReadOutput = lineBuffer.IsTruncated(); - } - -#if defined(AZ_PLATFORM_WINDOWS) - // Wait until child process exits. - WaitForSingleObject(pi.hProcess, INFINITE); -#else - DWORD exitCode = pclose(hChildStdOutRd); -#endif - -#if defined(AZ_PLATFORM_WINDOWS) - RcAutoLock lock(s_rcProcessHandleLock); - s_rcProcessHandle = 0; - - DWORD exitCode = eRcExitCode_Error; - if (bFailedToReadOutput || GetExitCodeProcess(pi.hProcess, &exitCode) == 0) - { - exitCode = eRcExitCode_Error; - } - - // Close process and thread handles. - CloseHandle(pi.hProcess); - CloseHandle(pi.hThread); -#endif - - return ConvertResourceCompilerExitCodeToResultCode(exitCode); -} - - -#endif //(CRY_ENABLE_RC_HELPER) diff --git a/Code/CryEngine/CryCommon/ResourceCompilerHelper.h b/Code/CryEngine/CryCommon/ResourceCompilerHelper.h deleted file mode 100644 index 913d72f642..0000000000 --- a/Code/CryEngine/CryCommon/ResourceCompilerHelper.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_RESOURCECOMPILERHELPER_H -#define CRYINCLUDE_CRYCOMMON_RESOURCECOMPILERHELPER_H - -#pragma once - -#if defined(CRY_ENABLE_RC_HELPER) - -#include "IResourceCompilerHelper.h" - -////////////////////////////////////////////////////////////////////////// -// Provides settings and functions to make calls to RC. -// calls RC locally. only works on windows, does not exist on other platforms -// note: You shouldn't be calling this directly -// instead, you should be calling it via the IResourceCompilerHelper interface. -// since it may be replaced with a custom RC for your platform or a remote invocation -class CResourceCompilerHelper - : public IResourceCompilerHelper -{ -public: - virtual ERcCallResult CallResourceCompiler( - const char* szFileName = 0, - const char* szAdditionalSettings = 0, - IResourceCompilerListener* listener = 0, - bool bMayShowWindow = true, - bool bSilent = false, - bool bNoUserDialog = false, - const wchar_t* szWorkingDirectory = 0, - const wchar_t* szRootPath = 0) override; -}; - -#endif // CRY_ENABLE_RC_HELPER - -#endif // CRYINCLUDE_CRYCOMMON_RESOURCECOMPILERHELPER_H diff --git a/Code/CryEngine/CryCommon/SettingsManagerHelpers.cpp b/Code/CryEngine/CryCommon/SettingsManagerHelpers.cpp deleted file mode 100644 index 9746b00574..0000000000 --- a/Code/CryEngine/CryCommon/SettingsManagerHelpers.cpp +++ /dev/null @@ -1,325 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "ProjectDefines.h" - -#if defined(CRY_ENABLE_RC_HELPER) - -#include "SettingsManagerHelpers.h" -#include "EngineSettingsManager.h" - -#include -#include -#include - -#include -#include - -#if defined(AZ_PLATFORM_WINDOWS) -#include -#include //ShellExecuteW() -#pragma comment(lib, "Shell32.lib") -#endif -#if AZ_TRAIT_OS_PLATFORM_APPLE -#include "AppleSpecific.h" -#endif - -bool SettingsManagerHelpers::Utf16ContainsAsciiOnly(const wchar_t* wstr) -{ - while (*wstr) - { - if (*wstr > 127 || *wstr < 0) - { - return false; - } - ++wstr; - } - return true; -} - - -void SettingsManagerHelpers::ConvertUtf16ToUtf8(const wchar_t* src, CCharBuffer dst) -{ - if (dst.getSizeInElements() <= 0) - { - return; - } - - if (src[0] == 0) - { - dst[0] = 0; - } - else - { - const std::codecvt& utf8Utf16Facet = std::use_facet>(std::locale()); - std::mbstate_t mb{}; - const wchar_t* from_next; - char* to_next; - std::codecvt_base::result result = utf8Utf16Facet.out(mb, src, src + wcslen(src), from_next, dst.getPtr(), dst.getPtr() + dst.getSizeInElements(), to_next); - if (result != std::codecvt_base::ok) - { - dst[0] = 0; - } - else - { - to_next = 0; - } - } -} - - -void SettingsManagerHelpers::ConvertUtf8ToUtf16(const char* src, CWCharBuffer dst) -{ - if (dst.getSizeInElements() <= 0) - { - return; - } - - if (src[0] == 0) - { - dst[0] = 0; - } - else - { - const std::codecvt& utf8Utf16Facet = std::use_facet>(std::locale()); - std::mbstate_t mb{}; - const char* from_next; - wchar_t* to_next; - std::codecvt_base::result result = utf8Utf16Facet.in(mb, src, src + strlen(src), from_next, dst.getPtr(), dst.getPtr() + dst.getSizeInElements(), to_next); - if (result != std::codecvt_base::ok) - { - dst[0] = 0; - } - else - { - to_next = 0; - } - } -} - - -void SettingsManagerHelpers::GetAsciiFilename(const wchar_t* wfilename, CCharBuffer buffer) -{ - if (buffer.getSizeInElements() <= 0) - { - return; - } - - if (wfilename[0] == 0) - { - buffer[0] = 0; - return; - } - - if (Utf16ContainsAsciiOnly(wfilename)) - { - ConvertUtf16ToUtf8(wfilename, buffer); - return; - } - -#if defined(AZ_PLATFORM_WINDOWS) - // The path is non-ASCII unicode, so let's resort to short filenames (they are always ASCII-only, I hope) - wchar_t shortW[MAX_PATH]; - const int bufferCharCount = sizeof(shortW) / sizeof(shortW[0]); - const int charCount = GetShortPathNameW(wfilename, shortW, bufferCharCount); - if (charCount <= 0 || charCount >= bufferCharCount) - { - buffer[0] = 0; - return; - } - - shortW[charCount] = 0; - if (!Utf16ContainsAsciiOnly(shortW)) - { - buffer[0] = 0; - return; - } - - ConvertUtf16ToUtf8(shortW, buffer); -#else - buffer[0] = 0; -#endif -} - - -////////////////////////////////////////////////////////////////////////// -CSettingsManagerTools::CSettingsManagerTools(const wchar_t* szModuleName) -{ - m_pSettingsManager = new CEngineSettingsManager(szModuleName); -} - -////////////////////////////////////////////////////////////////////////// -CSettingsManagerTools::~CSettingsManagerTools() -{ - delete m_pSettingsManager; -} - -////////////////////////////////////////////////////////////////////////// -bool CSettingsManagerTools::GetInstalledBuildPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) -{ - return m_pSettingsManager->GetInstalledBuildRootPathUtf16(index, name, path); -} - - -bool CSettingsManagerTools::GetInstalledBuildPathAscii(const int index, SettingsManagerHelpers::CCharBuffer name, SettingsManagerHelpers::CCharBuffer path) -{ - wchar_t wName[MAX_PATH]; - wchar_t wPath[MAX_PATH]; - if (GetInstalledBuildPathUtf16(index, SettingsManagerHelpers::CWCharBuffer(wName, sizeof(wName)), SettingsManagerHelpers::CWCharBuffer(wPath, sizeof(wPath)))) - { - SettingsManagerHelpers::GetAsciiFilename(wName, name); - SettingsManagerHelpers::GetAsciiFilename(wPath, path); - return true; - } - return false; -} - - - -////////////////////////////////////////////////////////////////////////// -static bool FileExists(const wchar_t* filename) -{ -#if defined(AZ_PLATFORM_WINDOWS) - const DWORD dwAttrib = GetFileAttributesW(filename); - return dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY); -#else - char utf8Filename[MAX_PATH]; - SettingsManagerHelpers::ConvertUtf16ToUtf8(filename, SettingsManagerHelpers::CCharBuffer(utf8Filename, sizeof(utf8Filename))); - struct stat buffer; - return (stat(utf8Filename, &buffer) == 0); -#endif -} - - -////////////////////////////////////////////////////////////////////////// -void CSettingsManagerTools::GetEditorExecutable(SettingsManagerHelpers::CWCharBuffer wbuffer) -{ - if (wbuffer.getSizeInElements() <= 0) - { - return; - } - - AZStd::string_view exePath; - AZ::ComponentApplicationBus::BroadcastResult(exePath, &AZ::ComponentApplicationRequests::GetExecutableFolder); - - SettingsManagerHelpers::CFixedString editorExe; - editorExe = wbuffer.getPtr(); - editorExe.appendAscii(exePath.data(), exePath.size()); - - if (editorExe.length() <= 0) - { - wbuffer[0] = 0; - return; - } - - bool bFound = false; - if (Is64bitWindows()) - { - const size_t len = editorExe.length(); - editorExe.appendAscii("/Editor.exe"); - bFound = FileExists(editorExe.c_str()); - if (!bFound) - { - editorExe.setLength(len); - } - } - - const size_t sizeToCopy = (editorExe.length() + 1) * sizeof(wbuffer[0]); - if (!bFound || sizeToCopy > wbuffer.getSizeInBytes()) - { - wbuffer[0] = 0; - } - else - { - memcpy(wbuffer.getPtr(), editorExe.c_str(), sizeToCopy); - } -} - - -////////////////////////////////////////////////////////////////////////// -bool CSettingsManagerTools::CallEditor(void** pEditorWindow, [[maybe_unused]] void* hParent, const char* pWindowName, const char* pFlag) -{ -#if !defined(AZ_PLATFORM_WINDOWS) - AZ_Assert(false, "CSettingsManagerTools::CallEditor is not supported on this platform!"); - return false; -#else - HWND window = ::FindWindowA(NULL, pWindowName); - if (window) - { - *pEditorWindow = window; - return true; - } - else - { - *pEditorWindow = 0; - - wchar_t buffer[512] = { L'\0' }; - GetEditorExecutable(SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))); - - SettingsManagerHelpers::CFixedString wFlags; - SettingsManagerHelpers::ConvertUtf8ToUtf16(pFlag, wFlags.getBuffer()); - wFlags.setLength(wcslen(wFlags.c_str())); - - if (buffer[0] != '\0') - { - INT_PTR hIns = (INT_PTR)ShellExecuteW(NULL, L"open", buffer, wFlags.c_str(), NULL, SW_SHOWNORMAL); - if (hIns > 32) - { - return true; - } - else - { - MessageBoxA(0, "Editor.exe was not found.\n\nPlease verify CryENGINE root path.", "Error", MB_ICONERROR | MB_OK); - } - } - } - - return false; -#endif -} - -////////////////////////////////////////////////////////////////////////// -// Modified version of -// http://msdn.microsoft.com/en-us/library/windows/desktop/ms684139(v=vs.85).aspx -bool CSettingsManagerTools::Is64bitWindows() -{ -#if defined(_WIN64) - // 64-bit programs run only on 64-bit Windows - return true; -#elif !defined(AZ_PLATFORM_WINDOWS) - return false; -#else - // 32-bit programs run on both 32-bit and 64-bit Windows - static bool bWin64 = false; - static bool bOnce = true; - if (bOnce) - { - typedef BOOL (WINAPI * LPFN_ISWOW64PROCESS)(HANDLE, PBOOL); - LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandleA("kernel32"), "IsWow64Process"); - if (fnIsWow64Process != NULL) - { - BOOL itIsWow64Process = FALSE; - if (fnIsWow64Process(GetCurrentProcess(), &itIsWow64Process)) - { - bWin64 = (itIsWow64Process == TRUE); - } - } - bOnce = false; - } - return bWin64; -#endif -} - -#endif // #if defined(CRY_ENABLE_RC_HELPER) - -// eof diff --git a/Code/CryEngine/CryCommon/SettingsManagerHelpers.h b/Code/CryEngine/CryCommon/SettingsManagerHelpers.h deleted file mode 100644 index e05d2b97aa..0000000000 --- a/Code/CryEngine/CryCommon/SettingsManagerHelpers.h +++ /dev/null @@ -1,491 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SETTINGSMANAGERHELPERS_H -#define CRYINCLUDE_CRYCOMMON_SETTINGSMANAGERHELPERS_H -#pragma once - -#include "ProjectDefines.h" -#include // memcpy -#include // std::min - - -namespace SettingsManagerHelpers -{ - namespace Utils - { - inline size_t strlen(const char* p) - { - return p ? ::strlen(p) : 0; - } - - inline size_t strcmp(const char* p0, const char* p1) - { - return ::strcmp(p0, p1); - } - - - inline size_t strlen(const wchar_t* p) - { - return p ? ::wcslen(p) : 0; - } - - inline size_t strcmp(const wchar_t* p0, const wchar_t* p1) - { - return ::wcscmp(p0, p1); - } - } - - // The function copies characters from src to dst one by one until any of - // the following conditions is met: - // 1) the end of the destination buffer (minus one character) is reached - // 2) the end of the source buffer is reached - // 3) zero character is found in the source buffer - // - // When any of 1), 2), 3) happens, the function writes the terminating zero - // character to the destination buffer and return. - // - // The function guarantees writing the terminating zero character to the - // destination buffer (if the buffer can fit at least one character). - // - // The function returns false when a null pointer is passed or when - // clamping happened (i.e. when the end of the destination buffer is - // reached but the source has some characters left). - inline bool strcpy_with_clamp(char* const dst, size_t const dst_size_in_bytes, const char* const src, size_t const src_size_in_bytes = (size_t)-1) - { - if (!dst || dst_size_in_bytes < sizeof(char)) - { - return false; - } - - if (!src || src_size_in_bytes < sizeof(char)) - { - dst[0] = 0; - return src != 0; // we return true for non-null src without characters - } - - const size_t src_n = src_size_in_bytes; - const size_t n = (std::min)(dst_size_in_bytes - 1, src_n); - - for (size_t i = 0; i < n; ++i) - { - dst[i] = src[i]; - if (!src[i]) - { - return true; - } - } - - dst[n] = 0; - return n >= src_n || src[n] == 0; - } - - - template - class CBuffer - { - public: - typedef T element_type; - - private: - element_type* m_ptr; - size_t m_sizeInBytes; - - public: - CBuffer(element_type* ptr, size_t sizeInBytes) - : m_ptr(ptr) - , m_sizeInBytes(ptr ? sizeInBytes : 0) - { - } - - const element_type* getPtr() const - { - return m_ptr; - } - - element_type* getPtr() - { - return m_ptr; - } - - size_t getSizeInElements() const - { - return m_sizeInBytes / sizeof(element_type); - } - - size_t getSizeInBytes() const - { - return m_sizeInBytes; - } - - const element_type& operator[](size_t pos) const - { - return m_ptr[pos]; - } - - element_type& operator[](size_t pos) - { - return m_ptr[pos]; - } - }; - - typedef CBuffer CCharBuffer; - typedef CBuffer CWCharBuffer; - - - template - class CFixedString - { - public: - typedef T char_type; - static const size_t npos = ~size_t(0); - private: - size_t m_count; // # chars (not counting trailing zero) - char_type m_buffer[CAPACITY + 1]; // '+ 1' is for trailing zero - - public: - CFixedString() - { - clear(); - } - - CFixedString(const char_type* p) - { - set(p); - } - - CFixedString& operator=(const char_type* p) - { - set(p); - return *this; - } - - CFixedString& operator=(const CFixedString& s) - { - if (&s != this) - { - set(s.m_buffer, s.m_count); - } - return *this; - } - - CBuffer getBuffer() - { - return CBuffer(m_buffer, (CAPACITY + 1) * sizeof(char_type)); - } - - char_type operator[](const size_t i) const - { - return m_buffer[i]; - } - - const char_type* c_str() const - { - return &m_buffer[0]; - } - - const size_t length() const - { - return m_count; - } - - void clear() - { - m_count = 0; - m_buffer[m_count] = 0; - } - - void setLength(size_t n) - { - m_count = (n <= CAPACITY) ? n : CAPACITY; - m_buffer[m_count] = 0; - } - - char_type* ptr() - { - return &m_buffer[0]; - } - - CFixedString substr(size_t pos = 0, size_t n = npos) const - { - CFixedString s; - if (pos < m_count && n > 0) - { - if (n > m_count || pos + n > m_count) - { - n = m_count - pos; - } - s.set(&m_buffer[pos], n); - } - return s; - } - - void set(const char_type* p, size_t n) - { - if (p == 0 || n <= 0) - { - m_count = 0; - } - else - { - m_count = (n > CAPACITY) ? CAPACITY : n; - // memmove() is used because p may point to m_buffer - memmove(m_buffer, p, m_count * sizeof(*p)); - } - m_buffer[m_count] = 0; - } - - void set(const char_type* p) - { - if (p && p[0]) - { - set(p, Utils::strlen(p)); - } - else - { - clear(); - } - } - - void append(const char_type* p, size_t n) - { - if (p && n > 0) - { - if (n > CAPACITY || m_count + n > CAPACITY) - { - // assert(0); - n = CAPACITY - m_count; - } - if (n > 0) - { - memcpy(&m_buffer[m_count], p, n * sizeof(*p)); - m_count += n; - m_buffer[m_count] = 0; - } - } - } - - void append(const char_type* p) - { - if (p && p[0]) - { - append(p, Utils::strlen(p)); - } - } - - void appendAscii(const char* p, size_t n) - { - if (p && n > 0) - { - if (n > CAPACITY || m_count + n > CAPACITY) - { - // assert(0); - n = CAPACITY - m_count; - } - if (n > 0) - { - for (size_t i = 0; i < n; ++i) - { - m_buffer[m_count + i] = p[i]; - } - m_count += n; - m_buffer[m_count] = 0; - } - } - } - - void appendAscii(const char* p) - { - if (p && p[0]) - { - appendAscii(p, Utils::strlen(p)); - } - } - - bool equals(const char_type* p) const - { - return (p == 0 || p[0] == 0) - ? (m_count == 0) - : (Utils::strcmp(m_buffer, p) == 0); - } - - void trim() - { - size_t begin = 0; - while (begin < m_count && (m_buffer[begin] == ' ' || m_buffer[begin] == '\r' || m_buffer[begin] == '\t' || m_buffer[begin] == '\n')) - { - ++begin; - } - - if (begin >= m_count) - { - clear(); - return; - } - - size_t end = m_count - 1; - while (end > begin && (m_buffer[begin] == ' ' || m_buffer[begin] == '\r' || m_buffer[begin] == '\t' || m_buffer[begin] == '\n')) - { - --end; - } - - m_count = end + 1; - m_buffer[m_count] = 0; - - if (begin > 0) - { - set(&m_buffer[begin], m_count - begin); - } - } - }; - - - struct SKeyValue - { - CFixedString key; - CFixedString value; - }; - - - template - class CKeyValueArray - { - private: - size_t count; - SKeyValue data[CAPACITY]; - - public: - CKeyValueArray() - : count(0) - { - } - - size_t size() const - { - return count; - } - - const SKeyValue& operator[](size_t i) const - { - return data[i]; - } - - void clear() - { - count = 0; - } - - const SKeyValue* find(const char* key) const - { - for (size_t i = 0; i < count; ++i) - { - if (data[i].key.equals(key)) - { - return &data[i]; - } - } - return 0; - } - - SKeyValue* find(const char* key) - { - for (size_t i = 0; i < count; ++i) - { - if (data[i].key.equals(key)) - { - return &data[i]; - } - } - return 0; - } - - SKeyValue* set(const char* key, const wchar_t* value) - { - SKeyValue* p = find(key); - if (!p) - { - if (count >= CAPACITY) - { - return 0; - } - p = &data[count++]; - p->key = key; - } - p->value = value; - return p; - } - }; - - -#if defined(CRY_ENABLE_RC_HELPER) - - bool Utf16ContainsAsciiOnly(const wchar_t* wstr); - - void ConvertUtf16ToUtf8(const wchar_t* src, CCharBuffer dst); - - void ConvertUtf8ToUtf16(const char* src, CWCharBuffer dst); - - template - void AddPathSeparator(CFixedString& wstr) - { - if (wstr.length() <= 0) - { - return; - } - - if (wstr[wstr.length() - 1] == L'/' || wstr[wstr.length() - 1] == L'\\') - { - return; - } - - wstr.appendAscii("/"); - } - - void GetAsciiFilename(const wchar_t* wfilename, CCharBuffer buffer); - -#endif // #if defined(CRY_ENABLE_RC_HELPER) -} // namespace SettingsManagerHelpers - - -#if defined(CRY_ENABLE_RC_HELPER) - -////////////////////////////////////////////////////////////////////////// -// Provides settings and functions to make calls to RC. -class CEngineSettingsManager; -class CSettingsManagerTools -{ -public: - CSettingsManagerTools(const wchar_t* szModuleName = 0); - ~CSettingsManagerTools(); - -private: - CEngineSettingsManager* m_pSettingsManager; - -public: - CEngineSettingsManager* GetEngineSettingsManager() - { - return m_pSettingsManager; - } - - bool GetInstalledBuildPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path); - bool GetInstalledBuildPathAscii(const int index, SettingsManagerHelpers::CCharBuffer name, SettingsManagerHelpers::CCharBuffer path); - - void GetEditorExecutable(SettingsManagerHelpers::CWCharBuffer wbuffer); - bool CallEditor(void** pEditorWindow, void* hParent, const char* pWndName, const char* pFlag); - - static bool Is64bitWindows(); -}; - -#endif // #if defined(CRY_ENABLE_RC_HELPER) - -#endif // CRYINCLUDE_CRYCOMMON_SETTINGSMANAGERHELPERS_H diff --git a/Code/CryEngine/CryCommon/crycommon_files.cmake b/Code/CryEngine/CryCommon/crycommon_files.cmake index ca95802fd9..77b51825f1 100644 --- a/Code/CryEngine/CryCommon/crycommon_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_files.cmake @@ -22,7 +22,6 @@ set(FILES IConsole.h IEntityRenderState.h IEntityRenderState_info.cpp - IFlares.h IFont.h IFunctorBase.h IFuncVariable.h @@ -40,12 +39,10 @@ set(FILES ILog.h ILZ4Decompressor.h IMaterial.h - IMaterialEffects.h IMemory.h IMeshBaking.h IMiniLog.h IMovieSystem.h - INotificationNetwork.h IPhysics.h IPhysicsDebugRenderer.h IPostEffectGroup.h @@ -55,12 +52,10 @@ set(FILES IRenderer.h IRenderMesh.h IResourceCollector.h - IResourceCompilerHelper.h IResourceManager.h ISerialize.h IShader.h IShader_info.h - ISoftCodeMgr.h ISplines.h IStatObj.h StatObjBus.h @@ -69,11 +64,8 @@ set(FILES IStreamEngineDefs.h ISurfaceType.h ISystem.h - ISystemScheduler.h ITextModeConsole.h ITexture.h - IThreadManager.h - IThreadTask.h ITimer.h IValidator.h IVideoRenderer.h @@ -108,7 +100,6 @@ set(FILES MaterialUtils.h MTPseudoRandom.cpp CryTypeInfo.cpp - IResourceCompilerHelper.cpp BaseTypes.h CompileTimeAssert.h CryThreadSafeWorkerContainer.h @@ -170,7 +161,6 @@ set(FILES PoolAllocator.h primitives.h primitives_info.h - ProfileLog.h ProjectDefines.h Range.h RenderContextConfig.h diff --git a/Code/CryEngine/CryCommon/physinterface.h b/Code/CryEngine/CryCommon/physinterface.h index 036f7e29ab..dd787d48b7 100644 --- a/Code/CryEngine/CryCommon/physinterface.h +++ b/Code/CryEngine/CryCommon/physinterface.h @@ -3244,7 +3244,6 @@ struct PhysicsVars int nBodiesLargeGroup; int bBreakOnValidation; int bLogActiveObjects; - int bMultiplayer; int bProfileEntities; int bProfileFunx; int bProfileGroups; diff --git a/Code/CryEngine/CryCommon/platform_impl.cpp b/Code/CryEngine/CryCommon/platform_impl.cpp index 142f07e5e7..885ea2984d 100644 --- a/Code/CryEngine/CryCommon/platform_impl.cpp +++ b/Code/CryEngine/CryCommon/platform_impl.cpp @@ -33,7 +33,7 @@ #define PLATFORM_IMPL_H_SECTION_VIRTUAL_ALLOCATORS 7 #endif -SC_API struct SSystemGlobalEnvironment* gEnv = nullptr; +struct SSystemGlobalEnvironment* gEnv = nullptr; // Traits #if defined(AZ_RESTRICTED_PLATFORM) @@ -147,7 +147,6 @@ void* GetDetachEnvironmentSymbol() #endif // !defined(SOFTCODE) bool g_bProfilerEnabled = false; -int g_iTraceAllocations = 0; ////////////////////////////////////////////////////////////////////////// // global random number generator used by cry_random functions diff --git a/Code/CryEngine/CrySystem/AutoDetectSpec.cpp b/Code/CryEngine/CrySystem/AutoDetectSpec.cpp index 31eee85d90..aa344684e3 100644 --- a/Code/CryEngine/CrySystem/AutoDetectSpec.cpp +++ b/Code/CryEngine/CrySystem/AutoDetectSpec.cpp @@ -1044,11 +1044,9 @@ void CSystem::AutoDetectSpec(const bool detectResolution) unsigned int numSysCores(1), numProcCores(1); Win32SysInspect::GetNumCPUCores(numSysCores, numProcCores); CryLogAlways("--- Number of available cores: %d (out of %d)", numProcCores, numSysCores); - const int numLogicalProcs = gEnv->pi.numLogicalProcessors; - CryLogAlways("--- Number of logical processors: %d", numLogicalProcs); // get CPU rating - const int cpuRating = numLogicalProcs >= 8 ? 3 : (numLogicalProcs >= 6 ? 2 : 1); + const int cpuRating = numProcCores >= 4 ? 3 : (numProcCores >= 3 ? 2 : 1); // get GPU info unsigned int gpuVendorId(0), gpuDeviceId(0), totVidMem(0); diff --git a/Code/CryEngine/CrySystem/CMakeLists.txt b/Code/CryEngine/CrySystem/CMakeLists.txt index 1a5593e5d8..3261526e8e 100644 --- a/Code/CryEngine/CrySystem/CMakeLists.txt +++ b/Code/CryEngine/CrySystem/CMakeLists.txt @@ -89,7 +89,6 @@ ly_add_target( Legacy::CrySystem.Static AZ::AzCore Legacy::CryCommon - Legacy::CryCommon.EngineSettings.Static ) ################################################################################ @@ -109,7 +108,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) PRIVATE AZ::AzTest Legacy::CryCommon - Legacy::CryCommon.EngineSettings.Static Legacy::CrySystem.Static AZ::AzFramework ) diff --git a/Code/CryEngine/CrySystem/ConsoleBatchFile.cpp b/Code/CryEngine/CrySystem/ConsoleBatchFile.cpp index 946edb9b64..b6eced4df3 100644 --- a/Code/CryEngine/CrySystem/ConsoleBatchFile.cpp +++ b/Code/CryEngine/CrySystem/ConsoleBatchFile.cpp @@ -87,14 +87,6 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) filename = PathUtil::ReplaceExtension(filename, "cfg"); } -#if defined(CVARS_WHITELIST) - bool ignoreWhitelist = true; - if (_stricmp(sFilename, "autoexec.cfg") == 0) - { - ignoreWhitelist = false; - } -#endif // defined(CVARS_WHITELIST) - ////////////////////////////////////////////////////////////////////////// CCryFile file; @@ -179,18 +171,9 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) continue; } -#if defined(CVARS_WHITELIST) - if (ignoreWhitelist || (gEnv->pSystem->GetCVarsWhiteList() && gEnv->pSystem->GetCVarsWhiteList()->IsWhiteListed(strLine, false))) -#endif // defined(CVARS_WHITELIST) { m_pConsole->ExecuteString(strLine); } -#if defined(CVARS_WHITELIST) - else if (gEnv->IsDedicated()) - { - gEnv->pSystem->GetILog()->LogError("Failed to execute command: '%s' as it is not whitelisted\n", strLine.c_str()); - } -#endif // defined(CVARS_WHITELIST) } // See above // ((CXConsole*)m_pConsole)->SetStatus(bConsoleStatus); diff --git a/Code/CryEngine/CrySystem/CrySystem_precompiled.h b/Code/CryEngine/CrySystem/CrySystem_precompiled.h index b446199b4e..1fab2d4ce1 100644 --- a/Code/CryEngine/CrySystem/CrySystem_precompiled.h +++ b/Code/CryEngine/CrySystem/CrySystem_precompiled.h @@ -117,7 +117,6 @@ struct IRenderer; struct ISystem; struct ITimer; struct IFFont; -struct IKeyboard; struct ICVar; struct IConsole; struct IProcess; diff --git a/Code/CryEngine/CrySystem/CryThreadUtil_pthread.h b/Code/CryEngine/CrySystem/CryThreadUtil_pthread.h deleted file mode 100644 index 4c920898f0..0000000000 --- a/Code/CryEngine/CrySystem/CryThreadUtil_pthread.h +++ /dev/null @@ -1,259 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -////////////////////////////////////////////////////////////////////////// -// NOTE: INTERNAL HEADER NOT FOR PUBLIC USE -// This header should only be include by SystemThreading.cpp only -// It provides an interface for PThread intrinsics -// It's only client should be CThreadManager which should manage all thread interaction -#if !defined(INCLUDED_FROM_SYSTEM_THREADING_CPP) -# error "CRYTEK INTERNAL HEADER. ONLY INCLUDE FROM SYSTEMTHRADING.CPP." -#endif -////////////////////////////////////////////////////////////////////////// - -#define DEFAULT_THREAD_STACK_SIZE_KB 0 -#define CRY_PTHREAD_THREAD_NAME_MAX 16 - -////////////////////////////////////////////////////////////////////////// -// THREAD CREATION AND MANAGMENT -////////////////////////////////////////////////////////////////////////// -namespace CryThreadUtil -{ - // Define type for platform specific thread handle - typedef pthread_t TThreadHandle; - - struct SThreadCreationDesc - { - // Define platform specific thread entry function functor type - typedef void* (* EntryFunc)(void*); - - const char* szThreadName; - EntryFunc fpEntryFunc; - void* pArgList; - uint32 nStackSizeInBytes; - }; - - ////////////////////////////////////////////////////////////////////////// - TThreadHandle CryGetCurrentThreadHandle() - { - return (TThreadHandle)pthread_self(); - } - - ////////////////////////////////////////////////////////////////////////// - // Note: Handle must be closed lated via CryCloseThreadHandle() - TThreadHandle CryDuplicateThreadHandle(const TThreadHandle& hThreadHandle) - { - // Do not do anything - // If you add a new platform which duplicates handles make sure to mirror the change in CryCloseThreadHandle(..) - return hThreadHandle; - } - - ////////////////////////////////////////////////////////////////////////// - void CryCloseThreadHandle(TThreadHandle& hThreadHandle) - { - pthread_detach(hThreadHandle); - } - - ////////////////////////////////////////////////////////////////////////// - threadID CryGetCurrentThreadId() - { - return threadID(pthread_self()); - } - - ////////////////////////////////////////////////////////////////////////// - threadID CryGetThreadId(TThreadHandle hThreadHandle) - { - return threadID(hThreadHandle); - } - - ////////////////////////////////////////////////////////////////////////// - // Note: On OSX the thread name can only be set by the thread itself. - void CrySetThreadName(TThreadHandle pThreadHandle, const char* sThreadName) - { - char threadName[CRY_PTHREAD_THREAD_NAME_MAX]; - if (!cry_strcpy(threadName, sThreadName)) - { - CryLog(" CrySetThreadName: input thread name '%s' truncated to '%s'", sThreadName, threadName); - } -#if AZ_TRAIT_OS_PLATFORM_APPLE - // On OSX the thread name can only be set by the thread itself. - assert(pthread_equal(pthread_self(), (pthread_t )pThreadHandle)); - - if (pthread_setname_np(threadName) != 0) -#else - if (pthread_setname_np(pThreadHandle, threadName) != 0) -#endif - { - switch (errno) - { - case ERANGE: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadName: Unable to rename thread \"%s\". Error Msg: \"Name to long. Exceeds %d bytes.\"", sThreadName, CRY_PTHREAD_THREAD_NAME_MAX); - break; - default: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadName: Unsupported error code: %i", errno); - break; - } - } - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadAffinityMask(TThreadHandle pThreadHandle, DWORD dwAffinityMask) - { -#if defined(AZ_PLATFORM_ANDROID) - // Not supported on ANDROID - // Alternative solution - // Watch out that android will clear the mask after a core has been switched off hence loosing the affinity mask setting! - // http://stackoverflow.com/questions/16319725/android-set-thread-affinity -#elif AZ_TRAIT_OS_PLATFORM_APPLE -# pragma message "Warning: CrySetThreadAffinityMask not implemented for platform" - // Implementation details can be found here - // https://developer.apple.com/library/mac/releasenotes/Performance/RN-AffinityAPI/ -#else - cpu_set_t cpu_mask; - CPU_ZERO(&cpu_mask); - for (int cpu = 0; cpu < sizeof(cpu_mask) * 8; ++cpu) - { - if (dwAffinityMask & (1 << cpu)) - { - CPU_SET(cpu, &cpu_mask); - } - } - - if (sched_setaffinity(0, sizeof(cpu_mask), &cpu_mask) != 0) - { - switch (errno) - { - case EFAULT: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadAffinityMask: Supplied memory address was invalid."); - break; - case EINVAL: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadAffinityMask: The affinity bit mask [%u] contains no processors that are currently physically on the system and permitted to the process .", dwAffinityMask); - break; - case EPERM: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadAffinityMask: The calling process does not have appropriate privileges. Mask [%u].", dwAffinityMask); - break; - case ESRCH: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadAffinityMask: The process whose ID is pid could not be found."); - break; - default: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadAffinityMask: Unsupported error code: %i", errno); - break; - } - } -#endif - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadPriority(TThreadHandle pThreadHandle, DWORD dwPriority) - { - int policy; - struct sched_param param; - - pthread_getschedparam(pThreadHandle, &policy, ¶m); - param.sched_priority = sched_get_priority_max(dwPriority); - pthread_setschedparam(pThreadHandle, policy, ¶m); - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadPriorityBoost(TThreadHandle pThreadHandle, bool bEnabled) - { - // Not supported - } - - ////////////////////////////////////////////////////////////////////////// - bool CryCreateThread(TThreadHandle* pThreadHandle, const SThreadCreationDesc& threadDesc) - { - uint32 nStackSize = threadDesc.nStackSizeInBytes != 0 ? threadDesc.nStackSizeInBytes : DEFAULT_THREAD_STACK_SIZE_KB * 1024; - - assert(pThreadHandle != reinterpret_cast(THREADID_NULL)); - pthread_attr_t threadAttr; - sched_param schedParam; - pthread_attr_init(&threadAttr); - pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_JOINABLE); - pthread_attr_setstacksize(&threadAttr, nStackSize); - - const int err = pthread_create( - pThreadHandle, - &threadAttr, - threadDesc.fpEntryFunc, - threadDesc.pArgList); - - // Handle error on thread creation - switch (err) - { - case 0: - // No error - break; - case EAGAIN: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to create thread \"%s\". Error Msg: \"Insufficient resources to create another thread, or a system-imposed limit on the number of threads was encountered.\"", threadDesc.szThreadName); - return false; - case EINVAL: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to create thread \"%s\". Error Msg: \"Invalid attribute setting for thread creation.\"", threadDesc.szThreadName); - return false; - case EPERM: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to create thread \"%s\". Error Msg: \"No permission to set the scheduling policy and parameters specified in attribute setting\"", threadDesc.szThreadName); - return false; - default: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to create thread \"%s\". Unknown error message. Error code %i", threadDesc.szThreadName, err); - break; - } - - // Print info to log - CryComment(": New thread \"%s\" | StackSize: %u(KB)", threadDesc.szThreadName, threadDesc.nStackSizeInBytes / 1024); - return true; - } - - ////////////////////////////////////////////////////////////////////////// - void CryThreadExitCall() - { - // Notes on: pthread_exit - // A thread that was create with pthread_create implicitly calls pthread_exit when the thread returns from its start routine (the function that was first called after a thread was created). - // pthread_exit(NULL); - } -} - - -////////////////////////////////////////////////////////////////////////// -// FLOATING POINT EXCEPTIONS -////////////////////////////////////////////////////////////////////////// -namespace CryThreadUtil -{ - /////////////////////////////////////////////////////////////////////////// - void EnableFloatExceptions(EFPE_Severity eFPESeverity) - { - // TODO: - // Not implemented - // for potential implementation see http://linux.die.net/man/3/feenableexcept - } - - ////////////////////////////////////////////////////////////////////////// - void EnableFloatExceptions(threadID nThreadId, EFPE_Severity eFPESeverity) - { - // TODO: - // Not implemented - // for potential implementation see http://linux.die.net/man/3/feenableexcept - } - - ////////////////////////////////////////////////////////////////////////// - uint GetFloatingPointExceptionMask() - { - // Not implemented - return ~0; - } - - ////////////////////////////////////////////////////////////////////////// - void SetFloatingPointExceptionMask(uint nMask) - { - // Not implemented - } -} diff --git a/Code/CryEngine/CrySystem/CryThreadUtil_win32_thread.h b/Code/CryEngine/CrySystem/CryThreadUtil_win32_thread.h deleted file mode 100644 index e5c7510feb..0000000000 --- a/Code/CryEngine/CrySystem/CryThreadUtil_win32_thread.h +++ /dev/null @@ -1,432 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -////////////////////////////////////////////////////////////////////////// -// NOTE: INTERNAL HEADER NOT FOR PUBLIC USE -// This header should only be include by SystemThreading.cpp only -// It provides an interface for WinApi intrinsics -// It's only client should be CThreadManager which should manage all thread interaction - -#pragma once - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define CRYTHREADUTIL_WIN32_THREAD_H_SECTION_1 1 -#define CRYTHREADUTIL_WIN32_THREAD_H_SECTION_2 2 -#endif - -#if !defined(INCLUDED_FROM_SYSTEM_THREADING_CPP) -# error "CRYTEK INTERNAL HEADER. ONLY INCLUDE FROM SYSTEMTHRADING.CPP." -#endif -////////////////////////////////////////////////////////////////////////// - -#define DEFAULT_THREAD_STACK_SIZE_KB 0 - -// Returns the last Win32 error, in string format. Returns an empty string if there is no error. -static string GetLastErrorAsString() -{ - // Get the error message, if any. - DWORD errorMessageID = GetLastError(); - if (errorMessageID == 0) - { - return ""; - } - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION CRYTHREADUTIL_WIN32_THREAD_H_SECTION_1 -#include AZ_RESTRICTED_FILE(CryThreadUtil_win32_thread_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - LPSTR messageBuffer = nullptr; - size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), messageBuffer, 0, NULL); - - string message(messageBuffer, size); - - // Free the buffer. - LocalFree(messageBuffer); - - return message; -#endif -} - -////////////////////////////////////////////////////////////////////////// -// THREAD CREATION AND MANAGMENT -////////////////////////////////////////////////////////////////////////// -namespace CryThreadUtil -{ - // Define type for platform specific thread handle - typedef THREAD_HANDLE TThreadHandle; - - struct SThreadCreationDesc - { - // Define platform specific thread entry function functor type - typedef unsigned int(_stdcall * EntryFunc)(void*); - - const char* szThreadName; - EntryFunc fpEntryFunc; - void* pArgList; - uint32 nStackSizeInBytes; - }; - - ////////////////////////////////////////////////////////////////////////// - TThreadHandle CryGetCurrentThreadHandle() - { - return GetCurrentThread(); // most likely returns pseudo handle (0xfffffffe) - } - - ////////////////////////////////////////////////////////////////////////// - // Note: Handle must be closed lated via CryCloseThreadHandle() - TThreadHandle CryDuplicateThreadHandle(const TThreadHandle& hThreadHandle) - { - // NOTES: - // GetCurrentThread() may return a psydo handle to the current thread - // to avoid going into the slower kernel mode. - // Hence the handle is useless when being used from an other thread. - // - GetCurrentThread() -> 0xfffffffe - // - GetCurrentProcess() -> 0xffffffff - - HANDLE hRealHandle = 0; - DuplicateHandle(GetCurrentProcess(), // Source Process Handle. - hThreadHandle, // Source Handle to dup. - GetCurrentProcess(), // Target Process Handle. - &hRealHandle, // Target Handle pointer. - 0, // Options flag. - TRUE, // Inheritable flag - DUPLICATE_SAME_ACCESS); // Options - - return (TThreadHandle)hRealHandle; - } - - ////////////////////////////////////////////////////////////////////////// - void CryCloseThreadHandle(TThreadHandle& hThreadHandle) - { - if (hThreadHandle) - { - CloseHandle(hThreadHandle); - } - } - - ////////////////////////////////////////////////////////////////////////// - threadID CryGetCurrentThreadId() - { - return GetCurrentThreadId(); - } - - ////////////////////////////////////////////////////////////////////////// - threadID CryGetThreadId(TThreadHandle hThreadHandle) - { - return GetThreadId(hThreadHandle); - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadName(TThreadHandle pThreadHandle, const char* sThreadName) - { - const DWORD MS_VC_EXCEPTION = 0x406D1388; - - struct SThreadNameDesc - { - DWORD dwType; // Must be 0x1000. - LPCSTR szName; // Pointer to name (in user addr space). - DWORD dwThreadID; // Thread ID (-1=caller thread). - DWORD dwFlags; // Reserved for future use, must be zero. - }; - - SThreadNameDesc info; - info.dwType = 0x1000; - info.szName = sThreadName; - info.dwThreadID = GetThreadId(pThreadHandle); - info.dwFlags = 0; -AZ_PUSH_DISABLE_WARNING(6312 6322, "-Wunknown-warning-option") - // warning C6312: Possible infinite loop: use of the constant EXCEPTION_CONTINUE_EXECUTION in the exception-filter expression of a try-except - // warning C6322: empty _except block - __try - { - // Raise exception to set thread name for attached debugger - RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(DWORD), (ULONG_PTR*)&info); - } - __except (GetExceptionCode() == MS_VC_EXCEPTION ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER) - { - } -AZ_POP_DISABLE_WARNING - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadAffinityMask(TThreadHandle pThreadHandle, DWORD dwAffinityMask) - { - SetThreadAffinityMask(pThreadHandle, dwAffinityMask); - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadPriority(TThreadHandle pThreadHandle, DWORD dwPriority) - { - if (!SetThreadPriority(pThreadHandle, dwPriority)) - { - string errMsg = GetLastErrorAsString(); - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to set thread priority. System Error Msg: \"%s\"", errMsg.c_str()); - return; - } - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadPriorityBoost(TThreadHandle pThreadHandle, bool bEnabled) - { - SetThreadPriorityBoost(pThreadHandle, !bEnabled); - } - - ////////////////////////////////////////////////////////////////////////// - bool CryCreateThread(TThreadHandle* pThreadHandle, const SThreadCreationDesc& threadDesc) - { - const uint32 nStackSize = threadDesc.nStackSizeInBytes != 0 ? threadDesc.nStackSizeInBytes : DEFAULT_THREAD_STACK_SIZE_KB * 1024; - - // Create thread - unsigned int threadId = 0; -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION CRYTHREADUTIL_WIN32_THREAD_H_SECTION_2 -#include AZ_RESTRICTED_FILE(CryThreadUtil_win32_thread_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - *pThreadHandle = (void*)_beginthreadex(NULL, nStackSize, threadDesc.fpEntryFunc, threadDesc.pArgList, CREATE_SUSPENDED, &threadId); -#endif - - if (!(*pThreadHandle)) - { - string errMsg = GetLastErrorAsString(); - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to create thread \"%s\". System Error Msg: \"%s\"", threadDesc.szThreadName, errMsg.c_str()); - return false; - } - - // Start thread - ResumeThread(*pThreadHandle); - - // Print info to log - CryComment(": New thread \"%s\" | StackSize: %u(KB)", threadDesc.szThreadName, threadDesc.nStackSizeInBytes / 1024); - return true; - } - - ////////////////////////////////////////////////////////////////////////// - void CryThreadExitCall() - { - // Note on: ExitThread() (from MSDN) - // ExitThread is the preferred method of exiting a thread in C code. - // However, in C++ code, the thread is exited before any destructor can be called or any other automatic cleanup can be performed. - // Therefore, in C++ code, you should return from your thread function. - } -} - -////////////////////////////////////////////////////////////////////////// -// FLOATING POINT EXCEPTIONS -////////////////////////////////////////////////////////////////////////// -namespace CryThreadUtil -{ - /////////////////////////////////////////////////////////////////////////// - void EnableFloatExceptions([[maybe_unused]] EFPE_Severity eFPESeverity) - { -AZ_PUSH_DISABLE_WARNING(4996, "-Wunknown-warning-option") - - // Optimization - // Enable DAZ/FZ - // Denormals Are Zeros - // Flush-to-Zero - _controlfp(_DN_FLUSH, _MCW_DN); - _mm_setcsr(_mm_getcsr() | _MM_FLUSH_ZERO_ON); - -#ifndef _RELEASE - if (eFPESeverity == eFPE_None) - { - // mask all floating exceptions off. - _controlfp(_MCW_EM, _MCW_EM); - _mm_setcsr(_mm_getcsr() | _MM_MASK_MASK); - } - else - { - // Clear pending exceptions - _fpreset(); - - if (eFPESeverity == eFPE_Basic) - { - // Enable: - // - _EM_ZERODIVIDE - // - _EM_INVALID - // - // Disable: - // - _EM_DENORMAL - // - _EM_OVERFLOW - // - _EM_UNDERFLOW - // - _EM_INEXACT - - _controlfp(_EM_INEXACT | _EM_DENORMAL | _EM_UNDERFLOW | _EM_OVERFLOW, _MCW_EM); - _mm_setcsr((_mm_getcsr() & ~_MM_MASK_MASK) | (_MM_MASK_DENORM | _MM_MASK_INEXACT | _MM_MASK_UNDERFLOW | _MM_MASK_OVERFLOW)); - - //_mm_setcsr(_mm_getcsr() & ~0x280); - } - - if (eFPESeverity == eFPE_All) - { - // Enable: - // - _EM_ZERODIVIDE - // - _EM_INVALID - // - _EM_UNDERFLOW - // - _EM_OVERFLOW - // - // Disable: - // - _EM_INEXACT - // - _EM_DENORMAL - - _controlfp(_EM_INEXACT | _EM_DENORMAL, _MCW_EM); - _mm_setcsr((_mm_getcsr() & ~_MM_MASK_MASK) | (_MM_MASK_INEXACT | _MM_MASK_DENORM)); - } - } -#endif // _RELEASE - -AZ_POP_DISABLE_WARNING -} - - ////////////////////////////////////////////////////////////////////////// - void EnableFloatExceptions(threadID nThreadId, EFPE_Severity eFPESeverity) - { - if (eFPESeverity >= eFPE_LastEntry) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Floating Point Exception (FPE) severity is out of range. (%i)", eFPESeverity); - } - - // Check if the thread ID matches the current thread - if (nThreadId == 0 || nThreadId == CryGetCurrentThreadId()) - { - EnableFloatExceptions(eFPESeverity); - return; - } - - HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, true, nThreadId); - - if (hThread == 0) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Unable to open thread. %p", hThread); - return; - } - - SuspendThread(hThread); - - CONTEXT ctx; - memset(&ctx, 0, sizeof(ctx)); - ctx.ContextFlags = CONTEXT_ALL; - if (GetThreadContext(hThread, &ctx) == 0) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Unable to get thread context"); - ResumeThread(hThread); - CloseHandle(hThread); - return; - } - -#ifdef PLATFORM_64BIT - ////////////////////////////////////////////////////////////////////////// - // Note: - // DO NOT USE ctx.FltSave.MxCsr ... SetThreadContext() will copy the value of ctx.MxCsr into it - ////////////////////////////////////////////////////////////////////////// - DWORD& floatMxCsr = ctx.MxCsr; // Hold FPE Mask and Status for MMX (SSE) floating point registers - WORD& floatControlWord = ctx.FltSave.ControlWord; // Hold FPE Mask for floating point registers - #ifndef _RELEASE - WORD& floatStatuslWord = ctx.FltSave.StatusWord; // Holds FPE Status for floating point registers - #endif -#else - DWORD& floatMxCsr = *(DWORD*)(&ctx.ExtendedRegisters[24]); // Hold FPE Mask and Status for MMX (SSE) floating point registers - DWORD& floatControlWord = ctx.FloatSave.ControlWord; // Hold FPE Mask for floating point registers - DWORD& floatStatuslWord = ctx.FloatSave.StatusWord; // Holds FPE Status for floating point registers -#endif - - // Flush-To-Zero Mode - // Two conditions must be met for FTZ processing to occur: - // - The FTZ bit (bit 15) in the MXCSR register must be masked (value = 1). - // - The underflow exception (bit 11) needs to be masked (value = 1). - - // Set flush mode to zero mode - floatControlWord = (floatControlWord & ~_MCW_DN) | _DN_FLUSH; - floatMxCsr = (floatMxCsr & ~_MM_FLUSH_ZERO_MASK) | (_MM_FLUSH_ZERO_ON); - -#ifndef _RELEASE - - // Reset FPE bits - floatControlWord = floatControlWord | _MCW_EM; - floatMxCsr = floatMxCsr | _MM_MASK_MASK; - - // Clear pending exceptions - floatStatuslWord = floatStatuslWord & ~(_SW_INEXACT | _SW_UNDERFLOW | _SW_OVERFLOW | _SW_ZERODIVIDE | _SW_INVALID | _SW_DENORMAL); - floatMxCsr = floatMxCsr & ~(_MM_EXCEPT_INEXACT | _MM_EXCEPT_UNDERFLOW | _MM_EXCEPT_OVERFLOW | _MM_EXCEPT_DIV_ZERO | _MM_EXCEPT_INVALID | _MM_EXCEPT_DENORM); - - if (eFPESeverity == eFPE_Basic) - { - // Enable: - // - _EM_ZERODIVIDE - // - _EM_INVALID - // - // Disable: - // - _EM_DENORMAL - // - _EM_OVERFLOW - // - _EM_UNDERFLOW - // - _EM_INEXACT - - floatControlWord = (floatControlWord & ~_MCW_EM) | (_EM_DENORMAL | _EM_INEXACT | EM_UNDERFLOW | _EM_OVERFLOW); - floatMxCsr = (floatMxCsr & ~_MM_MASK_MASK) | (_MM_MASK_DENORM | _MM_MASK_INEXACT | _MM_MASK_UNDERFLOW | _MM_MASK_OVERFLOW); - } - - if (eFPESeverity == eFPE_All) - { - // Enable: - // - _EM_ZERODIVIDE - // - _EM_INVALID - // - _EM_UNDERFLOW - // - _EM_OVERFLOW - // - // Disable: - // - _EM_INEXACT - // - _EM_DENORMAL - - floatControlWord = (floatControlWord & ~_MCW_EM) | (_EM_INEXACT | _EM_DENORMAL); - floatMxCsr = (floatMxCsr & ~_MM_MASK_MASK) | (_MM_MASK_INEXACT | _MM_MASK_DENORM); - } -#endif - - ctx.ContextFlags = CONTEXT_ALL; - if (SetThreadContext(hThread, &ctx) == 0) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Error setting ThreadContext for ThreadID: %u", nThreadId); - ResumeThread(hThread); - CloseHandle(hThread); - return; - } - - ResumeThread(hThread); - CloseHandle(hThread); - } - - ////////////////////////////////////////////////////////////////////////// - uint GetFloatingPointExceptionMask() - { - uint nMask = 0; - _clearfp(); - _controlfp_s(&nMask, 0, 0); - return nMask; - } - - ////////////////////////////////////////////////////////////////////////// - void SetFloatingPointExceptionMask(uint nMask) - { - uint temp = 0; - _clearfp(); - const unsigned int kAllowedBits = _MCW_DN | _MCW_EM | _MCW_RC; - _controlfp_s(&temp, nMask, kAllowedBits); - } -} diff --git a/Code/CryEngine/CrySystem/DebugCallStack.cpp b/Code/CryEngine/CrySystem/DebugCallStack.cpp deleted file mode 100644 index f33e793db6..0000000000 --- a/Code/CryEngine/CrySystem/DebugCallStack.cpp +++ /dev/null @@ -1,926 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "DebugCallStack.h" - -#if defined(WIN32) || defined(WIN64) - -#include -#include -#include -#include "System.h" - -#include -#include - -#include "resource.h" -__pragma(comment(lib, "version.lib")) - -//! Needs one external of DLL handle. -extern HMODULE gDLLHandle; - -#include - -#define MAX_PATH_LENGTH 1024 -#define MAX_SYMBOL_LENGTH 512 - -static HWND hwndException = 0; -static bool g_bUserDialog = true; // true=on crash show dialog box, false=supress user interaction - -static int PrintException(EXCEPTION_POINTERS* pex); - -static bool IsFloatingPointException(EXCEPTION_POINTERS* pex); - -extern LONG WINAPI CryEngineExceptionFilterWER(struct _EXCEPTION_POINTERS* pExceptionPointers); -extern LONG WINAPI CryEngineExceptionFilterMiniDump(struct _EXCEPTION_POINTERS* pExceptionPointers, const char* szDumpPath, MINIDUMP_TYPE mdumpValue); - -//============================================================================= -CONTEXT CaptureCurrentContext() -{ - CONTEXT context; - memset(&context, 0, sizeof(context)); - context.ContextFlags = CONTEXT_FULL; - RtlCaptureContext(&context); - - return context; -} - -LONG __stdcall CryUnhandledExceptionHandler(EXCEPTION_POINTERS* pex) -{ - return DebugCallStack::instance()->handleException(pex); -} - - -BOOL CALLBACK EnumModules( - PCSTR ModuleName, - DWORD64 BaseOfDll, - PVOID UserContext) -{ - DebugCallStack::TModules& modules = *static_cast(UserContext); - modules[(void*)BaseOfDll] = ModuleName; - - return TRUE; -} -//============================================================================= -// Class Statics -//============================================================================= - -// Return single instance of class. -IDebugCallStack* IDebugCallStack::instance() -{ - static DebugCallStack sInstance; - return &sInstance; -} - -//------------------------------------------------------------------------------------------------------------------------ -// Sets up the symbols for functions in the debug file. -//------------------------------------------------------------------------------------------------------------------------ -DebugCallStack::DebugCallStack() - : prevExceptionHandler(0) - , m_pSystem(0) - , m_nSkipNumFunctions(0) - , m_bCrash(false) - , m_szBugMessage(NULL) -{ -} - -DebugCallStack::~DebugCallStack() -{ -} - -void DebugCallStack::RemoveOldFiles() -{ - RemoveFile("error.log"); - RemoveFile("error.bmp"); - RemoveFile("error.dmp"); -} - -void DebugCallStack::RemoveFile(const char* szFileName) -{ - FILE* pFile = nullptr; - azfopen(&pFile, szFileName, "r"); - const bool bFileExists = (pFile != NULL); - - if (bFileExists) - { - fclose(pFile); - - WriteLineToLog("Removing file \"%s\"...", szFileName); - if (remove(szFileName) == 0) - { - WriteLineToLog("File successfully removed."); - } - else - { - WriteLineToLog("Couldn't remove file!"); - } - } -} - -void DebugCallStack::installErrorHandler(ISystem* pSystem) -{ - m_pSystem = pSystem; - prevExceptionHandler = (void*)SetUnhandledExceptionFilter(CryUnhandledExceptionHandler); -} - -////////////////////////////////////////////////////////////////////////// -void DebugCallStack::SetUserDialogEnable(const bool bUserDialogEnable) -{ - g_bUserDialog = bUserDialogEnable; -} - - -DWORD g_idDebugThreads[10]; -const char* g_nameDebugThreads[10]; -int g_nDebugThreads = 0; -volatile int g_lockThreadDumpList = 0; - -void MarkThisThreadForDebugging(const char* name) -{ - EBUS_EVENT(AZ::Debug::EventTraceDrillerSetupBus, SetThreadName, AZStd::this_thread::get_id(), name); - - WriteLock lock(g_lockThreadDumpList); - DWORD id = GetCurrentThreadId(); - if (g_nDebugThreads == sizeof(g_idDebugThreads) / sizeof(g_idDebugThreads[0])) - { - return; - } - for (int i = 0; i < g_nDebugThreads; i++) - { - if (g_idDebugThreads[i] == id) - { - return; - } - } - g_nameDebugThreads[g_nDebugThreads] = name; - g_idDebugThreads[g_nDebugThreads++] = id; - ((CSystem*)gEnv->pSystem)->EnableFloatExceptions(g_cvars.sys_float_exceptions); -} - -void UnmarkThisThreadFromDebugging() -{ - WriteLock lock(g_lockThreadDumpList); - DWORD id = GetCurrentThreadId(); - for (int i = g_nDebugThreads - 1; i >= 0; i--) - { - if (g_idDebugThreads[i] == id) - { - memmove(g_idDebugThreads + i, g_idDebugThreads + i + 1, (g_nDebugThreads - 1 - i) * sizeof(g_idDebugThreads[0])); - memmove(g_nameDebugThreads + i, g_nameDebugThreads + i + 1, (g_nDebugThreads - 1 - i) * sizeof(g_nameDebugThreads[0])); - --g_nDebugThreads; - } - } -} - -extern int prev_sys_float_exceptions; -void UpdateFPExceptionsMaskForThreads() -{ - int mask = -iszero(g_cvars.sys_float_exceptions); - CONTEXT ctx; - for (int i = 0; i < g_nDebugThreads; i++) - { - if (g_idDebugThreads[i] != GetCurrentThreadId()) - { - HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, TRUE, g_idDebugThreads[i]); - ctx.ContextFlags = CONTEXT_ALL; - SuspendThread(hThread); - GetThreadContext(hThread, &ctx); -#ifndef WIN64 - (ctx.FloatSave.ControlWord |= 7) &= ~5 | mask; - (*(WORD*)(ctx.ExtendedRegisters + 24) |= 0x280) &= ~0x280 | mask; -#else - (ctx.FltSave.ControlWord |= 7) &= ~5 | mask; - (ctx.FltSave.MxCsr |= 0x280) &= ~0x280 | mask; -#endif - SetThreadContext(hThread, &ctx); - ResumeThread(hThread); - } - } -} - -////////////////////////////////////////////////////////////////////////// -int DebugCallStack::handleException(EXCEPTION_POINTERS* exception_pointer) -{ - if (gEnv == NULL) - { - return EXCEPTION_EXECUTE_HANDLER; - } - - ResetFPU(exception_pointer); - - prev_sys_float_exceptions = 0; - const int cached_sys_float_exceptions = g_cvars.sys_float_exceptions; - - ((CSystem*)gEnv->pSystem)->EnableFloatExceptions(0); - - if (g_cvars.sys_WER) - { - gEnv->pLog->FlushAndClose(); - return CryEngineExceptionFilterWER(exception_pointer); - } - - if (g_cvars.sys_no_crash_dialog) - { - DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX); - SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX); - } - - m_bCrash = true; - - if (g_cvars.sys_no_crash_dialog) - { - DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX); - SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX); - } - - static bool firstTime = true; - - if (g_cvars.sys_dump_aux_threads) - { - for (int i = 0; i < g_nDebugThreads; i++) - { - if (g_idDebugThreads[i] != GetCurrentThreadId()) - { - SuspendThread(OpenThread(THREAD_ALL_ACCESS, TRUE, g_idDebugThreads[i])); - } - } - } - - // uninstall our exception handler. - SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)prevExceptionHandler); - - if (!firstTime) - { - WriteLineToLog("Critical Exception! Called Multiple Times!"); - gEnv->pLog->FlushAndClose(); - // Exception called more then once. - return EXCEPTION_EXECUTE_HANDLER; - } - - // Print exception info: - { - char excCode[80]; - char excAddr[80]; - WriteLineToLog(""); - sprintf_s(excAddr, "0x%04X:0x%p", exception_pointer->ContextRecord->SegCs, exception_pointer->ExceptionRecord->ExceptionAddress); - sprintf_s(excCode, "0x%08X", exception_pointer->ExceptionRecord->ExceptionCode); - WriteLineToLog("Exception: %s, at Address: %s", excCode, excAddr); - - { - IMemoryManager::SProcessMemInfo memInfo; - if (gEnv->pSystem->GetIMemoryManager()->GetProcessMemInfo(memInfo)) - { - uint32 nMemUsage = (uint32)(memInfo.PagefileUsage / (1024 * 1024)); - WriteLineToLog("Virtual memory usage: %dMb", nMemUsage); - } - gEnv->szDebugStatus[SSystemGlobalEnvironment::MAX_DEBUG_STRING_LENGTH - 1] = '\0'; - WriteLineToLog("Debug Status: %s", gEnv->szDebugStatus); - } - } - - firstTime = false; - - const int ret = SubmitBug(exception_pointer); - - if (ret != IDB_IGNORE) - { - CryEngineExceptionFilterWER(exception_pointer); - } - - gEnv->pLog->FlushAndClose(); - - if (exception_pointer->ExceptionRecord->ExceptionFlags & EXCEPTION_NONCONTINUABLE) - { - // This is non continuable exception. abort application now. - exit(exception_pointer->ExceptionRecord->ExceptionCode); - } - - //typedef long (__stdcall *ExceptionFunc)(EXCEPTION_POINTERS*); - //ExceptionFunc prevFunc = (ExceptionFunc)prevExceptionHandler; - //return prevFunc( (EXCEPTION_POINTERS*)exception_pointer ); - if (ret == IDB_EXIT) - { - // Immediate exit. - // on windows, exit() and _exit() do all sorts of things, unfortuantely - // TerminateProcess is the only way to die. - TerminateProcess(GetCurrentProcess(), exception_pointer->ExceptionRecord->ExceptionCode); // we crashed, so don't return a zero exit code! - // on linux based systems, _exit will not call ATEXIT and other things, which makes it more suitable for termination in an emergency such - // as an unhandled exception. - // however, this function is a windows exception handler. - } - else if (ret == IDB_IGNORE) - { -#ifndef WIN64 - exception_pointer->ContextRecord->FloatSave.StatusWord &= ~31; - exception_pointer->ContextRecord->FloatSave.ControlWord |= 7; - (*(WORD*)(exception_pointer->ContextRecord->ExtendedRegisters + 24) &= 31) |= 0x1F80; -#else - exception_pointer->ContextRecord->FltSave.StatusWord &= ~31; - exception_pointer->ContextRecord->FltSave.ControlWord |= 7; - (exception_pointer->ContextRecord->FltSave.MxCsr &= 31) |= 0x1F80; -#endif - firstTime = true; - prevExceptionHandler = (void*)SetUnhandledExceptionFilter(CryUnhandledExceptionHandler); - g_cvars.sys_float_exceptions = cached_sys_float_exceptions; - ((CSystem*)gEnv->pSystem)->EnableFloatExceptions(g_cvars.sys_float_exceptions); - return EXCEPTION_CONTINUE_EXECUTION; - } - - // Continue; - return EXCEPTION_EXECUTE_HANDLER; -} - -void DebugCallStack::ReportBug(const char* szErrorMessage) -{ - WriteLineToLog("Reporting bug: %s", szErrorMessage); - - m_szBugMessage = szErrorMessage; - m_context = CaptureCurrentContext(); - SubmitBug(NULL); - m_szBugMessage = NULL; -} - -void DebugCallStack::dumpCallStack(std::vector& funcs) -{ - WriteLineToLog("============================================================================="); - int len = (int)funcs.size(); - for (int i = 0; i < len; i++) - { - const char* str = funcs[i].c_str(); - WriteLineToLog("%2d) %s", len - i, str); - } - WriteLineToLog("============================================================================="); -} - - -////////////////////////////////////////////////////////////////////////// -void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) -{ - string path(""); - if ((gEnv) && (gEnv->pFileIO)) - { - const char* logAlias = gEnv->pFileIO->GetAlias("@log@"); - if (!logAlias) - { - logAlias = gEnv->pFileIO->GetAlias("@root@"); - } - if (logAlias) - { - path = logAlias; - path += "/"; - } - } - - string fileName = path; - fileName += "error.log"; - - struct stat fileInfo; - string timeStamp; - string backupPath; - if (gEnv->IsDedicated()) - { - backupPath = PathUtil::ToUnixPath(PathUtil::AddSlash(path + "DumpBackups")); - gEnv->pFileIO->CreatePath(backupPath.c_str()); - - if (stat(fileName.c_str(), &fileInfo) == 0) - { - // Backup log - tm creationTime; - localtime_s(&creationTime, &fileInfo.st_mtime); - char tempBuffer[32]; - strftime(tempBuffer, sizeof(tempBuffer), "%d %b %Y (%H %M %S)", &creationTime); - timeStamp = tempBuffer; - - string backupFileName = backupPath + timeStamp + " error.log"; - CopyFile(fileName.c_str(), backupFileName.c_str(), true); - } - } - - FILE* f = nullptr; - azfopen(&f, fileName.c_str(), "wt"); - - CDebugAllowFileAccess ignoreInvalidFileAccess; - - static char errorString[s_iCallStackSize]; - errorString[0] = 0; - - // Time and Version. - char versionbuf[1024]; - azstrcpy(versionbuf, AZ_ARRAY_SIZE(versionbuf), ""); - PutVersion(versionbuf, AZ_ARRAY_SIZE(versionbuf)); - cry_strcat(errorString, versionbuf); - cry_strcat(errorString, "\n"); - - char excCode[MAX_WARNING_LENGTH]; - char excAddr[80]; - char desc[1024]; - char excDesc[MAX_WARNING_LENGTH]; - - // make sure the mouse cursor is visible - ShowCursor(TRUE); - - const char* excName; - if (m_bIsFatalError || !pex) - { - const char* const szMessage = m_bIsFatalError ? s_szFatalErrorCode : m_szBugMessage; - excName = szMessage; - cry_strcpy(excCode, szMessage); - cry_strcpy(excAddr, ""); - cry_strcpy(desc, ""); - cry_strcpy(m_excModule, ""); - cry_strcpy(excDesc, szMessage); - } - else - { - sprintf_s(excAddr, "0x%04X:0x%p", pex->ContextRecord->SegCs, pex->ExceptionRecord->ExceptionAddress); - sprintf_s(excCode, "0x%08X", pex->ExceptionRecord->ExceptionCode); - excName = TranslateExceptionCode(pex->ExceptionRecord->ExceptionCode); - cry_strcpy(desc, ""); - sprintf_s(excDesc, "%s\r\n%s", excName, desc); - - - if (pex->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) - { - if (pex->ExceptionRecord->NumberParameters > 1) - { - ULONG_PTR iswrite = pex->ExceptionRecord->ExceptionInformation[0]; - DWORD64 accessAddr = pex->ExceptionRecord->ExceptionInformation[1]; - if (iswrite) - { - sprintf_s(desc, "Attempt to write data to address 0x%08llu\r\nThe memory could not be \"written\"", accessAddr); - } - else - { - sprintf_s(desc, "Attempt to read from address 0x%08llu\r\nThe memory could not be \"read\"", accessAddr); - } - } - } - } - - - WriteLineToLog("Exception Code: %s", excCode); - WriteLineToLog("Exception Addr: %s", excAddr); - WriteLineToLog("Exception Module: %s", m_excModule); - WriteLineToLog("Exception Name : %s", excName); - WriteLineToLog("Exception Description: %s", desc); - - - cry_strcpy(m_excDesc, excDesc); - cry_strcpy(m_excAddr, excAddr); - cry_strcpy(m_excCode, excCode); - - - char errs[32768]; - sprintf_s(errs, "Exception Code: %s\nException Addr: %s\nException Module: %s\nException Description: %s, %s\n", - excCode, excAddr, m_excModule, excName, desc); - - - IMemoryManager::SProcessMemInfo memInfo; - if (gEnv->pSystem->GetIMemoryManager()->GetProcessMemInfo(memInfo)) - { - char memoryString[256]; - double MB = 1024 * 1024; - sprintf_s(memoryString, "Memory in use: %3.1fMB\n", (double)(memInfo.PagefileUsage) / MB); - cry_strcat(errs, memoryString); - } - { - const int tempStringSize = 256; - char tempString[tempStringSize]; - - gEnv->szDebugStatus[SSystemGlobalEnvironment::MAX_DEBUG_STRING_LENGTH - 1] = '\0'; - sprintf_s(tempString, tempStringSize, "Debug Status: %s\n", gEnv->szDebugStatus); - cry_strcat(errs, tempString); - - sprintf_s(tempString, tempStringSize, "Out of Memory: %d\n", gEnv->bIsOutOfMemory); - cry_strcat(errs, tempString); - } - cry_strcat(errs, "\nCall Stack Trace:\n"); - - std::vector funcs; - if (gEnv->bIsOutOfMemory) - { - cry_strcat(errs, "1) OUT_OF_MEMORY()\n"); - } - else - { - AZ::Debug::StackFrame frames[25]; - AZ::Debug::SymbolStorage::StackLine lines[AZ_ARRAY_SIZE(frames)]; - unsigned int numFrames = AZ::Debug::StackRecorder::Record(frames, AZ_ARRAY_SIZE(frames), 3); - if (numFrames) - { - AZ::Debug::SymbolStorage::DecodeFrames(frames, numFrames, lines); - for (unsigned int i = 0; i < numFrames; i++) - { - funcs.push_back(lines[i]); - } - } - dumpCallStack(funcs); - // Fill call stack. - char str[s_iCallStackSize]; - cry_strcpy(str, ""); - for (unsigned int i = 0; i < funcs.size(); i++) - { - char temp[s_iCallStackSize]; - sprintf_s(temp, "%2zd) %s", funcs.size() - i, (const char*)funcs[i].c_str()); - cry_strcat(str, temp); - cry_strcat(str, "\r\n"); - cry_strcat(errs, temp); - cry_strcat(errs, "\n"); - } - cry_strcpy(m_excCallstack, str); - } - - cry_strcat(errorString, errs); - - if (f) - { - fwrite(errorString, strlen(errorString), 1, f); - if (!gEnv->bIsOutOfMemory) - { - if (g_cvars.sys_dump_aux_threads) - { - for (int i = 0; i < g_nDebugThreads; i++) - { - if (g_idDebugThreads[i] != GetCurrentThreadId()) - { - fprintf(f, "\n\nSuspended thread (%s):\n", g_nameDebugThreads[i]); - HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, TRUE, g_idDebugThreads[i]); - - // mirrors the AZ::Debug::Trace::PrintCallstack() functionality, but prints to a file - { - AZ::Debug::StackFrame frames[10]; - - // Without StackFrame explicit alignment frames array is aligned to 4 bytes - // which causes the stack tracing to fail. - AZ::Debug::SymbolStorage::StackLine lines[AZ_ARRAY_SIZE(frames)]; - - unsigned int numFrames = AZ::Debug::StackRecorder::Record(frames, AZ_ARRAY_SIZE(frames), 0, hThread); - if (numFrames) - { - AZ::Debug::SymbolStorage::DecodeFrames(frames, numFrames, lines); - for (unsigned int i2 = 0; i2 < numFrames; ++i2) - { - fprintf(f, "%2d) %s\n", numFrames - i2, lines[i2]); - } - } - } - - ResumeThread(hThread); - } - } - } - } - fflush(f); - fclose(f); - } - - if (pex) - { - MINIDUMP_TYPE mdumpValue; - bool bDump = true; - switch (g_cvars.sys_dump_type) - { - case 0: - bDump = false; - break; - case 1: - mdumpValue = MiniDumpNormal; - break; - case 2: - mdumpValue = (MINIDUMP_TYPE)(MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithDataSegs); - break; - case 3: - mdumpValue = MiniDumpWithFullMemory; - break; - default: - mdumpValue = (MINIDUMP_TYPE)g_cvars.sys_dump_type; - break; - } - if (bDump) - { - fileName = path + "error.dmp"; - - if (gEnv->IsDedicated() && stat(fileName.c_str(), &fileInfo) == 0) - { - // Backup dump (use timestamp from error.log if available) - if (timeStamp.empty()) - { - tm creationTime; - localtime_s(&creationTime, &fileInfo.st_mtime); - char tempBuffer[32]; - strftime(tempBuffer, sizeof(tempBuffer), "%d %b %Y (%H %M %S)", &creationTime); - timeStamp = tempBuffer; - } - - string backupFileName = backupPath + timeStamp + " error.dmp"; - CopyFile(fileName.c_str(), backupFileName.c_str(), true); - } - - CryEngineExceptionFilterMiniDump(pex, fileName.c_str(), mdumpValue); - } - } - - //if no crash dialog don't even submit the bug - if (m_postBackupProcess && g_cvars.sys_no_crash_dialog == 0 && g_bUserDialog) - { - m_postBackupProcess(); - } - else - { - // lawsonn: Disabling the JIRA-based crash reporter for now - // we'll need to deal with it our own way, pending QA. - // if you're customizing the engine this is also your opportunity to deal with it. - if (g_cvars.sys_no_crash_dialog != 0 || !g_bUserDialog) - { - // ------------ place custom crash handler here --------------------- - // it should launch an executable! - /// by this time, error.bmp will be in the engine root folder - // error.log and error.dmp will also be present in the engine root folder - // if your error dumper wants those, it should zip them up and send them or offer to do so. - // ------------------------------------------------------------------ - } - } - const bool bQuitting = !gEnv || !gEnv->pSystem || gEnv->pSystem->IsQuitting(); - - //[AlexMcC|16.04.10] When the engine is shutting down, MessageBox doesn't display a box - // and immediately returns IDYES. Avoid this by just not trying to save if we're quitting. - // Don't ask to save if this isn't a real crash (a real crash has exception pointers) - if (g_cvars.sys_no_crash_dialog == 0 && g_bUserDialog && gEnv->IsEditor() && !bQuitting && pex) - { - BackupCurrentLevel(); - - const INT_PTR res = DialogBoxParam(gDLLHandle, MAKEINTRESOURCE(IDD_CONFIRM_SAVE_LEVEL), NULL, DebugCallStack::ConfirmSaveDialogProc, NULL); - if (res == IDB_CONFIRM_SAVE) - { - if (SaveCurrentLevel()) - { - MessageBox(NULL, "Level has been successfully saved!\r\nPress Ok to terminate Editor.", "Save", MB_OK); - } - else - { - MessageBox(NULL, "Error saving level.\r\nPress Ok to terminate Editor.", "Save", MB_OK | MB_ICONWARNING); - } - } - } - - if (g_cvars.sys_no_crash_dialog != 0 || !g_bUserDialog) - { - // terminate immediately - since we're in a crash, there is no point unwinding stack, we've already done access violation or worse. - // calling exit will only cause further death down the line... - TerminateProcess(GetCurrentProcess(), pex->ExceptionRecord->ExceptionCode); - } -} - - -INT_PTR CALLBACK DebugCallStack::ExceptionDialogProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) -{ - static EXCEPTION_POINTERS* pex; - - static char errorString[32768] = ""; - - switch (message) - { - case WM_INITDIALOG: - { - pex = (EXCEPTION_POINTERS*)lParam; - HWND h; - - if (pex->ExceptionRecord->ExceptionFlags & EXCEPTION_NONCONTINUABLE) - { - // Disable continue button for non continuable exceptions. - //h = GetDlgItem( hwndDlg,IDB_CONTINUE ); - //if (h) EnableWindow( h,FALSE ); - } - - DebugCallStack* pDCS = static_cast(DebugCallStack::instance()); - - h = GetDlgItem(hwndDlg, IDC_EXCEPTION_DESC); - if (h) - { - SendMessage(h, EM_REPLACESEL, FALSE, (LONG_PTR)pDCS->m_excDesc); - } - - h = GetDlgItem(hwndDlg, IDC_EXCEPTION_CODE); - if (h) - { - SendMessage(h, EM_REPLACESEL, FALSE, (LONG_PTR)pDCS->m_excCode); - } - - h = GetDlgItem(hwndDlg, IDC_EXCEPTION_MODULE); - if (h) - { - SendMessage(h, EM_REPLACESEL, FALSE, (LONG_PTR)pDCS->m_excModule); - } - - h = GetDlgItem(hwndDlg, IDC_EXCEPTION_ADDRESS); - if (h) - { - SendMessage(h, EM_REPLACESEL, FALSE, (LONG_PTR)pDCS->m_excAddr); - } - - // Fill call stack. - HWND callStack = GetDlgItem(hwndDlg, IDC_CALLSTACK); - if (callStack) - { - SendMessage(callStack, WM_SETTEXT, FALSE, (LPARAM)pDCS->m_excCallstack); - } - - if (hwndException) - { - DestroyWindow(hwndException); - hwndException = 0; - } - - if (IsFloatingPointException(pex)) - { - EnableWindow(GetDlgItem(hwndDlg, IDB_IGNORE), TRUE); - } - } - break; - - case WM_COMMAND: - switch (LOWORD(wParam)) - { - case IDB_EXIT: - case IDB_IGNORE: - // Fall through. - - EndDialog(hwndDlg, wParam); - return TRUE; - } - } - return FALSE; -} - -INT_PTR CALLBACK DebugCallStack::ConfirmSaveDialogProc(HWND hwndDlg, UINT message, WPARAM wParam, [[maybe_unused]] LPARAM lParam) -{ - switch (message) - { - case WM_INITDIALOG: - { - // The user might be holding down the spacebar while the engine crashes. - // If we don't remove keyboard focus from this dialog, the keypress will - // press the default button before the dialog actually appears, even if - // the user has already released the key, which is bad. - SetFocus(NULL); - } break; - case WM_COMMAND: - { - switch (LOWORD(wParam)) - { - case IDB_CONFIRM_SAVE: // Fall through - case IDB_DONT_SAVE: - { - EndDialog(hwndDlg, wParam); - return TRUE; - } - } - } break; - } - - return FALSE; -} - -bool DebugCallStack::BackupCurrentLevel() -{ - CSystem* pSystem = static_cast(m_pSystem); - if (pSystem && pSystem->GetUserCallback()) - { - return pSystem->GetUserCallback()->OnBackupDocument(); - } - - return false; -} - -bool DebugCallStack::SaveCurrentLevel() -{ - CSystem* pSystem = static_cast(m_pSystem); - if (pSystem && pSystem->GetUserCallback()) - { - return pSystem->GetUserCallback()->OnSaveDocument(); - } - - return false; -} - -int DebugCallStack::SubmitBug(EXCEPTION_POINTERS* exception_pointer) -{ - int ret = IDB_EXIT; - - assert(!hwndException); - - RemoveOldFiles(); - - AZ::Debug::Trace::PrintCallstack("", 2); - - LogExceptionInfo(exception_pointer); - - if (IsFloatingPointException(exception_pointer)) - { - //! Print exception dialog. - ret = PrintException(exception_pointer); - } - - return ret; -} - -void DebugCallStack::ResetFPU(EXCEPTION_POINTERS* pex) -{ - if (IsFloatingPointException(pex)) - { - // How to reset FPU: http://www.experts-exchange.com/Programming/System/Windows__Programming/Q_10310953.html - _clearfp(); -#ifndef WIN64 - pex->ContextRecord->FloatSave.ControlWord |= 0x2F; - pex->ContextRecord->FloatSave.StatusWord &= ~0x8080; -#endif - } -} - -string DebugCallStack::GetModuleNameForAddr(void* addr) -{ - if (m_modules.empty()) - { - return "[unknown]"; - } - - if (addr < m_modules.begin()->first) - { - return "[unknown]"; - } - - TModules::const_iterator it = m_modules.begin(); - TModules::const_iterator end = m_modules.end(); - for (; ++it != end; ) - { - if (addr < it->first) - { - return (--it)->second; - } - } - - //if address is higher than the last module, we simply assume it is in the last module. - return m_modules.rbegin()->second; -} - -void DebugCallStack::GetProcNameForAddr(void* addr, string& procName, void*& baseAddr, string& filename, int& line) -{ - AZ::Debug::SymbolStorage::StackLine func, file, module; - AZ::Debug::SymbolStorage::FindFunctionFromIP(addr, &func, &file, &module, line, baseAddr); - procName = func; - filename = file; -} - -string DebugCallStack::GetCurrentFilename() -{ - char fullpath[MAX_PATH_LENGTH + 1]; - GetModuleFileName(NULL, fullpath, MAX_PATH_LENGTH); - return fullpath; -} - -static bool IsFloatingPointException(EXCEPTION_POINTERS* pex) -{ - if (!pex) - { - return false; - } - - DWORD exceptionCode = pex->ExceptionRecord->ExceptionCode; - switch (exceptionCode) - { - case EXCEPTION_FLT_DENORMAL_OPERAND: - case EXCEPTION_FLT_DIVIDE_BY_ZERO: - case EXCEPTION_FLT_INEXACT_RESULT: - case EXCEPTION_FLT_INVALID_OPERATION: - case EXCEPTION_FLT_OVERFLOW: - case EXCEPTION_FLT_UNDERFLOW: - case STATUS_FLOAT_MULTIPLE_FAULTS: - case STATUS_FLOAT_MULTIPLE_TRAPS: - return true; - - default: - return false; - } -} - -int DebugCallStack::PrintException(EXCEPTION_POINTERS* exception_pointer) -{ - return (int)DialogBoxParam(gDLLHandle, MAKEINTRESOURCE(IDD_CRITICAL_ERROR), NULL, DebugCallStack::ExceptionDialogProc, (LPARAM)exception_pointer); -} - -#else -void MarkThisThreadForDebugging(const char*) {} -void UnmarkThisThreadFromDebugging() {} -void UpdateFPExceptionsMaskForThreads() {} -#endif //WIN32 diff --git a/Code/CryEngine/CrySystem/DebugCallStack.h b/Code/CryEngine/CrySystem/DebugCallStack.h deleted file mode 100644 index c37e6ba0d4..0000000000 --- a/Code/CryEngine/CrySystem/DebugCallStack.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_DEBUGCALLSTACK_H -#define CRYINCLUDE_CRYSYSTEM_DEBUGCALLSTACK_H -#pragma once - - -#include "IDebugCallStack.h" - -#if defined (WIN32) || defined (WIN64) - -//! Limits the maximal number of functions in call stack. -const int MAX_DEBUG_STACK_ENTRIES_FILE_DUMP = 12; - -struct ISystem; - -//!============================================================================ -//! -//! DebugCallStack class, capture call stack information from symbol files. -//! -//!============================================================================ -class DebugCallStack - : public IDebugCallStack -{ -public: - DebugCallStack(); - virtual ~DebugCallStack(); - - ISystem* GetSystem() { return m_pSystem; }; - - virtual string GetModuleNameForAddr(void* addr); - virtual void GetProcNameForAddr(void* addr, string& procName, void*& baseAddr, string& filename, int& line); - virtual string GetCurrentFilename(); - - void installErrorHandler(ISystem* pSystem); - virtual int handleException(EXCEPTION_POINTERS* exception_pointer); - - virtual void ReportBug(const char*); - - void dumpCallStack(std::vector& functions); - - void SetUserDialogEnable(const bool bUserDialogEnable); - - typedef std::map TModules; -protected: - static void RemoveOldFiles(); - static void RemoveFile(const char* szFileName); - - static int PrintException(EXCEPTION_POINTERS* exception_pointer); - static INT_PTR CALLBACK ExceptionDialogProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam); - static INT_PTR CALLBACK ConfirmSaveDialogProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam); - - void LogExceptionInfo(EXCEPTION_POINTERS* exception_pointer); - bool BackupCurrentLevel(); - bool SaveCurrentLevel(); - int SubmitBug(EXCEPTION_POINTERS* exception_pointer); - void ResetFPU(EXCEPTION_POINTERS* pex); - - static const int s_iCallStackSize = 32768; - - char m_excLine[256]; - char m_excModule[128]; - - char m_excDesc[MAX_WARNING_LENGTH]; - char m_excCode[MAX_WARNING_LENGTH]; - char m_excAddr[80]; - char m_excCallstack[s_iCallStackSize]; - - void* prevExceptionHandler; - - bool m_bCrash; - const char* m_szBugMessage; - - ISystem* m_pSystem; - - int m_nSkipNumFunctions; - CONTEXT m_context; - - TModules m_modules; -}; - -#endif //WIN32 - -#endif // CRYINCLUDE_CRYSYSTEM_DEBUGCALLSTACK_H diff --git a/Code/CryEngine/CrySystem/DllMain.cpp b/Code/CryEngine/CrySystem/DllMain.cpp index 6173ebc0c6..c3a15812ce 100644 --- a/Code/CryEngine/CrySystem/DllMain.cpp +++ b/Code/CryEngine/CrySystem/DllMain.cpp @@ -14,7 +14,6 @@ #include "CrySystem_precompiled.h" #include "System.h" #include -#include "DebugCallStack.h" #if defined(AZ_RESTRICTED_PLATFORM) #undef AZ_RESTRICTED_SECTION @@ -72,10 +71,6 @@ public: { switch (event) { - case ESYSTEM_EVENT_LEVEL_UNLOAD: - gEnv->pSystem->SetThreadState(ESubsys_Physics, false); - break; - case ESYSTEM_EVENT_LEVEL_LOAD_START: case ESYSTEM_EVENT_LEVEL_LOAD_END: { @@ -87,7 +82,6 @@ public: { CryCleanup(); STLALLOCATOR_CLEANUP; - gEnv->pSystem->SetThreadState(ESubsys_Physics, true); break; } } @@ -135,21 +129,6 @@ CRYSYSTEM_API ISystem* CreateSystemInterface(const SSystemInitParams& startupPar startupParams.pUserCallback->OnSystemConnect(pSystem); } - // Environment Variable to signal we don't want to override our exception handler - our crash report system will set this - auto envVar = AZ::Environment::FindVariable("ExceptionHandlerIsSet"); - bool handlerIsSet = (envVar && *envVar); - - if (!startupParams.bMinimal && !handlerIsSet) // in minimal mode, we want to crash when we crash! - { -#if defined(WIN32) - // Install exception handler in Release modes. - ((DebugCallStack*)IDebugCallStack::instance())->installErrorHandler(pSystem); -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION DLLMAIN_CPP_SECTION_3 -#include AZ_RESTRICTED_FILE(DllMain_cpp) -#endif - } - bool retVal = false; { AZ::Debug::StartupLogSinkReporter initLogSink; @@ -171,20 +150,5 @@ CRYSYSTEM_API ISystem* CreateSystemInterface(const SSystemInitParams& startupPar return pSystem; } - -CRYSYSTEM_API void WINAPI CryInstallUnhandledExceptionHandler() -{ -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION DLLMAIN_CPP_SECTION_4 -#include AZ_RESTRICTED_FILE(DllMain_cpp) -#endif -} - -#if defined(ENABLE_PROFILING_CODE) && !defined(LINUX) && !defined(APPLE) -CRYSYSTEM_API void CryInstallPostExceptionHandler(void (* PostExceptionHandlerCallback)()) -{ - return IDebugCallStack::instance()->FileCreationCallback(PostExceptionHandlerCallback); -} -#endif }; diff --git a/Code/CryEngine/CrySystem/IDebugCallStack.cpp b/Code/CryEngine/CrySystem/IDebugCallStack.cpp deleted file mode 100644 index 3d865dee6c..0000000000 --- a/Code/CryEngine/CrySystem/IDebugCallStack.cpp +++ /dev/null @@ -1,278 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : A multiplatform base class for handling errors and collecting call stacks - - -#include "CrySystem_precompiled.h" -#include "IDebugCallStack.h" -#include -#include "System.h" -#include -#include -#include -#include -//#if !defined(LINUX) - -#include - -const char* const IDebugCallStack::s_szFatalErrorCode = "FATAL_ERROR"; - -IDebugCallStack::IDebugCallStack() - : m_bIsFatalError(false) - , m_postBackupProcess(0) - , m_memAllocFileHandle(AZ::IO::InvalidHandle) -{ -} - -IDebugCallStack::~IDebugCallStack() -{ - StopMemLog(); -} - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_DEBUGCALLSTACK_SINGLETON -IDebugCallStack* IDebugCallStack::instance() -{ - static IDebugCallStack sInstance; - return &sInstance; -} -#endif - -void IDebugCallStack::FileCreationCallback(void (* postBackupProcess)()) -{ - m_postBackupProcess = postBackupProcess; -} -////////////////////////////////////////////////////////////////////////// -void IDebugCallStack::LogCallstack() -{ - AZ::Debug::Trace::PrintCallstack("", 2); -} - -const char* IDebugCallStack::TranslateExceptionCode(DWORD dwExcept) -{ - switch (dwExcept) - { -#if AZ_LEGACY_CRYSYSTEM_TRAIT_DEBUGCALLSTACK_TRANSLATE - case EXCEPTION_ACCESS_VIOLATION: - return "EXCEPTION_ACCESS_VIOLATION"; - break; - case EXCEPTION_DATATYPE_MISALIGNMENT: - return "EXCEPTION_DATATYPE_MISALIGNMENT"; - break; - case EXCEPTION_BREAKPOINT: - return "EXCEPTION_BREAKPOINT"; - break; - case EXCEPTION_SINGLE_STEP: - return "EXCEPTION_SINGLE_STEP"; - break; - case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: - return "EXCEPTION_ARRAY_BOUNDS_EXCEEDED"; - break; - case EXCEPTION_FLT_DENORMAL_OPERAND: - return "EXCEPTION_FLT_DENORMAL_OPERAND"; - break; - case EXCEPTION_FLT_DIVIDE_BY_ZERO: - return "EXCEPTION_FLT_DIVIDE_BY_ZERO"; - break; - case EXCEPTION_FLT_INEXACT_RESULT: - return "EXCEPTION_FLT_INEXACT_RESULT"; - break; - case EXCEPTION_FLT_INVALID_OPERATION: - return "EXCEPTION_FLT_INVALID_OPERATION"; - break; - case EXCEPTION_FLT_OVERFLOW: - return "EXCEPTION_FLT_OVERFLOW"; - break; - case EXCEPTION_FLT_STACK_CHECK: - return "EXCEPTION_FLT_STACK_CHECK"; - break; - case EXCEPTION_FLT_UNDERFLOW: - return "EXCEPTION_FLT_UNDERFLOW"; - break; - case EXCEPTION_INT_DIVIDE_BY_ZERO: - return "EXCEPTION_INT_DIVIDE_BY_ZERO"; - break; - case EXCEPTION_INT_OVERFLOW: - return "EXCEPTION_INT_OVERFLOW"; - break; - case EXCEPTION_PRIV_INSTRUCTION: - return "EXCEPTION_PRIV_INSTRUCTION"; - break; - case EXCEPTION_IN_PAGE_ERROR: - return "EXCEPTION_IN_PAGE_ERROR"; - break; - case EXCEPTION_ILLEGAL_INSTRUCTION: - return "EXCEPTION_ILLEGAL_INSTRUCTION"; - break; - case EXCEPTION_NONCONTINUABLE_EXCEPTION: - return "EXCEPTION_NONCONTINUABLE_EXCEPTION"; - break; - case EXCEPTION_STACK_OVERFLOW: - return "EXCEPTION_STACK_OVERFLOW"; - break; - case EXCEPTION_INVALID_DISPOSITION: - return "EXCEPTION_INVALID_DISPOSITION"; - break; - case EXCEPTION_GUARD_PAGE: - return "EXCEPTION_GUARD_PAGE"; - break; - case EXCEPTION_INVALID_HANDLE: - return "EXCEPTION_INVALID_HANDLE"; - break; - //case EXCEPTION_POSSIBLE_DEADLOCK: return "EXCEPTION_POSSIBLE_DEADLOCK"; break ; - - case STATUS_FLOAT_MULTIPLE_FAULTS: - return "STATUS_FLOAT_MULTIPLE_FAULTS"; - break; - case STATUS_FLOAT_MULTIPLE_TRAPS: - return "STATUS_FLOAT_MULTIPLE_TRAPS"; - break; - - -#endif - default: - return "Unknown"; - break; - } -} - -void IDebugCallStack::PutVersion(char* str, size_t length) -{ -AZ_PUSH_DISABLE_WARNING(4996, "-Wunknown-warning-option") - - if (!gEnv || !gEnv->pSystem) - { - return; - } - - char sFileVersion[128]; - gEnv->pSystem->GetFileVersion().ToString(sFileVersion, sizeof(sFileVersion)); - - char sProductVersion[128]; - gEnv->pSystem->GetProductVersion().ToString(sProductVersion, sizeof(sFileVersion)); - - - //! Get time. - time_t ltime; - time(<ime); - tm* today = localtime(<ime); - - char s[1024]; - //! Use strftime to build a customized time string. - strftime(s, 128, "Logged at %#c\n", today); - azstrcat(str, length, s); - sprintf_s(s, "FileVersion: %s\n", sFileVersion); - azstrcat(str, length, s); - sprintf_s(s, "ProductVersion: %s\n", sProductVersion); - azstrcat(str, length, s); - - if (gEnv->pLog) - { - const char* logfile = gEnv->pLog->GetFileName(); - if (logfile) - { - sprintf (s, "LogFile: %s\n", logfile); - azstrcat(str, length, s); - } - } - - AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath(); - azstrcat(str, length, "ProjectDir: "); - azstrcat(str, length, projectPath.c_str()); - azstrcat(str, length, "\n"); - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_DEBUGCALLSTACK_APPEND_MODULENAME - GetModuleFileNameA(NULL, s, sizeof(s)); - - // Log EXE filename only if possible (not full EXE path which could contain sensitive info) - AZStd::string exeName; - if (AZ::StringFunc::Path::GetFullFileName(s, exeName)) - { - azstrcat(str, length, "Executable: "); - azstrcat(str, length, exeName.c_str()); - -# ifdef AZ_DEBUG_BUILD - azstrcat(str, length, " (debug: yes"); -# else - azstrcat(str, length, " (debug: no"); -# endif - } -#endif -AZ_POP_DISABLE_WARNING -} - - -//Crash the application, in this way the debug callstack routine will be called and it will create all the necessary files (error.log, dump, and eventually screenshot) -void IDebugCallStack::FatalError(const char* description) -{ - m_bIsFatalError = true; - WriteLineToLog(description); - -#ifndef _RELEASE - bool bShowDebugScreen = g_cvars.sys_no_crash_dialog == 0; - // showing the debug screen is not safe when not called from mainthread - // it normally leads to a infinity recursion followed by a stack overflow, preventing - // useful call stacks, thus they are disabled - bShowDebugScreen = bShowDebugScreen && gEnv->mMainThreadId == CryGetCurrentThreadId(); - if (bShowDebugScreen) - { - EBUS_EVENT(AZ::NativeUI::NativeUIRequestBus, DisplayOkDialog, "Open 3D Engine Fatal Error", description, false); - } -#endif - -#if defined(WIN32) || !defined(_RELEASE) - int* p = 0x0; - PREFAST_SUPPRESS_WARNING(6011) * p = 1; // we're intentionally crashing here -#endif -} - -void IDebugCallStack::WriteLineToLog(const char* format, ...) -{ - CDebugAllowFileAccess allowFileAccess; - - va_list ArgList; - char szBuffer[MAX_WARNING_LENGTH]; - va_start(ArgList, format); - vsnprintf_s(szBuffer, sizeof(szBuffer), sizeof(szBuffer) - 1, format, ArgList); - cry_strcat(szBuffer, "\n"); - szBuffer[sizeof(szBuffer) - 1] = '\0'; - va_end(ArgList); - - AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; - AZ::IO::FileIOBase::GetDirectInstance()->Open("@Log@\\error.log", AZ::IO::GetOpenModeFromStringMode("a+t"), fileHandle); - if (fileHandle != AZ::IO::InvalidHandle) - { - AZ::IO::FileIOBase::GetDirectInstance()->Write(fileHandle, szBuffer, strlen(szBuffer)); - AZ::IO::FileIOBase::GetDirectInstance()->Flush(fileHandle); - AZ::IO::FileIOBase::GetDirectInstance()->Close(fileHandle); - } -} - -////////////////////////////////////////////////////////////////////////// -void IDebugCallStack::StartMemLog() -{ - AZ::IO::FileIOBase::GetDirectInstance()->Open("@Log@\\memallocfile.log", AZ::IO::OpenMode::ModeWrite, m_memAllocFileHandle); - - assert(m_memAllocFileHandle != AZ::IO::InvalidHandle); -} - -////////////////////////////////////////////////////////////////////////// -void IDebugCallStack::StopMemLog() -{ - if (m_memAllocFileHandle != AZ::IO::InvalidHandle) - { - AZ::IO::FileIOBase::GetDirectInstance()->Close(m_memAllocFileHandle); - m_memAllocFileHandle = AZ::IO::InvalidHandle; - } -} -//#endif //!defined(LINUX) diff --git a/Code/CryEngine/CrySystem/IDebugCallStack.h b/Code/CryEngine/CrySystem/IDebugCallStack.h deleted file mode 100644 index f181b73913..0000000000 --- a/Code/CryEngine/CrySystem/IDebugCallStack.h +++ /dev/null @@ -1,90 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : A multiplatform base class for handling errors and collecting call stacks - -#ifndef CRYINCLUDE_CRYSYSTEM_IDEBUGCALLSTACK_H -#define CRYINCLUDE_CRYSYSTEM_IDEBUGCALLSTACK_H -#pragma once - -#include "System.h" - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_FORWARD_EXCEPTION_POINTERS -struct EXCEPTION_POINTERS; -#endif -//! Limits the maximal number of functions in call stack. -enum -{ - MAX_DEBUG_STACK_ENTRIES = 80 -}; - -class IDebugCallStack -{ -public: - // Returns single instance of DebugStack - static IDebugCallStack* instance(); - - virtual int handleException([[maybe_unused]] EXCEPTION_POINTERS* exception_pointer){return 0; } - - // returns the module name of a given address - virtual string GetModuleNameForAddr([[maybe_unused]] void* addr) { return "[unknown]"; } - - // returns the function name of a given address together with source file and line number (if available) of a given address - virtual void GetProcNameForAddr(void* addr, string& procName, void*& baseAddr, string& filename, int& line) - { - filename = "[unknown]"; - line = 0; - baseAddr = addr; -#if defined(PLATFORM_64BIT) - procName.Format("[%016llX]", addr); -#else - procName.Format("[%08X]", addr); -#endif - } - - // returns current filename - virtual string GetCurrentFilename() { return "[unknown]"; } - - //! Dumps Current Call Stack to log. - virtual void LogCallstack(); - //triggers a fatal error, so the DebugCallstack can create the error.log and terminate the application - void FatalError(const char*); - - //Reports a bug and continues execution - virtual void ReportBug(const char*) {} - - virtual void FileCreationCallback(void (* postBackupProcess)()); - - static void WriteLineToLog(const char* format, ...); - - virtual void StartMemLog(); - virtual void StopMemLog(); - -protected: - IDebugCallStack(); - virtual ~IDebugCallStack(); - - static const char* TranslateExceptionCode(DWORD dwExcept); - static void PutVersion(char* str, size_t length); - - bool m_bIsFatalError; - static const char* const s_szFatalErrorCode; - - void (* m_postBackupProcess)(); - - AZ::IO::HandleType m_memAllocFileHandle; -}; - - - -#endif // CRYINCLUDE_CRYSYSTEM_IDEBUGCALLSTACK_H diff --git a/Code/CryEngine/CrySystem/IThreadConfigManager.h b/Code/CryEngine/CrySystem/IThreadConfigManager.h deleted file mode 100644 index 97c4d7237b..0000000000 --- a/Code/CryEngine/CrySystem/IThreadConfigManager.h +++ /dev/null @@ -1,59 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -struct SThreadConfig -{ - enum eThreadParamFlag - { - eThreadParamFlag_ThreadName = BIT(0), - eThreadParamFlag_StackSize = BIT(1), - eThreadParamFlag_Affinity = BIT(2), - eThreadParamFlag_Priority = BIT(3), - eThreadParamFlag_PriorityBoost = BIT(4), - }; - - typedef uint32 TThreadParamFlag; - - const char* szThreadName; - uint32 stackSizeBytes; - uint32 affinityFlag; - int32 priority; - bool bDisablePriorityBoost; - - TThreadParamFlag paramActivityFlag; -}; - -class IThreadConfigManager -{ -public: - virtual ~IThreadConfigManager() - { - } - - //! Called once during System startup. - //! Loads the thread configuration for the executing platform from file. - virtual bool LoadConfig(const char* pcPath) = 0; - - //! Returns true if a config has been loaded. - virtual bool ConfigLoaded() const = 0; - - //! Gets the thread configuration for the specified thread on the active platform. - //! If no matching config is found a default configuration is returned (which does not have the same name as the search string). - virtual const SThreadConfig* GetThreadConfig(const char* sThreadName, ...) = 0; - virtual const SThreadConfig* GetDefaultThreadConfig() const = 0; - - //! Dump a detailed description of the thread startup configurations for this platform to the log file. - virtual void DumpThreadConfigurationsToLog() = 0; -}; diff --git a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp index b8002b74a9..0af52d8cc4 100644 --- a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp @@ -17,7 +17,6 @@ #include "LevelSystem.h" #include #include "IMovieSystem.h" -#include "IMaterialEffects.h" #include #include #include "CryPath.h" @@ -648,20 +647,6 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) AZStd::string levelPath(pLevelInfo->GetPath()); - /* - ICVar *pFileCache = gEnv->pConsole->GetCVar("sys_FileCache"); CRY_ASSERT(pFileCache); - - if(pFileCache->GetIVal()) - { - if(pPak->OpenPack("",pLevelInfo->GetPath()+string("/FileCache.dat"))) - gEnv->pLog->Log("FileCache.dat loaded"); - else - gEnv->pLog->Log("FileCache.dat not loaded"); - } - */ - - m_pSystem->SetThreadState(ESubsys_Physics, false); - ICVar* pSpamDelay = gEnv->pConsole->GetCVar("log_SpamDelay"); float spamDelay = 0.0f; if (pSpamDelay) @@ -768,8 +753,6 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_START, 0, 0); - m_pSystem->SetThreadState(ESubsys_Physics, true); - return m_pCurrentLevel; } diff --git a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp index 2a7f8d5c5e..8b3c75cce2 100644 --- a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp +++ b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp @@ -247,8 +247,6 @@ namespace LegacyLevelSystem auto pPak = gEnv->pCryPak; - m_pSystem->SetThreadState(ESubsys_Physics, false); - ICVar* pSpamDelay = gEnv->pConsole->GetCVar("log_SpamDelay"); float spamDelay = 0.0f; if (pSpamDelay) @@ -343,8 +341,6 @@ namespace LegacyLevelSystem gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_START, 0, 0); - m_pSystem->SetThreadState(ESubsys_Physics, true); - return true; } diff --git a/Code/CryEngine/CrySystem/Log.cpp b/Code/CryEngine/CrySystem/Log.cpp index 62cf29fef9..c51947d8bc 100644 --- a/Code/CryEngine/CrySystem/Log.cpp +++ b/Code/CryEngine/CrySystem/Log.cpp @@ -920,13 +920,7 @@ bool CLog::LogToMainThread(const char* szString, ELogType logType, bool bAdd, SL msg.bAdd = bAdd; msg.destination = destination; msg.logType = logType; - // don't try to store the log message for later in case of out of memory, since then its very likely that this allocation - // also fails and results in a stack overflow. This way we should at least get a out of memory on-screen message instead of - // a not obvious crash - if ((gEnv) && (gEnv->bIsOutOfMemory == false)) - { - m_threadSafeMsgQueue.push(msg); - } + m_threadSafeMsgQueue.push(msg); return true; } return false; @@ -1448,8 +1442,6 @@ void CLog::UpdateLoadingScreen(const char* szFormat, ...) if (CryGetCurrentThreadId() == m_nMainThreadId) { - ((CSystem*)m_pSystem)->UpdateLoadingScreen(); - #ifndef LINUX // Take this opportunity to update streaming engine. if (IStreamEngine* pStreamEngine = GetISystem()->GetStreamEngine()) diff --git a/Code/CryEngine/CrySystem/NotificationNetwork.cpp b/Code/CryEngine/CrySystem/NotificationNetwork.cpp deleted file mode 100644 index a0bd3fb9e6..0000000000 --- a/Code/CryEngine/CrySystem/NotificationNetwork.cpp +++ /dev/null @@ -1,1345 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "NotificationNetwork.h" -#include - -#include -#include - -#undef LockDebug -//#define LockDebug(str1,str2) {string strMessage;strMessage.Format(str1,str2);if (m_clients.size()) OutputDebugString(strMessage.c_str());} -#define LockDebug(str1, str2) - -// - -extern bool RCON_IsRemoteAllowedToConnect(const AZ::AzSock::AzSocketAddress& connectee); - -using namespace NotificationNetwork; - -// - -#include -class CQueryNotification - : public INotificationNetworkListener -{ - // INotificationNetworkListener -public: - virtual void OnNotificationNetworkReceive([[maybe_unused]] const void* pBuffer, [[maybe_unused]] size_t length) - { - INotificationNetwork* pNotificationNetwork = - gEnv->pSystem->GetINotificationNetwork(); - if (!pNotificationNetwork) - { - return; - } - - AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath(); - if (projectPath.empty()) - { - return; - } - - pNotificationNetwork->Send("SystemInfo", projectPath.c_str(), projectPath.size()); - } -} g_queryNotification; - -AZSOCKET CConnectionBase::CreateSocket() -{ - AZSOCKET sock = AZ::AzSock::Socket(); - if (!AZ::AzSock::IsAzSocketValid(sock)) - { - CryLog("CNotificationNetworkClient::Create: Failed to create socket."); - return AZ_SOCKET_INVALID; - } - - if (AZ::AzSock::SetSocketOption(sock, AZ::AzSock::AzSocketOption::REUSEADDR, true)) - { - AZ::AzSock::CloseSocket(sock); - CryLog("CNotificationNetworkClient::Create: Failed to set SO_REUSEADDR option."); - return AZ_SOCKET_INVALID; - } - -#if defined (WIN32) || defined(WIN64) //MS Platforms - if (AZ::AzSock::SetSocketBlockingMode(sock, false)) - { - AZ::AzSock::CloseSocket(sock); - CryLog("CNotificationNetworkClient::Connect: Failed to set socket to asynchronous operation."); - return AZ_SOCKET_INVALID; - } - -#endif - - // TCP_NODELAY required for win32 because of high latency connection otherwise -#if defined(WIN32) - if (AZ::AzSock::EnableTCPNoDelay(sock, true)) - { - AZ::AzSock::CloseSocket(sock); - CryLog("CNotificationNetworkClient::Create: Failed to set TCP_NODELAY option."); - return AZ_SOCKET_INVALID; - } -#endif - - return sock; -} - -bool CConnectionBase::Connect(const char* address, uint16 port) -{ - AZ::AzSock::AzSocketAddress socketAddress; - socketAddress.SetAddress(address, port); - - int result = AZ::AzSock::Connect(m_socket, socketAddress); - if (AZ::AzSock::SocketErrorOccured(result)) - { - AZ::AzSock::AzSockError err = AZ::AzSock::AzSockError(result); - if (err == AZ::AzSock::AzSockError::eASE_EWOULDBLOCK_CONN) - { - return true; - } - - if (err == AZ::AzSock::AzSockError::eASE_EISCONN) - { - if (!m_boIsConnected) - { - m_boIsConnected = true; - m_boIsFailedToConnect = false; - OnConnect(true); - } - return true; - } - - if (err == AZ::AzSock::AzSockError::eASE_EALREADY) - { - // It will happen, in case of DNS problems, or if the console is not - // reachable or turned off. - //CryLog("CNotificationNetworkClient::Connect: Failed to connect. Reason: already conencted."); - return true; - } - - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - CryLog("CNotificationNetworkClient::Connect: Failed to connect. Reason: %d ", result); - return false; - } - - return true; -} - -/* - - CChannel - -*/ - -bool CChannel::IsNameValid(const char* name) -{ - if (!name) - { - return false; - } - if (!*name) - { - return false; - } - - if (::strlen(name) > NN_CHANNEL_NAME_LENGTH_MAX) - { - return false; - } - - return true; -} - -// - -CChannel::CChannel() -{ -} - -CChannel::CChannel(const char* name) -{ - if (!name) - { - return; - } - - if (!*name) - { - return; - } - - size_t length = MIN(::strlen(name), NN_CHANNEL_NAME_LENGTH_MAX); - ::memset(m_name, 0, NN_CHANNEL_NAME_LENGTH_MAX); - ::memcpy(m_name, name, length); -} - -CChannel::~CChannel() -{ -} - -// - -void CChannel::WriteToPacketHeader(void* pPacket) const -{ - ::memcpy((uint8*)pPacket + NN_PACKET_HEADER_OFFSET_CHANNEL, - m_name, NN_CHANNEL_NAME_LENGTH_MAX); -} - -void CChannel::ReadFromPacketHeader(void* pPacket) -{ - ::memcpy(m_name, (uint8*)pPacket + NN_PACKET_HEADER_OFFSET_CHANNEL, - NN_CHANNEL_NAME_LENGTH_MAX); -} - -// - -bool CChannel::operator ==(const CChannel& channel) const -{ - return ::strncmp(m_name, channel.m_name, NN_CHANNEL_NAME_LENGTH_MAX) == 0; -} - -bool CChannel::operator !=(const CChannel& channel) const -{ - return ::strncmp(m_name, channel.m_name, NN_CHANNEL_NAME_LENGTH_MAX) != 0; -} - -/* - - CListeners - -*/ - -CListeners::CListeners() -{ - m_pNotificationWrite = &m_notifications[0]; - m_pNotificationRead = &m_notifications[1]; -} - -CListeners::~CListeners() -{ - while (!m_pNotificationRead->empty()) - { - SBuffer buffer = m_pNotificationRead->front(); - m_pNotificationRead->pop(); - delete[] buffer.pData; - } - - while (!m_pNotificationWrite->empty()) - { - SBuffer buffer = m_pNotificationWrite->front(); - m_pNotificationWrite->pop(); - delete[] buffer.pData; - } -} - -// - -size_t CListeners::Count(const CChannel& channel) -{ - size_t count = 0; - for (size_t i = 0; i < m_listeners.size(); ++i) - { - if (m_listeners[i].second != channel) - { - continue; - } - - ++count; - } - - return count; -} - -CChannel* CListeners::Channel(INotificationNetworkListener* pListener) -{ - for (size_t i = 0; i < m_listeners.size(); ++i) - { - if (m_listeners[i].first != pListener) - { - continue; - } - - return &m_listeners[i].second; - } - - return nullptr; -} - -bool CListeners::Bind(const CChannel& channel, INotificationNetworkListener* pListener) -{ - for (size_t i = 0; i < m_listeners.size(); ++i) - { - if (m_listeners[i].first == pListener) - { - m_listeners[i].second = channel; - return true; - } - } - - m_listeners.push_back(std::pair()); - m_listeners.back().first = pListener; - m_listeners.back().second = channel; - return true; -} - -bool CListeners::Remove(INotificationNetworkListener* pListener) -{ - for (size_t i = 0; i < m_listeners.size(); ++i) - { - if (m_listeners[i].first != pListener) - { - continue; - } - - m_listeners[i] = m_listeners.back(); - m_listeners.pop_back(); - return true; - } - - return false; -} - -void CListeners::NotificationPush(const SBuffer& buffer) -{ - // TODO: Use auto lock. - m_notificationCriticalSection.Lock(); - m_pNotificationWrite->push(buffer); - m_notificationCriticalSection.Unlock(); -} - -void CListeners::NotificationsProcess() -{ - m_notificationCriticalSection.Lock(); - std::swap(m_pNotificationWrite, m_pNotificationRead); - m_notificationCriticalSection.Unlock(); - - while (!m_pNotificationRead->empty()) - { - SBuffer buffer = m_pNotificationRead->front(); - m_pNotificationRead->pop(); - - for (size_t i = 0; i < m_listeners.size(); ++i) - { - if (m_listeners[i].second != buffer.channel) - { - continue; - } - - m_listeners[i].first->OnNotificationNetworkReceive( - buffer.pData, buffer.length); - } - - delete[] buffer.pData; - } -} - -/* - - CConnectionBase - -*/ - -CConnectionBase::CConnectionBase(CNotificationNetwork* pNotificationNetwork) -{ - m_pNotificationNetwork = pNotificationNetwork; - - m_port = 0; - - m_socket = AZ_SOCKET_INVALID; - - m_buffer.pData = nullptr; - m_buffer.length = 0; - m_dataLeft = 0; - - m_boIsConnected = false; - m_boIsFailedToConnect = false; -} - -CConnectionBase::~CConnectionBase() -{ - if (m_buffer.pData) - { - delete[] m_buffer.pData; - } - - if (m_socket != AZ_SOCKET_INVALID) - { - CloseSocket_Internal(); - } -} - -// - -void CConnectionBase::SetAddress(const char* address, uint16 port) -{ - size_t length = MIN(::strlen(address), 15); - ::memset(m_address, 0, sizeof(m_address)); - ::memcpy(m_address, address, length); - m_port = port; -} - -bool CConnectionBase::Validate() -{ - if (m_socket != AZ_SOCKET_INVALID) - { - if (!m_port) - { - AZ::AzSock::AzSocketAddress socketAddress; - int result = AZ::AzSock::GetSockName(m_socket, socketAddress); - if (AZ::AzSock::SocketErrorOccured(result)) - { - return false; - } - } - - return Select_Internal(); - } - - if (!m_port) // If port is not set we don't want to try to reconnect. - { - return false; - } - - m_socket = CreateSocket(); - // If the create sockect will fail, it is likely that we will never be able to connect, - // we might want to signal that. - - Connect(m_address, m_port); - - return false; -} - -bool CConnectionBase::Send(const void* pBuffer, size_t length) -{ - if (!Validate()) - { - return false; - } - - size_t sent = 0; - while (sent < length) - { - int r = AZ::AzSock::Send(m_socket, (const char*)pBuffer + sent, length - sent, 0); - if (AZ::AzSock::SocketErrorOccured(r)) - { - AZ::AzSock::AzSockError nCurrentError = AZ::AzSock::AzSockError(r); - if (nCurrentError == AZ::AzSock::AzSockError::eASE_ENOTCONN) - { - r = 0; - break; - } - else if (nCurrentError == AZ::AzSock::AzSockError::eASE_EWOULDBLOCK) - { - r = 0; - } - else - { - CryLog("CNotificationNetworkClient::Send: Failed to send package. Reason: %s", AZ::AzSock::GetStringForError(r)); - CloseSocket_Internal(); - return false; - } - } - - sent += r; - } - - return true; -} - -bool CConnectionBase::SendMessage(EMessage eMessage, const CChannel& channel, uint32 data) -{ - char header[NN_PACKET_HEADER_LENGTH]; - ::memset(header, 0, NN_PACKET_HEADER_LENGTH); - *(uint32*)&header[NN_PACKET_HEADER_OFFSET_MESSAGE] = AZ::AzSock::HostToNetLong(eMessage); - *(uint32*)&header[NN_PACKET_HEADER_OFFSET_DATA_LENGTH] = AZ::AzSock::HostToNetLong(data); - channel.WriteToPacketHeader(header); - - if (!Send(header, NN_PACKET_HEADER_LENGTH)) - { - return false; - } - - return true; -} - -bool CConnectionBase::Select_Internal() -{ - if (m_socket == AZ_SOCKET_INVALID) - { - return false; - } - - AZFD_SET stExceptions; - AZFD_SET stWriteSockets; - - FD_ZERO(&stExceptions); - FD_SET(m_socket, &stExceptions); - - FD_ZERO(&stWriteSockets); - FD_SET(m_socket, &stWriteSockets); - - AZTIMEVAL timeOut = { 0, 0 }; - - int r = AZ::AzSock::Select(m_socket, nullptr, &stWriteSockets, &stExceptions, &timeOut); - if (AZ::AzSock::SocketErrorOccured(r)) - { - CryLog("CNotificationNetworkClient:: Failed to select socket. Reason: %s", AZ::AzSock::GetStringForError(r)); - CloseSocket_Internal(); - m_boIsFailedToConnect = true; - return false; - } - else if (!r) - { - return m_boIsConnected; - } - - if (FD_ISSET(m_socket, &stExceptions)) - { - CloseSocket_Internal(); - m_boIsFailedToConnect = true; - OnConnect(m_boIsConnected); // Handles failed attempt to connect. - return false; - } - else if (FD_ISSET(m_socket, &stWriteSockets)) // In Windows a socket can be in both lists. - { - if (!m_boIsConnected) - { - m_boIsConnected = true; - m_boIsFailedToConnect = false; - OnConnect(m_boIsConnected); // Handles successful attempt to connect. - } - return true; - } - - return false; -} - -void CConnectionBase::CloseSocket_Internal() -{ - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - if (m_boIsConnected) - { - OnDisconnect(); - } - m_boIsConnected = false; -} - -bool CConnectionBase::SendNotification(const CChannel& channel, const void* pBuffer, size_t length) -{ - if (!SendMessage(eMessage_DataTransfer, channel, length)) - { - return false; - } - if (!length) - { - return true; - } - - if (!Send(pBuffer, length)) - { - return false; - } - - return true; -} - -bool CConnectionBase::ReceiveMessage(CListeners& listeners) -{ - if (!Validate()) - { - return false; - } - - if (!m_dataLeft) - { - m_dataLeft = NN_PACKET_HEADER_LENGTH; - } - int r = AZ::AzSock::Recv(m_socket, (char*)&m_bufferHeader[NN_PACKET_HEADER_LENGTH - m_dataLeft], m_dataLeft, 0); - if (!r) - { - // Connection terminated. - m_dataLeft = 0; - - CloseSocket_Internal(); - return false; - } - if (AZ::AzSock::SocketErrorOccured(r)) - { - m_dataLeft = 0; - - CryLog("CNotificationNetworkClient::ReceiveMessage: Failed to receive package. Reason: %s", AZ::AzSock::GetStringForError(r)); - CloseSocket_Internal(); - return false; - } - - if (m_dataLeft -= r) - { - return true; - } - - // The whole message was received, process it... - - EMessage eMessage = (EMessage)AZ::AzSock::NetToHostLong( - *(uint32*)&m_bufferHeader[NN_PACKET_HEADER_OFFSET_MESSAGE]); - const CChannel& channel = *(CChannel*)&m_bufferHeader[NN_PACKET_HEADER_OFFSET_CHANNEL]; - - if (eMessage == eMessage_DataTransfer) - { - m_dataLeft = AZ::AzSock::NetToHostLong(*(uint32*)&m_bufferHeader[NN_PACKET_HEADER_OFFSET_DATA_LENGTH]); - if (!m_dataLeft) - { - SBuffer buffer; - buffer.channel = channel; - buffer.pData = nullptr; - buffer.length = 0; - listeners.NotificationPush(buffer); - return true; - } - - m_buffer.pData = new uint8[m_buffer.length = m_dataLeft]; - if (!m_buffer.pData) - { - CryLog("CNotificationNetwork::CConnection::Receive: Failed to allocate buffer.\n"); - m_dataLeft = 0; - - CloseSocket_Internal(); - return false; - } - - m_buffer.channel.ReadFromPacketHeader(m_bufferHeader); - return +1; - } - - if (!OnMessage(eMessage, channel)) - { - CryLog("NotificationNetwork::CConnectionBase::ReceiveMessage: " - "Unknown message received, terminating Connection...\n"); - m_dataLeft = 0; - - CloseSocket_Internal(); - return false; - } - - return true; -} - -bool CConnectionBase::ReceiveNotification(CListeners& listeners) -{ - int r = AZ::AzSock::Recv(m_socket, (char*)&m_buffer.pData[m_buffer.length - m_dataLeft], m_dataLeft, 0); - if (!r) - { - CryLog("CNotificationNetworkClient::ReceiveNotification: Failed to receive package. Reason: Connection terminated."); - // Connection terminated. - m_dataLeft = 0; - - CloseSocket_Internal(); - return false; - } - - if (AZ::AzSock::SocketErrorOccured(r)) - { - m_dataLeft = 0; - - CryLog("CNotificationNetworkClient::ReceiveNotification: Failed to receive package. Reason: %s", AZ::AzSock::GetStringForError(r)); - CloseSocket_Internal(); - return false; - } - - if (m_dataLeft -= r) - { - return true; - } - - listeners.NotificationPush(m_buffer); - m_buffer.pData = nullptr; - m_buffer.length = 0; - m_dataLeft = 0; - return true; -} - -bool CConnectionBase::Receive(CListeners& listeners) -{ - if (m_buffer.pData) - { - return ReceiveNotification(listeners); - } - - return ReceiveMessage(listeners); -} - -bool CConnectionBase::GetIsConnectedFlag() -{ - return Select_Internal() || m_boIsConnected; -} - -bool CConnectionBase::GetIsFailedToConnectFlag() const -{ - return m_boIsFailedToConnect; -} - -/* - - CClient - -*/ - -CClient* CClient::Create(CNotificationNetwork* pNotificationNetwork, const char* address, uint16 port) -{ - CClient* pClient = new CClient(pNotificationNetwork); - AZSOCKET sock = pClient->CreateSocket(); - // In the current implementation, this is REALLY UNLIKELY to happen. - if (sock == AZ_SOCKET_INVALID) - { - delete pClient; - return nullptr; - } - - // - pClient->SetSocket(sock); - pClient->Connect(address, port); - - pClient->SetAddress(address, port); - pClient->SetSocket(sock); - return pClient; -} - -CClient* CClient::Create(CNotificationNetwork* pNotificationNetwork) -{ - CClient* pClient = new CClient(pNotificationNetwork); - return pClient; -} - -// - -CClient::CClient(CNotificationNetwork* pNotificationNetwork) - : CConnectionBase(pNotificationNetwork) -{ -} - -CClient::~CClient() -{ - GetNotificationNetwork()->ReleaseClients(this); -} - -// - -void CClient::Update() -{ - m_listeners.NotificationsProcess(); -} - -// CConnectionBase - -bool CClient::OnConnect(bool boConnected) -{ - if (boConnected) - { - for (size_t i = 0; i < m_listeners.Count(); ++i) - { - if (!SendMessage(eMessage_ChannelRegister, m_listeners.Channel(i), 0)) - { - return false; - } - } - } - - CryAutoLock lock(m_stConnectionCallbacksLock); - for (size_t nCount = 0; nCount < m_cNotificationNetworkConnectionCallbacks.size(); ++nCount) - { - m_cNotificationNetworkConnectionCallbacks[nCount]->OnConnect(this, boConnected); - } - - return boConnected; -} - -bool CClient::OnDisconnect() -{ - CryAutoLock lock(m_stConnectionCallbacksLock); - for (size_t nCount = 0; nCount < m_cNotificationNetworkConnectionCallbacks.size(); ++nCount) - { - m_cNotificationNetworkConnectionCallbacks[nCount]->OnDisconnected(this); - } - - return true; -} - -bool CClient::OnMessage([[maybe_unused]] EMessage eMessage, [[maybe_unused]] const CChannel& channel) -{ - return false; -} - -// INotificationNetworkClient - -bool CClient::Connect(const char* address, uint16 port) -{ - bool bReturnValue(false); - - if (m_socket == AZ_SOCKET_INVALID) - { - m_socket = CreateSocket(); - } - - bReturnValue = CConnectionBase::Connect(address, port); - if (bReturnValue) - { - SetAddress(address, port); - } - - return bReturnValue; -} - -bool CClient::ListenerBind(const char* channelName, INotificationNetworkListener* pListener) -{ - if (!CChannel::IsNameValid(channelName)) - { - return false; - } - - if (!m_listeners.Bind(CChannel(channelName), pListener)) - { - return false; - } - - if (!SendMessage(eMessage_ChannelRegister, CChannel(channelName), 0)) - { - return false; - } - - return true; -} - -bool CClient::ListenerRemove(INotificationNetworkListener* pListener) -{ - CChannel* pChannel = m_listeners.Channel(pListener); - if (!pChannel) - { - return false; - } - - if (!m_listeners.Remove(pListener)) - { - return false; - } - - if (!SendMessage(eMessage_ChannelUnregister, *pChannel, 0)) - { - return false; - } - - return true; -} - -bool CClient::Send(const char* channelName, const void* pBuffer, size_t length) -{ - CRY_ASSERT(CChannel::IsNameValid(channelName)); - // CRY_ASSERT_MESSAGE(channelLength <= NN_CHANNEL_NAME_LENGTH_MAX, - // "Channel name \"%s\" was passed to a Notification Network method, the name cannot be longer than %d chars.", - // channel, NN_CHANNEL_NAME_LENGTH_MAX); - - if (!CChannel::IsNameValid(channelName)) - { - return false; - } - if (!SendNotification(CChannel(channelName), pBuffer, length)) - { - return false; - } - - return true; -} - -bool CClient::RegisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback) -{ - CryAutoLock lock(m_stConnectionCallbacksLock); - return stl::push_back_unique(m_cNotificationNetworkConnectionCallbacks, pConnectionCallback); -} - -bool CClient::UnregisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback) -{ - CryAutoLock lock(m_stConnectionCallbacksLock); - return stl::find_and_erase(m_cNotificationNetworkConnectionCallbacks, pConnectionCallback); -} - -/* - - CNotificationNetwork::CConnection - -*/ - -CNotificationNetwork::CConnection::CConnection(CNotificationNetwork* pNotificationNetwork, AZSOCKET sock) - : CConnectionBase(pNotificationNetwork) -{ - SetSocket(sock); - m_listeningChannels.reserve(8); -} - -CNotificationNetwork::CConnection::~CConnection() -{ -} - -// - -bool CNotificationNetwork::CConnection::IsListening(const CChannel& channel) -{ - for (size_t i = 0; i < m_listeningChannels.size(); ++i) - { - if (m_listeningChannels[i] == channel) - { - return true; - } - } - - return false; -} - -// CConnectionBase - -bool CNotificationNetwork::CConnection::OnMessage(EMessage eMessage, const CChannel& channel) -{ - switch (eMessage) - { - case eMessage_ChannelRegister: - for (size_t i = 0; i < m_listeningChannels.size(); ++i) - { - if (m_listeningChannels[i] == channel) - { - return true; - } - } - m_listeningChannels.push_back(channel); - return true; - - case eMessage_ChannelUnregister: - for (size_t i = 0; i < m_listeningChannels.size(); ++i) - { - if (m_listeningChannels[i] != channel) - { - continue; - } - - m_listeningChannels[i] = m_listeningChannels.back(); - m_listeningChannels.pop_back(); - return true; - } - return true; - } - - return false; -} - -/* - - CNotificationNetwork::CThread - -*/ - -CNotificationNetwork::CThread::CThread() -{ - m_pNotificationNetwork = nullptr; - m_bRun = true; -} - -CNotificationNetwork::CThread::~CThread() -{ -} - -// - -bool CNotificationNetwork::CThread::Begin(CNotificationNetwork* pNotificationNetwork) -{ - m_pNotificationNetwork = pNotificationNetwork; - Start(-1, (char*)NN_THREAD_NAME); - return true; -} - - -void CNotificationNetwork::CThread::End() -{ - m_bRun = false; - // WaitForThread(); - - // TODO: Should properly close! -} - -// CryRunnable - -void CNotificationNetwork::CThread::Run() -{ - CryThreadSetName(threadID(THREADID_NULL), NN_THREAD_NAME); - while (m_bRun) - { - m_pNotificationNetwork->ProcessSockets(); - } -} - -/* - - CNotificationNetwork - -*/ - -CNotificationNetwork* CNotificationNetwork::Create() -{ - AZ::AzSock::Startup(); - - AZSOCKET sock = AZ::AzSock::Socket(); - if (!AZ::AzSock::IsAzSocketValid(sock)) - { - CryLog("CNotificationNetwork::Create: Failed to create socket.\n"); - return nullptr; - } - - // Disable nagling of small blocks to fight high latency connection - int result = AZ::AzSock::EnableTCPNoDelay(sock, true); - if (AZ::AzSock::SocketErrorOccured(result)) - { - AZ::AzSock::CloseSocket(sock); - CryLog("CNotificationNetworkClient::Create: Failed to set TCP_NODELAY option."); - return nullptr; - } - - result = AZ::AzSock::SetSocketBlockingMode(sock, false); - if (AZ::AzSock::SocketErrorOccured(result)) - { - AZ::AzSock::CloseSocket(sock); - CryLog("CNotificationNetworkClient::Connect: Failed to set socket to asynchronous operation."); - return nullptr; - } - - // Editor uses a different port to avoid conflicts when running both editor and game on same PC - // But allows the lua remote debugger to connect to the editor - unsigned short port = gEnv && gEnv->IsEditor() ? 9433 : 9432; - - AZ::AzSock::AzSocketAddress addr; - addr.SetAddrPort(port); - - result = AZ::AzSock::Bind(sock, addr); - if (AZ::AzSock::SocketErrorOccured(result)) - { - CryLog("CNotificationNetwork::Create: Failed to bind socket.\n"); - AZ::AzSock::CloseSocket(sock); - return nullptr; - } - - result = AZ::AzSock::Listen(sock, 8); - if (AZ::AzSock::SocketErrorOccured(result)) - { - CryLog("CNotificationNetwork::Create: Failed to listen.\n"); - AZ::AzSock::CloseSocket(sock); - return nullptr; - } - - CNotificationNetwork* pNotificationNetwork = new CNotificationNetwork(); - pNotificationNetwork->m_socket = sock; - - pNotificationNetwork->m_thread.Begin(pNotificationNetwork); - - return pNotificationNetwork; -} - -// - -CNotificationNetwork::CNotificationNetwork() -{ - m_socket = AZ_SOCKET_INVALID; - - m_connections.reserve(4); - - m_listeners.Bind("Query", &g_queryNotification); -} - -CNotificationNetwork::~CNotificationNetwork() -{ - m_thread.End(); - m_thread.Stop(); - m_thread.WaitForThread(); - while (!m_connections.empty()) - { - delete m_connections.back(); - m_connections.pop_back(); - } - - if (m_socket != AZ_SOCKET_INVALID) - { - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - } - - AZ::AzSock::Cleanup(); -} - -// - -void CNotificationNetwork::ReleaseClients(CClient* pClient) -{ - // TODO: Use CryAutoLock - LockDebug("Lock %s\n", "CNotificationNetwork::ReleaseClients()"); - m_clientsCriticalSection.Lock(); - for (size_t i = 0; i < m_clients.size(); ++i) - { - if (m_clients[i] != pClient) - { - continue; - } - - m_clients[i] = m_clients.back(); - m_clients.pop_back(); - break; - } - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock %s\n", "CNotificationNetwork::ReleaseClients()"); -} - -void CNotificationNetwork::ProcessSockets() -{ - fd_set read; - FD_ZERO(&read); - AZSOCKET socketMax = 0; - if (m_socket != AZ_SOCKET_INVALID) - { - FD_SET(m_socket, &read); - socketMax = m_socket; - } - for (size_t i = 0; i < m_connections.size(); ++i) - { - if (m_connections[i]->Validate()) - { - AZSOCKET sock = m_connections[i]->GetSocket(); - FD_SET(sock, &read); - - if (socketMax < sock) - { - socketMax = sock; - } - - continue; - } - - // The Connection is invalid, remove it. - CConnection* pConnection = m_connections[i]; - m_connections[i] = m_connections.back(); - m_connections.pop_back(); - delete pConnection; - - // Invalidate the loop increment since we just removed a Connection and - // in the process potentially replaced its slot with an unprocessed one. - --i; - - CryLog("Notification Network Connection terminated, current total: %d\n", - (int)m_connections.size()); - } - - LockDebug("Lock %s\n", "CNotificationNetwork::ProcessSockets()"); - m_clientsCriticalSection.Lock(); - for (size_t i = 0; i < m_clients.size(); ++i) - { - if (!m_clients[i]->Validate()) - { - continue; - } - - AZSOCKET sock = m_clients[i]->GetSocket(); - FD_SET(sock, &read); - - if (socketMax < sock) - { - socketMax = sock; - } - } - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock %s\n", "CNotificationNetwork::ProcessSockets()"); - - AZTIMEVAL timeOut = { 1, 0 }; - int r = AZ::AzSock::Select(socketMax, &read, nullptr, nullptr, &timeOut); - if (r == 0) - { - return; - } - - // When we have no sockets, the select statement will fail and not - // block for even 1 second, as it should... - if (AZ::AzSock::SocketErrorOccured(r)) - { - // So we force the sleep here for now. - Sleep(1000); - return; - } - - for (size_t i = 0; i < m_connections.size(); ++i) - { - if (!FD_ISSET(m_connections[i]->GetSocket(), &read)) - { - continue; - } - - m_connections[i]->Receive(m_listeners); - } - - LockDebug("Lock 2 %s\n", "CNotificationNetwork::ProcessSockets()"); - m_clientsCriticalSection.Lock(); - for (size_t i = 0; i < m_clients.size(); ++i) - { - if (!FD_ISSET(m_clients[i]->GetSocket(), &read)) - { - continue; - } - - m_clients[i]->Receive(); - } - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock 2 %s\n", "CNotificationNetwork::ProcessSockets()"); - - if (m_socket == AZ_SOCKET_INVALID) - { - return; - } - if (!FD_ISSET(m_socket, &read)) - { - return; - } - - AZ::AzSock::AzSocketAddress addr; - AZSOCKET sock = AZ::AzSock::Accept(m_socket, addr); - if (!AZ::AzSock::IsAzSocketValid(sock)) - { - return; - } - - if (!RCON_IsRemoteAllowedToConnect(addr)) - { - AZ::AzSock::CloseSocket(sock); - return; - } - - m_connections.push_back(new CConnection(this, sock)); - - CryLog("Notification Network accepted new Connection, current total: %d\n", - (int)m_connections.size()); -} - -// INotificationNetwork - -INotificationNetworkClient* CNotificationNetwork::CreateClient() -{ - CClient* pClient = CClient::Create(this); - - LockDebug("Lock %s\n", "CNotificationNetwork::CreateClient()"); - m_clientsCriticalSection.Lock(); - m_clients.push_back(pClient); - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock %s\n", "CNotificationNetwork::CreateClient()"); - - return pClient; -} - -INotificationNetworkClient* CNotificationNetwork::Connect(const char* address, uint16 port) -{ - CClient* pClient = CClient::Create(this, address, port); - if (!pClient) - { - return nullptr; - } - - LockDebug("Lock %s\n", "CNotificationNetwork::Connect()"); - m_clientsCriticalSection.Lock(); - m_clients.push_back(pClient); - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock %s\n", "CNotificationNetwork::Connect()"); - - return pClient; -} - -size_t CNotificationNetwork::GetConnectionCount(const char* channelName) -{ - if (!channelName) - { - return m_connections.size(); - } - - if (!CChannel::IsNameValid(channelName)) - { - return 0; - } - - CChannel channel(channelName); - size_t count = 0; - for (size_t i = 0; i < m_connections.size(); ++i) - { - if (!m_connections[i]->IsListening(channel)) - { - continue; - } - - ++count; - } - return count; -} - -bool CNotificationNetwork::ListenerBind(const char* channelName, INotificationNetworkListener* pListener) -{ - if (!CChannel::IsNameValid(channelName)) - { - return false; - } - - return m_listeners.Bind(CChannel(channelName), pListener); -} - -bool CNotificationNetwork::ListenerRemove(INotificationNetworkListener* pListener) -{ - return m_listeners.Remove(pListener); -} - -void CNotificationNetwork::Update() -{ - m_listeners.NotificationsProcess(); - - LockDebug("Lock %s\n", "CNotificationNetwork::Update()"); - m_clientsCriticalSection.Lock(); - for (size_t i = 0; i < m_clients.size(); ++i) - { - m_clients[i]->Update(); - } - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock %s\n", "CNotificationNetwork::Update()"); -} - -uint32 CNotificationNetwork::Send(const char* channelName, const void* pBuffer, size_t length) -{ - if (!CChannel::IsNameValid(channelName)) - { - return 0; - } - - CChannel channel(channelName); - - // TODO: There should be a mutex lock here to ensure thread safety. - - uint32 count = 0; - for (size_t i = 0; i < m_connections.size(); ++i) - { - if (!m_connections[i]->IsListening(channel)) - { - continue; - } - - if (m_connections[i]->SendNotification(channel, pBuffer, length)) - { - ++count; - } - } - - return count; -} diff --git a/Code/CryEngine/CrySystem/NotificationNetwork.h b/Code/CryEngine/CrySystem/NotificationNetwork.h deleted file mode 100644 index ee336dbbb0..0000000000 --- a/Code/CryEngine/CrySystem/NotificationNetwork.h +++ /dev/null @@ -1,293 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_NOTIFICATIONNETWORK_H -#define CRYINCLUDE_CRYSYSTEM_NOTIFICATIONNETWORK_H - -#pragma once - -#include -#include -#include - -#include - -class CNotificationNetwork; -namespace NotificationNetwork { - // Constants - - static const uint32 NN_PACKET_HEADER_LENGTH = 2 * sizeof(uint32) + NN_CHANNEL_NAME_LENGTH_MAX; - - static const uint32 NN_PACKET_HEADER_OFFSET_MESSAGE = 0; - static const uint32 NN_PACKET_HEADER_OFFSET_DATA_LENGTH = sizeof(uint32); - static const uint32 NN_PACKET_HEADER_OFFSET_CHANNEL = sizeof(uint32) + sizeof(uint32); - - static const char* NN_THREAD_NAME = "NotificationNetwork"; - - enum EMessage - { - eMessage_DataTransfer = 0xbada2217, - - eMessage_ChannelRegister = 0xab4eda30, - eMessage_ChannelUnregister = 0xfa4e3423, - }; - - // Classes - - struct CChannel - { - public: - static bool IsNameValid(const char* name); - - public: - CChannel(); - CChannel(const char* name); - ~CChannel(); - - public: - void WriteToPacketHeader(void* pPacket) const; - void ReadFromPacketHeader(void* pPacket); - - public: - bool operator ==(const CChannel& channel) const; - bool operator !=(const CChannel& channel) const; - - private: - char m_name[NN_CHANNEL_NAME_LENGTH_MAX]; - }; - - // TEMP - struct SBuffer - { - uint8* pData; - uint32 length; - CChannel channel; - }; - - class CListeners - { - public: - CListeners(); - ~CListeners(); - - public: - size_t Count() { return m_listeners.size(); } - size_t Count(const CChannel& channel); - - CChannel& Channel(size_t index) { return m_listeners[index].second; } - CChannel* Channel(INotificationNetworkListener* pListener); - - bool Bind(const CChannel& channel, INotificationNetworkListener* pListener); - bool Remove(INotificationNetworkListener* pListener); - - void NotificationPush(const SBuffer& buffer); - void NotificationsProcess(); - - private: - std::vector< std::pair > m_listeners; - - std::queue m_notifications[2]; - std::queue* m_pNotificationWrite; - std::queue* m_pNotificationRead; - CryCriticalSection m_notificationCriticalSection; - }; - - class CConnectionBase - { - public: - CConnectionBase(CNotificationNetwork* pNotificationNetwork); - virtual ~CConnectionBase(); - - public: - AZSOCKET CreateSocket(); - - bool Connect(const char* address, uint16 port); - - AZSOCKET GetSocket() { return m_socket; } - - bool Validate(); - - bool SendNotification(const CChannel& channel, const void* pBuffer, size_t length); - - bool Receive(CListeners& listeners); - - bool GetIsConnectedFlag(); - bool GetIsFailedToConnectFlag() const; - - protected: - CNotificationNetwork* GetNotificationNetwork() { return m_pNotificationNetwork; } - - void SetAddress(const char* address, uint16 port); - void SetSocket(AZSOCKET sock) { m_socket = sock; } - - bool Send(const void* pBuffer, size_t length); - bool SendMessage(EMessage eMessage, const CChannel& channel, uint32 data); - - bool Select_Internal(); - void CloseSocket_Internal(); - - virtual bool OnConnect([[maybe_unused]] bool bConnectionResult) { return true; } - virtual bool OnDisconnect() {return true; } - virtual bool OnMessage([[maybe_unused]] EMessage eMessage, [[maybe_unused]] const CChannel& channel) { return false; } - - private: - bool ReceiveMessage(CListeners& listeners); - bool ReceiveNotification(CListeners& listeners); - - protected: - CNotificationNetwork* m_pNotificationNetwork; - - char m_address[16]; - uint16 m_port; - - AZSOCKET m_socket; - - uint8 m_bufferHeader[NN_PACKET_HEADER_LENGTH]; - SBuffer m_buffer; - uint32 m_dataLeft; - - volatile bool m_boIsConnected; - volatile bool m_boIsFailedToConnect; - }; - - class CClient - : public CConnectionBase - , public INotificationNetworkClient - { - public: - typedef std::vector TDNotificationNetworkConnectionCallbacks; - - static CClient* Create(CNotificationNetwork* pNotificationNetwork, const char* address, uint16 port); - static CClient* Create(CNotificationNetwork* pNotificationNetwork); - - private: - CClient(CNotificationNetwork* pNotificationNetwork); - ~CClient(); - - public: - bool Receive() { return CConnectionBase::Receive(m_listeners); } - - void Update(); - - // CConnectionBase - public: - virtual bool OnConnect(bool bConnectionResult); - virtual bool OnDisconnect(); - virtual bool OnMessage(EMessage eMessage, const CChannel& channel); - - // INotificationNetworkClient - public: - bool Connect(const char* address, uint16 port); - - void Release() { delete this; } - - virtual bool ListenerBind(const char* channelName, INotificationNetworkListener* pListener); - virtual bool ListenerRemove(INotificationNetworkListener* pListener); - - virtual bool Send(const char* channelName, const void* pBuffer, size_t length); - - virtual bool IsConnected() {return CConnectionBase::GetIsConnectedFlag(); } - virtual bool IsFailedToConnect() const{return CConnectionBase::GetIsFailedToConnectFlag(); } - - virtual bool RegisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback); - virtual bool UnregisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback); - private: - CListeners m_listeners; - - TDNotificationNetworkConnectionCallbacks m_cNotificationNetworkConnectionCallbacks; - CryCriticalSection m_stConnectionCallbacksLock; - }; -} // namespace NotificationNetwork -class CNotificationNetwork - : public INotificationNetwork -{ -private: - class CConnection - : public NotificationNetwork::CConnectionBase - { - public: - CConnection(CNotificationNetwork* pNotificationNetwork, AZSOCKET sock); - virtual ~CConnection(); - - public: - bool IsListening(const NotificationNetwork::CChannel& channel); - - // CConnectionBase - protected: - virtual bool OnMessage(NotificationNetwork::EMessage eMessage, const NotificationNetwork::CChannel& channel); - - private: - std::vector m_listeningChannels; - }; - - class CThread - : public CryThread - { - public: - CThread(); - ~CThread(); - - public: - bool Begin(CNotificationNetwork* pNotificationNetwork); - void End(); - - // CryRunnable - public: - virtual void Run(); - - private: - CNotificationNetwork* m_pNotificationNetwork; - bool m_bRun; - } m_thread; - -public: - static CNotificationNetwork* Create(); - -public: - CNotificationNetwork(); - ~CNotificationNetwork(); - -public: - void ReleaseClients(NotificationNetwork::CClient* pClient); - -private: - void ProcessSockets(); - - // INotificationNetwork -public: - virtual void Release() { delete this; } - - virtual INotificationNetworkClient* CreateClient(); - - virtual INotificationNetworkClient* Connect(const char* address, uint16 port); - - virtual size_t GetConnectionCount(const char* channelName); - - virtual void Update(); - - virtual bool ListenerBind(const char* channelName, INotificationNetworkListener* pListener); - virtual bool ListenerRemove(INotificationNetworkListener* pListener); - - virtual uint32 Send(const char* channelName, const void* pBuffer, size_t length); - -private: - AZSOCKET m_socket; - - std::vector m_connections; - std::vector m_clients; - NotificationNetwork::CListeners m_listeners; - - CryCriticalSection m_clientsCriticalSection; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_NOTIFICATIONNETWORK_H diff --git a/Code/CryEngine/CrySystem/ProfileLogSystem.cpp b/Code/CryEngine/CrySystem/ProfileLogSystem.cpp deleted file mode 100644 index 2a86dfc2ef..0000000000 --- a/Code/CryEngine/CrySystem/ProfileLogSystem.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "ProfileLogSystem.h" - -////////////////////////////////////////////////////////////////////////// -// class CLogElement -////////////////////////////////////////////////////////////////////////// - -CLogElement::CLogElement() - : m_pParent (NULL) - , m_time (0) -{ -} - -CLogElement::CLogElement(CLogElement* pParent) - : m_pParent (pParent) - , m_time (0) -{ -} - -CLogElement::CLogElement(CLogElement* pParent, const char* name, const char* message) - : m_pParent (pParent) - , m_strName (name) - , m_strMessage(message) - , m_time (0) -{ -} - -void CLogElement::Flush(stack_string& indent) -{ - if (m_logElements.empty()) - { - CryLog("%s%s [%.3f ms] %s", indent.c_str(), m_strName.c_str(), m_time, m_strMessage.c_str()); - return; - } - - CryLog("%s+%s [%.3f ms] %s", indent.c_str(), m_strName.c_str(), m_time, m_strMessage.c_str()); - - indent += " "; - for (std::list::iterator it = m_logElements.begin(); it != m_logElements.end(); ++it) - { - (*it).Flush(indent); - } - indent.erase(0, 2); - - CryLog("%s-%s", indent.c_str(), m_strName.c_str()); -} - -ILogElement* CLogElement::Log(const char* name, const char* message) -{ - m_logElements.push_back(CLogElement(this)); - m_logElements.back().m_strName = name; - m_logElements.back().m_strMessage = message; - - return &m_logElements.back(); -} - -ILogElement* CLogElement::SetTime(float time) -{ - m_time = time; - - return m_pParent; -} - -void CLogElement::Clear() -{ - m_logElements.resize(0); -} - -////////////////////////////////////////////////////////////////////////// -// class CProfileLogSystem -////////////////////////////////////////////////////////////////////////// - -CProfileLogSystem::CProfileLogSystem() - : m_rootElelent(NULL) - , m_pLastElelent(NULL) -{ -} - -CProfileLogSystem::~CProfileLogSystem() -{ -} - -ILogElement* CProfileLogSystem::Log(const char* name, const char* message) -{ - if (m_pLastElelent) - { - m_pLastElelent = m_pLastElelent->Log(name, message); - } - else - { - m_rootElelent.Clear(); - m_rootElelent.SetName(name); - m_rootElelent.SetMessage(message); - m_pLastElelent = &m_rootElelent; - } - - return m_pLastElelent; -} - -void CProfileLogSystem::SetTime(ILogElement* pElement, float time) -{ - if (pElement == NULL) - { - return; - } - - m_pLastElelent = pElement->SetTime(time); - if (m_pLastElelent) - { - return; - } - - stack_string indent; - m_rootElelent.Flush(indent); - m_rootElelent.Clear(); -} - -void CProfileLogSystem::Release() -{ - delete this; -} diff --git a/Code/CryEngine/CrySystem/ProfileLogSystem.h b/Code/CryEngine/CrySystem/ProfileLogSystem.h deleted file mode 100644 index b54e3067ec..0000000000 --- a/Code/CryEngine/CrySystem/ProfileLogSystem.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Implementation of the IProfileLogSystem interface, which is used to -// save hierarchical log with SHierProfileLogItem - - -#ifndef CRYINCLUDE_CRYSYSTEM_PROFILELOGSYSTEM_H -#define CRYINCLUDE_CRYSYSTEM_PROFILELOGSYSTEM_H - -#pragma once - -#include "ProfileLog.h" - -class CLogElement - : public ILogElement -{ -public: - CLogElement(); - CLogElement(CLogElement* pParent); - CLogElement(CLogElement* pParent, const char* name, const char* message); - - virtual ILogElement* Log (const char* name, const char* message); - virtual ILogElement* SetTime (float time); - virtual void Flush (stack_string& indent); - - void Clear (); - - inline void SetName(const char* name) - { - m_strName = name; - } - - inline void SetMessage(const char* message) - { - m_strMessage = message; - } - -private: - string m_strName; - string m_strMessage; - float m_time; // milliSeconds - - CLogElement* m_pParent; - std::list m_logElements; -}; - -class CProfileLogSystem - : public IProfileLogSystem -{ -public: - CProfileLogSystem(); - ~CProfileLogSystem(); - - virtual ILogElement* Log (const char* name, const char* message); - virtual void SetTime (ILogElement* pElement, float time); - virtual void Release (); - -private: - CLogElement m_rootElelent; - ILogElement* m_pLastElelent; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_PROFILELOGSYSTEM_H diff --git a/Code/CryEngine/CrySystem/ResourceManager.cpp b/Code/CryEngine/CrySystem/ResourceManager.cpp index f78538760f..5e9477a99c 100644 --- a/Code/CryEngine/CrySystem/ResourceManager.cpp +++ b/Code/CryEngine/CrySystem/ResourceManager.cpp @@ -699,7 +699,7 @@ void CResourceManager::OnSystemEvent(ESystemEvent event, [[maybe_unused]] UINT_P if (g_cvars.archiveVars.nLoadCache) { //Load the frontend common mode switch pak, this can considerably reduce the time spent switching especially from disc - if (!gEnv->bMultiplayer && LoadMenuCommonPak(FRONTEND_COMMON_PAK_FILENAME_SP) == false) + if (LoadMenuCommonPak(FRONTEND_COMMON_PAK_FILENAME_SP) == false) { CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "Could not load %s during init. This file can significantly reduce frontend loading times.\n", FRONTEND_COMMON_PAK_FILENAME_SP); } @@ -710,14 +710,7 @@ void CResourceManager::OnSystemEvent(ESystemEvent event, [[maybe_unused]] UINT_P case ESYSTEM_EVENT_LEVEL_LOAD_PREPARE: { - if (!gEnv->bMultiplayer) - { - UnloadMenuCommonPak(FRONTEND_COMMON_PAK_FILENAME_SP, FRONTEND_COMMON_LIST_FILENAME "_sp"); - } - else - { - UnloadMenuCommonPak(FRONTEND_COMMON_PAK_FILENAME_MP, FRONTEND_COMMON_LIST_FILENAME "_mp"); - } + UnloadMenuCommonPak(FRONTEND_COMMON_PAK_FILENAME_SP, FRONTEND_COMMON_LIST_FILENAME "_sp"); m_bLevelTransitioning = !m_sLevelName.empty(); diff --git a/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.cpp b/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.cpp deleted file mode 100644 index 9e141cc5a5..0000000000 --- a/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.cpp +++ /dev/null @@ -1,787 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" - -#ifdef SOFTCODE_SYSTEM_ENABLED - -#ifndef SOFTCODE_ENABLED -// Even if this module isn't built with SC enabled, if the SC system is enabled we define -// it for this compilation unit to ensure we use the correct versions of the IType* interfaces. - #define SOFTCODE_ENABLED -#endif - -#include "SoftCodeMgr.h" -#include -#include -#include -#include // for function<> in find files - -// This should resolve to "GetTypeLibrary" but we export by ordinal to avoid overheads on 360 -// and keep everything consistent. -static const char* DLL_GETTYPELIBRARY = (LPCSTR)1; - -struct CInstanceData -{ - CInstanceData(void* pInstance, size_t memberCount) - : m_pOldInstance(pInstance) - , m_pNewInstance() - { - m_members.resize(memberCount); - } - - ~CInstanceData() - { - // Delete all members - for (TMemberVec::iterator iter(m_members.begin()); - iter != m_members.end(); - ++iter) - { - // TODO: Safe cross module? Same allocator? Use a Destroy() method? - delete *iter; - } - } - - void* Instance() { return m_pOldInstance; } - - void AddMember(size_t index, IExchangeValue& value) - { - // TODO: Add support for members with same name at different hierarchy levels - assert(m_members[index] == NULL); - assert(index != ~0); - - // Support expansion of m_members during while resolving members - if (index >= m_members.size()) - { - m_members.resize(index + 1); - } - - m_members[index] = value.Clone(); - } - - IExchangeValue* GetMember(size_t index) const - { - assert(index < m_members.size()); - return m_members[index]; - } - - void SetNewInstance(void* pNewInstance) { m_pNewInstance = pNewInstance; } - - void* m_pOldInstance; - void* m_pNewInstance; - - typedef std::vector TMemberVec; - TMemberVec m_members; -}; - - -class CExchanger - : public IExchanger -{ -public: - CExchanger() - : m_pInstanceData() - , m_instanceIndex(~0) - , m_state(eState_ResolvingMembers) - {} - - virtual ~CExchanger() - { - DestroyInstanceData(); - } - - virtual bool IsLoading() const { return m_state >= eState_WritingNewMembers; } - virtual size_t InstanceCount() const { return m_instances.size(); } - - virtual bool BeginInstance(void* pInstance) - { - if (IsLoading()) - { - if (++m_instanceIndex < m_instances.size()) - { - m_pInstanceData = m_instances[m_instanceIndex]; - m_pInstanceData->SetNewInstance(pInstance); - } - else - { - m_pInstanceData = NULL; - } - } - else // Reading/resolving members - { - m_instanceIndex = m_instances.size(); - m_pInstanceData = new CInstanceData(pInstance, m_memberMap.size()); - m_instances.push_back(m_pInstanceData); - } - - return m_pInstanceData != NULL; - } - - virtual bool SetValue(const char* name, IExchangeValue& value) - { - assert(!IsLoading()); - - const size_t index = FindMemberIndex(name); - const bool consumingValue = index != ~0; - - if (consumingValue) - { - m_pInstanceData->AddMember(index, value); - } - - return consumingValue; - } - - virtual IExchangeValue* GetValue(const char* name, void* pTarget, size_t targetSize) - { - assert(IsLoading()); - - const size_t index = FindMemberIndex(name); - - // If member resolved (may not be if restoring to old instances) - if (index != ~0) - { - // If member data available (may not be if member is new) - if (IExchangeValue* pValue = m_pInstanceData->GetMember(index)) - { - if (pValue->GetSizeOf() == targetSize) - { - return pValue; - } - else // Member size mismatch - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, - "SoftCode: Member %s of instance %p has changed size (old: %d new: %d), setting to default value.", - name, m_pInstanceData->Instance(), (int)pValue->GetSizeOf(), (int)targetSize); - } - } - else // Member unknown - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, - "SoftCode: Member %s (of instance %p) appears to be new.", - name, m_pInstanceData->Instance()); - - // TODO: Could attempt to validate against a known wipe pattern ie. 0xfefefefe - // This could catch most uninitialized variables... - - if (targetSize <= sizeof(void*)) - { - switch (targetSize) - { - case 1: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "\tLeaving as: %d", *reinterpret_cast(pTarget)); - break; - case 2: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "\tLeaving as: %04x", *reinterpret_cast(pTarget)); - break; - case 4: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "\tLeaving as: %08x", *reinterpret_cast(pTarget)); - break; - case 8: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "\tLeaving as: %llx", *reinterpret_cast(pTarget)); - break; - } - } - } - } - - // Indicate value should be default constructed - return NULL; - } - - // Used once required members have been established, members not already - // encountered will be ignored. - void LockMemberSet() - { - assert(m_state == eState_ResolvingMembers); - - DestroyInstanceData(); - m_state = eState_ReadingOldMembers; - } - - // Rewinds instance data and prepare for loading - void RewindForLoading() - { - assert(m_state == eState_ReadingOldMembers); - - m_pInstanceData = NULL; - m_instanceIndex = ~0; - m_state = eState_WritingNewMembers; - } - - // Rewinds instance data to prepare to restore old members (UNDO) - void RewindForRestore() - { - assert(m_state == eState_WritingNewMembers); - - m_pInstanceData = NULL; - m_instanceIndex = ~0; - m_state = eState_RestoringOldMembers; - } - - void NotifyListenerOfReplacements(ISoftCodeListener* pListener) - { - for (TInstanceVec::const_iterator iter(m_instances.begin()); iter != m_instances.end(); ++iter) - { - CInstanceData* pInstanceData = *iter; - pListener->InstanceReplaced(pInstanceData->m_pOldInstance, pInstanceData->m_pNewInstance); - } - } - -private: - void DestroyInstanceData() - { - m_pInstanceData = NULL; - m_instanceIndex = ~0; - - for (TInstanceVec::iterator iter(m_instances.begin()); iter != m_instances.end(); ++iter) - { - delete *iter; - } - - m_instances.resize(0); - } - - inline size_t FindMemberIndex(const string& memberName) - { - size_t index = ~0; - - // If needed members have been resolved - if (m_state != eState_ResolvingMembers) - { - TMemberMap::const_iterator iter(m_memberMap.find(memberName)); - if (iter != m_memberMap.end()) - { - index = iter->second; - } - } - else // Add this member to the map with a new index - { - // Ensure there's no member name duplicates - assert(m_memberMap.find(memberName) == m_memberMap.end()); - - // A new entry - index = m_memberMap.size(); - size_t& newIndex = m_memberMap[memberName]; - newIndex = index; - } - - return index; - } - -private: - CInstanceData* m_pInstanceData; - size_t m_instanceIndex; - - typedef std::vector TInstanceVec; - TInstanceVec m_instances; - - // Maps instance members to offsets in instance member vectors - typedef std::map TMemberMap; - TMemberMap m_memberMap; - - enum EState - { - eState_ResolvingMembers = 0, // Record new member names as found - eState_ReadingOldMembers, // Scrape requested member data from old instances - eState_WritingNewMembers, // Write old member data to new instances - eState_RestoringOldMembers, // Restore scraped values to old instances (UNDO) - }; - - EState m_state; -}; - - -// ---- - -DynamicTypeLibrary::DynamicTypeLibrary(const char* name) - : m_name(name) - , m_listeners(1) -{} - -const char* DynamicTypeLibrary::GetName() -{ - return m_name; -} - -void* DynamicTypeLibrary::CreateInstanceVoid(const char* typeName) -{ - TTypeMap::const_iterator typeIter(m_types.find(typeName)); - if (typeIter != m_types.end()) - { - ITypeRegistrar* pRegistrar = typeIter->second; - return pRegistrar->CreateInstance(); - } - - return NULL; -} - -void DynamicTypeLibrary::SetOverride(ITypeLibrary* /*pOverrideLib*/) -{ - CryFatalError("Unsupported: Attempting to SetOverride on a DynamicTypeLibrary!"); -} - -size_t DynamicTypeLibrary::GetTypes([[maybe_unused]] ITypeRegistrar** ppRegistrar, [[maybe_unused]] size_t& count) const -{ - CryFatalError("Unsupported: Attempting to GetTypes on a DynamicTypeLibrary!"); - return 0; -} - -void DynamicTypeLibrary::AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName) -{ - // This DynamicTypeLibrary could have been created by this listener request - // So ensure we have a name...! - if (!m_name) - { - m_name = libraryName; - } - - m_listeners.Add(pListener, listenerName); -} - -void DynamicTypeLibrary::RemoveListener(ISoftCodeListener* pListener) -{ - m_listeners.Remove(pListener); -} - -void DynamicTypeLibrary::IntegrateLibrary(ITypeLibrary* pLib, bool isDefault) -{ - typedef std::vector TTypeVec; - - // Resolve our name if we haven't already - if (!m_name) - { - m_name = pLib->GetName(); - } - - // Override the new lib immediately - pLib->SetOverride(this); - - // Query the new library for its types - size_t typeCount = 0; - pLib->GetTypes(NULL, typeCount); - if (typeCount > 0) - { - TTypeVec typeVec; - typeVec.resize(typeCount); - pLib->GetTypes(&(typeVec.front()), typeCount); - - if (!isDefault) - { - CryLogAlways("SoftCode: Integrating %d new types defined in %s...", (int)typeCount, m_name); - } - - // Attempt to integrate each type found - for (TTypeVec::iterator typeIter(typeVec.begin()); typeIter != typeVec.end(); ++typeIter) - { - IntegrateType(*typeIter, isDefault); - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "SoftCode: New %s library has no registered types. Nothing to integrate.", pLib->GetName()); - } -} - -ITypeRegistrar* DynamicTypeLibrary::FindTypeForInstance(void* pInstance) const -{ - for (TTypeMap::const_iterator iter(m_types.begin()); iter != m_types.end(); ++iter) - { - ITypeRegistrar* pType = iter->second; - if (pType->HasInstance(pInstance)) - { - return pType; - } - } - - return NULL; -} - -void DynamicTypeLibrary::IntegrateType(ITypeRegistrar* pType, bool isDefault) -{ - const char* typeName = pType->GetName(); - - // If there's an existing registrar - ITypeRegistrar* pExistingType = m_types[typeName]; - assert(pExistingType != pType); // Sanity check - - // If the new type is the default (built-in) type but it's already been overridden - if (isDefault && pExistingType) - { - return; // Nothing to do - } - // TODO: Inform listeners that there's a new library available - // and ask if we should use it immediately or defer - - CExchanger exchanger; - - // If the type can be safely created, visited and destroyed - if (EvaluateType(pType, exchanger)) - { - // Override the type - m_types[typeName] = pType; - - if (!isDefault) - { - CryLogAlways("SoftCode: Overridden %s in library %s", typeName, m_name); - } - - const size_t instanceCount = (pExistingType) ? pExistingType->InstanceCount() : 0; - - // If there are any existing instances - if (instanceCount > 0) - { - CryLogAlways("SoftCode: Attempting to exchange %d %s instances to the new version...", (int)instanceCount, typeName); - - // Read instance members for type (removes data for resolved members) - if (pExistingType->ExchangeInstances(exchanger)) - { - exchanger.RewindForLoading(); - - // Write instance members for type - if (pType->ExchangeInstances(exchanger)) - { - // Success! Tell the listeners to fix up their pointers - for (TListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) - { - exchanger.NotifyListenerOfReplacements(*notifier); - } - - CryLogAlways("SoftCode: %d %s instances successfully overridden to latest!", (int)instanceCount, typeName); - - // Clean up old instances - if (!pExistingType->DestroyInstances()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "SoftCode: Failed to destroy old instances of type %s - leak probable.", typeName); - } - } - else // Failed to create & write into new instances - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to create and write into new instances of %s. Attempting restore of old instances...", typeName); - if (!pType->DestroyInstances()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "SoftCode: Failed to destroy new instances of type %s - leak probable.", typeName); - } - - // Restore the original type library as the active one - m_types[typeName] = pExistingType; - - // Attempt to restore the old instances with their original data - exchanger.RewindForRestore(); - if (pExistingType->ExchangeInstances(exchanger)) - { - CryLogAlways("SoftCode: Type %s in library %s successfully restored to previous revision!", typeName, m_name); - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Restore of old %s instances failed. State now undefined!", typeName); - } - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to read members on %s", typeName); - } - } - } -} - -bool DynamicTypeLibrary::EvaluateType(ITypeRegistrar* pType, CExchanger& exchanger) -{ - // Try a full object life-time with a single instance of the - // new type before attempting a member exchange. This also allow the - // exchanger to determine the required members to be removed from the - // old instances. - bool testPassed = false; - - // Create a single test instance of the type - if (pType->CreateInstance()) - { - // Read the instance members (also prepares the exchanger member set) - if (pType->ExchangeInstances(exchanger)) - { - // Destroy the old instance - if (pType->DestroyInstances()) - { - // Indicate required members are now resolved - exchanger.LockMemberSet(); - testPassed = true; - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to destroy test instance of type: %s. New type will be skipped.", pType->GetName()); - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to read members in test instance of type: %s. New type will be skipped.", pType->GetName()); - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to create test instance of type: %s. New type will be skipped.", pType->GetName()); - } - - return testPassed; -} - -// ---- - -// The export we expect to find in the SoftCode modules -typedef ITypeLibrary* (__stdcall * TGetTypeLibraryFcn)(); - -static void SoftCode_UpdateCmd([[maybe_unused]] IConsoleCmdArgs* pArgs) -{ - gEnv->pSoftCodeMgr->LoadNewModules(); -} - -static int g_autoUpdatePeriod = 0; - -SoftCodeMgr::SoftCodeMgr() -{ - REGISTER_CVAR2("sc_autoupdate", &g_autoUpdatePeriod, 5, VF_CHEAT, "Set the auto-update poll period for new SoftCode modules. Set to zero to disable"); - REGISTER_COMMAND("sc_update", reinterpret_cast(&SoftCode_UpdateCmd), VF_CHEAT, "Loads any new SoftCode modules"); - - // Clear out any old modules - { - typedef std::vector TStringVec; - TStringVec filePaths; - - if (FindSoftCodeFiles("*", filePaths) > 0) - { - for (TStringVec::const_iterator iter(filePaths.begin()); iter != filePaths.end(); ++iter) - { - if (!DeleteFile(iter->c_str())) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to clean %s", iter->c_str()); - } - } - } - } -} - -SoftCodeMgr::~SoftCodeMgr() -{ - if (gEnv->pConsole) - { - gEnv->pConsole->RemoveCommand("sc_update"); - gEnv->pConsole->UnregisterVariable("sc_autoupdate"); - } -} - -// Used to register built-in libraries on first use -void SoftCodeMgr::RegisterLibrary(ITypeLibrary* pDefaultLib) -{ - DynamicTypeLibrary& typeLib = m_libraryMap[pDefaultLib->GetName()]; - typeLib.IntegrateLibrary(pDefaultLib, true); -} - -// Look for new SoftCode modules and load them, adding their types to the registry -void SoftCodeMgr::LoadNewModules() -{ - typedef std::vector TStringVec; - typedef TStringVec::const_iterator TModuleIter; - TStringVec modulePaths; - - // Find modules - FindSoftCodeFiles("*.dll", modulePaths); - - for (TModuleIter libIter(modulePaths.begin()); libIter != modulePaths.end(); ++libIter) - { - const char* moduleName = libIter->c_str(); - LoadModule(moduleName); - } -} - -void SoftCodeMgr::AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName) -{ - // Find an existing lib or create a new one to add the listener to - DynamicTypeLibrary& lib = m_libraryMap[libraryName]; - lib.AddListener(libraryName, pListener, listenerName); -} - -void SoftCodeMgr::RemoveListener(const char* libraryName, ISoftCodeListener* pListener) -{ - TLibMap::iterator iter(m_libraryMap.find(libraryName)); - - if (iter != m_libraryMap.end()) - { - iter->second.RemoveListener(pListener); - } -} - -// To be called regularly to poll for library updates -void SoftCodeMgr::PollForNewModules() -{ - if (g_autoUpdatePeriod > 0) - { - const CTimeValue frameStartTime(gEnv->pTimer->GetFrameStartTime(ITimer::ETIMER_UI)); - if (m_nextAutoCheckTime <= frameStartTime) - { - m_nextAutoCheckTime.SetSeconds((int64)g_autoUpdatePeriod); - m_nextAutoCheckTime += frameStartTime; - - // Attempt to find and load any new modules - LoadNewModules(); - } - } -} - -namespace -{ - // Util - class InstanceFixup - : public ISoftCodeListener - { - public: - InstanceFixup(void* pOldInstance) - : m_pOldInstance(pOldInstance) - , m_pNewInstance() {} - - virtual void InstanceReplaced(void* pOldInstance, void* pNewInstance) - { - if (m_pOldInstance == pOldInstance) - { - m_pNewInstance = pNewInstance; - } - } - - void* NewInstance() const { return m_pNewInstance; } - - private: - void* m_pOldInstance; - void* m_pNewInstance; - }; -} - -// Stops thread execution until a new SoftCode module is available -void* SoftCodeMgr::WaitForUpdate(void* pInstance) -{ - DynamicTypeLibrary* pOwningLib = NULL; - ITypeRegistrar* pOldType = NULL; - - // Find existing instance - for (TLibMap::iterator libIter(m_libraryMap.begin()); libIter != m_libraryMap.end(); ++libIter) - { - DynamicTypeLibrary& lib = libIter->second; - if (ITypeRegistrar* pType = lib.FindTypeForInstance(pInstance)) - { - pOwningLib = &lib; - pOldType = pType; - break; - } - } - - if (!pOwningLib) - { - CryFatalError("SoftCode: Attempting to wait for update on an unknown instance!"); - return NULL; - } - - InstanceFixup instanceFixup(pInstance); - pOwningLib->AddListener(pOwningLib->GetName(), &instanceFixup, "InstanceFixup"); - - while (true) - { - // Find and load new modules - LoadNewModules(); - - // Got a new instance? - if (instanceFixup.NewInstance()) - { - break; - } - - // Wait for a new module - CryLogAlways("SoftCode: Pausing execution until class %s in %s library is updated...", pOldType->GetName(), pOwningLib->GetName()); - __debugbreak(); // Stopped here? Check your log! - } - - pOwningLib->RemoveListener(&instanceFixup); - - return instanceFixup.NewInstance(); -} - -bool SoftCodeMgr::LoadModule(const char* moduleName) -{ - bool success = false; - - // If module not yet loaded - if (m_loadedSet.find(moduleName) == m_loadedSet.end()) - { - m_loadedSet.insert(moduleName); - - CryLogAlways("SoftCode: Found new module %s, attempting to load...", moduleName); - - HMODULE hModule = CryLoadLibrary(moduleName); - - if (hModule) - { - TGetTypeLibraryFcn pGetTypeLibraryFcn = reinterpret_cast(GetProcAddress(hModule, DLL_GETTYPELIBRARY)); - if (pGetTypeLibraryFcn) - { - // Add to list of loaded libs & override any earlier TypeLibraries already registered - ITypeLibrary* pTypeLibrary = pGetTypeLibraryFcn(); - if (pTypeLibrary) - { - const char* libraryName = pTypeLibrary->GetName(); - m_libraryMap[libraryName].IntegrateLibrary(pTypeLibrary, false); - - CryLogAlways("SoftCode: Loaded new type library \"%s\" from module %s.", libraryName, moduleName); - success = true; - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Failed to resolve GetTypeLibrary() export in: %s (error: %x)", moduleName, GetLastError()); - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Failed to load: %s (error: %x)", moduleName, GetLastError()); - } - } - - return success; -} - -size_t SoftCodeMgr::FindSoftCodeFiles(const string& searchName, std::vector& foundPaths) const -{ - foundPaths.clear(); - - stack_string scSoftCodeDir; - - TCHAR modulePath[MAX_PATH]; - GetModuleFileName(NULL, modulePath, sizeof(modulePath)); - scSoftCodeDir = PathUtil::GetParentDirectory(modulePath); - scSoftCodeDir += "\\SoftCode\\"; - - - gEnv->pFileIO->FindFiles(scSoftCodeDir.c_str(), searchName, [&](const char* filePath) -> bool - { - if (!gEnv->pFileIO->IsDirectory(filePath) && !gEnv->pFileIO->IsReadOnly(filePath)) - { - foundPaths.push_back(filePath); - } - - // Keep asking for more files, no early out - return true; - }); - - // Sort the paths into name order - std::sort(foundPaths.begin(), foundPaths.end()); - - return foundPaths.size(); -} - -#endif // SOFTCODE_ENABLED diff --git a/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.h b/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.h deleted file mode 100644 index f3f1b931a5..0000000000 --- a/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.h +++ /dev/null @@ -1,111 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_SOFTCODE_SOFTCODEMGR_H -#define CRYINCLUDE_CRYSYSTEM_SOFTCODE_SOFTCODEMGR_H -#pragma once - -#include - -#include "ISoftCodeMgr.h" - -struct ITypeLibrary; -struct ITypeRegistrar; -class CExchanger; - -// Internal: Performs the dynamic type management needed for SoftCoding -class DynamicTypeLibrary - : public ITypeLibrary -{ -public: - DynamicTypeLibrary(const char* name = NULL); - - // ITypeLibrary impl. - virtual const char* GetName(); - virtual void* CreateInstanceVoid(const char* typeName); - virtual void SetOverride(ITypeLibrary* pOverrideLib); - virtual size_t GetTypes(ITypeRegistrar** ppRegistrar, size_t& count) const; - - void AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName); - void RemoveListener(ISoftCodeListener* pListener); - - // Attempts to add the library types the active set - void IntegrateLibrary(ITypeLibrary* pLib, bool isDefault); - - ITypeRegistrar* FindTypeForInstance(void* pInstance) const; - -private: - // Attempts to add the type the active set - void IntegrateType(ITypeRegistrar* pType, bool isDefault); - // Ensure the type can be safely created, visited, destroyed and prep exchanger - bool EvaluateType(ITypeRegistrar* pType, CExchanger& exchanger); - -private: - typedef std::vector TLibVec; - typedef std::map TTypeMap; - typedef CListenerSet TListeners; - - // The current set of active types - std::map m_types; - // Current set of loaded libraries - TLibVec m_history; - // Set of listeners to SC changes - TListeners m_listeners; - - const char* m_name; // Supplied by the first real library that registers -}; - - -// Implements the global singleton responsible for SoftCode management -class SoftCodeMgr - : public ISoftCodeMgr -{ -public: - SoftCodeMgr(); - virtual ~SoftCodeMgr(); - - // Used to register built-in libraries on first use - virtual void RegisterLibrary(ITypeLibrary* pLib); - - // Look for new SoftCode modules and load them, adding their types to the registry - virtual void LoadNewModules(); - - virtual void AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName); - virtual void RemoveListener(const char* libraryName, ISoftCodeListener* pListener); - - // To be called regularly to poll for library updates - virtual void PollForNewModules(); - - // Stops thread execution until a new SoftCode module is available - virtual void* WaitForUpdate(void* pInstance); - -private: - bool LoadModule(const char* moduleName); - size_t FindSoftCodeFiles(const string& searchName, std::vector& foundPaths) const; - -private: - typedef std::map TLibMap; - typedef std::set TLoadedLibSet; - - // Records the history for each TypeLibrary keyed by library name - TLibMap m_libraryMap; - - // Records the library files already loaded - TLoadedLibSet m_loadedSet; - - // Used to determine when the next auto-update will occur - CTimeValue m_nextAutoCheckTime; -}; - - -#endif // CRYINCLUDE_CRYSYSTEM_SOFTCODE_SOFTCODEMGR_H diff --git a/Code/CryEngine/CrySystem/System.cpp b/Code/CryEngine/CrySystem/System.cpp index 8a8cf14d91..9016ea99f1 100644 --- a/Code/CryEngine/CrySystem/System.cpp +++ b/Code/CryEngine/CrySystem/System.cpp @@ -124,8 +124,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include #include #include -#include -#include #include #include @@ -133,8 +131,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include #include "XConsole.h" #include "Log.h" -#include "NotificationNetwork.h" -#include "ProfileLog.h" #include "XML/xml.h" #include "XML/ReadWriteXMLSink.h" @@ -148,7 +144,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include "ServerThrottle.h" #include "ResourceManager.h" #include "HMDBus.h" -#include #include "IZLibCompressor.h" #include "IZlibDecompressor.h" @@ -267,22 +262,6 @@ namespace } #endif -#if defined(CVARS_WHITELIST) -struct SCVarsWhitelistConfigSink - : public ILoadConfigurationEntrySink -{ - virtual void OnLoadConfigurationEntry(const char* szKey, const char* szValue, const char* szGroup) - { - ICVarsWhitelist* pCVarsWhitelist = gEnv->pSystem->GetCVarsWhiteList(); - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(szKey, false) : true; - if (whitelisted) - { - gEnv->pConsole->LoadConfigVar(szKey, szValue); - } - } -} g_CVarsWhitelistConfigSink; -#endif // defined(CVARS_WHITELIST) - ///////////////////////////////////////////////////////////////////////////////// // System Implementation. ////////////////////////////////////////////////////////////////////////// @@ -322,27 +301,13 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_env.pSystem = this; m_env.pTimer = &m_Time; m_env.pNameTable = &m_nameTable; - m_env.bServer = false; - m_env.bMultiplayer = false; - m_env.bHostMigrating = false; m_env.bIgnoreAllAsserts = false; m_env.bNoAssertDialog = false; - m_env.bTesting = false; m_env.pSharedEnvironment = pSharedEnvironment; - - m_env.SetFMVIsPlaying(false); - m_env.SetCutsceneIsPlaying(false); - - m_env.szDebugStatus[0] = '\0'; - -#if !defined(CONSOLE) - m_env.SetIsClient(false); -#endif ////////////////////////////////////////////////////////////////////////// m_pStreamEngine = NULL; - m_PhysThread = 0; m_pIFont = NULL; m_pIFontUi = NULL; @@ -370,7 +335,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_pILZ4Decompressor = NULL; m_pIZStdDecompressor = nullptr; m_pLocalizationManager = NULL; - m_sys_physics_CPU = 0; #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_2 #include AZ_RESTRICTED_FILE(System_cpp) @@ -378,15 +342,9 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_sys_min_step = 0; m_sys_max_step = 0; - m_pNotificationNetwork = NULL; - m_cvAIUpdate = NULL; m_pUserCallback = NULL; -#if defined(CVARS_WHITELIST) - m_pCVarsWhitelist = NULL; - m_pCVarsWhitelistConfigSink = &g_CVarsWhitelistConfigSink; -#endif // defined(CVARS_WHITELIST) m_sys_memory_debug = NULL; m_sysWarnings = NULL; m_sysKeyboard = NULL; @@ -409,13 +367,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_bNoCrashDialog = false; m_bNoErrorReportWindow = false; -#ifndef _RELEASE - m_checkpointLoadCount = 0; - m_loadOrigin = eLLO_Unknown; - m_hasJustResumed = false; - m_expectingMapCommand = false; -#endif - m_pCVarQuit = NULL; m_bForceNonDevMode = false; @@ -429,13 +380,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_nServerConfigSpec = CONFIG_VERYHIGH_SPEC; m_nMaxConfigSpec = CONFIG_VERYHIGH_SPEC; - //m_hPhysicsThread = INVALID_HANDLE_VALUE; - //m_hPhysicsActive = INVALID_HANDLE_VALUE; - //m_bStopPhysics = 0; - //m_bPhysicsActive = 0; - - m_pProgressListener = 0; - m_bPaused = false; m_bNoUpdate = false; m_nUpdateCounter = 0; @@ -444,12 +388,9 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_pXMLUtils = new CXmlUtils(this); m_pMemoryManager = CryGetIMemoryManager(); - m_pThreadTaskManager = new CThreadTaskManager; m_pResourceManager = new CResourceManager; m_pTextModeConsole = NULL; - InitThreadSystem(); - g_pPakHeap = new CMTSafeHeap; if (!AZ::AllocatorInstance::IsReady()) @@ -464,7 +405,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) AZ::Debug::Trace::Instance().Init(); } - m_UpdateTimesIdx = 0U; m_bNeedDoWorkDuringOcclusionChecks = false; m_eRuntimeState = ESYSTEM_EVENT_LEVEL_UNLOAD; @@ -478,15 +418,12 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) #endif m_ConfigPlatform = CONFIG_INVALID_PLATFORM; - - AzFramework::Terrain::TerrainDataNotificationBus::Handler::BusConnect(); } ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// CSystem::~CSystem() { - AzFramework::Terrain::TerrainDataNotificationBus::Handler::BusDisconnect(); ShutDown(); #if AZ_LEGACY_CRYSYSTEM_TRAIT_USE_MESSAGE_HANDLER @@ -496,16 +433,8 @@ CSystem::~CSystem() CRY_ASSERT(m_windowMessageHandlers.empty() && "There exists a dangling window message handler somewhere"); SAFE_DELETE(m_pXMLUtils); - SAFE_DELETE(m_pThreadTaskManager); SAFE_DELETE(m_pResourceManager); SAFE_DELETE(m_pSystemEventDispatcher); - // SAFE_DELETE(m_pMemoryManager); - - if (gEnv && gEnv->pThreadManager) - { - gEnv->pThreadManager->UnRegisterThirdPartyThread("Main"); - } - ShutDownThreadSystem(); SAFE_DELETE(g_pPakHeap); @@ -617,8 +546,6 @@ void CSystem::ShutDown() SAFE_DELETE(m_pTextModeConsole); - KillPhysicsThread(); - if (m_sys_firstlaunch) { m_sys_firstlaunch->Set("0"); @@ -664,8 +591,6 @@ void CSystem::ShutDown() gEnv->pLyShine = nullptr; } - SAFE_DELETE(m_env.pResourceCompilerHelper); - SAFE_RELEASE(m_env.pMovieSystem); SAFE_RELEASE(m_env.pLyShine); SAFE_RELEASE(m_env.pCryFont); @@ -706,7 +631,6 @@ void CSystem::ShutDown() SAFE_RELEASE(m_sys_GraphicsQuality); SAFE_RELEASE(m_sys_firstlaunch); SAFE_RELEASE(m_sys_enable_budgetmonitoring); - SAFE_RELEASE(m_sys_physics_CPU); #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_3 @@ -716,9 +640,6 @@ void CSystem::ShutDown() SAFE_RELEASE(m_sys_min_step); SAFE_RELEASE(m_sys_max_step); - SAFE_RELEASE(m_pNotificationNetwork); - - SAFE_DELETE(m_env.pSoftCodeMgr); SAFE_DELETE(m_pDefaultValidator); m_pValidator = nullptr; @@ -743,7 +664,6 @@ void CSystem::ShutDown() SAFE_RELEASE(m_env.pConsole); // Log must be last thing released. - SAFE_RELEASE(m_env.pProfileLogSystem); if (m_env.pLog) { m_env.pLog->FlushAndClose(); @@ -752,10 +672,6 @@ void CSystem::ShutDown() ShutdownFileSystem(); -#if defined(MAP_LOADING_SLICING) - delete gEnv->pSystemScheduler; -#endif // defined(MAP_LOADING_SLICING) - ShutdownModuleLibraries(); EBUS_EVENT(CrySystemEventBus, OnCrySystemPostShutdown); @@ -841,273 +757,6 @@ ISystem* CSystem::GetCrySystem() return this; } -////////////////////////////////////////////////////////////////////////// -// Physics thread task -////////////////////////////////////////////////////////////////////////// -class CPhysicsThreadTask - : public IThreadTask -{ -public: - - CPhysicsThreadTask() - { - m_bStopRequested = 0; - m_bIsActive = 0; - m_stepRequested = 0; - m_bProcessing = 0; - m_doZeroStep = 0; - m_lastStepTimeTaken = 0U; - m_lastWaitTimeTaken = 0U; - } - - ////////////////////////////////////////////////////////////////////////// - // IThreadTask implementation. - ////////////////////////////////////////////////////////////////////////// - virtual void OnUpdate() - { - Run(); - // At the end.. delete the task - delete this; - } - virtual void Stop() - { - Cancel(); - } - virtual SThreadTaskInfo* GetTaskInfo() { return &m_TaskInfo; } - ////////////////////////////////////////////////////////////////////////// - - virtual void Run() - { - m_bStopRequested = 0; - m_bIsActive = 1; - - float step, timeTaken, kSlowdown = 1.0f; - int nSlowFrames = 0; - int64 timeStart; -#ifdef ENABLE_LW_PROFILERS - LARGE_INTEGER stepStart, stepEnd; -#endif - LARGE_INTEGER waitStart, waitEnd; - MarkThisThreadForDebugging("Physics"); - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_5 -#include AZ_RESTRICTED_FILE(System_cpp) -#endif - while (true) - { - QueryPerformanceCounter(&waitStart); - m_FrameEvent.Wait(); // Wait untill new frame - QueryPerformanceCounter(&waitEnd); - m_lastWaitTimeTaken = waitEnd.QuadPart - waitStart.QuadPart; - - if (m_bStopRequested) - { - UnmarkThisThreadFromDebugging(); - return; - } - bool stepped = false; -#ifdef ENABLE_LW_PROFILERS - QueryPerformanceCounter(&stepStart); -#endif - while ((step = m_stepRequested) > 0 || m_doZeroStep) - { - stepped = true; - m_stepRequested = 0; - m_bProcessing = 1; - m_doZeroStep = 0; - - if (kSlowdown != 1.0f) - { - step = max(1, FtoI(step * kSlowdown * 50 - 0.5f)) * 0.02f; - } - timeStart = CryGetTicks(); - timeTaken = gEnv->pTimer->TicksToSeconds(CryGetTicks() - timeStart); - if (timeTaken > step * 0.9f) - { - if (++nSlowFrames > 5) - { - kSlowdown = step * 0.9f / timeTaken; - } - } - else - { - kSlowdown = 1.0f, nSlowFrames = 0; - } - m_bProcessing = 0; - //int timeSleep = (int)((m_timeTarget-gEnv->pTimer->GetAsyncTime()).GetMilliSeconds()*0.9f); - //Sleep(max(0,timeSleep)); - } - if (!stepped) - { - Sleep(0); - } - m_FrameDone.Set(); -#ifdef ENABLE_LW_PROFILERS - QueryPerformanceCounter(&stepEnd); - m_lastStepTimeTaken = stepEnd.QuadPart - stepStart.QuadPart; -#endif - } - } - virtual void Cancel() - { - Pause(); - m_bStopRequested = 1; - m_FrameEvent.Set(); - m_bIsActive = 0; - } - - int Pause() - { - if (m_bIsActive) - { - AZ_PROFILE_FUNCTION_STALL(AZ::Debug::ProfileCategory::System); - m_bIsActive = 0; - while (m_bProcessing) - { - ; - } - return 1; - } - return 0; - } - int Resume() - { - if (!m_bIsActive) - { - m_bIsActive = 1; - return 1; - } - return 0; - } - int IsActive() { return m_bIsActive; } - int RequestStep(float dt) - { - if (m_bIsActive && dt > FLT_EPSILON) - { - m_stepRequested += dt; - if (dt <= 0.0f) - { - m_doZeroStep = 1; - } - m_FrameEvent.Set(); - } - - return m_bProcessing; - } - float GetRequestedStep() { return m_stepRequested; } - - uint64 LastStepTaken() const - { - return m_lastStepTimeTaken; - } - - uint64 LastWaitTime() const - { - return m_lastWaitTimeTaken; - } - - void EnsureStepDone() - { - FRAME_PROFILER("SysUpdate:PhysicsEnsureDone", gEnv->pSystem, PROFILE_SYSTEM); - if (m_bIsActive) - { - while (m_stepRequested > 0.0f || m_bProcessing) - { - m_FrameDone.Wait(); - } - } - } - -protected: - - volatile int m_bStopRequested; - volatile int m_bIsActive; - volatile float m_stepRequested; - volatile int m_bProcessing; - volatile int m_doZeroStep; - volatile uint64 m_lastStepTimeTaken; - volatile uint64 m_lastWaitTimeTaken; - - CryEvent m_FrameEvent; - CryEvent m_FrameDone; - - SThreadTaskInfo m_TaskInfo; -}; - -void CSystem::CreatePhysicsThread() -{ - if (!m_PhysThread) - { - ////////////////////////////////////////////////////////////////////////// - SThreadTaskParams threadParams; - threadParams.name = "Physics"; - threadParams.nFlags = THREAD_TASK_BLOCKING; - threadParams.nStackSizeKB = PHYSICS_STACK_SIZE >> 10; -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_6 -#include AZ_RESTRICTED_FILE(System_cpp) -#endif - - { - m_PhysThread = new CPhysicsThreadTask; - GetIThreadTaskManager()->RegisterTask(m_PhysThread, threadParams); - } - } - -} - -void CSystem::KillPhysicsThread() -{ - if (m_PhysThread) - { - GetIThreadTaskManager()->UnregisterTask(m_PhysThread); - m_PhysThread = 0; - } -} - -/////////////////////////////////////////////////////////////////////////// -// AzFramework::Terrain::TerrainDataNotificationBus START -void CSystem::OnTerrainDataCreateBegin() -{ - KillPhysicsThread(); -} - -void CSystem::OnTerrainDataDestroyBegin() -{ - OnTerrainDataCreateBegin(); -} - -// AzFramework::Terrain::TerrainDataNotificationBus END -/////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -int CSystem::SetThreadState(ESubsystem subsys, bool bActive) -{ - switch (subsys) - { - case ESubsys_Physics: - { - if (m_PhysThread) - { - return bActive ? ((CPhysicsThreadTask*)m_PhysThread)->Resume() : ((CPhysicsThreadTask*)m_PhysThread)->Pause(); - } - } - break; - } - return 0; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::SleepIfInactive() -{ - // ProcessSleep() - if (m_bDedicatedServer || m_bEditor || gEnv->bMultiplayer) - { - return; - } -} - ////////////////////////////////////////////////////////////////////////// void CSystem::SleepIfNeeded() { @@ -1180,11 +829,7 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) // do the dedicated sleep earlier than the frame profiler to avoid having it counted if (gEnv->IsDedicated()) { -#if defined(MAP_LOADING_SLICING) - gEnv->pSystemScheduler->SchedulingSleepIfNeeded(); -#else SleepIfNeeded(); -#endif // defined(MAP_LOADING_SLICING) } #endif //EXCLUDE_UPDATE_ON_CONSOLE @@ -1199,9 +844,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) m_nUpdateCounter++; #ifndef EXCLUDE_UPDATE_ON_CONSOLE - // Check if game needs to be sleeping when not active. - SleepIfInactive(); - if (m_pUserCallback) { m_pUserCallback->OnUpdate(); @@ -1216,7 +858,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) prev_sys_float_exceptions = g_cvars.sys_float_exceptions; EnableFloatExceptions(g_cvars.sys_float_exceptions); - UpdateFPExceptionsMaskForThreads(); } #endif //EXCLUDE_UPDATE_ON_CONSOLE ////////////////////////////////////////////////////////////////////////// @@ -1263,13 +904,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) } #endif //PROFILE_WITH_VTUNE -#ifdef SOFTCODE_SYSTEM_ENABLED - if (m_env.pSoftCodeMgr) - { - m_env.pSoftCodeMgr->PollForNewModules(); - } -#endif - if (m_pStreamEngine) { FRAME_PROFILER("StreamEngine::Update()", this, PROFILE_SYSTEM); @@ -1290,7 +924,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) if (m_sysNoUpdate && m_sysNoUpdate->GetIVal()) { bNoUpdate = true; - updateFlags = ESYSUPDATE_IGNORE_PHYSICS; } m_bNoUpdate = bNoUpdate; @@ -1373,16 +1006,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) return false; } -#ifndef EXCLUDE_UPDATE_ON_CONSOLE - - ////////////////////////////////////////////////////////////////////// - //update notification network system - if (m_pNotificationNetwork) - { - FRAME_PROFILER("SysUpdate:NotificationNetwork", this, PROFILE_SYSTEM); - m_pNotificationNetwork->Update(); - } -#endif //EXCLUDE_UPDATE_ON_CONSOLE ////////////////////////////////////////////////////////////////////// //update sound system Part 1 if in Editor / in Game Mode Viewsystem updates the Listeners if (!m_env.IsEditorGameMode()) @@ -1401,15 +1024,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) } } - ////////////////////////////////////////////////////////////////////////// - // Update Threads Task Manager. - ////////////////////////////////////////////////////////////////////////// - if (m_pThreadTaskManager) - { - FRAME_PROFILER("SysUpdate:ThreadTaskManager", this, PROFILE_SYSTEM); - m_pThreadTaskManager->OnUpdate(); - } - ////////////////////////////////////////////////////////////////////////// // Update Resource Manager. ////////////////////////////////////////////////////////////////////////// @@ -1418,77 +1032,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) m_pResourceManager->Update(); } - ////////////////////////////////////////////////////////////////////// - // update physic system - //static float time_zero = 0; - if (m_sys_physics_CPU->GetIVal() > 0 && !gEnv->IsDedicated()) - { - CreatePhysicsThread(); - } - else - { - KillPhysicsThread(); - } - - static int g_iPausedPhys = 0; - - CPhysicsThreadTask* pPhysicsThreadTask = ((CPhysicsThreadTask*)m_PhysThread); - if (!pPhysicsThreadTask) - { - FRAME_PROFILER_LEGACYONLY("SysUpdate:AllAIAndPhysics", this, PROFILE_SYSTEM); - AZ_TRACE_METHOD_NAME("SysUpdate::AllAIAndPhysics"); - - ////////////////////////////////////////////////////////////////////// - // update entity system (a little bit) before physics - if (nPauseMode != 1) - { - if (!bNoUpdate) - { - EBUS_EVENT(CrySystemEventBus, OnCrySystemPrePhysicsUpdate); - } - } - - // intermingle physics/AI updates so that if we get a big timestep (frame rate glitch etc) the - // AI gets to steer entities before they travel over cliffs etc. - const float maxTimeStep = 0.25f; - int maxSteps = 1; - //float fCurTime = m_Time.GetCurrTime(); - float timeToDo = m_Time.GetFrameTime();//fCurTime - fPrevTime; - if (m_env.bMultiplayer) - { - timeToDo = m_Time.GetRealFrameTime(); - } - - - - while (timeToDo > 0.0001f && maxSteps-- > 0) - { - float thisStep = min(maxTimeStep, timeToDo); - timeToDo -= thisStep; - - - EBUS_EVENT(CrySystemEventBus, OnCrySystemPostPhysicsUpdate); - } - - } - else - { - - // In multithreaded physics mode, post physics fires after physics events are dispatched on the main thread. - EBUS_EVENT(CrySystemEventBus, OnCrySystemPostPhysicsUpdate); - - ////////////////////////////////////////////////////////////////////// - // update entity system (a little bit) before physics - if (nPauseMode != 1) - { - if (!bNoUpdate) - { - EBUS_EVENT(CrySystemEventBus, OnCrySystemPrePhysicsUpdate); - } - } - - } - // Use UI timer for CryMovie, because it should not be affected by pausing game time const float fMovieFrameTime = m_Time.GetFrameTime(ITimer::ETIMER_UI); @@ -1550,8 +1093,6 @@ bool CSystem::UpdatePostTickBus(int updateFlags, int /*nPauseMode*/) m_updateTimes.push_back(std::make_pair(cur_time, updateTime)); } - UpdateUpdateTimes(); - { FRAME_PROFILER("SysUpdate - SystemEventDispatcher::Update", this, PROFILE_SYSTEM); m_pSystemEventDispatcher->Update(); @@ -1890,12 +1431,6 @@ ILocalizationManager* CSystem::GetLocalizationManager() return m_pLocalizationManager; } -////////////////////////////////////////////////////////////////////////// -IThreadTaskManager* CSystem::GetIThreadTaskManager() -{ - return m_pThreadTaskManager; -} - ////////////////////////////////////////////////////////////////////////// IResourceManager* CSystem::GetIResourceManager() { @@ -1960,10 +1495,6 @@ void CSystem::ExecuteCommandLine(bool deferred) if (pCmd->GetType() == eCLAT_Post) { string sLine = pCmd->GetName(); - -#if defined(CVARS_WHITELIST) - if (!GetCVarsWhiteList() || GetCVarsWhiteList()->IsWhiteListed(sLine, false)) -#endif { if (pCmd->GetValue()) { @@ -1973,12 +1504,6 @@ void CSystem::ExecuteCommandLine(bool deferred) GetILog()->Log("Executing command from command line: \n%s\n", sLine.c_str()); // - the actual command might be executed much later (e.g. level load pause) GetIConsole()->ExecuteString(sLine.c_str(), false, deferred); } -#if defined(CVARS_WHITELIST) - else if (gEnv->IsDedicated()) - { - GetILog()->LogError("Failed to execute command: '%s' as it is not whitelisted\n", sLine.c_str()); - } -#endif } } @@ -2078,93 +1603,6 @@ void CProfilingSystem::VTunePause() #endif } -////////////////////////////////////////////////////////////////////////// -sUpdateTimes& CSystem::GetCurrentUpdateTimeStats() -{ - return m_UpdateTimes[m_UpdateTimesIdx]; -} - -////////////////////////////////////////////////////////////////////////// -const sUpdateTimes* CSystem::GetUpdateTimeStats(uint32& index, uint32& num) -{ - index = m_UpdateTimesIdx; - num = NUM_UPDATE_TIMES; - return m_UpdateTimes; -} - -void CSystem::UpdateUpdateTimes() -{ - sUpdateTimes& sample = m_UpdateTimes[m_UpdateTimesIdx]; - if (m_PhysThread) - { - static uint64 lastPhysTime = 0U; - static uint64 lastMainTime = 0U; - static uint64 lastYields = 0U; - static uint64 lastPhysWait = 0U; - uint64 physTime = 0, mainTime = 0; - uint32 yields = 0; - physTime = ((CPhysicsThreadTask*)m_PhysThread)->LastStepTaken(); - mainTime = CryGetTicks() - lastMainTime; - lastMainTime = mainTime; - lastPhysWait = ((CPhysicsThreadTask*)m_PhysThread)->LastWaitTime(); - sample.PhysStepTime = physTime; - sample.SysUpdateTime = mainTime; - sample.PhysYields = yields; - sample.physWaitTime = lastPhysWait; - } - ++m_UpdateTimesIdx; - if (m_UpdateTimesIdx >= NUM_UPDATE_TIMES) - { - m_UpdateTimesIdx = 0; - } -} - - -#ifndef _RELEASE -void CSystem::GetCheckpointData(ICheckpointData& data) -{ - data.m_totalLoads = m_checkpointLoadCount; - data.m_loadOrigin = m_loadOrigin; -} - -void CSystem::IncreaseCheckpointLoadCount() -{ - if (!m_hasJustResumed) - { - ++m_checkpointLoadCount; - } - - m_hasJustResumed = false; -} - -void CSystem::SetLoadOrigin(LevelLoadOrigin origin) -{ - switch (origin) - { - case eLLO_NewLevel: // Intentional fall through - case eLLO_Level2Level: - m_expectingMapCommand = true; - break; - - case eLLO_Resumed: - m_hasJustResumed = true; - break; - - case eLLO_MapCmd: - if (m_expectingMapCommand) - { - // We knew a map command was coming, so don't process this. - m_expectingMapCommand = false; - return; - } - break; - } - - m_loadOrigin = origin; - m_checkpointLoadCount = 0; -} -#endif - bool CSystem::SteamInit() { #if USE_STEAM diff --git a/Code/CryEngine/CrySystem/System.h b/Code/CryEngine/CrySystem/System.h index c4f3bfabd6..e27dfe4866 100644 --- a/Code/CryEngine/CrySystem/System.h +++ b/Code/CryEngine/CrySystem/System.h @@ -26,14 +26,12 @@ #include "MTSafeAllocator.h" #include "CPUDetect.h" #include -#include "ThreadTask.h" #include "RenderBus.h" #include #include #include -#include namespace AzFramework { @@ -44,7 +42,6 @@ struct IConsoleCmdArgs; class CServerThrottle; struct IZLibCompressor; class CWatchdogThread; -class CThreadManager; #if defined(AZ_RESTRICTED_PLATFORM) #undef AZ_RESTRICTED_SECTION @@ -183,8 +180,6 @@ class CThreadManager; #include "CryLibrary.h" #endif -#define NUM_UPDATE_TIMES (128U) - #ifdef WIN32 typedef void* WIN_HMODULE; #else @@ -241,7 +236,6 @@ struct SSystemCVars int sys_WER; int sys_dump_type; int sys_ai; - int sys_physics; int sys_entitysystem; int sys_trackview; int sys_vtune; @@ -342,7 +336,6 @@ class CSystem , public IWindowMessageHandler , public AZ::RenderNotificationsBus::Handler , public CrySystemRequestBus::Handler - , private AzFramework::Terrain::TerrainDataNotificationBus::Handler { public: @@ -397,20 +390,8 @@ public: ISystem* GetCrySystem() override; //////////////////////////////////////////////////////////////////////// - //! Update screen during loading. - void UpdateLoadingScreen(); - - //! Update screen and call some important tick functions during loading. - void SynchronousLoadingTick(const char* pFunc, int line); - uint32 GetUsedMemory(); -#ifndef _RELEASE - virtual void GetCheckpointData(ICheckpointData& data); - virtual void IncreaseCheckpointLoadCount(); - virtual void SetLoadOrigin(LevelLoadOrigin origin); -#endif - virtual bool SteamInit(); void Relaunch(bool bRelaunch); @@ -425,8 +406,6 @@ public: virtual const char* GetUserName(); virtual int GetApplicationInstance(); int GetApplicationLogInstance(const char* logFilePath) override; - virtual sUpdateTimes& GetCurrentUpdateTimeStats(); - virtual const sUpdateTimes* GetUpdateTimeStats(uint32&, uint32&); ITimer* GetITimer(){ return m_env.pTimer; } AZ::IO::IArchive* GetIPak() { return m_env.pCryPak; }; @@ -434,7 +413,6 @@ public: IRemoteConsole* GetIRemoteConsole(); IMovieSystem* GetIMovieSystem() { return m_env.pMovieSystem; }; IMemoryManager* GetIMemoryManager(){ return m_pMemoryManager; } - IThreadManager* GetIThreadManager() override {return m_env.pThreadManager; } ICryFont* GetICryFont(){ return m_env.pCryFont; } ILog* GetILog(){ return m_env.pLog; } ICmdLine* GetICmdLine(){ return m_pCmdLine; } @@ -444,11 +422,8 @@ public: IViewSystem* GetIViewSystem(); ILevelSystem* GetILevelSystem(); ISystemEventDispatcher* GetISystemEventDispatcher() { return m_pSystemEventDispatcher; } - IThreadTaskManager* GetIThreadTaskManager(); IResourceManager* GetIResourceManager(); ITextModeConsole* GetITextModeConsole(); - IVisualLog* GetIVisualLog() { return m_env.pVisualLog; } - INotificationNetwork* GetINotificationNetwork() { return m_pNotificationNetwork; } IProfilingSystem* GetIProfilingSystem() { return &m_ProfilingSystem; } IZLibCompressor* GetIZLibCompressor() { return m_pIZLibCompressor; } IZLibDecompressor* GetIZLibDecompressor() { return m_pIZLibDecompressor; } @@ -459,19 +434,6 @@ public: CPNoise3* GetNoiseGen(); virtual uint64 GetUpdateCounter() { return m_nUpdateCounter; }; - virtual void SetLoadingProgressListener(ILoadingProgressListener* pLoadingProgressListener) - { - m_pProgressListener = pLoadingProgressListener; - }; - - virtual ILoadingProgressListener* GetLoadingProgressListener() const - { - return m_pProgressListener; - }; - - void SetIMaterialEffects(IMaterialEffects* pMaterialEffects) { m_env.pMaterialEffects = pMaterialEffects; } - void SetIOpticsManager(IOpticsManager* pOpticsManager) { m_env.pOpticsManager = pOpticsManager; } - void SetIVisualLog(IVisualLog* pVisualLog) { m_env.pVisualLog = pVisualLog; } void DetectGameFolderAccessRights(); virtual void ExecuteCommandLine(bool deferred=true); @@ -554,12 +516,6 @@ public: //! Return pointer to user defined callback. ISystemUserCallback* GetUserCallback() const { return m_pUserCallback; }; -#if defined(CVARS_WHITELIST) - virtual ICVarsWhitelist* GetCVarsWhiteList() const { return m_pCVarsWhitelist; }; - virtual ILoadConfigurationEntrySink* GetCVarsWhiteListConfigSink() const { return m_pCVarsWhitelistConfigSink; } -#else - virtual ILoadConfigurationEntrySink* GetCVarsWhiteListConfigSink() const { return nullptr; } -#endif // defined(CVARS_WHITELIST) ////////////////////////////////////////////////////////////////////////// virtual void SaveConfiguration(); @@ -571,7 +527,6 @@ public: virtual void SetConfigPlatform(ESystemConfigPlatform platform); ////////////////////////////////////////////////////////////////////////// - virtual int SetThreadState(ESubsystem subsys, bool bActive); virtual bool IsPaused() const { return m_bPaused; }; virtual ILocalizationManager* GetLocalizationManager(); @@ -608,8 +563,6 @@ private: // Release all resources. void ShutDown(); - void SleepIfInactive(); - bool LoadEngineDLLs(); //! @name Initialization routines @@ -623,12 +576,6 @@ private: //@} - ////////////////////////////////////////////////////////////////////////// - // Threading functions. - ////////////////////////////////////////////////////////////////////////// - void InitThreadSystem(); - void ShutDownThreadSystem(); - ////////////////////////////////////////////////////////////////////////// // Helper functions. ////////////////////////////////////////////////////////////////////////// @@ -645,9 +592,6 @@ private: void LogBuildInfo(); void SetDevMode(bool bEnable); - void CreatePhysicsThread(); - void KillPhysicsThread(); - #ifndef _RELEASE static void SystemVersionChanged(ICVar* pCVar); #endif // #ifndef _RELEASE @@ -676,7 +620,6 @@ public: virtual bool GetForceNonDevMode() const; virtual bool WasInDevMode() const { return m_bWasInDevMode; }; virtual bool IsDevMode() const { return m_bInDevMode && !GetForceNonDevMode(); } - virtual bool IsMinimalMode() const { return m_bMinimal; } virtual bool IsMODValid(const char* szMODName) const { if (!szMODName || strstr(szMODName, ".") || strstr(szMODName, "\\")) @@ -727,7 +670,6 @@ private: // ------------------------------------------------------ bool m_bRelaunch; //!< relaunching the app or not (true beforerelaunch) int m_iLoadingMode; //!< Game is loading w/o changing context (0 not, 1 quickloading, 2 full loading) bool m_bTestMode; //!< If running in testing mode. - bool m_bMinimal; //!< If running in 'minimal mode'. bool m_bEditor; //!< If running in Editor. bool m_bNoCrashDialog; bool m_bNoErrorReportWindow; @@ -742,16 +684,6 @@ private: // ------------------------------------------------------ SDefaultValidator* m_pDefaultValidator; //!< CCpuFeatures* m_pCpu; //!< CPU features int m_ttMemStatSS; //!< Time to memstat screenshot - string m_szCmdLine; - - int m_iTraceAllocations; - -#ifndef _RELEASE - int m_checkpointLoadCount;// Total times game has loaded from a checkpoint - LevelLoadOrigin m_loadOrigin; // Where the load was initiated from - bool m_hasJustResumed; // Has resume game just been called - bool m_expectingMapCommand; -#endif bool m_bDrawConsole; //!< Set to true if OK to draw the console. bool m_bDrawUI; //!< Set to true if OK to draw UI. @@ -867,8 +799,6 @@ private: // ------------------------------------------------------ ICVar* m_sys_asset_processor; ICVar* m_sys_load_files_to_memory; - ICVar* m_sys_physics_CPU; - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION SYSTEM_H_SECTION_4 #include AZ_RESTRICTED_FILE(System_h) @@ -891,15 +821,6 @@ private: // ------------------------------------------------------ //! User define callback for system events. ISystemUserCallback* m_pUserCallback; -#if defined(CVARS_WHITELIST) - ////////////////////////////////////////////////////////////////////////// - //! User define callback for whitelisting cvars - ICVarsWhitelist* m_pCVarsWhitelist; - ILoadConfigurationEntrySink* m_pCVarsWhitelistConfigSink; -#endif // defined(CVARS_WHITELIST) - - //int m_nCurrentLogVerbosity; - SFileVersion m_fileVersion; SFileVersion m_productVersion; SFileVersion m_buildVersion; @@ -910,8 +831,6 @@ private: // ------------------------------------------------------ // Name table. CNameTable m_nameTable; - IThreadTask* m_PhysThread; - ESystemConfigSpec m_nServerConfigSpec; ESystemConfigSpec m_nMaxConfigSpec; ESystemConfigPlatform m_ConfigPlatform; @@ -919,8 +838,6 @@ private: // ------------------------------------------------------ std::unique_ptr m_pServerThrottle; CProfilingSystem m_ProfilingSystem; - sUpdateTimes m_UpdateTimes[NUM_UPDATE_TIMES]; - uint32 m_UpdateTimesIdx; // Pause mode. bool m_bPaused; @@ -991,26 +908,14 @@ private: ESystemGlobalState m_systemGlobalState; static const char* GetSystemGlobalStateName(const ESystemGlobalState systemGlobalState); - /////////////////////////////////////////////////////////////////////////// - // AzFramework::Terrain::TerrainDataNotificationBus START - void OnTerrainDataCreateBegin() override; - void OnTerrainDataDestroyBegin() override; - // AzFramework::Terrain::TerrainDataNotificationBus END - /////////////////////////////////////////////////////////////////////////// - public: void InitLocalization(); - void UpdateUpdateTimes(); protected: // ------------------------------------------------------------- - ILoadingProgressListener* m_pProgressListener; CCmdLine* m_pCmdLine; - CThreadManager* m_pThreadManager; - CThreadTaskManager* m_pThreadTaskManager; class CResourceManager* m_pResourceManager; ITextModeConsole* m_pTextModeConsole; - INotificationNetwork* m_pNotificationNetwork; string m_currentLanguageAudio; string m_systemConfigName; // computed from system_(hardwareplatform)_(assetsPlatform) - eg, system_android_es3.cfg or system_android_opengl.cfg or system_windows_pc.cfg diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 8bf2fb8930..48cb5e0d9e 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -35,13 +35,9 @@ #define SYSTEMINIT_CPP_SECTION_17 17 #endif -#if defined(MAP_LOADING_SLICING) -#include "SystemScheduler.h" -#endif // defined(MAP_LOADING_SLICING) #include "CryLibrary.h" #include "CryPath.h" #include -#include #include #include @@ -103,16 +99,12 @@ #include "PhysRenderer.h" #include "LocalizedStringManager.h" #include "SystemEventDispatcher.h" -#include "ThreadConfigManager.h" #include "Validator.h" #include "ServerThrottle.h" #include "SystemCFG.h" #include "AutoDetectSpec.h" #include "ResourceManager.h" #include "MTSafeAllocator.h" -#include "NotificationNetwork.h" -#include "ProfileLogSystem.h" -#include "SoftCode/SoftCodeMgr.h" #include "ZLibCompressor.h" #include "ZLibDecompressor.h" #include "ZStdDecompressor.h" @@ -146,8 +138,6 @@ #include "MobileDetectSpec.h" #endif -#include "IDebugCallStack.h" - #include "WindowsConsole.h" #if defined(EXTERNAL_CRASH_REPORTING) @@ -163,11 +153,6 @@ # include #endif -// if we enable the built-in local version instead of remote: -#if defined(CRY_ENABLE_RC_HELPER) -#include "ResourceCompilerHelper.h" -#endif - #ifdef WIN32 extern LONG WINAPI CryEngineExceptionFilterWER(struct _EXCEPTION_POINTERS* pExceptionPointers); #endif @@ -400,26 +385,20 @@ struct SysSpecOverrideSink } else { - // This could bypass the restricted/whitelisted cvar checks that exist elsewhere depending on + // This could bypass the restricted cvar checks that exist elsewhere depending on // the calling code so we also need check here before setting. bool isConst = pCvar->IsConstCVar(); bool isCheat = ((pCvar->GetFlags() & (VF_CHEAT | VF_CHEAT_NOCHECK | VF_CHEAT_ALWAYS_CHECK)) != 0); bool isReadOnly = ((pCvar->GetFlags() & VF_READONLY) != 0); bool isDeprecated = ((pCvar->GetFlags() & VF_DEPRECATED) != 0); bool allowApplyCvar = true; - bool whitelisted = true; - -#if defined CVARS_WHITELIST - ICVarsWhitelist* cvarWhitelist = gEnv->pSystem->GetCVarsWhiteList(); - whitelisted = cvarWhitelist ? cvarWhitelist->IsWhiteListed(szKey, true) : true; -#endif if ((isConst || isCheat || isReadOnly) || isDeprecated) { allowApplyCvar = !isDeprecated && (gEnv->pSystem->IsDevMode()) || (gEnv->IsEditor()); } - if ((allowApplyCvar && whitelisted) || ALLOW_CONST_CVAR_MODIFICATIONS) + if ((allowApplyCvar) || ALLOW_CONST_CVAR_MODIFICATIONS) { applyCvar = true; } @@ -1028,7 +1007,6 @@ bool CSystem::InitFileSystem() // get the DirectInstance FileIOBase which should be the AZ::LocalFileIO m_env.pFileIO = AZ::IO::FileIOBase::GetDirectInstance(); - m_env.pResourceCompilerHelper = nullptr; m_env.pCryPak = AZ::Interface::Get(); m_env.pFileIO = AZ::IO::FileIOBase::GetInstance(); @@ -1107,8 +1085,7 @@ bool CSystem::InitFileSystem_LoadEngineFolders(const SSystemInitParams&) { LOADING_TIME_PROFILE_SECTION; { - ILoadConfigurationEntrySink* pCVarsWhiteListConfigSink = GetCVarsWhiteListConfigSink(); - LoadConfiguration(m_systemConfigName.c_str(), pCVarsWhiteListConfigSink); + LoadConfiguration(m_systemConfigName.c_str()); AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "Loading system configuration from %s...", m_systemConfigName.c_str()); } @@ -1118,13 +1095,6 @@ bool CSystem::InitFileSystem_LoadEngineFolders(const SSystemInitParams&) GetISystem()->SetConfigPlatform(GetDevicePlatform()); -#if defined(CRY_ENABLE_RC_HELPER) - if (!m_env.pResourceCompilerHelper) - { - m_env.pResourceCompilerHelper = new CResourceCompilerHelper(); - } -#endif - auto projectPath = AZ::Utils::GetProjectPath(); AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "Project Path: %s\n", projectPath.empty() ? "None specified" : projectPath.c_str()); @@ -1179,7 +1149,6 @@ bool CSystem::InitAudioSystem(const SSystemInitParams& initParams) bool useRealAudioSystem = false; if (!initParams.bPreview - && !initParams.bMinimal && !m_bDedicatedServer && m_sys_audio_disable->GetIVal() == 0) { @@ -1672,12 +1641,8 @@ bool CSystem::Init(const SSystemInitParams& startupParams) gEnv->mMainThreadId = GetCurrentThreadId(); //Set this ASAP on startup InlineInitializationProcessing("CSystem::Init start"); - m_szCmdLine = startupParams.szSystemCmdLine; - m_env.szCmdLine = m_szCmdLine.c_str(); - m_env.bTesting = startupParams.bTesting; - m_env.bNoAssertDialog = startupParams.bTesting; - m_env.bNoRandomSeed = startupParams.bNoRandom; + m_env.bNoAssertDialog = false; m_bNoCrashDialog = gEnv->IsDedicated(); @@ -1754,16 +1719,10 @@ AZ_POP_DISABLE_WARNING m_bPreviewMode = startupParams.bPreview; m_bTestMode = startupParams.bTestMode; m_pUserCallback = startupParams.pUserCallback; - m_bMinimal = startupParams.bMinimal; -#if defined(CVARS_WHITELIST) - m_pCVarsWhitelist = startupParams.pCVarsWhitelist; -#endif // defined(CVARS_WHITELIST) m_bDedicatedServer = startupParams.bDedicatedServer; m_currentLanguageAudio = ""; - memcpy(gEnv->pProtectedFunctions, startupParams.pProtectedFunctions, sizeof(startupParams.pProtectedFunctions)); - #if !defined(CONSOLE) m_env.SetIsEditor(m_bEditor); m_env.SetIsEditorGameMode(false); @@ -1771,7 +1730,6 @@ AZ_POP_DISABLE_WARNING #endif m_env.SetToolMode(startupParams.bToolMode); - m_env.bIsOutOfMemory = false; if (m_bEditor) { @@ -1935,23 +1893,6 @@ AZ_POP_DISABLE_WARNING // so we log this immediately after setting the log filename LogVersion(); - //here we should be good to ask Crypak to do something - - // Initialise after pLog and CPU feature initialization - // AND after console creation (Editor only) - // May need access to engine folder .pak files - gEnv->pThreadManager->GetThreadConfigManager()->LoadConfig("config/engine_core.thread_config"); - - if (m_bEditor) - { - gEnv->pThreadManager->GetThreadConfigManager()->LoadConfig("config/engine_sandbox.thread_config"); - } - - // Setup main thread - void* pThreadHandle = 0; // Let system figure out thread handle - gEnv->pThreadManager->RegisterThirdPartyThread(pThreadHandle, "Main"); - m_env.pProfileLogSystem = new CProfileLogSystem(); - bool devModeEnable = true; #if defined(_RELEASE) @@ -1967,22 +1908,6 @@ AZ_POP_DISABLE_WARNING SetDevMode(devModeEnable); - ////////////////////////////////////////////////////////////////////////// - // CREATE NOTIFICATION NETWORK - ////////////////////////////////////////////////////////////////////////// - m_pNotificationNetwork = nullptr; -#ifndef _RELEASE - #ifndef LINUX - - if (!startupParams.bMinimal) - { - m_pNotificationNetwork = CNotificationNetwork::Create(); - } - #endif//LINUX -#endif // _RELEASE - - InlineInitializationProcessing("CSystem::Init NotificationNetwork"); - ////////////////////////////////////////////////////////////////////////// // CREATE CONSOLE ////////////////////////////////////////////////////////////////////////// @@ -2051,8 +1976,6 @@ AZ_POP_DISABLE_WARNING // CPU features detection. m_pCpu = new CCpuFeatures; m_pCpu->Detect(); - m_env.pi.numCoresAvailableToProcess = m_pCpu->GetCPUCount(); - m_env.pi.numLogicalProcessors = m_pCpu->GetLogicalCPUCount(); // Check hard minimum CPU requirements if (!CheckCPURequirements(m_pCpu, this)) @@ -2102,17 +2025,15 @@ AZ_POP_DISABLE_WARNING } { - ILoadConfigurationEntrySink* pCVarsWhiteListConfigSink = GetCVarsWhiteListConfigSink(); - // We have to load this file again since first time we did it without devmode - LoadConfiguration(m_systemConfigName.c_str(), pCVarsWhiteListConfigSink); + LoadConfiguration(m_systemConfigName.c_str()); // Optional user defined overrides - LoadConfiguration("user.cfg", pCVarsWhiteListConfigSink); + LoadConfiguration("user.cfg"); #if defined(ENABLE_STATS_AGENT) if (m_pCmdLine->FindArg(eCLAT_Pre, "useamblecfg")) { - LoadConfiguration("amble.cfg", pCVarsWhiteListConfigSink); + LoadConfiguration("amble.cfg"); } #endif } @@ -2159,7 +2080,7 @@ AZ_POP_DISABLE_WARNING InlineInitializationProcessing("CSystem::Init LoadConfigurations"); #ifdef WIN32 - if ((g_cvars.sys_WER) && (!startupParams.bMinimal)) + if ((g_cvars.sys_WER)) { SetUnhandledExceptionFilter(CryEngineExceptionFilterWER); } @@ -2169,7 +2090,6 @@ AZ_POP_DISABLE_WARNING ////////////////////////////////////////////////////////////////////////// // Localization ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bMinimal) { InitLocalization(); } @@ -2187,7 +2107,6 @@ AZ_POP_DISABLE_WARNING ////////////////////////////////////////////////////////////////////////// // AUDIO ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bMinimal) { if (InitAudioSystem(startupParams)) { @@ -2210,12 +2129,6 @@ AZ_POP_DISABLE_WARNING m_pUserCallback->OnInitProgress("First time asset processing - may take a minute..."); } -#ifdef SOFTCODE_SYSTEM_ENABLED - m_env.pSoftCodeMgr = new SoftCodeMgr(); -#else - m_env.pSoftCodeMgr = nullptr; -#endif - ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // System cursor @@ -2225,8 +2138,7 @@ AZ_POP_DISABLE_WARNING // - System cursor has to be enabled manually by the Game if needed; the custom UiCursor will typically be used instead if (!gEnv->IsDedicated() && - !gEnv->IsEditor() && - !startupParams.bTesting) + !gEnv->IsEditor()) { AzFramework::InputSystemCursorRequestBus::Event(AzFramework::InputDeviceMouse::Id, &AzFramework::InputSystemCursorRequests::SetSystemCursorState, @@ -2322,27 +2234,6 @@ AZ_POP_DISABLE_WARNING InlineInitializationProcessing("CSystem::Init ZStdDecompressor"); - ////////////////////////////////////////////////////////////////////////// - // Initialize task threads. - ////////////////////////////////////////////////////////////////////////// - { - m_pThreadTaskManager->InitThreads(); - - SetAffinity(); - AZ_Assert(CryMemory::IsHeapValid(), "CryMemory heap must be valid before initializing VTune."); - - - if (strstr(startupParams.szSystemCmdLine, "-VTUNE") != 0 || g_cvars.sys_vtune != 0) - { - if (!InitVTuneProfiler()) - { - return false; - } - } - } - - InlineInitializationProcessing("CSystem::Init InitTaskThreads"); - if (m_env.pLyShine) { m_env.pLyShine->PostInit(); @@ -2366,8 +2257,6 @@ AZ_POP_DISABLE_WARNING } } EnableFloatExceptions(g_cvars.sys_float_exceptions); - - MarkThisThreadForDebugging("Main"); } InlineInitializationProcessing("CSystem::Init End"); @@ -2422,8 +2311,7 @@ static void LoadConfigurationCmd(IConsoleCmdArgs* pParams) return; } - ILoadConfigurationEntrySink* pCVarsWhiteListConfigSink = GetISystem()->GetCVarsWhiteListConfigSink(); - GetISystem()->LoadConfiguration(string("Config/") + pParams->GetArg(1), pCVarsWhiteListConfigSink); + GetISystem()->LoadConfiguration(string("Config/") + pParams->GetArg(1)); } @@ -2648,20 +2536,6 @@ void CmdDrillToFile(IConsoleCmdArgs* pArgs) } } -void ChangeLogAllocations(ICVar* pVal) -{ - g_iTraceAllocations = pVal->GetIVal(); - - if (g_iTraceAllocations == 2) - { - IDebugCallStack::instance()->StartMemLog(); - } - else - { - IDebugCallStack::instance()->StopMemLog(); - } -} - ////////////////////////////////////////////////////////////////////////// void CSystem::CreateSystemVars() { @@ -2719,9 +2593,6 @@ void CSystem::CreateSystemVars() m_cvAIUpdate = REGISTER_INT("ai_NoUpdate", 0, VF_CHEAT, "Disables AI system update when 1"); - m_iTraceAllocations = g_iTraceAllocations; - REGISTER_CVAR2_CB("sys_logallocations", &m_iTraceAllocations, m_iTraceAllocations, VF_DUMPTODISK, "Save allocation call stack", ChangeLogAllocations); - m_cvMemStats = REGISTER_INT("MemStats", 0, 0, "0/x=refresh rate in milliseconds\n" "Use 1000 to switch on and 0 to switch off\n" @@ -2860,16 +2731,6 @@ void CSystem::CreateSystemVars() m_sys_TaskThread_CPU[5] = REGISTER_INT("sys_TaskThread5_CPU", 1, 0, "Specifies the physical CPU index taskthread5 will run on"); - //if physics thread is excluded all locks inside are mapped to NO_LOCK - //var must be not visible to accidentally get enabled -#if defined(EXCLUDE_PHYSICS_THREAD) - m_sys_physics_CPU = REGISTER_INT("sys_physics_CPU_disabled", 0, 0, - "Specifies the physical CPU index physics will run on"); -#else - m_sys_physics_CPU = REGISTER_INT("sys_physics_CPU", 1, 0, - "Specifies the physical CPU index physics will run on"); -#endif - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_12 #include AZ_RESTRICTED_FILE(SystemInit_cpp) @@ -3033,7 +2894,6 @@ void CSystem::CreateSystemVars() "0=off / 1=enabled"); */ REGISTER_CVAR2("sys_AI", &g_cvars.sys_ai, 1, 0, "Enables AI Update"); - REGISTER_CVAR2("sys_physics", &g_cvars.sys_physics, 1, 0, "Enables Physics Update"); REGISTER_CVAR2("sys_entities", &g_cvars.sys_entitysystem, 1, 0, "Enables Entities Update"); REGISTER_CVAR2("sys_trackview", &g_cvars.sys_trackview, 1, 0, "Enables TrackView Update"); @@ -3068,10 +2928,6 @@ void CSystem::CreateSystemVars() REGISTER_STRING("dlc_directory", "", 0, "Holds the path to the directory where DLC should be installed to and read from"); -#if defined(MAP_LOADING_SLICING) - CreateSystemScheduler(this); -#endif // defined(MAP_LOADING_SLICING) - #if defined(WIN32) || defined(WIN64) REGISTER_INT("sys_screensaver_allowed", 0, VF_NULL, "Specifies if screen saver is allowed to start up while the game is running."); #endif diff --git a/Code/CryEngine/CrySystem/SystemRender.cpp b/Code/CryEngine/CrySystem/SystemRender.cpp index 9e148bbc2b..b608ef5335 100644 --- a/Code/CryEngine/CrySystem/SystemRender.cpp +++ b/Code/CryEngine/CrySystem/SystemRender.cpp @@ -39,8 +39,6 @@ #include #include -#include "ThreadInfo.h" - #include #if defined(AZ_RESTRICTED_PLATFORM) @@ -90,52 +88,6 @@ void CSystem::OnScene3DEnd() } } - -//! Update screen and call some important tick functions during loading. -void CSystem::SynchronousLoadingTick([[maybe_unused]] const char* pFunc, [[maybe_unused]] int line) -{ - LOADING_TIME_PROFILE_SECTION; - if (gEnv && gEnv->bMultiplayer && !gEnv->IsEditor()) - { - //UpdateLoadingScreen currently contains a couple of tick functions that need to be called regularly during the synchronous level loading, - //when the usual engine and game ticks are suspended. - UpdateLoadingScreen(); - -#if defined(MAP_LOADING_SLICING) - GetISystemScheduler()->SliceAndSleep(pFunc, line); -#endif - } -} - - -////////////////////////////////////////////////////////////////////////// -void CSystem::UpdateLoadingScreen() -{ - // Do not update the network thread from here - it will cause context corruption - use the NetworkStallTicker thread system - - if (GetCurrentThreadId() != gEnv->mMainThreadId) - { - return; - } - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMRENDERER_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(SystemRender_cpp) -#endif - -#if AZ_LOADSCREENCOMPONENT_ENABLED - EBUS_EVENT(LoadScreenBus, UpdateAndRender); -#endif // if AZ_LOADSCREENCOMPONENT_ENABLED - - if (!m_bEditor && !IsQuitting()) - { - if (m_pProgressListener) - { - m_pProgressListener->OnLoadingProgress(0); - } - } -} - ////////////////////////////////////////////////////////////////////////// void CSystem::DisplayErrorMessage(const char* acMessage, diff --git a/Code/CryEngine/CrySystem/SystemScheduler.cpp b/Code/CryEngine/CrySystem/SystemScheduler.cpp deleted file mode 100644 index 5cee6d5529..0000000000 --- a/Code/CryEngine/CrySystem/SystemScheduler.cpp +++ /dev/null @@ -1,211 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Implementation of the CSystemScheduler class - - -#include "CrySystem_precompiled.h" - -#include "ProjectDefines.h" -#if defined(MAP_LOADING_SLICING) - -#include "SystemScheduler.h" - -#include "MiniQueue.h" -#include "ClientHandler.h" -#include "ServerHandler.h" - -void CreateSystemScheduler(CSystem* pSystem) -{ - gEnv->pSystemScheduler = new CSystemScheduler(pSystem); -} - -CSystemScheduler::CSystemScheduler(CSystem* pSystem) - : m_pSystem(pSystem) - , m_lastSliceCheckTime(0.0f) - , m_sliceLoadingRef(0) -{ - int defaultSchedulingMode = 0; - if (gEnv->IsDedicated()) - { - defaultSchedulingMode = 2; - } - - m_svSchedulingMode = REGISTER_INT("sv_scheduling", defaultSchedulingMode, 0, "Scheduling mode\n" - " 0: Normal mode\n" - " 1: Client\n" - " 2: Server\n"); - - m_svSchedulingBucket = REGISTER_INT("sv_schedulingBucket", 0, 0, "Scheduling bucket\n"); - - m_svSchedulingAffinity = REGISTER_INT("sv_SchedulingAffinity", 0, 0, "Scheduling affinity\n"); - - m_svSchedulingClientTimeout = REGISTER_INT("sv_schedulingClientTimeout", 1000, 0, "Client wait server\n"); - m_svSchedulingServerTimeout = REGISTER_INT("sv_schedulingServerTimeout", 100, 0, "Server wait server\n"); - -#if defined(MAP_LOADING_SLICING) - m_svSliceLoadEnable = REGISTER_INT("sv_sliceLoadEnable", 1, 0, "Enable/disable slice loading logic\n"); - ; - m_svSliceLoadBudget = REGISTER_INT("sv_sliceLoadBudget", 10, 0, "Slice budget\n"); - ; - m_svSliceLoadLogging = REGISTER_INT("sv_sliceLoadLogging", 0, 0, "Enable/disable slice loading logging\n"); -#endif - - m_pLastSliceName = "INACTIVE"; - m_lastSliceLine = 0; -} - -CSystemScheduler::~CSystemScheduler(void) -{ -} - -void CSystemScheduler::SliceLoadingBegin() -{ - m_lastSliceCheckTime = gEnv->pTimer->GetAsyncTime(); - m_sliceLoadingRef++; - m_pLastSliceName = "START"; - m_lastSliceLine = 0; -} - -void CSystemScheduler::SliceLoadingEnd() -{ - m_sliceLoadingRef--; - m_pLastSliceName = "INACTIVE"; - m_lastSliceLine = 0; -} - -void CSystemScheduler::SliceAndSleep(const char* sliceName, int line) -{ -#if defined(MAP_LOADING_SLICING) - if (!gEnv->IsDedicated()) - { - return; - } - - if (!m_sliceLoadingRef) - { - return; - } - - if (!m_svSliceLoadEnable->GetIVal()) - { - return; - } - - SchedulingModeUpdate(); - - CTimeValue currTime = gEnv->pTimer->GetAsyncTime(); - - float sliceBudget = CLAMP(m_svSliceLoadBudget->GetFVal(), 0, 1000.0f / m_pSystem->GetDedicatedMaxRate()->GetFVal()); - bool doSleep = true; - if ((currTime - m_pSystem->GetLastTickTime()).GetMilliSeconds() < sliceBudget) - { - m_lastSliceCheckTime = currTime; - doSleep = false; - } - - if (doSleep) - { - if (m_svSliceLoadLogging->GetIVal()) - { - float diff = (currTime - m_lastSliceCheckTime).GetMilliSeconds(); - if (diff > sliceBudget) - { - CryLogAlways("[SliceAndSleep]: Interval between slice [%s:%i] and [%s:%i] was [%f] out of budget [%f]", m_pLastSliceName, m_lastSliceLine, sliceName, line, diff, sliceBudget); - } - } - - m_pSystem->SleepIfNeeded(); - } - - m_pLastSliceName = sliceName; - m_lastSliceLine = line; -#endif -} - -void CSystemScheduler::SchedulingSleepIfNeeded() -{ - if (!gEnv->IsDedicated()) - { - return; - } - - SchedulingModeUpdate(); - m_pSystem->SleepIfNeeded(); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Scheduling mode routines -// -/////////////////////////////////////////////////////////////////////////////////////////////////// - - - - - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Scheduling mode update logic -// -/////////////////////////////////////////////////////////////////////////////////////////////////// - -void CSystemScheduler::SchedulingModeUpdate() -{ - static std::unique_ptr m_client; - static std::unique_ptr m_server; - - if (int scheduling = m_svSchedulingMode->GetIVal()) - { - if (scheduling == 1) //client - { - if (!m_client.get()) - { - m_server.reset(); - m_client.reset(new ClientHandler(m_svSchedulingBucket->GetString(), m_svSchedulingAffinity->GetIVal(), m_svSchedulingClientTimeout->GetIVal())); - } - if (m_client->Sync()) - { - return; - } - } - else if (scheduling == 2) //server - { - if (!m_server.get()) - { - m_client.reset(); - m_server.reset(new ServerHandler(m_svSchedulingBucket->GetString(), m_svSchedulingAffinity->GetIVal(), m_svSchedulingServerTimeout->GetIVal())); - } - if (m_server->Sync()) - { - return; - } - } - } - else - { - m_client.reset(); - m_server.reset(); - } -} - -#endif // defined(MAP_LOADING_SLICING) - -extern "C" void SliceAndSleep(const char* pFunc, int line) -{ - if (GetISystemScheduler()) - { - GetISystemScheduler()->SliceAndSleep(pFunc, line); - } -} - diff --git a/Code/CryEngine/CrySystem/SystemScheduler.h b/Code/CryEngine/CrySystem/SystemScheduler.h deleted file mode 100644 index feb6e2850c..0000000000 --- a/Code/CryEngine/CrySystem/SystemScheduler.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_SYSTEMSCHEDULER_H -#define CRYINCLUDE_CRYSYSTEM_SYSTEMSCHEDULER_H - -#pragma once - -#include "System.h" -#include - -class CSystemScheduler - : public ISystemScheduler -{ -public: - CSystemScheduler(CSystem* pSystem); - virtual ~CSystemScheduler(void); - - // ISystemScheduler - virtual void SliceAndSleep(const char* sliceName, int line); - virtual void SliceLoadingBegin(); - virtual void SliceLoadingEnd(); - - virtual void SchedulingSleepIfNeeded(void); - // ~ISystemScheduler - -protected: - void SchedulingModeUpdate(void); - -private: - CSystem* m_pSystem; - ICVar* m_svSchedulingAffinity; - ICVar* m_svSchedulingClientTimeout; - ICVar* m_svSchedulingServerTimeout; - ICVar* m_svSchedulingBucket; - ICVar* m_svSchedulingMode; - ICVar* m_svSliceLoadEnable; - ICVar* m_svSliceLoadBudget; - ICVar* m_svSliceLoadLogging; - - CTimeValue m_lastSliceCheckTime; - - int m_sliceLoadingRef; - - const char* m_pLastSliceName; - int m_lastSliceLine; -}; - -// Summary: -// Creates the system scheduler interface. -void CreateSystemScheduler(CSystem* pSystem); - -#endif // CRYINCLUDE_CRYSYSTEM_SYSTEMSCHEDULER_H diff --git a/Code/CryEngine/CrySystem/SystemThreading.cpp b/Code/CryEngine/CrySystem/SystemThreading.cpp deleted file mode 100644 index 9354e4e1c3..0000000000 --- a/Code/CryEngine/CrySystem/SystemThreading.cpp +++ /dev/null @@ -1,697 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "System.h" -#include "ThreadConfigManager.h" -#include "IThreadManager.h" -#include -#include "CryUtils.h" - -#define INCLUDED_FROM_SYSTEM_THREADING_CPP - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define SYSTEMTHREADING_CPP_SECTION_1 1 -#define SYSTEMTHREADING_CPP_SECTION_2 2 -#define SYSTEMTHREADING_CPP_SECTION_3 3 -#endif - -#if defined(WIN32) || defined(WIN64) - #include "CryThreadUtil_win32_thread.h" -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMTHREADING_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(SystemThreading_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - #include "CryThreadUtil_pthread.h" -#endif -#undef INCLUDED_FROM_SYSTEM_THREADING_CPP - -////////////////////////////////////////////////////////////////////////// -static void ApplyThreadConfig(CryThreadUtil::TThreadHandle pThreadHandle, const SThreadConfig& rThreadDesc) -{ - // Apply config - if (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_ThreadName) - { - CryThreadUtil::CrySetThreadName(pThreadHandle, rThreadDesc.szThreadName); - } - if (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_Affinity) - { - CryThreadUtil::CrySetThreadAffinityMask(pThreadHandle, rThreadDesc.affinityFlag); - } - if (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_Priority) - { - CryThreadUtil::CrySetThreadPriority(pThreadHandle, rThreadDesc.priority); - } - if (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_PriorityBoost) - { - CryThreadUtil::CrySetThreadPriorityBoost(pThreadHandle, !rThreadDesc.bDisablePriorityBoost); - } - - CryComment(" Configured thread \"%s\" %s | AffinityMask: %u %s | Priority: %i %s | PriorityBoost: %s %s", - rThreadDesc.szThreadName, (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_ThreadName) ? "" : "(ignored)", - rThreadDesc.affinityFlag, (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_Affinity) ? "" : "(ignored)", - rThreadDesc.priority, (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_Priority) ? "" : "(ignored)", - !rThreadDesc.bDisablePriorityBoost ? "enabled" : "disabled", (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_PriorityBoost) ? "" : "(ignored)"); -} - -////////////////////////////////////////////////////////////////////////// -struct SThreadMetaData - : public CMultiThreadRefCount -{ - SThreadMetaData() - : m_pThreadTask(0) - , m_threadHandle(0) - , m_threadId(0) - , m_threadName("Cry_UnnamedThread") - , m_isRunning(false) - { - } - - IThread* m_pThreadTask; // Pointer to thread task to be executed - CThreadManager* m_pThreadMngr; // Pointer to thread manager - - CryThreadUtil::TThreadHandle m_threadHandle; // Thread handle - threadID m_threadId; // The active threadId, 0 = Invalid Id - - CryMutex m_threadExitMutex; // Mutex used to safeguard thread exit condition signaling - CryConditionVariable m_threadExitCondition; // Signaled when the thread is about to exit - - CryFixedStringT m_threadName; // Thread name - volatile bool m_isRunning; // Indicates the thread is not ready to exit yet -}; - -////////////////////////////////////////////////////////////////////////// -class CThreadManager - : public IThreadManager -{ -public: - // - virtual ~CThreadManager() - { - } - - virtual bool SpawnThread(IThread* pThread, const char* sThreadName, ...) override; - virtual bool JoinThread(IThread* pThreadTask, EJoinMode eJoinMode) override; - - virtual bool RegisterThirdPartyThread(void* pThreadHandle, const char* sThreadName, ...) override; - virtual bool UnRegisterThirdPartyThread(const char* sThreadName, ...) override; - - virtual const char* GetThreadName(threadID nThreadId) override; - virtual threadID GetThreadId(const char* sThreadName, ...) override; - - virtual void ForEachOtherThread(IThreadManager::ThreadModifFunction fpThreadModiFunction, void* pFuncData = 0) override; - - virtual void EnableFloatExceptions(EFPE_Severity eFPESeverity, threadID nThreadId = 0) override; - virtual void EnableFloatExceptionsForEachOtherThread(EFPE_Severity eFPESeverity) override; - - virtual uint GetFloatingPointExceptionMask() override; - virtual void SetFloatingPointExceptionMask(uint nMask) override; - - IThreadConfigManager* GetThreadConfigManager() override - { - return &m_threadConfigManager; - } - // -private: -#if defined(WIN32) || defined(WIN64) - static unsigned __stdcall RunThread(void* thisPtr); -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMTHREADING_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(SystemThreading_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - static void* RunThread(void* thisPtr); -#endif - -private: - bool UnregisterThread(IThread* pThreadTask); - - bool SpawnThreadImpl(IThread* pThread, const char* sThreadName); - - bool RegisterThirdPartyThreadImpl(CryThreadUtil::TThreadHandle pThreadHandle, const char* sThreadName); - bool UnRegisterThirdPartyThreadImpl(const char* sThreadName); - - threadID GetThreadIdImpl(const char* sThreadName); - -private: - // Note: Guard SThreadMetaData with a _smart_ptr and lock to ensure that a thread waiting to be signaled by another still - // has access to valid SThreadMetaData even though the other thread terminated and as a result unregistered itself from the CThreadManager. - // An example would be the join method. Where one thread waits on a signal from an other thread to terminate and release its SThreadMetaData, - // sharing the same SThreadMetaData condition variable. - typedef std::map > SpawnedThreadMap; - typedef std::map >::iterator SpawnedThreadMapIter; - typedef std::map >::const_iterator SpawnedThreadMapConstIter; - typedef std::pair > ThreadMapPair; - - typedef std::map, _smart_ptr > SpawnedThirdPartyThreadMap; - typedef std::map, _smart_ptr >::iterator SpawnedThirdPartyThreadMapIter; - typedef std::map, _smart_ptr >::const_iterator SpawnedThirdPartyThreadMapConstIter; - typedef std::pair, _smart_ptr > ThirdPartyThreadMapPair; - - CryCriticalSection m_spawnedThreadsLock; // Use lock for the rare occasion a thread is created/destroyed - SpawnedThreadMap m_spawnedThreads; // Holds information of all spawned threads (through this system) - - CryCriticalSection m_spawnedThirdPartyThreadsLock; // Use lock for the rare occasion a thread is created/destroyed - SpawnedThirdPartyThreadMap m_spawnedThirdPartyThread; // Holds information of all registered 3rd party threads (through this system) - - CThreadConfigManager m_threadConfigManager; -}; - -////////////////////////////////////////////////////////////////////////// -#if defined(WIN32) || defined(WIN64) -unsigned __stdcall CThreadManager::RunThread(void* thisPtr) -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMTHREADING_CPP_SECTION_3 -#include AZ_RESTRICTED_FILE(SystemThreading_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -void* CThreadManager::RunThread(void* thisPtr) -#endif -{ - // Check that we are not spawning a thread before gEnv->pSystem has been set - // Otherwise we cannot enable floating point exceptions - if (!gEnv || !gEnv->pSystem) - { - CryFatalError("[Error]: CThreadManager::RunThread requires gEnv->pSystem to be initialized."); - } - - IThreadConfigManager* pThreadConfigMngr = gEnv->pThreadManager->GetThreadConfigManager(); - - SThreadMetaData* pThreadData = reinterpret_cast(thisPtr); - pThreadData->m_threadId = CryThreadUtil::CryGetCurrentThreadId(); - - // Apply config - const SThreadConfig* pThreadConfig = pThreadConfigMngr->GetThreadConfig(pThreadData->m_threadName.c_str()); - ApplyThreadConfig(pThreadData->m_threadHandle, *pThreadConfig); - - // Config not found, append thread name with no config tag - if (pThreadConfig == pThreadConfigMngr->GetDefaultThreadConfig()) - { - CryFixedStringT tmpString(pThreadData->m_threadName); - const char* cNoConfigAppendix = "(NoCfgFound)"; - int nNumCharsToReplace = strlen(cNoConfigAppendix); - - // Replace thread name ending - if (pThreadData->m_threadName.size() > THREAD_NAME_LENGTH_MAX - nNumCharsToReplace) - { - tmpString.replace(THREAD_NAME_LENGTH_MAX - nNumCharsToReplace, nNumCharsToReplace, cNoConfigAppendix, nNumCharsToReplace); - } - else - { - tmpString.append(cNoConfigAppendix); - } - - // Print to log - if (pThreadConfigMngr->ConfigLoaded()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " No Thread config found for thread %s using ... default config.", pThreadData->m_threadName.c_str()); - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Thread config not loaded yet. Hence no thread config was found for thread %s ... using default config.", pThreadData->m_threadName.c_str()); - } - - // Rename Thread - CryThreadUtil::CrySetThreadName(pThreadData->m_threadHandle, tmpString.c_str()); - } - - // Enable FPEs - gEnv->pThreadManager->EnableFloatExceptions((EFPE_Severity)g_cvars.sys_float_exceptions); - - // Execute thread code - pThreadData->m_pThreadTask->ThreadEntry(); - - // Disable FPEs - gEnv->pThreadManager->EnableFloatExceptions(eFPE_None); - - // Signal imminent thread end - pThreadData->m_threadExitMutex.Lock(); - pThreadData->m_isRunning = false; - pThreadData->m_threadExitCondition.Notify(); - pThreadData->m_threadExitMutex.Unlock(); - - // Unregister thread - // Note: Unregister after m_threadExitCondition.Notify() to ensure pThreadData is still valid - pThreadData->m_pThreadMngr->UnregisterThread(pThreadData->m_pThreadTask); - - CryThreadUtil::CryThreadExitCall(); - - return NULL; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::JoinThread(IThread* pThreadTask, EJoinMode eJoinMode) -{ - // Get thread object - _smart_ptr pThreadImpl = 0; - { - AUTO_LOCK(m_spawnedThreadsLock); - - SpawnedThreadMapIter res = m_spawnedThreads.find(pThreadTask); - if (res == m_spawnedThreads.end()) - { - // Thread has already finished and unregistered itself. - // As it is complete we cannot wait for it. - // Hence return true. - return true; - } - - pThreadImpl = res->second; // Keep object alive - } - - // On try join, exit if the thread is not in a state to exit - if (eJoinMode == eJM_TryJoin && pThreadImpl->m_isRunning) - { - return false; - } - - // Wait for completion of the target thread exit condition - pThreadImpl->m_threadExitMutex.Lock(); - while (pThreadImpl->m_isRunning) - { - pThreadImpl->m_threadExitCondition.Wait(pThreadImpl->m_threadExitMutex); - } - pThreadImpl->m_threadExitMutex.Unlock(); - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::UnregisterThread(IThread* pThreadTask) -{ - AUTO_LOCK(m_spawnedThreadsLock); - - SpawnedThreadMapIter res = m_spawnedThreads.find(pThreadTask); - if (res == m_spawnedThreads.end()) - { - // Duplicate thread deletion - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": UnregisterThread: Unable to unregister thread. Thread name could not be found. Double deletion? IThread pointer: %p", pThreadTask); - return false; - } - - m_spawnedThreads.erase(res); - return true; -} - -////////////////////////////////////////////////////////////////////////// -const char* CThreadManager::GetThreadName(threadID nThreadId) -{ - // Loop over internally spawned threads - { - AUTO_LOCK(m_spawnedThreadsLock); - - SpawnedThreadMapConstIter iter = m_spawnedThreads.begin(); - SpawnedThreadMapConstIter iterEnd = m_spawnedThreads.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadId == nThreadId) - { - return iter->second->m_threadName.c_str(); - } - } - } - - // Loop over third party threads - { - AUTO_LOCK(m_spawnedThirdPartyThreadsLock); - - SpawnedThirdPartyThreadMapConstIter iter = m_spawnedThirdPartyThread.begin(); - SpawnedThirdPartyThreadMapConstIter iterEnd = m_spawnedThirdPartyThread.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadId == nThreadId) - { - return iter->second->m_threadName.c_str(); - } - } - } - - return ""; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadManager::ForEachOtherThread(IThreadManager::ThreadModifFunction fpThreadModiFunction, void* pFuncData) -{ - threadID nCurThreadId = CryThreadUtil::CryGetCurrentThreadId(); - - // Loop over internally spawned threads - { - AUTO_LOCK(m_spawnedThreadsLock); - - SpawnedThreadMapConstIter iter = m_spawnedThreads.begin(); - SpawnedThreadMapConstIter iterEnd = m_spawnedThreads.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadId != nCurThreadId) - { - fpThreadModiFunction(iter->second->m_threadId, pFuncData); - } - } - } - - // Loop over third party threads - { - AUTO_LOCK(m_spawnedThirdPartyThreadsLock); - - SpawnedThirdPartyThreadMapConstIter iter = m_spawnedThirdPartyThread.begin(); - SpawnedThirdPartyThreadMapConstIter iterEnd = m_spawnedThirdPartyThread.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadId != nCurThreadId) - { - fpThreadModiFunction(iter->second->m_threadId, pFuncData); - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::SpawnThread(IThread* pThreadTask, const char* sThreadName, ...) -{ - va_list args; - va_start(args, sThreadName); - - // Format thread name - char strThreadName[THREAD_NAME_LENGTH_MAX]; - const int cNumCharsNeeded = azvsnprintf(strThreadName, CRY_ARRAY_COUNT(strThreadName), sThreadName, args); - if (cNumCharsNeeded > THREAD_NAME_LENGTH_MAX - 1 || cNumCharsNeeded < 0) - { - strThreadName[THREAD_NAME_LENGTH_MAX - 1] = '\0'; // The WinApi only null terminates if strLen < bufSize - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": ThreadName \"%s\" has been truncated. Max characters allowed: %i. ", strThreadName, THREAD_NAME_LENGTH_MAX - 1); - } - - // Spawn thread - bool ret = SpawnThreadImpl(pThreadTask, strThreadName); - - if (!ret) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": CSystem::SpawnThread error spawning thread: \"%s\" ", strThreadName); - } - - va_end(args); - return ret; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::SpawnThreadImpl(IThread* pThreadTask, const char* sThreadName) -{ - if (pThreadTask == NULL) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, ": SpawnThread '%s' ThreadTask is NULL : ignoring", sThreadName); - return false; - } - - // Init thread meta data - SThreadMetaData* pThreadMetaData = new SThreadMetaData(); - pThreadMetaData->m_pThreadTask = pThreadTask; - pThreadMetaData->m_pThreadMngr = this; - pThreadMetaData->m_threadName = sThreadName; - - // Add thread to map - { - AUTO_LOCK(m_spawnedThreadsLock); - SpawnedThreadMapIter res = m_spawnedThreads.find(pThreadTask); - if (res != m_spawnedThreads.end()) - { - // Thread with same name already spawned - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": SpawnThread: Thread \"%s\" already exists.", sThreadName); - delete pThreadMetaData; - return false; - } - - // Insert thread data - m_spawnedThreads.insert(ThreadMapPair(pThreadTask, pThreadMetaData)); - } - - // Load config if we can and if no config has been defined to be loaded - const SThreadConfig* pThreadConfig = gEnv->pThreadManager->GetThreadConfigManager()->GetThreadConfig(sThreadName); - - // Create thread description - CryThreadUtil::SThreadCreationDesc desc = {sThreadName, RunThread, pThreadMetaData, pThreadConfig->paramActivityFlag & SThreadConfig::eThreadParamFlag_StackSize ? pThreadConfig->stackSizeBytes : 0}; - - // Spawn new thread - pThreadMetaData->m_isRunning = CryThreadUtil::CryCreateThread(&(pThreadMetaData->m_threadHandle), desc); - - // Validate thread creation - if (!pThreadMetaData->m_isRunning) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": SpawnThread: Could not spawn thread \"%s\" .", sThreadName); - - // Remove thread from map (also releases SThreadMetaData _smart_ptr) - m_spawnedThreads.erase(m_spawnedThreads.find(pThreadTask)); - return false; - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::RegisterThirdPartyThread(void* pThreadHandle, const char* sThreadName, ...) -{ - if (!pThreadHandle) - { - pThreadHandle = reinterpret_cast(CryThreadUtil::CryGetCurrentThreadHandle()); - } - - va_list args; - va_start(args, sThreadName); - - // Format thread name - char strThreadName[THREAD_NAME_LENGTH_MAX]; - const int cNumCharsNeeded = azvsnprintf(strThreadName, CRY_ARRAY_COUNT(strThreadName), sThreadName, args); - if (cNumCharsNeeded > THREAD_NAME_LENGTH_MAX - 1) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": ThreadName \"%s\" has been truncated. Max characters allowed: %i. ", strThreadName, THREAD_NAME_LENGTH_MAX - 1); - } - - // Register 3rd party thread - bool ret = RegisterThirdPartyThreadImpl(reinterpret_cast(pThreadHandle), strThreadName); - - va_end(args); - return ret; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::RegisterThirdPartyThreadImpl(CryThreadUtil::TThreadHandle threadHandle, const char* sThreadName) -{ - if (strcmp(sThreadName, "") == 0) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": CThreadManager::RegisterThirdPartyThread error registering third party thread. No name provided."); - return false; - } - // Init thread meta data - SThreadMetaData* pThreadMetaData = new SThreadMetaData(); - pThreadMetaData->m_pThreadTask = 0; - pThreadMetaData->m_pThreadMngr = this; - pThreadMetaData->m_threadName = sThreadName; - pThreadMetaData->m_threadHandle = CryThreadUtil::CryDuplicateThreadHandle(threadHandle); // Ensure that we are not storing a pseudo handle - pThreadMetaData->m_threadId = CryThreadUtil::CryGetThreadId(pThreadMetaData->m_threadHandle); - - { - AUTO_LOCK(m_spawnedThirdPartyThreadsLock); - - // Check for duplicate - SpawnedThirdPartyThreadMapConstIter res = m_spawnedThirdPartyThread.find(sThreadName); - if (res != m_spawnedThirdPartyThread.end()) - { - CryFatalError("CThreadManager::RegisterThirdPartyThread - Unable to register thread \"%s\"" - "because another third party thread with the same name \"%s\" has already been registered with ThreadHandle: %p", - sThreadName, res->second->m_threadName.c_str(), reinterpret_cast(threadHandle)); - - delete pThreadMetaData; - return false; - } - - // Insert thread data - m_spawnedThirdPartyThread.insert(ThirdPartyThreadMapPair(pThreadMetaData->m_threadName.c_str(), pThreadMetaData)); - } - - // Get thread config - const SThreadConfig* pThreadConfig = gEnv->pThreadManager->GetThreadConfigManager()->GetThreadConfig(sThreadName); - - // Apply config (if not default config) - if (strcmp(pThreadConfig->szThreadName, sThreadName) == 0) - { - ApplyThreadConfig(threadHandle, *pThreadConfig); - } - - // Update FP exception mask for 3rd party thread - if (pThreadMetaData->m_threadId) - { - CryThreadUtil::EnableFloatExceptions(pThreadMetaData->m_threadId, (EFPE_Severity)g_cvars.sys_float_exceptions); - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::UnRegisterThirdPartyThread(const char* sThreadName, ...) -{ - va_list args; - va_start(args, sThreadName); - - // Format thread name - char strThreadName[THREAD_NAME_LENGTH_MAX]; - const int cNumCharsNeeded = azvsnprintf(strThreadName, CRY_ARRAY_COUNT(strThreadName), sThreadName, args); - if (cNumCharsNeeded > THREAD_NAME_LENGTH_MAX - 1) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": ThreadName \"%s\" has been truncated. Max characters allowed: %i. ", strThreadName, THREAD_NAME_LENGTH_MAX - 1); - } - - // Unregister 3rd party thread - bool ret = UnRegisterThirdPartyThreadImpl(strThreadName); - - va_end(args); - return ret; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::UnRegisterThirdPartyThreadImpl(const char* sThreadName) -{ - AUTO_LOCK(m_spawnedThirdPartyThreadsLock); - - SpawnedThirdPartyThreadMapIter res = m_spawnedThirdPartyThread.find(sThreadName); - if (res == m_spawnedThirdPartyThread.end()) - { - // Duplicate thread deletion - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": UnRegisterThirdPartyThread: Unable to unregister thread. Thread name \"%s\" could not be found. Double deletion? ", sThreadName); - return false; - } - - // Close thread handle - CryThreadUtil::CryCloseThreadHandle(res->second->m_threadHandle); - - // Delete reference from container - m_spawnedThirdPartyThread.erase(res); - return true; -} - -////////////////////////////////////////////////////////////////////////// -threadID CThreadManager::GetThreadId(const char* sThreadName, ...) -{ - va_list args; - va_start(args, sThreadName); - - // Format thread name - char strThreadName[THREAD_NAME_LENGTH_MAX]; - const int cNumCharsNeeded = azvsnprintf(strThreadName, CRY_ARRAY_COUNT(strThreadName), sThreadName, args); - if (cNumCharsNeeded > THREAD_NAME_LENGTH_MAX - 1) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": ThreadName \"%s\" has been truncated. Max characters allowed: %i. ", strThreadName, THREAD_NAME_LENGTH_MAX - 1); - } - - // Get thread name - threadID ret = GetThreadIdImpl(strThreadName); - - va_end(args); - return ret; -} - -////////////////////////////////////////////////////////////////////////// -threadID CThreadManager::GetThreadIdImpl(const char* sThreadName) -{ - // Loop over internally spawned threads - { - AUTO_LOCK(m_spawnedThreadsLock); - - SpawnedThreadMapConstIter iter = m_spawnedThreads.begin(); - SpawnedThreadMapConstIter iterEnd = m_spawnedThreads.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadName.compare(sThreadName) == 0) - { - return iter->second->m_threadId; - } - } - } - - // Loop over third party threads - { - AUTO_LOCK(m_spawnedThirdPartyThreadsLock); - - SpawnedThirdPartyThreadMapConstIter iter = m_spawnedThirdPartyThread.begin(); - SpawnedThirdPartyThreadMapConstIter iterEnd = m_spawnedThirdPartyThread.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadName.compare(sThreadName) == 0) - { - return iter->second->m_threadId; - } - } - } - - return 0; -} - -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -static void EnableFPExceptionsForThread(threadID nThreadId, void* pData) -{ - EFPE_Severity eFPESeverity = *(EFPE_Severity*)pData; - CryThreadUtil::EnableFloatExceptions(nThreadId, eFPESeverity); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadManager::EnableFloatExceptions(EFPE_Severity eFPESeverity, threadID nThreadId /*=0*/) -{ - CryThreadUtil::EnableFloatExceptions(nThreadId, eFPESeverity); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadManager::EnableFloatExceptionsForEachOtherThread(EFPE_Severity eFPESeverity) -{ - ForEachOtherThread(EnableFPExceptionsForThread, &eFPESeverity); -} - -////////////////////////////////////////////////////////////////////////// -uint CThreadManager::GetFloatingPointExceptionMask() -{ - return CryThreadUtil::GetFloatingPointExceptionMask(); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadManager::SetFloatingPointExceptionMask(uint nMask) -{ - CryThreadUtil::SetFloatingPointExceptionMask(nMask); -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::InitThreadSystem() -{ - m_pThreadManager = new CThreadManager(); - m_env.pThreadManager = m_pThreadManager; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::ShutDownThreadSystem() -{ - SAFE_DELETE(m_pThreadManager); -} diff --git a/Code/CryEngine/CrySystem/SystemWin32.cpp b/Code/CryEngine/CrySystem/SystemWin32.cpp index c694979a14..72c43bceed 100644 --- a/Code/CryEngine/CrySystem/SystemWin32.cpp +++ b/Code/CryEngine/CrySystem/SystemWin32.cpp @@ -46,8 +46,6 @@ #include #endif -#include "IDebugCallStack.h" - #if defined(APPLE) || defined(LINUX) #include #endif @@ -752,13 +750,6 @@ void CSystem::FatalError(const char* format, ...) } // Dump callstack. -#endif -#if defined (WIN32) - //Triggers a fatal error, so the DebugCallstack can create the error.log and terminate the application - IDebugCallStack::instance()->FatalError(szBuffer); -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMWIN32_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(SystemWin32_cpp) #endif CryDebugBreak(); @@ -800,8 +791,6 @@ void CSystem::ReportBug([[maybe_unused]] const char* format, ...) va_start(ArgList, format); azvsnprintf(szBuffer + strlen(sPrefix), MAX_WARNING_LENGTH - strlen(sPrefix), format, ArgList); va_end(ArgList); - - IDebugCallStack::instance()->ReportBug(szBuffer); #endif } @@ -910,10 +899,6 @@ void CSystem::LogSystemInfo() OSVERSIONINFO OSVerInfo; OSVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - // log Windows type - Win32SysInspect::GetOS(m_env.pi.winVer, m_env.pi.win64Bit, szBuffer, sizeof(szBuffer)); - CryLogAlways(szBuffer); - // log system language GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SENGLANGUAGE, szLanguageBuffer, sizeof(szLanguageBuffer)); azsprintf(szBuffer, "System language: %s", szLanguageBuffer); diff --git a/Code/CryEngine/CrySystem/ThreadConfigManager.cpp b/Code/CryEngine/CrySystem/ThreadConfigManager.cpp deleted file mode 100644 index b582aac578..0000000000 --- a/Code/CryEngine/CrySystem/ThreadConfigManager.cpp +++ /dev/null @@ -1,577 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "ThreadConfigManager.h" -#include "IConsole.h" -#include "System.h" -#include -#include -#include "CryUtils.h" -namespace -{ - const char* sCurThreadConfigFilename = ""; - const uint32 sPlausibleStackSizeLimitKB = (1024 * 100); // 100mb -} - -////////////////////////////////////////////////////////////////////////// -CThreadConfigManager::CThreadConfigManager() -{ - m_defaultConfig.szThreadName = "CryThread_Unnamed"; - m_defaultConfig.stackSizeBytes = 0; - m_defaultConfig.affinityFlag = -1; - m_defaultConfig.priority = THREAD_PRIORITY_NORMAL; - m_defaultConfig.bDisablePriorityBoost = false; - m_defaultConfig.paramActivityFlag = (SThreadConfig::TThreadParamFlag)~0; -} - -////////////////////////////////////////////////////////////////////////// -const SThreadConfig* CThreadConfigManager::GetThreadConfig(const char* szThreadName, ...) -{ - va_list args; - va_start(args, szThreadName); - - // Format thread name - char strThreadName[THREAD_NAME_LENGTH_MAX]; - const int cNumCharsNeeded = azvsnprintf(strThreadName, CRY_ARRAY_COUNT(strThreadName), szThreadName, args); - if (cNumCharsNeeded > THREAD_NAME_LENGTH_MAX - 1) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": ThreadName \"%s\" has been truncated. Max characters allowed: %i. ", strThreadName, THREAD_NAME_LENGTH_MAX - 1); - } - - // Get Thread Config - const SThreadConfig* retThreasdConfig = GetThreadConfigImpl(strThreadName); - - va_end(args); - return retThreasdConfig; -} - -////////////////////////////////////////////////////////////////////////// -const SThreadConfig* CThreadConfigManager::GetThreadConfigImpl(const char* szThreadName) -{ - // Get thread config for platform - ThreadConfigMapConstIter threatRet = m_threadConfig.find(CryFixedStringT(szThreadName)); - if (threatRet == m_threadConfig.end()) - { - // Search in wildcard setups - ThreadConfigMapConstIter wildCardIter = m_wildcardThreadConfig.begin(); - ThreadConfigMapConstIter wildCardIterEnd = m_wildcardThreadConfig.end(); - for (; wildCardIter != wildCardIterEnd; ++wildCardIter) - { - if (CryStringUtils::MatchWildcard(szThreadName, wildCardIter->second.szThreadName)) - { - // Store new thread config - SThreadConfig threadConfig = wildCardIter->second; - std::pair res; - res = m_threadConfig.insert(ThreadConfigMapPair(CryFixedStringT(szThreadName), threadConfig)); - - // Store name (ref to key) - SThreadConfig& rMapThreadConfig = res.first->second; - rMapThreadConfig.szThreadName = res.first->first.c_str(); - - // Return new thread config - return &res.first->second; - } - } - - // Failure case, no match found - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": Unable to find config for thread:%s", szThreadName); - return &m_defaultConfig; - } - - // Return thread config - return &threatRet->second; -} - -////////////////////////////////////////////////////////////////////////// -const SThreadConfig* CThreadConfigManager::GetDefaultThreadConfig() const -{ - return &m_defaultConfig; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadConfigManager::LoadConfig(const char* pcPath) -{ - // Adjust filename for OnDisk or in .pak file loading - char szFullPathBuf[AZ::IO::IArchive::MaxPath]; - gEnv->pCryPak->AdjustFileName(pcPath, szFullPathBuf, AZ_ARRAY_SIZE(szFullPathBuf), 0); - - // Open file - XmlNodeRef xmlRoot = GetISystem()->LoadXmlFromFile(szFullPathBuf); - if (!xmlRoot) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": File \"%s\" not found!", pcPath); - return false; - } - - // Load config for active platform - sCurThreadConfigFilename = pcPath; - const char* strPlatformId = IdentifyPlatform(); - CryFixedStringT<32> tmpPlatformStr; - bool retValue = false; - - // Try load common platform settings - tmpPlatformStr.Format("%s_Common", strPlatformId); - LoadPlatformConfig(xmlRoot, tmpPlatformStr.c_str()); - -#if defined(CRY_PLATFORM_DESKTOP) - // Handle PC specifically as we do not know the core setup of the executing machine. - // Try and find the next power of 2 core setup. Otherwise fallback to a lower power of 2 core setup spec - - // Try and load next pow of 2 setup for active pc core configuration - const unsigned int numCPUs = ((CSystem*)GetISystem())->GetCPUFeatures()->GetLogicalCPUCount(); - uint32 i = numCPUs; - for (; i > 0; --i) - { - tmpPlatformStr.Format("%s_%i", strPlatformId, i); - retValue = LoadPlatformConfig(xmlRoot, tmpPlatformStr.c_str()); - if (retValue) - { - break; - } - } - - if (retValue && i != numCPUs) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": (%s: %u core) Unable to find platform config \"%s\". Next valid config found was %s_%u.", - strPlatformId, numCPUs, tmpPlatformStr.c_str(), strPlatformId, i); - } - -#else - tmpPlatformStr.Format("%s", strPlatformId); - retValue = LoadPlatformConfig(xmlRoot, strPlatformId); -#endif - - // Print out info - if (retValue) - { - CryLogAlways(": Thread profile loaded: \"%s\" (%s) ", tmpPlatformStr.c_str(), pcPath); - } - else - { - // Could not find any matching platform - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": Active platform identifier string \"%s\" not found in config \"%s\".", strPlatformId, sCurThreadConfigFilename); - } - - sCurThreadConfigFilename = ""; - return retValue; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadConfigManager::ConfigLoaded() const -{ - return !m_threadConfig.empty(); -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadConfigManager::LoadPlatformConfig(const XmlNodeRef& rXmlRoot, const char* sPlatformId) -{ - // Validate node - if (!rXmlRoot->isTag("ThreadConfig")) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": Unable to find root xml node \"ThreadConfig\""); - return false; - } - - // Find active platform - const uint32 numPlatforms = rXmlRoot->getChildCount(); - for (uint32 i = 0; i < numPlatforms; ++i) - { - const XmlNodeRef xmlPlatformNode = rXmlRoot->getChild(i); - - // Is platform node - if (!xmlPlatformNode->isTag("Platform")) - { - continue; - } - - // Is has Name attribute - if (!xmlPlatformNode->haveAttr("Name")) - { - continue; - } - - // Is platform of interest - const char* platformName = xmlPlatformNode->getAttr("Name"); - if (_stricmp(sPlatformId, platformName) == 0) - { - // Load platform - LoadThreadDefaultConfig(xmlPlatformNode); - LoadPlatformThreadConfigs(xmlPlatformNode); - return true; - } - } - - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadPlatformThreadConfigs(const XmlNodeRef& rXmlPlatformRef) -{ - // Get thread configurations for active platform - const uint32 numThreads = rXmlPlatformRef->getChildCount(); - for (uint32 j = 0; j < numThreads; ++j) - { - const XmlNodeRef xmlThreadNode = rXmlPlatformRef->getChild(j); - - if (!xmlThreadNode->isTag("Thread")) - { - continue; - } - - // Ensure thread config has name - if (!xmlThreadNode->haveAttr("Name")) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Thread node without \"name\" attribute encountered."); - continue; - } - - // Load thread config - SThreadConfig loadedThreadConfig = SThreadConfig(m_defaultConfig); - LoadThreadConfig(xmlThreadNode, loadedThreadConfig); - - // Get thread name and check if it contains wildcard characters - const char* szThreadName = xmlThreadNode->getAttr("Name"); - bool bWildCard = strchr(szThreadName, '*') ? true : false; - ThreadConfigMap& threadConfig = bWildCard ? m_wildcardThreadConfig : m_threadConfig; - - // Check for duplicate and override it with new config if found - if (threadConfig.find(szThreadName) != threadConfig.end()) - { - CryLogAlways(": [XML Parsing] Thread with name \"%s\" already loaded. Overriding with new configuration", szThreadName); - threadConfig[szThreadName] = loadedThreadConfig; - continue; - } - - // Store new thread config - std::pair res; - res = threadConfig.insert(ThreadConfigMapPair(CryFixedStringT(szThreadName), loadedThreadConfig)); - - // Store name (ref to key) - SThreadConfig& rMapThreadConfig = res.first->second; - rMapThreadConfig.szThreadName = res.first->first.c_str(); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadConfigManager::LoadThreadDefaultConfig(const XmlNodeRef& rXmlPlatformRef) -{ - // Find default thread config node - const uint32 numNodes = rXmlPlatformRef->getChildCount(); - for (uint32 j = 0; j < numNodes; ++j) - { - const XmlNodeRef xmlNode = rXmlPlatformRef->getChild(j); - - // Load default config - if (xmlNode->isTag("ThreadDefault")) - { - LoadThreadConfig(xmlNode, m_defaultConfig); - return true; - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadAffinity(const XmlNodeRef& rXmlThreadRef, uint32& rAffinity, SThreadConfig::TThreadParamFlag& rParamActivityFlag) -{ - const char* szValidCharacters = "-,0123456789"; - uint32 affinity = 0; - - // Validate node - if (!rXmlThreadRef->haveAttr("Affinity")) - { - return; - } - - // Validate token - CryFixedStringT<32> affinityRawStr(rXmlThreadRef->getAttr("Affinity")); - if (affinityRawStr.empty()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Empty attribute \"Affinity\" encountered"); - return; - } - - if (affinityRawStr.compareNoCase("ignore") == 0) - { - // Param is inactive, clear bit - rParamActivityFlag &= ~SThreadConfig::eThreadParamFlag_Affinity; - return; - } - - CryFixedStringT<32>::size_type nPos = affinityRawStr.find_first_not_of(" -,0123456789"); - if (nPos != CryFixedStringT<32>::npos) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, - ": [XML Parsing] Invalid character \"%c\" encountered in \"Affinity\" attribute. Valid characters:\"%s\" Offending token:\"%s\"", affinityRawStr.at(nPos), - szValidCharacters, affinityRawStr.c_str()); - return; - } - - // Tokenize comma separated string - int pos = 0; - CryFixedStringT<32> affnityTokStr = affinityRawStr.Tokenize(",", pos); - while (!affnityTokStr.empty()) - { - affnityTokStr.Trim(); - - long affinityId = strtol(affnityTokStr.c_str(), NULL, 10); - if (affinityId == LONG_MAX || affinityId == LONG_MIN) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Unknown value \"%s\" encountered for attribute \"Affinity\"", affnityTokStr.c_str()); - return; - } - - // Allow scheduler to pick thread - if (affinityId == -1) - { - affinity = ~0; - break; - } - - // Set affinity bit - affinity |= BIT(affinityId); - - // Move to next token - affnityTokStr = affinityRawStr.Tokenize(",", pos); - } - - // Set affinity reference - rAffinity = affinity; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadPriority(const XmlNodeRef& rXmlThreadRef, int32& rPriority, SThreadConfig::TThreadParamFlag& rParamActivityFlag) -{ - const char* szValidCharacters = "-,0123456789"; - - // Validate node - if (!rXmlThreadRef->haveAttr("Priority")) - { - return; - } - - // Validate token - CryFixedStringT<32> threadPrioStr(rXmlThreadRef->getAttr("Priority")); - threadPrioStr.Trim(); - if (threadPrioStr.empty()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Empty attribute \"Priority\" encountered"); - return; - } - - if (threadPrioStr.compareNoCase("ignore") == 0) - { - // Param is inactive, clear bit - rParamActivityFlag &= ~SThreadConfig::eThreadParamFlag_Priority; - return; - } - - // Test for character string (no numbers allowed) - if (threadPrioStr.find_first_of(szValidCharacters) == CryFixedStringT<32>::npos) - { - threadPrioStr.MakeLower(); - - // Set priority - if (threadPrioStr.compare("below_normal") == 0) - { - rPriority = THREAD_PRIORITY_BELOW_NORMAL; - } - else if (threadPrioStr.compare("normal") == 0) - { - rPriority = THREAD_PRIORITY_NORMAL; - } - else if (threadPrioStr.compare("above_normal") == 0) - { - rPriority = THREAD_PRIORITY_ABOVE_NORMAL; - } - else if (threadPrioStr.compare("idle") == 0) - { - rPriority = THREAD_PRIORITY_IDLE; - } - else if (threadPrioStr.compare("lowest") == 0) - { - rPriority = THREAD_PRIORITY_LOWEST; - } - else if (threadPrioStr.compare("highest") == 0) - { - rPriority = THREAD_PRIORITY_HIGHEST; - } - else if (threadPrioStr.compare("time_critical") == 0) - { - rPriority = THREAD_PRIORITY_TIME_CRITICAL; - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Platform unsupported value \"%s\" encountered for attribute \"Priority\"", threadPrioStr.c_str()); - return; - } - } - // Test for number string (no alphabetical characters allowed) - else if (threadPrioStr.find_first_not_of(szValidCharacters) == CryFixedStringT<32>::npos) - { - long numValue = strtol(threadPrioStr.c_str(), NULL, 10); - if (numValue == LONG_MAX || numValue == LONG_MIN) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Unsupported number type \"%s\" for for attribute \"Priority\"", threadPrioStr.c_str()); - return; - } - - // Set priority - rPriority = numValue; - } - else - { - // String contains characters and numbers - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Unsupported type \"%s\" encountered for attribute \"Priority\". Token containers numbers and characters", threadPrioStr.c_str()); - return; - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadDisablePriorityBoost(const XmlNodeRef& rXmlThreadRef, bool& rPriorityBoost, SThreadConfig::TThreadParamFlag& rParamActivityFlag) -{ - // Validate node - if (!rXmlThreadRef->haveAttr("DisablePriorityBoost")) - { - return; - } - - // Extract bool info - CryFixedStringT<16> sAttribToken(rXmlThreadRef->getAttr("DisablePriorityBoost")); - sAttribToken.Trim(); - sAttribToken.MakeLower(); - - if (sAttribToken.compare("ignore") == 0) - { - // Param is inactive, clear bit - rParamActivityFlag &= ~SThreadConfig::eThreadParamFlag_PriorityBoost; - return; - } - else if (sAttribToken.compare("true") == 0 || sAttribToken.compare("1") == 0) - { - rPriorityBoost = true; - } - else if (sAttribToken.compare("false") == 0 || sAttribToken.compare("0") == 0) - { - rPriorityBoost = false; - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Unsupported bool type \"%s\" encountered for attribute \"DisablePriorityBoost\"", - rXmlThreadRef->getAttr("DisablePriorityBoost")); - return; - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadStackSize(const XmlNodeRef& rXmlThreadRef, uint32& rStackSize, SThreadConfig::TThreadParamFlag& rParamActivityFlag) -{ - const char* sValidCharacters = "0123456789"; - - if (rXmlThreadRef->haveAttr("StackSizeKB")) - { - // Read stack size - CryFixedStringT<32> stackSize(rXmlThreadRef->getAttr("StackSizeKB")); - - // Validate stack size - if (stackSize.empty()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Empty attribute \"StackSize\" encountered"); - return; - } - else if (stackSize.compareNoCase("ignore") == 0) - { - // Param is inactive, clear bit - rParamActivityFlag &= ~SThreadConfig::eThreadParamFlag_StackSize; - return; - } - else if (stackSize.find_first_not_of(sValidCharacters) == CryFixedStringT<32>::npos) - { - // Convert string to long - long stackSizeVal = strtol(stackSize.c_str(), NULL, 10); - if (stackSizeVal == LONG_MAX || stackSizeVal == LONG_MIN) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Invalid number for \"StackSize\" encountered. \"%s\"", stackSize.c_str()); - return; - } - else if (stackSizeVal <= 0 || stackSizeVal > sPlausibleStackSizeLimitKB) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] \"StackSize\" value not plausible \"%" PRId64 "KB\"", (int64)stackSizeVal); - return; - } - - // Set stack size - rStackSize = stackSizeVal * 1024; // Convert to bytes - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadThreadConfig(const XmlNodeRef& rXmlThreadRef, SThreadConfig& rThreadConfig) -{ - LoadAffinity(rXmlThreadRef, rThreadConfig.affinityFlag, rThreadConfig.paramActivityFlag); - LoadPriority(rXmlThreadRef, rThreadConfig.priority, rThreadConfig.paramActivityFlag); - LoadDisablePriorityBoost(rXmlThreadRef, rThreadConfig.bDisablePriorityBoost, rThreadConfig.paramActivityFlag); - LoadStackSize(rXmlThreadRef, rThreadConfig.stackSizeBytes, rThreadConfig.paramActivityFlag); -} - -////////////////////////////////////////////////////////////////////////// -const char* CThreadConfigManager::IdentifyPlatform() -{ -#if defined(AZ_RESTRICTED_PLATFORM) -#include AZ_RESTRICTED_FILE(ThreadConfigManager_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(ANDROID) - return "android"; -#elif defined(LINUX) - return "linux"; -#elif defined(APPLE) - return "mac"; -#elif defined(WIN32) || defined(WIN64) - return "pc"; -#else -#error "Undefined platform" -#endif -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::DumpThreadConfigurationsToLog() -{ -#if !defined(RELEASE) - - // Print header - CryLogAlways("== Thread Startup Config List (\"%s\") ==", IdentifyPlatform()); - - // Print loaded default config - CryLogAlways(" (Default) 1. \"%s\" (StackSize:%uKB | Affinity:%u | Priority:%i | PriorityBoost:\"%s\")", m_defaultConfig.szThreadName, m_defaultConfig.stackSizeBytes / 1024, - m_defaultConfig.affinityFlag, m_defaultConfig.priority, m_defaultConfig.bDisablePriorityBoost ? "disabled" : "enabled"); - - // Print loaded thread configs - int listItemCounter = 1; - ThreadConfigMapConstIter iter = m_threadConfig.begin(); - ThreadConfigMapConstIter iterEnd = m_threadConfig.end(); - for (; iter != iterEnd; ++iter) - { - const SThreadConfig& threadConfig = iter->second; - CryLogAlways("%3d.\"%s\" %s (StackSize:%uKB %s | Affinity:%u %s | Priority:%i %s | PriorityBoost:\"%s\" %s)", ++listItemCounter, - threadConfig.szThreadName, (threadConfig.paramActivityFlag & SThreadConfig::eThreadParamFlag_ThreadName) ? "" : "(ignored)", - threadConfig.stackSizeBytes / 1024u, (threadConfig.paramActivityFlag & SThreadConfig::eThreadParamFlag_StackSize) ? "" : "(ignored)", - threadConfig.affinityFlag, (threadConfig.paramActivityFlag & SThreadConfig::eThreadParamFlag_Affinity) ? "" : "(ignored)", - threadConfig.priority, (threadConfig.paramActivityFlag & SThreadConfig::eThreadParamFlag_Priority) ? "" : "(ignored)", - !threadConfig.bDisablePriorityBoost ? "enabled" : "disabled", (threadConfig.paramActivityFlag & SThreadConfig::eThreadParamFlag_PriorityBoost) ? "" : "(ignored)"); - } -#endif -} diff --git a/Code/CryEngine/CrySystem/ThreadConfigManager.h b/Code/CryEngine/CrySystem/ThreadConfigManager.h deleted file mode 100644 index ef0c9dca3d..0000000000 --- a/Code/CryEngine/CrySystem/ThreadConfigManager.h +++ /dev/null @@ -1,137 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include -#include "IThreadConfigManager.h" - -/* -ThreadConfigManager: -Loads a thread configuration from an xml file and stores them. - -== XML File Layout and Rules: === - -= Platform names = -(case insensitive) -"ANDROID" -"PC" -"MAC" -etc. - -= Basic Layout = - - - - - -... - - - -... - - - -= Parser Order for Platform = -1. PlatformName_Common (valid for all potential platform configurations. Can be overridden by concert platform configuration) -2. PlatformName or PlatformName_X (for platforms with unknown CPU count where X is the number of potential cores. The equal or next lower matching configuration for the identified core count at runtime will be taken) - -Note: Overriding of thread configuration by later parsed configuration allowed. - -= and XML attributes = - -!!! -Note: Use "ignore" as value if you do not want the thread system to set the value specifically! - If a value is not defines the value of the parameter will be used. - This is useful when dealing with 3rdParty threads where you are not in control of the parameter setup. -!!! - -Name: - "x" (string) : Name of thread - "x*y" (string) : Name of thread with wildcard character - -Affinity: - "-1" : Put SW thread affinity in the hands of the scheduler - (default) - - "x" : Run thread on specified core - "x, y, ..." : Run thread on specified cores - -Priority: - "idle" : Hint to CryEngine to run thread with pre-set priority - "below_normal" : Hint to CryEngine to run thread with pre-set priority - "normal" : Hint to CryEngine to run thread with pre-set priority - (default) - - "above_normal" : Hint to CryEngine to run thread with pre-set priority - "highest" : Hint to CryEngine to run thread with pre-set priority - "time_critical" : Hint to CryEngine to run thread with pre-set priority - "x" (number) : User defined thread priority number - -StackSizeKB: - "0" : Let platform decide on the stack size - (default) - - "x" : Create thread with "x" KB of stack size - -DisablePriorityBoost: - "true" : Disable priority boosting - (default) - - "false" : Enable priority boosting -*/ - -class CThreadConfigManager - : public IThreadConfigManager -{ -public: - typedef std::map, SThreadConfig> ThreadConfigMap; - typedef std::pair, SThreadConfig> ThreadConfigMapPair; - typedef std::map, SThreadConfig>::iterator ThreadConfigMapIter; - typedef std::map, SThreadConfig>::const_iterator ThreadConfigMapConstIter; - -public: - CThreadConfigManager(); - ~CThreadConfigManager() - { - } - - // Called once during System startup. - // Loads the thread configuration for the executing platform from file. - virtual bool LoadConfig(const char* pcPath) override; - - // Returns true if a config has been loaded - virtual bool ConfigLoaded() const override; - - // Gets the thread configuration for the specified thread on the active platform. - // If no matching config is found a default configuration is returned - // (which does not have the same name as the search string). - virtual const SThreadConfig* GetThreadConfig(const char* sThreadName, ...) override; - virtual const SThreadConfig* GetDefaultThreadConfig() const override; - - virtual void DumpThreadConfigurationsToLog() override; - -private: - const char* IdentifyPlatform(); - - const SThreadConfig* GetThreadConfigImpl(const char* cThreadName); - - bool LoadPlatformConfig(const XmlNodeRef& rXmlRoot, const char* sPlatformId); - - void LoadPlatformThreadConfigs(const XmlNodeRef& rXmlPlatformRef); - bool LoadThreadDefaultConfig(const XmlNodeRef& rXmlPlatformRef); - void LoadThreadConfig(const XmlNodeRef& rXmlThreadRef, SThreadConfig& rThreadConfig); - - void LoadAffinity(const XmlNodeRef& rXmlThreadRef, uint32& rAffinity, SThreadConfig::TThreadParamFlag& rParamActivityFlag); - void LoadPriority(const XmlNodeRef& rXmlThreadRef, int32& rPriority, SThreadConfig::TThreadParamFlag& rParamActivityFlag); - void LoadDisablePriorityBoost(const XmlNodeRef& rXmlThreadRef, bool& rPriorityBoost, SThreadConfig::TThreadParamFlag& rParamActivityFlag); - void LoadStackSize(const XmlNodeRef& rXmlThreadRef, uint32& rStackSize, SThreadConfig::TThreadParamFlag& rParamActivityFlag); - -private: - ThreadConfigMap m_threadConfig; // Note: The map key is referenced by as const char* by the value's storage class. Other containers may not support this behaviour as they will re-allocate memory as they grow/shrink. - ThreadConfigMap m_wildcardThreadConfig; - SThreadConfig m_defaultConfig; -}; diff --git a/Code/CryEngine/CrySystem/ThreadInfo.cpp b/Code/CryEngine/CrySystem/ThreadInfo.cpp deleted file mode 100644 index 14285215b8..0000000000 --- a/Code/CryEngine/CrySystem/ThreadInfo.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "ThreadInfo.h" -#include "System.h" - -//////////////////////////////////////////////////////////////////////////// - - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define THREADINFO_CPP_SECTION_1 1 -#define THREADINFO_CPP_SECTION_2 2 -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION THREADINFO_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(ThreadInfo_cpp) -#endif - -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -#if AZ_LEGACY_CRYSYSTEM_TRAIT_THREADINFO_WINDOWS_STYLE -//////////////////////////////////////////////////////////////////////////// -void SThreadInfo::GetCurrentThreads(TThreadInfo& threadsOut) -{ - HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); - DWORD currProcessId = GetCurrentProcessId(); - if (h != INVALID_HANDLE_VALUE) - { - THREADENTRY32 te; - te.dwSize = sizeof(te); - if (Thread32First(h, &te)) - { - do - { - if (te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(te.th32OwnerProcessID)) - { - if (te.th32OwnerProcessID == currProcessId) - { - threadsOut[te.th32ThreadID] = CryThreadGetName(te.th32ThreadID); - } - } - te.dwSize = sizeof(te); - } while (Thread32Next(h, &te)); - } - CloseHandle(h); - } -} - -//////////////////////////////////////////////////////////////////////////// -void SThreadInfo::OpenThreadHandles(TThreads& threadsOut, const TThreadIds& threadIds /* = TThreadIds()*/, bool ignoreCurrThread /* = true*/) -{ - TThreadIds threadids = threadIds; - if (threadids.empty()) - { - TThreadInfo threads; - GetCurrentThreads(threads); - DWORD currThreadId = GetCurrentThreadId(); - for (TThreadInfo::iterator it = threads.begin(), end = threads.end(); it != end; ++it) - { - if (!ignoreCurrThread || it->first != currThreadId) - { - threadids.push_back(it->first); - } - } - } - for (TThreadIds::iterator it = threadids.begin(), end = threadids.end(); it != end; ++it) - { - SThreadHandle thread; - thread.Id = *it; - thread.Handle = OpenThread(THREAD_ALL_ACCESS, FALSE, *it); - threadsOut.push_back(thread); - } -} - -//////////////////////////////////////////////////////////////////////////// -void SThreadInfo::CloseThreadHandles(const TThreads& threads) -{ - for (TThreads::const_iterator it = threads.begin(), end = threads.end(); it != end; ++it) - { - CloseHandle(it->Handle); - } -} - -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION THREADINFO_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(ThreadInfo_cpp) -#elif defined(LINUX) || defined(APPLE) -void SThreadInfo::GetCurrentThreads(TThreadInfo& threadsOut) -{ - assert(false); // not implemented! -} - -//////////////////////////////////////////////////////////////////////////// -void SThreadInfo::OpenThreadHandles(TThreads& threadsOut, const TThreadIds& threadIds /* = TThreadIds()*/, bool ignoreCurrThread /* = true*/) -{ - assert(false); // not implemented! -} - -//////////////////////////////////////////////////////////////////////////// -void SThreadInfo::CloseThreadHandles(const TThreads& threads) -{ - assert(false); // not implemented! -} - -//////////////////////////////////////////////////////////////////////////// -#endif diff --git a/Code/CryEngine/CrySystem/ThreadInfo.h b/Code/CryEngine/CrySystem/ThreadInfo.h deleted file mode 100644 index 4bcacf71d5..0000000000 --- a/Code/CryEngine/CrySystem/ThreadInfo.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_THREADINFO_H -#define CRYINCLUDE_CRYSYSTEM_THREADINFO_H -#pragma once - - -struct SThreadInfo -{ -public: - struct SThreadHandle - { - HANDLE Handle; - uint32 Id; - }; - - typedef std::vector TThreadIds; - typedef std::vector TThreads; - typedef std::map TThreadInfo; - - // returns thread info - static void GetCurrentThreads(TThreadInfo& threadsOut); - - // fills threadsOut vector with thread handles of given thread ids; if threadIds vector is emtpy it fills all running threads - // if ignoreCurrThread is true it will not return the current thread - static void OpenThreadHandles(TThreads& threadsOut, const TThreadIds& threadIds = TThreadIds(), bool ignoreCurrThread = true); - - // closes thread handles; should be called whenever GetCurrentThreads was called! - static void CloseThreadHandles(const TThreads& threads); -}; - -#endif // CRYINCLUDE_CRYSYSTEM_THREADINFO_H diff --git a/Code/CryEngine/CrySystem/ThreadTask.cpp b/Code/CryEngine/CrySystem/ThreadTask.cpp deleted file mode 100644 index d1ae7304e6..0000000000 --- a/Code/CryEngine/CrySystem/ThreadTask.cpp +++ /dev/null @@ -1,1046 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "ThreadTask.h" -#include "CPUDetect.h" -#include "IConsole.h" -#include "System.h" - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define THREADTASK_CPP_SECTION_1 1 -#define THREADTASK_CPP_SECTION_2 2 -#endif - -#ifdef WIN32 -#define WIN32_LEAN_AND_MEAN -#include -#endif //WIN32 - -#include "BitFiddling.h" - -#if defined(ANDROID) -#include -#include -#endif -#if defined(LINUX) - -#endif -#if defined(APPLE) -// include for thread_policy_set -#include -#include -#endif - -#include - -////////////////////////////////////////////////////////////////////////// -CThreadTask_Thread::CThreadTask_Thread(CThreadTaskManager* pTaskMgr, const char* sName, - int nIndex, int nProcessor, int nThreadPriority, ThreadPoolHandle poolHandle /* = -1*/) - : tasks(64) -{ - m_nThreadPriority = nThreadPriority; - m_pTaskManager = pTaskMgr; - m_sThreadName = sName; - bStopThread = false; - bRunning = false; - m_hThreadHandle = 0; - m_nThreadIndex = nIndex; - m_nProcessor = nProcessor; - m_poolHandle = poolHandle; -} - -CThreadTask_Thread::~CThreadTask_Thread() -{ - while (!tasks.empty()) - { - tasks.pop()->m_pThread = 0; - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::SingleUpdate() -{ - while (true) - { - m_pProcessingTask = NULL; - - { - if (tasks.empty()) - { - break; - } - // remove from queue - m_pProcessingTask = tasks.pop(); - } - - if (m_pProcessingTask) - { - m_pProcessingTask->m_pTask->OnUpdate(); - } - - if (m_pProcessingTask) // push it back - { - tasks.push(m_pProcessingTask); - } - - if (bStopThread) - { - break; - } - } - - if (m_poolHandle != -1) // if this thread is in the pool, we need to reassign some tasks for it - { - m_pTaskManager->BalanceThreadInPool(this); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::Run() -{ - Init(); - - bRunning = true; - while (!bStopThread) - { - while (tasks.empty() && !bStopThread) - { - m_waitForTasks.Wait(); - } - - if (!bStopThread) - { - SingleUpdate(); - } - } - bRunning = false; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::Cancel() -{ - bStopThread = true; - m_waitForTasks.Set(); - Stop(); - - // for blocking thread notify the blocking task - if (m_nThreadIndex == -1) - { - if (m_pProcessingTask && m_pProcessingTask->m_params.nFlags & THREAD_TASK_BLOCKING) // check if we have a blocking task - { - if (m_pProcessingTask->m_pTask) // cancel it - { - m_pProcessingTask->m_pTask->Stop(); - } - } - } - - WaitForThread(); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::Terminate() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::AddTask(SThreadTaskInfo* pTaskInfo) -{ - pTaskInfo->m_pThread = this; - tasks.push(pTaskInfo); - m_waitForTasks.Set(); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::RemoveTask(SThreadTaskInfo* pTaskInfo) -{ - if (!pTaskInfo) - { - return; - } - - if (m_pProcessingTask == pTaskInfo) - { - pTaskInfo->m_pThread = NULL; - m_pProcessingTask = NULL; - return; - } - - // search for task(mirrored search because of locklessness) - bool bFound = false; - Tasks newTasks; - while (!tasks.empty()) - { - SThreadTaskInfo* pTask = tasks.pop(); - if (pTask == pTaskInfo) - { - pTaskInfo->m_pThread = NULL; - bFound = true; - break; - } - if (pTask) - { - newTasks.push(pTask); - } - } - (void)bFound; - // Don't assert if newTasks is empty. There is a thread race condition between - // the thread shutting down and this code being executed (both update/use - // m_pProcessTask with no locks). newTasks will be empty - // and bFound == false when the race condition is won by the task thread and - // not by the thread that is executing this code - CRY_ASSERT(bFound || newTasks.empty()); - - // fill back - while (!newTasks.empty()) - { - tasks.push(newTasks.pop()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::RemoveAllTasks() -{ - while (!tasks.empty()) - { - tasks.pop()->m_pThread = NULL; - } -} - -void CThreadTask_Thread::Init() -{ -#if AZ_TRAIT_OS_USE_WINDOWS_THREADS - m_hThreadHandle = GetCurrentThread(); -#endif - - // Name this thread. - CryThreadSetName(GetCurrentThreadId(), m_sThreadName); - - // Set affinity - if (m_nProcessor > 0) - { - ChangeProcessor(m_nProcessor); - } -#if defined(WIN32) - ((CSystem*)gEnv->pSystem)->EnableFloatExceptions(g_cvars.sys_float_exceptions); -#endif -} - -void CThreadTask_Thread::ChangeProcessor(int nProcessor) -{ - // note this function is not thread-safe - m_nProcessor = nProcessor; -#if defined(WIN32) - DWORD_PTR mask1, mask2; - GetProcessAffinityMask(GetCurrentProcess(), &mask1, &mask2); - if (BIT64(m_nProcessor) & mask1) // Check if we have this affinity - { - SetThreadAffinityMask(m_hThreadHandle, BIT64(m_nProcessor)); - } - else // Reserve CPU 1 for main thread. - { - SetThreadAffinityMask(m_hThreadHandle, (mask1 & (~1))); - } - assert(THREAD_PRIORITY_IDLE <= m_nThreadPriority && m_nThreadPriority <= THREAD_PRIORITY_TIME_CRITICAL); - SetThreadPriority(m_hThreadHandle, m_nThreadPriority); -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION THREADTASK_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(ThreadTask_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(ANDROID) - int err, syscallres; - pid_t pid = gettid(); - syscallres = syscall(__NR_sched_setaffinity, pid, sizeof(nProcessor), &nProcessor); - if (syscallres) - { - err = errno; - CryLog("Error in the syscall setaffinity: mask=%d=0x%x sysconf#=%ld err=%d=0x%x", nProcessor, nProcessor, sysconf(_SC_NPROCESSORS_ONLN), err, err); - } -#elif defined(LINUX) - // Check if the processor is valid - assert(nProcessor < sysconf(_SC_NPROCESSORS_ONLN)); - cpu_set_t cpuset; - CPU_ZERO(&cpuset); - CPU_SET(nProcessor, &cpuset); - pthread_t current_thread = pthread_self(); - int ret = pthread_setaffinity_np(current_thread, sizeof(cpu_set_t), &cpuset); - (void) ret; - // check if the operation completed succesfully - assert(ret == 0 && "ChangeProcessor operation failed"); -#elif defined(APPLE) - assert(nProcessor != 0 && "CThreadTask_Thread::ChangeProcessor - If " - "nProcessor is equal to 0, the default afinity will be applied " - "to the thread. Can be fixed by incrementing nProcess by 1."); - thread_affinity_policy_data_t thread_affinity; - thread_affinity.affinity_tag = nProcessor; - thread_policy_set(pthread_mach_thread_np(pthread_self()), THREAD_AFFINITY_POLICY, (thread_policy_t)&thread_affinity, THREAD_AFFINITY_POLICY_COUNT); - //CryWarning(VALIDATOR_MODULE_SYSTEM,VALIDATOR_WARNING, "CThreadTask_Thread::ChangeProcessor: Feature is not supported on Mac OS X."); -#else - assert(0); -#endif -} - -////////////////////////////////////////////////////////////////////////// -CThreadTaskManager::CThreadTaskManager() -{ - m_nMaxThreads = 1; - - SetThreadName(GetCurrentThreadId(), "Main"); - - m_systemThreads.push_back(GetCurrentThreadId()); -} - -////////////////////////////////////////////////////////////////////////// -CThreadTaskManager::~CThreadTaskManager() -{ - CloseThreads(); - - AUTO_MODIFYLOCK(m_threadsPoolsLock); - while (!m_threadsPools.empty()) - { -#if !defined(NDEBUG) - bool res = -#endif - DestroyThreadsPool(m_threadsPools.begin()->m_hHandle); - assert(res); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::StopAllThreads() -{ - if (m_threads.empty()) - { - return; - } - - size_t i; - // Start from 2nd thread, 1st is main thread. - for (i = 1; i < m_threads.size(); i++) - { - CThreadTask_Thread* pThread = m_threads[i]; - pThread->Cancel(); - } - bool bAllStoped = true; - do - { - bAllStoped = true; - CrySleep(10); - for (i = 1; i < m_threads.size(); i++) - { - CThreadTask_Thread* pThread = m_threads[i]; - // Needs ReadWriteBarrier here. - if (pThread->bRunning) - { - bAllStoped = false; - } - } - } - while (!bAllStoped); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::CloseThreads() -{ - if (m_threads.size() > 0) - { - StopAllThreads(); - } - for (size_t i = MAIN_THREAD_INDEX, numThreads = m_threads.size(); i < numThreads; i++) - { - delete m_threads[i]; - } - m_threads.clear(); - //make sure blocking threads are cancelled - for (bool repeat = true; repeat; ) - { - CThreadTask_Thread* thr = NULL; - { - CryAutoCriticalSection lock(m_threadRemove); - - if (!m_blockingThreads.empty()) - { - thr = *m_blockingThreads.rbegin(); - m_blockingThreads.pop_back(); - } - } - - if (thr) - { - thr->Cancel(); - delete thr; - } - else - { - repeat = false; - } - } - - m_blockingThreads.clear(); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::InitThreads() -{ - m_nMaxThreads = gEnv->IsDedicated() ? 1 : 4; - CloseThreads(); - - // Create a dummy thread that is used for main thread. - m_threads.resize(1); - m_threads[0] = new CThreadTask_Thread(this, "Main Thread", 0, AFFINITY_MASK_MAINTHREAD, THREAD_PRIORITY_NORMAL); - - CCpuFeatures* pCPU = ((CSystem*)gEnv->pSystem)->GetCPUFeatures(); - - int nThreads = min((int)m_nMaxThreads, (int)pCPU->GetCPUCount()); - - if (nThreads < 1) - { - nThreads = 1; - } - int nAddThreads = nThreads - 1; - - char str[32]; - m_threads.resize(1 + nAddThreads); - for (int i = 0; i < nAddThreads; i++) - { - int nIndex = i + 1; - int nCPU = i + 1; - sprintf_s(str, "TaskThread%d", i); - if (i < m_nMaxThreads) - { - nCPU = ((CSystem*)gEnv->pSystem)->m_sys_TaskThread_CPU[i]->GetIVal(); - } - - // Clamp to random thread between 1 and max, avoid cpu 0 with main thread - if (nCPU >= nThreads) - { - nCPU = (rand() % (nThreads - 1)) + 1; - } - m_threads[nIndex] = new CThreadTask_Thread(this, str, nIndex, nCPU, THREAD_PRIORITY_NORMAL); - m_threads[nIndex]->Start(0, str, THREAD_PRIORITY_NORMAL, SIMPLE_THREAD_STACK_SIZE_KB * 1024); - } - RescheduleTasks(); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::SetMaxThreadCount(int nMaxThreads) -{ - if (nMaxThreads == m_nMaxThreads) - { - return; - } - - m_nMaxThreads = nMaxThreads; - - bool bReallocateThreads = false; - if (m_nMaxThreads < (int)m_threads.size()) - { - bReallocateThreads = true; - } - if (m_nMaxThreads > (int)m_threads.size()) - { - CCpuFeatures* pCPU = ((CSystem*)gEnv->pSystem)->GetCPUFeatures(); - if (m_threads.size() < pCPU->GetCPUCount()) - { - bReallocateThreads = true; - } - } - if (bReallocateThreads) - { - CloseThreads(); - InitThreads(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::RegisterTask(IThreadTask* pTask, const SThreadTaskParams& options) -{ - if (!pTask) - { - assert(0); - return; - } - SThreadTaskInfo* pTaskInfo = pTask->GetTaskInfo(); - pTaskInfo->m_pTask = pTask; - pTaskInfo->m_params = options; - - if ((options.nFlags & THREAD_TASK_BLOCKING) == 0) - { - ScheduleTask(pTaskInfo); - } - else - { - CryAutoCriticalSection lock(m_threadRemove); - // Blocking task will need it`s own thread. - const int threadPriority = THREAD_PRIORITY_NORMAL; - CThreadTask_Thread* pThread = - new CThreadTask_Thread(this, options.name, -1, options.nPreferedThread, threadPriority); - pThread->Start(0, (char*)options.name, threadPriority, options.nStackSizeKB * 1024); - pThread->AddTask(pTaskInfo); - - m_blockingThreads.push_back(pThread); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::UnregisterTask(IThreadTask* pTask) -{ - assert(pTask); - if (!pTask) - { - return; - } - SThreadTaskInfo* pTaskInfo = pTask->GetTaskInfo(); - assert(pTaskInfo); - - IThreadTask_Thread* pThread = pTaskInfo->m_pThread; - uint32 flags = pTaskInfo->m_params.nFlags; - - // Remove from thread. - if (pThread) - { - pThread->RemoveTask(pTaskInfo); - } - - pTask->Stop(); - - if (flags & THREAD_TASK_BLOCKING) - { - CThreadTask_Thread* thr = NULL; - { - CryAutoCriticalSection lock(m_threadRemove); - Threads::iterator end = m_blockingThreads.end(); - Threads::iterator toErase = std::find(m_blockingThreads.begin(), end, pThread); - - if (toErase != end) // impossible to find anything. no push_back done on m_blockingThreads - { - thr = *toErase; - m_blockingThreads.erase(toErase); - } - } - - if (thr) - { - thr->Cancel(); - delete thr; - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::ScheduleTask(SThreadTaskInfo* pTaskInfo) -{ - size_t i; - - if (pTaskInfo->m_pThread) - { - assert(0); - pTaskInfo->m_pThread->RemoveTask(pTaskInfo); - } - - CThreadTask_Thread* pGoodThread = NULL; - - if (pTaskInfo->m_params.nFlags & THREAD_TASK_ASSIGN_TO_POOL) - { - AUTO_READLOCK(m_threadsPoolsLock); - - // find the pool - CThreadsPool* pool = NULL; - size_t nSize = m_threadsPools.size(); - for (i = 0; i < nSize; ++i) - { - if (m_threadsPools[i].m_hHandle == pTaskInfo->m_params.nThreadsGroupId) - { - pool = &m_threadsPools[i]; - } - } - - if (pool) - { - // Find available thread for the task. - for (i = 0; i < (int)pool->m_Threads.size(); ++i) - { - CThreadTask_Thread* pThread = pool->m_Threads[i]; - const bool threadIsFree = pThread->tasks.empty() && pThread->m_pProcessingTask == NULL; - if (threadIsFree || pGoodThread == NULL) - { - pGoodThread = pThread; - if (threadIsFree) - { - break; - } - } - } - } - else - { - gEnv->pLog->LogError("[Error]Task manager: threads pool not found!"); - assert(0); - } - } - else if (pTaskInfo->m_params.nPreferedThread >= 0 && pTaskInfo->m_params.nPreferedThread < (int)m_threads.size()) - { - assert((int)m_threads.size() > pTaskInfo->m_params.nPreferedThread); - // Assign task to desired thread. - pGoodThread = m_threads[pTaskInfo->m_params.nPreferedThread]; - } - else - { - // Find available thread for the task. - for (i = MAIN_THREAD_INDEX + 1; i < (int)m_threads.size(); i++) - { - CThreadTask_Thread* pThread = m_threads[i]; - PREFAST_ASSUME(pThread); - if (pThread->tasks.empty() || pGoodThread == NULL) - { - pGoodThread = pThread; - if (pThread->tasks.empty()) - { - break; - } - } - } - } - if (!pGoodThread && !m_threads.empty()) - { - // Assign to last thread. - pGoodThread = m_threads[m_threads.size() - 1]; - } - - if (pGoodThread) - { - pGoodThread->AddTask(pTaskInfo); - } - else - { - m_unassignedTasks.push(pTaskInfo); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::RescheduleTasks() -{ - // Un-schedule all tasks. - for (int i = 0; i < (int)m_threads.size(); i++) - { - while (!m_threads[i]->tasks.empty()) - { - SThreadTaskInfo* pTask = m_threads[i]->tasks.pop(); - if (!pTask) - { - break; - } - if (pTask->m_params.nFlags & THREAD_TASK_BLOCKING) // Do not schedule blocking tasks. - { - m_threads[i]->tasks.push(pTask); - break; - } - pTask->m_pThread = NULL; - m_unassignedTasks.push(pTask); - } - } - - while (!m_unassignedTasks.empty()) - { - ScheduleTask(m_unassignedTasks.pop()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::OnUpdate() -{ - AZ_TRACE_METHOD(); - FUNCTION_PROFILER_LEGACYONLY(GetISystem(), PROFILE_SYSTEM); - - // Emulate single update of the main thread. - if (m_threads[0]) - { - m_threads[0]->SingleUpdate(); - } - - // assign unassigned tasks - while (!m_unassignedTasks.empty()) - { - ScheduleTask(m_unassignedTasks.pop()); - } - - // balance all pools - AUTO_READLOCK(m_threadsPoolsLock); - size_t nSize = m_threadsPools.size(); - for (size_t itPool = 0; itPool < nSize; ++itPool) - { - BalanceThreadsPool(m_threadsPools[itPool].m_hHandle); - } -} - -struct THREADNAME_INFO_TASK -{ - DWORD dwType; - LPCSTR szName; - DWORD dwThreadID; - DWORD dwFlags; -}; - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::SetThreadName(threadID dwThreadId, const char* sThreadName) -{ - if (dwThreadId == (THREADID_NULL)) - { - dwThreadId = GetCurrentThreadId(); - } - -#if defined(AZ_PROFILE_TELEMETRY) && AZ_TRAIT_OS_USE_WINDOWS_THREADS - AZStd::thread_desc desc; - desc.m_name = sThreadName; - // we broadcast to the "client" bus and then to the "driller" (profiling) bus - AZStd::ThreadEventBus::Broadcast(&AZStd::ThreadEventBus::Events::OnThreadEnter, AZStd::thread::id(dwThreadId), &desc); - AZStd::ThreadDrillerEventBus::Broadcast(&AZStd::ThreadDrillerEventBus::Events::OnThreadEnter, AZStd::thread::id(dwThreadId), &desc); -#endif - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_THREADTASK_EXCEPTIONS - ////////////////////////////////////////////////////////////////////////// - // Raise exception to set thread name for debugger. - ////////////////////////////////////////////////////////////////////////// - THREADNAME_INFO_TASK threadName; - threadName.dwType = 0x1000; - threadName.szName = sThreadName; - threadName.dwThreadID = dwThreadId; - threadName.dwFlags = 0; - - __try - { - RaiseException(0x406D1388, 0, sizeof(threadName) / sizeof(DWORD), (ULONG_PTR*)&threadName); - } - __except (EXCEPTION_CONTINUE_EXECUTION) - { - } -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION THREADTASK_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(ThreadTask_cpp) -#endif - - { - m_threadNameLock.Lock(); - m_threadNames[dwThreadId] = sThreadName; - m_threadNameLock.Unlock(); - } -} - -////////////////////////////////////////////////////////////////////////// -const char* CThreadTaskManager::GetThreadName(threadID dwThreadId) -{ - CryAutoCriticalSection lock(m_threadNameLock); - ThreadNames::const_iterator it = m_threadNames.find(dwThreadId); - if (it != m_threadNames.end()) - { - return it->second.c_str(); - } - - return ""; -} - -////////////////////////////////////////////////////////////////////////// -threadID CThreadTaskManager::GetThreadByName(const char* sThreadName) -{ - CryAutoCriticalSection lock(m_threadNameLock); - for (ThreadNames::const_iterator it = m_threadNames.begin(); it != m_threadNames.end(); ++it) - { - if (it->second.compareNoCase(sThreadName) == 0) - { - return it->first; - } - } - return 0; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::AddSystemThread(threadID nThreadId) -{ - CryAutoCriticalSection lock(m_systemThreadsLock); - m_systemThreads.push_back(nThreadId); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::RemoveSystemThread(threadID nThreadId) -{ - CryAutoCriticalSection lock(m_systemThreadsLock); - stl::find_and_erase(m_systemThreads, nThreadId); -} - -////////////////////////////////////////////////////////////////////////// -ThreadPoolHandle CThreadTaskManager::CreateThreadsPool(const ThreadPoolDesc& desc) -{ - AUTO_MODIFYLOCK(m_threadsPoolsLock); - - ThreadPoolHandle newId = m_threadsPools.empty() ? 0 : m_threadsPools.rbegin()->m_hHandle + 1; - - if (desc.AffinityMask == INVALID_AFFINITY) - { - assert(0); - return -1; - } - - // create the pool - m_threadsPools.push_back(CThreadsPool()); - CThreadsPool& rPool = m_threadsPools.back(); - - // assign the new handle - rPool.m_hHandle = newId; - - // fill up the desc - rPool.m_pDescription = desc; - - Threads& threads = rPool.m_Threads; - - size_t threadNameSize = desc.sPoolName.size() + 30; - std::vector threadName(threadNameSize); - uint32 iThread = 0; - for (uint32 nIndex = 0; nIndex < sizeof(desc.AffinityMask) * 8; ++nIndex) - { - // check if we have affinity mask bit set for this thread - if (!(desc.AffinityMask & (1 << nIndex))) - { - continue; - } - - const int32 nThreadPriority = (desc.nThreadPriority == -1) ? THREAD_PRIORITY_NORMAL : desc.nThreadPriority; - const int32 nThreadStackSizeKB = (desc.nThreadStackSizeKB == -1) ? SIMPLE_THREAD_STACK_SIZE_KB : desc.nThreadStackSizeKB; - - // create a thread - sprintf_s(&threadName[0], threadNameSize, "%s%d", desc.sPoolName.c_str(), iThread); - CThreadTask_Thread* thread = new CThreadTask_Thread(this, &threadName[0], iThread, nIndex, nThreadPriority, newId); - - // start thread - thread->Start(0, (char*)&threadName[0], nThreadPriority, nThreadStackSizeKB * 1024); - - // add to pool - threads.push_back(thread); - - iThread++; - } - - return newId; -} - -const bool CThreadTaskManager::DestroyThreadsPool(const ThreadPoolHandle& handle) -{ - AUTO_MODIFYLOCK(m_threadsPoolsLock); - - CThreadsPool* pPool = NULL; - size_t nSize = m_threadsPools.size(); - size_t iPool = 0; - for (; iPool < nSize; ++iPool) - { - if (m_threadsPools[iPool].m_hHandle == handle) - { - pPool = &m_threadsPools[iPool]; - break; - } - } - - if (pPool) - { - Threads& threads = pPool->m_Threads; - size_t nThreads = threads.size(); - for (size_t iThread = 0; iThread < nThreads; ++iThread) - { - CThreadTask_Thread* pThread = threads[iThread]; - PREFAST_ASSUME(pThread); - pThread->Cancel(); - assert(!(pThread->bRunning)); - delete pThread; - } - - m_threadsPools.erase(m_threadsPools.begin() + iPool); - return true; - } - return false; -} - -const bool CThreadTaskManager::GetThreadsPoolDesc(const ThreadPoolHandle handle, ThreadPoolDesc* pDesc) const -{ - AUTO_READLOCK(m_threadsPoolsLock); - - const CThreadsPool* pPool = NULL; - size_t iPool = 0, nSize = m_threadsPools.size(); - for (; iPool < nSize; ++iPool) - { - if (m_threadsPools[iPool].m_hHandle == handle) - { - pPool = &m_threadsPools[iPool]; - break; - } - } - - if (pPool) - { - if (pDesc) - { - *pDesc = pPool->m_pDescription; - return true; - } - } - - return false; -} - -const bool CThreadTaskManager::SetThreadsPoolAffinity(const ThreadPoolHandle handle, const ThreadPoolAffinityMask AffinityMask) -{ - CThreadsPool* pPool = NULL; - - AUTO_MODIFYLOCK(m_threadsPoolsLock); - - size_t iPool = 0, nSize = m_threadsPools.size(); - for (; iPool < nSize; ++iPool) - { - if (m_threadsPools[iPool].m_hHandle == handle) - { - pPool = &m_threadsPools[iPool]; - break; - } - } - - if (pPool) - { - return pPool->SetAffinity(AffinityMask); - } - - return false; -} - -void CThreadTaskManager::BalanceThreadsPool(const ThreadPoolHandle& handle) -{ - CThreadsPool* pPool = NULL; - - AUTO_READLOCK(m_threadsPoolsLock); - - size_t iPool = 0, nSize = m_threadsPools.size(); - for (; iPool < nSize; ++iPool) - { - if (m_threadsPools[iPool].m_hHandle == handle) - { - pPool = &m_threadsPools[iPool]; - break; - } - } - - if (pPool) - { - // balancing tasks in the pool - for (size_t itThread = 0, nThreads = pPool->m_Threads.size(); itThread < nThreads; ++itThread) - { - CThreadTask_Thread* pThread = pPool->m_Threads[itThread]; - if (pThread->tasks.empty()) // found free thread(without tasks) - { - BalanceThreadInPool(pThread, &pPool->m_Threads); - } - } - } - else - { - assert(0); - } -} - -void CThreadTaskManager::BalanceThreadInPool(CThreadTask_Thread* pFreeThread, Threads* pThreads /* = NULL */) -{ - assert(pFreeThread->m_poolHandle != -1); - - AUTO_READLOCK(m_threadsPoolsLock); - - if (pThreads == NULL) - { - CThreadsPool* pPool = NULL; - size_t iPool = 0, nSize = m_threadsPools.size(); - for (; iPool < nSize; ++iPool) - { - if (m_threadsPools[iPool].m_hHandle == pFreeThread->m_poolHandle) - { - pPool = &m_threadsPools[iPool]; - break; - } - } - - if (pPool) - { - pThreads = &pPool->m_Threads; - } - } - assert(pThreads); - PREFAST_ASSUME(pThreads); - // search for thread with tasks - for (size_t itAnotherThread = 0, nThreads = pThreads->size(); itAnotherThread < nThreads; ++itAnotherThread) - { - CThreadTask_Thread* pAnotherThread = (*pThreads)[itAnotherThread]; - if (pFreeThread == pAnotherThread) - { - continue; - } - if (pAnotherThread->tasks.empty()) - { - continue; - } - - // we found a thread with more than one task - SThreadTaskInfo* pTask = pAnotherThread->tasks.pop(); - if (pTask) - { - assert(pTask->m_pThread == pAnotherThread); - // reassign the last task to another thread - pFreeThread->AddTask(pTask); - break; // process next free thread - } - } -} - -void CThreadTaskManager::MarkThisThreadForDebugging(const char* name, bool bDump) -{ - bDump ? ::MarkThisThreadForDebugging(name) : ::UnmarkThisThreadFromDebugging(); -} - - -const bool CThreadTaskManager::CThreadsPool::SetAffinity(const ThreadPoolAffinityMask AffinityMask) -{ - // check if all threads in the pool are covered by the bits of this mask - if (CountBits(AffinityMask) != m_Threads.size()) - { - // wrong arguments - return false; - } - - // update affinity mask - m_pDescription.AffinityMask = AffinityMask; - - size_t itThread = 0; - for (uint32 nProcessorIndex = 0; nProcessorIndex < sizeof(AffinityMask) * 8; ++nProcessorIndex) - { - assert(itThread < m_Threads.size()); - // check if we have affinity mask bit set for this thread - if (!(AffinityMask & (1 << nProcessorIndex))) - { - continue; - } - - // changin thread's affinity in the pool - m_Threads[itThread]->ChangeProcessor(nProcessorIndex); - ++itThread; - } - return true; -} diff --git a/Code/CryEngine/CrySystem/ThreadTask.h b/Code/CryEngine/CrySystem/ThreadTask.h deleted file mode 100644 index e528fedf5f..0000000000 --- a/Code/CryEngine/CrySystem/ThreadTask.h +++ /dev/null @@ -1,181 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_THREADTASK_H -#define CRYINCLUDE_CRYSYSTEM_THREADTASK_H -#pragma once - - -#include -#include -#include - -#define MAIN_THREAD_INDEX 0 - -class CThreadTask_Thread; - - -void MarkThisThreadForDebugging(const char* name); -void UnmarkThisThreadFromDebugging(); -void UpdateFPExceptionsMaskForThreads(); - - -class CThreadTaskManager; -/// -struct IThreadTaskRunnable -{ - virtual ~IThreadTaskRunnable(){} - virtual void Run() = 0; - virtual void Cancel() = 0; -}; -////////////////////////////////////////////////////////////////////////// -class CThreadTask_Thread - : public CryThread - , public IThreadTask_Thread -{ -protected: - void Init(); -public: - CThreadTask_Thread(CThreadTaskManager* pTaskMgr, const char* sName, int nThreadIndex, int nProcessor, int nThreadPriority, ThreadPoolHandle poolHandle = -1); - ~CThreadTask_Thread(); - - // see IThreadTaskRunnable, CryThread<> - void Run() override; - void Cancel() override; - - // see CryThread<> - void Terminate() override; - - // IThreadTask_Thread - void AddTask(SThreadTaskInfo* pTaskInfo) override; - void RemoveTask(SThreadTaskInfo* pTaskInfo) override; - void RemoveAllTasks() override; - void SingleUpdate() override; - - void ChangeProcessor(int nProcessor); -public: - CThreadTaskManager* m_pTaskManager; - string m_sThreadName; - int m_nThreadIndex; // -1 means the thread is blocking - int m_nProcessor; - int m_nThreadPriority; - - THREAD_HANDLE m_hThreadHandle; - - // Tasks running on this thread. - typedef CryMT::CLocklessPointerQueue > Tasks; - Tasks tasks; - - // The task is being processing now - SThreadTaskInfo* m_pProcessingTask; - - CryEvent m_waitForTasks; - - // Set to true when thread must stop. - volatile bool bStopThread; - volatile bool bRunning; - - // handle of threads pool which this thread belongs to(if any) - ThreadPoolHandle m_poolHandle; -}; - -////////////////////////////////////////////////////////////////////////// -class CThreadTaskManager - : public IThreadTaskManager -{ -private: - typedef std::vector > Threads; - // note: this struct is auxilary and NOT thread-safe - // it is only for internal use inside the task manager - struct CThreadsPool - { - ThreadPoolHandle m_hHandle; - Threads m_Threads; - ThreadPoolDesc m_pDescription; - const bool SetAffinity(const ThreadPoolAffinityMask AffinityMask); - const bool operator < (const CThreadsPool& p) const { return m_hHandle < p.m_hHandle; } - const bool operator == (const CThreadsPool& p) const { return m_hHandle == p.m_hHandle; } - }; - - typedef std::vector ThreadsPools; - -public: - CThreadTaskManager(); - ~CThreadTaskManager(); - - void InitThreads(); - void CloseThreads(); - void StopAllThreads(); - - ////////////////////////////////////////////////////////////////////////// - // IThreadTaskManager - ////////////////////////////////////////////////////////////////////////// - virtual void RegisterTask(IThreadTask* pTask, const SThreadTaskParams& options); - virtual void UnregisterTask(IThreadTask* pTask); - virtual void SetMaxThreadCount(int nMaxThreads); - virtual void SetThreadName(threadID dwThreadId, const char* sThreadName); - virtual const char* GetThreadName(threadID dwThreadId); - virtual threadID GetThreadByName(const char* sThreadName); - - // Thread pool framework - virtual ThreadPoolHandle CreateThreadsPool(const ThreadPoolDesc& desc); - virtual const bool DestroyThreadsPool(const ThreadPoolHandle& handle); - virtual const bool GetThreadsPoolDesc(const ThreadPoolHandle handle, ThreadPoolDesc* pDesc) const; - virtual const bool SetThreadsPoolAffinity(const ThreadPoolHandle handle, const ThreadPoolAffinityMask AffinityMask); - - virtual void MarkThisThreadForDebugging(const char* name, bool bDump); - ////////////////////////////////////////////////////////////////////////// - - // This is on update function of the main thread. - void OnUpdate(); - - void AddSystemThread(threadID nThreadId); - void RemoveSystemThread(threadID nThreadId); - - // Balancing tasks in the pool between threads - void BalanceThreadsPool(const ThreadPoolHandle& handle); - void BalanceThreadInPool(CThreadTask_Thread* pFreeThread, Threads* pThreads = NULL); - -private: - void ScheduleTask(SThreadTaskInfo* pTaskInfo); - void RescheduleTasks(); -private: - - // User created threads pools - mutable CryReadModifyLock m_threadsPoolsLock; - ThreadsPools m_threadsPools; - - // Physical threads available to system. - Threads m_threads; - - // Threads with single blocking task attached. - Threads m_blockingThreads; - - typedef CryMT::CLocklessPointerQueue Tasks; - - Tasks m_unassignedTasks; - - mutable CryCriticalSection m_threadNameLock; - mutable CryCriticalSection m_threadRemove; - typedef std::map ThreadNames; - ThreadNames m_threadNames; - - mutable CryCriticalSection m_systemThreadsLock; - std::vector m_systemThreads; - - // Max threads that can be executed at same time. - int m_nMaxThreads; -}; - - -#endif // CRYINCLUDE_CRYSYSTEM_THREADTASK_H diff --git a/Code/CryEngine/CrySystem/UnitTests/CryMathTests.cpp b/Code/CryEngine/CrySystem/UnitTests/CryMathTests.cpp deleted file mode 100644 index 6fc9ae7830..0000000000 --- a/Code/CryEngine/CrySystem/UnitTests/CryMathTests.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "CrySystem_precompiled.h" -#include -#include - -namespace UnitTest -{ - class CryMathTestFixture - : public ::testing::Test - {}; - -#if AZ_TRAIT_DISABLE_FAILED_MATH_TESTS - TEST_F(CryMathTestFixture, DISABLED_InverserSqrt_HasAtLeast22BitsOfAccuracy) -#else - TEST_F(CryMathTestFixture, InverserSqrt_HasAtLeast22BitsOfAccuracy) -#endif - { - float testFloat(0.336950600); - const float result = isqrt_safe_tpl(testFloat * testFloat); - const float epsilon = 0.00001f; - EXPECT_NEAR(2.96779, result, epsilon); - } - -#if AZ_TRAIT_DISABLE_FAILED_MATH_TESTS - TEST_F(CryMathTestFixture, DISABLED_SimdSqrt_HasAtLeast23BitsOfAccuracy) -#else - TEST_F(CryMathTestFixture, SimdSqrt_HasAtLeast23BitsOfAccuracy) -#endif - { - float testFloat(3434.34839439); - const float result = sqrt_tpl(testFloat); - const float epsilon = 0.00001f; - EXPECT_NEAR(58.60331, result, epsilon); - } -} diff --git a/Code/CryEngine/CrySystem/UnitTests/CryPakUnitTests.cpp b/Code/CryEngine/CrySystem/UnitTests/CryPakUnitTests.cpp deleted file mode 100644 index 1935196570..0000000000 --- a/Code/CryEngine/CrySystem/UnitTests/CryPakUnitTests.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "CrySystem_precompiled.h" - -#include -#include - -#include -#include // for max path decl -#include -#include -#include // for function<> in the find files callback. -#include -#include -#include -#include -#include - -namespace CryPakUnitTests -{ - -#if defined(AZ_PLATFORM_WINDOWS) - - // Note: none of the below is really a unit test, its all basic feature tests - // for critical functionality - - class Integ_CryPakUnitTests - : public ::testing::Test - { - protected: - bool IsPackValid(const char* path) - { - AZ::IO::IArchive* pak = gEnv->pCryPak; - if (!pak) - { - return false; - } - - if (!pak->OpenPack(path, AZ::IO::IArchive::FLAGS_PATH_REAL)) - { - return false; - } - - pak->ClosePack(path); - return true; - } - }; - - TEST_F(Integ_CryPakUnitTests, TestCryPakModTime) - { - AZ::IO::FileIOBase* fileIo = AZ::IO::FileIOBase::GetInstance(); - ASSERT_NE(nullptr, fileIo); - - AZ::IO::IArchive* pak = gEnv->pCryPak; - // repeat the following test multiple times, since timing (seconds) can affect it and it involves time! - for (int iteration = 0; iteration < 10; ++iteration) - { - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds{ 100 }); - - // helper paths and strings - AZStd::string gameFolder = fileIo->GetAlias("@usercache@"); - - AZStd::string testFile = "unittest.bin"; - AZStd::string testFilePath = gameFolder + "\\" + testFile; - AZStd::string testPak = "unittest.pak"; - AZStd::string testPakPath = gameFolder + "\\" + testPak; - AZStd::string zipCmd = "-zip=" + testPakPath; - - // delete test files in case they already exist - fileIo->Remove(testFilePath.c_str()); - pak->ClosePack(testPakPath); - fileIo->Remove(testPakPath.c_str()); - - // create a test file - char data[] = "unittest"; - FILE* f = nullptr; - azfopen(&f, testFilePath.c_str(), "wb"); - EXPECT_TRUE(f != nullptr); // file successfully opened for writing - EXPECT_TRUE(fwrite(data, sizeof(char), sizeof(data), f) == sizeof(data)); // file written to successfully - EXPECT_TRUE(fclose(f) == 0); // file closed successfully - - AZ::IO::HandleType fDisk = pak->FOpen(testFilePath.c_str(), "rb"); - EXPECT_TRUE(fDisk > 0); // opened file on disk successfully - uint64_t modTimeDisk = pak->GetModificationTime(fDisk); // high res mod time extracted from file on disk - EXPECT_TRUE(pak->FClose(fDisk) == 0); // file closed successfully - - // create a low res copy of disk file's mod time - uint64_t absDiff, maxDiff = 20000000ul; - uint16_t dosDate, dosTime; - FILETIME ft; - LARGE_INTEGER lt; - - ft.dwHighDateTime = modTimeDisk >> 32; - ft.dwLowDateTime = modTimeDisk & 0xFFFFFFFF; - EXPECT_TRUE(FileTimeToDosDateTime(&ft, &dosDate, &dosTime) != FALSE); // converted to DOSTIME successfully - ft.dwHighDateTime = 0; - ft.dwLowDateTime = 0; - EXPECT_TRUE(DosDateTimeToFileTime(dosDate, dosTime, &ft) != FALSE); // converted to FILETIME successfully - lt.HighPart = ft.dwHighDateTime; - lt.LowPart = ft.dwLowDateTime; - uint64_t modTimeDiskLowRes = lt.QuadPart; - - absDiff = modTimeDiskLowRes >= modTimeDisk ? modTimeDiskLowRes - modTimeDisk : modTimeDisk - modTimeDiskLowRes; - EXPECT_LE(absDiff, maxDiff); // FILETIME (high res) and DOSTIME (low res) should be at most 2 seconds apart - - gEnv->pResourceCompilerHelper->CallResourceCompiler(testFilePath.c_str(), zipCmd.c_str()); - EXPECT_EQ(AZ::IO::ResultCode::Success, fileIo->Remove(testFilePath.c_str())); // test file on disk deleted successfully - - EXPECT_TRUE(pak->OpenPack(testPakPath)); // opened pak successfully - - AZ::IO::HandleType fPak = pak->FOpen(testFilePath.c_str(), "rb"); - EXPECT_GT(fPak, 0); // file (in pak) opened correctly - uint64_t modTimePak = pak->GetModificationTime(fPak); // low res mod time extracted from file in pak - EXPECT_EQ(0, pak->FClose(fPak)); // file closed successfully - - EXPECT_TRUE(pak->ClosePack(testPakPath)); // closed pak successfully - EXPECT_EQ(AZ::IO::ResultCode::Success, fileIo->Remove(testPakPath.c_str())); // test pak file deleted successfully - - absDiff = modTimePak >= modTimeDisk ? modTimePak - modTimeDisk : modTimeDisk - modTimePak; - // compare mod times. They are allowed to be up to 2 seconds apart but no more - EXPECT_LE(absDiff, maxDiff); // FILETIME (disk) and DOSTIME (pak) should be at most 2 seconds apart - // note: Do not directly compare the disk time and pack time, the resolution drops the last digit off in some cases in pak - // it only has a 2 second resolution. you may compare to make sure that the pak time is WITHIN 2 seconds (as above) but not equal. - - // we depend on the fact that crypak is rounding up, instead of down - EXPECT_GE(modTimePak, modTimeDisk); - } - } - - -#endif -} diff --git a/Code/CryEngine/CrySystem/UnixConsole.cpp b/Code/CryEngine/CrySystem/UnixConsole.cpp index d0a7bc15ff..5ec186b8b8 100644 --- a/Code/CryEngine/CrySystem/UnixConsole.cpp +++ b/Code/CryEngine/CrySystem/UnixConsole.cpp @@ -783,12 +783,6 @@ void CUNIXConsole::KeyEnter() if (pushCommand) { - CSystem* pSystem = static_cast(gEnv->pSystem); -#if defined(CVARS_WHITELIST) - ICVarsWhitelist* pCVarsWhitelist = pSystem->GetCVarsWhiteList(); - bool execute = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(m_InputLine, false) : true; - if (execute) -#endif // defined(CVARS_WHITELIST) { m_CommandQueue.push_back(m_InputLine); } diff --git a/Code/CryEngine/CrySystem/XConsole.cpp b/Code/CryEngine/CrySystem/XConsole.cpp index 3b30a7eeed..32fe67dcc0 100644 --- a/Code/CryEngine/CrySystem/XConsole.cpp +++ b/Code/CryEngine/CrySystem/XConsole.cpp @@ -140,147 +140,6 @@ void Command_SetWaitFrames(IConsoleCmdArgs* pCmd) } } -/* - - CNotificationNetworkConsole - -*/ - -#include -class CNotificationNetworkConsole - : public INotificationNetworkListener -{ -private: - static const uint32 LENGTH_MAX = 256; - static CNotificationNetworkConsole* s_pInstance; - -public: - static bool Initialize() - { - if (s_pInstance) - { - return true; - } - - INotificationNetwork* pNotificationNetwork = gEnv->pSystem->GetINotificationNetwork(); - if (!pNotificationNetwork) - { - return false; - } - - s_pInstance = new CNotificationNetworkConsole(); - pNotificationNetwork->ListenerBind("Command", s_pInstance); - return true; - } - - static void Shutdown() - { - if (!s_pInstance) - { - return; - } - - delete s_pInstance; - s_pInstance = NULL; - } - - static void Update() - { - if (s_pInstance) - { - s_pInstance->ProcessCommand(); - } - } - -private: - CNotificationNetworkConsole() - { - m_pConsole = NULL; - - m_commandBuffer[0][0] = '\0'; - m_commandBuffer[1][0] = '\0'; - m_commandBufferIndex = 0; - m_commandCriticalSection = ::CryCreateCriticalSection(); - } - - ~CNotificationNetworkConsole() - { - if (m_commandCriticalSection) - { - ::CryDeleteCriticalSection(m_commandCriticalSection); - } - } - -private: - void ProcessCommand() - { - if (!ValidateConsole()) - { - return; - } - - char* command = NULL; - ::CryEnterCriticalSection(m_commandCriticalSection); - if (*m_commandBuffer[m_commandBufferIndex]) - { - command = m_commandBuffer[m_commandBufferIndex]; - } - ++m_commandBufferIndex &= 1; - ::CryLeaveCriticalSection(m_commandCriticalSection); - - if (command) - { - m_pConsole->ExecuteString(command); - *command = '\0'; - } - } - - bool ValidateConsole() - { - if (m_pConsole) - { - return true; - } - - if (!gEnv->pConsole) - { - return false; - } - - m_pConsole = gEnv->pConsole; - return true; - } - - // INotificationNetworkListener -public: - void OnNotificationNetworkReceive(const void* pBuffer, size_t length) - { - if (!ValidateConsole()) - { - return; - } - - if (length > LENGTH_MAX) - { - length = LENGTH_MAX; - } - - ::CryEnterCriticalSection(m_commandCriticalSection); - ::memcpy(m_commandBuffer[m_commandBufferIndex], pBuffer, length); - m_commandBuffer[m_commandBufferIndex][LENGTH_MAX - 1] = '\0'; - ::CryLeaveCriticalSection(m_commandCriticalSection); - } - -private: - IConsole* m_pConsole; - - char m_commandBuffer[2][LENGTH_MAX]; - size_t m_commandBufferIndex; - void* m_commandCriticalSection; -}; - -CNotificationNetworkConsole* CNotificationNetworkConsole::s_pInstance = NULL; - void ConsoleShow(IConsoleCmdArgs*) { gEnv->pConsole->ShowConsole(true); @@ -359,8 +218,6 @@ CXConsole::CXConsole() m_waitSeconds = 0.0f; m_blockCounter = 0; - CNotificationNetworkConsole::Initialize(); - AzFramework::ConsoleRequestBus::Handler::BusConnect(); AzFramework::CommandRegistrationBus::Handler::BusConnect(); @@ -379,8 +236,6 @@ CXConsole::~CXConsole() gEnv->pSystem->GetIRemoteConsole()->UnregisterListener(this); } - CNotificationNetworkConsole::Shutdown(); - if (!m_mapVariables.empty()) { while (!m_mapVariables.empty()) @@ -1205,8 +1060,6 @@ void CXConsole::Update() } } } - - CNotificationNetworkConsole::Update(); } //enable this for now, we need it for profiling etc @@ -1749,11 +1602,6 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) int devOnlyMask = VF_DEV_ONLY; int dediOnlyMask = VF_DEDI_ONLY; int excludeMask = cheatMask | constMask | readOnlyMask | devOnlyMask | dediOnlyMask; -#if defined(CVARS_WHITELIST) - CSystem* pSystem = static_cast(gEnv->pSystem); - ICVarsWhitelist* pCVarsWhitelist = pSystem->GetCVarsWhiteList(); - bool excludeWhitelist = true; -#endif // defined(CVARS_WHITELIST) if (numArgs > 1) { @@ -1786,13 +1634,6 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) excludeMask &= ~dediOnlyMask; } -#if defined(CVARS_WHITELIST) - if (azstricmp(arg, "whitelist") == 0) - { - excludeWhitelist = false; - } -#endif // defined(CVARS_WHITELIST) - --numArgs; } } @@ -1810,11 +1651,6 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) int devOnlyFlags = (command.m_nFlags & devOnlyMask); int dediOnlyFlags = (command.m_nFlags & dediOnlyMask); bool shouldLog = ((cheatFlags | devOnlyFlags | dediOnlyFlags) == 0) || (((cheatFlags | devOnlyFlags | dediOnlyFlags) & ~excludeMask) != 0); -#if defined(CVARS_WHITELIST) - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(command.m_sName, true) : true; - shouldLog &= (!whitelisted || (whitelisted & !excludeWhitelist)); -#endif // defined(CVARS_WHITELIST) - if (shouldLog) { CryLogAlways("[CVARS]: [COMMAND] %s%s%s%s%s", @@ -1822,11 +1658,7 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) (cheatFlags != 0) ? " [VF_CHEAT]" : "", (devOnlyFlags != 0) ? " [VF_DEV_ONLY]" : "", (dediOnlyFlags != 0) ? " [VF_DEDI_ONLY]" : "", -#if defined(CVARS_WHITELIST) - (whitelisted == true) ? " [WHITELIST]" : "" -#else "" -#endif // defined(CVARS_WHITELIST) ); ++commandCount; } @@ -1843,11 +1675,6 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) int devOnlyFlags = (flags & devOnlyMask); int dediOnlyFlags = (flags & dediOnlyMask); bool shouldLog = ((cheatFlags | constFlags | readOnlyFlags | devOnlyFlags | dediOnlyFlags) == 0) || (((cheatFlags | constFlags | readOnlyFlags | devOnlyFlags | dediOnlyFlags) & ~excludeMask) != 0); -#if defined(CVARS_WHITELIST) - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(pVariable->GetName(), true) : true; - shouldLog &= (!whitelisted || (whitelisted & !excludeWhitelist)); -#endif // defined(CVARS_WHITELIST) - if (shouldLog) { CryLogAlways("[CVARS]: [VARIABLE] %s%s%s%s%s%s%s", @@ -1857,11 +1684,7 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) (readOnlyFlags != 0) ? " [VF_READONLY]" : "", (devOnlyFlags != 0) ? " [VF_DEV_ONLY]" : "", (dediOnlyFlags != 0) ? " [VF_DEDI_ONLY]" : "", -#if defined(CVARS_WHITELIST) - (whitelisted == true) ? " [WHITELIST]" : "" -#else "" -#endif // defined(CVARS_WHITELIST) ); ++cvarCount; } @@ -2520,11 +2343,6 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer) } } //try to search in command list - -#if defined(CVARS_WHITELIST) - CSystem* pSystem = static_cast(gEnv->pSystem); - ICVarsWhitelist* pCVarsWhitelist = pSystem->GetCVarsWhiteList(); -#endif // defined(CVARS_WHITELIST) bool bArgumentAutoComplete = false; std::vector matches; @@ -2565,10 +2383,6 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer) string cmd = string(sVar) + " " + pArgumentAutoComplete->GetValue(i); if (_strnicmp(m_sPrevTab.c_str(), cmd.c_str(), m_sPrevTab.length()) == 0) { -#if defined(CVARS_WHITELIST) - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(cmd, true) : true; - if (whitelisted) -#endif // defined(CVARS_WHITELIST) { bArgumentAutoComplete = true; matches.push_back(cmd); @@ -2590,10 +2404,6 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer) { if (_strnicmp(m_sPrevTab.c_str(), itrCmds->first.c_str(), m_sPrevTab.length()) == 0) { -#if defined(CVARS_WHITELIST) - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(itrCmds->first, true) : true; - if (whitelisted) -#endif // defined(CVARS_WHITELIST) { matches.push_back((char* const)itrCmds->first.c_str()); } @@ -2613,10 +2423,6 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer) {//if(itrVars->first.compare(0,m_sPrevTab.length(),m_sPrevTab)==0) if (_strnicmp(m_sPrevTab.c_str(), itrVars->first, m_sPrevTab.length()) == 0) { -#if defined(CVARS_WHITELIST) - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(itrVars->first, true) : true; - if (whitelisted) -#endif // defined(CVARS_WHITELIST) { matches.push_back((char* const)itrVars->first); } @@ -2990,12 +2796,6 @@ void CXConsole::ExecuteInputBuffer() AddCommandToHistory(sTemp.c_str()); -#if defined(CVARS_WHITELIST) - CSystem* pSystem = static_cast(gEnv->pSystem); - ICVarsWhitelist* pCVarsWhitelist = pSystem->GetCVarsWhiteList(); - bool execute = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(sTemp, false) : true; - if (execute) -#endif // defined(CVARS_WHITELIST) { ExecuteStringInternal(sTemp.c_str(), true); // from console } diff --git a/Code/CryEngine/CrySystem/XML/xml.cpp b/Code/CryEngine/CrySystem/XML/xml.cpp index 601b14eeb3..438b35b6c8 100644 --- a/Code/CryEngine/CrySystem/XML/xml.cpp +++ b/Code/CryEngine/CrySystem/XML/xml.cpp @@ -1809,8 +1809,6 @@ XmlNodeRef XmlParserImp::ParseFile(const char* filename, XmlString& errorString, ParseEnd(); } - SYNCHRONOUS_LOADING_TICK(); - delete [] pFileContents; return root; diff --git a/Code/CryEngine/CrySystem/crysystem_files.cmake b/Code/CryEngine/CrySystem/crysystem_files.cmake index 5dc8a68f8b..50cbdc24e4 100644 --- a/Code/CryEngine/CrySystem/crysystem_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_files.cmake @@ -19,14 +19,11 @@ set(FILES ConsoleBatchFile.cpp ConsoleHelpGen.cpp CryAsyncMemcpy.cpp - DebugCallStack.cpp GeneralMemoryHeap.cpp HandlerBase.cpp - IDebugCallStack.cpp AsyncPakManager.cpp Log.cpp SystemRender.cpp - NotificationNetwork.cpp PhysRenderer.cpp ResourceManager.cpp ServerHandler.cpp @@ -36,7 +33,6 @@ set(FILES SystemCFG.cpp SystemEventDispatcher.cpp SystemInit.cpp - SystemScheduler.cpp SystemWin32.cpp Timer.cpp UnixConsole.cpp @@ -52,7 +48,6 @@ set(FILES ServerHandler.h ServerThrottle.h SyncLock.h - SystemScheduler.h UnixConsole.h SystemInit.h XML/ReadWriteXMLSink.h @@ -63,12 +58,8 @@ set(FILES ConsoleBatchFile.h ConsoleHelpGen.h CryWaterMark.h - DebugCallStack.h GeneralMemoryHeap.h - IDebugCallStack.h - IThreadConfigManager.h Log.h - NotificationNetwork.h resource.h SimpleStringPool.h CrySystem_precompiled.h @@ -107,24 +98,12 @@ set(FILES XML/WriteXMLSource.cpp ZipFile.h ZipFileFormat_info.h - ProfileLogSystem.cpp Sampler.cpp - ProfileLogSystem.h Sampler.h LocalizedStringManager.cpp LocalizedStringManager.h - CryThreadUtil_win32_thread.h - ThreadInfo.cpp - ThreadInfo.h - ThreadTask.h - ThreadTask.cpp - ThreadConfigManager.h - ThreadConfigManager.cpp - SystemThreading.cpp ZLibCompressor.cpp ZLibCompressor.h - SoftCode/SoftCodeMgr.cpp - SoftCode/SoftCodeMgr.h Huffman.cpp Huffman.h RemoteConsole/RemoteConsole.cpp diff --git a/Code/CryEngine/CrySystem/crysystem_test_files.cmake b/Code/CryEngine/CrySystem/crysystem_test_files.cmake index a57ba57f77..d8f6887da6 100644 --- a/Code/CryEngine/CrySystem/crysystem_test_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_test_files.cmake @@ -18,7 +18,5 @@ set(FILES Tests/Test_Localization.cpp Tests/test_Main.cpp Tests/test_MaterialUtils.cpp - UnitTests/CryMathTests.cpp - UnitTests/CryPakUnitTests.cpp DllMain.cpp ) diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp index daf5b5efd2..b2fe4417d3 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp @@ -1304,7 +1304,7 @@ namespace AZ // Add all auto loadable non-asset gems to the list of gem modules to load if (!moduleLoadData.m_autoLoad) { - break; + continue; } for (AZ::OSString& dynamicLibraryPath : moduleLoadData.m_dynamicLibraryPaths) { diff --git a/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp b/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp index 78e2288a4c..d6122b81f1 100644 --- a/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp +++ b/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp @@ -1042,11 +1042,7 @@ namespace UnitTest -#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS TEST_F(AssetJobsFloodTest, DISABLED_ContainerCoreTest_BasicDependencyManagement_Success) -#else - TEST_F(AssetJobsFloodTest, ContainerCoreTest_BasicDependencyManagement_Success) -#endif // !AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS { m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusConnect(); // Setup has already created/destroyed assets diff --git a/Code/Framework/AzFramework/AzFramework/Application/Application.cpp b/Code/Framework/AzFramework/AzFramework/Application/Application.cpp index ba313812ce..dc6ae684cf 100644 --- a/Code/Framework/AzFramework/AzFramework/Application/Application.cpp +++ b/Code/Framework/AzFramework/AzFramework/Application/Application.cpp @@ -52,8 +52,6 @@ #include #include #include -#include -#include #include #include #include @@ -66,7 +64,6 @@ #include #include #include -#include #include #include #include @@ -197,7 +194,6 @@ namespace AzFramework ApplicationRequests::Bus::Handler::BusConnect(); AZ::UserSettingsFileLocatorBus::Handler::BusConnect(); - NetSystemRequestBus::Handler::BusConnect(); } Application::~Application() @@ -207,7 +203,6 @@ namespace AzFramework Stop(); } - NetSystemRequestBus::Handler::BusDisconnect(); AZ::UserSettingsFileLocatorBus::Handler::BusDisconnect(); ApplicationRequests::Bus::Handler::BusDisconnect(); @@ -285,13 +280,6 @@ namespace AzFramework m_pimpl.reset(); - /* The following line of code is a temporary fix. - * GridMate's ReplicaChunkDescriptor is stored in a global environment variable 'm_globalDescriptorTable' - * which does not get cleared when Application shuts down. We need to un-reflect here to clear ReplicaChunkDescriptor - * so that ReplicaChunkDescriptor::m_vdt doesn't get flooded when we repeatedly instantiate Application in unit tests. - */ - AZ::ReflectionEnvironment::GetReflectionManager()->RemoveReflectContext(); - // Free any memory owned by the command line container. m_commandLine = CommandLine(); @@ -320,8 +308,6 @@ namespace AzFramework azrtti_typeid(), azrtti_typeid(), azrtti_typeid(), - azrtti_typeid(), - azrtti_typeid(), azrtti_typeid(), azrtti_typeid(), azrtti_typeid(), @@ -457,9 +443,6 @@ namespace AzFramework void Application::CreateReflectionManager() { ComponentApplication::CreateReflectionManager(); - - // Setup NetworkContext - AZ::ReflectionEnvironment::GetReflectionManager()->AddReflectContext(); } //////////////////////////////////////////////////////////////////////////// @@ -479,19 +462,6 @@ namespace AzFramework return uuid; } - //////////////////////////////////////////////////////////////////////////// - NetworkContext* Application::GetNetworkContext() - { - NetworkContext* result = nullptr; - - if (auto reflectionManager = AZ::ReflectionEnvironment::GetReflectionManager()) - { - result = reflectionManager->GetReflectContext(); - } - - return result; - } - void Application::ResolveEnginePath(AZStd::string& engineRelativePath) const { AZ::IO::FixedMaxPath fullPath = m_engineRoot / engineRelativePath; diff --git a/Code/Framework/AzFramework/AzFramework/Application/Application.h b/Code/Framework/AzFramework/AzFramework/Application/Application.h index 4d7e45a423..6b1283be34 100644 --- a/Code/Framework/AzFramework/AzFramework/Application/Application.h +++ b/Code/Framework/AzFramework/AzFramework/Application/Application.h @@ -21,7 +21,6 @@ #include #include -#include #include #include @@ -49,7 +48,6 @@ namespace AzFramework : public AZ::ComponentApplication , public AZ::UserSettingsFileLocatorBus::Handler , public ApplicationRequests::Bus::Handler - , public NetSystemRequestBus::Handler { public: // Base class for platform specific implementations of the application. @@ -138,11 +136,6 @@ namespace AzFramework // Convenience function that should be called instead of the standard exit() function to ensure platform requirements are met. static void Exit(int errorCode) { ApplicationRequests::Bus::Broadcast(&ApplicationRequests::TerminateOnError, errorCode); } - ////////////////////////////////////////////////////////////////////////// - //! NetSystemEventBus::Handler - ////////////////////////////////////////////////////////////////////////// - NetworkContext* GetNetworkContext() override; - protected: /** diff --git a/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp b/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp index 644a7d099d..d1e4b4977a 100644 --- a/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp +++ b/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp @@ -22,8 +22,6 @@ #include #include #include -#include -#include #include #include #include @@ -42,8 +40,6 @@ namespace AzFramework AzFramework::AssetCatalogComponent::CreateDescriptor(), AzFramework::CustomAssetTypeComponent::CreateDescriptor(), AzFramework::FileTag::ExcludeFileComponent::CreateDescriptor(), - AzFramework::NetBindingComponent::CreateDescriptor(), - AzFramework::NetBindingSystemComponent::CreateDescriptor(), AzFramework::TransformComponent::CreateDescriptor(), AzFramework::NonUniformScaleComponent::CreateDescriptor(), AzFramework::GameEntityContextComponent::CreateDescriptor(), diff --git a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp index 5605fe567c..3c05887a89 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.cpp @@ -878,15 +878,15 @@ namespace AzFramework AZ::SerializeContext* serializeContext = azrtti_cast(reflection); if (serializeContext) { - serializeContext->Class() + serializeContext->ClassDeprecate("NetBindable", "{80206665-D429-4703-B42E-94434F82F381}"); + + serializeContext->Class() ->Version(4, &TransformComponentVersionConverter) ->Field("Parent", &TransformComponent::m_parentId) ->Field("Transform", &TransformComponent::m_worldTM) ->Field("LocalTransform", &TransformComponent::m_localTM) ->Field("ParentActivationTransformMode", &TransformComponent::m_parentActivationTransformMode) ->Field("IsStatic", &TransformComponent::m_isStatic) - ->Field("InterpolatePosition", &TransformComponent::m_interpolatePosition) - ->Field("InterpolateRotation", &TransformComponent::m_interpolateRotation) ; } diff --git a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h index abea0bd4dd..0dd53d84ed 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h +++ b/Code/Framework/AzFramework/AzFramework/Components/TransformComponent.h @@ -17,7 +17,6 @@ #include #include #include -#include namespace AzToolsFramework { @@ -41,10 +40,9 @@ namespace AzFramework , public AZ::TransformBus::Handler , public AZ::TransformNotificationBus::Handler , private AZ::TransformHierarchyInformationBus::Handler - , public NetBindable { public: - AZ_COMPONENT(TransformComponent, AZ::TransformComponentTypeId, NetBindable, AZ::TransformInterface); + AZ_COMPONENT(TransformComponent, AZ::TransformComponentTypeId, AZ::TransformInterface); friend class AzToolsFramework::Components::TransformComponent; @@ -218,11 +216,5 @@ namespace AzFramework bool m_parentActive = false; ///< Keeps track of the state of the parent entity. bool m_onNewParentKeepWorldTM = true; ///< If set, recompute localTM instead of worldTM when parent becomes active. bool m_isStatic = false; ///< If true, the transform is static and doesn't move while entity is active. - - //! @deprecated - //! @{ - AZ::InterpolationMode m_interpolatePosition = AZ::InterpolationMode::NoInterpolation; - AZ::InterpolationMode m_interpolateRotation = AZ::InterpolationMode::NoInterpolation; - //! @} }; } // namespace AZ diff --git a/Code/Framework/AzFramework/AzFramework/Network/DynamicSerializableFieldMarshaler.h b/Code/Framework/AzFramework/AzFramework/Network/DynamicSerializableFieldMarshaler.h deleted file mode 100644 index 3e69454f59..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/DynamicSerializableFieldMarshaler.h +++ /dev/null @@ -1,146 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once -#ifndef AZFRAMEWORK_NETWORK_DYNAMICSERIALIZABLEFIELDMARSHALER_H -#define AZFRAMEWORK_NETWORK_DYNAMICSERIALIZABLEFIELDMARSHALER_H - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace GridMate -{ - /** - * Marshaler for DynamicSerializableField, contains a template param for allocating the memory buffer that it's going to use to write to. - */ - template - class DynamicSerializableFieldMarshaler - { - public: - DynamicSerializableFieldMarshaler() - : m_serializeContext(nullptr) - { - EBUS_EVENT_RESULT(m_serializeContext, AZ::ComponentApplicationBus, GetSerializeContext); - } - - // Mainly here for unit test purposes. - DynamicSerializableFieldMarshaler(AZ::SerializeContext* context) - : m_serializeContext(context) - { - } - - AZ_FORCE_INLINE void Marshal(WriteBuffer& wb, const AZ::DynamicSerializableField& value) const - { - AZ_Error("DynamicSerializableFieldMarshaler", m_serializeContext, "Unknown SerializationContext. Aborting Marshal attempt.\n"); - if (m_serializeContext) - { - Marshaler sizeMarshaler; - Marshaler uuidMarshaler; - - AZStd::vector memoryBuffer(BufferSize); - - // Start buffer in write mode. - AZ::IO::ByteContainerStream memoryStream(&memoryBuffer); - - AZ::u32 bufferSize = 0; - - if (m_serializeContext->FindClassData(value.m_typeId)) - { - if (AZ::Utils::SaveObjectToStream(memoryStream, AZ::DataStream::StreamType::ST_BINARY, value.m_data, value.m_typeId, m_serializeContext)) - { - bufferSize = static_cast(memoryStream.GetCurPos()); - } - } - else - { - AZ_Error("DynamicSerializableFieldMarshaler", !value.IsValid(), "Could not save object to stream because type Id %s is not registered with the serializer.\n", value.m_typeId.ToString().c_str()); - } - - sizeMarshaler.Marshal(wb, bufferSize); - uuidMarshaler.Marshal(wb, value.m_typeId); - wb.WriteRaw(memoryBuffer.data(), bufferSize); - } - } - - AZ_FORCE_INLINE void Unmarshal(AZ::DynamicSerializableField& value, ReadBuffer& rb) const - { - value.DestroyData(m_serializeContext); - - AZ_Error("DynamicSerializableFieldMarshaler", m_serializeContext, "Unknown SerializationContext. Aborting Unmarshal attempt.\n"); - if (m_serializeContext) - { - Marshaler sizeMarshaler; - AZ::u32 marshaledBufferSize = 0; - sizeMarshaler.Unmarshal(marshaledBufferSize, rb); - - AZ_Assert(marshaledBufferSize <= BufferSize,"Trying to deserialize too much data for the allocated buffer size\n"); - - // Marshal out the TypeId so I can use it on the receiving end. - Marshaler uuidMarshaler; - uuidMarshaler.Unmarshal(value.m_typeId, rb); - - if (marshaledBufferSize > 0) - { - // See if there's some nice way to use this. - // - Can't make this a member variable, since both these methods are const. - AZStd::vector memoryBuffer(marshaledBufferSize + 1); - - if (rb.ReadRaw(memoryBuffer.data(), marshaledBufferSize)) - { - // Start buffer in read mode. - AZ::IO::ByteContainerStream memoryStream(&memoryBuffer); - - // we'll use a strict filter here, one that doesn't allow deserialization to automatically start loading assets, nor tolerates errors. - // this is becuase this is coming from a network interface and should always be error-free. - AZ::ObjectStream::FilterDescriptor filterToUse(&AZ::Data::AssetFilterNoAssetLoading, AZ::ObjectStream::FILTERFLAG_STRICT); - value.m_data = AZ::Utils::LoadObjectFromStream(memoryStream, m_serializeContext, &value.m_typeId, filterToUse); - } - } - } - } - - private: - AZ::SerializeContext* m_serializeContext; - }; - - /** - * Specialized marshaler for AZ::DynamicSerializableField - * Mainly here to hook into the DataSet Marshaler auto detection logic, and provide a default buffer size for the actual marshaler - */ - template<> - class Marshaler - : public DynamicSerializableFieldMarshaler<1024> - { - public: - - Marshaler() - { - } - - // Mainly here for unit test purposes. - Marshaler(AZ::SerializeContext* context) - : DynamicSerializableFieldMarshaler(context) - { - } - }; -} - -#endif diff --git a/Code/Framework/AzFramework/AzFramework/Network/EntityIdMarshaler.h b/Code/Framework/AzFramework/AzFramework/Network/EntityIdMarshaler.h deleted file mode 100644 index 0116020cc0..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/EntityIdMarshaler.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once -#ifndef AZFRAMEWORK_NETWORK_ENTITYIDMARSHALER_H -#define AZFRAMEWORK_NETWORK_ENTITYIDMARSHALER_H - -#include -#include - -#include -#include - -namespace GridMate -{ - template<> - class Marshaler - { - public: - AZ_TYPE_INFO_LEGACY( Marshaler, "{23F4722F-D104-4E30-9342-43F4DDD1894D}", AZ::EntityId ); - - void Marshal(GridMate::WriteBuffer& wb, const AZ::EntityId& source) const - { - Marshaler idMarshaler; - idMarshaler.Marshal(wb,static_cast(source)); - } - - void Unmarshal(AZ::EntityId& target, GridMate::ReadBuffer& rb) const - { - AZ::u64 id = 0; - - Marshaler idMarshaler; - idMarshaler.Unmarshal(id,rb); - - target = AZ::EntityId(id); - } - }; - - template<> - class Marshaler - { - public: - void Marshal(GridMate::WriteBuffer& wb, const AZ::NamedEntityId& source) const - { - Marshaler idMarshaler; - idMarshaler.Marshal(wb, static_cast(source)); - - Marshaler stringMarshaler; - stringMarshaler.Marshal(wb, source.GetName()); - } - - void Unmarshal(AZ::NamedEntityId& target, GridMate::ReadBuffer& rb) const - { - AZ::u64 id = 0; - - Marshaler idMarshaler; - idMarshaler.Unmarshal(id, rb); - - AZStd::string name; - Marshaler stringMarshaler; - stringMarshaler.Unmarshal(name, rb); - - target = AZ::NamedEntityId(AZ::EntityId(id), name); - } - }; -} - -#endif diff --git a/Code/Framework/AzFramework/AzFramework/Network/InterestManagerComponent.cpp b/Code/Framework/AzFramework/AzFramework/Network/InterestManagerComponent.cpp deleted file mode 100644 index 6aa32158f1..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/InterestManagerComponent.cpp +++ /dev/null @@ -1,187 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include - -#include -#include -#include - -#include -#include -#include -#include - -using namespace GridMate; - -namespace AzFramework -{ - void InterestManagerComponent::Reflect(AZ::ReflectContext* context) - { - if (context) - { - AZ::SerializeContext* serializeContext = azrtti_cast(context); - if (serializeContext) - { - serializeContext->Class() - ->Version(1); - - AZ::EditContext* editContext = serializeContext->GetEditContext(); - - if (editContext) - { - editContext->Class( - "InterestManagerComponent", "Interest manager instance") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b)); - } - } - - // We need to register the chunk types for each handler here at reflect time - if (!GridMate::ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(GridMate::ReplicaChunkClassId(ProximityInterestChunk::GetChunkName()))) - { - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - } - - if (!GridMate::ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(GridMate::ReplicaChunkClassId(BitmaskInterestChunk::GetChunkName()))) - { - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - } - } - } - - void InterestManagerComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("InterestManager", 0x79993873)); - } - - void InterestManagerComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("InterestManager", 0x79993873)); - } - - - - InterestManagerComponent::InterestManagerComponent() - : m_im(nullptr) - , m_bitmaskHandler(nullptr) - , m_proximityHandler(nullptr) - , m_session(nullptr) - { - - } - - void InterestManagerComponent::Activate() - { - InterestManagerRequestsBus::Handler::BusConnect(); - NetBindingSystemEventsBus::Handler::BusConnect(); - AZ::SystemTickBus::Handler::BusConnect(); - } - - void InterestManagerComponent::Deactivate() - { - AZ::SystemTickBus::Handler::BusDisconnect(); - NetBindingSystemEventsBus::Handler::BusDisconnect(); - InterestManagerRequestsBus::Handler::BusDisconnect(); - - ShutdownInterestManager(); - } - - void InterestManagerComponent::OnSystemTick() - { - if (m_im && m_im->IsReady()) - { - m_im->Update(); - } - } - - InterestManager* InterestManagerComponent::GetInterestManager() - { - return m_im.get(); - } - - BitmaskInterestHandler* InterestManagerComponent::GetBitmaskInterest() - { - return m_bitmaskHandler.get(); - } - - ProximityInterestHandler* InterestManagerComponent::GetProximityInterest() - { - return m_proximityHandler.get(); - } - - void InterestManagerComponent::OnNetworkSessionActivated(GridSession* session) - { - AZ_Assert(m_session == nullptr, "Already bound to the session"); - - AZ_TracePrintf("AzFramework", "Interest manager hooked up to the session '%s'\n", session->GetId().c_str()); - - m_session = session; - m_session->GetReplicaMgr()->SetAutoBroadcast(false); - - InitInterestManager(); - } - - void InterestManagerComponent::OnNetworkSessionDeactivated(GridSession* session) - { - if (m_session && m_session == session) - { - AZ_TracePrintf("AzFramework", "Interest manager disconnected from the session '%s'\n", session ? session->GetId().c_str() : "nullptr"); - - if (m_session->GetReplicaMgr()) - { - m_session->GetReplicaMgr()->SetAutoBroadcast(true); - } - - m_session = nullptr; - ShutdownInterestManager(); - } - else - { - AZ_Warning("AzFramework", false, "Interest manager was never active for session '%s'\n", session ? session->GetId().c_str() : "nullptr"); - } - } - - void InterestManagerComponent::InitInterestManager() - { - AZ_Assert(m_im == nullptr, "Already initialized interest manager"); - m_im = AZStd::make_unique(); - - InterestManagerDesc desc; - desc.m_rm = m_session->GetReplicaMgr(); - m_im->Init(desc); - - m_bitmaskHandler = AZStd::make_unique(); - m_im->RegisterHandler(m_bitmaskHandler.get()); - - m_proximityHandler = AZStd::make_unique(); - m_im->RegisterHandler(m_proximityHandler.get()); - - InterestManagerEventsBus::Broadcast( - &InterestManagerEventsBus::Events::OnInterestManagerActivate, m_im.get()); - } - - void InterestManagerComponent::ShutdownInterestManager() - { - if (m_im) - { - InterestManagerEventsBus::Broadcast( - &InterestManagerEventsBus::Events::OnInterestManagerDeactivate, m_im.get()); - - m_im->UnregisterHandler(m_bitmaskHandler.get()); - m_im->UnregisterHandler(m_proximityHandler.get()); - - m_bitmaskHandler = nullptr; - m_proximityHandler = nullptr; - m_im = nullptr; - } - } -} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Network/InterestManagerComponent.h b/Code/Framework/AzFramework/AzFramework/Network/InterestManagerComponent.h deleted file mode 100644 index de45c78d43..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/InterestManagerComponent.h +++ /dev/null @@ -1,120 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef AZFRAMEWORK_NET_INTERESTMANAGER_COMPONENT_H -#define AZFRAMEWORK_NET_INTERESTMANAGER_COMPONENT_H - - -#include -#include -#include - -#include - -#include - -namespace GridMate -{ - class InterestManager; - class GridSession; - class BitmaskInterestHandler; - class ProximityInterestHandler; -} - -namespace AzFramework -{ - class InterestManagerSystemRequests - : public AZ::EBusTraits - { - public: - virtual ~InterestManagerSystemRequests() {} - - // Returns interest manager instance - virtual GridMate::InterestManager* GetInterestManager() = 0; - - // Returns interest manager instance - virtual GridMate::BitmaskInterestHandler* GetBitmaskInterest() = 0; - - // Returns interest manager instance - virtual GridMate::ProximityInterestHandler* GetProximityInterest() = 0; - }; - - // Interface Bus - using InterestManagerRequestsBus = AZ::EBus; - - class InterestManagerEvents - : public AZ::EBusTraits - { - public: - virtual ~InterestManagerEvents() {} - - // Called when interest manager is initialized and ready to use - virtual void OnInterestManagerActivate(GridMate::InterestManager* im) { (void)im; } - - // Called when interest manager is deactivated - virtual void OnInterestManagerDeactivate(GridMate::InterestManager* im) { (void)im; } - }; - - // Interface Bus - using InterestManagerEventsBus = AZ::EBus; - - /** - * Interest manager component. - * When component is activated replicas will go through interest filtering before being sent to other peers - */ - class InterestManagerComponent - : public AZ::Component - , public AZ::SystemTickBus::Handler - , public InterestManagerRequestsBus::Handler - , public NetBindingSystemEventsBus::Handler - { - public: - AZ_COMPONENT(InterestManagerComponent, "{55371FA7-2942-4A3C-A3EA-27FF2C7DB6C5}"); - - static void Reflect(AZ::ReflectContext* context); - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); - - InterestManagerComponent(); - - void Activate() override; - void Deactivate() override; - - protected: - - // AZ::SystemTickBus::Listener interface implementation - void OnSystemTick() override; - - // InterestManagerSystemRequests implementation - GridMate::InterestManager* GetInterestManager() override; - GridMate::BitmaskInterestHandler* GetBitmaskInterest() override; - GridMate::ProximityInterestHandler* GetProximityInterest() override; - - // SessionEventBus - void OnNetworkSessionActivated(GridMate::GridSession* session) override; - void OnNetworkSessionDeactivated(GridMate::GridSession* session) override; - - void InitInterestManager(); - void ShutdownInterestManager(); - - // Interest handlers - AZStd::unique_ptr m_im; - AZStd::unique_ptr m_bitmaskHandler; - AZStd::unique_ptr m_proximityHandler; - - GridMate::GridSession* m_session; ///< currently bound session - - private: - InterestManagerComponent(const InterestManagerComponent&) = delete; //Cannot use default due to unique_ptr. - }; -} // namesapce AzFramework - -#endif // AZFRAMEWORK_NET_INTERESTMANAGER_COMPONENT_H diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindable.cpp b/Code/Framework/AzFramework/AzFramework/Network/NetBindable.cpp deleted file mode 100644 index eb0e6efa47..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindable.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include -#include -#include -#include -#include -#include -#include - -namespace AzFramework -{ - //////////////// - // NetBindable - //////////////// - - NetBindable::NetBindable() - : m_isSyncEnabled(true) - { - } - - NetBindable::~NetBindable() - { - if (m_chunk) - { - // NetBindable is a base class for handlers for replica chunks, so we have to clear the handler since this object is about to go away - m_chunk->SetHandler(nullptr); - m_chunk = nullptr; - } - } - - GridMate::ReplicaChunkPtr NetBindable::GetNetworkBinding() - { - NetworkContext* netContext = nullptr; - NetSystemRequestBus::BroadcastResult(netContext, &NetSystemRequestBus::Events::GetNetworkContext); - AZ_Assert(netContext, "Cannot bind objects to the network with no NetworkContext"); - if (netContext) - { - m_chunk = netContext->CreateReplicaChunk(azrtti_typeid(this)); - netContext->Bind(this, m_chunk, NetworkContextBindMode::Authoritative); - return m_chunk; - } - - return nullptr; - } - - void NetBindable::SetNetworkBinding (GridMate::ReplicaChunkPtr chunk) - { - m_chunk = chunk; - - NetworkContext* netContext = nullptr; - NetSystemRequestBus::BroadcastResult(netContext, &NetSystemRequestBus::Events::GetNetworkContext); - AZ_Assert(netContext, "Cannot bind objects to the network with no NetworkContext"); - if (netContext) - { - netContext->Bind(this, m_chunk, NetworkContextBindMode::NonAuthoritative); - } - } - - void NetBindable::UnbindFromNetwork() - { - if (m_chunk) - { - // NetworkContext-reflected chunks need access to the handler when they are being destroyed, so we won't null handler in here - m_chunk = nullptr; - } - } - - void NetBindable::NetInit() - { - NetworkContext* netContext = nullptr; - NetSystemRequestBus::BroadcastResult(netContext, &NetSystemRequestBus::Events::GetNetworkContext); - AZ_Assert(netContext, "Cannot bind objects to the network with no NetworkContext"); - if (netContext) - { - netContext->Bind(this, nullptr, NetworkContextBindMode::NonAuthoritative); - } - } - - void NetBindable::Reflect(AZ::ReflectContext* reflection) - { - AZ::SerializeContext* serializeContext = azrtti_cast(reflection); - if (serializeContext) - { - serializeContext->Class() - ->Field("m_isSyncEnabled", &NetBindable::m_isSyncEnabled); - - AZ::EditContext* editContext = serializeContext->GetEditContext(); - - if (editContext) - { - editContext->Class( - "Network Bindable", "Network-bindable components are synchronized over the network.") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Networking") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) - ->DataElement(AZ::Edit::UIHandlers::Default, &NetBindable::m_isSyncEnabled, "Bind To network", "Enable binding to the network."); - } - } - } -} diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindable.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindable.h deleted file mode 100644 index 39a05c4fc1..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindable.h +++ /dev/null @@ -1,799 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#ifndef AZFRAMEWORK_NET_BINDABLE_H -#define AZFRAMEWORK_NET_BINDABLE_H - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -/* - * Including common GridMate marshallers. - * Otherwise, users of NetBindable/NetworkContext have to find and include them themselves. - */ -#include -#include -#include -#include -#include -#include -#include - -namespace AZ -{ - class ReflectContext; - namespace Internal - { - template - class AzFrameworkNetBindableFieldContainer; - } -} - -namespace AzFramework -{ - using GridMate::DataSetBase; - using GridMate::DataSet; - using GridMate::Marshaler; - using GridMate::BasicThrottle; - using GridMate::RpcBase; - using GridMate::TimeContext; - using GridMate::RpcContext; - using GridMate::RpcDefaultTraits; - - enum class NetworkContextBindMode - { - Authoritative, - NonAuthoritative - }; - - /** - * Components that want to be synchronized over the network should implement NetBindable. - * The NetBindable interface is obtained via AZ_RTTI so components need to make sure to - * declare NetBindable as a base class in their AZ_RTTI declaration (or AZ_COMPONENT declaration), - * as well as to declare both AZ::Component and NetBindable as base classes in the reflection. - * - * For example, here is how to mark a component for network replication in its class declaration: - * - * class TestFieldComponent - * : public AZ::Component - * , public AzFramework::NetBindable - * { - * public: - * AZ_COMPONENT(TestFieldComponent, "{DD02A926-F6B3-4820-9587-62EED9EEBB3F}", NetBindable); - * - * static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) - * { - * required.push_back(AZ_CRC("ReplicaChunkService")); - * } - * - * Note, you should declare a dependency on NetBindingComponent as it is done above with "ReplicaChunkService." - * NetBindingComponent is required for an entity to be considered for network replication and replicate your NetBindable-components. - */ - class NetBindable - : public GridMate::ReplicaChunkInterface - { - public: - AZ_RTTI(NetBindable, "{80206665-D429-4703-B42E-94434F82F381}"); - - NetBindable(); - virtual ~NetBindable(); - - void NetInit(); - - //! Called during network binding on the master. The default implementation will use the - //! NetworkContext to create a chunk. User implementations should create and return a new binding. - virtual GridMate::ReplicaChunkPtr GetNetworkBinding(); - - //! Called during network binding on proxies. - virtual void SetNetworkBinding(GridMate::ReplicaChunkPtr chunk); - - //! Called when network is unbound. Implementations should release their references to the binding, if they held a reference. - virtual void UnbindFromNetwork(); - - static void Reflect(AZ::ReflectContext* reflection); - - template , typename ThrottlerType = BasicThrottle > - class Field; - - template , typename ThrottlerType = BasicThrottle > - class BoundField; - - template - class Rpc; - - inline bool IsSyncEnabled() const { return m_isSyncEnabled; } - //! Can be used to disabled net sync on a per component basis - inline void SetSyncEnabled(bool enabled) { m_isSyncEnabled = enabled; } - protected: - bool m_isSyncEnabled; - GridMate::ReplicaChunkPtr m_chunk = nullptr; - }; - - class NetBindableFieldBase - { - public: - virtual ~NetBindableFieldBase() = default; - virtual void Bind(DataSetBase* dataSet, NetworkContextBindMode mode) = 0; - }; - - /** - * \brief NetBindable provides a simplified network interface to mark a member variable inside AZ::Component - * as a network field that will be replicated by GridMate. - * - * \tparam DataType data type of the field, can be either a common C++ type or a custom type - * \tparam MarshalerType optional, marshaler type that provides custom marshal and unmarshal logic, i.e. how to write @DataType to the network and back, see @GridMate::Marshaler - * \tparam ThrottlerType optional, throttler provides the ability to detect if a value is to be considered changed significantly enough for GridMate to replicate its state, see @GridMate::BasicThrottle - * - * Example: - * - * class TestFieldComponent : public AZ::Component , public AzFramework::NetBindable - * { - * public: - * Field m_testInt; - * - * And it must be reflected to SerializeContext _and_ NetworkContext: - * - * void TestFieldComponent::Reflect(AZ::ReflectContext* context) - * { - * if (AZ::SerializeContext* serialize = azrtti_cast(context)) - * { - * serialize->Class() - * ->Field("Test Int", &TestFieldComponent::m_testInt) - * ->Version(1); - * } - * - * if (AzFramework::NetworkContext* net = azrtti_cast(context)) - * { - * net->Class() - * ->Field("Test Int", &TestFieldComponent::m_testInt); - * } - * } - * - * Then you can simply write to it as it was an integer: - * - * m_testInt = 3; - * // or - * m_testInt = *m_testInt + 1; - */ - template - class NetBindable::Field - : public NetBindableFieldBase - { - friend class AZ::Internal::AzFrameworkNetBindableFieldContainer >; - public: - using DataSetType = DataSet; - using ValueType = DataType; - - explicit Field(const DataType& value = DataType()) - : m_dataSet(nullptr) - , m_value(value) - {} - ~Field() override = default; - - /* - * Disabling copy and move constructors in order to allow for a common use of fields, for example: - * m_field = m_field + 1; - */ - Field (const Field& other) = delete; - Field (Field&& other) = delete; - Field& operator= (const Field& other) = delete; - Field& operator= (Field&& other) = delete; - - const DataType& Get() const - { - return m_dataSet ? m_dataSet->Get() : m_value; - } - - virtual operator const DataType&() const - { - return Get(); - } - - virtual const DataType& operator*() const - { - return Get(); - } - - virtual Field& operator=(const DataType& val) - { - if (m_dataSet) - { - m_dataSet->Set(val); - } - else - { - m_value = val; - } - return *this; - } - - virtual Field& operator=(const DataType&& val) - { - if (m_dataSet) - { - m_dataSet->Set(AZStd::forward(val)); - } - else - { - m_value = AZStd::move(val); - } - return *this; - } - - void Bind(DataSetBase* dataSet, NetworkContextBindMode mode) override - { - BindDataSet(static_cast(dataSet), mode); - } - - static void ConstructDataSet(void* mem, const char* name) - { - new (mem) DataSetType(name, DataType(), MarshalerType(), ThrottlerType()); - } - - static void DestructDataSet(void* mem) - { - DataSetType* dataSet = reinterpret_cast(mem); - dataSet->~DataSetType(); - } - - protected: - template - void BindDataSet(DST* dataSet, NetworkContextBindMode mode) - { - if (m_dataSet) - { - m_value = m_dataSet->Get(); - } - m_dataSet = dataSet; - if (m_dataSet) - { - if (mode == NetworkContextBindMode::Authoritative) - { - /* - * If we are binding Field<> or BoundField<> on a component of an authoritative entity, - * then we want to bring over the value of the field in the component. This occurs during GetNetworkBinding(). - * - * Whereas on a client's (non-authoritative entities and their components) dataSet already has the desired value - * and should not be overwritten here. - */ - m_dataSet->Set(AZStd::move(m_value)); - } - m_value = DataType(); - } - } - - DataType* CacheValue() - { - if (m_dataSet) - { - m_value = m_dataSet->Get(); - } - return &m_value; - } - - const DataType& GetCachedValue() const - { - return m_value; - } - - private: - DataSet* m_dataSet; - DataType m_value; - }; - - /** - * \brief An extension of @NetBindable::Field with an ability to invoke a callback whenever the value changes on both authoritative and non-authoritative components. - * Or in other terms, on both the server and clients (when GridMate is setup to run in server-authoritative mode). - * - * \tparam DataType data type, same as @NetBindable::Field - * \tparam InterfaceType Component type class that holds this @BoundField - * \tparam FuncPtr member function pointer to the callback to invoke when this value is updated on non-authoritative components. - * \tparam MarshalerType optional, same as @NetBindable::Field - * \tparam ThrottlerType optional, same as @NetBindable::Field - * - * Example: - * - * BoundField m_testInt; - * - * And it must be reflected to SerializeContext _and_ NetworkContext just like @NetBindable::Field - * - * void TestFieldComponent::Reflect(AZ::ReflectContext* context) - * { - * if (AZ::SerializeContext* serialize = azrtti_cast(context)) - * { - * serialize->Class() - * ->Field("Test Int", &TestFieldComponent::m_testInt) - * ->Version(1); - * } - * - * if (AzFramework::NetworkContext* net = azrtti_cast(context)) - * { - * net->Class() - * ->Field("Test Int", &TestFieldComponent::m_testInt); - * } - * } - */ - template - class NetBindable::BoundField - : public NetBindable::Field - { - using BaseClass = NetBindable::Field; - friend class AZ::Internal::AzFrameworkNetBindableFieldContainer >; - public: - AZ_TYPE_INFO_LEGACY(BoundField, "{5151CEAF-6AC0-45D7-AEDF-8B6C46CE07B9}", DataType, InterfaceType, MarshalerType, ThrottlerType); - using DataSetType = typename DataSet::template BindInterface; - - explicit BoundField(const DataType& value = DataType()) - : BaseClass(value) - {} - ~BoundField() override = default; - - /* - * Disabling copy and move constructors in order to allow for a common use of fields, for example: - * m_field = m_field + 1; - */ - BoundField (const BoundField& other) = delete; - BoundField (BoundField&& other) = delete; - BoundField& operator= (const BoundField& other) = delete; - BoundField& operator= (BoundField&& other) = delete; - - operator DataType() const - { - return BaseClass::Get(); - } - - const DataType& operator*() const override - { - return BaseClass::Get(); - } - - BaseClass& operator=(const DataType& val) override - { - BaseClass::operator=(val); - return *this; - } - - BaseClass& operator=(const DataType&& val) override - { - BaseClass::operator=(val); - return *this; - } - - void Bind(DataSetBase* dataSet, NetworkContextBindMode mode) override - { - BaseClass::BindDataSet(static_cast(dataSet), mode); - } - - static void ConstructDataSet(void* mem, const char* name) - { - new (mem) DataSetType(name, DataType(), MarshalerType(), ThrottlerType()); - } - - static void DestructDataSet(void* mem) - { - DataSetType* dataSet = reinterpret_cast(mem); - dataSet->~DataSetType(); - } - }; - - class NetBindableRpcBase - { - public: - virtual ~NetBindableRpcBase() = default; - virtual void Bind(RpcBase* rpc) = 0; - virtual void Bind(NetBindable* handler) = 0; - }; - - /** - * \brief NetBindable::Rpc::Binder should be used for any RPC in a NetBindable that you want - * to be able to call remotely. If the object is not network bound, RPC - * calls will dispatch directly, as if the object was authoritative. - * - * \tparam Args any custom parameters for the remote procedure calls. - * - * Here is an example: - * - * // callback - * bool OnRpc(float value, const GridMate::RpcContext& rc); - * - * // Rpc declaration - * Rpc::Binder m_testRpc; - * - * Rpc needs to be reflected in NetworkContext like this: - * - * void TestRPCComponent::Reflect(AZ::ReflectContext* context) - * { - * if (AZ::SerializeContext* serialize = azrtti_cast(context)) - * { - * serialize->Class() - * ->Version(1); - * } - * - * if (AzFramework::NetworkContext* net = azrtti_cast(context)) - * { - * net->Class() - * ->RPC("Test RPC", &TestRPCComponent::m_testRpc); - * } - * } - * - * It can be invoked as if it was a method: - * - * m_testRpc(deltaTime); - */ - template - class NetBindable::Rpc - { - public: - /** - * \brief Binds rpc callback to a pointer to member function of AZ::Component derived from AzFramework::NetBindable - * See @NetBindable::Rpc - */ - template - class Binder - : public NetBindableRpcBase - { - friend class NetworkContext; - public: - using BindInterfaceType = typename GridMate::Rpc...>::template BindInterface; - - Binder() - : m_rpc(nullptr) - , m_instance(nullptr) - {} - - void Bind(RpcBase* rpc) override - { - m_rpc = static_cast(rpc); - m_instance = nullptr; - } - - void Bind(NetBindable* bindable) override - { - m_instance = static_cast(bindable); - m_rpc = nullptr; - } - - template - void operator()(CallArgs&& ... args) - { - AZ_Assert(m_instance || m_rpc, "Cannot call an RPC without either a local instance or a network bound handler, did you forget to register with NetworkContext()?"); - if (m_rpc) // connected to network - { - (*m_rpc)(AZStd::forward(args) ...); - } - else if (m_instance) // local dispatch - { - (*m_instance.*FuncPtr)(AZStd::forward(args) ..., RpcContext()); - } - } - - protected: - static void ConstructRpc(void* mem, const char* name) - { - new (mem) BindInterfaceType(name); - } - - static void DestructRpc(void*) { } - - private: - BindInterfaceType* m_rpc; - InterfaceType* m_instance; - }; - - Rpc() = delete; - }; -} // namespace AzFramework - -namespace AZ -{ - AZ_TYPE_INFO_TEMPLATE_WITH_NAME(AzFramework::NetBindable::Field, "Field", "{00D56FA7-F8BD-402B-97FB-0E2599897056}", AZ_TYPE_INFO_CLASS, AZ_TYPE_INFO_TYPENAME, AZ_TYPE_INFO_TYPENAME); - - namespace Internal - { - template - class AzFrameworkNetBindableFieldContainer - : public SerializeContext::IDataContainer - { - using ValueType = typename FieldType::ValueType; - public: - AzFrameworkNetBindableFieldContainer() - { - m_classElement.m_name = GetDefaultElementName(); - m_classElement.m_nameCrc = GetDefaultElementNameCrc(); - m_classElement.m_dataSize = sizeof(ValueType); - m_classElement.m_offset = 0; - m_classElement.m_azRtti = GetRttiHelper(); - m_classElement.m_flags = AZStd::is_pointer::value ? SerializeContext::ClassElement::FLG_POINTER : 0; - m_classElement.m_genericClassInfo = SerializeGenericTypeInfo::GetGenericInfo(); - m_classElement.m_typeId = SerializeGenericTypeInfo::GetClassTypeId(); - m_classElement.m_editData = nullptr; - } - - /// Returns the element generic (offsets are mostly invalid 0xbad0ffe0, there are exceptions). Null if element with this name can't be found. - virtual const SerializeContext::ClassElement* GetElement(AZ::u32 elementNameCrc) const override - { - if (elementNameCrc == m_classElement.m_nameCrc) - { - return &m_classElement; - } - return nullptr; - } - - bool GetElement(SerializeContext::ClassElement& classElement, const SerializeContext::DataElement& dataElement) const override - { - if (dataElement.m_nameCrc == m_classElement.m_nameCrc) - { - classElement = m_classElement; - return true; - } - return false; - } - - /// Enumerate elements in the array - virtual void EnumElements(void* instance, const ElementCB& cb) override - { - FieldType* field = reinterpret_cast(instance); - // We can't mess with the internal storage of the dataset safely, so we copy it into - // the field's local value cache temporarily, then hand that to the callback - // This will modify the local value cache, but that shouldn't matter as it will never - // be used as long as a dataset is bound - // If this turns out to be a perf problem due to copies of complex types, then - // the easy solution is to get DataSets to expose a pointer to their underlying - // data storage, and then we can return a pointer to that and modify it directly - // if the field is bound to the network - ValueType* valPtr = field->CacheValue(); - cb(valPtr, m_classElement.m_typeId, m_classElement.m_genericClassInfo ? m_classElement.m_genericClassInfo->GetClassData() : nullptr, &m_classElement); - // Ensure that the dataset is updated if changes happened - *field = *valPtr; - } - - void EnumTypes(const ElementTypeCB& cb) override - { - cb(m_classElement.m_typeId, &m_classElement); - } - - /// Return number of elements in the container. - virtual size_t Size(void*) const override - { - return 1; - } - - /// Returns the capacity of the container. Returns 0 for objects without fixed capacity. - virtual size_t Capacity(void* instance) const override - { - (void)instance; - return 1; - } - - /// Returns true if elements pointers don't change on add/remove. If false you MUST enumerate all elements. - virtual bool IsStableElements() const override { return true; } - - /// Returns true if the container is fixed size, otherwise false. - virtual bool IsFixedSize() const override { return true; } - - /// Returns if the container is fixed capacity, otherwise false - virtual bool IsFixedCapacity() const override { return true; } - - /// Returns true if the container is a smart pointer. - virtual bool IsSmartPointer() const override { return true; } - - /// Returns true if the container elements can be addressed by index, otherwise false. - virtual bool CanAccessElementsByIndex() const override { return false; } - - /// Reserve element - virtual void* ReserveElement(void* instance, const SerializeContext::ClassElement*) override - { - FieldType* field = reinterpret_cast(instance); - *field = ValueType(); - return field->CacheValue(); // return the local value, should be accurate as the field will be unbound at serialization time - } - - /// Get an element's address by its index (called before the element is loaded). - virtual void* GetElementByIndex(void*, const SerializeContext::ClassElement*, size_t) override - { - return nullptr; - } - - /// Store element - virtual void StoreElement(void* instance, void*) override - { - // force store the value again, just in case the field is bound to a dataset - FieldType* field = reinterpret_cast(instance); - *field = field->GetCachedValue(); - } - - /// Remove element in the container. - virtual bool RemoveElement(void* instance, const void*, SerializeContext*) override - { - FieldType* field = reinterpret_cast(instance); - *field = ValueType(); - return false; // you can't remove element from this container. - } - - /// Remove elements (removed array of elements) regardless if the container is Stable or not (IsStableElements) - virtual size_t RemoveElements(void* instance, const void**, size_t, SerializeContext*) override - { - RemoveElement(instance, nullptr, nullptr); - return 0; // you can't remove elements from this container. - } - - /// Clear elements in the instance. - virtual void ClearElements(void* instance, SerializeContext*) override - { - RemoveElement(instance, nullptr, nullptr); - } - - SerializeContext::ClassElement m_classElement; ///< Generic class element covering as must as possible of the element (offset, and some other fields are invalid) - }; - } - - template - struct SerializeGenericTypeInfo< AzFramework::NetBindable::Field > - { - typedef typename AzFramework::NetBindable::Field ContainerType; - - class GenericClassNetBindableField - : public GenericClassInfo - { - public: - AZ_TYPE_INFO(GenericClassNetBindableField, "{C1D4DD97-5DD7-42ED-969C-7435F27F5D8C}"); - GenericClassNetBindableField() - : m_classData{ SerializeContext::ClassData::Create("AzFramework::NetBindable::Field", GetSpecializedTypeId(), Internal::NullFactory::GetInstance(), nullptr, &m_containerStorage) } - { - } - - SerializeContext::ClassData* GetClassData() override - { - return &m_classData; - } - - size_t GetNumTemplatedArguments() override - { - return 1; - } - - const Uuid& GetTemplatedTypeId(size_t) override - { - return SerializeGenericTypeInfo::GetClassTypeId(); - } - - const Uuid& GetSpecializedTypeId() const override - { - return azrtti_typeid(); - } - - const Uuid& GetGenericTypeId() const override - { - return TYPEINFO_Uuid(); - } - - const Uuid& GetLegacySpecializedTypeId() const override - { - return AZ::AzTypeInfo::template Uuid(); - } - - void Reflect(SerializeContext* serializeContext) - { - if (serializeContext) - { - serializeContext->RegisterGenericClassInfo(GetSpecializedTypeId(), this, &AnyTypeInfoConcept::CreateAny); - if (GenericClassInfo* containerGenericClassInfo = m_containerStorage.m_classElement.m_genericClassInfo) - { - containerGenericClassInfo->Reflect(serializeContext); - } - } - } - - protected: - Internal::AzFrameworkNetBindableFieldContainer m_containerStorage; - SerializeContext::ClassData m_classData; - }; - - using ClassInfoType = GenericClassNetBindableField; - - static ClassInfoType* GetGenericInfo() - { - return GetCurrentSerializeContextModule().CreateGenericClassInfo(); - } - - static const Uuid& GetClassTypeId() - { - return GetGenericInfo()->GetClassData()->m_typeId; - } - }; - - template - struct SerializeGenericTypeInfo< typename AzFramework::NetBindable::BoundField > - { - typedef typename AzFramework::NetBindable::BoundField ContainerType; - - class GenericClassNetBindableBoundField - : public GenericClassInfo - { - public: - AZ_TYPE_INFO(GenericClassNetBindableBoundField, "{EFD64FE7-9432-401A-B7A1-1767F4C5A7F0}"); - GenericClassNetBindableBoundField() - : m_classData{ SerializeContext::ClassData::Create("AzFramework::NetBindable::BoundField", GetSpecializedTypeId(), Internal::NullFactory::GetInstance(), nullptr, &m_containerStorage) } - { - } - - SerializeContext::ClassData* GetClassData() override - { - return &m_classData; - } - - size_t GetNumTemplatedArguments() override - { - return 1; - } - - const Uuid& GetTemplatedTypeId(size_t) override - { - return SerializeGenericTypeInfo::GetClassTypeId(); - } - - const Uuid& GetSpecializedTypeId() const override - { - return azrtti_typeid(); - } - - const Uuid& GetGenericTypeId() const override - { - return TYPEINFO_Uuid(); - } - - const Uuid& GetLegacySpecializedTypeId() const override - { - return AZ::AzTypeInfo::template Uuid(); - } - - void Reflect(SerializeContext* serializeContext) - { - if (serializeContext) - { - serializeContext->RegisterGenericClassInfo(GetSpecializedTypeId(), this, &AnyTypeInfoConcept::CreateAny); - if (GenericClassInfo* containerGenericClassInfo = m_containerStorage.m_classElement.m_genericClassInfo) - { - containerGenericClassInfo->Reflect(serializeContext); - } - } - } - - protected: - Internal::AzFrameworkNetBindableFieldContainer m_containerStorage; - SerializeContext::ClassData m_classData; - }; - - using ClassInfoType = GenericClassNetBindableBoundField; - - static ClassInfoType* GetGenericInfo() - { - return GetCurrentSerializeContextModule().CreateGenericClassInfo(); - } - - static const Uuid& GetClassTypeId() - { - return GetGenericInfo()->GetClassData()->m_typeId; - } - }; -} - -#endif // AZFRAMEWORK_NET_BINDABLE_H -#pragma once diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponent.cpp b/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponent.cpp deleted file mode 100644 index 90613daabe..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponent.cpp +++ /dev/null @@ -1,287 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace AzFramework -{ - void NetBindingComponent::Reflect(AZ::ReflectContext* reflection) - { - NetBindable::Reflect(reflection); - - AZ::SerializeContext* serializeContext = azrtti_cast(reflection); - if (serializeContext) - { - serializeContext->Class() - ; - - AZ::EditContext* editContext = serializeContext->GetEditContext(); - - if (editContext) - { - editContext->Class( - "Network Binding", "The Network Binding component marks an entity as able to be replicated across the network") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Networking") - ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/NetBinding.svg") - ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/NetBinding.png") - ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://docs.aws.amazon.com/lumberyard/latest/userguide/component-network-binding.html") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)); - } - } - - AZ::BehaviorContext* behaviorContext = azrtti_cast(reflection); - - if (behaviorContext) - { - behaviorContext->EBus("NetBindingHandlerBus") - ->Event("IsEntityBoundToNetwork", &NetBindingHandlerBus::Events::IsEntityBoundToNetwork) - ->Event("IsEntityAuthoritative", &NetBindingHandlerBus::Events::IsEntityAuthoritative) - - // Desired, but currently unsupported events. - // Seems to be an unsupported type(AZ::u16) - //->Event("SetReplicaPriority", &NetBindingHandlerBus::Events::SetReplicaPriority) - //->Event("GetReplicaPriority", &NetBindingHandlerBus::Events::GetReplicaPriority) - ; - } - - // We also need to register the chunk type, and this would be a good time to do so. - if (!GridMate::ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(GridMate::ReplicaChunkClassId(NetBindingComponentChunk::GetChunkName()))) - { - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - } - } - - NetBindingComponent::NetBindingComponent() - : m_isLevelSliceEntity(false) - { - } - - void NetBindingComponent::Activate() - { - NetBindingHandlerBus::Handler::BusConnect(GetEntityId()); - - if (!IsEntityBoundToNetwork()) - { - bool shouldBind = false; - NetBindingSystemBus::BroadcastResult( shouldBind, &NetBindingSystemBus::Events::ShouldBindToNetwork); - if (shouldBind) - { - BindToNetwork(nullptr); - } - else - { - /* - * This is the Editor path. We still need to call NetBindable::NetInit() in order - * to initialize NetworkContext Fields and RPCs, so that they behave as - * authoritative in game editor mode. Without this call RPCs callbacks won't invoke inside the Editor. - * For example: - * - * static void Reflect(...) - * { - * NetworkContext->Class()->RPC("my rpc", &MyNetworkComponent::m_myRpc); - * } - * ... - * m_myRpc(); // <--- will not invoke the callback inside the Editor unless NetInit() is called below. - */ - for (Component* component : GetEntity()->GetComponents()) - { - if (NetBindable* netBindable = azrtti_cast(component)) - { - netBindable->NetInit(); - } - } - } - } - } - - void NetBindingComponent::Deactivate() - { - NetBindingHandlerBus::Handler::BusDisconnect(); - if (IsEntityBoundToNetwork()) - { - static_cast(m_chunk.get())->SetBinding(nullptr); - if (m_chunk->IsMaster()) - { - m_chunk->GetReplica()->Destroy(); - } - m_chunk = nullptr; - } - } - - bool NetBindingComponent::IsEntityBoundToNetwork() - { - return m_chunk && m_chunk->GetReplica(); - } - - bool NetBindingComponent::IsEntityAuthoritative() - { - return !m_chunk || m_chunk->IsMaster(); - } - - void NetBindingComponent::BindToNetwork(GridMate::ReplicaPtr bindTo) - { - AZ_Assert(!IsEntityBoundToNetwork(), "We shouldn't be bound to the network if the network is just starting!"); - - if (bindTo) - { - NetBindingComponentChunkPtr bindingChunk = bindTo->FindReplicaChunk(); - AZ_Assert(bindingChunk, "Can't find NetBindingComponentChunk!"); - m_chunk = bindingChunk; - bindingChunk->SetBinding(this); - - GridMate::Replica* replica = bindingChunk->GetReplica(); - size_t nChunks = replica->GetNumChunks(); - size_t nBindings = bindingChunk->m_bindMap.Get().size(); - AZ_Assert(nChunks == nBindings, "Number of chunks received is not the same as the size of the bind map!"); - nBindings = AZ::GetMin(nBindings, nChunks); - for (size_t i = 0; i < nBindings; ++i) - { - AZ::ComponentId bindToId = bindingChunk->m_bindMap.Get()[i]; - if (bindToId != AZ::InvalidComponentId) - { - AZ::Component* component = GetEntity()->FindComponent(bindToId); - NetBindable* netBindable = azrtti_cast(component); - AZ_Assert(netBindable, "Can't find net bindable component with id %llu to be bound to chunk type %s!", bindToId, replica->GetChunkByIndex(i)->GetDescriptor()->GetChunkName()); - if (netBindable && netBindable->IsSyncEnabled()) - { - netBindable->SetNetworkBinding(replica->GetChunkByIndex(i)); - } - } - } - } - else - { - GridMate::ReplicaPtr replica = GridMate::Replica::CreateReplica(GetEntity()->GetName().c_str()); - NetBindingComponentChunk* chunk = GridMate::CreateReplicaChunk(); - m_chunk = chunk; - chunk->SetBinding(this); - replica->AttachReplicaChunk(chunk); - - chunk->m_bindMap.Modify([&](AZStd::vector& bindMap) - { - // Mark the chunks already in the replica as non-components. - bindMap.resize(replica->GetNumChunks(), AZ::InvalidComponentId); - - // Collect the bindings and add the to the replica - AZ::Entity* entity = GetEntity(); - for (Component* component : entity->GetComponents()) - { - NetBindable* netBindable = azrtti_cast(component); - if (netBindable && netBindable->IsSyncEnabled()) - { - GridMate::ReplicaChunkPtr bindingChunk = netBindable->GetNetworkBinding(); - if (bindingChunk) - { - bindMap.push_back(component->GetId()); - replica->AttachReplicaChunk(bindingChunk); - } - } - } - return true; - }); - - // Add replica to session replica manager (may be deferred) - NetBindingSystemBus::Broadcast( &NetBindingSystemBus::Events::AddReplicaMaster, GetEntity(), replica); - } - } - - void NetBindingComponent::UnbindFromNetwork() - { - if (m_chunk) - { - for (Component* component : GetEntity()->GetComponents()) - { - NetBindable* netBindable = azrtti_cast(component); - if (netBindable && netBindable->IsSyncEnabled()) - { - netBindable->UnbindFromNetwork(); - } - } - - NetBindingComponentChunkPtr chunk = static_cast(m_chunk.get()); - chunk->SetBinding(nullptr); - m_chunk = nullptr; - if (chunk->IsProxy()) - { - EntityContextId contextId = EntityContextId::CreateNull(); - EntityIdContextQueryBus::EventResult( contextId, GetEntityId(), &EntityIdContextQueryBus::Events::GetOwningContextId); - if (contextId.IsNull()) - { - delete GetEntity(); - } - else if (!IsLevelSliceEntity()) - { - NetBindingSystemBus::Broadcast( &NetBindingSystemBus::Events::UnbindGameEntity, GetEntityId(), m_sliceInstanceId); - } - } - } - } - - void NetBindingComponent::MarkAsLevelSliceEntity() - { - AZ_Assert(!IsEntityBoundToNetwork(), "MarkAsLevelSliceEntity() has to be called before the entity is bound to the network!"); - m_isLevelSliceEntity = true; - } - - void NetBindingComponent::SetSliceInstanceId(const AZ::SliceComponent::SliceInstanceId& sliceInstanceId) - { - m_sliceInstanceId = sliceInstanceId; - } - - void NetBindingComponent::RequestEntityChangeOwnership(GridMate::PeerId peerId) - { - if (m_chunk && m_chunk->GetReplica()) - { - m_chunk->GetReplica()->RequestChangeOwnership(peerId); - } - } - - void NetBindingComponent::SetReplicaPriority(GridMate::ReplicaPriority replicaPriority) - { - if (m_chunk) - { - m_chunk->SetPriority(replicaPriority); - } - } - - GridMate::ReplicaPriority NetBindingComponent::GetReplicaPriority() const - { - if (m_chunk && m_chunk->GetReplica()) - { - return m_chunk->GetReplica()->GetPriority(); - } - else - { - AZ_Error("NetBindingComponent",false,"Trying to gather ReplicaPriority without having a Replica."); - return GridMate::k_replicaPriorityLowest; - } - } - - bool NetBindingComponent::IsLevelSliceEntity() const - { - return m_isLevelSliceEntity; - } -} // namespace AzFramework - diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponent.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponent.h deleted file mode 100644 index 5f4ec1c7f3..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponent.h +++ /dev/null @@ -1,85 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#ifndef AZFRAMEWORK_NET_BINDING_COMPONENT_H -#define AZFRAMEWORK_NET_BINDING_COMPONENT_H - -#include -#include - -namespace AzFramework -{ - /** - * NetBindingComponent enables network synchronization for the entity. - * It works in conjunction with NetBindingComponentChunk and NetBindingSystemComponent - * to perform network binding and notifies other components on the entity to bind - * their ReplicaChunks via the NetBindable interface. - * - * Entities bound to proxy replicas will be automatically destroyed when they are - * unbound from the network. - */ - class NetBindingComponent - : public AZ::Component - , public NetBindingHandlerBus::Handler - { - friend class NetBindingComponentChunk; - - public: - AZ_COMPONENT(NetBindingComponent, "{E9CA5D63-ED2D-4B59-B3C4-EBCD4A0013E4}", NetBindingHandlerInterface); - - NetBindingComponent(); - - protected: - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("ReplicaChunkService", 0xf86b88a8)); - } - - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("ReplicaChunkService", 0xf86b88a8)); - } - - /////////////////////////////////////////////////////////////////////// - // AZ::Component - static void Reflect(AZ::ReflectContext* reflection); - void Activate() override; - void Deactivate() override; - /////////////////////////////////////////////////////////////////////// - - /////////////////////////////////////////////////////////////////////// - // NetBindingHandlerBus::Handler - void BindToNetwork(GridMate::ReplicaPtr bindTo) override; - void UnbindFromNetwork() override; - bool IsEntityBoundToNetwork() override; - bool IsEntityAuthoritative() override; - void MarkAsLevelSliceEntity() override; - void SetSliceInstanceId(const AZ::SliceComponent::SliceInstanceId& sliceInstanceId) override; - void RequestEntityChangeOwnership(GridMate::PeerId peerId = GridMate::InvalidReplicaPeerId) override; - - void SetReplicaPriority(GridMate::ReplicaPriority replicaPriority) override; - GridMate::ReplicaPriority GetReplicaPriority() const override; - /////////////////////////////////////////////////////////////////////// - - //! Returns if the entity belongs to the level slice for binding purposes. - bool IsLevelSliceEntity() const; - - //! Points to the NetBindingComponentChunk counterpart. - GridMate::ReplicaChunkPtr m_chunk; - bool m_isLevelSliceEntity; - AZ::SliceComponent::SliceInstanceId m_sliceInstanceId; - }; -} // namespace AzFramework - -#endif // AZFRAMEWORK_NET_BINDING_COMPONENT_H -#pragma once diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponentChunk.cpp b/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponentChunk.cpp deleted file mode 100644 index 6ebfe63507..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponentChunk.cpp +++ /dev/null @@ -1,254 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace AzFramework -{ - NetBindingComponentChunk::SpawnInfo::SpawnInfo() - : m_runtimeEntityId(AZ::EntityId::InvalidEntityId) - , m_owningContextId(UnspecifiedNetBindingContextSequence) - , m_staticEntityId(AZ::EntityId::InvalidEntityId) - , m_sliceInstanceId(UnspecifiedSliceInstanceId) - , m_sliceAssetId(UnspecifiedSliceInstanceId, 0) - { - } - - bool NetBindingComponentChunk::SpawnInfo::operator==(const SpawnInfo& rhs) - { - return m_owningContextId == rhs.m_owningContextId - && m_runtimeEntityId == rhs.m_runtimeEntityId - && m_staticEntityId == rhs.m_staticEntityId - && m_serializedState == rhs.m_serializedState - && m_sliceAssetId == rhs.m_sliceAssetId; - } - - bool NetBindingComponentChunk::SpawnInfo::ContainsSerializedState() const - { - return !m_serializedState.empty(); - } - - void NetBindingComponentChunk::SpawnInfo::Marshaler::Marshal(GridMate::WriteBuffer& wb, const SpawnInfo& data) - { - wb.Write(data.m_owningContextId, GridMate::VlqU32Marshaler()); - wb.Write(data.m_runtimeEntityId); - - bool useSerializedState = data.ContainsSerializedState(); - wb.Write(useSerializedState); - if (useSerializedState) - { - wb.Write(data.m_serializedState); - } - else - { - wb.Write(data.m_sliceAssetId); - wb.Write(data.m_staticEntityId); - wb.Write(data.m_sliceInstanceId); - } - } - - void NetBindingComponentChunk::SpawnInfo::Marshaler::Unmarshal(SpawnInfo& data, GridMate::ReadBuffer& rb) - { - rb.Read(data.m_owningContextId, GridMate::VlqU32Marshaler()); - rb.Read(data.m_runtimeEntityId); - - bool hasSerializedState = false; - rb.Read(hasSerializedState); - if (hasSerializedState) - { - rb.Read(data.m_serializedState); - } - else - { - rb.Read(data.m_sliceAssetId); - rb.Read(data.m_staticEntityId); - rb.Read(data.m_sliceInstanceId); - } - } - - NetBindingComponentChunk::NetBindingComponentChunk() - : m_bindingComponent(nullptr) - , m_spawnInfo("SpawnInfo") - , m_bindMap("ComponentBindMap") - { - m_spawnInfo.SetMaxIdleTime(0.f); - m_bindMap.SetMaxIdleTime(0.f); - } - - void NetBindingComponentChunk::OnReplicaActivate(const GridMate::ReplicaContext& rc) - { - (void)rc; - if (IsMaster()) - { - // Get and store entity spawn data - AZ_Assert(m_bindingComponent, "Entity binding is invalid!"); - - m_spawnInfo.Modify([&](SpawnInfo& spawnInfo) - { - spawnInfo.m_runtimeEntityId = static_cast(m_bindingComponent->GetEntity()->GetId()); - - bool isProceduralEntity = true; - AZ::SliceComponent::SliceInstanceAddress sliceInfo; - - EntityContextId contextId = EntityContextId::CreateNull(); - const AZ::EntityId bindingComponentEntityId = m_bindingComponent->GetEntityId(); - EntityIdContextQueryBus::EventResult(contextId, bindingComponentEntityId, - &EntityIdContextQueryBus::Events::GetOwningContextId); - if (!contextId.IsNull()) - { - EBUS_EVENT_RESULT(spawnInfo.m_owningContextId, NetBindingSystemBus, GetCurrentContextSequence); - SliceEntityRequestBus::EventResult(sliceInfo, bindingComponentEntityId, - &SliceEntityRequestBus::Events::GetOwningSlice); - bool isDynamicSliceEntity = sliceInfo.IsValid(); - - isProceduralEntity = !m_bindingComponent->IsLevelSliceEntity() && !isDynamicSliceEntity; - } - - if (isProceduralEntity) - { - // write cloning info - AZ::SerializeContext* sc = nullptr; - EBUS_EVENT_RESULT(sc, AZ::ComponentApplicationBus, GetSerializeContext); - AZ_Assert(sc, "Can't find SerializeContext!"); - AZ::IO::ByteContainerStream> spawnDataStream(&spawnInfo.m_serializedState); - AZ::ObjectStream* objStream = AZ::ObjectStream::Create(&spawnDataStream, *sc, AZ::DataStream::ST_BINARY); - objStream->WriteClass(m_bindingComponent->GetEntity()); - objStream->Finalize(); - } - else - { - // write slice info - if (sliceInfo.IsValid()) - { - AZ::Data::AssetId sliceAssetId = sliceInfo.GetReference()->GetSliceAsset().GetId(); - spawnInfo.m_sliceAssetId = AZStd::make_pair(sliceAssetId.m_guid, sliceAssetId.m_subId); - } - if (sliceInfo.GetInstance()) - { - spawnInfo.m_sliceInstanceId = sliceInfo.GetInstance()->GetId(); - } - - AZ::EntityId staticEntityId; - EBUS_EVENT_RESULT(staticEntityId, NetBindingSystemBus, GetStaticIdFromEntityId, m_bindingComponent->GetEntity()->GetId()); - spawnInfo.m_staticEntityId = static_cast(staticEntityId); - } - - return true; - }); - } - else - { - AZ::EntityId runtimeEntityId(m_spawnInfo.Get().m_runtimeEntityId); - NetBindingContextSequence owningContextId = m_spawnInfo.Get().m_owningContextId; - - //TODO Move to Filter Hook - // Reject and cancel sessions with duplicate MachineIds? - // Reject and cancel sessions with duplicate entity ID creation requests? - //Check MachineId collision - bool collision = AZ::Entity::GetProcessSignature() == (m_spawnInfo.Get().m_runtimeEntityId & 0xFFFFFFFF); - AZ_Error("GridMate", !collision, "Replica received with duplicate Entity Machine IDs. Ignoring"); - - if (!collision) - { - //Check EntityID collision - AZ::Entity* entity = nullptr; - EBUS_EVENT_RESULT(entity, AZ::ComponentApplicationBus, FindEntity, runtimeEntityId); - - /* - * Only false if no machine ID collision and no entity ID collision - * And the entity is already active, it's possible the entity already exists in deactivated state as a cache mechanism - */ - collision = (entity != nullptr) && (entity->GetState() == AZ::Entity::State::Active); - } - - /** - * Special case - static entities should not count as duplicates. - * Static entities are loaded with the level and will be bounded here. - */ - if (collision) - { - AZ::EntityId staticEntityId; - EBUS_EVENT_RESULT(staticEntityId, NetBindingSystemBus, GetStaticIdFromEntityId, runtimeEntityId); - if (staticEntityId == runtimeEntityId) - { - collision = false; - } - } - - if (!collision) //Ignore duplicate runtime entity IDs - { - if (m_spawnInfo.Get().ContainsSerializedState()) - { - // Spawn the entity from stream input data - AZ::IO::MemoryStream spawnData(m_spawnInfo.Get().m_serializedState.data(), m_spawnInfo.Get().m_serializedState.size()); - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromStream, spawnData, runtimeEntityId, GetReplicaId(), owningContextId); - } - else - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = owningContextId; - spawnContext.m_sliceAssetId = AZ::Data::AssetId(m_spawnInfo.Get().m_sliceAssetId.first, m_spawnInfo.Get().m_sliceAssetId.second); - spawnContext.m_runtimeEntityId = runtimeEntityId; - spawnContext.m_staticEntityId = AZ::EntityId(m_spawnInfo.Get().m_staticEntityId); - spawnContext.m_sliceInstanceId = m_spawnInfo.Get().m_sliceInstanceId; - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, GetReplicaId(), spawnContext); - } - } - else //Fail early to prevent unnecessary spawning of duplicate entity IDs - { - //Misconfiguration or potential cheating/DoS? - AZ_Warning("NetBinding", false, "Received duplicate Entity ID %llu. Ignoring.", runtimeEntityId); - } - } - } - - void NetBindingComponentChunk::OnReplicaDeactivate(const GridMate::ReplicaContext& rc) - { - (void)rc; - if (m_bindingComponent) - { - m_bindingComponent->UnbindFromNetwork(); - } - } - - bool NetBindingComponentChunk::AcceptChangeOwnership(GridMate::PeerId requestor, const GridMate::ReplicaContext& rc) - { - bool result = true; - - if (m_bindingComponent) - { - EBUS_EVENT_ID_RESULT(result, m_bindingComponent->GetEntityId(), NetBindingEventsBus, OnEntityAcceptChangeOwnership, requestor, rc); - } - - return result; - } - - void NetBindingComponentChunk::OnReplicaChangeOwnership(const GridMate::ReplicaContext& rc) - { - if (m_bindingComponent) - { - EBUS_EVENT_ID(m_bindingComponent->GetEntityId(), NetBindingEventsBus, OnEntityChangeOwnership, rc); - } - } -} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponentChunk.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponentChunk.h deleted file mode 100644 index 5a0f023fa2..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingComponentChunk.h +++ /dev/null @@ -1,112 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#ifndef AZFRAMEWORK_NET_BINDING_COMPONENT_CHUNK_H -#define AZFRAMEWORK_NET_BINDING_COMPONENT_CHUNK_H - -#include -#include -#include -#include -#include -#include -#include - -namespace AzFramework -{ - class NetBindingComponent; - class NetBindingComponentChunkDescriptor; - - /** - * NetBindingComponentChunk is the counterpart of NetBindingComponent on the network side. - * It contains entity spawn data. It is created by NetBindingComponent during network - * binding on the master and initiates entity creation and binding on the proxy side. - */ - class NetBindingComponentChunk - : public GridMate::ReplicaChunk - { - friend NetBindingComponent; - friend NetBindingComponentChunkDescriptor; - - public: - AZ_CLASS_ALLOCATOR(NetBindingComponentChunk, AZ::SystemAllocator, 0); - - static const char* GetChunkName() { return "NetBindingComponentChunk"; } - - NetBindingComponentChunk(); - - void SetBinding(NetBindingComponent* bindingComponent) { m_bindingComponent = bindingComponent; } - NetBindingComponent* GetBinding() const { return m_bindingComponent; } - - protected: - /////////////////////////////////////////////////////////////////////// - // ReplicaChunk - bool IsReplicaMigratable() override { return true; } - void OnReplicaActivate(const GridMate::ReplicaContext& rc) override; - void OnReplicaDeactivate(const GridMate::ReplicaContext& rc) override; - bool AcceptChangeOwnership(GridMate::PeerId requestor, const GridMate::ReplicaContext& rc) override; - void OnReplicaChangeOwnership(const GridMate::ReplicaContext& rc) override; - /////////////////////////////////////////////////////////////////////// - - NetBindingComponent* m_bindingComponent; - - class SpawnInfo - { - public: - class Marshaler - { - public: - void Marshal(GridMate::WriteBuffer& wb, const SpawnInfo& data); - void Unmarshal(SpawnInfo& data, GridMate::ReadBuffer& rb); - }; - - class Throttle - { - public: - //! Always return true because SpawnInfo never changes - bool WithinThreshold(const SpawnInfo&) const { return true; } - void UpdateBaseline(const SpawnInfo& baseline) { (void)baseline; } - }; - - SpawnInfo(); - - bool operator==(const SpawnInfo& rhs); - - bool ContainsSerializedState() const; - - /** - * \brief Same as m_staticEntityId on authoritative entity with master replica - */ - AZ::u64 m_runtimeEntityId; - NetBindingContextSequence m_owningContextId; - AZStd::vector m_serializedState; - - /** - * \brief EntityId of authoritative entity with master replica - */ - AZ::u64 m_staticEntityId; - - AZStd::pair m_sliceAssetId; - /** - * \brief uniquely identifies the slice instance that this entity is being replicated from - */ - AZ::SliceComponent::SliceInstanceId m_sliceInstanceId; - }; - - GridMate::DataSet m_spawnInfo; - GridMate::DataSet > m_bindMap; - }; - typedef AZStd::intrusive_ptr NetBindingComponentChunkPtr; -} // namespace AZ - -#endif // AZFRAMEWORK_NET_BINDING_COMPONENT_CHUNK_H -#pragma once diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingEventsBus.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindingEventsBus.h deleted file mode 100644 index f3089947dc..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingEventsBus.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#ifndef AZFRAMEWORK_NET_BINDING_EVENTS_BUS_H -#define AZFRAMEWORK_NET_BINDING_EVENTS_BUS_H - -#include -#include -#include - -namespace AzFramework -{ - /** - * NetBindingEventsBus - * Throws networking related entity events - */ - class NetBindingEvents - : public AZ::EBusTraits - { - public: - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - typedef AZ::EntityId BusIdType; - - virtual ~NetBindingEvents() {} - - /** - * Called on authoritative(Master) entity when ownership of this entity is about to be transferred to another peer - * Returning false from this call will result in denying request for ownership transfer - */ - virtual bool OnEntityAcceptChangeOwnership(GridMate::PeerId requestor, const GridMate::ReplicaContext& rc) { (void)requestor; (void)rc; return true; } - - /** - * Called when ownership transfer of an entity is finished. - */ - virtual void OnEntityChangeOwnership(const GridMate::ReplicaContext& rc) { (void)rc; } - }; - - typedef AZ::EBus NetBindingEventsBus; -} // namespace AzFramework - -#endif // AZFRAMEWORK_NET_BINDING_EVENTS_BUS_H -#pragma once diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingHandlerBus.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindingHandlerBus.h deleted file mode 100644 index 55fa4c0217..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingHandlerBus.h +++ /dev/null @@ -1,112 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#ifndef AZFRAMEWORK_NET_BINDING_HANDLER_BUS_H -#define AZFRAMEWORK_NET_BINDING_HANDLER_BUS_H - -#include -#include -#include -#include -#include - -namespace AzFramework -{ - /** - * The NetBindingSystemComponent notifies net binding handlers of binding events on this bus. - * The net binding component implements this interface and listens on the NetBindingHandlerBus. - */ - class NetBindingHandlerInterface - : public AZ::EBusTraits - { - public: - AZ_RTTI(NetBindingHandlerInterface, "{9F84E9FE-81A0-4105-9C51-6C42C83FECAF}"); - - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - typedef AZ::EntityId BusIdType; - - virtual ~NetBindingHandlerInterface() {} - - /** - * Called to let the entity know that it should bind to the network. - * If bindTo is set, it means that the entity is a proxy and the handler - * should bind the entity to the specified - * replica, otherwise it should bind to a new replica and add it via - * NetBindingSystemBus::AddReplicaMaster. - */ - virtual void BindToNetwork(GridMate::ReplicaPtr bindTo) = 0; - - /** - * Called to let the entity know that it should unbind from the network. - */ - virtual void UnbindFromNetwork() = 0; - - /** - * Returns true if the entity is bound to the network. - */ - virtual bool IsEntityBoundToNetwork() = 0; - - /** - * Returns true if the entity is authoritative on the local node. - */ - virtual bool IsEntityAuthoritative() = 0; - - /** - * Flags the entity as part of the level slice. - */ - virtual void MarkAsLevelSliceEntity() = 0; - - /** - * Set the slice instance id that this entity was spawned by and belongs to. - */ - virtual void SetSliceInstanceId(const AZ::SliceComponent::SliceInstanceId& sliceInstanceId) = 0; - - /** - * Sets the Replica Priority - */ - virtual void SetReplicaPriority(GridMate::ReplicaPriority replicaPriority) = 0; - - /** - * Request entity ownership to a given peer (by default to local peer) - */ - virtual void RequestEntityChangeOwnership(GridMate::PeerId peerId = GridMate::InvalidReplicaPeerId) = 0; - - /** - * Gets the Replica Priority - */ - virtual GridMate::ReplicaPriority GetReplicaPriority() const = 0; - }; - typedef AZ::EBus NetBindingHandlerBus; - - /** - * Set of queries that might want to be made about the networking system - * mainly wraps up EBus calls to keep the implementing code a bit more readable - */ - class NetQuery - { - public: - AZ_RTTI(NetQuery, "{AA4C5699-889D-4A73-9AD2-53EB03D8BB99}"); - - virtual ~NetQuery() = default; - - static AZ_FORCE_INLINE bool IsEntityAuthoritative(AZ::EntityId entityId) - { - bool result = true; - EBUS_EVENT_ID_RESULT(result,entityId,NetBindingHandlerBus,IsEntityAuthoritative); - return result; - } - }; - -} // namespace AzFramework - -#endif // AZFRAMEWORK_NET_BINDING_HANDLER_BUS_H -#pragma once diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemBus.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemBus.h deleted file mode 100644 index c26c6d6350..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemBus.h +++ /dev/null @@ -1,119 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#ifndef AZFRAMEWORK_NET_BINDING_SYSTEM_BUS_H -#define AZFRAMEWORK_NET_BINDING_SYSTEM_BUS_H - -#include -#include -#include -#include -#include -#include - -namespace AZ -{ - namespace IO - { - class GenericStream; - } -} - -namespace AzFramework -{ - const AZ::SliceComponent::SliceInstanceId UnspecifiedSliceInstanceId = AZ::Uuid::CreateNull(); - - /** - */ - typedef AZ::u32 NetBindingContextSequence; - const NetBindingContextSequence UnspecifiedNetBindingContextSequence = 0; - - /** - */ - struct NetBindingSliceContext - { - NetBindingContextSequence m_contextSequence; - AZ::Data::AssetId m_sliceAssetId; - AZ::EntityId m_staticEntityId; - AZ::EntityId m_runtimeEntityId; - /** - * \brief uniquely identifies the slice instance that this entity is being replicated from - */ - AZ::SliceComponent::SliceInstanceId m_sliceInstanceId; - }; - - /** - * The net binding system implements this interface and listens on the NetBindingSystemBus. - * - * Network binding is activated when OnNetworkSessionActivated event is received with the binding session, - * and is deactivated by the OnNetworkSessionDeactivated event. - */ - class NetBindingSystemInterface - : public AZ::EBusTraits - { - public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - virtual ~NetBindingSystemInterface() {} - - //! Returns true if a network session is available and entities should bind themselves to the network. - virtual bool ShouldBindToNetwork() = 0; - - //! Returns the current entity context sequence - virtual NetBindingContextSequence GetCurrentContextSequence() = 0; - - //! Get a level entity's static id. - virtual AZ::EntityId GetStaticIdFromEntityId(AZ::EntityId entity) = 0; - - //! Get a level entity's id based on the static id - virtual AZ::EntityId GetEntityIdFromStaticId(AZ::EntityId staticEntityId) = 0; - - //! Adds a bound replica to the network session as master. - virtual void AddReplicaMaster(AZ::Entity* entity, GridMate::ReplicaPtr replica) = 0; - - //! Spawn and bind an entity from a slice - virtual void SpawnEntityFromSlice(GridMate::ReplicaId bindTo, const NetBindingSliceContext& bindToContext) = 0; - - //! Spawn and bind an entity from stream - virtual void SpawnEntityFromStream(AZ::IO::GenericStream& spawnData, AZ::EntityId useEntityId, GridMate::ReplicaId bindTo, NetBindingContextSequence addToContext) = 0; - - //! De-spawn an entity: deactivates or removes the entity. - /** - * /note @sliceInstanceId is the slice instance that the entity belongs to. If it's a level entity, then this should be AZ::Uuid::CreateNull() - */ - virtual void UnbindGameEntity(AZ::EntityId entity, const AZ::SliceComponent::SliceInstanceId& sliceInstanceId) = 0; - }; - typedef AZ::EBus NetBindingSystemBus; - - class NetBindingSystemEvents - : public AZ::EBusTraits - { - public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - //! Notification that a network session is created - virtual void OnNetworkSessionCreated(GridMate::GridSession* session) { (void)session; } - - //! Notification that a network session is ready - virtual void OnNetworkSessionActivated(GridMate::GridSession* session) { (void)session; } - - //! Notification that a network session is no longer available - virtual void OnNetworkSessionDeactivated(GridMate::GridSession* session) { (void)session; } - }; - typedef AZ::EBus NetBindingSystemEventsBus; -} // namespace AzFramework - -#endif // AZFRAMEWORK_NET_BINDING_SYSTEM_BUS_H diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemComponent.cpp b/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemComponent.cpp deleted file mode 100644 index 85081d1637..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemComponent.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include -#include - -namespace AzFramework -{ - NetBindingSystemComponent::NetBindingSystemComponent() - { - } - - NetBindingSystemComponent::~NetBindingSystemComponent() - { - } - - void NetBindingSystemComponent::Activate() - { - NetBindingSystemImpl::Init(); - } - - void NetBindingSystemComponent::Deactivate() - { - NetBindingSystemImpl::Shutdown(); - } - - void NetBindingSystemComponent::Reflect(AZ::ReflectContext* context) - { - NetBindingSystemImpl::Reflect(context); - - if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ; - - if (AZ::EditContext* editContext = serializeContext->GetEditContext()) - { - editContext->Class( - "NetBinding System", "Performs network binding for game entities.") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Engine") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b)) - ; - } - } - } - - void NetBindingSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("NetBindingSystemService", 0xa0ad6656)); - } - - void NetBindingSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("NetBindingSystemService", 0xa0ad6656)); - } -} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemComponent.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemComponent.h deleted file mode 100644 index 03ff6aa86f..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemComponent.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#ifndef AZFRAMEWORK_NET_BINDING_SYSTEM_COMPONENT_H -#define AZFRAMEWORK_NET_BINDING_SYSTEM_COMPONENT_H - -#include -#include - -namespace AZ -{ - class ReflectContext; -} - -namespace AzFramework -{ - /** - * NetBindingSystemComponent exposes NetBindingSystemImpl as a component - */ - class NetBindingSystemComponent - : public AZ::Component - , public NetBindingSystemImpl - { - friend class NetBindingSystemContextData; - public: - AZ_COMPONENT(NetBindingSystemComponent, "{B96548CC-0866-4BB3-A87B-BF0C4F69E8AC}"); - - NetBindingSystemComponent(); - ~NetBindingSystemComponent() override; - - ////////////////////////////////////////////////////////////////////////// - // Component overrides - void Activate() override; - void Deactivate() override; - static void Reflect(AZ::ReflectContext* context); - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); - ////////////////////////////////////////////////////////////////////////// - }; -} // namespace AzFramework - -#endif // AZFRAMEWORK_NET_BINDING_SYSTEM_COMPONENT_H -#pragma once - diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemImpl.cpp b/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemImpl.cpp deleted file mode 100644 index bb40432ffb..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemImpl.cpp +++ /dev/null @@ -1,957 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -//#define Extra_Tracing -#undef Extra_Tracing - -#if defined(Extra_Tracing) -#include -#define AZ_ExtraTracePrintf(window, ...) AZ::Debug::Trace::Instance().Printf(window, __VA_ARGS__); -#else -#define AZ_ExtraTracePrintf(window, ...) -#endif - -namespace AzFramework -{ - const AZStd::chrono::milliseconds NetBindingSystemImpl::s_sliceBindingTimeout = AZStd::chrono::milliseconds(5000); - - namespace - { - NetBindingHandlerInterface* GetNetBindingHandler(AZ::Entity* entity) - { - NetBindingHandlerInterface* handler = nullptr; - for (AZ::Component* component : entity->GetComponents()) - { - handler = azrtti_cast(component); - if (handler) - { - break; - } - } - return handler; - } - } - - NetBindingSliceInstantiationHandler::~NetBindingSliceInstantiationHandler() - { - // m_bindRequests in NetBindingSystemImpl could be cleaned before slice instantiation finished - if (m_state == State::Spawning) - { - AzFramework::SliceInstantiationResultBus::Handler::BusDisconnect(); - SliceGameEntityOwnershipServiceRequestBus::Broadcast( - &SliceGameEntityOwnershipServiceRequests::CancelDynamicSliceInstantiation, m_ticket - ); - } - - for (AZ::Entity* entity : m_boundEntities) - { - AZ_ExtraTracePrintf("NetBindingSystemImpl", "Cleanup - deleting %llu\n", entity->GetId()); - EBUS_EVENT(GameEntityContextRequestBus, DestroyGameEntity, entity->GetId()); - } - } - - void NetBindingSliceInstantiationHandler::InstantiateEntities() - { - if (m_sliceAssetId.IsValid()) - { - AZ_ExtraTracePrintf("NetBindingSystemImpl", "InstantiateEntities sliceid %s\n", - m_sliceInstanceId.ToString(false, false).c_str()); - - if (AZ::Data::AssetManager::IsReady()) - { - auto remapFunc = [bindingQueue=m_bindingQueue](AZ::EntityId originalId, bool /*isEntityId*/, const AZStd::function&) -> AZ::EntityId - { - auto iter = bindingQueue.find(originalId); - if (iter != bindingQueue.end()) - { - return iter->second.m_desiredRuntimeEntityId; - } - return AZ::Entity::MakeId(); - }; - - AZ::Data::Asset asset = AZ::Data::AssetManager::Instance().FindOrCreateAsset(m_sliceAssetId, AZ::Data::AssetLoadBehavior::Default); - - SliceGameEntityOwnershipServiceRequestBus::BroadcastResult(m_ticket, - &SliceGameEntityOwnershipServiceRequests::InstantiateDynamicSlice, asset, AZ::Transform::Identity(), remapFunc); - SliceInstantiationResultBus::Handler::BusConnect(m_ticket); - - m_state = State::Spawning; - } - else - { - AZ_Warning("NetBindingSystemImpl", false, "AssetManager was not ready when attempting to instantiate sliceid %s\n", - m_sliceInstanceId.ToString(false, false).c_str()); - InstantiationFailureCleanup(); - } - } - } - - bool NetBindingSliceInstantiationHandler::IsInstantiated() const - { - return m_state == State::Spawned; - } - - bool NetBindingSliceInstantiationHandler::IsANewSliceRequest() const - { - return m_state == State::NewRequest && m_sliceAssetId.IsValid() && !m_ticket.IsValid(); - } - - bool NetBindingSliceInstantiationHandler::IsBindingComplete() const - { - return !SliceInstantiationResultBus::Handler::BusIsConnected() && m_bindingQueue.empty(); - } - - bool NetBindingSliceInstantiationHandler::HasActiveEntities() const - { - for (const AZ::Entity* entity : m_boundEntities) - { - if (entity->GetState() == AZ::Entity::State::Active) - { - return true; - } - } - - return false; - } - - void NetBindingSliceInstantiationHandler::OnSlicePreInstantiate(const AZ::Data::AssetId& /*sliceAssetId*/, const AZ::SliceComponent::SliceInstanceAddress& sliceAddress) - { - const auto& entityMapping = sliceAddress.GetInstance()->GetEntityIdToBaseMap(); - - const AZ::SliceComponent::EntityList& sliceEntities = sliceAddress.GetInstance()->GetInstantiated()->m_entities; - for (AZ::Entity *sliceEntity : sliceEntities) - { - auto it = entityMapping.find(sliceEntity->GetId()); - AZ_Assert(it != entityMapping.end(), "Failed to retrieve static entity id for a slice entity!"); - const AZ::EntityId staticEntityId = it->second; - - auto itBindRecord = m_bindingQueue.find(staticEntityId); - if (itBindRecord != m_bindingQueue.end()) - { - AZ_Assert(GetNetBindingHandler(sliceEntity), "Slice entity matched the static id of replicated entity, but there is no valid NetBindingHandlerInterface on it!"); - - itBindRecord->second.m_actualRuntimeEntityId = sliceEntity->GetId(); - } - else if (GetNetBindingHandler(sliceEntity)) - { - AZ_ExtraTracePrintf("NetBindingSystemImpl", "OnSlicePreInstantiate late bindRequest, slice %s, staticid %llu, spawned %llu\n", - m_sliceInstanceId.ToString(false, false).c_str(), - static_cast(staticEntityId), - static_cast(sliceEntity->GetId())); - - BindRequest& request = m_bindingQueue[staticEntityId]; - request.m_desiredRuntimeEntityId = staticEntityId; - request.m_actualRuntimeEntityId = sliceEntity->GetId(); - request.m_requestTime = m_bindTime; - request.m_state = BindRequest::State::PlaceholderBind; - } - - sliceEntity->SetRuntimeActiveByDefault(false); - } - } - - void NetBindingSliceInstantiationHandler::OnSliceInstantiated(const AZ::Data::AssetId& /*sliceAssetId*/, const AZ::SliceComponent::SliceInstanceAddress& sliceAddress) - { - SliceInstantiationResultBus::Handler::BusDisconnect(); - - CloseEntityMap(sliceAddress.GetInstance()->GetEntityIdMap()); - - const AZ::SliceComponent::EntityList sliceEntities = sliceAddress.GetInstance()->GetInstantiated()->m_entities; - for (AZ::Entity *sliceEntity : sliceEntities) - { - auto it = sliceAddress.GetInstance()->GetEntityIdToBaseMap().find(sliceEntity->GetId()); - AZ_Assert(it != sliceAddress.GetInstance()->GetEntityIdToBaseMap().end(), "Failed to retrieve static entity id for a slice entity!"); - const AZ::EntityId staticEntityId = it->second; - const auto itUnbound = m_bindingQueue.find(staticEntityId); - if (itUnbound == m_bindingQueue.end()) - { - /* - * Remove entities that aren't meant to be net bounded. - */ - if (!GetNetBindingHandler(sliceEntity)) - { - EBUS_EVENT(GameEntityContextRequestBus, DestroyGameEntity, sliceEntity->GetId()); - continue; - } - } - - AZ_ExtraTracePrintf("NetBindingSystemImpl", "Adding %llu \n", sliceEntity->GetId()); - m_boundEntities.push_back(sliceEntity); - } - - m_state = State::Spawned; - } - - void NetBindingSliceInstantiationHandler::OnSliceInstantiationFailed(const AZ::Data::AssetId& sliceAssetId) - { - SliceInstantiationResultBus::Handler::BusDisconnect(); - - AZ_UNUSED(sliceAssetId); - AZ_TracePrintf("NetBindingSystemImpl", "Failed to instantiate a slice %s!", sliceAssetId.ToString().c_str()); - - InstantiationFailureCleanup(); - } - - void NetBindingSliceInstantiationHandler::InstantiationFailureCleanup() - { - m_boundEntities.clear(); - m_bindingQueue.clear(); - - // With m_bindingQueue empty, this slice instance handler will be removed on the next tick of NetBindingSystemImpl - m_state = State::Failed; - } - - void NetBindingSliceInstantiationHandler::UseCacheFor(BindRequest& request, const AZ::EntityId& staticEntityId) - { - AZ_Warning("NetBindingSystemImpl", !m_staticToRuntimeEntityMap.empty(), "An empty slice, really? static %llu", - static_cast(staticEntityId)); - - const auto actualRuntimeIter = m_staticToRuntimeEntityMap.find(staticEntityId); - if (actualRuntimeIter == m_staticToRuntimeEntityMap.end()) - { - AZ_Warning("NetBindingSystemImpl", false, "Wrong mapping, expected cache to have entity %llu for slice %s \n", - static_cast(staticEntityId), - m_sliceInstanceId.ToString(false, false).c_str()); - -#if defined(Extra_Tracing) - for (auto& item: m_staticToRuntimeEntityMap) - { - AZ_UNUSED(item); - AZ_ExtraTracePrintf("NetBindingSystemImpl", "mapping had %llu to %llu \n", - static_cast(item.first), - static_cast(item.second)); - } -#endif - - return; - } - - const AZ::EntityId actualRuntimeEntityId = actualRuntimeIter->second; - const auto itCache = AZStd::find_if(m_boundEntities.begin(), m_boundEntities.end(), [&actualRuntimeEntityId](AZ::Entity* entity) { - return entity->GetId() == actualRuntimeEntityId; - }); - - if (itCache != m_boundEntities.end()) - { - AZ_ExtraTracePrintf("NetBindingSystemImpl", "OnSlicePreInstantiate late bindRequest, slice %s, staticid %llu, spawned %llu\n", - m_sliceInstanceId.ToString(false, false).c_str(), - static_cast(staticEntityId), - static_cast(actualRuntimeEntityId)); - - request.m_actualRuntimeEntityId = actualRuntimeEntityId; - request.m_desiredRuntimeEntityId = staticEntityId; - } - else - { - AZ_Warning("NetBindingSystemImpl", false, "Expected cache to have entity %llu for slice %s \n", - static_cast(request.m_desiredRuntimeEntityId), - m_sliceInstanceId.ToString(false, false).c_str()); - } - } - - void NetBindingSliceInstantiationHandler::CloseEntityMap( - const AZ::SliceComponent::EntityIdToEntityIdMap& staticToRuntimeMap) - { - m_staticToRuntimeEntityMap.clear(); - for (auto& item : staticToRuntimeMap) - { - m_staticToRuntimeEntityMap[item.first] = item.second; - } - } - - NetBindingSystemContextData::NetBindingSystemContextData() - : m_bindingContextSequence("BindingContextSequence", UnspecifiedNetBindingContextSequence) - { - } - - void NetBindingSystemContextData::OnReplicaActivate(const GridMate::ReplicaContext& rc) - { - (void)rc; - NetBindingSystemImpl* system = static_cast(NetBindingSystemBus::FindFirstHandler()); - AZ_Assert(system, "NetBindingSystemContextData requires a valid NetBindingSystemComponent to function!"); - system->OnContextDataActivated(this); - } - - void NetBindingSystemContextData::OnReplicaDeactivate(const GridMate::ReplicaContext& rc) - { - (void)rc; - NetBindingSystemImpl* system = static_cast(NetBindingSystemBus::FindFirstHandler()); - if (system) - { - system->OnContextDataDeactivated(this); - } - } - - - NetBindingSystemImpl::NetBindingSystemImpl() - : m_bindingSession(nullptr) - , m_currentBindingContextSequence(UnspecifiedNetBindingContextSequence) - , m_isAuthoritativeRootSliceLoad(false) - , m_overrideRootSliceLoadAuthoritative(false) - { - } - - NetBindingSystemImpl::~NetBindingSystemImpl() - { - } - - void NetBindingSystemImpl::Init() - { - NetBindingSystemBus::Handler::BusConnect(); - NetBindingSystemEventsBus::Handler::BusConnect(); - - // Start listening for game context events - EntityContextId gameContextId = EntityContextId::CreateNull(); - EBUS_EVENT_RESULT(gameContextId, GameEntityContextRequestBus, GetGameEntityContextId); - if (!gameContextId.IsNull()) - { - EntityContextEventBus::Handler::BusConnect(gameContextId); - } - } - - void NetBindingSystemImpl::Shutdown() - { - EntityContextEventBus::Handler::BusDisconnect(); - NetBindingSystemEventsBus::Handler::BusDisconnect(); - NetBindingSystemBus::Handler::BusDisconnect(); - - m_contextData.reset(); - } - - bool NetBindingSystemImpl::ShouldBindToNetwork() - { - return m_contextData && m_contextData->ShouldBindToNetwork(); - } - - NetBindingContextSequence NetBindingSystemImpl::GetCurrentContextSequence() - { - return m_currentBindingContextSequence; - } - - bool NetBindingSystemImpl::ReadyToAddReplica() const - { - return m_bindingSession && m_bindingSession->GetReplicaMgr(); - } - - void NetBindingSystemImpl::AddReplicaMaster(AZ::Entity* entity, GridMate::ReplicaPtr replica) - { - bool addReplica = ShouldBindToNetwork(); - AZ_Assert(addReplica, "Entities shouldn't be binding to the network right now!"); - if (addReplica) - { - if (ReadyToAddReplica()) - { - m_bindingSession->GetReplicaMgr()->AddMaster(replica); - } - else - { - m_addMasterRequests.push_back(AZStd::make_pair(entity->GetId(), replica)); - } - } - } - - - AZ::EntityId NetBindingSystemImpl::GetStaticIdFromEntityId(AZ::EntityId entityId) - { - AZ::EntityId staticId = entityId; // if no static id mapping is found, then the static id is the same as the runtime id - - // If entity came from a slice, try to get the mapping from it - AZ::SliceComponent::SliceInstanceAddress sliceInfo; - SliceEntityRequestBus::EventResult(sliceInfo, entityId, &SliceEntityRequestBus::Events::GetOwningSlice); - AZ::SliceComponent::SliceInstance* sliceInstance = sliceInfo.GetInstance(); - if (sliceInstance) - { - const auto it = sliceInstance->GetEntityIdToBaseMap().find(entityId); - if (it != sliceInstance->GetEntityIdToBaseMap().end()) - { - staticId = it->second; - } - } - - return staticId; - } - - AZ::EntityId NetBindingSystemImpl::GetEntityIdFromStaticId(AZ::EntityId staticEntityId) - { - AZ::EntityId runtimeId = AZ::EntityId(); - - // if we can find an entity with the static id, then the static id is the same as the runtime id. - AZ::Entity* entity = nullptr; - EBUS_EVENT(AZ::ComponentApplicationBus, FindEntity, staticEntityId); - if (entity) - { - runtimeId = staticEntityId; - } - - return runtimeId; - } - - void NetBindingSystemImpl::SpawnEntityFromSlice(GridMate::ReplicaId bindTo, const NetBindingSliceContext& bindToContext) - { - auto& sliceQueue = m_bindRequests[bindToContext.m_contextSequence]; - - const bool slicePresent = sliceQueue.find(bindToContext.m_sliceInstanceId) != sliceQueue.end(); - - auto iterSliceRequest = sliceQueue.insert_key(bindToContext.m_sliceInstanceId); - NetBindingSliceInstantiationHandler& sliceHandler = iterSliceRequest.first->second; - sliceHandler.m_sliceAssetId = bindToContext.m_sliceAssetId; - sliceHandler.m_sliceInstanceId = bindToContext.m_sliceInstanceId; - - BindRequest& request = sliceHandler.m_bindingQueue[bindToContext.m_staticEntityId]; - - if (!slicePresent) - { - request.m_state = BindRequest::State::FirstBindInSlice; - } - else - { - request.m_state = BindRequest::State::LateBind; - } - - AZ_ExtraTracePrintf("NetBindingSystemImpl", "SpawnEntityFromSlice late, slice %s, static %llu, desired %llu, state %d \n", - bindToContext.m_sliceInstanceId.ToString(false, false).c_str(), - static_cast(bindToContext.m_staticEntityId), - static_cast(bindToContext.m_runtimeEntityId), - request.m_state); - - sliceHandler.m_bindTime = Now(); - - request.m_bindTo = bindTo; - request.m_desiredRuntimeEntityId = bindToContext.m_runtimeEntityId; - request.m_requestTime = Now(); - - if (sliceHandler.IsInstantiated()) - { - // The slice has been instantiated now, thus we have to use the cache to populated the request with the entity. - sliceHandler.UseCacheFor(request, bindToContext.m_staticEntityId); - } - } - - void NetBindingSystemImpl::SpawnEntityFromStream(AZ::IO::GenericStream& spawnData, AZ::EntityId useEntityId, GridMate::ReplicaId bindTo, NetBindingContextSequence addToContext) - { - auto& requestQueue = m_spawnRequests[addToContext]; - requestQueue.push_back(); - SpawnRequest& request = requestQueue.back(); - request.m_bindTo = bindTo; - request.m_useEntityId = useEntityId; - request.m_spawnDataBuffer.resize_no_construct(spawnData.GetLength()); - spawnData.Read(request.m_spawnDataBuffer.size(), request.m_spawnDataBuffer.data()); - } - - void NetBindingSystemImpl::OnNetworkSessionActivated(GridMate::GridSession* session) - { - AZ_Assert(!m_bindingSession, "We already have an active session! Was the previous session deactivated?"); - if (!m_bindingSession) - { - m_bindingSession = session; - - if (m_bindingSession->IsHost()) - { - GridMate::Replica* replica = CreateSystemReplica(); - session->GetReplicaMgr()->AddMaster(replica); - } - } - } - - void NetBindingSystemImpl::OnNetworkSessionDeactivated(GridMate::GridSession* session) - { - if (session == m_bindingSession) - { - m_bindingSession = nullptr; - } - } - - void NetBindingSystemImpl::UnbindGameEntity(AZ::EntityId entityId, const AZ::SliceComponent::SliceInstanceId& sliceInstanceId) - { - if (!m_bindRequests.empty()) - { - const auto itCurrentContextQueue = m_bindRequests.lower_bound(GetCurrentContextSequence()); - - if (itCurrentContextQueue != m_bindRequests.end()) - { - if (itCurrentContextQueue->first == GetCurrentContextSequence()) - { - const auto itSliceHandler = itCurrentContextQueue->second.find(sliceInstanceId); - if (itSliceHandler != itCurrentContextQueue->second.end()) - { - NetBindingSliceInstantiationHandler& sliceHandler = itSliceHandler->second; - for (AZ::Entity* entity : sliceHandler.m_boundEntities) - { - if (entity->GetId() == entityId) - { - entity->Deactivate(); - return; - } - } - - // clean any relevant bind requests as well - const auto bindQueueItem = sliceHandler.m_bindingQueue.find(entityId); - if (bindQueueItem != sliceHandler.m_bindingQueue.end()) - { - sliceHandler.m_bindingQueue.erase(bindQueueItem); - return; - } - } - } - } - } - - AZ_ExtraTracePrintf("NetBindingSystemImpl", "Not in cache - deleting %llu \n", entityId); - EBUS_EVENT(GameEntityContextRequestBus, DestroyGameEntity, entityId); - } - - void NetBindingSystemImpl::OnEntityContextReset() - { - const bool isContextOwner = m_contextData && m_contextData->IsMaster() && m_bindingSession && m_bindingSession->IsHost(); - if (isContextOwner) - { - ++m_currentBindingContextSequence; - NetBindingSystemContextData* context = static_cast(m_contextData.get()); - context->m_bindingContextSequence.Set(m_currentBindingContextSequence); - } - } - - bool NetBindingSystemImpl::IsAuthoritateLoad() const - { - if (m_overrideRootSliceLoadAuthoritative) - { - return m_isAuthoritativeRootSliceLoad; - } - - return !m_bindingSession || m_bindingSession->IsHost(); - } - - void NetBindingSystemImpl::UpdateClock(float deltaTime) - { - m_currentTime += AZStd::chrono::milliseconds(aznumeric_cast(deltaTime * AZStd::milli::den)); - } - - AZStd::chrono::system_clock::time_point NetBindingSystemImpl::Now() const - { - return m_currentTime; - } - - void NetBindingSystemImpl::OnEntityContextLoadedFromStream(const AZ::SliceComponent::EntityList& contextEntities) - { - const bool isAuthoritativeLoad = IsAuthoritateLoad(); - - for (AZ::Entity* entity : contextEntities) - { - NetBindingHandlerInterface* netBinder = GetNetBindingHandler(entity); - if (netBinder) - { - netBinder->MarkAsLevelSliceEntity(); - } - - if (!isAuthoritativeLoad && netBinder) - { - entity->SetRuntimeActiveByDefault(false); - - auto& slicesQueue = m_bindRequests[GetCurrentContextSequence()]; - auto& sliceHandler = slicesQueue[UnspecifiedSliceInstanceId]; - BindRequest& request = sliceHandler.m_bindingQueue[entity->GetId()]; - request.m_actualRuntimeEntityId = entity->GetId(); - request.m_requestTime = Now(); - } - } - } - - void NetBindingSystemImpl::OnTick(float deltaTime, AZ::ScriptTimePoint time) - { - AZ_UNUSED(time); - - UpdateClock(deltaTime); - UpdateContextSequence(); - -#if defined(Extra_Tracing) - static AZ::Debug::Timer sTimer; - sTimer.Stamp(); -#endif - ProcessBindRequests(); -#if defined(Extra_Tracing) - const float seconds = sTimer.StampAndGetDeltaTimeInSeconds(); - - static float debugPeriod = 2.f; - static float accumulator = 0; - static float totalTimeTaken = 0; - static AZ::u32 totalTicks = 0; - accumulator += deltaTime; - totalTimeTaken += seconds; - totalTicks++; - - if (accumulator >= debugPeriod) - { - AZ_ExtraTracePrintf("NetBindingSystemImpl", "ProcessBindRequests() took %f sec \n", totalTicks > 0 ? totalTimeTaken / totalTicks : 0); - - accumulator -= debugPeriod; - totalTimeTaken = 0; - totalTicks = 0; - } -#endif - - ProcessSpawnRequests(); - } - - int NetBindingSystemImpl::GetTickOrder() - { - return AZ::TICK_PLACEMENT + 1; - } - - void NetBindingSystemImpl::UpdateContextSequence() - { - NetBindingSystemContextData* contextChunk = static_cast(m_contextData.get()); - if (m_currentBindingContextSequence != contextChunk->m_bindingContextSequence.Get()) - { - m_currentBindingContextSequence = contextChunk->m_bindingContextSequence.Get(); - } - } - - GridMate::Replica* NetBindingSystemImpl::CreateSystemReplica() - { - AZ_Assert(m_bindingSession->IsHost(), "CreateSystemReplica should only be called on the host!"); - GridMate::Replica* replica = GridMate::Replica::CreateReplica("NetBindingSystem"); - NetBindingSystemContextData* contextChunk = GridMate::CreateReplicaChunk(); - replica->AttachReplicaChunk(contextChunk); - - return replica; - } - - void NetBindingSystemImpl::OnContextDataActivated(GridMate::ReplicaChunkPtr contextData) - { - AZ_Assert(!m_contextData, "We already have our context!"); - m_contextData = contextData; - - // Make sure we always have the unspecified entry. This should also - // be the lower_bound in the map and assuming it is always there - // makes things simpler. - m_spawnRequests.insert(UnspecifiedNetBindingContextSequence); - m_bindRequests.insert(UnspecifiedNetBindingContextSequence); - - if (contextData->IsMaster()) - { - ++m_currentBindingContextSequence; - static_cast(contextData.get())->m_bindingContextSequence.Set(m_currentBindingContextSequence); - } - else - { - UpdateContextSequence(); - } - AZ::TickBus::Handler::BusConnect(); - EBUS_EVENT(AzFramework::NetBindingHandlerBus, BindToNetwork, nullptr); - } - - void NetBindingSystemImpl::OnContextDataDeactivated(GridMate::ReplicaChunkPtr contextData) - { - AZ_Assert(m_contextData == contextData, "This is not our context!"); - m_contextData = nullptr; - - AZ::TickBus::Handler::BusDisconnect(); - m_spawnRequests.clear(); - m_bindRequests.clear(); - m_addMasterRequests.clear(); - m_currentBindingContextSequence = UnspecifiedNetBindingContextSequence; - } - - void NetBindingSystemImpl::ProcessSpawnRequests() - { - AZ::SerializeContext* serializeContext = nullptr; - EBUS_EVENT_RESULT(serializeContext, AZ::ComponentApplicationBus, GetSerializeContext); - AZ_Assert(serializeContext, "NetBindingSystemComponent requires a valid SerializeContext in order to spawn entities!"); - const auto spawnFunc = [=](SpawnRequest& spawnData, AZ::EntityId useEntityId, bool addToContext) - { - AZ::Entity* proxyEntity = nullptr; - AZ::ObjectStream::ClassReadyCB readyCB([&](void* classPtr, const AZ::Uuid& classId, AZ::SerializeContext* sc) - { - (void)classId; - (void)sc; - proxyEntity = static_cast(classPtr); - }); - AZ::IO::ByteContainerStream > stream(&spawnData.m_spawnDataBuffer); - AZ::ObjectStream::LoadBlocking(&stream, *serializeContext, readyCB); - - AZ_Warning("NetBindingSystemImpl", proxyEntity, "Could not spawn entity from stream %llu", useEntityId); - if (proxyEntity) - { - proxyEntity->SetId(useEntityId); - if (!BindAndActivate(proxyEntity, spawnData.m_bindTo, addToContext, AZ::Uuid::CreateNull())) - { - AzFramework::EntityContextId contextId = AzFramework::EntityContextId::CreateNull(); - AzFramework::EntityIdContextQueryBus::EventResult( - contextId, proxyEntity->GetId(), &AzFramework::EntityIdContextQueryBus::Events::GetOwningContextId); - - if (contextId.IsNull()) - { - delete proxyEntity; - } - else - { - GameEntityContextRequestBus::Broadcast( - &GameEntityContextRequestBus::Events::DestroyGameEntity, proxyEntity->GetId()); - } - - } - } - }; - - if (!m_spawnRequests.empty()) - { - SpawnRequestContextContainerType::iterator itContextQueue = m_spawnRequests.lower_bound(UnspecifiedNetBindingContextSequence); - AZ_Assert(itContextQueue->first == UnspecifiedNetBindingContextSequence, "We should always have the unspecified (aka global entity) spawn queue!");// - - // Process requests for global entities (not part of any context) - SpawnRequestContainerType& globalQueue = itContextQueue->second; - for (SpawnRequest& request : globalQueue) - { - spawnFunc(request, request.m_useEntityId, false); - } - globalQueue.clear(); - - if (GetCurrentContextSequence() != UnspecifiedNetBindingContextSequence) - { - ++itContextQueue; - - // Clear any obsolete requests (any contexts below the current context sequence) - SpawnRequestContextContainerType::iterator itCurrentContextQueue = m_spawnRequests.lower_bound(GetCurrentContextSequence()); - if (itContextQueue != itCurrentContextQueue) - { - m_spawnRequests.erase(itContextQueue, itCurrentContextQueue); - } - - // Spawn any entities for the current context - if (itCurrentContextQueue != m_spawnRequests.end()) - { - if (itCurrentContextQueue->first == GetCurrentContextSequence()) - { - for (SpawnRequest& request : itCurrentContextQueue->second) - { - spawnFunc(request, request.m_useEntityId, true); - } - itCurrentContextQueue->second.clear(); - } - } - } - } - } - - void NetBindingSystemImpl::ProcessBindRequests() - { - AZ::SerializeContext* serializeContext = nullptr; - EBUS_EVENT_RESULT(serializeContext, AZ::ComponentApplicationBus, GetSerializeContext); - AZ_Assert(serializeContext, "NetBindingSystemComponent requires a valid SerializeContext in order to spawn entities!"); - - if (!m_bindRequests.empty()) - { - BindRequestContextContainerType::iterator itContextQueue = m_bindRequests.lower_bound(UnspecifiedNetBindingContextSequence); - AZ_Assert(itContextQueue->first == UnspecifiedNetBindingContextSequence, "We should always have the unspecified/global spawn queue!"); - - if (GetCurrentContextSequence() != UnspecifiedNetBindingContextSequence) - { - ++itContextQueue; - - // Clear any obsolete requests (any contexts below the current context sequence) - BindRequestContextContainerType::iterator itCurrentContextQueue = m_bindRequests.lower_bound(GetCurrentContextSequence()); - if (itContextQueue != itCurrentContextQueue) - { - m_bindRequests.erase(itContextQueue, itCurrentContextQueue); - } - - // Spawn any proxy entities for the current context - if (itCurrentContextQueue != m_bindRequests.end()) - { - if (itCurrentContextQueue->first == GetCurrentContextSequence()) - { - for (auto itSliceHandler = itCurrentContextQueue->second.begin(); itSliceHandler != itCurrentContextQueue->second.end(); /*++itSliceHandler*/) - { - NetBindingSliceInstantiationHandler& sliceHandler = itSliceHandler->second; - - // If this is a new slice request, instantiate it - if (sliceHandler.IsANewSliceRequest()) - { - sliceHandler.InstantiateEntities(); - } - /* - * A slice instance is kept alive for caching purposes. As we check each bind request for its readiness, - * we are also going to check if the slice instance itself has become inactive and needs to be removed. - */ - bool mightBeInactiveSlice = true; - if (sliceHandler.m_bindingQueue.empty() && sliceHandler.HasActiveEntities()) - { - // The slice instance is spawned and full bound. - mightBeInactiveSlice = false; - } - - // If the entity is ready to be bound to the network, bind it. - // NOTE: It is possible for entities spawned from a slice containing multiple entities with net binding - // to never receive their replica counterpart, either because the replica was destroyed, or was interest - // filtered. We don't have a very good pipeline to prevent these slices from being authored, so if we - // encounter them, we will delete them after a timeout. - for (auto itRequest = sliceHandler.m_bindingQueue.begin(); itRequest != sliceHandler.m_bindingQueue.end(); /*++itRequest*/) - { - BindRequest& request = itRequest->second; - - if (request.m_bindTo != GridMate::InvalidReplicaId && request.m_actualRuntimeEntityId.IsValid()) - { - AZ::Entity* proxyEntity = nullptr; - EBUS_EVENT_RESULT(proxyEntity, AZ::ComponentApplicationBus, FindEntity, request.m_actualRuntimeEntityId); - AZ_Warning("NetBindingSystemImpl", proxyEntity, "Could not find entity for binding %llu", request.m_actualRuntimeEntityId); - if (proxyEntity) - { - AZ_ExtraTracePrintf("NetBindingSystemImpl", "BindAndActivate desired id %llu, actual %llu, slice %s \n", - static_cast(request.m_desiredRuntimeEntityId), - static_cast(request.m_actualRuntimeEntityId), - sliceHandler.m_sliceInstanceId.ToString(false, false).c_str()); - - BindAndActivate(proxyEntity, request.m_bindTo, false, sliceHandler.m_sliceInstanceId); - } - itRequest = sliceHandler.m_bindingQueue.erase(itRequest); - - // The slice instance is not fully bound. It may remain for a while for caching purposes. - mightBeInactiveSlice = false; - } - else if (AZStd::chrono::milliseconds(Now() - request.m_requestTime) > s_sliceBindingTimeout) - { - // If the real request never showed up, then no need for a trace - if (request.m_state == BindRequest::State::FirstBindInSlice || - request.m_state == BindRequest::State::LateBind) - { - AZ_TracePrintf("NetBindingSystemImpl", "Entity with static id [%llu], slice [%s]\n is still unbound after %llu ms. Discarding unbound entity.\n", - static_cast(request.m_actualRuntimeEntityId), - sliceHandler.m_sliceInstanceId.ToString(false, false).c_str(), - s_sliceBindingTimeout.count()); - } - - switch (sliceHandler.m_state) - { - case NetBindingSliceInstantiationHandler::State::NewRequest: - case NetBindingSliceInstantiationHandler::State::Spawning: - // The slice instance isn't ready yet. We will wait to consider the timing logic until it is ready. - mightBeInactiveSlice = false; - break; - case NetBindingSliceInstantiationHandler::State::Spawned: - case NetBindingSliceInstantiationHandler::State::Failed: - // Now the timing logic for removing the slice instance becomes valid. - mightBeInactiveSlice = true; - break; - default: - break; - } - - ++itRequest; - } - else - { - mightBeInactiveSlice = false; - ++itRequest; - } - } - - if (mightBeInactiveSlice && !sliceHandler.HasActiveEntities()) - { - AZ_ExtraTracePrintf("NetBindingSystemImpl", "Removing inactive slice %s \n", - sliceHandler.m_sliceInstanceId.ToString(false, false).c_str()); - - itSliceHandler = itCurrentContextQueue->second.erase(itSliceHandler); - } - else - { - ++itSliceHandler; - } - } - } - } - } - } - - // Spawn replicas for any local entities that are still valid - for (auto& addRequest : m_addMasterRequests) - { - AZ::Entity* entity = nullptr; - EBUS_EVENT_RESULT(entity, AZ::ComponentApplicationBus, FindEntity, addRequest.first); - if (entity) - { - m_bindingSession->GetReplicaMgr()->AddMaster(addRequest.second); - } - } - m_addMasterRequests.clear(); - } - - bool NetBindingSystemImpl::BindAndActivate(AZ::Entity* entity, GridMate::ReplicaId replicaId, bool addToContext, - const AZ::SliceComponent::SliceInstanceId& sliceInstanceId) - { - bool success = false; - - if ( ShouldBindToNetwork() ) - { - const GridMate::ReplicaPtr bindTo = m_contextData->GetReplicaManager()->FindReplica(replicaId); - if (bindTo) - { - if (addToContext) - { - EBUS_EVENT(GameEntityContextRequestBus, AddGameEntity, entity); - } - - if (entity->GetState() == AZ::Entity::State::Constructed) - { - entity->Init(); - } - - NetBindingHandlerInterface* binding = GetNetBindingHandler(entity); - AZ_Warning("NetBindingSystemImpl", binding, "Can't find NetBindingComponent on entity %llu (%s)!", static_cast(entity->GetId()), entity->GetName().c_str()); - if (binding) - { - binding->BindToNetwork(bindTo); - binding->SetSliceInstanceId(sliceInstanceId); - - entity->Activate(); - success = true; - } - } - else - { - // NOTE: It is possible for entities spawned from a slice containing multiple entities with net binding - // to never receive their replica counterpart, either because the replica was destroyed, or was interest - // filtered. - AZ_ExtraTracePrintf("NetBindingSystemImpl", "Failed to bind entity %llu - could not find replica %u", entity->GetId(), replicaId); - } - } - - return success; - } - - void NetBindingSystemImpl::Reflect(AZ::ReflectContext* context) - { - if (context) - { - // We need to register the chunk type, and this would be a good time to do so. - if (!GridMate::ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(GridMate::ReplicaChunkClassId(NetBindingSystemContextData::GetChunkName()))) - { - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - } - } - } -} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemImpl.h b/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemImpl.h deleted file mode 100644 index 543d9544ce..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetBindingSystemImpl.h +++ /dev/null @@ -1,311 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -namespace AzFramework -{ - /** - * \brief Represents a request to bind a particular replica to an entity - */ - class BindRequest - { - public: - BindRequest() - : m_bindTo(GridMate::InvalidReplicaId) - , m_state(State::None) - { - } - - GridMate::ReplicaId m_bindTo; - AZ::EntityId m_desiredRuntimeEntityId; - AZ::EntityId m_actualRuntimeEntityId; - AZStd::chrono::system_clock::time_point m_requestTime; - - /** - * \brief Represents the state of this bind request and it's relation to the slice instantiation process - */ - enum class State : AZ::u8 - { - None, - /** - * \brief This is the first request that led to instantiating a slice - */ - FirstBindInSlice, - /** - * \brief The request is a placeholder in case a real bind request arrives later. - * Some part of the slice may never be bound (e.g. if a replica is omitted by Interest Manager) - */ - PlaceholderBind, - /** - * \brief The real request did arrive to replace a placeholder request. - */ - LateBind, - }; - - State m_state; - }; - - typedef AZStd::unordered_map BindRequestContainerType; - - /** - * \brief Represents a slice instance being instantiated and bound to replicas - * \note It's possible that only some of the entities are activated and bound to replicas. - */ - class NetBindingSliceInstantiationHandler - : public SliceInstantiationResultBus::Handler - { - public: - ~NetBindingSliceInstantiationHandler() override; - - void InstantiateEntities(); - bool IsInstantiated() const; - bool IsANewSliceRequest() const; - bool IsBindingComplete() const; - - /** - * \note Returns false if there are no entities in the slice or the slice instance isn't ready yet. - * \return true if any of the entities from the slice are active - */ - bool HasActiveEntities() const; - - ////////////////////////////////////////////////////////////////////////// - // SliceInstantiationResultBus - void OnSlicePreInstantiate(const AZ::Data::AssetId& sliceAssetId, const AZ::SliceComponent::SliceInstanceAddress& sliceAddress) override; - void OnSliceInstantiated(const AZ::Data::AssetId& sliceAssetId, const AZ::SliceComponent::SliceInstanceAddress& sliceAddress) override; - void OnSliceInstantiationFailed(const AZ::Data::AssetId& sliceAssetId) override; - ////////////////////////////////////////////////////////////////////////// - - void InstantiationFailureCleanup(); - void UseCacheFor(BindRequest& request, const AZ::EntityId& staticEntityId); - void CloseEntityMap(const AZ::SliceComponent::EntityIdToEntityIdMap& staticToRuntimeMap); - - AZ::Data::AssetId m_sliceAssetId; - BindRequestContainerType m_bindingQueue; - SliceInstantiationTicket m_ticket; - - /** - * \breif a cache of entities that might be networked at some point - * \note they might be bound and unbound if their replicas leave and come back in the view - */ - AZStd::vector m_boundEntities; - - /** - * \brief identifies which slice instance the instantiation will be performed for - */ - AZ::SliceComponent::SliceInstanceId m_sliceInstanceId; - /** - * \brief when was the request to spawn a slice and bind it made - */ - AZStd::chrono::system_clock::time_point m_bindTime; - - AZ::SliceComponent::EntityIdToEntityIdMap m_staticToRuntimeEntityMap; - - /** - * \brief The state of the slice instance. - */ - enum class State - { - /** - * \brief Has not started instantiating the slice instance. - */ - NewRequest, - /** - * \brief Waiting on the slice to spawn. - */ - Spawning, - /** - * \brief Successfully spawned the slice assets. - */ - Spawned, - /** - * \brief Failed to spawn the slice. - */ - Failed - }; - - State m_state = State::NewRequest; - }; - - /** - * NetBindingSystemImpl works in conjunction with NetBindingComponent and - * NetBindingComponentChunk to perform network binding for game entities. - * - * It is responsible for adding entity replicas to the network on the master side - * and servicing entity spawn requests from the network on the proxy side, as - * well as detecting network availability and triggering network binding/unbinding. - * - * The system is first activated on the host side when OnNetworkSessionActivated event - * is received, and NetBindingSystemContextData is created. - * The system becomes fully operational when the NetBindingSystemContextData is activated - * and bound to the system, and remains operational as long as the NetBindingSystemContextData - * remains valid. - * - * Level switching is tracked by a monotonically increasing context sequence number controlled - * by the host. Spawn and bind operations are deferred until the correct sequence number - * is reached. Spawning is always performed from the game thread. - */ - class NetBindingSystemImpl - : public NetBindingSystemBus::Handler - , public NetBindingSystemEventsBus::Handler - , public EntityContextEventBus::Handler - , public AZ::TickBus::Handler - { - friend class NetBindingSystemContextData; - - public: - NetBindingSystemImpl(); - ~NetBindingSystemImpl() override; - - static void Reflect(AZ::ReflectContext* context); - - virtual void Init(); - virtual void Shutdown(); - - static const AZStd::chrono::milliseconds s_sliceBindingTimeout; - - ////////////////////////////////////////////////////////////////////////// - // NetBindingSystemBus - bool ShouldBindToNetwork() override; - NetBindingContextSequence GetCurrentContextSequence() override; - void AddReplicaMaster(AZ::Entity* entity, GridMate::ReplicaPtr replica) override; - AZ::EntityId GetStaticIdFromEntityId(AZ::EntityId entity) override; - AZ::EntityId GetEntityIdFromStaticId(AZ::EntityId staticEntityId) override; - void SpawnEntityFromSlice(GridMate::ReplicaId bindTo, const NetBindingSliceContext& bindToContext) override; - void SpawnEntityFromStream(AZ::IO::GenericStream& spawnData, AZ::EntityId useEntityId, GridMate::ReplicaId bindTo, NetBindingContextSequence addToContext) override; - void OnNetworkSessionActivated(GridMate::GridSession* session) override; - void OnNetworkSessionDeactivated(GridMate::GridSession* session) override; - void UnbindGameEntity(AZ::EntityId entity, const AZ::SliceComponent::SliceInstanceId& sliceInstanceId) override; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // EntityContextEventBus::Handler - void OnEntityContextReset() override; - void OnEntityContextLoadedFromStream(const AZ::SliceComponent::EntityList& contextEntities) override; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // TickBus::Handler - void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - int GetTickOrder() override; - ////////////////////////////////////////////////////////////////////////// - - protected: - //! Called by the NetBindingContext chunk when it is activated - void OnContextDataActivated(GridMate::ReplicaChunkPtr contextData); - - //! Called by the NetBindingContext chunk when it is deactivated - void OnContextDataDeactivated(GridMate::ReplicaChunkPtr contextData); - - //! Update the current binding context sequence - virtual void UpdateContextSequence(); - - //! Process pending spawn requests - virtual void ProcessSpawnRequests(); - - //! Process pending bind requests - virtual void ProcessBindRequests(); - - //! Performs final stage of entity spawning process - virtual bool BindAndActivate(AZ::Entity* entity, GridMate::ReplicaId replicaId, bool addToContext, const AZ::SliceComponent::SliceInstanceId& sliceInstanceId); - - //! Called on the host to spawn the net binding system replica - virtual GridMate::Replica* CreateSystemReplica(); - - AZ_FORCE_INLINE bool ReadyToAddReplica() const; - - class SpawnRequest - { - public: - GridMate::ReplicaId m_bindTo; - AZ::EntityId m_useEntityId; - AZStd::vector m_spawnDataBuffer; - }; - - typedef AZStd::list SpawnRequestContainerType; - typedef AZStd::map SpawnRequestContextContainerType; - - typedef AZStd::unordered_map SliceRequestContainerType; - typedef AZStd::map BindRequestContextContainerType; - - GridMate::GridSession* m_bindingSession; - GridMate::ReplicaChunkPtr m_contextData; - NetBindingContextSequence m_currentBindingContextSequence; - SpawnRequestContextContainerType m_spawnRequests; - BindRequestContextContainerType m_bindRequests; - AZStd::list> m_addMasterRequests; - - /** - * \brief override how root slice entities' replicas should be loaded - * - * We occasionally get GameContextBridge replica (that tells us what level to load) before we get - * a replica that tells us that we are connecting to a network sessions, thus we may not figure out in time if we - * need to load the root slice entities with NetBindingComponent as master replicas or proxy replicas. - * This is a fix until proper order is established. - * - * \param isAuthoritative true if root slice entities with NetBindingComponents to be loaded authoritatively - */ - void OverrideRootSliceLoadMode(bool isAuthoritative) - { - m_isAuthoritativeRootSliceLoad = isAuthoritative; - m_overrideRootSliceLoadAuthoritative = true; - } - - private: - /** - * \brief True if the root slice is to be loaded authoritatively - */ - bool m_isAuthoritativeRootSliceLoad; - /** - * \brief True if root slice loading mode was overriden, otherwise the mode would be determined via m_bindingSession - */ - bool m_overrideRootSliceLoadAuthoritative; - /** - * \brief A helper method to figure the mode of loading root slice entities' replicas - * \return True if the root slice entities is to be loaded authoritatively - */ - bool IsAuthoritateLoad() const; - - void UpdateClock(float deltaTime); - AZStd::chrono::system_clock::time_point Now() const; - - AZStd::chrono::system_clock::time_point m_currentTime; - }; - - class NetBindingSystemContextData - : public GridMate::ReplicaChunk - { - public: - AZ_CLASS_ALLOCATOR(NetBindingSystemContextData, AZ::SystemAllocator, 0); - - static const char* GetChunkName() { return "NetBindingSystemContextData"; } - - NetBindingSystemContextData(); - - bool IsReplicaMigratable() override { return true; } - bool IsBroadcast() override { return true; } - - void OnReplicaActivate(const GridMate::ReplicaContext& rc) override; - - void OnReplicaDeactivate(const GridMate::ReplicaContext& rc) override; - - GridMate::DataSet m_bindingContextSequence; - }; -} // namespace AzFramework - diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetSystemBus.h b/Code/Framework/AzFramework/AzFramework/Network/NetSystemBus.h deleted file mode 100644 index 788eacf8b5..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetSystemBus.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include - -namespace AzFramework -{ - class NetworkContext; - - /** - * The NetSystemRequestBus services requests for global networking systems in AzFramework - */ - class NetSystemRequests - : public AZ::EBusTraits - { - public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - NetSystemRequests() = default; - virtual ~NetSystemRequests() = default; - - virtual NetworkContext* GetNetworkContext() = 0; - }; - - using NetSystemRequestBus = AZ::EBus; -} diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetworkContext.cpp b/Code/Framework/AzFramework/AzFramework/Network/NetworkContext.cpp deleted file mode 100644 index 98ef897d29..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetworkContext.cpp +++ /dev/null @@ -1,378 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include -#include -#include - - -namespace AzFramework -{ - NetworkContext::DescBase::DescBase(const char* name, ptrdiff_t offset) - : m_name(name) - , m_offset(offset) - { - } - - NetworkContext::FieldDescBase::FieldDescBase(const char* name, ptrdiff_t offset) - : DescBase(name, offset) - , m_dataSetIdx(static_cast(-1)) - { - } - - NetworkContext::RpcDescBase::RpcDescBase(const char* name, ptrdiff_t offset) - : DescBase(name, offset) - , m_rpcIdx(static_cast(-1)) - { - } - - NetworkContext::CtorDataBase::CtorDataBase(const char* name) - : m_name(name) - { - } - - NetworkContext::ClassBuilder::ClassBuilder(NetworkContext* context, ClassDescPtr binding) - : m_binding(binding) - , m_context(context) - { - } - - NetworkContext::ClassBuilder::~ClassBuilder() - { - if (m_context->IsRemovingReflection()) - { - if (m_binding->UnregisterChunkType) - { - m_binding->UnregisterChunkType(); - } - } - else - { - if (m_binding->RegisterChunkType) - { - m_binding->RegisterChunkType(); - } - } - } - - NetworkContext::ClassDesc::ClassDesc(const char* name, const AZ::Uuid& typeId /* = AZ::Uuid() */) - : m_name(name) - , m_typeId(typeId) - { - } - - /////////////////////////////////////////////////////////////////////////// - /// NetworkContext - /////////////////////////////////////////////////////////////////////////// - NetworkContext::NetworkContext() - { - } - - NetworkContext::~NetworkContext() - { - } - - size_t NetworkContext::GetReflectedChunkSize(const AZ::Uuid& typeId) const - { - size_t totalSize = 0; - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - ClassDescPtr binding = it->second; - for (const auto& field : binding->m_chunkDesc.m_fields) - { - totalSize += field->GetDataSetSize(); - } - - for (const auto& rpc : binding->m_chunkDesc.m_rpcs) - { - totalSize += rpc->GetRpcSize(); - } - } - - return totalSize; - } - - bool NetworkContext::UsesSelfAsChunk(const AZ::Uuid& typeId) const - { - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - ClassDescPtr binding = it->second; - return !binding->m_chunkDesc.m_external && binding->m_chunkDesc.m_fields.size() > 0; - } - return false; - } - - bool NetworkContext::UsesExternalChunk(const AZ::Uuid& typeId) const - { - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - ClassDescPtr binding = it->second; - return binding->m_chunkDesc.m_external && (AZ::u32(binding->m_chunkDesc.m_chunkId) != 0); - } - return false; - } - - ReplicaChunkBase* NetworkContext::CreateReplicaChunk(const AZ::Uuid& typeId) - { - const auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - const ClassDescPtr binding = it->second; - if (binding->CreateReplicaChunk) - { - ReplicaChunkDescriptor* descriptor = ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(binding->m_chunkDesc.m_chunkId); - AZ_Assert(descriptor, "NetworkContext cannot find replica chunk descriptor for %s. Did you remember to register the chunk type?", binding->m_name); - ReplicaChunkDescriptorTable::Get().BeginConstructReplicaChunk(descriptor); - ReplicaChunkBase* chunk = binding->CreateReplicaChunk(); - ReplicaChunkDescriptorTable::Get().EndConstructReplicaChunk(); - chunk->Init(descriptor); - return chunk; - } - } - - /* - * Special case: empty declarations such as: - * - * static void Reflect() { - * .... - * NetworkContext->Class(); - * } - * - * Result in no ReplicaChunks being created. It's treated as a no-op. No replication will be performed. - */ - return nullptr; - } - - void NetworkContext::DestroyReplicaChunk(ReplicaChunkBase* chunk) - { - ReplicaChunkClassId chunkId = chunk->GetDescriptor()->GetChunkTypeId(); - auto it = m_chunkBindings.find(chunkId); - if (it != m_chunkBindings.end()) - { - ClassDescPtr binding = it->second; - binding->DestroyReplicaChunk(chunk); - return; - } - - AZ_Warning("NetworkContext", false, "DestroyReplicaChunk could not find a binding for %s", chunk->GetDescriptor()->GetChunkName()); - } - - void NetworkContext::Bind(NetBindable* instance, ReplicaChunkPtr chunk, NetworkContextBindMode mode) - { - const AZ::Uuid& typeId = instance->RTTI_GetType(); - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - ClassDescPtr binding = it->second; - if (chunk) - { - ReplicaChunkClassId chunkId = chunk->GetDescriptor()->GetChunkTypeId(); - AZ_Assert(binding->m_chunkDesc.m_chunkId == chunkId, "NetworkContext detected a type mismatch while trying to bind an instance to a ReplicaChunk"); - if (binding->m_chunkDesc.m_chunkId == chunkId) - { - if (!binding->m_chunkDesc.m_external) - { - ReflectedReplicaChunkBase* refChunk = static_cast(chunk.get()); - refChunk->Bind(instance, mode); - } - } - } - else - { - if (binding->BindRpcs) - { - binding->BindRpcs(instance); - } - } - } - } - - void NetworkContext::EnumerateFields(const ReplicaChunkClassId& chunkId, FieldVisitor visitor) const - { - auto it = m_chunkBindings.find(chunkId); - if (it != m_chunkBindings.end()) - { - const ChunkDesc& chunkDesc = it->second->m_chunkDesc; - for (const auto& field : chunkDesc.m_fields) - { - visitor(field.get()); - } - } - } - - void NetworkContext::EnumerateFields(const AZ::Uuid& typeId, FieldVisitor visitor) const - { - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - const ChunkDesc& chunkDesc = it->second->m_chunkDesc; - for (const auto& field : chunkDesc.m_fields) - { - visitor(field.get()); - } - } - } - - void NetworkContext::EnumerateRpcs(const ReplicaChunkClassId& chunkId, RpcVisitor visitor) const - { - auto it = m_chunkBindings.find(chunkId); - if (it != m_chunkBindings.end()) - { - const ChunkDesc& chunkDesc = it->second->m_chunkDesc; - for (const auto& rpc : chunkDesc.m_rpcs) - { - visitor(rpc.get()); - } - } - } - - void NetworkContext::EnumerateRpcs(const AZ::Uuid& typeId, RpcVisitor visitor) const - { - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - const ChunkDesc& chunkDesc = it->second->m_chunkDesc; - for (const auto& rpc : chunkDesc.m_rpcs) - { - visitor(rpc.get()); - } - } - } - - void NetworkContext::EnumerateCtorData(const ReplicaChunkClassId& chunkId, CtorVisitor visitor) const - { - auto it = m_chunkBindings.find(chunkId); - if (it != m_chunkBindings.end()) - { - const ChunkDesc& chunkDesc = it->second->m_chunkDesc; - for (const auto& ctor : chunkDesc.m_ctors) - { - visitor(ctor.get()); - } - } - } - - void NetworkContext::EnumerateCtorData(const AZ::Uuid& typeId, CtorVisitor visitor) const - { - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - const ChunkDesc& chunkDesc = it->second->m_chunkDesc; - for (const auto& ctor : chunkDesc.m_ctors) - { - visitor(ctor.get()); - } - } - } - - /////////////////////////////////////////////////////////////////////////// - ReflectedReplicaChunkBase::ReflectedReplicaChunkBase() - : m_ctorBuffer(GridMate::EndianType::IgnoreEndian, 0) - { - } - - /////////////////////////////////////////////////////////////////////////// - NetworkContextChunkDescriptor::NetworkContextChunkDescriptor(const char* name, size_t size, const AZ::Uuid& typeId) - : ReplicaChunkDescriptor(name, size) - , m_typeId(typeId) - { - } - - ReplicaChunkBase* NetworkContextChunkDescriptor::CreateFromStream(UnmarshalContext& ctx) - { - AZ_Assert(!m_typeId.IsNull(), "No typeid associated with NetworkContextChunkDescriptor, cannot spawn Chunk"); - if (!m_typeId.IsNull()) - { - NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_Assert(netContext, "No NetworkContext found while trying to construct ReflectedReplicaChunk"); - - ReplicaChunkBase* replicaChunk = netContext->CreateReplicaChunk(m_typeId); - if (ctx.m_hasCtorData && ctx.m_iBuf) - { - NetworkContextChunkDescriptor* netChunkDesc = static_cast(replicaChunk->GetDescriptor()); - if (netChunkDesc->IsAuto()) - { - // copy each ctor data field into the ctor buffer - ReflectedReplicaChunkBase* refChunk = static_cast(replicaChunk); - netContext->EnumerateCtorData(m_typeId, - [&ctx, refChunk](NetworkContext::CtorDataBase* ctorData) - { - ctorData->Copy(*ctx.m_iBuf, refChunk->m_ctorBuffer); - }); - } - } - return replicaChunk; - } - return nullptr; - } - - void NetworkContextChunkDescriptor::DeleteReplicaChunk(ReplicaChunkBase* chunk) - { - NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_Assert(netContext, "No NetworkContext found while trying to destroy ReflectedReplicaChunk"); - netContext->DestroyReplicaChunk(chunk); - } - - void NetworkContextChunkDescriptor::MarshalCtorData(ReplicaChunkBase* chunk, WriteBuffer& buffer) - { - NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_Assert(netContext, "No NetworkContext found while trying to collect ctor data for ReflectedReplicaChunk"); - NetBindable* netBindable = static_cast(chunk->GetHandler()); - NetworkContextChunkDescriptor* netChunkDesc = static_cast(chunk->GetDescriptor()); - if (!netChunkDesc->IsAuto()) - { - return; - } - - if (netBindable) // chunk is bound, get source data from the netBindable - { - netContext->EnumerateCtorData(m_typeId, - [netBindable, &buffer](NetworkContext::CtorDataBase* ctorData) - { - ctorData->Marshal(netBindable, buffer); - }); - } - else // chunk is not bound yet, copy the ctor data for forwarding - { - ReflectedReplicaChunkBase* refChunk = static_cast(chunk); - ReadBuffer src(refChunk->m_ctorBuffer.GetEndianType(), refChunk->m_ctorBuffer.Get(), refChunk->m_ctorBuffer.Size()); - netContext->EnumerateCtorData(m_typeId, - [&src, &buffer](NetworkContext::CtorDataBase* ctorData) - { - ctorData->Copy(src, buffer); - }); - } - } - - void NetworkContextChunkDescriptor::DiscardCtorStream(UnmarshalContext& ctx) - { - NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_Assert(netContext, "No NetworkContext found while trying to skip ctor data for ReflectedReplicaChunk"); - if (ctx.m_hasCtorData) - { - // Iterate over all of the ctor data and unmarshal it with no destination, - // which will advance the buffer past the ctor data for this object - netContext->EnumerateCtorData(m_typeId, - [&ctx](NetworkContext::CtorDataBase* ctorData) - { - ctorData->Unmarshal(*ctx.m_iBuf, nullptr); - }); - } - } -} diff --git a/Code/Framework/AzFramework/AzFramework/Network/NetworkContext.h b/Code/Framework/AzFramework/AzFramework/Network/NetworkContext.h deleted file mode 100644 index 5b6d420a79..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Network/NetworkContext.h +++ /dev/null @@ -1,969 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace AzFramework -{ - class NetBindable; - - using GridMate::ReplicaChunkInterface; - using GridMate::ReplicaChunkBase; - using GridMate::ReplicaChunk; - using GridMate::ReplicaChunkDescriptor; - using GridMate::DefaultReplicaChunkDescriptor; - using GridMate::ReplicaChunkDescriptorTable; - using GridMate::ReplicaChunkClassId; - using GridMate::ReplicaChunkPtr; - using GridMate::Rpc; - using GridMate::ZoneMask; - using GridMate::ZoneMask_All; - using GridMate::UnmarshalContext; - using GridMate::ReadBuffer; - using GridMate::WriteBuffer; - using GridMate::WriteBufferDynamic; - - /////////////////////////////////////////////////////////////////////////// - // GridMate ReplicaChunk/ReplicaChunkDescriptors - /////////////////////////////////////////////////////////////////////////// - class ReflectedReplicaChunkBase - : public ReplicaChunkBase - , public ReplicaChunkInterface - { - friend NetworkContext; - public: - ReflectedReplicaChunkBase(); - bool IsReplicaMigratable() override { return true; } - - /// Returns the chunk type name, e.g. "ReflectedReplicaChunk" - virtual const char* GetName() const = 0; - /// Returns the linear size of the chunk including DataSets and RPCs - virtual size_t GetSize() const = 0; - /// Returns a pointer to the start of the DataSet/RPC storage allocated with the chunk - virtual AZ::u8* GetDataStart() const = 0; - /// Binds an instance of the reflected class to this chunk - virtual void Bind(NetBindable* instance, NetworkContextBindMode mode) = 0; - /// Removes network bindings from the bound NetBindable - virtual void Unbind() = 0; - - WriteBufferDynamic m_ctorBuffer; ///< Buffer to hold ctor data before the chunk is bound - }; - - /// This will be the header for a blob in memory: - /// The layout looks like: - /// * ReflectedReplicaChunk - /// * DataSets - /// * RPCs - template - class ReflectedReplicaChunk - : public ReflectedReplicaChunkBase - { - friend NetworkContext; - public: - static const char* GetChunkName(); - static size_t GetChunkSize(); - - public: - AZ_CLASS_ALLOCATOR(ReflectedReplicaChunk, AZ::SystemAllocator, 0); - ReflectedReplicaChunk() - : m_dataSets(reinterpret_cast(this) + sizeof(*this)) - { - } - - const char* GetName() const override { return GetChunkName(); } - size_t GetSize() const override { return GetChunkSize(); } - AZ::u8* GetDataStart() const override { return const_cast(m_dataSets); } - void Bind(NetBindable* instance, NetworkContextBindMode mode) override; - void Unbind() override; - - private: - const AZ::u8* m_dataSets; ///< Points to the beginning of the datasets for this chunk - }; - - class NetworkContextChunkDescriptor - : public ReplicaChunkDescriptor - { - public: - NetworkContextChunkDescriptor(const char* name, size_t size, const AZ::Uuid& typeId = AZ::Uuid()); - - ReplicaChunkBase* CreateFromStream(UnmarshalContext& ctx) override; - void DeleteReplicaChunk(ReplicaChunkBase* chunkInstance) override; - void DiscardCtorStream(UnmarshalContext&) override; - void MarshalCtorData(ReplicaChunkBase*, WriteBuffer&) override; - - void Bind(const AZ::Uuid& typeId) { m_typeId = typeId; } - virtual bool IsAuto() const { return false; } - - private: - AZ::Uuid m_typeId; ///< TypeId of the class this descriptor represents (not the chunk type) - }; - - template - class AutoChunkDescriptor - : public NetworkContextChunkDescriptor - { - public: - AutoChunkDescriptor() - : NetworkContextChunkDescriptor(ReflectedReplicaChunk::GetChunkName(), ReflectedReplicaChunk::GetChunkSize(), AZ::RttiTypeId()) - { - } - - ZoneMask GetZoneMask() const override { return mask; } - - bool IsAuto() const override { return true; } - }; - - template - class ExternalChunkDescriptor - : public NetworkContextChunkDescriptor - { - public: - ExternalChunkDescriptor() - : NetworkContextChunkDescriptor(ChunkType::GetChunkName(), sizeof(ChunkType)) - {} - - ZoneMask GetZoneMask() const override { return mask; } - }; - - /////////////////////////////////////////////////////////////////////////// - /// NetworkContext can be used to reflect classes for network serialization - /// It will automatically generate ReplicaChunks and bind them to instances - /// when requested. It also serves as a binding registry for binding a class - /// to the ReplicaChunk that should be used to replicate it. - /////////////////////////////////////////////////////////////////////////// - class NetworkContext - : public AZ::ReflectContext - { - public: - /// @cond EXCLUDE_DOCS - class ClassBuilder; - class ClassDesc; - using ClassDescPtr = AZStd::intrusive_ptr; - using ClassBuilderPtr = AZStd::intrusive_ptr; - using ClassBindings = AZStd::unordered_map; - using ChunkBindings = AZStd::unordered_map; - using ClassInfo = ClassBuilder; ///< @deprecated Use NetworkContext::ClassBuilder - using ClassInfoPtr = ClassBuilderPtr; ///< @deprecated Use NetworkContext::ClassBuilderPtr - /// @endcond - - class IntrusiveRefCounted - { - public: - virtual ~IntrusiveRefCounted() {} - private: - // refcount - template - friend struct AZStd::IntrusivePtrCountPolicy; - mutable unsigned int m_refCount = 0; - AZ_FORCE_INLINE void add_ref() { ++m_refCount; } - AZ_FORCE_INLINE void release() - { - AZ_Assert(m_refCount > 0, "Reference count logic error, trying to remove reference when refcount is 0"); - if (--m_refCount == 0) - { - delete this; - } - } - }; - - /** - * Interface for recording classes, chunks, and datasets - * When destructed at the end of reflection, it will register/unregister the ChunkDescriptor - */ - class ClassBuilder - : public IntrusiveRefCounted - { - friend class NetworkContext; - - protected: - AZ_CLASS_ALLOCATOR(ClassBuilder, AZ::SystemAllocator, 0); - ClassBuilder(NetworkContext* context, ClassDescPtr binding); - - public: - ~ClassBuilder(); - ClassBuilderPtr operator->() { return this; } - - /// Bind a ReplicaChunk type to this class for network serialization - template > - ClassBuilderPtr Chunk(); - - /// Bind a NetBindable's Field - template - typename AZStd::enable_if::value, ClassBuilderPtr>::type - Field(const char* name, FieldType ClassType::* address); - - /// Declare an external chunk's DataSet - template - typename AZStd::enable_if::value, ClassBuilderPtr>::type - Field(const char* name, DataSetType ClassType::* address); - - /// Bind an Rpc::BindInterface for this chunk - template ::template BindInterface > - typename AZStd::enable_if::value, ClassBuilderPtr>::type - RPC(const char* name, RpcBindType ClassType::* rpc); - - /// Bind a NetBindable::Rpc for this NetBindable - template ::template Bind > - typename AZStd::enable_if::value, ClassBuilderPtr>::type - RPC(const char* name, RpcBindType ClassType::* rpc); - -#define CTOR_DATA_OVERLOAD(_getsig, _setsig) \ - template > \ - ClassBuilderPtr CtorData(const char* name, _getsig, _setsig, const MarshalerType&marshaler = MarshalerType()) \ - { \ - return CtorDataImpl(name, getter, setter, marshaler); \ - } - - /// Bind a getter/setter pair for data required during object construction - // this has to be done via overload so that the user does not have to explicitly provide - // the template arguments, they can be divined from the function call - CTOR_DATA_OVERLOAD(DataType(ClassType::* getter)(), void (ClassType::* setter)(const DataType&)); - CTOR_DATA_OVERLOAD(DataType(ClassType::* getter)() const, void (ClassType::* setter)(const DataType&)); - CTOR_DATA_OVERLOAD(DataType & (ClassType::* getter)(), void (ClassType::* setter)(const DataType&)); - CTOR_DATA_OVERLOAD(DataType & (ClassType::* getter)() const, void (ClassType::* setter)(const DataType&)); - CTOR_DATA_OVERLOAD(const DataType&(ClassType::* getter)(), void (ClassType::* setter)(const DataType&)); - CTOR_DATA_OVERLOAD(const DataType&(ClassType::* getter)() const, void (ClassType::* setter)(const DataType&)); - CTOR_DATA_OVERLOAD(DataType(ClassType::* getter)(), void (ClassType::* setter)(DataType)); - CTOR_DATA_OVERLOAD(DataType(ClassType::* getter)() const, void (ClassType::* setter)(DataType)); - CTOR_DATA_OVERLOAD(DataType & (ClassType::* getter)(), void (ClassType::* setter)(DataType)); - CTOR_DATA_OVERLOAD(DataType & (ClassType::* getter)() const, void (ClassType::* setter)(DataType)); - CTOR_DATA_OVERLOAD(const DataType&(ClassType::* getter)(), void (ClassType::* setter)(DataType)); - CTOR_DATA_OVERLOAD(const DataType&(ClassType::* getter)() const, void (ClassType::* setter)(DataType)); -#undef CTOR_DATA_OVERLOAD - - private: - template > - ClassBuilderPtr CtorDataImpl(const char* name, GetterFunction getter, SetterFunction setter, const MarshalerType& marshaler = MarshalerType()); - - private: - ClassDescPtr m_binding; - NetworkContext* m_context; - }; - - class DescBase - : public IntrusiveRefCounted - { - friend class NetworkContext; - public: - AZ_CLASS_ALLOCATOR(DescBase, AZ::SystemAllocator, 0); - DescBase(const char* name, ptrdiff_t offset); - virtual ~DescBase() {} - - const char* GetName() const { return m_name; } - ptrdiff_t GetOffset() const { return m_offset; } - protected: - const char* m_name; ///< Field name, will be used as DataSet debug name - ptrdiff_t m_offset; ///< Offset from an instance pointer (a ReplicaChunk or the actual class instance) - }; - - class FieldDescBase - : public DescBase - { - friend class NetworkContext; - - public: - AZ_CLASS_ALLOCATOR(FieldDescBase, AZ::SystemAllocator, 0); - FieldDescBase(const char* name, ptrdiff_t offset); - virtual ~FieldDescBase() {} - - virtual void ConstructDataSet(void*) const = 0; - virtual void DestructDataSet(void*) const = 0; - virtual size_t GetDataSetSize() const = 0; - - size_t GetDataSetIndex() const { return m_dataSetIdx; } - - protected: - size_t m_dataSetIdx; - }; - - /** - * Represents a DataSet in a chunk or class - * NOTE: m_offset in this class is the offset from ReplicaChunk* -> DataSet - */ - template - class DataSetDesc - : public FieldDescBase - { - public: - AZ_CLASS_ALLOCATOR(DataSetDesc, AZ::SystemAllocator, 0); - DataSetDesc(const char* name, ptrdiff_t offset); - - void ConstructDataSet(void*) const override {} - void DestructDataSet(void*) const override {} - size_t GetDataSetSize() const override { return sizeof(DataSetType); } - }; - - /** - * Represents a field in a chunk, responsible for creating a DataSet - * that represents the field - * NOTE: m_offset in this class is the offset from NetBindable* -> NetBindable::Field - */ - template - class NetBindableFieldDesc - : public FieldDescBase - { - public: - using DataSetType = typename FieldType::DataSetType; - - public: - AZ_CLASS_ALLOCATOR(NetBindableFieldDesc, AZ::SystemAllocator, 0); - NetBindableFieldDesc(const char* name, ptrdiff_t offset); - - void ConstructDataSet(void* mem) const override { FieldType::ConstructDataSet(mem, m_name); } - void DestructDataSet(void* mem) const override { FieldType::DestructDataSet(mem); } - size_t GetDataSetSize() const override { return sizeof(DataSetType); } - }; - - class RpcDescBase - : public DescBase - { - friend class NetworkContext; - public: - AZ_CLASS_ALLOCATOR(RpcDescBase, AZ::SystemAllocator, 0); - RpcDescBase(const char* name, ptrdiff_t offset); - virtual ~RpcDescBase() {} - - virtual void ConstructRpc(void*) const {} - virtual void DestructRpc(void*) const {} - virtual size_t GetRpcSize() const { return 0; } - - size_t GetRpcIndex() const { return m_rpcIdx; } - - protected: - size_t m_rpcIdx; - }; - - template - class NetBindableRpcDesc - : public RpcDescBase - { - friend class NetworkContext; - public: - AZ_CLASS_ALLOCATOR(NetBindableRpcDesc, AZ::SystemAllocator, 0); - NetBindableRpcDesc(const char* name, ptrdiff_t offset) - : RpcDescBase(name, offset) - { - static_assert((AZStd::is_base_of::value), "NetBindableRpcDesc is intended for use only with NetBindableRpcs"); - } - - void ConstructRpc(void* mem) const override { RpcBindType::ConstructRpc(mem, m_name); } - void DestructRpc(void* mem) const override { RpcBindType::DestructRpc(mem); } - size_t GetRpcSize() const override { return sizeof(typename RpcBindType::BindInterfaceType); } - }; - - class CtorDataBase - : public IntrusiveRefCounted - { - public: - AZ_CLASS_ALLOCATOR(CtorDataBase, AZ::SystemAllocator, 0); - CtorDataBase(const char* name); - virtual ~CtorDataBase() {} - - virtual void Marshal(NetBindable* netBindable, WriteBuffer& buffer) const = 0; - virtual void Unmarshal(ReadBuffer& buffer, NetBindable* netBindable) const = 0; - virtual void Copy(ReadBuffer& src, WriteBuffer& dest) const = 0; - - protected: - const char* m_name; - }; - - template - class CtorDataDesc - : public CtorDataBase - { - using GetterFunction = AZStd::function; - using SetterFunction = AZStd::function; - public: - AZ_CLASS_ALLOCATOR(CtorDataDesc, AZ::SystemAllocator, 0); - CtorDataDesc(const char* name, GetterFunction get, SetterFunction set) - : CtorDataBase(name) - , m_get(get) - , m_set(set) - {} - - CtorDataDesc(const char* name, DataType(ClassType::* getter)(), void (ClassType::* setter)(const DataType&)) - : CtorDataBase(name) - , m_get(AZStd::bind(getter, AZStd::placeholders::_1)) - , m_set(AZStd::bind(setter, AZStd::placeholders::_1, AZStd::placeholders::_2)) - {} - - void Marshal(NetBindable* netBindable, WriteBuffer& buffer) const override; - void Unmarshal(ReadBuffer& buffer, NetBindable* netBindable) const override; - virtual void Copy(ReadBuffer& src, WriteBuffer& dest) const override; - - GetterFunction m_get; - SetterFunction m_set; - MarshalerType m_marshaler; - }; - - struct ChunkDesc - { - public: - using Fields = AZStd::vector >; - using Rpcs = AZStd::vector >; - using Ctors = AZStd::vector >; - - const char* m_name = nullptr; ///< The name of the chunk - ReplicaChunkClassId m_chunkId; ///< The registered id of the ReplicaChunk this class will use - Fields m_fields; ///< list of data fields in the ReplicaChunk - Rpcs m_rpcs; ///< list of RPCs in the ReplicaChunk - Ctors m_ctors; ///< list of ctor callbacks to gather/apply ctor data - bool m_external = false; ///< If true, this chunk is separate from the class bound to it - }; - - /** - * Contains the chunk factory and field descriptions for a given class - */ - class ClassDesc - : public IntrusiveRefCounted - { - public: - - AZ_CLASS_ALLOCATOR(ClassDesc, AZ::SystemAllocator, 0); - ClassDesc(const char* name = nullptr, const AZ::Uuid& typeId = AZ::Uuid()); - - public: - const char* m_name; ///< The name of the class that is bound - AZ::Uuid m_typeId; ///< The type that this binding represents (null for chunks) - ChunkDesc m_chunkDesc; ///< Descriptor for the chunk for this type - - /// Functor which will register the ReplicaChunkDescriptor with the global registry - AZStd::function RegisterChunkType; - /// Functor to unregister the ReplicaChunkDescriptor (during reflection removal) - AZStd::function UnregisterChunkType; - /// Functor which will create a ReplicaChunk and bind it to the given instance - AZStd::function CreateReplicaChunk; - /// Functor which can destroy a ReplicaChunk and free its memory - AZStd::function DestroyReplicaChunk; - /// Functor which binds an instance of this class to its RPCs for local dispatch - AZStd::function BindRpcs; - }; - - AZ_CLASS_ALLOCATOR(NetworkContext, AZ::SystemAllocator, 0); - AZ_RTTI(NetworkContext, "{B1172D4A-EA1B-441D-AAE6-A9933DAECA8A}", AZ::ReflectContext); - - NetworkContext(); - virtual ~NetworkContext(); - - /// Register a class with the NetworkContext for replication - template - ClassBuilderPtr Class(); - - /// Create a replica chunk for a given class - ReplicaChunkBase* CreateReplicaChunk(const AZ::Uuid& typeId); - - /// Create a replica chunk for a given class, template version - template - ReplicaChunkBase* CreateReplicaChunk(); - - /// Destroy a replica chunk for a given class - void DestroyReplicaChunk(ReplicaChunkBase * chunk); - - /// Bind an instance and a chunk to each other - void Bind(NetBindable * instance, ReplicaChunkPtr chunk, NetworkContextBindMode mode); - - /// Returns whether or not a given type uses a reflected (automatic) ReplicaChunk - bool UsesSelfAsChunk(const AZ::Uuid & typeId) const; - - /// Returns whether or not a given type uses a custom ReplicaChunk - bool UsesExternalChunk(const AZ::Uuid & typeId) const; - - /// Return the size of the the chunk which will represent the given type - size_t GetReflectedChunkSize(const AZ::Uuid & typeId) const; - - using FieldVisitor = AZStd::function; - void EnumerateFields(const ReplicaChunkClassId&chunkId, FieldVisitor visitor) const; - void EnumerateFields(const AZ::Uuid & typeId, FieldVisitor visitor) const; - - using RpcVisitor = AZStd::function; - void EnumerateRpcs(const ReplicaChunkClassId&chunkId, RpcVisitor visitor) const; - void EnumerateRpcs(const AZ::Uuid & typeId, RpcVisitor visitor) const; - - using CtorVisitor = AZStd::function; - void EnumerateCtorData(const ReplicaChunkClassId&chunkId, CtorVisitor visitor) const; - void EnumerateCtorData(const AZ::Uuid & typeId, CtorVisitor visitor) const; - - private: - template - void InitReflectedChunkBinding(ClassDescPtr binding); - - template > - void InitExternalChunkBinding(ClassDescPtr binding); - - private: - ClassBindings m_classBindings; - ChunkBindings m_chunkBindings; - }; - - /////////////////////////////////////////////////////////////////////////// - template - NetworkContext::ClassBuilderPtr NetworkContext::Class() - { - static_assert((AZStd::is_base_of::value), "Classes reflected through NetworkContext must be derived from NetBindable"); - const AZ::Uuid& typeId = AZ::AzTypeInfo::Uuid(); - ClassDescPtr binding = nullptr; - if (IsRemovingReflection()) // Just remove the entire class definition - { - auto it = m_classBindings.find(typeId); - if (it != m_classBindings.end()) - { - binding = it->second; - m_chunkBindings.erase(binding->m_chunkDesc.m_chunkId); - m_classBindings.erase(it); - } - } - else - { - auto ret = m_classBindings.insert_key(typeId); - AZ_Assert(ret.second, "Cannot register more than one type with the same Uuid in the NetworkContext"); - binding = ret.first->second = aznew ClassDesc(AZ::AzTypeInfo::Name(), AZ::AzTypeInfo::Uuid()); - } - - return aznew ClassBuilder(this, binding); - } - - template - void NetworkContext::InitReflectedChunkBinding(ClassDescPtr binding) - { - if (!binding->RegisterChunkType) - { - binding->m_chunkDesc.m_name = ReflectedReplicaChunk::GetChunkName(); - ReplicaChunkClassId chunkClassId = ReplicaChunkClassId(binding->m_chunkDesc.m_name); - m_chunkBindings[chunkClassId] = binding; - NetworkContext* netContext = this; - - binding->RegisterChunkType = [chunkClassId, netContext]() - { - bool result = ReplicaChunkDescriptorTable::Get().RegisterChunkType, AutoChunkDescriptor >(); - ReplicaChunkDescriptor* desc = ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(chunkClassId); - ReplicaChunkDescriptorTable::Get().BeginConstructReplicaChunk(desc); - // The offset recorded in NetBindableFields is the offset in the NetBindable - // We must compute the offset of the generated DataSets here and record the - // index from the descriptor - ptrdiff_t offset = sizeof(ReflectedReplicaChunk); // data sets are right after the ReflectedReplicaChunk<> in memory - netContext->EnumerateFields(chunkClassId, - [desc, &offset](FieldDescBase* field) - { - desc->RegisterDataSet(field->m_name, offset); - field->m_dataSetIdx = desc->GetDataSetIndex(offset); - offset += field->GetDataSetSize(); - }); - netContext->EnumerateRpcs(chunkClassId, - [desc, &offset](RpcDescBase* rpc) - { - desc->RegisterRPC(rpc->m_name, offset); - rpc->m_rpcIdx = desc->GetRpcIndex(offset); - offset += rpc->GetRpcSize(); - }); - AZ_Assert(offset == static_cast(ReflectedReplicaChunk::GetChunkSize()), "Overflow/underflow while registering DataSets for %s", ReflectedReplicaChunk::GetChunkName()); - ReplicaChunkDescriptorTable::Get().EndConstructReplicaChunk(); - return result; - }; - - binding->UnregisterChunkType = [chunkClassId]() - { - ReplicaChunkDescriptorTable::Get().UnregisterReplicaChunkDescriptor(chunkClassId); - }; - - binding->CreateReplicaChunk = [netContext, chunkClassId]() - { - ReflectedReplicaChunkBase* chunk = new(azmalloc(ReflectedReplicaChunk::GetChunkSize(), AZStd::alignment_of >::value, AZ::SystemAllocator, ReflectedReplicaChunk::GetChunkName()))ReflectedReplicaChunk(); - AZ::u8* dataStart = chunk->GetDataStart(); - AZ::u8* dataEnd = reinterpret_cast(chunk) + chunk->GetSize(); - ptrdiff_t offset = 0; - netContext->EnumerateFields(chunkClassId, - [&offset, dataStart, dataEnd](FieldDescBase* field) - { - AZ_Assert((dataStart + offset) < dataEnd, "Overflow in NetworkContext::CreateReplicaChunk while creating %s", ReflectedReplicaChunk::GetChunkName()); - void* dataSetMem = reinterpret_cast(dataStart + offset); - field->ConstructDataSet(dataSetMem); - offset += field->GetDataSetSize(); - }); - netContext->EnumerateRpcs(chunkClassId, - [&offset, dataStart, dataEnd](RpcDescBase* rpc) - { - AZ_Assert((dataStart + offset) < dataEnd, "Overflow in NetworkContext::CreateReplicaChunk while creating %s", ReflectedReplicaChunk::GetChunkName()); - void* rpcMem = reinterpret_cast(dataStart + offset); - rpc->ConstructRpc(rpcMem); - offset += rpc->GetRpcSize(); - }); - AZ_Assert((dataStart + offset) == dataEnd, "Overflow/underflow in NetworkContext::CreateReplicaChunk while creating %s", ReflectedReplicaChunk::GetChunkName()); - return chunk; - }; - - binding->DestroyReplicaChunk = [netContext, chunkClassId](ReplicaChunkBase* chunkBase) - { - AZ_Assert(chunkBase->GetDescriptor()->GetChunkTypeId() == chunkClassId, "Mismatched chunk type id for %s (0x%p)", ReflectedReplicaChunk::GetChunkName(), chunkBase); - ReflectedReplicaChunkBase* chunk = static_cast(chunkBase); - chunk->Unbind(); - - AZ::u8* dataStart = chunk->GetDataStart(); - AZ::u8* dataEnd = reinterpret_cast(chunk) + chunk->GetSize(); - ptrdiff_t offset = 0; - netContext->EnumerateFields(chunkClassId, - [&offset, dataStart, dataEnd](FieldDescBase* field) - { - AZ_Assert((dataStart + offset) < dataEnd, "Overflow in dtor while destroying %s", ReflectedReplicaChunk::GetChunkName()); - void* dataSetMem = reinterpret_cast(dataStart + offset); - field->DestructDataSet(dataSetMem); - offset += field->GetDataSetSize(); - }); - netContext->EnumerateRpcs(chunkClassId, - [&offset, dataStart, dataEnd](RpcDescBase* rpc) - { - AZ_Assert((dataStart + offset) < dataEnd, "Overflow in NetworkContext::CreateReplicaChunk while creating %s", ReflectedReplicaChunk::GetChunkName()); - void* rpcMem = reinterpret_cast(dataStart + offset); - rpc->DestructRpc(rpcMem); - offset += rpc->GetRpcSize(); - }); - AZ_Assert((dataStart + offset) == dataEnd, "Overflow/underflow in dtor while destroying %s", ReflectedReplicaChunk::GetChunkName()); - chunk->~ReflectedReplicaChunkBase(); - azfree(chunk, AZ::SystemAllocator, ReflectedReplicaChunk::GetChunkSize(), AZStd::alignment_of >::value); - }; - - binding->BindRpcs = [netContext, chunkClassId](NetBindable* bindable) - { - ClassType* derivedInstance = static_cast(bindable); - netContext->EnumerateRpcs(chunkClassId, - [derivedInstance](const RpcDescBase* rpc) - { - NetBindableRpcBase* bindableRpc = reinterpret_cast(reinterpret_cast(derivedInstance) + rpc->GetOffset()); - bindableRpc->Bind(derivedInstance); - }); - }; - - binding->m_chunkDesc.m_chunkId = chunkClassId; - } - } - - template - void NetworkContext::InitExternalChunkBinding(ClassDescPtr binding) - { - if (!binding->RegisterChunkType) - { - binding->m_chunkDesc.m_name = ChunkType::GetChunkName(); - ReplicaChunkClassId chunkClassId = ReplicaChunkClassId(binding->m_chunkDesc.m_name); - m_chunkBindings[chunkClassId] = binding; - const AZ::Uuid& typeId = binding->m_typeId; - NetworkContext* netContext = this; - binding->RegisterChunkType = [chunkClassId, typeId, netContext]() - { - bool result = ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - NetworkContextChunkDescriptor* desc = static_cast(ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(chunkClassId)); - desc->Bind(typeId); - netContext->EnumerateFields(chunkClassId, - [desc](FieldDescBase* field) - { - desc->RegisterDataSet(field->m_name, field->m_offset); - field->m_dataSetIdx = desc->GetDataSetIndex(field->m_offset); - }); - netContext->EnumerateRpcs(chunkClassId, - [desc](RpcDescBase* rpc) - { - desc->RegisterRPC(rpc->m_name, rpc->m_offset); - }); - return result; - }; - - binding->UnregisterChunkType = [chunkClassId]() - { - return ReplicaChunkDescriptorTable::Get().UnregisterReplicaChunkDescriptor(chunkClassId); - }; - - binding->CreateReplicaChunk = []() - { - return aznew ChunkType(); - }; - - binding->DestroyReplicaChunk = [](ReplicaChunkBase* chunk) - { - delete chunk; - }; - - binding->m_chunkDesc.m_chunkId = chunkClassId; - } - } - - template - ReplicaChunkBase* NetworkContext::CreateReplicaChunk() - { - return CreateReplicaChunk(AZ::AzTypeInfo::Uuid()); - } - - /////////////////////////////////////////////////////////////////////////// - template - NetworkContext::DataSetDesc::DataSetDesc(const char* name, ptrdiff_t offset) - : NetworkContext::FieldDescBase(name, offset) - { - } - - /////////////////////////////////////////////////////////////////////////// - template - NetworkContext::NetBindableFieldDesc::NetBindableFieldDesc(const char* name, ptrdiff_t offset) - : NetworkContext::FieldDescBase(name, offset) - { - } - - /////////////////////////////////////////////////////////////////////////// - template - void NetworkContext::CtorDataDesc::Marshal(NetBindable* netBindable, WriteBuffer& buffer) const - { - ClassType* instance = static_cast(netBindable); - DataType data = m_get(instance); - buffer.Write(data, m_marshaler); - } - - template - void NetworkContext::CtorDataDesc::Unmarshal(ReadBuffer& buffer, NetBindable* netBindable) const - { - ClassType* instance = static_cast(netBindable); - DataType data; - buffer.Read(data, m_marshaler); - if (instance) - { - m_set(instance, data); - } - } - - template - void NetworkContext::CtorDataDesc::Copy(ReadBuffer& src, WriteBuffer& dest) const - { - DataType data; - src.Read(data, m_marshaler); - dest.Write(data, m_marshaler); - } - - /////////////////////////////////////////////////////////////////////////// - template - NetworkContext::ClassBuilderPtr NetworkContext::ClassBuilder::Chunk() - { - if (!m_context->IsRemovingReflection()) - { - static_assert((AZStd::is_base_of::value), "ReplicaChunks being registered with the NetworkContext must derive from ReplicaChunk"); - static_assert((AZStd::is_base_of::value), "Chunk bindings via NetworkContext must use a NetworkContextChunkDescriptor derived descriptor"); - AZ_Assert(!m_binding->m_typeId.IsNull(), "Cannot register a ReplicaChunk for a class which has not been declared to the NetworkContext"); - AZ_Assert(!m_binding->m_chunkDesc.m_chunkId, "Cannot register more than one ReplicaChunk binding for a class in the NetworkContext"); - - m_context->InitExternalChunkBinding(m_binding); - m_binding->m_chunkDesc.m_external = true; - } - return this; - } - - template - typename AZStd::enable_if::value, NetworkContext::ClassBuilderPtr>::type - NetworkContext::ClassBuilder::Field(const char* name, FieldType ClassType::* address) - { - if (!m_context->IsRemovingReflection()) - { - AZ_Assert(!m_binding->m_typeId.IsNull(), "Cannot register a field for a class which has not been declared to the NetworkContext"); - AZ_Assert(!m_binding->m_chunkDesc.m_external, "Cannot register a NetBindable::Field from within an external chunk"); - - m_context->InitReflectedChunkBinding(m_binding); - ptrdiff_t offset = reinterpret_cast(&(reinterpret_cast(0)->*address)); - m_binding->m_chunkDesc.m_fields.push_back(aznew NetBindableFieldDesc(name, offset)); - } - - return this; - } - - template - typename AZStd::enable_if::value, NetworkContext::ClassBuilderPtr>::type - NetworkContext::ClassBuilder::Field(const char* name, DataSetType ClassType::* address) - { - if (!m_context->IsRemovingReflection()) - { - AZ_Assert(!m_binding->m_typeId.IsNull(), "Cannot register a field for a class which has not been declared to the NetworkContext"); - - ptrdiff_t offset = reinterpret_cast(&(reinterpret_cast(0)->*address)); - m_binding->m_chunkDesc.m_fields.push_back(aznew DataSetDesc(name, offset)); - } - - return this; - } - - template - typename AZStd::enable_if::value, NetworkContext::ClassBuilderPtr>::type - NetworkContext::ClassBuilder::RPC(const char* name, RpcBindType ClassType::* rpc) - { - if (!m_context->IsRemovingReflection()) - { - static_assert((AZStd::is_base_of::value), "Cannot bind an RPC call to an object which is not a ReplicaChunkInterface"); - AZ_Assert(!m_binding->m_typeId.IsNull(), "Cannot register an RPC for a class which has not been declared to the NetworkContext"); - - ptrdiff_t offset = reinterpret_cast(&(reinterpret_cast(0)->*rpc)); - m_binding->m_chunkDesc.m_rpcs.push_back(aznew RpcDescBase(name, offset)); - } - - return this; - } - - template - typename AZStd::enable_if::value, NetworkContext::ClassBuilderPtr>::type - NetworkContext::ClassBuilder::RPC(const char* name, RpcBindType ClassType::* rpc) - { - if (!m_context->IsRemovingReflection()) - { - static_assert((AZStd::is_base_of::value), "Cannot bind an RPC call to an object which is not a ReplicaChunkInterface"); - AZ_Assert(!m_binding->m_typeId.IsNull(), "Cannot register an RPC for a class which has not been declared to the NetworkContext"); - - m_context->InitReflectedChunkBinding(m_binding); - - ptrdiff_t offset = reinterpret_cast(&(reinterpret_cast(0)->*rpc)); - m_binding->m_chunkDesc.m_rpcs.push_back(aznew NetBindableRpcDesc(name, offset)); - } - - return this; - } - - template - NetworkContext::ClassBuilderPtr NetworkContext::ClassBuilder::CtorDataImpl(const char* name, GetterFunction getter, SetterFunction setter, const MarshalerType&) - { - if (!m_context->IsRemovingReflection()) - { - m_context->InitReflectedChunkBinding(m_binding); - - auto get = [getter](NetBindable* nb) -> DataType { return (*static_cast(nb).*getter)(); }; - auto set = [setter](NetBindable* nb, const DataType& data) { (*static_cast(nb).*setter)(data); }; - m_binding->m_chunkDesc.m_ctors.push_back(aznew CtorDataDesc(name, get, set)); - } - - return this; - } - - /////////////////////////////////////////////////////////////////////////// - template - const char* ReflectedReplicaChunk::GetChunkName() - { - static char name[128] = { 0 }; - if (!name[0]) - { - AZ::Internal::AzTypeInfoSafeCat(name, AZ_ARRAY_SIZE(name), "ReflectedReplicaChunk<"); - AZ::Internal::AzTypeInfoSafeCat(name, AZ_ARRAY_SIZE(name), AZ::AzTypeInfo::Name()); - AZ::Internal::AzTypeInfoSafeCat(name, AZ_ARRAY_SIZE(name), ">"); - } - return name; - } - - template - size_t ReflectedReplicaChunk::GetChunkSize() - { - static size_t chunkSize = 0; - if (chunkSize == 0) - { - NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_Assert(netContext, "No NetworkContext found while trying to compute chunk size"); - if (!netContext) - { - return 0; - } - chunkSize = sizeof(ReflectedReplicaChunk) + netContext->GetReflectedChunkSize(AZ::AzTypeInfo::Uuid()); - } - - return chunkSize; - } - - template - void ReflectedReplicaChunk::Bind(NetBindable* instance, NetworkContextBindMode mode) - { - SetHandler(instance); - ClassType* derivedInstance = azrtti_cast(instance); - AZ_Assert(derivedInstance, "Unable to convert NetBindable to %s", AZ::AzTypeInfo::Name()); - ReplicaChunkDescriptor* desc = GetDescriptor(); - NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - netContext->EnumerateFields(desc->GetChunkTypeId(), - [this, derivedInstance, desc, mode](NetworkContext::FieldDescBase* field) - { - NetBindableFieldBase* bindableField = reinterpret_cast(reinterpret_cast(derivedInstance) + field->GetOffset()); - DataSetBase* dataSet = desc->GetDataSet(this, field->GetDataSetIndex()); - bindableField->Bind(dataSet, mode); - }); - netContext->EnumerateRpcs(desc->GetChunkTypeId(), - [this, derivedInstance, desc](NetworkContext::RpcDescBase* rpc) - { - NetBindableRpcBase* bindableRpc = reinterpret_cast(reinterpret_cast(derivedInstance) + rpc->GetOffset()); - RpcBase* rpcBase = desc->GetRpc(this, rpc->GetRpcIndex()); - bindableRpc->Bind(rpcBase); - }); - - // Transfer any stored ctor data from the buffer -> NetBindable instance - if (m_ctorBuffer.Size() > 0) - { - ReadBuffer ctorBuffer(m_ctorBuffer.GetEndianType(), m_ctorBuffer.Get(), m_ctorBuffer.Size()); - netContext->EnumerateCtorData(desc->GetChunkTypeId(), - [instance, &ctorBuffer](NetworkContext::CtorDataBase* ctorData) - { - ctorData->Unmarshal(ctorBuffer, instance); - }); - } - } - - template - void ReflectedReplicaChunk::Unbind() - { - ReplicaChunkInterface* handler = GetHandler(); - if (!handler || handler == this) - { - return; - } - - NetBindable* netBindable = static_cast(handler); - ClassType* derivedInstance = azrtti_cast(netBindable); - AZ_Assert(derivedInstance, "Unable to convert NetBindable to %s. Have you forgotten to derive your component from AzFramework::NetBindable?", AZ::AzTypeInfo::Name()); - if (derivedInstance) - { - ReplicaChunkDescriptor* desc = GetDescriptor(); - NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - netContext->EnumerateFields(desc->GetChunkTypeId(), - [derivedInstance](NetworkContext::FieldDescBase* field) - { - NetBindableFieldBase* bindableField = reinterpret_cast(reinterpret_cast(derivedInstance) + field->GetOffset()); - bindableField->Bind(nullptr, NetworkContextBindMode::NonAuthoritative); - }); - netContext->EnumerateRpcs(desc->GetChunkTypeId(), - [derivedInstance](NetworkContext::RpcDescBase* rpc) - { - NetBindableRpcBase* bindableRpc = reinterpret_cast(reinterpret_cast(derivedInstance) + rpc->GetOffset()); - bindableRpc->Bind(derivedInstance); - }); - } - - // We have disconnected from the handler and erased any connections from DataFields or Rpcs - SetHandler(nullptr); - } -} // namespace AZ diff --git a/Code/Framework/AzFramework/AzFramework/Physics/WindBus.h b/Code/Framework/AzFramework/AzFramework/Physics/WindBus.h index 60da2c3607..f96af2bcf9 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/WindBus.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/WindBus.h @@ -13,6 +13,7 @@ #include #include +#include #include namespace Physics diff --git a/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.cpp b/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.cpp index 838ab0b6e2..30343b1322 100644 --- a/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.cpp @@ -26,12 +26,9 @@ #include #include -#include -#include #include -#include #include @@ -429,83 +426,60 @@ namespace AzFramework { LSV_BEGIN(lua, 1); - // calling format __index(table,key) - ScriptNetBindingTable* netBindingTable = reinterpret_cast(lua_touserdata(lua, lua_upvalueindex(1))); - - bool readValue = false; - - if (netBindingTable != nullptr) + AZ::ScriptContext::FromNativeContext(lua)->Error(AZ::ScriptContext::ErrorType::Warning, true, + "Property %s not found in entity table. Please push this property to your slice to avoid decrease in performance.", lua_tostring(lua, -1)); + int lookupKey = lua_gettop(lua); + + int lookupTable = lookupKey - 1; + // This is a slow function and it's made slow so we don't cache any extra data. + // This is done because this function will be called only the exported components + // and script are not in sync and we added new properties. + lua_getmetatable(lua, -2); // get the metatable which will be the top property table + int entityProperties = lua_gettop(lua); + if (lua_getmetatable(lua, -1) == 0) // get the metatable of the property which will be the original table { - AZ_Error("ScriptComponent",netBindingTable->GetScriptContext() != nullptr,"ScriptNetBindingTable is missing ScriptContext."); - AZ_Error("ScriptComponent",netBindingTable->GetScriptContext() == nullptr || netBindingTable->GetScriptContext()->NativeContext() == lua,"Trying to use a NetBindingTable in wrong lua context"); - - AZ::ScriptContext* scriptContext = netBindingTable->GetScriptContext(); - - if (scriptContext) - { - AZ::ScriptDataContext stackContext; - scriptContext->ReadStack(stackContext); - - readValue = netBindingTable->InspectTableValue(stackContext); - } + // we are looking at top level properties + lua_pushvalue(lua, -2); // copy the key + lua_rawget(lua, -2); // read the value } - - if (!readValue) + else { - AZ::ScriptContext::FromNativeContext(lua)->Error(AZ::ScriptContext::ErrorType::Warning, true, - "Property %s not found in entity table. Please push this property to your slice to avoid decrease in performance.", lua_tostring(lua, -1)); - int lookupKey = lua_gettop(lua); - - int lookupTable = lookupKey - 1; - // This is a slow function and it's made slow so we don't cache any extra data. - // This is done because this function will be called only the exported components - // and script are not in sync and we added new properties. - lua_getmetatable(lua, -2); // get the metatable which will be the top property table - int entityProperties = lua_gettop(lua); - if (lua_getmetatable(lua, -1) == 0) // get the metatable of the property which will be the original table + // we are looking into the sub table, so do a slow traversal + int scriptProperties = lua_gettop(lua); + if (!Properties__IndexFindSubtable(lua, lookupTable, entityProperties, scriptProperties)) { - // we are looking at top level properties - lua_pushvalue(lua, -2); // copy the key - lua_rawget(lua, -2); // read the value + lua_pushnil(lua); + return 1; // we did not find the table } else { - // we are looking into the sub table, so do a slow traversal - int scriptProperties = lua_gettop(lua); - if (!Properties__IndexFindSubtable(lua, lookupTable, entityProperties, scriptProperties)) - { - lua_pushnil(lua); - return 1; // we did not find the table - } - else - { - lua_pushvalue(lua, lookupKey); - lua_rawget(lua, -2); - } + lua_pushvalue(lua, lookupKey); + lua_rawget(lua, -2); } + } - if (lua_istable(lua, -1)) + if (lua_istable(lua, -1)) + { + // if we are here the target table is on the top if the stack + lua_pushstring(lua, ScriptComponent::DefaultFieldName); + lua_rawget(lua, -2); + if (lua_isnil(lua, -1)) { - // if we are here the target table is on the top if the stack - lua_pushstring(lua, ScriptComponent::DefaultFieldName); - lua_rawget(lua, -2); - if (lua_isnil(lua, -1)) - { - // parent table is a group, pop the value and return the table - lua_pop(lua, 1); - } + // parent table is a group, pop the value and return the table + lua_pop(lua, 1); } + } - // Duplicate the value, so once the storage is done its on top of the stack, and returned - lua_pushvalue(lua, -1); + // Duplicate the value, so once the storage is done its on top of the stack, and returned + lua_pushvalue(lua, -1); - // Push key, and then move it below the value - lua_pushvalue(lua, lookupKey); - lua_insert(lua, -2); + // Push key, and then move it below the value + lua_pushvalue(lua, lookupKey); + lua_insert(lua, -2); + + // Cache the value so that subsequent accesses to this property don't result in warnings + lua_rawset(lua, lookupTable); - // Cache the value so that subsequent accesses to this property don't result in warnings - lua_rawset(lua, lookupTable); - } return 1; } //========================================================================= @@ -515,30 +489,7 @@ namespace AzFramework { LSV_BEGIN_VARIABLE(lua); - // calling format __newindex(table,key,value) - ScriptNetBindingTable* netBindingTable = reinterpret_cast(lua_touserdata(lua, lua_upvalueindex(1))); - if (netBindingTable != nullptr) - { - AZ_Error("ScriptContext",netBindingTable->GetScriptContext() != nullptr,"ScriptNetBindingTable is missing ScriptContext."); - AZ_Error("ScriptContext",netBindingTable->GetScriptContext() == nullptr || netBindingTable->GetScriptContext()->NativeContext() == lua,"Trying to use a NetBindingTable in wrong lua context"); - - AZ::ScriptContext* scriptContext = netBindingTable->GetScriptContext(); - if (scriptContext) - { - AZ::ScriptDataContext stackContext; - scriptContext->ReadStack(stackContext); - - const bool assignedValue = netBindingTable->AssignTableValue(stackContext); - if (assignedValue) - { - LSV_END_VARIABLE(0); - return 0; - } - } - } - - // If we didn't assign the value above, we want - // to raw set the value to avoid coming back in here. + // We want to raw set the value to avoid coming back in here. lua_rawset(lua, 1); LSV_END_VARIABLE(-2); return 0; @@ -553,7 +504,6 @@ namespace AzFramework // [8/9/2013] //========================================================================= - const char* ScriptComponent::NetRPCFieldName = "NetRPCs"; const char* ScriptComponent::DefaultFieldName = "default"; ScriptComponent::ScriptComponent() @@ -561,7 +511,6 @@ namespace AzFramework , m_contextId(AZ::ScriptContextIds::DefaultScriptContextId) , m_script(AZ::Data::AssetLoadBehavior::PreLoad) , m_table(LUA_NOREF) - , m_netBindingTable(nullptr) { m_properties.m_name = "Properties"; } @@ -573,8 +522,6 @@ namespace AzFramework ScriptComponent::~ScriptComponent() { m_properties.Clear(); - - delete m_netBindingTable; } //========================================================================= @@ -604,11 +551,6 @@ namespace AzFramework return m_properties.GetProperty(propertyName); } - const AZ::ScriptProperty* ScriptComponent::GetNetworkedScriptProperty(const char* propertyName) const - { - return m_netBindingTable->FindScriptProperty(propertyName); - } - void ScriptComponent::Init() { // Grab the script context @@ -622,11 +564,6 @@ namespace AzFramework //========================================================================= void ScriptComponent::Activate() { - if (m_isSyncEnabled && m_netBindingTable == nullptr) - { - m_netBindingTable = aznew ScriptNetBindingTable(); - } - // if we have valid asset listen for script asset events, like reload if (m_script.GetId().IsValid()) { @@ -681,43 +618,6 @@ namespace AzFramework LoadScript(); } - //========================================================================= - // ScriptComponent::GetNetworkBinding - //========================================================================= - GridMate::ReplicaChunkPtr ScriptComponent::GetNetworkBinding() - { - if (m_netBindingTable == nullptr) - { - m_netBindingTable = aznew ScriptNetBindingTable(); - } - - return m_netBindingTable->GetNetworkBinding(); - } - - //========================================================================= - // ScriptComponent::SetNetworkBinding - //========================================================================= - void ScriptComponent::SetNetworkBinding(GridMate::ReplicaChunkPtr chunk) - { - if (m_netBindingTable == nullptr) - { - m_netBindingTable = aznew ScriptNetBindingTable(); - } - - m_netBindingTable->SetNetworkBinding(chunk); - } - - //========================================================================= - // ScriptComponent::UnbindFromNetwork - //========================================================================= - void ScriptComponent::UnbindFromNetwork() - { - if (m_netBindingTable) - { - m_netBindingTable->UnbindFromNetwork(); - } - } - //========================================================================= // LoadScript //========================================================================= @@ -741,11 +641,6 @@ namespace AzFramework AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::Script, "Unload: %s", m_script.GetHint().c_str()); DestroyEntityTable(); - - if (m_netBindingTable) - { - m_netBindingTable->Unload(); - } } //========================================================================= @@ -798,12 +693,10 @@ namespace AzFramework // set the __index so we can read values in case we change the script // after we export the component lua_pushliteral(lua, "__index"); - lua_pushlightuserdata(lua, m_netBindingTable); lua_pushcclosure(lua, &Internal::Properties__Index, 1); lua_rawset(lua, -3); lua_pushliteral(lua, "__newindex"); - lua_pushlightuserdata(lua, m_netBindingTable); lua_pushcclosure(lua, &Internal::Properties__NewIndex, 1); lua_rawset(lua, -3); } @@ -835,8 +728,7 @@ namespace AzFramework { const char* tableName = lua_tolstring(lua, -2, nullptr); if (strncmp(tableName, "__", 2) == 0 || // skip metatables - strcmp(tableName, propertyTableName) == 0 || // Skip the Properties table - strcmp(tableName, ScriptComponent::NetRPCFieldName) == 0) // Want to skip the RPC table as well + strcmp(tableName, propertyTableName) == 0) // Skip the Properties table { break; } @@ -904,13 +796,10 @@ namespace AzFramework } lua_createtable(lua, 0, 1); // Create entity table; - int entityStackIndex = lua_gettop(lua); + [[maybe_unused]] int entityStackIndex = lua_gettop(lua); // Stack: ScriptRootTable PropertiesTable EntityTable - // Create our network binding. - CreateNetworkBindingTable(baseStackIndex, entityStackIndex); - if (basePropertyTable > -1) // if property table exists { CreatePropertyGroup(m_properties, basePropertyTable, lua_gettop(lua), basePropertyTable, true); @@ -932,11 +821,6 @@ namespace AzFramework // Keep the entity table in the registry m_table = luaL_ref(lua, LUA_REGISTRYINDEX); - if (m_netBindingTable) - { - m_netBindingTable->FinalizeNetworkTable(m_context, m_table); - } - // call OnActivate lua_pushliteral(lua, "OnActivate"); lua_rawget(lua, baseStackIndex); // ScriptTable[OnActivate] @@ -993,18 +877,6 @@ namespace AzFramework } } - //========================================================================= - // CreateNetworkBindingTable - // [6/27/2016] - //========================================================================= - void ScriptComponent::CreateNetworkBindingTable(int baseStackIndex, int entityStackIndex) - { - if (m_netBindingTable) - { - m_netBindingTable->CreateNetworkBindingTable(m_context, baseStackIndex, entityStackIndex); - } - } - //========================================================================= // CreatePropertyGroup // [3/3/2014] @@ -1028,12 +900,10 @@ namespace AzFramework // Ensure that this instance of Properties table has the proper __index and __newIndex metamethods. lua_newtable(lua); // This new table will become the Properties instance metatable. Stack: ScriptRootTable PropertiesTable EntityTable "Properties" {} {} lua_pushliteral(lua, "__index"); // Stack: ScriptRootTable PropertiesTable EntityTable "Properties" {} {} __index - lua_pushlightuserdata(lua, m_netBindingTable); // Stack: ScriptRootTable PropertiesTable EntityTable "Properties" {} {} __index m_netBinding lua_pushcclosure(lua, &Internal::Properties__Index, 1); // Stack: ScriptRootTable PropertiesTable EntityTable "Properties" {} {} __index function lua_rawset(lua, -3); // Stack: ScriptRootTable PropertiesTable EntityTable "Properties" {} {__index=Internal::Properties__Index} lua_pushliteral(lua, "__newindex"); - lua_pushlightuserdata(lua, m_netBindingTable); lua_pushcclosure(lua, &Internal::Properties__NewIndex, 1); lua_rawset(lua, -3); // Stack: ScriptRootTable PropertiesTable EntityTable "Properties" {} {__index=Internal::Properties__Index __newindex=Internal::Properties__NewIndex} lua_setmetatable(lua, -2); // Stack: ScriptRootTable PropertiesTable EntityTable "Properties" {Meta{__index=Internal::Properties__Index __newindex=Internal::Properties__NewIndex} } @@ -1050,55 +920,6 @@ namespace AzFramework { AZ::ScriptProperty* prop = group.m_properties[i]; - if (m_netBindingTable != nullptr) - { - lua_pushlstring(lua, prop->m_name.c_str(), prop->m_name.length()); - lua_rawget(lua, propertyGroupTableIndex); - - // Stack: ... SomePropertyInThePropertiesTable. This may be any basic lua type (number, string, table etc) - if (lua_istable(lua, -1)) - { - bool isNetworkedProperty = false; - - AZ::ScriptDataContext stackContext; - - // If we find a table value. We want to inspect it for information. - if (m_context->ReadStack(stackContext)) - { - // check if the current property, which is a table, has a sub-table called "netSynched" - lua_pushliteral(lua, "netSynched"); // Stack: ... SomePropertyInThePropertiesTable netSynched - lua_rawget(lua, -2); // Stack: ... SomePropertyInThePropertiesTable NetSynchedSubTable/nil - if (stackContext.IsTable(-1)) - { - AZ::ScriptDataContext networkTableContext; - if (stackContext.InspectTable(-1, networkTableContext)) // Stack: ... SomePropertyInThePropertiesTable NetSynchedSubTable NetSynchedSubTable nil nil - { - // RegisterDataSet will make sure our __NewIndex function callback will be triggered whenever modifying netSynched Properties. - //isNetworkedProperty = true; - isNetworkedProperty = m_netBindingTable->RegisterDataSet(networkTableContext, prop); - } - } - - // Network binding table - lua_pop(lua, 1); // Stack: ... SomePropertyInThePropertiesTable - } - - // Pop this PropertiesTable's property - lua_pop(lua, 1); - - // If the property is networked, we don't want to copy it over into the table. - if (isNetworkedProperty) - { - continue; - } - } - else - { - // Remove the value we just pushed onto the stack - lua_pop(lua, 1); - } - } - lua_pushlstring(lua, prop->m_name.c_str(), prop->m_name.length()); if (prop->Write(*m_context)) { @@ -1157,7 +978,7 @@ namespace AzFramework return true; }; - serializeContext->Class() + serializeContext->Class() ->Version(3, converter) ->Field("ContextID", &ScriptComponent::m_contextId) ->Field("Properties", &ScriptComponent::m_properties) @@ -1174,8 +995,6 @@ namespace AzFramework AZ::ScriptProperties::Reflect(reflection); } } - - ScriptNetBindingTable::Reflect(reflection); } //========================================================================= diff --git a/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.h b/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.h index 4d15bc527d..8294f3849c 100644 --- a/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.h +++ b/Code/Framework/AzFramework/AzFramework/Script/ScriptComponent.h @@ -20,8 +20,6 @@ #include #include -#include - namespace AZ { class ScriptProperty; @@ -37,8 +35,6 @@ namespace AzToolsFramework namespace AzFramework { - class ScriptNetBindingTable; - struct ScriptCompileRequest; using WriteFunction = AZStd::function< AZ::Outcome(const ScriptCompileRequest&, AZ::IO::GenericStream& in, AZ::IO::GenericStream& out) >; @@ -92,15 +88,13 @@ namespace AzFramework class ScriptComponent : public AZ::Component , private AZ::Data::AssetBus::Handler - , public AzFramework::NetBindable { friend class AzToolsFramework::Components::ScriptEditorComponent; public: - static const char* NetRPCFieldName; static const char* DefaultFieldName; - AZ_COMPONENT(AzFramework::ScriptComponent, "{8D1BC97E-C55D-4D34-A460-E63C57CD0D4B}", NetBindable); + AZ_COMPONENT(AzFramework::ScriptComponent, "{8D1BC97E-C55D-4D34-A460-E63C57CD0D4B}", AZ::Component); /// \red ComponentDescriptor::Reflect static void Reflect(AZ::ReflectContext* reflection); @@ -116,7 +110,6 @@ namespace AzFramework // Methods used for unit tests AZ::ScriptProperty* GetScriptProperty(const char* propertyName); - const AZ::ScriptProperty* GetNetworkedScriptProperty(const char* propertyName) const; protected: ScriptComponent(const ScriptComponent&) = delete; @@ -133,13 +126,6 @@ namespace AzFramework void OnAssetReloaded(AZ::Data::Asset asset) override; ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - // NetBindable - GridMate::ReplicaChunkPtr GetNetworkBinding() override; - void SetNetworkBinding(GridMate::ReplicaChunkPtr chunk) override; - void UnbindFromNetwork() override; - ////////////////////////////////////////////////////////////////////////// - /// Load script (unless already by other instances) and creates the script instance into the VM void LoadScript(); /// Removes the script instance and unloads the script (unless needed by other instances) @@ -152,8 +138,6 @@ namespace AzFramework void CreateEntityTable(); void DestroyEntityTable(); - void CreateNetworkBindingTable(int baseStackIndex, int entityStackIndex); - void CreatePropertyGroup(const ScriptPropertyGroup& group, int propertyGroupTableIndex, int parentIndex, int metatableIndex, bool isRoot); AZ::ScriptContext* m_context; ///< Context in which the script will be running @@ -161,7 +145,6 @@ namespace AzFramework AZ::Data::Asset m_script; ///< Reference to the script asset used for this component. int m_table; ///< Cached table index ScriptPropertyGroup m_properties; ///< List with all properties that were tweaked in the editor and should override values in the m_sourceScriptName class inside m_script. - ScriptNetBindingTable* m_netBindingTable; ///< Table that will hold our networked script values, and manage callbacks }; } // namespace AZ diff --git a/Code/Framework/AzFramework/AzFramework/Script/ScriptMarshal.cpp b/Code/Framework/AzFramework/AzFramework/Script/ScriptMarshal.cpp deleted file mode 100644 index f02e050e74..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Script/ScriptMarshal.cpp +++ /dev/null @@ -1,573 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include -#include - -#include "AzFramework/Script/ScriptMarshal.h" - -namespace AzFramework -{ - //////////////////////////// - // ScriptPropertyMarshaler - //////////////////////////// - - template - bool UnmarshalGenericType(AZ::DynamicSerializableField& serializableField, GridMate::ReadBuffer& rb) - { - bool valueChanged = true; - - GridMate::Marshaler serializableFieldMarshaler; - - // Store the old value, to compare with the unmarshaled value, to signal - T oldValue = (*serializableField.Get()); - - serializableFieldMarshaler.Unmarshal(serializableField,rb); - - // If our type hasn't changed, compare the values. - if (serializableField.m_typeId == T::TYPEINFO_Uuid()) - { - valueChanged = !(oldValue == (*serializableField.Get())); - } - - return valueChanged; - } - - class ScriptPropertyTableMarshalerHelper - { - public: - template - static void MarshalScriptPropertyGenericMap(const ScriptPropertyMarshaler& scriptPropertyMarshaler, GridMate::WriteBuffer& wb, const AZ::ScriptPropertyTable* scriptPropertyTable) - { - GridMate::Marshaler sizeMarshaler; - - auto mapIter = scriptPropertyTable->m_genericMapping.find(T::TYPEINFO_Uuid()); - - if (mapIter != scriptPropertyTable->m_genericMapping.end()) - { - AZ::ScriptPropertyGenericClassMapImpl* genericClassKeyMap = static_cast*>(mapIter->second); - - auto& valueMap = genericClassKeyMap->GetPairMapping(); - - // We will write out all of our keys. Since it is easier to write out nil values for the properties. - sizeMarshaler.Marshal(wb,static_cast(valueMap.size())); - - GridMate::Marshaler keyMarshaler; - - for (auto& mapPair : valueMap) - { - keyMarshaler.Marshal(wb,mapPair.first); - scriptPropertyMarshaler.Marshal(wb,mapPair.second.m_valueProperty); - } - } - else - { - sizeMarshaler.Marshal(wb,0); - } - } - - template - static bool UnmarshalScriptPropertyGenericMap(const ScriptPropertyMarshaler& scriptPropertyMarshaler, AZ::ScriptPropertyTable* scriptPropertyTable, GridMate::ReadBuffer& rb) - { - bool valueChanged = false; - - AZ::SerializeContext* useContext = nullptr; - EBUS_EVENT_RESULT(useContext, AZ::ComponentApplicationBus, GetSerializeContext); - - if (useContext) - { - const AZ::SerializeContext::ClassData* classData = useContext->FindClassData(T::TYPEINFO_Uuid()); - - if (classData && classData->m_factory) - { - auto mapIter = scriptPropertyTable->m_genericMapping.find(T::TYPEINFO_Uuid()); - - if (mapIter != scriptPropertyTable->m_genericMapping.end()) - { - // This whole thing is an in-place map update. - // to try to minimize the number of allocations. We try to re-use objects as much as possible. - // - // Two phase approach: Step one, update all of the existing properties, while keeping track of all of the used keys. - // Step two, go through and delete any unupdated keys from the mapping. - AZ::ScriptPropertyGenericClassMapImpl* genericClassKeyMap = static_cast*>(mapIter->second); - - AZStd::unordered_set newKeys; - - GridMate::Marshaler sizeMarshaler; - - AZ::u32 mapSize; - sizeMarshaler.Unmarshal(mapSize,rb); - - auto& valueMap = genericClassKeyMap->GetPairMapping(); - - GridMate::Marshaler keyMarshaler; - - for (unsigned int i=0; i < mapSize; ++i) - { - T propertyKey; - keyMarshaler.Unmarshal(propertyKey,rb); - - newKeys.insert(propertyKey); - - auto valueIter = valueMap.find(propertyKey); - - if (valueIter != valueMap.end()) - { - if (scriptPropertyMarshaler.UnmarshalToPointer(valueIter->second.m_valueProperty,rb)) - { - valueChanged = true; - } - } - else - { - valueChanged = true; - - AZ::ScriptProperty* newValueProperty = nullptr; - scriptPropertyMarshaler.UnmarshalToPointer(newValueProperty,rb); - - AZ::ScriptPropertyGenericClassMap::MapValuePair newPair; - - newPair.m_valueProperty = newValueProperty; - - T* serializableData = nullptr; - serializableData = static_cast(classData->m_factory->Create("ScriptProperty")); - (*serializableData) = propertyKey; - - AZ::ScriptPropertyGenericClass* genericPropertyClass = aznew AZ::ScriptPropertyGenericClass(); - - genericPropertyClass->Set(serializableData); - - newPair.m_keyProperty = genericPropertyClass; - - valueMap.emplace(propertyKey,newPair); - } - } - - // Delete all of the unused keyes from the map - auto valueIter = valueMap.begin(); - - while (valueIter != valueMap.end()) - { - if (newKeys.find(valueIter->first) == newKeys.end()) - { - valueChanged = true; - valueIter->second.Destroy(); - valueIter = valueMap.erase(valueIter); - } - else - { - ++valueIter; - } - } - } - } - } - - return valueChanged; - } - }; - - - - void ScriptPropertyMarshaler::Marshal(GridMate::WriteBuffer& wb, AZ::ScriptProperty*const& property) const - { - GridMate::Marshaler typeMarshaler; - GridMate::Marshaler idMarshaler; - GridMate::Marshaler nameMarshaler; - - if (property == nullptr) - { - // Write out a nil property if we have a nullptr property - nameMarshaler.Marshal(wb,""); - idMarshaler.Marshal(wb,0); - typeMarshaler.Marshal(wb,AZ::ScriptPropertyNil::RTTI_Type()); - return; - } - - // Common points: - // Always going to marshal the uuid of the type(or something similar) - // so we know what type we have on the other side. - // - // Next need to pass along the name field. - const AZ::Uuid& typeId = azrtti_typeid(property); - - nameMarshaler.Marshal(wb,property->m_name); - idMarshaler.Marshal(wb,property->m_id); - - // Method 1: - // - Allow each ScriptProperty to marshal itself. - // - Currently unavailable since the ScriptProperties live in AZCore - // and the WriteBuffer is in GridMate. - // cont.Marshal(wb); - - // Method 2: - // - Process all of our known marshallable types and use the appropriate marshaler - if (typeId == AZ::ScriptPropertyBoolean::RTTI_Type()) - { - typeMarshaler.Marshal(wb,typeId); - - GridMate::Marshaler boolMarshaler; - boolMarshaler.Marshal(wb,static_cast(property)->m_value); - } - else if (typeId == AZ::ScriptPropertyNumber::RTTI_Type()) - { - typeMarshaler.Marshal(wb,typeId); - - GridMate::Marshaler doubleMarshaler; - doubleMarshaler.Marshal(wb,static_cast(property)->m_value); - } - else if (typeId == AZ::ScriptPropertyString::RTTI_Type()) - { - typeMarshaler.Marshal(wb,typeId); - - GridMate::Marshaler stringMarshaler; - stringMarshaler.Marshal(wb,static_cast(property)->m_value); - } - else if (typeId == AZ::ScriptPropertyGenericClass::RTTI_Type()) - { - const AZ::DynamicSerializableField& serializableField = static_cast(property)->GetSerializableField(); - - typeMarshaler.Marshal(wb,typeId); - - GridMate::Marshaler serializableFieldMarshaler; - serializableFieldMarshaler.Marshal(wb,serializableField); - } - else if (typeId == AZ::ScriptPropertyTable::TYPEINFO_Uuid()) - { - const AZ::ScriptPropertyTable* scriptPropertyTable = static_cast(property); - - typeMarshaler.Marshal(wb,typeId); - - GridMate::Marshaler mapSizeMarshaler; - mapSizeMarshaler.Marshal(wb,static_cast(scriptPropertyTable->m_indexMapping.size())); - - GridMate::Marshaler indexMarshaler; - - // Currently only support integers as keys inside of the table. - for (auto& mapPair : scriptPropertyTable->m_indexMapping) - { - indexMarshaler.Marshal(wb,mapPair.first); - this->Marshal(wb,mapPair.second); - } - - mapSizeMarshaler.Marshal(wb, static_cast(scriptPropertyTable->m_keyMapping.size())); - - GridMate::Marshaler hashMarshaler; - - for (auto& mapPair : scriptPropertyTable->m_keyMapping) - { - // For hashed values. The name of the script property is the same as the hash it should be using. - // We still synchronize the Crc so we can unmarshal in place on the other side. - hashMarshaler.Marshal(wb,mapPair.first); - Marshal(wb,mapPair.second); - } - - // EntityId's - ScriptPropertyTableMarshalerHelper::MarshalScriptPropertyGenericMap((*this), wb, scriptPropertyTable); - } - else - { - typeMarshaler.Marshal(wb,AZ::ScriptPropertyNil::RTTI_Type()); - } - } - - bool ScriptPropertyMarshaler::UnmarshalToPointer(AZ::ScriptProperty*& target, GridMate::ReadBuffer& rb) const - { - bool typeChanged = false; - AZ::Uuid typeId; - AZ::u64 id; - AZStd::string name; - - GridMate::Marshaler typeMarshaler; - GridMate::Marshaler idMarshaler; - GridMate::Marshaler nameMarshaler; - - nameMarshaler.Unmarshal(name,rb); - idMarshaler.Unmarshal(id,rb); - typeMarshaler.Unmarshal(typeId,rb); - - if (target == nullptr || typeId != azrtti_typeid(target)) - { - typeChanged = true; - - AZ::ScriptProperty* actualScriptProperty = nullptr; - if (typeId == AZ::ScriptPropertyBoolean::RTTI_Type()) - { - actualScriptProperty = aznew AZ::ScriptPropertyBoolean(); - } - else if (typeId == AZ::ScriptPropertyNumber::RTTI_Type()) - { - actualScriptProperty = aznew AZ::ScriptPropertyNumber(); - } - else if (typeId == AZ::ScriptPropertyString::RTTI_Type()) - { - actualScriptProperty = aznew AZ::ScriptPropertyString(); - } - else if (typeId == AZ::ScriptPropertyGenericClass::RTTI_Type()) - { - actualScriptProperty = aznew AZ::ScriptPropertyGenericClass(); - } - else if (typeId == AZ::ScriptPropertyTable::RTTI_Type()) - { - actualScriptProperty = aznew AZ::ScriptPropertyTable(); - } - else - { - actualScriptProperty = aznew AZ::ScriptPropertyNil(); - } - - actualScriptProperty->m_name = name; - delete target; - - target = actualScriptProperty; - } - - // Update our ID - target->m_id = id; - - // Method 1: - // - Allow each ScriptProperty to unmarshal itself - // - Currently unavailable since the ScriptProperties live in AZCore - // and the WriteBuffer is in GridMate - // actualScriptProperty->Unmarshal(rb); - // - // Method 2: - // - Process all of our known marshallable types and use the appropriate marshaler - - bool valueChanged = false; - - if (typeId == AZ::ScriptPropertyBoolean::RTTI_Type()) - { - AZ::ScriptPropertyBoolean* booleanProperty = static_cast(target); - bool oldValue = booleanProperty->m_value; - - GridMate::Marshaler boolMarshaler; - boolMarshaler.Unmarshal(booleanProperty->m_value,rb); - - valueChanged = !(oldValue == booleanProperty->m_value); - } - else if (typeId == AZ::ScriptPropertyString::RTTI_Type()) - { - AZ::ScriptPropertyString* stringProperty = static_cast(target); - AZStd::string oldValue = stringProperty->m_value; - - GridMate::Marshaler stringMarshaler; - stringMarshaler.Unmarshal(stringProperty->m_value,rb); - - valueChanged = !(oldValue == stringProperty->m_value); - } - else if (typeId == AZ::ScriptPropertyNumber::RTTI_Type()) - { - AZ::ScriptPropertyNumber* numberProperty = static_cast(target); - double oldValue = numberProperty->m_value; - - GridMate::Marshaler numberMarshaler; - numberMarshaler.Unmarshal(numberProperty->m_value,rb); - - valueChanged = !(oldValue == numberProperty->m_value); - } - else if (typeId == AZ::ScriptPropertyGenericClass::RTTI_Type()) - { - AZ::ScriptPropertyGenericClass* genericProperty = static_cast(target); - - AZ::DynamicSerializableField& serializableField = genericProperty->m_value; - - AZ::DynamicSerializableField oldField; - - oldField.CopyDataFrom(serializableField); - - GridMate::Marshaler serializableFieldMarshaler; - serializableFieldMarshaler.Unmarshal(serializableField,rb); - - // If our type hasn't changed, compare the values. - valueChanged = !oldField.IsEqualTo(serializableField); - } - else if (typeId == AZ::ScriptPropertyTable::RTTI_Type()) - { - AZ::ScriptPropertyTable* scriptPropertyTable = static_cast(target); - GridMate::Marshaler mapSizeMarshaler; - - // Unmarshal all of the indexes properties - { - AZ::u32 mapSize = 0; - mapSizeMarshaler.Unmarshal(mapSize, rb); - - AZStd::unordered_set newIndexes; - GridMate::Marshaler indexMarshaler; - - for (AZ::u32 i=0; i < mapSize; ++i) - { - int index = 0; - indexMarshaler.Unmarshal(index,rb); - - auto mapIter = scriptPropertyTable->m_indexMapping.find(index); - - if (mapIter != scriptPropertyTable->m_indexMapping.end()) - { - if (UnmarshalToPointer(mapIter->second,rb)) - { - valueChanged = true; - } - } - else - { - valueChanged = true; - - AZ::ScriptProperty* scriptProperty = nullptr; - UnmarshalToPointer(scriptProperty,rb); - auto insertResult = scriptPropertyTable->m_indexMapping.emplace(index,scriptProperty); - mapIter = insertResult.first; - } - - if (mapIter->second == nullptr || azrtti_istypeof(mapIter->second)) - { - valueChanged = true; - - delete mapIter->second; - scriptPropertyTable->m_indexMapping.erase(mapIter); - } - else - { - newIndexes.insert(index); - } - } - - auto mapIter = scriptPropertyTable->m_indexMapping.begin(); - - while (mapIter != scriptPropertyTable->m_indexMapping.end()) - { - if (newIndexes.find(mapIter->first) == newIndexes.end()) - { - valueChanged = true; - - delete mapIter->second; - mapIter = scriptPropertyTable->m_indexMapping.erase(mapIter); - } - else - { - ++mapIter; - } - } - } - - // Unmarshal all of the hashed values - { - AZ::u32 mapSize = 0; - mapSizeMarshaler.Unmarshal(mapSize, rb); - - AZStd::unordered_set newHashes; - GridMate::Marshaler hashMarshaler; - - for (AZ::u32 i=0; i < mapSize; ++i) - { - AZ::u32 newHash; - hashMarshaler.Unmarshal(newHash, rb); - - auto mapIter = scriptPropertyTable->m_keyMapping.find(newHash); - - if (mapIter != scriptPropertyTable->m_keyMapping.end()) - { - if (UnmarshalToPointer(mapIter->second,rb)) - { - valueChanged = true; - } - } - else - { - valueChanged = true; - - AZ::ScriptProperty* scriptProperty = nullptr; - UnmarshalToPointer(scriptProperty,rb); - auto emplaceResult = scriptPropertyTable->m_keyMapping.emplace(newHash,scriptProperty); - mapIter = emplaceResult.first; - } - - if (mapIter->second == nullptr || azrtti_istypeof(mapIter->second)) - { - valueChanged = true; - - delete mapIter->second; - scriptPropertyTable->m_keyMapping.erase(mapIter); - } - else - { - newHashes.insert(newHash); - } - } - - auto mapIter = scriptPropertyTable->m_keyMapping.begin(); - - while (mapIter != scriptPropertyTable->m_keyMapping.end()) - { - if (newHashes.find(mapIter->first) == newHashes.end()) - { - valueChanged = true; - - delete mapIter->second; - mapIter = scriptPropertyTable->m_keyMapping.erase(mapIter); - } - else - { - ++mapIter; - } - } - } - - // Unmarshal all of the generic properties - - // EntityId's - if (ScriptPropertyTableMarshalerHelper::UnmarshalScriptPropertyGenericMap((*this), scriptPropertyTable, rb)) - { - valueChanged = true; - } - } - - return typeChanged || valueChanged; - } - - //////////////////////////// - // ScriptPropertyThrottler - //////////////////////////// - - ScriptPropertyThrottler::ScriptPropertyThrottler() - : m_isDirty(true) - { - - } - - void ScriptPropertyThrottler::SignalDirty() - { - m_isDirty = true; - } - - bool ScriptPropertyThrottler::WithinThreshold(AZ::ScriptProperty* newValue) const - { - return newValue == nullptr || !m_isDirty; - } - - void ScriptPropertyThrottler::UpdateBaseline(AZ::ScriptProperty* baseline) - { - (void)baseline; - - m_isDirty = false; - } -} diff --git a/Code/Framework/AzFramework/AzFramework/Script/ScriptMarshal.h b/Code/Framework/AzFramework/AzFramework/Script/ScriptMarshal.h deleted file mode 100644 index c13749d46b..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Script/ScriptMarshal.h +++ /dev/null @@ -1,94 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef AZFRAMEWORK_SCRIPT_SCRIPTMARSHAL_H -#define AZFRAMEWORK_SCRIPT_SCRIPTMARSHAL_H - -#include - -#include - -namespace AZ -{ - class ScriptProperty; -} - -namespace AzFramework -{ - /** - * Specalized helper marshaler for ScriptProperty class - */ - class ScriptPropertyMarshaler - { - public: - void Marshal(GridMate::WriteBuffer& wb, AZ::ScriptProperty*const& cont) const; - bool UnmarshalToPointer(AZ::ScriptProperty*& target, GridMate::ReadBuffer& rb) const; - }; - - class ScriptPropertyThrottler - { - public: - ScriptPropertyThrottler(); - - void SignalDirty(); - bool WithinThreshold(AZ::ScriptProperty* newValue) const; - void UpdateBaseline(AZ::ScriptProperty* baseline); - - private: - bool m_isDirty; - }; - - /** - * Specialized helper marshaler to help with the vector creation/destruction - */ - class ScriptRPCMarshaler - { - public: - - typedef AZStd::vector< AZ::ScriptProperty* > Container; - - ScriptRPCMarshaler() - { - } - - AZ_FORCE_INLINE void Marshal(GridMate::WriteBuffer& wb, const Container& container) const - { - AZ_Assert(container.size() < USHRT_MAX, "Container has too many elements for marshaling!"); - AZ::u16 size = static_cast(container.size()); - wb.Write(size); - for (const auto& i : container) - { - m_marshaler.Marshal(wb, i); - } - } - - AZ_FORCE_INLINE void Unmarshal(Container& container, GridMate::ReadBuffer& rb) const - { - container.clear(); - - AZ::u16 size; - rb.Read(size); - container.reserve(size); - - for (AZ::u16 i = 0; i < size; ++i) - { - AZ::ScriptProperty* readProperty = nullptr; - m_marshaler.UnmarshalToPointer(readProperty, rb); - container.insert(container.end(), readProperty); - } - } - - protected: - ScriptPropertyMarshaler m_marshaler; - }; -} - -#endif diff --git a/Code/Framework/AzFramework/AzFramework/Script/ScriptNetBindings.cpp b/Code/Framework/AzFramework/AzFramework/Script/ScriptNetBindings.cpp deleted file mode 100644 index 45690eac01..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Script/ScriptNetBindings.cpp +++ /dev/null @@ -1,1427 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include - -#include -#include - -#include - -extern "C" { -# include -# include -} - -namespace AzFramework -{ - namespace Internal - { - static int NetBinding__IsAuthoritative(lua_State* lua) - { - ScriptNetBindingTable* netBindingTable = reinterpret_cast(lua_touserdata(lua,lua_upvalueindex(1))); - - //AZ_Assert(netBindingTable != nullptr && netBindingTable->GetScriptContext(),"Missing or misconfigured ScriptNetBindingTable as upvalue in lua_cclosure"); - if (netBindingTable && netBindingTable->GetScriptContext()) - { - lua_pushboolean(lua,netBindingTable->IsMaster()); - } - else - { - // If we don't have a net binding table, or a a script context, return true - // since we likely are the master. - lua_pushboolean(lua,true); - } - - return 1; - } - - static int NetBinding__IsMaster(lua_State* lua) - { - AZ_Warning("ScriptNetBindings", false, "IsMaster deprecated for the more lexical consistent IsAuthoritative"); - return NetBinding__IsAuthoritative(lua); - } - - static int NetBinding__CallRPC(lua_State* lua) - { - ScriptNetBindingTable* netBindingTable = reinterpret_cast(lua_touserdata(lua,lua_upvalueindex(1))); - - AZ_Error("ScriptComponent", netBindingTable != nullptr,"Missing ScriptNetBindingTable as upvalue in lua_cclosure"); - AZ_Error("ScriptComponent", netBindingTable == nullptr || netBindingTable->GetScriptContext(),"Missing ScriptNetBindingTable as upvalue in lua_cclosure"); - if (netBindingTable && netBindingTable->GetScriptContext()) - { - AZ::ScriptContext* context = netBindingTable->GetScriptContext(); - - AZ::ScriptDataContext stackContext; - bool validIndex = context->ReadStack(stackContext); - - if (validIndex) - { - netBindingTable->InvokeRPC(stackContext); - } - } - - return 0; - } - } - - ////////////////////////// - // ScriptPropertyDataSet - ////////////////////////// - - // Necessary since the field doesn't make a copy, but keeps the actual literal. - // But overall :( - - const char* ScriptPropertyDataSet::GetDataSetName() - { - static size_t s_chunkIndex = 0; - static const char* s_nameArray[] = { - "DataSet1","DataSet2","DataSet3","DataSet4","DataSet5", - "DataSet6","DataSet7","DataSet8","DataSet9","DataSet10", - "DataSet11","DataSet12","DataSet13","DataSet14","DataSet15", - "DataSet16","DataSet17","DataSet18","DataSet19","DataSet20", - "DataSet21","DataSet22","DataSet23","DataSet24","DataSet25", - "DataSet26","DataSet27","DataSet28","DataSet29","DataSet30", - "DataSet31","DataSet32" - }; - - if ((s_chunkIndex >= AZ_ARRAY_SIZE(s_nameArray)) && (AZ_ARRAY_SIZE(s_nameArray) >= 0)) - { - s_chunkIndex = s_chunkIndex % AZ_ARRAY_SIZE(s_nameArray); - } - - return s_nameArray[s_chunkIndex++]; - } - - ScriptPropertyDataSet::ScriptPropertyDataSet() - : ScriptPropertyDataSetType(GetDataSetName()) - , m_reserver(nullptr) - { - } - - ScriptPropertyDataSet::~ScriptPropertyDataSet() - { - AZ::FunctionalScriptProperty* functionalScriptProperty = azrtti_cast(Get()); - - if (functionalScriptProperty) - { - functionalScriptProperty->DisableInPlaceControls(); - functionalScriptProperty->RemoveWatcher(this); - } - } - - void ScriptPropertyDataSet::Reserve(ScriptNetBindingTable::NetworkedTableValue* reserver) - { - AZ_Error("ScriptComponent",m_reserver == nullptr || reserver == m_reserver, "Trying to reserve the same DataSet for two NetworkedTableVaules."); - - if (m_reserver == nullptr) - { - m_reserver = reserver; - AZ::ScriptPropertyWatcherBus::Handler::BusConnect(this); - - AZ::FunctionalScriptProperty* functionalScriptProperty = azrtti_cast(Get()); - - if (functionalScriptProperty) - { - functionalScriptProperty->EnableInPlaceControls(); - functionalScriptProperty->AddWatcher(this); - } - } - } - - void ScriptPropertyDataSet::Release(ScriptNetBindingTable::NetworkedTableValue* reserver) - { - AZ_Error("ScriptComponent",m_reserver == nullptr || m_reserver == reserver, "Incorrect NetworkedTableValue trying to release a reserver DataSet."); - if (m_reserver == reserver) - { - m_reserver = nullptr; - AZ::ScriptPropertyWatcherBus::Handler::BusDisconnect(this); - } - } - - bool ScriptPropertyDataSet::IsReserved() const - { - return m_reserver != nullptr; - } - - bool ScriptPropertyDataSet::UpdateScriptProperty(AZ::ScriptDataContext& scriptDataContext, const AZStd::string& propertyName) - { - bool wroteValue = false; - - Modify([&](AZ::ScriptProperty*& scriptProperty) - { - wroteValue = true; - if (scriptProperty == nullptr || !scriptProperty->TryRead(scriptDataContext,-1)) - { - AZ::ScriptProperty* newPropertyType = scriptDataContext.ConstructScriptProperty(-1,propertyName.c_str()); - - delete scriptProperty; - - if (newPropertyType == nullptr) - { - scriptProperty = aznew AZ::ScriptPropertyNil(); - } - else - { - scriptProperty = newPropertyType; - } - - AZ::FunctionalScriptProperty* functionalScriptProperty = azrtti_cast(newPropertyType); - - if (functionalScriptProperty) - { - functionalScriptProperty->EnableInPlaceControls(); - functionalScriptProperty->AddWatcher(this); - } - } - - m_throttler.SignalDirty(); - - return wroteValue; - }); - - return wroteValue; - } - - void ScriptPropertyDataSet::SetScriptProperty(AZ::ScriptProperty* scriptProperty) - { - Modify([&](AZ::ScriptProperty*& dataSetProperty) - { - AZ::ScriptProperty* tempProperty = dataSetProperty; - - if (scriptProperty == nullptr) - { - if (tempProperty) - { - dataSetProperty = aznew AZ::ScriptPropertyNil(tempProperty->m_name.c_str()); - } - else - { - dataSetProperty = aznew AZ::ScriptPropertyNil(); - } - } - else - { - dataSetProperty = scriptProperty; - } - - if (tempProperty) - { - delete tempProperty; - } - - AZ::FunctionalScriptProperty* functionalScriptProperty = azrtti_cast(dataSetProperty); - - if (functionalScriptProperty) - { - functionalScriptProperty->EnableInPlaceControls(); - functionalScriptProperty->AddWatcher(this); - } - - m_throttler.SignalDirty(); - - return true; - }); - } - - void ScriptPropertyDataSet::OnObjectModified() - { - m_throttler.SignalDirty(); - SetDirty(); - } - - //////////////////////// - // EntityScriptContext - //////////////////////// - - ScriptNetBindingTable::EntityScriptContext::EntityScriptContext() - : m_scriptContext(nullptr) - , m_entityTableRegistryIndex(LUA_REFNIL) - { - } - - void ScriptNetBindingTable::EntityScriptContext::Unload() - { - m_scriptContext = nullptr; - m_entityTableRegistryIndex = LUA_REFNIL; - } - - bool ScriptNetBindingTable::EntityScriptContext::HasEntityTableRegistryIndex() const - { - return m_entityTableRegistryIndex != LUA_REFNIL; - } - - int ScriptNetBindingTable::EntityScriptContext::GetEntityTableRegistryIndex() const - { - return m_entityTableRegistryIndex; - } - - bool ScriptNetBindingTable::EntityScriptContext::HasScriptContext() const - { - return m_scriptContext != nullptr; - } - - AZ::ScriptContext* ScriptNetBindingTable::EntityScriptContext::GetScriptContext() const - { - return m_scriptContext; - } - - void ScriptNetBindingTable::EntityScriptContext::ConfigureContext(AZ::ScriptContext* scriptContext, int entityTableRegistryIndex) - { - m_scriptContext = scriptContext; - m_entityTableRegistryIndex = entityTableRegistryIndex; - - AZ_Error("ScriptComponent",SanityCheckContext(),"Invalid configuration given to ScriptNetBindingTable"); - } - - bool ScriptNetBindingTable::EntityScriptContext::SanityCheckContext() const - { - bool isSane = HasScriptContext(); - - if (isSane) - { - // We want to check if our reference is actually pointing to a table - // which we will assume is our entity table - lua_State* nativeContext = m_scriptContext->NativeContext(); - - lua_rawgeti(nativeContext,LUA_REGISTRYINDEX,m_entityTableRegistryIndex); - isSane = lua_istable(nativeContext,-1); - lua_pop(nativeContext,1); - } - - return isSane; - } - - //////////////////////// - // NetworkedTableValue - //////////////////////// - - ScriptNetBindingTable::NetworkedTableValue::NetworkedTableValue(AZ::ScriptProperty* initialValue) - : m_shimmedScriptProperty(initialValue) - , m_dataSet(nullptr) - , m_forcedDataSetIndex(-1) - , m_functionReference(LUA_REFNIL) - { - AZ::FunctionalScriptProperty* functionalScriptProperty = azrtti_cast(initialValue); - - if (functionalScriptProperty) - { - functionalScriptProperty->EnableInPlaceControls(); - } - } - - ScriptNetBindingTable::NetworkedTableValue::~NetworkedTableValue() - { - // Always want to release our dataset if we have one when we are destroyed. - // - // We do not want to delete our proeprty thought, since we might have been copied over. - if (m_dataSet) - { - m_dataSet->Release(this); - } - } - - void ScriptNetBindingTable::NetworkedTableValue::Destroy() - { - if (m_shimmedScriptProperty) - { - delete m_shimmedScriptProperty; - m_shimmedScriptProperty = nullptr; - } - - if (m_dataSet) - { - m_dataSet->Release(this); - } - } - - bool ScriptNetBindingTable::NetworkedTableValue::HasDataSet() const - { - return m_dataSet != nullptr; - } - - void ScriptNetBindingTable::NetworkedTableValue::RegisterDataSet(ScriptPropertyDataSet* dataSet) - { - m_dataSet = dataSet; - - if (m_dataSet) - { - if (m_shimmedScriptProperty) - { - m_dataSet->SetScriptProperty(m_shimmedScriptProperty); - m_shimmedScriptProperty = nullptr; - } - - m_dataSet->Reserve(this); - } - } - - void ScriptNetBindingTable::NetworkedTableValue::UnbindFromDataSet() - { - if (m_dataSet) - { - // Take ownership of the DataSet script property into our shimmed value - // - // If we are the master, we can take ownership and set the data set value to null - if (m_dataSet->CanSet()) - { - m_shimmedScriptProperty = m_dataSet->Get(); - m_dataSet->Set(nullptr); - } - // Otherwise, we need to clone the data in the data set since we can't modify it and we need to avoid a double deletion. - else - { - AZ::ScriptProperty* scriptProperty = m_dataSet->Get(); - m_shimmedScriptProperty = scriptProperty->Clone(); - } - - m_dataSet->Release(this); - m_dataSet = nullptr; - } - } - - ScriptPropertyDataSet* ScriptNetBindingTable::NetworkedTableValue::GetDataSet() const - { - return m_dataSet; - } - - bool ScriptNetBindingTable::NetworkedTableValue::HasForcedDataSetIndex() const - { - return m_forcedDataSetIndex >= 1; - } - - void ScriptNetBindingTable::NetworkedTableValue::SetForcedDataSetIndex(int index) - { - m_forcedDataSetIndex = index; - } - - int ScriptNetBindingTable::NetworkedTableValue::GetForcedDataSetIndex() const - { - return m_forcedDataSetIndex; - } - - bool ScriptNetBindingTable::NetworkedTableValue::HasCallback() const - { - return m_functionReference != LUA_REFNIL; - } - - void ScriptNetBindingTable::NetworkedTableValue::RegisterCallback(int functionReference) - { - AZ_Warning("ScriptComponent",!HasCallback() || functionReference == LUA_REFNIL,"Overriding an already registered callback for a DataSet."); - - m_functionReference = functionReference; - } - - void ScriptNetBindingTable::NetworkedTableValue::ReleaseCallback(AZ::ScriptContext& scriptContext) - { - if (HasCallback()) - { - scriptContext.ReleaseCached(m_functionReference); - m_functionReference = LUA_REFNIL; - } - } - - void ScriptNetBindingTable::NetworkedTableValue::InvokeCallback(EntityScriptContext& entityContext, const GridMate::TimeContext& timeContext) - { - (void)timeContext; - - AZ::ScriptContext* scriptContext = entityContext.GetScriptContext(); - - AZ_Warning("ScriptComponent",scriptContext,"DataSetCallback given null ScriptContext."); - AZ_Warning("ScriptComponent",entityContext.HasEntityTableRegistryIndex(),"DataSetCallback given invalid entity table reference"); - if (scriptContext && entityContext.HasEntityTableRegistryIndex()) - { - AZ::ScriptDataContext callContext; - - if (scriptContext->CallCached(m_functionReference,callContext)) - { - callContext.PushArgFromRegistryIndex(entityContext.GetEntityTableRegistryIndex()); - callContext.CallExecute(); - } - } - } - - bool ScriptNetBindingTable::NetworkedTableValue::AssignValue(AZ::ScriptDataContext& scriptDataContext, const AZStd::string& propertyName) - { - bool assignedValue = false; - if (HasDataSet()) - { - assignedValue = GetDataSet()->UpdateScriptProperty(scriptDataContext, propertyName); - } - else - { - if (m_shimmedScriptProperty == nullptr || !m_shimmedScriptProperty->TryRead(scriptDataContext,-1)) - { - delete m_shimmedScriptProperty; - m_shimmedScriptProperty = nullptr; - m_shimmedScriptProperty = scriptDataContext.ConstructScriptProperty(-1,propertyName.c_str()); - - AZ::FunctionalScriptProperty* functionalScriptProperty = azrtti_cast(m_shimmedScriptProperty); - - if (functionalScriptProperty) - { - functionalScriptProperty->EnableInPlaceControls(); - } - } - - assignedValue = (m_shimmedScriptProperty != nullptr); - } - - return assignedValue; - } - - bool ScriptNetBindingTable::NetworkedTableValue::InspectValue(AZ::ScriptContext* scriptContext) const - { - AZ::ScriptProperty* inspectedProperty = m_shimmedScriptProperty; - - if (HasDataSet()) - { - inspectedProperty = GetDataSet()->Get(); - } - - bool inspectedValue = false; - - if (inspectedProperty) - { - inspectedValue = inspectedProperty->Write((*scriptContext)); - } - - if (!inspectedValue) - { - inspectedValue = true; - - AZ::ScriptPropertyNil nilProperty; - nilProperty.Write((*scriptContext)); - } - - return inspectedValue; - } - - ////////////// - // RPCHelper - ////////////// - - // Maybe make this guy create the table himself? - // Encapsulate the whole binding process in here. - ScriptNetBindingTable::RPCBindingHelper::RPCBindingHelper() - : m_masterReference(LUA_REFNIL) - , m_proxyReference(LUA_REFNIL) - { - } - - ScriptNetBindingTable::RPCBindingHelper::~RPCBindingHelper() - { - } - - void ScriptNetBindingTable::RPCBindingHelper::ReleaseTableIndex(AZ::ScriptContext& scriptContext) - { - if (m_masterReference != LUA_REFNIL) - { - scriptContext.ReleaseCached(m_masterReference); - m_masterReference = LUA_REFNIL; - } - - if (m_proxyReference != LUA_REFNIL) - { - scriptContext.ReleaseCached(m_proxyReference); - m_proxyReference = LUA_REFNIL; - } - } - - bool ScriptNetBindingTable::RPCBindingHelper::IsValid() const - { - // Proxy is optional, so we only care about having the master index. - return m_masterReference != LUA_REFNIL; - } - - void ScriptNetBindingTable::RPCBindingHelper::SetMasterFunction(int masterReference) - { - AZ_Error("ScriptComponent",m_masterReference == LUA_REFNIL || masterReference == LUA_REFNIL, "Trying to rebind RPC master callback"); - - if (m_masterReference == LUA_REFNIL || masterReference == LUA_REFNIL) - { - m_masterReference = masterReference; - } - } - - bool ScriptNetBindingTable::RPCBindingHelper::InvokeMaster(EntityScriptContext& entityScriptContext, const ScriptRPCMarshaler::Container& params) - { - if (!entityScriptContext.HasScriptContext()) - { - AZ_Error("ScriptComponent",false,"Invoking RPC with invalid ScriptContext"); - return false; - } - - bool allowRPC = false; - - if (m_masterReference != LUA_REFNIL) - { - AZ::ScriptDataContext callContext; - AZ::ScriptContext* scriptContext = entityScriptContext.GetScriptContext(); - - if (scriptContext->CallCached(m_masterReference,callContext)) - { - callContext.PushArgFromRegistryIndex(entityScriptContext.GetEntityTableRegistryIndex()); - - for (AZ::ScriptProperty* property : params) - { - callContext.PushArgScriptProperty(property); - } - - if (callContext.CallExecute()) - { - bool hasResult = false; - if (callContext.GetNumResults() == 1) - { - hasResult = callContext.ReadResult(0,allowRPC); - } - - AZ_Assert(hasResult,"Master RPC function needs to return a boolean value"); - (void)hasResult; - } - } - - } - - return allowRPC; - } - - void ScriptNetBindingTable::RPCBindingHelper::SetProxyFunction(int proxyReference) - { - AZ_Error("ScriptComponent",m_proxyReference == LUA_REFNIL || proxyReference == LUA_REFNIL,"Trying to rebind an RPC Proxy call."); - - if (m_proxyReference == LUA_REFNIL || proxyReference == LUA_REFNIL) - { - m_proxyReference = proxyReference; - } - } - - void ScriptNetBindingTable::RPCBindingHelper::InvokeProxy(EntityScriptContext& entityScriptContext, const ScriptRPCMarshaler::Container& params) - { - if (!entityScriptContext.HasScriptContext()) - { - AZ_Error("ScriptComponent",false,"Trying to call a callback without a script context."); - return; - } - - AZ_Warning("ScriptComponent",m_proxyReference != LUA_REFNIL,"Trying to invoke an RPC on the proxy without a callback being set."); - if (m_proxyReference != LUA_REFNIL) - { - AZ::ScriptDataContext callContext; - AZ::ScriptContext* scriptContext = entityScriptContext.GetScriptContext(); - - if (scriptContext->CallCached(m_proxyReference,callContext)) - { - callContext.PushArgFromRegistryIndex(entityScriptContext.GetEntityTableRegistryIndex()); - - for (AZ::ScriptProperty* property : params) - { - callContext.PushArgScriptProperty(property); - } - - callContext.CallExecute(); - } - } - } - - ////////////////////////// - // ScriptNetBindingTable - ////////////////////////// - void ScriptNetBindingTable::Reflect(AZ::ReflectContext* reflection) - { - NetworkContext* netContext = azrtti_cast(reflection); - - if (netContext) - { - // Using old method until we update the network context to allow for array offests. - // Or find a better way to handle the script replica chunk - if (!GridMate::ReplicaChunkDescriptorTable::Get().FindReplicaChunkDescriptor(GridMate::ReplicaChunkClassId(ScriptComponentReplicaChunk::GetChunkName()))) - { - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - } - } - } - - // Template specialization for the ConvertPropertyArrayToTable GenericClass support to deal with extra memory copies. - template<> - AZ::ScriptPropertyTable* ScriptNetBindingTable::ConvertPropertyArrayToTable(AZ::ScriptPropertyGenericClassArray* arrayProperty) - { - AZ::ScriptPropertyTable* scriptPropertyTable = aznew AZ::ScriptPropertyTable(arrayProperty->m_name.c_str()); - - AZ::ScriptPropertyGenericClass emptyGenericClass; - - for (unsigned int i=0; i < arrayProperty->m_values.size(); ++i) - { - // Offset by 1 to deal with lua 1 indexing. - // Table will make a clone of our object. - // - // To avoid pointlessly double copying the data. Insert the empty class. - scriptPropertyTable->SetTableValue(i+1, &emptyGenericClass); - - // Then do a find for the class back, to load up the data into the final object directly. - AZ::ScriptPropertyGenericClass* ownedClass = static_cast(scriptPropertyTable->FindTableValue(i+1)); - - const AZ::DynamicSerializableField& serializableField = arrayProperty->m_values[i]; - - ownedClass->Set(serializableField); - } - - return scriptPropertyTable; - } - - ScriptNetBindingTable::ScriptNetBindingTable() - { - } - - ScriptNetBindingTable::~ScriptNetBindingTable() - { - - } - - void ScriptNetBindingTable::Unload() - { - // Unbind our elements from our script context. - if (m_entityScriptContext.HasScriptContext()) - { - AZ::ScriptContext& scriptContext = (*m_entityScriptContext.GetScriptContext()); - for (NetworkedTableMap::value_type& tablePair : m_networkedTable) - { - NetworkedTableValue& tableValue = tablePair.second; - tableValue.ReleaseCallback(scriptContext); - } - - for (RPCHelperMap::value_type& rpcPair : m_rpcHelperMap) - { - RPCBindingHelper& bindingHelper = rpcPair.second; - bindingHelper.ReleaseTableIndex(scriptContext); - } - } - - // Destroy the table values, since they might contain some memory - for (NetworkedTableMap::value_type& tablePair : m_networkedTable) - { - tablePair.second.Destroy(); - } - - m_networkedTable.clear(); - m_rpcHelperMap.clear(); - - m_entityScriptContext.Unload(); - } - - void ScriptNetBindingTable::CreateNetworkBindingTable(AZ::ScriptContext* scriptContext, int baseTableIndex, int entityTableIndex) - { - (void)baseTableIndex; - - lua_State* nativeContext = scriptContext->NativeContext(); - - lua_pushliteral(nativeContext,"IsMaster"); - lua_pushlightuserdata(nativeContext,this); - lua_pushcclosure(nativeContext, &Internal::NetBinding__IsMaster,1); - lua_rawset(nativeContext,entityTableIndex); - - lua_pushliteral(nativeContext,"IsAuthoritative"); - lua_pushlightuserdata(nativeContext,this); - lua_pushcclosure(nativeContext, &Internal::NetBinding__IsAuthoritative,1); - lua_rawset(nativeContext,entityTableIndex); - - lua_pushstring(nativeContext,ScriptComponent::NetRPCFieldName); - lua_createtable(nativeContext,0,0); - - int rpcTableIndex = lua_gettop(nativeContext); - - // Read the stack - AZ::ScriptDataContext stackContext; - if (scriptContext->ReadStack(stackContext)) - { - // Inspect the element we know to be our table context - AZ::ScriptDataContext entityDataContext; - if (stackContext.IsTable(baseTableIndex) && stackContext.InspectTable(baseTableIndex,entityDataContext)) - { - // Find our RPC table inside of baseTableIndex - int tableIndex = 0; - if (entityDataContext.PushTableElement(ScriptComponent::NetRPCFieldName,&tableIndex)) - { - // If it's a table, we want to inspect it. - AZ::ScriptDataContext rpcTable; - if (entityDataContext.IsTable(tableIndex) && entityDataContext.InspectTable(tableIndex,rpcTable)) - { - // Iterate over the fields here, and register and RPC for each element inside of that table. - int fieldIndex; - int elementIndex; - const char* fieldName; - - while (rpcTable.InspectNextElement(elementIndex, fieldName, fieldIndex)) - { - if (fieldName != nullptr) - { - RegisterRPC(rpcTable,fieldName,elementIndex,rpcTableIndex); - } - } - } - } - } - } - - lua_rawset(nativeContext,entityTableIndex); - } - - void ScriptNetBindingTable::FinalizeNetworkTable(AZ::ScriptContext* scriptContext, int entityTableRegistryIndex) - { - m_entityScriptContext.ConfigureContext(scriptContext, entityTableRegistryIndex); - - if (m_replicaChunk) - { - AssignDataSets(); - } - } - - AZ::ScriptContext* ScriptNetBindingTable::GetScriptContext() const - { - return m_entityScriptContext.GetScriptContext(); - } - - bool ScriptNetBindingTable::IsMaster() const - { - return (m_replicaChunk != nullptr) ? m_replicaChunk->IsMaster() : true; - } - - bool ScriptNetBindingTable::AssignTableValue(AZ::ScriptDataContext& stackDataContext) - { - bool wroteValue = false; - AZ_Error("ScriptComponent",stackDataContext.GetScriptContext() == m_entityScriptContext.GetScriptContext(),"Trying to use a ScriptNetBindings in the wrong context."); - - // We do not want to allow assignments on proxy replicas - // since that information will be discarded anyway. - if ((m_replicaChunk && !m_replicaChunk->IsMaster()) || (stackDataContext.GetScriptContext() != m_entityScriptContext.GetScriptContext())) - { - return false; - } - - AZStd::string key; - - if (stackDataContext.ReadValue(-2,key)) - { - NetworkedTableValue* networkedTableValue = FindTableValue(key); - - // If we don't have the value, it means we aren't trying to network it. - if (networkedTableValue) - { - if (m_replicaChunk && !networkedTableValue->HasDataSet()) - { - ScriptComponentReplicaChunk* scriptChunk = static_cast(m_replicaChunk.get()); - - scriptChunk->AssignDataSet((*networkedTableValue)); - } - - wroteValue = networkedTableValue->AssignValue(stackDataContext,key); - } - } - - return wroteValue; - } - - bool ScriptNetBindingTable::InspectTableValue(AZ::ScriptDataContext& stackContext) const - { - bool readValue = false; - AZStd::string key; - - if (stackContext.ReadValue(-1,key)) - { - AZ::ScriptContext* scriptContext = stackContext.GetScriptContext(); - - if (scriptContext) - { - const NetworkedTableValue* networkTableValue = FindTableValue(key); - - if (networkTableValue) - { - readValue = networkTableValue->InspectValue((stackContext.GetScriptContext())); - - // Default to nil if we have a network table value registered, but couldn't - // inspect it for some reason. - if (!readValue) - { - readValue = true; - static AZ::ScriptPropertyNil s_nilValue; - s_nilValue.Write((*scriptContext)); - } - } - } - else - { - AZ_Error("ScriptComponent",false,"Trying to read value into invalid ScriptContext"); - } - } - - return readValue; - } - - bool ScriptNetBindingTable::RegisterDataSet(AZ::ScriptDataContext& networkTableContext, AZ::ScriptProperty* scriptProperty) - { - if (scriptProperty == nullptr) - { - AZ_Error("ScriptComponent",false,"Trying to Create a dataset for a null script property."); - return false; - } - - AZ::Uuid typeId = azrtti_typeid(scriptProperty); - - if ( typeId == azrtti_typeid() - || typeId == azrtti_typeid()) - { - AZ_Error("ScriptComponent",false,"Using unsupported type for ScriptProperty(%s) net binding. Value will not be networked.", scriptProperty->m_name.c_str()); - return false; - } - - // If we've already got an item inside of our network table. - // We need to surpress that problem, since it may happen when we reload the script - if (m_networkedTable.find(scriptProperty->m_name) != m_networkedTable.end()) - { - return true; - } - - int elementIndex; - bool enabled = false; - bool handledProperty = false; - - if (networkTableContext.PushTableElement("Enabled",&elementIndex)) - { - // If we have the enabled field and it's not a boolean. - // Assume false. - if (networkTableContext.IsBoolean(elementIndex)) - { - // If we didn't read in the enabled value, assume it's false. - if (!networkTableContext.ReadValue(elementIndex,enabled)) - { - enabled = false; - } - } - } - else - { - // If we don't have an enabled field, assume that we want to be bound. - enabled = true; - } - - if (enabled) - { - NetworkedTableValue networkedTableValue; - - // Convert the property arrays over to a table to simplify the logic flow of detecting - // the various changes, and to more readily support what the general LUA syntax. - if (typeId == azrtti_typeid()) - { - AZ::ScriptPropertyBooleanArray* sourceArray = static_cast(scriptProperty); - - networkedTableValue = NetworkedTableValue(ConvertPropertyArrayToTable(sourceArray)); - } - else if (typeId == azrtti_typeid()) - { - AZ::ScriptPropertyNumberArray* sourceArray = static_cast(scriptProperty); - - networkedTableValue = NetworkedTableValue(ConvertPropertyArrayToTable(sourceArray)); - } - else if (typeId == azrtti_typeid()) - { - AZ::ScriptPropertyStringArray* sourceArray = static_cast(scriptProperty); - - networkedTableValue = NetworkedTableValue(ConvertPropertyArrayToTable(sourceArray)); - } - else if (typeId == azrtti_typeid()) - { - AZ::ScriptPropertyGenericClassArray* sourceArray = static_cast(scriptProperty); - - networkedTableValue = NetworkedTableValue(ConvertPropertyArrayToTable(sourceArray)); - } - else - { - networkedTableValue = NetworkedTableValue(scriptProperty->Clone()); - } - - if (networkTableContext.PushTableElement("OnNewValue", &elementIndex)) - { - if (networkTableContext.IsFunction(elementIndex)) - { - networkedTableValue.RegisterCallback( networkTableContext.CacheValue(elementIndex) ); - } - } - - if (networkTableContext.PushTableElement("ForceIndex",&elementIndex)) - { - if (networkTableContext.IsNumber(elementIndex)) - { - int forcedDataSetIndex = 0; - if (networkTableContext.ReadValue(elementIndex,forcedDataSetIndex)) - { - AZ_Error("ScriptComponent",forcedDataSetIndex >= 1 && forcedDataSetIndex <= ScriptComponentReplicaChunk::k_maxScriptableDataSets,"Trying to force Property (%s) to an invalid DataSetIndex(%i).",scriptProperty->m_name.c_str(),forcedDataSetIndex); - if(forcedDataSetIndex >= 1 && forcedDataSetIndex <= ScriptComponentReplicaChunk::k_maxScriptableDataSets) - { - networkedTableValue.SetForcedDataSetIndex(forcedDataSetIndex); - } - } - else - { - AZ_Error("ScriptComponent",false,"Trying to force Property (%s) to unknown DataSetIndex. Ignoring field.", scriptProperty->m_name.c_str()); - } - } - } - - AZStd::pair insertResult = m_networkedTable.insert(NetworkedTableMap::value_type(scriptProperty->m_name,networkedTableValue)); - - // If we failed to insert the object, we need to destroy the networked table value. - // To avoid leaking memory - if (!insertResult.second) - { - networkedTableValue.Destroy(); - } - - handledProperty = true; - } - - return handledProperty; - } - - bool ScriptNetBindingTable::InvokeRPC(AZ::ScriptDataContext& stackContext) - { - lua_State* nativeContext = stackContext.GetScriptContext()->NativeContext(); - - bool invokedRPC = false; - AZStd::string rpcName; - - // Assuming this is coming from an __call metamethod - // the lua stack will look as follows - // 1 - Table - // n - Params - if (stackContext.IsTable(1)) - { - // Get the RPC name - lua_pushliteral(nativeContext,"_rpcName"); - lua_gettable(nativeContext,1); - - if (stackContext.IsString(-1)) - { - if (stackContext.ReadValue(-1,rpcName)) - { - // Pop off the key value we just read in; It's no longer necessary - lua_pop(nativeContext,1); - - RPCHelperMap::iterator rpcIter = m_rpcHelperMap.find(rpcName); - - if (rpcIter != m_rpcHelperMap.end()) - { - bool foundParams = true; - - ScriptRPCMarshaler::Container paramContainer; - - // Need to start at 2, since 1 is our table. - for (int i=2; i <= lua_gettop(nativeContext); ++i) - { - AZ::ScriptProperty* property = stackContext.ConstructScriptProperty(i,"param"); - - if (property) - { - paramContainer.push_back(property); - } - else - { - foundParams = false; - break; - } - } - - // The script marshaler will clean up the keys after it has marshalled them out. - if (foundParams) - { - invokedRPC = true; - - if (m_replicaChunk) - { - ScriptComponentReplicaChunk* scriptReplicaChunk = static_cast(m_replicaChunk.get()); - scriptReplicaChunk->m_scriptRPC(rpcName,paramContainer); - } - else - { - rpcIter->second.InvokeMaster(m_entityScriptContext,paramContainer); - } - } - else - { - for (AZ::ScriptProperty* property : paramContainer) - { - delete property; - } - - paramContainer.clear(); - } - } - } - else - { - // We failed to read, so we need to pop the value we pushed off the stack. - lua_pop(nativeContext,1); - } - } - else - { - // Pop off the value we added to the top of the stack - lua_pop(nativeContext,1); - } - } - - return invokedRPC; - } - - void ScriptNetBindingTable::RegisterRPC(AZ::ScriptDataContext& rpcTableContext, const AZStd::string& rpc, int elementIndex, int tableStackIndex) - { - if (rpcTableContext.IsTable(elementIndex)) - { - RPCBindingHelper helper; - - AZ::ScriptDataContext rpcContext; - if (rpcTableContext.InspectTable(elementIndex,rpcContext)) - { - int functionIndex = 0; - if (rpcContext.PushTableElement("OnMaster",&functionIndex)) - { - helper.SetMasterFunction(rpcContext.CacheValue(functionIndex)); - } - else - { - AZ_Error("ScriptNetBinding", false, "Could not find OnMaster function for RPC (%s).", rpc.c_str()); - } - - if (rpcContext.PushTableElement("OnProxy",&functionIndex)) - { - helper.SetProxyFunction(rpcContext.CacheValue(functionIndex)); - } - } - else - { - AZ_Error("ScriptNetBinding", false, "Could inspect table for RPC (%s).", rpc.c_str()); - } - - if (helper.IsValid()) - { - lua_State* nativeContext = rpcTableContext.GetScriptContext()->NativeContext(); - - // Create the RPC Table inside of our entity table to allow for functions to be called on it. - // - lua_pushlstring(nativeContext,rpc.c_str(),rpc.size()); - lua_createtable(nativeContext,0,1); - - // Set up a name field inside of the table - lua_pushliteral(nativeContext,"_rpcName"); - lua_pushlstring(nativeContext,rpc.c_str(),rpc.size()); - lua_rawset(nativeContext,-3); - - // - lua_createtable(nativeContext,0,1); - lua_pushliteral(nativeContext,"__call"); - lua_pushlightuserdata(nativeContext, this); - lua_pushcclosure(nativeContext, &Internal::NetBinding__CallRPC,1); - lua_rawset(nativeContext,-3); - - lua_setmetatable(nativeContext,-2); - // - - lua_rawset(nativeContext,tableStackIndex); - // - - m_rpcHelperMap.insert(RPCHelperMap::value_type(rpc,helper)); - } - } - } - - GridMate::ReplicaChunkPtr ScriptNetBindingTable::GetNetworkBinding() - { - m_replicaChunk = GridMate::CreateReplicaChunk(); - m_replicaChunk->SetHandler(this); - - if (m_entityScriptContext.HasScriptContext()) - { - AssignDataSets(); - } - - return m_replicaChunk; - } - - void ScriptNetBindingTable::SetNetworkBinding(GridMate::ReplicaChunkPtr chunk) - { - m_replicaChunk = chunk; - m_replicaChunk->SetHandler(this); - - if (m_entityScriptContext.HasScriptContext()) - { - AssignDataSets(); - } - } - - void ScriptNetBindingTable::UnbindFromNetwork() - { - if (m_replicaChunk) - { - m_replicaChunk->SetHandler(nullptr); - - for (NetworkedTableMap::value_type& tablePair : m_networkedTable) - { - tablePair.second.UnbindFromDataSet(); - } - - m_replicaChunk = nullptr; - } - } - - void ScriptNetBindingTable::OnPropertyUpdate(AZ::ScriptProperty*const& scriptProperty, const GridMate::TimeContext& tc) - { - AZ_Error("ScriptComponent",m_replicaChunk != nullptr,"DataSet callback method called without ReplicaChunk present."); - - if (scriptProperty && m_replicaChunk) - { - ScriptComponentReplicaChunk* scriptReplicaChunk = static_cast(m_replicaChunk.get()); - - NetworkedTableValue* tableValue = FindTableValue(scriptProperty->m_name); - - if (tableValue) - { - if (!tableValue->HasDataSet()) - { - scriptReplicaChunk->AssignDataSetForProperty((*tableValue),scriptProperty); - AZ_Error("ScriptComponent",tableValue->HasDataSet(),"Unable to bind received ScriptProperty to DataSet."); - } - else - { - AZ_Error("ScriptComponent",scriptReplicaChunk->SanityCheckDataSet(scriptProperty,tableValue->GetDataSet()),"Mismatch between DataSet being chagned and mapping to dataset index."); - } - - if (tableValue->HasCallback()) - { - tableValue->InvokeCallback(m_entityScriptContext,tc); - } - } - else - { - AZ_Error("ScriptComponent",false,"Receiving update for unknown ScriptProperty."); - } - } - } - - bool ScriptNetBindingTable::OnInvokeRPC(AZStd::string functionName, AZStd::vector< AZ::ScriptProperty*> params, const GridMate::RpcContext& rpcContext) - { - (void)rpcContext; - - bool canProxyExecute = false; - AZ_Error("ScriptComponent",m_replicaChunk,"Receiving RPC callback with null ReplicaChunk."); - - RPCHelperMap::iterator rpcIter = m_rpcHelperMap.find(functionName); - - if (rpcIter != m_rpcHelperMap.end()) - { - RPCBindingHelper& rpcHelper = rpcIter->second; - - if (m_replicaChunk == nullptr || m_replicaChunk->IsMaster()) - { - canProxyExecute = rpcHelper.InvokeMaster(m_entityScriptContext,params); - } - else - { - // The canProxyExecute return value is meaningless on proxies. - rpcHelper.InvokeProxy(m_entityScriptContext,params); - } - } - - return canProxyExecute; - } - - const AZ::ScriptProperty* ScriptNetBindingTable::FindScriptProperty(const AZStd::string& name) const - { - const NetworkedTableValue* networkedTableValue = FindTableValue(name); - return networkedTableValue ? networkedTableValue->GetShimmedScriptProperty() : nullptr; - } - - void ScriptNetBindingTable::AssignDataSets() - { - if (m_replicaChunk) - { - ScriptComponentReplicaChunk* scriptComponentChunk = static_cast(m_replicaChunk.get()); - - // Going to do this in two passes, first to do all of the forced ones, then all of the arbitrary ones. - for (NetworkedTableMap::value_type& tablePair : m_networkedTable) - { - if (tablePair.second.HasForcedDataSetIndex() && !tablePair.second.HasDataSet()) - { - if (!scriptComponentChunk->AssignDataSet(tablePair.second)) - { - // Remove the forced DataSet index since it was invalid. - // Second pass will assign this an arbitrary one. - tablePair.second.SetForcedDataSetIndex(-1); - } - } - } - - for (NetworkedTableMap::value_type& tablePair : m_networkedTable) - { - // Try to assign everything that doesn't already have a dataset. - if (!tablePair.second.HasDataSet()) - { - scriptComponentChunk->AssignDataSet(tablePair.second); - } - } - } - } - - ScriptNetBindingTable::NetworkedTableValue* ScriptNetBindingTable::FindTableValue(const AZStd::string& name) - { - NetworkedTableValue* retVal = nullptr; - NetworkedTableMap::iterator tableIter = m_networkedTable.find(name); - - if (tableIter != m_networkedTable.end()) - { - retVal = &(tableIter->second); - } - - return retVal; - } - - const ScriptNetBindingTable::NetworkedTableValue* ScriptNetBindingTable::FindTableValue(const AZStd::string& name) const - { - const NetworkedTableValue* retVal = nullptr; - NetworkedTableMap::const_iterator tableIter = m_networkedTable.find(name); - - if (tableIter != m_networkedTable.end()) - { - retVal = &(tableIter->second); - } - - return retVal; - } - - //////////////////////////////// - // ScriptComponentReplicaChunk - //////////////////////////////// - - ScriptComponentReplicaChunk::ScriptComponentReplicaChunk() - : m_scriptRPC("ScriptRPC") - , m_enabledDataSetMask(0) - { - } - - ScriptComponentReplicaChunk::~ScriptComponentReplicaChunk() - { - for (int i=0; i < k_maxScriptableDataSets; ++i) - { - ScriptPropertyDataSet& dataSet = m_propertyDataSets[i]; - - dataSet.Modify([](AZ::ScriptProperty*& scriptProperty) - { - delete scriptProperty; - scriptProperty = nullptr; - return false; - }); - } - } - - bool ScriptComponentReplicaChunk::IsReplicaMigratable() - { - return true; - } - - AZ::u32 ScriptComponentReplicaChunk::CalculateDirtyDataSetMask(GridMate::MarshalContext& marshalContext) - { - if ((marshalContext.m_marshalFlags & GridMate::ReplicaMarshalFlags::ForceDirty)) - { - return m_enabledDataSetMask; - } - - return GridMate::ReplicaChunkBase::CalculateDirtyDataSetMask(marshalContext); - } - - bool ScriptComponentReplicaChunk::AssignDataSet(ScriptNetBindingTable::NetworkedTableValue& helper) - { - bool assigned = false; - - if (helper.HasForcedDataSetIndex()) - { - int testIndex = helper.GetForcedDataSetIndex() - 1; - - if (testIndex >= 0 && testIndex < k_maxScriptableDataSets) - { - ScriptPropertyDataSet* testDataSet = &m_propertyDataSets[testIndex]; - - if (!testDataSet->IsReserved()) - { - assigned = true; - helper.RegisterDataSet(testDataSet); - m_enabledDataSetMask |= (1 << testIndex); - } - else - { - AZ_Error("ScriptComponent",false,"Trying to register a networked value to a previously used DataSet."); - } - } - else - { - AZ_Error("ScriptComponent",false,"Trying to register a table value to an invalid DataSet index."); - } - } - else - { - for (int i=0; i < k_maxScriptableDataSets; ++i) - { - if (!m_propertyDataSets[i].IsReserved()) - { - assigned = true; - helper.RegisterDataSet(&m_propertyDataSets[i]); - m_enabledDataSetMask |= (1 << i); - break; - } - } - - AZ_Error("ScriptComponent",assigned, "Trying to create more then %i datasets for a script",k_maxScriptableDataSets); - } - - return assigned; - } - - void ScriptComponentReplicaChunk::AssignDataSetForProperty(ScriptNetBindingTable::NetworkedTableValue& helper, AZ::ScriptProperty* targetProperty) - { - AZ_Error("ScriptComponent",!IsMaster(),"Binding table value to specified DataSet on Master(Master should be making that choice, not responding to a choice)."); - - if (!IsMaster()) - { - for (int i=0; i < k_maxScriptableDataSets; ++i) - { - if (m_propertyDataSets[i].Get() == targetProperty) - { - helper.RegisterDataSet(&m_propertyDataSets[i]); - m_enabledDataSetMask |= (1 << i); - break; - } - } - } - } - - bool ScriptComponentReplicaChunk::SanityCheckDataSet(AZ::ScriptProperty* targetProperty, ScriptPropertyDataSet* assumedDataSet) - { - bool isSane = false; - - for (int i=0; i < k_maxScriptableDataSets; ++i) - { - if (m_propertyDataSets[i].Get() == targetProperty) - { - isSane = &(m_propertyDataSets[i]) == assumedDataSet; - break; - } - } - - return isSane; - } -} diff --git a/Code/Framework/AzFramework/AzFramework/Script/ScriptNetBindings.h b/Code/Framework/AzFramework/AzFramework/Script/ScriptNetBindings.h deleted file mode 100644 index eec28b71b0..0000000000 --- a/Code/Framework/AzFramework/AzFramework/Script/ScriptNetBindings.h +++ /dev/null @@ -1,320 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef AZFRAMEWORK_SCRIPT_NET_BINDINGS_H -#define AZFRAMEWORK_SCRIPT_NET_BINDINGS_H - -#include -#include - -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace AzFramework -{ - class ScriptPropertyDataSet; - class ScriptComponentReplicaChunk; - - // ScriptNetBindingTable will act as the go between for the ScriptComponent and the Replica's. - // It will also allow for holding of values in the case where you haven't been bound to a replica chunk yet and the - // script tries to interact with something that is networked. - // - // Allows for scripts to be re-used seamlessly in a offline vs online scenario(and support for going from offline to online), - // including RPCs(will alawys call the master version if offline) - class ScriptNetBindingTable - : public GridMate::ReplicaChunkInterface - { - private: - friend class ScriptComponentReplicaChunk; - friend class ScriptPropertyDataSet; - - // Helper struct to keep track of a a ScriptContext - // and the entityTableReference. Mainly used for - // calling in to functions in LUA where we want - // to push in the table reference as the first parameter - struct EntityScriptContext - { - public: - EntityScriptContext(); - - void Unload(); - - bool HasEntityTableRegistryIndex() const; - int GetEntityTableRegistryIndex() const; - - bool HasScriptContext() const; - AZ::ScriptContext* GetScriptContext() const; - - void ConfigureContext(AZ::ScriptContext* scriptContext, int entityTableRegistryIndex); - - private: - - bool SanityCheckContext() const; - - AZ::ScriptContext* m_scriptContext; - int m_entityTableRegistryIndex; - }; - - class NetworkedTableValue; - friend NetworkedTableValue; - - typedef AZStd::unordered_map NetworkedTableMap; - - class RPCBindingHelper; - friend RPCBindingHelper; - - typedef AZStd::unordered_map RPCHelperMap; - - // Helper class that will wrap up our interactions with the actual stored value - // to hide the general use case of if we are connected to a replica or not. - // - // Additionally this will serve as a holding ground for a 'networked' - // value that doesn't have a dataset. - // - // Lastly holds onto the Callback references. - class NetworkedTableValue - { - public: - AZ_CLASS_ALLOCATOR(NetworkedTableValue, AZ::SystemAllocator, 0); - - NetworkedTableValue(AZ::ScriptProperty* initialValue = nullptr); - ~NetworkedTableValue(); - - void Destroy(); - - // Methods to register this value to a chunk - bool HasDataSet() const; - void RegisterDataSet(ScriptPropertyDataSet* dataSet); - void UnbindFromDataSet(); - ScriptPropertyDataSet* GetDataSet() const; - - // Information kept in order to force these values to use a particular dataset for debugging. - bool HasForcedDataSetIndex() const; - void SetForcedDataSetIndex(int index); - int GetForcedDataSetIndex() const; - - // Callback functions - bool HasCallback() const; - void RegisterCallback(int functionReference); - void ReleaseCallback(AZ::ScriptContext& scriptContext); - void InvokeCallback(EntityScriptContext& scriptContext, const GridMate::TimeContext& timeContext); - - bool AssignValue(AZ::ScriptDataContext& scriptDataContext, const AZStd::string& propertyName); - bool InspectValue(AZ::ScriptContext* scriptContext) const; - - // Methods used for unit tests - const AZ::ScriptProperty* GetShimmedScriptProperty() const { return m_shimmedScriptProperty; } - private: - - // This value will be used if we have a networked property, but don't have a valid chunk yet. - // Works as a temporary store, which will be resolved once we get assigned to a DataSet - AZ::ScriptProperty* m_shimmedScriptProperty; - - // The data set we are bound to - ScriptPropertyDataSet* m_dataSet; - int m_forcedDataSetIndex; - - int m_functionReference; - }; - - // Future thoughts - // - Move the actual RPC meta table creation - // into this guy - class RPCBindingHelper - { - public: - AZ_CLASS_ALLOCATOR(RPCBindingHelper, AZ::SystemAllocator, 0); - - RPCBindingHelper(); - ~RPCBindingHelper(); - - void ReleaseTableIndex(AZ::ScriptContext& scriptContext); - - bool IsValid() const; - - void SetMasterFunction(int masterReference); - bool InvokeMaster(EntityScriptContext& entityScriptContext, const ScriptRPCMarshaler::Container& params); - - void SetProxyFunction(int masterReference); - void InvokeProxy(EntityScriptContext& entityScriptContext, const ScriptRPCMarshaler::Container& params); - - private: - int m_masterReference; - int m_proxyReference; - }; - - public: - AZ_CLASS_ALLOCATOR(ScriptNetBindingTable, AZ::SystemAllocator, 0); - static void Reflect(AZ::ReflectContext* reflect); - - ScriptNetBindingTable(); - ~ScriptNetBindingTable(); - - void Unload(); - - void CreateNetworkBindingTable(AZ::ScriptContext* scriptContext, int baseTableIndex, int entityTableIndex); - void FinalizeNetworkTable(AZ::ScriptContext* scriptContext, int entityTableRegistryIndex); - - AZ::ScriptContext* GetScriptContext() const; - - bool IsMaster() const; - - ////////////////////////////////////////////////////////////////////////////////////////////////////// - // DataSet Functionality - // - // Called when the script wants to bind a function callback to when - // a value changes - // - // Might change this to just be register DataSet - bool RegisterDataSet(AZ::ScriptDataContext& stackContext, AZ::ScriptProperty* scriptProperty); - - // Called when the script wants to assign a value to the script value - bool AssignTableValue(AZ::ScriptDataContext& stackContext); - - // Called when the script wants to know the value of a script value. - bool InspectTableValue(AZ::ScriptDataContext& stackContext) const; - ////////////////////////////////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////////////////////////////////// - /// RPC Functionality - void RegisterRPC(AZ::ScriptDataContext& rpcTableContext, const AZStd::string& rpcName, int elementIndex, int tableStackIndex); - bool InvokeRPC(AZ::ScriptDataContext& stackContext); - ////////////////////////////////////////////////////////////////////////////////////////////////////// - - // Netbinding Interface duplication here to be called from the ScriptComponent - GridMate::ReplicaChunkPtr GetNetworkBinding(); - void SetNetworkBinding(GridMate::ReplicaChunkPtr chunk); - void UnbindFromNetwork(); - - void OnPropertyUpdate(AZ::ScriptProperty*const& scriptProperty, const GridMate::TimeContext& tc); - bool OnInvokeRPC(AZStd::string functionName, AZStd::vector< AZ::ScriptProperty*> properties, const GridMate::RpcContext& rpcContext); - - // Methods used for unit tests - const AZ::ScriptProperty* FindScriptProperty(const AZStd::string& name) const; - - - private: - - void RegisterMetaTableCache(); - - template - AZ::ScriptPropertyTable* ConvertPropertyArrayToTable(PropertyArrayType* arrayProperty) - { - AZ::ScriptPropertyTable* scriptPropertyTable = aznew AZ::ScriptPropertyTable(arrayProperty->m_name.c_str()); - - PropertyType propertyType; - - for (unsigned int i=0; i < arrayProperty->m_values.size(); ++i) - { - propertyType.m_value = arrayProperty->m_values[i]; - - // Offset by 1 to deal with lua 1 indexing. - // Table will make a clone of our object. - scriptPropertyTable->SetTableValue(i+1, &propertyType); - } - - return scriptPropertyTable; - } - - void AssignDataSets(); - - NetworkedTableValue* FindTableValue(const AZStd::string& name); - const NetworkedTableValue* FindTableValue(const AZStd::string& name) const; - - EntityScriptContext m_entityScriptContext; - - GridMate::ReplicaChunkPtr m_replicaChunk; - - NetworkedTableMap m_networkedTable; - RPCHelperMap m_rpcHelperMap; - }; - - // Typedeffing out the RPC and DataSet definitions. - typedef GridMate::Rpc< GridMate::RpcArg< AZStd::string >, GridMate::RpcArg< ScriptRPCMarshaler::Container, ScriptRPCMarshaler > >::BindInterface ScriptPropertyRPC; - typedef GridMate::DataSet::BindInterface ScriptPropertyDataSetType; - - class ScriptComponentReplicaChunk; - - // Specialized DataSet used by the ScriptProperties, just to add some wrapped around functionality - // and to allow me to manipulate the DataSet throttler in order to properly manage a dirty flag - class ScriptPropertyDataSet - : public ScriptPropertyDataSetType - , public AZ::ScriptPropertyWatcherBus::Handler - , public AZ::ScriptPropertyWatcher - { - private: - friend class ScriptComponentReplicaChunk; - friend class ScriptNetBindingTable::NetworkedTableValue; - - const char* GetDataSetName(); - - public: - ScriptPropertyDataSet(); - ~ScriptPropertyDataSet(); - bool IsReserved() const; - - bool UpdateScriptProperty(AZ::ScriptDataContext& scriptDataContext, const AZStd::string& propertyName); - void SetScriptProperty(AZ::ScriptProperty* scriptProperty); - - void OnObjectModified() override; - - private: - void Reserve(ScriptNetBindingTable::NetworkedTableValue* reserver); - void Release(ScriptNetBindingTable::NetworkedTableValue* reserver); - - ScriptNetBindingTable::NetworkedTableValue* m_reserver; - }; - - // The actual ReplicaChunk that the script will use - class ScriptComponentReplicaChunk - : public GridMate::ReplicaChunkBase - { - public: - AZ_CLASS_ALLOCATOR(ScriptComponentReplicaChunk, AZ::SystemAllocator,0); - static const int k_maxScriptableDataSets = GM_MAX_DATASETS_IN_CHUNK; - - static const char* GetChunkName() { return "ScriptComponentReplicaChunk"; } - - // Might want to add some type of comment field into the various fields so this can be properly parsed - // and determined what we are actually sending. - ScriptComponentReplicaChunk(); - ~ScriptComponentReplicaChunk(); - - bool IsReplicaMigratable() override; - - AZ::u32 CalculateDirtyDataSetMask(GridMate::MarshalContext& marshalContext) override; - - // Called from the Master, will assign the table value to the DataSet specified by the helper. - bool AssignDataSet(ScriptNetBindingTable::NetworkedTableValue& helper); - - // Called from teh Proxy. Will Assign the TableValue to the DataSet that contains the target property - void AssignDataSetForProperty(ScriptNetBindingTable::NetworkedTableValue& helper, AZ::ScriptProperty* targetProperty); - - // Only called inside of an assert, checks that the DataSet that the targetProperty is in is the same as the assumedDataSet - // Used to confirm that we don't get a confusion between master/proxy about which ScriptProperty is assigned to which DataSet. - bool SanityCheckDataSet(AZ::ScriptProperty* targetProperty, ScriptPropertyDataSet* assumedDataSet); - - ScriptPropertyRPC m_scriptRPC; - - private: - AZ::u32 m_enabledDataSetMask; - ScriptPropertyDataSet m_propertyDataSets[k_maxScriptableDataSets]; - }; -} - -#endif diff --git a/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementComponent.cpp b/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementComponent.cpp index e44185bd33..d3ba48d587 100644 --- a/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementComponent.cpp @@ -177,7 +177,7 @@ namespace AzFramework Neighborhood::NeighborReplicaPtr replicaChunk = GridMate::CreateReplicaChunk(session->GetMyMember()->GetId().Compact(), m_component->m_settings->m_persistentName.c_str(), Neighborhood::NEIGHBOR_CAP_LUA_VM | Neighborhood::NEIGHBOR_CAP_LUA_DEBUGGER); replicaChunk->SetDisplayName(m_component->m_settings->m_persistentName.c_str()); replica->AttachReplicaChunk(replicaChunk); - session->GetReplicaMgr()->AddMaster(replica); + session->GetReplicaMgr()->AddPrimary(replica); } } diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 4c95865938..8669b58911 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -407,11 +407,6 @@ namespace AzFramework { if (input->m_state == InputChannel::State::Began) { - if (input->m_state == InputChannel::State::Updated) - { - return; - } - m_translation |= translationFromKey(input->m_channelId); if (m_translation != TranslationType::Nil) { diff --git a/Code/Framework/AzFramework/AzFramework/azframework_files.cmake b/Code/Framework/AzFramework/AzFramework/azframework_files.cmake index 1b1cd49aa7..48b0202a5b 100644 --- a/Code/Framework/AzFramework/AzFramework/azframework_files.cmake +++ b/Code/Framework/AzFramework/AzFramework/azframework_files.cmake @@ -161,26 +161,6 @@ set(FILES Metrics/MetricsPlainTextNameRegistration.h Network/AssetProcessorConnection.cpp Network/AssetProcessorConnection.h - Network/DynamicSerializableFieldMarshaler.h - Network/EntityIdMarshaler.h - Network/InterestManagerComponent.h - Network/InterestManagerComponent.cpp - Network/NetBindable.h - Network/NetBindable.cpp - Network/NetBindingEventsBus.h - Network/NetBindingHandlerBus.h - Network/NetBindingSystemBus.h - Network/NetBindingComponent.h - Network/NetBindingComponent.cpp - Network/NetBindingComponentChunk.h - Network/NetBindingComponentChunk.cpp - Network/NetBindingSystemImpl.h - Network/NetBindingSystemImpl.cpp - Network/NetBindingSystemComponent.h - Network/NetBindingSystemComponent.cpp - Network/NetworkContext.h - Network/NetworkContext.cpp - Network/NetSystemBus.h Network/SocketConnection.cpp Network/SocketConnection.h Logging/LogFile.cpp @@ -203,10 +183,6 @@ set(FILES Script/ScriptDebugAgentBus.h Script/ScriptDebugMsgReflection.cpp Script/ScriptDebugMsgReflection.h - Script/ScriptMarshal.h - Script/ScriptMarshal.cpp - Script/ScriptNetBindings.h - Script/ScriptNetBindings.cpp Script/ScriptRemoteDebugging.cpp Script/ScriptRemoteDebugging.h StreamingInstall/StreamingInstall.h @@ -279,6 +255,7 @@ set(FILES Physics/ClassConverters.cpp Physics/ClassConverters.h Physics/MaterialBus.h + Physics/WindBus.h Process/ProcessCommunicator.cpp Process/ProcessCommunicator.h Process/ProcessWatcher.cpp diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserComponent.cpp index 8d3513cbcb..c505639338 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserComponent.cpp @@ -263,8 +263,6 @@ namespace AzToolsFramework return SourceFileDetails("Icons/AssetBrowser/XML_16.svg"); } - - // this is here to prevent having to include IResourceCompilerHelper, which is in CryCommon. static const char* sourceFormats[] = { ".tif", ".bmp", ".gif", ".jpg", ".jpeg", ".jpe", ".tga", ".png" }; for (unsigned int sourceImageFormatIndex = 0, numSources = AZ_ARRAY_SIZE(sourceFormats); sourceImageFormatIndex < numSources; ++sourceImageFormatIndex) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFrameworkModule.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFrameworkModule.cpp index 373787e7dd..3a84c4249c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFrameworkModule.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFrameworkModule.cpp @@ -52,6 +52,7 @@ #include #include #include +#include #include #include @@ -91,6 +92,7 @@ namespace AzToolsFramework AzToolsFramework::AssetBundleComponent::CreateDescriptor(), AzToolsFramework::SliceDependencyBrowserComponent::CreateDescriptor(), AzToolsFramework::Thumbnailer::ThumbnailerComponent::CreateDescriptor(), + AzToolsFramework::Thumbnailer::ThumbnailerNullComponent::CreateDescriptor(), AzToolsFramework::AssetBrowser::AssetBrowserComponent::CreateDescriptor(), AzToolsFramework::EditorInteractionSystemComponent::CreateDescriptor(), AzToolsFramework::Components::EditorComponentAPIComponent::CreateDescriptor(), diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp index 6b6f1475bb..02243a8c77 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp @@ -282,14 +282,6 @@ namespace AzToolsFramework containerEntity->AddComponent(aznew Prefab::EditorPrefabComponent()); HandleEntitiesAdded({containerEntity}); HandleEntitiesAdded(entities); - - // Update the template of the instance since we modified the entities of the instance by calling HandleEntitiesAdded. - Prefab::PrefabDom serializedInstance; - if (Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(addedInstance, serializedInstance)) - { - m_prefabSystemComponent->UpdatePrefabTemplate(addedInstance.GetTemplateId(), serializedInstance); - } - return addedInstance; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp index b1c5f64ef9..a21c5301aa 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp @@ -270,7 +270,7 @@ namespace AzToolsFramework return parentInstance; } - void InstanceToTemplatePropagator::AddPatchesToLink(PrefabDom& patches, Link& link) + void InstanceToTemplatePropagator::AddPatchesToLink(const PrefabDom& patches, Link& link) { PrefabDom& linkDom = link.GetLinkDom(); PrefabDomValueReference linkPatchesReference = @@ -279,7 +279,14 @@ namespace AzToolsFramework // This logic only covers addition of patches. If patches already exists, the given list of patches must be appended to them. if (!linkPatchesReference.has_value()) { - linkDom.AddMember(rapidjson::StringRef(PrefabDomUtils::PatchesName), patches, linkDom.GetAllocator()); + /* + If the original allocator the patches were created with gets destroyed, then the patches would become garbage in the + linkDom. Since we cannot guarantee the lifecycle of the patch allocators, we are doing a copy of the patches here to + associate them with the linkDom's allocator. + */ + PrefabDom patchesCopy; + patchesCopy.CopyFrom(patches, linkDom.GetAllocator()); + linkDom.AddMember(rapidjson::StringRef(PrefabDomUtils::PatchesName), patchesCopy, linkDom.GetAllocator()); } } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h index ca1f3a7c91..9a6aad8ac1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h @@ -41,7 +41,7 @@ namespace AzToolsFramework void ApplyPatchesToInstance(const AZ::EntityId& entityId, PrefabDom& patches, const Instance& instanceToAddPatches) override; - void AddPatchesToLink(PrefabDom& patches, Link& link); + void AddPatchesToLink(const PrefabDom& patches, Link& link); private: diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomTypes.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomTypes.h index e32f817227..e897630a91 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomTypes.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomTypes.h @@ -27,6 +27,7 @@ namespace AzToolsFramework using PrefabDomList = AZStd::vector; using PrefabDomReference = AZStd::optional>; + using PrefabDomConstReference = AZStd::optional>; using PrefabDomValueReference = AZStd::optional>; using PrefabDomValueConstReference = AZStd::optional>; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 14537683ef..9649818ed9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -122,30 +122,49 @@ namespace AzToolsFramework AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId(); + // Parent the entities to the container entity. Parenting the container entities of the instances passed to createPrefab + // will be done during the creation of links below. + for (AZ::Entity* topLevelEntity : entities) + { + AZ::TransformBus::Event(topLevelEntity->GetId(), &AZ::TransformBus::Events::SetParent, containerEntityId); + } + + // Update the template of the instance since the entities are modified since the template creation. + Prefab::PrefabDom serializedInstance; + if (Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(instanceToCreate->get(), serializedInstance)) + { + m_prefabSystemComponentInterface->UpdatePrefabTemplate(instanceToCreate->get().GetTemplateId(), serializedInstance); + } + instanceToCreate->get().GetNestedInstances([&](AZStd::unique_ptr& nestedInstance) { AZ_Assert(nestedInstance, "Invalid nested instance found in the new prefab created."); EntityOptionalReference nestedInstanceContainerEntity = nestedInstance->GetContainerEntity(); AZ_Assert( nestedInstanceContainerEntity, "Invalid container entity found for the nested instance used in prefab creation."); + + // These link creations shouldn't be undone because that would put the template in a non-usable state if a user + // chooses to instantiate the template after undoing the creation. CreateLink( {&nestedInstanceContainerEntity->get()}, *nestedInstance, instanceToCreate->get().GetTemplateId(), - undoBatch.GetUndoBatch(), containerEntityId); + undoBatch.GetUndoBatch(), containerEntityId, false); }); + // Create a link between the templates of the newly created instance and the instance it's being parented under. CreateLink( - topLevelEntities, instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch(), - commonRootEntityId); + topLevelEntities, instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(), + undoBatch.GetUndoBatch(), commonRootEntityId); - // Change top level entities to be parented to the container entity - // Mark them as dirty so this change is correctly applied to the template for (AZ::Entity* topLevelEntity : topLevelEntities) { AZ::EntityId topLevelEntityId = topLevelEntity->GetId(); if (topLevelEntityId.IsValid()) { - m_prefabUndoCache.UpdateCache(topLevelEntityId); - undoBatch.MarkEntityDirty(topLevelEntityId); - AZ::TransformBus::Event(topLevelEntityId, &AZ::TransformBus::Events::SetParent, containerEntityId); + m_prefabUndoCache.UpdateCache(topLevelEntity->GetId()); + + // Parenting entities would mark entities as dirty. But we want to unmark the top level entities as dirty because + // if we don't, the template created would be updated and cause issues with undo operation followed by instantiation. + ToolsApplicationRequests::Bus::Broadcast( + &ToolsApplicationRequests::Bus::Events::RemoveDirtyEntity, topLevelEntity->GetId()); } } @@ -296,7 +315,7 @@ namespace AzToolsFramework void PrefabPublicHandler::CreateLink( const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId, - UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId) + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool isUndoRedoSupportNeeded) { AZ::EntityId containerEntityId = sourceInstance.GetContainerEntityId(); AZ::Entity* containerEntity = GetEntityById(containerEntityId); @@ -322,9 +341,19 @@ namespace AzToolsFramework m_instanceToTemplateInterface->GeneratePatch(patch, containerEntityDomBefore, containerEntityDomAfter); m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(patch, containerEntityId); - LinkId linkId = PrefabUndoHelpers::CreateLink( - sourceInstance.GetTemplateId(), targetTemplateId, patch, sourceInstance.GetInstanceAlias(), - undoBatch); + LinkId linkId; + if (isUndoRedoSupportNeeded) + { + linkId = PrefabUndoHelpers::CreateLink( + sourceInstance.GetTemplateId(), targetTemplateId, AZStd::move(patch), sourceInstance.GetInstanceAlias(), undoBatch); + } + else + { + linkId = m_prefabSystemComponentInterface->CreateLink( + targetTemplateId, sourceInstance.GetTemplateId(), sourceInstance.GetInstanceAlias(), patch, + InvalidLinkId); + m_prefabSystemComponentInterface->PropagateTemplateChanges(targetTemplateId); + } sourceInstance.SetLinkId(linkId); @@ -357,7 +386,7 @@ namespace AzToolsFramework patchesCopyForUndoSupport.CopyFrom(nestedInstanceLinkPatches->get(), patchesCopyForUndoSupport.GetAllocator()); PrefabUndoHelpers::RemoveLink( sourceInstance->GetTemplateId(), targetTemplateId, sourceInstance->GetInstanceAlias(), sourceInstance->GetLinkId(), - patchesCopyForUndoSupport, undoBatch); + AZStd::move(patchesCopyForUndoSupport), undoBatch); } PrefabOperationResult PrefabPublicHandler::SavePrefab(AZ::IO::Path filePath) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 03b3827328..138bc84aa0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -77,10 +77,11 @@ namespace AzToolsFramework * \param targetInstance The id of the target template. * \param undoBatch The undo batch to set as parent for this create link action. * \param commonRootEntityId The id of the entity that the source instance should be parented under. + * \param isUndoRedoSupportNeeded The flag indicating whether the link should be created with undo/redo support or not. */ void CreateLink( const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId, - UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId); + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool isUndoRedoSupportNeeded = true); /** * Removes the link between template of the sourceInstance and the template corresponding to targetTemplateId. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index 3910e80f75..c4e6415b02 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -583,7 +583,7 @@ namespace AzToolsFramework const TemplateId& linkTargetId, const TemplateId& linkSourceId, const InstanceAlias& instanceAlias, - const PrefabDomReference linkPatch, + const PrefabDomConstReference linkPatches, const LinkId& linkId) { if (linkTargetId == InvalidTemplateId) @@ -667,9 +667,9 @@ namespace AzToolsFramework rapidjson::StringRef(PrefabDomUtils::SourceName), rapidjson::StringRef(sourceTemplate.GetFilePath().c_str()), newLink.GetLinkDom().GetAllocator()); - if (linkPatch && linkPatch->get().IsArray() && !(linkPatch->get().Empty())) + if (linkPatches && linkPatches->get().IsArray() && !(linkPatches->get().Empty())) { - m_instanceToTemplatePropagator.AddPatchesToLink(linkPatch.value(), newLink); + m_instanceToTemplatePropagator.AddPatchesToLink(linkPatches.value(), newLink); } //update the target template dom to have the proper values for the source template dom diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h index 30d03ba2ef..0a9a450f64 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h @@ -156,7 +156,7 @@ namespace AzToolsFramework const TemplateId& linkTargetId, const TemplateId& linkSourceId, const InstanceAlias& instanceAlias, - const PrefabDomReference linkPatch, + const PrefabDomConstReference linkPatches, const LinkId& linkId = InvalidLinkId) override; /** diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h index 6491d67401..f47941254a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h @@ -43,9 +43,9 @@ namespace AzToolsFramework PrefabDomValue::MemberIterator& instanceIterator, InstanceOptionalReference instance) = 0; //creates a new Link - virtual LinkId CreateLink(const TemplateId& linkTargetId, const TemplateId& linkSourceId, - const InstanceAlias& instanceAlias, const PrefabDomReference linkPatch, - const LinkId& linkId = InvalidLinkId) = 0; + virtual LinkId CreateLink( + const TemplateId& linkTargetId, const TemplateId& linkSourceId, const InstanceAlias& instanceAlias, + const PrefabDomConstReference linkPatches, const LinkId& linkId = InvalidLinkId) = 0; virtual void RemoveLink(const LinkId& linkId) = 0; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp index ad0cdc166a..aadcdcdea0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp @@ -124,7 +124,7 @@ namespace AzToolsFramework const TemplateId& targetId, const TemplateId& sourceId, const InstanceAlias& instanceAlias, - PrefabDomReference linkPatches, + PrefabDom linkPatches, const LinkId linkId) { m_targetId = targetId; @@ -132,10 +132,7 @@ namespace AzToolsFramework m_instanceAlias = instanceAlias; m_linkId = linkId; - if (linkPatches.has_value()) - { - m_linkPatches = AZStd::move(linkPatches->get()); - } + m_linkPatches = AZStd::move(linkPatches); //if linkId is invalid, set as ADD if (m_linkId == InvalidLinkId) @@ -228,7 +225,7 @@ namespace AzToolsFramework if (link.has_value()) { - m_linkDomPrevious = AZStd::move(link->get().GetLinkDom()); + m_linkDomPrevious.CopyFrom(link->get().GetLinkDom(), m_linkDomPrevious.GetAllocator()); } //get source templateDom @@ -275,7 +272,7 @@ namespace AzToolsFramework if (patchesIter == m_linkDomNext.MemberEnd()) { m_linkDomNext.AddMember( - rapidjson::GenericStringRef(PrefabDomUtils::PatchesName), patchLinkCopy, m_linkDomNext.GetAllocator()); + rapidjson::GenericStringRef(PrefabDomUtils::PatchesName), AZStd::move(patchLinkCopy), m_linkDomNext.GetAllocator()); } else { @@ -303,9 +300,7 @@ namespace AzToolsFramework return; } - PrefabDom moveLink; - moveLink.CopyFrom(linkDom, linkDom.GetAllocator()); - link->get().GetLinkDom() = AZStd::move(moveLink); + link->get().SetLinkDom(linkDom); //propagate the link changes link->get().UpdateTarget(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h index 49bae4eda0..33d9e5ad33 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h @@ -101,7 +101,7 @@ namespace AzToolsFramework const TemplateId& targetId, const TemplateId& sourceId, const InstanceAlias& instanceAlias, - PrefabDomReference linkPatches = PrefabDomReference(), + PrefabDom linkPatches = PrefabDom(), const LinkId linkId = InvalidLinkId); void Undo() override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp index 24eb71e055..5ba8d3c940 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp @@ -34,11 +34,11 @@ namespace AzToolsFramework } LinkId CreateLink( - TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDomReference patch, + TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDom patch, const InstanceAlias& instanceAlias, UndoSystem::URSequencePoint* undoBatch) { auto linkAddUndo = aznew PrefabUndoInstanceLink("Create Link"); - linkAddUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, patch, InvalidLinkId); + linkAddUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, AZStd::move(patch), InvalidLinkId); linkAddUndo->SetParent(undoBatch); linkAddUndo->Redo(); @@ -47,10 +47,10 @@ namespace AzToolsFramework void RemoveLink( TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, LinkId linkId, - PrefabDomReference linkPatches, UndoSystem::URSequencePoint* undoBatch) + PrefabDom linkPatches, UndoSystem::URSequencePoint* undoBatch) { auto linkRemoveUndo = aznew PrefabUndoInstanceLink("Remove Link"); - linkRemoveUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, linkPatches, linkId); + linkRemoveUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, AZStd::move(linkPatches), linkId); linkRemoveUndo->SetParent(undoBatch); linkRemoveUndo->Redo(); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h index 6429df3b04..17cf7f52c1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h @@ -22,11 +22,11 @@ namespace AzToolsFramework const Instance& instance, AZStd::string_view undoMessage, const PrefabDom& instanceDomBeforeUpdate, UndoSystem::URSequencePoint* undoBatch); LinkId CreateLink( - TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDomReference patch, + TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDom patch, const InstanceAlias& instanceAlias, UndoSystem::URSequencePoint* undoBatch); void RemoveLink( TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, LinkId linkId, - PrefabDomReference linkPatches, UndoSystem::URSequencePoint* undoBatch); + PrefabDom linkPatches, UndoSystem::URSequencePoint* undoBatch); } } // namespace Prefab } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp index a89b364471..fa8eb3fd65 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabCatchmentProcessor.cpp @@ -84,8 +84,6 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils } SpawnableUtils::SortEntitiesByTransformHierarchy(*spawnable); context.GetProcessedObjects().push_back(AZStd::move(object)); - - context.RemovePrefab(prefabName); } else { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp index eb206349d0..38f58503ed 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.cpp @@ -10,6 +10,8 @@ * */ +#include + #include namespace AzToolsFramework::Prefab::PrefabConversionUtils @@ -24,37 +26,14 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils return result.second; } - bool PrefabProcessorContext::RemovePrefab(AZStd::string_view prefabName) - { - if (!m_isIterating) - { - return m_prefabs.erase(prefabName) > 0; - } - else - { - m_delayedDelete.emplace_back(prefabName); - } - return false; - } - void PrefabProcessorContext::ListPrefabs(const AZStd::function& callback) { m_isIterating = true; for (auto& it : m_prefabs) { - if (AZStd::find(m_delayedDelete.begin(), m_delayedDelete.end(), it.first) == m_delayedDelete.end()) - { - callback(it.first, it.second); - } + callback(it.first, it.second); } m_isIterating = false; - - // Clear out any prefabs that have been deleted. - for (AZStd::string& deleted : m_delayedDelete) - { - m_prefabs.erase(deleted); - } - m_delayedDelete.clear(); } void PrefabProcessorContext::ListPrefabs(const AZStd::function& callback) const @@ -70,6 +49,44 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils return !m_prefabs.empty(); } + bool PrefabProcessorContext::RegisterSpawnableProductAssetDependency(AZStd::string prefabName, AZStd::string dependentPrefabName) + { + using ConversionUtils = PrefabConversionUtils::ProcessedObjectStore; + + prefabName += AzFramework::Spawnable::DotFileExtension; + uint32_t spawnableSubId = ConversionUtils::BuildSubId(AZStd::move(prefabName)); + + dependentPrefabName += AzFramework::Spawnable::DotFileExtension; + uint32_t spawnablePrefabSubId = ConversionUtils::BuildSubId(AZStd::move(dependentPrefabName)); + + return RegisterSpawnableProductAssetDependency(spawnableSubId, spawnablePrefabSubId); + } + + bool PrefabProcessorContext::RegisterSpawnableProductAssetDependency(AZStd::string prefabName, const AZ::Data::AssetId& dependentAssetId) + { + using ConversionUtils = PrefabConversionUtils::ProcessedObjectStore; + + prefabName += AzFramework::Spawnable::DotFileExtension; + uint32_t spawnableSubId = ConversionUtils::BuildSubId(AZStd::move(prefabName)); + + AZ::Data::AssetId spawnableAssetId(GetSourceUuid(), spawnableSubId); + + return RegisterProductAssetDependency(spawnableAssetId, dependentAssetId); + } + + bool PrefabProcessorContext::RegisterSpawnableProductAssetDependency(uint32_t spawnableAssetSubId, uint32_t dependentSpawnableAssetSubId) + { + AZ::Data::AssetId spawnableAssetId(GetSourceUuid(), spawnableAssetSubId); + AZ::Data::AssetId dependentSpawnableAssetId(GetSourceUuid(), dependentSpawnableAssetSubId); + + return RegisterProductAssetDependency(spawnableAssetId, dependentSpawnableAssetId); + } + + bool PrefabProcessorContext::RegisterProductAssetDependency(const AZ::Data::AssetId& assetId, const AZ::Data::AssetId& dependentAssetId) + { + return m_registeredProductAssetDependencies[assetId].emplace(dependentAssetId).second; + } + PrefabProcessorContext::ProcessedObjectStoreContainer& PrefabProcessorContext::GetProcessedObjects() { return m_products; @@ -80,6 +97,16 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils return m_products; } + PrefabProcessorContext::ProductAssetDependencyContainer& PrefabProcessorContext::GetRegisteredProductAssetDependencies() + { + return m_registeredProductAssetDependencies; + } + + const PrefabProcessorContext::ProductAssetDependencyContainer& PrefabProcessorContext::GetRegisteredProductAssetDependencies() const + { + return m_registeredProductAssetDependencies; + } + void PrefabProcessorContext::SetPlatformTags(AZ::PlatformTagSet tags) { m_platformTags = AZStd::move(tags); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h index 66368f335b..3dc8c99bf3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Spawnable/PrefabProcessorContext.h @@ -29,6 +29,8 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils { public: using ProcessedObjectStoreContainer = AZStd::vector; + using ProductAssetDependencyContainer = + AZStd::unordered_map>; AZ_CLASS_ALLOCATOR(PrefabProcessorContext, AZ::SystemAllocator, 0); AZ_RTTI(PrefabProcessorContext, "{C7D77E3A-C544-486B-B774-7C82C38FE22F}"); @@ -37,14 +39,21 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils virtual ~PrefabProcessorContext() = default; virtual bool AddPrefab(AZStd::string prefabName, PrefabDom prefab); - virtual bool RemovePrefab(AZStd::string_view prefabName); virtual void ListPrefabs(const AZStd::function& callback); virtual void ListPrefabs(const AZStd::function& callback) const; virtual bool HasPrefabs() const; + virtual bool RegisterSpawnableProductAssetDependency(AZStd::string prefabName, AZStd::string dependentPrefabName); + virtual bool RegisterSpawnableProductAssetDependency(AZStd::string prefabName, const AZ::Data::AssetId& dependentAssetId); + virtual bool RegisterSpawnableProductAssetDependency(uint32_t spawnableAssetSubId, uint32_t dependentSpawnableAssetSubId); + virtual bool RegisterProductAssetDependency(const AZ::Data::AssetId& assetId, const AZ::Data::AssetId& dependentAssetId); + virtual ProcessedObjectStoreContainer& GetProcessedObjects(); virtual const ProcessedObjectStoreContainer& GetProcessedObjects() const; + virtual ProductAssetDependencyContainer& GetRegisteredProductAssetDependencies(); + virtual const ProductAssetDependencyContainer& GetRegisteredProductAssetDependencies() const; + virtual void SetPlatformTags(AZ::PlatformTagSet tags); virtual const AZ::PlatformTagSet& GetPlatformTags() const; virtual const AZ::Uuid& GetSourceUuid() const; @@ -57,7 +66,8 @@ namespace AzToolsFramework::Prefab::PrefabConversionUtils NamedPrefabContainer m_prefabs; ProcessedObjectStoreContainer m_products; - AZStd::vector m_delayedDelete; + ProductAssetDependencyContainer m_registeredProductAssetDependencies; + AZ::PlatformTagSet m_platformTags; AZ::Uuid m_sourceUuid; bool m_isIterating{ false }; diff --git a/Code/Tools/Standalone/Source/ThumbnailerNullComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerNullComponent.cpp similarity index 95% rename from Code/Tools/Standalone/Source/ThumbnailerNullComponent.cpp rename to Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerNullComponent.cpp index e33cb8aa51..d156ae7c04 100644 --- a/Code/Tools/Standalone/Source/ThumbnailerNullComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerNullComponent.cpp @@ -12,16 +12,16 @@ #include #include -#include "ThumbnailerNullComponent.h" +#include #include #include -namespace LUAEditor +namespace AzToolsFramework { namespace Thumbnailer { ThumbnailerNullComponent::ThumbnailerNullComponent() : - m_nullThumbnail(new AzToolsFramework::Thumbnailer::MissingThumbnail()) + m_nullThumbnail() { } diff --git a/Code/Tools/Standalone/Source/ThumbnailerNullComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerNullComponent.h similarity index 89% rename from Code/Tools/Standalone/Source/ThumbnailerNullComponent.h rename to Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerNullComponent.h index 9d0c638305..d8386235e5 100644 --- a/Code/Tools/Standalone/Source/ThumbnailerNullComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Thumbnails/ThumbnailerNullComponent.h @@ -15,7 +15,11 @@ #include #include -namespace LUAEditor +// ThumbnailerNullComponent is an alternative to ThumbnailerComponent that can be used by tools that don't use Qt. +// It doesn't do anything (hence "null"), but it allows the system and editor components that rely on the ThumbnailService +// to start up and function. + +namespace AzToolsFramework { namespace Thumbnailer { @@ -53,4 +57,4 @@ namespace LUAEditor AzToolsFramework::Thumbnailer::SharedThumbnail m_nullThumbnail; }; } // Thumbnailer -} // namespace LUAEditor +} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp index ac5f1136f5..70cad69268 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp @@ -1287,7 +1287,6 @@ namespace AzToolsFramework Field("Cached World Transform Parent", &TransformComponent::m_cachedWorldTransformParent)-> Field("Parent Activation Transform Mode", &TransformComponent::m_parentActivationTransformMode)-> Field("IsStatic", &TransformComponent::m_isStatic)-> - Field("Sync Enabled", &TransformComponent::m_netSyncEnabled)-> Field("InterpolatePosition", &TransformComponent::m_interpolatePosition)-> Field("InterpolateRotation", &TransformComponent::m_interpolateRotation)-> Version(9, &Internal::TransformComponentDataConverter); @@ -1322,21 +1321,7 @@ namespace AzToolsFramework Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Hide)-> DataElement(AZ::Edit::UIHandlers::Default, &TransformComponent::m_cachedWorldTransform, "Cached World Transform", "")-> Attribute(AZ::Edit::Attributes::SliceFlags, AZ::Edit::SliceFlags::NotPushable)-> - Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Hide)-> - - ClassElement(AZ::Edit::ClassElements::Group, "Network Sync")-> - Attribute(AZ::Edit::Attributes::AutoExpand, true)-> - - DataElement(AZ::Edit::UIHandlers::Default, &TransformComponent::m_netSyncEnabled, "Sync to replicas", "Sync to network replicas.")-> - DataElement(AZ::Edit::UIHandlers::ComboBox, &TransformComponent::m_interpolatePosition, - "Position Interpolation", "Enable local interpolation of position.")-> - EnumAttribute(AZ::InterpolationMode::NoInterpolation, "None")-> - EnumAttribute(AZ::InterpolationMode::LinearInterpolation, "Linear")-> - - DataElement(AZ::Edit::UIHandlers::ComboBox, &TransformComponent::m_interpolateRotation, - "Rotation Interpolation", "Enable local interpolation of rotation.")-> - EnumAttribute(AZ::InterpolationMode::NoInterpolation, "None")-> - EnumAttribute(AZ::InterpolationMode::LinearInterpolation, "Linear"); + Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Hide); ptrEdit->Class("Values", "XYZ PYR")-> DataElement(AZ::Edit::UIHandlers::Default, &EditorTransform::m_translate, "Translate", "Local Position (Relative to parent) in meters.")-> diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index 9388f3f5f0..c6450d03c7 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -13,6 +13,9 @@ #include "EditorTransformComponentSelection.h" #include +#include +#include +#include #include #include #include diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake index a7fcf2e711..06f78ecdd3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake @@ -72,6 +72,8 @@ set(FILES AssetCatalog/PlatformAddressedAssetCatalogManager.cpp Thumbnails/ThumbnailerComponent.cpp Thumbnails/ThumbnailerComponent.h + Thumbnails/ThumbnailerNullComponent.cpp + Thumbnails/ThumbnailerNullComponent.h Thumbnails/LoadingThumbnail.cpp Thumbnails/LoadingThumbnail.h Thumbnails/MissingThumbnail.cpp diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUndoLinkTests.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUndoLinkTests.cpp index 2122b116d8..3d540a7a95 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUndoLinkTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUndoLinkTests.cpp @@ -120,7 +120,7 @@ namespace UnitTest //create an undo node to apply the patch and prep for undo PrefabUndoInstanceLink undoInstanceLinkNode("Undo Link Patch"); - undoInstanceLinkNode.Capture(rootTemplateId, nestedTemplateId, aliases[0], patch, InvalidLinkId); + undoInstanceLinkNode.Capture(rootTemplateId, nestedTemplateId, aliases[0], AZStd::move(patch), InvalidLinkId); undoInstanceLinkNode.Redo(); m_instanceUpdateExecutorInterface->UpdateTemplateInstancesInQueue(); @@ -196,7 +196,7 @@ namespace UnitTest //create an undo node to apply the patch and prep for undo PrefabUndoInstanceLink undoInstanceLinkNode("Undo Link Patch"); - undoInstanceLinkNode.Capture(rootTemplateId, nestedTemplateId, aliases[0], linkPatch, InvalidLinkId); + undoInstanceLinkNode.Capture(rootTemplateId, nestedTemplateId, aliases[0], AZStd::move(linkPatch), InvalidLinkId); undoInstanceLinkNode.Redo(); m_instanceUpdateExecutorInterface->UpdateTemplateInstancesInQueue(); diff --git a/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp b/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp index e3b474ba5d..380739bab1 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp +++ b/Code/Framework/GridMate/GridMate/Carrier/SecureSocketDriver.cpp @@ -1486,7 +1486,7 @@ namespace GridMate // Only support a single cipher suite in OpenSSL that supports: // - // ECDHE Master key exchange using ephemeral elliptic curve diffie-hellman. + // ECDHE Key exchange using ephemeral elliptic curve diffie-hellman. // RSA Authentication (public and private key) used to sign ECDHE parameters and can be checked against a CA. // AES256 AES cipher for symmetric key encryption using a 256-bit key. // GCM Mode of operation for symmetric key encryption. diff --git a/Code/Framework/GridMate/GridMate/Carrier/StreamSecureSocketDriver.cpp b/Code/Framework/GridMate/GridMate/Carrier/StreamSecureSocketDriver.cpp index 9e59496ed1..30c2c63ed9 100644 --- a/Code/Framework/GridMate/GridMate/Carrier/StreamSecureSocketDriver.cpp +++ b/Code/Framework/GridMate/GridMate/Carrier/StreamSecureSocketDriver.cpp @@ -97,7 +97,7 @@ namespace GridMate // Only support a single cipher suite in OpenSSL that supports: // - // ECDHE Master key exchange using ephemeral elliptic curve diffie-hellman. + // ECDHE Key exchange using ephemeral elliptic curve diffie-hellman. // RSA Authentication (public and private key) used to sign ECDHE parameters and can be checked against a CA. // AES256 AES cipher for symmetric key encryption using a 256-bit key. // GCM Mode of operation for symmetric key encryption. diff --git a/Code/Framework/GridMate/GridMate/Replica/DataSet.cpp b/Code/Framework/GridMate/GridMate/Replica/DataSet.cpp index 614c50a7e0..fb6a6fe5cd 100644 --- a/Code/Framework/GridMate/GridMate/Replica/DataSet.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/DataSet.cpp @@ -52,6 +52,6 @@ namespace GridMate bool DataSetBase::CanSet() const { - return m_replicaChunk ? m_replicaChunk->IsMaster() : true; + return m_replicaChunk ? m_replicaChunk->IsPrimary() : true; } } diff --git a/Code/Framework/GridMate/GridMate/Replica/DataSet.h b/Code/Framework/GridMate/GridMate/Replica/DataSet.h index f91a86dcec..61ff75516b 100644 --- a/Code/Framework/GridMate/GridMate/Replica/DataSet.h +++ b/Code/Framework/GridMate/GridMate/Replica/DataSet.h @@ -43,7 +43,7 @@ namespace GridMate struct DataSetDefaultTraits { /** - * \brief Should a change in DataSet value invoke a callback on a master replica chunk? + * \brief Should a change in DataSet value invoke a callback on a primary replica chunk? * * By default, DataSet::BindInterface only invokes on client/non-authoritative replica chunks. * This switch enables the callback on server/authoritative replica chunks. @@ -55,7 +55,7 @@ namespace GridMate }; /** - * \brief Turns on DataSet callbacks to be invoked on the master replica as well as client replicas. + * \brief Turns on DataSet callbacks to be invoked on the primary replica as well as client replicas. */ struct DataSetInvokeEverywhereTraits : DataSetDefaultTraits { @@ -200,7 +200,7 @@ namespace GridMate } /** - Modify the DataSet. Call this on the Master node to change the data, + Modify the DataSet. Call this on the Primary node to change the data, which will be propagated to all proxies. **/ void Set(const DataType& v) @@ -214,7 +214,7 @@ namespace GridMate } /** - Modify the DataSet. Call this on the Master node to change the data, + Modify the DataSet. Call this on the Primary node to change the data, which will be propagated to all proxies. **/ void Set(DataType&& v) @@ -228,7 +228,7 @@ namespace GridMate } /** - Modify the DataSet. Call this on the Master node to change the data, + Modify the DataSet. Call this on the Primary node to change the data, which will be propagated to all proxies. **/ template @@ -243,7 +243,7 @@ namespace GridMate } /** - Modify the DataSet directly without copying it. Call this on the Master node, + Modify the DataSet directly without copying it. Call this on the Primary node, passing in a function object that takes the value by reference, optionally modifies the data, and returns true if the data was changed. **/ diff --git a/Code/Framework/GridMate/GridMate/Replica/DeltaCompressedDataSet.h b/Code/Framework/GridMate/GridMate/Replica/DeltaCompressedDataSet.h index cc19c2336b..8d88635c07 100644 --- a/Code/Framework/GridMate/GridMate/Replica/DeltaCompressedDataSet.h +++ b/Code/Framework/GridMate/GridMate/Replica/DeltaCompressedDataSet.h @@ -159,7 +159,7 @@ namespace GridMate } /** - Modify the DataSet. Call this on the Master node to change the data, + Modify the DataSet. Call this on the Primary node to change the data, which will be propagated to all proxies. **/ void Set(const FieldType& v) @@ -201,7 +201,7 @@ namespace GridMate private: DataSet m_absolutePortion; DataSet m_relativePortion; - FieldType m_combinedValue; // the latest value on either master or proxy + FieldType m_combinedValue; // the latest value on either primary or proxy }; //----------------------------------------------------------------------------- diff --git a/Code/Framework/GridMate/GridMate/Replica/Interest/BitmaskInterestHandler.cpp b/Code/Framework/GridMate/GridMate/Replica/Interest/BitmaskInterestHandler.cpp index 1a35fd1893..75f4c8bdd2 100644 --- a/Code/Framework/GridMate/GridMate/Replica/Interest/BitmaskInterestHandler.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/Interest/BitmaskInterestHandler.cpp @@ -366,7 +366,7 @@ namespace GridMate auto replica = Replica::CreateReplica("BitmaskInterestHandlerRules"); m_rulesReplica = CreateAndAttachReplicaChunk(replica); - m_rm->AddMaster(replica); + m_rm->AddPrimary(replica); } void BitmaskInterestHandler::OnRulesHandlerUnregistered(InterestManager* manager) diff --git a/Code/Framework/GridMate/GridMate/Replica/Interest/InterestManager.cpp b/Code/Framework/GridMate/GridMate/Replica/Interest/InterestManager.cpp index 770dcd4f1f..ff1a29a917 100644 --- a/Code/Framework/GridMate/GridMate/Replica/Interest/InterestManager.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/Interest/InterestManager.cpp @@ -206,7 +206,7 @@ namespace GridMate return false; } - if (replica->IsMaster()) // own the replica? + if (replica->IsPrimary()) // own the replica? { return true; } diff --git a/Code/Framework/GridMate/GridMate/Replica/Interest/ProximityInterestHandler.cpp b/Code/Framework/GridMate/GridMate/Replica/Interest/ProximityInterestHandler.cpp index 4e3c2c77a4..13a0151bc7 100644 --- a/Code/Framework/GridMate/GridMate/Replica/Interest/ProximityInterestHandler.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/Interest/ProximityInterestHandler.cpp @@ -508,7 +508,7 @@ namespace GridMate auto replica = Replica::CreateReplica("ProximityInterestHandlerRules"); m_rulesReplica = CreateAndAttachReplicaChunk(replica); - m_rm->AddMaster(replica); + m_rm->AddPrimary(replica); } void ProximityInterestHandler::OnRulesHandlerUnregistered(InterestManager* manager) diff --git a/Code/Framework/GridMate/GridMate/Replica/MigrationSequence.cpp b/Code/Framework/GridMate/GridMate/Replica/MigrationSequence.cpp index 48fbfe5289..a1150a198a 100644 --- a/Code/Framework/GridMate/GridMate/Replica/MigrationSequence.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/MigrationSequence.cpp @@ -26,7 +26,7 @@ namespace GridMate m_replicaMgr = replica->GetReplicaManager(); - if (replica->IsMaster() && newOwnerId != m_replicaMgr->GetLocalPeerId()) + if (replica->IsPrimary() && newOwnerId != m_replicaMgr->GetLocalPeerId()) { m_sm.SetStateHandler(AZ_HSM_STATE_NAME(MST_TOP), AZ::HSM::StateHandler(this, &MigrationSequence::DefaultHandler), AZ::HSM::InvalidStateId, MST_MIGRATING); } @@ -312,7 +312,7 @@ namespace GridMate return true; case ME_MODIFY_NEW_OWNER: m_newOwnerId = *static_cast(event.userData); - if (m_replica->IsMaster() && m_newOwnerId != m_replicaMgr->m_self.GetId()) + if (m_replica->IsPrimary() && m_newOwnerId != m_replicaMgr->m_self.GetId()) { sm.Transition(MST_MIGRATING); } diff --git a/Code/Framework/GridMate/GridMate/Replica/RemoteProcedureCall.h b/Code/Framework/GridMate/GridMate/Replica/RemoteProcedureCall.h index 98494267ad..4256dd978b 100644 --- a/Code/Framework/GridMate/GridMate/Replica/RemoteProcedureCall.h +++ b/Code/Framework/GridMate/GridMate/Replica/RemoteProcedureCall.h @@ -370,8 +370,8 @@ namespace GridMate PeerId sourcePeerId = GetSourcePeerId(); bool shouldQueue = true; bool processed = false; - bool isMaster = m_replicaChunk->IsMaster(); - if (isMaster) + bool isPrimary = m_replicaChunk->IsPrimary(); + if (isPrimary) { // We are authoritative so execute the RPC immediately, forwarding the args along RpcRequest localRequest(this, rc.m_realTime, rc.m_realTime, rc.m_localTime); @@ -385,7 +385,7 @@ namespace GridMate if (shouldQueue) { TypeTuple* storage = aznew TypeTuple(this, RpcContext(rc.m_realTime, rc.m_realTime, rc.m_localTime, sourcePeerId), AZStd::forward(args) ...); - storage->m_authoritative = isMaster; + storage->m_authoritative = isPrimary; storage->m_processed = processed; storage->m_reliable = Traits::s_isReliable; OnRpcRequest(storage); diff --git a/Code/Framework/GridMate/GridMate/Replica/Replica.cpp b/Code/Framework/GridMate/GridMate/Replica/Replica.cpp index 483e523e05..c0a92de0d8 100644 --- a/Code/Framework/GridMate/GridMate/Replica/Replica.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/Replica.cpp @@ -106,7 +106,7 @@ namespace GridMate //----------------------------------------------------------------------------- void Replica::Destroy() { - AZ_Assert(IsMaster(), "We don't own replica 0x%x!", GetRepId()); + AZ_Assert(IsPrimary(), "We don't own replica 0x%x!", GetRepId()); if (m_manager) { m_manager->Destroy(this); @@ -327,7 +327,7 @@ namespace GridMate if (IsActive()) { - if (IsMaster()) + if (IsPrimary()) { EBUS_EVENT(Debug::ReplicaDrillerBus, OnRequestReplicaChangeOwnership, this, requestor); diff --git a/Code/Framework/GridMate/GridMate/Replica/Replica.h b/Code/Framework/GridMate/GridMate/Replica/Replica.h index fb630ac1a4..5291a7f143 100644 --- a/Code/Framework/GridMate/GridMate/Replica/Replica.h +++ b/Code/Framework/GridMate/GridMate/Replica/Replica.h @@ -68,7 +68,7 @@ namespace GridMate Rep_ManagedAlloc = 1 << 1, Rep_CanMigrate = 1 << 2, Rep_New = 1 << 3, - Rep_Master = 1 << 4, + Rep_Primary = 1 << 4, Rep_Active = 1 << 6, Rep_ChangedOwner = 1 << 7, Rep_SuspendDownstream = 1 << 8, @@ -85,7 +85,7 @@ namespace GridMate void Destroy(); - void UpdateReplica(const ReplicaContext& rc); // Called when updating replica master from source + void UpdateReplica(const ReplicaContext& rc); // Called when updating replica primary from source void UpdateFromReplica(const ReplicaContext& rc); // Called when updating game with replica info bool AcceptChangeOwnership(PeerId requestor, const ReplicaContext& rc); // Return true to accept the transfer void OnActivate(const ReplicaContext& rc); @@ -112,8 +112,8 @@ namespace GridMate void RequestChangeOwnership(PeerId newOwner = InvalidReplicaPeerId); // If newOwner is not specified we assume it should be the local peer - bool IsMaster() const { return !IsActive() || !!(m_flags & Rep_Master); } - bool IsProxy() const { return !IsMaster(); } + bool IsPrimary() const { return !IsActive() || !!(m_flags & Rep_Primary); } + bool IsProxy() const { return !IsPrimary(); } bool IsNew() const { return !!(m_flags & Rep_New); } bool IsNewOwner() const { return !!(m_flags & Rep_ChangedOwner); } bool IsActive() const { return !!(m_flags & Rep_Active); } @@ -170,7 +170,7 @@ namespace GridMate void MarkRPCsAsRelayed(); - void SetMaster(bool isMaster) { m_flags = isMaster ? m_flags | Rep_Master : m_flags & ~Rep_Master; } + void SetPrimary(bool isPrimary) { m_flags = isPrimary ? m_flags | Rep_Primary : m_flags & ~Rep_Primary; } void SetNew() { m_flags |= Rep_New; } void SetRepId(ReplicaId id); void SetMigratable(bool migratable); diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.cpp b/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.cpp index 087f5f3273..adcff38190 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.cpp @@ -125,18 +125,18 @@ namespace GridMate return false; } //----------------------------------------------------------------------------- - bool ReplicaChunkBase::IsMaster() const + bool ReplicaChunkBase::IsPrimary() const { if (m_replica) { - return m_replica->IsMaster(); + return m_replica->IsPrimary(); } return true; } //----------------------------------------------------------------------------- bool ReplicaChunkBase::IsProxy() const { - return !IsMaster(); + return !IsPrimary(); } //----------------------------------------------------------------------------- bool ReplicaChunkBase::IsDirty(AZ::u32 marshalFlags) const @@ -398,8 +398,8 @@ namespace GridMate { if (mc.m_peer != m_replica->m_upstreamHop) { - AZ_TracePrintf("GridMate", "Received dataset updates for replica id %08x(%s) from unexpected peer.", GetReplicaId(), IsActive() && IsMaster() ? "master" : "proxy"); - if (IsMaster()) + AZ_TracePrintf("GridMate", "Received dataset updates for replica id %08x(%s) from unexpected peer.", GetReplicaId(), IsActive() && IsPrimary() ? "primary" : "proxy"); + if (IsPrimary()) { mc.m_iBuf->Skip(mc.m_iBuf->Left()); return; @@ -547,7 +547,7 @@ namespace GridMate AZ_Assert(false, "Discarding non-authoritative RPC <%s> because s_allowNonAuthoritativeRequests trait is disabled!", GetDescriptor()->GetRpcName(this, rpc)); isRpcValid = false; } - if (!rpc->IsAllowNonAuthoritativeRequestsRelay() && !IsMaster()) + if (!rpc->IsAllowNonAuthoritativeRequestsRelay() && !IsPrimary()) { AZ_Assert(false, "Discarding non-authoritative RPC <%s> because s_allowNonAuthoritativeRequestRelay trait is disabled!", GetDescriptor()->GetRpcName(this, rpc)); isRpcValid = false; @@ -639,19 +639,19 @@ namespace GridMate for (RPCQueue::iterator iRPC = m_rpcQueue.begin(); iRPC != m_rpcQueue.end(); ) { Internal::RpcRequest* request = *iRPC; - bool isMaster = IsMaster(); // need to do this check after each RPC because ownership may change + bool isPrimary = IsPrimary(); // need to do this check after each RPC because ownership may change if (!m_replica->IsActive()) // this can happen if replica was deactivated within a previous RPC call { request->m_relayed = true; } - else if (!request->m_processed && (isMaster || request->m_authoritative)) + else if (!request->m_processed && (isPrimary || request->m_authoritative)) { request->m_realTime = rc.m_realTime; request->m_localTime = rc.m_localTime; bool ret = request->m_rpc->Invoke(request); request->m_processed = true; - if (isMaster) + if (isPrimary) { if (ret) { diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.h b/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.h index 7cfff0fe26..50b6bb8584 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.h +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaChunk.h @@ -45,17 +45,17 @@ namespace GridMate /** A single unit of network functionality A ReplicaChunk is a user extendable network object. One or more ReplicaChunks can be owned by a Replica, which is both a container and manager for them. A replica is owned - by a Master, and is propagated to other network nodes, who interact with is as a Proxy. + by a Primary, and is propagated to other network nodes, who interact with is as a Proxy. The data a ReplicaChunk contains should generally be related to the other data stored within it. Since multiple chunks can be attached to a Replica, unrelated data can simply be stored in other chunks on the same Replica. A ReplicaChunk has two primary ways to interact with it: DataSets and Remote Procedure Calls (RPCs). - DataSets store arbitrary data, which only the Master is able to modify. Any changes are + DataSets store arbitrary data, which only the Primary is able to modify. Any changes are propagated to the Proxy ReplicaChunks on the other nodes. RPCs are methods that can be executed on a remote node. They are first invoked on the - Master, who then decides if the invocation should be propagated to the Proxies. + Primary, who then decides if the invocation should be propagated to the Proxies. ReplicaChunks can be created by inheriting from the class and registered by calling ReplicaChunkDescriptorTable::RegisterChunkType() to create the factory required by @@ -107,7 +107,7 @@ namespace GridMate PeerId GetPeerId() const; virtual ReplicaManager* GetReplicaManager(); bool IsActive() const; - bool IsMaster() const; + bool IsPrimary() const; bool IsProxy() const; virtual void OnAttachedToReplica(Replica* replica) { (void) replica; } @@ -191,7 +191,7 @@ namespace GridMate void AddDataSetEvent(DataSetBase* dataset); // Called to enqueue a user event handler for a modified DataSet on a proxy node - void SignalDataSetChanged(const DataSetBase& dataset); // Called when the DataSet changes on the master node + void SignalDataSetChanged(const DataSetBase& dataset); // Called when the DataSet changes on the primary node void EnqueueMarshalTask(); diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaDrillerEvents.h b/Code/Framework/GridMate/GridMate/Replica/ReplicaDrillerEvents.h index 09b454a03e..14e70a3213 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaDrillerEvents.h +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaDrillerEvents.h @@ -62,7 +62,7 @@ namespace GridMate //! Called when an ownership transfer request is received. virtual void OnRequestReplicaChangeOwnership(Replica* replica, PeerId requestor) { (void)replica; (void)requestor; } //! Called when a replica changes ownership, not necessarily to or from the local node. - virtual void OnReplicaChangeOwnership(Replica* replica, bool wasMaster) { (void)replica; (void)wasMaster; } + virtual void OnReplicaChangeOwnership(Replica* replica, bool wasPrimary) { (void)replica; (void)wasPrimary; } //! Called when a chunk has been created. It doesn't mean it will be added to the system. //! Object will be partially constructed at this point if you inherit from ReplicaChunk @@ -91,9 +91,9 @@ namespace GridMate //! Called when data is received for a dataset. virtual void OnReceiveDataSet(ReplicaChunkBase* chunk, AZ::u32 chunkIndex, DataSetBase* dataSet, PeerId from, PeerId to, const void* data, size_t len) { (void)chunk; (void)chunkIndex; (void)dataSet; (void)from; (void)to; (void)data; (void)len; } - //! Called when an rpc request is received. RpcRequest pointer will be null if rpc is called on master replica. + //! Called when an rpc request is received. RpcRequest pointer will be null if rpc is called on primary replica. virtual void OnRequestRpc(ReplicaChunkBase* chunk, Internal::RpcRequest* rpc) { (void)chunk; (void)rpc; } - //! Called when an rpc is invoked. RpcRequest pointer will be null if rpc is called on master replica. + //! Called when an rpc is invoked. RpcRequest pointer will be null if rpc is called on primary replica. virtual void OnInvokeRpc(ReplicaChunkBase* chunk, Internal::RpcRequest* rpc) { (void)chunk; (void)rpc; } //! Called every time an rpc is sent to a peer. virtual void OnSendRpc(ReplicaChunkBase* chunk, AZ::u32 chunkIndex, Internal::RpcRequest* rpc, PeerId from, PeerId to, const void* data, size_t len) { (void)chunk; (void)chunkIndex; (void)rpc; (void)from; (void)to; (void)data; (void)len; } diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.cpp b/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.cpp index 32a941ef4a..78d6f260db 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.cpp @@ -386,7 +386,7 @@ namespace GridMate replica->SetMigratable(true); // register global session info - // this one is kind of special so don't go through AddMaster() + // this one is kind of special so don't go through AddPrimary() ReplicaContext rc(this, GetTime(), &m_self); replica->m_createTime = rc.m_realTime; replica->SetRepId(RepId_SessionInfo); @@ -405,7 +405,7 @@ namespace GridMate else { // take over ownership of the session info - AZ_Assert(!m_sessionInfo->IsMaster(), "We just became host but we were already the owner of sessionInfo!"); + AZ_Assert(!m_sessionInfo->IsPrimary(), "We just became host but we were already the owner of sessionInfo!"); AZ_Assert(m_sessionInfo->m_pHostPeer->IsOrphan(), "We can't be promoted if we are still connected to the host!"); m_sessionInfo->m_pHostPeer->Remove(m_sessionInfo->GetReplica()); m_self.Add(m_sessionInfo->GetReplica()); @@ -903,7 +903,7 @@ namespace GridMate ReplicaContext rc(this, GetTime()); for (auto& replicaObject : m_self.m_objectsTimeSort) { - if (replicaObject.m_replica->IsMaster()) + if (replicaObject.m_replica->IsPrimary()) { replicaObject.m_replica->UpdateReplica(rc); } @@ -1357,11 +1357,11 @@ namespace GridMate m_flags &= ~Rm_Processing; } //----------------------------------------------------------------------------- - void ReplicaManager::RegisterReplica(const ReplicaPtr& pReplica, bool isMaster, ReplicaContext& rc) + void ReplicaManager::RegisterReplica(const ReplicaPtr& pReplica, bool isPrimary, ReplicaContext& rc) { AZ_Assert((pReplica->m_flags & ~Replica::Rep_Traits) == 0, "This replica is not clean, flags=0x%x, rpcs=%d!", pReplica->m_flags); AZ_Assert(pReplica->GetRepId() != InvalidReplicaId, "You should set the replica ID before you register it!"); - pReplica->SetMaster(isMaster); + pReplica->SetPrimary(isPrimary); pReplica->SetNew(); auto it = m_replicas.insert(AZStd::make_pair(pReplica->GetRepId(), pReplica)); // register with lookup table (void)it; @@ -1371,21 +1371,21 @@ namespace GridMate OnReplicaChanged(pReplica); } //----------------------------------------------------------------------------- - ReplicaId ReplicaManager::AddMaster(const ReplicaPtr& pMaster) + ReplicaId ReplicaManager::AddPrimary(const ReplicaPtr& pPrimary) { AZ_Assert(IsReady(), "ReplicaManager is not ready!"); - AZ_Assert(pMaster, "Attempting to register NULL replica!"); + AZ_Assert(pPrimary, "Attempting to register NULL replica!"); ReplicaId newId = m_localIdBlocks.Alloc(); ReplicaContext rc(this, GetTime(), &m_self); - pMaster->m_createTime = rc.m_realTime; - pMaster->SetRepId(newId); - m_self.Add(pMaster.get()); - AZStd::static_pointer_cast(pMaster->m_replicaStatus)->m_ownerSeq.Set(1); - pMaster->InitReplica(this); - RegisterReplica(pMaster, true, rc); + pPrimary->m_createTime = rc.m_realTime; + pPrimary->SetRepId(newId); + m_self.Add(pPrimary.get()); + AZStd::static_pointer_cast(pPrimary->m_replicaStatus)->m_ownerSeq.Set(1); + pPrimary->InitReplica(this); + RegisterReplica(pPrimary, true, rc); - //AZ_TracePrintf("GridMate", "Peer 0x%x: Added replica master 0x%x.\n", - // GetLocalPeerId(), pMaster->GetRepId()); + //AZ_TracePrintf("GridMate", "Peer 0x%x: Added replica primary 0x%x.\n", + // GetLocalPeerId(), pPrimary->GetRepId()); return newId; } @@ -1458,9 +1458,9 @@ namespace GridMate continue; } - ReplicaPeer* source = replica->IsMaster() ? &m_self : replica->m_upstreamHop; + ReplicaPeer* source = replica->IsPrimary() ? &m_self : replica->m_upstreamHop; - if (replica->IsMaster() + if (replica->IsPrimary() || (IsSyncHost() && source->GetId() != target->GetId() && !(source->GetMode() == Mode_Peer && target->GetMode() == Mode_Peer))) { ReplicaTarget::AddReplicaTarget(target, replica.get()); @@ -1471,7 +1471,7 @@ namespace GridMate else { // Replica might've changed owner -> we need to update its targets accordingly - ReplicaPeer* source = replica->IsMaster() ? &m_self : replica->m_upstreamHop; + ReplicaPeer* source = replica->IsPrimary() ? &m_self : replica->m_upstreamHop; for (auto it = replica->m_targets.begin(); it != replica->m_targets.end(); ) { @@ -1652,14 +1652,14 @@ namespace GridMate } } //----------------------------------------------------------------------------- - void ReplicaManager::ChangeReplicaOwnership(ReplicaPtr replica, const ReplicaContext& rc, bool isMaster) + void ReplicaManager::ChangeReplicaOwnership(ReplicaPtr replica, const ReplicaContext& rc, bool isPrimary) { - bool wasMaster = replica->IsMaster(); - if (wasMaster != isMaster) // wasMaster == isMaster can happen when host's replica is moved to client, and client confirms with Cmd_NewOwner + bool wasPrimary = replica->IsPrimary(); + if (wasPrimary != isPrimary) // wasPrimary == isPrimary can happen when host's replica is moved to client, and client confirms with Cmd_NewOwner { - replica->SetMaster(isMaster); + replica->SetPrimary(isPrimary); replica->OnChangeOwnership(rc); - EBUS_EVENT(Debug::ReplicaDrillerBus, OnReplicaChangeOwnership, replica.get(), wasMaster); + EBUS_EVENT(Debug::ReplicaDrillerBus, OnReplicaChangeOwnership, replica.get(), wasPrimary); } } //----------------------------------------------------------------------------- diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.h b/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.h index 55b8551441..00de7e9e11 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.h +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaMgr.h @@ -190,7 +190,7 @@ namespace GridMate //----------------------------------------------------------------------------- struct ReplicaMgrDesc { - // Single-master roles that replica managers can have + // Single-primary roles that replica managers can have enum Roles { Role_SyncHost = 1 << 0, @@ -421,13 +421,13 @@ namespace GridMate size_t ReleaseIdBlock(PeerId requestor); void _Unmarshal(ReadBuffer& rb, ReplicaPeer* from); - void RegisterReplica(const ReplicaPtr& pReplica, bool isMaster, ReplicaContext& rc); + void RegisterReplica(const ReplicaPtr& pReplica, bool isPrimary, ReplicaContext& rc); void UnregisterReplica(const ReplicaPtr& replica, const ReplicaContext& rc); void RemoveReplicaFromDownstream(const ReplicaPtr& replica, const ReplicaContext& rc); void MigrateReplica(ReplicaPtr replica, PeerId newOwnerId); void AnnounceReplicaMigrated(ReplicaId replicaId, PeerId newOwnerId); void OnReplicaMigrated(ReplicaPtr replica, bool isOwner, const ReplicaContext& rc); - void ChangeReplicaOwnership(ReplicaPtr replica, const ReplicaContext& rc, bool isMaster); + void ChangeReplicaOwnership(ReplicaPtr replica, const ReplicaContext& rc, bool isPrimary); void AckUpstreamSuspended(ReplicaId replicaId, PeerId sendTo, AZ::u32 requestTime); void OnAckUpstreamSuspended(ReplicaId replicaId, PeerId from, AZ::u32 requestTime); void AckDownstream(ReplicaId replicaId, PeerId sendTo, AZ::u32 requestTime); @@ -595,7 +595,7 @@ namespace GridMate * Replicas */ virtual ReplicaPtr FindReplica(ReplicaId replicaId); - ReplicaId AddMaster(const ReplicaPtr& pMaster); + ReplicaId AddPrimary(const ReplicaPtr& pPrimary); /* * Tasks diff --git a/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h b/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h index 7e72dbab63..f3afb7747d 100644 --- a/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h +++ b/Code/Framework/GridMate/GridMate/Replica/ReplicaStatus.h @@ -50,10 +50,10 @@ namespace GridMate //! Called on the originator node to request replica migration. Rpc >::BindInterface RequestOwnership; - //! Called by the master to suspend upstream requests during replica migration. + //! Called by the primary to suspend upstream requests during replica migration. Rpc, RpcArg >::BindInterface MigrationSuspendUpstream; - //! Called by the master to signal downstream flush during replica migration. + //! Called by the primary to signal downstream flush during replica migration. Rpc, RpcArg >::BindInterface MigrationRequestDownstreamAck; struct ReplicaOptions diff --git a/Code/Framework/GridMate/GridMate/Replica/SystemReplicas.cpp b/Code/Framework/GridMate/GridMate/Replica/SystemReplicas.cpp index cbaf97ad1d..944524ed2f 100644 --- a/Code/Framework/GridMate/GridMate/Replica/SystemReplicas.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/SystemReplicas.cpp @@ -84,7 +84,7 @@ namespace GridMate // on activation of this replica, create our PeerInfo replica Replica* peerReplica = Replica::CreateReplica("PeerInfo"); CreateAndAttachReplicaChunk(peerReplica); - rc.m_rm->AddMaster(peerReplica); + rc.m_rm->AddPrimary(peerReplica); } //----------------------------------------------------------------------------- void SessionInfo::OnReplicaDeactivate(const ReplicaContext& rc) @@ -132,7 +132,7 @@ namespace GridMate (void)rc; if (m_pMgr->IsSyncHost()) { - AZ_Assert(IsMaster(), "The host should always own sessionInfo!!!"); + AZ_Assert(IsPrimary(), "The host should always own sessionInfo!!!"); AZ_Assert(m_pendingPeerReports.find(peerId) == m_pendingPeerReports.end(), "We are already waiting for reports for peer 0x%8x!", peerId); vector peers; @@ -205,7 +205,7 @@ namespace GridMate //----------------------------------------------------------------------------- void PeerReplica::OnReplicaActivate(const ReplicaContext& rc) { - if (IsMaster()) + if (IsPrimary()) { m_peerId.Set(rc.m_rm->GetLocalPeerId()); } diff --git a/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaMarshalTasks.cpp b/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaMarshalTasks.cpp index e295e74556..37c0c1d8c4 100644 --- a/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaMarshalTasks.cpp +++ b/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaMarshalTasks.cpp @@ -294,7 +294,7 @@ namespace GridMate //----------------------------------------------------------------------------- ReplicaTask::TaskStatus ReplicaMarshalZombieTask::Run(const RunContext& context) { - if (m_replica->IsMaster() || context.m_replicaManager->IsSyncHost()) + if (m_replica->IsPrimary() || context.m_replicaManager->IsSyncHost()) { m_replica->PrepareData(context.m_replicaManager->GetGridMate()->GetDefaultEndianType(), // A zombie task occurs right before replica gets removed, by design it needs to set all properties one last time. diff --git a/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaUpdateTasks.h b/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaUpdateTasks.h index 7d9d7e90fe..61e11ed56d 100644 --- a/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaUpdateTasks.h +++ b/Code/Framework/GridMate/GridMate/Replica/Tasks/ReplicaUpdateTasks.h @@ -35,7 +35,7 @@ namespace GridMate }; /** - * Task to update master & proxy replicas. + * Task to update primary & proxy replicas. * Processes RPCs and calls replicas UpdateFromReplica. Will complete immediately if no RPCs * left queued after processing, otherweise will be repeated next update tick. * Initiates replica migration if proxy owner has died. diff --git a/Code/Framework/GridMate/GridMate/Session/Session.cpp b/Code/Framework/GridMate/GridMate/Session/Session.cpp index cf9edff496..9e8aab50ec 100644 --- a/Code/Framework/GridMate/GridMate/Session/Session.cpp +++ b/Code/Framework/GridMate/GridMate/Session/Session.cpp @@ -960,7 +960,7 @@ GridSession::AddMember(GridMember* member) replica->AttachReplicaChunk(member); } - m_replicaMgr->AddMaster(replica); + m_replicaMgr->AddPrimary(replica); member->m_isHost.Set(member->IsLocal()); } @@ -1583,7 +1583,7 @@ GridSession::OnStateCreate(HSM& sm, const HSM::Event& e) // Bind session replica Replica* stateReplica = Replica::CreateReplica("SessionStateInfo"); stateReplica->AttachReplicaChunk(m_state); - m_replicaMgr->AddMaster(stateReplica); + m_replicaMgr->AddPrimary(stateReplica); // Bind member replica bool isAdded = AddMember(m_myMember); @@ -2005,7 +2005,7 @@ GridMember::OnReplicaActivate(const ReplicaContext& rc) { // if this member is me... add my state to the system. AZ_Assert(m_session->GetMyMember() == this, "The only local member should be myMember too!"); - rc.m_rm->AddMaster(m_clientState->GetReplica()); + rc.m_rm->AddPrimary(m_clientState->GetReplica()); // Both member and client state are valid! send member joined message EBUS_DBG_EVENT(Debug::SessionDrillerBus, OnMemberJoined, m_session, this); @@ -2052,7 +2052,7 @@ GridMember::OnReplicaChangeOwnership(const ReplicaContext& rc) { (void)rc; AZ_Assert(m_session->IsMigratingHost(), "This function can be called only during host migration!"); - if (IsMaster()) + if (IsPrimary()) { // Host owns the members, if I became the owner means I am the HOST! if (m_session->m_myMember == this) @@ -2084,7 +2084,7 @@ GridMember::OnKick(AZ::u8 reason, const RpcContext& rc) m_session->Leave(false); } - return true; // this is called only on the master + return true; // this is called only on the primary } return false; } @@ -2320,8 +2320,8 @@ void GridMemberStateReplica::OnReplicaDeactivate(const ReplicaContext& rc) { (void)rc; - // for master (this is our state) we always keep it. So don't do anything. - if (IsMaster()) + // for primary (this is our state) we always keep it. So don't do anything. + if (IsPrimary()) { return; } diff --git a/Code/Framework/GridMate/Tests/Interest.cpp b/Code/Framework/GridMate/Tests/Interest.cpp index b4fb9b7654..c449c92083 100644 --- a/Code/Framework/GridMate/Tests/Interest.cpp +++ b/Code/Framework/GridMate/Tests/Interest.cpp @@ -534,7 +534,7 @@ namespace GridMate auto replica = Replica::CreateReplica("ProximityInterestHandlerRules"); m_rulesReplica = CreateAndAttachReplicaChunk(replica); - m_rm->AddMaster(replica); + m_rm->AddPrimary(replica); } void ProximityInterestHandler::OnRulesHandlerUnregistered(InterestManager* manager) @@ -658,7 +658,7 @@ class Integ_InterestTest { AZ_Printf("GridMate", "InterestTestChunk::OnReplicaActivate repId=%08X(%s) fromPeerId=%08X localPeerId=%08X\n", GetReplicaId(), - IsMaster() ? "master" : "proxy", + IsPrimary() ? "primary" : "proxy", rc.m_peer ? rc.m_peer->GetId() : 0, rc.m_rm->GetLocalPeerId()); @@ -674,7 +674,7 @@ class Integ_InterestTest { AZ_Printf("GridMate", "InterestTestChunk::OnReplicaDeactivate repId=%08X(%s) fromPeerId=%08X localPeerId=%08X\n", GetReplicaId(), - IsMaster() ? "master" : "proxy", + IsPrimary() ? "primary" : "proxy", rc.m_peer ? rc.m_peer->GetId() : 0, rc.m_rm->GetLocalPeerId()); @@ -734,7 +734,7 @@ class Integ_InterestTest m_replica->m_data.Set(m_num); m_replica->m_bitmaskAttributeData.Set(1 << i); - m_session->GetReplicaMgr()->AddMaster(r); + m_session->GetReplicaMgr()->AddPrimary(r); } void UpdateAttribute() @@ -952,7 +952,7 @@ public: if (numUpdates == 250) { - // Checking everybody lost all replicas (except master) + // Checking everybody lost all replicas (except primary) for (int i = 0; i < k_numMachines; ++i) { for (int j = 0; j < k_numMachines; ++j) @@ -1079,11 +1079,11 @@ class LargeWorldTest void OnReplicaActivate(const ReplicaContext& rc) override { - /*if (!IsMaster())*/ + /*if (!IsPrimary())*/ /*{ AZ_Printf("GridMate", "LargeWorldTestChunk::OnReplicaActivate repId=%08X(%s) fromPeerId=%08X localPeerId=%08X\n", GetReplicaId(), - IsMaster() ? "master" : "proxy", + IsPrimary() ? "primary" : "proxy", rc.m_peer ? rc.m_peer->GetId() : 0, rc.m_rm->GetLocalPeerId()); }*/ @@ -1214,7 +1214,7 @@ class LargeWorldTest m_replicas.push_back(replica); - m_session->GetReplicaMgr()->AddMaster(r); + m_session->GetReplicaMgr()->AddPrimary(r); } void PopulateWorld() @@ -1453,7 +1453,7 @@ public: if (numUpdates == 250) { - // Checking everybody lost all replicas (except master) + // Checking everybody lost all replicas (except primary) for (int i = 0; i < k_numMachines; ++i) { /*for (int j = 0; j < k_numMachines; ++j) diff --git a/Code/Framework/GridMate/Tests/Replica.cpp b/Code/Framework/GridMate/Tests/Replica.cpp index 4d2f8d1e3a..624ee8c7e0 100644 --- a/Code/Framework/GridMate/Tests/Replica.cpp +++ b/Code/Framework/GridMate/Tests/Replica.cpp @@ -1615,7 +1615,7 @@ public: { (void)f; (void)rc; - AZ_TracePrintf("GridMate", "Executed MyHandler123 requested at %u with %g on %s at %u.\n", rc.m_timestamp, f, GetReplica()->IsMaster() ? "Master" : "Proxy", rc.m_realTime); + AZ_TracePrintf("GridMate", "Executed MyHandler123 requested at %u with %g on %s at %u.\n", rc.m_timestamp, f, GetReplica()->IsPrimary() ? "Primary" : "Proxy", rc.m_realTime); return true; } @@ -1653,14 +1653,14 @@ public: (void)rc; if (rc.m_rm->GetUserContext(12345)) { - AZ_TracePrintf("GridMate", "Activate %s with UserData:%p\n", GetReplica()->IsMaster() ? "master" : "proxy", rc.m_rm->GetUserContext(12345)); + AZ_TracePrintf("GridMate", "Activate %s with UserData:%p\n", GetReplica()->IsPrimary() ? "primary" : "proxy", rc.m_rm->GetUserContext(12345)); } if (IsProxy()) { Bind(aznew MyObj()); } - if (IsMaster()) + if (IsPrimary()) { EBUS_EVENT(MigratableReplicaDebugMsgs::EBus, OnNewOwner, GetReplicaId(), rc.m_rm); } @@ -1679,9 +1679,9 @@ public: void OnReplicaChangeOwnership(const ReplicaContext& rc) override { (void)rc; - AZ_TracePrintf("GridMate", "Migratable replica 0x%x became %s on Peer %d\n", (int) GetReplicaId(), IsMaster() ? "master" : "proxy", (int) rc.m_rm->GetLocalPeerId()); + AZ_TracePrintf("GridMate", "Migratable replica 0x%x became %s on Peer %d\n", (int) GetReplicaId(), IsPrimary() ? "primary" : "proxy", (int) rc.m_rm->GetLocalPeerId()); - if (IsMaster()) + if (IsPrimary()) { EBUS_EVENT(MigratableReplicaDebugMsgs::EBus, OnNewOwner, GetReplicaId(), rc.m_rm); } @@ -1725,7 +1725,7 @@ protected: { (void)f; (void)rc; - AZ_TracePrintf("GridMate", "Executed MyHandler123 requested at %u with %g on %s at %u.\n", rc.m_timestamp, f, IsMaster() ? "Master" : "Proxy", rc.m_realTime); + AZ_TracePrintf("GridMate", "Executed MyHandler123 requested at %u with %g on %s at %u.\n", rc.m_timestamp, f, IsPrimary() ? "Primary" : "Proxy", rc.m_realTime); return true; } bool MyHandler2(const float& f, int p2, const RpcContext& rc) @@ -1733,7 +1733,7 @@ protected: (void)f; (void)p2; (void)rc; - AZ_TracePrintf("GridMate", "Executed MyHandler2 requested at %u with %g,%d on %s at %u.\n", rc.m_timestamp, f, p2, IsMaster() ? "Master" : "Proxy", rc.m_realTime); + AZ_TracePrintf("GridMate", "Executed MyHandler2 requested at %u with %g,%d on %s at %u.\n", rc.m_timestamp, f, p2, IsPrimary() ? "Primary" : "Proxy", rc.m_realTime); return true; } bool MyHandler3(const float& f, int p2, EBla p3, const RpcContext& rc) @@ -1742,7 +1742,7 @@ protected: (void)p2; (void)p3; (void)rc; - AZ_TracePrintf("GridMate", "Executed MyHandler3 requested at %u with %g,%d,%d on %s at %u.\n", rc.m_timestamp, f, p2, p3, IsMaster() ? "Master" : "Proxy", rc.m_realTime); + AZ_TracePrintf("GridMate", "Executed MyHandler3 requested at %u with %g,%d,%d on %s at %u.\n", rc.m_timestamp, f, p2, p3, IsPrimary() ? "Primary" : "Proxy", rc.m_realTime); return true; } bool MyHandler4(const float& f, int p2, EBla p3, const IntVectorType& p4, const RpcContext& rc) @@ -1752,13 +1752,13 @@ protected: (void)p3; (void)p4; (void)rc; - AZ_TracePrintf("GridMate", "Executed MyHandler4 requested at %u with %g,%d,%d,%d,%d on %s at %u.\n", rc.m_timestamp, f, p2, p3, p4[0], p4[1], IsMaster() ? "Master" : "Proxy", rc.m_realTime); + AZ_TracePrintf("GridMate", "Executed MyHandler4 requested at %u with %g,%d,%d,%d,%d on %s at %u.\n", rc.m_timestamp, f, p2, p3, p4[0], p4[1], IsPrimary() ? "Primary" : "Proxy", rc.m_realTime); return true; } bool MyHandlerUnreliable(const int& i, const RpcContext& rc) { (void)rc; - AZ_TracePrintf("GridMate", "Executed MyHandlerUnreliable requested at %u with %d on %s at %u.\n", rc.m_timestamp, i, IsMaster() ? "Master" : "Proxy", rc.m_realTime); + AZ_TracePrintf("GridMate", "Executed MyHandlerUnreliable requested at %u with %d on %s at %u.\n", rc.m_timestamp, i, IsPrimary() ? "Primary" : "Proxy", rc.m_realTime); AZ_TEST_ASSERT(i > m_prevUnreliableValue); if ((i - m_prevUnreliableValue) > 1) { @@ -1824,7 +1824,7 @@ public: (void)rc; if (rc.m_rm->GetUserContext(12345)) { - AZ_TracePrintf("GridMate", "Activate %s with UserData:%p\n", IsMaster() ? "master" : "proxy", rc.m_rm->GetUserContext(12345)); + AZ_TracePrintf("GridMate", "Activate %s with UserData:%p\n", IsPrimary() ? "primary" : "proxy", rc.m_rm->GetUserContext(12345)); } if (IsProxy()) { @@ -1845,7 +1845,7 @@ public: void OnReplicaChangeOwnership(const ReplicaContext& rc) override { (void)rc; - AZ_TracePrintf("GridMate", "NonMigratable replica 0x%x became %s on Peer %d\n", (int) GetReplicaId(), IsMaster() ? "master" : "proxy", (int) rc.m_rm->GetLocalPeerId()); + AZ_TracePrintf("GridMate", "NonMigratable replica 0x%x became %s on Peer %d\n", (int) GetReplicaId(), IsPrimary() ? "primary" : "proxy", (int) rc.m_rm->GetLocalPeerId()); } void Bind(MyObj* pObj) @@ -1950,7 +1950,7 @@ TEST_F(Integ_ReplicaGMTest, ReplicaTest) // put something on s1 to get it going auto rep = Replica::CreateReplica(nullptr); s1rep1 = CreateAndAttachReplicaChunk(rep); - s1rep1id = sessions[s1].GetReplicaMgr().AddMaster(rep); + s1rep1id = sessions[s1].GetReplicaMgr().AddPrimary(rep); s1rep1->Bind(s1obj1 = aznew MyObj()); // connect s2 to s1 @@ -1993,7 +1993,7 @@ TEST_F(Integ_ReplicaGMTest, ReplicaTest) { auto newReplica = Replica::CreateReplica(nullptr); s2rep1 = CreateAndAttachReplicaChunk(newReplica); - s2rep1id = sessions[s2].GetReplicaMgr().AddMaster(newReplica); + s2rep1id = sessions[s2].GetReplicaMgr().AddPrimary(newReplica); s2rep1->Bind(s2obj1 = aznew MyObj()); } else @@ -2020,7 +2020,7 @@ TEST_F(Integ_ReplicaGMTest, ReplicaTest) { auto newReplica = Replica::CreateReplica(nullptr); s1rep2 = CreateAndAttachReplicaChunk(newReplica); - s1rep2id = sessions[s1].GetReplicaMgr().AddMaster(newReplica); + s1rep2id = sessions[s1].GetReplicaMgr().AddPrimary(newReplica); s1rep2->Bind(s1obj2 = aznew MyObj); } else @@ -2041,7 +2041,7 @@ TEST_F(Integ_ReplicaGMTest, ReplicaTest) { auto newReplica = Replica::CreateReplica(nullptr); s3rep1 = CreateAndAttachReplicaChunk(newReplica); - s3rep1id = sessions[s3].GetReplicaMgr().AddMaster(newReplica); + s3rep1id = sessions[s3].GetReplicaMgr().AddPrimary(newReplica); s3rep1->Bind(s3obj1 = aznew MyObj()); } else @@ -2289,13 +2289,13 @@ TEST_F(Integ_ForcedReplicaMigrationTest, ForcedReplicaMigrationTest) { auto rep = Replica::CreateReplica(nullptr); migrRep[i] = CreateAndAttachReplicaChunk(rep, aznew MyObj()); - peers[i].GetReplicaMgr().AddMaster(rep); + peers[i].GetReplicaMgr().AddPrimary(rep); AZ_TEST_ASSERT(m_replicaOwnership[migrRep[i]->GetReplicaId()] == &peers[i].GetReplicaMgr()); } { auto rep = Replica::CreateReplica(nullptr); nonMigrRep[i] = CreateAndAttachReplicaChunk(rep, aznew MyObj()); - peers[i].GetReplicaMgr().AddMaster(rep); + peers[i].GetReplicaMgr().AddPrimary(rep); } } addReplicas = false; @@ -2418,7 +2418,7 @@ public: void OnReplicaActivate(const ReplicaContext& rc) override { - if (IsMaster()) + if (IsPrimary()) { m_owner.Set(rc.m_rm->GetLocalPeerId() - 1); m_control.Set(rc.m_rm->GetLocalPeerId() - 1); @@ -2427,9 +2427,9 @@ public: void OnReplicaChangeOwnership(const ReplicaContext& rc) override { - if (IsMaster()) + if (IsPrimary()) { - AZ_TracePrintf("GridMate", "OnChangeOwnership: 0x%04x Became master on node %d\n", GetReplicaId(), rc.m_rm->GetLocalPeerId() - 1); + AZ_TracePrintf("GridMate", "OnChangeOwnership: 0x%04x Became primary on node %d\n", GetReplicaId(), rc.m_rm->GetLocalPeerId() - 1); m_owner.Set(rc.m_rm->GetLocalPeerId() - 1); } else @@ -2591,18 +2591,18 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) { auto rep = Replica::CreateReplica(nullptr); nodes[iNode].m_always = CreateAndAttachReplicaChunk(rep); - nodes[iNode].m_session.GetReplicaMgr().AddMaster(rep); + nodes[iNode].m_session.GetReplicaMgr().AddPrimary(rep); } { auto rep = Replica::CreateReplica(nullptr); nodes[iNode].m_never = CreateAndAttachReplicaChunk(rep); - nodes[iNode].m_session.GetReplicaMgr().AddMaster(rep); + nodes[iNode].m_session.GetReplicaMgr().AddPrimary(rep); } { auto rep = Replica::CreateReplica(nullptr); nodes[iNode].m_sometimes = CreateAndAttachReplicaChunk(rep); nodes[iNode].m_sometimes->m_acceptMigrationRequests = iNode == Peer1 || iNode == Client1; - nodes[iNode].m_session.GetReplicaMgr().AddMaster(rep); + nodes[iNode].m_session.GetReplicaMgr().AddPrimary(rep); } } } @@ -2675,7 +2675,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(nodes[Client1].m_always->m_accepted == 1); AZ_TEST_ASSERT(nodes[Client1].m_always->GetReplica()->IsProxy()); AZ_TEST_ASSERT(nodes[Client1].m_always->m_owner.Get() == Client2); - AZ_TEST_ASSERT(nodes[Client2].m_session.GetReplicaMgr().FindReplica(nodes[Client1].m_always->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Client2].m_session.GetReplicaMgr().FindReplica(nodes[Client1].m_always->GetReplicaId())->IsPrimary()); // C1 -> C2 -> Host (2nd migration) ReplicaPtr aHonC1 = nodes[Host].m_session.GetReplicaMgr().FindReplica(nodes[Client1].m_always->GetReplicaId()); @@ -2737,7 +2737,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(nodes[Peer1].m_always->m_accepted == 1); AZ_TEST_ASSERT(nodes[Peer1].m_always->GetReplica()->IsProxy()); AZ_TEST_ASSERT(nodes[Peer1].m_always->m_owner.Get() == Peer2); - AZ_TEST_ASSERT(nodes[Peer2].m_session.GetReplicaMgr().FindReplica(nodes[Peer1].m_always->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Peer2].m_session.GetReplicaMgr().FindReplica(nodes[Peer1].m_always->GetReplicaId())->IsPrimary()); AZ_TEST_ASSERT(nodes[Peer1].m_always->m_control.Get() == Peer2); // P2 -> Host -> C2 (both at same time, with C2 arriving second) @@ -2750,7 +2750,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(aP2onH->m_accepted == 1); AZ_TEST_ASSERT(aP2onH->GetReplica()->IsProxy()); AZ_TEST_ASSERT(aP2onH->m_owner.Get() == Client2); - AZ_TEST_ASSERT(nodes[Client2].m_session.GetReplicaMgr().FindReplica(nodes[Peer2].m_always->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Client2].m_session.GetReplicaMgr().FindReplica(nodes[Peer2].m_always->GetReplicaId())->IsPrimary()); AZ_TEST_ASSERT(nodes[Peer2].m_always->m_control.Get() == Client2); // Host -> C1 @@ -2758,7 +2758,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(nodes[Host].m_always->m_accepted == 1); AZ_TEST_ASSERT(nodes[Host].m_always->GetReplica()->IsProxy()); AZ_TEST_ASSERT(nodes[Host].m_always->m_owner.Get() == Client1); - AZ_TEST_ASSERT(nodes[Client1].m_session.GetReplicaMgr().FindReplica(nodes[Host].m_always->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Client1].m_session.GetReplicaMgr().FindReplica(nodes[Host].m_always->GetReplicaId())->IsPrimary()); AZ_TEST_ASSERT(nodes[Host].m_always->m_control.Get() == Client1); // C1 -> C2 -> Host (2nd migration) @@ -2771,7 +2771,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(aC1onC2->m_accepted == 1); AZ_TEST_ASSERT(aC1onC2->GetReplica()->IsProxy()); AZ_TEST_ASSERT(aC1onC2->m_owner.Get() == Host); - AZ_TEST_ASSERT(nodes[Host].m_session.GetReplicaMgr().FindReplica(nodes[Client1].m_always->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Host].m_session.GetReplicaMgr().FindReplica(nodes[Client1].m_always->GetReplicaId())->IsPrimary()); AZ_TEST_ASSERT(nodes[Client1].m_always->m_control.Get() == Host); // C2 -> P1 @@ -2779,13 +2779,13 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(nodes[Client2].m_always->m_accepted == 1); AZ_TEST_ASSERT(nodes[Client2].m_always->GetReplica()->IsProxy()); AZ_TEST_ASSERT(nodes[Client2].m_always->m_owner.Get() == Peer1); - AZ_TEST_ASSERT(nodes[Peer1].m_session.GetReplicaMgr().FindReplica(nodes[Client2].m_always->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Peer1].m_session.GetReplicaMgr().FindReplica(nodes[Client2].m_always->GetReplicaId())->IsPrimary()); AZ_TEST_ASSERT(nodes[Client2].m_always->m_control.Get() == Peer1); // P1 -> C1 (Forbidden) AZ_TEST_ASSERT(nodes[Peer1].m_never->m_requests == 0); AZ_TEST_ASSERT(nodes[Peer1].m_never->m_accepted == 0); - AZ_TEST_ASSERT(nodes[Peer1].m_never->GetReplica()->IsMaster()); + AZ_TEST_ASSERT(nodes[Peer1].m_never->GetReplica()->IsPrimary()); AZ_TEST_ASSERT(nodes[Peer1].m_never->m_owner.Get() == Peer1); AZ_TEST_ASSERT(nodes[Client1].m_session.GetReplicaMgr().FindReplica(nodes[Peer1].m_never->GetReplicaId())->IsProxy()); AZ_TEST_ASSERT(nodes[Peer1].m_never->m_control.Get() == Peer1); @@ -2793,7 +2793,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) // C2 -> P2 (Forbidden) AZ_TEST_ASSERT(nodes[Client2].m_never->m_requests == 0); AZ_TEST_ASSERT(nodes[Client2].m_never->m_accepted == 0); - AZ_TEST_ASSERT(nodes[Client2].m_never->GetReplica()->IsMaster()); + AZ_TEST_ASSERT(nodes[Client2].m_never->GetReplica()->IsPrimary()); AZ_TEST_ASSERT(nodes[Client2].m_never->m_owner.Get() == Client2); AZ_TEST_ASSERT(nodes[Peer2].m_session.GetReplicaMgr().FindReplica(nodes[Client2].m_never->GetReplicaId())->IsProxy()); AZ_TEST_ASSERT(nodes[Client2].m_never->m_control.Get() == Client2); @@ -2803,7 +2803,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(nodes[Peer1].m_sometimes->m_accepted == 1); AZ_TEST_ASSERT(nodes[Peer1].m_sometimes->GetReplica()->IsProxy()); AZ_TEST_ASSERT(nodes[Peer1].m_sometimes->m_owner.Get() == Host); - AZ_TEST_ASSERT(nodes[Host].m_session.GetReplicaMgr().FindReplica(nodes[Peer1].m_sometimes->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Host].m_session.GetReplicaMgr().FindReplica(nodes[Peer1].m_sometimes->GetReplicaId())->IsPrimary()); AZ_TEST_ASSERT(nodes[Peer1].m_sometimes->m_control.Get() == Host); // C1 -> P1 @@ -2811,13 +2811,13 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) AZ_TEST_ASSERT(nodes[Client1].m_sometimes->m_accepted == 1); AZ_TEST_ASSERT(nodes[Client1].m_sometimes->GetReplica()->IsProxy()); AZ_TEST_ASSERT(nodes[Client1].m_sometimes->m_owner.Get() == Peer1); - AZ_TEST_ASSERT(nodes[Peer1].m_session.GetReplicaMgr().FindReplica(nodes[Client1].m_sometimes->GetReplicaId())->IsMaster()); + AZ_TEST_ASSERT(nodes[Peer1].m_session.GetReplicaMgr().FindReplica(nodes[Client1].m_sometimes->GetReplicaId())->IsPrimary()); AZ_TEST_ASSERT(nodes[Client1].m_sometimes->m_control.Get() == Peer1); // P2 -> C2 (Forbidden) AZ_TEST_ASSERT(nodes[Peer2].m_sometimes->m_requests == 1); AZ_TEST_ASSERT(nodes[Peer2].m_sometimes->m_accepted == 0); - AZ_TEST_ASSERT(nodes[Peer2].m_sometimes->GetReplica()->IsMaster()); + AZ_TEST_ASSERT(nodes[Peer2].m_sometimes->GetReplica()->IsPrimary()); AZ_TEST_ASSERT(nodes[Peer2].m_sometimes->m_owner.Get() == Peer2); AZ_TEST_ASSERT(nodes[Client2].m_session.GetReplicaMgr().FindReplica(nodes[Peer2].m_never->GetReplicaId())->IsProxy()); AZ_TEST_ASSERT(nodes[Peer2].m_sometimes->m_control.Get() == Peer2); @@ -2825,7 +2825,7 @@ TEST_F(Integ_ReplicaMigrationRequestTest, ReplicaMigrationRequestTest) // C2 -> Host (Forbidden) AZ_TEST_ASSERT(nodes[Client2].m_sometimes->m_requests == 1); AZ_TEST_ASSERT(nodes[Client2].m_sometimes->m_accepted == 0); - AZ_TEST_ASSERT(nodes[Client2].m_sometimes->GetReplica()->IsMaster()); + AZ_TEST_ASSERT(nodes[Client2].m_sometimes->GetReplica()->IsPrimary()); AZ_TEST_ASSERT(nodes[Client2].m_sometimes->m_owner.Get() == Client2); AZ_TEST_ASSERT(nodes[Host].m_session.GetReplicaMgr().FindReplica(nodes[Client2].m_never->GetReplicaId())->IsProxy()); AZ_TEST_ASSERT(nodes[Client2].m_sometimes->m_control.Get() == Client2); @@ -2946,12 +2946,12 @@ TEST_F(Integ_PeerRejoinTest, PeerRejoinTest) { auto rep = Replica::CreateReplica(nullptr); migrRep[i] = CreateAndAttachReplicaChunk(rep, aznew MyObj()); - peers[i].GetReplicaMgr().AddMaster(rep); + peers[i].GetReplicaMgr().AddPrimary(rep); } { auto rep = Replica::CreateReplica(nullptr); nonMigrRep[i] = CreateAndAttachReplicaChunk(rep, aznew MyObj()); - peers[i].GetReplicaMgr().AddMaster(rep); + peers[i].GetReplicaMgr().AddPrimary(rep); } } addReplicas = false; @@ -3099,7 +3099,7 @@ public: { // make sure the requestor is set to s1 AZ_TEST_ASSERT(rpcContext.m_sourcePeer == s1 + 1); - if (IsMaster()) + if (IsPrimary()) { m_nAuthoritativeOnlyRpcCallsFromS1.Modify([](int& value) { ++value; return true; }); } @@ -3114,7 +3114,7 @@ public: { // make sure the requestor is set to s2 AZ_TEST_ASSERT(rpcContext.m_sourcePeer == s2 + 1); - if (IsMaster()) + if (IsPrimary()) { m_nAuthoritativeOnlyRpcCallsFromS2.Modify([](int& value) { ++value; return true; }); } @@ -3129,7 +3129,7 @@ public: { // make sure the requestor is set to s3 AZ_TEST_ASSERT(rpcContext.m_sourcePeer == s3 + 1); - if (IsMaster()) + if (IsPrimary()) { m_nAuthoritativeOnlyRpcCallsFromS3.Modify([](int& value) { ++value; return true; }); } @@ -3168,7 +3168,7 @@ TEST_F(Integ_ReplicationSecurityOptionsTest, ReplicationSecurityOptionsTest) ReplicaChunkDescriptorTable::Get().RegisterChunkType(); MPSession sessions[nSessions]; - ReplicaPtr masters[nSessions]; + ReplicaPtr primarys[nSessions]; // initialize transport int basePort = 4427; @@ -3202,10 +3202,10 @@ TEST_F(Integ_ReplicationSecurityOptionsTest, ReplicationSecurityOptionsTest) for (int i = 0; i < nSessions; ++i) { AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().IsReady()); - masters[i] = Replica::CreateReplica("ReplicationSecurityOptionsTest::TestReplica"); + primarys[i] = Replica::CreateReplica("ReplicationSecurityOptionsTest::TestReplica"); TestChunkPtr chunk = CreateReplicaChunk(); - masters[i]->AttachReplicaChunk(chunk); - sessions[i].GetReplicaMgr().AddMaster(masters[i]); + primarys[i]->AttachReplicaChunk(chunk); + sessions[i].GetReplicaMgr().AddPrimary(primarys[i]); } } @@ -3214,9 +3214,9 @@ TEST_F(Integ_ReplicationSecurityOptionsTest, ReplicationSecurityOptionsTest) AZ_TEST_START_TRACE_SUPPRESSION; for (int i = 0; i < nSessions; ++i) { - sessions[s1].GetReplicaMgr().FindReplica(masters[i]->GetRepId())->FindReplicaChunk()->ForwardSourcePeerRpcFromS1(); - sessions[s2].GetReplicaMgr().FindReplica(masters[i]->GetRepId())->FindReplicaChunk()->ForwardSourcePeerRpcFromS2(); - sessions[s3].GetReplicaMgr().FindReplica(masters[i]->GetRepId())->FindReplicaChunk()->ForwardSourcePeerRpcFromS3(); + sessions[s1].GetReplicaMgr().FindReplica(primarys[i]->GetRepId())->FindReplicaChunk()->ForwardSourcePeerRpcFromS1(); + sessions[s2].GetReplicaMgr().FindReplica(primarys[i]->GetRepId())->FindReplicaChunk()->ForwardSourcePeerRpcFromS2(); + sessions[s3].GetReplicaMgr().FindReplica(primarys[i]->GetRepId())->FindReplicaChunk()->ForwardSourcePeerRpcFromS3(); } } @@ -3227,36 +3227,36 @@ TEST_F(Integ_ReplicationSecurityOptionsTest, ReplicationSecurityOptionsTest) AZ_TEST_STOP_TRACE_SUPPRESSION(2); // All chunks should have received the call from the host - AZ_TEST_ASSERT(masters[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1 == 1); - AZ_TEST_ASSERT(masters[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1 == 1); - AZ_TEST_ASSERT(masters[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1 == 1); + AZ_TEST_ASSERT(primarys[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1 == 1); + AZ_TEST_ASSERT(primarys[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1 == 1); + AZ_TEST_ASSERT(primarys[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1 == 1); // the host chunk should have received calls from both clients - AZ_TEST_ASSERT(masters[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2 == 1); - AZ_TEST_ASSERT(masters[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3 == 1); + AZ_TEST_ASSERT(primarys[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2 == 1); + AZ_TEST_ASSERT(primarys[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3 == 1); // the chunk on s2 should receive its own call but not from s3 - AZ_TEST_ASSERT(masters[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2 == 1); - AZ_TEST_ASSERT(masters[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3 == 0); + AZ_TEST_ASSERT(primarys[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2 == 1); + AZ_TEST_ASSERT(primarys[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3 == 0); // the chunk on s3 should receive its own call but not from s2 - AZ_TEST_ASSERT(masters[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2 == 0); - AZ_TEST_ASSERT(masters[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3 == 1); + AZ_TEST_ASSERT(primarys[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2 == 0); + AZ_TEST_ASSERT(primarys[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3 == 1); // all datasets should have propagated properly for (int i = 0; i < nSessions; ++i) { - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get() == masters[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get() == masters[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get() == masters[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get() == primarys[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get() == primarys[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get() == primarys[s1]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get() == masters[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get() == masters[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get() == masters[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get() == primarys[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get() == primarys[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get() == primarys[s2]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get() == masters[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get() == masters[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get() == masters[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get() == primarys[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS1.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get() == primarys[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS2.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get() == primarys[s3]->FindReplicaChunk()->m_nForwardSourcePeerRpcCallsFromS3.Get()); } } @@ -3265,9 +3265,9 @@ TEST_F(Integ_ReplicationSecurityOptionsTest, ReplicationSecurityOptionsTest) AZ_TEST_START_TRACE_SUPPRESSION; for (int i = 0; i < nSessions; ++i) { - sessions[s1].GetReplicaMgr().FindReplica(masters[i]->GetRepId())->FindReplicaChunk()->AuthoritativeOnlyRpcFromS1(); - sessions[s2].GetReplicaMgr().FindReplica(masters[i]->GetRepId())->FindReplicaChunk()->AuthoritativeOnlyRpcFromS2(); - sessions[s3].GetReplicaMgr().FindReplica(masters[i]->GetRepId())->FindReplicaChunk()->AuthoritativeOnlyRpcFromS3(); + sessions[s1].GetReplicaMgr().FindReplica(primarys[i]->GetRepId())->FindReplicaChunk()->AuthoritativeOnlyRpcFromS1(); + sessions[s2].GetReplicaMgr().FindReplica(primarys[i]->GetRepId())->FindReplicaChunk()->AuthoritativeOnlyRpcFromS2(); + sessions[s3].GetReplicaMgr().FindReplica(primarys[i]->GetRepId())->FindReplicaChunk()->AuthoritativeOnlyRpcFromS3(); } } @@ -3278,40 +3278,40 @@ TEST_F(Integ_ReplicationSecurityOptionsTest, ReplicationSecurityOptionsTest) AZ_TEST_STOP_TRACE_SUPPRESSION(6); // Each chunk should have received their own AuthoritativeOnlyRpc once. - AZ_TEST_ASSERT(masters[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1 == 1); - AZ_TEST_ASSERT(masters[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2 == 1); - AZ_TEST_ASSERT(masters[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3 == 1); + AZ_TEST_ASSERT(primarys[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1 == 1); + AZ_TEST_ASSERT(primarys[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2 == 1); + AZ_TEST_ASSERT(primarys[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3 == 1); // Calls from other nodes should have been discarded. - AZ_TEST_ASSERT(masters[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2 == 0); - AZ_TEST_ASSERT(masters[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3 == 0); - AZ_TEST_ASSERT(masters[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1 == 0); - AZ_TEST_ASSERT(masters[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3 == 0); - AZ_TEST_ASSERT(masters[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1 == 0); - AZ_TEST_ASSERT(masters[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2 == 0); + AZ_TEST_ASSERT(primarys[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2 == 0); + AZ_TEST_ASSERT(primarys[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3 == 0); + AZ_TEST_ASSERT(primarys[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1 == 0); + AZ_TEST_ASSERT(primarys[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3 == 0); + AZ_TEST_ASSERT(primarys[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1 == 0); + AZ_TEST_ASSERT(primarys[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2 == 0); // Calls should have successfully propagated to the other 2 proxies - AZ_TEST_ASSERT(sessions[s1].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS2 == 1); - AZ_TEST_ASSERT(sessions[s1].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS3 == 1); - AZ_TEST_ASSERT(sessions[s2].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS1 == 1); - AZ_TEST_ASSERT(sessions[s2].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS3 == 1); - AZ_TEST_ASSERT(sessions[s3].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS1 == 1); - AZ_TEST_ASSERT(sessions[s3].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS2 == 1); + AZ_TEST_ASSERT(sessions[s1].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS2 == 1); + AZ_TEST_ASSERT(sessions[s1].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS3 == 1); + AZ_TEST_ASSERT(sessions[s2].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS1 == 1); + AZ_TEST_ASSERT(sessions[s2].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS3 == 1); + AZ_TEST_ASSERT(sessions[s3].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS1 == 1); + AZ_TEST_ASSERT(sessions[s3].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyProxyRpcCallsFromS2 == 1); // all datasets should have propagated properly for (int i = 0; i < nSessions; ++i) { - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get() == masters[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get() == masters[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get() == masters[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get() == primarys[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get() == primarys[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s1]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get() == primarys[s1]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get() == masters[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get() == masters[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get() == masters[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get() == primarys[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get() == primarys[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s2]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get() == primarys[s2]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get() == masters[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get() == masters[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get()); - AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(masters[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get() == masters[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get() == primarys[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS1.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get() == primarys[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS2.Get()); + AZ_TEST_ASSERT(sessions[i].GetReplicaMgr().FindReplica(primarys[s3]->GetRepId())->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get() == primarys[s3]->FindReplicaChunk()->m_nAuthoritativeOnlyRpcCallsFromS3.Get()); } } @@ -3594,7 +3594,7 @@ public: auto rep = Replica::CreateReplica(nullptr); auto chunk = CreateAndAttachReplicaChunk(rep); replicas.push_back(AZStd::make_pair(rep, chunk)); - session.GetReplicaMgr().AddMaster(rep); + session.GetReplicaMgr().AddPrimary(rep); } } @@ -3730,7 +3730,7 @@ public: { auto rep = Replica::CreateReplica(nullptr); chunks[i] = CreateAndAttachReplicaChunk(rep); - sessions[sHost].GetReplicaMgr().AddMaster(rep); + sessions[sHost].GetReplicaMgr().AddPrimary(rep); } // connect to host diff --git a/Code/Framework/GridMate/Tests/ReplicaBehavior.cpp b/Code/Framework/GridMate/Tests/ReplicaBehavior.cpp index 3f9db2ba0e..c3dac305db 100644 --- a/Code/Framework/GridMate/Tests/ReplicaBehavior.cpp +++ b/Code/Framework/GridMate/Tests/ReplicaBehavior.cpp @@ -687,7 +687,7 @@ namespace ReplicaBehavior { AZ_TEST_ASSERT(chunk->Data1.IsDefaultValue()); AZ_TEST_ASSERT(chunk->Data2.IsDefaultValue()); - m_replicaIdDefault = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaIdDefault = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } } @@ -725,7 +725,7 @@ namespace ReplicaBehavior { AZ_TEST_ASSERT(!chunk->Data1.IsDefaultValue()); AZ_TEST_ASSERT(!chunk->Data2.IsDefaultValue()); - m_replicaIdModified = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaIdModified = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } break; } @@ -816,7 +816,7 @@ namespace ReplicaBehavior { LargeChunkWithDefaults* chunk = CreateAndAttachReplicaChunk(replica); AZ_TEST_ASSERT(chunk); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } ~Integ_ReplicaDefaultDataSetDriller() @@ -923,13 +923,13 @@ namespace ReplicaBehavior { ChunkWithBools* chunk1 = CreateAndAttachReplicaChunk(replica1); AZ_TEST_ASSERT(chunk1); - m_replicaBoolsId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica1); + m_replicaBoolsId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica1); ReplicaPtr replica2 = Replica::CreateReplica(nullptr); ChunkWithShortInts* chunk2 = CreateAndAttachReplicaChunk(replica2); AZ_TEST_ASSERT(chunk2); - m_replicaU8Id = m_sessions[sHost].GetReplicaMgr().AddMaster(replica2); + m_replicaU8Id = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica2); } ~Integ_Replica_ComparePackingBoolsVsU8() @@ -1058,7 +1058,7 @@ namespace ReplicaBehavior { auto chunk = CreateAndAttachReplicaChunk(replica); AZ_TEST_ASSERT(chunk); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } ~Integ_CheckDataSetStreamIsntWrittenMoreThanNecessary() @@ -1155,7 +1155,7 @@ namespace ReplicaBehavior { auto chunk = CreateAndAttachReplicaChunk(replica); AZ_TEST_ASSERT(chunk); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } ~Integ_CheckDataSetStreamIsntWrittenMoreThanNecessaryOnceDirty() @@ -1249,7 +1249,7 @@ namespace ReplicaBehavior { ForcingDirtyTestChunk* chunk = CreateAndAttachReplicaChunk(replica); AZ_TEST_ASSERT(chunk); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } ~Integ_CheckReplicaIsntSentWithNoChanges() @@ -1360,7 +1360,7 @@ namespace ReplicaBehavior { auto chunk = CreateAndAttachReplicaChunk(replica); AZ_TEST_ASSERT(chunk); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } ~Integ_CheckEntityScriptReplicaIsntSentWithNoChanges() diff --git a/Code/Framework/GridMate/Tests/ReplicaMedium.cpp b/Code/Framework/GridMate/Tests/ReplicaMedium.cpp index 7c04c26487..fbdf4ee493 100644 --- a/Code/Framework/GridMate/Tests/ReplicaMedium.cpp +++ b/Code/Framework/GridMate/Tests/ReplicaMedium.cpp @@ -73,12 +73,12 @@ public: static const char* GetChunkName() { return "RPCChunk"; } RPCChunk() - : m_fromMasterBroadcast(0) - , m_fromMasterNotBroadcast(0) + : m_fromPrimaryBroadcast(0) + , m_fromPrimaryNotBroadcast(0) , m_fromProxyBroadcast(0) , m_fromProxyNotBroadcast(0) - , FromMasterBroadcast("FromMasterBroadcast") - , FromMasterNotBroadcast("FromMasterNotBroadcast") + , FromPrimaryBroadcast("FromPrimaryBroadcast") + , FromPrimaryNotBroadcast("FromPrimaryNotBroadcast") , FromProxyBroadcast("FromProxyBroadcast") , FromProxyNotBroadcast("FromProxyNotBroadcast") , BroadcastInt("BroadcastInt") @@ -86,30 +86,30 @@ public: bool IsReplicaMigratable() override { return false; } - bool FromMasterBroadcastFn(const RpcContext&) + bool FromPrimaryBroadcastFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed FromMasterBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); - m_fromMasterBroadcast++; + AZ_TracePrintf("GridMate", "Executed FromPrimaryBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); + m_fromPrimaryBroadcast++; return true; } - bool FromMasterNotBroadcastFn(const RpcContext&) + bool FromPrimaryNotBroadcastFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed FromMasterNotBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); - m_fromMasterNotBroadcast++; + AZ_TracePrintf("GridMate", "Executed FromPrimaryNotBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); + m_fromPrimaryNotBroadcast++; return false; } bool FromProxyBroadcastFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed FromProxyBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); + AZ_TracePrintf("GridMate", "Executed FromProxyBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); m_fromProxyBroadcast++; return true; } bool FromProxyNotBroadcastFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed FromProxyNotBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); + AZ_TracePrintf("GridMate", "Executed FromProxyNotBroadcast %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); m_fromProxyNotBroadcast++; return false; } @@ -120,14 +120,14 @@ public: return true; } - int m_fromMasterBroadcast; - int m_fromMasterNotBroadcast; + int m_fromPrimaryBroadcast; + int m_fromPrimaryNotBroadcast; int m_fromProxyBroadcast; int m_fromProxyNotBroadcast; AZStd::vector m_sentData; - Rpc<>::BindInterface FromMasterBroadcast; - Rpc<>::BindInterface FromMasterNotBroadcast; + Rpc<>::BindInterface FromPrimaryBroadcast; + Rpc<>::BindInterface FromPrimaryNotBroadcast; Rpc<>::BindInterface FromProxyBroadcast; Rpc<>::BindInterface FromProxyNotBroadcast; Rpc >::BindInterface BroadcastInt; @@ -158,21 +158,21 @@ public: bool Zero(const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[0]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[0]; (void) list; return true; } bool One(AZ::u32 t1, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[1]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[1]; list.push_back(t1); return true; } bool Two(AZ::u32 t1, AZ::u32 t2, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[2]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[2]; list.push_back(t1); list.push_back(t2); return true; @@ -180,7 +180,7 @@ public: bool Three(AZ::u32 t1, AZ::u32 t2, AZ::u32 t3, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[3]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[3]; list.push_back(t1); list.push_back(t2); list.push_back(t3); @@ -189,7 +189,7 @@ public: bool Four(AZ::u32 t1, AZ::u32 t2, AZ::u32 t3, AZ::u32 t4, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[4]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[4]; list.push_back(t1); list.push_back(t2); list.push_back(t3); @@ -199,7 +199,7 @@ public: bool Five(AZ::u32 t1, AZ::u32 t2, AZ::u32 t3, AZ::u32 t4, AZ::u32 t5, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[5]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[5]; list.push_back(t1); list.push_back(t2); list.push_back(t3); @@ -210,7 +210,7 @@ public: bool Six(AZ::u32 t1, AZ::u32 t2, AZ::u32 t3, AZ::u32 t4, AZ::u32 t5, AZ::u32 t6, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[6]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[6]; list.push_back(t1); list.push_back(t2); list.push_back(t3); @@ -222,7 +222,7 @@ public: bool Seven(AZ::u32 t1, AZ::u32 t2, AZ::u32 t3, AZ::u32 t4, AZ::u32 t5, AZ::u32 t6, AZ::u32 t7, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[7]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[7]; list.push_back(t1); list.push_back(t2); list.push_back(t3); @@ -235,7 +235,7 @@ public: bool Eight(AZ::u32 t1, AZ::u32 t2, AZ::u32 t3, AZ::u32 t4, AZ::u32 t5, AZ::u32 t6, AZ::u32 t7, AZ::u32 t8, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[8]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[8]; list.push_back(t1); list.push_back(t2); list.push_back(t3); @@ -249,7 +249,7 @@ public: bool Nine(AZ::u32 t1, AZ::u32 t2, AZ::u32 t3, AZ::u32 t4, AZ::u32 t5, AZ::u32 t6, AZ::u32 t7, AZ::u32 t8, AZ::u32 t9, const RpcContext&) { - auto& list = (IsMaster() ? m_sentData : m_receivedData)[9]; + auto& list = (IsPrimary() ? m_sentData : m_receivedData)[9]; list.push_back(t1); list.push_back(t2); list.push_back(t3); @@ -890,7 +890,7 @@ public: // put something on s1 to get it going auto replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } RPCChunk::Ptr m_chunk; @@ -905,11 +905,11 @@ TEST_F(Integ_ReplicaChunkRPCExec, ReplicaChunkRPCExec) switch (tick) { case 10: - m_chunk->FromMasterBroadcast(); + m_chunk->FromPrimaryBroadcast(); break; case 20: - m_chunk->FromMasterNotBroadcast(); + m_chunk->FromPrimaryNotBroadcast(); break; case 30: @@ -932,13 +932,13 @@ TEST_F(Integ_ReplicaChunkRPCExec, ReplicaChunkRPCExec) auto s2proxy = m_sessions[s2].GetReplicaMgr().FindReplica(m_replicaId)->FindReplicaChunk(); auto s3proxy = m_sessions[s3].GetReplicaMgr().FindReplica(m_replicaId)->FindReplicaChunk(); - AZ_TEST_ASSERT(s1host->m_fromMasterBroadcast == 1); - AZ_TEST_ASSERT(s2proxy->m_fromMasterBroadcast == 1); - AZ_TEST_ASSERT(s3proxy->m_fromMasterBroadcast == 1); + AZ_TEST_ASSERT(s1host->m_fromPrimaryBroadcast == 1); + AZ_TEST_ASSERT(s2proxy->m_fromPrimaryBroadcast == 1); + AZ_TEST_ASSERT(s3proxy->m_fromPrimaryBroadcast == 1); - AZ_TEST_ASSERT(s1host->m_fromMasterNotBroadcast == 1); - AZ_TEST_ASSERT(s2proxy->m_fromMasterNotBroadcast == 0); - AZ_TEST_ASSERT(s3proxy->m_fromMasterNotBroadcast == 0); + AZ_TEST_ASSERT(s1host->m_fromPrimaryNotBroadcast == 1); + AZ_TEST_ASSERT(s2proxy->m_fromPrimaryNotBroadcast == 0); + AZ_TEST_ASSERT(s3proxy->m_fromPrimaryNotBroadcast == 0); AZ_TEST_ASSERT(s1host->m_fromProxyBroadcast == 1); AZ_TEST_ASSERT(s2proxy->m_fromProxyBroadcast == 1); @@ -965,12 +965,12 @@ public: GM_CLASS_ALLOCATOR(DestroyRPCChunk); DestroyRPCChunk() - : DestroyFromMaster("DestroyFromMaster") + : DestroyFromPrimary("DestroyFromPrimary") , DestroyFromProxy("DestroyFromProxy") , BeforeDestroyFromProxy("BeforeDestroyFromProxy") , AfterDestroyFromProxy("AfterDestroyFromProxy") - , BeforeDestroyFromMaster("BeforeDestroyFromMaster") - , AfterDestroyFromMaster("AfterDestroyFromMaster") + , BeforeDestroyFromPrimary("BeforeDestroyFromPrimary") + , AfterDestroyFromPrimary("AfterDestroyFromPrimary") { } @@ -979,11 +979,11 @@ public: bool IsReplicaMigratable() override { return false; } - bool DestroyFromMasterFn(const RpcContext&) + bool DestroyFromPrimaryFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed DestroyFromMaster %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); - ++s_destroyFromMasterCalls; - if (GetReplica()->IsMaster()) + AZ_TracePrintf("GridMate", "Executed DestroyFromPrimary %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); + ++s_destroyFromPrimaryCalls; + if (GetReplica()->IsPrimary()) { GetReplica()->Destroy(); } @@ -992,9 +992,9 @@ public: bool DestroyFromProxyFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed DestroyFromProxy %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); + AZ_TracePrintf("GridMate", "Executed DestroyFromProxy %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); ++s_destroyFromProxyCalls; - if (GetReplica()->IsMaster()) + if (GetReplica()->IsPrimary()) { GetReplica()->Destroy(); } @@ -1003,53 +1003,53 @@ public: bool BeforeDestroyFromProxyFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed BeforeDestroyFromProxy %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); + AZ_TracePrintf("GridMate", "Executed BeforeDestroyFromProxy %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); ++s_beforeDestroyFromProxyCalls; return true; } bool AfterDestroyFromProxyFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed AfterDestroyFromProxy %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); + AZ_TracePrintf("GridMate", "Executed AfterDestroyFromProxy %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); ++s_afterDestroyFromProxyCalls; return true; } - bool BeforeDestroyFromMasterFn(const RpcContext&) + bool BeforeDestroyFromPrimaryFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed BeforeDestroyFromMaster %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); - ++s_beforeDestroyFromMasterCalls; + AZ_TracePrintf("GridMate", "Executed BeforeDestroyFromPrimary %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); + ++s_beforeDestroyFromPrimaryCalls; return true; } - bool AfterDestroyFromMasterFn(const RpcContext&) + bool AfterDestroyFromPrimaryFn(const RpcContext&) { - AZ_TracePrintf("GridMate", "Executed AfterDestroyFromMaster %d %s\n", GetReplicaId(), GetReplica()->IsMaster() ? "master" : "proxy"); - ++s_afterDestroyFromMasterCalls; + AZ_TracePrintf("GridMate", "Executed AfterDestroyFromPrimary %d %s\n", GetReplicaId(), GetReplica()->IsPrimary() ? "primary" : "proxy"); + ++s_afterDestroyFromPrimaryCalls; return true; } - Rpc<>::BindInterface DestroyFromMaster; + Rpc<>::BindInterface DestroyFromPrimary; Rpc<>::BindInterface DestroyFromProxy; Rpc<>::BindInterface BeforeDestroyFromProxy; Rpc<>::BindInterface AfterDestroyFromProxy; - Rpc<>::BindInterface BeforeDestroyFromMaster; - Rpc<>::BindInterface AfterDestroyFromMaster; + Rpc<>::BindInterface BeforeDestroyFromPrimary; + Rpc<>::BindInterface AfterDestroyFromPrimary; - static int s_destroyFromMasterCalls; - static int s_beforeDestroyFromMasterCalls; - static int s_afterDestroyFromMasterCalls; + static int s_destroyFromPrimaryCalls; + static int s_beforeDestroyFromPrimaryCalls; + static int s_afterDestroyFromPrimaryCalls; static int s_destroyFromProxyCalls; static int s_beforeDestroyFromProxyCalls; static int s_afterDestroyFromProxyCalls; }; int DestroyRPCChunk::s_destroyFromProxyCalls = 0; -int DestroyRPCChunk::s_destroyFromMasterCalls = 0; +int DestroyRPCChunk::s_destroyFromPrimaryCalls = 0; int DestroyRPCChunk::s_beforeDestroyFromProxyCalls = 0; int DestroyRPCChunk::s_afterDestroyFromProxyCalls = 0; -int DestroyRPCChunk::s_beforeDestroyFromMasterCalls = 0; -int DestroyRPCChunk::s_afterDestroyFromMasterCalls = 0; +int DestroyRPCChunk::s_beforeDestroyFromPrimaryCalls = 0; +int DestroyRPCChunk::s_afterDestroyFromPrimaryCalls = 0; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- @@ -1077,7 +1077,7 @@ public: { auto replica = Replica::CreateReplica(nullptr); CreateAndAttachReplicaChunk(replica); - m_repId[i] = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_repId[i] = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } } @@ -1092,12 +1092,12 @@ TEST_F(Integ_ReplicaDestroyedInRPC, ReplicaDestroyedInRPC) { case 10: { - // calling destroy on master - auto master = m_sessions[sHost].GetReplicaMgr().FindReplica(m_repId[0]); - auto masterChunk = master->FindReplicaChunk(); - masterChunk->BeforeDestroyFromMaster(); - masterChunk->DestroyFromMaster(); - masterChunk->AfterDestroyFromMaster(); + // calling destroy on primary + auto primary = m_sessions[sHost].GetReplicaMgr().FindReplica(m_repId[0]); + auto primaryChunk = primary->FindReplicaChunk(); + primaryChunk->BeforeDestroyFromPrimary(); + primaryChunk->DestroyFromPrimary(); + primaryChunk->AfterDestroyFromPrimary(); // calling destroy on proxy auto proxy = m_sessions[s2].GetReplicaMgr().FindReplica(m_repId[1]); @@ -1113,15 +1113,15 @@ TEST_F(Integ_ReplicaDestroyedInRPC, ReplicaDestroyedInRPC) { // checking if before destroy RPC was called on every peer AZ_TEST_ASSERT(DestroyRPCChunk::s_beforeDestroyFromProxyCalls == nSessions); - AZ_TEST_ASSERT(DestroyRPCChunk::s_beforeDestroyFromMasterCalls == nSessions); + AZ_TEST_ASSERT(DestroyRPCChunk::s_beforeDestroyFromPrimaryCalls == nSessions); // checking if destroy itself was called on every peer AZ_TEST_ASSERT(DestroyRPCChunk::s_destroyFromProxyCalls == nSessions); - AZ_TEST_ASSERT(DestroyRPCChunk::s_destroyFromMasterCalls == nSessions); + AZ_TEST_ASSERT(DestroyRPCChunk::s_destroyFromPrimaryCalls == nSessions); // checking if after destroy RPC was never called AZ_TEST_ASSERT(DestroyRPCChunk::s_afterDestroyFromProxyCalls == 0); // RPCs that arrive via the network after deactivation should be dropped. - AZ_TEST_ASSERT(DestroyRPCChunk::s_afterDestroyFromMasterCalls == 1); // RPCs explicitly called on an inactive replica should still be executed. + AZ_TEST_ASSERT(DestroyRPCChunk::s_afterDestroyFromPrimaryCalls == 1); // RPCs explicitly called on an inactive replica should still be executed. return TestStatus::Completed; } @@ -1157,7 +1157,7 @@ public: { // put something on s1 to get it going m_replica = Replica::CreateReplica(nullptr); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); } ReplicaPtr m_replica; @@ -1232,7 +1232,7 @@ public: // put something on s1 to get it going m_replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(m_replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); } ReplicaPtr m_replica; @@ -1286,7 +1286,7 @@ public: // put something on s1 to get it going m_replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(m_replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); } ReplicaPtr m_replica; @@ -1391,7 +1391,7 @@ public: { // put something on s1 to get it going m_replica = Replica::CreateReplica(nullptr); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); } @@ -1453,7 +1453,7 @@ public: { ReplicaPtr replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); AZ_TEST_ASSERT(m_chunk->m_attaches == 1); AZ_TEST_ASSERT(m_chunk->m_activates == 1); @@ -1531,7 +1531,7 @@ public: auto chunk = CreateAndAttachReplicaChunk(replica); AZ_TEST_ASSERT(chunk); } - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); auto numChunks = replica->GetNumChunks(); AZ_TEST_ASSERT(numChunks == GM_MAX_CHUNKS_PER_REPLICA); @@ -1594,7 +1594,7 @@ public: { m_replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(m_replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); AZ_TEST_ASSERT(m_chunk->m_attaches == 1); AZ_TEST_ASSERT(m_chunk->m_activates == 1); @@ -1820,16 +1820,16 @@ public: ++m_numRequestChangeOwnership; } - void OnReplicaChangeOwnership(Replica* replica, bool wasMaster) override + void OnReplicaChangeOwnership(Replica* replica, bool wasPrimary) override { AZ_TEST_ASSERT(replica); switch (m_numChangedOwnership) { case 0: // host loses ownership - AZ_TEST_ASSERT(replica->IsProxy() && wasMaster == true); + AZ_TEST_ASSERT(replica->IsProxy() && wasPrimary == true); break; case 1: // peer acquires ownership - AZ_TEST_ASSERT(replica->IsMaster() && wasMaster == false); + AZ_TEST_ASSERT(replica->IsPrimary() && wasPrimary == false); break; default: AZ_TEST_ASSERT(0); @@ -2008,7 +2008,7 @@ public: ReplicaPtr replica = Replica::CreateReplica(nullptr); CreateAndAttachReplicaChunk(replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } ~Integ_ReplicaDriller() @@ -2038,7 +2038,7 @@ TEST_F(Integ_ReplicaDriller, ReplicaDriller) { auto rep = m_sessions[s2].GetReplicaMgr().FindReplica(m_replicaId); AZ_TEST_ASSERT(rep); - AZ_TEST_ASSERT(rep->IsMaster()); + AZ_TEST_ASSERT(rep->IsPrimary()); rep->Destroy(); break; } @@ -2110,7 +2110,7 @@ public: { m_replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(m_replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); } @@ -2172,16 +2172,16 @@ public: { m_replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(m_replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); - m_masterHandler.reset(aznew CustomHandler()); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); + m_primaryHandler.reset(aznew CustomHandler()); m_proxyHandler.reset(aznew CustomHandler()); - m_chunk->SetHandler(m_masterHandler.get()); + m_chunk->SetHandler(m_primaryHandler.get()); } ReplicaPtr m_replica; ReplicaId m_replicaId; CustomHandlerChunk::Ptr m_chunk; - AZStd::scoped_ptr m_masterHandler; + AZStd::scoped_ptr m_primaryHandler; AZStd::scoped_ptr m_proxyHandler; }; @@ -2262,7 +2262,7 @@ public: { m_replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(m_replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); } ReplicaPtr m_replica; @@ -2338,7 +2338,7 @@ public: { m_replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(m_replica); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(m_replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(m_replica); } ReplicaPtr m_replica; @@ -2488,7 +2488,7 @@ public: m_chunks[i] = CreateAndAttachReplicaChunk(replica); m_chunks[i]->m_value.Set(i + 1); // setting dataset values to 1..kNumReplicas m_chunks[i]->SetPriority(k_replicaPriorityNormal + static_cast(i)); // the later created - the higher priorities, so should be sent in reverse order - m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } } @@ -2594,7 +2594,7 @@ public: ReplicaPtr replica = Replica::CreateReplica(nullptr); m_chunk = CreateAndAttachReplicaChunk(replica); - m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } SuspendUpdatesChunk::Ptr m_chunk = nullptr; @@ -2684,9 +2684,9 @@ public: void OnReplicaActivate(const GridMate::ReplicaContext&) override { - if (IsMaster()) + if (IsPrimary()) { - nMasterActivations++; + nPrimaryActivations++; } else { @@ -2694,11 +2694,11 @@ public: } } - static int nMasterActivations; + static int nPrimaryActivations; static int nProxyActivations; }; }; -int Integ_BasicHostChunkDescriptorTest::HostChunk::nMasterActivations = 0; +int Integ_BasicHostChunkDescriptorTest::HostChunk::nPrimaryActivations = 0; int Integ_BasicHostChunkDescriptorTest::HostChunk::nProxyActivations = 0; TEST_F(Integ_BasicHostChunkDescriptorTest, BasicHostChunkDescriptorTest) @@ -2744,25 +2744,25 @@ TEST_F(Integ_BasicHostChunkDescriptorTest, BasicHostChunkDescriptorTest) { hostReplica = Replica::CreateReplica("HostReplica"); hostReplica->AttachReplicaChunk(CreateReplicaChunk()); - nodes[Host].GetReplicaMgr().AddMaster(hostReplica); + nodes[Host].GetReplicaMgr().AddPrimary(hostReplica); } if (tick == 300) { - AZ_TEST_ASSERT(HostChunk::nMasterActivations == 1); + AZ_TEST_ASSERT(HostChunk::nPrimaryActivations == 1); AZ_TEST_ASSERT(HostChunk::nProxyActivations == 1); AZ_TEST_ASSERT(nodes[Client].GetReplicaMgr().FindReplica(hostReplica->GetRepId())->FindReplicaChunk()); AZ_TEST_START_TRACE_SUPPRESSION; clientReplica = Replica::CreateReplica("ClientReplica"); clientReplica->AttachReplicaChunk(CreateReplicaChunk()); - nodes[Client].GetReplicaMgr().AddMaster(clientReplica); + nodes[Client].GetReplicaMgr().AddPrimary(clientReplica); } if (tick == 400) { AZ_TEST_STOP_TRACE_SUPPRESSION(1); - AZ_TEST_ASSERT(HostChunk::nMasterActivations == 2); + AZ_TEST_ASSERT(HostChunk::nPrimaryActivations == 2); AZ_TEST_ASSERT(HostChunk::nProxyActivations == 1); AZ_TEST_ASSERT(!nodes[Host].GetReplicaMgr().FindReplica(clientReplica->GetRepId())->FindReplicaChunk()); } @@ -2792,10 +2792,10 @@ TEST_F(Integ_BasicHostChunkDescriptorTest, BasicHostChunkDescriptorTest) } /* - * Create and immedietly destroy master replica + * Create and immedietly destroy primary replica * Test that it does not result in any network sync */ -class Integ_CreateDestroyMaster +class Integ_CreateDestroyPrimary : public Integ_SimpleTest , public Debug::ReplicaDrillerBus::Handler { @@ -2831,7 +2831,7 @@ public: } }; -TEST_F(Integ_CreateDestroyMaster, CreateDestroyMaster) +TEST_F(Integ_CreateDestroyPrimary, CreateDestroyPrimary) { RunTickLoop([this](int tick)-> TestStatus { @@ -2843,7 +2843,7 @@ TEST_F(Integ_CreateDestroyMaster, CreateDestroyMaster) ConnectDriller(); auto replica = Replica::CreateReplica(nullptr); CreateAndAttachReplicaChunk(replica); - m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); // Destroying replica right away replica->Destroy(); @@ -2894,7 +2894,7 @@ public: LargeChunkWithDefaultsMedium* chunk = CreateAndAttachReplicaChunk(replica); AZ_TEST_ASSERT(chunk); - m_replicaId = m_sessions[sHost].GetReplicaMgr().AddMaster(replica); + m_replicaId = m_sessions[sHost].GetReplicaMgr().AddPrimary(replica); } ~ReplicaACKfeedbackTestFixture() diff --git a/Code/Framework/GridMate/Tests/ReplicaSmall.cpp b/Code/Framework/GridMate/Tests/ReplicaSmall.cpp index c2cd8845da..f1d78d5a18 100644 --- a/Code/Framework/GridMate/Tests/ReplicaSmall.cpp +++ b/Code/Framework/GridMate/Tests/ReplicaSmall.cpp @@ -234,7 +234,7 @@ public: /** * OfflineModeTest verifies that replica chunks are usable without -* an active session, and basically behave as masters. +* an active session, and basically behave as primarys. */ class OfflineModeTest : public UnitTest::GridMateMPTestFixture @@ -297,7 +297,7 @@ public: AZ_TEST_ASSERT(OfflineChunk::s_nInstances == 1); ReplicaChunkPtr chunkPtr = offlineChunk; chunkPtr->Init(ReplicaChunkClassId(OfflineChunk::GetChunkName())); - AZ_TEST_ASSERT(chunkPtr->IsMaster()); + AZ_TEST_ASSERT(chunkPtr->IsPrimary()); AZ_TEST_ASSERT(!chunkPtr->IsProxy()); offlineChunk->m_data1.Set(5); AZ_TEST_ASSERT(offlineChunk->m_data1.Get() == 5); @@ -315,7 +315,7 @@ public: return true; }); AZ_TEST_ASSERT(offlineChunk->m_data2.Get() == 10); - AZ_TEST_ASSERT(offlineChunk->m_nCallsDataSetChangeCB == 0); // DataSet change CB doesn't get called on master. + AZ_TEST_ASSERT(offlineChunk->m_nCallsDataSetChangeCB == 0); // DataSet change CB doesn't get called on primary. offlineChunk->CallRpc(); AZ_TEST_ASSERT(offlineChunk->m_nCallsRpcHandlerCB == 1); @@ -325,11 +325,11 @@ public: AZ_TEST_ASSERT(strcmp(offlineReplica->GetDebugName(), replicaName) == 0); offlineReplica->AttachReplicaChunk(chunkPtr); - AZ_TEST_ASSERT(chunkPtr->IsMaster()); + AZ_TEST_ASSERT(chunkPtr->IsPrimary()); AZ_TEST_ASSERT(!chunkPtr->IsProxy()); offlineReplica->DetachReplicaChunk(chunkPtr); - AZ_TEST_ASSERT(chunkPtr->IsMaster()); + AZ_TEST_ASSERT(chunkPtr->IsPrimary()); AZ_TEST_ASSERT(!chunkPtr->IsProxy()); AZ_TEST_ASSERT(OfflineChunk::s_nInstances == 1); @@ -462,7 +462,7 @@ public: ReplicaPeer peer(&rm); AZ_TracePrintf("GridMate", "\n"); - Replica* replica = Replica::CreateReplica("TestMasterReplica"); + Replica* replica = Replica::CreateReplica("TestPrimaryReplica"); ReplicaChunkDescriptorTable::Get().RegisterChunkType(); AZStd::unique_ptr chunk(CreateReplicaChunk()); diff --git a/Code/Framework/Tests/GridMocks.h b/Code/Framework/Tests/GridMocks.h deleted file mode 100644 index 08426bf5a6..0000000000 --- a/Code/Framework/Tests/GridMocks.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include -#include -#include -#include - -namespace UnitTest -{ - class MockSession - : public GridMate::GridSession - { - public: - MockSession(GridMate::SessionService* service) - : GridSession(service) - { - } - - void SetReplicaManager(GridMate::ReplicaManager* replicaManager) - { - m_replicaMgr = replicaManager; - } - - MOCK_METHOD4(CreateRemoteMember, GridMate::GridMember*(const GridMate::string&, GridMate::ReadBuffer&, GridMate::RemotePeerMode, GridMate::ConnectionID)); - MOCK_METHOD1(OnSessionParamChanged, void(const GridMate::GridSessionParam&)); - MOCK_METHOD1(OnSessionParamRemoved, void(const GridMate::string&)); - }; - - class MockSessionService - : public GridMate::SessionService - { - public: - MockSessionService() - : SessionService(GridMate::SessionServiceDesc()) - { - } - - ~MockSessionService() - { - m_activeSearches.clear(); - m_gridMate = nullptr; - } - - MOCK_CONST_METHOD0(IsReady, bool()); - }; -} diff --git a/Code/Framework/Tests/InterestManagerComponentTests.cpp b/Code/Framework/Tests/InterestManagerComponentTests.cpp deleted file mode 100644 index f321609785..0000000000 --- a/Code/Framework/Tests/InterestManagerComponentTests.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "GridMocks.h" - -#include -#include -#include - -#include -#include -#include - -namespace UnitTest -{ - using testing::_; - - class MockInterestManagerEvents - : public AzFramework::InterestManagerEventsBus::Handler - { - public: - MockInterestManagerEvents() - { - BusConnect(); - } - - virtual ~MockInterestManagerEvents() - { - BusDisconnect(); - } - - MOCK_METHOD1(OnInterestManagerActivate, void(GridMate::InterestManager* im)); - MOCK_METHOD1(OnInterestManagerDeactivate, void(GridMate::InterestManager* im)); - }; - - class InterestManagerComponentFixture - : public AllocatorsFixture - { - public: - InterestManagerComponentFixture() - : AllocatorsFixture() - { - - } - - ~InterestManagerComponentFixture() - { - - } - - void SetUp() override - { - AZ::AzSock::Startup(); - - AllocatorsFixture::SetUp(); - AZ::AllocatorInstance::Create(); - m_gridMate = GridMate::GridMateCreate(GridMate::GridMateDesc()); - m_carrier = GridMate::DefaultCarrier::Create(GridMate::CarrierDesc(), m_gridMate); - - m_sessionService = AZStd::make_unique(); - m_gridSession = AZStd::make_unique(m_sessionService.get()); - - m_replicaManagerDesc.m_carrier = m_carrier; - m_replicaManagerDesc.m_myPeerId = AZ::Crc32(testing::UnitTest::GetInstance()->current_test_info()->test_case_name()); - m_replicaManagerDesc.m_roles = GridMate::ReplicaMgrDesc::Role_SyncHost; - m_replicaManager = AZStd::make_unique(); - m_replicaManager->Init(m_replicaManagerDesc); - - m_gridSession->SetReplicaManager(m_replicaManager.get()); - } - - void TearDown() override - { - m_gridSession = nullptr; - m_sessionService = nullptr; - - m_replicaManager->Shutdown(); - m_replicaManager = nullptr; - - m_carrier->Shutdown(); - delete m_carrier; - GridMate::GridMateDestroy(m_gridMate); - AZ::AllocatorInstance::Destroy(); - AllocatorsFixture::TearDown(); - - AZ::AzSock::Cleanup(); - } - - AZStd::unique_ptr m_sessionService; - AZStd::unique_ptr m_gridSession; - - GridMate::IGridMate* m_gridMate; - GridMate::Carrier* m_carrier; - - GridMate::ReplicaMgrDesc m_replicaManagerDesc; - AZStd::unique_ptr m_replicaManager; - }; - - TEST_F(InterestManagerComponentFixture, TestNetworkSessionDeactivate) - { - // Using StrictMock here will ensure that the test fails if any of the events fire (as no EXPECT_CALL has been set). - testing::StrictMock interestManagerEvents; - AzFramework::InterestManagerComponent interestManagerComponent; - - // This will connect the component to the NetBindingSystemEventsBus - interestManagerComponent.Activate(); - - // Ensure that the interest manager component handles receiving OnNetworkSessionDeactivated for a session that was never activated. - // This can happen in the event of a client failing to connect to a host. - AzFramework::NetBindingSystemEventsBus::Broadcast( - &AzFramework::NetBindingSystemEvents::OnNetworkSessionDeactivated, m_gridSession.get()); - - interestManagerComponent.Deactivate(); - } - - TEST_F(InterestManagerComponentFixture, TestNetworkSessionActivateAndDeactivate) - { - // Using StrictMock here will ensure that the test fails if any of the events fire (as no EXPECT_CALL has been set). - testing::StrictMock interestManagerEvents; - AzFramework::InterestManagerComponent interestManagerComponent; - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - - // This will connect the component to the NetBindingSystemEventsBus - interestManagerComponent.Activate(); - - // Golden path test that the interest manager component behaves as expected under normal conditions - // (receiving OnNetworkSessionActivated followed by OnNetworkSessionDeactivated). - testing::Expectation activationEvent = EXPECT_CALL(interestManagerEvents, OnInterestManagerActivate(_)) - .Times(1); - AzFramework::NetBindingSystemEventsBus::Broadcast( - &AzFramework::NetBindingSystemEvents::OnNetworkSessionActivated, m_gridSession.get()); - - EXPECT_CALL(interestManagerEvents, OnInterestManagerDeactivate(_)) - .Times(1) - .After(activationEvent); - AzFramework::NetBindingSystemEventsBus::Broadcast( - &AzFramework::NetBindingSystemEvents::OnNetworkSessionDeactivated, m_gridSession.get()); - - interestManagerComponent.Deactivate(); - } -} diff --git a/Code/Framework/Tests/NetBinding.cpp b/Code/Framework/Tests/NetBinding.cpp deleted file mode 100644 index cf2455be0f..0000000000 --- a/Code/Framework/Tests/NetBinding.cpp +++ /dev/null @@ -1,600 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace UnitTest -{ -#if 0 - using namespace AZ; - - /** - */ - class NetBindingTestComponent - : public AZ::Component - , public AzFramework::NetBindable - { - friend class NetBindingComponentChunk; - - public: - AZ_COMPONENT(NetBindingTestComponent, "{DE5CF1C0-B4B6-4BB0-86FE-936B400871E0}", AzFramework::NetBindable); - - protected: - class NetChunk - : public GridMate::ReplicaChunk - { - public: - AZ_CLASS_ALLOCATOR(NetChunk, AZ::SystemAllocator, 0); - - static const char* GetChunkName() { return "NetBindingTestComponent::NetChunk"; } - - bool IsReplicaMigratable() override { return false; } - }; - - /////////////////////////////////////////////////////////////////////// - // NetBindable - GridMate::ReplicaChunkPtr GetNetworkBinding() override - { - AZ_TracePrintf("NetBinding", "NetBindingTestComponent::GetNetworkBinding()\n"); - m_chunk = GridMate::CreateReplicaChunk(); - AZ_Assert(m_chunk, "Failed to create NetBindingTestComponent::NetChunk!"); - return m_chunk; - } - - void SetNetworkBinding(GridMate::ReplicaChunkPtr binding) override - { - AZ_TracePrintf("NetBinding", "NetBindingTestComponent::SetNetworkBinding()\n"); - AZ_TEST_ASSERT(binding); - AZ_TEST_ASSERT(binding->GetDescriptor()->GetChunkTypeId() == GridMate::ReplicaChunkClassId(NetChunk::GetChunkName())); - m_chunk = AZStd::static_pointer_cast(binding); - } - - void UnbindFromNetwork() override - { - if (m_chunk) - { - AZ_TracePrintf("NetBinding", "NetBindingTestComponent::UnbindFromNetwork()\n"); - m_chunk = nullptr; - } - } - /////////////////////////////////////////////////////////////////////// - - /////////////////////////////////////////////////////////////////////// - // AZ::Component - static void Reflect(AZ::ReflectContext* reflection) - { - AZ::SerializeContext* serializeContext = azrtti_cast(reflection); - if (serializeContext) - { - serializeContext->Class() - ; - } - - // We also need to register the chunk type, and this would be a good time to do so. - GridMate::ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - } - - void Activate() override - { - AZ_TracePrintf("NetBinding", "NetBindingTestComponent::Activate()\n"); - } - - void Deactivate() override - { - AZ_TracePrintf("NetBinding", "NetBindingTestComponent::Deactivate()\n"); - UnbindFromNetwork(); - } - /////////////////////////////////////////////////////////////////////// - - AZStd::intrusive_ptr m_chunk; - }; - - /** - * Fakes the behavior of NetBindingSystemContextData on the host side - */ - class FakeNetBindingContextChunk - : public GridMate::ReplicaChunk - { - public: - AZ_CLASS_ALLOCATOR(FakeNetBindingContextChunk, AZ::SystemAllocator, 0); - - static const char* GetChunkName() { return "NetBindingSystemContextData"; } // We are pretending to be a NetBindingSystemContextData - - FakeNetBindingContextChunk() - : m_bindingContextSequence("BindingContextSequence", AzFramework::UnspecifiedNetBindingContextSequence) - { - } - - bool IsReplicaMigratable() override { return true; } - - GridMate::DataSet m_bindingContextSequence; - }; - - /* - * NetBindingSystemComponentLifecycleTest - */ - class NetBindingSystemComponentLifecycleTest - : public GridMate::SessionEventBus::Handler - , public AzFramework::NetBindingHandlerBus::Handler - { - public: - void OnSessionCreated(GridMate::GridSession* session) override - { - if (session == m_session) - { - if (session->IsHost()) - { - EBUS_EVENT(AzFramework::NetBindingSystemBus, OnNetworkSessionActivated, session); - } - } - } - - void OnSessionJoined(GridMate::GridSession* session) override - { - if (session == m_session) - { - EBUS_EVENT(AzFramework::NetBindingSystemBus, OnNetworkSessionActivated, session); - } - } - - void OnSessionDelete(GridMate::GridSession* session) - { - if (session == m_session) - { - EBUS_EVENT(AzFramework::NetBindingSystemBus, OnNetworkSessionDeactivated, session); - m_session = nullptr; - } - } - - void BindToNetwork(GridMate::ReplicaPtr bindTo) override - { - // Verify that BindToNetwork() is not called more than once - AZ_TEST_ASSERT(!m_receivedBindEvent); - m_receivedBindEvent = true; - - // Test that now we should be binding to the network - bool shouldBindToNetwork = false; - EBUS_EVENT_RESULT(shouldBindToNetwork, AzFramework::NetBindingSystemBus, ShouldBindToNetwork); - AZ_TEST_ASSERT(shouldBindToNetwork); - - // Verify that the context sequence is no longer unspecified - AzFramework::NetBindingContextSequence contextSequence = AzFramework::UnspecifiedNetBindingContextSequence; - EBUS_EVENT_RESULT(contextSequence, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(contextSequence != AzFramework::UnspecifiedNetBindingContextSequence); - } - - void UnbindFromNetwork() override - { - // Verify that UnbindFromNetwork() is not called more than once - AZ_TEST_ASSERT(!m_receivedUnbindEvent); - m_receivedUnbindEvent = true; - } - - void run() - { - // Setup - AZ::ComponentApplication app; - AZ::ComponentApplication::Descriptor appDesc; - appDesc.m_recordsMode = AZ::Debug::AllocationRecords::RECORD_FULL; - AZ::Entity* systemEntity = app.Create(appDesc); - - app.RegisterComponentDescriptor(AzFramework::NetBindingSystemComponent::CreateDescriptor()); - app.RegisterComponentDescriptor(AzFramework::GameEntityContextComponent::CreateDescriptor()); - - systemEntity->Init(); - systemEntity->CreateComponent(); - systemEntity->CreateComponent(); - systemEntity->CreateComponent(); - systemEntity->CreateComponent(); - systemEntity->Activate(); - AzFramework::NetBindingHandlerBus::Handler::BusConnect(); - - GridMate::GridMateDesc gridMateDesc; - GridMate::IGridMate* gridMate = GridMate::GridMateCreate(gridMateDesc); - GridMate::GridMateAllocatorMP::Descriptor allocDesc; - allocDesc.m_stackRecordLevels = 15; - allocDesc.m_custom = &AZ::AllocatorInstance::Get(); - AZ::AllocatorInstance::Create(allocDesc); - if (AZ::AllocatorInstance::Get().GetRecords()) - { - AZ::AllocatorInstance::Get().GetRecords()->SetMode(AZ::Debug::AllocationRecords::RECORD_FULL); - } - GridMate::StartGridMateService(gridMate, GridMate::SessionServiceDesc()); - GridMate::SessionEventBus::Handler::BusConnect(gridMate); - - // Test offline behavior - { - bool shouldBindToNetwork = true; - EBUS_EVENT_RESULT(shouldBindToNetwork, AzFramework::NetBindingSystemBus, ShouldBindToNetwork); - AZ_TEST_ASSERT(!shouldBindToNetwork); - - AzFramework::NetBindingContextSequence offlineContextSequence = 0xBADF00D; - EBUS_EVENT_RESULT(offlineContextSequence, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(offlineContextSequence == AzFramework::UnspecifiedNetBindingContextSequence); - } - - // Test host-side behavior - { - m_receivedBindEvent = m_receivedUnbindEvent = false; - - // Host a session - GridMate::CarrierDesc carrierDesc; - carrierDesc.m_enableDisconnectDetection = true; - GridMate::LANSessionParams sessionParams; - sessionParams.m_numPublicSlots = 10; - sessionParams.m_flags = 0; - sessionParams.m_port = HOST_PORT; - sessionParams.m_params[sessionParams.m_numParams].m_id = "filter"; - sessionParams.m_params[sessionParams.m_numParams].m_value = GridMate::Utils::GetMachineAddress(); - sessionParams.m_numParams++; - m_session = gridMate->GetMultiplayerService()->HostSession(&sessionParams, carrierDesc); - - int nFrame = 0; - while (m_session) - { - if (nFrame == 10) - { - // Verify that BindToNetwork() has been called - AZ_TEST_ASSERT(m_receivedBindEvent); - - // Verify that we have a valid context sequence - AzFramework::NetBindingContextSequence contextSequence1 = AzFramework::UnspecifiedNetBindingContextSequence; - EBUS_EVENT_RESULT(contextSequence1, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(contextSequence1 != AzFramework::UnspecifiedNetBindingContextSequence); - - EBUS_EVENT(AzFramework::GameEntityContextRequestBus, ResetGameContext); - - // Verify that the context sequence was incremented - AzFramework::NetBindingContextSequence contextSequence2 = contextSequence1; - EBUS_EVENT_RESULT(contextSequence2, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(contextSequence2 != AzFramework::UnspecifiedNetBindingContextSequence); - AZ_TEST_ASSERT(contextSequence2 > contextSequence1); - - m_session->Leave(false); - } - - app.Tick(); - gridMate->Update(); - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(10)); - nFrame++; - } - - // Verify that we should no longer bind to the network - bool shouldBindToNetwork = true; - EBUS_EVENT_RESULT(shouldBindToNetwork, AzFramework::NetBindingSystemBus, ShouldBindToNetwork); - AZ_TEST_ASSERT(!shouldBindToNetwork); - - // Verify that the context sequence was reset to unspecified - AzFramework::NetBindingContextSequence offlineContextSequence = 0xBADF00D; - EBUS_EVENT_RESULT(offlineContextSequence, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(offlineContextSequence == AzFramework::UnspecifiedNetBindingContextSequence); - } - - // Test nonhost-side behavior by faking the behavior on the host side and then joining the host session. - { - m_receivedBindEvent = m_receivedUnbindEvent = false; - - // Host a session - GridMate::CarrierDesc carrierDesc; - carrierDesc.m_enableDisconnectDetection = true; - GridMate::LANSessionParams sessionParams; - sessionParams.m_numPublicSlots = 10; - sessionParams.m_flags = 0; - sessionParams.m_port = HOST_PORT; - sessionParams.m_params[sessionParams.m_numParams].m_id = "filter"; - sessionParams.m_params[sessionParams.m_numParams].m_value = GridMate::Utils::GetMachineAddress(); - sessionParams.m_numParams++; - GridMate::GridSession* hostSession = gridMate->GetMultiplayerService()->HostSession(&sessionParams, carrierDesc); - - // Add the fake context replica on the host and set the context sequence to 1 - GridMate::ReplicaPtr replica = GridMate::Replica::CreateReplica("Potato"); - FakeNetBindingContextChunk* contextChunk = GridMate::CreateReplicaChunk(); - replica->AttachReplicaChunk(contextChunk); - while (!hostSession->IsReady()) - { - gridMate->Update(); - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(10)); - } - hostSession->GetReplicaMgr()->AddMaster(replica); - contextChunk->m_bindingContextSequence.Set(1); - - int nFrame = 0; - while (m_session) - { - if (nFrame == 10) - { - // Join the hosted session - GridMate::SessionIdInfo sessionInfo; - sessionInfo.m_sessionId = hostSession->GetId(); - m_session = gridMate->GetMultiplayerService()->JoinSession(&sessionInfo, GridMate::JoinParams(), carrierDesc); - } - - if (nFrame == 20) - { - // Verify that BindToNetwork() has been called - AZ_TEST_ASSERT(m_receivedBindEvent); - - // Verify that we have a valid context sequence - AzFramework::NetBindingContextSequence contextSequence = AzFramework::UnspecifiedNetBindingContextSequence; - EBUS_EVENT_RESULT(contextSequence, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(contextSequence == contextChunk->m_bindingContextSequence.Get()); - - // Simulate a context switch on the host - contextChunk->m_bindingContextSequence.Set(contextChunk->m_bindingContextSequence.Get() + 1); - } - - if (nFrame == 30) - { - // Verify that the context sequence was incremented - AzFramework::NetBindingContextSequence contextSequence = AzFramework::UnspecifiedNetBindingContextSequence; - EBUS_EVENT_RESULT(contextSequence, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(contextSequence == contextChunk->m_bindingContextSequence.Get()); - - hostSession->Leave(false); - } - - app.Tick(); - gridMate->Update(); - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(10)); - nFrame++; - } - - // Verify that we should no longer bind to the network - bool shouldBindToNetwork = true; - EBUS_EVENT_RESULT(shouldBindToNetwork, AzFramework::NetBindingSystemBus, ShouldBindToNetwork); - AZ_TEST_ASSERT(!shouldBindToNetwork); - - // Verify that the context sequence was reset to unspecified - AzFramework::NetBindingContextSequence offlineContextSequence = 0xBADF00D; - EBUS_EVENT_RESULT(offlineContextSequence, AzFramework::NetBindingSystemBus, GetCurrentContextSequence); - AZ_TEST_ASSERT(offlineContextSequence == AzFramework::UnspecifiedNetBindingContextSequence); - } - - // Clean up - GridMate::SessionEventBus::Handler::BusDisconnect(); - GridMate::GridMateDestroy(gridMate); - AZ::AllocatorInstance::Destroy(); - AzFramework::NetBindingHandlerBus::Handler::BusDisconnect(); - app.Destroy(); - } - - static const int HOST_PORT = 5000; - - GridMate::GridSession* m_session; - bool m_receivedBindEvent; - bool m_receivedUnbindEvent; - }; - - /* - * NetBindingFeatureTest (requires two instances) - */ - class NetBindingFeatureTest - : public GridMate::SessionEventBus::Handler - { - public: - void OnSessionCreated(GridMate::GridSession* session) override - { - if (session == m_session) - { - if (session->IsHost()) - { - EBUS_EVENT(AzFramework::NetBindingSystemBus, OnNetworkSessionActivated, session); - } - } - } - - void OnSessionJoined(GridMate::GridSession* session) override - { - if (session == m_session) - { - EBUS_EVENT(AzFramework::NetBindingSystemBus, OnNetworkSessionActivated, session); - } - } - - void OnSessionDelete(GridMate::GridSession* session) - { - if (session == m_session) - { - EBUS_EVENT(AzFramework::NetBindingSystemBus, OnNetworkSessionDeactivated, session); - m_session = nullptr; - } - } - - void OnGridSearchComplete(GridMate::GridSearch* results) override - { - if (results == m_search) - { - GridMate::CarrierDesc carrierDesc; - carrierDesc.m_enableDisconnectDetection = true; - - // Create an entity before we get in the session - AZ_TracePrintf("NetBinding", "Spawning master entity...\n"); - AZ::Entity* newEntity = nullptr; - newEntity = aznew Entity; - newEntity->CreateComponent(); - newEntity->CreateComponent(); - newEntity->Init(); - newEntity->Activate(); - m_entities.push_back(newEntity); - - if (results->GetNumResults() == 0) - { - // Host a session instead - GridMate::LANSessionParams sessionParams; - sessionParams.m_numPublicSlots = 10; - sessionParams.m_flags = 0; - sessionParams.m_port = HOST_PORT; - sessionParams.m_params[sessionParams.m_numParams].m_id = "filter"; - sessionParams.m_params[sessionParams.m_numParams].m_value = GridMate::Utils::GetMachineAddress(); - sessionParams.m_numParams++; - m_session = m_gridMate->GetMultiplayerService()->HostSession(&sessionParams, carrierDesc); - - m_search->Release(); - } - else - { - // Join the session - GridMate::JoinParams joinParams; - m_session = m_gridMate->GetMultiplayerService()->JoinSession(results->GetResult(0), joinParams, carrierDesc); - } - m_search = nullptr; - } - } - - void OnMemberJoined(GridMate::GridSession* session, GridMate::GridMember* member) override - { - if (session == m_session) - { - if (session->IsHost()) - { - if (member != session->GetMyMember()) - { - // Spawn an entity after session creation - AZ_TracePrintf("NetBinding", "Spawning master entity...\n"); - AZ::Entity* newEntity = nullptr; - EBUS_EVENT_RESULT(newEntity, AzFramework::GameEntityContextRequestBus, CreateGameEntity, "ReplicatedEntity2"); - newEntity->CreateComponent(); - newEntity->CreateComponent(); - newEntity->Init(); - newEntity->Activate(); - m_entities.push_back(newEntity); - } - } - } - } - - void run() - { - m_gridMate = nullptr; - m_session = nullptr; - - AZ::ComponentApplication app; - AZ::ComponentApplication::Descriptor appDesc; - AZ::Entity* systemEntity = app.Create(appDesc); - - app.RegisterComponentDescriptor(AzFramework::NetBindingSystemComponent::CreateDescriptor()); - app.RegisterComponentDescriptor(AzFramework::NetBindingComponent::CreateDescriptor()); - app.RegisterComponentDescriptor(NetBindingTestComponent::CreateDescriptor()); - app.RegisterComponentDescriptor(AzFramework::GameEntityContextComponent::CreateDescriptor()); - - systemEntity->Init(); - systemEntity->CreateComponent(); - systemEntity->CreateComponent(); - systemEntity->CreateComponent(); - systemEntity->CreateComponent(); - systemEntity->Activate(); - - GridMate::GridMateDesc gridMateDesc; - m_gridMate = GridMate::GridMateCreate(gridMateDesc); - - GridMate::GridMateAllocatorMP::Descriptor allocDesc; - allocDesc.m_custom = &AZ::AllocatorInstance::Get(); - AZ::AllocatorInstance::Create(allocDesc); - - GridMate::StartGridMateService(m_gridMate, GridMate::SessionServiceDesc()); - - GridMate::SessionEventBus::Handler::BusConnect(m_gridMate); - - // Search for an existing session - // If a session is not found, we will host a session from within the search callback. - { - GridMate::LANSearchParams searchParams; - searchParams.m_serverPort = HOST_PORT; - searchParams.m_params[searchParams.m_numParams].m_id = "filter"; - searchParams.m_params[searchParams.m_numParams].m_value = GridMate::Utils::GetMachineAddress(); - searchParams.m_params[searchParams.m_numParams].m_op = GridMate::GridSessionSearchOperators::SSO_OPERATOR_EQUAL; - searchParams.m_numParams++; - m_search = m_gridMate->GetMultiplayerService()->StartGridSearch(&searchParams); - - while (m_search) - { - m_gridMate->Update(); - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(10)); - } - } - - // Tick for a while - //static int nTicks = 100; - for (int i = 0; m_session; ++i) - { - if (m_session->IsHost()) - { - if (i > 4000 && m_session->GetNumberOfMembers() == 1) - { - m_session->Leave(false); - } - } - - m_gridMate->Update(); - app.Tick(); - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(10)); - } - - GridMate::SessionEventBus::Handler::BusDisconnect(); - - GridMate::GridMateDestroy(m_gridMate); - - AZ::AllocatorInstance::Destroy(); - - for (AZ::Entity* entity : m_entities) - { - AzFramework::EntityContextId contextId = AzFramework::EntityContextId::CreateNull(); - EBUS_EVENT_ID_RESULT(contextId, entity->GetId(), AzFramework::EntityIdContextQueryBus, GetOwningContextId); - if (contextId.IsNull()) - { - delete entity; - } - else - { - EBUS_EVENT(AzFramework::GameEntityContextRequestBus, DestroyGameEntity, entity); - } - } - - app.Destroy(); - } - - static const int HOST_PORT = 6000; - - GridMate::IGridMate* m_gridMate; - GridMate::GridSession* m_session; - GridMate::GridSearch* m_search; - AZStd::fixed_vector m_entities; - }; -#endif -} - -AZ_TEST_SUITE(NetBinding) -//AZ_TEST(UnitTest::NetBindingSystemComponentLifecycleTest) -//AZ_TEST(UnitTest::NetBindingFeatureTest) -AZ_TEST_SUITE_END diff --git a/Code/Framework/Tests/NetBindingMocks.h b/Code/Framework/Tests/NetBindingMocks.h deleted file mode 100644 index 3973fe670d..0000000000 --- a/Code/Framework/Tests/NetBindingMocks.h +++ /dev/null @@ -1,335 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#ifndef AZCORE_UNITTEST_NETBINDINGMOCKS_H -#define AZCORE_UNITTEST_NETBINDINGMOCKS_H - -#include -#include -#include -#include -#include -#include -#include - -namespace UnitTest -{ - class MockGameEntityContext - : public AzFramework::GameEntityContextRequestBus::Handler - , public AzFramework::SliceGameEntityOwnershipServiceRequestBus::Handler - { - public: - MockGameEntityContext() - { - AzFramework::GameEntityContextRequestBus::Handler::BusConnect(); - AzFramework::SliceGameEntityOwnershipServiceRequestBus::Handler::BusConnect(); - } - - ~MockGameEntityContext() - { - AzFramework::SliceGameEntityOwnershipServiceRequestBus::Handler::BusDisconnect(); - AzFramework::GameEntityContextRequestBus::Handler::BusDisconnect(); - } - - MOCK_METHOD3(InstantiateDynamicSlice, AzFramework::SliceInstantiationTicket(const AZ::Data::Asset&, const AZ::Transform&, const AZ::IdUtils::Remapper::IdMapper&)); - MOCK_METHOD0(GetGameEntityContextId, AzFramework::EntityContextId()); - MOCK_METHOD0(GetGameEntityContextInstance, AzFramework::EntityContext*()); - MOCK_METHOD1(CreateGameEntity, AZ::Entity*(const char*)); - MOCK_METHOD1(AddGameEntity, void (AZ::Entity*)); - MOCK_METHOD1(DestroyGameEntity, void (const AZ::EntityId&)); - MOCK_METHOD1(DestroyGameEntityAndDescendants, void (const AZ::EntityId&)); - MOCK_METHOD1(ActivateGameEntity, void (const AZ::EntityId&)); - MOCK_METHOD1(DeactivateGameEntity, void (const AZ::EntityId&)); - MOCK_METHOD1(DestroyDynamicSliceByEntity, bool (const AZ::EntityId&)); - MOCK_METHOD2(LoadFromStream, bool (AZ::IO::GenericStream&, bool)); - MOCK_METHOD0(ResetGameContext, void ()); - MOCK_METHOD1(GetEntityName, AZStd::string (const AZ::EntityId&)); - MOCK_METHOD1(DestroySliceByEntity, bool(const AZ::EntityId&)); - MOCK_METHOD1(CreateGameEntityForBehaviorContext, AzFramework::BehaviorEntity (const char *)); - MOCK_METHOD1(CancelDynamicSliceInstantiation, void (const AzFramework::SliceInstantiationTicket &)); - }; - - class MockNetBindingSystemContextData - : public AzFramework::NetBindingSystemContextData - { - public: - AZ_CLASS_ALLOCATOR(MockNetBindingSystemContextData, AZ::SystemAllocator, 0); - - static const char* GetChunkName() - { - return "MockNetBindingSystemContextData"; - } - - MOCK_METHOD1(OnAttachedToReplica, void (GridMate::Replica*)); - MOCK_METHOD1(OnDetachedFromReplica, void (GridMate::Replica*)); - MOCK_METHOD1(UpdateChunk, void (const GridMate::ReplicaContext&)); - MOCK_METHOD1(UpdateFromChunk, void (const GridMate::ReplicaContext&)); - MOCK_METHOD2(AcceptChangeOwnership, bool (GridMate::PeerId, const GridMate::ReplicaContext&)); - MOCK_METHOD1(OnReplicaChangeOwnership, void (const GridMate::ReplicaContext&)); - MOCK_METHOD0(IsUpdateFromReplicaEnabled, bool ()); - MOCK_CONST_METHOD1(ShouldSendToPeer, bool (GridMate::ReplicaPeer*)); - MOCK_METHOD1(CalculateDirtyDataSetMask, AZ::u32 (GridMate::MarshalContext&)); - MOCK_METHOD1(OnDataSetChanged, void (const GridMate::DataSetBase&)); - MOCK_METHOD2(Marshal, void (GridMate::MarshalContext&, AZ::u32)); - MOCK_METHOD2(Unmarshal, void (GridMate::UnmarshalContext&, AZ::u32)); - MOCK_METHOD0(IsReplicaMigratable, bool ()); - MOCK_METHOD0(IsBroadcast, bool ()); - MOCK_METHOD1(OnReplicaActivate, void (const GridMate::ReplicaContext&)); - MOCK_METHOD1(OnReplicaDeactivate, void (const GridMate::ReplicaContext&)); - - /** - * \brief Helper method for GoogleMock to call NetBindingSystemContextData::OnReplicaActivate - */ - void Base_OnReplicaActivate(const GridMate::ReplicaContext& rc) - { - NetBindingSystemContextData::OnReplicaActivate(rc); - } - - MOCK_METHOD0(GetReplicaManager, GridMate::ReplicaManager* ()); - MOCK_METHOD0(ShouldBindToNetwork, bool ()); - }; - - class MockReplicaManager - : public GridMate::ReplicaManager - { - public: - MOCK_METHOD2(OnIncomingConnection, void (GridMate::Carrier*, GridMate::ConnectionID)); - MOCK_METHOD3(OnFailedToConnect, void (GridMate::Carrier*, GridMate::ConnectionID, GridMate::CarrierDisconnectReason)); - MOCK_METHOD3(OnDriverError, void (GridMate::Carrier*, GridMate::ConnectionID, const GridMate::DriverError&)); - MOCK_METHOD3(OnSecurityError, void (GridMate::Carrier*, GridMate::ConnectionID, const GridMate::SecurityError&)); - MOCK_METHOD1(Destroy, bool (GridMate::Replica*)); - MOCK_METHOD2(GetReplicaContext, void (const GridMate::Replica*, GridMate::ReplicaContext&)); - MOCK_METHOD2(OnConnectionEstablished, void (GridMate::Carrier*, GridMate::ConnectionID)); - MOCK_METHOD3(OnDisconnect, void (GridMate::Carrier*, GridMate::ConnectionID, GridMate::CarrierDisconnectReason)); - MOCK_METHOD3(OnRateChange, void (GridMate::Carrier*, GridMate::ConnectionID, AZ::u32)); - MOCK_METHOD1(FindReplica, GridMate::ReplicaPtr (GridMate::ReplicaId)); - }; - - class MockAssetHandler - : public AZ::Data::AssetHandler - { - public: - AZ_CLASS_ALLOCATOR(MockAssetHandler, AZ::SystemAllocator, 0) - - MOCK_METHOD2(CreateAsset, AZ::Data::AssetPtr (const AZ::Data::AssetId&, const AZ::Data::AssetType&)); - MOCK_METHOD3(LoadAssetData, AZ::Data::AssetHandler::LoadResult ( - const AZ::Data::Asset&, - AZStd::shared_ptr, - const AZ::Data::AssetFilterCB&)); - MOCK_METHOD2(SaveAssetData, bool (const AZ::Data::Asset&, AZ::IO::GenericStream*)); - MOCK_METHOD3(InitAsset, void (const AZ::Data::Asset&, bool, bool)); - MOCK_METHOD1(DestroyAsset, void (AZ::Data::AssetPtr)); - MOCK_METHOD1(GetHandledAssetTypes, void (AZStd::vector&)); - MOCK_CONST_METHOD1(CanHandleAsset, bool (const AZ::Data::AssetId&)); - }; - - class MockAsset - : public AZ::DynamicSliceAsset - { - public: - AZ_RTTI(MockAsset, "{78ABC204-452E-4621-A552-F04D3ABF1690}", DynamicSliceAsset); - - MockAsset(const AZ::Data::AssetId& assetId = AZ::Data::AssetId()) - : DynamicSliceAsset(assetId) - { - } - - ~MockAsset() = default; - }; - - class MockSliceReference - : public AZ::SliceComponent::SliceReference - { - public: - using SliceReference::SliceReference; - - MOCK_METHOD1(CreateInstance, AZ::SliceComponent::SliceInstance*(const AZ::IdUtils::Remapper::IdMapper&)); - MOCK_METHOD2(CloneInstance, AZ::SliceComponent::SliceInstance*(AZ::SliceComponent::SliceInstance*, AZ::SliceComponent::EntityIdToEntityIdMap&)); - MOCK_METHOD1(FindInstance, AZ::SliceComponent::SliceInstance*(const AZ::SliceComponent::SliceInstanceId&)); - MOCK_METHOD1(RemoveInstance, bool(AZ::SliceComponent::SliceInstance*)); - MOCK_METHOD3(RemoveEntity, bool(AZ::EntityId, bool, AZ::SliceComponent::SliceInstance*)); - MOCK_CONST_METHOD0(GetInstances, const AZ::SliceComponent::SliceReference::SliceInstances&()); - MOCK_CONST_METHOD0(GetSliceAsset, const AZ::Data::Asset& ()); - MOCK_CONST_METHOD0(GetSliceComponent, AZ::SliceComponent*()); - MOCK_CONST_METHOD0(IsInstantiated, bool ()); - MOCK_CONST_METHOD3(GetInstanceEntityAncestry, bool(const AZ::EntityId&, AZ::SliceComponent::EntityAncestorList&, AZ::u32)); - MOCK_METHOD0(ComputeDataPatch, void()); - }; - - class MockSliceInstance - : public AZ::SliceComponent::SliceInstance - { - public: - using SliceInstance::SliceInstance; - - void SetMockInstantiatedContainer(AZ::SliceComponent::InstantiatedContainer* newContainer) - { - m_instantiated = newContainer; - - for (AZ::Entity* entity : m_instantiated->m_entities) - { - m_entityIdToBaseCache.insert(AZStd::make_pair(entity->GetId(), entity->GetId())); - } - - for (AZ::Entity* entity : m_instantiated->m_entities) - { - m_baseToNewEntityIdMap.insert(AZStd::make_pair(entity->GetId(), entity->GetId())); - } - } - - MOCK_CONST_METHOD0(GetInstantiated, const AZ::SliceComponent::InstantiatedContainer*()); - MOCK_CONST_METHOD0(GetDataPatch, const AZ::DataPatch&()); - MOCK_CONST_METHOD0(GetDataFlags, const AZ::SliceComponent::DataFlagsPerEntity&()); - MOCK_METHOD0(GetDataFlags, AZ::SliceComponent::DataFlagsPerEntity&()); - MOCK_CONST_METHOD0(GetEntityIdMap, const AZ::SliceComponent::EntityIdToEntityIdMap& ()); - MOCK_CONST_METHOD0(GetEntityIdToBaseMap, const AZ::SliceComponent::EntityIdToEntityIdMap& ()); - MOCK_CONST_METHOD0(GetId, const AZ::SliceComponent::SliceInstanceId& ()); - MOCK_CONST_METHOD0(GetMetadataEntity, AZ::Entity* ()); - }; - - class MockEntity - : public AZ::Entity - { - public: - ~MockEntity() override {} - - MOCK_METHOD0(Init, void ()); - MOCK_METHOD0(Activate, void ()); - MOCK_METHOD0(Deactivate, void ()); - - /** - * \brief Helper method for GoogleMock to call base class method - */ - void Base_Init() - { - Entity::Init(); - } - - /** - * \brief Helper method for GoogleMock to mark an entity as activated - */ - void Base_Activate() - { - m_state = State::Active; - } - - /** - * \brief Helper method for GoogleMock to mark an entity as deactivated - */ - void Base_Deactivate() - { - m_state = State::Init; - } - }; - - class MockComponentApplication - : public AZ::ComponentApplicationBus::Handler - { - public: - MockComponentApplication() - { - AZ::ComponentApplicationBus::Handler::BusConnect(); - AZ::Interface::Register(this); - } - ~MockComponentApplication() - { - AZ::Interface::Unregister(this); - AZ::ComponentApplicationBus::Handler::BusDisconnect(); - } - - AZStd::vector m_mockEntities; - - bool AddEntity(AZ::Entity* entity) override - { - const auto it = AZStd::find(m_mockEntities.begin(), m_mockEntities.end(), entity); - if (it == m_mockEntities.end()) - { - m_mockEntities.push_back(entity); - return true; - } - - return false; - } - - AZ::Entity* FindEntity(const AZ::EntityId& id) override - { - const auto it = AZStd::find_if(m_mockEntities.begin(), m_mockEntities.end(), [id](AZ::Entity* entity) - { - return entity->GetId() == id; - }); - - if (it != m_mockEntities.end()) - { - return *it; - } - return nullptr; - } - - MOCK_METHOD0(Destroy, void ()); - MOCK_METHOD1(RegisterComponentDescriptor, void (const AZ::ComponentDescriptor*)); - MOCK_METHOD1(UnregisterComponentDescriptor, void (const AZ::ComponentDescriptor*)); - MOCK_METHOD1(RegisterEntityAddedEventHandler, void(AZ::EntityAddedEvent::Handler&)); - MOCK_METHOD1(RegisterEntityRemovedEventHandler, void(AZ::EntityRemovedEvent::Handler&)); - MOCK_METHOD1(RegisterEntityActivatedEventHandler, void(AZ::EntityActivatedEvent::Handler&)); - MOCK_METHOD1(RegisterEntityDeactivatedEventHandler, void(AZ::EntityDeactivatedEvent::Handler&)); - MOCK_METHOD1(SignalEntityActivated, void(AZ::Entity*)); - MOCK_METHOD1(SignalEntityDeactivated, void(AZ::Entity*)); - MOCK_METHOD1(RemoveEntity, bool (AZ::Entity*)); - MOCK_METHOD1(DeleteEntity, bool (const AZ::EntityId&)); - MOCK_METHOD1(GetEntityName, AZStd::string (const AZ::EntityId&)); - MOCK_METHOD1(EnumerateEntities, void (const ComponentApplicationRequests::EntityCallback&)); - MOCK_METHOD0(GetApplication, AZ::ComponentApplication* ()); - MOCK_METHOD0(GetSerializeContext, AZ::SerializeContext* ()); - MOCK_METHOD0(GetBehaviorContext, AZ::BehaviorContext* ()); - MOCK_METHOD0(GetJsonRegistrationContext, AZ::JsonRegistrationContext* ()); - MOCK_CONST_METHOD0(GetAppRoot, const char* ()); - MOCK_CONST_METHOD0(GetEngineRoot, const char* ()); - MOCK_CONST_METHOD0(GetExecutableFolder, const char* ()); - MOCK_METHOD0(GetDrillerManager, AZ::Debug::DrillerManager* ()); - MOCK_METHOD0(GetTickDeltaTime, float ()); - MOCK_METHOD0(GetTimeAtCurrentTick, AZ::ScriptTimePoint ()); - MOCK_METHOD1(Tick, void (float)); - MOCK_METHOD0(TickSystem, void ()); - MOCK_CONST_METHOD0(GetRequiredSystemComponents, AZ::ComponentTypeList ()); - MOCK_METHOD1(ResolveModulePath, void (AZ::OSString&)); - MOCK_METHOD0(RegisterCoreComponents, void ()); - MOCK_METHOD1(Reflect, void (AZ::ReflectContext*)); - MOCK_CONST_METHOD1(QueryApplicationType, void(AZ::ApplicationTypeQuery&)); - }; - - class MockBindingComponent - : public AZ::Component - , public AzFramework::NetBindingHandlerBus::Handler - { - public: - AZ_COMPONENT(MockBindingComponent, "{8393809A-3256-4865-97A9-1CCA43073B4A}", NetBindingHandlerInterface); - - static void Reflect(AZ::ReflectContext*) {} - - MOCK_METHOD0(Init, void ()); - MOCK_METHOD0(Activate, void ()); - MOCK_METHOD0(Deactivate, void ()); - MOCK_METHOD1(ReadInConfig, bool (const AZ::ComponentConfig*)); - MOCK_CONST_METHOD1(WriteOutConfig, bool (AZ::ComponentConfig*)); - MOCK_METHOD1(BindToNetwork, void (GridMate::ReplicaPtr)); - MOCK_METHOD0(UnbindFromNetwork, void ()); - MOCK_METHOD0(IsEntityBoundToNetwork, bool ()); - MOCK_METHOD0(IsEntityAuthoritative, bool ()); - MOCK_METHOD0(MarkAsLevelSliceEntity, void ()); - MOCK_METHOD1(SetSliceInstanceId, void (const AZ::SliceComponent::SliceInstanceId&)); - MOCK_METHOD1(SetReplicaPriority, void (GridMate::ReplicaPriority)); - MOCK_METHOD1(RequestEntityChangeOwnership, void (GridMate::PeerId)); - MOCK_CONST_METHOD0(GetReplicaPriority, GridMate::ReplicaPriority ()); - }; -} - -#endif // AZCORE_UNITTEST_NETBINDINGMOCKS_H diff --git a/Code/Framework/Tests/NetBindingSystemImplTest.cpp b/Code/Framework/Tests/NetBindingSystemImplTest.cpp deleted file mode 100644 index 790ef1cd72..0000000000 --- a/Code/Framework/Tests/NetBindingSystemImplTest.cpp +++ /dev/null @@ -1,605 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include "NetBindingMocks.h" -#include -#include -#include -#include - -namespace UnitTest -{ - using namespace AZ; - using namespace AzFramework; - using namespace GridMate; - - class NetBindingWithSlicesTest - : public ScopedAllocatorSetupFixture - { - public: - const NetBindingContextSequence k_fakeContextSeq = 1; - const AZ::SliceComponent::SliceInstanceId k_fakeSliceInstanceId = Uuid::CreateRandom(); - const AZ::SliceComponent::SliceInstanceId k_fakeSliceInstanceId_Another = Uuid::CreateRandom(); - - SliceInstantiationTicket m_sliceTicket = SliceInstantiationTicket(EntityContextId::CreateName("Test"), 1); - const Data::AssetId k_fakeAssetId = Data::AssetId(Uuid::CreateRandom(), 0); - - const EntityId k_fakeEntityId_One = EntityId(9001); - const ReplicaId k_repId_One = 1001; - const EntityId k_fakeEntityId_Two = EntityId(9002); - const ReplicaId k_repId_Two = 1002; - - AZStd::unique_ptr m_netBindingImpl; - AZStd::unique_ptr m_componentApplication; - AZStd::unique_ptr m_applicationContext; - - AZStd::unique_ptr m_gameEntityMock; - AZStd::unique_ptr m_replicaManagerMock; - ReplicaPtr m_replicaMock; - - ComponentDescriptor* m_netBindingSystemComponentDescriptor = nullptr; - - AZStd::intrusive_ptr m_contextChunkMock; - - MockAssetHandler* m_myAssetHandlerAndCatalog = nullptr; // owned by AssetManager - AZStd::unique_ptr m_fakeAsset; - - const float k_wayOverSliceTimeout = NetBindingSystemImpl::s_sliceBindingTimeout.count() * 2.f; - const float k_smallStep = 0.1f; - - void SetUpFakeAssetManager() - { - using namespace testing; - - const Data::AssetManager::Descriptor desc; - Data::AssetManager::Create(desc); - - m_myAssetHandlerAndCatalog = aznew NiceMock; - - ON_CALL(*m_myAssetHandlerAndCatalog, CreateAsset(_, _)) - .WillByDefault(Invoke([this](const Data::AssetId&, const Data::AssetType&) -> Data::AssetPtr - { - m_fakeAsset = AZStd::make_unique>(k_fakeAssetId); - return m_fakeAsset.get(); - })); - - ON_CALL(*m_myAssetHandlerAndCatalog, DestroyAsset(_)) - .WillByDefault(Invoke([this](const Data::AssetPtr asset) - { - EXPECT_EQ(asset, m_fakeAsset.get()); - m_fakeAsset.reset(); - })); - - Data::AssetManager::Instance().RegisterHandler(m_myAssetHandlerAndCatalog, AzTypeInfo::Uuid()); - Data::AssetManager::Instance().RegisterHandler(m_myAssetHandlerAndCatalog, AzTypeInfo::Uuid()); - } - - void SetUp() override - { - using namespace testing; - - m_applicationContext.reset(aznew SerializeContext()); - - AllocatorInstance::Create(); - AllocatorInstance::Create(); - - DefaultValue::Set(m_sliceTicket); - - m_gameEntityMock = AZStd::make_unique>(); - m_componentApplication = AZStd::make_unique>(); - - ON_CALL(*m_componentApplication, GetSerializeContext()) - .WillByDefault(Invoke([this]() - { - return m_applicationContext.get(); - })); - - ON_CALL(*m_gameEntityMock, GetGameEntityContextId()) - .WillByDefault(Return(EntityContextId::CreateRandom())); - - m_netBindingSystemComponentDescriptor = NetBindingSystemComponent::CreateDescriptor(); - - ReplicaChunkDescriptorTable::Get().RegisterChunkType(); - m_contextChunkMock.reset(CreateReplicaChunk>()); - - ON_CALL(*m_contextChunkMock, ShouldBindToNetwork()) - .WillByDefault(Return(true)); - - m_replicaManagerMock = AZStd::make_unique>(); - - ON_CALL(*m_contextChunkMock, GetReplicaManager()) - .WillByDefault(Invoke([this]() - { - return m_replicaManagerMock.get(); - })); - - m_replicaMock = Replica::CreateReplica("unittest"); - - ON_CALL(*m_replicaManagerMock, FindReplica(_)) - .WillByDefault(Invoke([this](ReplicaId id) -> ReplicaPtr - { - AZ_UNUSED(id); - return m_replicaMock; - })); - - ON_CALL(*m_contextChunkMock, OnReplicaActivate(_)) - .WillByDefault(Invoke(m_contextChunkMock.get(), &MockNetBindingSystemContextData::Base_OnReplicaActivate)); - - m_netBindingImpl = AZStd::make_unique(); - m_netBindingImpl->Init(); - - m_contextChunkMock->OnReplicaActivate(ReplicaContext(nullptr, TimeContext())); - - SetUpFakeAssetManager(); - } - - void TearDown() override - { - Data::AssetManager::Destroy(); - - m_replicaMock.reset(); - m_replicaManagerMock.reset(); - m_contextChunkMock.reset(); - - m_fakeAsset.reset(); - m_netBindingImpl->Shutdown(); - m_netBindingImpl.reset(); - - ReplicaChunkDescriptorTable::Get().UnregisterReplicaChunkDescriptor(ReplicaChunkClassId(MockNetBindingSystemContextData::GetChunkName())); - - m_netBindingSystemComponentDescriptor->ReleaseDescriptor(); - - m_componentApplication.reset(); - m_gameEntityMock.reset(); - - AllocatorInstance::Destroy(); - AllocatorInstance::Destroy(); - - m_applicationContext.reset(); - } - }; - - TEST_F(NetBindingWithSlicesTest, SameSliceInstanceId_InstantiateDynamicSlice_CallOnce) - { - using namespace testing; - - EXPECT_CALL(*m_gameEntityMock, InstantiateDynamicSlice(_, _, _)) - .Times(1); - EXPECT_CALL(*m_gameEntityMock, CancelDynamicSliceInstantiation(_)) - .Times(1); - - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; // both mock entities come from the same slice - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_Two; - spawnContext.m_staticEntityId = k_fakeEntityId_Two; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; // both mock entities come from the same slice - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_Two, spawnContext); - } - - // this should kick off NetBindingSystemImpl::ProcessBindRequests - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - } - - TEST_F(NetBindingWithSlicesTest, DifferentSliceInstanceId_InstantiateDynamicSlice_CalledTwice) - { - using namespace testing; - - EXPECT_CALL(*m_gameEntityMock, InstantiateDynamicSlice(_, _, _)) - .Times(2); - EXPECT_CALL(*m_gameEntityMock, CancelDynamicSliceInstantiation(_)) - .Times(2); - - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_Two; - spawnContext.m_staticEntityId = k_fakeEntityId_Two; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId_Another; // different slice entity - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_Two, spawnContext); - } - - // this should kick off NetBindingSystemImpl::ProcessBindRequests - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - } - - TEST_F(NetBindingWithSlicesTest, AssetManagerDestroyed_InstantiateDynamicSlice_NotCalled) - { - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; // both mock entities come from the same slice - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - - Data::AssetManager::Destroy(); - - // this should kick off NetBindingSystemImpl::ProcessBindRequests, but InstantiateDynamicSlice will not be called - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - } - - class ExtendedBindingWithSlicesTest - : public NetBindingWithSlicesTest - { - public: - void SetUp() override - { - NetBindingWithSlicesTest::SetUp(); - } - - void TearDown() override - { - using namespace testing; - - EXPECT_CALL(*m_gameEntityMock, DestroyGameEntity(k_fakeEntityId_One)) - .Times(AtMost(1)); - EXPECT_CALL(*m_gameEntityMock, DestroyGameEntity(k_fakeEntityId_Two)) - .Times(AtMost(1)); - - NetBindingWithSlicesTest::TearDown(); - } - - class InstantiateMockSlice - { - public: - explicit InstantiateMockSlice(ExtendedBindingWithSlicesTest* parent) - { - using namespace testing; - - m_mockSliceRef = AZStd::make_unique(); - m_mockSliceInstance = AZStd::make_unique(); - - // container owns the entities and will delete them - auto mockContainer = AZStd::make_unique(); - - auto binding1 = AZStd::make_unique>(); - mockContainer->m_entities.push_back(CreateMockEntity(parent->k_fakeEntityId_One, binding1.release())); - - auto binding2 = AZStd::make_unique>(); - mockContainer->m_entities.push_back(CreateMockEntity(parent->k_fakeEntityId_Two, binding2.release())); - - m_mockSliceInstance->SetMockInstantiatedContainer(mockContainer.release()); - - SliceComponent::SliceInstanceAddress sliceInstanceAddress(m_mockSliceRef.get(), m_mockSliceInstance.get()); - - // This will pass our mock slice to NetBindingSystem - EBUS_EVENT_ID(parent->m_sliceTicket, SliceInstantiationResultBus, OnSlicePreInstantiate, parent->k_fakeAssetId, sliceInstanceAddress); - EBUS_EVENT_ID(parent->m_sliceTicket, SliceInstantiationResultBus, OnSliceInstantiated, parent->k_fakeAssetId, sliceInstanceAddress); - } - - Entity* CreateMockEntity(const EntityId& id, Component* optional = nullptr) - { - using namespace testing; - - auto mock = AZStd::make_unique>(); - mock->SetId(EntityId(id)); - if (optional) - { - mock->AddComponent(optional); // entity owns the component - } - ON_CALL(*mock, Init()) - .WillByDefault(Invoke(mock.get(), &MockEntity::Base_Init)); - mock->Init(); - - ON_CALL(*mock, Activate()) - .WillByDefault(Invoke(mock.get(), &MockEntity::Base_Activate)); - - ON_CALL(*mock, Deactivate()) - .WillByDefault(Invoke(mock.get(), &MockEntity::Base_Deactivate)); - - return mock.release(); - } - - AZStd::unique_ptr m_mockSliceRef; - AZStd::unique_ptr m_mockSliceInstance; - }; - - AZStd::unique_ptr m_slice; - - void CreateMockSlice() - { - m_slice = AZStd::make_unique(this); - } - }; - - TEST_F(ExtendedBindingWithSlicesTest, ActiveSlice_EntitiesThatWerentBounded_StayDeactivated) - { - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - CreateMockSlice(); - - MockEntity* mock1 = static_cast(m_componentApplication->FindEntity(k_fakeEntityId_One)); - EXPECT_CALL(*mock1, Activate()). - Times(1); - - MockEntity* mock2 = static_cast(m_componentApplication->FindEntity(k_fakeEntityId_Two)); - EXPECT_CALL(*mock2, Activate()). - Times(0); - - EXPECT_CALL(*m_gameEntityMock, DestroyGameEntity(k_fakeEntityId_Two)) - .Times(0); - - // Now it should time out the slice handler and the second entity should remain deactivated since we didn't give binding request for it - EBUS_EVENT(AZ::TickBus, OnTick, k_wayOverSliceTimeout, AZ::ScriptTimePoint()); - - } - - TEST_F(ExtendedBindingWithSlicesTest, ActiveSlice_SpawnSecondEntity_AfterLongDelay_InSameSlicenInstance) - { - EXPECT_CALL(*m_gameEntityMock, DestroyGameEntity(k_fakeEntityId_Two)) - .Times(0); - - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - CreateMockSlice(); - - MockEntity* mock2 = static_cast(m_componentApplication->FindEntity(k_fakeEntityId_Two)); - EXPECT_CALL(*mock2, Activate()). - Times(0); - - // This should not trigger removal of the second entity yet - auto halfTimeoutInSeconds = AZStd::chrono::seconds(NetBindingSystemImpl::s_sliceBindingTimeout).count() * 10.f; - EBUS_EVENT(AZ::TickBus, OnTick, halfTimeoutInSeconds, AZ::ScriptTimePoint()); - - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_Two; - spawnContext.m_staticEntityId = k_fakeEntityId_Two; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; // both mock entities come from the same slice - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_Two, spawnContext); - } - - EXPECT_CALL(*mock2, Activate()). - Times(1); - - // This should give net binding system time to bind the second entity - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - - // Let the slice timeout, this should lead to no destruction since both entities ought to have been bound by now - EBUS_EVENT(AZ::TickBus, OnTick, k_wayOverSliceTimeout, AZ::ScriptTimePoint()); - } - - TEST_F(ExtendedBindingWithSlicesTest, ActiveSlice_DespawnLastEntity_DespawnWholeSliceAfterTimeout) - { - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - CreateMockSlice(); - - MockEntity* mock1 = static_cast(m_componentApplication->FindEntity(k_fakeEntityId_One)); - EXPECT_CALL(*mock1, Activate()). - Times(1); - - // This should not trigger removal of the second entity yet - auto halfTimeoutInSeconds = AZStd::chrono::seconds(NetBindingSystemImpl::s_sliceBindingTimeout).count() * 10.f; - EBUS_EVENT(AZ::TickBus, OnTick, halfTimeoutInSeconds, AZ::ScriptTimePoint()); - - EXPECT_CALL(*mock1, Deactivate()). - Times(1); - EBUS_EVENT(NetBindingSystemBus, UnbindGameEntity, k_fakeEntityId_One, k_fakeSliceInstanceId); - - EXPECT_CALL(*m_gameEntityMock, DestroyGameEntity(k_fakeEntityId_One)) - .Times(1); - EXPECT_CALL(*m_gameEntityMock, DestroyGameEntity(k_fakeEntityId_Two)) - .Times(1); - - EBUS_EVENT(AZ::TickBus, OnTick, k_wayOverSliceTimeout, AZ::ScriptTimePoint()); - } - - TEST_F(ExtendedBindingWithSlicesTest, ActiveSlice_DespawnLastEntityBeforeSliceInstantiation_DespawnWholeSlice) - { - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - - EBUS_EVENT(NetBindingSystemBus, UnbindGameEntity, k_fakeEntityId_One, k_fakeSliceInstanceId); - - CreateMockSlice(); - - MockEntity* mock1 = static_cast(m_componentApplication->FindEntity(k_fakeEntityId_One)); - EXPECT_CALL(*mock1, Activate()). - Times(0); - - auto halfTimeoutInSeconds = AZStd::chrono::seconds(NetBindingSystemImpl::s_sliceBindingTimeout).count() * 10.f; - EBUS_EVENT(AZ::TickBus, OnTick, halfTimeoutInSeconds, AZ::ScriptTimePoint()); - - EBUS_EVENT(AZ::TickBus, OnTick, k_wayOverSliceTimeout, AZ::ScriptTimePoint()); - } - - TEST_F(ExtendedBindingWithSlicesTest, ActiveSlice_ReuseEntity) - { - EXPECT_CALL(*m_gameEntityMock, DestroyGameEntity(k_fakeEntityId_Two)) - .Times(0); - - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_Two; - spawnContext.m_staticEntityId = k_fakeEntityId_Two; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; // both mock entities come from the same slice - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_Two, spawnContext); - } - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - CreateMockSlice(); - - MockEntity* mock2 = static_cast(m_componentApplication->FindEntity(k_fakeEntityId_Two)); - EXPECT_CALL(*mock2, Activate()). - Times(1); - - EBUS_EVENT(AZ::TickBus, OnTick, k_wayOverSliceTimeout, AZ::ScriptTimePoint()); - - EXPECT_CALL(*mock2, Deactivate()). - Times(1); - - // some time later the second entity goes away and comes back - EBUS_EVENT(NetBindingSystemBus, UnbindGameEntity, k_fakeEntityId_Two, k_fakeSliceInstanceId); - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_Two; - spawnContext.m_staticEntityId = k_fakeEntityId_Two; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; // both mock entities come from the same slice - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_Two, spawnContext); - } - - // The same entity should be activated for the second time - EXPECT_CALL(*mock2, Activate()). - Times(1); // Note, Google Mock treats each expect_call separately and satisfies them separately. That's why it's 1 here, despite being a second call. - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - } - - TEST_F(ExtendedBindingWithSlicesTest, SliceFailedToSpawn) - { - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - - EBUS_EVENT_ID(m_sliceTicket, SliceInstantiationResultBus, OnSliceInstantiationFailed, k_fakeAssetId); - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - - EXPECT_TRUE(m_componentApplication->FindEntity(k_fakeEntityId_One) == nullptr); - } - - TEST_F(ExtendedBindingWithSlicesTest, SliceSpawned_AfterTimeout) - { - { - NetBindingSliceContext spawnContext; - spawnContext.m_contextSequence = k_fakeContextSeq; - spawnContext.m_sliceAssetId = k_fakeAssetId; - spawnContext.m_runtimeEntityId = k_fakeEntityId_One; - spawnContext.m_staticEntityId = k_fakeEntityId_One; - spawnContext.m_sliceInstanceId = k_fakeSliceInstanceId; - - EBUS_EVENT(NetBindingSystemBus, SpawnEntityFromSlice, k_repId_One, spawnContext); - } - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - EBUS_EVENT(AZ::TickBus, OnTick, k_wayOverSliceTimeout, AZ::ScriptTimePoint()); - - CreateMockSlice(); - - MockEntity* mock1 = static_cast(m_componentApplication->FindEntity(k_fakeEntityId_One)); - EXPECT_CALL(*mock1, Activate()). - Times(1); - - EBUS_EVENT(AZ::TickBus, OnTick, k_smallStep, AZ::ScriptTimePoint()); - } -} diff --git a/Code/Framework/Tests/NetworkContext.cpp b/Code/Framework/Tests/NetworkContext.cpp deleted file mode 100644 index 5af9ca70d8..0000000000 --- a/Code/Framework/Tests/NetworkContext.cpp +++ /dev/null @@ -1,801 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace UnitTest -{ - using namespace AZ; - using namespace AzFramework; - - class TestComponentExternalChunk - : public AZ::Component - , public NetBindable - { - public: - AZ_COMPONENT(TestComponentExternalChunk, "{73BB3B15-7C4D-4BD5-9568-F3B2DCBC7725}", AZ::Component); - - static void Reflect(ReflectContext* context); - - void Init() override - { - NetBindable::NetInit(); - } - - void Activate() override {} - void Deactivate() override {} - - bool SetPos(float x, float y, const RpcContext&) - { - m_x = x; - m_y = y; - return true; - } - - void OnFloatChanged(const float&, const TimeContext&) - { - m_floatChanged = true; - } - - bool m_floatChanged = false; - private: - float m_x = 0, m_y = 0; - }; - - class TestComponentReplicaChunk - : public ReplicaChunkBase - , public ReplicaChunkInterface - { - public: - GM_CLASS_ALLOCATOR(TestComponentReplicaChunk); - static const char* GetChunkName() { return "TestComponentReplicaChunk"; } - bool IsReplicaMigratable() override { return true; } - - public: - TestComponentReplicaChunk() - : m_int("m_int", 42) - , m_float("m_float", 96.4f) - , SetInt("SetInt") - , SetPos("SetPos") - { - } - - bool SetIntImpl(int newValue, const RpcContext&) - { - m_int.Set(newValue); - return true; - } - - DataSet m_int; - DataSet::BindInterface m_float; - GridMate::Rpc > >::BindInterface SetInt; - GridMate::Rpc, GridMate::RpcArg >::BindInterface SetPos; - }; - - void TestComponentExternalChunk::Reflect(ReflectContext* context) - { - NetworkContext* netContext = azrtti_cast(context); - if (netContext) - { - netContext->Class() - ->Chunk() - ->Field("m_int", &TestComponentReplicaChunk::m_int) - ->Field("m_float", &TestComponentReplicaChunk::m_float) - ->RPC("SetInt", &TestComponentReplicaChunk::SetInt) - ->RPC("SetPos", &TestComponentReplicaChunk::SetPos); - } - } - - class TestComponentAutoChunk - : public AZ::Component - , public NetBindable - { - public: - enum TestEnum - { - TEST_Value0 = 0, - TEST_Value1 = 1, - TEST_Value255 = 255 - }; - - AZ_COMPONENT(TestComponentAutoChunk, "{003FD1BC-8456-43D5-9879-1B3804327A4F}", AZ::Component); - - static void Reflect(ReflectContext* context) - { - NetworkContext* netContext = azrtti_cast(context); - if (netContext) - { - netContext->Class() - ->Field("m_int", &TestComponentAutoChunk::m_int) - ->Field("m_float", &TestComponentAutoChunk::m_float) - ->Field("m_enum", &TestComponentAutoChunk::m_enum) - ->RPC("SetInt", &TestComponentAutoChunk::SetInt) - ->CtorData("CtorInt", &TestComponentAutoChunk::GetCtorInt, &TestComponentAutoChunk::SetCtorInt) - ->CtorData("CtorVec", &TestComponentAutoChunk::GetCtorVec, &TestComponentAutoChunk::SetCtorVec); - } - SerializeContext* serializeContext = azrtti_cast(context); - if (serializeContext) - { - serializeContext->Class() - ->Version(1) - ->Field("m_int", &TestComponentAutoChunk::m_int) - ->Field("m_float", &TestComponentAutoChunk::m_float) - ->Field("m_enum", &TestComponentAutoChunk::m_enum) - ->Field("ctorInt", &TestComponentAutoChunk::m_ctorInt) - ->Field("ctorVec", &TestComponentAutoChunk::m_ctorVec); - } - } - - void Init() override - { - NetBindable::NetInit(); - } - - void Activate() override {} - void Deactivate() override {} - - void SetNetworkBinding(ReplicaChunkPtr chunk) override {} - void UnbindFromNetwork() override {} - - bool SetIntImpl(int val, const RpcContext&) - { - m_int = val; - return true; - } - - void OnFloatChanged(const float&, const TimeContext&) - { - } - - int GetCtorInt() const { return m_ctorInt; } - void SetCtorInt(const int& ctorInt) { m_ctorInt = ctorInt; } - - AZStd::vector& GetCtorVec() { return m_ctorVec; } - void SetCtorVec(const AZStd::vector& vec) { m_ctorVec = vec; } - - int m_ctorInt; - AZStd::vector m_ctorVec; - Field m_int; - BoundField m_float; - Field > m_enum; - Rpc::Binder SetInt; - }; - - class NetContextReflectionTest - : public AllocatorsTestFixture - { - public: - void SetUp() override - { - AllocatorsTestFixture::SetUp(); - - AZ::AllocatorInstance::Create(); - } - - void TearDown() override - { - AZ::AllocatorInstance::Destroy(); - - AllocatorsTestFixture::TearDown(); - } - - void run() - { - AzFramework::Application app; - AzFramework::Application::Descriptor appDesc; - appDesc.m_recordingMode = Debug::AllocationRecords::RECORD_NO_RECORDS; - appDesc.m_allocationRecords = false; - appDesc.m_enableDrilling = false; - - app.Start(appDesc); - - // Without this, the user settings component would attempt to save on finalize/shutdown. Since the file is - // shared across the whole engine, if multiple tests are run in parallel, the saving could cause a crash - // in the unit tests. - AZ::UserSettingsComponentRequestBus::Broadcast(&AZ::UserSettingsComponentRequests::DisableSaveOnFinalize); - - AzFramework::NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_TEST_ASSERT(netContext); - - AZ::ComponentDescriptor* descTestComponentExternalChunk = TestComponentExternalChunk::CreateDescriptor(); - app.RegisterComponentDescriptor(descTestComponentExternalChunk); - - AZ::ComponentDescriptor* descTestComponentAutoChunk = TestComponentAutoChunk::CreateDescriptor(); - app.RegisterComponentDescriptor(descTestComponentAutoChunk); - - AZ::Entity* testEntity = aznew AZ::Entity("TestEntity"); - testEntity->Init(); - testEntity->CreateComponent(); - testEntity->CreateComponent(); - testEntity->Activate(); - - // test field binding/auto reflection/creation - { - TestComponentAutoChunk* testComponent = testEntity->FindComponent(); - AZ_TEST_ASSERT(testComponent); - - testComponent->SetInt(2048); // should happen locally - AZ_TEST_ASSERT(testComponent->m_int == 2048); - - ReplicaChunkPtr chunk = testComponent->GetNetworkBinding(); - AZ_TEST_ASSERT(chunk); - - GridMate::ReplicaChunkDescriptor* desc = chunk->GetDescriptor(); - AZ_TEST_ASSERT(desc); - - testComponent->m_ctorInt = 8192; - for (int n = 0; n < 16; ++n) - { - testComponent->m_ctorVec.push_back(n); - } - - GridMate::WriteBufferDynamic wb(GridMate::EndianType::IgnoreEndian); - desc->MarshalCtorData(chunk.get(), wb); - - { - // Create a chunk from the recorded ctor data, ensure that it stores - // the ctor data in preparation for copying it to the instance - GridMate::TimeContext tc; - GridMate::ReplicaContext rc(nullptr, tc); - GridMate::ReadBuffer rb(wb.GetEndianType(), wb.Get(), wb.Size()); - GridMate::UnmarshalContext ctx(rc); - ctx.m_hasCtorData = true; - ctx.m_iBuf = &rb; - ReplicaChunkPtr chunk2 = desc->CreateFromStream(ctx); - AZ_TEST_ASSERT(chunk2); // ensure a new chunk was created - ReflectedReplicaChunkBase* refChunk = static_cast(chunk2.get()); - AZ_TEST_ASSERT(refChunk->m_ctorBuffer.Size() == sizeof(int) + sizeof(AZ::u16) + (sizeof(int) * testComponent->m_ctorVec.size())); - } - - { - // discard a ctor data stream and ensure that the stream is emptied - GridMate::TimeContext tc; - GridMate::ReplicaContext rc(nullptr, tc); - GridMate::ReadBuffer rb(wb.GetEndianType(), wb.Get(), wb.Size()); - GridMate::UnmarshalContext ctx(rc); - ctx.m_hasCtorData = true; - ctx.m_iBuf = &rb; - desc->DiscardCtorStream(ctx); - AZ_TEST_ASSERT(rb.IsEmptyIgnoreTrailingBits()); // should have discarded the whole stream - } - - { - // Make another chunk and bind it to a new component and make sure the ctor data matches - AZ::Entity* testEntity2 = aznew AZ::Entity("TestEntity2"); - testEntity2->Init(); - testEntity2->CreateComponent(); - testEntity2->Activate(); - - GridMate::TimeContext tc; - GridMate::ReplicaContext rc(nullptr, tc); - GridMate::ReadBuffer rb(wb.GetEndianType(), wb.Get(), wb.Size()); - GridMate::UnmarshalContext ctx(rc); - ctx.m_hasCtorData = true; - ctx.m_iBuf = &rb; - ReplicaChunkPtr chunk2 = desc->CreateFromStream(ctx); - - TestComponentAutoChunk* testComponent2 = testEntity2->FindComponent(); - netContext->Bind(testComponent2, chunk2, NetworkContextBindMode::NonAuthoritative); - // Ensure values match after ctor data is applied - AZ_TEST_ASSERT(testComponent2->m_ctorInt == testComponent->m_ctorInt); - AZ_TEST_ASSERT(testComponent2->m_ctorVec == testComponent->m_ctorVec); - } - - testComponent->SetInt(4096); - AZ_TEST_ASSERT(testComponent->m_int == 4096); - - testComponent->m_int = 42; // now it should change - AZ_TEST_ASSERT(testComponent->m_int == 42); - testComponent->m_enum = TestComponentAutoChunk::TEST_Value1; - - chunk.reset(); // should cause netContext->DestroyReplicaChunk() - } - - // test chunk binding/creation - { - TestComponentExternalChunk* testComponent = testEntity->FindComponent(); - AZ_TEST_ASSERT(testComponent); - - ReplicaChunkPtr chunk = testComponent->GetNetworkBinding(); - AZ_TEST_ASSERT(chunk); - - TestComponentReplicaChunk* testChunk = static_cast(chunk.get()); - - // for now, this will throw a warning, but will at least attempt the dispatch - testChunk->SetPos(42.0f, 96.0f); - - AZ_TEST_ASSERT(testComponent->m_floatChanged == false); - testChunk->m_float.Set(1024.0f); - // I would like to test that the notify fired, but without a Replica, cant :( - - testComponent->UnbindFromNetwork(); - chunk.reset(); ///// CRASHES FROM HERE - } - - // test serialization of NetBindable::Fields - { - TestComponentAutoChunk* testComponent = testEntity->FindComponent(); - AZStd::vector buffer; - AZ::IO::ByteContainerStream > saveStream(&buffer); - bool saved = AZ::Utils::SaveObjectToStream(saveStream, AZ::DataStream::ST_XML, testComponent); - AZ_TEST_ASSERT(saved); - AZ::IO::ByteContainerStream > loadStream(&buffer); - TestComponentAutoChunk* testCopy = AZ::Utils::LoadObjectFromStream(loadStream); - AZ_TEST_ASSERT(testCopy); - delete testCopy; - } - - testEntity->Deactivate(); - delete testEntity; - - descTestComponentExternalChunk->ReleaseDescriptor(); - descTestComponentAutoChunk->ReleaseDescriptor(); - - app.Stop(); - } - }; - - TEST_F(NetContextReflectionTest, Test) - { - run(); - } - - template - class NetContextFixture - : public ::testing::Test - { - public: - NetContextFixture() = default; - ~NetContextFixture() = default; - - void SetUp() override - { - AZ::AllocatorInstance::Create(); - - m_app = AZStd::make_unique(); - m_app->Start(AzFramework::Application::Descriptor()); - - // Without this, the user settings component would attempt to save on finalize/shutdown. Since the file is - // shared across the whole engine, if multiple tests are run in parallel, the saving could cause a crash - // in the unit tests. - AZ::UserSettingsComponentRequestBus::Broadcast(&AZ::UserSettingsComponentRequests::DisableSaveOnFinalize); - - AzFramework::NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_TEST_ASSERT(netContext); - - m_descTestComponentAutoChunk = ComponentType::CreateDescriptor(); - m_app->RegisterComponentDescriptor(m_descTestComponentAutoChunk); - - m_entity = AZStd::make_unique("TestEntity"); - m_entity->Init(); - m_entity->CreateComponent(); - m_entity->Activate(); - } - - void TearDown() override - { - m_descTestComponentAutoChunk->ReleaseDescriptor(); - - m_entity->Deactivate(); - m_entity.reset(); - - m_app->Stop(); - m_app.reset(); - - AZ::AllocatorInstance::Destroy(); - } - - void RunTest() - { - const ComponentType* testComponent = m_entity->FindComponent(); - AZStd::vector buffer; - AZ::IO::ByteContainerStream > saveStream(&buffer); - const bool saved = AZ::Utils::SaveObjectToStream(saveStream, AZ::DataStream::ST_XML, testComponent); - AZ_TEST_ASSERT(saved); - AZ::IO::ByteContainerStream > loadStream(&buffer); - const AZStd::unique_ptr testCopy(AZ::Utils::LoadObjectFromStream(loadStream)); - AZ_TEST_ASSERT(testCopy); - } - - AZStd::unique_ptr m_app; - AZStd::unique_ptr m_entity; - AZ::ComponentDescriptor* m_descTestComponentAutoChunk = nullptr; - }; - - class TestComponent_EmptyNetContext - : public AZ::Component - , public NetBindable - { - public: - AZ_COMPONENT(TestComponent_EmptyNetContext, "{B1E2E2DD-DA70-4D59-A185-AF9A5CCF1574}", AZ::Component, NetBindable); - - static void Reflect(ReflectContext* context) - { - if (SerializeContext* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1); - } - if (NetworkContext* netContext = azrtti_cast(context)) - { - netContext->Class(); - } - } - - void Activate() override {} - void Deactivate() override {} - }; - - using NetContextEmpty = NetContextFixture; - TEST_F(NetContextEmpty, SerializationTests) - { - RunTest(); - } - - template - class TestComponent_OneField - : public AZ::Component - , public NetBindable - { - public: - AZ_COMPONENT(TestComponent_OneField, "{A7BCDBEF-3D4F-4D04-A6FA-DF48D4B66ABE}", AZ::Component, NetBindable); - - using ThisComponentType = TestComponent_OneField; - - static void Reflect(ReflectContext* context) - { - if (SerializeContext* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Field("Field", &TestComponent_OneField::m_field) - ->Version(1); - } - if (NetworkContext* netContext = azrtti_cast(context)) - { - netContext->Class() - ->Field("Field", &TestComponent_OneField::m_field); - } - } - - void Activate() override {} - void Deactivate() override {} - - Field m_field; - }; - - TYPED_TEST_CASE_P(NetContextFixture); - - TYPED_TEST_P(NetContextFixture, SerializationTests) - { - this->RunTest(); - } - - REGISTER_TYPED_TEST_CASE_P(NetContextFixture, SerializationTests); - - /* - * Testing the basic common types. - */ - using CommonTypes = ::testing::Types< - TestComponent_OneField, - TestComponent_OneField, - TestComponent_OneField, - TestComponent_OneField, - TestComponent_OneField, - TestComponent_OneField, - TestComponent_OneField - >; - - INSTANTIATE_TYPED_TEST_CASE_P(NetContextCommonSerialization, NetContextFixture, CommonTypes); - - /* - * And some less common types. - */ - using LessCommonTypes = ::testing::Types< - TestComponent_OneField, - TestComponent_OneField, - TestComponent_OneField, - TestComponent_OneField>, - TestComponent_OneField - >; - - INSTANTIATE_TYPED_TEST_CASE_P(NetContextLessCommonSerialization, NetContextFixture, LessCommonTypes); - - /* - * Next up are marshal and unmarshal tests. - */ - - template - class NetContextMarshalFixture - : public UnitTest::AllocatorsTestFixture - { - public: - NetContextMarshalFixture() = default; - ~NetContextMarshalFixture() = default; - - void SetUp() override - { - UnitTest::AllocatorsTestFixture::SetUp(); - - AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); - - m_app = AZStd::make_unique(); - m_app->Start(AzFramework::Application::Descriptor()); - - // Without this, the user settings component would attempt to save on finalize/shutdown. Since the file is - // shared across the whole engine, if multiple tests are run in parallel, the saving could cause a crash - // in the unit tests. - AZ::UserSettingsComponentRequestBus::Broadcast(&AZ::UserSettingsComponentRequests::DisableSaveOnFinalize); - - AzFramework::NetworkContext* netContext = nullptr; - EBUS_EVENT_RESULT(netContext, NetSystemRequestBus, GetNetworkContext); - AZ_TEST_ASSERT(netContext); - - m_descTestComponentAutoChunk = ComponentType::CreateDescriptor(); - m_app->RegisterComponentDescriptor(m_descTestComponentAutoChunk); - - m_entityFrom = AZStd::make_unique("TestEntityFrom"); - m_entityFrom->Init(); - m_componentFrom = m_entityFrom->CreateComponent(); - m_entityFrom->Activate(); - - m_entityTo = AZStd::make_unique("TestEntityTo"); - m_entityTo->Init(); - m_componentTo = m_entityTo->CreateComponent(); - m_entityTo->Activate(); - } - - void MarshalUnMarshal() - { - AzFramework::NetworkContext* netContext = nullptr; - NetSystemRequestBus::BroadcastResult(netContext, &NetSystemRequestBus::Events::GetNetworkContext); - AZ_TEST_ASSERT(netContext); - - ComponentType* testComponent = m_entityFrom->FindComponent(); - AZ_TEST_ASSERT(testComponent); - ReplicaChunkPtr chunk = testComponent->GetNetworkBinding(); - AZ_TEST_ASSERT(chunk); - - m_outReplica = AZStd::make_unique("ReplicaTo"); - { - m_outManager = AZStd::make_unique(); - m_outPeer = AZStd::make_unique(m_outManager.get()); - - GridMate::WriteBufferDynamic wb(GridMate::EndianType::IgnoreEndian); - { - GridMate::TimeContext tc; - const GridMate::ReplicaContext rc(nullptr, tc); - GridMate::MarshalContext mc(GridMate::ReplicaMarshalFlags::FullSync, &wb, nullptr, rc); - mc.m_peer = m_outPeer.get(); - mc.m_rm = m_outManager.get(); - chunk->Debug_PrepareData(wb.GetEndianType(), GridMate::ReplicaMarshalFlags::FullSync); - chunk->Debug_Marshal(mc, 0); - } - - // and now unmarshal into the other entity - { - GridMate::TimeContext tc; - const GridMate::ReplicaContext rc(nullptr, tc); - GridMate::ReadBuffer rb(wb.GetEndianType(), wb.Get(), wb.Size()); - GridMate::UnmarshalContext ctx(rc); - ctx.m_hasCtorData = false; - ctx.m_iBuf = &rb; - ctx.m_peer = m_outPeer.get(); - ctx.m_rm = m_outManager.get(); - m_outReplicaChunk = chunk->GetDescriptor()->CreateFromStream(ctx); - - m_outReplicaChunk->Debug_AttachedToReplica(m_outReplica.get()); - ctx.m_peer->Debug_Add(m_outReplica.get()); - m_outReplicaChunk->Debug_Unmarshal(ctx, 0); - /* - * Note the order: unmarshal first to populate the chunk with data, then apply it to a component. - * The expectation is that the valid will apply to NetBindable::Field without being overwritten. - */ - m_componentTo->SetNetworkBinding(m_outReplicaChunk); - - // the main test body can now test for the equality - } - } - } - - void TearDown() override - { - m_outReplicaChunk.reset(); - m_outManager.reset(); - m_outPeer.reset(); - m_outReplica.release(); // Replica is held by as an intrusive pointer in @m_outPeer and is destroyed there. - - if (m_entityFrom) - { - m_entityFrom->Deactivate(); - m_entityFrom.reset(); - } - - if (m_entityTo) - { - m_entityTo->Deactivate(); - m_entityTo.reset(); - } - - m_descTestComponentAutoChunk->ReleaseDescriptor(); - - m_app->Stop(); - m_app.reset(); - - AZ::AllocatorInstance::Destroy(); - AZ::AllocatorInstance::Destroy(); - - UnitTest::AllocatorsTestFixture::TearDown(); - } - - AZStd::unique_ptr m_app; - AZStd::unique_ptr m_entityFrom; - AZStd::unique_ptr m_entityTo; - - ComponentType* m_componentFrom = nullptr; - ComponentType* m_componentTo = nullptr; - - AZ::ComponentDescriptor* m_descTestComponentAutoChunk = nullptr; - - GridMate::ReplicaChunkPtr m_outReplicaChunk; - AZStd::unique_ptr m_outReplica; - AZStd::unique_ptr m_outManager; - AZStd::unique_ptr m_outPeer; - }; - - using NetContextVector3 = NetContextMarshalFixture>; - TEST_F(NetContextVector3, SerializationTests) - { - const Vector3 value = AZ::Vector3::CreateAxisZ( 1.f ); - - m_componentFrom->m_field = value; - MarshalUnMarshal(); - - AZ_TEST_ASSERT(m_componentTo->m_field.Get() == value); - } - - /* - * Now the same test but with NetBindable::BoundField<> - */ - - template - class TestComponent_OneBoundField - : public AZ::Component - , public NetBindable - { - public: - AZ_COMPONENT(TestComponent_OneBoundField, "{2B283821-41DF-46BB-BE8E-66EF7301B62A}", AZ::Component, NetBindable); - - using ThisComponentType = TestComponent_OneBoundField; - - static void Reflect(ReflectContext* context) - { - if (SerializeContext* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Field("Field", &ThisComponentType::m_boundField) - ->Version(1); - } - if (NetworkContext* netContext = azrtti_cast(context)) - { - netContext->Class() - ->Field("Field", &ThisComponentType::m_boundField); - } - } - - void Activate() override {} - void Deactivate() override {} - - void OnBoundFieldChanged( const FieldType&, const GridMate::TimeContext& ) {} - - BoundField m_boundField; - }; - - using NetContextBoundVector2 = NetContextMarshalFixture>; - TEST_F(NetContextBoundVector2, SerializationTests) - { - const Vector2 value = AZ::Vector2::CreateAxisX( 4.f ); - - m_componentFrom->m_boundField = value; - MarshalUnMarshal(); - - AZ_TEST_ASSERT(m_componentTo->m_boundField.Get() == value); - } - - TEST_F(NetContextBoundVector2, Delete_Authoritative_Entity) - { - using ThisComponentType = TestComponent_OneBoundField; - - AzFramework::NetworkContext* netContext = nullptr; - NetSystemRequestBus::BroadcastResult(netContext, &NetSystemRequestBus::Events::GetNetworkContext); - AZ_TEST_ASSERT(netContext); - ThisComponentType* testComponent = m_entityFrom->FindComponent(); - AZ_TEST_ASSERT(testComponent); - ReplicaChunkPtr chunk = testComponent->GetNetworkBinding(); - - // Testing early deletion of an entity on the server. - m_entityFrom->Deactivate(); - m_entityFrom.reset(); - - // This test passes if it doesn't crash on cleanup. - chunk.reset(); - } - - template - class TestComponent_OneBoundField_ServerCallback - : public AZ::Component - , public NetBindable - { - public: - AZ_COMPONENT(TestComponent_OneBoundField_ServerCallback, "{74F5B232-0544-45CA-B207-9846052ED1AD}", AZ::Component, NetBindable); - - using ThisComponentType = TestComponent_OneBoundField_ServerCallback; - - static void Reflect(ReflectContext* context) - { - if (SerializeContext* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Field("Field", &ThisComponentType::m_boundField) - ->Version(1); - } - if (NetworkContext* netContext = azrtti_cast(context)) - { - netContext->Class() - ->Field("Field", &ThisComponentType::m_boundField); - } - } - - void Activate() override {} - void Deactivate() override {} - - void OnBoundFieldChanged( const FieldType&, const GridMate::TimeContext& ) - { - ++m_callbacksInvokeCount; - } - - AZ::u8 m_callbacksInvokeCount = 0; - - BoundField m_boundField; - }; - - using NetContextBoundVector2WithCallbackCount = NetContextMarshalFixture>; - TEST_F(NetContextBoundVector2WithCallbackCount, BoundField_Invoke_OnServer_Test) - { - MarshalUnMarshal(); - - m_componentFrom->m_callbacksInvokeCount = 0; // resetting the count - - const Vector2 value = AZ::Vector2::CreateAxisX( 4.f ); - m_componentFrom->m_boundField = value; - - AZ_TEST_ASSERT(m_componentFrom->m_callbacksInvokeCount == 1); - } -} diff --git a/Code/Framework/Tests/NetworkMarshal.cpp b/Code/Framework/Tests/NetworkMarshal.cpp deleted file mode 100644 index e9c8b336f6..0000000000 --- a/Code/Framework/Tests/NetworkMarshal.cpp +++ /dev/null @@ -1,552 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "TestTypes.h" - -#include -#include -#include -#include - -#include - -namespace UnitTest -{ - template - class MarshalerTester - : public AllocatorsFixture - { - public: - MarshalerTester() - : m_writeBuffer(GridMate::EndianType::BigEndian) - , m_readBuffer(GridMate::EndianType::BigEndian) - { - } - - void SetUp() override - { - AllocatorsFixture::SetUp(); - m_random.SetSeed(AZStd::chrono::milliseconds().count()); - } - - void PopulateReadBuffer() - { - m_readBuffer = GridMate::ReadBuffer(m_writeBuffer.GetEndianType(), m_writeBuffer.Get(), m_writeBuffer.Size()); - } - - AZ::SimpleLcgRandom m_random; - - GridMate::Marshaler m_marshaler; - GridMate::WriteBufferStatic<> m_writeBuffer; - GridMate::ReadBuffer m_readBuffer; - }; - - // EntityIdMarshalerTest - typedef MarshalerTester EntityIdMarshalerTest; - - TEST_F(EntityIdMarshalerTest, SingleMarshalUnmarshalTest_EquivalentEmptyValue) - { - AZ::EntityId initialId; - m_marshaler.Marshal(m_writeBuffer, initialId); - - PopulateReadBuffer(); - - AZ::EntityId receivedId; - m_marshaler.Unmarshal(receivedId, m_readBuffer); - - EXPECT_EQ(initialId,receivedId); - EXPECT_FALSE(receivedId.IsValid()); - } - - TEST_F(EntityIdMarshalerTest, SingleMarshalUnmarshalTest_EquivalentRandomValue) - { - AZ::EntityId initialId = AZ::EntityId(m_random.GetRandom()); - m_marshaler.Marshal(m_writeBuffer, initialId); - - PopulateReadBuffer(); - - AZ::EntityId receivedId; - m_marshaler.Unmarshal(receivedId, m_readBuffer); - - EXPECT_EQ(initialId,receivedId); - } - - TEST_F(EntityIdMarshalerTest, MultipleMarshalUnmarshalTest_EquivalentEmptyRandomEmptyRandomValueChain) - { - AZ::EntityId sentId1_empty; - AZ::EntityId sentId2_random = AZ::EntityId(m_random.GetRandom()); - AZ::EntityId sentId3_empty; - AZ::EntityId sentId4_random = AZ::EntityId(m_random.GetRandom()); - - m_marshaler.Marshal(m_writeBuffer, sentId1_empty); - m_marshaler.Marshal(m_writeBuffer, sentId2_random); - m_marshaler.Marshal(m_writeBuffer, sentId3_empty); - m_marshaler.Marshal(m_writeBuffer, sentId4_random); - - PopulateReadBuffer(); - - AZ::EntityId receivedId1_empty; - AZ::EntityId receivedId2_random; - AZ::EntityId receivedId3_empty; - AZ::EntityId receivedId4_random; - - m_marshaler.Unmarshal(receivedId1_empty, m_readBuffer); - m_marshaler.Unmarshal(receivedId2_random, m_readBuffer); - m_marshaler.Unmarshal(receivedId3_empty, m_readBuffer); - m_marshaler.Unmarshal(receivedId4_random, m_readBuffer); - - EXPECT_EQ(sentId1_empty, receivedId1_empty); - EXPECT_EQ(sentId2_random, receivedId2_random); - EXPECT_EQ(sentId3_empty, receivedId3_empty); - EXPECT_EQ(sentId4_random, receivedId4_random); - } - - // AZ::DynamicSerializableFieldMarshaler - class FooSerializable - { - public: - AZ_RTTI(FooSerializable, "{A60F0B2B-6085-4FF1-BD17-A0B0143BB03D}"); - AZ_CLASS_ALLOCATOR(FooSerializable, AZ::SystemAllocator,0); - - static void Reflect(AZ::SerializeContext& serializeContext) - { - serializeContext.Class() - ->Version(1) - ->Field("IntValue", &FooSerializable::m_intValue) - ->Field("FloatValue", &FooSerializable::m_floatValue) - ; - } - - FooSerializable() - : m_intValue(0) - , m_floatValue(0.0f) - { - } - - bool operator==(const FooSerializable& other) const - { - return m_intValue == other.m_intValue && AZ::IsClose(m_floatValue, other.m_floatValue,0.0001f); - } - - AZ::u32 m_intValue; - float m_floatValue; - }; - - class BarSerializable - { - public: - AZ_RTTI(BarSerializable, "{2389C23F-D247-420B-A385-71AB8455CD2E}"); - AZ_CLASS_ALLOCATOR(BarSerializable, AZ::SystemAllocator,0); - - static void Reflect(AZ::SerializeContext& serializeContext) - { - serializeContext.Class() - ->Version(1) - ->Field("LongValue", &BarSerializable::m_longValue) - ->Field("DoubleValue", &BarSerializable::m_doubleValue) - ; - } - - BarSerializable() - : m_longValue(0) - , m_doubleValue(0.0) - { - } - - bool operator==(const BarSerializable& other) const - { - return m_longValue == other.m_longValue && AZ::IsClose(m_doubleValue,other.m_doubleValue,0.0001); - } - - long m_longValue; - double m_doubleValue; - }; - - class ComplexSerializable - { - public: - AZ_RTTI(ComplexSerializable,"{055CB45C-702C-499F-8221-E9ABB21CF1D4}"); - AZ_CLASS_ALLOCATOR(ComplexSerializable, AZ::SystemAllocator,0); - - static void Reflect(AZ::SerializeContext& serializeContext) - { - serializeContext.Class() - ->Version(1) - ->Field("FooSerializable",&ComplexSerializable::m_fooField) - ->Field("BarSerializable",&ComplexSerializable::m_barField) - ; - } - - bool operator==(const ComplexSerializable& other) const - { - return m_fooField == other.m_fooField && m_barField == other.m_barField; - } - - FooSerializable m_fooField; - BarSerializable m_barField; - }; - - class DynamicSerializableFieldMarshalerTest - : public MarshalerTester - , public AZ::ComponentApplicationBus::Handler - { - public: - DynamicSerializableFieldMarshalerTest() - : MarshalerTester() - { - } - - void SetUp() override - { - MarshalerTester::SetUp(); - - FooSerializable::Reflect(m_serializeContext); - BarSerializable::Reflect(m_serializeContext); - ComplexSerializable::Reflect(m_serializeContext); - - // Create the Marshaler with access to our custom serialize context. - m_marshaler = GridMate::Marshaler(&m_serializeContext); - - AZ::ComponentApplicationBus::Handler::BusConnect(); - } - - void TearDown() override - { - MarshalerTester::TearDown(); - - AZ::ComponentApplicationBus::Handler::BusDisconnect(); - } - - FooSerializable* GenerateFooSerializable() - { - FooSerializable* field = new FooSerializable(); - - RandomizeFooSerializable((*field)); - - return field; - } - - void RandomizeFooSerializable(FooSerializable& serializable) - { - serializable.m_intValue = m_random.GetRandom(); - serializable.m_floatValue = m_random.GetRandomFloat(); - } - - BarSerializable* GenerateBarSerializable() - { - BarSerializable* field = new BarSerializable(); - - return field; - } - - void RandomizeBarSerializable(BarSerializable& serializable) - { - serializable.m_longValue = static_cast(m_random.GetRandom()); - serializable.m_doubleValue = static_cast(m_random.GetRandomFloat()); - } - - ComplexSerializable* GenerateComplexSerializable() - { - ComplexSerializable* complexField = new ComplexSerializable(); - - RandomizeFooSerializable(complexField->m_fooField); - RandomizeBarSerializable(complexField->m_barField); - - return complexField; - } - - // Used Component Application Methods - AZ::SerializeContext* GetSerializeContext() { return &m_serializeContext; } - - // Unused ComponentApplication methods - void RegisterComponentDescriptor(const AZ::ComponentDescriptor* descriptor) override { (void)descriptor; AZ_Assert(false,"Unsupported method in Unit Test"); } - void UnregisterComponentDescriptor(const AZ::ComponentDescriptor* descriptor) override { (void)descriptor; AZ_Assert(false,"Unsupported method in Unit Test"); } - - AZ::ComponentApplication* GetApplication() override { AZ_Assert(false,"Unsupported method in Unit Test"); return nullptr; } - bool AddEntity(AZ::Entity* entity) override { (void)entity; AZ_Assert(false,"Unsupported method in Unit Test"); return false; } - bool RemoveEntity(AZ::Entity* entity) override { (void)entity; AZ_Assert(false,"Unsupported method in Unit Test"); return false; } - bool DeleteEntity(const AZ::EntityId& id) override { (void)id; AZ_Assert(false,"Unsupported method in Unit Test"); return false; } - AZ::Entity* FindEntity(const AZ::EntityId& id) override { (void)id; AZ_Assert(false,"Unsupported method in Unit Test"); return nullptr; } - void EnumerateEntities(const EntityCallback& callback) override { (void)callback; AZ_Assert(false,"Unsupported method in Unit Test"); } - AZ::BehaviorContext* GetBehaviorContext() override { AZ_Assert(false,"Unsupported method in Unit Test"); return nullptr; } - const char* GetAppRoot() override { AZ_Assert(false,"Unsupported method in Unit Test"); return nullptr; } - const char* GetExecutableFolder() override { AZ_Assert(false,"Unsupported method in Unit Test"); return nullptr; } - AZ::Debug::DrillerManager* GetDrillerManager() override { AZ_Assert(false,"Unsupported method in Unit Test"); return nullptr; } - void ReloadModule(const char* moduleFullPath) override { (void)moduleFullPath; AZ_Assert(false,"Unsupported method in Unit Test"); } - - AZ::SerializeContext m_serializeContext; - }; - - TEST_F(DynamicSerializableFieldMarshalerTest, SingleMarshalUnmarshalTest_EquivalentEmptyValue) - { - AZ::DynamicSerializableField sentField; - m_marshaler.Marshal(m_writeBuffer, sentField); - - PopulateReadBuffer(); - - AZ::DynamicSerializableField receivedField; - m_marshaler.Unmarshal(receivedField,m_readBuffer); - - EXPECT_TRUE(sentField.IsEqualTo(receivedField, &m_serializeContext)); - } - - TEST_F(DynamicSerializableFieldMarshalerTest, SingleMarshalUnmarshalTest_EquivalentFooValue) - { - AZ::DynamicSerializableField sentField; - - FooSerializable* fooSerializable = GenerateFooSerializable(); - sentField.Set(fooSerializable); - - m_marshaler.Marshal(m_writeBuffer, sentField); - - PopulateReadBuffer(); - - AZ::DynamicSerializableField receivedField; - m_marshaler.Unmarshal(receivedField,m_readBuffer); - - EXPECT_TRUE(sentField.IsEqualTo(receivedField, &m_serializeContext)); - - sentField.DestroyData(&m_serializeContext); - receivedField.DestroyData(&m_serializeContext); - } - - TEST_F(DynamicSerializableFieldMarshalerTest, SingleMarshalUnmarshalTest_EquivalentBarValue) - { - AZ::DynamicSerializableField sentField; - - BarSerializable* barSerializable = GenerateBarSerializable(); - sentField.Set(barSerializable); - - m_marshaler.Marshal(m_writeBuffer, sentField); - - PopulateReadBuffer(); - - AZ::DynamicSerializableField receivedField; - m_marshaler.Unmarshal(receivedField,m_readBuffer); - - EXPECT_TRUE(sentField.IsEqualTo(receivedField, &m_serializeContext)); - - sentField.DestroyData(&m_serializeContext); - receivedField.DestroyData(&m_serializeContext); - } - - TEST_F(DynamicSerializableFieldMarshalerTest, SingleMarshalUnmarshalTest_EquivalentComplexValue) - { - AZ::DynamicSerializableField sentField; - - ComplexSerializable* complexSerializable = GenerateComplexSerializable(); - sentField.Set(complexSerializable); - - m_marshaler.Marshal(m_writeBuffer, sentField); - - PopulateReadBuffer(); - - AZ::DynamicSerializableField receivedField; - m_marshaler.Unmarshal(receivedField,m_readBuffer); - - EXPECT_TRUE(sentField.IsEqualTo(receivedField, &m_serializeContext)); - - sentField.DestroyData(&m_serializeContext); - receivedField.DestroyData(&m_serializeContext); - } - - TEST_F(DynamicSerializableFieldMarshalerTest, MultipleMarshalUnmarshalTest_EmptyEmptyChainEquivalentValue) - { - AZ::DynamicSerializableField sentField1; - AZ::DynamicSerializableField sentField2; - - m_marshaler.Marshal(m_writeBuffer, sentField1); - m_marshaler.Marshal(m_writeBuffer, sentField2); - - PopulateReadBuffer(); - - AZ::DynamicSerializableField receivedField1; - AZ::DynamicSerializableField receivedField2; - - m_marshaler.Unmarshal(receivedField1,m_readBuffer); - m_marshaler.Unmarshal(receivedField2,m_readBuffer); - - EXPECT_TRUE(sentField1.IsEqualTo(receivedField1, &m_serializeContext)); - EXPECT_TRUE(sentField2.IsEqualTo(receivedField2, &m_serializeContext)); - - sentField1.DestroyData(&m_serializeContext); - sentField2.DestroyData(&m_serializeContext); - receivedField1.DestroyData(&m_serializeContext); - receivedField2.DestroyData(&m_serializeContext); - } - - TEST_F(DynamicSerializableFieldMarshalerTest, MultipleMarshalUnmarshalTest_FooBarComplexChainEquivalentValue) - { - AZ::DynamicSerializableField sentField1; - FooSerializable* fooSerializable = GenerateFooSerializable(); - sentField1.Set(fooSerializable); - - AZ::DynamicSerializableField sentField2; - BarSerializable* barSerializable = GenerateBarSerializable(); - sentField2.Set(barSerializable); - - AZ::DynamicSerializableField sentField3; - ComplexSerializable* complexSerializable = GenerateComplexSerializable(); - sentField3.Set(complexSerializable); - - m_marshaler.Marshal(m_writeBuffer, sentField1); - m_marshaler.Marshal(m_writeBuffer, sentField2); - m_marshaler.Marshal(m_writeBuffer, sentField3); - - PopulateReadBuffer(); - - AZ::DynamicSerializableField receivedField1; - AZ::DynamicSerializableField receivedField2; - AZ::DynamicSerializableField receivedField3; - - m_marshaler.Unmarshal(receivedField1, m_readBuffer); - m_marshaler.Unmarshal(receivedField2, m_readBuffer); - m_marshaler.Unmarshal(receivedField3, m_readBuffer); - - EXPECT_TRUE(sentField1.IsEqualTo(receivedField1, &m_serializeContext)); - EXPECT_TRUE(sentField2.IsEqualTo(receivedField2, &m_serializeContext)); - EXPECT_TRUE(sentField3.IsEqualTo(receivedField3, &m_serializeContext)); - - sentField1.DestroyData(&m_serializeContext); - sentField2.DestroyData(&m_serializeContext); - sentField3.DestroyData(&m_serializeContext); - - receivedField1.DestroyData(&m_serializeContext); - receivedField2.DestroyData(&m_serializeContext); - receivedField3.DestroyData(&m_serializeContext); - } - - TEST_F(DynamicSerializableFieldMarshalerTest, MultipleMarshalUnmarshalTest_EmptyFooEmptyBarEmptyComplexChainEquivalentValue) - { - AZ::DynamicSerializableField emptyField; - - AZ::DynamicSerializableField sentField1; - FooSerializable* fooSerializable = GenerateFooSerializable(); - sentField1.Set(fooSerializable); - - AZ::DynamicSerializableField sentField2; - BarSerializable* barSerializable = GenerateBarSerializable(); - sentField2.Set(barSerializable); - - AZ::DynamicSerializableField sentField3; - ComplexSerializable* complexSerializable = GenerateComplexSerializable(); - sentField3.Set(complexSerializable); - - m_marshaler.Marshal(m_writeBuffer, emptyField); - m_marshaler.Marshal(m_writeBuffer, sentField1); - m_marshaler.Marshal(m_writeBuffer, emptyField); - m_marshaler.Marshal(m_writeBuffer, sentField2); - m_marshaler.Marshal(m_writeBuffer, emptyField); - m_marshaler.Marshal(m_writeBuffer, sentField3); - m_marshaler.Marshal(m_writeBuffer, emptyField); - - PopulateReadBuffer(); - - AZ::DynamicSerializableField receivedEmptyField1; - AZ::DynamicSerializableField receivedField1; - AZ::DynamicSerializableField receivedEmptyField2; - AZ::DynamicSerializableField receivedField2; - AZ::DynamicSerializableField receivedEmptyField3; - AZ::DynamicSerializableField receivedField3; - AZ::DynamicSerializableField receivedEmptyField4; - - m_marshaler.Unmarshal(receivedEmptyField1, m_readBuffer); - m_marshaler.Unmarshal(receivedField1, m_readBuffer); - m_marshaler.Unmarshal(receivedEmptyField2, m_readBuffer); - m_marshaler.Unmarshal(receivedField2, m_readBuffer); - m_marshaler.Unmarshal(receivedEmptyField3, m_readBuffer); - m_marshaler.Unmarshal(receivedField3, m_readBuffer); - m_marshaler.Unmarshal(receivedEmptyField4, m_readBuffer); - - EXPECT_TRUE(emptyField.IsEqualTo(receivedEmptyField1, &m_serializeContext)); - EXPECT_TRUE(sentField1.IsEqualTo(receivedField1, &m_serializeContext)); - EXPECT_TRUE(emptyField.IsEqualTo(receivedEmptyField2, &m_serializeContext)); - EXPECT_TRUE(sentField2.IsEqualTo(receivedField2, &m_serializeContext)); - EXPECT_TRUE(emptyField.IsEqualTo(receivedEmptyField3, &m_serializeContext)); - EXPECT_TRUE(sentField3.IsEqualTo(receivedField3, &m_serializeContext)); - EXPECT_TRUE(emptyField.IsEqualTo(receivedEmptyField4, &m_serializeContext)); - - emptyField.DestroyData(&m_serializeContext); - sentField1.DestroyData(&m_serializeContext); - sentField2.DestroyData(&m_serializeContext); - sentField3.DestroyData(&m_serializeContext); - - receivedEmptyField1.DestroyData(&m_serializeContext); - receivedField1.DestroyData(&m_serializeContext); - receivedEmptyField2.DestroyData(&m_serializeContext); - receivedField2.DestroyData(&m_serializeContext); - receivedEmptyField3.DestroyData(&m_serializeContext); - receivedField3.DestroyData(&m_serializeContext); - receivedEmptyField4.DestroyData(&m_serializeContext); - } - - TEST_F(DynamicSerializableFieldMarshalerTest, MultipleMarshalUnmarshalTest_RandomChainEquivalentValue) - { - // Need to watch out for the size of the WriteBuffer. It's about ~2048 bytes, at worst case here, I'll write ~100 Bytes to the field per test object) - // So I need to keep this ~20 elements. - int numValues = 5 + m_random.GetRandom()%10; - AZStd::vector< AZ::DynamicSerializableField > sentValues; - AZStd::vector< AZ::DynamicSerializableField > receivedValues; - - sentValues.resize(numValues); - receivedValues.resize(numValues); - - for (auto& currentField : sentValues) - { - int value = m_random.GetRandom() % 4; - switch (value) - { - case 0: - { - currentField.Set(GenerateFooSerializable()); - } - break; - case 1: - { - currentField.Set(GenerateBarSerializable()); - } - break; - case 2: - { - currentField.Set(GenerateComplexSerializable()); - } - break; - case 3: - default: - // Empty field - break; - } - } - - for (auto& currentField : sentValues) - { - m_marshaler.Marshal(m_writeBuffer,currentField); - } - - PopulateReadBuffer(); - - for (auto& currentField : receivedValues) - { - m_marshaler.Unmarshal(currentField,m_readBuffer); - } - - for (unsigned int i=0; i < sentValues.size(); ++i) - { - AZ::DynamicSerializableField& sentField = sentValues[i]; - AZ::DynamicSerializableField& receivedField = receivedValues[i]; - - EXPECT_TRUE(sentField.IsEqualTo(receivedField, &m_serializeContext)); - - sentField.DestroyData(&m_serializeContext); - receivedField.DestroyData(&m_serializeContext); - } - } -} diff --git a/Code/Framework/Tests/Script/ScriptComponentTests.cpp b/Code/Framework/Tests/Script/ScriptComponentTests.cpp index a463192dd0..54c0d1dfa3 100644 --- a/Code/Framework/Tests/Script/ScriptComponentTests.cpp +++ b/Code/Framework/Tests/Script/ScriptComponentTests.cpp @@ -17,7 +17,6 @@ #include #include #include -#include #include "EntityTestbed.h" @@ -63,8 +62,6 @@ namespace UnitTest EBUS_EVENT_RESULT(m_behaviorContext, AZ::ComponentApplicationBus, GetBehaviorContext); EBUS_EVENT_RESULT(m_serializeContext, AZ::ComponentApplicationBus, GetSerializeContext); - NetBindable::Reflect(m_serializeContext); - AzToolsFramework::Components::ScriptEditorComponent::CreateDescriptor(); // descriptor is deleted by app AzToolsFramework::Components::ScriptEditorComponent::Reflect(m_serializeContext); @@ -228,63 +225,4 @@ namespace UnitTest EXPECT_NE(scriptComponent->GetScriptProperty("myNum"), nullptr); } - - TEST_F(ScriptComponentTest, UpdateNetSynchedProperty) - { - // Make sure altering a netsynched property in script only affects the single entity instance - const AZStd::string script = "local test = {\ - Properties = {\ - myNetSynchedNum = { default = 41, netSynched ={} },\ - doUpdate = { default = false },\ - },\ - }\ - function test:OnActivate()\ - self.tickBusHandler = TickBus.Connect(self, self.entityId)\ - end\ - function test:OnDeactivate()\ - self.tickBusHandler:Disconnect()\ - end\ - function test:OnTick(deltaTime, timePoint)\ - if self.Properties.doUpdate then\ - self.Properties.myNetSynchedNum = self.Properties.myNetSynchedNum+1\ - end\ - end\ - return test"; - - - const Data::Asset scriptAsset = CreateAndLoadScriptAsset(script); - Entity entity1, entity2; - ScriptComponent* scriptComponentInstance1 = BuildGameEntity(scriptAsset, entity1); - ScriptComponent* scriptComponentInstance2 = BuildGameEntity(scriptAsset, entity2); - - // Change the value of entity1's doUpdate to true. - // This way entity1's myNetSynchedNum should be incremented during OnTick - auto* doUpdateScriptProperty = azrtti_cast(scriptComponentInstance1->GetScriptProperty("doUpdate")); - ASSERT_NE(doUpdateScriptProperty, nullptr); - doUpdateScriptProperty->m_value = true; - - entity1.Init(); - entity2.Init(); - entity1.Activate(); - entity2.Activate(); - - // Tick in order to call OnTick in our lua script. - m_app.Tick(); - m_app.TickSystem(); - - // Ensure Entity1's myNetSynchedNum updated, but not Entity2 - auto* netSynchedProperty1 = scriptComponentInstance1->GetNetworkedScriptProperty("myNetSynchedNum"); - auto* netSynchedProperty2 = scriptComponentInstance2->GetNetworkedScriptProperty("myNetSynchedNum"); - ASSERT_NE(netSynchedProperty1, nullptr); - ASSERT_NE(netSynchedProperty2, nullptr); - - auto* num1 = azrtti_cast(netSynchedProperty1); - auto* num2 = azrtti_cast(netSynchedProperty2); - - ASSERT_NE(num1, nullptr); - ASSERT_NE(num2, nullptr); - - EXPECT_EQ(num1->m_value, 42); - EXPECT_EQ(num2->m_value, 41); - } } // namespace UnitTest diff --git a/Code/Framework/Tests/TransformComponent.cpp b/Code/Framework/Tests/TransformComponent.cpp index de172dc051..c2615f2a30 100644 --- a/Code/Framework/Tests/TransformComponent.cpp +++ b/Code/Framework/Tests/TransformComponent.cpp @@ -955,37 +955,6 @@ namespace UnitTest const char* m_objectStreamBuffer = nullptr; }; - class TransformComponentConvertFromV2 - : public TransformComponentVersionConverter - { - public: - TransformComponentConvertFromV2() - { - m_objectStreamBuffer = - R"DELIMITER( - - - - - - - - - - - - - - -)DELIMITER"; - } - }; - - TEST_F(TransformComponentConvertFromV2, IsStatic_False) - { - EXPECT_FALSE(m_transformInterface->IsStaticTransform()); - } - /////////////////////////////////////////////////////////////////////////// // TransformConfig diff --git a/Code/Framework/Tests/frameworktests_files.cmake b/Code/Framework/Tests/frameworktests_files.cmake index cf02b007b4..07990dc8fa 100644 --- a/Code/Framework/Tests/frameworktests_files.cmake +++ b/Code/Framework/Tests/frameworktests_files.cmake @@ -26,8 +26,6 @@ set(FILES GenAppDescriptors.cpp GenericComponentWrapperTest.cpp InstanceDataHierarchy.cpp - NetBinding.cpp - NetworkContext.cpp OctreePerformanceTests.cpp OctreeTests.cpp Slices.cpp @@ -35,12 +33,8 @@ set(FILES Script/ScriptEntityTests.cpp AssetCatalog.cpp AssetProcessorConnection.cpp - NetBindingSystemImplTest.cpp - NetBindingMocks.h NativeWindow.cpp TransformComponent.cpp - GridMocks.h - InterestManagerComponentTests.cpp SQLiteConnectionTests.cpp ProcessLaunchParseTests.cpp Application.cpp diff --git a/Code/LauncherUnified/Launcher.cpp b/Code/LauncherUnified/Launcher.cpp index 033169ac6d..1f29478399 100644 --- a/Code/LauncherUnified/Launcher.cpp +++ b/Code/LauncherUnified/Launcher.cpp @@ -573,11 +573,6 @@ namespace O3DELauncher systemInitParams.hWnd = mainInfo.m_window; systemInitParams.pPrintSync = mainInfo.m_printSink; - if (strstr(mainInfo.m_commandLine, "-norandom")) - { - systemInitParams.bNoRandom = true; - } - systemInitParams.bDedicatedServer = IsDedicatedServer(); if (IsDedicatedServer()) { diff --git a/Code/Sandbox/Editor/BackgroundScheduleManager.cpp b/Code/Sandbox/Editor/BackgroundScheduleManager.cpp deleted file mode 100644 index 23eee6daf4..0000000000 --- a/Code/Sandbox/Editor/BackgroundScheduleManager.cpp +++ /dev/null @@ -1,629 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "BackgroundScheduleManager.h" - -namespace BackgroundScheduleManager -{ - //----------------------------------------------------------------------------- - - CScheduleItem::CScheduleItem(const char* szName) - : m_name(szName) - , m_refCount(1) - , m_state(eScheduleItemState_Pending) - { - } - - CScheduleItem::~CScheduleItem() - { - CRY_ASSERT(m_refCount == 0); - - for (TWorkItems::const_iterator it = m_workItems.begin(); - it != m_workItems.end(); ++it) - { - (*it)->Release(); - } - } - - const char* CScheduleItem::GetDescription() const - { - return m_name.c_str(); - } - - EScheduleItemState CScheduleItem::GetState() const - { - return m_state; - } - - const float CScheduleItem::GetProgress() const - { - if (m_workItems.empty()) - { - return 1.0f; - } - else - { - float totalProgress = 0.0f; - - for (TWorkItems::const_iterator it = m_workItems.begin(); - it != m_workItems.end(); ++it) - { - totalProgress += (*it)->GetProgress(); - } - - return totalProgress / (float)m_workItems.size(); - } - } - - const uint32 CScheduleItem::GetNumWorkItems() const - { - return m_workItems.size(); - } - - IBackgroundScheduleItemWork* CScheduleItem::GetWorkItem(const uint32 index) const - { - return m_workItems[index]; - } - - void CScheduleItem::AddWorkItem(IBackgroundScheduleItemWork* pWork) - { - // cannot add new work items when item has finished or failed - if (m_state == eScheduleItemState_Failed || m_state == eScheduleItemState_Completed) - { - CryFatalError("Cannot add new work items when item has finished or failed"); - return; - } - - // add to the work list - if (m_state == eScheduleItemState_Processing) - { - m_addedWorkItems.push_back(pWork); - } - else - { - m_workItems.push_back(pWork); - } - } - - void CScheduleItem::AddRef() - { - CryInterlockedIncrement(&m_refCount); - } - - void CScheduleItem::Release() - { - const int nCount = CryInterlockedDecrement(&m_refCount); - assert(nCount >= 0); - if (nCount == 0) - { - delete this; - } - else if (nCount < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } - } - - void CScheduleItem::RequestStop() - { - if (m_state == eScheduleItemState_Pending) - { - // we can stop right away :) - m_state = eScheduleItemState_Failed; - } - else if (m_state == eScheduleItemState_Processing) - { - m_state = eScheduleItemState_Stopping; - - // signal all pending work to stop - uint32 curIndex = 0; - while (curIndex < m_processedWorkItems.size()) - { - IBackgroundScheduleItemWork* pWork = m_processedWorkItems[curIndex]; - if (pWork->OnStop()) - { - // if the work was stopped remove it from list - m_processedWorkItems.erase(m_processedWorkItems.begin() + curIndex); - continue; - } - else - { - // this work item cannot be stopped this frame - curIndex += 1; - } - } - - // if all pending work has been stopped we can assume the failed state - if (m_processedWorkItems.empty()) - { - m_state = eScheduleItemState_Failed; - } - } - } - - EScheduleWorkItemStatus CScheduleItem::Update() - { - EScheduleWorkItemStatus retStatus = eScheduleWorkItemStatus_NotFinished; - - switch (m_state) - { - // finial state - work failed - case eScheduleItemState_Failed: - { - retStatus = eScheduleWorkItemStatus_Failed; - break; - } - - // final state - work completed - case eScheduleItemState_Completed: - { - retStatus = eScheduleWorkItemStatus_Finished; - break; - } - - // first update, start all the work items - case eScheduleItemState_Pending: - { - // start all of the tasks - bool bHasFailedStarts = false; - for (TWorkItems::const_iterator it = m_workItems.begin(); - it != m_workItems.end(); ++it) - { - IBackgroundScheduleItemWork* pWork = (*it); - - if (pWork->OnStart()) - { - m_processedWorkItems.push_back(pWork); - } - else - { - bHasFailedStarts = true; - break; - } - } - - if (bHasFailedStarts) - { - m_state = eScheduleItemState_Stopping; - break; - } - else - { - m_state = eScheduleItemState_Processing; - /* FALLS THROUGHT TO PROCESSING STATE */ - } - } - - // work processing state - case eScheduleItemState_Processing: - { - // process new work items that were added while the schedule was created - if (!m_addedWorkItems.empty()) - { - for (TWorkItems::const_iterator it = m_addedWorkItems.begin(); - it != m_addedWorkItems.end(); ++it) - { - IBackgroundScheduleItemWork* pWork = (*it); - pWork->OnStart(); - m_processedWorkItems.push_back(pWork); - m_workItems.push_back(pWork); - } - - m_addedWorkItems.clear(); - } - - // update work items - bool bHasFailedItems = false; - TWorkItems completedItems; - for (TWorkItems::const_iterator it = m_processedWorkItems.begin(); - it != m_processedWorkItems.end(); ++it) - { - IBackgroundScheduleItemWork* pWork = (*it); - - // update given work item - const EScheduleWorkItemStatus status = pWork->OnUpdate(); - if (status == eScheduleWorkItemStatus_Finished) - { - completedItems.push_back(pWork); - continue; - } - - // item failed - we need to stop other tasks - if (status == eScheduleWorkItemStatus_Failed) - { - bHasFailedItems = true; - break; - } - } - - // cleanup completed items - for (TWorkItems::iterator it = completedItems.begin(); - it != completedItems.end(); ++it) - { - IBackgroundScheduleItemWork* pWork = (*it); - TWorkItems::iterator jt = std::find(m_processedWorkItems.begin(), m_processedWorkItems.end(), pWork); - m_processedWorkItems.erase(jt); - } - - if (!bHasFailedItems) - { - // all work has finished - if (m_processedWorkItems.empty()) - { - retStatus = eScheduleWorkItemStatus_Finished; - m_state = eScheduleItemState_Completed; - } - - break; - } - else - { - // some of the items failed - m_state = eScheduleItemState_Stopping; - /* FALL THROUGH TO STOPPING STATE */ - } - } - - // We are stopping failed work - case eScheduleItemState_Stopping: - { - uint32 curIndex = 0; - while (curIndex < m_processedWorkItems.size()) - { - IBackgroundScheduleItemWork* pWork = m_processedWorkItems[curIndex]; - if (pWork->OnStop()) - { - // if the work was stopped remove it from list - m_processedWorkItems.erase(m_processedWorkItems.begin() + curIndex); - continue; - } - else - { - // this work item cannot be stopped this frame - curIndex += 1; - } - } - - // if all pending work has been stopped we can assume the failed state - if (m_processedWorkItems.empty()) - { - m_state = eScheduleItemState_Failed; - return eScheduleWorkItemStatus_Failed; - } - } - } - - return retStatus; - } - - //----------------------------------------------------------------------------- - - CSchedule::CSchedule(const char* szName) - : m_name(szName) - , m_refCount(1) - , m_bCanceled(false) - , m_currentItem(0) - , m_state(eScheduleState_Pending) - { - } - - CSchedule::~CSchedule() - { - CRY_ASSERT(m_refCount == 0); - - for (TItems::const_iterator it = m_items.begin(); - it != m_items.end(); ++it) - { - CScheduleItem* pItem = *it; - SAFE_RELEASE(pItem); - } - - m_items.clear(); - } - - const char* CSchedule::GetDescription() const - { - return m_name.c_str(); - } - - float CSchedule::GetProgress() const - { - if (m_currentItem >= m_items.size()) - { - return 1.0f; - } - else - { - const float itemProgress = 1.0f / (float)(m_items.size()); - const IBackgroundScheduleItem* pItem = m_items[m_currentItem]; - return (m_currentItem + pItem->GetProgress()) * itemProgress; - } - } - - IBackgroundScheduleItem* CSchedule::GetProcessedItem() const - { - if (m_currentItem >= m_items.size()) - { - return NULL; - } - else - { - IBackgroundScheduleItem* pItem = m_items[m_currentItem]; - return pItem; - } - } - - const uint32 CSchedule::GetNumItems() const - { - return m_items.size(); - } - - IBackgroundScheduleItem* CSchedule::GetItem(const uint32 index) const - { - return m_items[index]; - } - - EScheduleState CSchedule::GetState() const - { - return m_state; - } - - void CSchedule::Cancel() - { - m_bCanceled = true; - } - - bool CSchedule::IsCanceled() const - { - return m_bCanceled; - } - - void CSchedule::AddItem(IBackgroundScheduleItem* pItem) - { - if (NULL == pItem) - { - return; - } - - // we can add items only in the "pending" state - if (pItem->GetState() != eScheduleItemState_Pending) - { - CryFatalError("Schedule items can be added to schedule only before their work starts"); - return; - } - - // item has no jobs, do not add - if (pItem->GetNumWorkItems() == 0) - { - return; - } - - m_items.push_back(static_cast(pItem)); - pItem->AddRef(); - } - - void CSchedule::AddRef() - { - CryInterlockedIncrement(&m_refCount); - } - - void CSchedule::Release() - { - const int nCount = CryInterlockedDecrement(&m_refCount); - assert(nCount >= 0); - if (nCount == 0) - { - delete this; - } - else if (nCount < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } - } - - EScheduleWorkItemStatus CSchedule::Update() - { - EScheduleWorkItemStatus retStatus = eScheduleWorkItemStatus_NotFinished; - - // we have a cancel request - if (m_bCanceled) - { - CryLog("Schedule '%s' was canceled", GetDescription()); - - if (m_state == eScheduleState_Processing && m_currentItem < m_items.size()) - { - // stop the current item - CScheduleItem* pItem = m_items[m_currentItem]; - pItem->RequestStop(); - m_state = eSccheduleState_Stopping; - } - else if (m_state != eScheduleState_Completed) - { - m_state = eScheduleState_Failed; - return eScheduleWorkItemStatus_Failed; - } - } - - // process internal state machine - switch (m_state) - { - // final state - work failed - case eScheduleState_Failed: - { - retStatus = eScheduleWorkItemStatus_Failed; - break; - } - - // final state - work completed - case eScheduleState_Completed: - { - retStatus = eScheduleWorkItemStatus_Finished; - break; - } - - // stopping current task - case eSccheduleState_Stopping: - { - if (m_currentItem < m_items.size()) - { - CScheduleItem* pItem = m_items[m_currentItem]; - if (pItem->Update() != eScheduleWorkItemStatus_NotFinished) - { - // task was finally stopped - m_state = eScheduleState_Failed; - retStatus = eScheduleWorkItemStatus_Failed; - } - } - - break; - } - - // first update, switch to processing - case eScheduleState_Pending: - { - m_state = eScheduleState_Processing; - m_currentItem = 0; - /* FALLS THROUGHT */ - } - - // if we were in the processing phase inform the current schedule item to stop all it's work - case eScheduleState_Processing: - { - // update schedule items - while (m_currentItem < m_items.size()) - { - CScheduleItem* pItem = m_items[m_currentItem]; - - const EScheduleWorkItemStatus itemStatus = pItem->Update(); - if (itemStatus == eScheduleWorkItemStatus_Finished) - { - m_currentItem += 1; - continue; - } - else if (itemStatus == eScheduleWorkItemStatus_Failed) - { - m_state = eScheduleState_Failed; - retStatus = eScheduleWorkItemStatus_Failed; - gEnv->pLog->LogWarning("Schedule '%s' failed on item '%s'.", GetDescription(), pItem->GetDescription()); - } - - break; - } - - // all items updated - if (m_currentItem >= m_items.size()) - { - // empty schedule, complete in one tick - m_state = eScheduleState_Completed; - retStatus = eScheduleWorkItemStatus_Finished; - CryLog("Schedule '%s' completed", GetDescription()); - } - - break; - } - } - - return retStatus; - } - - //----------------------------------------------------------------------------- - - CScheduleManager::CScheduleManager() - { - GetIEditor()->RegisterNotifyListener(this); - } - - CScheduleManager::~CScheduleManager() - { - GetIEditor()->UnregisterNotifyListener(this); - - for (TSchedules::const_iterator it = m_schedules.begin(); - it != m_schedules.end(); ++it) - { - CSchedule* pSchedule = *it; - SAFE_RELEASE(pSchedule); - } - - m_schedules.clear(); - } - - IBackgroundSchedule* CScheduleManager::CreateSchedule(const char* szName) - { - return new CSchedule(szName); - } - - IBackgroundScheduleItem* CScheduleManager::CreateScheduleItem(const char* szName) - { - return new CScheduleItem(szName); - } - - void CScheduleManager::SubmitSchedule(IBackgroundSchedule* pSchedule) - { - if (NULL != pSchedule) - { - if (pSchedule->GetState() != eScheduleState_Pending) - { - CryFatalError("Only schedules with pending state can be submitted"); - return; - } - - pSchedule->AddRef(); - m_schedules.push_back(static_cast(pSchedule)); - } - } - - const uint32 CScheduleManager::GetNumSchedules() const - { - return m_schedules.size(); - } - - IBackgroundSchedule* CScheduleManager::GetSchedule(const uint32 index) const - { - return m_schedules[index]; - } - - void CScheduleManager::Update() - { - while (!m_schedules.empty()) - { - CSchedule* pSchedule = m_schedules[0]; - - const EScheduleWorkItemStatus status = pSchedule->Update(); - if (status == eScheduleWorkItemStatus_NotFinished) - { - // we need more work next frame - break; - } - - // schedule has finished, remove current reference - m_schedules.erase(m_schedules.begin()); - SAFE_RELEASE(pSchedule); - } - } - - void CScheduleManager::OnEditorNotifyEvent(EEditorNotifyEvent ev) - { - switch (ev) - { - case eNotify_OnQuit: - GetIEditor()->UnregisterNotifyListener(this); - break; - } - } - - //----------------------------------------------------------------------------- -} // BackgroundScheduleManager diff --git a/Code/Sandbox/Editor/BackgroundScheduleManager.h b/Code/Sandbox/Editor/BackgroundScheduleManager.h deleted file mode 100644 index 4deeaba64f..0000000000 --- a/Code/Sandbox/Editor/BackgroundScheduleManager.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_BACKGROUNDSCHEDULEMANAGER_H -#define CRYINCLUDE_EDITOR_BACKGROUNDSCHEDULEMANAGER_H -#pragma once - -#include "Include/IBackgroundScheduleManager.h" - -namespace BackgroundScheduleManager -{ - class CScheduleItem - : public IBackgroundScheduleItem - { - private: - std::string m_name; - volatile int m_refCount; - - EScheduleItemState m_state; - - typedef std::vector TWorkItems; - TWorkItems m_workItems; - TWorkItems m_addedWorkItems; - TWorkItems m_processedWorkItems; - - public: - CScheduleItem(const char* szName); - virtual ~CScheduleItem(); - - // IBackgroundScheduleItem interface - virtual const char* GetDescription() const; - virtual EScheduleItemState GetState() const; - virtual const float GetProgress() const; - virtual const uint32 GetNumWorkItems() const; - virtual IBackgroundScheduleItemWork* GetWorkItem(const uint32 index) const; - virtual void AddWorkItem(IBackgroundScheduleItemWork* pWork); - virtual void AddRef(); - virtual void Release(); - - // Update schedule item - EScheduleWorkItemStatus Update(); - - // Request to stop work in this item - void RequestStop(); - }; - - class CSchedule - : public IBackgroundSchedule - { - private: - std::string m_name; - volatile int m_refCount; - bool m_bCanceled; - - EScheduleState m_state; - - typedef std::vector TItems; - TItems m_items; - - uint32 m_currentItem; - - public: - CSchedule(const char* szName); - virtual ~CSchedule(); - - // IBackgroundSchedule interface - virtual const char* GetDescription() const; - virtual float GetProgress() const; - virtual IBackgroundScheduleItem* GetProcessedItem() const; - virtual const uint32 GetNumItems() const; - virtual IBackgroundScheduleItem* GetItem(const uint32 index) const; - virtual EScheduleState GetState() const; - virtual void Cancel(); - virtual bool IsCanceled() const; - virtual void AddItem(IBackgroundScheduleItem* pItem); - virtual void AddRef(); - virtual void Release(); - - // Update schedule item - EScheduleWorkItemStatus Update(); - }; - - class CScheduleManager - : public IBackgroundScheduleManager - , public IEditorNotifyListener - { - private: - typedef std::vector TSchedules; - TSchedules m_schedules; - - public: - CScheduleManager(); - virtual ~CScheduleManager(); - - // IBackgroundScheduleManager interface - virtual IBackgroundSchedule* CreateSchedule(const char* szName); - virtual IBackgroundScheduleItem* CreateScheduleItem(const char* szName); - virtual void SubmitSchedule(IBackgroundSchedule* pSchedule); - virtual const uint32 GetNumSchedules() const; - virtual IBackgroundSchedule* GetSchedule(const uint32 index) const; - virtual void Update(); - - // IEditorNotifyListener interface implementation - virtual void OnEditorNotifyEvent(EEditorNotifyEvent ev) override; - }; -} -#endif // CRYINCLUDE_EDITOR_BACKGROUNDSCHEDULEMANAGER_H diff --git a/Code/Sandbox/Editor/BackgroundTaskManager.cpp b/Code/Sandbox/Editor/BackgroundTaskManager.cpp deleted file mode 100644 index c05e709fd0..0000000000 --- a/Code/Sandbox/Editor/BackgroundTaskManager.cpp +++ /dev/null @@ -1,410 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "BackgroundTaskManager.h" - -namespace BackgroundTaskManager -{ - //----------------------------------------------------------------------------- - - CTaskManager::CThread::CThread(class CTaskManager* pManager, CQueue* pQueue) - : m_pManager(pManager) - , m_pQueue(pQueue) - { - start(); - } - - CTaskManager::CThread::~CThread() - { - } - - void CTaskManager::CThread::WaitForThread() - { - wait(); - } - - void CTaskManager::CThread::run() - { - CryThreadSetName(-1, "BackgroundTaskThread"); - - while (!m_pManager->IsStopped()) - { - STaskHandle taskHandle; - - // This blocks on Semaphore waiting for task from queue - m_pQueue->PopTask(taskHandle); - - // Should not happen but it's a stupid way to crash :) - if (NULL == taskHandle.pTask) - { - continue; - } - - if (taskHandle.pTask->IsCanceled()) - { - // Task was canceled before we got here - m_pManager->AddCompletedTask(taskHandle, eTaskResult_Canceled); - } - else - { - const ETaskResult state = taskHandle.pTask->Work(); - - if (state == eTaskResult_Resume) - { - // Put it back into queue, so more important task can take over. - m_pManager->AddTask(taskHandle); - } - else - { - // Finish task - m_pManager->AddCompletedTask(taskHandle, state); - } - } - } - } - - //----------------------------------------------------------------------------- - - CTaskManager::CQueue::CQueue() - : m_semaphore(INT_MAX, 0) // no good maximum value, assume worst case - { - } - - void CTaskManager::CQueue::AddTask(const STaskHandle& taskHandle) - { - { - CryAutoLock lock(m_lock); - - // TODO: use heap? - m_pendingTasks.insert(m_pendingTasks.begin(), taskHandle); - std::stable_sort(m_pendingTasks.begin(), m_pendingTasks.end()); - } - - taskHandle.pTask->SetState(eTaskState_Pending); - - // release internal semaphore so threads can pick up the work - m_semaphore.Release(); - } - - void CTaskManager::CQueue::PopTask(STaskHandle& outTaskHandle) - { - // wait for job - m_semaphore.Acquire(); - - { - CryAutoLock lock(m_lock); - - if (m_pendingTasks.empty()) - { - outTaskHandle.pTask = NULL; - } - else - { - outTaskHandle = m_pendingTasks.back(); - outTaskHandle.pTask->SetState(eTaskState_Working); - m_pendingTasks.pop_back(); - } - } - } - - void CTaskManager::CQueue::ReleaseSemaphore() - { - m_semaphore.Release(); - } - - void CTaskManager::CQueue::Clear() - { - CryAutoLock lock(m_lock); - for (uint i = 0; i < m_pendingTasks.size(); ++i) - { - m_pendingTasks[i].pTask->Release(); - } - - m_pendingTasks.clear(); - } - - //----------------------------------------------------------------------------- - - CTaskManager::CTaskManager() - : m_bStop(false) - , m_nextTaskID(1) - , m_listeners(1) - { - GetIEditor()->RegisterNotifyListener(this); - } - - CTaskManager::~CTaskManager() - { - if (!m_bStop) - { - Stop(); - } - } - - void CTaskManager::Start(const uint32 threadCount /*=kDefaultThreadCount*/) - { - m_bStop = false; - - if (m_pThreads.empty()) - { - // Always create one IO thread - { - CThread* pThread = new CThread(this, &m_pendingTasks[ eTaskThreadMask_IO ]); - m_pThreads.push_back(pThread); - } - - // We also need at least one generic thread - const uint32 numGenericThreads = max(threadCount, 1); - for (uint32 i = 0; i < numGenericThreads; ++i) - { - CThread* pThread = new CThread(this, &m_pendingTasks[ eTaskThreadMask_Any ]); - m_pThreads.push_back(pThread); - } - } - } - - void CTaskManager::StartScheduledTasks() - { - CryAutoLock lock(m_tasksLock); - - if (!m_scheduledTasks.empty()) - { - const unsigned int time = GetTickCount(); - while (!m_scheduledTasks.empty()) - { - const int delta = (int)(time - m_scheduledTasks[0].time); - if (delta > 0) - { - // the soonest task on the list is still in the future, no point in looking at the next entries in the list - break; - } - - // promote the scheduled task to be a full task - AddTask(m_scheduledTasks[0].handle); - - // We held a reference to the task on list, release it - m_scheduledTasks[0].handle.pTask->Release(); - - m_scheduledTasks.erase(m_scheduledTasks.begin()); - } - } - } - - void CTaskManager::Stop() - { - if (!m_bStop) - { - m_bStop = true; - GetIEditor()->UnregisterNotifyListener(this); - - // clear queues - no new tasks will be processed - for (uint32 i = 0; i < eTaskThreadMask_COUNT; ++i) - { - m_pendingTasks[i].Clear(); - } - - // kick all the threads to allow them to quit - for (uint32 j = 0; j < m_pThreads.size(); ++j) - { - for (uint32 i = 0; i < eTaskThreadMask_COUNT; ++i) - { - m_pendingTasks[i].ReleaseSemaphore(); - } - } - - // Stop threads - for (TWorkerThreads::iterator it = m_pThreads.begin(); - it != m_pThreads.end(); ++it) - { - (*it)->WaitForThread(); - delete *it; - } - - m_pThreads.clear(); - } - } - - void CTaskManager::AddListener(IBackgroundTaskManagerListener* pListener, const char* name) - { - m_listeners.Add(pListener, name); - } - - void CTaskManager::RemoveListener(IBackgroundTaskManagerListener* pListener) - { - m_listeners.Remove(pListener); - } - - void CTaskManager::AddTask(IBackgroundTask* pTask, ETaskPriority priority, ETaskThreadMask threadMask) - { - MAKE_SURE(pTask != 0, return ); - - // keep an extra reference to the task in the manager - pTask->AddRef(); - - STaskHandle handle; - handle.id = CryInterlockedIncrement(&m_nextTaskID); - handle.priority = priority; - handle.threadMask = threadMask; - handle.pTask = pTask; - - AddTask(handle); - - for (TListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) - { - notifier->OnBackgroundTaskAdded(pTask->Description()); - } - } - - void CTaskManager::ScheduleTask(IBackgroundTask* pTask, ETaskPriority priority, int delayMilliseconds, ETaskThreadMask threadMask) - { - MAKE_SURE(delayMilliseconds >= 0, return ); - MAKE_SURE(pTask != 0, return ); - - // keep an extra reference to the task in the manager - pTask->AddRef(); - - SScheduledTask task; - task.time = GetTickCount() + delayMilliseconds; - task.handle.pTask = pTask; - task.handle.id = CryInterlockedIncrement(&m_nextTaskID); - task.handle.threadMask = threadMask; - task.handle.priority = priority; - - { - CryAutoLock lock(m_tasksLock); - m_scheduledTasks.push_back(task); - } - - for (TListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) - { - notifier->OnBackgroundTaskAdded(pTask->Description()); - } - } - - void CTaskManager::AddTask(const STaskHandle& handle) - { - MAKE_SURE(handle.pTask != 0, return ); - MAKE_SURE(handle.id != 0, return ); - - // add task to appropriate queue (every thread mask has it's own queue) - m_pendingTasks[handle.threadMask].AddTask(handle); - } - - void CTaskManager::AddCompletedTask(const STaskHandle& handle, ETaskResult resultState) - { - CryAutoLock lock(m_tasksLock); - - CRY_ASSERT(handle.pTask->GetState() == eTaskState_Working); - CRY_ASSERT(resultState != eTaskResult_Resume); - - // Update task state - switch (resultState) - { - case eTaskResult_Canceled: - { - handle.pTask->SetState(eTaskState_Canceled); - break; - } - - case eTaskResult_Completed: - { - handle.pTask->SetState(eTaskState_Completed); - break; - } - - case eTaskResult_Failed: - { - handle.pTask->SetState(eTaskState_Failed); - break; - } - } - - // add to the list of completed tasks (for calling the Finalize) - // TODO: some of the tasks do not require Finalize() and they could be released here instead of the main thread - SCompletedTask info; - info.pTask = handle.pTask; - info.id = handle.id; - info.state = resultState; - m_completedTasks.push_back(info); - } - - void CTaskManager::Update() - { - std::vector completedTasks; - { - CryAutoLock lock(m_tasksLock); - m_completedTasks.swap(completedTasks); - } - - // call finalize for the completed tasks - for (size_t i = 0; i < completedTasks.size(); ++i) - { - SCompletedTask& handle = completedTasks[i]; - - if (NULL != handle.pTask) - { - string description = handle.pTask->Description(); // copy string as the description is used after pTask is destroyed - - if (handle.state == eTaskResult_Completed) - { - if (description && description[0] != '\0') - { - gEnv->pLog->Log("Task Completed: %s", description.c_str()); - } - } - else if (handle.state == eTaskResult_Failed) - { - if (description && description[0] != '\0' && !handle.pTask->FailReported()) - { - gEnv->pLog->LogError("Task Failed: %s ", description.c_str()); - - const char* errorMessage = handle.pTask->ErrorMessage(); - if (errorMessage && errorMessage[0] != '\0') - { - gEnv->pLog->LogError("\tReason: [%s]", errorMessage); - } - } - } - - handle.pTask->Finalize(); - - // release the internal (task manager) reference. - // Tthis is usually the last reference to the task so it gets deleted here. - handle.pTask->Release(); - - for (TListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) - { - notifier->OnBackgroundTaskCompleted(handle.state, description.c_str()); - } - } - } - } - - void CTaskManager::OnEditorNotifyEvent(EEditorNotifyEvent ev) - { - switch (ev) - { - case eNotify_OnInit: - Start(); - break; - case eNotify_OnIdleUpdate: - Update(); - break; - case eNotify_OnQuit: - Stop(); - break; - } - } -} diff --git a/Code/Sandbox/Editor/BackgroundTaskManager.h b/Code/Sandbox/Editor/BackgroundTaskManager.h deleted file mode 100644 index b440c66f1a..0000000000 --- a/Code/Sandbox/Editor/BackgroundTaskManager.h +++ /dev/null @@ -1,161 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_BACKGROUNDTASKMANAGER_H -#define CRYINCLUDE_EDITOR_BACKGROUNDTASKMANAGER_H -#pragma once - -#include "Include/IBackgroundTaskManager.h" -#include "CryListenerSet.h" - -#include - -namespace BackgroundTaskManager -{ - typedef int TTaskID; - - struct STaskHandle - { - ETaskPriority priority; - ETaskThreadMask threadMask; - TTaskID id; - IBackgroundTask* pTask; - - bool operator<(const STaskHandle& rhs) const - { - if (priority < rhs.priority) - { - return true; - } - if (priority > rhs.priority) - { - return false; - } - return id < rhs.id; - } - }; - - struct SCompletedTask - { - ETaskResult state; - TTaskID id; - ETaskThreadMask threadMask; - IBackgroundTask* pTask; - }; - - struct SScheduledTask - { - unsigned int time; - STaskHandle handle; - }; - - class CTaskManager - : public IBackgroundTaskManager - , public IEditorNotifyListener - { - public: - CTaskManager(); - ~CTaskManager(); - - // IBackgroundTaskManager interface implementation - virtual void AddTask(IBackgroundTask* pTask, ETaskPriority priority, ETaskThreadMask threadMask) override; - virtual void ScheduleTask(IBackgroundTask* pTask, ETaskPriority priority, int delayMilliseconds, ETaskThreadMask threadMask) override; - void AddListener(IBackgroundTaskManagerListener* pListener, const char* name) override; - void RemoveListener(IBackgroundTaskManagerListener* pListener) override; - - private: - // IEditorNotifyListener interface implementation - virtual void OnEditorNotifyEvent(EEditorNotifyEvent ev) override; - - void Start(const uint32 threadCount = kDefaultThreadCount); - void Stop(); - void StartScheduledTasks(); - void AddTask(const STaskHandle& outTask); - void AddCompletedTask(const STaskHandle& outTask, ETaskResult resultState); - void Update(); - - inline bool IsStopped() const - { - return m_bStop; - } - - private: - // Internal queue (per thread mask) - class CQueue - { - public: - CQueue(); - - // Add task to list - void AddTask(const STaskHandle& taskHandle); - - // Pop task from list - void PopTask(STaskHandle& outTaskHandle); - - // Release thread semaphore without adding a task - void ReleaseSemaphore(); - - // Remove all pending tasks - void Clear(); - - private: - CrySemaphore m_semaphore; - std::vector m_pendingTasks; - CryMutex m_lock; - }; - - // Worker thread class implementation - class CThread : public QThread - { - public: - CThread(CTaskManager* pManager, CQueue* pQueue); - ~CThread(); - - void WaitForThread(); - - private: - void run() override; - - private: - CTaskManager* m_pManager; - CQueue* m_pQueue; - }; - - private: - static const uint32 kMaxThreadCloseWaitTime = 10000; // ms - static const uint32 kDefaultThreadCount = 4; // good enough for LiveCreate (main user right now), do not set to less than 2 - - CQueue m_pendingTasks[ eTaskThreadMask_COUNT ]; - - // Task scheduled for execution in the future - std::vector m_scheduledTasks; - - // Completed tasks (waiting for the "finalize" call) - std::vector m_completedTasks; - - volatile TTaskID m_nextTaskID; - - typedef std::vector TWorkerThreads; - TWorkerThreads m_pThreads; - - CryMutex m_tasksLock; - bool m_bStop; - - typedef CListenerSet TListeners; - TListeners m_listeners; - }; -} - -//----------------------------------------------------------------------------- - -#endif // CRYINCLUDE_EDITOR_BACKGROUNDTASKMANAGER_H diff --git a/Code/Sandbox/Editor/CMakeLists.txt b/Code/Sandbox/Editor/CMakeLists.txt index 726f7ac2c7..7d89717391 100644 --- a/Code/Sandbox/Editor/CMakeLists.txt +++ b/Code/Sandbox/Editor/CMakeLists.txt @@ -112,7 +112,6 @@ ly_add_target( 3rdParty::zlib 3rdParty::AWSNativeSDK::STS Legacy::CryCommon - Legacy::CryCommon.EngineSettings.Static Legacy::EditorCommon AZ::AzCore AZ::AzToolsFramework diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index 6e33d32c6e..0bbc48d5f9 100644 --- a/Code/Sandbox/Editor/CryEdit.cpp +++ b/Code/Sandbox/Editor/CryEdit.cpp @@ -85,7 +85,6 @@ AZ_POP_DISABLE_WARNING // Editor #include "Settings.h" -#include "Include/IBackgroundScheduleManager.h" #include "GameExporter.h" #include "GameResourcesExporter.h" @@ -2314,15 +2313,6 @@ int CCryEditApp::IdleProcessing(bool bBackgroundUpdate) #endif } - // process the work schedule - regardless if the app is active or not - GetIEditor()->GetBackgroundScheduleManager()->Update(); - - // if there are active schedules keep updating the application - if (GetIEditor()->GetBackgroundScheduleManager()->GetNumSchedules() > 0) - { - bActive = true; - } - m_bPrevActive = bActive; AZStd::chrono::system_clock::time_point now = AZStd::chrono::system_clock::now(); diff --git a/Code/Sandbox/Editor/GameEngine.cpp b/Code/Sandbox/Editor/GameEngine.cpp index 1c91ce58aa..2112d00d64 100644 --- a/Code/Sandbox/Editor/GameEngine.cpp +++ b/Code/Sandbox/Editor/GameEngine.cpp @@ -420,7 +420,6 @@ AZ::Outcome CGameEngine::Init( #else sip.hWnd = hwndForInputSystem; #endif - sip.hWndForInputSystem = hwndForInputSystem; sip.pLogCallback = &m_logFile; sip.sLogFileName = "@log@/Editor.log"; @@ -503,7 +502,6 @@ AZ::Outcome CGameEngine::Init( bool CGameEngine::InitGame(const char*) { - // in editor we do it later, bExecuteCommandLine was set to false m_pISystem->ExecuteCommandLine(); return true; @@ -608,8 +606,6 @@ void CGameEngine::SwitchToInGame() GetIEditor()->Notify(eNotify_OnBeginGameMode); - m_pISystem->SetThreadState(ESubsys_Physics, false); - m_pISystem->GetIMovieSystem()->EnablePhysicsEvents(true); m_bInGameMode = true; @@ -646,8 +642,6 @@ void CGameEngine::SwitchToInEditor() } m_pISystem->GetIMovieSystem()->Reset(false, false); - m_pISystem->SetThreadState(ESubsys_Physics, false); - CViewport* pGameViewport = GetIEditor()->GetViewManager()->GetGameViewport(); m_pISystem->GetIMovieSystem()->EnablePhysicsEvents(m_bSimulationMode); @@ -791,8 +785,6 @@ void CGameEngine::SetSimulationMode(bool enabled, bool bOnlyPhysics) // Enables engine to know about simulation mode. gEnv->SetIsEditorSimulationMode(enabled); - m_pISystem->SetThreadState(ESubsys_Physics, false); - if (m_bSimulationMode) { // [Anton] the order of the next 3 calls changed, since, EVENT_INGAME loads physics state (if any), @@ -903,19 +895,6 @@ void CGameEngine::Update() // [marco] check current sound and vis areas for music etc. // but if in game mode, 'cos is already done in the above call to game->update() unsigned int updateFlags = ESYSUPDATE_EDITOR; - - if (!m_bSimulationMode) - { - updateFlags |= ESYSUPDATE_IGNORE_PHYSICS; - } - - bool bUpdateAIPhysics = GetSimulationMode(); - - if (bUpdateAIPhysics) - { - updateFlags |= ESYSUPDATE_EDITOR_AI_PHYSICS; - } - GetIEditor()->GetAnimation()->Update(); GetIEditor()->GetSystem()->UpdatePreTickBus(updateFlags); componentApplication->Tick(gEnv->pTimer->GetFrameTime(ITimer::ETIMER_GAME)); diff --git a/Code/Sandbox/Editor/IEditor.h b/Code/Sandbox/Editor/IEditor.h index 62672a6505..af98158037 100644 --- a/Code/Sandbox/Editor/IEditor.h +++ b/Code/Sandbox/Editor/IEditor.h @@ -550,7 +550,6 @@ struct IEditor virtual class CViewManager* GetViewManager() = 0; virtual class CViewport* GetActiveView() = 0; virtual void SetActiveView(CViewport* viewport) = 0; - virtual struct IBackgroundTaskManager* GetBackgroundTaskManager() = 0; virtual struct IEditorFileMonitor* GetFileMonitor() = 0; // These are needed for Qt integration: @@ -720,7 +719,6 @@ struct IEditor virtual ESystemConfigPlatform GetEditorConfigPlatform() const = 0; virtual void ReloadTemplates() = 0; virtual IResourceSelectorHost* GetResourceSelectorHost() = 0; - virtual struct IBackgroundScheduleManager* GetBackgroundScheduleManager() = 0; virtual void ShowStatusText(bool bEnable) = 0; // Provides a way to extend the context menu of an object. The function gets called every time the menu is opened. diff --git a/Code/Sandbox/Editor/IEditorImpl.cpp b/Code/Sandbox/Editor/IEditorImpl.cpp index fb9b737733..380fc80e66 100644 --- a/Code/Sandbox/Editor/IEditorImpl.cpp +++ b/Code/Sandbox/Editor/IEditorImpl.cpp @@ -66,8 +66,6 @@ AZ_POP_DISABLE_WARNING #include "Objects/SelectionGroup.h" #include "Objects/ObjectManager.h" -#include "BackgroundTaskManager.h" -#include "BackgroundScheduleManager.h" #include "EditorFileMonitor.h" #include "MainStatusBar.h" @@ -176,8 +174,6 @@ CEditorImpl::CEditorImpl() regCtx.pCommandManager = m_pCommandManager; regCtx.pClassFactory = m_pClassFactory; m_pEditorFileMonitor.reset(new CEditorFileMonitor()); - m_pBackgroundTaskManager.reset(new BackgroundTaskManager::CTaskManager); - m_pBackgroundScheduleManager.reset(new BackgroundScheduleManager::CScheduleManager); m_pUIEnumsDatabase = new CUIEnumsDatabase; m_pDisplaySettings = new CDisplaySettings; m_pDisplaySettings->LoadRegistry(); @@ -843,16 +839,6 @@ IIconManager* CEditorImpl::GetIconManager() return m_pIconManager; } -IBackgroundTaskManager* CEditorImpl::GetBackgroundTaskManager() -{ - return m_pBackgroundTaskManager.get(); -} - -IBackgroundScheduleManager* CEditorImpl::GetBackgroundScheduleManager() -{ - return m_pBackgroundScheduleManager.get(); -} - IEditorFileMonitor* CEditorImpl::GetFileMonitor() { return m_pEditorFileMonitor.get(); diff --git a/Code/Sandbox/Editor/IEditorImpl.h b/Code/Sandbox/Editor/IEditorImpl.h index 7ad97d79e5..0ebd02b5fd 100644 --- a/Code/Sandbox/Editor/IEditorImpl.h +++ b/Code/Sandbox/Editor/IEditorImpl.h @@ -43,15 +43,12 @@ class CGameEngine; class CExportManager; class CErrorsDlg; class CIconManager; -class CBackgroundTaskManager; class CTrackViewSequenceManager; class CEditorFileMonitor; class AzAssetWindow; class AzAssetBrowserRequestHandler; class AssetEditorRequestsHandler; class CAlembicCompiler; -struct IBackgroundTaskManager; -struct IBackgroundScheduleManager; struct IEditorFileMonitor; class CVegetationMap; @@ -61,16 +58,6 @@ namespace Editor class EditorQtApplication; } -namespace BackgroundScheduleManager -{ - class CScheduleManager; -} - -namespace BackgroundTaskManager -{ - class CTaskManager; -} - namespace WinWidget { class WinWidgetManager; @@ -179,8 +166,6 @@ public: IDataBaseManager* GetDBItemManager(EDataBaseItemType itemType); CMusicManager* GetMusicManager() { return m_pMusicManager; }; - IBackgroundTaskManager* GetBackgroundTaskManager() override; - IBackgroundScheduleManager* GetBackgroundScheduleManager() override; IEditorFileMonitor* GetFileMonitor() override; void RegisterEventLoopHook(IEventLoopHook* pHook) override; void UnregisterEventLoopHook(IEventLoopHook* pHook) override; @@ -394,8 +379,6 @@ protected: //! Export manager for exporting objects and a terrain from the game to DCC tools CExportManager* m_pExportManager; - std::unique_ptr m_pBackgroundTaskManager; - std::unique_ptr m_pBackgroundScheduleManager; std::unique_ptr m_pEditorFileMonitor; std::unique_ptr m_pResourceSelectorHost; QString m_selectFileBuffer; diff --git a/Code/Sandbox/Editor/Include/IBackgroundScheduleManager.h b/Code/Sandbox/Editor/Include/IBackgroundScheduleManager.h deleted file mode 100644 index bfa9eb6333..0000000000 --- a/Code/Sandbox/Editor/Include/IBackgroundScheduleManager.h +++ /dev/null @@ -1,207 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// -// IBackgroundScheduleManager manages schedule of group of larger operations that should be run in sequence -// -// Schedules are derived from IBackgroundSchedule and consist of a list of IBackgroundScheduleItems. -// Each schedule item is executed IN ORDER for the previous item to complete first. -// Each IBackgroundScheduleItems consists of list of user defined work via IBackgroundScheduleItemsWork classes. -// Each schedule item work is executed IN PARALEL (they are all started when the item starts). -// -// Whenever a work item fails to complete the other work items are stopped, the schedule item is marked as "failed" -// and so is the whole schedule. -// -// All logic is performed on the main thread although schedule items are free to use threads. -// It is recommended to use IBackgroundTaskManager for dispatching a task list for every schedule work item. -// -// All objects in the schedule system are reference counted. -// - -// State of the whole schedule - -#ifndef CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDSCHEDULEMANAGER_H -#define CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDSCHEDULEMANAGER_H -#pragma once -enum EScheduleState -{ - // Item has not started yet but is on the list - eScheduleState_Pending, - - // We are processing this item - eScheduleState_Processing, - - // We are stopping the schedule - eSccheduleState_Stopping, - - // Schedule item has failed - eScheduleState_Failed, - - // Schedule item was canceled - eScheduleState_Canceled, - - // Schedule item has completed it's work - eScheduleState_Completed, -}; - -// State of the single schedule item -enum EScheduleItemState -{ - // Item has not started yet but is on the list - eScheduleItemState_Pending, - - // We are processing this item - eScheduleItemState_Processing, - - // We are stopping this item - eScheduleItemState_Stopping, - - // Schedule item has failed - eScheduleItemState_Failed, - - // Schedule item has completed it's work - eScheduleItemState_Completed, -}; - -// Work item status -enum EScheduleWorkItemStatus -{ - // Work is still not finished - eScheduleWorkItemStatus_NotFinished, - - // Work has failed - eScheduleWorkItemStatus_Failed, - - // Work has finished - eScheduleWorkItemStatus_Finished, -}; - -struct IBackgroundScheduleItemWork -{ - // Get human readable description - virtual const char* GetDescription() const = 0; - - // Get work item progress - virtual float GetProgress() const = 0; - - // Called when the schedule item containing this work piece has started - // If the work cannot be started for any reason return false. - virtual bool OnStart() = 0; - - // Called when the schedule item containing this work piece has been canceled or failed externally - // Not called when schedule item completed without errors. - // If the work cannot be stopped this frame return false. - virtual bool OnStop() = 0; - - // Called every frame to advance and check the work state - // Should return one of the EBackgroundScheduleWorkItemStatus value - virtual EScheduleWorkItemStatus OnUpdate() = 0; - - // Reference counting - virtual void AddRef() = 0; - virtual void Release() = 0; - -protected: - virtual ~IBackgroundScheduleItemWork() {}; -}; - -struct IBackgroundScheduleItem -{ - // Get name of the schedule (debug & display) - virtual const char* GetDescription() const = 0; - - // Get interal state - virtual EScheduleItemState GetState() const = 0; - - // Get overall progress of this schedule item - virtual const float GetProgress() const = 0; - - // Get number of work items in this schedule item - virtual const uint32 GetNumWorkItems() const = 0; - - // Get n-th work item from the schedule item - virtual IBackgroundScheduleItemWork* GetWorkItem(const uint32 index) const = 0; - - // Add work item to the schedule item - virtual void AddWorkItem(IBackgroundScheduleItemWork* pWork) = 0; - - // Reference counting - virtual void AddRef() = 0; - virtual void Release() = 0; - -protected: - virtual ~IBackgroundScheduleItem() {}; -}; - -struct IBackgroundSchedule -{ - // Get name of the schedule (debug & display) - virtual const char* GetDescription() const = 0; - - // Get overall progress of the whole schedule - virtual float GetProgress() const = 0; - - // Get item being currently processed - virtual IBackgroundScheduleItem* GetProcessedItem() const = 0; - - // Get number of items in the schedule - virtual const uint32 GetNumItems() const = 0; - - // Get single schedule item - virtual IBackgroundScheduleItem* GetItem(const uint32 index) const = 0; - - // Get schedule item - virtual EScheduleState GetState() const = 0; - - // Cancel the whole schedule - virtual void Cancel() = 0; - - // Is the schedule canceled ? - virtual bool IsCanceled() const = 0; - - // Add schedule item at the end of the list - virtual void AddItem(IBackgroundScheduleItem* pItem) = 0; - - // Reference counting - virtual void AddRef() = 0; - virtual void Release() = 0; - -protected: - virtual ~IBackgroundSchedule() {}; -}; - -struct IBackgroundScheduleManager -{ - virtual ~IBackgroundScheduleManager() {}; - - // Create empty schedule - virtual IBackgroundSchedule* CreateSchedule(const char* szName) = 0; - - // Create empty schedule item - virtual IBackgroundScheduleItem* CreateScheduleItem(const char* szName) = 0; - - // Issue a schedule to the list (will start processing it) - virtual void SubmitSchedule(IBackgroundSchedule* pSchedule) = 0; - - // Get number of schedules on the list - virtual const uint32 GetNumSchedules() const = 0; - - // Get n-th schedule - virtual IBackgroundSchedule* GetSchedule(const uint32 index) const = 0; - - // Advance work on the schedules - virtual void Update() = 0; -}; - - -#endif // CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDSCHEDULEMANAGER_H diff --git a/Code/Sandbox/Editor/Include/IBackgroundTaskManager.h b/Code/Sandbox/Editor/Include/IBackgroundTaskManager.h deleted file mode 100644 index b586e3022f..0000000000 --- a/Code/Sandbox/Editor/Include/IBackgroundTaskManager.h +++ /dev/null @@ -1,230 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// -// IBackgroundTaskManager runs background tasks in worker thread. -// -// Tasks are derived from IBackgroundTask. Each task is split in two parts for: -// Work - done in background thread. -// Finalize - called afterward in main thread to apply results. -// -// Task objects are reference counted. Task manager will hold its own reference to the task object -// for as long as the task is pending or being executed. If you want to keep the task object around -// in your code you will have to call AddRef() and Release() on the task object by yourself so there -// will be an extra reference to the task object held by your code. -// -// Work returns the state of the task. Task can be resumed, then the Work -// method will be called again. Other tasks can work between calls to Work. -// It is possible to Cancel task. Work method is not invoked any more for -// Canceled tasks. -// - -#ifndef CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDTASKMANAGER_H -#define CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDTASKMANAGER_H -#pragma once - -enum ETaskPriority -{ - eTaskPriority_FileUpdateFinal, - eTaskPriority_BackgroundScan, - eTaskPriority_FileUpdate, - eTaskPriority_RealtimePreview -}; - -// Result code returned by task Work() function -enum ETaskResult -{ - // Task has not yet completed, add it back to the task queue with the same parameters (priority and thread mask) - eTaskResult_Resume, - - // Task has completed without errors (it's assumed that the result the task was supposed to achieve was achieved) - eTaskResult_Completed, - - // Task was canceled - eTaskResult_Canceled, - - // Task has failed to complete it's work - eTaskResult_Failed, -}; - -// Internal task tracking state -enum ETaskState -{ - // Task was just created. - eTaskState_Created, - - // Task was scheduled to be executed in the future. - eTaskState_Scheduled, - - // Task was added to the task queue and is waiting for it's time to be executed. - eTaskState_Pending, - - // Task is being processed right now. - eTaskState_Working, - - // Task was canceled before it has finished (indication that TaskManager has seen the Cancel() call). - eTaskState_Canceled, - - // Task Work() function was called but it ended with an error code. - eTaskState_Failed, - - // Task has completed it's Work() function without errors. - eTaskState_Completed, -}; - -// Thread mask controls which on which threads given task can be executed. -enum ETaskThreadMask -{ - // Task can run only on the IO thread (default) - // There is only one IO thread so all task with this flag are run in a sequence. - eTaskThreadMask_IO, - - // Task can run on any thread (concurrent tasks allowed) - // There can be many threads with this mask so there's no limit on the concurrent task count. - eTaskThreadMask_Any, - - eTaskThreadMask_COUNT, -}; - -struct IBackgroundTask -{ -public: - IBackgroundTask() - : m_bCanceled(false) - , m_state(eTaskState_Created) - , m_progress(-1.0f) - , m_refCount(0) - , m_bFailReported(false) - {} - - void Cancel() - { - m_bCanceled = true; - } - - bool IsCanceled() const - { - return m_bCanceled; - } - - bool HasFinished() const - { - return (m_state == eTaskState_Canceled) || - (m_state == eTaskState_Completed) || - (m_state == eTaskState_Failed); - } - - bool HasFinishedWithoutError() const - { - return (m_state == eTaskState_Completed); - } - - ETaskState GetState() const - { - return m_state; - } - - void SetState(ETaskState state) - { - m_state = state; - } - - float GetProgress() const - { - return m_progress; - } - - int AddRef() - { - return CryInterlockedIncrement(&m_refCount); - } - - int Release() - { - const int nCount = CryInterlockedDecrement(&m_refCount); - assert(nCount >= 0); - if (nCount == 0) - { - Delete(); - } - else if (nCount < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } - return nCount; - } - - bool FailReported() const{ return m_bFailReported; } - - // Get the user readable description (name) of this task, used for logging - virtual const char* Description() const { return ""; } - - // Get the user readable error message (in case when the task fails), used for logging the errors - virtual const char* ErrorMessage() const { return ""; } - - // Called from main thread after task is completed just before the task gets destroyed - virtual void Finalize() {} - - // Since there's a possibility that task object were created using different allocator - // we need a way to delete the task object once we are done with it - virtual void Delete() = 0; - - // Invoked from worker thread, actual work is done here - virtual ETaskResult Work() = 0; - -protected: - void SetProgress(float progress) { m_progress = progress; } - void SetFailReported() { m_bFailReported = true; } - - // destructor is hidden to indicate that we should use Release() method - virtual ~IBackgroundTask() {} - -private: - volatile int m_refCount; - ETaskState m_state; - float m_progress; - bool m_bCanceled; - bool m_bFailReported; -}; - -struct IBackgroundTaskManagerListener -{ - virtual ~IBackgroundTaskManagerListener() {} - - virtual void OnBackgroundTaskAdded(const char* description) = 0; - virtual void OnBackgroundTaskCompleted(ETaskResult taskResult, const char* description) = 0; -}; - -struct IBackgroundTaskManager -{ - enum - { - BACKGROUND_TASK_ID_INVALID = 0 - }; - - virtual ~IBackgroundTaskManager() {} - - // Add task to the queue with given priority and thread mask - virtual void AddTask(IBackgroundTask* pTask, ETaskPriority priority, ETaskThreadMask threadMask) = 0; - - // Schedule task to be executed in the future - virtual void ScheduleTask(IBackgroundTask* pTask, ETaskPriority priority, int delayMilliseconds, ETaskThreadMask threadMask) = 0; - - virtual void AddListener(IBackgroundTaskManagerListener* pListener, const char* name) = 0; - - virtual void RemoveListener(IBackgroundTaskManagerListener* pListener) = 0; -}; - - -#endif // CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDTASKMANAGER_H diff --git a/Code/Sandbox/Editor/LevelInfo.cpp b/Code/Sandbox/Editor/LevelInfo.cpp index 81441a3797..55c432094a 100644 --- a/Code/Sandbox/Editor/LevelInfo.cpp +++ b/Code/Sandbox/Editor/LevelInfo.cpp @@ -97,10 +97,6 @@ void CLevelInfo::ValidateObjects() pObject->Validate(m_pReport); - CUsedResources rs; - pObject->GatherUsedResources(rs); - rs.Validate(m_pReport); - m_pReport->SetCurrentValidatorObject(NULL); } diff --git a/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h b/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h index 38a35e6684..949bc72e03 100644 --- a/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h +++ b/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h @@ -102,7 +102,6 @@ public: MOCK_METHOD0(GetViewManager, class CViewManager* ()); MOCK_METHOD0(GetActiveView, class CViewport* ()); MOCK_METHOD1(SetActiveView, void(CViewport*)); - MOCK_METHOD0(GetBackgroundTaskManager, struct IBackgroundTaskManager* ()); MOCK_METHOD0(GetFileMonitor, struct IEditorFileMonitor* ()); MOCK_METHOD1(RegisterEventLoopHook, void(IEventLoopHook* )); MOCK_METHOD1(UnregisterEventLoopHook, void(IEventLoopHook* )); @@ -184,7 +183,6 @@ public: MOCK_CONST_METHOD0(GetEditorConfigPlatform, ESystemConfigPlatform()); MOCK_METHOD0(ReloadTemplates, void()); MOCK_METHOD0(GetResourceSelectorHost, IResourceSelectorHost* ()); - MOCK_METHOD0(GetBackgroundScheduleManager, struct IBackgroundScheduleManager* ()); MOCK_METHOD1(ShowStatusText, void(bool )); MOCK_METHOD1(RegisterObjectContextMenuExtension, void(TContextMenuExtensionFunc )); MOCK_METHOD0(GetEnv, SSystemGlobalEnvironment* ()); diff --git a/Code/Sandbox/Editor/MainStatusBarItems.h b/Code/Sandbox/Editor/MainStatusBarItems.h index 3f43f1818f..095183363f 100644 --- a/Code/Sandbox/Editor/MainStatusBarItems.h +++ b/Code/Sandbox/Editor/MainStatusBarItems.h @@ -13,7 +13,6 @@ #pragma once #include -#include #include #include #include diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index e9b27ee9b8..6f6b600a84 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -92,7 +92,6 @@ AZ_POP_DISABLE_WARNING #include "ErrorReportDialog.h" #include "Dialogs/PythonScriptsDialog.h" -#include "EngineSettingsManager.h" #include "AzAssetBrowser/AzAssetBrowserWindow.h" #include "AssetEditor/AssetEditorWindow.h" @@ -1941,12 +1940,6 @@ void MainWindow::ConnectivityStateChanged(const AzToolsFramework::SourceControlS } } -#if defined(CRY_ENABLE_RC_HELPER) - CEngineSettingsManager settingsManager; - settingsManager.SetModuleSpecificBoolEntry("RC_EnableSourceControl", connected); - settingsManager.StoreData(); -#endif - gSettings.enableSourceControl = connected; gSettings.SaveEnableSourceControlFlag(false); } diff --git a/Code/Sandbox/Editor/Objects/EntityObject.h b/Code/Sandbox/Editor/Objects/EntityObject.h index 85368f7804..b367384f08 100644 --- a/Code/Sandbox/Editor/Objects/EntityObject.h +++ b/Code/Sandbox/Editor/Objects/EntityObject.h @@ -35,7 +35,6 @@ class CEntityObject; class QMenu; -class IOpticsElementBase; /*! * CEntityEventTarget is an Entity event target and type. diff --git a/Code/Sandbox/Editor/UsedResources.cpp b/Code/Sandbox/Editor/UsedResources.cpp index 35384b0f34..013d35d4a7 100644 --- a/Code/Sandbox/Editor/UsedResources.cpp +++ b/Code/Sandbox/Editor/UsedResources.cpp @@ -27,38 +27,3 @@ void CUsedResources::Add(const char* pResourceFileName) files.insert(pResourceFileName); } } - -void CUsedResources::Validate(IErrorReport* pReport) -{ - auto pPak = gEnv->pCryPak; - - for (TResourceFiles::iterator it = files.begin(); it != files.end(); ++it) - { - const QString& filename = *it; - - bool fileExists = pPak->IsFileExist(filename.toUtf8().data()); - - if (!fileExists) - { - for (int i = 0; !fileExists && i < IResourceCompilerHelper::GetNumEngineImageFormats(); ++i) - { - fileExists = gEnv->pCryPak->IsFileExist(PathUtil::ReplaceExtension(filename.toUtf8().data(), IResourceCompilerHelper::GetEngineImageFormat(i, true)).c_str()); - } - for (int i = 0; !fileExists && i < IResourceCompilerHelper::GetNumSourceImageFormats(); ++i) - { - fileExists = gEnv->pCryPak->IsFileExist(PathUtil::ReplaceExtension(filename.toUtf8().data(), IResourceCompilerHelper::GetSourceImageFormat(i, true)).c_str()); - } - } - - - if (!fileExists) - { - CErrorRecord err; - - err.error = QObject::tr("Resource File %1 not found,").arg(filename); - err.severity = CErrorRecord::ESEVERITY_ERROR; - err.flags |= CErrorRecord::FLAG_NOFILE; - pReport->ReportError(err); - } - } -} diff --git a/Code/Sandbox/Editor/UsedResources.h b/Code/Sandbox/Editor/UsedResources.h index e22c672d30..acf8b79783 100644 --- a/Code/Sandbox/Editor/UsedResources.h +++ b/Code/Sandbox/Editor/UsedResources.h @@ -36,8 +36,6 @@ public: CUsedResources(); void Add(const char* pResourceFileName); - //! validate gathered resources, reports warning if resource is not found - void Validate(struct IErrorReport* pReport); AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING TResourceFiles files; diff --git a/Code/Sandbox/Editor/ViewportManipulatorController.cpp b/Code/Sandbox/Editor/ViewportManipulatorController.cpp index 0bf2bbc412..248d2ba52c 100644 --- a/Code/Sandbox/Editor/ViewportManipulatorController.cpp +++ b/Code/Sandbox/Editor/ViewportManipulatorController.cpp @@ -21,206 +21,228 @@ #include -static const auto ManipulatorPriority = AzFramework::ViewportControllerPriority::High; -static const auto InteractionPriority = AzFramework::ViewportControllerPriority::Low; +static const auto ManipulatorPriority = AzFramework::ViewportControllerPriority::Highest; +static const auto InteractionPriority = AzFramework::ViewportControllerPriority::High; namespace SandboxEditor { - -ViewportManipulatorControllerInstance::ViewportManipulatorControllerInstance(AzFramework::ViewportId viewport, ViewportManipulatorController* controller) - : AzFramework::MultiViewportControllerInstanceInterface(viewport, controller) -{ -} - -AzToolsFramework::ViewportInteraction::MouseButton ViewportManipulatorControllerInstance::GetMouseButton( - const AzFramework::InputChannel& inputChannel) -{ - using AzToolsFramework::ViewportInteraction::MouseButton; - using InputButton = AzFramework::InputDeviceMouse::Button; - const auto& id = inputChannel.GetInputChannelId(); - if (id == InputButton::Left) + ViewportManipulatorControllerInstance::ViewportManipulatorControllerInstance( + AzFramework::ViewportId viewport, ViewportManipulatorController* controller) + : AzFramework::MultiViewportControllerInstanceInterface(viewport, controller) { - return MouseButton::Left; } - if (id == InputButton::Middle) - { - return MouseButton::Middle; - } - if (id == InputButton::Right) - { - return MouseButton::Right; - } - return MouseButton::None; -} - -bool ViewportManipulatorControllerInstance::IsMouseMove(const AzFramework::InputChannel& inputChannel) -{ - return inputChannel.GetInputChannelId() == AzFramework::InputDeviceMouse::SystemCursorPosition; -} -AzToolsFramework::ViewportInteraction::KeyboardModifier ViewportManipulatorControllerInstance::GetKeyboardModifier( - const AzFramework::InputChannel& inputChannel) -{ - using AzToolsFramework::ViewportInteraction::KeyboardModifier; - using Key = AzFramework::InputDeviceKeyboard::Key; - const auto& id = inputChannel.GetInputChannelId(); - if (id == Key::ModifierAltL || id == Key::ModifierAltR) + AzToolsFramework::ViewportInteraction::MouseButton ViewportManipulatorControllerInstance::GetMouseButton( + const AzFramework::InputChannel& inputChannel) { - return KeyboardModifier::Alt; + using AzToolsFramework::ViewportInteraction::MouseButton; + using InputButton = AzFramework::InputDeviceMouse::Button; + const auto& id = inputChannel.GetInputChannelId(); + if (id == InputButton::Left) + { + return MouseButton::Left; + } + if (id == InputButton::Middle) + { + return MouseButton::Middle; + } + if (id == InputButton::Right) + { + return MouseButton::Right; + } + return MouseButton::None; } - if (id == Key::ModifierCtrlL || id == Key::ModifierCtrlR) + + bool ViewportManipulatorControllerInstance::IsMouseMove(const AzFramework::InputChannel& inputChannel) { - return KeyboardModifier::Ctrl; + return inputChannel.GetInputChannelId() == AzFramework::InputDeviceMouse::SystemCursorPosition; } - if (id == Key::ModifierShiftL || id == Key::ModifierShiftR) + + AzToolsFramework::ViewportInteraction::KeyboardModifier ViewportManipulatorControllerInstance::GetKeyboardModifier( + const AzFramework::InputChannel& inputChannel) { - return KeyboardModifier::Shift; + using AzToolsFramework::ViewportInteraction::KeyboardModifier; + using Key = AzFramework::InputDeviceKeyboard::Key; + const auto& id = inputChannel.GetInputChannelId(); + if (id == Key::ModifierAltL || id == Key::ModifierAltR) + { + return KeyboardModifier::Alt; + } + if (id == Key::ModifierCtrlL || id == Key::ModifierCtrlR) + { + return KeyboardModifier::Ctrl; + } + if (id == Key::ModifierShiftL || id == Key::ModifierShiftR) + { + return KeyboardModifier::Shift; + } + return KeyboardModifier::None; } - return KeyboardModifier::None; -} -bool ViewportManipulatorControllerInstance::HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) -{ - // We only care about manipulator and viewport interaction events - if (event.m_priority != ManipulatorPriority && event.m_priority != InteractionPriority) + bool ViewportManipulatorControllerInstance::HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) { - return false; - } + // We only care about manipulator and viewport interaction events + if (event.m_priority != ManipulatorPriority && event.m_priority != InteractionPriority) + { + return false; + } - using InteractionBus = AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; - using namespace AzToolsFramework::ViewportInteraction; - using AzFramework::InputChannel; + using InteractionBus = AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; + using namespace AzToolsFramework::ViewportInteraction; + using AzFramework::InputChannel; - bool interactionHandled = false; - AZStd::optional overrideButton; - AZStd::optional eventType; + bool interactionHandled = false; + float wheelDelta = 0.0f; + AZStd::optional overrideButton; + AZStd::optional eventType; - // Because we receive events multiple times at separate priorities for manipulator events and - // viewport interaction events, we want to avoid updating our "last tick state" until we're on our last event, - // which currently is the low priority Interaction processor. - const bool finishedProcessingEvents = event.m_priority == InteractionPriority; + // Because we receive events multiple times at separate priorities for manipulator events and + // viewport interaction events, we want to avoid updating our "last tick state" until we're on our last event, + // which currently is the low priority Interaction processor. + const bool finishedProcessingEvents = event.m_priority == InteractionPriority; - if (IsMouseMove(event.m_inputChannel)) - { - // Cache the ray trace results when doing manipulator interaction checks, no need to recalculate after - if (event.m_priority == ManipulatorPriority) + const auto state = event.m_inputChannel.GetState(); + if (IsMouseMove(event.m_inputChannel)) { - AzFramework::ScreenPoint screenPosition = AzFramework::ScreenPoint(0, 0); - ViewportMouseCursorRequestBus::EventResult( - screenPosition, GetViewportId(), &ViewportMouseCursorRequestBus::Events::ViewportCursorScreenPosition); + // Cache the ray trace results when doing manipulator interaction checks, no need to recalculate after + if (event.m_priority == ManipulatorPriority) + { + AzFramework::ScreenPoint screenPosition = AzFramework::ScreenPoint(0, 0); + ViewportMouseCursorRequestBus::EventResult( + screenPosition, GetViewportId(), &ViewportMouseCursorRequestBus::Events::ViewportCursorScreenPosition); - m_state.m_mousePick.m_screenCoordinates = screenPosition; - AZStd::optional ray; - ViewportInteractionRequestBus::EventResult( - ray, GetViewportId(), &ViewportInteractionRequestBus::Events::ViewportScreenToWorldRay, screenPosition); + m_mouseInteraction.m_mousePick.m_screenCoordinates = screenPosition; + AZStd::optional ray; + ViewportInteractionRequestBus::EventResult( + ray, GetViewportId(), &ViewportInteractionRequestBus::Events::ViewportScreenToWorldRay, screenPosition); - if (ray.has_value()) - { - m_state.m_mousePick.m_rayOrigin = ray.value().origin; - m_state.m_mousePick.m_rayDirection = ray.value().direction; + if (ray.has_value()) + { + m_mouseInteraction.m_mousePick.m_rayOrigin = ray.value().origin; + m_mouseInteraction.m_mousePick.m_rayDirection = ray.value().direction; + } } + eventType = MouseEvent::Move; } - eventType = MouseEvent::Move; - } - else if (auto mouseButton = GetMouseButton(event.m_inputChannel); mouseButton != MouseButton::None) - { - const AZ::u32 mouseButtonValue = static_cast(mouseButton); - overrideButton = mouseButton; - if (event.m_inputChannel.GetState() == InputChannel::State::Began) + else if (auto mouseButton = GetMouseButton(event.m_inputChannel); mouseButton != MouseButton::None) { - m_state.m_mouseButtons.m_mouseButtons |= mouseButtonValue; - if (IsDoubleClick(mouseButton)) + const AZ::u32 mouseButtonValue = static_cast(mouseButton); + overrideButton = mouseButton; + if (state == InputChannel::State::Began) { - // Only remove the double click flag once we're done processing both Manipulator and Interaction events - if (event.m_priority == InteractionPriority) + m_mouseInteraction.m_mouseButtons.m_mouseButtons |= mouseButtonValue; + if (IsDoubleClick(mouseButton)) + { + // Only remove the double click flag once we're done processing both Manipulator and Interaction events + if (event.m_priority == InteractionPriority) + { + m_pendingDoubleClicks.erase(mouseButton); + } + eventType = MouseEvent::DoubleClick; + } + else { - m_pendingDoubleClicks.erase(mouseButton); + // Only insert the double click timing once we're done processing events, to avoid a false IsDoubleClick positive + if (finishedProcessingEvents) + { + m_pendingDoubleClicks[mouseButton] = m_curTime; + } + eventType = MouseEvent::Down; } - eventType = MouseEvent::DoubleClick; } - else + else if (state == InputChannel::State::Ended) { - // Only insert the double click timing once we're done processing events, to avoid a false IsDoubleClick positive - if (finishedProcessingEvents) + // If we've actually logged a mouse down event, forward a mouse up event. + // This prevents corner cases like the context menu thinking it should be opened even though no one clicked in this viewport, + // due to RenderViewportWidget ensuring all controllers get InputChannel::State::Ended events. + if (m_mouseInteraction.m_mouseButtons.m_mouseButtons & mouseButtonValue) { - m_pendingDoubleClicks[mouseButton] = m_curTime; + // Erase the button from our state if we're done processing events. + if (event.m_priority == InteractionPriority) + { + m_mouseInteraction.m_mouseButtons.m_mouseButtons &= ~mouseButtonValue; + } + eventType = MouseEvent::Up; } - eventType = MouseEvent::Down; } } - else if (event.m_inputChannel.GetState() == InputChannel::State::Ended) + else if (auto keyboardModifier = GetKeyboardModifier(event.m_inputChannel); keyboardModifier != KeyboardModifier::None) { - // If we've actually logged a mouse down event, forward a mouse up event. - // This prevents corner cases like the context menu thinking it should be opened even though no one clicked in this viewport, - // due to RenderViewportWidget ensuring all controllers get InputChannel::State::Ended events. - if (m_state.m_mouseButtons.m_mouseButtons & mouseButtonValue) + if (state == InputChannel::State::Began || state == InputChannel::State::Updated) { - // Erase the button from our state if we're done processing events. - if (event.m_priority == InteractionPriority) - { - m_state.m_mouseButtons.m_mouseButtons &= ~mouseButtonValue; - } - eventType = MouseEvent::Up; + m_mouseInteraction.m_keyboardModifiers.m_keyModifiers |= static_cast(keyboardModifier); + } + else if (state == InputChannel::State::Ended) + { + m_mouseInteraction.m_keyboardModifiers.m_keyModifiers &= ~static_cast(keyboardModifier); } } - } - else if (auto keyboardModifier = GetKeyboardModifier(event.m_inputChannel); keyboardModifier != KeyboardModifier::None) - { - if (event.m_inputChannel.GetState() == InputChannel::State::Began || event.m_inputChannel.GetState() == InputChannel::State::Updated) + else if (event.m_inputChannel.GetInputChannelId() == AzFramework::InputDeviceMouse::Movement::Z) { - m_state.m_keyboardModifiers.m_keyModifiers |= static_cast(keyboardModifier); + if (state == InputChannel::State::Began || state == InputChannel::State::Updated) + { + eventType = MouseEvent::Wheel; + wheelDelta = event.m_inputChannel.GetValue(); + } } - else if (event.m_inputChannel.GetState() == InputChannel::State::Ended) + + if (eventType) { - m_state.m_keyboardModifiers.m_keyModifiers &= ~static_cast(keyboardModifier); + MouseInteraction mouseInteraction = m_mouseInteraction; + if (overrideButton) + { + mouseInteraction.m_mouseButtons.m_mouseButtons = static_cast(overrideButton.value()); + } + + mouseInteraction.m_interactionId.m_viewportId = GetViewportId(); + + // Depending on priority, we dispatch to either the manipulator or viewport interaction event + const auto& targetInteractionEvent = event.m_priority == ManipulatorPriority + ? &InteractionBus::Events::InternalHandleMouseManipulatorInteraction + : &InteractionBus::Events::InternalHandleMouseViewportInteraction; + + const auto mouseInteractionEvent = [mouseInteraction, event = eventType.value(), wheelDelta] { + switch (event) + { + case MouseEvent::Up: + case MouseEvent::Down: + case MouseEvent::Move: + case MouseEvent::DoubleClick: + return MouseInteractionEvent(AZStd::move(mouseInteraction), event); + case MouseEvent::Wheel: + return MouseInteractionEvent(AZStd::move(mouseInteraction), wheelDelta); + } + + AZ_Assert(false, "Unhandled MouseEvent"); + return MouseInteractionEvent(MouseInteraction{}, MouseEvent::Up); + }(); + + InteractionBus::EventResult( + interactionHandled, AzToolsFramework::GetEntityContextId(), targetInteractionEvent, mouseInteractionEvent); } + + return interactionHandled; } - if (eventType) + void ViewportManipulatorControllerInstance::ResetInputChannels() { - MouseInteraction mouseInteraction = m_state; - if (overrideButton) - { - mouseInteraction.m_mouseButtons.m_mouseButtons = static_cast(overrideButton.value()); - } - mouseInteraction.m_interactionId.m_viewportId = GetViewportId(); - - // Depending on priority, we dispatch to either the manipulator or viewport interaction event - const auto& targetInteractionEvent = - event.m_priority == ManipulatorPriority - ? &InteractionBus::Events::InternalHandleMouseManipulatorInteraction - : &InteractionBus::Events::InternalHandleMouseViewportInteraction; - - InteractionBus::EventResult( - interactionHandled, - AzToolsFramework::GetEntityContextId(), - targetInteractionEvent, - MouseInteractionEvent(AZStd::move(mouseInteraction), eventType.value())); + m_pendingDoubleClicks.clear(); + m_mouseInteraction = AzToolsFramework::ViewportInteraction::MouseInteraction(); } - return interactionHandled; -} - -void ViewportManipulatorControllerInstance::ResetInputChannels() -{ - m_pendingDoubleClicks.clear(); - m_state = AzToolsFramework::ViewportInteraction::MouseInteraction(); -} - -void ViewportManipulatorControllerInstance::UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) -{ - m_curTime = event.m_time; -} - -bool ViewportManipulatorControllerInstance::IsDoubleClick(AzToolsFramework::ViewportInteraction::MouseButton button) const -{ - auto clickIt = m_pendingDoubleClicks.find(button); - if (clickIt == m_pendingDoubleClicks.end()) + void ViewportManipulatorControllerInstance::UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) { - return false; + m_curTime = event.m_time; } - const double doubleClickThresholdMilliseconds = qApp->doubleClickInterval(); - return (m_curTime.GetMilliseconds() - clickIt->second.GetMilliseconds()) < doubleClickThresholdMilliseconds; -} + bool ViewportManipulatorControllerInstance::IsDoubleClick(AzToolsFramework::ViewportInteraction::MouseButton button) const + { + auto clickIt = m_pendingDoubleClicks.find(button); + if (clickIt == m_pendingDoubleClicks.end()) + { + return false; + } + const double doubleClickThresholdMilliseconds = qApp->doubleClickInterval(); + return (m_curTime.GetMilliseconds() - clickIt->second.GetMilliseconds()) < doubleClickThresholdMilliseconds; + } } //namespace SandboxEditor diff --git a/Code/Sandbox/Editor/ViewportManipulatorController.h b/Code/Sandbox/Editor/ViewportManipulatorController.h index d5540229c4..6d4ab4d1ba 100644 --- a/Code/Sandbox/Editor/ViewportManipulatorController.h +++ b/Code/Sandbox/Editor/ViewportManipulatorController.h @@ -39,7 +39,7 @@ namespace SandboxEditor static bool IsMouseMove(const AzFramework::InputChannel& inputChannel); static AzToolsFramework::ViewportInteraction::KeyboardModifier GetKeyboardModifier(const AzFramework::InputChannel& inputChannel); - AzToolsFramework::ViewportInteraction::MouseInteraction m_state; + AzToolsFramework::ViewportInteraction::MouseInteraction m_mouseInteraction; AZStd::unordered_map m_pendingDoubleClicks; AZ::ScriptTimePoint m_curTime; }; diff --git a/Code/Sandbox/Editor/editor_lib_files.cmake b/Code/Sandbox/Editor/editor_lib_files.cmake index 3d6112d186..401b7c6e39 100644 --- a/Code/Sandbox/Editor/editor_lib_files.cmake +++ b/Code/Sandbox/Editor/editor_lib_files.cmake @@ -280,8 +280,6 @@ set(FILES Include/IAnimationCompressionManager.h Include/IAssetItem.h Include/IAssetItemDatabase.h - Include/IBackgroundScheduleManager.h - Include/IBackgroundTaskManager.h Include/ICommandManager.h Include/IConsoleConnectivity.h Include/IDataBaseItem.h @@ -343,10 +341,6 @@ set(FILES AssetEditor/AssetEditorWindow.cpp AssetEditor/AssetEditorWindow.h AssetEditor/AssetEditorWindow.ui - BackgroundTaskManager.cpp - BackgroundScheduleManager.cpp - BackgroundTaskManager.h - BackgroundScheduleManager.h Commands/CommandManager.cpp Commands/CommandManager.h Controls/BitmapToolTip.cpp diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index 33d4b5baf4..f38b295128 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -160,7 +160,6 @@ void SandboxIntegrationManager::Setup() AzToolsFramework::SliceEditorEntityOwnershipServiceNotificationBus::Handler::BusConnect(); AzFramework::DisplayContextRequestBus::Handler::BusConnect(); - SetupFileExtensionMap(); MainWindow::instance()->GetActionManager()->RegisterActionHandler(ID_FILE_SAVE_SLICE_TO_ROOT, [this]() { SaveSlice(false); @@ -1926,30 +1925,6 @@ void SandboxIntegrationManager::MakeSliceFromEntities(const AzToolsFramework::En AzToolsFramework::SliceUtilities::MakeNewSlice(entitiesAndDescendants, path, inheritSlices, setAsDynamic); } -void SandboxIntegrationManager::SetupFileExtensionMap() -{ - // There's no central registry for geometry file types. - const char* geometryFileExtensions[] = - { - CRY_GEOMETRY_FILE_EXT, // .cgf - CRY_SKEL_FILE_EXT, // .chr - CRY_CHARACTER_DEFINITION_FILE_EXT, // .cdf - }; - - // Cry geometry file extensions. - for (const char* extension : geometryFileExtensions) - { - m_extensionToFileType[AZ::Crc32(extension)] = IFileUtil::EFILE_TYPE_GEOMETRY; - } - - // Cry image file extensions. - for (size_t i = 0; i < IResourceCompilerHelper::GetNumSourceImageFormats(); ++i) - { - const char* extension = IResourceCompilerHelper::GetSourceImageFormat(i, false); - m_extensionToFileType[AZ::Crc32(extension)] = IFileUtil::EFILE_TYPE_TEXTURE; - } -} - void SandboxIntegrationManager::RegisterViewPane(const char* name, const char* category, const AzToolsFramework::ViewPaneOptions& viewOptions, const WidgetCreationFunc& widgetCreationFunc) { QtViewPaneManager::instance()->RegisterPane(name, category, widgetCreationFunc, viewOptions); diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h index b3c60bca45..14f52591a4 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h @@ -319,12 +319,10 @@ private: void OnLayerComponentDeactivated(AZ::EntityId entityId) override; private: - void SetupFileExtensionMap(); // Right click context menu when a layer is included in the selection. void SetupLayerContextMenu(QMenu* menu); void SetupSliceContextMenu(QMenu* menu); void SetupSliceContextMenu_Modify(QMenu* menu, const AzToolsFramework::EntityIdList& selectedEntities, const AZ::u32 numEntitiesInSlices); - void SetupScriptCanvasContextMenu(QMenu* menu); void SaveSlice(const bool& QuickPushToFirstLevel); void GetEntitiesInSlices(const AzToolsFramework::EntityIdList& selectedEntities, AZ::u32& entitiesInSlices, AZStd::vector& sliceInstances); @@ -348,9 +346,6 @@ private: }; private: - typedef AZStd::unordered_map ExtensionMap; - ExtensionMap m_extensionToFileType; - AZ::Vector2 m_contextMenuViewPoint; AZ::Vector3 m_sliceWorldPos; diff --git a/Code/Sandbox/Plugins/MaglevControlPanel/CloudCanvasPythonWorkerInterface.h b/Code/Sandbox/Plugins/MaglevControlPanel/CloudCanvasPythonWorkerInterface.h deleted file mode 100644 index 1d557e35f7..0000000000 --- a/Code/Sandbox/Plugins/MaglevControlPanel/CloudCanvasPythonWorkerInterface.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include - -#include - -using PythonWorkerRequestId = int; - -//! Interface to signal the python worker output -class PythonWorkerEventsInterface -{ -protected: - PythonWorkerEventsInterface() = default; - virtual ~PythonWorkerEventsInterface() = default; - PythonWorkerEventsInterface(PythonWorkerEventsInterface&&) = delete; - PythonWorkerEventsInterface& operator=(PythonWorkerEventsInterface&&) = delete; - -public: - AZ_RTTI(PythonWorkerEventsInterface, "{60C83A5A-B8DD-4B98-B8C6-DC2F5914D7C4}"); - - // if any OnOutput returns true, it means the command was handled and the worker won't process any further - virtual bool OnPythonWorkerOutput(PythonWorkerRequestId requestId, const QString& key, const QVariant& value) = 0; -}; - -//! Interface to send the python worker requests -class PythonWorkerRequestsInterface -{ -protected: - PythonWorkerRequestsInterface() = default; - virtual ~PythonWorkerRequestsInterface() = default; - PythonWorkerRequestsInterface(PythonWorkerRequestsInterface&&) = delete; - PythonWorkerRequestsInterface& operator=(PythonWorkerRequestsInterface&&) = delete; - -public: - AZ_RTTI(PythonWorkerRequestsInterface, "{B0293028-3575-408E-8CE3-D1B7F3C59A6C}"); - - virtual PythonWorkerRequestId AllocateRequestId() = 0; - virtual void ExecuteAsync(PythonWorkerRequestId requestId, const char* command, const QVariantMap& args = QVariantMap{}) = 0; - virtual bool IsStarted() = 0; -}; - diff --git a/Code/Sandbox/Plugins/MaglevControlPanel/MaglevControlPanelPlugin_stub.cpp b/Code/Sandbox/Plugins/MaglevControlPanel/MaglevControlPanelPlugin_stub.cpp deleted file mode 100644 index 1508e9f7b0..0000000000 --- a/Code/Sandbox/Plugins/MaglevControlPanel/MaglevControlPanelPlugin_stub.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "stdafx.h" -#include -#include - -const char* TAG = "MaglevControlPanelPlugin"; - -MaglevControlPanelPlugin::MaglevControlPanelPlugin(IEditor* editor) - : m_pluginSettings(QSettings::IniFormat, QSettings::UserScope, "Amazon", "Lumberyard") -{ - -} - -void MaglevControlPanelPlugin::Release() -{ -} - -void MaglevControlPanelPlugin::OnEditorNotify(EEditorNotifyEvent aEventId) -{ -} - diff --git a/Code/Tools/CryCommonTools/Export/AnimationData.cpp b/Code/Tools/CryCommonTools/Export/AnimationData.cpp deleted file mode 100644 index 2b2c5966a6..0000000000 --- a/Code/Tools/CryCommonTools/Export/AnimationData.cpp +++ /dev/null @@ -1,297 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "AnimationData.h" - -AnimationData::AnimationData(int modelCount, float fps, float startTime) - : m_entries(modelCount) - , m_frameCount(0) - , m_startTime(startTime) - , m_fps(fps) -{ -} - -void AnimationData::SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3]) -{ - State& state = m_entries[modelIndex].samples[frameIndex]; - state.translation[0] = translation[0]; - state.translation[1] = translation[1]; - state.translation[2] = translation[2]; - state.rotation[0] = rotation[0]; - state.rotation[1] = rotation[1]; - state.rotation[2] = rotation[2]; - state.scale[0] = scale[0]; - state.scale[1] = scale[1]; - state.scale[2] = scale[2]; -} - -void AnimationData::SetFrameCount(int frameCount) -{ - m_frameCount = frameCount; - for (int modelIndex = 0, modelCount = int(m_entries.size()); modelIndex < modelCount; ++modelIndex) - { - m_entries[modelIndex].samples.resize(frameCount); - } -} - -void AnimationData::SetModelFlags(int modelIndex, unsigned modelFlags) -{ - m_entries[modelIndex].flags = modelFlags; -} - -void AnimationData::GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const -{ - translation = m_entries[modelIndex].samples[frameIndex].translation; - rotation = m_entries[modelIndex].samples[frameIndex].rotation; - scale = m_entries[modelIndex].samples[frameIndex].scale; -} - -void AnimationData::GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const -{ - translation = m_entries[modelIndex].samples[frameIndex].translation; -} - -void AnimationData::GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const -{ - rotation = m_entries[modelIndex].samples[frameIndex].rotation; -} - -void AnimationData::GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const -{ - scale = m_entries[modelIndex].samples[frameIndex].scale; -} - -int AnimationData::GetFrameCount() const -{ - return m_frameCount; -} - -unsigned AnimationData::GetModelFlags(int modelIndex) const -{ - return m_entries[modelIndex].flags; -} - -AnimationData::State::State() -{ - translation[0] = translation[1] = translation[2] = 0.0f; - rotation[0] = rotation[1] = rotation[2] = 0.0f; - scale[0] = scale[1] = scale[2] = 1.0f; -} - -AnimationData::ModelEntry::ModelEntry() - : flags(0) -{ -} - -/////////////////////////////////////////////////////////////////////////// -NonSkeletalAnimationData::NonSkeletalAnimationData(int modelCount) - : m_entries(modelCount) -{ -} - -void NonSkeletalAnimationData::SetModelFlags(int modelIndex, unsigned modelFlags) -{ - m_entries[modelIndex].flags = modelFlags; -} - -unsigned NonSkeletalAnimationData::GetModelFlags(int modelIndex) const -{ - return m_entries[modelIndex].flags; -} - -void NonSkeletalAnimationData::SetFrameTimePos(int modelIndex, int frameIndex, float time) -{ - State& state = m_entries[modelIndex].samplesPos[frameIndex]; - state.time = time; -} - -void NonSkeletalAnimationData::SetFrameDataPos(int modelIndex, int frameIndex, float translation[3]) -{ - State& state = m_entries[modelIndex].samplesPos[frameIndex]; - state.data[0] = translation[0]; - state.data[1] = translation[1]; - state.data[2] = translation[2]; -} - -void NonSkeletalAnimationData::SetFrameCountPos(int modelIndex, int frameCount) -{ - m_entries[modelIndex].samplesPos.resize(frameCount); -} - -void NonSkeletalAnimationData::SetFrameTimeRot(int modelIndex, int frameIndex, float time) -{ - State& state = m_entries[modelIndex].samplesRot[frameIndex]; - state.time = time; -} - -void NonSkeletalAnimationData::SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3]) -{ - State& state = m_entries[modelIndex].samplesRot[frameIndex]; - state.data[0] = rotation[0]; - state.data[1] = rotation[1]; - state.data[2] = rotation[2]; -} - -void NonSkeletalAnimationData::SetFrameCountRot(int modelIndex, int frameCount) -{ - m_entries[modelIndex].samplesRot.resize(frameCount); -} - -void NonSkeletalAnimationData::SetFrameTimeScl(int modelIndex, int frameIndex, float time) -{ - State& state = m_entries[modelIndex].samplesScl[frameIndex]; - state.time = time; -} - -void NonSkeletalAnimationData::SetFrameDataScl(int modelIndex, int frameIndex, float scale[3]) -{ - State& state = m_entries[modelIndex].samplesScl[frameIndex]; - state.data[0] = scale[0]; - state.data[1] = scale[1]; - state.data[2] = scale[2]; -} - -void NonSkeletalAnimationData::SetFrameCountScl(int modelIndex, int frameCount) -{ - m_entries[modelIndex].samplesScl.resize(frameCount); -} - -float NonSkeletalAnimationData::GetFrameTimePos(int modelIndex, int frameIndex) const -{ - return m_entries[modelIndex].samplesPos[frameIndex].time; -} - -void NonSkeletalAnimationData::GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const -{ - translation = m_entries[modelIndex].samplesPos[frameIndex].data; -} - -int NonSkeletalAnimationData::GetFrameCountPos(int modelIndex) const -{ - return int(m_entries[modelIndex].samplesPos.size()); -} - -float NonSkeletalAnimationData::GetFrameTimeRot(int modelIndex, int frameIndex) const -{ - return m_entries[modelIndex].samplesRot[frameIndex].time; -} - -void NonSkeletalAnimationData::GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const -{ - rotation = m_entries[modelIndex].samplesRot[frameIndex].data; -} - -int NonSkeletalAnimationData::GetFrameCountRot(int modelIndex) const -{ - return int(m_entries[modelIndex].samplesRot.size()); -} - -float NonSkeletalAnimationData::GetFrameTimeScl(int modelIndex, int frameIndex) const -{ - return m_entries[modelIndex].samplesScl[frameIndex].time; -} - -void NonSkeletalAnimationData::GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const -{ - scale = m_entries[modelIndex].samplesScl[frameIndex].data; -} - -int NonSkeletalAnimationData::GetFrameCountScl(int modelIndex) const -{ - return int(m_entries[modelIndex].samplesScl.size()); -} - -void NonSkeletalAnimationData::SetFrameTCBPos(int modelIndex, int frameIndex, IAnimationData::TCB tcb) -{ - State& state = m_entries[modelIndex].samplesPos[frameIndex]; - state.tcb = tcb; -} - -void NonSkeletalAnimationData::SetFrameTCBRot(int modelIndex, int frameIndex, IAnimationData::TCB tcb) -{ - State& state = m_entries[modelIndex].samplesRot[frameIndex]; - state.tcb = tcb; -} - -void NonSkeletalAnimationData::SetFrameTCBScl(int modelIndex, int frameIndex, IAnimationData::TCB tcb) -{ - State& state = m_entries[modelIndex].samplesScl[frameIndex]; - state.tcb = tcb; -} - -void NonSkeletalAnimationData::SetFrameEaseInOutPos(int modelIndex, int frameIndex, IAnimationData::Ease ease) -{ - State& state = m_entries[modelIndex].samplesPos[frameIndex]; - state.ease = ease; -} - -void NonSkeletalAnimationData::SetFrameEaseInOutRot(int modelIndex, int frameIndex, IAnimationData::Ease ease) -{ - State& state = m_entries[modelIndex].samplesRot[frameIndex]; - state.ease = ease; -} - -void NonSkeletalAnimationData::SetFrameEaseInOutScl(int modelIndex, int frameIndex, IAnimationData::Ease ease) -{ - State& state = m_entries[modelIndex].samplesScl[frameIndex]; - state.ease = ease; -} - -void NonSkeletalAnimationData::GetFrameTCBPos(int modelIndex, int frameIndex, IAnimationData::TCB& tcb) const -{ - const State& state = m_entries[modelIndex].samplesPos[frameIndex]; - tcb = state.tcb; -} - -void NonSkeletalAnimationData::GetFrameTCBRot(int modelIndex, int frameIndex, IAnimationData::TCB& tcb) const -{ - const State& state = m_entries[modelIndex].samplesRot[frameIndex]; - tcb = state.tcb; -} - -void NonSkeletalAnimationData::GetFrameTCBScl(int modelIndex, int frameIndex, IAnimationData::TCB& tcb) const -{ - const State& state = m_entries[modelIndex].samplesScl[frameIndex]; - tcb = state.tcb; -} - -void NonSkeletalAnimationData::GetFrameEaseInOutPos(int modelIndex, int frameIndex, IAnimationData::Ease& ease) const -{ - const State& state = m_entries[modelIndex].samplesPos[frameIndex]; - ease = state.ease; -} - -void NonSkeletalAnimationData::GetFrameEaseInOutRot(int modelIndex, int frameIndex, IAnimationData::Ease& ease) const -{ - const State& state = m_entries[modelIndex].samplesRot[frameIndex]; - ease = state.ease; -} - -void NonSkeletalAnimationData::GetFrameEaseInOutScl(int modelIndex, int frameIndex, IAnimationData::Ease& ease) const -{ - const State& state = m_entries[modelIndex].samplesScl[frameIndex]; - ease = state.ease; -} - - -NonSkeletalAnimationData::State::State() -{ - time = 0.0f; - data[0] = data[1] = data[2] = 0.0f; -} - -NonSkeletalAnimationData::ModelEntry::ModelEntry() - : flags(0) -{ -} diff --git a/Code/Tools/CryCommonTools/Export/AnimationData.h b/Code/Tools/CryCommonTools/Export/AnimationData.h deleted file mode 100644 index 65b699e49b..0000000000 --- a/Code/Tools/CryCommonTools/Export/AnimationData.h +++ /dev/null @@ -1,211 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ANIMATIONDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ANIMATIONDATA_H -#pragma once - - -#include "IAnimationData.h" - -#include - -// Animation data class for skeletal animations -// It has a same count of samples for all models(bones) -// and always has translation/rotation/scaling data together as a set. -class AnimationData - : public IAnimationData -{ -public: - AnimationData(int modelCount, float fps, float startTime); - virtual ~AnimationData() {} - - // IAnimationData - virtual void SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3]); - virtual void SetFrameCount(int frameCount); - virtual void SetModelFlags(int modelIndex, unsigned modelFlags); - - virtual void SetFrameTimePos(int modelIndex, int frameIndex, float time) - { assert(0); } - virtual void SetFrameDataPos(int modelIndex, int frameIndex, float translation[3]) - { assert(0); } - virtual void SetFrameCountPos(int modelIndex, int frameCount) - { assert(0); } - virtual void SetFrameTimeRot(int modelIndex, int frameIndex, float time) - { assert(0); } - virtual void SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3]) - { assert(0); } - virtual void SetFrameCountRot(int modelIndex, int frameCount) - { assert(0); } - virtual void SetFrameTimeScl(int modelIndex, int frameIndex, float time) - { assert(0); } - virtual void SetFrameDataScl(int modelIndex, int frameIndex, float scale[3]) - { assert(0); } - virtual void SetFrameCountScl(int modelIndex, int frameCount) - { assert(0); } - - virtual void GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const; - virtual int GetFrameCount() const; - virtual unsigned GetModelFlags(int modelIndex) const; - - virtual float GetFrameTimePos(int modelIndex, int frameIndex) const - { return m_startTime + frameIndex / m_fps; } - virtual void GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const; - virtual int GetFrameCountPos(int) const - { return GetFrameCount(); } - virtual float GetFrameTimeRot(int modelIndex, int frameIndex) const - { return m_startTime + frameIndex / m_fps; } - virtual void GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const; - virtual int GetFrameCountRot(int) const - { return GetFrameCount(); } - virtual float GetFrameTimeScl(int modelIndex, int frameIndex) const - { return m_startTime + frameIndex / m_fps; } - virtual void GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const; - virtual int GetFrameCountScl(int) const - { return GetFrameCount(); } - - // TCB & Ease-In/-Out not supported for the skeletal animation. - virtual void SetFrameTCBPos(int modelIndex, int frameIndex, TCB tcb) - { assert(0); } - virtual void SetFrameTCBRot(int modelIndex, int frameIndex, TCB tcb) - { assert(0); } - virtual void SetFrameTCBScl(int modelIndex, int frameIndex, TCB tcb) - { assert(0); } - virtual void SetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease ease) - { assert(0); } - virtual void SetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease ease) - { assert(0); } - virtual void SetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease ease) - { assert(0); } - virtual void GetFrameTCBPos(int modelIndex, int frameIndex, TCB& tcb) const - { assert(0); } - virtual void GetFrameTCBRot(int modelIndex, int frameIndex, TCB& tcb) const - { assert(0); } - virtual void GetFrameTCBScl(int modelIndex, int frameIndex, TCB& tcb) const - { assert(0); } - virtual void GetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease& ease) const - { assert(0); } - virtual void GetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease& ease) const - { assert(0); } - virtual void GetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease& ease) const - { assert(0); } - -private: - struct State - { - public: - State(); - float translation[3]; - float rotation[3]; - float scale[3]; - }; - - struct ModelEntry - { - ModelEntry(); - - unsigned flags; - std::vector samples; - }; - - std::vector m_entries; - int m_frameCount; - float m_startTime; - float m_fps; -}; - -// Animation data class for non-skeletal animations -// It can have different counts of samples for each model -// and each channel of transformation data. -class NonSkeletalAnimationData - : public IAnimationData -{ -public: - NonSkeletalAnimationData(int modelCount); - virtual ~NonSkeletalAnimationData() {} - - // IAnimationData - virtual void SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3]) - { assert(0); } - virtual void SetFrameCount(int frameCount) - { assert(0); } - virtual void SetModelFlags(int modelIndex, unsigned modelFlags); - - virtual void SetFrameTimePos(int modelIndex, int frameIndex, float time); - virtual void SetFrameDataPos(int modelIndex, int frameIndex, float translation[3]); - virtual void SetFrameCountPos(int modelIndex, int frameCount); - virtual void SetFrameTimeRot(int modelIndex, int frameIndex, float time); - virtual void SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3]); - virtual void SetFrameCountRot(int modelIndex, int frameCount); - virtual void SetFrameTimeScl(int modelIndex, int frameIndex, float time); - virtual void SetFrameDataScl(int modelIndex, int frameIndex, float scale[3]); - virtual void SetFrameCountScl(int modelIndex, int frameCount); - - virtual void GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const - { assert(0); } - virtual int GetFrameCount() const - { - assert(0); - return 0; - } - virtual unsigned GetModelFlags(int modelIndex) const; - - virtual float GetFrameTimePos(int modelIndex, int frameIndex) const; - virtual void GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const; - virtual int GetFrameCountPos(int) const; - virtual float GetFrameTimeRot(int modelIndex, int frameIndex) const; - virtual void GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const; - virtual int GetFrameCountRot(int) const; - virtual float GetFrameTimeScl(int modelIndex, int frameIndex) const; - virtual void GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const; - virtual int GetFrameCountScl(int) const; - - virtual void SetFrameTCBPos(int modelIndex, int frameIndex, TCB tcb); - virtual void SetFrameTCBRot(int modelIndex, int frameIndex, TCB tcb); - virtual void SetFrameTCBScl(int modelIndex, int frameIndex, TCB tcb); - virtual void SetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease ease); - virtual void SetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease ease); - virtual void SetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease ease); - - virtual void GetFrameTCBPos(int modelIndex, int frameIndex, TCB& tcb) const; - virtual void GetFrameTCBRot(int modelIndex, int frameIndex, TCB& tcb) const; - virtual void GetFrameTCBScl(int modelIndex, int frameIndex, TCB& tcb) const; - virtual void GetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease& ease) const; - virtual void GetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease& ease) const; - virtual void GetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease& ease) const; - -private: - struct State - { - public: - State(); - float time; - float data[3]; - TCB tcb; - Ease ease; - }; - - struct ModelEntry - { - ModelEntry(); - - unsigned flags; - std::vector samplesPos; - std::vector samplesRot; - std::vector samplesScl; - }; - - std::vector m_entries; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ANIMATIONDATA_H diff --git a/Code/Tools/CryCommonTools/Export/CBAHelpers.cpp b/Code/Tools/CryCommonTools/Export/CBAHelpers.cpp deleted file mode 100644 index d724e349be..0000000000 --- a/Code/Tools/CryCommonTools/Export/CBAHelpers.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "CBAHelpers.h" -#include "../PathHelpers.h" -#include "StringHelpers.h" - -static string FindRootContainingFileGoingUpwards(const char* filePath, const char* filePathToLookFor, IPakSystem* pakSystem) -{ - // Here we just search upwards from the current directory, looking for a directory that - // contains a file at the relative path "Animations/Animations.cba". This is designed to - // handle root Game paths that differ from the default "Game". - string rootDirCandidate = PathHelpers::GetDirectory(filePath); - string rootDir; - while (!rootDirCandidate.empty()) - { - string cbaCandidatePath = PathHelpers::Join(rootDirCandidate, filePathToLookFor); - if (PakSystemFile* file = pakSystem->Open(cbaCandidatePath.c_str(), "r")) - { - // File exists, we have found the correct root path. - pakSystem->Close(file); - - rootDir = rootDirCandidate; - break; - } - - string previousCandidate = rootDirCandidate; - rootDirCandidate = PathHelpers::GetDirectory(rootDirCandidate); - if (rootDirCandidate == previousCandidate) - { - break; - } - } - - return (rootDir.empty() ? rootDir : PathHelpers::Join(rootDir, filePathToLookFor)); -} - -string CBAHelpers::FindCBAFileForFile(const char* filePath, IPakSystem* pakSystem) -{ - return FindRootContainingFileGoingUpwards(filePath, "Animations/Animations.cba", pakSystem); -} - -string CBAHelpers::FindSkeletonListForFile(const char* filePath, IPakSystem* pakSystem) -{ - return FindRootContainingFileGoingUpwards(filePath, "Animations/SkeletonList.xml", pakSystem); -} diff --git a/Code/Tools/CryCommonTools/Export/CBAHelpers.h b/Code/Tools/CryCommonTools/Export/CBAHelpers.h deleted file mode 100644 index 48af5c74d2..0000000000 --- a/Code/Tools/CryCommonTools/Export/CBAHelpers.h +++ /dev/null @@ -1,27 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_CBAHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_CBAHELPERS_H -#pragma once - - -#include "IPakSystem.h" - -namespace CBAHelpers -{ - string FindCBAFileForFile(const char* filePath, IPakSystem* pakSystem); - string FindSkeletonListForFile(const char* filePath, IPakSystem* pakSystem); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_CBAHELPERS_H diff --git a/Code/Tools/CryCommonTools/Export/ColladaExportWriter.cpp b/Code/Tools/CryCommonTools/Export/ColladaExportWriter.cpp deleted file mode 100644 index d0796a4838..0000000000 --- a/Code/Tools/CryCommonTools/Export/ColladaExportWriter.cpp +++ /dev/null @@ -1,556 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" - -#include "ColladaExportWriter.h" -#include "ColladaWriter.h" -#include "IExportSource.h" -#include "PathHelpers.h" -#include "ResourceCompilerHelper.h" -#include "SettingsManagerHelpers.h" -#include "IExportContext.h" -#include "ProgressRange.h" -#include "XMLWriter.h" -#include "XMLPakFileSink.h" -#include "ISettings.h" -#include "SingleAnimationExportSourceAdapter.h" -#include "GeometryExportSourceAdapter.h" -#include "ModelData.h" -#include "MaterialData.h" -#include "GeometryFileData.h" -#include "FileUtil.h" -#include "CBAHelpers.h" -#include "ModuleHelpers.h" -#include "PropertyHelpers.h" -#include "StringHelpers.h" -#include -#include - -namespace -{ - class ResourceCompilerLogListener - : public IResourceCompilerListener - { - public: - ResourceCompilerLogListener(IExportContext* context) - : m_context(context) - { - } - - virtual void OnRCMessage(IResourceCompilerListener::MessageSeverity severity, const char* text) - { - ILogger::ESeverity outSeverity; - switch (severity) - { - case IResourceCompilerListener::MessageSeverity_Debug: - case IResourceCompilerListener::MessageSeverity_Info: // normal RC text should just be debug - outSeverity = ILogger::eSeverity_Debug; - break; - case IResourceCompilerListener::MessageSeverity_Warning: - outSeverity = ILogger::eSeverity_Warning; - break; - case IResourceCompilerListener::MessageSeverity_Error: - outSeverity = ILogger::eSeverity_Error; - break; - default: - outSeverity = ILogger::eSeverity_Error; - break; - } - - m_context->Log(outSeverity, "%s", text); - } - - private: - IExportContext* m_context; - }; -} - -void ColladaExportWriter::Export(IExportSource* source, IExportContext* context) -{ - // Create an object to report on our progress to the export context. - ProgressRange progressRange(context, &IExportContext::SetProgress); - CResourceCompilerHelper compiler; // we need a real instance of this specific implementation. - - // Log build information. - context->Log(ILogger::eSeverity_Info, "Exporter build created on " __DATE__); - -#ifdef STLPORT - context->Log(ILogger::eSeverity_Info, "Using STLport C++ Standard Library implementation"); -#else //STLPORT - context->Log(ILogger::eSeverity_Info, "Using Microsoft (tm) C++ Standard Library implementation"); -#endif //STLPORT - -#if defined(_DEBUG) - context->Log(ILogger::eSeverity_Info, "******DEBUG BUILD******"); -#else //_DEBUG - context->Log(ILogger::eSeverity_Info, "Release build."); -#endif //_DEBUG - - context->Log(ILogger::eSeverity_Debug, "Bit count == %d.", (sizeof(void*) * 8)); - - std::string exePath = StringHelpers::ConvertString(ModuleHelpers::GetCurrentModulePath(ModuleHelpers::CurrentModuleSpecifier_Executable)); - context->Log(ILogger::eSeverity_Debug, "Application path: %s", exePath.c_str()); - - std::string exporterPath = StringHelpers::ConvertString(ModuleHelpers::GetCurrentModulePath(ModuleHelpers::CurrentModuleSpecifier_Library)); - context->Log(ILogger::eSeverity_Debug, "Exporter path: %s", exporterPath.c_str()); - - bool const bExportCompressed = (GetSetting(context->GetSettings(), "ExportCompressedCOLLADA", 1)) != 0; - context->Log(ILogger::eSeverity_Debug, "ExportCompressedCOLLADA key: %d", (bExportCompressed ? 1 : 0)); - - std::string const exportExtension = bExportCompressed ? ".dae.zip" : ".dae"; - - // Log the start time. - { - char buf[1024]; - std::time_t t = std::time(0); - std::strftime(buf, sizeof(buf) / sizeof(buf[0]), "%H:%M:%S on %a, %d/%m/%Y", std::localtime(&t)); - context->Log(ILogger::eSeverity_Info, "Export begun at %s", buf); - } - - // Select the name of the directory to export to. - std::string const originalExportDirectory = source->GetExportDirectory(); - if (originalExportDirectory.empty()) - { - throw IExportContext::NeedSaveError("Scene must be saved before exporting."); - } - - GeometryFileData geometryFileData; - std::vector colladaGeometryFileNameList; - std::vector assetGeometryFileNameList; - typedef std::vector, std::string> > AnimationFileNameList; - AnimationFileNameList animationFileNameList; - AnimationFileNameList animationCompileFileNameList; - { - CurrentTaskScope currentTask(context, "dae"); - - // Choose the files to which to export all the animations. - std::list animationExportSources; - std::list geometryExportSources; - typedef std::vector > ExportList; - ExportList exportList; - std::vector geometryFileIndices; - { - ProgressRange readProgressRange(progressRange, 0.2f); - - source->ReadGeometryFiles(context, &geometryFileData); - - for (int geometryFileIndex = 0; geometryFileIndex < geometryFileData.GetGeometryFileCount(); ++geometryFileIndex) - { - const std::string geometryFileName = geometryFileData.GetGeometryFileName(geometryFileIndex); - - IGeometryFileData::SProperties properties = geometryFileData.GetProperties(geometryFileIndex); - if (properties.filetypeInt == CRY_FILE_TYPE_CAF) - { - // LDS: This is a temporary fix for some old hacky code that would activate a deprecated compression path during export - // It needs a proper fix by tearing out the old compression code and moving the system to the new i_caf system by default. - // See for http://docs.cryengine.com/display/SDKDOC3/Transition+from+CBA+to+AnimSettings details. - properties.filetypeInt = CRY_FILE_TYPE_INTERMEDIATE_CAF; - geometryFileData.SetProperties(geometryFileIndex, properties); - } - - bool const hasGeometry = (properties.filetypeInt != CRY_FILE_TYPE_CAF && - properties.filetypeInt != CRY_FILE_TYPE_INTERMEDIATE_CAF); - - if (hasGeometry && !geometryFileName.empty()) - { - geometryFileIndices.push_back(geometryFileIndex); - } - } - - if (!geometryFileIndices.empty()) - { - std::string name = PathHelpers::RemoveExtension(PathHelpers::GetFilename(source->GetDCCFileName())); - std::replace(name.begin(), name.end(), ' ', '_'); - std::string const colladaPath = PathHelpers::Join(originalExportDirectory, name + exportExtension); - colladaGeometryFileNameList.push_back(colladaPath); - - geometryExportSources.push_back(GeometryExportSourceAdapter(source, &geometryFileData, geometryFileIndices)); - exportList.push_back(std::make_pair(colladaPath, &geometryExportSources.back())); - } - - for (int geometryFileIndex = 0; geometryFileIndex < geometryFileData.GetGeometryFileCount(); ++geometryFileIndex) - { - std::string const geometryFileName = geometryFileData.GetGeometryFileName(geometryFileIndex); - int const fileTypeInt = geometryFileData.GetProperties(geometryFileIndex).filetypeInt; - std::string customExportPath = geometryFileData.GetProperties(geometryFileIndex).customExportPath; - bool const hasGeometry = (fileTypeInt != CRY_FILE_TYPE_CAF && - fileTypeInt != CRY_FILE_TYPE_INTERMEDIATE_CAF); - - if (hasGeometry && !geometryFileName.empty()) - { - std::string extension = "missingextension"; - if (fileTypeInt == CRY_FILE_TYPE_CGF) - { - extension = "cgf"; - } - else if ((fileTypeInt == CRY_FILE_TYPE_CGA) || (fileTypeInt == (CRY_FILE_TYPE_CGA | CRY_FILE_TYPE_ANM))) - { - extension = "cga"; - } - else if (fileTypeInt == CRY_FILE_TYPE_ANM) - { - extension = "anm"; - } - else if (fileTypeInt == CRY_FILE_TYPE_CHR || - (fileTypeInt == (CRY_FILE_TYPE_CHR | CRY_FILE_TYPE_CAF)) || - (fileTypeInt == (CRY_FILE_TYPE_CHR | CRY_FILE_TYPE_INTERMEDIATE_CAF))) - { - extension = "chr"; - } - else if (fileTypeInt == CRY_FILE_TYPE_SKIN) - { - extension = "skin"; - } - - std::string safeGeometryFileName = geometryFileName; - std::replace(safeGeometryFileName.begin(), safeGeometryFileName.end(), ' ', '_'); - std::string finalFileName; - if (customExportPath.size() > 0) - { - if (PathHelpers::IsRelative(customExportPath)) - { - std::string const assetRelativePath = PathHelpers::Join(originalExportDirectory, customExportPath); - finalFileName = PathHelpers::Join(assetRelativePath, safeGeometryFileName + "." + extension); - } - else - { - context->Log(ILogger::eSeverity_Warning, "An absolute path was specified for export of node %s (%s) - This is unlikely to be correct", geometryFileName.c_str(), customExportPath.c_str()); - finalFileName = PathHelpers::Join(customExportPath, safeGeometryFileName + "." + extension); - } - } - else - { - // no relative path, just export it in the original directory. - finalFileName = PathHelpers::Join(originalExportDirectory, safeGeometryFileName + "." + extension); - } - if (finalFileName.size() > 0) - { - assetGeometryFileNameList.push_back(finalFileName); - if (!FileUtil::EnsureDirectoryExists(PathHelpers::GetDirectory(finalFileName).c_str())) - { - context->Log(ILogger::eSeverity_Error, "Unable to create directory for %s", finalFileName.c_str()); - return; - } - } - } - - if ((fileTypeInt & (CRY_FILE_TYPE_CAF | CRY_FILE_TYPE_INTERMEDIATE_CAF)) != 0) - { - for (int animationIndex = 0; animationIndex < source->GetAnimationCount(); ++animationIndex) - { - std::string const animationName = source->GetAnimationName(&geometryFileData, geometryFileIndex, animationIndex); - - // Animations beginning with an underscore should be ignored. - bool const ignoreAnimation = animationName.empty() || (animationName[0] == '_'); - - if (!ignoreAnimation) - { - std::string safeAnimationName = animationName; - std::replace(safeAnimationName.begin(), safeAnimationName.end(), ' ', '_'); - - std::string exportPath = PathHelpers::Join(originalExportDirectory, safeAnimationName + exportExtension); - animationFileNameList.push_back(std::make_pair(std::make_pair(animationIndex, geometryFileIndex), exportPath)); - if (fileTypeInt & CRY_FILE_TYPE_CAF) - { - animationCompileFileNameList.push_back(std::make_pair(std::make_pair(animationIndex, geometryFileIndex), exportPath)); - } - animationExportSources.push_back(SingleAnimationExportSourceAdapter(source, &geometryFileData, geometryFileIndex, animationIndex)); - exportList.push_back(std::make_pair(exportPath, &animationExportSources.back())); - } - } - } - } - } - - // Export the COLLADA file to the chosen file. - { - ProgressRange exportProgressRange(progressRange, 0.6f); - - size_t const daeCount = exportList.size(); - float const daeProgressRangeSlice = 1.0f / (daeCount > 0 ? daeCount : 1); - for (ExportList::iterator itFile = exportList.begin(); itFile != exportList.end(); ++itFile) - { - const std::string& colladaFileName = (*itFile).first; - IExportSource* fileExportSource = (*itFile).second; - - ProgressRange animationExportProgressRange(exportProgressRange, daeProgressRangeSlice); - - try - { - context->Log(ILogger::eSeverity_Info, "Exporting to file '%s'", colladaFileName.c_str()); - - // Try to create the directory for the file. - if (!FileUtil::EnsureDirectoryExists(PathHelpers::GetDirectory(colladaFileName).c_str())) - { - context->Log(ILogger::eSeverity_Error, "Unable to create directory for %s", colladaFileName.c_str()); - return; - } - - bool ok; - - if (bExportCompressed) - { - IPakSystem* pakSystem = (context ? context->GetPakSystem() : 0); - if (!pakSystem) - { - throw IExportContext::PakSystemError("No pak system provided."); - } - - std::string const archivePath = colladaFileName; - std::string archiveRelativePath = colladaFileName.substr(0, colladaFileName.length() - exportExtension.length()) + ".dae"; - archiveRelativePath = PathHelpers::GetFilename(archiveRelativePath); - - XMLPakFileSink sink(pakSystem, archivePath, archiveRelativePath); - ok = ColladaWriter::Write(fileExportSource, context, &sink, animationExportProgressRange); - } - else - { - XMLFileSink fileSink(colladaFileName); - ok = ColladaWriter::Write(fileExportSource, context, &fileSink, animationExportProgressRange); - } - - if (!ok) - { - // FIXME: erase the resulting file somehow - context->Log(ILogger::eSeverity_Error, "Failed to export '%s'", colladaFileName.c_str()); - return; - } - } - catch (IXMLSink::OpenFailedError e) - { - context->Log(ILogger::eSeverity_Error, "Unable to open output file: %s", e.what()); - return; - } - catch (...) - { - context->Log(ILogger::eSeverity_Error, "Unexpected crash in COLLADA exporter"); - return; - } - } - } - } - - // Get the RC path. If a custom one isn't specified then fall back to the registry method as per the default. - wchar_t resourceCompilerPath[512]; - { - const std::string resourceCompilerPathString = source->GetResourceCompilerPath(); - if (!resourceCompilerPathString.empty()) - { - SettingsManagerHelpers::ConvertUtf8ToUtf16(resourceCompilerPathString.c_str(), SettingsManagerHelpers::CWCharBuffer(resourceCompilerPath, sizeof(resourceCompilerPath))); - } - } - - // Run the resource compiler on the COLLADA file to generate uncompressed CAFs. - { - ProgressRange compilerProgressRange(progressRange, 0.075f); - - CurrentTaskScope currentTask(context, "rc"); - - size_t const daeCount = animationFileNameList.size(); - float const animationProgressRangeSlice = 1.0f / (daeCount > 0 ? daeCount : 1); - for (AnimationFileNameList::iterator itFile = animationFileNameList.begin(); itFile != animationFileNameList.end(); ++itFile) - { - std::string colladaFileName = (*itFile).second; - int geometryFileIndex = itFile->first.second; - - std::string expectedCAFPath; - { - bool isIntermediateCAF = (geometryFileData.GetProperties(geometryFileIndex).filetypeInt & CRY_FILE_TYPE_INTERMEDIATE_CAF) != 0; - string nameWithoutExtension = colladaFileName.substr(0, colladaFileName.length() - exportExtension.length()); - expectedCAFPath = nameWithoutExtension + (isIntermediateCAF ? ".i_caf" : ".caf"); - } - - if (FileUtil::FileExists(expectedCAFPath.c_str())) - { - if (!DeleteFileA(expectedCAFPath.c_str())) - { - context->Log(ILogger::eSeverity_Error, "Failed to remove existing animation file: %s", expectedCAFPath.c_str()); - continue; - } - } - - string arguments = "/refresh"; - - ProgressRange animationCompileProgressRange(compilerProgressRange, animationProgressRangeSlice); - ResourceCompilerLogListener listener(context); - - context->Log(ILogger::eSeverity_Info, "Calling RC to generate uncompressed CAF file: %s", colladaFileName.c_str()); - CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler( // actual instance of compiler used - colladaFileName.c_str(), - arguments.c_str(), - &listener, - true, false, false, 0, resourceCompilerPath); - - if (result != CResourceCompilerHelper::eRcCallResult_success) - { - context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result)); - continue; - } - - context->Log(ILogger::eSeverity_Debug, "RC finished: %s", colladaFileName.c_str()); - if (!FileUtil::FileExists(expectedCAFPath.c_str())) - { - context->Log(ILogger::eSeverity_Error, "Following Animation file is expected to be created by RC: %s", expectedCAFPath.c_str()); - context->Log(ILogger::eSeverity_Error, "Do you have an old RC version?"); - } - -#if !defined(_DEBUG) - // Delete the Collada file. - DeleteFileA(colladaFileName.c_str()); -#endif - } - } - - // Run the resource compiler on the COLLADA file to generate the geometry assets. - { - ProgressRange compilerProgressRange(progressRange, 0.075f); - - CurrentTaskScope currentTask(context, "rc"); - - size_t const daeCount = colladaGeometryFileNameList.size(); - float const assetProgressRangeSlice = 1.0f / (daeCount > 0 ? daeCount : 1); - for (size_t i = 0; i < daeCount; ++i) - { - const std::string& colladaFileName = colladaGeometryFileNameList[i]; - - ProgressRange assetCompileProgressRange(compilerProgressRange, assetProgressRangeSlice); - ResourceCompilerLogListener listener(context); - context->Log(ILogger::eSeverity_Info, "Calling RC to generate raw asset file: %s", colladaFileName.c_str()); - CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler( - colladaFileName.c_str(), - "/refresh", - &listener, - true, false, false, 0, resourceCompilerPath); - -#if !defined(_DEBUG) - // Delete the Collada file. - DeleteFileA(colladaFileName.c_str()); -#endif - - if (result == CResourceCompilerHelper::eRcCallResult_success) - { - context->Log(ILogger::eSeverity_Debug, "RC finished: %s", colladaFileName.c_str()); - } - else - { - context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result)); - return; - } - } - } - - { - // Create an RC helper - do it outside the loop, since it queries the registry on construction. - ResourceCompilerLogListener listener(context); - - // Check the registry to see whether we should compress the animations or not. - int processAnimations = GetSetting(context->GetSettings(), "CompressCAFs", 1); - - if (!processAnimations) - { - context->Log(ILogger::eSeverity_Warning, "CompressCAFs registry key set to 0 - not compressing CAFs"); - } - else - { - // Run the resource compiler again on the generated CAF files to compress/process them. - context->Log(ILogger::eSeverity_Debug, "CompressCAFs not set or set to 1 - compressing CAFs"); - - CurrentTaskScope currentTask(context, "compress"); - ProgressRange compressRange(progressRange, 0.025f); - - size_t const cafCount = animationCompileFileNameList.size(); - float const animationProgressRangeSlice = 1.0f / (cafCount > 0 ? cafCount : 1); - for (AnimationFileNameList::iterator itFile = animationCompileFileNameList.begin(); itFile != animationCompileFileNameList.end(); ++itFile) - { - std::string colladaFileName = (*itFile).second; - ProgressRange animationProgressRange(compressRange, animationProgressRangeSlice); - - // Assume the RC generated the CAF file using the take name and adding .CAF. - std::string cafPath = colladaFileName.substr(0, colladaFileName.length() - exportExtension.length()) + ".caf"; - std::string cbaPath = StringHelpers::ConvertString(CBAHelpers::FindCBAFileForFile(cafPath.c_str(), context->GetPakSystem())); - - if (cbaPath.empty()) - { - context->Log(ILogger::eSeverity_Error, "Unable to find CBA file for file \"%s\" (looked for a root game directory that contains a relative path of \"Animations/Animations.cba\"", cafPath.c_str()); - } - else - { - char buffer[2048]; - sprintf(buffer, "/file=\"%s\" /refresh /SkipDba", cafPath.c_str()); - context->Log(ILogger::eSeverity_Info, "Calling RC to compress CAF file: (CBA file = %s) %s", cbaPath.c_str(), buffer); - CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler(cbaPath.c_str(), buffer, &listener, true, resourceCompilerPathType, false, false, 0, resourceCompilerPath); - if (result == CResourceCompilerHelper::eRcCallResult_success) - { - context->Log(ILogger::eSeverity_Debug, "RC finished: %s %s", cbaPath.c_str(), buffer); - } - else - { - context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result)); - return; - } - } - } - } - - // Check the registry to see whether we should optimize the geometry files or not. - int optimizeGeometry = GetSetting(context->GetSettings(), "OptimizeAssets", 1); - - // Run the resource compiler again on the generated geometry files to compress/process them. - // TODO: This should not be necessary, the RC should be modified so that assets are automatically - // compressed when exported from COLLADA. - if (!optimizeGeometry) - { - context->Log(ILogger::eSeverity_Warning, "OptimizeAssets registry key set to 0 - not compressing CAFs"); - } - else - { - context->Log(ILogger::eSeverity_Debug, "OptimizeAssets not set or set to 1 - optimizing geometry"); - - CurrentTaskScope currentTask(context, "compress"); - ProgressRange compressRange(progressRange, 0.025f); - - size_t const assetCount = assetGeometryFileNameList.size(); - float const assetProgressRangeSlice = 1.0f / (assetCount > 0 ? assetCount : 1); - for (size_t i = 0; i < assetCount; ++i) - { - const std::string& assetFileName = assetGeometryFileNameList[i]; - ProgressRange animationProgressRange(compressRange, assetProgressRangeSlice); - - // note: we skip some asset types because we know that they are "optimized" already - if (StringHelpers::EndsWithIgnoreCase(assetFileName, ".anm") || StringHelpers::EndsWithIgnoreCase(assetFileName, ".chr") || StringHelpers::EndsWithIgnoreCase(assetFileName, ".skin")) - { - context->Log(ILogger::eSeverity_Info, "Calling RC to optimize asset \"%s\"", assetFileName.c_str()); - CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler(assetFileName.c_str(), "/refresh", &listener, true, resourceCompilerPathType, false, false, 0, resourceCompilerPath); - if (result == CResourceCompilerHelper::eRcCallResult_success) - { - context->Log(ILogger::eSeverity_Debug, "RC finished: %s", assetFileName.c_str()); - } - else - { - context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result)); - return; - } - } - } - } - } - - // Log the end time. - { - char buf[1024]; - std::time_t t = std::time(0); - std::strftime(buf, sizeof(buf) / sizeof(buf[0]), "%H:%M:%S on %a, %d/%m/%Y", std::localtime(&t)); - context->Log(ILogger::eSeverity_Info, "Export finished at %s", buf); - } -} diff --git a/Code/Tools/CryCommonTools/Export/ColladaExportWriter.h b/Code/Tools/CryCommonTools/Export/ColladaExportWriter.h deleted file mode 100644 index 8dc53ad62f..0000000000 --- a/Code/Tools/CryCommonTools/Export/ColladaExportWriter.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAEXPORTWRITER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAEXPORTWRITER_H -#pragma once - - -#include "IExportWriter.h" - -class ColladaExportWriter - : public IExportWriter -{ -public: - // IExportWriter - virtual void Export(IExportSource* source, IExportContext* context); -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAEXPORTWRITER_H diff --git a/Code/Tools/CryCommonTools/Export/ColladaWriter.cpp b/Code/Tools/CryCommonTools/Export/ColladaWriter.cpp deleted file mode 100644 index 106ed02ba4..0000000000 --- a/Code/Tools/CryCommonTools/Export/ColladaWriter.cpp +++ /dev/null @@ -1,2918 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ColladaWriter.h" -#include "IExportSource.h" -#include "ISettings.h" -#include "XMLWriter.h" -#include "SkeletonData.h" -#include "AnimationData.h" -#include "ProgressRange.h" -#include "ModelData.h" -#include "IExportContext.h" -#include "GeometryFileData.h" -#include "GeometryData.h" -#include "MaterialData.h" -#include "SkinningData.h" -#include "Cry_Math.h" -#include "LocaleChanger.h" -#include "MorphData.h" -#include "StringHelpers.h" -#include "GeometryMaterialData.h" -#include "ColladaShared.h" -#include -#include -#include -#include - -namespace -{ - bool FloatingPointHasPrecisionIssues() - { - Matrix44 m; - - m.m00 = 0.729367f; - m.m01 = -0.143863f; - m.m02 = -0.668825f; - m.m03 = 0.595435f; - - m.m10 = -0.573746f; - m.m11 = 0.403844f; - m.m12 = -0.712549f; - m.m13 = 1.14523f; - - m.m20 = 0.37261f; - m.m21 = 0.903445f; - m.m22 = 0.21201f; - m.m23 = 0.0669039f; - - m.m30 = 0; - m.m31 = 0; - m.m32 = 0; - m.m33 = 1; - - m.Invert(); - - return m.m33 <= 0.999f || m.m33 >= 1.001f; - - // For testing with www.wolframalpha.com: - // string a = StringHelpers::Format("inverse{{%g,%g,%g,%g},{%g,%g,%g,%g},{%g,%g,%g,%g},{%g,%g,%g,%g}}", - // m.m00, m.m01, m.m02, m.m03, - // m.m10, m.m11, m.m12, m.m13, - // m.m20, m.m21, m.m22, m.m23, - // m.m30, m.m31, m.m32, m.m33); - } -} - - -namespace -{ - void DecomposeTransform(Vec3& translation, CryQuat& rotation, Vec3& scale, const Matrix34& transform) - { - translation = transform.GetTranslation(); - Matrix33 orientation(transform); - scale.x = Vec3(orientation.m00, orientation.m10, orientation.m20).GetLength(); - scale.y = Vec3(orientation.m01, orientation.m11, orientation.m21).GetLength(); - scale.z = Vec3(orientation.m02, orientation.m12, orientation.m22).GetLength(); - orientation.OrthonormalizeFast(); - rotation = !CryQuat(orientation); - } - - struct BoneEntry - { - std::string name; - std::string physName; - std::string parentFrameName; - }; - - typedef std::map, SkeletonData> SkeletonDataMap; - typedef std::map, MorphData> MorphDataMap; - typedef std::map, std::vector > BoneDataMap; - - struct GeometryEntry - { - GeometryEntry(const std::string& name, int geometryFileIndex, int modelIndex) - : name(name) - , geometryFileIndex(geometryFileIndex) - , modelIndex(modelIndex) {} - std::string name; - int geometryFileIndex; - int modelIndex; - }; - - struct BoneGeometryEntry - { - BoneGeometryEntry(const std::string& name, int geometryFileIndex, int modelIndex, int boneIndex) - : name(name) - , geometryFileIndex(geometryFileIndex) - , modelIndex(modelIndex) - , boneIndex(boneIndex) {} - std::string name; - int geometryFileIndex; - int modelIndex; - int boneIndex; - }; - - struct MorphGeometryEntry - { - MorphGeometryEntry(const std::string& name, const std::string& morphName, int geometryFileIndex, int modelIndex, int morphIndex) - : name(name) - , morphName(morphName) - , geometryFileIndex(geometryFileIndex) - , modelIndex(modelIndex) - , morphIndex(morphIndex) {} - std::string name; - std::string morphName; - int geometryFileIndex; - int modelIndex; - int morphIndex; - }; - - struct EffectsEntry - { - EffectsEntry(const std::string& name) - : name(name) {} - - std::string name; - }; - - struct MaterialEntry - { - MaterialEntry(const std::string& name) - : name(name) {} - - std::string name; - }; - - struct SkinControllerEntry - { - std::string name; - int geometryFileIndex; - int modelIndex; - }; - - struct MorphControllerEntry - { - std::string name; - int geometryFileIndex; - int modelIndex; - }; - - typedef std::map, MorphControllerEntry> MorphControllerMap; - - void BindMaterials(XMLWriter& writer, IExportContext* context, MaterialData& materialData, const ModelData& modelData, int modelIndex, const std::map& materialMaterialMap, const std::vector& materials, IExportSource* source) - { - // Instance any materials that the node uses. - GeometryMaterialData geometryMaterialData; - source->ReadGeometryMaterialData(context, &geometryMaterialData, &modelData, &materialData, modelIndex); - - std::set usedMaterialIndices; - for (int materialIndex = 0, materialCount = geometryMaterialData.GetUsedMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - usedMaterialIndices.insert(geometryMaterialData.GetUsedMaterialIndex(materialIndex)); - } - if (!usedMaterialIndices.empty()) - { - XMLWriter::Element bindMaterialElement(writer, "bind_material"); - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - for (std::set::const_iterator usedMtlPos = usedMaterialIndices.begin(), usedMtlEnd = usedMaterialIndices.end(); usedMtlPos != usedMtlEnd; ++usedMtlPos) - { - std::map::const_iterator entryMapPos = materialMaterialMap.find(*usedMtlPos); - int entryIndex = (entryMapPos != materialMaterialMap.end() ? (*entryMapPos).second : -1); - std::string name = (entryIndex >= 0 ? materials[entryIndex].name : "UNKNOWN_INSTANCED_MATERIAL"); - - XMLWriter::Element instanceMaterialElement(writer, "instance_material"); - instanceMaterialElement.Attribute("symbol", name); - instanceMaterialElement.Attribute("target", "#" + name); - } - } - } - - void BindBoneMaterials(XMLWriter& writer, IExportContext* context, MaterialData& materialData, SkeletonData& skeletonData, int boneIndex, const std::map& materialMaterialMap, const std::vector& materials, IExportSource* source) - { - // Instance any materials that the node uses. - GeometryMaterialData geometryMaterialData; - source->ReadBoneGeometryMaterialData(context, &geometryMaterialData, &skeletonData, boneIndex, &materialData); - - std::set usedMaterialIndices; - for (int materialIndex = 0, materialCount = geometryMaterialData.GetUsedMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - usedMaterialIndices.insert(geometryMaterialData.GetUsedMaterialIndex(materialIndex)); - } - if (!usedMaterialIndices.empty()) - { - XMLWriter::Element bindMaterialElement(writer, "bind_material"); - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - for (std::set::const_iterator usedMtlPos = usedMaterialIndices.begin(), usedMtlEnd = usedMaterialIndices.end(); usedMtlPos != usedMtlEnd; ++usedMtlPos) - { - std::map::const_iterator entryMapPos = materialMaterialMap.find(*usedMtlPos); - int entryIndex = (entryMapPos != materialMaterialMap.end() ? (*entryMapPos).second : -1); - std::string name = (entryIndex >= 0 ? materials[entryIndex].name : "UNKNOWN_INSTANCED_MATERIAL"); - - XMLWriter::Element instanceMaterialElement(writer, "instance_material"); - instanceMaterialElement.Attribute("symbol", name); - instanceMaterialElement.Attribute("target", "#" + name); - } - } - - //// Instance any materials that the node uses. - //std::vector materialIDs; - //for (int materialIndex = 0, materialCount = materialData.GetMaterialCount(); materialIndex < materialCount; ++materialIndex) - //{ - // int parentIndex = materialData.GetParentIndex(materialIndex); - // if (parentIndex >= 0 && parentIndex == skeletonData.GetMaterial(boneIndex)) - // materialIDs.push_back(materialIndex); - //} - - //if (!materialIDs.empty()) - //{ - // XMLWriter::Element bindMaterialElement(writer, "bind_material"); - // XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - // for (int i = 0, count = int(materialIDs.size()); i < count; ++i) - // { - // std::map::const_iterator entryMapPos = materialMaterialMap.find(materialIDs[i]); - // int entryIndex = (entryMapPos != materialMaterialMap.end() ? (*entryMapPos).second : -1); - // std::string name = (entryIndex >= 0 ? materials[entryIndex].name : 0); - - // XMLWriter::Element instanceMaterialElement(writer, "instance_material"); - // instanceMaterialElement.Attribute("symbol", name); - // instanceMaterialElement.Attribute("target", "#" + name); - // } - //} - } - - void WriteExtraData(XMLWriter& writer, const SHelperData& helperData, const std::string& properties) - { - // Write helper data (if it's helper node) and properties - if ((!properties.empty()) || (helperData.m_eHelperType != SHelperData::eHelperType_UNKNOWN)) - { - XMLWriter::Element elem(writer, "extra"); - { - XMLWriter::Element elem(writer, "technique"); - elem.Attribute("profile", "CryEngine"); - { - if (!properties.empty()) - { - // TODO: Sokov: check for invalid characters in properties string, like '<', '>', <' ', >127 etc. - XMLWriter::Element elem(writer, "properties"); - elem.Content(properties); - } - - if (helperData.m_eHelperType != SHelperData::eHelperType_UNKNOWN) - { - XMLWriter::Element elem(writer, "helper"); - switch (helperData.m_eHelperType) - { - case SHelperData::eHelperType_Point: - elem.Attribute("type", "point"); - break; - case SHelperData::eHelperType_Dummy: - elem.Attribute("type", "dummy"); - { - XMLWriter::Element elem(writer, "bound_box_min"); - elem.ContentArrayElement(helperData.m_boundBoxMin[0]); - elem.ContentArrayElement(helperData.m_boundBoxMin[1]); - elem.ContentArrayElement(helperData.m_boundBoxMin[2]); - } - { - XMLWriter::Element elem(writer, "bound_box_max"); - elem.ContentArrayElement(helperData.m_boundBoxMax[0]); - elem.ContentArrayElement(helperData.m_boundBoxMax[1]); - elem.ContentArrayElement(helperData.m_boundBoxMax[2]); - } - break; - default: - assert(false); - elem.Attribute("type", "UNKNOWN"); - break; - } - } - } - } - } - - // ****** I dont think we need this anymore. These files are not readable by XSI as far as I know. ****** - // ****** Removed 03-Jan-2012 - // Write special properties for importing to the XSI. - /*{ - XMLWriter::Element elem(writer, "technique"); - elem.Attribute("profile","XSI"); - { - XMLWriter::Element elem(writer, "XSI_CustomPSet"); - elem.Attribute("name","ObjectProperties"); - { - XMLWriter::Element elem(writer, "propagation"); - elem.Content("NODE"); - } - { - XMLWriter::Element elem(writer, "type"); - elem.Content("CryNodeProperties"); - } - { - XMLWriter::Element elem(writer, "XSI_Parameter"); - elem.Attribute("id","Props"); - elem.Attribute("type","Text"); - elem.Attribute("value",properties.c_str()); - } - } - }*/ - } - - void WriteSkeletonRecurse(XMLWriter& writer, IExportContext* context, const std::string& modelName, SkeletonData& skeletonData, int boneIndex, const std::string& name, const std::vector& bones, std::map, int>, int>& boneGeometryMap, std::vector& boneGeometries, int geometryFileIndex, int modelIndex, MaterialData& materialData, const std::map& materialMaterialMap, const std::vector& materials, IExportSource* source, ProgressRange& progressRange) - { - XMLWriter::Element nodeElement(writer, "node"); - nodeElement.Attribute("id", name); // The ID must be unique. - nodeElement.Attribute("name", name); // The name must not include model name as prefix, so it can match the skeleton. - - // Calculate the transforms for the bone and its parent. This could be made a lot simpler by using proper - // transforms in the skeleton data. - Matrix34 transform; - { - Matrix44 transforms[2]; - int boneIndices[2] = {boneIndex, skeletonData.GetBoneParentIndex(boneIndex)}; - for (int i = 0; i < 2; ++i) - { - transforms[i] = IDENTITY; - - if (boneIndices[i] >= 0) - { - Vec3 scaleParams; - skeletonData.GetScale((float*)&scaleParams, boneIndices[i]); - Matrix44 scale = Matrix33::CreateScale(scaleParams); - - Ang3 rotationParams; - skeletonData.GetRotation((float*)&rotationParams, boneIndices[i]); - Matrix44 rotation = Matrix33::CreateRotationXYZ(rotationParams); - - Vec3 translationParams; - skeletonData.GetTranslation((float*)&translationParams, boneIndices[i]); - Matrix44 translation(IDENTITY); - translation.SetTranslation(translationParams); - - transforms[i] = translation * (rotation * scale); - } - } - transform = Matrix34(transforms[1].GetInverted() * transforms[0]); - } - - Vec3 translation, scaling; - CryQuat orientation; - DecomposeTransform(translation, orientation, scaling, transform); - Ang3 rotation = Ang3::GetAnglesXYZ(orientation); - - // Write translation element. - { - XMLWriter::Element translateElement(writer, "translate"); - translateElement.Attribute("sid", "translation"); - translateElement.ContentArrayElement(translation[0]); - translateElement.ContentArrayElement(translation[1]); - translateElement.ContentArrayElement(translation[2]); - } - - // Write rotation elements. - for (int axisIndex = 0; axisIndex < 3; ++axisIndex) - { - XMLWriter::Element rotateElement(writer, "rotate"); - char sidBuffer[1024]; - sprintf(sidBuffer, "rotation_%c", 'z' - axisIndex); - rotateElement.Attribute("sid", sidBuffer); - rotateElement.ContentArrayElement(axisIndex == 2 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 1 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 0 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(rotation[2 - axisIndex] * 180.0f / 3.14159f); - } - - // Write scale elements - { - XMLWriter::Element scaleElement(writer, "scale"); - scaleElement.Attribute("sid", "scale"); - scaleElement.ContentArrayElement(scaling[0]); - scaleElement.ContentArrayElement(scaling[1]); - scaleElement.ContentArrayElement(scaling[2]); - } - - // If the node has geometry, write out the reference to it. - std::map, int>, int>::iterator boneGeometryMapPos = boneGeometryMap.find(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), boneIndex)); - if (boneGeometryMapPos != boneGeometryMap.end()) - { - const std::string& boneGeometryName = boneGeometries[(*boneGeometryMapPos).second].name; - XMLWriter::Element instanceGeometryElement(writer, "instance_geometry"); - instanceGeometryElement.Attribute("url", std::string("#") + boneGeometryName); - - BindBoneMaterials(writer, context, materialData, skeletonData, boneIndex, materialMaterialMap, materials, source); - } - - SHelperData dummyHelperData; - WriteExtraData(writer, dummyHelperData, skeletonData.GetBoneProperties(boneIndex)); - - int childIndexCount = skeletonData.GetChildCount(boneIndex); - float progressRangeSlice = 1.0f / (childIndexCount > 0 ? float(childIndexCount) : 1.0f); - for (int childIndexIndex = 0; childIndexIndex < childIndexCount; ++childIndexIndex) - { - int childIndex = skeletonData.GetChildIndex(boneIndex, childIndexIndex); - WriteSkeletonRecurse(writer, context, modelName, skeletonData, childIndex, bones[childIndex].name, bones, boneGeometryMap, boneGeometries, geometryFileIndex, modelIndex, materialData, materialMaterialMap, materials, source, ProgressRange(progressRange, progressRangeSlice)); - } - } - - void WritePhysSkeletonRecurse(XMLWriter& writer, const std::string& modelName, const SkeletonData& skeletonData, int boneIndex, const std::vector& bones, ProgressRange& progressRange, const Matrix34& physFrameTM, const Matrix34& parentTM) - { - Matrix34 currentPhysFrameTM = physFrameTM; - - // Output a node for the parent frame. - bool shouldWriteParentFrame = skeletonData.HasParentFrame(boneIndex); - XMLWriter::Element parentFrameElement(writer, "node", shouldWriteParentFrame); - if (shouldWriteParentFrame) - { - parentFrameElement.Attribute("id", bones[boneIndex].parentFrameName); // The ID must be unique. - parentFrameElement.Attribute("name", bones[boneIndex].parentFrameName); // The name must not include model name as prefix, so it can match the skeleton. - - // Write translation element. - float translation[3]; - skeletonData.GetParentFrameTranslation(boneIndex, translation); - { - XMLWriter::Element translateElement(writer, "translate"); - translateElement.Attribute("sid", "translation"); - translateElement.ContentArrayElement(translation[0]); - translateElement.ContentArrayElement(translation[1]); - translateElement.ContentArrayElement(translation[2]); - } - - // Write rotation elements. - float rotation[3]; - skeletonData.GetParentFrameRotation(boneIndex, rotation); - for (int axisIndex = 0; axisIndex < 3; ++axisIndex) - { - XMLWriter::Element rotateElement(writer, "rotate"); - char sidBuffer[1024]; - sprintf(sidBuffer, "rotation_%c", 'z' - axisIndex); - rotateElement.Attribute("sid", sidBuffer); - rotateElement.ContentArrayElement(axisIndex == 2 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 1 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 0 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(rotation[2 - axisIndex] * 180.0f / 3.14159f); - } - - // Write scale elements - float scaling[3]; - skeletonData.GetParentFrameScale(boneIndex, scaling); - { - XMLWriter::Element scaleElement(writer, "scale"); - scaleElement.Attribute("sid", "scale"); - scaleElement.ContentArrayElement(scaling[0]); - scaleElement.ContentArrayElement(scaling[1]); - scaleElement.ContentArrayElement(scaling[2]); - } - - Matrix34 tm(IDENTITY); - Matrix34 translationTM(IDENTITY); - translationTM.SetTranslation(Vec3(translation[0], translation[1], translation[2])); - Matrix34 rotationTM = Matrix33::CreateRotationXYZ(Ang3(rotation[0], rotation[1], rotation[2])); - Matrix34 scaleTM = Matrix33::CreateScale(Vec3(scaling[0], scaling[1], scaling[2])); - Matrix34 transform = translationTM * (rotationTM * scaleTM); - - currentPhysFrameTM = transform * currentPhysFrameTM; - } - - Matrix34 worldTM; - { - float translation[3]; - skeletonData.GetTranslation(translation, boneIndex); - float rotation[3]; - skeletonData.GetRotation(rotation, boneIndex); - float scaling[3]; - skeletonData.GetScale(scaling, boneIndex); - Matrix34 tm(IDENTITY); - Matrix34 translationTM(IDENTITY); - translationTM.SetTranslation(Vec3(translation[0], translation[1], translation[2])); - Matrix34 rotationTM = Matrix33::CreateRotationXYZ(Ang3(rotation[0], rotation[1], rotation[2])); - Matrix34 scaleTM = Matrix33::CreateScale(Vec3(scaling[0], scaling[1], scaling[2])); - worldTM = translationTM * (rotationTM * scaleTM); - } - Matrix34 transform = parentTM.GetInverted() * worldTM; - - XMLWriter::Element nodeElement(writer, "node", skeletonData.GetPhysicalized(boneIndex)); - if (skeletonData.GetPhysicalized(boneIndex)) - { - Matrix34 physTM = currentPhysFrameTM.GetInverted() * worldTM; - Vec3 translation, scaling; - CryQuat orientation; - DecomposeTransform(translation, orientation, scaling, physTM); - Ang3 rotation = Ang3::GetAnglesXYZ(orientation); - - nodeElement.Attribute("id", bones[boneIndex].physName); // The ID must be unique. - nodeElement.Attribute("name", bones[boneIndex].physName); // The name must not include model name as prefix, so it can match the skeleton. - - // Write translation element. - { - XMLWriter::Element translateElement(writer, "translate"); - translateElement.Attribute("sid", "translation"); - translateElement.ContentArrayElement(translation[0]); - translateElement.ContentArrayElement(translation[1]); - translateElement.ContentArrayElement(translation[2]); - } - - // Write rotation elements. - for (int axisIndex = 0; axisIndex < 3; ++axisIndex) - { - XMLWriter::Element rotateElement(writer, "rotate"); - char sidBuffer[1024]; - sprintf(sidBuffer, "rotation_%c", 'z' - axisIndex); - rotateElement.Attribute("sid", sidBuffer); - rotateElement.ContentArrayElement(axisIndex == 2 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 1 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 0 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(rotation[2 - axisIndex] * 180.0f / 3.14159f); - } - - // Write scale elements - { - XMLWriter::Element scaleElement(writer, "scale"); - scaleElement.Attribute("sid", "scale"); - scaleElement.ContentArrayElement(scaling[0]); - scaleElement.ContentArrayElement(scaling[1]); - scaleElement.ContentArrayElement(scaling[2]); - } - - currentPhysFrameTM = worldTM; - } - - SHelperData dummyHelperData; - WriteExtraData(writer, dummyHelperData, skeletonData.GetBoneGeomProperties(boneIndex)); - - int childIndexCount = skeletonData.GetChildCount(boneIndex); - float progressRangeSlice = 1.0f / (childIndexCount > 0 ? float(childIndexCount) : 1.0f); - for (int childIndexIndex = 0; childIndexIndex < childIndexCount; ++childIndexIndex) - { - int childIndex = skeletonData.GetChildIndex(boneIndex, childIndexIndex); - WritePhysSkeletonRecurse(writer, modelName, skeletonData, childIndex, bones, ProgressRange(progressRange, progressRangeSlice), currentPhysFrameTM, worldTM); - } - } - - void WriteGeometryData(XMLWriter& writer, const std::string& id, const std::string& name, GeometryData& geometryData, MaterialData& materialData, std::map& materialMaterialMap, std::vector& materials) - { - XMLWriter::Element geometryElement(writer, "geometry"); - geometryElement.Attribute("id", id); - if (!name.empty()) - { - geometryElement.Attribute("name", name); - } - XMLWriter::Element meshElement(writer, "mesh"); - - // Write out the positions. - std::string posSourceName = id + "-pos"; - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", posSourceName); - - std::string arrayName = posSourceName + "-array"; - { - XMLWriter::Element arrayElement(writer, "float_array"); - arrayElement.Attribute("id", arrayName); - arrayElement.Attribute("count", int(geometryData.positions.size()) * 3); - for (int positionIndex = 0, positionCount = int(geometryData.positions.size()); positionIndex < positionCount; ++positionIndex) - { - arrayElement.ContentArrayElement(geometryData.positions[positionIndex].x); - arrayElement.ContentArrayElement(geometryData.positions[positionIndex].y); - arrayElement.ContentArrayElement(geometryData.positions[positionIndex].z); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", std::string("#") + arrayName); - accessorElement.Attribute("count", int(geometryData.positions.size())); - accessorElement.Attribute("stride", 3); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "X"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "Y"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "Z"); - paramElement.Attribute("type", "float"); - } - } - - // Write out the normals. - std::string normalSourceName = id + "-normal"; - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", normalSourceName); - - std::string arrayName = normalSourceName + "-array"; - { - XMLWriter::Element arrayElement(writer, "float_array"); - arrayElement.Attribute("id", arrayName); - arrayElement.Attribute("count", int(geometryData.normals.size()) * 3); - for (int normalIndex = 0, normalCount = int(geometryData.normals.size()); normalIndex < normalCount; ++normalIndex) - { - arrayElement.ContentArrayElement(geometryData.normals[normalIndex].x); - arrayElement.ContentArrayElement(geometryData.normals[normalIndex].y); - arrayElement.ContentArrayElement(geometryData.normals[normalIndex].z); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", std::string("#") + arrayName); - accessorElement.Attribute("count", int(geometryData.normals.size())); - accessorElement.Attribute("stride", 3); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "X"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "Y"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "Z"); - paramElement.Attribute("type", "float"); - } - } - - // Write out the texture coordinates. - std::string textureCoordinateSourceName = id + "-uvs"; - if (!geometryData.textureCoordinates.empty()) - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", textureCoordinateSourceName); - - std::string arrayName = textureCoordinateSourceName + "-array"; - { - XMLWriter::Element arrayElement(writer, "float_array"); - arrayElement.Attribute("id", arrayName); - arrayElement.Attribute("count", int(geometryData.textureCoordinates.size()) * 2); - for (int textureCoordinateIndex = 0, textureCoordinateCount = int(geometryData.textureCoordinates.size()); textureCoordinateIndex < textureCoordinateCount; ++textureCoordinateIndex) - { - arrayElement.ContentArrayElement(geometryData.textureCoordinates[textureCoordinateIndex].u); - arrayElement.ContentArrayElement(geometryData.textureCoordinates[textureCoordinateIndex].v); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", std::string("#") + arrayName); - accessorElement.Attribute("count", int(geometryData.textureCoordinates.size())); - accessorElement.Attribute("stride", 2); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "S"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "T"); - paramElement.Attribute("type", "float"); - } - } - - // Write out the vertex colors. - std::string vertexColorSourceName = id + "-vcol"; - if (!geometryData.vertexColors.empty()) - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", vertexColorSourceName); - - std::string arrayName = vertexColorSourceName + "-array"; - { - XMLWriter::Element arrayElement(writer, "float_array"); - arrayElement.Attribute("id", arrayName); - arrayElement.Attribute("count", int(geometryData.vertexColors.size()) * 4); - for (int vertexColorIndex = 0, vertexColorCount = int(geometryData.vertexColors.size()); vertexColorIndex < vertexColorCount; ++vertexColorIndex) - { - arrayElement.ContentArrayElement(geometryData.vertexColors[vertexColorIndex].r); - arrayElement.ContentArrayElement(geometryData.vertexColors[vertexColorIndex].g); - arrayElement.ContentArrayElement(geometryData.vertexColors[vertexColorIndex].b); - arrayElement.ContentArrayElement(geometryData.vertexColors[vertexColorIndex].a); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", std::string("#") + arrayName); - accessorElement.Attribute("count", int(geometryData.vertexColors.size())); - accessorElement.Attribute("stride", 4); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "R"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "G"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "B"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "A"); - paramElement.Attribute("type", "float"); - } - } - - // Write out the vertex elements. - std::string vertexName = id + "-vtx"; - { - XMLWriter::Element vertexElement(writer, "vertices"); - vertexElement.Attribute("id", vertexName); - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "POSITION"); - inputElement.Attribute("source", std::string("#") + posSourceName); - } - - // Sort the triangles by material. - std::vector > polygonsByMaterial(materialData.GetMaterialCount() + 1); - for (int polygonIndex = 0, polygonCount = int(geometryData.polygons.size()); polygonIndex < polygonCount; ++polygonIndex) - { - polygonsByMaterial[geometryData.polygons[polygonIndex].mtlID + 1].push_back(geometryData.polygons[polygonIndex]); - } - - // Write out the triangles. - for (int materialIndex = -1, materialCount = materialData.GetMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - if (!polygonsByMaterial[materialIndex + 1].empty()) - { - std::map::iterator materialMapPos = materialMaterialMap.find(materialIndex); - int materialEntryIndex = (materialMapPos != materialMaterialMap.end() ? (*materialMapPos).second : -1); - - std::vector& polygons = polygonsByMaterial[materialIndex + 1]; - - XMLWriter::Element trianglesElement(writer, "triangles"); - trianglesElement.Attribute("count", int(polygons.size())); - if (materialEntryIndex >= 0) - { - trianglesElement.Attribute("material", materials[materialEntryIndex].name); - } - int offset = 0; - bool hasPositions = false; - if (!geometryData.positions.empty()) - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "VERTEX"); - inputElement.Attribute("source", std::string("#") + vertexName); - inputElement.Attribute("offset", offset++); - hasPositions = true; - } - bool hasNormals = false; - if (!geometryData.normals.empty()) - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "NORMAL"); - inputElement.Attribute("source", std::string("#") + normalSourceName); - inputElement.Attribute("offset", offset++); - hasNormals = true; - } - bool hasUVs = false; - if (!geometryData.textureCoordinates.empty()) - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "TEXCOORD"); - inputElement.Attribute("source", std::string("#") + textureCoordinateSourceName); - inputElement.Attribute("offset", offset++); - hasUVs = true; - } - bool hasColors = false; - if (!geometryData.vertexColors.empty()) - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "COLOR"); - inputElement.Attribute("source", std::string("#") + vertexColorSourceName); - inputElement.Attribute("offset", offset++); - hasColors = true; - } - - XMLWriter::Element pElement(writer, "p"); - for (int polygonIndex = 0, polygonCount = int(polygons.size()); polygonIndex < polygonCount; ++polygonIndex) - { - for (int vertexIndex = 0; vertexIndex < 3; ++vertexIndex) - { - if (hasPositions && polygons[polygonIndex].v[vertexIndex].positionIndex >= 0) - { - pElement.ContentArrayElement(polygons[polygonIndex].v[vertexIndex].positionIndex); - } - if (hasNormals && polygons[polygonIndex].v[vertexIndex].normalIndex >= 0) - { - pElement.ContentArrayElement(polygons[polygonIndex].v[vertexIndex].normalIndex); - } - if (hasUVs && polygons[polygonIndex].v[vertexIndex].textureCoordinateIndex >= 0) - { - pElement.ContentArrayElement(polygons[polygonIndex].v[vertexIndex].textureCoordinateIndex); - } - if (hasColors && polygons[polygonIndex].v[vertexIndex].vertexColorIndex >= 0) - { - pElement.ContentArrayElement(polygons[polygonIndex].v[vertexIndex].vertexColorIndex); - } - } - } - } - } - } - - bool WriteGeometries(IExportContext* context, XMLWriter& writer, std::vector& geometries, GeometryFileData& geometryFileData, const std::vector& modelData, MorphDataMap& morphData, MaterialData& materialData, std::vector& materials, std::map& materialMaterialMap, SkeletonDataMap& skeletonData, std::vector& boneGeometries, std::map, int>, int>& boneGeometryMap, std::map, int>, int>& morphGeometryMap, std::vector& morphGeometries, IExportSource* source, ProgressRange& progressRange) - { - XMLWriter::Element libraryGeometriesElement(writer, "library_geometries"); - - // Loop through all the geometries. - for (int geometryIndex = 0, geometryCount = int(geometries.size()); geometryIndex < geometryCount; ++geometryIndex) - { - GeometryEntry& geometryEntry = geometries[geometryIndex]; - - // Read in the geometry data. - GeometryData geometryData; - bool ok = source->ReadGeometry(context, &geometryData, &modelData[geometryEntry.geometryFileIndex], &materialData, geometryEntry.modelIndex); - if (!ok) - { - return false; - } - - WriteGeometryData(writer, geometryEntry.name, "", geometryData, materialData, materialMaterialMap, materials); - } - - // Loop through all the bone geometries. - for (int boneGeometryIndex = 0, boneGeometryCount = int(boneGeometries.size()); boneGeometryIndex < boneGeometryCount; ++boneGeometryIndex) - { - BoneGeometryEntry& boneGeometryEntry = boneGeometries[boneGeometryIndex]; - - GeometryData geometryData; - SkeletonDataMap::iterator skeletonDataPos = skeletonData.find(std::make_pair(boneGeometryEntry.geometryFileIndex, boneGeometryEntry.modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - source->ReadBoneGeometry(context, &geometryData, &(*skeletonDataPos).second, boneGeometryEntry.boneIndex, &materialData); - } - - WriteGeometryData(writer, boneGeometryEntry.name, "", geometryData, materialData, materialMaterialMap, materials); - } - - // Loop through all the morph geometries. - for (int morphGeometryIndex = 0, morphGeometryCount = int(morphGeometries.size()); morphGeometryIndex < morphGeometryCount; ++morphGeometryIndex) - { - MorphGeometryEntry& morphGeometryEntry = morphGeometries[morphGeometryIndex]; - - GeometryData geometryData; - MorphDataMap::iterator morphDataPos = morphData.find(std::make_pair(morphGeometryEntry.geometryFileIndex, morphGeometryEntry.modelIndex)); - if (morphDataPos != morphData.end()) - { - source->ReadMorphGeometry(context, &geometryData, &modelData[morphGeometryEntry.geometryFileIndex], morphGeometryEntry.modelIndex, &(*morphDataPos).second, morphGeometryEntry.morphIndex, &materialData); - } - - WriteGeometryData(writer, morphGeometryEntry.name, morphGeometryEntry.morphName, geometryData, materialData, materialMaterialMap, materials); - } - - return true; - } - - void WriteExportNodeProperties(const IExportSource& source, XMLWriter& writer, const char* geomFilename, const IGeometryFileData::SProperties& properties) - { - XMLWriter::Element elem(writer, "extra"); - { - XMLWriter::Element elem(writer, "technique"); - elem.Attribute("profile", "CryEngine"); - { - std::string const filetypeStr = ExportFileTypeHelpers::CryFileTypeToString(properties.filetypeInt); - std::string props = std::string("fileType=") + filetypeStr; - if (properties.bDoNotMerge) - { - props += std::string("\r\n") + "DoNotMerge"; - } - if (properties.bUseCustomNormals) - { - props += std::string("\r\n") + "UseCustomNormals"; - } - if (properties.filetypeInt == CRY_FILE_TYPE_SKIN && properties.b8WeightsPerVertex) - { - props += std::string("\r\n") + "EightWeightsPerVertex"; - } - if (properties.bUseF32VertexFormat) - { - props += std::string("\r\n") + "UseF32VertexFormat"; - } - - props += std::string("\r\n") + std::string("CustomExportPath=") + properties.customExportPath; - XMLWriter::Element elem(writer, "properties"); - elem.Content(props); - } - } - - // Write special properties for importing to the XSI. - { - XMLWriter::Element elem(writer, "technique"); - elem.Attribute("profile", "XSI"); - { - XMLWriter::Element elem(writer, "XSI_CustomPSet"); - elem.Attribute("name", "ExportProperties"); - { - XMLWriter::Element elem(writer, "propagation"); - elem.Content("NODE"); - } - { - XMLWriter::Element elem(writer, "type"); - elem.Content("CryExportNodeProperties"); - } - { - XMLWriter::Element elem(writer, "XSI_Parameter"); - elem.Attribute("id", "Filetype"); - elem.Attribute("type", "Integer"); - elem.Attribute("value", properties.filetypeInt); - } - { - XMLWriter::Element elem(writer, "XSI_Parameter"); - elem.Attribute("id", "Filename"); - elem.Attribute("type", "Text"); - elem.Attribute("value", geomFilename); - } - { - XMLWriter::Element elem(writer, "XSI_Parameter"); - elem.Attribute("id", "Exportable"); - elem.Attribute("type", "Boolean"); - elem.Attribute("value", "1"); - } - { - XMLWriter::Element elem(writer, "XSI_Parameter"); - elem.Attribute("id", "MergeObjects"); - elem.Attribute("type", "Boolean"); - elem.Attribute("value", (!properties.bDoNotMerge)); - } - } - } - } - - - void WriteHierarchyRecurse( - XMLWriter& writer, - IExportContext* context, - int geometryFileIndex, - MaterialData& materialData, - const std::map& materialMaterialMap, - const std::vector& materials, - const ModelData& modelData, - int const modelIndex, - std::map, int>& modelGeometryMap, - std::vector& geometries, - std::map, int>& modelControllerMap, - std::vector& controllers, - std::map, int>& modelMorphControllerMap, - std::vector& morphControllers, - IExportSource* source, - ProgressRange& progressRange) - { - XMLWriter::Element nodeElement(writer, "node"); - nodeElement.Attribute("id", modelData.GetModelName(modelIndex)); // The ID must be unique. - - { - float translation[3]; - float rotation[3]; - float scaling[3]; - modelData.GetTranslationRotationScale(modelIndex, translation, rotation, scaling); - - // Write translation element. - { - XMLWriter::Element translateElement(writer, "translate"); - translateElement.Attribute("sid", "translation"); - translateElement.ContentArrayElement(translation[0]); - translateElement.ContentArrayElement(translation[1]); - translateElement.ContentArrayElement(translation[2]); - } - - // Write rotation elements. - for (int axisIndex = 0; axisIndex < 3; ++axisIndex) - { - XMLWriter::Element rotateElement(writer, "rotate"); - char sidBuffer[1024]; - sprintf(sidBuffer, "rotation_%c", 'z' - axisIndex); - rotateElement.Attribute("sid", sidBuffer); - rotateElement.ContentArrayElement(axisIndex == 2 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 1 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 0 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(rotation[2 - axisIndex] * 180.0f / 3.14159f); - } - - // Write scale elements - { - XMLWriter::Element scaleElement(writer, "scale"); - scaleElement.Attribute("sid", "scale"); - scaleElement.ContentArrayElement(scaling[0]); - scaleElement.ContentArrayElement(scaling[1]); - scaleElement.ContentArrayElement(scaling[2]); - } - } - - // If the node has a controller, write out the reference to it. - std::map, int>::iterator modelControllerMapPos = modelControllerMap.find(std::make_pair(geometryFileIndex, modelIndex)); - std::map, int>::iterator modelMorphControllerMapPos = modelMorphControllerMap.find(std::make_pair(geometryFileIndex, modelIndex)); - if (modelControllerMapPos != modelControllerMap.end()) - { - const std::string& controllerName = controllers[(*modelControllerMapPos).second].name; - XMLWriter::Element instanceControllerElement(writer, "instance_controller"); - instanceControllerElement.Attribute("url", "#" + controllerName); - - BindMaterials(writer, context, materialData, modelData, modelIndex, materialMaterialMap, materials, source); - } - else if (modelMorphControllerMapPos != modelMorphControllerMap.end()) - { - const std::string& controllerName = morphControllers[(*modelMorphControllerMapPos).second].name; - XMLWriter::Element instanceControllerElement(writer, "instance_controller"); - instanceControllerElement.Attribute("url", "#" + controllerName); - - BindMaterials(writer, context, materialData, modelData, modelIndex, materialMaterialMap, materials, source); - } - else - { - // If the node has geometry, write out the reference to it. - std::map, int>::iterator modelGeometryMapPos = modelGeometryMap.find(std::make_pair(geometryFileIndex, modelIndex)); - if (modelGeometryMapPos != modelGeometryMap.end()) - { - const std::string& geometryName = geometries[(*modelGeometryMapPos).second].name; - XMLWriter::Element instanceGeometryElement(writer, "instance_geometry"); - instanceGeometryElement.Attribute("url", std::string("#") + geometryName); - - BindMaterials(writer, context, materialData, modelData, modelIndex, materialMaterialMap, materials, source); - } - } - - // Recurse to the child nodes. - int childIndexCount = modelData.GetChildCount(modelIndex); - float progressRangeSlice = 1.0f / (childIndexCount > 0 ? float(childIndexCount) : 1.0f); - for (int childIndexIndex = 0; childIndexIndex < childIndexCount; ++childIndexIndex) - { - int childIndex = modelData.GetChildIndex(modelIndex, childIndexIndex); - WriteHierarchyRecurse(writer, context, geometryFileIndex, materialData, materialMaterialMap, materials, modelData, childIndex, modelGeometryMap, geometries, modelControllerMap, controllers, modelMorphControllerMap, morphControllers, source, ProgressRange(progressRange, progressRangeSlice)); - } - - // Write properties, HelperData - WriteExtraData(writer, modelData.GetHelperData(modelIndex), modelData.GetProperties(modelIndex)); - } - - void WriteHierarchy( - XMLWriter& writer, - IExportContext* context, - const GeometryFileData& geometryFileData, - MaterialData& materialData, - const std::map& materialMaterialMap, - const std::vector& materials, - const std::vector& modelData, - SkeletonDataMap& skeletonData, - std::map, int>& modelGeometryMap, - std::vector& geometries, - std::map, int>& modelControllerMap, - std::vector& controllers, - BoneDataMap& boneDataMap, - std::map, int>, int>& boneGeometryMap, - std::vector& boneGeometries, - std::map, int>& modelMorphControllerMap, - std::vector& morphControllers, - IExportSource* source, - ProgressRange& progressRange) - { - XMLWriter::Element libraryVisualScenesElement(writer, "library_visual_scenes"); - XMLWriter::Element visualSceneElement(writer, "visual_scene"); - visualSceneElement.Attribute("id", "visual_scene_0"); - visualSceneElement.Attribute("name", "untitled"); - - int geometryFileCount = geometryFileData.GetGeometryFileCount(); - float geometryFileRangeSlice = 1.0f / (geometryFileCount > 0 ? float(geometryFileCount) : 1.0f); - for (int geometryFileIndex = 0; geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - ProgressRange geometryFileRange(progressRange, geometryFileRangeSlice); - - // Make sure to write out a LumberyardExportNode - this is expected by the RC. - std::string nodeName; - - nodeName = geometryFileData.GetGeometryFileName(geometryFileIndex); - XMLWriter::Element nodeElement(writer, "node"); - nodeElement.Attribute("id", nodeName); - nodeElement.Attribute(g_LumberyardExportNodeTag, true); - - // Write translation element. - { - XMLWriter::Element translateElement(writer, "translate"); - translateElement.Attribute("sid", "translation"); - translateElement.Content("0 0 0"); - } - - // Write rotation elements. - { - XMLWriter::Element rotateElement(writer, "rotate"); - rotateElement.Attribute("sid", "rotation_z"); - rotateElement.Content("0 0 1 0"); - } - - { - XMLWriter::Element rotateElement(writer, "rotate"); - rotateElement.Attribute("sid", "rotation_y"); - rotateElement.Content("0 1 0 0"); - } - - { - XMLWriter::Element rotateElement(writer, "rotate"); - rotateElement.Attribute("sid", "rotation_x"); - rotateElement.Content("1 0 0 0"); - } - - // Write scale elements - { - XMLWriter::Element scaleElement(writer, "scale"); - scaleElement.Attribute("sid", "scale"); - scaleElement.Content("1 1 1"); - } - - { - ProgressRange modelProgressRange(geometryFileRange, 0.5f); - int rootIndexCount = modelData[geometryFileIndex].GetRootCount(); - float progressRangeSlice = 1.0f / (rootIndexCount > 0 ? float(rootIndexCount) : 1.0f); - for (int rootIndexIndex = 0; rootIndexIndex < rootIndexCount; ++rootIndexIndex) - { - int rootModelIndex = modelData[geometryFileIndex].GetRootIndex(rootIndexIndex); - WriteHierarchyRecurse(writer, context, geometryFileIndex, materialData, materialMaterialMap, materials, modelData[geometryFileIndex], rootModelIndex, modelGeometryMap, geometries, modelControllerMap, controllers, modelMorphControllerMap, morphControllers, source, ProgressRange(modelProgressRange, progressRangeSlice)); - } - } - - { - ProgressRange skeletonProgressRange(geometryFileRange, 0.5f); - //write the skeleton for the first model in the geometry file only - //for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - if (modelData[geometryFileIndex].GetModelCount() > 0) - { - int modelIndex = 0; - int modelCount = 1; - SkeletonDataMap::iterator skeletonDataPos = skeletonData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - SkeletonData& skeletonDataInstance = (*skeletonDataPos).second; - const std::vector& bones = (*boneDataMap.find(std::make_pair(geometryFileIndex, modelIndex))).second; - int rootIndexCount = skeletonDataInstance.GetRootCount(); - float progressRangeSlice = 1.0f / ((rootIndexCount > 0 ? float(rootIndexCount) : 1.0f) * modelCount); - for (int rootIndexIndex = 0; rootIndexIndex < rootIndexCount; ++rootIndexIndex) - { - int rootBoneIndex = skeletonDataInstance.GetRootIndex(rootIndexIndex); - WriteSkeletonRecurse(writer, context, geometryFileData.GetGeometryFileName(geometryFileIndex), skeletonDataInstance, rootBoneIndex, bones[rootBoneIndex].name, bones, boneGeometryMap, boneGeometries, geometryFileIndex, modelIndex, materialData, materialMaterialMap, materials, source, ProgressRange(skeletonProgressRange, progressRangeSlice * 0.5f)); - WritePhysSkeletonRecurse(writer, geometryFileData.GetGeometryFileName(geometryFileIndex), skeletonDataInstance, rootBoneIndex, bones, ProgressRange(skeletonProgressRange, progressRangeSlice * 0.5f), Matrix34(IDENTITY), Matrix34(IDENTITY)); - } - } - } - } - - // Write properties if they exist - WriteExportNodeProperties(*source, writer, geometryFileData.GetGeometryFileName(geometryFileIndex), geometryFileData.GetProperties(geometryFileIndex)); - } - } - - void WriteMetaData(IExportSource* pExportSource, XMLWriter& writer, ProgressRange& progressRange) - { - SExportMetaData metaData; - pExportSource->GetMetaData(metaData); - - XMLWriter::Element assetElement(writer, "asset"); - { - XMLWriter::Element contributorElement(writer, "contributor"); - contributorElement.Child("author", metaData.author); - contributorElement.Child("authoring_tool", metaData.authoring_tool); - contributorElement.Child("source_data", metaData.source_data); - } - - std::time_t time = std::time(0); - std::tm dateTime = *std::localtime(&time); - char scratchBuffer[1024]; - std::strftime(scratchBuffer, sizeof(scratchBuffer) / sizeof(scratchBuffer[0]), "%Y-%m-%dT%H:%M:%SZ", &dateTime); - assetElement.Child("created", scratchBuffer); - assetElement.Child("modified", scratchBuffer); - assetElement.Child("revision", metaData.revision); - { - XMLWriter::Element unitElement(writer, "unit"); - unitElement.Attribute("meter", metaData.fMeterUnit); - unitElement.Attribute("name", "meter"); - } - - switch (metaData.up_axis) - { - case SExportMetaData::X_UP: - assetElement.Child("up_axis", "X_UP"); - break; - case SExportMetaData::Y_UP: - assetElement.Child("up_axis", "Y_UP"); - break; - case SExportMetaData::Z_UP: - default: - assetElement.Child("up_axis", "Z_UP"); - break; - } - - int framesPerSecond = metaData.fFramesPerSecond <= 0.f ? 30 : static_cast(metaData.fFramesPerSecond); - sprintf_s(scratchBuffer, sizeof(scratchBuffer) / sizeof(scratchBuffer[0]), "%i", framesPerSecond); - XMLWriter::Element frameRateElement(writer, "framerate"); - frameRateElement.Attribute("fps", scratchBuffer); - } - - enum AnimationBoneParameter - { - AnimationBoneParameter_TransX, - AnimationBoneParameter_TransY, - AnimationBoneParameter_TransZ, - AnimationBoneParameter_RotX, - AnimationBoneParameter_RotY, - AnimationBoneParameter_RotZ, - AnimationBoneParameter_SclX, - AnimationBoneParameter_SclY, - AnimationBoneParameter_SclZ, - }; - const char* parameterStrings[] = { - "posx", - "posy", - "posz", - "rotx", - "roty", - "rotz", - "sclx", - "scly", - "sclz" - }; - const char* parameterTargetStrings[] = { - "translation.X", - "translation.Y", - "translation.Z", - "rotation_x.ANGLE", - "rotation_y.ANGLE", - "rotation_z.ANGLE", - "scale.X", - "scale.Y", - "scale.Z" - }; - struct AnimationBoneParameterEntry - { - std::string name; - int boneIndex; - AnimationBoneParameter parameter; - }; - struct AnimationEntry - { - std::string name; - int geometryFileIndex; - int modelIndex; - int animationIndex; - float start; - float stop; - std::vector parameters; - }; - void AddParametersRecursive(AnimationEntry& animation, AnimationData& animationData, const SkeletonData& skeletonData, int boneIndex, ProgressRange& progressRange) - { - for (AnimationBoneParameter parameter = AnimationBoneParameter_TransX; parameter <= AnimationBoneParameter_SclZ; parameter = AnimationBoneParameter(parameter + 1)) - { - animation.parameters.push_back(AnimationBoneParameterEntry()); - AnimationBoneParameterEntry& parameterEntry = animation.parameters.back(); - parameterEntry.boneIndex = boneIndex; - parameterEntry.parameter = parameter; - parameterEntry.name = animation.name + "-" + skeletonData.GetSafeName(boneIndex) + "_" + parameterStrings[parameter] + "-anim"; - - // Encode the flags as naming conventions. - unsigned modelFlags = animationData.GetModelFlags(boneIndex); - if (modelFlags & IAnimationData::ModelFlags_NoExport) - { - parameterEntry.name += "-NoExport"; - } - } - - int childIndexCount = skeletonData.GetChildCount(boneIndex); - float progressRangeSlice = 1.0f / (childIndexCount > 0 ? float(childIndexCount) : 1.0f); - for (int childIndexIndex = 0; childIndexIndex < childIndexCount; ++childIndexIndex) - { - AddParametersRecursive(animation, animationData, skeletonData, skeletonData.GetChildIndex(boneIndex, childIndexIndex), ProgressRange(progressRange, progressRangeSlice)); - } - } - - void AddParametersForNoSkeleton(AnimationEntry& animation, int modelIndex, const std::string& modelName, AnimationBoneParameter whichParameter) - { - for (AnimationBoneParameter parameter = whichParameter; parameter < whichParameter + 3; parameter = AnimationBoneParameter(parameter + 1)) - { - animation.parameters.push_back(AnimationBoneParameterEntry()); - AnimationBoneParameterEntry& parameterEntry = animation.parameters.back(); - parameterEntry.boneIndex = modelIndex; - parameterEntry.parameter = parameter; - parameterEntry.name = animation.name + "-" + modelName + "_" + parameterStrings[parameter] + "-anim"; - } - } - - void AddAnimationEntry(std::vector& animations, int animationIndex, int geometryFileIndex, int modelIndex, IExportSource* source, GeometryFileData& geometryFileData) - { - animations.push_back(AnimationEntry()); - AnimationEntry& animation = animations.back(); - animation.animationIndex = animationIndex; - animation.geometryFileIndex = geometryFileIndex; - animation.modelIndex = modelIndex; - - std::string safeAnimationName = source->GetAnimationName(&geometryFileData, geometryFileIndex, animationIndex); - std::replace(safeAnimationName.begin(), safeAnimationName.end(), ' ', '_'); - animation.name = safeAnimationName + std::string("-") + geometryFileData.GetGeometryFileName(geometryFileIndex); - source->GetAnimationTimeSpan(animation.start, animation.stop, animationIndex); - } - - void GenerateAnimationList(IExportContext* context, std::vector& animations, GeometryFileData& geometryFileData, const std::vector& modelData, SkeletonDataMap& skeletonData, IExportSource* source, ProgressRange& progressRange) - { - int geometryFileCount = geometryFileData.GetGeometryFileCount(); - float geometryFileProgressRangeSlice = 1.0f / (geometryFileCount > 0 ? float(geometryFileCount) : 1.0f); - for (int geometryFileIndex = 0; geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - ProgressRange geometryFileProgressRange(progressRange, geometryFileProgressRangeSlice); - - int modelCount = modelData[geometryFileIndex].GetModelCount(); - float modelProgressRangeSlice = 1.0f / (modelCount > 0 ? float(modelCount) : 1.0f); - - int animationCount = source->GetAnimationCount(); - float animProgressRangeSlice = 1.0f / (animationCount > 0 ? float(animationCount) : 1.0f); - for (int animationIndex = 0; animationIndex < animationCount; ++animationIndex) - { - ProgressRange animationProgressRange(geometryFileProgressRange, animProgressRangeSlice); - - if (skeletonData.empty()) // Non-skeletal mesh - { - AddAnimationEntry(animations, animationIndex, geometryFileIndex, -1, source, geometryFileData); - } - else // Skeletal mesh - { - AddAnimationEntry(animations, animationIndex, geometryFileIndex, 0, source, geometryFileData); - } - AnimationEntry& animation = animations.back(); - for (int modelIndex = 0; modelIndex < modelCount; ++modelIndex) - { - ProgressRange modelProgressRange(animationProgressRange, modelProgressRangeSlice); - - if (skeletonData.empty()) // Non-skeletal mesh - { - bool hasPos = source->HasValidPosController(&modelData[geometryFileIndex], modelIndex); - bool hasRot = source->HasValidRotController(&modelData[geometryFileIndex], modelIndex); - bool hasScl = source->HasValidSclController(&modelData[geometryFileIndex], modelIndex); - if (hasPos || hasRot || hasScl) - { - std::string modelName = modelData[geometryFileIndex].GetModelName(modelIndex); - std::replace_if(modelName.begin(), modelName.end(), std::isspace, '_'); - if (hasPos) - { - AddParametersForNoSkeleton(animation, modelIndex, modelName, - AnimationBoneParameter_TransX); - } - if (hasRot) - { - AddParametersForNoSkeleton(animation, modelIndex, modelName, - AnimationBoneParameter_RotX); - } - if (hasScl) - { - AddParametersForNoSkeleton(animation, modelIndex, modelName, - AnimationBoneParameter_SclX); - } - } - } - else // Skeletal mesh - { - ProgressRange animationProgressRange(modelProgressRange, animProgressRangeSlice); - - // Read the animation flags. - SkeletonDataMap::const_iterator skeletonDataPos = skeletonData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - const SkeletonData& skeletonDataInstance = (*skeletonDataPos).second; - float FPS = ExportGlobal::g_defaultFrameRate; // This is only used for reading flags, using the default since it will have no impact - AnimationData animationData(skeletonDataInstance.GetBoneCount(), FPS, 0); - source->ReadAnimationFlags(context, &animationData, &geometryFileData, &modelData[geometryFileIndex], modelIndex, &skeletonDataInstance, animationIndex); - - int rootIndexCount = skeletonDataInstance.GetRootCount(); - float rootProgressRangeSlice = 1.0f / (rootIndexCount > 0 ? float(rootIndexCount) : 1.0f); - for (int rootIndexIndex = 0; rootIndexIndex < rootIndexCount; ++rootIndexIndex) - { - ProgressRange rootProgressRange(animationProgressRange, rootProgressRangeSlice); - - int rootBoneIndex = skeletonDataInstance.GetRootIndex(rootIndexIndex); - - // Generate the list of animated parameters for this animation - by generating the names in one place, we can - // use them in both passes to refer to each other. - AddParametersRecursive(animation, animationData, skeletonDataInstance, rootBoneIndex, rootProgressRange); - } - } - } - } - } - } - } - - void GenerateSkinControllerList(IExportContext* context, std::vector& controllers, std::map, int>& modelControllerMap, SkeletonDataMap& skeletonData, GeometryFileData& geometryFileData, const std::vector& modelData, std::map, int>& modelGeometryMap, std::vector& geometries, ProgressRange& progressRange) - { - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - std::map, int>::iterator modelGeometryPos = modelGeometryMap.find(std::make_pair(geometryFileIndex, modelIndex)); - SkeletonDataMap::const_iterator skeletonDataPos = skeletonData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (skeletonDataPos != skeletonData.end() && modelGeometryPos != modelGeometryMap.end()) - { - const SkeletonData& skeleton = (*skeletonDataPos).second; - - int controllerIndex = int(controllers.size()); - controllers.resize(controllers.size() + 1); - - SkinControllerEntry& entry = controllers.back(); - char nameBuf[1024]; - sprintf(nameBuf, "controller_%d", controllerIndex); - entry.name = nameBuf; - entry.geometryFileIndex = geometryFileIndex; - entry.modelIndex = modelIndex; - - modelControllerMap.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), controllerIndex)); - } - } - } - } - - void GenerateMorphControllerList(IExportContext* context, std::vector& morphControllers, std::map, int>& modelMorphControllerMap, MorphDataMap& morphData, GeometryFileData& geometryFileData, const std::vector& modelData, std::map, int>& modelGeometryMap, std::vector& geometries, ProgressRange& progressRange) - { - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - std::map, int>::iterator modelGeometryPos = modelGeometryMap.find(std::make_pair(geometryFileIndex, modelIndex)); - MorphDataMap::const_iterator morphDataPos = morphData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (morphDataPos != morphData.end() && modelGeometryPos != modelGeometryMap.end()) - { - int controllerIndex = int(morphControllers.size()); - morphControllers.resize(morphControllers.size() + 1); - - MorphControllerEntry& entry = morphControllers.back(); - char nameBuf[1024]; - sprintf(nameBuf, "morphController_%d", controllerIndex); - entry.name = nameBuf; - entry.geometryFileIndex = geometryFileIndex; - entry.modelIndex = modelIndex; - - modelMorphControllerMap.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), controllerIndex)); - } - } - } - } - - void GenerateEffectsList(IExportContext* context, std::map& materialFXMap, std::vector& effects, MaterialData& materialData) - { - for (int materialIndex = 0, materialCount = materialData.GetMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - std::string name; - - std::string mtlName = materialData.GetName(materialIndex); - assert(!mtlName.empty()); - - name = mtlName; - - char buffer[100]; - const int id = materialData.GetID(materialIndex); - assert(id >= 0); - sprintf(buffer, "-%d", id + 1); - - name += buffer; - - name += "-submat"; - - name += "-effect"; - - const int effectIndex = int(effects.size()); - effects.push_back(EffectsEntry(name)); - - materialFXMap.insert(std::make_pair(materialIndex, effectIndex)); - } - } - - void GenerateMaterialList(IExportContext* context, std::map& materialMaterialMap, std::map& materialFXMap, std::vector& effects, std::vector& materials, MaterialData& materialData) - { - for (int materialIndex = 0, materialCount = materialData.GetMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - // Material needs to be named according to a specific format - this communicates information to - // the resource compiler about the settings to be used for the material. - // Format is: ____[__...] - - std::string name; - - std::string mtlName = materialData.GetName(materialIndex); - assert(!mtlName.empty()); - - std::string mtlProperties = materialData.GetProperties(materialIndex); - assert(!mtlProperties.empty()); - - name = mtlName; - - char buffer[100]; - const int id = materialData.GetID(materialIndex); - assert(id >= 0); - sprintf(buffer, "__%d", id + 1); - - name += buffer; - - name += "__"; - name += materialData.GetSubMatName(materialIndex); - - name += mtlProperties; - - const int index = int(materials.size()); - materials.push_back(MaterialEntry(name)); - - materialMaterialMap.insert(std::make_pair(materialIndex, index)); - } - } - - void GenerateGeometryList(IExportContext* context, std::map, int>& modelGeometryMap, std::vector& geometries, GeometryFileData& geometryFileData, const std::vector& modelData) - { - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - if (modelData[geometryFileIndex].HasGeometry(modelIndex)) - { - std::string geometryName = std::string(geometryFileData.GetGeometryFileName(geometryFileIndex)) + "_" + modelData[geometryFileIndex].GetModelName(modelIndex) + "_geometry"; - int geometryIndex = int(geometries.size()); - geometries.push_back(GeometryEntry(geometryName, geometryFileIndex, modelIndex)); - modelGeometryMap.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), geometryIndex)); - } - } - } - } - - void GenerateBoneGeometryList(IExportContext* context, std::map, int>, int>& boneGeometryMap, std::vector& boneGeometries, GeometryFileData& geometryFileData, const std::vector& modelData, SkeletonDataMap& skeletonData) - { - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - SkeletonDataMap::iterator skeletonDataPos = skeletonData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - SkeletonData& modelSkeletonData = (*skeletonDataPos).second; - for (int boneIndex = 0, boneCount = modelSkeletonData.GetBoneCount(); boneIndex < boneCount; ++boneIndex) - { - if (modelSkeletonData.HasGeometry(boneIndex)) - { - std::string geometryName = std::string(geometryFileData.GetGeometryFileName(geometryFileIndex)) + "_" + modelData[geometryFileIndex].GetModelName(modelIndex) + "_" + modelSkeletonData.GetSafeName(boneIndex) + "_boneGeometry"; - int geometryIndex = int(boneGeometries.size()); - boneGeometries.push_back(BoneGeometryEntry(geometryName, geometryFileIndex, modelIndex, boneIndex)); - boneGeometryMap.insert(std::make_pair(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), boneIndex), geometryIndex)); - } - } - } - } - } - } - - void GenerateMorphGeometryList(IExportContext* context, std::map, int>, int>& morphGeometryMap, std::vector& morphGeometries, GeometryFileData& geometryFileData, const std::vector& modelData, MorphDataMap& morphData) - { - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - MorphDataMap::iterator morphDataPos = morphData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (morphDataPos != morphData.end()) - { - MorphData& modelMorphData = (*morphDataPos).second; - for (int morphIndex = 0, morphCount = modelMorphData.GetMorphCount(); morphIndex < morphCount; ++morphIndex) - { - std::string geometryName = std::string(geometryFileData.GetGeometryFileName(geometryFileIndex)) + "_" + modelData[geometryFileIndex].GetModelName(modelIndex) + "_" + modelMorphData.GetMorphFullName(morphIndex) + "_morphGeometry"; - int geometryIndex = int(morphGeometries.size()); - morphGeometries.push_back(MorphGeometryEntry(geometryName, modelMorphData.GetMorphName(morphIndex), geometryFileIndex, modelIndex, morphIndex)); - morphGeometryMap.insert(std::make_pair(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), morphIndex), geometryIndex)); - } - } - } - } - } - - void GenerateIKPropertyList(const SkeletonData& skeletonData, int boneIndex, std::vector >& propertyList) - { - // Loop through each axis, adding the properties for this axis to the list. - for (int axis = 0; axis < 3; ++axis) - { - // Add the limit properties for this axis. - const char* extremeNames[] = {"min", "max"}; - for (int extreme = 0; extreme < 2; ++extreme) - { - std::string key; - key += ('x' + axis); - key += extremeNames[extreme]; - if (skeletonData.HasLimit(boneIndex, ISkeletonData::Axis(axis), ISkeletonData::Limit(extreme))) - { - float limit = skeletonData.GetLimit(boneIndex, ISkeletonData::Axis(axis), ISkeletonData::Limit(extreme)); - char buffer[1024]; - sprintf(buffer, "%f", limit * 180.0f / 3.14159f); // Convert to degrees. - propertyList.push_back(std::make_pair(key, buffer)); - } - } - - // Add the remaining properties. - const char* propNames[] = {"damping", "springangle", "springtension"}; - typedef bool (SkeletonData::* HasMember)(int boneIndex, ISkeletonData::Axis axis) const; - typedef float (SkeletonData::* GetMember)(int boneIndex, ISkeletonData::Axis axis) const; - HasMember hasMembers[] = {&SkeletonData::HasAxisDamping, &SkeletonData::HasSpringAngle, &SkeletonData::HasSpringTension}; - GetMember getMembers[] = {&SkeletonData::GetAxisDamping, &SkeletonData::GetSpringAngle, &SkeletonData::GetSpringTension}; - for (int propIndex = 0; propIndex < 3; ++propIndex) - { - std::string key; - key += ('x' + axis); - key += propNames[propIndex]; - if ((skeletonData.*(hasMembers[propIndex]))(boneIndex, ISkeletonData::Axis(axis))) - { - float value = (skeletonData.*(getMembers[propIndex]))(boneIndex, ISkeletonData::Axis(axis)); - char buffer[1024]; - sprintf(buffer, "%f", value); - propertyList.push_back(std::make_pair(key, buffer)); - } - } - } - } - - void GenerateBoneList(IExportContext* context, BoneDataMap& boneDataMap, const SkeletonDataMap& skeletonData, const std::vector& modelData) - { - for (SkeletonDataMap::const_iterator skeletonDataPos = skeletonData.begin(), skeletonDataEnd = skeletonData.end(); skeletonDataPos != skeletonDataEnd; ++skeletonDataPos) - { - int geometryFileIndex = (*skeletonDataPos).first.first; - int modelIndex = (*skeletonDataPos).first.second; - const SkeletonData& skeleton = (*skeletonDataPos).second; - - BoneDataMap::iterator boneDataPos = boneDataMap.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), std::vector())).first; - std::vector& bones = (*boneDataPos).second; - bones.resize(skeleton.GetBoneCount()); - - std::string modelName = modelData[geometryFileIndex].GetModelName(modelIndex); - - for (int boneIndex = 0, boneCount = skeleton.GetBoneCount(); boneIndex < boneCount; ++boneIndex) - { - typedef std::string BoneEntry::* BoneNamePtr; - BoneNamePtr boneNames[3] = {&BoneEntry::name, &BoneEntry::physName, &BoneEntry::parentFrameName}; - const char* suffixes[3] = {"", " Phys", " Phys ParentFrame"}; - std::vector > properties[3]; - - // Add the IK properties to the phys bone. - GenerateIKPropertyList(skeleton, boneIndex, properties[1]); - - for (int nameIndex = 0; nameIndex < 3; ++nameIndex) - { - std::string unsafeName = skeleton.GetName(boneIndex); - unsafeName += suffixes[nameIndex]; - bool containsSpaces = (unsafeName.find_first_of(" \t") != std::string::npos); - std::string name = unsafeName; - if (containsSpaces) - { - std::string overrideName = unsafeName; - std::replace_if(overrideName.begin(), overrideName.end(), std::isspace, '*'); - - std::string safeName = unsafeName; - std::replace_if(safeName.begin(), safeName.end(), std::isspace, '_'); - - name = safeName + "%" + modelName + "%" + "--PRprops_name=" + overrideName; - - // Add all the properties. - for (size_t propIndex = 0, propCount = properties[nameIndex].size(); propIndex < propCount; ++propIndex) - { - name += "_" + properties[nameIndex][propIndex].first + "=" + properties[nameIndex][propIndex].second; - } - - name += "__"; - } - else - { - name = unsafeName + "%" + modelName + "%"; - } - (bones[boneIndex].*(boneNames[nameIndex])) = name; - } - } - } - } - - void WriteAnimationList(XMLWriter& writer, std::vector& animations, ProgressRange& progressRange) - { - // Write out all the animations in the library_animation_clips element. Each animation lists the name and timespan - // of the clip, and the controllers for each model parameter. The actual animation data is written out in a separate pass. - XMLWriter::Element libraryAnimationClipsElement(writer, "library_animation_clips"); - - for (int animationEntryIndex = 0, animationEntryCount = int(animations.size()); animationEntryIndex < animationEntryCount; ++animationEntryIndex) - { - AnimationEntry& entry = animations[animationEntryIndex]; - - XMLWriter::Element animationClipElement(writer, "animation_clip"); - animationClipElement.Attribute("start", entry.start); - animationClipElement.Attribute("end", entry.stop); - animationClipElement.Attribute("id", entry.name); - - // For each parameter write out a reference to the controller for that parameter. - for (int parameterEntryIndex = 0, parameterEntryCount = int(entry.parameters.size()); parameterEntryIndex < parameterEntryCount; ++parameterEntryIndex) - { - AnimationBoneParameterEntry& parameter = entry.parameters[parameterEntryIndex]; - - XMLWriter::Element instanceAnimationElement(writer, "instance_animation"); - instanceAnimationElement.Attribute("url", std::string("#") + parameter.name); - } - } - } - - void WriteAnimationTags( - ProgressRange& animationEntryProgressRange, - const AnimationEntry& entry, - const IAnimationData* animationData, - XMLWriter& writer, - const std::vector* pBones, - const IModelData* pModelData) - { - // Loop through all the parameters of all the models. - ProgressRange writeAnimProgressRange(animationEntryProgressRange, 0.5f); - for (int parameterEntryIndex = 0, parameterEntryCount = int(entry.parameters.size()); parameterEntryIndex < parameterEntryCount; ++parameterEntryIndex) - { - const AnimationBoneParameterEntry& parameter = entry.parameters[parameterEntryIndex]; - - int frameCount = 0; - switch (parameter.parameter) - { - case AnimationBoneParameter_TransX: - case AnimationBoneParameter_TransY: - case AnimationBoneParameter_TransZ: - frameCount = animationData->GetFrameCountPos(parameter.boneIndex); - break; - case AnimationBoneParameter_RotX: - case AnimationBoneParameter_RotY: - case AnimationBoneParameter_RotZ: - frameCount = animationData->GetFrameCountRot(parameter.boneIndex); - break; - case AnimationBoneParameter_SclX: - case AnimationBoneParameter_SclY: - case AnimationBoneParameter_SclZ: - frameCount = animationData->GetFrameCountScl(parameter.boneIndex); - break; - } - - XMLWriter::Element animationElement(writer, "animation"); - animationElement.Attribute("id", parameter.name); - - std::string inputID = parameter.name + "-input"; - std::string outputID = parameter.name + "-output"; - std::string interpID = parameter.name + "-interp"; - std::string tcbID = parameter.name + "-tcb"; - std::string easeinoutID = parameter.name + "-easeinout"; - - // Write out the times. - { - XMLWriter::Element inputElement(writer, "source"); - inputElement.Attribute("id", inputID); - std::string arrayID = inputID + "-array"; - { - XMLWriter::Element array(writer, "float_array"); - array.Attribute("count", frameCount); - array.Attribute("id", arrayID); - - float floatBuffer[24]; - int bufferCount = 0; - for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) - { - switch (parameter.parameter) - { - case AnimationBoneParameter_TransX: - case AnimationBoneParameter_TransY: - case AnimationBoneParameter_TransZ: - floatBuffer[bufferCount++] = animationData->GetFrameTimePos(parameter.boneIndex, frameIndex); - break; - case AnimationBoneParameter_RotX: - case AnimationBoneParameter_RotY: - case AnimationBoneParameter_RotZ: - floatBuffer[bufferCount++] = animationData->GetFrameTimeRot(parameter.boneIndex, frameIndex); - break; - case AnimationBoneParameter_SclX: - case AnimationBoneParameter_SclY: - case AnimationBoneParameter_SclZ: - floatBuffer[bufferCount++] = animationData->GetFrameTimeScl(parameter.boneIndex, frameIndex); - break; - } - if (bufferCount == 24) - { - array.ContentArrayFloat24(floatBuffer, bufferCount); - bufferCount = 0; - } - } - if (bufferCount > 0) - { - array.ContentArrayFloat24(floatBuffer, bufferCount); - bufferCount = 0; - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", arrayID); - accessorElement.Attribute("count", frameCount); - accessorElement.Attribute("stride", 1); - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "TIME"); - paramElement.Attribute("type", "float"); - } - - // Write out the values. - { - XMLWriter::Element inputElement(writer, "source"); - inputElement.Attribute("id", outputID); - std::string arrayID = outputID + "-array"; - { - XMLWriter::Element array(writer, "float_array"); - array.Attribute("count", frameCount); - array.Attribute("id", arrayID); - - float floatBuffer[24]; - int bufferCount = 0; - for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) - { - const float* translation, * rotation, * scale; - switch (parameter.parameter) - { - case AnimationBoneParameter_TransX: - case AnimationBoneParameter_TransY: - case AnimationBoneParameter_TransZ: - animationData->GetFrameDataPos(parameter.boneIndex, frameIndex, translation); - floatBuffer[bufferCount++] = translation[parameter.parameter - AnimationBoneParameter_TransX]; - break; - case AnimationBoneParameter_RotX: - case AnimationBoneParameter_RotY: - case AnimationBoneParameter_RotZ: - animationData->GetFrameDataRot(parameter.boneIndex, frameIndex, rotation); - floatBuffer[bufferCount++] = rotation[parameter.parameter - AnimationBoneParameter_RotX]; - break; - case AnimationBoneParameter_SclX: - case AnimationBoneParameter_SclY: - case AnimationBoneParameter_SclZ: - animationData->GetFrameDataScl(parameter.boneIndex, frameIndex, scale); - floatBuffer[bufferCount++] = scale[parameter.parameter - AnimationBoneParameter_SclX]; - break; - } - if (bufferCount == 24) - { - array.ContentArrayFloat24(floatBuffer, bufferCount); - bufferCount = 0; - } - } - if (bufferCount > 0) - { - array.ContentArrayFloat24(floatBuffer, bufferCount); - bufferCount = 0; - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", arrayID); - accessorElement.Attribute("count", frameCount); - accessorElement.Attribute("stride", 1); - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "VALUE"); - paramElement.Attribute("type", "float"); - } - - // Write out the interpolation method. - { - XMLWriter::Element inputElement(writer, "source"); - inputElement.Attribute("id", interpID); - std::string arrayID = interpID + "-array"; - { - XMLWriter::Element array(writer, "Name_array"); - array.Attribute("count", frameCount); - array.Attribute("id", arrayID); - for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) - { - array.WriteDirectText(" CONSTANT"); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", arrayID); - accessorElement.Attribute("count", frameCount); - accessorElement.Attribute("stride", 1); - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "INTERPOLATION"); - paramElement.Attribute("type", "Name"); - } - - if (pModelData) // only for the non-skeletal animation - { - // Write out the TCB values. - { - const int stride = 3; - XMLWriter::Element inputElement(writer, "source"); - inputElement.Attribute("id", tcbID); - std::string arrayID = tcbID + "-array"; - { - XMLWriter::Element array(writer, "float_array"); - array.Attribute("count", frameCount * stride); - array.Attribute("id", arrayID); - for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) - { - IAnimationData::TCB tcb; - switch (parameter.parameter) - { - case AnimationBoneParameter_TransX: - case AnimationBoneParameter_TransY: - case AnimationBoneParameter_TransZ: - animationData->GetFrameTCBPos(parameter.boneIndex, frameIndex, tcb); - break; - case AnimationBoneParameter_RotX: - case AnimationBoneParameter_RotY: - case AnimationBoneParameter_RotZ: - animationData->GetFrameTCBRot(parameter.boneIndex, frameIndex, tcb); - break; - case AnimationBoneParameter_SclX: - case AnimationBoneParameter_SclY: - case AnimationBoneParameter_SclZ: - animationData->GetFrameTCBScl(parameter.boneIndex, frameIndex, tcb); - break; - } - array.ContentArrayElement(tcb.tension); - array.ContentArrayElement(tcb.continuity); - array.ContentArrayElement(tcb.bias); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", arrayID); - accessorElement.Attribute("count", frameCount); - accessorElement.Attribute("stride", stride); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "TENSION"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "CONTINUITY"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "BIAS"); - paramElement.Attribute("type", "float"); - } - } - - // Write out the ease-in/-out values. - { - const int stride = 2; - XMLWriter::Element inputElement(writer, "source"); - inputElement.Attribute("id", easeinoutID); - std::string arrayID = easeinoutID + "-array"; - { - XMLWriter::Element array(writer, "float_array"); - array.Attribute("count", frameCount * stride); - array.Attribute("id", arrayID); - for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) - { - IAnimationData::Ease ease; - switch (parameter.parameter) - { - case AnimationBoneParameter_TransX: - case AnimationBoneParameter_TransY: - case AnimationBoneParameter_TransZ: - animationData->GetFrameEaseInOutPos(parameter.boneIndex, frameIndex, ease); - break; - case AnimationBoneParameter_RotX: - case AnimationBoneParameter_RotY: - case AnimationBoneParameter_RotZ: - animationData->GetFrameEaseInOutRot(parameter.boneIndex, frameIndex, ease); - break; - case AnimationBoneParameter_SclX: - case AnimationBoneParameter_SclY: - case AnimationBoneParameter_SclZ: - animationData->GetFrameEaseInOutScl(parameter.boneIndex, frameIndex, ease); - break; - } - array.ContentArrayElement(ease.in); - array.ContentArrayElement(ease.out); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", arrayID); - accessorElement.Attribute("count", frameCount); - accessorElement.Attribute("stride", stride); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "EASE_IN"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "EASE_OUT"); - paramElement.Attribute("type", "float"); - } - } - } - - // Write out the sampler element. - std::string samplerID = parameter.name + "-sampler"; - { - XMLWriter::Element samplerElement(writer, "sampler"); - samplerElement.Attribute("id", samplerID); - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "INPUT"); - inputElement.Attribute("source", std::string("#") + inputID); - } - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "OUTPUT"); - inputElement.Attribute("source", std::string("#") + outputID); - } - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "INTERPOLATION"); - inputElement.Attribute("source", std::string("#") + interpID); - } - if (pModelData) // only for the non-skeletal animation - { - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "TCB"); - inputElement.Attribute("source", std::string("#") + tcbID); - } - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "EASE_IN_OUT"); - inputElement.Attribute("source", std::string("#") + easeinoutID); - } - } - } - - // Write out the channel element. - XMLWriter::Element channelElement(writer, "channel"); - channelElement.Attribute("source", std::string("#") + samplerID); - std::string targetName; - if (pBones) - { - targetName = (*pBones)[parameter.boneIndex].name; - } - else - { - assert(pModelData); - targetName = pModelData->GetModelName(parameter.boneIndex); - } - targetName = targetName + "/" + parameterTargetStrings[parameter.parameter]; - channelElement.Attribute("target", targetName); - } - } - - void WriteAnimationData( - IExportContext* context, - XMLWriter& writer, - std::vector& animations, - GeometryFileData& geometryFileData, - const std::vector& modelData, - SkeletonDataMap& skeletonData, - const BoneDataMap& boneDataMap, - IExportSource* source, - ProgressRange& progressRange) - { - XMLWriter::Element libraryAnimationsElement(writer, "library_animations"); - - int animationEntryCount = int(animations.size()); - float animationEntryProgressSlice = (1.0f / (animationEntryCount ? float(animationEntryCount) : 1.0f)); - for (int animationEntryIndex = 0; animationEntryIndex < animationEntryCount; ++animationEntryIndex) - { - float FPS = source->GetDCCFrameRate(); - ProgressRange animationEntryProgressRange(progressRange, animationEntryProgressSlice); - - AnimationEntry& entry = animations[animationEntryIndex]; - - if (skeletonData.empty()) // Non-skeletal mesh - { - IAnimationData* animationData = NULL; - { - ProgressRange readAnimProgressRange(animationEntryProgressRange, 0.5f); - animationData = source->ReadAnimation(context, &geometryFileData, &modelData[0], -1, NULL, animationEntryIndex, FPS); - } - - if (animationData) - { - WriteAnimationTags(animationEntryProgressRange, entry, animationData, writer, NULL, &modelData[0]); - delete animationData; - } - } - else // Skeletal mesh - { - // Read the animation data. - SkeletonDataMap::const_iterator skeletonDataPos = skeletonData.find(std::make_pair(entry.geometryFileIndex, entry.modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - IAnimationData* animationData = NULL; - const SkeletonData& skeletonDataInstance = (*skeletonDataPos).second; - { - ProgressRange readAnimProgressRange(animationEntryProgressRange, 0.5f); - - animationData = source->ReadAnimation(context, &geometryFileData, &modelData[entry.modelIndex], entry.modelIndex, &skeletonDataInstance, entry.animationIndex, FPS); - } - - // Look up the bone entries for this model. - BoneDataMap::const_iterator boneDataPos = boneDataMap.find(std::make_pair(entry.geometryFileIndex, entry.modelIndex)); - const std::vector& bones = (*boneDataPos).second; - - if (animationData) - { - WriteAnimationTags(animationEntryProgressRange, entry, animationData, writer, &bones, NULL); - delete animationData; - } - } - } - } - } - - void WriteEffects(XMLWriter& writer, std::vector& effects, ProgressRange& progressRange) - { - XMLWriter::Element libraryEffectsElement(writer, "library_effects"); - for (int effectIndex = 0, effectCount = int(effects.size()); effectIndex < effectCount; ++effectIndex) - { - XMLWriter::Element effectElement(writer, "effect"); - effectElement.Attribute("id", effects[effectIndex].name); - - // Write out dummy effects values. - XMLWriter::Element profileElement(writer, "profile_COMMON"); - XMLWriter::Element techniqueElement(writer, "technique"); - techniqueElement.Attribute("sid", "default"); - XMLWriter::Element phongElement(writer, "phong"); - { - XMLWriter::Element emissionElement(writer, "emission"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "emission"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(1.0f); - } - { - XMLWriter::Element ambientElement(writer, "ambient"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "ambient"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(1.0f); - } - { - XMLWriter::Element diffuseElement(writer, "diffuse"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "diffuse"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(1.0f); - } - { - XMLWriter::Element specularElement(writer, "specular"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "specular"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(1.0f); - } - { - XMLWriter::Element shininessElement(writer, "shininess"); - XMLWriter::Element floatElement(writer, "float"); - floatElement.Attribute("sid", "shininess"); - floatElement.ContentArrayElement(0.0f); - } - { - XMLWriter::Element reflectiveElement(writer, "reflective"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "reflective"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(1.0f); - } - { - XMLWriter::Element reflectivityElement(writer, "reflectivity"); - XMLWriter::Element floatElement(writer, "float"); - floatElement.Attribute("sid", "reflectivity"); - floatElement.ContentArrayElement(0.0f); - } - { - XMLWriter::Element transparentElement(writer, "transparent"); - transparentElement.Attribute("opaque", "RGB_ZERO"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "transparent"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - } - { - XMLWriter::Element transparencyElement(writer, "transparency"); - XMLWriter::Element floatElement(writer, "float"); - floatElement.Attribute("sid", "transparency"); - floatElement.ContentArrayElement(0.0f); - } - { - XMLWriter::Element refractionElement(writer, "index_of_refraction"); - XMLWriter::Element floatElement(writer, "float"); - floatElement.Attribute("sid", "index_of_refraction"); - floatElement.ContentArrayElement(0.0f); - } - } - } - - void WriteControllers( - XMLWriter& writer, - IExportContext* context, - IExportSource* exportSource, - std::vector& skinControllers, - std::vector& morphControllers, - std::map, int> modelMorphControllerMap, - GeometryFileData& geometryFileData, - const std::vector& modelData, - SkeletonDataMap& skeletonData, - MorphDataMap& morphData, - std::vector& morphGeometries, - std::map, int>, int>& morphGeometryMap, - std::vector& geometries, - std::map, int>& modelGeometryMap, - const BoneDataMap& boneDataMap, - ProgressRange& progressRange) - { - // - XMLWriter::Element libraryControllersElement(writer, "library_controllers"); - for (int controllerIndex = 0, controllerCount = int(skinControllers.size()); controllerIndex < controllerCount; ++controllerIndex) - { - SkinControllerEntry& controller = skinControllers[controllerIndex]; - SkeletonDataMap::iterator skeletonDataPos = skeletonData.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex)); - if (skeletonDataPos == skeletonData.end()) - { - continue; - } - - SkeletonData skeleton = (*skeletonDataPos).second; - - // - XMLWriter::Element controllerElement(writer, "controller"); - controllerElement.Attribute("id", controller.name); - - // - std::string geometryName; - bool sourceFound = false; - { - std::map, int>::const_iterator modelMorphControllerMapPos = modelMorphControllerMap.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex)); - int morphControllerIndex = (modelMorphControllerMapPos != modelMorphControllerMap.end() ? (*modelMorphControllerMapPos).second : -1); - geometryName = (morphControllerIndex >= 0 ? morphControllers[morphControllerIndex].name : "MISSING MORPH CONTROLLER NAME"); - sourceFound = (morphControllerIndex >= 0); - } - if (!sourceFound) - { - std::map, int>::const_iterator geometryMapPos = modelGeometryMap.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex)); - int geometryIndex = (geometryMapPos != modelGeometryMap.end() ? (*geometryMapPos).second : -1); - geometryName = (geometryIndex >= 0 ? geometries[geometryIndex].name : "MISSING GEOMETRY NAME"); - sourceFound = (geometryIndex >= 0); - } - XMLWriter::Element skinElement(writer, "skin"); - skinElement.Attribute("source", "#" + geometryName); - - // - // 1.000000 0.000000 0.000000 0.000000 - // 0.000000 1.000000 0.000000 0.000000 - // 0.000000 0.000000 1.000000 0.000000 - // 0.000000 0.000000 0.000000 1.000000 - // - { - XMLWriter::Element bindMatrixElement(writer, "bind_shape_matrix"); - bindMatrixElement.ContentArrayElement(1.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(1.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(1.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(1.0f); - } - - // - std::string jointsSourceName = controller.name + "_joints"; - { - XMLWriter::Element jointsSourceElement(writer, "source"); - jointsSourceElement.Attribute("id", jointsSourceName); - - // - const std::vector& bones = (*boneDataMap.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex))).second; - std::string arrayName = jointsSourceName + "_array"; - { - XMLWriter::Element idArrayElement(writer, "IDREF_array"); - idArrayElement.Attribute("id", arrayName); - idArrayElement.Attribute("count", skeleton.GetBoneCount()); - for (int boneIndex = 0, boneCount = skeleton.GetBoneCount(); boneIndex < boneCount; ++boneIndex) - { - idArrayElement.ContentArrayElement(bones[boneIndex].name); - } - } - - // - { - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - // - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("count", skeleton.GetBoneCount()); - accessorElement.Attribute("stride", 1); - accessorElement.Attribute("source", "#" + arrayName); - - // - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("type", std::string("IDREF")); - // - // - // - } - } - - // - std::string matricesSourceName = controller.name + "_matrices"; - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", matricesSourceName); - - // - std::string arrayName = matricesSourceName + "_array"; - { - XMLWriter::Element arrayElement(writer, "float_array"); - arrayElement.Attribute("id", arrayName); - arrayElement.Attribute("count", skeleton.GetBoneCount() * 16); - arrayElement.ContentLine(""); - for (int boneIndex = 0, boneCount = skeleton.GetBoneCount(); boneIndex < boneCount; ++boneIndex) - { - Vec3 scaleParams; - skeleton.GetScale((float*)&scaleParams, boneIndex); - Matrix44 scale = Matrix33::CreateScale(scaleParams); - - Ang3 rotationParams; - skeleton.GetRotation((float*)&rotationParams, boneIndex); - Matrix44 rotation = Matrix33::CreateRotationXYZ(rotationParams); - - Vec3 translationParams; - skeleton.GetTranslation((float*)&translationParams, boneIndex); - Matrix44 translation(IDENTITY); - translation.SetTranslation(translationParams); - - Matrix44 transform = translation * (rotation * scale); - transform.Invert(); - for (int i = 0; i < 4; ++i) - { - for (int j = 0; j < 4; ++j) - { - arrayElement.ContentArrayElement(transform(i, j)); - } - arrayElement.ContentLine(""); - } - } - } - - // - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - - // - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("count", skeleton.GetBoneCount()); - accessorElement.Attribute("stride", 16); - accessorElement.Attribute("source", "#" + arrayName); - - // - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("type", std::string("float4x4")); - - // - // - // - } - - // Read in the skinning info. - SkinningData skinningData; - exportSource->ReadSkinning(context, &skinningData, &modelData[controller.geometryFileIndex], controller.modelIndex, &skeleton); - - // Build a single array of weights. - std::vector weightsArray; - std::vector > weightIndexArray; - int vertexCount = skinningData.GetVertexCount(); - weightIndexArray.resize(vertexCount); - for (int vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) - { - int linkCount = skinningData.GetBoneLinkCount(vertexIndex); - weightIndexArray[vertexIndex].resize(linkCount); - for (int linkIndex = 0; linkIndex < linkCount; ++linkIndex) - { - int weightIndex = int(weightsArray.size()); - weightsArray.push_back(skinningData.GetWeight(vertexIndex, linkIndex)); - weightIndexArray[vertexIndex][linkIndex] = weightIndex; - } - } - - // - std::string weightsSourceName = controller.name + "_weights"; - { - XMLWriter::Element weightsSourceElement(writer, "source"); - weightsSourceElement.Attribute("id", weightsSourceName); - - // - int weightCount = int(weightsArray.size()); - std::string arrayName = weightsSourceName + "_array"; - { - XMLWriter::Element floatArrayElement(writer, "float_array"); - floatArrayElement.Attribute("count", weightCount); - floatArrayElement.Attribute("id", arrayName); - - for (int weightIndex = 0; weightIndex < weightCount; ++weightIndex) - { - floatArrayElement.ContentArrayElement(weightsArray[weightIndex]); - } - } - - // - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - - // - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("count", weightCount); - accessorElement.Attribute("stride", 1); - accessorElement.Attribute("source", "#" + arrayName); - - // - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("type", "float"); - - // - // - // - } - - { - // - XMLWriter::Element jointsElement(writer, "joints"); - - // - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "JOINT"); - inputElement.Attribute("source", "#" + jointsSourceName); - } - - // - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "INV_BIND_MATRIX"); - inputElement.Attribute("source", "#" + matricesSourceName); - } - - // - } - - { - // - XMLWriter::Element vertexWeightsElement(writer, "vertex_weights"); - int vertexCount = skinningData.GetVertexCount(); - vertexWeightsElement.Attribute("count", vertexCount); - - // - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "JOINT"); - inputElement.Attribute("offset", 0); - inputElement.Attribute("source", "#" + jointsSourceName); - } - - // - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "WEIGHT"); - inputElement.Attribute("offset", 1); - inputElement.Attribute("source", "#" + weightsSourceName); - } - - // - { - XMLWriter::Element vcountElement(writer, "vcount"); - - for (int vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) - { - vcountElement.ContentArrayElement(int(weightIndexArray[vertexIndex].size())); - } - } - - // - { - XMLWriter::Element vElement(writer, "v"); - vElement.ContentLine(""); - - for (int vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) - { - for (int linkIndex = 0, linkCount = int(weightIndexArray[vertexIndex].size()); linkIndex < linkCount; ++linkIndex) - { - vElement.ContentArrayElement(skinningData.GetBoneIndex(vertexIndex, linkIndex)); - vElement.ContentArrayElement(weightIndexArray[vertexIndex][linkIndex]); - } - vElement.ContentLine(""); - } - - // - } - // - } - - // - // - // - } - - // Write out the morph controllers. - for (int controllerIndex = 0, controllerCount = int(morphControllers.size()); controllerIndex < controllerCount; ++controllerIndex) - { - MorphControllerEntry& controller = morphControllers[controllerIndex]; - - // Find the geometry and morphs for the model. - std::map, int>::const_iterator modelGeometryMapPos = modelGeometryMap.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex)); - MorphDataMap::const_iterator modelMorphDataPos = morphData.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex)); - - if (modelGeometryMapPos != modelGeometryMap.end() && modelMorphDataPos != morphData.end()) - { - GeometryEntry& geometry = geometries[(*modelGeometryMapPos).second]; - const MorphData& modelMorphData = (*modelMorphDataPos).second; - - XMLWriter::Element controllerElement(writer, "controller"); - controllerElement.Attribute("id", controller.name); - XMLWriter::Element morphElement(writer, "morph"); - morphElement.Attribute("source", "#" + geometry.name); - - std::string targetsSourceID = controller.name + "-source_targets"; - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", targetsSourceID); - std::string arrayID = targetsSourceID + "-array"; - { - XMLWriter::Element idrefArrayElement(writer, "IDREF_array"); - idrefArrayElement.Attribute("id", arrayID); - idrefArrayElement.Attribute("count", modelMorphData.GetMorphCount()); - for (int morphIndex = 0, morphCount = modelMorphData.GetMorphCount(); morphIndex < morphCount; ++morphIndex) - { - // Look up the geometry for this morph. - //std::vector& morphGeometries - std::map, int>, int>::const_iterator morphGeometryMapPos = morphGeometryMap.find(std::make_pair(std::make_pair(controller.geometryFileIndex, controller.modelIndex), morphIndex)); - int morphGeometryIndex = (morphGeometryMapPos != morphGeometryMap.end() ? (*morphGeometryMapPos).second : -1); - if (morphGeometryIndex >= -1) - { - const MorphGeometryEntry& morphGeometry = morphGeometries[morphGeometryIndex]; - idrefArrayElement.ContentArrayElement(morphGeometry.name); - } - } - } - { - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", "#" + arrayID); - accessorElement.Attribute("count", modelMorphData.GetMorphCount()); - accessorElement.Attribute("offset", 0); - accessorElement.Attribute("stride", 1); - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "MORPH_TARGET"); - paramElement.Attribute("type", "IDREF"); - } - } - std::string weightsSourceID = controller.name + "-source_weights"; - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", weightsSourceID); - std::string arrayID = weightsSourceID + "-array"; - { - XMLWriter::Element floatArrayElement(writer, "float_array"); - floatArrayElement.Attribute("id", arrayID); - floatArrayElement.Attribute("count", modelMorphData.GetMorphCount()); - for (int morphIndex = 0, morphCount = modelMorphData.GetMorphCount(); morphIndex < morphCount; ++morphIndex) - { - // Look up the geometry for this morph. - //std::vector& morphGeometries - std::map, int>, int>::const_iterator morphGeometryMapPos = morphGeometryMap.find(std::make_pair(std::make_pair(controller.geometryFileIndex, controller.modelIndex), morphIndex)); - int morphGeometryIndex = (morphGeometryMapPos != morphGeometryMap.end() ? (*morphGeometryMapPos).second : -1); - if (morphGeometryIndex >= -1) - { - const MorphGeometryEntry& morphGeometry = morphGeometries[morphGeometryIndex]; - floatArrayElement.ContentArrayElement(0); - } - } - } - { - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", "#" + arrayID); - accessorElement.Attribute("count", modelMorphData.GetMorphCount()); - accessorElement.Attribute("offset", 0); - accessorElement.Attribute("stride", 1); - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "MORPH_WEIGHT"); - paramElement.Attribute("type", "float"); - } - } - XMLWriter::Element targestElement(writer, "targets"); - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "MORPH_TARGET"); - inputElement.Attribute("source", "#" + targetsSourceID); - } - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "MORPH_WEIGHT"); - inputElement.Attribute("source", "#" + weightsSourceID); - } - } - } - } - - void WriteImages(XMLWriter& writer, ProgressRange& progressRange) - { - XMLWriter::Element libraryImagesElement(writer, "library_images"); - } - - void WriteMaterials(XMLWriter& writer, MaterialData& materialData, std::map& materialFXMap, std::vector& effects, std::map& materialMaterialMap, std::vector& materials, ProgressRange& progressRange) - { - XMLWriter::Element libraryMaterialsElement(writer, "library_materials"); - - for (int materialIndex = 0, materialCount = materialData.GetMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - std::map::iterator materialMapPos = materialMaterialMap.find(materialIndex); - int entryIndex = (materialMapPos != materialMaterialMap.end() ? (*materialMapPos).second : -1); - std::map::iterator effectMapPos = materialFXMap.find(materialIndex); - int effectIndex = (effectMapPos != materialFXMap.end() ? (*effectMapPos).second : -1); - - if (entryIndex >= 0) - { - std::string name = materials[entryIndex].name; - XMLWriter::Element materialElement(writer, "material"); - materialElement.Attribute("id", name); - if (effectIndex >= 0) - { - XMLWriter::Element effectElement(writer, "instance_effect"); - effectElement.Attribute("url", "#" + effects[effectIndex].name); - } - } - } - } - - void WriteScene(XMLWriter& writer, ProgressRange& progressRange) - { - XMLWriter::Element sceneElement(writer, "scene"); - XMLWriter::Element instanceElement(writer, "instance_visual_scene"); - instanceElement.Attribute("url", "#visual_scene_0"); - } -} - -bool ColladaWriter::Write(IExportSource* source, IExportContext* context, IXMLSink* sink, ProgressRange& progressRange) -{ - if (FloatingPointHasPrecisionIssues()) - { - // If you hit this point, please change floating point settings in your VS project (and recompile it): - // ConfigurationProperties -> C/C++ -> CodeGeneration -> FloatingPointModel: "/fp:strict". - // Note: using "/fp:precise" doesn't help. - assert(0); - context->Log(ILogger::eSeverity_Error, "Cannot write Collada file, because the writer has precision issues. Contact Crytek tools programmers."); - return false; - } - - // Temporarily change the current locale so that floats get written out using periods rather than commas. - LocaleChanger localeChangeToStandard(LC_NUMERIC, "C"); - - // Create an object to format the xml. - XMLWriter writer(sink); - - // Export the animations to the file. - { - XMLWriter::Element colladaElement(writer, "COLLADA"); - colladaElement.Attribute("xmlns", "http://www.collada.org/2005/11/COLLADASchema"); - colladaElement.Attribute("version", "1.4.1"); - - // Write out the document metadata. - WriteMetaData(source, writer, ProgressRange(progressRange, 0.01f)); - - // Read the skeleton. - GeometryFileData geometryFileData; - MaterialData materialData; - std::vector modelData; - SkeletonDataMap skeletonData; - MorphDataMap morphData; - { - ProgressRange subProgressRange(progressRange, 0.1f); - - source->ReadGeometryFiles(context, &geometryFileData); - - bool ok = source->ReadMaterials(context, &geometryFileData, &materialData); - if (!ok) - { - return false; - } - - modelData.resize(geometryFileData.GetGeometryFileCount()); - - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - source->ReadModels(&geometryFileData, geometryFileIndex, &modelData[geometryFileIndex]); - - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - MorphDataMap::iterator morphDataPos = morphData.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), MorphData())).first; - source->ReadMorphs(context, &(*morphDataPos).second, &modelData[geometryFileIndex], modelIndex); - if ((*morphDataPos).second.GetMorphCount() == 0) - { - morphData.erase(morphDataPos); - } - - SkeletonDataMap::iterator skeletonDataPos = skeletonData.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), SkeletonData())).first; - if (!source->ReadSkeleton(&geometryFileData, geometryFileIndex, &modelData[geometryFileIndex], modelIndex, &materialData, &(*skeletonDataPos).second)) - { - skeletonData.erase(skeletonDataPos); - } - -#if !defined(HACK_HACK_FORCE_PELVIS_TO_BE_BONE_1_BECAUSE_LOADING_CODE_EXPECTS_IT) -# define HACK_HACK_FORCE_PELVIS_TO_BE_BONE_1_BECAUSE_LOADING_CODE_EXPECTS_IT 0 -#endif //!defined(HACK_HACK_FORCE_PELVIS_TO_BE_BONE_1_BECAUSE_LOADING_CODE_EXPECTS_IT) - - skeletonDataPos = skeletonData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - SkeletonData newData, & oldData = (*skeletonDataPos).second; - int pelvisIndex = -1; - for (int i = 0, count = oldData.GetBoneCount(); i < count; ++i) - { - pelvisIndex = ((_stricmp(oldData.GetName(i).c_str(), "Bip01 Pelvis") == 0) ? i : pelvisIndex); - } - if (pelvisIndex >= 0) - { - if (pelvisIndex != 1) - { - context->Log(ILogger::eSeverity_Warning, "`Bip01 Pelvis` should be the second bone."); - } -#if HACK_HACK_FORCE_PELVIS_TO_BE_BONE_1_BECAUSE_LOADING_CODE_EXPECTS_IT == 1 - std::vector oldToNewMap(oldData.GetBoneCount()); - std::vector newToOldMap(oldData.GetBoneCount()); - for (int i = 0, count = oldData.GetBoneCount(); i < count; ++i) - { - oldToNewMap[i] = i, newToOldMap[i] = i; - } - std::swap(oldToNewMap[pelvisIndex], oldToNewMap[1]); - std::swap(newToOldMap[pelvisIndex], newToOldMap[1]); - for (int i = 0, count = oldData.GetBoneCount(); i < count; ++i) - { - int oldIndex = newToOldMap[i]; - void* handle = oldData.GetBoneHandle(oldIndex); - std::string name = oldData.GetName(oldIndex); - int oldParentIndex = oldData.GetParentIndex(oldIndex); - int parentIndex = (oldParentIndex >= 0 ? oldToNewMap[oldParentIndex] : -1); - float translation[3], rotation[3], scale[3]; - oldData.GetTranslation(translation, oldIndex); - oldData.GetRotation(rotation, oldIndex); - oldData.GetScale(scale, oldIndex); - - int boneIndex = newData.AddBone(handle, name.c_str(), parentIndex); - newData.SetTranslation(boneIndex, translation); - newData.SetRotation(boneIndex, rotation); - newData.SetScale(boneIndex, scale); - - newData.SetHasGeometry(boneIndex, oldData.HasGeometry(oldIndex)); - - if (oldData.HasParentFrame(oldIndex)) - { - float parentFrameTranslation[3], parentFrameRotation[3], parentFrameScale[3]; - oldData.GetParentFrameTranslation(oldIndex, parentFrameTranslation); - oldData.GetParentFrameRotation(oldIndex, parentFrameRotation); - oldData.GetParentFrameScale(oldIndex, parentFrameScale); - newData.SetParentFrameTranslation(boneIndex, parentFrameTranslation); - newData.SetParentFrameRotation(boneIndex, parentFrameRotation); - newData.SetParentFrameScale(boneIndex, parentFrameScale); - } - for (int axisIndex = 0; axisIndex < 3; ++axisIndex) - { - ISkeletonData::Axis axis = ISkeletonData::Axis(axisIndex); - if (oldData.HasLimit(oldIndex, axis, ISkeletonData::LimitMin)) - { - newData.SetLimit(boneIndex, axis, ISkeletonData::LimitMin, oldData.GetLimit(oldIndex, axis, ISkeletonData::LimitMin)); - } - if (oldData.HasLimit(oldIndex, axis, ISkeletonData::LimitMax)) - { - newData.SetLimit(boneIndex, axis, ISkeletonData::LimitMax, oldData.GetLimit(oldIndex, axis, ISkeletonData::LimitMax)); - } - if (oldData.HasSpringTension(oldIndex, axis)) - { - newData.SetSpringTension(boneIndex, axis, oldData.GetSpringTension(oldIndex, axis)); - } - if (oldData.HasSpringAngle(oldIndex, axis)) - { - newData.SetSpringAngle(boneIndex, axis, oldData.GetSpringAngle(oldIndex, axis)); - } - if (oldData.HasAxisDamping(oldIndex, axis)) - { - newData.SetAxisDamping(boneIndex, axis, oldData.GetAxisDamping(oldIndex, axis)); - } - newData.SetPhysicalized(boneIndex, oldData.GetPhysicalized(oldIndex)); - } - } - (*skeletonDataPos).second = newData; -#endif //HACK_HACK_FORCE_PELVIS_TO_BE_BONE_1_BECAUSE_LOADING_CODE_EXPECTS_IT == 1 - } - } - } - } - } - - // Generate a list of fx to export. - std::map materialFXMap; - std::vector effects; - GenerateEffectsList(context, materialFXMap, effects, materialData); - - // Generate a list of geometry to export. - std::map, int> modelGeometryMap; - std::vector geometries; - GenerateGeometryList(context, modelGeometryMap, geometries, geometryFileData, modelData); - - // Generate a list of bone geometries to export. - std::map, int>, int> boneGeometryMap; - std::vector boneGeometries; - GenerateBoneGeometryList(context, boneGeometryMap, boneGeometries, geometryFileData, modelData, skeletonData); - - // Generate a list of morph geometries to export. - std::map, int>, int> morphGeometryMap; - std::vector morphGeometries; - GenerateMorphGeometryList(context, morphGeometryMap, morphGeometries, geometryFileData, modelData, morphData); - - BoneDataMap boneDataMap; - GenerateBoneList(context, boneDataMap, skeletonData, modelData); - - // Generate a list of animations to export. - std::vector animations; - GenerateAnimationList(context, animations, geometryFileData, modelData, skeletonData, source, ProgressRange(progressRange, 0.025f)); - - // Generate a list of morph controllers to export. - std::vector morphControllers; - std::map, int> modelMorphControllerMap; - GenerateMorphControllerList(context, morphControllers, modelMorphControllerMap, morphData, geometryFileData, modelData, modelGeometryMap, geometries, ProgressRange(progressRange, 0.0125f)); - - // Generate a list of skin controllers to export. - std::vector controllers; - std::map, int> modelControllerMap; - GenerateSkinControllerList(context, controllers, modelControllerMap, skeletonData, geometryFileData, modelData, modelGeometryMap, geometries, ProgressRange(progressRange, 0.0125f)); - - // Write out all the animations. - WriteAnimationList(writer, animations, ProgressRange(progressRange, 0.025f)); - WriteAnimationData(context, writer, animations, geometryFileData, modelData, skeletonData, boneDataMap, source, ProgressRange(progressRange, 0.475f)); - - // Write out all the effects. - WriteEffects(writer, effects, ProgressRange(progressRange, 0.01f)); - - // Write out the materials. - std::map materialMaterialMap; - std::vector materials; - GenerateMaterialList(context, materialMaterialMap, materialFXMap, effects, materials, materialData); - WriteMaterials(writer, materialData, materialFXMap, effects, materialMaterialMap, materials, ProgressRange(progressRange, 0.005f)); - - // Write out all the geometries. - bool ok = WriteGeometries(context, writer, geometries, geometryFileData, modelData, morphData, materialData, materials, materialMaterialMap, skeletonData, boneGeometries, boneGeometryMap, morphGeometryMap, morphGeometries, source, ProgressRange(progressRange, 0.2f)); - if (!ok) - { - return false; - } - - // Write out all the controllers. - WriteControllers(writer, context, source, controllers, morphControllers, modelMorphControllerMap, geometryFileData, modelData, skeletonData, morphData, morphGeometries, morphGeometryMap, geometries, modelGeometryMap, boneDataMap, ProgressRange(progressRange, 0.005f)); - - // Write out the list of models. - WriteHierarchy(writer, context, geometryFileData, materialData, materialMaterialMap, materials, modelData, skeletonData, modelGeometryMap, geometries, modelControllerMap, controllers, boneDataMap, boneGeometryMap, boneGeometries, modelMorphControllerMap, morphControllers, source, ProgressRange(progressRange, 0.1f)); - - // Write out all the other libraries. - WriteImages(writer, ProgressRange(progressRange, 0.01f)); - WriteScene(writer, ProgressRange(progressRange, 0.01f)); - } - - return true; -} diff --git a/Code/Tools/CryCommonTools/Export/ColladaWriter.h b/Code/Tools/CryCommonTools/Export/ColladaWriter.h deleted file mode 100644 index f880e8ce1b..0000000000 --- a/Code/Tools/CryCommonTools/Export/ColladaWriter.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAWRITER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAWRITER_H -#pragma once - - -#include - -class IExportSource; -class IExportContext; -class ProgressRange; -class IXMLSink; - -class ColladaWriter -{ -public: - static bool Write(IExportSource* source, IExportContext* context, IXMLSink* sink, ProgressRange& progressRange); -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAWRITER_H diff --git a/Code/Tools/CryCommonTools/Export/ExportFileType.cpp b/Code/Tools/CryCommonTools/Export/ExportFileType.cpp deleted file mode 100644 index 8e552f361b..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportFileType.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ExportFileType.h" -#include "StringHelpers.h" - - -struct SFileTypeInfo -{ - int type; - const char* name; -}; - -SFileTypeInfo s_fileTypes[] = -{ - { CRY_FILE_TYPE_CGF, "cgf" }, - { CRY_FILE_TYPE_CGA, "cga" }, - { CRY_FILE_TYPE_CHR, "chr" }, - { CRY_FILE_TYPE_CAF, "caf" }, - { CRY_FILE_TYPE_ANM, "anm" }, - { CRY_FILE_TYPE_CHR | CRY_FILE_TYPE_CAF, "chrcaf" }, - { CRY_FILE_TYPE_CGA | CRY_FILE_TYPE_ANM, "cgaanm" }, - { CRY_FILE_TYPE_SKIN, "skin" }, - { CRY_FILE_TYPE_INTERMEDIATE_CAF, "i_caf" }, -}; - -static const int s_fileTypeCount = (sizeof(s_fileTypes) / sizeof(s_fileTypes[0])); - - -const char* ExportFileTypeHelpers::CryFileTypeToString(int const cryFileType) -{ - for (int i = 0; i < s_fileTypeCount; ++i) - { - if (s_fileTypes[i].type == cryFileType) - { - return s_fileTypes[i].name; - } - } - return "unknown"; -} - -int ExportFileTypeHelpers::StringToCryFileType(const char* str) -{ - if (str) - { - for (int i = 0; i < s_fileTypeCount; ++i) - { - if (_stricmp(str, s_fileTypes[i].name) == 0) - { - return s_fileTypes[i].type; - } - } - } - return CRY_FILE_TYPE_NONE; -} diff --git a/Code/Tools/CryCommonTools/Export/ExportFileType.h b/Code/Tools/CryCommonTools/Export/ExportFileType.h deleted file mode 100644 index 11d68f699b..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportFileType.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTFILETYPE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTFILETYPE_H -#pragma once - - -enum CryFileType -{ - CRY_FILE_TYPE_NONE = 0x0000, - CRY_FILE_TYPE_CGF = 0x0001, - CRY_FILE_TYPE_CGA = 0x0002, - CRY_FILE_TYPE_CHR = 0x0004, - CRY_FILE_TYPE_CAF = 0x0008, - CRY_FILE_TYPE_ANM = 0x0010, - CRY_FILE_TYPE_SKIN = 0x0020, - CRY_FILE_TYPE_INTERMEDIATE_CAF = 0x0040, - //START: Add Skinned Geometry (.CGF) export type (for touch bending vegetation) - CRY_FILE_TYPE_SKIN_CGF = 0x0080, - //END: Add Skinned Geometry (.CGF) export type (for touch bending vegetation) -}; - -namespace ExportFileTypeHelpers -{ - const char* CryFileTypeToString(int cryFileType); - int StringToCryFileType(const char* str); -}; - - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTFILETYPE_H - diff --git a/Code/Tools/CryCommonTools/Export/ExportHelpers.h b/Code/Tools/CryCommonTools/Export/ExportHelpers.h deleted file mode 100644 index 00780696fe..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportHelpers.h +++ /dev/null @@ -1,83 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTHELPERS_H -#pragma once - - -#include - -namespace ExportHelpers -{ - inline void GenerateTextureCoordinates(float* const res_s, float* const res_t, const float x, const float y, const float z) - { - const float ax = ::fabs(x); - const float ay = ::fabs(y); - const float az = ::fabs(z); - - float s = 0.0f; - float t = 0.0f; - - if (ax > 1e-3f || ay > 1e-3f || az > 1e-3f) - { - if (ax > ay) - { - if (ax > az) - { - // X rules - s = y / ax; - t = z / ax; - } - else - { - // Z rules - s = x / az; - t = y / az; - } - } - else - { - // ax <= ay - if (ay > az) - { - // Y rules - s = x / ay; - t = z / ay; - } - else - { - // Z rules - s = x / az; - t = y / az; - } - } - } - - // Now the texture coordinates are in the range [-1,1]. - // We want normalized [0,1] texture coordinates. - s = (s + 1) * 0.5f; - t = (t + 1) * 0.5f; - - if (res_s) - { - *res_s = s; - } - if (res_t) - { - *res_t = t; - } - } -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTHELPERS_H diff --git a/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.cpp b/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.cpp deleted file mode 100644 index 5fd0cb855f..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ExportSourceDecoratorBase.h" - -ExportSourceDecoratorBase::ExportSourceDecoratorBase(IExportSource* source) - : source(source) -{ -} - -void ExportSourceDecoratorBase::GetMetaData(SExportMetaData& metaData) const -{ - this->source->GetMetaData(metaData); -} - -std::string ExportSourceDecoratorBase::GetDCCFileName() const -{ - return this->source->GetDCCFileName(); -} - -std::string ExportSourceDecoratorBase::GetExportDirectory() const -{ - return this->source->GetExportDirectory(); -} - -void ExportSourceDecoratorBase::ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData) -{ - this->source->ReadGeometryFiles(context, geometryFileData); -} - -bool ExportSourceDecoratorBase::ReadMaterials(IExportContext* context, const IGeometryFileData* const geometryFileData, IMaterialData* materialData) -{ - return this->source->ReadMaterials(context, geometryFileData, materialData); -} - -void ExportSourceDecoratorBase::ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData) -{ - this->source->ReadModels(geometryFileData, geometryFileIndex, modelData); -} - -void ExportSourceDecoratorBase::ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* const modelData, int modelIndex, ISkeletonData* skeletonData) -{ - this->source->ReadSkinning(context, skinningData, modelData, modelIndex, skeletonData); -} - -bool ExportSourceDecoratorBase::ReadSkeleton(const IGeometryFileData* const geometryFileData, int geometryFileIndex, const IModelData* const modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData) -{ - return this->source->ReadSkeleton(geometryFileData, geometryFileIndex, modelData, modelIndex, materialData, skeletonData); -} - -int ExportSourceDecoratorBase::GetAnimationCount() const -{ - return this->source->GetAnimationCount(); -} - -std::string ExportSourceDecoratorBase::GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const -{ - return this->source->GetAnimationName(geometryFileData, geometryFileIndex, animationIndex); -} - -void ExportSourceDecoratorBase::GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const -{ - this->source->GetAnimationTimeSpan(start, stop, animationIndex); -} - -void ExportSourceDecoratorBase::ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const -{ - this->source->ReadAnimationFlags(context, animationData, geometryFileData, modelData, modelIndex, skeletonData, animationIndex); -} - -IAnimationData* ExportSourceDecoratorBase::ReadAnimation(IExportContext* context, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const -{ - return this->source->ReadAnimation(context, geometryFileData, modelData, modelIndex, skeletonData, animationIndex, fps); -} - -bool ExportSourceDecoratorBase::ReadGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* const modelData, const IMaterialData* const materialData, int modelIndex) -{ - return this->source->ReadGeometry(context, geometry, modelData, materialData, modelIndex); -} - -bool ExportSourceDecoratorBase::ReadGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, const IModelData* const modelData, const IMaterialData* const materialData, int modelIndex) const -{ - return this->source->ReadGeometryMaterialData(context, geometryMaterialData, modelData, materialData, modelIndex); -} - -bool ExportSourceDecoratorBase::ReadBoneGeometry(IExportContext* context, IGeometryData* geometry, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* const materialData) -{ - return this->source->ReadBoneGeometry(context, geometry, skeletonData, boneIndex, materialData); -} - -bool ExportSourceDecoratorBase::ReadBoneGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* const materialData) const -{ - return this->source->ReadBoneGeometryMaterialData(context, geometryMaterialData, skeletonData, boneIndex, materialData); -} - -void ExportSourceDecoratorBase::ReadMorphs(IExportContext* context, IMorphData* morphData, const IModelData* const modelData, int modelIndex) -{ - this->source->ReadMorphs(context, morphData, modelData, modelIndex); -} - -bool ExportSourceDecoratorBase::ReadMorphGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* const modelData, int modelIndex, const IMorphData* const morphData, int morphIndex, const IMaterialData* materialData) -{ - return this->source->ReadMorphGeometry(context, geometry, modelData, modelIndex, morphData, morphIndex, materialData); -} - -bool ExportSourceDecoratorBase::HasValidPosController(const IModelData* modelData, int modelIndex) const -{ - return this->source->HasValidPosController(modelData, modelIndex); -} - -bool ExportSourceDecoratorBase::HasValidRotController(const IModelData* modelData, int modelIndex) const -{ - return this->source->HasValidRotController(modelData, modelIndex); -} - -bool ExportSourceDecoratorBase::HasValidSclController(const IModelData* modelData, int modelIndex) const -{ - return this->source->HasValidSclController(modelData, modelIndex); -} diff --git a/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.h b/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.h deleted file mode 100644 index df5bea80ee..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSOURCEDECORATORBASE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSOURCEDECORATORBASE_H -#pragma once - - -#include "IExportSource.h" - -class ExportSourceDecoratorBase - : public IExportSource -{ -public: - ExportSourceDecoratorBase(IExportSource* source); - - virtual std::string GetResourceCompilerPath() const { return std::string(""); }; - virtual void GetMetaData(SExportMetaData& metaData) const; - virtual std::string GetDCCFileName() const; - virtual std::string GetExportDirectory() const; - virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData); - virtual bool ReadMaterials(IExportContext* context, const IGeometryFileData* geometryFileData, IMaterialData* materialData); - virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData); - virtual void ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* modelData, int modelIndex, ISkeletonData* skeletonData); - virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData); - virtual int GetAnimationCount() const; - virtual std::string GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const; - virtual void GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const; - virtual void ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const; - virtual IAnimationData* ReadAnimation(IExportContext* context, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const; - virtual bool ReadGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, const IMaterialData* materialData, int modelIndex); - virtual bool ReadGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, const IModelData* modelData, const IMaterialData* materialData, int modelIndex) const; - virtual bool ReadBoneGeometry(IExportContext* context, IGeometryData* geometry, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData); - virtual bool ReadBoneGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData) const; - virtual void ReadMorphs(IExportContext* context, IMorphData* morphData, const IModelData* modelData, int modelIndex); - virtual bool ReadMorphGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, int modelIndex, const IMorphData* morphData, int morphIndex, const IMaterialData* materialData); - virtual bool HasValidPosController(const IModelData* modelData, int modelIndex) const; - virtual bool HasValidRotController(const IModelData* modelData, int modelIndex) const; - virtual bool HasValidSclController(const IModelData* modelData, int modelIndex) const; -protected: - IExportSource* source; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSOURCEDECORATORBASE_H diff --git a/Code/Tools/CryCommonTools/Export/ExportStatusWindow.cpp b/Code/Tools/CryCommonTools/Export/ExportStatusWindow.cpp deleted file mode 100644 index bc10a107e7..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportStatusWindow.cpp +++ /dev/null @@ -1,215 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ExportStatusWindow.h" -#include "UI/Win32GUI.h" -#include "StringHelpers.h" -#include -#include - -enum -{ - WM_USER_TASK_FINISHED = WM_USER + 53, - WM_USER_ACCEPTED -}; - -struct ThreadData -{ - ExportStatusWindow* statusWindow; - void (ExportStatusWindow::* initialize)(int width, int height, const std::vector >& tasks); - void (ExportStatusWindow::* run)(); - int width; - int height; - const std::vector >* tasks; - HANDLE initializedSemaphore; -}; -unsigned int __stdcall ThreadFunc(void* threadDataMemory) -{ - ThreadData* data = static_cast(threadDataMemory); - ExportStatusWindow* statusWindow = data->statusWindow; - void (ExportStatusWindow::* initialize)(int width, int height, const std::vector >& tasks) = data->initialize; - void (ExportStatusWindow::* run)() = data->run; - int width = data->width; - int height = data->height; - const std::vector >& tasks = *data->tasks; - HANDLE initializedSemaphore = data->initializedSemaphore; - - // Initialize the data. - (statusWindow->*initialize)(width, height, tasks); - - // Let the creating thread know that we have read the data - it is - // now safe for it to clear it. - ReleaseSemaphore(initializedSemaphore, 1, 0); - - // Perform the main thread processing. - (statusWindow->*run)(); - return 0; -} - -#pragma warning(push) -#pragma warning(disable: 4355) // 'this' : used in base member initializer list -ExportStatusWindow::ExportStatusWindow(int width, int height, const std::vector >& tasks) - : m_threadHandle(0) - , m_warningsEncountered(false) - , m_errorsEncountered(false) - , m_waitState(WaitState_WarningsAndErrors) - , m_okButtonSpacer(0, 0, 2000, 0) - , m_okButton(_T("OK"), this, &ExportStatusWindow::OkPressed) - , m_okButtonLayout(Layout::DirectionHorizontal) -{ - OutputDebugString(_T("Showing status window.\n")); - - Win32GUI::Initialize(); - - HANDLE initializedSemaphore = CreateSemaphore(0, 0, 1, 0); - - // Create a thread to handle the message pump for the window. - ThreadData threadData; - threadData.statusWindow = this; - threadData.initialize = &ExportStatusWindow::Initialize; - threadData.run = &ExportStatusWindow::Run; - threadData.width = width; - threadData.height = height; - threadData.tasks = &tasks; - threadData.initializedSemaphore = initializedSemaphore; - m_threadHandle = (HANDLE)_beginthreadex( - 0, //void *security, - 0, //unsigned stack_size, - ThreadFunc, //unsigned ( *start_address )( void * ), - &threadData, //void *arglist, - 0, //unsigned initflag, - 0); //unsigned *thrdaddr - - // Wait until the thread has read the data, since once we return the data will be lost. - WaitForSingleObject(initializedSemaphore, INFINITE); - CloseHandle(initializedSemaphore); -} -#pragma warning(pop) - -ExportStatusWindow::~ExportStatusWindow() -{ - OutputDebugString(_T("Hiding status window.\n")); - - // Tell the thread to exit and then wait for it to do so. - if (HWND hwnd = (HWND)m_frameWindow.GetHWND()) - { - PostMessage(hwnd, WM_USER_TASK_FINISHED, 0, 0); - m_okButton.Enable(true); - WaitForSingleObject((HANDLE)m_threadHandle, INFINITE); - } -} - -void ExportStatusWindow::Initialize(int width, int height, const std::vector >& tasks) -{ - OutputDebugString(_T("Beginning status window thread.\n")); - - for (int taskIndex = 0, taskCount = int(tasks.size()); taskIndex < taskCount; ++taskIndex) - { - m_taskList.AddTask(tasks[taskIndex].first, tasks[taskIndex].second); - } - - m_okButtonLayout.AddComponent(&m_okButtonSpacer); - m_okButtonLayout.AddComponent(&m_okButton); - m_okButton.Enable(false); - - m_frameWindow.AddComponent(&m_taskList); - m_frameWindow.AddComponent(&m_progressBar); - m_frameWindow.AddComponent(&m_logWindow); - m_frameWindow.AddComponent(&m_okButtonLayout); - m_frameWindow.Show(true, width, height); -} - -void ExportStatusWindow::Run() -{ - MSG msg; - BOOL status; - bool waitingAcceptance = false; - while ((status = GetMessage(&msg, HWND(0), UINT(0), UINT(0))) != 0) - { - if (status == -1) - { - break; - } - else if (msg.message == WM_USER_TASK_FINISHED) - { - if (m_waitState == WaitState_Always || - (m_waitState == WaitState_WarningsAndErrors && m_warningsEncountered || m_errorsEncountered) || - (m_waitState == WaitState_ErrorsOnly && m_errorsEncountered)) - { - waitingAcceptance = true; - } - else - { - break; - } - } - else if (waitingAcceptance && msg.message == WM_USER_ACCEPTED) - { - break; - } - else - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - - m_frameWindow.Show(false, 0, 0); - OutputDebugString(_T("Ending status window thread.\n")); -} - -void ExportStatusWindow::OkPressed() -{ - if (HWND hwnd = (HWND)m_frameWindow.GetHWND()) - { - PostMessage(hwnd, WM_USER_ACCEPTED, 0, 0); - } -} - -void ExportStatusWindow::SetWaitState(WaitState state) -{ - m_waitState = state; -} - -void ExportStatusWindow::AddTask(const std::string& id, const std::string& description) -{ - m_taskList.AddTask(id, description); -} - -void ExportStatusWindow::SetCurrentTask(const std::string& id) -{ - m_taskList.SetCurrentTask(id); -} - -void ExportStatusWindow::SetProgress(float progress) -{ - TCHAR buffer[2048]; - _sntprintf_s(buffer, sizeof(buffer), _TRUNCATE, _T("%.1f%% complete - exporting scene."), progress * 100); - m_frameWindow.SetCaption(buffer); - m_progressBar.SetProgress(progress); -} - -void ExportStatusWindow::Log(ILogger::ESeverity eSeverity, const char* message) -{ - if (eSeverity == ILogger::eSeverity_Error) - { - m_errorsEncountered = true; - } - else if (eSeverity == ILogger::eSeverity_Warning) - { - m_warningsEncountered = true; - } - - m_logWindow.Log(eSeverity, StringHelpers::ConvertString(message).c_str()); -} diff --git a/Code/Tools/CryCommonTools/Export/ExportStatusWindow.h b/Code/Tools/CryCommonTools/Export/ExportStatusWindow.h deleted file mode 100644 index d82869ae96..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportStatusWindow.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSTATUSWINDOW_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSTATUSWINDOW_H -#pragma once - - -#include "UI/FrameWindow.h" -#include "UI/ProgressBar.h" -#include "UI/TaskList.h" -#include "UI/LogWindow.h" -#include "UI/Spacer.h" -#include "UI/Layout.h" -#include "UI/PushButton.h" -#include "ILogger.h" - -class ExportStatusWindow -{ -public: - enum WaitState - { - WaitState_WarningsAndErrors, - WaitState_ErrorsOnly, - WaitState_Always, - WaitState_Never, - }; - - ExportStatusWindow(int width, int height, const std::vector >& tasks); - ~ExportStatusWindow(); - - void SetWaitState(WaitState state); - - void AddTask(const std::string& id, const std::string& description); - void SetCurrentTask(const std::string& id); - void SetProgress(float progress); - void Log(ILogger::ESeverity eSeverity, const char* message); - -private: - void Initialize(int width, int height, const std::vector >& tasks); - void Run(); - void OkPressed(); - - FrameWindow m_frameWindow; - TaskList m_taskList; - ProgressBar m_progressBar; - Spacer m_okButtonSpacer; - PushButton m_okButton; - Layout m_okButtonLayout; - LogWindow m_logWindow; - void* m_threadHandle; - bool m_warningsEncountered; - bool m_errorsEncountered; - WaitState m_waitState; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSTATUSWINDOW_H diff --git a/Code/Tools/CryCommonTools/Export/GeometryData.cpp b/Code/Tools/CryCommonTools/Export/GeometryData.cpp deleted file mode 100644 index dd82d90181..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryData.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "GeometryData.h" - -GeometryData::GeometryData() -{ -} - -int GeometryData::AddPosition(float x, float y, float z) -{ - int positionIndex = int(this->positions.size()); - this->positions.push_back(Vector(x, y, z)); - return positionIndex; -} - -int GeometryData::AddNormal(float x, float y, float z) -{ - int normalIndex = int(this->normals.size()); - this->normals.push_back(Vector(x, y, z)); - return normalIndex; -} - -int GeometryData::AddTextureCoordinate(float u, float v) -{ - int textureCoordinateIndex = int(this->textureCoordinates.size()); - this->textureCoordinates.push_back(TextureCoordinate(u, v)); - return textureCoordinateIndex; -} - -int GeometryData::AddVertexColor(float r, float g, float b, float a) -{ - int vertexColorIndex = int(this->vertexColors.size()); - this->vertexColors.push_back(VertexColor(r, g, b, a)); - return vertexColorIndex; -} - -int GeometryData::AddPolygon(const int* indices, int mtlID) -{ - int polygonIndex = int(this->polygons.size()); - this->polygons.push_back(Polygon(mtlID, - Polygon::Vertex(indices[0], indices[1], indices[2], indices[3]), - Polygon::Vertex(indices[4], indices[5], indices[6], indices[7]), - Polygon::Vertex(indices[8], indices[9], indices[10], indices[11]))); - return polygonIndex; -} - -int GeometryData::GetNumberOfPositions() const -{ - return (int)this->positions.size(); -} - -int GeometryData::GetNumberOfNormals() const -{ - return (int)this->normals.size(); -} - -int GeometryData::GetNumberOfTextureCoordinates() const -{ - return (int)this->textureCoordinates.size(); -} - -int GeometryData::GetNumberOfVertexColors() const -{ - return (int)this->vertexColors.size(); -} - -int GeometryData::GetNumberOfPolygons() const -{ - return (int)this->polygons.size(); -} diff --git a/Code/Tools/CryCommonTools/Export/GeometryData.h b/Code/Tools/CryCommonTools/Export/GeometryData.h deleted file mode 100644 index aa42925128..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryData.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYDATA_H -#pragma once - - -#include "IGeometryData.h" -#include - -class GeometryData - : public IGeometryData -{ -public: - GeometryData(); - - // IGeometryData - virtual int AddPosition(float x, float y, float z); - virtual int AddNormal(float x, float y, float z); - virtual int AddTextureCoordinate(float u, float v); - virtual int AddVertexColor(float r, float g, float b, float a); - - virtual int AddPolygon(const int* indices, int mtlID); - - virtual int GetNumberOfPositions() const; - virtual int GetNumberOfNormals() const; - virtual int GetNumberOfTextureCoordinates() const; - virtual int GetNumberOfVertexColors() const; - - virtual int GetNumberOfPolygons() const; - - struct Vector - { - Vector(float x, float y, float z) - : x(x) - , y(y) - , z(z) {} - float x, y, z; - }; - - struct TextureCoordinate - { - TextureCoordinate(float u, float v) - : u(u) - , v(v) {} - float u, v; - }; - - struct VertexColor - { - VertexColor(float r, float g, float b, float a) - : r(r) - , g(g) - , b(b) - , a(a) {} - float r, g, b, a; - }; - - struct Polygon - { - struct Vertex - { - Vertex() {} - Vertex(int positionIndex, int normalIndex, int textureCoordinateIndex, int vertexColorIndex) - : positionIndex(positionIndex) - , normalIndex(normalIndex) - , textureCoordinateIndex(textureCoordinateIndex) - , vertexColorIndex(vertexColorIndex) {} - int positionIndex, normalIndex, textureCoordinateIndex, vertexColorIndex; - }; - - Polygon(int mtlID, const Vertex& v0, const Vertex& v1, const Vertex& v2) - : mtlID(mtlID) - { - v[0] = v0; - v[1] = v1; - v[2] = v2; - } - - int mtlID; - Vertex v[3]; - }; - - std::vector positions; - std::vector normals; - std::vector textureCoordinates; - std::vector vertexColors; - std::vector polygons; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYDATA_H diff --git a/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.cpp b/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.cpp deleted file mode 100644 index 3333e12ca6..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "GeometryExportSourceAdapter.h" -#include "IGeometryFileData.h" -#include - -GeometryExportSourceAdapter::GeometryExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryFileData, const std::vector& geometryFileIndices) - : ExportSourceDecoratorBase(source) - , m_geometryFileData(geometryFileData) - , m_geometryFileIndices(geometryFileIndices) -{ - assert(m_geometryFileIndices.size() <= m_geometryFileData->GetGeometryFileCount()); - for (size_t i = 0; i < m_geometryFileIndices.size(); ++i) - { - int const geometryFileIndex = m_geometryFileIndices[i]; - assert(geometryFileIndex >= 0 && geometryFileIndex < m_geometryFileData->GetGeometryFileCount()); - } -} - -void GeometryExportSourceAdapter::ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData) -{ - for (size_t i = 0; i < m_geometryFileIndices.size(); ++i) - { - int const geometryFileIndex = m_geometryFileIndices[i]; - int const newGeometryFileIndex = geometryFileData->AddGeometryFile( - m_geometryFileData->GetGeometryFileHandle(geometryFileIndex), - m_geometryFileData->GetGeometryFileName(geometryFileIndex), - m_geometryFileData->GetProperties(geometryFileIndex)); - } -} - -void GeometryExportSourceAdapter::ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData) -{ - assert(geometryFileIndex >= 0 && geometryFileIndex < m_geometryFileIndices.size()); - this->source->ReadModels(m_geometryFileData, m_geometryFileIndices[geometryFileIndex], modelData); -} - -bool GeometryExportSourceAdapter::ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData) -{ - assert(geometryFileIndex >= 0 && geometryFileIndex < m_geometryFileIndices.size()); - return this->source->ReadSkeleton(m_geometryFileData, m_geometryFileIndices[geometryFileIndex], modelData, modelIndex, materialData, skeletonData); -} diff --git a/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.h b/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.h deleted file mode 100644 index 7fb6ee081d..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYEXPORTSOURCEADAPTER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYEXPORTSOURCEADAPTER_H -#pragma once - - -#include "ExportSourceDecoratorBase.h" - -class GeometryExportSourceAdapter - : public ExportSourceDecoratorBase -{ -public: - GeometryExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryFileData, const std::vector& geometryFileIndices); - - virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData); - virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData); - virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData); - -private: - IGeometryFileData* m_geometryFileData; - std::vector m_geometryFileIndices; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYEXPORTSOURCEADAPTER_H diff --git a/Code/Tools/CryCommonTools/Export/GeometryFileData.cpp b/Code/Tools/CryCommonTools/Export/GeometryFileData.cpp deleted file mode 100644 index f67c0905dd..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryFileData.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "GeometryFileData.h" - -int GeometryFileData::AddGeometryFile(const void* handle, const char* name, const SProperties& properties) -{ - const int geometryFileIndex = int(m_geometryFiles.size()); - m_geometryFiles.push_back(GeometryFileEntry(handle, name, properties)); - return geometryFileIndex; -} - -int GeometryFileData::GetGeometryFileCount() const -{ - return int(m_geometryFiles.size()); -} - -const void* GeometryFileData::GetGeometryFileHandle(int geometryFileIndex) const -{ - return m_geometryFiles[geometryFileIndex].handle; -} - -const char* GeometryFileData::GetGeometryFileName(int geometryFileIndex) const -{ - return m_geometryFiles[geometryFileIndex].name.c_str(); -} - -////////////////////////////////////////////////////////////////////////// -const IGeometryFileData::SProperties& GeometryFileData::GetProperties(int geometryFileIndex) const -{ - if (size_t(geometryFileIndex) >= m_geometryFiles.size()) - { - assert(0); - static SProperties badValue; - return badValue; - } - return m_geometryFiles[geometryFileIndex].properties; -} - -void GeometryFileData::SetProperties(int geometryFileIndex, const IGeometryFileData::SProperties& properties) -{ - if (size_t(geometryFileIndex) >= m_geometryFiles.size()) - { - assert(0); - return; - } - m_geometryFiles[geometryFileIndex].properties = properties; -} diff --git a/Code/Tools/CryCommonTools/Export/GeometryFileData.h b/Code/Tools/CryCommonTools/Export/GeometryFileData.h deleted file mode 100644 index 975a9cc5f7..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryFileData.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYFILEDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYFILEDATA_H -#pragma once - - -#include "IGeometryFileData.h" -#include "STLHelpers.h" - -class GeometryFileData - : public IGeometryFileData -{ -public: - // IGeometryFileData - virtual int AddGeometryFile(const void* handle, const char* name, const SProperties& properties); - virtual const SProperties& GetProperties(int geometryFileIndex) const; - virtual void SetProperties(int geometryFileIndex, const SProperties& properties); - virtual int GetGeometryFileCount() const; - virtual const void* GetGeometryFileHandle(int geometryFileIndex) const; - virtual const char* GetGeometryFileName(int geometryFileIndex) const; - -private: - struct GeometryFileEntry - { - GeometryFileEntry(const void* a_handle, const char* a_name, const SProperties& a_properties) - : handle(a_handle) - , name(a_name) - , properties(a_properties) - { - } - - const void* handle; - std::string name; - SProperties properties; - }; - - std::vector m_geometryFiles; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYFILEDATA_H diff --git a/Code/Tools/CryCommonTools/Export/GeometryMaterialData.cpp b/Code/Tools/CryCommonTools/Export/GeometryMaterialData.cpp deleted file mode 100644 index ddc27daf52..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryMaterialData.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "GeometryMaterialData.h" - -void GeometryMaterialData::AddUsedMaterialIndex(int materialIndex) -{ - std::map::iterator usedMaterialPos = m_usedMaterialIndexIndexMap.find(materialIndex); - if (usedMaterialPos == m_usedMaterialIndexIndexMap.end()) - { - int materialIndexIndex = int(m_usedMaterialIndices.size()); - m_usedMaterialIndices.push_back(materialIndex); - m_usedMaterialIndexIndexMap.insert(std::make_pair(materialIndex, materialIndexIndex)); - } -} - -int GeometryMaterialData::GetUsedMaterialCount() const -{ - return int(m_usedMaterialIndices.size()); -} - -int GeometryMaterialData::GetUsedMaterialIndex(int usedMaterialIndex) const -{ - return m_usedMaterialIndices[usedMaterialIndex]; -} diff --git a/Code/Tools/CryCommonTools/Export/GeometryMaterialData.h b/Code/Tools/CryCommonTools/Export/GeometryMaterialData.h deleted file mode 100644 index b2fb5deb30..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryMaterialData.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYMATERIALDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYMATERIALDATA_H -#pragma once - - -#include "IGeometryMaterialData.h" - -class GeometryMaterialData - : public IGeometryMaterialData -{ -public: - // IGeometryMaterialData - virtual void AddUsedMaterialIndex(int materialIndex); - virtual int GetUsedMaterialCount() const; - virtual int GetUsedMaterialIndex(int usedMaterialIndex) const; - -private: - std::vector m_usedMaterialIndices; - std::map m_usedMaterialIndexIndexMap; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYMATERIALDATA_H diff --git a/Code/Tools/CryCommonTools/Export/HelperData.h b/Code/Tools/CryCommonTools/Export/HelperData.h deleted file mode 100644 index adede42194..0000000000 --- a/Code/Tools/CryCommonTools/Export/HelperData.h +++ /dev/null @@ -1,41 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_HELPERDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_HELPERDATA_H -#pragma once - - -struct SHelperData -{ -public: - enum EHelperType - { - eHelperType_UNKNOWN, - eHelperType_Point, - eHelperType_Dummy - }; - -public: - SHelperData() - : m_eHelperType(eHelperType_UNKNOWN) - { - } - -public: - EHelperType m_eHelperType; - float m_boundBoxMin[3]; // used for eHelperType_Dummy only - float m_boundBoxMax[3]; // used for eHelperType_Dummy only -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_HELPERDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IAnimationData.h b/Code/Tools/CryCommonTools/Export/IAnimationData.h deleted file mode 100644 index 4ac11abbb5..0000000000 --- a/Code/Tools/CryCommonTools/Export/IAnimationData.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IANIMATIONDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IANIMATIONDATA_H -#pragma once - - -class IAnimationData -{ -public: - virtual ~IAnimationData() {} - - virtual void SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3]) = 0; - virtual void SetFrameCount(int frameCount) = 0; - - virtual void SetFrameTimePos(int modelIndex, int frameIndex, float time) = 0; - virtual void SetFrameDataPos(int modelIndex, int frameIndex, float translation[3]) = 0; - virtual void SetFrameCountPos(int modelIndex, int frameCount) = 0; - virtual void SetFrameTimeRot(int modelIndex, int frameIndex, float time) = 0; - virtual void SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3]) = 0; - virtual void SetFrameCountRot(int modelIndex, int frameCount) = 0; - virtual void SetFrameTimeScl(int modelIndex, int frameIndex, float time) = 0; - virtual void SetFrameDataScl(int modelIndex, int frameIndex, float scale[3]) = 0; - virtual void SetFrameCountScl(int modelIndex, int frameCount) = 0; - - // For TCB & Ease-In/-Out support - struct TCB - { - float tension; - float continuity; - float bias; - - TCB() - : tension(0) - , continuity(0) - , bias(0) {} - }; - struct Ease - { - float in; - float out; - - Ease() - : in(0) - , out(0) {} - }; - virtual void SetFrameTCBPos(int modelIndex, int frameIndex, TCB tcb) = 0; - virtual void SetFrameTCBRot(int modelIndex, int frameIndex, TCB tcb) = 0; - virtual void SetFrameTCBScl(int modelIndex, int frameIndex, TCB tcb) = 0; - virtual void SetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease ease) = 0; - virtual void SetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease ease) = 0; - virtual void SetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease ease) = 0; - - enum ModelFlags - { - ModelFlags_NoExport = 1 << 0 - }; - - virtual void SetModelFlags(int modelIndex, unsigned modelFlags) = 0; - - virtual void GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const = 0; - virtual int GetFrameCount() const = 0; - - virtual float GetFrameTimePos(int modelIndex, int frameIndex) const = 0; - virtual void GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const = 0; - virtual int GetFrameCountPos(int modelIndex) const = 0; - virtual float GetFrameTimeRot(int modelIndex, int frameIndex) const = 0; - virtual void GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const = 0; - virtual int GetFrameCountRot(int modelIndex) const = 0; - virtual float GetFrameTimeScl(int modelIndex, int frameIndex) const = 0; - virtual void GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const = 0; - virtual int GetFrameCountScl(int modelIndex) const = 0; - - // For TCB & Ease-In/-Out support - virtual void GetFrameTCBPos(int modelIndex, int frameIndex, TCB& tcb) const = 0; - virtual void GetFrameTCBRot(int modelIndex, int frameIndex, TCB& tcb) const = 0; - virtual void GetFrameTCBScl(int modelIndex, int frameIndex, TCB& tcb) const = 0; - virtual void GetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease& ease) const = 0; - virtual void GetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease& ease) const = 0; - virtual void GetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease& ease) const = 0; - - virtual unsigned GetModelFlags(int modelIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IANIMATIONDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IExportContext.h b/Code/Tools/CryCommonTools/Export/IExportContext.h deleted file mode 100644 index b2da053e6f..0000000000 --- a/Code/Tools/CryCommonTools/Export/IExportContext.h +++ /dev/null @@ -1,55 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTCONTEXT_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTCONTEXT_H -#pragma once - - -#include -#include "Exceptions.h" -#include "ILogger.h" - -struct IPakSystem; -class ISettings; - -class IExportContext - : public ILogger -{ -public: - // Declare an exception type to report the case where the scene must be saved before exporting. - struct NeedSaveErrorTag {}; - typedef Exception NeedSaveError; - struct PakSystemErrorTag {}; - typedef Exception PakSystemError; - - virtual void SetProgress(float progress) = 0; - virtual void SetCurrentTask(const std::string& id) = 0; - virtual IPakSystem* GetPakSystem() = 0; - virtual ISettings* GetSettings() = 0; - virtual void GetRootPath(char* buffer, int bufferSizeInBytes) = 0; - -protected: - // ILogger - virtual void LogImpl(ILogger::ESeverity eSeverity, const char* message) = 0; -}; - -struct CurrentTaskScope -{ - CurrentTaskScope(IExportContext* context, const std::string& id) - : context(context) {context->SetCurrentTask(id); } - ~CurrentTaskScope() {context->SetCurrentTask(""); } - IExportContext* context; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTCONTEXT_H diff --git a/Code/Tools/CryCommonTools/Export/IExportSource.h b/Code/Tools/CryCommonTools/Export/IExportSource.h deleted file mode 100644 index 61051d6a2a..0000000000 --- a/Code/Tools/CryCommonTools/Export/IExportSource.h +++ /dev/null @@ -1,98 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTSOURCE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTSOURCE_H -#pragma once - - -#include "Exceptions.h" - -class ISkeletonData; -class IAnimationData; -class IExportContext; -class IModelData; -class IGeometryFileData; -class IGeometryData; -class IMaterialData; -class ISkinningData; -class IMorphData; -class IGeometryMaterialData; - -namespace ExportGlobal -{ - const float g_defaultFrameRate = 30.f; -}; - -struct SExportMetaData -{ - enum EAxisUp - { - X_UP, - Y_UP, - Z_UP - }; - - char authoring_tool[128]; - char source_data[1024]; // Filename of the source. - char author[128]; // Name of the author. - char revision[64]; - EAxisUp up_axis; - float fMeterUnit; - float fFramesPerSecond; - - SExportMetaData() - { - fMeterUnit = 1.0f; - up_axis = Z_UP; - fFramesPerSecond = ExportGlobal::g_defaultFrameRate; - strcpy(authoring_tool, "CryENGINE Collada Exporter"); - strcpy(source_data, ""); - strcpy(author, ""); - strcpy(revision, "1.4.1"); - } -}; - -class IExportSource -{ -public: - virtual ~IExportSource() - { - } - virtual std::string GetResourceCompilerPath() const = 0; - virtual void GetMetaData(SExportMetaData& metaData) const = 0; - virtual std::string GetDCCFileName() const = 0; - virtual float GetDCCFrameRate() const{ return ExportGlobal::g_defaultFrameRate; } - virtual std::string GetExportDirectory() const = 0; - virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData) = 0; - virtual bool ReadMaterials(IExportContext* context, const IGeometryFileData* geometryFileData, IMaterialData* materialData) = 0; - virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData) = 0; - virtual void ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* modelData, int modelIndex, ISkeletonData* skeletonData) = 0; - virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData) = 0; - virtual int GetAnimationCount() const = 0; - virtual std::string GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const = 0; - virtual void GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const = 0; - virtual void ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const = 0; - virtual IAnimationData* ReadAnimation(IExportContext* context, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const = 0; - virtual bool ReadGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, const IMaterialData* materialData, int modelIndex) = 0; - virtual bool ReadGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, const IModelData* modelData, const IMaterialData* materialData, int modelIndex) const = 0; - virtual bool ReadBoneGeometry(IExportContext* context, IGeometryData* geometry, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData) = 0; - virtual bool ReadBoneGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData) const = 0; - virtual void ReadMorphs(IExportContext* context, IMorphData* morphData, const IModelData* modelData, int modelIndex) = 0; - virtual bool ReadMorphGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, int modelIndex, const IMorphData* morphData, int morphIndex, const IMaterialData* materialData) = 0; - virtual bool HasValidPosController(const IModelData* modelData, int modelIndex) const = 0; - virtual bool HasValidRotController(const IModelData* modelData, int modelIndex) const = 0; - virtual bool HasValidSclController(const IModelData* modelData, int modelIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTSOURCE_H diff --git a/Code/Tools/CryCommonTools/Export/IExportWriter.h b/Code/Tools/CryCommonTools/Export/IExportWriter.h deleted file mode 100644 index 5f53f01049..0000000000 --- a/Code/Tools/CryCommonTools/Export/IExportWriter.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTWRITER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTWRITER_H -#pragma once - - -class IExportSource; -class IExportContext; - -class IExportWriter -{ -public: - virtual void Export(IExportSource* source, IExportContext* context) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTWRITER_H diff --git a/Code/Tools/CryCommonTools/Export/IGeometryData.h b/Code/Tools/CryCommonTools/Export/IGeometryData.h deleted file mode 100644 index 0869c97421..0000000000 --- a/Code/Tools/CryCommonTools/Export/IGeometryData.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYDATA_H -#pragma once - - -class IGeometryData -{ -public: - virtual int AddPosition(float x, float y, float z) = 0; - virtual int AddNormal(float x, float y, float z) = 0; - virtual int AddTextureCoordinate(float u, float v) = 0; - virtual int AddVertexColor(float r, float g, float b, float a) = 0; - virtual int AddPolygon(const int* indices, int mtlID) = 0; - - virtual int GetNumberOfPositions() const = 0; - virtual int GetNumberOfNormals() const = 0; - virtual int GetNumberOfTextureCoordinates() const = 0; - virtual int GetNumberOfVertexColors() const = 0; - virtual int GetNumberOfPolygons() const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IGeometryFileData.h b/Code/Tools/CryCommonTools/Export/IGeometryFileData.h deleted file mode 100644 index bc81366ab2..0000000000 --- a/Code/Tools/CryCommonTools/Export/IGeometryFileData.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYFILEDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYFILEDATA_H -#pragma once - - -#include "ExportFileType.h" -#include - -class IGeometryFileData -{ -public: - struct SProperties - { - int filetypeInt; // combination of flags from CryFileType - bool bDoNotMerge; - bool bUseCustomNormals; - bool bUseF32VertexFormat; - bool b8WeightsPerVertex; - std::string customExportPath; - - SProperties() - : filetypeInt(CRY_FILE_TYPE_NONE) - , bDoNotMerge(false) - , bUseCustomNormals(false) - , bUseF32VertexFormat(false) - , b8WeightsPerVertex(false) - { - } - }; -public: - virtual int AddGeometryFile(const void* handle, const char* name, const SProperties& properties) = 0; - virtual const SProperties& GetProperties(int geometryFileIndex) const = 0; - virtual int GetGeometryFileCount() const = 0; - - // return an implementation-specific handle (for example a maya Dag Path string, or a MAX node name or whatever) - // its opaque to the exporter, but you can cast it yourself. - virtual const void* GetGeometryFileHandle(int geometryFileIndex) const = 0; - virtual const char* GetGeometryFileName(int geometryFileIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYFILEDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IGeometryMaterialData.h b/Code/Tools/CryCommonTools/Export/IGeometryMaterialData.h deleted file mode 100644 index 1c4eca55bf..0000000000 --- a/Code/Tools/CryCommonTools/Export/IGeometryMaterialData.h +++ /dev/null @@ -1,27 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYMATERIALDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYMATERIALDATA_H -#pragma once - - -class IGeometryMaterialData -{ -public: - virtual void AddUsedMaterialIndex(int materialIndex) = 0; - virtual int GetUsedMaterialCount() const = 0; - virtual int GetUsedMaterialIndex(int usedMaterialIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYMATERIALDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IMaterialData.h b/Code/Tools/CryCommonTools/Export/IMaterialData.h deleted file mode 100644 index 82102eb3ce..0000000000 --- a/Code/Tools/CryCommonTools/Export/IMaterialData.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMATERIALDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMATERIALDATA_H -#pragma once - - -class IMaterialData -{ -public: - // the handle represents an implementation specific underlying handle (like a maya pointer to a string dag name). - virtual int AddMaterial(const char* name, int id, const void* handle, const char* properties) = 0; - virtual int AddMaterial(const char* name, int id, const char* subMatName, const void* handle, const char* properties) = 0; - virtual int GetMaterialCount() const = 0; - virtual const char* GetName(int materialIndex) const = 0; - virtual int GetID(int materialIndex) const = 0; - virtual const char* GetSubMatName(int materialIndex) const = 0; - virtual const void* GetHandle(int materialIndex) const = 0; - virtual const char* GetProperties(int materialIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMATERIALDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IModelData.h b/Code/Tools/CryCommonTools/Export/IModelData.h deleted file mode 100644 index 26ea7ed385..0000000000 --- a/Code/Tools/CryCommonTools/Export/IModelData.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMODELDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMODELDATA_H -#pragma once - - -#include "HelperData.h" -#include - -class IModelData -{ -public: - virtual int AddModel(const void* handle, const char* modelName, int parentModelIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString) = 0; - virtual int GetModelCount() const = 0; - virtual const void* GetModelHandle(int modelIndex) const = 0; - virtual const char* GetModelName(int modelIndex) const = 0; - virtual void SetTranslationRotationScale(int modelIndex, const float* translation, const float* rotation, const float* scale) = 0; - virtual void GetTranslationRotationScale(int modelIndex, float* translation, float* rotation, float* scale) const = 0; - virtual const SHelperData& GetHelperData(int modelIndex) const = 0; - virtual const std::string& GetProperties(int modelIndex) const = 0; - virtual bool IsRoot(int modelIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMODELDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IMorphData.h b/Code/Tools/CryCommonTools/Export/IMorphData.h deleted file mode 100644 index 26c4f05e71..0000000000 --- a/Code/Tools/CryCommonTools/Export/IMorphData.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMORPHDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMORPHDATA_H -#pragma once - - -class IMorphData -{ -public: - virtual void SetHandle(const void* handle) = 0; - virtual void AddMorph(const void* handle, const char* name, const char* fullName = NULL) = 0; - virtual const void* GetHandle() const = 0; - virtual int GetMorphCount() const = 0; - virtual const void* GetMorphHandle(int morphIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMORPHDATA_H diff --git a/Code/Tools/CryCommonTools/Export/ISkeletonData.h b/Code/Tools/CryCommonTools/Export/ISkeletonData.h deleted file mode 100644 index 75f3317343..0000000000 --- a/Code/Tools/CryCommonTools/Export/ISkeletonData.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKELETONDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKELETONDATA_H -#pragma once - - -class ISkeletonData -{ -public: - enum Axis - { - AxisX, - AxisY, - AxisZ - }; - enum Limit - { - LimitMin, - LimitMax - }; - - virtual int AddBone(const void* handle, const char* name, int parentIndex) = 0; - virtual int FindBone(const char* name) const = 0; - virtual const void* GetBoneHandle(int boneIndex) const = 0; - virtual int GetBoneParentIndex(int boneIndex) const = 0; - virtual int GetBoneCount() const = 0; - virtual void SetTranslation(int boneIndex, const float* vec) = 0; - virtual void SetRotation(int boneIndex, const float* vec) = 0; - virtual void SetScale(int boneIndex, const float* vec) = 0; - virtual void SetParentFrameTranslation(int boneIndex, const float* vec) = 0; - virtual void SetParentFrameRotation(int boneIndex, const float* vec) = 0; - virtual void SetParentFrameScale(int boneIndex, const float* vec) = 0; - virtual void SetPhysicalized(int boneIndex, bool physicalized) = 0; - virtual void SetHasGeometry(int boneIndex, bool hasGeometry) = 0; - virtual void SetBoneProperties(int boneIndex, const char* propertiesString) = 0; - virtual void SetBoneGeomProperties(int boneIndex, const char* propertiesString) = 0; - - virtual void SetLimit(int boneIndex, Axis axis, Limit extreme, float limit) = 0; - virtual void SetSpringTension(int boneIndex, Axis axis, float springTension) = 0; - virtual void SetSpringAngle(int boneIndex, Axis axis, float springAngle) = 0; - virtual void SetAxisDamping(int boneIndex, Axis axis, float damping) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKELETONDATA_H diff --git a/Code/Tools/CryCommonTools/Export/ISkinningData.h b/Code/Tools/CryCommonTools/Export/ISkinningData.h deleted file mode 100644 index d20a3ad301..0000000000 --- a/Code/Tools/CryCommonTools/Export/ISkinningData.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKINNINGDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKINNINGDATA_H -#pragma once - - -class ISkinningData -{ -public: - virtual void SetVertexCount(int vertexCount) = 0; - virtual void AddWeight(int vertexIndex, int boneIndex, float weight) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKINNINGDATA_H diff --git a/Code/Tools/CryCommonTools/Export/MaterialData.cpp b/Code/Tools/CryCommonTools/Export/MaterialData.cpp deleted file mode 100644 index 243a0dcd93..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaterialData.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "MaterialData.h" - -int MaterialData::AddMaterial(const char* name, int id, const void* handle, const char* properties) -{ - const int materialIndex = int(m_materials.size()); - m_materials.push_back(MaterialEntry(name, id, "submat", handle, properties)); - return materialIndex; -} - -int MaterialData::AddMaterial(const char* name, int id, const char* subMatName, const void* handle, const char* properties) -{ - const int materialIndex = int(m_materials.size()); - m_materials.push_back(MaterialEntry(name, id, subMatName, handle, properties)); - return materialIndex; -} - -int MaterialData::GetMaterialCount() const -{ - return int(m_materials.size()); -} - -const char* MaterialData::GetName(int materialIndex) const -{ - assert(materialIndex >= 0); - assert(materialIndex < int(m_materials.size())); - return m_materials[materialIndex].name.c_str(); -} - -int MaterialData::GetID(int materialIndex) const -{ - assert(materialIndex >= 0); - assert(materialIndex < int(m_materials.size())); - return m_materials[materialIndex].id; -} - -const char* MaterialData::GetSubMatName(int materialIndex) const -{ - assert(materialIndex >= 0); - assert(materialIndex < int(m_materials.size())); - return m_materials[materialIndex].subMatName.c_str(); -} - -const void* MaterialData::GetHandle(int materialIndex) const -{ - assert(materialIndex >= 0); - assert(materialIndex < int(m_materials.size())); - return m_materials[materialIndex].handle; -} - -const char* MaterialData::GetProperties(int materialIndex) const -{ - assert(materialIndex >= 0); - assert(materialIndex < int(m_materials.size())); - return m_materials[materialIndex].properties.c_str(); -} diff --git a/Code/Tools/CryCommonTools/Export/MaterialData.h b/Code/Tools/CryCommonTools/Export/MaterialData.h deleted file mode 100644 index 5916f56f9b..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaterialData.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALDATA_H -#pragma once - - -#include "IMaterialData.h" - -class MaterialData - : public IMaterialData -{ -public: - virtual int AddMaterial(const char* name, int id, const void* handle, const char* properties); - virtual int AddMaterial(const char* name, int id, const char* subMatName, const void* handle, const char* properties); - virtual int GetMaterialCount() const; - virtual const char* GetName(int materialIndex) const; - virtual int GetID(int materialIndex) const; - virtual const char* GetSubMatName(int materialIndex) const; - virtual const void* GetHandle(int materialIndex) const; - virtual const char* GetProperties(int materialIndex) const; - -private: - struct MaterialEntry - { - MaterialEntry(const char* a_name, int a_id, const char* a_subMatName, const void* a_handle, const char* a_properties) - : name(a_name) - , id(a_id) - , subMatName(a_subMatName) - , handle(a_handle) - , properties(a_properties ? a_properties : "") - { - } - - string name; - int id; - string subMatName; - const void* handle; - string properties; - }; - - std::vector m_materials; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALDATA_H diff --git a/Code/Tools/CryCommonTools/Export/MaterialHelpers.cpp b/Code/Tools/CryCommonTools/Export/MaterialHelpers.cpp deleted file mode 100644 index 82b9d1b88d..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaterialHelpers.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "MaterialHelpers.h" -#include "StringHelpers.h" -#include "PathHelpers.h" -#include "properties.h" - -MaterialHelpers::MaterialInfo::MaterialInfo() -{ - this->id = -1; - this->name = ""; - this->physicalize = "None"; - this->diffuseTexture = ""; - this->diffuseColor[0] = this->diffuseColor[1] = this->diffuseColor[2] = 1.0f; - this->specularColor[0] = this->specularColor[1] = this->specularColor[2] = 1.0f; - this->emissiveColor[0] = this->emissiveColor[1] = this->emissiveColor[2] = 0.0f; -} - -std::string MaterialHelpers::PhysicsIDToString(const int physicsID) -{ - switch (physicsID) - { - case 1: - return "Default"; - break; - case 2: - return "ProxyNoDraw"; - break; - case 3: - return "NoCollide"; - break; - case 4: - return "Obstruct"; - break; - default: - return "None"; - break; - } -} - -bool MaterialHelpers::WriteMaterials(const std::string& filename, const std::vector& materialList) -{ - FILE* materialFile = fopen(filename.c_str(), "w"); - if (materialFile) - { - fprintf(materialFile, "\n"); - fprintf(materialFile, " \n"); - for (int i = 0; i < materialList.size(); i++) - { - const MaterialInfo& material = materialList[i]; - - fprintf(materialFile, " \n"); - - fprintf(materialFile, " \n"); - - // Write out diffuse texture. - if (material.diffuseTexture.length() > 0) - { - //fprintf( materialFile, " \n", ProcessTexturePath( material.diffuseTexture ).c_str() ); - fprintf(materialFile, " \n", material.diffuseTexture.c_str()); - fprintf(materialFile, " \n"); - fprintf(materialFile, " \n"); - } - - fprintf(materialFile, " \n"); - fprintf(materialFile, " \n"); - } - fprintf(materialFile, " \n"); - fprintf(materialFile, "\n"); - fclose(materialFile); - - return true; - } - else - { - return false; - } -} diff --git a/Code/Tools/CryCommonTools/Export/MaterialHelpers.h b/Code/Tools/CryCommonTools/Export/MaterialHelpers.h deleted file mode 100644 index 0afe9de48c..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaterialHelpers.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALHELPERS_H -#pragma once - - -namespace MaterialHelpers -{ - struct MaterialInfo - { - MaterialInfo();// : id(-1) { } - - std::string name; - std::string physicalize; - int id; - - float diffuseColor[3]; - float specularColor[3]; - float emissiveColor[3]; - std::string diffuseTexture; - }; - - std::string PhysicsIDToString(const int physicsID); - bool WriteMaterials(const std::string& filename, const std::vector& materialList); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALHELPERS_H diff --git a/Code/Tools/CryCommonTools/Export/MaxHelpers.h b/Code/Tools/CryCommonTools/Export/MaxHelpers.h deleted file mode 100644 index bbb1cf17b7..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaxHelpers.h +++ /dev/null @@ -1,138 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXHELPERS_H -#pragma once - - -#include "CompileTimeAssert.h" -#include "PathHelpers.h" -#include "StringHelpers.h" - - -namespace MaxHelpers -{ - enum - { - kBadChar = '_' - }; - -#if !defined(MAX_PRODUCT_VERSION_MAJOR) - #error MAX_PRODUCT_VERSION_MAJOR is undefined -#elif (MAX_PRODUCT_VERSION_MAJOR >= 15) - COMPILE_TIME_ASSERT(sizeof(MCHAR) == 2); - #define MAX_MCHAR_SIZE 2 - typedef wstring MaxCompatibleString; -#elif (MAX_PRODUCT_VERSION_MAJOR >= 12) - COMPILE_TIME_ASSERT(sizeof(MCHAR) == 1); - #define MAX_MCHAR_SIZE 1 - typedef string MaxCompatibleString; -#else - #error 3dsMax 2009 and older are not supported anymore -#endif - - inline string CreateAsciiString(const char* s_ansi) - { - return StringHelpers::ConvertAnsiToAscii(s_ansi, kBadChar); - } - - - inline string CreateAsciiString(const wchar_t* s_utf16) - { - const string s_ansi = StringHelpers::ConvertUtf16ToAnsi(s_utf16, kBadChar); - return CreateAsciiString(s_ansi.c_str()); - } - - - inline string CreateUtf8String(const char* s_ansi) - { - return StringHelpers::ConvertAnsiToUtf8(s_ansi); - } - - - inline string CreateUtf8String(const wchar_t* s_utf16) - { - return StringHelpers::ConvertUtf16ToUtf8(s_utf16); - } - - - inline string CreateTidyAsciiNodeName(const char* s_ansi) - { - const size_t len = strlen(s_ansi); - - string res; - res.reserve(len); - - for (size_t i = 0; i < len; ++i) - { - char c = s_ansi[i]; - if (c < ' ' || c >= 127) - { - c = kBadChar; - } - res.append(1, c); - } - return res; - } - - - inline string CreateTidyAsciiNodeName(const wchar_t* s_utf16) - { - const string s_ansi = StringHelpers::ConvertUtf16ToAnsi(s_utf16, kBadChar); - return CreateTidyAsciiNodeName(s_ansi.c_str()); - ; - } - - - inline MSTR CreateMaxStringFromAscii(const char* s_ascii) - { -#if (MAX_MCHAR_SIZE == 2) - return MSTR(StringHelpers::ConvertAsciiToUtf16(s_ascii).c_str()); -#else - return MSTR(s_ascii); -#endif - } - - - inline MaxCompatibleString CreateMaxCompatibleStringFromAscii(const char* s_ascii) - { -#if (MAX_MCHAR_SIZE == 2) - return StringHelpers::ConvertAsciiToUtf16(s_ascii); -#else - return MaxCompatibleString(s_ascii); -#endif - } - - - inline string GetAbsoluteAsciiPath(const char* s_ansi) - { - if (!s_ansi || !s_ansi[0]) - { - return string(); - } - return PathHelpers::GetAbsoluteAsciiPath(StringHelpers::ConvertAnsiToUtf16(s_ansi).c_str()); - } - - - inline string GetAbsoluteAsciiPath(const wchar_t* s_utf16) - { - if (!s_utf16 || !s_utf16[0]) - { - return string(); - } - return PathHelpers::GetAbsoluteAsciiPath(s_utf16); - } -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXHELPERS_H diff --git a/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.cpp b/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.cpp deleted file mode 100644 index 2afe2ca0b0..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "MaxUserPropertyHelpers.h" -#include "StringHelpers.h" -#include "MaxHelpers.h" - - -std::string MaxUserPropertyHelpers::GetNodeProperties(INode* node) -{ - if (node == 0) - { - return std::string(); - } - - MSTR buf; - node->GetUserPropBuffer(buf); - - return MaxHelpers::CreateAsciiString(buf); -} - - -std::string MaxUserPropertyHelpers::GetStringNodeProperty(INode* node, const char* name, const char* defaultValue) -{ - if (node == 0) - { - return defaultValue; - } - - MSTR val; - if (!node->GetUserPropString(MaxHelpers::CreateMaxStringFromAscii(name), val)) - { - return defaultValue; - } - - return MaxHelpers::CreateAsciiString(val); -} - - -float MaxUserPropertyHelpers::GetFloatNodeProperty(INode* node, const char* name, float defaultValue) -{ - if (node == 0) - { - return defaultValue; - } - - float val; - if (!node->GetUserPropFloat(MaxHelpers::CreateMaxStringFromAscii(name), val)) - { - return defaultValue; - } - - return val; -} - - -int MaxUserPropertyHelpers::GetIntNodeProperty(INode* node, const char* name, int defaultValue) -{ - if (node == 0) - { - return defaultValue; - } - - int val; - if (!node->GetUserPropInt(MaxHelpers::CreateMaxStringFromAscii(name), val)) - { - return defaultValue; - } - - return val; -} - - -bool MaxUserPropertyHelpers::GetBoolNodeProperty(INode* node, const char* name, bool defaultValue) -{ - if (node == 0) - { - return defaultValue; - } - - BOOL val; - if (!node->GetUserPropBool(MaxHelpers::CreateMaxStringFromAscii(name), val)) - { - return defaultValue; - } - - return (val != 0); -} diff --git a/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.h b/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.h deleted file mode 100644 index efef23e167..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXUSERPROPERTYHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXUSERPROPERTYHELPERS_H -#pragma once - - -#include - -class INode; - -namespace MaxUserPropertyHelpers -{ - std::string GetNodeProperties(INode* node); - std::string GetStringNodeProperty(INode* node, const char* name, const char* defaultValue); - float GetFloatNodeProperty(INode* node, const char* name, float defaultValue); - int GetIntNodeProperty(INode* node, const char* name, int defaultValue); - bool GetBoolNodeProperty(INode* node, const char* name, bool defaultValue); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXUSERPROPERTYHELPERS_H diff --git a/Code/Tools/CryCommonTools/Export/MeshUtils.h b/Code/Tools/CryCommonTools/Export/MeshUtils.h deleted file mode 100644 index 81b456bffb..0000000000 --- a/Code/Tools/CryCommonTools/Export/MeshUtils.h +++ /dev/null @@ -1,914 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MESHUTILS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MESHUTILS_H -#pragma once - - -#include "BaseTypes.h" // uint8 -#include "Cry_Vector3.h" // Vec3 -#include "IIndexedMesh.h" // CMesh -namespace MeshUtils -{ - struct Face - { - int vertexIndex[3]; - }; - - struct Color - { - uint8 r; - uint8 g; - uint8 b; - }; - - // Stores linking of a vertex to bone(s) - class VertexLinks - { - public: - struct Link - { - int boneId; - float weight; - Vec3 offset; - - Link() - : boneId(-1) - , weight(-1.0f) - , offset(0.0f, 0.0f, 0.0f) - { - } - }; - - enum ESort - { - eSort_ByWeight, - eSort_ByBoneId, - }; - - public: - std::vector links; - - public: - // minWeightToDelete: links with weights <= minWeightToDelete will be deleted - const char* Normalize(ESort eSort, const float minWeightToDelete, const int maxLinkCount) - { - if (minWeightToDelete < 0 || minWeightToDelete >= 1) - { - return "Bad minWeightToDelete passed"; - } - if (maxLinkCount <= 0) - { - return "Bad maxLinkCount passed"; - } - - // Merging links with matching bone ids - { - DeleteByWeight(0.0f); - - if (links.empty()) - { - return "All bone links of a vertex have zero weight"; - } - - std::sort(links.begin(), links.end(), CompareLinksByBoneId); - - size_t dst = 0; - for (size_t i = 1; i < links.size(); ++i) - { - if (links[i].boneId == links[dst].boneId) - { - const float w0 = links[dst].weight; - const float w1 = links[i].weight; - const float a = w0 / (w0 + w1); - links[dst].offset = links[dst].offset * a + links[i].offset * (1 - a); - links[dst].weight = w0 + w1; - } - else - { - links[++dst] = links[i]; - } - } - - links.resize(dst + 1); - } - - // Deleting links, normalizing link weights. - // - // Note: we produce meaningful results even in cases like this: - // input weights are { 0.03, 0.01 }, minWeightTodelete is 0.2. - // Output weights produced are { 0.75, 0.25 }. - { - std::sort(links.begin(), links.end(), CompareLinksByWeight); - - if (links.size() > maxLinkCount) - { - links.resize(maxLinkCount); - } - - NormalizeWeights(); - - const size_t oldSize = links.size(); - - DeleteByWeight(minWeightToDelete); - - if (links.empty()) - { - return "All bone links of a vertex are deleted (minWeightToDelete is too big)"; - } - - if (links.size() != oldSize) - { - NormalizeWeights(); - } - } - - switch (eSort) - { - case eSort_ByWeight: - // Do nothing because we already sorted links by weight (see above) - break; - case eSort_ByBoneId: - std::sort(links.begin(), links.end(), CompareLinksByBoneId); - break; - default: - assert(0); - break; - } - - return 0; - } - - private: - void DeleteByWeight(float minWeightToDelete) - { - for (size_t i = 0; i < links.size(); ++i) - { - if (links[i].weight <= minWeightToDelete) - { - if (i < links.size() - 1) - { - links[i] = links[links.size() - 1]; - } - links.resize(links.size() - 1); - --i; - } - } - } - - void NormalizeWeights() - { - assert(!links.empty() && links[0].weight > 0); - - float w = 0; - - for (size_t i = 0; i < links.size(); ++i) - { - w += links[i].weight; - } - - w = 1 / w; - - for (size_t i = 0; i < links.size(); ++i) - { - links[i].weight *= w; - } - } - - static bool CompareLinksByBoneId(const Link& left, const Link& right) - { - if (left.boneId != right.boneId) - { - return left.boneId < right.boneId; - } - if (left.weight != right.weight) - { - return left.weight < right.weight; - } - return memcmp(&left.offset, &right.offset, sizeof(left.offset)) < 0; - } - - static bool CompareLinksByWeight(const Link& left, const Link& right) - { - if (left.weight != right.weight) - { - return left.weight > right.weight; - } - if (left.boneId != right.boneId) - { - return left.boneId < right.boneId; - } - return memcmp(&left.offset, &right.offset, sizeof(left.offset)) < 0; - } - }; - - - class Mesh - { - public: - // Vertex data - std::vector m_positions; - std::vector m_topologyIds; - std::vector m_normals; - std::vector> m_texCoords; - std::vector m_colors; - std::vector m_alphas; - std::vector m_links; - std::vector m_vertexMatIds; - size_t m_auxSizeof; - std::vector m_aux; - - // Face data - std::vector m_faces; - std::vector m_faceMatIds; - - // Mappings computed and filled by ComputeVertexRemapping() - std::vector m_vertexOldToNew; - std::vector m_vertexNewToOld; - - public: - Mesh() - : m_auxSizeof(0) - { - } - - int GetVertexCount() const - { - return m_positions.size(); - } - - int GetFaceCount() const - { - return m_faces.size(); - } - - ////////////////////////////////////////////////////////////////////////// - // Setters - - void Clear() - { - m_positions.clear(); - m_topologyIds.clear(); - m_normals.clear(); - m_texCoords.clear(); - m_colors.clear(); - m_alphas.clear(); - m_links.clear(); - m_vertexMatIds.clear(); - m_aux.clear(); - - m_faces.clear(); - m_faceMatIds.clear(); - - m_vertexOldToNew.clear(); - m_vertexNewToOld.clear(); - } - - const char* SetPositions(const float* pVec3, int count, int stride, const float scale) - { - if (count <= 0) - { - return "bad position count"; - } - if (stride < 0 || (stride > 0 && stride < sizeof(Vec3))) - { - return "bad position stride"; - } - - m_positions.resize(count); - - for (int i = 0; i < count; ++i) - { - const float* const p = (const float*)(((const char*)pVec3) + ((size_t)i * stride)); - if (!_finite(p[0]) || !_finite(p[1]) || !_finite(p[2])) - { - m_positions.clear(); - return "Illegal (NAN) vertex position. Fix the 3d Model."; - } - m_positions[i].x = p[0] * scale; - m_positions[i].y = p[1] * scale; - m_positions[i].z = p[2] * scale; - } - - return 0; - } - - const char* SetTopologyIds(const int* pTopo, int count, int stride) - { - if (count <= 0) - { - return "bad topologyId count"; - } - if (stride < 0 || (stride > 0 && stride < sizeof(int))) - { - return "bad topologyId stride"; - } - - m_topologyIds.resize(count); - - for (int i = 0; i < count; ++i) - { - const int* const p = (const int*)(((const char*)pTopo) + ((size_t)i * stride)); - m_topologyIds[i] = p[0]; - } - - return 0; - } - - const char* SetNormals(const float* pVec3, int count, int stride) - { - if (count <= 0) - { - return "bad normal count"; - } - if (stride < 0 || (stride > 0 && stride < sizeof(Vec3))) - { - return "bad normal stride"; - } - - m_normals.resize(count); - - for (int i = 0; i < count; ++i) - { - const float* const p = (const float*)(((const char*)pVec3) + ((size_t)i * stride)); - if (!_finite(p[0]) || !_finite(p[1]) || !_finite(p[2])) - { - m_normals.clear(); - return "Illegal (NAN) vertex normal. Fix the 3d Model."; - } - m_normals[i].x = p[0]; - m_normals[i].y = p[1]; - m_normals[i].z = p[2]; - m_normals[i] = m_normals[i].GetNormalizedSafe(Vec3_OneZ); - } - - return 0; - } - - const char* SetTexCoords(const float* pVec2, int count, int stride, bool bFlipT, uint streamIndex) - { - if (count <= 0) - { - return "bad texCoord count"; - } - if (stride < 0 || (stride > 0 && stride < sizeof(float) * 2)) - { - return "bad texCoord stride"; - } - if (m_texCoords.size() <= streamIndex) - { - m_texCoords.resize(streamIndex + 1); - } - - m_texCoords[streamIndex].resize(count); - - for (int i = 0; i < count; ++i) - { - const float* const p = (const float*)(((const char*)pVec2) + ((size_t)i * stride)); - if (!_finite(p[0]) || !_finite(p[1])) - { - m_texCoords[streamIndex].clear(); - return "Illegal (NAN) texture coordinate. Fix the 3d Model."; - } - m_texCoords[streamIndex][i].x = p[0]; - m_texCoords[streamIndex][i].y = bFlipT ? 1 - p[1] : p[1]; - } - - return 0; - } - - const char* SetColors(const uint8* pRgb, int count, int stride) - { - if (count <= 0) - { - return "bad color count"; - } - if (stride < 0 || (stride > 0 && stride < 3)) - { - return "bad color stride"; - } - - m_colors.resize(count); - - for (int i = 0; i < count; ++i) - { - const uint8* const p = (((const uint8*)pRgb) + ((size_t)i * stride)); - m_colors[i].r = p[0]; - m_colors[i].g = p[1]; - m_colors[i].b = p[2]; - } - - return 0; - } - - const char* SetAlphas(const uint8* pAlpha, int count, int stride) - { - if (count <= 0) - { - return "bad alpha count"; - } - if (stride < 0) - { - return "bad alpha stride"; - } - - m_alphas.resize(count); - - for (int i = 0; i < count; ++i) - { - const uint8* const p = (((const uint8*)pAlpha) + ((size_t)i * stride)); - m_alphas[i] = p[0]; - } - - return 0; - } - - const char* SetFaces(const int* pVertIdx3, int count, int stride) - { - if (count <= 0) - { - return "bad face count"; - } - if (stride < 0 || (stride > 0 && stride < 3 * sizeof(int))) - { - return "bad face stride"; - } - - m_faces.resize(count); - - for (int i = 0; i < count; ++i) - { - const int* const p = (const int*)(((const char*)pVertIdx3) + ((size_t)i * stride)); - for (int j = 0; j < 3; ++j) - { - if (p[j] < 0 || p[j] >= m_positions.size()) - { - return "bad vertex index found in a face"; - } - m_faces[i].vertexIndex[j] = p[j]; - } - } - - return 0; - } - - const char* SetFaceMatIds(const int* pMatIds, int count, int stride, int maxMaterialId) - { - if (count <= 0) - { - return "bad face materialId count"; - } - if (stride < 0 || (stride > 0 && stride < sizeof(int))) - { - return "bad face materialIdstride"; - } - - m_faceMatIds.resize(count); - - for (int i = 0; i < count; ++i) - { - const int* const p = (const int*)(((const char*)pMatIds) + ((size_t)i * stride)); - if (p[0] < 0) - { - return "negative material ID found in a face"; - } - if (p[0] >= maxMaterialId) - { - return "material ID found in a face is outside of allowed ranges"; - } - m_faceMatIds[i] = p[0]; - } - - return 0; - } - - const char* SetAux(size_t auxSizeof, const void* pData, int count, int stride) - { - if (auxSizeof <= 0) - { - return "bad aux sizeof"; - } - if (count <= 0) - { - return "bad aux count"; - } - if (stride < 0 || (stride > 0 && stride < auxSizeof)) - { - return "bad aux stride"; - } - - m_auxSizeof = auxSizeof; - - m_aux.resize(count * m_auxSizeof); - - for (int i = 0; i < count; ++i) - { - const uint8* const p = (((const uint8*)pData) + ((size_t)i * stride)); - memcpy(&m_aux[i * m_auxSizeof], p, m_auxSizeof); - } - - return 0; - } - - ////////////////////////////////////////////////////////////////////////// - // Validation - - // Returns 0 if ok, or pointer to the error text - const char* Validate() const - { - const int nVerts = (int)m_positions.size(); - if (nVerts <= 0) - { - return "No vertices"; - } - - const int nFaces = (int)m_faces.size(); - if (nFaces <= 0) - { - return "No faces"; - } - - if (!m_topologyIds.empty() && nVerts != (int)m_topologyIds.size()) - { - return "Mismatch in the number of topology IDs"; - } - - if (!m_normals.empty() && nVerts != (int)m_normals.size()) - { - return "Mismatch in the number of normals"; - } - - for (uint streamIndex = 0; streamIndex < m_texCoords.size(); ++streamIndex) - { - if (!m_texCoords[streamIndex].empty() && nVerts != (int)m_texCoords[streamIndex].size()) - { - return "Mismatch in the number of texture coordinates"; - } - } - - if (!m_colors.empty() && nVerts != (int)m_colors.size()) - { - return "Mismatch in the number of colors"; - } - - if (!m_alphas.empty() && nVerts != (int)m_alphas.size()) - { - return "Mismatch in the number of alphas"; - } - - if (!m_links.empty() && nVerts != (int)m_links.size()) - { - return "Mismatch in the number of vertex-bone links"; - } - - for (size_t i = 0; i < m_links.size(); ++i) - { - if (m_links[i].links.empty()) - { - return "Found a vertex without bone linking"; - } - } - - if (!m_vertexMatIds.empty() && nVerts != (int)m_vertexMatIds.size()) - { - return "Mismatch in the number of vertex materials"; - } - - if (!m_aux.empty() && nVerts != (int)(m_aux.size() / m_auxSizeof)) - { - return "Mismatch in the number of auxiliary elements"; - } - - if (!m_faceMatIds.empty() && nFaces != (int)m_faceMatIds.size()) - { - return "Mismatch in the number of face materials"; - } - - return 0; - } - - ////////////////////////////////////////////////////////////////////////// - // Computation - - void RemoveDegenerateFaces() - { - int writePos = 0; - for (int readPos = 0; readPos < (int)m_faces.size(); ++readPos) - { - const Face& face = m_faces[readPos]; - if (face.vertexIndex[0] != face.vertexIndex[1] && - face.vertexIndex[1] != face.vertexIndex[2] && - face.vertexIndex[0] != face.vertexIndex[2]) - { - m_faces[writePos] = m_faces[readPos]; - if (!m_faceMatIds.empty()) - { - m_faceMatIds[writePos] = m_faceMatIds[readPos]; - } - ++writePos; - } - } - m_faces.resize(writePos); - if (!m_faceMatIds.empty()) - { - m_faceMatIds.resize(writePos); - } - } - - int AddVertexCopy(int sourceVertexIndex) - { - if (sourceVertexIndex < 0 || sourceVertexIndex >= m_positions.size()) - { - assert(0); - return -1; - } - - m_positions.push_back(m_positions[sourceVertexIndex]); - if (!m_topologyIds.empty()) - { - m_topologyIds.push_back(m_topologyIds[sourceVertexIndex]); - } - if (!m_normals.empty()) - { - m_normals.push_back(m_normals[sourceVertexIndex]); - } - for (uint streamIndex = 0; streamIndex < m_texCoords.size(); ++streamIndex) - { - if (!m_texCoords[streamIndex].empty()) - { - m_texCoords[streamIndex].push_back(m_texCoords[streamIndex][sourceVertexIndex]); - } - } - if (!m_colors.empty()) - { - m_colors.push_back(m_colors[sourceVertexIndex]); - } - if (!m_alphas.empty()) - { - m_alphas.push_back(m_alphas[sourceVertexIndex]); - } - if (!m_links.empty()) - { - m_links.push_back(m_links[sourceVertexIndex]); - } - if (!m_vertexMatIds.empty()) - { - m_vertexMatIds.push_back(m_vertexMatIds[sourceVertexIndex]); - } - if (!m_aux.empty()) - { - m_aux.resize(m_aux.size() + m_auxSizeof); - memcpy(&m_aux[m_aux.size() - m_auxSizeof], &m_aux[sourceVertexIndex * m_auxSizeof], m_auxSizeof); - } - return (int)m_positions.size() - 1; - } - - // Note: might create new vertices and modify vertex indices in faces - void SetVertexMaterialIdsFromFaceMaterialIds() - { - m_vertexMatIds.clear(); - if (m_faceMatIds.empty()) - { - return; - } - m_vertexMatIds.resize(m_positions.size(), -1); - - for (size_t i = 0; i < m_faces.size(); ++i) - { - const int faceMatId = m_faceMatIds[i]; - for (int j = 0; j < 3; ++j) - { - int v = m_faces[i].vertexIndex[j]; - if (m_vertexMatIds[v] >= 0 && m_vertexMatIds[v] != faceMatId) - { - v = AddVertexCopy(v); - m_faces[i].vertexIndex[j] = v; - } - m_vertexMatIds[v] = faceMatId; - } - } - } - - // Computes m_vertexOldToNew and m_vertexNewToOld by detecting duplicate vertices - void ComputeVertexRemapping() - { - const size_t nVerts = m_positions.size(); - - m_vertexNewToOld.resize(nVerts); - for (size_t i = 0; i < nVerts; ++i) - { - m_vertexNewToOld[i] = i; - } - - VertexLess less(*this); - std::sort(m_vertexNewToOld.begin(), m_vertexNewToOld.end(), less); - - m_vertexOldToNew.resize(nVerts); - - int nVertsNew = 0; - for (size_t i = 0; i < nVerts; ++i) - { - if (i == 0 || less(m_vertexNewToOld[i - 1], m_vertexNewToOld[i])) - { - m_vertexNewToOld[nVertsNew++] = m_vertexNewToOld[i]; - } - m_vertexOldToNew[m_vertexNewToOld[i]] = nVertsNew - 1; - } - m_vertexNewToOld.resize(nVertsNew); - } - - // Changes order of vertices, number of vertices, vertex indices in faces - void RemoveVerticesByUsingComputedRemapping() - { - CompactVertices(m_positions, m_vertexNewToOld); - CompactVertices(m_topologyIds, m_vertexNewToOld); - CompactVertices(m_normals, m_vertexNewToOld); - for (uint streamIndex = 0; streamIndex < m_texCoords.size(); ++streamIndex) - { - CompactVertices(m_texCoords[streamIndex], m_vertexNewToOld); - } - CompactVertices(m_colors, m_vertexNewToOld); - CompactVertices(m_alphas, m_vertexNewToOld); - CompactVertices(m_links, m_vertexNewToOld); - CompactVertices(m_vertexMatIds, m_vertexNewToOld); - CompactVerticesRaw(m_aux, m_auxSizeof, m_vertexNewToOld); - - for (size_t i = 0, count = m_faces.size(); i < count; ++i) - { - for (int j = 0; j < 3; ++j) - { - const int oldVertedIdx = m_faces[i].vertexIndex[j]; - assert(oldVertedIdx >= 0 && (size_t)oldVertedIdx < m_vertexOldToNew.size()); - const int newVertexIndex = m_vertexOldToNew[oldVertedIdx]; - m_faces[i].vertexIndex[j] = newVertexIndex; - } - } - } - - // Deleting degraded faces (faces with two or more vertices - // sharing same position in space) - void RemoveDegradedFaces() - { - size_t j = 0; - - for (size_t i = 0, count = m_faces.size(); i < count; ++i) - { - const Vec3& p0 = m_positions[m_faces[i].vertexIndex[0]]; - const Vec3& p1 = m_positions[m_faces[i].vertexIndex[1]]; - const Vec3& p2 = m_positions[m_faces[i].vertexIndex[2]]; - if (p0 != p1 && p1 != p2 && p2 != p0) - { - m_faces[j] = m_faces[i]; - if (!m_faceMatIds.empty()) - { - m_faceMatIds[j] = m_faceMatIds[i]; - } - ++j; - } - } - - m_faces.resize(j); - if (!m_faceMatIds.empty()) - { - m_faceMatIds.resize(j); - } - } - - private: - ////////////////////////////////////////////////////////////////////////// - // Internal helpers - - template - static void CompactVertices(std::vector& arr, const std::vector& newToOld) - { - if (arr.empty()) - { - return; - } - - const size_t newCount = newToOld.size(); - - std::vector tmp; - tmp.reserve(newCount); - - for (size_t i = 0; i < newCount; ++i) - { - tmp.push_back(arr[newToOld[i]]); - } - - arr.swap(tmp); - } - - static void CompactVerticesRaw(std::vector& arr, size_t elemSizeof, const std::vector& newToOld) - { - if (arr.empty()) - { - return; - } - - const size_t newCount = newToOld.size(); - - std::vector tmp; - tmp.resize(newCount * elemSizeof); - - for (size_t i = 0; i < newCount; ++i) - { - memcpy(&tmp[i * elemSizeof], &arr[newToOld[i] * elemSizeof], elemSizeof); - } - - arr.swap(tmp); - } - - struct VertexLess - { - const Mesh& m; - - VertexLess(const Mesh& mesh) - : m(mesh) - { - } - - bool operator()(int a, int b) const - { - if (!m.m_topologyIds.empty()) - { - const int res = m.m_topologyIds[a] - m.m_topologyIds[b]; - if (res != 0) - { - return res < 0; - } - } - - { - const int res = memcmp(&m.m_positions[a], &m.m_positions[b], sizeof(m.m_positions[0])); - if (res != 0) - { - return res < 0; - } - } - - int res = 0; - - if (res == 0 && !m.m_normals.empty()) - { - res = memcmp(&m.m_normals[a], &m.m_normals[b], sizeof(m.m_normals[0])); - } - - for (uint streamIndex = 0; streamIndex < m.m_texCoords.size(); ++streamIndex) - { - if (res == 0 && !m.m_texCoords[streamIndex].empty()) - { - res = memcmp(&m.m_texCoords[streamIndex][a], &m.m_texCoords[streamIndex][b], sizeof(m.m_texCoords[streamIndex][0])); - } - } - - if (res == 0 && !m.m_colors.empty()) - { - res = memcmp(&m.m_colors[a], &m.m_colors[b], sizeof(m.m_colors[0])); - } - - if (res == 0 && !m.m_alphas.empty()) - { - res = (int)m.m_alphas[a] - (int)m.m_alphas[b]; - } - - if (res == 0 && !m.m_links.empty()) - { - if (m.m_links[a].links.size() != m.m_links[b].links.size()) - { - res = (m.m_links[a].links.size() < m.m_links[b].links.size()) ? -1 : +1; - } - else - { - res = memcmp(&m.m_links[a].links[0], &m.m_links[b].links[0], sizeof(m.m_links[a].links[0]) * m.m_links[a].links.size()); - } - } - - if (res == 0 && !m.m_vertexMatIds.empty()) - { - res = m.m_vertexMatIds[a] - m.m_vertexMatIds[b]; - } - - if (res == 0 && !m.m_aux.empty()) - { - res = memcmp(&m.m_aux[a * m.m_auxSizeof], &m.m_aux[b * m.m_auxSizeof], m.m_auxSizeof); - } - - return res < 0; - } - }; - }; -} // namespace MeshUtils - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MESHUTILS_H diff --git a/Code/Tools/CryCommonTools/Export/ModelData.cpp b/Code/Tools/CryCommonTools/Export/ModelData.cpp deleted file mode 100644 index 5a6baf170c..0000000000 --- a/Code/Tools/CryCommonTools/Export/ModelData.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ModelData.h" - -int ModelData::AddModel(const void* handle, const char* modelName, int parentModelIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString) -{ - int modelIndex = int(m_models.size()); - m_models.push_back(ModelEntry(handle, modelName, parentModelIndex, geometry, helperData, propertiesString)); - if (parentModelIndex >= 0) - { - m_models[parentModelIndex].children.push_back(modelIndex); - } - else - { - m_roots.push_back(modelIndex); - } - return modelIndex; -} - -const void* ModelData::GetModelHandle(int modelIndex) const -{ - return m_models[modelIndex].handle; -} - -const char* ModelData::GetModelName(int modelIndex) const -{ - return m_models[modelIndex].name.c_str(); -} - -void ModelData::SetTranslationRotationScale(int const modelIndex, const float* const translation, const float* const rotation, const float* const scale) -{ - for (int i = 0; i < 3; ++i) - { - m_models[modelIndex].translation[i] = translation[i]; - m_models[modelIndex].rotation[i] = rotation[i]; - m_models[modelIndex].scale[i] = scale[i]; - } -} - -void ModelData::GetTranslationRotationScale(int const modelIndex, float* const translation, float* const rotation, float* const scale) const -{ - for (int i = 0; i < 3; ++i) - { - translation[i] = m_models[modelIndex].translation[i]; - rotation[i] = m_models[modelIndex].rotation[i]; - scale[i] = m_models[modelIndex].scale[i]; - } -} - -const SHelperData& ModelData::GetHelperData(int modelIndex) const -{ - return m_models[modelIndex].helperData; -} - -const std::string& ModelData::GetProperties(int modelIndex) const -{ - return m_models[modelIndex].propertiesString; -} - -bool ModelData::IsRoot(int modelIndex) const -{ - return (m_models[modelIndex].parentIndex < 0); -} - -int ModelData::GetModelCount() const -{ - return int(m_models.size()); -} - -int ModelData::GetRootCount() const -{ - return int(m_roots.size()); -} - -int ModelData::GetRootIndex(int rootIndex) const -{ - return m_roots[rootIndex]; -} - -int ModelData::GetChildCount(int modelIndex) const -{ - return int(m_models[modelIndex].children.size()); -} - -int ModelData::GetChildIndex(int modelIndex, int childIndexIndex) const -{ - return m_models[modelIndex].children[childIndexIndex]; -} - -bool ModelData::HasGeometry(int modelIndex) const -{ - return m_models[modelIndex].geometry; -} - -ModelData::ModelEntry::ModelEntry(const void* a_handle, const std::string& a_name, int a_parentIndex, bool a_geometry, const SHelperData& a_helperData, const std::string& a_propertiesString) - : handle(a_handle) - , name(a_name) - , parentIndex(a_parentIndex) - , geometry(a_geometry) - , helperData(a_helperData) - , propertiesString(a_propertiesString) -{ - translation[0] = translation[1] = translation[2] = 0.0f; - rotation[0] = rotation[1] = rotation[2] = 0.0f; - scale[0] = scale[1] = scale[2] = 1.0f; -} diff --git a/Code/Tools/CryCommonTools/Export/ModelData.h b/Code/Tools/CryCommonTools/Export/ModelData.h deleted file mode 100644 index f6dcb1a921..0000000000 --- a/Code/Tools/CryCommonTools/Export/ModelData.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MODELDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MODELDATA_H -#pragma once - - -#include "IModelData.h" - -class ModelData - : public IModelData -{ -public: - // IModelData - virtual int AddModel(const void* handle, const char* name, int parentModelIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString); - virtual int GetModelCount() const; - virtual const void* GetModelHandle(int modelIndex) const; - virtual const char* GetModelName(int modelIndex) const; - virtual void SetTranslationRotationScale(int modelIndex, const float* translation, const float* rotation, const float* scale); - virtual void GetTranslationRotationScale(int modelIndex, float* translation, float* rotation, float* scale) const; - virtual const SHelperData& GetHelperData(int modelIndex) const; - virtual const std::string& GetProperties(int modelIndex) const; - virtual bool IsRoot(int modelIndex) const; - - int GetRootCount() const; - int GetRootIndex(int rootIndex) const; - int GetChildCount(int modelIndex) const; - int GetChildIndex(int modelIndex, int childIndexIndex) const; - bool HasGeometry(int modelIndex) const; - -private: - struct ModelEntry - { - ModelEntry(const void* handle, const std::string& name, int parentIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString); - - const void* handle; - std::string name; - int parentIndex; - bool geometry; - std::vector children; - float translation[3]; - float rotation[3]; - float scale[3]; - SHelperData helperData; - std::string propertiesString; - }; - - std::vector m_models; - std::vector m_roots; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MODELDATA_H diff --git a/Code/Tools/CryCommonTools/Export/MorphData.cpp b/Code/Tools/CryCommonTools/Export/MorphData.cpp deleted file mode 100644 index feadb87a33..0000000000 --- a/Code/Tools/CryCommonTools/Export/MorphData.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "MorphData.h" - -MorphData::MorphData() - : m_handle(0) -{ -} - -void MorphData::SetHandle(const void* handle) -{ - m_handle = handle; -} - -void MorphData::AddMorph(const void* handle, const char* name, const char* fullname) -{ - m_morphs.push_back(Entry(handle, name, fullname ? fullname : "")); -} - -const void* MorphData::GetHandle() const -{ - return m_handle; -} - -int MorphData::GetMorphCount() const -{ - return int(m_morphs.size()); -} - -std::string MorphData::GetMorphName(int morphIndex) const -{ - return m_morphs[morphIndex].name; -} - -std::string MorphData::GetMorphFullName(int morphIndex) const -{ - return m_morphs[morphIndex].fullname.length() > 0 ? m_morphs[morphIndex].fullname : m_morphs[morphIndex].name; -} - -const void* MorphData::GetMorphHandle(int morphIndex) const -{ - return m_morphs[morphIndex].handle; -} diff --git a/Code/Tools/CryCommonTools/Export/MorphData.h b/Code/Tools/CryCommonTools/Export/MorphData.h deleted file mode 100644 index c9c942905a..0000000000 --- a/Code/Tools/CryCommonTools/Export/MorphData.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MORPHDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MORPHDATA_H -#pragma once - - -#include "IMorphData.h" - -class MorphData - : public IMorphData -{ -public: - MorphData(); - - virtual void SetHandle(const void* handle); - virtual void AddMorph(const void* handle, const char* name, const char* fullname); - virtual const void* GetHandle() const; - virtual int GetMorphCount() const; - virtual const void* GetMorphHandle(int morphIndex) const; - - std::string GetMorphName(int morphIndex) const; - std::string GetMorphFullName(int morphIndex) const; - -private: - struct Entry - { - Entry(const void* handle, const std::string& name, const std::string& fullname) - : handle(handle) - , name(name) - , fullname(fullname) {} - const void* handle; - std::string name; - std::string fullname; - }; - - const void* m_handle; - std::vector m_morphs; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MORPHDATA_H diff --git a/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.cpp b/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.cpp deleted file mode 100644 index be924eedf3..0000000000 --- a/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "SingleAnimationExportSourceAdapter.h" -#include "IGeometryFileData.h" -#include - -SingleAnimationExportSourceAdapter::SingleAnimationExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) - : ExportSourceDecoratorBase(source) - , animationIndex(animationIndex) - , geometryFileData(geometryFileData) - , geometryFileIndex(geometryFileIndex) -{ - assert(this->animationIndex < this->source->GetAnimationCount()); -} - -float SingleAnimationExportSourceAdapter::GetDCCFrameRate() const -{ - return this->source->GetDCCFrameRate(); -} - -void SingleAnimationExportSourceAdapter::ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData) -{ - const int geometryFileIndex = geometryFileData->AddGeometryFile( - this->geometryFileData->GetGeometryFileHandle(this->geometryFileIndex), - this->geometryFileData->GetGeometryFileName(this->geometryFileIndex), - this->geometryFileData->GetProperties(this->geometryFileIndex)); -} - -void SingleAnimationExportSourceAdapter::ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData) -{ - assert(geometryFileIndex == 0); - this->source->ReadModels(this->geometryFileData, this->geometryFileIndex, modelData); -} - -void SingleAnimationExportSourceAdapter::ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* const modelData, int modelIndex, ISkeletonData* skeletonData) -{ - this->source->ReadSkinning(context, skinningData, modelData, modelIndex, skeletonData); -} - -bool SingleAnimationExportSourceAdapter::ReadSkeleton(const IGeometryFileData* const geometryFileData, int geometryFileIndex, const IModelData* const modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData) -{ - assert(geometryFileIndex == 0); - return this->source->ReadSkeleton(this->geometryFileData, this->geometryFileIndex, modelData, modelIndex, materialData, skeletonData); -} - -int SingleAnimationExportSourceAdapter::GetAnimationCount() const -{ - return 1; -} - -std::string SingleAnimationExportSourceAdapter::GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const -{ - assert(geometryFileIndex == 0); - assert(animationIndex == 0); - return this->source->GetAnimationName(this->geometryFileData, this->geometryFileIndex, this->animationIndex); -} - -void SingleAnimationExportSourceAdapter::GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const -{ - assert(animationIndex == 0); - this->source->GetAnimationTimeSpan(start, stop, this->animationIndex); -} - -void SingleAnimationExportSourceAdapter::ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const -{ - assert(animationIndex == 0); - this->source->ReadAnimationFlags(context, animationData, geometryFileData, modelData, modelIndex, skeletonData, this->animationIndex); -} - -IAnimationData* SingleAnimationExportSourceAdapter::ReadAnimation(IExportContext* context, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const -{ - assert(animationIndex == 0); - return this->source->ReadAnimation(context, geometryFileData, modelData, modelIndex, skeletonData, this->animationIndex, fps); -} diff --git a/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.h b/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.h deleted file mode 100644 index 13da9b47a0..0000000000 --- a/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SINGLEANIMATIONEXPORTSOURCEADAPTER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SINGLEANIMATIONEXPORTSOURCEADAPTER_H -#pragma once - - -#include "ExportSourceDecoratorBase.h" - -class SingleAnimationExportSourceAdapter - : public ExportSourceDecoratorBase -{ -public: - SingleAnimationExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryData, int geometryFileIndex, int animationIndex); - - virtual float GetDCCFrameRate() const; - - virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData); - virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData); - virtual void ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* modelData, int modelIndex, ISkeletonData* skeletonData); - virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData); - virtual int GetAnimationCount() const; - virtual std::string GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const; - virtual void GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const; - virtual void ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const; - virtual IAnimationData* ReadAnimation(IExportContext* context, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const; - -private: - int animationIndex; - IGeometryFileData* geometryFileData; - int geometryFileIndex; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SINGLEANIMATIONEXPORTSOURCEADAPTER_H diff --git a/Code/Tools/CryCommonTools/Export/SkeletonData.cpp b/Code/Tools/CryCommonTools/Export/SkeletonData.cpp deleted file mode 100644 index 13d38678b2..0000000000 --- a/Code/Tools/CryCommonTools/Export/SkeletonData.cpp +++ /dev/null @@ -1,309 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "SkeletonData.h" -#include - -int SkeletonData::AddBone(const void* handle, const char* name, int parentIndex) -{ - int modelIndex = int(m_bones.size()); - m_bones.push_back(BoneEntry(handle, name, parentIndex)); - m_nameBoneIndexMap.insert(std::make_pair(name, modelIndex)); - if (parentIndex >= 0) - { - m_bones[parentIndex].children.push_back(modelIndex); - } - else - { - m_roots.push_back(modelIndex); - } - return modelIndex; -} - -int SkeletonData::FindBone(const char* name) const -{ - std::map::const_iterator modelPos = m_nameBoneIndexMap.find(name); - return (modelPos != m_nameBoneIndexMap.end() ? (*modelPos).second : -1); -} - -const void* SkeletonData::GetBoneHandle(int boneIndex) const -{ - return m_bones[boneIndex].handle; -} - -int SkeletonData::GetBoneParentIndex(int boneIndex) const -{ - return m_bones[boneIndex].parentIndex; -} - -int SkeletonData::GetBoneCount() const -{ - return int(m_bones.size()); -} - -void SkeletonData::SetTranslation(int modelIndex, const float* vec) -{ - for (int i = 0; i < 3; ++i) - { - m_bones[modelIndex].translation[i] = vec[i]; - } -} - -void SkeletonData::SetRotation(int modelIndex, const float* vec) -{ - for (int i = 0; i < 3; ++i) - { - m_bones[modelIndex].rotation[i] = vec[i]; - } -} - -void SkeletonData::SetScale(int modelIndex, const float* vec) -{ - for (int i = 0; i < 3; ++i) - { - m_bones[modelIndex].scale[i] = vec[i]; - } -} - -void SkeletonData::SetParentFrameTranslation(int boneIndex, const float* vec) -{ - EnsureParentFrameExists(boneIndex); - std::copy(vec, vec + 3, m_bones[boneIndex].parentFrameTranslation); -} - -void SkeletonData::SetParentFrameRotation(int boneIndex, const float* vec) -{ - EnsureParentFrameExists(boneIndex); - std::copy(vec, vec + 3, m_bones[boneIndex].parentFrameRotation); -} - -void SkeletonData::SetParentFrameScale(int boneIndex, const float* vec) -{ - EnsureParentFrameExists(boneIndex); - std::copy(vec, vec + 3, m_bones[boneIndex].parentFrameScale); -} - -void SkeletonData::SetLimit(int boneIndex, Axis axis, Limit extreme, float limit) -{ - m_bones[boneIndex].limits.insert(std::make_pair(AxisLimit(axis, extreme), limit)); -} - -void SkeletonData::SetSpringTension(int boneIndex, Axis axis, float springTension) -{ - m_bones[boneIndex].springTensions.insert(std::make_pair(axis, springTension)); -} - -void SkeletonData::SetSpringAngle(int boneIndex, Axis axis, float springAngle) -{ - m_bones[boneIndex].springAngles.insert(std::make_pair(axis, springAngle)); -} - -void SkeletonData::SetAxisDamping(int boneIndex, Axis axis, float damping) -{ - m_bones[boneIndex].dampings.insert(std::make_pair(axis, damping)); -} - -void SkeletonData::SetPhysicalized(int boneIndex, bool physicalized) -{ - m_bones[boneIndex].physicalized = physicalized; -} - -void SkeletonData::SetHasGeometry(int boneIndex, bool hasGeometry) -{ - m_bones[boneIndex].hasGeometry = hasGeometry; -} - -void SkeletonData::SetBoneProperties(int boneIndex, const char* propertiesString) -{ - m_bones[boneIndex].propertiesString = propertiesString; -} - -void SkeletonData::SetBoneGeomProperties(int boneIndex, const char* propertiesString) -{ - m_bones[boneIndex].geomPropertiesString = propertiesString; -} - -bool SkeletonData::HasParentFrame(int boneIndex) const -{ - return m_bones[boneIndex].hasParentFrame; -} - -void SkeletonData::GetParentFrameTranslation(int boneIndex, float* vec) const -{ - std::copy(m_bones[boneIndex].parentFrameTranslation, m_bones[boneIndex].parentFrameTranslation + 3, vec); -} - -void SkeletonData::GetParentFrameRotation(int boneIndex, float* vec) const -{ - std::copy(m_bones[boneIndex].parentFrameRotation, m_bones[boneIndex].parentFrameRotation + 3, vec); -} - -void SkeletonData::GetParentFrameScale(int boneIndex, float* vec) const -{ - std::copy(m_bones[boneIndex].parentFrameScale, m_bones[boneIndex].parentFrameScale + 3, vec); -} - -bool SkeletonData::HasLimit(int boneIndex, Axis axis, Limit extreme) const -{ - return m_bones[boneIndex].limits.find(AxisLimit(axis, extreme)) != m_bones[boneIndex].limits.end(); -} - -float SkeletonData::GetLimit(int boneIndex, Axis axis, Limit extreme) const -{ - return (*m_bones[boneIndex].limits.find(AxisLimit(axis, extreme))).second; -} - -bool SkeletonData::HasSpringTension(int boneIndex, Axis axis) const -{ - return m_bones[boneIndex].springTensions.find(axis) != m_bones[boneIndex].springTensions.end(); -} - -float SkeletonData::GetSpringTension(int boneIndex, Axis axis) const -{ - return (*m_bones[boneIndex].springTensions.find(axis)).second; -} - -bool SkeletonData::HasSpringAngle(int boneIndex, Axis axis) const -{ - return m_bones[boneIndex].springAngles.find(axis) != m_bones[boneIndex].springAngles.end(); -} - -float SkeletonData::GetSpringAngle(int boneIndex, Axis axis) const -{ - return (*m_bones[boneIndex].springAngles.find(axis)).second; -} - -bool SkeletonData::HasAxisDamping(int boneIndex, Axis axis) const -{ - return m_bones[boneIndex].dampings.find(axis) != m_bones[boneIndex].dampings.end(); -} - -float SkeletonData::GetAxisDamping(int boneIndex, Axis axis) const -{ - return (*m_bones[boneIndex].dampings.find(axis)).second; -} - -bool SkeletonData::GetPhysicalized(int boneIndex) const -{ - return m_bones[boneIndex].physicalized; -} - -bool SkeletonData::HasGeometry(int boneIndex) const -{ - return m_bones[boneIndex].hasGeometry; -} - -int SkeletonData::GetRootCount() const -{ - return int(m_roots.size()); -} - -int SkeletonData::GetRootIndex(int rootIndex) const -{ - return m_roots[rootIndex]; -} - -int SkeletonData::GetParentIndex(int modelIndex) const -{ - return m_bones[modelIndex].parentIndex; -} - -const std::string SkeletonData::GetName(int modelIndex) const -{ - std::string copy(m_bones[modelIndex].name); - for (int i = 0, count = int(copy.size()); i < count; ++i) - { - if (!std::isalnum(copy[i]) && copy[i] != ' ') - { - copy[i] = '_'; - } - } - return copy; -} - - -const std::string SkeletonData::GetSafeName(int modelIndex) const -{ - std::string name = GetName(modelIndex); - std::replace_if(name.begin(), name.end(), std::isspace, '_'); - return name; -} - -int SkeletonData::GetChildCount(int modelIndex) const -{ - return int(m_bones[modelIndex].children.size()); -} - -int SkeletonData::GetChildIndex(int modelIndex, int childIndexIndex) const -{ - return m_bones[modelIndex].children[childIndexIndex]; -} - -void SkeletonData::GetTranslation(float* vec, int modelIndex) const -{ - for (int i = 0; i < 3; ++i) - { - vec[i] = m_bones[modelIndex].translation[i]; - } -} - -void SkeletonData::GetRotation(float* vec, int modelIndex) const -{ - for (int i = 0; i < 3; ++i) - { - vec[i] = m_bones[modelIndex].rotation[i]; - } -} - -void SkeletonData::GetScale(float* vec, int modelIndex) const -{ - for (int i = 0; i < 3; ++i) - { - vec[i] = m_bones[modelIndex].scale[i]; - } -} - -const std::string SkeletonData::GetBoneProperties(int boneIndex) const -{ - return m_bones[boneIndex].propertiesString; -} - -const std::string SkeletonData::GetBoneGeomProperties(int boneIndex) const -{ - return m_bones[boneIndex].geomPropertiesString; -} - -void SkeletonData::EnsureParentFrameExists(int boneIndex) -{ - if (!m_bones[boneIndex].hasParentFrame) - { - std::fill(m_bones[boneIndex].parentFrameTranslation, m_bones[boneIndex].parentFrameTranslation + 3, 0.0f); - std::fill(m_bones[boneIndex].parentFrameRotation, m_bones[boneIndex].parentFrameRotation + 3, 0.0f); - std::fill(m_bones[boneIndex].parentFrameScale, m_bones[boneIndex].parentFrameScale + 3, 0.0f); - m_bones[boneIndex].hasParentFrame = true; - } -} - -SkeletonData::BoneEntry::BoneEntry(const void* handle, const std::string& name, int parentIndex) - : handle(handle) - , name(name) - , parentIndex(parentIndex) - , hasParentFrame(false) - , physicalized(false) - , hasGeometry(hasGeometry) -{ - translation[0] = translation[1] = translation[2] = 0.0f; - rotation[0] = rotation[1] = rotation[2] = 0.0f; - scale[0] = scale[1] = scale[2] = 1.0f; -} diff --git a/Code/Tools/CryCommonTools/Export/SkeletonData.h b/Code/Tools/CryCommonTools/Export/SkeletonData.h deleted file mode 100644 index 60bd8274b7..0000000000 --- a/Code/Tools/CryCommonTools/Export/SkeletonData.h +++ /dev/null @@ -1,116 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKELETONDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKELETONDATA_H -#pragma once - - -#include "ISkeletonData.h" -#include -#include -#include - -class SkeletonData - : public ISkeletonData -{ -public: - // ISkeletonData - virtual int AddBone(const void* handle, const char* name, int parentIndex); - virtual int FindBone(const char* name) const; - virtual const void* GetBoneHandle(int boneIndex) const; - virtual int GetBoneParentIndex(int boneIndex) const; - virtual int GetBoneCount() const; - virtual void SetTranslation(int boneIndex, const float* vec); - virtual void SetRotation(int boneIndex, const float* vec); - virtual void SetScale(int boneIndex, const float* vec); - virtual void SetParentFrameTranslation(int boneIndex, const float* vec); - virtual void SetParentFrameRotation(int boneIndex, const float* vec); - virtual void SetParentFrameScale(int boneIndex, const float* vec); - virtual void SetLimit(int boneIndex, Axis axis, Limit extreme, float limit); - virtual void SetSpringTension(int boneIndex, Axis axis, float springTension); - virtual void SetSpringAngle(int boneIndex, Axis axis, float springAngle); - virtual void SetAxisDamping(int boneIndex, Axis axis, float damping); - virtual void SetPhysicalized(int boneIndex, bool physicalized); - virtual void SetHasGeometry(int boneIndex, bool hasGeometry); - virtual void SetBoneProperties(int boneIndex, const char* propertiesString); - virtual void SetBoneGeomProperties(int boneIndex, const char* propertiesString); - - bool HasParentFrame(int boneIndex) const; - void GetParentFrameTranslation(int boneIndex, float* vec) const; - void GetParentFrameRotation(int boneIndex, float* vec) const; - void GetParentFrameScale(int boneIndex, float* vec) const; - bool HasLimit(int boneIndex, Axis axis, Limit extreme) const; - float GetLimit(int boneIndex, Axis axis, Limit extreme) const; - bool HasSpringTension(int boneIndex, Axis axis) const; - float GetSpringTension(int boneIndex, Axis axis) const; - bool HasSpringAngle(int boneIndex, Axis axis) const; - float GetSpringAngle(int boneIndex, Axis axis) const; - bool HasAxisDamping(int boneIndex, Axis axis) const; - float GetAxisDamping(int boneIndex, Axis axis) const; - bool GetPhysicalized(int boneIndex) const; - bool HasGeometry(int boneIndex) const; - - int GetRootCount() const; - int GetRootIndex(int rootIndex) const; - int GetParentIndex(int boneIndex) const; - const std::string GetName(int boneIndex) const; - const std::string GetSafeName(int boneIndex) const; - int GetChildCount(int boneIndex) const; - int GetChildIndex(int boneIndex, int childIndexIndex) const; - void GetTranslation(float* vec, int boneIndex) const; - void GetRotation(float* vec, int boneIndex) const; - void GetScale(float* vec, int boneIndex) const; - const std::string GetBoneProperties(int boneIndex) const; - const std::string GetBoneGeomProperties(int boneIndex) const; - -private: - void EnsureParentFrameExists(int boneIndex); - - typedef std::pair AxisLimit; - typedef std::map AxisLimitLimitMap; - typedef std::map AxisSpringTensionMap; - typedef std::map AxisSpringAngleMap; - typedef std::map AxisDampingMap; - - struct BoneEntry - { - public: - BoneEntry(const void* handle, const std::string& name, int parentIndex); - const void* handle; - std::string name; - int parentIndex; - AxisLimitLimitMap limits; - AxisSpringTensionMap springTensions; - AxisSpringAngleMap springAngles; - AxisDampingMap dampings; - bool hasParentFrame; - float parentFrameTranslation[3]; - float parentFrameRotation[3]; - float parentFrameScale[3]; - bool physicalized; - std::vector children; - float translation[3]; - float rotation[3]; - float scale[3]; - bool hasGeometry; - std::string propertiesString; - std::string geomPropertiesString; - }; - - std::vector m_bones; - std::vector m_roots; - std::map m_nameBoneIndexMap; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKELETONDATA_H diff --git a/Code/Tools/CryCommonTools/Export/SkinningData.cpp b/Code/Tools/CryCommonTools/Export/SkinningData.cpp deleted file mode 100644 index eeef150cad..0000000000 --- a/Code/Tools/CryCommonTools/Export/SkinningData.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "SkinningData.h" - -void SkinningData::SetVertexCount(int vertexCount) -{ - m_weights.resize(vertexCount); -} - -void SkinningData::AddWeight(int vertexIndex, int boneIndex, float weight) -{ - m_weights[vertexIndex].push_back(BoneWeight(boneIndex, weight)); -} - -int SkinningData::GetVertexCount() const -{ - return int(m_weights.size()); -} - -int SkinningData::GetBoneLinkCount(int vertexIndex) const -{ - return int(m_weights[vertexIndex].size()); -} - -int SkinningData::GetBoneIndex(int vertexIndex, int linkIndex) const -{ - return m_weights[vertexIndex][linkIndex].boneIndex; -} - -float SkinningData::GetWeight(int vertexIndex, int linkIndex) const -{ - return m_weights[vertexIndex][linkIndex].weight; -} diff --git a/Code/Tools/CryCommonTools/Export/SkinningData.h b/Code/Tools/CryCommonTools/Export/SkinningData.h deleted file mode 100644 index 6e3a9a6712..0000000000 --- a/Code/Tools/CryCommonTools/Export/SkinningData.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKINNINGDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKINNINGDATA_H -#pragma once - - -#include "ISkinningData.h" - -class SkinningData - : public ISkinningData -{ -public: - virtual void SetVertexCount(int vertexCount); - virtual void AddWeight(int vertexIndex, int boneIndex, float weight); - - int GetVertexCount() const; - int GetBoneLinkCount(int vertexIndex) const; - int GetBoneIndex(int vertexIndex, int linkIndex) const; - float GetWeight(int vertexIndex, int linkIndex) const; - -private: - struct BoneWeight - { - BoneWeight(int boneIndex, float weight) - : boneIndex(boneIndex) - , weight(weight) {} - int boneIndex; - float weight; - }; - - std::vector > m_weights; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKINNINGDATA_H diff --git a/Code/Tools/CryCommonTools/Export/TransformHelpers.h b/Code/Tools/CryCommonTools/Export/TransformHelpers.h deleted file mode 100644 index cdddd78337..0000000000 --- a/Code/Tools/CryCommonTools/Export/TransformHelpers.h +++ /dev/null @@ -1,119 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_TRANSFORMHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_TRANSFORMHELPERS_H -#pragma once - - -#include "Cry_Math.h" - - -namespace TransformHelpers -{ - // Format of forwardUpAxes: "". - // Example of forwardUpAxes: "-Y+Z". - // Returns 0 if successful, or returns a pointer to an error message in case of an error. - // In case of success: X axis in res represents "forward" direction, - // Y axis represents "up" direction. - inline const char* GetForwardUpAxesMatrix(Matrix33& res, const char* forwardUpAxes) - { - Vec3 axisX(ZERO); - Vec3 axisY(ZERO); - - for (int i = 0; i < 2; ++i) - { - Vec3& v = (i == 0) ? axisX : axisY; - - const float val = forwardUpAxes[i * 2 + 0] == '-' ? -1.0f : +1.0f; - - switch (forwardUpAxes[i * 2 + 1]) - { - case 'X': - case 'x': - v.x = val; - break; - case 'Y': - case 'y': - v.y = val; - break; - case 'Z': - case 'z': - v.z = val; - break; - default: - assert(0); - return "Found a bad axis character in forwardUpAxes string"; - } - } - - if (axisX == axisY) - { - assert(0); - return "Forward and up axes are equal in forwardUpAxes string"; - } - - const Vec3 axisZ = axisX.cross(axisY); - - res.SetFromVectors(axisX, axisY, axisZ); - - return 0; - } - - - // Computes transform matrix that converts everything from forwardUpAxesSrc - // coordinate system to forwardUpAxesDst coordinate system. - // Format of forwardUpAxesXXX: "". - // Example of forwardUpAxesXXX: "-Y+Z". - // Returns 0 if successful, or returns a pointer to an error message in case of an error. - // In case of success puts computed transform into res. - // See comments to GetForwardUpAxesMatrix(). - inline const char* ComputeForwardUpAxesTransform(Matrix34& res, const char* forwardUpAxesSrc, const char* forwardUpAxesDst) - { - Matrix33 srcToWorld; - Matrix33 dstToWorld; - - const char* const err0 = GetForwardUpAxesMatrix(srcToWorld, forwardUpAxesSrc); - const char* const err1 = GetForwardUpAxesMatrix(dstToWorld, forwardUpAxesDst); - - if (err0 || err1) - { - return err0 ? err0 : err1; - } - - res = Matrix34(dstToWorld * srcToWorld.GetTransposed()); - - return 0; - } - - - inline Matrix34 ComputeOrthonormalMatrix(const Matrix34& m) - { - Vec3 x = m.GetColumn0(); - x.Normalize(); - - Vec3 y = m.GetColumn1(); - - Vec3 z = x.cross(y); - z.Normalize(); - - y = z.cross(x); - - Matrix34 result; - result.SetFromVectors(x, y, z, m.GetTranslation()); - - return result; - } -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_TRANSFORMHELPERS_H diff --git a/Code/Tools/CryCommonTools/UI/EULADialog.cpp b/Code/Tools/CryCommonTools/UI/EULADialog.cpp deleted file mode 100644 index a4b8696eea..0000000000 --- a/Code/Tools/CryCommonTools/UI/EULADialog.cpp +++ /dev/null @@ -1,132 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "EULADialog.h" -#include "Win32GUI.h" -#include "ModuleHelpers.h" -#include "Richedit.h" -#include - -EULADialog::EULADialog() - : m_frameWindow() - , m_cancelButton(_T("Cancel"), this, &EULADialog::CancelPressed) - , m_buttonSpacer(0, 0, 2000, 0) - , m_acceptButton(_T("Accept"), this, &EULADialog::AcceptPressed) - , m_buttonLayout(Layout::DirectionHorizontal) - , m_edit() -{ - Win32GUI::Initialize(); - - m_buttonLayout.AddComponent(&m_buttonSpacer); - m_buttonLayout.AddComponent(&m_cancelButton); - m_buttonLayout.AddComponent(&m_acceptButton); - - m_frameWindow.AddComponent(&m_edit); - m_frameWindow.AddComponent(&m_buttonLayout); -} - -namespace -{ - class EditStreamCallbackObject - { - public: - EditStreamCallbackObject(const char* data, int size) - : data(data) - , position(0) - , size(size) {} - static DWORD WINAPI EditStreamCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG* pcb) - { - return ((EditStreamCallbackObject*)dwCookie)->EditStreamCallback_Member(dwCookie, pbBuff, cb, pcb); - } - - private: - DWORD EditStreamCallback_Member(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG* pcb) - { - int bytesToRead = (std::min)(this->size - this->position, (int)cb); - std::memcpy(pbBuff, this->data + this->position, bytesToRead); - this->position += bytesToRead; - if (pcb) - { - *pcb = bytesToRead; - } - return 0; - } - - const char* data; - int position; - int size; - }; -} - -EULADialog::UserResponse EULADialog::Run(int width, int height, TCHAR* resourceID) -{ - m_frameWindow.Show(true, width, height); - - // Attempt to load the resource. - HINSTANCE module = ModuleHelpers::GetCurrentModule(ModuleHelpers::CurrentModuleSpecifier_Library); - HRSRC resource = (resourceID ? FindResource(module, resourceID, RT_RCDATA) : 0); - int resourceLength = (resource ? SizeofResource(module, resource) : 0); - HGLOBAL resourceGlobal = (resource ? LoadResource(module, resource) : 0); - void* resourceData = (resourceGlobal ? LockResource(resourceGlobal) : 0); - // No need to unlock/delete data. - - m_userResponse = UserResponseNone; - - // Load the text. - if (resourceData && resourceLength > 0) - { - EditStreamCallbackObject callbackObject((const char*)resourceData, resourceLength); - EDITSTREAM editStream; - std::memset(&editStream, 0, sizeof(editStream)); - editStream.dwCookie = (DWORD_PTR)&callbackObject; - editStream.pfnCallback = &EditStreamCallbackObject::EditStreamCallback; - SendMessage((HWND)m_edit.m_edit, EM_STREAMIN, SF_RTF, (LPARAM)&editStream); - } - - MSG msg; - BOOL status; - bool waitingAcceptance = false; - while (m_userResponse == UserResponseNone && (status = GetMessage(&msg, HWND(0), UINT(0), UINT(0))) != 0) - { - if (status == -1) - { - break; - } - else - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - - m_frameWindow.Show(false, 0, 0); - - return m_userResponse; -} - -void EULADialog::CancelPressed() -{ - m_userResponse = UserResponseCancel; -} - -void EULADialog::AcceptPressed() -{ - m_userResponse = UserResponseAccept; -} - -EULADialog::UserResponse EULADialog::Show(int width, int height, TCHAR* resourceID) -{ - EULADialog dlg; - return dlg.Run(width, height, resourceID); -} diff --git a/Code/Tools/CryCommonTools/UI/EULADialog.h b/Code/Tools/CryCommonTools/UI/EULADialog.h deleted file mode 100644 index 4af9bde758..0000000000 --- a/Code/Tools/CryCommonTools/UI/EULADialog.h +++ /dev/null @@ -1,55 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_EULADIALOG_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_EULADIALOG_H -#pragma once - - -#include "FrameWindow.h" -#include "EditControl.h" -#include "Spacer.h" -#include "Layout.h" -#include "PushButton.h" - -class EULADialog -{ -public: - enum UserResponse - { - UserResponseNone, - UserResponseCancel, - UserResponseAccept - }; - - static UserResponse Show(int width, int height, TCHAR* resourceID); - -private: - EULADialog(); - - UserResponse Run(int width, int height, TCHAR* resourceID); - - void CancelPressed(); - void AcceptPressed(); - - FrameWindow m_frameWindow; - PushButton m_cancelButton; - Spacer m_buttonSpacer; - PushButton m_acceptButton; - Layout m_buttonLayout; - EditControl m_edit; - - UserResponse m_userResponse; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_EULADIALOG_H diff --git a/Code/Tools/CryCommonTools/UI/EditControl.cpp b/Code/Tools/CryCommonTools/UI/EditControl.cpp deleted file mode 100644 index 61ac51f41d..0000000000 --- a/Code/Tools/CryCommonTools/UI/EditControl.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "EditControl.h" -#include "Win32GUI.h" -#include -#include -#include - -EditControl::EditControl() - : m_edit(0) -{ -} - -void EditControl::CreateUI(void* window, int left, int top, int width, int height) -{ - m_edit = Win32GUI::CreateControl(RICHEDIT_CLASS, ES_MULTILINE /*| ES_READONLY*/, (HWND)window, left, top, width, height); -} - -void EditControl::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_edit, left, top, width, height, true); -} - -void EditControl::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_edit); - m_edit = 0; -} - -void EditControl::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 20; - maxWidth = 2000; - minHeight = 20; - maxHeight = 2000; -} diff --git a/Code/Tools/CryCommonTools/UI/EditControl.h b/Code/Tools/CryCommonTools/UI/EditControl.h deleted file mode 100644 index da00059e94..0000000000 --- a/Code/Tools/CryCommonTools/UI/EditControl.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_EDITCONTROL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_EDITCONTROL_H -#pragma once - - -#include "IUIComponent.h" - -class EditControl - : public IUIComponent -{ -public: - EditControl(); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - - void* m_edit; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_EDITCONTROL_H diff --git a/Code/Tools/CryCommonTools/UI/FrameWindow.cpp b/Code/Tools/CryCommonTools/UI/FrameWindow.cpp deleted file mode 100644 index feaa7ab293..0000000000 --- a/Code/Tools/CryCommonTools/UI/FrameWindow.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "FrameWindow.h" -#include "Win32GUI.h" -#include "IUIComponent.h" -#include -#include - -FrameWindow::FrameWindow() - : m_hwnd(0) - , m_layout(Layout::DirectionVertical) -{ -} - -FrameWindow::~FrameWindow() -{ - if (m_hwnd) - { - Show(false, 0, 0); - } -} - -void FrameWindow::AddComponent(IUIComponent* component) -{ - assert(m_hwnd == 0); - m_layout.AddComponent(component); -} - -void FrameWindow::Show(bool show, int width, int height) -{ - if (show) - { - assert(m_hwnd == 0); - TCHAR* className = _T("CustomFrameWindowClass212"); - Win32GUI::RegisterFrameClass(className); - m_hwnd = Win32GUI::CreateFrame(className, WS_MINIMIZEBOX | WS_OVERLAPPED | WS_THICKFRAME | WS_CAPTION | WS_SYSMENU | WS_MAXIMIZEBOX, width, height); - Win32GUI::SetCallback((HWND)m_hwnd, this, &FrameWindow::CalculateExtremeDimensions); - Win32GUI::SetCallback((HWND)m_hwnd, this, &FrameWindow::OnSizeChanged); - std::pair size = InitializeSize(); - m_layout.CreateUI(m_hwnd, 0, 0, size.first, size.second); - ShowWindow((HWND)m_hwnd, SW_SHOWDEFAULT); - } - else - { - m_layout.DestroyUI(m_hwnd); - assert(m_hwnd != 0); - DestroyWindow((HWND)m_hwnd); - m_hwnd = 0; - } -} - -void FrameWindow::SetCaption(const TCHAR* caption) -{ - SendMessage((HWND)m_hwnd, WM_SETTEXT, 0, (LPARAM)caption); -} - -void* FrameWindow::GetHWND() -{ - return m_hwnd; -} - -std::pair FrameWindow::InitializeSize() -{ - int minW, maxW, minH, maxH; - CalculateExtremeDimensions(minW, maxW, minH, maxH); - RECT rect; - GetWindowRect((HWND)m_hwnd, &rect); - int width = int((std::min)(maxW, (std::max)(minW, int(rect.right - rect.left)))); - int height = int((std::min)(maxH, (std::max)(minH, int(rect.bottom - rect.top)))); - MoveWindow((HWND)m_hwnd, rect.left, rect.top, width, height, false); - return std::make_pair(width, height); -} - -void FrameWindow::CalculateExtremeDimensions(int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - int minW = 0; - int maxW = 0; - int minH = 0; - int maxH = 0; - m_layout.GetExtremeDimensions(m_hwnd, minW, maxW, minH, maxH); - - // Add the space required for the window decorations. - RECT rect; - rect.left = 0, rect.top = 0, rect.right = minW, rect.bottom = minH; - unsigned style = GetWindowLong((HWND)m_hwnd, GWL_STYLE); - AdjustWindowRect(&rect, style, false); - minW = rect.right - rect.left; - minH = rect.bottom - rect.top; - - rect.left = 0, rect.top = 0, rect.right = maxW, rect.bottom = maxH; - AdjustWindowRect(&rect, style, false); - maxW = rect.right - rect.left; - maxH = rect.bottom - rect.top; - - minWidth = minW; - maxWidth = maxW; - minHeight = minH; - maxHeight = maxH; -} - -void FrameWindow::OnSizeChanged(int width, int height) -{ - m_layout.Resize(m_hwnd, 0, 0, width, height); -} diff --git a/Code/Tools/CryCommonTools/UI/FrameWindow.h b/Code/Tools/CryCommonTools/UI/FrameWindow.h deleted file mode 100644 index ff1bba893d..0000000000 --- a/Code/Tools/CryCommonTools/UI/FrameWindow.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_FRAMEWINDOW_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_FRAMEWINDOW_H -#pragma once - - -#include -#include "Layout.h" - -class IUIComponent; - -class FrameWindow -{ -public: - FrameWindow(); - ~FrameWindow(); - void AddComponent(IUIComponent* component); - void Show(bool show, int width, int height); - void SetCaption(const TCHAR* caption); - void* GetHWND(); - -private: - void UpdateComponentUI(bool create); - std::pair InitializeSize(); - void CalculateExtremeDimensions(int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - void OnSizeChanged(int width, int height); - - void* m_hwnd; - Layout m_layout; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_FRAMEWINDOW_H diff --git a/Code/Tools/CryCommonTools/UI/IUIComponent.h b/Code/Tools/CryCommonTools/UI/IUIComponent.h deleted file mode 100644 index 08b06c424b..0000000000 --- a/Code/Tools/CryCommonTools/UI/IUIComponent.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_IUICOMPONENT_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_IUICOMPONENT_H -#pragma once - - -class IUIComponent -{ -public: - virtual void CreateUI(void* window, int left, int top, int width, int height) = 0; - virtual void Resize(void* window, int left, int top, int width, int height) = 0; - virtual void DestroyUI(void* window) = 0; - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_IUICOMPONENT_H diff --git a/Code/Tools/CryCommonTools/UI/Layout.cpp b/Code/Tools/CryCommonTools/UI/Layout.cpp deleted file mode 100644 index 3225544be2..0000000000 --- a/Code/Tools/CryCommonTools/UI/Layout.cpp +++ /dev/null @@ -1,233 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "Layout.h" -#include -#include - -Layout::Layout(Direction direction) - : m_direction(direction) -{ -} - -void Layout::AddComponent(IUIComponent* component) -{ - m_components.push_back(ComponentEntry(component)); -} - -void Layout::CreateUI(void* window, int left, int top, int width, int height) -{ - UpdateLayout(window, left, top, width, height); - - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - component->CreateUI(window, m_components[componentIndex].left, m_components[componentIndex].top, m_components[componentIndex].width, m_components[componentIndex].height); - } -} - -void Layout::Resize(void* window, int left, int top, int width, int height) -{ - UpdateLayout(window, left, top, width, height); - - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - component->Resize(window, m_components[componentIndex].left, m_components[componentIndex].top, m_components[componentIndex].width, m_components[componentIndex].height); - } -} - -void Layout::DestroyUI(void* window) -{ - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - component->DestroyUI(window); - } -} - -void Layout::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - int minW = 0; - int maxW = 0; - int minH = 0; - int maxH = 0; - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - int compMinW, compMaxW, compMinH, compMaxH; - component->GetExtremeDimensions(window, compMinW, compMaxW, compMinH, compMaxH); - switch (m_direction) - { - case DirectionVertical: - minW = (minW > compMinW ? minW : compMinW); - maxW = (maxW > compMaxW ? maxW : compMaxW); // Deliberately take the larger maximum. - minH += compMinH; - maxH += compMaxH; - break; - case DirectionHorizontal: - minW += compMinW; - maxW += compMaxW; - minH = (minH > compMinH ? minH : compMinH); - maxH = (maxH > compMaxH ? maxH : compMaxH); // Deliberately take the larger maximum. - break; - } - } - - // Make sure the window is at least a certain size; - minW = (minW >= 10 ? minW : 10); - maxW = (maxW >= minW ? maxW : minW); - minH = (minH >= 10 ? minH : 10); - maxH = (maxH >= minH ? maxH : minH); - - minWidth = minW; - maxWidth = maxW; - minHeight = minH; - maxHeight = maxH; -} - -void Layout::UpdateLayout(void* window, int left, int top, int width, int height) -{ - assert(window); - - int remainingToAllocate; - switch (m_direction) - { - case DirectionVertical: - remainingToAllocate = height; - break; - case DirectionHorizontal: - remainingToAllocate = width; - break; - } - - int smallestAllocationAmount = INT_MAX; - int canBeExtendedCount = 0; - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - int compMinW, compMaxW, compMinH, compMaxH; - component->GetExtremeDimensions(window, compMinW, compMaxW, compMinH, compMaxH); - - switch (m_direction) - { - case DirectionVertical: - { - int allocationAmount = compMaxH - compMinH; - if (allocationAmount > 0) - { - ++canBeExtendedCount; - smallestAllocationAmount = (smallestAllocationAmount < allocationAmount ? smallestAllocationAmount : allocationAmount); - } - m_components[componentIndex].height = compMinH; - m_components[componentIndex].width = (width > compMaxW ? compMaxW : width); - remainingToAllocate -= m_components[componentIndex].height; - } - break; - - case DirectionHorizontal: - { - int allocationAmount = compMaxW - compMinW; - if (allocationAmount > 0) - { - ++canBeExtendedCount; - smallestAllocationAmount = (smallestAllocationAmount < allocationAmount ? smallestAllocationAmount : allocationAmount); - } - m_components[componentIndex].width = compMinW; - m_components[componentIndex].height = (height > compMaxH ? compMaxH : height); - remainingToAllocate -= m_components[componentIndex].width; - } - break; - } - } - - while (remainingToAllocate > 0 && canBeExtendedCount > 0) - { - int equitablePerCompAllocation = remainingToAllocate / canBeExtendedCount; - int compAllocation = (equitablePerCompAllocation < smallestAllocationAmount ? equitablePerCompAllocation : smallestAllocationAmount); - compAllocation = (compAllocation > 0 ? compAllocation : 1); - canBeExtendedCount = 0; - smallestAllocationAmount = INT_MAX; - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - int compMinW, compMaxW, compMinH, compMaxH; - component->GetExtremeDimensions(window, compMinW, compMaxW, compMinH, compMaxH); - switch (m_direction) - { - case DirectionVertical: - { - int componentExpandAmount = compMaxH - m_components[componentIndex].height; - if (componentExpandAmount > 0) - { - m_components[componentIndex].height += compAllocation; - assert(m_components[componentIndex].height <= compMaxH); - componentExpandAmount -= compAllocation; - remainingToAllocate -= compAllocation; - if (componentExpandAmount > 0) - { - smallestAllocationAmount = (smallestAllocationAmount < componentExpandAmount ? smallestAllocationAmount : componentExpandAmount); - ++canBeExtendedCount; - } - } - } - break; - - case DirectionHorizontal: - { - int componentExpandAmount = compMaxW - m_components[componentIndex].width; - if (componentExpandAmount > 0) - { - m_components[componentIndex].width += compAllocation; - assert(m_components[componentIndex].width <= compMaxW); - componentExpandAmount -= compAllocation; - remainingToAllocate -= compAllocation; - if (componentExpandAmount > 0) - { - smallestAllocationAmount = (smallestAllocationAmount < componentExpandAmount ? smallestAllocationAmount : componentExpandAmount); - ++canBeExtendedCount; - } - } - } - break; - } - } - } - - switch (m_direction) - { - case DirectionVertical: - { - int posY = top; - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - m_components[componentIndex].left = left; - m_components[componentIndex].top = posY; - posY += m_components[componentIndex].height; - } - } - break; - case DirectionHorizontal: - { - int posX = left; - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - m_components[componentIndex].top = top; - m_components[componentIndex].left = posX; - posX += m_components[componentIndex].width; - } - } - break; - } -} diff --git a/Code/Tools/CryCommonTools/UI/Layout.h b/Code/Tools/CryCommonTools/UI/Layout.h deleted file mode 100644 index a2de6c4f69..0000000000 --- a/Code/Tools/CryCommonTools/UI/Layout.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_LAYOUT_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_LAYOUT_H -#pragma once - - -#include "IUIComponent.h" -#include - -class Layout - : public IUIComponent -{ -public: - enum Direction - { - DirectionHorizontal, - DirectionVertical - }; - Layout(Direction direction); - void AddComponent(IUIComponent* component); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - void UpdateLayout(void* window, int left, int top, int width, int height); - - struct ComponentEntry - { - explicit ComponentEntry(IUIComponent* component) - : component(component) - , left(0) - , top(0) - , width(0) - , height(0) {} - IUIComponent* component; - int left; - int top; - int width; - int height; - }; - std::vector m_components; - Direction m_direction; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_LAYOUT_H diff --git a/Code/Tools/CryCommonTools/UI/ListView.cpp b/Code/Tools/CryCommonTools/UI/ListView.cpp deleted file mode 100644 index dc43d41fc8..0000000000 --- a/Code/Tools/CryCommonTools/UI/ListView.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ListView.h" -#include "Win32GUI.h" -#include "resource.h" -#include "ModuleHelpers.h" -#include -#include -#include - -ListView::ListView() - : m_list(0) -{ -} - -void ListView::Add(int imageIndex, const TCHAR* message) -{ - int itemCount = int(SendMessage((HWND)m_list, LVM_GETITEMCOUNT, 0, 0)); - - LVITEM item; - std::memset(&item, 0, sizeof(item)); - item.mask = LVIF_TEXT | LVIF_IMAGE; - item.iItem = itemCount; - item.iSubItem = 0; - item.pszText = (TCHAR*)message; - item.iImage = imageIndex; - - SendMessage((HWND)m_list, LVM_INSERTITEM, 0, (LPARAM)&item); -} - -void ListView::Clear() -{ - SendMessage((HWND)m_list, LVM_DELETEALLITEMS, 0, 0); -} - -void ListView::CreateUI(void* window, int left, int top, int width, int height) -{ - m_list = Win32GUI::CreateControl(WC_LISTVIEW, LVS_REPORT | LVS_NOCOLUMNHEADER, (HWND)window, left, top, width, height); - - LVCOLUMN column; - std::memset(&column, 0, sizeof(column)); - column.mask = LVCF_TEXT | LVCF_WIDTH; - column.pszText = _T("Message"); - column.cx = width; - SendMessage((HWND)m_list, LVM_INSERTCOLUMN, 0, (LPARAM)&column); - - HIMAGELIST imageList = (HIMAGELIST)CreateImageList(); - SendMessage((HWND)m_list, LVM_SETIMAGELIST, LVSIL_SMALL, (LPARAM)imageList); -} - -void ListView::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_list, left, top, width, height, true); - SendMessage((HWND)m_list, LVM_SETCOLUMNWIDTH, 0, width); -} - -void ListView::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_list); - m_list = 0; -} - -void ListView::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 20; - maxWidth = 2000; - minHeight = 20; - maxHeight = 2000; -} - -void* ListView::CreateImageList() -{ - HINSTANCE instance = ModuleHelpers::GetCurrentModule(ModuleHelpers::CurrentModuleSpecifier_Library); - - HBITMAP image = (HBITMAP)LoadImage(instance, MAKEINTRESOURCE(IDB_LOG_ICONS), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION); - DIBSECTION dibSection; - GetObject(image, sizeof(dibSection), &dibSection); - int height = dibSection.dsBmih.biHeight; - int width = height; - int count = dibSection.dsBmih.biWidth / width; - HIMAGELIST imageList = ImageList_Create(16, 16, ILC_COLOR32, count, 0); - ImageList_Add(imageList, image, 0); - return imageList; -} diff --git a/Code/Tools/CryCommonTools/UI/ListView.h b/Code/Tools/CryCommonTools/UI/ListView.h deleted file mode 100644 index 60531dd13d..0000000000 --- a/Code/Tools/CryCommonTools/UI/ListView.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_LISTVIEW_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_LISTVIEW_H -#pragma once - - -#include "IUIComponent.h" - -class ListView - : public IUIComponent -{ -public: - ListView(); - - void Add(int imageIndex, const TCHAR* message); - void Clear(); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - void* CreateImageList(); - - void* m_list; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_LISTVIEW_H diff --git a/Code/Tools/CryCommonTools/UI/LogWindow.cpp b/Code/Tools/CryCommonTools/UI/LogWindow.cpp deleted file mode 100644 index af96a389e1..0000000000 --- a/Code/Tools/CryCommonTools/UI/LogWindow.cpp +++ /dev/null @@ -1,158 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "LogWindow.h" - -LogWindow::LogWindow() - : m_mainLayout(Layout::DirectionVertical) - , m_toolbarLayout(Layout::DirectionHorizontal) - , m_filterFlags(0) -{ - m_buttons.push_back(new ToggleButton(_T("Debug"), this, &LogWindow::DebugToggled)); - m_buttons.push_back(new ToggleButton(_T("Info"), this, &LogWindow::InfoToggled)); - m_buttons.push_back(new ToggleButton(_T("Warnings"), this, &LogWindow::WarningsToggled)); - m_buttons.push_back(new ToggleButton(_T("Errors"), this, &LogWindow::ErrorsToggled)); - - SetFilter(ILogger::eSeverity_Error, true); - SetFilter(ILogger::eSeverity_Warning, true); - SetFilter(ILogger::eSeverity_Info, true); - SetFilter(ILogger::eSeverity_Debug, false); - - m_toolbarLayout.AddComponent(m_buttons[3]); - m_toolbarLayout.AddComponent(m_buttons[2]); - m_toolbarLayout.AddComponent(m_buttons[1]); - m_toolbarLayout.AddComponent(m_buttons[0]); - - m_mainLayout.AddComponent(&m_toolbarLayout); - m_mainLayout.AddComponent(&m_list); -} - -LogWindow::~LogWindow() -{ - for (std::vector::iterator button = m_buttons.begin(), end = m_buttons.end(); button != end; ++button) - { - delete *button; - } -} - -void LogWindow::Log(ILogger::ESeverity eSeverity, const TCHAR* message) -{ - m_messages.push_back(LogMessage(eSeverity, message)); - - if (m_filterFlags & (1 << GetSeverityIndex(eSeverity))) - { - m_list.Add(GetImageIndex(eSeverity), message); - } -} - -void LogWindow::SetFilter(ILogger::ESeverity eSeverity, bool visible) -{ - int index = GetSeverityIndex(eSeverity); - if (visible) - { - m_filterFlags |= (1 << index); - } - else - { - m_filterFlags &= ~(1 << index); - } - m_buttons[index]->SetState(visible); - RefillList(); -} - -void LogWindow::CreateUI(void* window, int left, int top, int width, int height) -{ - m_mainLayout.CreateUI(window, left, top, width, height); -} - -void LogWindow::Resize(void* window, int left, int top, int width, int height) -{ - m_mainLayout.Resize(window, left, top, width, height); -} - -void LogWindow::DestroyUI(void* window) -{ - m_mainLayout.DestroyUI(window); -} - -void LogWindow::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - m_mainLayout.GetExtremeDimensions(window, minWidth, maxWidth, minHeight, maxHeight); -} - -void LogWindow::ErrorsToggled(bool value) -{ - SetFilter(ILogger::eSeverity_Error, value); -} - -void LogWindow::WarningsToggled(bool value) -{ - SetFilter(ILogger::eSeverity_Warning, value); -} - -void LogWindow::InfoToggled(bool value) -{ - SetFilter(ILogger::eSeverity_Info, value); -} - -void LogWindow::DebugToggled(bool value) -{ - SetFilter(ILogger::eSeverity_Debug, value); -} - -void LogWindow::RefillList() -{ - m_list.Clear(); - for (int messageIndex = 0, messageCount = int(m_messages.size()); messageIndex < messageCount; ++messageIndex) - { - if (m_filterFlags & (1 << m_messages[messageIndex].severity)) - { - m_list.Add(GetImageIndex(m_messages[messageIndex].severity), m_messages[messageIndex].message.c_str()); - } - } -} - -int LogWindow::GetImageIndex(ILogger::ESeverity eSeverity) -{ - switch (eSeverity) - { - case ILogger::eSeverity_Debug: - return 2; - case ILogger::eSeverity_Info: - return -1; - case ILogger::eSeverity_Warning: - return 1; - case ILogger::eSeverity_Error: - return 0; - default: - return 0; - } -} - -int LogWindow::GetSeverityIndex(ILogger::ESeverity eSeverity) -{ - switch (eSeverity) - { - case ILogger::eSeverity_Debug: - return 0; - case ILogger::eSeverity_Info: - return 1; - case ILogger::eSeverity_Warning: - return 2; - case ILogger::eSeverity_Error: - return 3; - default: - return 3; - } -} diff --git a/Code/Tools/CryCommonTools/UI/LogWindow.h b/Code/Tools/CryCommonTools/UI/LogWindow.h deleted file mode 100644 index 13afeac57c..0000000000 --- a/Code/Tools/CryCommonTools/UI/LogWindow.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_LOGWINDOW_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_LOGWINDOW_H -#pragma once - - -#include "IUIComponent.h" -#include "Layout.h" -#include "ListView.h" -#include "ToggleButton.h" -#include -#include "ILogger.h" - -class LogWindow - : public IUIComponent -{ -public: - LogWindow(); - ~LogWindow(); - - void Log(ILogger::ESeverity eSeverity, const TCHAR* message); - void SetFilter(ILogger::ESeverity eSeverity, bool visible); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - struct LogMessage - { - LogMessage(ILogger::ESeverity severity, tstring message) - : severity(severity) - , message(message) - { - } - ILogger::ESeverity severity; - tstring message; - }; - - void ErrorsToggled(bool value); - void WarningsToggled(bool value); - void InfoToggled(bool value); - void DebugToggled(bool value); - void RefillList(); - static int GetImageIndex(ILogger::ESeverity eSeverity); - static int GetSeverityIndex(ILogger::ESeverity eSeverity); - - Layout m_mainLayout; - Layout m_toolbarLayout; - ListView m_list; - std::vector m_buttons; - std::vector m_messages; - - unsigned m_filterFlags; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_LOGWINDOW_H diff --git a/Code/Tools/CryCommonTools/UI/ProgressBar.cpp b/Code/Tools/CryCommonTools/UI/ProgressBar.cpp deleted file mode 100644 index d83c8bf3ad..0000000000 --- a/Code/Tools/CryCommonTools/UI/ProgressBar.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ProgressBar.h" -#include -#include - -ProgressBar::ProgressBar() - : m_progressBar(0) -{ -} - -void ProgressBar::CreateUI(void* window, int left, int top, int width, int height) -{ - m_progressBar = CreateWindowEx( - 0, - PROGRESS_CLASS, - 0, - WS_CHILD | WS_VISIBLE, - left, - top, - width, - height, - (HWND)window, - (HMENU)0, - GetModuleHandle(0), - 0); - SendMessage((HWND)m_progressBar, PBM_SETRANGE, 0, MAKELPARAM(0, 1000)); - SendMessage((HWND)m_progressBar, PBM_SETSTEP, (WPARAM) 1, 0); -} - -void ProgressBar::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_progressBar, left, top, width, height, true); -} - -void ProgressBar::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_progressBar); -} - -void ProgressBar::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 200; - maxWidth = 2000; - minHeight = 30; - maxHeight = 30; -} - -void ProgressBar::SetProgress(float progress) -{ - int newPos = int(progress * 1000.0f); - SendMessage((HWND)m_progressBar, PBM_SETPOS, newPos, 0); -} diff --git a/Code/Tools/CryCommonTools/UI/ProgressBar.h b/Code/Tools/CryCommonTools/UI/ProgressBar.h deleted file mode 100644 index 16ce456abe..0000000000 --- a/Code/Tools/CryCommonTools/UI/ProgressBar.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_PROGRESSBAR_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_PROGRESSBAR_H -#pragma once - - -#include "IUIComponent.h" - -class ProgressBar - : public IUIComponent -{ -public: - ProgressBar(); - - void SetProgress(float progress); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - void* m_progressBar; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_PROGRESSBAR_H diff --git a/Code/Tools/CryCommonTools/UI/PushButton.cpp b/Code/Tools/CryCommonTools/UI/PushButton.cpp deleted file mode 100644 index e1458db0d6..0000000000 --- a/Code/Tools/CryCommonTools/UI/PushButton.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "PushButton.h" -#include "Win32GUI.h" - -PushButton::~PushButton() -{ - m_callback->Release(); -} - -void PushButton::Enable(bool enabled) -{ - m_enabled = enabled; - EnableWindow((HWND)m_button, m_enabled); -} - -void PushButton::CreateUI(void* window, int left, int top, int width, int height) -{ - m_button = Win32GUI::CreateControl(_T("BUTTON"), WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON, (HWND)window, left, top, 40, 20); - m_font = Win32GUI::CreateFont(); - SendMessage((HWND)m_button, WM_SETFONT, (WPARAM)m_font, 0); - SendMessage((HWND)m_button, WM_SETTEXT, 0, (LPARAM)m_text.c_str()); - EnableWindow((HWND)m_button, m_enabled); - - Win32GUI::SetCallback((HWND)m_button, this, &PushButton::OnPushed); -} - -void PushButton::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_button, left, top, width, height, true); -} - -void PushButton::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_button); - m_button = 0; - DeleteObject(m_font); - m_font = 0; -} - -void PushButton::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 50; - maxWidth = 50; - minHeight = 20; - maxHeight = 20; -} - -void PushButton::OnPushed() -{ - m_callback->Call(); -} diff --git a/Code/Tools/CryCommonTools/UI/PushButton.h b/Code/Tools/CryCommonTools/UI/PushButton.h deleted file mode 100644 index a6199208d5..0000000000 --- a/Code/Tools/CryCommonTools/UI/PushButton.h +++ /dev/null @@ -1,78 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_PUSHBUTTON_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_PUSHBUTTON_H -#pragma once - - -#include "IUIComponent.h" -#include - -class PushButton - : public IUIComponent -{ -public: - template - PushButton(const TCHAR* text, T* object, void (T::* method)()); - ~PushButton(); - - void Enable(bool enabled); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - PushButton(const PushButton&); - PushButton& operator=(const PushButton&); - - struct ICallback - { - virtual void Release() = 0; - virtual void Call() = 0; - }; - - template - struct Callback - : public ICallback - { - Callback(T* object, void (T::* method)()) - : object(object) - , method(method) {} - virtual void Release() {delete this; } - virtual void Call() {(object->*method)(); } - T* object; - void (T::* method)(); - }; - - void OnPushed(); - - std::basic_string m_text; - void* m_button; - void* m_font; - ICallback* m_callback; - bool m_enabled; -}; - -template -PushButton::PushButton(const TCHAR* text, T* object, void (T::* method)()) - : m_text(text) - , m_callback(new Callback(object, method)) - , m_enabled(true) -{ -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_PUSHBUTTON_H diff --git a/Code/Tools/CryCommonTools/UI/Spacer.cpp b/Code/Tools/CryCommonTools/UI/Spacer.cpp deleted file mode 100644 index 822831116e..0000000000 --- a/Code/Tools/CryCommonTools/UI/Spacer.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "Spacer.h" - -Spacer::Spacer(int minWidth, int minHeight, int maxWidth, int maxHeight) - : m_minWidth(minWidth) - , m_minHeight(minHeight) - , m_maxWidth(maxWidth) - , m_maxHeight(maxHeight) -{ -} - -void Spacer::CreateUI(void* window, int left, int top, int width, int height) -{ -} - -void Spacer::Resize(void* window, int left, int top, int width, int height) -{ -} - -void Spacer::DestroyUI(void* window) -{ -} - -void Spacer::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = m_minWidth; - maxWidth = m_maxWidth; - minHeight = m_minHeight; - maxHeight = m_maxHeight; -} diff --git a/Code/Tools/CryCommonTools/UI/Spacer.h b/Code/Tools/CryCommonTools/UI/Spacer.h deleted file mode 100644 index 173fb7ab13..0000000000 --- a/Code/Tools/CryCommonTools/UI/Spacer.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_SPACER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_SPACER_H -#pragma once - - -#include "IUIComponent.h" - -class Spacer - : public IUIComponent -{ -public: - Spacer(int minWidth, int minHeight, int maxWidth, int maxHeight); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - int m_minWidth; - int m_minHeight; - int m_maxWidth; - int m_maxHeight; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_SPACER_H diff --git a/Code/Tools/CryCommonTools/UI/TaskList.cpp b/Code/Tools/CryCommonTools/UI/TaskList.cpp deleted file mode 100644 index 477041fd59..0000000000 --- a/Code/Tools/CryCommonTools/UI/TaskList.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "TaskList.h" -#include "Win32GUI.h" -#include -#include -#include -#include - -TaskList::TaskList() - : m_edit(0) -{ -} - -void TaskList::AddTask(const std::string& id, const std::string description) -{ - int taskIndex = int(m_tasks.size()); - m_tasks.push_back(std::make_pair(id, description)); - m_idTaskMap.insert(std::make_pair(id, taskIndex)); -} - -void TaskList::SetCurrentTask(const std::string& id) -{ - SetText(id); -} - -void TaskList::SetColor() -{ - SendMessage((HWND)m_edit, EM_SETBKGNDCOLOR, 0, GetSysColor(COLOR_3DFACE)); -} - -void TaskList::SetText(const std::string& highlightedTask) -{ - PARAFORMAT2 paragraphFormat; - std::memset(¶graphFormat, 0, sizeof(paragraphFormat)); - paragraphFormat.cbSize = sizeof(paragraphFormat); - paragraphFormat.dwMask = PFM_LINESPACING | PFM_SPACEBEFORE; - paragraphFormat.bLineSpacingRule = 5; // Specify spacing in 20ths of a line. - paragraphFormat.dyLineSpacing = 22; - paragraphFormat.dySpaceBefore = 70; - SendMessage((HWND)m_edit, EM_SETPARAFORMAT, 0, (LPARAM)¶graphFormat); - - CHARFORMAT format; - std::memset(&format, 0, sizeof(format)); - format.cbSize = sizeof(format); - format.dwMask = CFM_BOLD; - format.dwEffects = 0; - SendMessage((HWND)m_edit, EM_SETCHARFORMAT, 0, (LPARAM)&format); - - SETTEXTEX textEx; - std::memset(&textEx, 0, sizeof(textEx)); - textEx.flags = ST_DEFAULT; - textEx.codepage = CP_ACP; - SendMessage((HWND)m_edit, EM_SETTEXTEX, (WPARAM)&textEx, (LPARAM)_T("")); - int highlightedLineStart = 0; - int highlightedLineEnd = 0; - - for (std::vector >::const_iterator taskPos = m_tasks.begin(), taskEnd = m_tasks.end(); taskPos != taskEnd; ++taskPos) - { - textEx.flags = ST_SELECTION; - const std::string& id = (*taskPos).first; - const std::string& description = (*taskPos).second; - const char* margin = " "; - if (highlightedTask == id) - { - margin = "* "; - CHARRANGE range; - SendMessage((HWND)m_edit, EM_EXGETSEL, 0, (LPARAM)&range); - highlightedLineStart = range.cpMin; - } - SendMessageA((HWND)m_edit, EM_SETTEXTEX, (WPARAM)&textEx, (LPARAM)margin); - SendMessageA((HWND)m_edit, EM_SETTEXTEX, (WPARAM)&textEx, (LPARAM)description.c_str()); - SendMessageA((HWND)m_edit, EM_SETTEXTEX, (WPARAM)&textEx, (LPARAM)"\n"); - if (highlightedTask == id) - { - CHARRANGE range; - SendMessage((HWND)m_edit, EM_EXGETSEL, 0, (LPARAM)&range); - highlightedLineEnd = range.cpMin; - } - } - - CHARRANGE range = {highlightedLineStart, highlightedLineEnd}; - SendMessage((HWND)m_edit, EM_EXSETSEL, 0, (LPARAM)&range); - - format.dwEffects = CFE_BOLD; - SendMessage((HWND)m_edit, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format); - - range.cpMin = 0; - range.cpMax = 0; - SendMessage((HWND)m_edit, EM_EXSETSEL, 0, (LPARAM)&range); -} - -void TaskList::CreateUI(void* window, int left, int top, int width, int height) -{ - // Create the window. - LoadLibrary(_T("Riched20.dll")); - m_edit = CreateWindowEx( - 0, //DWORD dwExStyle, - RICHEDIT_CLASS, //LPCTSTR lpClassName, - 0, //LPCTSTR lpWindowName, - WS_CHILD | WS_VISIBLE | ES_LEFT | ES_MULTILINE | ES_READONLY, //DWORD dwStyle, - left, //int x, - top, //int y, - width, //int nWidth, - height, //int nHeight, - (HWND)window, //HWND hWndParent, - 0, //HMENU hMenu, - GetModuleHandle(0), //HINSTANCE hInstance, - 0); //LPVOID lpParam); - HFONT font = Win32GUI::CreateFont(); - SendMessage((HWND)m_edit, WM_SETFONT, (WPARAM)font, 0); - DeleteObject(font); - SetColor(); - - SetText(""); -} - -void TaskList::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_edit, left, top, width, height, true); -} - -void TaskList::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_edit); - m_edit = 0; -} - -void TaskList::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 10; - maxWidth = 2000; - int height = 25 * int(m_tasks.size()); - minHeight = height; - maxHeight = height; -} diff --git a/Code/Tools/CryCommonTools/UI/TaskList.h b/Code/Tools/CryCommonTools/UI/TaskList.h deleted file mode 100644 index 54f825a5b5..0000000000 --- a/Code/Tools/CryCommonTools/UI/TaskList.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_TASKLIST_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_TASKLIST_H -#pragma once - - -#include "IUIComponent.h" -#include -#include -#include - -class TaskList - : public IUIComponent -{ -public: - TaskList(); - - void AddTask(const std::string& id, const std::string description); - void SetCurrentTask(const std::string& id); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - void SetColor(); - void SetText(const std::string& highlightedTask); - - std::map m_idTaskMap; - std::vector > m_tasks; - void* m_edit; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_TASKLIST_H diff --git a/Code/Tools/CryCommonTools/UI/ToggleButton.cpp b/Code/Tools/CryCommonTools/UI/ToggleButton.cpp deleted file mode 100644 index 6f93a9c303..0000000000 --- a/Code/Tools/CryCommonTools/UI/ToggleButton.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ToggleButton.h" -#include "Win32GUI.h" - -ToggleButton::~ToggleButton() -{ - m_callback->Release(); -} - -void ToggleButton::SetState(bool state) -{ - m_state = state; - SendMessage((HWND)m_button, BM_SETCHECK, m_state, 0); -} - -void ToggleButton::CreateUI(void* window, int left, int top, int width, int height) -{ - m_button = Win32GUI::CreateControl(_T("BUTTON"), WS_VISIBLE | WS_CHILD | BS_AUTOCHECKBOX | BS_NOTIFY | BS_PUSHLIKE, (HWND)window, left, top, 40, 20); - m_font = Win32GUI::CreateFont(); - SendMessage((HWND)m_button, WM_SETFONT, (WPARAM)m_font, 0); - SendMessage((HWND)m_button, WM_SETTEXT, 0, (LPARAM)m_text.c_str()); - SendMessage((HWND)m_button, BM_SETCHECK, m_state, 0); - - Win32GUI::SetCallback((HWND)m_button, this, &ToggleButton::OnChecked); -} - -void ToggleButton::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_button, left, top, width, height, true); -} - -void ToggleButton::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_button); - m_button = 0; - DeleteObject(m_font); - m_font = 0; -} - -void ToggleButton::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 50; - maxWidth = 50; - minHeight = 20; - maxHeight = 20; -} - -void ToggleButton::OnChecked(bool checked) -{ - m_state = checked; - m_callback->Call(checked); -} diff --git a/Code/Tools/CryCommonTools/UI/ToggleButton.h b/Code/Tools/CryCommonTools/UI/ToggleButton.h deleted file mode 100644 index 27eec0906c..0000000000 --- a/Code/Tools/CryCommonTools/UI/ToggleButton.h +++ /dev/null @@ -1,78 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_TOGGLEBUTTON_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_TOGGLEBUTTON_H -#pragma once - - -#include "IUIComponent.h" -#include - -class ToggleButton - : public IUIComponent -{ -public: - template - ToggleButton(const TCHAR* text, T* object, void (T::* method)(bool value)); - ~ToggleButton(); - - void SetState(bool value); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - ToggleButton(const ToggleButton&); - ToggleButton& operator=(const ToggleButton); - - struct ICallback - { - virtual void Release() = 0; - virtual void Call(bool value) = 0; - }; - - template - struct Callback - : public ICallback - { - Callback(T* object, void (T::* method)(bool value)) - : object(object) - , method(method) {} - virtual void Release() {delete this; } - virtual void Call(bool value) {(object->*method)(value); } - T* object; - void (T::* method)(bool value); - }; - - void OnChecked(bool checked); - - tstring m_text; - void* m_button; - void* m_font; - bool m_state; - ICallback* m_callback; -}; - -template -ToggleButton::ToggleButton(const TCHAR* text, T* object, void (T::* method)(bool value)) - : m_text(text) - , m_state(false) - , m_callback(new Callback(object, method)) -{ -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_TOGGLEBUTTON_H diff --git a/Code/Tools/CryCommonTools/UI/Win32GUI.cpp b/Code/Tools/CryCommonTools/UI/Win32GUI.cpp deleted file mode 100644 index e34348271d..0000000000 --- a/Code/Tools/CryCommonTools/UI/Win32GUI.cpp +++ /dev/null @@ -1,390 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "Win32GUI.h" -#include -#include -#include -#include -#include "commctrl.h" -#include "StringHelpers.h" - -namespace Win32GUI -{ - const int WM_REFLECT_BASE = WM_USER + 0x1c00; - const int WM_COMMAND_REFLECT = WM_REFLECT_BASE + WM_COMMAND; - const int WM_NOTIFY_REFLECT = WM_REFLECT_BASE + WM_NOTIFY; - - class Window - { - public: - typedef LRESULT (Window::* WindowProcMethod)(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - - Window(WindowProcMethod windowProc); - ~Window(); - static LRESULT CALLBACK StaticWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - LRESULT WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - LRESULT FrameWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - - void Subclass(HWND window); - void Unsubclass(HWND window); - - WNDPROC m_oldWndProc; - WindowProcMethod m_windowProc; - typedef std::multimap CallbackMap; - CallbackMap m_callbackMap; - }; -} - -void Win32GUI::Initialize() -{ - InitCommonControls(); - LoadLibrary(_T("riched20.dll")); -} - -void Win32GUI::RegisterFrameClass(const TCHAR* name) -{ - WNDCLASS cls; - std::memset(&cls, 0, sizeof(cls)); - cls.style = 0; - cls.lpfnWndProc = &Window::StaticWindowProc; - cls.cbClsExtra = 0; - cls.cbWndExtra = 0; - cls.hInstance = GetModuleHandle(0); - cls.hIcon = 0; - cls.hCursor = LoadCursor(0, IDC_ARROW); - cls.hbrBackground = GetSysColorBrush(COLOR_BTNFACE); - cls.lpszMenuName = 0; - cls.lpszClassName = name; - - RegisterClass(&cls); -} - -HWND Win32GUI::CreateFrame(const TCHAR* className, unsigned style, int width, int height) -{ - Window* window = new Window(&Window::FrameWindowProc); - - HWND hwnd = CreateWindow( - className, // LPCTSTR lpClassName, - TEXT(""), // LPCTSTR lpWindowName, - style, // DWORD dwStyle, - CW_USEDEFAULT, // int x, - CW_USEDEFAULT, // int y, - width, // int nWidth, - height, // int nHeight, - 0, // HWND hWndParent, - 0, // HMENU hMenu, - GetModuleHandle(0), // HINSTANCE hInstance, - window); // LPVOID lpParam - - return hwnd; -} - -HWND Win32GUI::CreateControl(const TCHAR* className, unsigned style, HWND parent, int left, int top, int width, int height) -{ - Window* window = new Window(&Window::WindowProc); - - HWND hwnd = CreateWindow( - className, // LPCTSTR lpClassName, - 0, // LPCTSTR lpWindowName, - style | WS_CHILD | WS_VISIBLE, // DWORD dwStyle, - left, // int x, - top, // int y, - width, // int nWidth, - height, // int nHeight, - parent, // HWND hWndParent, - 0, // HMENU hMenu, - GetModuleHandle(0), // HINSTANCE hInstance, - 0); // LPVOID lpParam - - window->Subclass(hwnd); - - return hwnd; -} - -int Win32GUI::Run() -{ - MSG msg; - BOOL status; - while ((status = GetMessage(&msg, HWND(0), UINT(0), UINT(0))) != 0) - { - if (status == -1) - { - return -1; - } - else - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - - return (int)msg.wParam; -} - -Win32GUI::Window::Window(WindowProcMethod windowProc) - : m_windowProc(windowProc) - , m_oldWndProc(0) -{ -} - -Win32GUI::Window::~Window() -{ - for (CallbackMap::iterator callbackPos = m_callbackMap.begin(); callbackPos != m_callbackMap.end(); ++callbackPos) - { - (*callbackPos).second->Release(); - } -} - -LRESULT CALLBACK Win32GUI::Window::StaticWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - Window* window = 0; - { - if (uMsg == WM_CREATE) - { - CREATESTRUCT* create_struct = (CREATESTRUCT*)lParam; - window = (Window*)create_struct->lpCreateParams; -#if defined(_WIN64) - SetWindowLongPtr(hwnd, GWLP_USERDATA, LONG_PTR(window)); -#else //defined(_WIN64) - SetWindowLong(hwnd, GWL_USERDATA, PtrToLong(window)); -#endif //defined(_WIN64) - } - else - { -#if defined(_WIN64) - window = (Window*)GetWindowLongPtr(hwnd, GWLP_USERDATA); -#else //defined(_WIN64) - window = (Window*)LongToPtr(GetWindowLong(hwnd, GWL_USERDATA)); -#endif //defined(_WIN64) - } - } - - LRESULT result = 0; - if (window) - { - result = (window->*(window->m_windowProc))(hwnd, uMsg, wParam, lParam); - } - else - { - result = DefWindowProc(hwnd, uMsg, wParam, lParam); - } - - if (uMsg == WM_DESTROY) - { - delete window; -#if defined(_WIN64) - SetWindowLongPtr(hwnd, GWLP_USERDATA, 0); -#else //defined(_WIN64) - SetWindowLong(hwnd, GWL_USERDATA, 0); -#endif //defined(_WIN64) - } - - return result; -} - -LRESULT Win32GUI::Window::WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - switch (uMsg) - { - case WM_COMMAND: - { - HWND control = (HWND)lParam; - if (control) - { - SendMessage(control, WM_COMMAND_REFLECT, wParam, lParam); - } - } - break; - - case WM_NOTIFY: - { - NMHDR* notify_header = reinterpret_cast(lParam); - if (notify_header->hwndFrom) - { - SendMessage(notify_header->hwndFrom, WM_NOTIFY_REFLECT, wParam, lParam); - } - } - break; - - case WM_COMMAND_REFLECT: - switch (HIWORD(wParam)) - { - case EN_CHANGE: - { - std::string text = GetWindowString(hwnd); - - std::pair range = m_callbackMap.equal_range(EventCallbacks::TextChanged::ID); - for (CallbackMap::iterator callbackPos = range.first; callbackPos != range.second; ++callbackPos) - { - EventCallbacks::IStringCallback* callback = static_cast((*callbackPos).second); - callback->Call(text); - } - } - break; - - case BN_CLICKED: - { - if (GetWindowLong(hwnd, GWL_STYLE) & BS_CHECKBOX) - { - bool checked = (0 != SendMessage(hwnd, BM_GETCHECK, 0, 0)); - std::pair range = m_callbackMap.equal_range(EventCallbacks::Checked::ID); - for (CallbackMap::iterator callbackPos = range.first; callbackPos != range.second; ++callbackPos) - { - EventCallbacks::IBoolCallback* callback = static_cast((*callbackPos).second); - callback->Call(checked); - } - } - else - { - std::pair range = m_callbackMap.equal_range(EventCallbacks::Pushed::ID); - for (CallbackMap::iterator callbackPos = range.first; callbackPos != range.second; ++callbackPos) - { - EventCallbacks::IVoidCallback* callback = static_cast((*callbackPos).second); - callback->Call(); - } - } - } - break; - } - break; - - case WM_GETMINMAXINFO: - { - int minW = 0, maxW = 0, minH = 100000, maxH = 100000; - - std::pair range = m_callbackMap.equal_range(EventCallbacks::GetDimensions::ID); - for (CallbackMap::iterator callbackPos = range.first; callbackPos != range.second; ++callbackPos) - { - EventCallbacks::IGetDimensionsCallback* callback = static_cast((*callbackPos).second); - callback->Call(minW, maxW, minH, maxH); - } - - MINMAXINFO* minMaxInfo = (MINMAXINFO*)lParam; - minMaxInfo->ptMinTrackSize.x = minW; - minMaxInfo->ptMaxTrackSize.x = maxW; - minMaxInfo->ptMinTrackSize.y = minH; - minMaxInfo->ptMaxTrackSize.y = maxH; - } - break; - - case WM_SIZE: - { - int width = LOWORD(lParam); - int height = HIWORD(lParam); - std::pair range = m_callbackMap.equal_range(EventCallbacks::SizeChanged::ID); - for (CallbackMap::iterator callbackPos = range.first; callbackPos != range.second; ++callbackPos) - { - EventCallbacks::ISizeCallback* callback = static_cast((*callbackPos).second); - callback->Call(width, height); - } - } - break; - - case WM_NOTIFY_REFLECT: - break; - } - - LRESULT result = 0; - if (m_oldWndProc) - { - result = CallWindowProc(m_oldWndProc, hwnd, uMsg, wParam, lParam); - } - else - { - result = DefWindowProc(hwnd, uMsg, wParam, lParam); - } - - return result; -} - -LRESULT Win32GUI::Window::FrameWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - switch (uMsg) - { - case WM_CLOSE: - PostQuitMessage(0); - break; - } - - return WindowProc(hwnd, uMsg, wParam, lParam); -} - -void Win32GUI::Window::Subclass(HWND window) -{ -#if defined(_WIN64) - SetWindowLongPtr(window, GWLP_USERDATA, LONG_PTR(this)); - m_oldWndProc = (WNDPROC)GetWindowLongPtr(window, GWLP_WNDPROC); - SetWindowLongPtr(window, GWLP_WNDPROC, LONG_PTR(&Window::StaticWindowProc)); -#else //defined(_WIN64) - SetWindowLong(window, GWL_USERDATA, PtrToLong(this)); - m_oldWndProc = (WNDPROC)LongToPtr(GetWindowLong(window, GWL_WNDPROC)); - SetWindowLong(window, GWL_WNDPROC, PtrToLong(&Window::StaticWindowProc)); -#endif //defined(_WIN64) -} - -void Win32GUI::Window::Unsubclass(HWND window) -{ -#if defined(_WIN64) - SetWindowLongPtr(window, GWLP_USERDATA, 0); - SetWindowLongPtr(window, GWLP_WNDPROC, LONG_PTR(m_oldWndProc)); -#else //defined(_WIN64) - SetWindowLongPtr(window, GWL_USERDATA, 0); - SetWindowLong(window, GWLP_WNDPROC, PtrToLong(m_oldWndProc)); -#endif //defined(_WIN64) - m_oldWndProc = 0; -} - -std::string Win32GUI::GetWindowString(HWND hwnd) -{ - LRESULT length = SendMessage(hwnd, WM_GETTEXTLENGTH, 0, 0); - std::wstring wtext(length, 0); - SendMessageW(hwnd, WM_GETTEXT, length + 1, (LPARAM)&wtext[0]); - return StringHelpers::ConvertUtf16ToAnsi(wtext.c_str(), '?'); -} - -void Win32GUI::SetWindowString(HWND hwnd, const std::string& text) -{ - std::wstring wtext = StringHelpers::ConvertAnsiToUtf16(text.c_str()); - SendMessageW(hwnd, WM_SETTEXT, 0, (LPARAM)&wtext[0]); -} - -HFONT Win32GUI::CreateFont() -{ - HFONT hFont = 0; - HFONT hGuiFont = static_cast(::GetStockObject(DEFAULT_GUI_FONT)); - - LOGFONT lfGuiFont = { 0 }; - if (::GetObject(hGuiFont, sizeof(LOGFONT), &lfGuiFont) == sizeof(LOGFONT)) - { - _tcsncpy(lfGuiFont.lfFaceName, _T("MS Shell Dlg 2"), sizeof(lfGuiFont.lfFaceName) / sizeof(TCHAR)); - lfGuiFont.lfFaceName[(sizeof(lfGuiFont.lfFaceName) / sizeof(TCHAR)) - 1] = '\0'; - - hFont = ::CreateFontIndirect(&lfGuiFont); - - return hFont; - } - return 0; -} - -void Win32GUI::SetCallbackObject(HWND hwnd, unsigned eventID, EventCallbacks::ICallback* callback) -{ -#if defined(_WIN64) - Window* window = (Window*)GetWindowLongPtr(hwnd, GWLP_USERDATA); -#else //defined(_WIN64) - Window* window = (Window*)LongToPtr(GetWindowLong(hwnd, GWL_USERDATA)); -#endif //defined(_WIN64) - - window->m_callbackMap.insert(std::make_pair(eventID, callback)); -} diff --git a/Code/Tools/CryCommonTools/UI/Win32GUI.h b/Code/Tools/CryCommonTools/UI/Win32GUI.h deleted file mode 100644 index 60b91ece9f..0000000000 --- a/Code/Tools/CryCommonTools/UI/Win32GUI.h +++ /dev/null @@ -1,216 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_WIN32GUI_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_WIN32GUI_H -#pragma once - - -#include -#include - -namespace Win32GUI -{ - void Initialize(); - void RegisterFrameClass(const TCHAR* name); - HWND CreateFrame(const TCHAR* className, unsigned style, int width, int height); - HWND CreateControl(const TCHAR* className, unsigned style, HWND parent, int left, int top, int width, int height); - int Run(); - std::string GetWindowString(HWND hwnd); - void SetWindowString(HWND hwnd, const std::string& text); - HFONT CreateFont(); - - namespace EventCallbacks - { - class ICallback - { - public: - virtual ~ICallback() {} - virtual void Release() = 0; - }; - - struct IVoidCallback - : public ICallback - { - virtual void Call() = 0; - }; - - struct VoidCallback - { - template - struct Callback - : public IVoidCallback - { - typedef void (O::* Signature)(); - - Callback(O* object, Signature method) - : m_object(object) - , m_method(method) {} - virtual void Release() {delete this; } - virtual void Call() {(m_object->*m_method)(); } - O* m_object; - Signature m_method; - }; - }; - - struct IStringCallback - : public ICallback - { - virtual void Call(const std::string& text) = 0; - }; - - struct StringCallback - { - template - struct Callback - : public IStringCallback - { - typedef void (O::* Signature)(const std::string& text); - - Callback(O* object, Signature method) - : m_object(object) - , m_method(method) {} - virtual void Release() {delete this; } - virtual void Call(const std::string& text) {(m_object->*m_method)(text); } - O* m_object; - Signature m_method; - }; - }; - - struct IGetDimensionsCallback - : public ICallback - { - virtual void Call(int& minW, int& maxW, int& minH, int& maxH) = 0; - }; - - struct GetDimensionsCallback - { - template - struct Callback - : public IGetDimensionsCallback - { - typedef void (O::* Signature)(int& minW, int& maxW, int& minH, int& maxH); - - Callback(O* object, Signature method) - : m_object(object) - , m_method(method) {} - virtual void Release() {delete this; } - virtual void Call(int& minW, int& maxW, int& minH, int& maxH) {(m_object->*m_method)(minW, maxW, minH, maxH); } - O* m_object; - Signature m_method; - }; - }; - - struct ISizeCallback - : public ICallback - { - virtual void Call(int width, int height) = 0; - }; - - struct SizeCallback - { - template - struct Callback - : public ISizeCallback - { - typedef void (O::* Signature)(int width, int height); - - Callback(O* object, Signature method) - : m_object(object) - , m_method(method) {} - virtual void Release() {delete this; } - virtual void Call(int width, int height) {(m_object->*m_method)(width, height); } - O* m_object; - Signature m_method; - }; - }; - - struct IBoolCallback - : public ICallback - { - virtual void Call(bool value) = 0; - }; - - struct BoolCallback - { - template - struct Callback - : public IBoolCallback - { - typedef void (O::* Signature)(bool callback); - Callback(O* object, Signature method) - : m_object(object) - , m_method(method) {} - virtual void Release() {delete this; } - virtual void Call(bool value) {(m_object->*m_method)(value); } - O* m_object; - Signature m_method; - }; - }; - - struct TextChanged - : public StringCallback - { - enum - { - ID = 0x00005001 - }; - }; - struct GetDimensions - : public GetDimensionsCallback - { - enum - { - ID = 0x00005002 - }; - }; - struct SizeChanged - : public SizeCallback - { - enum - { - ID = 0x00005003 - }; - }; - struct Pushed - : public VoidCallback - { - enum - { - ID = 0x00005004 - }; - }; - struct Checked - : public BoolCallback - { - enum - { - ID = 0x00005005 - }; - }; - }; - - void SetCallbackObject(HWND hwnd, unsigned eventID, EventCallbacks::ICallback* callback); - template - inline void SetCallback(HWND hwnd, O* object, typename T::template Callback::Signature method); -} - -template -inline void Win32GUI::SetCallback(HWND hwnd, O* object, typename T::template Callback::Signature method) -{ - typedef T::template Callback Callback; - Callback* callback = new Callback(object, method); - SetCallbackObject(hwnd, T::ID, callback); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_WIN32GUI_H diff --git a/Code/Tools/SerializeContextTools/Application.cpp b/Code/Tools/SerializeContextTools/Application.cpp index 2ab9847aa6..da0cca5ca6 100644 --- a/Code/Tools/SerializeContextTools/Application.cpp +++ b/Code/Tools/SerializeContextTools/Application.cpp @@ -16,12 +16,23 @@ #include #include +#include + namespace AZ { + // SerializeContextTools is a full ToolsApplication that will load a project's Gem DLLs and initialize the system components. + // This level of initialization is required to get all the serialization contexts and asset handlers registered, so that when + // data transformations take place, none of the data is dropped due to not being recognized. + // However, as a simplification, anything requiring Python or Qt is skipped during initialization: + // - The gem_autoload.serializecontexttools.setreg file disables autoload for QtForPython, EditorPythonBindings, and PythonAssetBuilder + // - The system component initialization below uses ThumbnailerNullComponent so that other components relying on a ThumbnailService + // can still be started up, but the thumbnail service itself won't do anything. The real ThumbnailerComponent uses Qt, which is why + // it isn't used. + namespace SerializeContextTools { Application::Application(int argc, char** argv) - : AZ::ComponentApplication(argc, argv) + : AzToolsFramework::ToolsApplication(&argc, &argv) { AZ::IO::FixedMaxPath projectPath = AZ::Utils::GetProjectPath(); if (projectPath.empty()) @@ -51,14 +62,27 @@ namespace AZ else { AZ::SettingsRegistryInterface::Specializations projectSpecializations{ projectName }; - AZ::IO::PathView configFilenameStem = m_configFilePath.Stem(); - if (AZ::StringFunc::Equal(configFilenameStem.Native(), "Editor")) + + // If a project specialization has been passed in via the command line, use it. + if (size_t specializationCount = m_commandLine.GetNumSwitchValues("specializations"); specializationCount > 0) { - projectSpecializations.Append("editor"); + for (size_t specializationIndex = 0; specializationIndex < specializationCount; ++specializationIndex) + { + projectSpecializations.Append(m_commandLine.GetSwitchValue("specializations", specializationIndex)); + } } - else if (AZ::StringFunc::Equal(configFilenameStem.Native(), "Game")) + // Otherwise, if a config file was passed in, auto-set the specialization based on the config file name. + else { - projectSpecializations.Append(projectName + "_GameLauncher"); + AZ::IO::PathView configFilenameStem = m_configFilePath.Stem(); + if (AZ::StringFunc::Equal(configFilenameStem.Native(), "Editor")) + { + projectSpecializations.Append("editor"); + } + else if (AZ::StringFunc::Equal(configFilenameStem.Native(), "Game")) + { + projectSpecializations.Append(projectName + "_GameLauncher"); + } } // Used the project specializations to merge the build dependencies *.setreg files @@ -78,5 +102,14 @@ namespace AZ AZ::ComponentApplication::SetSettingsRegistrySpecializations(specializations); specializations.Append("serializecontexttools"); } + + AZ::ComponentTypeList Application::GetRequiredSystemComponents() const + { + // Use all of the default system components, but also add in the ThumbnailerNullComponent so that components requiring + // a ThumbnailService can still be started up. + AZ::ComponentTypeList components = AzToolsFramework::ToolsApplication::GetRequiredSystemComponents(); + components.emplace_back(azrtti_typeid()); + return components; + } } // namespace SerializeContextTools } // namespace AZ diff --git a/Code/Tools/SerializeContextTools/Application.h b/Code/Tools/SerializeContextTools/Application.h index 63bc1892ed..b1b818e27d 100644 --- a/Code/Tools/SerializeContextTools/Application.h +++ b/Code/Tools/SerializeContextTools/Application.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace AZ @@ -20,13 +20,14 @@ namespace AZ namespace SerializeContextTools { class Application final - : public AZ::ComponentApplication + : public AzToolsFramework::ToolsApplication { public: Application(int argc, char** argv); ~Application() override = default; const char* GetConfigFilePath() const; + AZ::ComponentTypeList GetRequiredSystemComponents() const override; protected: void SetSettingsRegistrySpecializations(AZ::SettingsRegistryInterface::Specializations& specializations) override; diff --git a/Code/Tools/SerializeContextTools/CMakeLists.txt b/Code/Tools/SerializeContextTools/CMakeLists.txt index 1a993de53c..e73fd014ab 100644 --- a/Code/Tools/SerializeContextTools/CMakeLists.txt +++ b/Code/Tools/SerializeContextTools/CMakeLists.txt @@ -29,4 +29,6 @@ ly_add_target( BUILD_DEPENDENCIES PRIVATE AZ::AzCore + AZ::AzFramework + AZ::AzToolsFramework ) diff --git a/Code/Tools/SerializeContextTools/Utilities.cpp b/Code/Tools/SerializeContextTools/Utilities.cpp index 127f833f6b..1c50466443 100644 --- a/Code/Tools/SerializeContextTools/Utilities.cpp +++ b/Code/Tools/SerializeContextTools/Utilities.cpp @@ -236,7 +236,6 @@ namespace AZ::SerializeContextTools AZ::IO::MemoryStream stream(data.data(), fileLength); ObjectStream::FilterDescriptor filter; - filter.m_flags = ObjectStream::FILTERFLAG_IGNORE_UNKNOWN_CLASSES; // Never load dependencies. That's another file that would need to be processed // separately from this one. filter.m_assetCB = AZ::Data::AssetFilterNoAssetLoading; diff --git a/Code/Tools/SerializeContextTools/main.cpp b/Code/Tools/SerializeContextTools/main.cpp index ee505c9cc0..fb2dc442ed 100644 --- a/Code/Tools/SerializeContextTools/main.cpp +++ b/Code/Tools/SerializeContextTools/main.cpp @@ -23,6 +23,8 @@ void PrintHelp() AZ_Printf("Help", "Serialize Context Tool\n"); AZ_Printf("Help", " [-config] *\n"); AZ_Printf("Help", " [opt] -config=: optional path to application's config file. Default is 'config/editor.xml'.\n"); + AZ_Printf("Help", " [opt] -specializations=: -separated list of optional Registry project\n"); + AZ_Printf("Help", " specializations, such as 'editor' or 'game' or 'editor;test'. Default is none. \n"); AZ_Printf("Help", "\n"); AZ_Printf("Help", " 'help': Print this help\n"); AZ_Printf("Help", " example: 'help'\n"); @@ -81,11 +83,7 @@ int main(int argc, char** argv) bool result = false; Application application(argc, argv); AZ::ComponentApplication::StartupParameters startupParameters; - startupParameters.m_loadDynamicModules = false; - application.Create({}, startupParameters); - // Load the DynamicModules after the Application starts to prevent Gem System Components - // from activating - application.LoadDynamicModules(); + application.Start({}, startupParameters); const AZ::CommandLine* commandLine = application.GetAzCommandLine(); if (commandLine->GetNumMiscValues() < 1) diff --git a/Code/Tools/Standalone/Source/LuaIDEApplication.cpp b/Code/Tools/Standalone/Source/LuaIDEApplication.cpp index cd72fda4e3..8e52bb4d95 100644 --- a/Code/Tools/Standalone/Source/LuaIDEApplication.cpp +++ b/Code/Tools/Standalone/Source/LuaIDEApplication.cpp @@ -22,9 +22,9 @@ #include #include #include +#include #include -#include #include #include #include @@ -55,7 +55,7 @@ namespace LUAEditor RegisterComponentDescriptor(AzToolsFramework::Components::PropertyManagerComponent::CreateDescriptor()); RegisterComponentDescriptor(AzFramework::AssetSystem::AssetSystemComponent::CreateDescriptor()); RegisterComponentDescriptor(AzToolsFramework::AssetSystem::AssetSystemComponent::CreateDescriptor()); - RegisterComponentDescriptor(LUAEditor::Thumbnailer::ThumbnailerNullComponent::CreateDescriptor()); + RegisterComponentDescriptor(AzToolsFramework::Thumbnailer::ThumbnailerNullComponent::CreateDescriptor()); RegisterComponentDescriptor(AzToolsFramework::AssetBrowser::AssetBrowserComponent::CreateDescriptor()); RegisterComponentDescriptor(AzToolsFramework::Components::EditorSelectionAccentSystemComponent::CreateDescriptor()); @@ -75,7 +75,7 @@ namespace LUAEditor EnsureComponentCreated(AzToolsFramework::Components::PropertyManagerComponent::RTTI_Type()); EnsureComponentCreated(AzFramework::AssetSystem::AssetSystemComponent::RTTI_Type()); EnsureComponentCreated(AzToolsFramework::AssetSystem::AssetSystemComponent::RTTI_Type()); - EnsureComponentCreated(LUAEditor::Thumbnailer::ThumbnailerNullComponent::RTTI_Type()); + EnsureComponentCreated(AzToolsFramework::Thumbnailer::ThumbnailerNullComponent::RTTI_Type()); EnsureComponentCreated(AzToolsFramework::AssetBrowser::AssetBrowserComponent::RTTI_Type()); EnsureComponentCreated(AzToolsFramework::Components::EditorSelectionAccentSystemComponent::RTTI_Type()); } diff --git a/Code/Tools/Standalone/lua_ide_files.cmake b/Code/Tools/Standalone/lua_ide_files.cmake index c6e2c538f2..ff2196db62 100644 --- a/Code/Tools/Standalone/lua_ide_files.cmake +++ b/Code/Tools/Standalone/lua_ide_files.cmake @@ -14,8 +14,6 @@ set(FILES Source/LuaIDEApplication.cpp Source/AssetDatabaseLocationListener.h Source/AssetDatabaseLocationListener.cpp - Source/ThumbnailerNullComponent.h - Source/ThumbnailerNullComponent.cpp Source/Editor/LuaEditor.h Source/Editor/LuaEditor.cpp Source/LUA/BasicScriptChecker.h diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl index 23e28e8742..a91e88afad 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl @@ -150,7 +150,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth, displacementIsClipped); + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth, IN.m_position.w, displacementIsClipped); // Apply second part of the offset to the detail UV (see comment above) IN.m_detailUv[MaterialSrg::m_parallaxUvIndex] -= IN.m_uv[MaterialSrg::m_parallaxUvIndex]; diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli index ab601429e8..ffd7c18045 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli @@ -32,7 +32,7 @@ option bool prefix##o_useDepthMap; void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float depthFactor, float depthOffset, float4x4 objectWorldMatrix, float3x3 uvMatrix, float3x3 uvMatrixInverse, - inout float2 uv, inout float3 worldPosition, inout float depth, out bool isClipped) + inout float2 uv, inout float3 worldPosition, inout float depthNDC, inout float depthCS, out bool isClipped) { if(o_parallax_feature_enabled) { @@ -72,7 +72,8 @@ void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float dep objectWorldMatrix, ViewSrg::m_viewProjectionMatrix); - depth = pdo.m_depth; + depthCS = pdo.m_depthCS; + depthNDC = pdo.m_depthNDC; worldPosition = pdo.m_worldPosition; } @@ -82,9 +83,17 @@ void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float dep void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float depthFactor, float depthOffset, float4x4 objectWorldMatrix, float3x3 uvMatrix, float3x3 uvMatrixInverse, - inout float2 uv, inout float3 worldPosition, inout float depth) + inout float2 uv, inout float3 worldPosition, inout float depthNDC, inout float depthCS) { bool isClipped; - GetParallaxInput(normal, tangent, bitangent, depthFactor, depthOffset, objectWorldMatrix, uvMatrix, uvMatrixInverse, uv, worldPosition, depth, isClipped); + GetParallaxInput(normal, tangent, bitangent, depthFactor, depthOffset, objectWorldMatrix, uvMatrix, uvMatrixInverse, uv, worldPosition, depthNDC, depthCS, isClipped); +} + +void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float depthFactor, float depthOffset, + float4x4 objectWorldMatrix, float3x3 uvMatrix, float3x3 uvMatrixInverse, + inout float2 uv, inout float3 worldPosition, inout float depthNDC) +{ + float depthCS; + GetParallaxInput(normal, tangent, bitangent, depthFactor, depthOffset, objectWorldMatrix, uvMatrix, uvMatrixInverse, uv, worldPosition, depthNDC, depthCS); } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl index a83ea629e4..bc32aa1370 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl @@ -130,9 +130,9 @@ VSOutput ForwardPassVS(VSInput IN) // ---------- Pixel Shader ---------- -PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float depth) +PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float depthNDC) { - depth = IN.m_position.z; + depthNDC = IN.m_position.z; // ------- Tangents & Bitangets ------- @@ -185,7 +185,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float parallaxOverallFactor = MaterialSrg::m_displacementMax - MaterialSrg::m_displacementMin; GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], parallaxOverallFactor, parallaxOverallOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth, displacementIsClipped); + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depthNDC, IN.m_position.w, displacementIsClipped); // Adjust directional light shadow coorinates for parallax correction if(o_parallax_enablePixelDepthOffset) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl index 325937b228..c76dd15975 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl @@ -109,7 +109,7 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) GetDepth_Setup(IN.m_blendMask); - float depth; + float depthNDC; float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); @@ -118,9 +118,9 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) float parallaxOverallFactor = MaterialSrg::m_displacementMax - MaterialSrg::m_displacementMin; GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], parallaxOverallFactor, parallaxOverallOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depthNDC); - OUT.m_depth = depth; + OUT.m_depth = depthNDC; } return OUT; diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl index 22751b49bc..f362349a7b 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl @@ -105,7 +105,7 @@ VSOutput StandardPbr_ForwardPassVS(VSInput IN) // ---------- Pixel Shader ---------- -PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float depth) +PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float depthNDC) { // ------- Tangents & Bitangets ------- @@ -125,7 +125,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // ------- Depth & Parallax ------- - depth = IN.m_position.z; + depthNDC = IN.m_position.z; bool displacementIsClipped = false; @@ -137,7 +137,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth, displacementIsClipped); + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depthNDC, IN.m_position.w, displacementIsClipped); // Adjust directional light shadow coorinates for parallax correction if(o_parallax_enablePixelDepthOffset) diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli index 1d2beb0f10..8b1efc8eea 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli @@ -398,7 +398,8 @@ ParallaxOffset GetParallaxOffset( float depthFactor, struct PixelDepthOffset { - float m_depth; + float m_depthNDC; //!< The new depth value, in normalized device coordinates (used for final depth output) + float m_depthCS; //!< The new depth value, in clip space (can be used for other operations like light culling) float3 m_worldPosition; }; @@ -432,7 +433,8 @@ PixelDepthOffset CalcPixelDepthOffset( float depthFactor, float4 clipOffsetPosition = mul(viewProjectionMatrix, float4(worldOffsetPosition, 1.0)); PixelDepthOffset pdo; - pdo.m_depth = clipOffsetPosition.z / clipOffsetPosition.w; + pdo.m_depthCS = clipOffsetPosition.z; + pdo.m_depthNDC = clipOffsetPosition.z / clipOffsetPosition.w; pdo.m_worldPosition = worldOffsetPosition; return pdo; } diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/DeviceFeatures.h b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/DeviceFeatures.h index 246db1522a..94d1cbd9ae 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/DeviceFeatures.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI.Reflect/DeviceFeatures.h @@ -76,6 +76,9 @@ namespace AZ //! Whether Ray Tracing support is available. bool m_rayTracing = false; + //! Whether Unbounded Array support is available. + bool m_unboundedArrays = false; + /// Additional features here. }; } diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp index 2c47a5a443..af94aef3fb 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/Device.cpp @@ -166,6 +166,8 @@ namespace AZ m_features.m_rayTracing = false; #endif + m_features.m_unboundedArrays = true; + m_limits.m_maxImageDimension1D = D3D12_REQ_TEXTURE1D_U_DIMENSION; m_limits.m_maxImageDimension2D = D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION; m_limits.m_maxImageDimension3D = D3D12_REQ_TEXTURE3D_U_V_OR_W_DIMENSION; diff --git a/Gems/Atom/RHI/Null/Code/CMakeLists.txt b/Gems/Atom/RHI/Null/Code/CMakeLists.txt index 1b88e72648..be1c5d22aa 100644 --- a/Gems/Atom/RHI/Null/Code/CMakeLists.txt +++ b/Gems/Atom/RHI/Null/Code/CMakeLists.txt @@ -89,7 +89,7 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) ) ly_add_target( - NAME Atom_RHI_Null.Builders MODULE + NAME Atom_RHI_Null.Builders GEM_MODULE NAMESPACE Gem FILES_CMAKE atom_rhi_null_builders_shared_files.cmake diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp index ff7eb7f4c0..76662ebc6e 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI/Device.cpp @@ -720,6 +720,7 @@ namespace AZ StringList deviceExtensions = physicalDevice.GetDeviceExtensionNames(); StringList::iterator itRayTracingExtension = AZStd::find(deviceExtensions.begin(), deviceExtensions.end(), VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME); m_features.m_rayTracing = (itRayTracingExtension != deviceExtensions.end()); + m_features.m_unboundedArrays = true; const auto& deviceLimits = physicalDevice.GetDeviceLimits(); m_limits.m_maxImageDimension1D = deviceLimits.maxImageDimension1D; diff --git a/Gems/Atom/RPI/Assets/ShaderLib/Atom/RPI/ShaderResourceGroups/BindlessPrototypeSrg.azsli b/Gems/Atom/RPI/Assets/ShaderLib/Atom/RPI/ShaderResourceGroups/BindlessPrototypeSrg.azsli index c955c5d2f8..7304af9e1e 100644 --- a/Gems/Atom/RPI/Assets/ShaderLib/Atom/RPI/ShaderResourceGroups/BindlessPrototypeSrg.azsli +++ b/Gems/Atom/RPI/Assets/ShaderLib/Atom/RPI/ShaderResourceGroups/BindlessPrototypeSrg.azsli @@ -31,10 +31,6 @@ ShaderResourceGroupSemantic FloatBufferSemanticId ShaderResourceGroup ImageSrg : FrequencyPerScene { - // Array of textures - // NOTE: The size of the texture array has to match the number of textures in the example - Texture2D m_textureArray[8]; - Sampler m_sampler { MaxAnisotropy = 16; @@ -42,6 +38,9 @@ ShaderResourceGroup ImageSrg : FrequencyPerScene AddressV = Wrap; AddressW = Wrap; }; + + // Array of textures + Texture2D m_textureArray[]; } ShaderResourceGroup FloatBufferSrg : FloatBufferSemanticId diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Shader/ShaderResourceGroup.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Shader/ShaderResourceGroup.h index 8c53ed2eb2..6d99d287f3 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Shader/ShaderResourceGroup.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Shader/ShaderResourceGroup.h @@ -75,6 +75,9 @@ namespace AZ RHI::ShaderInputSamplerIndex FindShaderInputSamplerIndex(const Name& name) const; RHI::ShaderInputConstantIndex FindShaderInputConstantIndex(const Name& name) const; + RHI::ShaderInputBufferUnboundedArrayIndex FindShaderInputBufferUnboundedArrayIndex(const Name& name) const; + RHI::ShaderInputImageUnboundedArrayIndex FindShaderInputImageUnboundedArrayIndex(const Name& name) const; + /// Returns the parent shader resource group asset. const Data::Asset& GetAsset() const; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/ShaderResourceGroup.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/ShaderResourceGroup.cpp index 28ba48c370..77ea0b9494 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/ShaderResourceGroup.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Shader/ShaderResourceGroup.cpp @@ -118,6 +118,16 @@ namespace AZ return m_layout->FindShaderInputConstantIndex(name); } + RHI::ShaderInputBufferUnboundedArrayIndex ShaderResourceGroup::FindShaderInputBufferUnboundedArrayIndex(const Name& name) const + { + return m_layout->FindShaderInputBufferUnboundedArrayIndex(name); + } + + RHI::ShaderInputImageUnboundedArrayIndex ShaderResourceGroup::FindShaderInputImageUnboundedArrayIndex(const Name& name) const + { + return m_layout->FindShaderInputImageUnboundedArrayIndex(name); + } + const Data::Asset& ShaderResourceGroup::GetAsset() const { return m_asset; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp index cc25fb39ba..0dae5ac2d0 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp @@ -40,9 +40,10 @@ namespace AZ { m_projectionMatrixChangedEvent.Signal(matrix); }); + m_onViewMatrixChangedHandler = ViewportContext::MatrixChangedEvent::Handler([this](const AZ::Matrix4x4& matrix) { - m_projectionMatrixChangedEvent.Signal(matrix); + m_viewMatrixChangedEvent.Signal(matrix); }); SetRenderScene(renderScene); diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt index b684e445b3..33873e0dfa 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt +++ b/Gems/AtomLyIntegration/AtomBridge/Code/CMakeLists.txt @@ -9,6 +9,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Source/Platform/${PAL_PLATFORM_NAME}) + ly_add_target( NAME Atom_AtomBridge.Static STATIC NAMESPACE Gem @@ -41,12 +43,26 @@ ly_add_target( Source PUBLIC Include + PLATFORM_INCLUDE_FILES + ${pal_dir}/additional_${PAL_PLATFORM_NAME_LOWERCASE}_runtime_deps.cmake COMPILE_DEFINITIONS PRIVATE ENABLE_ATOM_DEBUG_DISPLAY=1 BUILD_DEPENDENCIES PRIVATE Gem::Atom_AtomBridge.Static + RUNTIME_DEPENDENCIES + Gem::Atom_RHI.Private + Gem::Atom_RPI.Private + Gem::Atom_RHI_Null.Private + Gem::Atom_Feature_Common + Gem::Atom_Bootstrap + Gem::Atom_Component_DebugCamera + Gem::AtomImGuiTools + Gem::AtomLyIntegration_CommonFeatures + Gem::EMotionFX_Atom + Gem::ImguiAtom + Gem::AtomFont ) if(PAL_TRAIT_BUILD_HOST_TOOLS) @@ -60,6 +76,8 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) Source PUBLIC Include + PLATFORM_INCLUDE_FILES + ${pal_dir}/additional_${PAL_PLATFORM_NAME_LOWERCASE}_tool_deps.cmake COMPILE_DEFINITIONS PRIVATE EDITOR @@ -68,5 +86,23 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS) AZ::AssetBuilderSDK Gem::Atom_Utils.Static Gem::Atom_AtomBridge.Static + RUNTIME_DEPENDENCIES + Gem::Atom_RHI.Private + Gem::Atom_RPI.Builders + Gem::Atom_RPI.Editor + Gem::Atom_RHI_Null.Private + Gem::Atom_RHI_Null.Builders + Gem::Atom_Feature_Common.Builders + Gem::Atom_Feature_Common.Editor + Gem::Atom_Bootstrap + Gem::Atom_Asset_Shader.Builders + Gem::Atom_Component_DebugCamera + Gem::AtomImGuiTools + Gem::AtomLyIntegration_CommonFeatures.Editor + Gem::EMotionFX_Atom.Editor + Gem::ImageProcessingAtom.Editor + Gem::ImguiAtom + Gem::AtomFont + Gem::AtomToolsFramework.Editor ) endif() diff --git a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_enginesettings_mac_files.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_runtime_deps.cmake similarity index 85% rename from Code/CryEngine/CryCommon/Platform/Mac/crycommon_enginesettings_mac_files.cmake rename to Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_runtime_deps.cmake index f862be24f6..31c0cab74b 100644 --- a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_enginesettings_mac_files.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_runtime_deps.cmake @@ -9,7 +9,6 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(FILES - ../../EngineSettingsBackendApple.cpp - ../../EngineSettingsBackendApple.h +set(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Vulkan.Private ) diff --git a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_enginesettings_windows_files.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_tool_deps.cmake similarity index 85% rename from Code/CryEngine/CryCommon/Platform/Windows/crycommon_enginesettings_windows_files.cmake rename to Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_tool_deps.cmake index db9fd5b464..99eec9a733 100644 --- a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_enginesettings_windows_files.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Android/additional_android_tool_deps.cmake @@ -9,7 +9,5 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(FILES - ../../EngineSettingsBackendWin32.cpp - ../../EngineSettingsBackendWin32.h +set(LY_RUNTIME_DEPENDENCIES ) diff --git a/Code/CryEngine/CryCommon/crycommon_enginesettings_files.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_runtime_deps.cmake similarity index 53% rename from Code/CryEngine/CryCommon/crycommon_enginesettings_files.cmake rename to Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_runtime_deps.cmake index 0fbd223d21..31c0cab74b 100644 --- a/Code/CryEngine/CryCommon/crycommon_enginesettings_files.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_runtime_deps.cmake @@ -9,19 +9,6 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(FILES - ProjectDefines.h - SettingsManagerHelpers.cpp - SettingsManagerHelpers.h - EngineSettingsManager.cpp - EngineSettingsManager.h - EngineSettingsBackend.cpp - EngineSettingsBackend.h - ResourceCompilerHelper.cpp - ResourceCompilerHelper.h -) - -# Remove files that cause #define collisions on Mac due to multiple inclusions of 'AppleSpecific.h' and include orders -set(SKIP_UNITY_BUILD_INCLUSION_FILES - SettingsManagerHelpers.cpp +set(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Vulkan.Private ) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake new file mode 100644 index 0000000000..c76527afa0 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake @@ -0,0 +1,19 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Vulkan.Private + Gem::Atom_RHI_DX12.Private + Gem::Atom_RHI_Metal.Private + Gem::Atom_RHI_Vulkan.Builders + Gem::Atom_RHI_DX12.Builders + Gem::Atom_RHI_Metal.Builders +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_runtime_deps.cmake new file mode 100644 index 0000000000..a0aa67c703 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_runtime_deps.cmake @@ -0,0 +1,14 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Metal.Private +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake new file mode 100644 index 0000000000..81046d3071 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake @@ -0,0 +1,19 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Metal.Private + Gem::Atom_RHI_Vulkan.Private + Gem::Atom_RHI_DX12.Private + Gem::Atom_RHI_Metal.Builders + Gem::Atom_RHI_Vulkan.Builders + Gem::Atom_RHI_DX12.Builders +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_runtime_deps.cmake new file mode 100644 index 0000000000..dfd0319c05 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_runtime_deps.cmake @@ -0,0 +1,16 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Vulkan.Private + Gem::Atom_RHI_DX12.Private + Gem::Atom_RHI_Null.Private +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake new file mode 100644 index 0000000000..c76527afa0 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake @@ -0,0 +1,19 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Vulkan.Private + Gem::Atom_RHI_DX12.Private + Gem::Atom_RHI_Metal.Private + Gem::Atom_RHI_Vulkan.Builders + Gem::Atom_RHI_DX12.Builders + Gem::Atom_RHI_Metal.Builders +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_runtime_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_runtime_deps.cmake new file mode 100644 index 0000000000..a0aa67c703 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_runtime_deps.cmake @@ -0,0 +1,14 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Metal.Private +) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_tool_deps.cmake new file mode 100644 index 0000000000..99eec9a733 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/iOS/additional_ios_tool_deps.cmake @@ -0,0 +1,13 @@ +# +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# + +set(LY_RUNTIME_DEPENDENCIES +) diff --git a/Gems/AudioEngineWwise/Code/CMakeLists.txt b/Gems/AudioEngineWwise/Code/CMakeLists.txt index dfd9ae6e24..5ea6a6d461 100644 --- a/Gems/AudioEngineWwise/Code/CMakeLists.txt +++ b/Gems/AudioEngineWwise/Code/CMakeLists.txt @@ -18,10 +18,15 @@ set(AUDIOENGINEWWISE_COMPILEDEFINITIONS $,WWISE_RELEASE,ENABLE_AUDIO_LOGGING> ) +find_package(Wwise MODULE) +if (NOT Wwise_FOUND) + message(STATUS "** Update the LY_WWISE_INSTALL_PATH cache variable if you intend to use Wwise.") +endif() + ################################################################################ # Server / Unsupported ################################################################################ -if (PAL_TRAIT_BUILD_SERVER_SUPPORTED OR PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB) +if (PAL_TRAIT_BUILD_SERVER_SUPPORTED OR PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB OR NOT Wwise_FOUND) # Stub gem for server and unsupported platforms. Audio Engine Wwise is client only ly_add_target( NAME AudioEngineWwise.Stub ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} @@ -34,11 +39,17 @@ if (PAL_TRAIT_BUILD_SERVER_SUPPORTED OR PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB) ) endif() -if (PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB) - add_library(Gem::AudioEngineWwise ALIAS AudioEngineWwise.Stub) #setup an alias so the stub will be used if something references AudioEngineWwise +if (PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB OR NOT Wwise_FOUND) + # setup aliases so stubs will be used if something references AudioEngineWwise(.Editor) + add_library(Gem::AudioEngineWwise ALIAS AudioEngineWwise.Stub) + add_library(Gem::AudioEngineWwise.Editor ALIAS AudioEngineWwise.Stub) return() endif() + +################################################################################ +# Runtime / Game +################################################################################ ly_add_target( NAME AudioEngineWwise.Static STATIC NAMESPACE Gem @@ -165,7 +176,7 @@ if (PAL_TRAIT_BUILD_TESTS_SUPPORTED) TARGETS ${testTargets} FILES - ${CMAKE_CURRENT_SOURCE_DIR}/Tests/Sounds//wwise/soundbanks/init.bnk + ${CMAKE_CURRENT_SOURCE_DIR}/Tests/Sounds/wwise/soundbanks/init.bnk OUTPUT_SUBDIRECTORY Test.Assets/Gems/AudioEngineWwise/sounds/wwise/soundbanks ) @@ -173,7 +184,7 @@ if (PAL_TRAIT_BUILD_TESTS_SUPPORTED) endif() ################################################################################ -# Editor +# Tools / Editor ################################################################################ if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( @@ -199,7 +210,6 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_target( NAME AudioEngineWwise.Editor GEM_MODULE - NAMESPACE Gem FILES_CMAKE audioenginewwise_editor_shared_files.cmake diff --git a/Gems/AudioEngineWwise/Code/Platform/Android/PAL_android.cmake b/Gems/AudioEngineWwise/Code/Platform/Android/PAL_android.cmake index 69420d8aca..9600a0a2cb 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Android/PAL_android.cmake +++ b/Gems/AudioEngineWwise/Code/Platform/Android/PAL_android.cmake @@ -9,4 +9,4 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB TRUE) +set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB FALSE) diff --git a/Gems/AudioEngineWwise/Code/Platform/Linux/PAL_linux.cmake b/Gems/AudioEngineWwise/Code/Platform/Linux/PAL_linux.cmake index 69420d8aca..9600a0a2cb 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Linux/PAL_linux.cmake +++ b/Gems/AudioEngineWwise/Code/Platform/Linux/PAL_linux.cmake @@ -9,4 +9,4 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB TRUE) +set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB FALSE) diff --git a/Gems/AudioEngineWwise/Code/Platform/Mac/PAL_mac.cmake b/Gems/AudioEngineWwise/Code/Platform/Mac/PAL_mac.cmake index 69420d8aca..9600a0a2cb 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Mac/PAL_mac.cmake +++ b/Gems/AudioEngineWwise/Code/Platform/Mac/PAL_mac.cmake @@ -9,4 +9,4 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB TRUE) +set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB FALSE) diff --git a/Gems/AudioEngineWwise/Code/Platform/Windows/AudioSystemImpl_wwise_Windows.cpp b/Gems/AudioEngineWwise/Code/Platform/Windows/AudioSystemImpl_wwise_Windows.cpp index b6ae569e30..2cf8acba9c 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Windows/AudioSystemImpl_wwise_Windows.cpp +++ b/Gems/AudioEngineWwise/Code/Platform/Windows/AudioSystemImpl_wwise_Windows.cpp @@ -25,8 +25,6 @@ namespace Audio void SetupAkSoundEngine(AkPlatformInitSettings& platformInitSettings) { - // Turn off XAudio2 output type due to rare startup crashes. Prefers WASAPI or DirectSound. - platformInitSettings.eAudioAPI = static_cast(platformInitSettings.eAudioAPI & ~AkAPI_XAudio2); platformInitSettings.threadBankManager.dwAffinityMask = 0; platformInitSettings.threadLEngine.dwAffinityMask = 0; platformInitSettings.threadMonitor.dwAffinityMask = 0; diff --git a/Gems/AudioEngineWwise/Code/Platform/Windows/PAL_windows.cmake b/Gems/AudioEngineWwise/Code/Platform/Windows/PAL_windows.cmake index 69420d8aca..9600a0a2cb 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Windows/PAL_windows.cmake +++ b/Gems/AudioEngineWwise/Code/Platform/Windows/PAL_windows.cmake @@ -9,4 +9,4 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB TRUE) +set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB FALSE) diff --git a/Gems/AudioEngineWwise/Code/Platform/iOS/PAL_ios.cmake b/Gems/AudioEngineWwise/Code/Platform/iOS/PAL_ios.cmake index 69420d8aca..9600a0a2cb 100644 --- a/Gems/AudioEngineWwise/Code/Platform/iOS/PAL_ios.cmake +++ b/Gems/AudioEngineWwise/Code/Platform/iOS/PAL_ios.cmake @@ -9,4 +9,4 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB TRUE) +set(PAL_TRAIT_AUDIO_ENGINE_WWISE_USE_STUB FALSE) diff --git a/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp b/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp index 2e11c7a810..6fb21964a3 100644 --- a/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp +++ b/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp @@ -66,12 +66,18 @@ namespace Audio { void* Malloc(AkMemPoolId memId, size_t size) { - return AZ::AllocatorInstance::Get().Allocate(size, 0, 0, MemoryManagerCategories[memId & AkMemID_MASK]); + size_t memCategory = memId & AkMemID_MASK; + AZ_Assert(memCategory < AkMemID_NUM, "Wwise::MemHooks::Malloc - Bad AkMemPoolId passed: %zu", memCategory); + return AZ::AllocatorInstance::Get().Allocate(size, 0, 0, + (memCategory < AkMemID_NUM) ? MemoryManagerCategories[memCategory] : nullptr); } void* Malign(AkMemPoolId memId, size_t size, AkUInt32 alignment) { - return AZ::AllocatorInstance::Get().Allocate(size, alignment, 0, MemoryManagerCategories[memId & AkMemID_MASK]); + size_t memCategory = memId & AkMemID_MASK; + AZ_Assert(memCategory < AkMemID_NUM, "WWise::MemHooks::Malign - Bad AkMemPoolId passed: %zu", memCategory); + return AZ::AllocatorInstance::Get().Allocate(size, alignment, 0, + (memCategory < AkMemID_NUM) ? MemoryManagerCategories[memCategory] : nullptr); } void* Realloc([[maybe_unused]] AkMemPoolId memId, void* address, size_t size) @@ -79,12 +85,12 @@ namespace Audio return AZ::AllocatorInstance::Get().ReAllocate(address, size, 0); } - void Free([[maybe_unused]] AkMemPoolId memId, void* address) + void* ReallocAligned([[maybe_unused]] AkMemPoolId memId, void* address, size_t size, AkUInt32 alignment) { - AZ::AllocatorInstance::Get().DeAllocate(address); + return AZ::AllocatorInstance::Get().ReAllocate(address, size, alignment); } - void Falign([[maybe_unused]] AkMemPoolId memId, void* address) + void Free([[maybe_unused]] AkMemPoolId memId, void* address) { AZ::AllocatorInstance::Get().DeAllocate(address); } @@ -427,8 +433,8 @@ namespace Audio akMemSettings.pfMalloc = Wwise::MemHooks::Malloc; akMemSettings.pfMalign = Wwise::MemHooks::Malign; akMemSettings.pfRealloc = Wwise::MemHooks::Realloc; + akMemSettings.pfReallocAligned = Wwise::MemHooks::ReallocAligned; akMemSettings.pfFree = Wwise::MemHooks::Free; - akMemSettings.pfFalign = Wwise::MemHooks::Falign; akMemSettings.pfTotalReservedMemorySize = Wwise::MemHooks::TotalReservedMemorySize; akMemSettings.pfSizeOfMemory = Wwise::MemHooks::SizeOfMemory; akMemSettings.uMemAllocationSizeLimit = Wwise::Cvars::s_PrimaryMemorySize << 10; diff --git a/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h b/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h index 2e806a80e9..25e6a22d84 100644 --- a/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h +++ b/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h @@ -91,8 +91,9 @@ namespace Audio // See AkMemoryMgr.h inline static const char* MemoryManagerCategories[] { - "Object", "Event", "Structure", "Media", "GameObject", "Processing", "ProcessingPlugin", "Streaming", "StreamingIO", "SpatialAudio", - "SpatialAudioGeometry", "SpatialAudioPaths", "GameSim", "MonitorQueue", "Profiler", "FilePackage", "SoundEngine" + "Object", "Event", "Structure", "Media", "GameObject", "Processing", "ProcessingPlugin", "Streaming", "StreamingIO", + "SpatialAudio", "SpatialAudioGeometry", "SpatialAudioPaths", "GameSim", "MonitorQueue", "Profiler", "FilePackage", + "SoundEngine", "Integration" }; static_assert(AZ_ARRAY_SIZE(MemoryManagerCategories) == AkMemID_NUM, diff --git a/Gems/AudioEngineWwise/Tools/WwiseAuthoringScripts/ly_copy_output_and_generate_metadata.wcmdline b/Gems/AudioEngineWwise/Tools/WwiseAuthoringScripts/ly_copy_output_and_generate_metadata.wcmdline index 5d2394fae2..3cc868384b 100644 --- a/Gems/AudioEngineWwise/Tools/WwiseAuthoringScripts/ly_copy_output_and_generate_metadata.wcmdline +++ b/Gems/AudioEngineWwise/Tools/WwiseAuthoringScripts/ly_copy_output_and_generate_metadata.wcmdline @@ -1,3 +1,3 @@ -"$(WwiseExePath)\CopyStreamedFiles.exe" -info "$(InfoFilePath)" -outputpath "$(SoundBankPath)" -banks "$(SoundBankListAsTextFile)" -languages "$(LanguageList)" -"$(WwiseProjectPath)\..\..\..\python.cmd" "$(WwiseProjectPath)\..\..\..\Gems\AudioEngineWwise\Tools\WwiseAuthoringScripts\bank_info_parser.py" "$(InfoFilePath)" "$(SoundBankPath)" +"$(CopyStreamedFilesExePath)" -info "$(InfoFilePath)" -outputpath "$(SoundBankPath)" -banks "$(SoundBankListAsTextFile)" -languages "$(LanguageList)" +"$(WwiseProjectPath)\..\..\..\python\python.cmd" "$(WwiseProjectPath)\..\..\..\Gems\AudioEngineWwise\Tools\WwiseAuthoringScripts\bank_info_parser.py" "$(InfoFilePath)" "$(SoundBankPath)" diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncComponent.cpp deleted file mode 100644 index 904f500018..0000000000 --- a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncComponent.cpp +++ /dev/null @@ -1,448 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "EMotionFX_precompiled.h" -#include -#include -#include -#include -#include -#include - -namespace EMotionFX -{ - namespace Integration - { - namespace Network - { - /** - * \brief This is a GridMate chunk that replicates Anim Graph parameters. - * It's challenge is to replicate any of the supported parameter types where - * the types are only known at runtime. To solve that, many datasets are created - * with helper macros to avoid code duplication (@PARAM_DATASET and @PARAM_DATASET_NAME). - * - * For maximum compression, one should build a custom component that specifies the anim graph parameters by hand, for example: - * - * DataSet m_param0; - * - * or if using delta compression feature of GridMate: - * - * DeltaCompressedDataSet m_param1; - * - * Active nodes (@m_activeNodes) change infrequently. - * - * Warning: @m_motionNodes motion nodes often do change frequently as their motion play time ticks down. - * Care must be applied when aiming for the network budget of a project. - */ - class AnimGraphNetSyncComponent::Chunk : public GridMate::ReplicaChunkBase - { - public: - GM_CLASS_ALLOCATOR(Chunk); - - Chunk() : m_activeNodes("Active Nodes", NodeIndexContainer{}), m_motionNodes("Motion Nodes", MotionNodePlaytimeContainer{}) {} - - static const char* GetChunkName() { return "AnimGraphNetSyncComponent::Chunk"; } - bool IsReplicaMigratable() override { return true; } - - using AnimDataSetType = GridMate::DataSet; - - template - using AnimDataSet = AnimDataSetType::BindInterface; - - // A helper macro that creates a variable like this one: - // AnimDataSet<&AnimGraphNetSyncComponent::OnAnimParameterChanged<0>> m_parameter0 = { "Param 0" }; - #define PARAM_DATASET( N ) AnimDataSet<&AnimGraphNetSyncComponent::OnAnimParameterChanged< N >> m_parameter##N = { "Param " #N } - - PARAM_DATASET(0); - PARAM_DATASET(1); - PARAM_DATASET(2); - PARAM_DATASET(3); - PARAM_DATASET(4); - PARAM_DATASET(5); - PARAM_DATASET(6); - PARAM_DATASET(7); - PARAM_DATASET(8); - PARAM_DATASET(9); - - /* - * Note: GridMate by default supports up to 32 DataSets per ReplicaChunk: @GM_MAX_DATASETS_IN_CHUNK. - * That means that a component can sync up to 32 separate network fields. One can vary the number of supported number - * of parameters by simply creating new entries of @PARAM_DATASET above and @PARAM_DATASET_NAME below. - */ - - // A collection of datasets that are used to synchronize anim graph parameters. - AZStd::array m_parameters = { { // clang pre-6.0 requires double "{{" here but doesn't perform compile length verification :( - &m_parameter0, - &m_parameter1, - &m_parameter2, - &m_parameter3, - &m_parameter4, - &m_parameter5, - &m_parameter6, - &m_parameter7, - &m_parameter8, - &m_parameter9, - } }; - - GridMate::DataSet:: - BindInterface m_activeNodes; - GridMate::DataSet:: - BindInterface m_motionNodes; - }; - - void AnimGraphNetSyncComponent::Reflect(AZ::ReflectContext* context) - { - GridMate::ReplicaChunkDescriptorTable& descTable = GridMate::ReplicaChunkDescriptorTable::Get(); - if (!descTable.FindReplicaChunkDescriptor(GridMate::ReplicaChunkClassId(Chunk::GetChunkName()))) - { - descTable.RegisterChunkType(); - } - - AZ::SerializeContext* serializeContext = azrtti_cast(context); - if (serializeContext) - { - serializeContext->Class() - ->Version(1) - ->Field( "Sync parameters", &AnimGraphNetSyncComponent::m_syncParameters ) - ->Field( "Sync active nodes", &AnimGraphNetSyncComponent::m_syncActiveNodes ) - ->Field( "Sync motion nodes", &AnimGraphNetSyncComponent::m_syncMotionNodes ) - ; - - AZ::EditContext* editContent = serializeContext->GetEditContext(); - if (editContent) - { - editContent->Class("Anim Graph Net Sync", - "Replicates anim graph parameters over the network using GridMate") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) - ->Attribute(AZ::Edit::Attributes::Category, "Networking") - ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/AnimGraphNetSync.svg") - ->DataElement( AZ::Edit::UIHandlers::Default, &AnimGraphNetSyncComponent::m_syncParameters, "Sync parameters", - "Synchronize parameters of the anim graph on the entity" ) - ->DataElement( AZ::Edit::UIHandlers::Default, &AnimGraphNetSyncComponent::m_syncActiveNodes, "Sync active nodes", - "Synchronize active nodes in the anim graph on the entity" ) - ->DataElement( AZ::Edit::UIHandlers::Default, &AnimGraphNetSyncComponent::m_syncMotionNodes, "Sync motion nodes", - "Synchronize motion nodes in the anim graph on the entity. Warning: this may take a significant amount of network bandwidth" ) - ; - } - } - } - - void AnimGraphNetSyncComponent::Activate() - { - AnimGraphComponentNotificationBus::Handler::BusConnect(GetEntityId()); - - if (m_syncMotionNodes || m_syncActiveNodes) // if there is anything synchronize over the network - { - const bool isAuthoritative = AzFramework::NetQuery::IsEntityAuthoritative(GetEntityId()); - if (isAuthoritative) - { - // Only the server (or authoritative entity) needs to watch the nodes values. - AZ::TickBus::Handler::BusConnect(); - } - - // We need to get anim graph instance. It will be either available to us now or later via a notification bus. See @OnAnimGraphInstanceCreated - AnimGraphComponentRequestBus::EventResult(m_instance, GetEntityId(), &AnimGraphComponentRequestBus::Events::GetAnimGraphInstance); - if (m_instance) - { - if (!m_instance->GetSnapshot()) - { - m_instance->CreateSnapshot(isAuthoritative); - } - } - } - } - - void AnimGraphNetSyncComponent::Deactivate() - { - AnimGraphComponentNotificationBus::Handler::BusDisconnect(); - AZ::TickBus::Handler::BusDisconnect(); - } - - void AnimGraphNetSyncComponent::SetParameterOnClient(const AnimParameter& value, AZ::u8 index) - { - switch (value.m_type) - { - case AnimParameter::Type::Unsupported: - break; - case AnimParameter::Type::Float: - AnimGraphComponentRequestBus::Event(GetEntityId(), &AnimGraphComponentRequestBus::Events::SetParameterFloat, index, value.m_value.f); - break; - case AnimParameter::Type::Bool: - AnimGraphComponentRequestBus::Event(GetEntityId(), &AnimGraphComponentRequestBus::Events::SetParameterBool, index, value.m_value.b); - break; - case AnimParameter::Type::Vector2: - AnimGraphComponentRequestBus::Event(GetEntityId(), &AnimGraphComponentRequestBus::Events::SetParameterVector2, index, value.m_value.v2); - break; - case AnimParameter::Type::Vector3: - AnimGraphComponentRequestBus::Event(GetEntityId(), &AnimGraphComponentRequestBus::Events::SetParameterVector3, index, value.m_value.v3); - break; - case AnimParameter::Type::Quaternion: - AnimGraphComponentRequestBus::Event(GetEntityId(), &AnimGraphComponentRequestBus::Events::SetParameterRotation, index, value.m_value.q); - break; - default: - AZ_Assert(false, "Unsupported type"); - break; - } - } - - template - void AnimGraphNetSyncComponent::OnAnimParameterChanged(const AnimParameter& value, const GridMate::TimeContext&) - { - SetParameterOnClient(value, Index); - } - - template - void AnimGraphNetSyncComponent::SetParameterOnServer(AZ::u8 parameterIndex, const FieldType& newValue) - { - if (m_syncParameters) - { - if (Chunk* chunk = GetChunk()) - { - if (parameterIndex < chunk->m_parameters.size()) - { - AnimParameter param; - param.m_type = AnimParameterType; - - static_assert(sizeof(FieldType) <= sizeof(param.m_value), "The largest value param.m_value can store is a Quaternion"); - // This is to simplify writing a value into a union. - // Ideally, one would use std::variant (C++17) instead of a union. - memcpy(¶m.m_value, &newValue, sizeof(FieldType)); - - chunk->m_parameters[parameterIndex]->Set(param); - } - else - { - AZ_Warning("EMotionFX", false, "AnimGraphNetSyncComponent does not support synchronizing more than %u parameters", chunk->m_parameters.size()); - } - } - } - } - - void AnimGraphNetSyncComponent::OnAnimGraphFloatParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - float beforeValue, - float afterValue) - { - AZ_UNUSED(beforeValue); - SetParameterOnServer(static_cast(parameterIndex), afterValue); - } - - void AnimGraphNetSyncComponent::OnAnimGraphBoolParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - bool beforeValue, - bool afterValue) - { - AZ_UNUSED(beforeValue); - SetParameterOnServer(static_cast(parameterIndex), afterValue); - } - - void AnimGraphNetSyncComponent::OnAnimGraphStringParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const char* beforeValue, - const char* afterValue) - { - AZ_UNUSED(parameterIndex); - AZ_UNUSED(beforeValue); - AZ_UNUSED(afterValue); - AZ_Warning("EMotionFX", false, "AnimGraphNetSync component does not supported synchronizing string parameters, please consider refactoring your anim graph to replace strings with integers or enum values."); - } - - void AnimGraphNetSyncComponent::OnAnimGraphVector2ParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const AZ::Vector2& beforeValue, - const AZ::Vector2& afterValue) - { - AZ_UNUSED(beforeValue); - SetParameterOnServer(static_cast(parameterIndex), afterValue); - } - - void AnimGraphNetSyncComponent::OnAnimGraphVector3ParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const AZ::Vector3& beforeValue, - const AZ::Vector3& afterValue) - { - AZ_UNUSED(beforeValue); - SetParameterOnServer(static_cast(parameterIndex), afterValue); - } - - void AnimGraphNetSyncComponent::OnAnimGraphRotationParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const AZ::Quaternion& beforeValue, - const AZ::Quaternion& afterValue) - { - AZ_UNUSED(beforeValue); - SetParameterOnServer(static_cast(parameterIndex), afterValue); - } - - void AnimGraphNetSyncComponent::OnActiveNodesChanged(const NodeIndexContainer& activeNodes, const GridMate::TimeContext& tc) - { - AZ_UNUSED(tc); - // Client receiving values - if (m_instance) - { - if (const AZStd::shared_ptr snapshot = m_instance->GetSnapshot()) - { - snapshot->SetActiveNodes(activeNodes); - } - } - } - - void AnimGraphNetSyncComponent::OnMotionNodesChanged(const MotionNodePlaytimeContainer& motionNodes, const GridMate::TimeContext& tc) - { - AZ_UNUSED(tc); - // Client receiving values - if (m_instance) - { - if (const AZStd::shared_ptr snapshot = m_instance->GetSnapshot()) - { - snapshot->SetMotionNodePlaytimes(motionNodes); - } - } - } - - bool AnimGraphNetSyncComponent::IsDifferent(const MotionNodePlaytimeContainer& oldList, const MotionNodePlaytimeContainer& newList) const - { - if (oldList.size() != newList.size()) - { - return true; - } - - AZStd::size_t i = 0; - for (auto& value : oldList) - { - if (value.first != newList[i].first || value.second != newList[i].second) - { - return true; - } - - ++i; - } - - return false; - } - - bool AnimGraphNetSyncComponent::IsDifferent(const NodeIndexContainer& oldList, const NodeIndexContainer& newList) const - { - if (oldList.size() != newList.size()) - { - return true; - } - - AZStd::size_t i = 0; - for (AZ::u32 value : oldList) - { - if (value != newList[i]) - { - return true; - } - - ++i; - } - - return false; - } - - void AnimGraphNetSyncComponent::OnTick(float deltaTime, AZ::ScriptTimePoint time) - { - AZ_UNUSED(deltaTime); - AZ_UNUSED(time); - - if (!GetChunk()) - { - return; // network is not ready yet - } - - if (m_instance) - { - if (const AZStd::shared_ptr snapshot = m_instance->GetSnapshot()) - { - if (m_syncActiveNodes) - { - const NodeIndexContainer& activeNodes = snapshot->GetActiveNodes(); - const NodeIndexContainer& currentValue = GetChunk()->m_activeNodes.Get(); - if (IsDifferent(currentValue, activeNodes)) - { - GetChunk()->m_activeNodes.Set(activeNodes); // Server sending the values - } - } - - if (m_syncMotionNodes) - { - const MotionNodePlaytimeContainer& playTimes = snapshot->GetMotionNodePlaytimes(); - const MotionNodePlaytimeContainer& currentTimes = GetChunk()->m_motionNodes.Get(); - if (IsDifferent(currentTimes, playTimes)) - { - GetChunk()->m_motionNodes.Set(playTimes); // Server sending the values - } - } - } - } - } - - void AnimGraphNetSyncComponent::OnAnimGraphInstanceCreated(EMotionFX::AnimGraphInstance* instance) - { - m_instance = instance; - if (m_instance) - { - const bool isAuthoritative = AzFramework::NetQuery::IsEntityAuthoritative(GetEntityId()); - if (!m_instance->GetSnapshot()) - { - m_instance->CreateSnapshot(isAuthoritative); - } - } - } - - void AnimGraphNetSyncComponent::OnAnimGraphInstanceDestroyed(EMotionFX::AnimGraphInstance*) - { - m_instance = nullptr; - } - - AnimGraphNetSyncComponent::Chunk* AnimGraphNetSyncComponent::GetChunk() const - { - return static_cast(m_chunk.get()); - } - - GridMate::ReplicaChunkPtr AnimGraphNetSyncComponent::GetNetworkBinding() - { - m_chunk = GridMate::CreateReplicaChunk(); - AZ_Assert(m_chunk, "Failed to create a chunk"); - - if (m_instance) - { - if (!m_instance->GetSnapshot()) - { - m_instance->CreateSnapshot(true /* authoritative */); - } - } - - return m_chunk; - } - - void AnimGraphNetSyncComponent::SetNetworkBinding(GridMate::ReplicaChunkPtr chunk) - { - m_chunk = chunk; - m_chunk->SetHandler(this); - } - - void AnimGraphNetSyncComponent::UnbindFromNetwork() - { - AZ_Assert(m_chunk, "There wasn't any chunk present"); - if (m_chunk) - { - m_chunk->SetHandler(nullptr); - m_chunk = nullptr; - } - } - } - } // namespace Integration -} // namespace EMotionFXAnimation diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncComponent.h deleted file mode 100644 index b6cfc2c795..0000000000 --- a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncComponent.h +++ /dev/null @@ -1,153 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include -#include -#include -#include -#include - -namespace EMotionFX -{ - namespace Integration - { - namespace Network - { - /** - * \brief Generic solution for synchronizing parameters of Anim Graph component. - * Synchronization is done over GridMate. - * - * Note that this is not the most optimal synchronization but it does - * work for just about all Anim Graphs. - * - * Disclaimer: string parameters are not supported! Because one should not synchronize - * strings over the network. They ought to be converted to enum/int values beforehand. - */ - class AnimGraphNetSyncComponent - : public AZ::Component - , public AzFramework::NetBindable - , public AnimGraphComponentNotificationBus::Handler - , public AZ::TickBus::Handler - { - public: - AZ_COMPONENT(AnimGraphNetSyncComponent, "{2F9428C1-0F07-4667-B052-40D9BC473AD3}", NetBindable); - - static void Reflect(AZ::ReflectContext* context); - - // AZ::Component interface implementation - void Activate() override; - void Deactivate() override; - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("EMotionFXAnimGraphNetSyncService", 0x42e6f127)); - } - - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("EMotionFXAnimGraphNetSyncService", 0x42e6f127)); - } - - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) - { - required.push_back(AZ_CRC("EMotionFXAnimGraphService", 0x9ec3c819)); - required.push_back(AZ_CRC("ReplicaChunkService", 0xf86b88a8)); - } - - protected: - // NetBindable interface implementation - GridMate::ReplicaChunkPtr GetNetworkBinding() override; - void SetNetworkBinding(GridMate::ReplicaChunkPtr chunk) override; - void UnbindFromNetwork() override; - - // AnimGraphComponentNotificationBus interface implementation - void OnAnimGraphFloatParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - float beforeValue, - float afterValue) override; - void OnAnimGraphBoolParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - bool beforeValue, - bool afterValue) override; - void OnAnimGraphStringParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const char* beforeValue, - const char* afterValue) override; - void OnAnimGraphVector2ParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const AZ::Vector2& beforeValue, - const AZ::Vector2& afterValue) override; - void OnAnimGraphVector3ParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const AZ::Vector3& beforeValue, - const AZ::Vector3& afterValue) override; - void OnAnimGraphRotationParameterChanged(EMotionFX::AnimGraphInstance*, - AZ::u32 parameterIndex, - const AZ::Quaternion& beforeValue, - const AZ::Quaternion& afterValue) override; - - // TickBus - void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - - // AnimGraphComponentNotificationBus - void OnAnimGraphInstanceCreated(EMotionFX::AnimGraphInstance* instance) override; - void OnAnimGraphInstanceDestroyed(EMotionFX::AnimGraphInstance* instance) override; - - private: - class Chunk; - GridMate::ReplicaChunkPtr m_chunk; - Chunk* GetChunk() const; - - // DataSet callback, it's a template to avoid duplicating similar callbacks - template - void OnAnimParameterChanged(const AnimParameter& value, const GridMate::TimeContext& tc); - - // Helper on a client side - void SetParameterOnClient(const AnimParameter& value, AZ::u8 index); - - // Helper on the server side to avoid duplicating very similar callbacks - template - void SetParameterOnServer(AZ::u8 parameterIndex, const FieldType& newValue); - - /** - * \brief Optionally turn on or off replicating parameters of an anim graph on the same entity as this component. - */ - bool m_syncParameters = true; - - /** - * \brief Optionally turn on or off replicating active nodes of an anim graph on the same entity as this component. - */ - bool m_syncActiveNodes = false; - /** - * \brief Optionally turn on or off replicating motion playtime nodes of an anim graph on the same entity as this component. - * - * It's off by default because these nodes are very frequently changing and would result in a high network bandwidth use. - */ - bool m_syncMotionNodes = false; - - // GridMate DataSet callback on clients - void OnActiveNodesChanged(const NodeIndexContainer& activeNodes, const GridMate::TimeContext& tc); - // GridMate DataSet callback on clients - void OnMotionNodesChanged(const MotionNodePlaytimeContainer& motionNodes, const GridMate::TimeContext& tc); - - // Helper comparison method to avoid sending the same data - bool IsDifferent(const NodeIndexContainer& oldList, const NodeIndexContainer& newList) const; - // Helper comparison method to avoid sending the same data - bool IsDifferent(const MotionNodePlaytimeContainer& oldList, const MotionNodePlaytimeContainer& newList) const; - - EMotionFX::AnimGraphInstance* m_instance = nullptr; - }; - } - } // namespace Integration -} // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncTypes.h b/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncTypes.h deleted file mode 100644 index 9194dc1b65..0000000000 --- a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphNetSyncTypes.h +++ /dev/null @@ -1,285 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include -#include -#include - -namespace EMotionFX -{ - namespace Integration - { - namespace Network - { - /** - * \brief A general storage for an anim graph parameter. - */ - class AnimParameter - { - public: - /** - * \brief String type is not supported because one should not be syncing strings over the network. - */ - enum class Type : AZ::u8 - { - Unsupported, - Float, - Bool, - Vector2, - Vector3, - Quaternion, - }; - - /** - * \brief A storage for all possible supported types in @AnimGraphNetSyncComponent - */ - union Value - { - Value() - { - q = AZ::Quaternion::CreateZero(); - } - - float f; - bool b = false; - AZ::Vector2 v2; - AZ::Vector3 v3; - AZ::Quaternion q; - }; - - AnimParameter() : m_type(Type::Unsupported) {} - - Type m_type; - Value m_value; - - AnimParameter(const AnimParameter& other) - { - m_type = other.m_type; - CopyValue(other); - } - - AnimParameter& operator=(const AnimParameter& other) - { - m_type = other.m_type; - CopyValue(other); - - return *this; - } - - friend bool operator==(const AnimParameter& lhs, const AnimParameter& rhs) - { - if (lhs.m_type != rhs.m_type) - { - return false; - } - - switch (lhs.m_type) - { - case Type::Float: - return lhs.m_value.f == rhs.m_value.f; - case Type::Bool: - return lhs.m_value.b == rhs.m_value.b; - case Type::Vector2: - return lhs.m_value.v2 == rhs.m_value.v2; - case Type::Vector3: - return lhs.m_value.v3 == rhs.m_value.v3; - case Type::Quaternion: - return lhs.m_value.q == rhs.m_value.q; - default: - return true; - } - } - - private: - void CopyValue(const AnimParameter& other) - { - switch (m_type) - { - case Type::Float: - m_value.f = other.m_value.f; - break; - case Type::Bool: - m_value.b = other.m_value.b; - break; - case Type::Vector2: - m_value.v2 = other.m_value.v2; - break; - case Type::Vector3: - m_value.v3 = other.m_value.v3; - break; - case Type::Quaternion: - m_value.q = other.m_value.q; - break; - default: - break; - } - } - }; - - /** - * \brief Custom GridMate throttler. See GridMate:: @BasicThrottle - */ - class AnimParameterThrottler - { - public: - bool WithinThreshold(const AnimParameter& newValue) const - { - return m_baseline == newValue; - } - - void UpdateBaseline(const AnimParameter& baseline) - { - m_baseline = baseline; - } - - private: - AnimParameter m_baseline; - }; - - /** - * \brief A custom GridMate marshaler. - * 1 byte is spend on the type. And a variable number of bytes afterwards for the value. - */ - class AnimParameterMarshaler - { - public: - void Marshal(GridMate::WriteBuffer& wb, const AnimParameter& parameter) - { - wb.Write(AZ::u8(parameter.m_type)); - - switch (parameter.m_type) - { - case AnimParameter::Type::Float: - wb.Write(parameter.m_value.f); - break; - case AnimParameter::Type::Bool: - wb.Write(parameter.m_value.b); - break; - case AnimParameter::Type::Vector2: - wb.Write(parameter.m_value.v2); - break; - case AnimParameter::Type::Vector3: - wb.Write(parameter.m_value.v3); - break; - case AnimParameter::Type::Quaternion: - wb.Write(parameter.m_value.q); - break; - default: - // other types are not supported - break; - } - } - - void Unmarshal(AnimParameter& parameter, GridMate::ReadBuffer& rb) - { - AZ::u8 type; - rb.Read(type); - parameter.m_type = static_cast(type); - - switch (parameter.m_type) - { - case AnimParameter::Type::Float: - rb.Read(parameter.m_value.f); - break; - case AnimParameter::Type::Bool: - rb.Read(parameter.m_value.b); - break; - case AnimParameter::Type::Vector2: - rb.Read(parameter.m_value.v2); - break; - case AnimParameter::Type::Vector3: - rb.Read(parameter.m_value.v3); - break; - case AnimParameter::Type::Quaternion: - rb.Read(parameter.m_value.q); - break; - default: - // other types are not supported - break; - } - } - }; - - /** - * \brief Custom marshaler for Animation node index that is used by Activate Nodes list - */ - struct NodeIndexContainerMarshaler - { - void Marshal(GridMate::WriteBuffer& wb, const NodeIndexContainer& source) const - { - GridMate::VlqU64Marshaler m64; - GridMate::VlqU32Marshaler m32; - - m64.Marshal(wb, source.size()); // 1 byte most of the time (if the size is less than 127) - for (AZ::u32 item : source) - { - m32.Marshal(wb, item); // 1 byte most of the time (if the value is less than 127) - } - } - - void Unmarshal(NodeIndexContainer& target, GridMate::ReadBuffer& rb) const - { - target.clear(); - GridMate::VlqU64Marshaler m64; - GridMate::VlqU32Marshaler m32; - - AZ::u64 arraySize; - m64.Unmarshal(arraySize, rb); - target.resize(arraySize); - - for (AZ::u64 i = 0; i < arraySize; ++i) - { - m32.Unmarshal(target[i], rb); - } - } - }; - - /** - * \brief Custom marshaler for Animation motion node information that is used by motion node playtime list - */ - struct MotionNodePlaytimeContainerMarshaler - { - void Marshal(GridMate::WriteBuffer& wb, const MotionNodePlaytimeContainer& source) const - { - GridMate::VlqU64Marshaler m64; - GridMate::VlqU32Marshaler m32; - - m64.Marshal(wb, source.size()); - for (const AZStd::pair& item : source) - { - m32.Marshal(wb, item.first); // average of 1 byte - wb.Write(item.second); // 4 bytes - } - } - - void Unmarshal(MotionNodePlaytimeContainer& target, GridMate::ReadBuffer& rb) const - { - target.clear(); - GridMate::VlqU64Marshaler m64; - GridMate::VlqU32Marshaler m32; - - AZ::u64 arraySize; - m64.Unmarshal(arraySize, rb); - target.resize(arraySize); - - for (AZ::u64 i = 0; i < arraySize; ++i) - { - m32.Unmarshal(target[i].first, rb); - rb.Read(target[i].second); - } - } - }; - } - } // namespace Integration -} // namespace EMotionFXAnimation diff --git a/Gems/EMotionFX/Code/Source/Integration/System/AnimationModule.cpp b/Gems/EMotionFX/Code/Source/Integration/System/AnimationModule.cpp index 4d7db16133..e5561697fd 100644 --- a/Gems/EMotionFX/Code/Source/Integration/System/AnimationModule.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/System/AnimationModule.cpp @@ -17,7 +17,6 @@ #include #include #include -#include #include #include #include @@ -74,8 +73,6 @@ namespace EMotionFX AnimGraphComponent::CreateDescriptor(), SimpleMotionComponent::CreateDescriptor(), SimpleLODComponent::CreateDescriptor(), - - Network::AnimGraphNetSyncComponent::CreateDescriptor(), #if defined(EMOTIONFXANIMATION_EDITOR) // Pipeline components diff --git a/Gems/EMotionFX/Code/emotionfx_shared_files.cmake b/Gems/EMotionFX/Code/emotionfx_shared_files.cmake index 0c7e4ef0e7..88c6525f91 100644 --- a/Gems/EMotionFX/Code/emotionfx_shared_files.cmake +++ b/Gems/EMotionFX/Code/emotionfx_shared_files.cmake @@ -31,9 +31,6 @@ set(FILES Source/Integration/Components/ActorComponent.cpp Source/Integration/Components/AnimAudioComponent.h Source/Integration/Components/AnimAudioComponent.cpp - Source/Integration/Components/AnimGraphNetSyncComponent.h - Source/Integration/Components/AnimGraphNetSyncTypes.h - Source/Integration/Components/AnimGraphNetSyncComponent.cpp Source/Integration/Components/AnimGraphComponent.h Source/Integration/Components/AnimGraphComponent.cpp Source/Integration/Components/SimpleMotionComponent.h diff --git a/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp b/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp index 20721d4624..5123d120d5 100644 --- a/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp +++ b/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp @@ -27,8 +27,6 @@ #include "SpriteBorderEditorCommon.h" -#include - #include #include diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.h b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.h index 4374b67e32..a1fb6d5572 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.h +++ b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.h @@ -14,6 +14,7 @@ #include #include +#include #include diff --git a/Gems/PhysX/Code/Tests/PhysXTestCommon.h b/Gems/PhysX/Code/Tests/PhysXTestCommon.h index c4d08953eb..d130cccf9f 100644 --- a/Gems/PhysX/Code/Tests/PhysXTestCommon.h +++ b/Gems/PhysX/Code/Tests/PhysXTestCommon.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include diff --git a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp index 84a4cd5cc6..a95ec60d61 100644 --- a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp +++ b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.cpp @@ -176,6 +176,7 @@ namespace AZ::Prefab bool PrefabBuilderComponent::StoreProducts( AZ::IO::PathView tempDirPath, const AzToolsFramework::Prefab::PrefabConversionUtils::PrefabProcessorContext::ProcessedObjectStoreContainer& store, + const AzToolsFramework::Prefab::PrefabConversionUtils::PrefabProcessorContext::ProductAssetDependencyContainer& registeredDependencies, AZStd::vector& outputProducts) const { outputProducts.reserve(store.size()); @@ -214,6 +215,18 @@ namespace AZ::Prefab if (AssetBuilderSDK::OutputObject(&object.GetAsset(), object.GetAssetType(), productPath.String(), object.GetAssetType(), object.GetAsset().GetId().m_subId, product)) { + auto findRegisteredDependencies = registeredDependencies.find(object.GetAsset().GetId()); + if (findRegisteredDependencies != registeredDependencies.end()) + { + AZStd::transform(findRegisteredDependencies->second.begin(), findRegisteredDependencies->second.end(), + AZStd::back_inserter(product.m_dependencies), + [](const AZ::Data::AssetId& productId) -> AssetBuilderSDK::ProductDependency + { + return AssetBuilderSDK::ProductDependency(productId, + AZ::Data::ProductDependencyInfo::CreateFlags(AZ::Data::AssetLoadBehavior::NoLoad)); + }); + } + outputProducts.push_back(AZStd::move(product)); } @@ -248,20 +261,15 @@ namespace AZ::Prefab if (context.HasCompletedSuccessfully()) { AZ_TracePrintf("Prefab Builder", "Finalizing products.\n"); - if (!context.HasPrefabs()) + + if (StoreProducts(tempDirPath, context.GetProcessedObjects(), + context.GetRegisteredProductAssetDependencies(), jobProducts)) { - if (StoreProducts(tempDirPath, context.GetProcessedObjects(), jobProducts)) - { - return true; - } - else - { - AZ_Error("Prefab Builder", false, "One or more objects couldn't be committed to disk."); - } + return true; } else { - AZ_Error("Prefab Builder", false, "After processing there were still Prefabs left."); + AZ_Error("Prefab Builder", false, "One or more objects couldn't be committed to disk."); } } else diff --git a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.h b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.h index 7fbd0b4be0..f78e2cb889 100644 --- a/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.h +++ b/Gems/Prefab/PrefabBuilder/PrefabBuilderComponent.h @@ -69,6 +69,7 @@ namespace AZ::Prefab bool StoreProducts( AZ::IO::PathView tempDirPath, const AzToolsFramework::Prefab::PrefabConversionUtils::PrefabProcessorContext::ProcessedObjectStoreContainer& store, + const AzToolsFramework::Prefab::PrefabConversionUtils::PrefabProcessorContext::ProductAssetDependencyContainer& registeredDependencies, AZStd::vector& outputProducts) const; void ProcessJob(const AssetBuilderSDK::ProcessJobRequest& request, AssetBuilderSDK::ProcessJobResponse& response); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp index ba1d34fea0..d5745cf3cc 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.cpp @@ -19,11 +19,9 @@ #include #include #include -#include #include #include #include -#include #if !defined(_RELEASE) && !defined(PERFORMANCE_BUILD) #define SCRIPT_CANVAS_RUNTIME_ASSET_CHECK @@ -163,8 +161,6 @@ namespace ScriptCanvas ->Field("m_variableOverrides", &RuntimeComponent::m_variableOverrides) ; } - - GraphVariableNetBindingTable::Reflect(context); } void RuntimeComponent::SetVariableOverrides(const VariableData& overrideData) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.h index ef90155e41..81f46d27b9 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Execution/RuntimeComponent.h @@ -15,8 +15,6 @@ #include #include -#include - #include #include #include @@ -41,11 +39,10 @@ namespace ScriptCanvas //! This component should only be used at runtime class RuntimeComponent : public AZ::Component - , public AzFramework::NetBindable , public AZ::EntityBus::Handler { public: - AZ_COMPONENT(RuntimeComponent, "{95BFD916-E832-4956-837D-525DE8384282}", NetBindable); + AZ_COMPONENT(RuntimeComponent, "{95BFD916-E832-4956-837D-525DE8384282}", AZ::Component); static void Reflect(AZ::ReflectContext* context); @@ -67,8 +64,6 @@ namespace ScriptCanvas const VariableData& GetVariableOverrides() const; - void SetNetworkBinding(GridMate::ReplicaChunkPtr) {} - void SetVariableOverrides(const VariableData& overrideData); protected: @@ -103,8 +98,6 @@ namespace ScriptCanvas void StopExecution(); - void UnbindFromNetwork(void) {} - private: AZ::Data::Asset m_runtimeAsset; ExecutionStatePtr m_executionState; diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableMarshal.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableMarshal.cpp deleted file mode 100644 index 8d8db1d876..0000000000 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableMarshal.cpp +++ /dev/null @@ -1,245 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace ScriptCanvas -{ - void DatumMarshaler::SetNetBindingTable(GraphVariableNetBindingTable* netBindingTable) - { - m_graphVariableNetBindingTable = netBindingTable; - } - - void DatumMarshaler::Marshal(GridMate::WriteBuffer& wb, const Datum* const & property) const - { - if (!property) - { - return; - } - - GridMate::Marshaler typeMarshaler; - const Data::eType& datumType = property->GetType().GetType(); - typeMarshaler.Marshal(wb, datumType); - - VariableId assetVariableId; - AZStd::unordered_map>& variableIdMap = m_graphVariableNetBindingTable->GetVariableIdMap(); - - for (AZStd::pair>& pair : variableIdMap) - { - AZStd::pair& variableIndexPair = pair.second; - - if (variableIndexPair.first->GetDatum() == property) - { - assetVariableId = m_graphVariableNetBindingTable->FindAssetVariableIdByRuntimeVariableId(pair.first); - break; - } - } - - if (!assetVariableId.IsValid()) - { - return; - } - - GridMate::Marshaler uuidMarshaler; - uuidMarshaler.Marshal(wb, assetVariableId.GetDatumId()); - - AZStd::string uuidString = assetVariableId.m_id.ToString(); - - switch (datumType) - { - case Data::eType::AABB: - MarshalType(wb, property); - break; - - case Data::eType::Boolean: - MarshalType(wb, property); - break; - - case Data::eType::Color: - MarshalType(wb, property); - break; - - case Data::eType::CRC: - MarshalType(wb, property); - break; - - case Data::eType::EntityID: - MarshalType(wb, property); - break; - - case Data::eType::Matrix3x3: - MarshalType(wb, property); - break; - - case Data::eType::Matrix4x4: - MarshalType(wb, property); - break; - - case Data::eType::NamedEntityID: - MarshalType(wb, property); - break; - - case Data::eType::Number: - MarshalType(wb, property); - break; - - case Data::eType::OBB: - MarshalType(wb, property); - break; - - case Data::eType::Plane: - MarshalType(wb, property); - break; - - case Data::eType::Quaternion: - MarshalType(wb, property); - break; - - case Data::eType::String: - MarshalType(wb, property); - break; - - case Data::eType::Transform: - MarshalType(wb, property); - break; - - case Data::eType::Vector2: - MarshalType(wb, property); - break; - - case Data::eType::Vector3: - MarshalType(wb, property); - break; - - case Data::eType::Vector4: - MarshalType(wb, property); - break; - - default: - AZ_Warning("ScriptCanvasNetworking", false, "Marshal unsupported data type"); - break; - } - } - - bool DatumMarshaler::UnmarshalToPointer(const Datum*& target, GridMate::ReadBuffer& rb) - { - // :SCTODO: for some reason, this UnmarshalToPointer can get called before SetNetworkBinding is called - // (which is where we set m_graphVariableNetBindingTable). So we check for nullptr here just in case. - if (!m_graphVariableNetBindingTable) - { - return false; - } - - ScriptCanvas::Data::eType datumType = Data::eType::Invalid; - GridMate::Marshaler typeMarshaler; - typeMarshaler.Unmarshal(datumType, rb); - - AZ::Uuid uuid; - GridMate::Marshaler uuidMarshaler; - uuidMarshaler.Unmarshal(uuid, rb); - - VariableId runtimeVariableId = m_graphVariableNetBindingTable->FindRuntimeVariableIdByAssetVariableId(VariableId(uuid)); - - if (!runtimeVariableId.IsValid()) - { - return false; - } - - AZStd::string uuidString = runtimeVariableId.m_id.ToString(); - - AZStd::unordered_map>& m_variableIdMap = m_graphVariableNetBindingTable->GetVariableIdMap(); - AZStd::pair& variableIndexPair = m_variableIdMap[runtimeVariableId]; - GraphVariable* graphVariable = variableIndexPair.first; - - switch (datumType) - { - case Data::eType::AABB: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Boolean: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Color: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::CRC: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::EntityID: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Matrix3x3: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Matrix4x4: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::NamedEntityID: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Number: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::OBB: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Plane: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Quaternion: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::String: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Transform: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Vector2: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Vector3: - return UnmarshalType(target, rb, graphVariable); - - case Data::eType::Vector4: - return UnmarshalType(target, rb, graphVariable); - - default: - AZ_Warning("ScriptCanvasNetworking", false, "Unmarshal unsupported data type"); - break; - } - - return false; - } - - void DatumThrottler::SignalDirty() - { - m_isDirty = true; - } - - bool DatumThrottler::WithinThreshold(const Datum* newValue) const - { - return (newValue == nullptr || !m_isDirty); - } - - void DatumThrottler::UpdateBaseline([[maybe_unused]] const Datum* baseline) - { - m_isDirty = false; - } -} diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableMarshal.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableMarshal.h deleted file mode 100644 index 5fd8c3fa0d..0000000000 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableMarshal.h +++ /dev/null @@ -1,86 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include -#include -#include -#include - -namespace ScriptCanvas -{ - class GraphVariableNetBindingTable; - - class DatumMarshaler - { - public: - void SetNetBindingTable(GraphVariableNetBindingTable* netBindingTable); - void Marshal(GridMate::WriteBuffer& wb, const Datum* const & cont) const; - bool UnmarshalToPointer(const Datum*& target, GridMate::ReadBuffer& rb); - - private: - template - void MarshalType(GridMate::WriteBuffer& wb, const Datum* const & property) const - { - GridMate::Marshaler marshaler; - const T* value = property->GetAs(); - marshaler.Marshal(wb, *value); - } - - template - bool UnmarshalType(const Datum*& target, GridMate::ReadBuffer& rb, GraphVariable* graphVariable) - { - bool valueChanged = false; - ModifiableDatumView datumView; - - if (graphVariable) - { - graphVariable->ConfigureDatumView(datumView); - - if (datumView.IsValid()) - { - GridMate::Marshaler marshaler; - T value; - - marshaler.Unmarshal(value, rb); - datumView.SetAs(value); - target = graphVariable->GetDatum(); - valueChanged = true; - } - } - - return valueChanged; - } - - private: - //! The network binding table is needed to determine which Datum to update - //! when unmarshaling data. - // :SCTODO: synced Datums should be tracked via ID - //! and that ID should be used to lookup Datums (right now we can assume - //! which Datum should be updated, since only one Datum is supported). - GraphVariableNetBindingTable* m_graphVariableNetBindingTable = nullptr; - }; - - //! Simple throttler that simple operates via dirty flag. - class DatumThrottler - { - public: - DatumThrottler() = default; - - void SignalDirty(); - bool WithinThreshold(const Datum* newValue) const; - void UpdateBaseline(const Datum* baseline); - - private: - bool m_isDirty = false; - }; -} diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableNetBindings.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableNetBindings.cpp deleted file mode 100644 index e30cb95255..0000000000 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableNetBindings.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include -#include -#include -#include -#include -#include -#include - -namespace ScriptCanvas -{ - const char* DatumDataSet::GetDataSetName() - { - static size_t s_chunkIndex = 0; - static const char* s_nameArray[] = { - "DataSet1","DataSet2","DataSet3","DataSet4","DataSet5", - "DataSet6","DataSet7","DataSet8","DataSet9","DataSet10", - "DataSet11","DataSet12","DataSet13","DataSet14","DataSet15", - "DataSet16","DataSet17","DataSet18","DataSet19","DataSet20", - "DataSet21","DataSet22","DataSet23","DataSet24","DataSet25", - "DataSet26","DataSet27","DataSet28","DataSet29","DataSet30", - "DataSet31","DataSet32" - }; - - if (s_chunkIndex > AZ_ARRAY_SIZE(s_nameArray) && AZ_ARRAY_SIZE(s_nameArray) >= 0) - { - s_chunkIndex = s_chunkIndex % AZ_ARRAY_SIZE(s_nameArray); - } - - return s_nameArray[s_chunkIndex++]; - } - - DatumDataSet::DatumDataSet() - : DatumDataSetType(DatumDataSet::GetDataSetName()) - { - } - - ////////////////////////// - // GraphVariableReplicaChunk - ////////////////////////// - - const char* GraphVariableReplicaChunk::GetChunkName() - { - return "GraphVariableReplicaChunk"; - } - - bool GraphVariableReplicaChunk::IsReplicaMigratable() - { - return true; - } - - ////////////////////////// - // GraphVariableNetBindingTable - ////////////////////////// - - void GraphVariableNetBindingTable::Reflect([[maybe_unused]] AZ::ReflectContext* reflect) - { - GridMate::ReplicaChunkDescriptorTable& descriptorTable = GridMate::ReplicaChunkDescriptorTable::Get(); - AZ::Crc32 hash = GridMate::ReplicaChunkClassId(GraphVariableReplicaChunk::GetChunkName()); - - if (!descriptorTable.FindReplicaChunkDescriptor(hash)) - { - descriptorTable.RegisterChunkType(); - } - } - - GridMate::ReplicaChunkPtr GraphVariableNetBindingTable::GetNetworkBinding() - { - if (!m_replicaChunk) - { - m_replicaChunk = GridMate::CreateReplicaChunk(); - m_replicaChunk->SetHandler(this); - SetGraphNetBindingTable(); - } - - return m_replicaChunk; - } - - void GraphVariableNetBindingTable::SetNetworkBinding(GridMate::ReplicaChunkPtr chunk) - { - m_replicaChunk = chunk; - m_replicaChunk->SetHandler(this); - SetGraphNetBindingTable(); - } - - void GraphVariableNetBindingTable::UnbindFromNetwork() - { - if (m_replicaChunk) - { - m_replicaChunk->SetHandler(nullptr); - m_replicaChunk = nullptr; - } - } - - void GraphVariableNetBindingTable::OnPropertyUpdate([[maybe_unused]] const Datum* const & scriptProperty, [[maybe_unused]] const GridMate::TimeContext& tc) - { - } - - void GraphVariableNetBindingTable::AddDatum(GraphVariable* variable) - { - size_t index = m_variableIdMap.size(); - - m_variableIdMap[variable->GetVariableId()] = AZStd::make_pair(variable, static_cast(index)); - } - - void GraphVariableNetBindingTable::OnDatumChanged(GraphVariable& variable) - { - if (m_replicaChunk && m_replicaChunk->IsMaster()) - { - GraphVariableReplicaChunk* graphVarChunk = static_cast(m_replicaChunk.get()); - auto iter = m_variableIdMap.find(variable.GetVariableId()); - - if (iter == m_variableIdMap.end()) - { - AZ_TracePrintf("ScriptCanvasNetworking", "GraphVariableNetBindingTable::OnDatumChanged: variable not found"); - return; - } - - const AZStd::pair& pair = iter->second; - DatumDataSet& datumDataSet = graphVarChunk->m_properties[pair.second]; - datumDataSet.GetThrottler().SignalDirty(); - datumDataSet.Set(variable.GetDatum()); - } - } - - void GraphVariableNetBindingTable::SetVariableMappings(const AZStd::unordered_map& assetToRuntimeVariableMap, const AZStd::unordered_map& runtimeToAssetVariableMap) - { - m_assetToRuntimeVariableMap = assetToRuntimeVariableMap; - m_runtimeToAssetVariableMap = runtimeToAssetVariableMap; - } - - VariableId GraphVariableNetBindingTable::FindAssetVariableIdByRuntimeVariableId(VariableId runtimeVariableId) - { - auto iter = m_runtimeToAssetVariableMap.find(runtimeVariableId); - - if (iter != m_runtimeToAssetVariableMap.end()) - { - return iter->second; - } - - return VariableId(); - } - - VariableId GraphVariableNetBindingTable::FindRuntimeVariableIdByAssetVariableId(VariableId assetVariableId) - { - auto iter = m_assetToRuntimeVariableMap.find(assetVariableId); - - if (iter != m_assetToRuntimeVariableMap.end()) - { - return iter->second; - } - - return VariableId(); - } - - AZStd::unordered_map>& GraphVariableNetBindingTable::GetVariableIdMap() - { - return m_variableIdMap; - } - - void GraphVariableNetBindingTable::SetGraphNetBindingTable() - { - GraphVariableReplicaChunk* graphVariableChunk = static_cast(m_replicaChunk.get()); - - for (DatumDataSet& dataSet : graphVariableChunk->m_properties) - { - dataSet.GetMarshaler().SetNetBindingTable(this); - } - } -} diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableNetBindings.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableNetBindings.h deleted file mode 100644 index d0f945523d..0000000000 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Variable/GraphVariableNetBindings.h +++ /dev/null @@ -1,101 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include -#include -#include -#include -#include - -namespace ScriptCanvas -{ - class GraphVariable; - class GraphVariableReplicaChunk; - - //! Core functionality for managing replicated Datums in a script canvas and the - //! corresponding GridMate callbacks and data structs (DataSets). - class GraphVariableNetBindingTable - : public GridMate::ReplicaChunkInterface - { - public: - AZ_CLASS_ALLOCATOR(GraphVariableNetBindingTable, AZ::SystemAllocator, 0); - - static void Reflect(AZ::ReflectContext* reflect); - - GraphVariableNetBindingTable() = default; - ~GraphVariableNetBindingTable() = default; - - GridMate::ReplicaChunkPtr GetNetworkBinding(); - void SetNetworkBinding(GridMate::ReplicaChunkPtr chunk); - void UnbindFromNetwork(); - - //! Gets called when the given Datum object is updated with a new value - //! that was received over the network. - void OnPropertyUpdate(const Datum* const & scriptProperty, const GridMate::TimeContext& tc); - - //! Adds the given Datum to the list of "synced datums" for this instance. - void AddDatum(GraphVariable* variable); - - //! Called when local data changes for a Datum whose values should be replicated - //! over the network. - void OnDatumChanged(GraphVariable& variable); - - void SetVariableMappings(const AZStd::unordered_map& assetToRuntimeVariableMap, const AZStd::unordered_map& runtimeToAssetVariableMap); - VariableId FindAssetVariableIdByRuntimeVariableId(VariableId runtimeVariableId); - VariableId FindRuntimeVariableIdByAssetVariableId(VariableId assetVariableId); - AZStd::unordered_map>& GetVariableIdMap(); - - private: - void SetGraphNetBindingTable(); - - private: - AZStd::unordered_map m_assetToRuntimeVariableMap; - AZStd::unordered_map m_runtimeToAssetVariableMap; - - //! Replica chunk used for GridMate networking binding. See GraphVariableReplicaChunk. - GridMate::ReplicaChunkPtr m_replicaChunk; - - //! Contains pointers to all replicated variables contained within the runtime component - //! of the canvas this net binding is associated with. - AZStd::unordered_map> m_variableIdMap; - }; - - typedef GridMate::DataSet::BindInterface DatumDataSetType; - - class DatumDataSet - : public DatumDataSetType - { - public: - DatumDataSet(); - ~DatumDataSet() = default; - - private: - const char* GetDataSetName(); - }; - - class GraphVariableReplicaChunk - : public GridMate::ReplicaChunkBase - { - public: - AZ_CLASS_ALLOCATOR(GraphVariableReplicaChunk, AZ::SystemAllocator, 0); - - static const char* GetChunkName(); - - GraphVariableReplicaChunk() = default; - ~GraphVariableReplicaChunk() = default; - - bool IsReplicaMigratable() override; - - DatumDataSet m_properties[GM_MAX_DATASETS_IN_CHUNK]; - }; -} diff --git a/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake b/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake index 871d8d4c5d..84391021df 100644 --- a/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake +++ b/Gems/ScriptCanvas/Code/scriptcanvasgem_common_files.cmake @@ -597,10 +597,6 @@ set(FILES Include/ScriptCanvas/Variable/GraphVariable.cpp Include/ScriptCanvas/Variable/GraphVariableManagerComponent.h Include/ScriptCanvas/Variable/GraphVariableManagerComponent.cpp - Include/ScriptCanvas/Variable/GraphVariableNetBindings.h - Include/ScriptCanvas/Variable/GraphVariableNetBindings.cpp - Include/ScriptCanvas/Variable/GraphVariableMarshal.h - Include/ScriptCanvas/Variable/GraphVariableMarshal.cpp Include/ScriptCanvas/Variable/VariableCore.h Include/ScriptCanvas/Variable/VariableCore.cpp Include/ScriptCanvas/Variable/VariableData.h diff --git a/Registry/gem_autoload.serializecontexttools.setreg b/Registry/gem_autoload.serializecontexttools.setreg new file mode 100644 index 0000000000..1f4a8931c5 --- /dev/null +++ b/Registry/gem_autoload.serializecontexttools.setreg @@ -0,0 +1,15 @@ +{ + "Amazon": { + "Gems": { + "QtForPython.Editor": { + "AutoLoad": false + }, + "EditorPythonBindings.Editor": { + "AutoLoad": false + }, + "PythonAssetBuilder.Editor": { + "AutoLoad": false + } + } + } +} diff --git a/cmake/3rdParty/FindWwise.cmake b/cmake/3rdParty/FindWwise.cmake index 27b78695f2..9b46c24d75 100644 --- a/cmake/3rdParty/FindWwise.cmake +++ b/cmake/3rdParty/FindWwise.cmake @@ -9,6 +9,59 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# The current supported version of Wwise +set(WWISE_VERSION 2021.1.1.7601) + +# Wwise Install Path +# Initialize to the default 3rdParty path +set(LY_WWISE_INSTALL_PATH "" CACHE PATH "Path to Wwise version ${WWISE_VERSION} installation.") + +function(is_valid_sdk sdk_path is_valid) + set(${is_valid} FALSE PARENT_SCOPE) + if(EXISTS ${sdk_path}) + set(sdk_version_file ${sdk_path}/SDK/include/AK/AkWwiseSDKVersion.h) + if(EXISTS ${sdk_version_file}) + string(FIND ${sdk_path} ${WWISE_VERSION} index) + if(NOT index EQUAL -1) + set(${is_valid} TRUE PARENT_SCOPE) + else() + # The install path doesn't contain the WWISE_VERSION string. + # The path could still be correct, but it would require parsing the AkWwiseSDKVersion.h to verify. + endif() + endif() + endif() +endfunction() + +# Paths that will be checked, in order: +# - CMake cache variable +# - WWISEROOT Environment Variable +# - Standard 3rdParty path +set(WWISE_SDK_PATHS + "${LY_WWISE_INSTALL_PATH}" + "$ENV{WWISEROOT}" + "${LY_3RDPARTY_PATH}/Wwise/${WWISE_VERSION}" +) + +set(found_sdk FALSE) +foreach(test_path ${WWISE_SDK_PATHS}) + is_valid_sdk(${test_path} found_sdk) + if(found_sdk) + # Update the Wwise Install Path cache variable + set(LY_WWISE_INSTALL_PATH "${test_path}" CACHE PATH "Path to Wwise version ${WWISE_VERSION} installation." FORCE) + break() + endif() +endforeach() + +if(NOT found_sdk) + # If we don't find a path that appears to be a valid Wwise install, we can bail here. + # No 3rdParty::Wwise target will exist, so that can be checked elsewhere. + message(STATUS "Wwise SDK version ${WWISE_VERSION} was not found.") + return() +else() + message(STATUS "Using Wwise SDK at ${LY_WWISE_INSTALL_PATH}") +endif() + + set(WWISE_COMMON_LIB_NAMES # Core AK AkMemoryMgr @@ -55,44 +108,26 @@ set(WWISE_NON_RELEASE_LIB_NAMES CommunicationCentral ) -# Additional Libraries -# These can be added/enabled to the linker depending on what your Wwise project uses. -# In addition to uncommenting the libraries here, be sure to add the appropriate plugin factory -# header includes to PluginRegistration_wwise.h. - set(WWISE_ADDITIONAL_LIB_NAMES -# Common - #AkConvolutionReverbFX - #AkReflectFX - #AkRouterMixerFX - #ResonanceAudioFX - #MasteringSuiteFX - #AkSoundSeedImpactFX - #AkSoundSeedGrainSource - #AkSoundSeedWindSource - #AkSoundSeedWooshSource - #AuroHeadphoneFX - #CrankcaseAudioREVModelPlayerSource - #McDSPFutzBoxFX - #McDSPLimiterFX - -# iZotope - #iZHybridReverbFX - #iZTrashBoxModelerFX - #iZTrashDelayFX - #iZTrashDistortionFX - #iZTrashDynamicsFX - #iZTrashFiltersFX - #iZTrashMultibandDistortionFX + # Additional Libraries ) set(WWISE_COMPILE_DEFINITIONS $,AK_OPTIMIZED,> ) + +# The default install path might look different than the standard 3rdParty format (${LY_3RDPARTY_PATH}//). +# Use these to get the parent path and folder name before adding the external 3p target. +get_filename_component(WWISE_3P_ROOT ${LY_WWISE_INSTALL_PATH} DIRECTORY) +get_filename_component(WWISE_FOLDER ${LY_WWISE_INSTALL_PATH} NAME) + ly_add_external_target( NAME Wwise - VERSION 2019.2.8.7432 + VERSION "${WWISE_FOLDER}" + 3RDPARTY_ROOT_DIRECTORY "${WWISE_3P_ROOT}" INCLUDE_DIRECTORIES SDK/include COMPILE_DEFINITIONS ${WWISE_COMPILE_DEFINITIONS} ) + +set(Wwise_FOUND TRUE) diff --git a/cmake/3rdParty/Platform/Android/Wwise_android.cmake b/cmake/3rdParty/Platform/Android/Wwise_android.cmake index 5d7713511b..d204688489 100644 --- a/cmake/3rdParty/Platform/Android/Wwise_android.cmake +++ b/cmake/3rdParty/Platform/Android/Wwise_android.cmake @@ -10,9 +10,6 @@ # set(WWISE_ANDROID_LIB_NAMES - AkMotionGeneratorSource - AkMotionSink - AkMotionSourceSource zip ) diff --git a/cmake/3rdParty/Platform/Windows/Wwise_windows.cmake b/cmake/3rdParty/Platform/Windows/Wwise_windows.cmake index 37141f7e6d..09b9478ac0 100644 --- a/cmake/3rdParty/Platform/Windows/Wwise_windows.cmake +++ b/cmake/3rdParty/Platform/Windows/Wwise_windows.cmake @@ -10,16 +10,11 @@ # set(WWISE_WINDOWS_LIB_NAMES - ASIOSourceSink AkAutobahn - AkMotionGeneratorSource - AkMotionSink - AkMotionSourceSource - MSSpatialSink SFLib ) -set(WWISE_VS_VER "vc150") # use the version of Wwise built with MSVC2017, or toolset 141 +set(WWISE_VS_VER "vc160") set(WWISE_LIB_PATH ${BASE_PATH}/SDK/x64_${WWISE_VS_VER}/$,Debug,$,Profile,Release>>/lib) diff --git a/scripts/build/build_node/Platform/Windows/install_android.ps1 b/scripts/build/build_node/Platform/Windows/install_android.ps1 index 30e651cc3a..2fde5fcb8c 100644 --- a/scripts/build/build_node/Platform/Windows/install_android.ps1 +++ b/scripts/build/build_node/Platform/Windows/install_android.ps1 @@ -28,8 +28,8 @@ Start-Process -FilePath $sdkmanager -ArgumentList $build_tools -NoNewWindow -Wai Write-Host "Installing Gradle and Ninja" Import-Module C:\ProgramData\chocolatey\helpers\chocolateyInstaller.psm1 #Grade needs a custom installer due to being hardcoded to C:\Programdata in Chocolatey $packageName = 'gradle' -$version = '5.6.4' -$checksum = 'ABC10BCEDB58806E8654210F96031DB541BCD2D6FC3161E81CB0572D6A15E821' +$version = '7.0' +$checksum = '81003F83B0056D20EEDF48CDDD4F52A9813163D4BA185BCF8ABD34B8EEEA4CBD' $url = "https://services.gradle.org/distributions/gradle-$version-all.zip" $installDir = "C:\Gradle" @@ -38,6 +38,6 @@ Install-ChocolateyZipPackage $packageName $url $installDir -Checksum $checksum - $gradle_home = Join-Path $installDir "$packageName-$version" $gradle_bat = Join-Path $gradle_home 'bin/gradle.bat' -Install-ChocolateyEnvironmentVariable "GRADLE_HOME" $gradle_home 'Machine' +Install-ChocolateyEnvironmentVariable "GRADLE_BUILD_HOME" $gradle_home 'Machine' choco install -y ninja --version=1.10.0 --package-parameters="/installDir:C:\Ninja" \ No newline at end of file diff --git a/scripts/build/tools/alert_build_failures.py b/scripts/build/tools/alert_build_failures.py deleted file mode 100755 index 486d84123d..0000000000 --- a/scripts/build/tools/alert_build_failures.py +++ /dev/null @@ -1,76 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -import os -from incremental_build_util import get_iam_role_credentials -try: - import requests -except ImportError: - import pip - pip.main(['install', 'requests', '--ignore-installed', '-q']) - import requests -try: - from requests_aws4auth import AWS4Auth -except ImportError: - import pip - pip.main(['install', 'requests_aws4auth', '--ignore-installed', '-q']) - from requests_aws4auth import AWS4Auth - -IAM_ROLE_NAME = 'ec2-jenkins-node' -TEAM = 'lumberyard-build' -CHIME_ROOM_WEB_HOOK = "https://hooks.chime.aws/incomingwebhooks/2a6018c9-3bf5-4e03-851c-32ba82c7c4e2?token=YWhTVXZsWVJ8MXxaLTg5RkVZNlA5Q1NiMVdfQndGeS1TSHNnYW5VREVha3pjX1pUUEd5b1JF" - - -def find_curr_oncalls_for_team(team): - host = "who-is-oncall-pdx.corp.amazon.com" - service_name = "who-is-oncall" - aws_region = "us-west-2" - headers = {"content-type": "application/json", "host": host} - - credentials = get_iam_role_credentials(IAM_ROLE_NAME) - try: - aws_access_key_id = credentials['AccessKeyId'] - aws_secret_access_key = credentials['SecretAccessKey'] - aws_session_token = credentials['Token'] - except Exception as e: - print(f'ERROR: Cannot get AWS credentials.\n{e}') - return ['All'] - - auth = AWS4Auth(aws_access_key_id, aws_secret_access_key, aws_region, service_name, session_token=aws_session_token) - r = requests.get(f"https://who-is-oncall-pdx.corp.amazon.com/teams/{team}", headers=headers, auth=auth, verify=False) - if r.ok: - res = r.json() - try: - return res['currOncalls'] - except KeyError: - return ['All'] - return ['All'] - - -def send_alert_to_chime_room(web_hook, content): - data = '{"Content":"' + content + '"}' - headers = {'Content-Type': 'application/json'} - requests.post(web_hook, headers=headers, data=data) - - -def create_content(): - content = '' - oncalls = find_curr_oncalls_for_team(TEAM) - for oncall in oncalls: - content += f'@{oncall} ' - job_name = os.environ['JOB_NAME'] - build_url = os.environ['BUILD_URL'] - content += fr'\nJob {job_name} failed\nBuild URL: {build_url}\n' - return content - - -send_alert_to_chime_room(CHIME_ROOM_WEB_HOOK, create_content()) - diff --git a/scripts/build/tools/email_to_lionbridge.py b/scripts/build/tools/email_to_lionbridge.py deleted file mode 100755 index 7f522bb564..0000000000 --- a/scripts/build/tools/email_to_lionbridge.py +++ /dev/null @@ -1,128 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -""" -This script will be used in the Sandobx Jenkins job PACKAGE_COPY_S3 -PACKAGE_COPY_S3 is a downstream job of nightly packaging job, it copies the nightly packages from Infra S3 bucket to Lionbridge S3 bucket based on the INCLUDE_FILTER passed from packaging job -""" -import os -import re -import json -import requests -from requests.auth import HTTPBasicAuth -import boto3 -from util import error, warn - - -# Write EMAIL_TEMPLATE to a file and inject it into the email sent to Lionbridge -EMAIL_TEMPLATE = '''Packages are uploaded to S3 bucket {} -Package List: -{} - - -Changelists: -{} -''' - - -def get_jenkins_env(key): - try: - return os.environ[key] - except KeyError: - print('Error: Jenkins parameters {} is not set.'.format(key)) - return None - - -JENKINS_USERNAME = get_jenkins_env('JENKINS_USERNAME') -JENKINS_API_TOKEN = get_jenkins_env('JENKINS_API_TOKEN') -JENKINS_URL = get_jenkins_env('JENKINS_URL') -WORKSPACE = get_jenkins_env('WORKSPACE') -S3_TARGET = get_jenkins_env('S3_TARGET') -INCLUDE_FILTER = get_jenkins_env('INCLUDE_FILTER') -EMAIL_TEMPLATE_FILE = get_jenkins_env('EMAIL_TEMPLATE_FILE') -if None in [JENKINS_USERNAME, JENKINS_API_TOKEN, JENKINS_URL, WORKSPACE, S3_TARGET, INCLUDE_FILTER, EMAIL_TEMPLATE_FILE]: - error('Please make sure all Jenkins parameters are set correctly.') - - -def parse_include_filter(include_filter): - try: - res = re.search('^(\w*)-*lumberyard-(\d+)\.(\d+)-(\d+)-(\w+).*\*(\d+)\.\*', include_filter) - branch = res.group(1) - major_version = int(res.group(2)) - minor_version = int(res.group(3)) - changelist_number = res.group(4) - platform = res.group(5) - build_number = res.group(6) - return branch, major_version, minor_version, changelist_number, platform, build_number - except (AttributeError, IndexError): - error('Unable to parse INCLUDE_FILTER, please make sure the INCLUDE_FILTER is set correctly') - - -# Get the changelists that trigger the build -def get_changelists(job_name, build_number): - changelists = [] - headers = {'Content-type': 'application/json', 'Accept': 'application/json'} - try: - res = requests.get('{}/job/{}/{}/api/json'.format(JENKINS_URL, job_name, build_number), - auth=HTTPBasicAuth(JENKINS_USERNAME, JENKINS_API_TOKEN), headers=headers, verify=False) - res = json.loads(res.content) - changelists = res.get('changeSet').get('items') - return changelists - except: - warn('Error: Failed to get changes from build {} in job {}'.format(build_number, job_name)) - return [] - - -def get_packaging_job_name(branch, major_version, minor_version, platform): - if branch == '': - branch = 'ML' if major_version + minor_version == 0 else 'v{}_{}'.format(major_version, minor_version) - job_name = 'PKG_{}_{}'.format(branch, platform.capitalize()) - return job_name - - -# Get package names by looking up S3 bucket -def get_package_names(branch, major_version, minor_version, include_filter, build_number): - package_names = [] - prefix = include_filter[:include_filter.find('*')] - pattern = '.*{}.*{}..*'.format(prefix, build_number) - if branch == '': - bucket_name = 'ly-packages-mainline' if major_version + minor_version == 0 else 'ly-packages-release-candidate' - folder = 'lumberyard-packages' - else: - bucket_name = 'ly-packages-feature-branches' - folder = 'lumberyard-packages/{}'.format(branch) - s3 = boto3.resource('s3') - bucket = s3.Bucket(bucket_name) - for obj in bucket.objects.filter(Prefix='{}/{}'.format(folder, prefix)): - package_name = obj.key - if re.match(pattern, package_name): - package_names.append(package_name.replace('{}/'.format(folder), '')) - return package_names - - -if __name__ == "__main__": - branch, major_version, minor_version, changelist_number, platform, build_number = parse_include_filter(INCLUDE_FILTER) - packaging_job_name = get_packaging_job_name(branch, major_version, minor_version, platform) - changelists = get_changelists(packaging_job_name, build_number) - package_names = get_package_names(branch, major_version, minor_version, INCLUDE_FILTER, build_number) - with open(os.path.join(WORKSPACE, EMAIL_TEMPLATE_FILE), 'w+') as output: - if len(package_names) > 0: - package_list_str = '\n'.join(package_names) - changelists_str = '' - for item in changelists: - changelists_str += '---------------------------------------------------------------------------------------------\n' - try: - changelists_str += 'CL{} by {} on {}\n{}\n'.format(item['changeNumber'], item['author']['fullName'], item['changeTime'], item['msg'].encode('utf-8', 'ignore')) - except KeyError: - error('Internal error, check the output of Jenkins API.') - output.write(EMAIL_TEMPLATE.format(S3_TARGET, package_list_str, changelists_str)) - -