diff --git a/.lfsconfig b/.lfsconfig index e51eb5e7c4..546f34ff1c 100644 --- a/.lfsconfig +++ b/.lfsconfig @@ -2,10 +2,14 @@ # Default LFS endpoint for this repository url=https://d3df09qsjufr6g.cloudfront.net/api/v1 -# To use the endpoint with your fork: -# 1. uncomment the url line below by removing the '#' -# 2. replace 'owner' with the username or organization that owns the fork -# 3. have git ignore your local modification of this file by running -# git update-index --skip-worktree .lfsconfig - -# url=https://d3df09qsjufr6g.cloudfront.net/api/v1/fork/owner +# To use the endpoint with your fork, run the following git command +# in your local repository (without the '#'), replacing 'owner' with +# the username or organization that owns the fork. +# +# git config lfs.url "https://d3df09qsjufr6g.cloudfront.net/api/v1/fork/owner" +# +# For example, if your fork is https://github.com/octocat/o3de use +# git config lfs.url "https://d3df09qsjufr6g.cloudfront.net/api/v1/fork/octocat" +# +# IMPORTANT: authenticate with your GitHub username and personal access token +# not your GitHub password diff --git a/Assets/Editor/LambdaFunctions/LwALambdaFunction.js b/Assets/Editor/LambdaFunctions/LwALambdaFunction.js index c57eb13253..562a7573a6 100644 --- a/Assets/Editor/LambdaFunctions/LwALambdaFunction.js +++ b/Assets/Editor/LambdaFunctions/LwALambdaFunction.js @@ -1,5 +1,5 @@ /* - * Copyright (c) Contributors to the Open 3D Engine Project + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * diff --git a/Assets/Editor/LambdaFunctions/LwFacebookLambdaFunction.js b/Assets/Editor/LambdaFunctions/LwFacebookLambdaFunction.js index 5235829e08..81e47bfb15 100644 --- a/Assets/Editor/LambdaFunctions/LwFacebookLambdaFunction.js +++ b/Assets/Editor/LambdaFunctions/LwFacebookLambdaFunction.js @@ -1,5 +1,5 @@ /* - * Copyright (c) Contributors to the Open 3D Engine Project + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * diff --git a/Assets/Editor/LambdaFunctions/LwGenericOpenIdConnectLambdaFunction.js b/Assets/Editor/LambdaFunctions/LwGenericOpenIdConnectLambdaFunction.js index 5b0d503e18..636b3a6b85 100644 --- a/Assets/Editor/LambdaFunctions/LwGenericOpenIdConnectLambdaFunction.js +++ b/Assets/Editor/LambdaFunctions/LwGenericOpenIdConnectLambdaFunction.js @@ -1,5 +1,5 @@ /* - * Copyright (c) Contributors to the Open 3D Engine Project + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * diff --git a/Assets/Editor/LambdaFunctions/LwGoogleLambdaFunction.js b/Assets/Editor/LambdaFunctions/LwGoogleLambdaFunction.js index 106b4b7208..2df17a9ac4 100644 --- a/Assets/Editor/LambdaFunctions/LwGoogleLambdaFunction.js +++ b/Assets/Editor/LambdaFunctions/LwGoogleLambdaFunction.js @@ -1,5 +1,5 @@ /* - * Copyright (c) Contributors to the Open 3D Engine Project + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * diff --git a/Assets/Editor/MissionTemplate.lua b/Assets/Editor/MissionTemplate.lua index 287d2ffb28..bdff5191ae 100644 --- a/Assets/Editor/MissionTemplate.lua +++ b/Assets/Editor/MissionTemplate.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Editor/Scripts/TrackView/example.py b/Assets/Editor/Scripts/TrackView/example.py index b8e13e4641..f60cfcc038 100755 --- a/Assets/Editor/Scripts/TrackView/example.py +++ b/Assets/Editor/Scripts/TrackView/example.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/Assets/Editor/Scripts/editor_script_validation.py b/Assets/Editor/Scripts/editor_script_validation.py index bb4ec0053e..d132484558 100755 --- a/Assets/Editor/Scripts/editor_script_validation.py +++ b/Assets/Editor/Scripts/editor_script_validation.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/Assets/Editor/Scripts/export_all_project_levels.py b/Assets/Editor/Scripts/export_all_project_levels.py index ab0789fe23..0f52d9250a 100755 --- a/Assets/Editor/Scripts/export_all_project_levels.py +++ b/Assets/Editor/Scripts/export_all_project_levels.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/Assets/Editor/Scripts/generatelod.py b/Assets/Editor/Scripts/generatelod.py index da9d0ffa81..32fd0a7b22 100755 --- a/Assets/Editor/Scripts/generatelod.py +++ b/Assets/Editor/Scripts/generatelod.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/Assets/Editor/Scripts/rename_cgf.py b/Assets/Editor/Scripts/rename_cgf.py index dff4d6c5cb..47d92bb61d 100755 --- a/Assets/Editor/Scripts/rename_cgf.py +++ b/Assets/Editor/Scripts/rename_cgf.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/Assets/Editor/Scripts/select_story_anim_objects.py b/Assets/Editor/Scripts/select_story_anim_objects.py index 4717799381..62ad25a0ea 100755 --- a/Assets/Editor/Scripts/select_story_anim_objects.py +++ b/Assets/Editor/Scripts/select_story_anim_objects.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/Assets/Editor/Scripts/tools_shelf_actions.py b/Assets/Editor/Scripts/tools_shelf_actions.py index a9ba4d56da..670082fa02 100755 --- a/Assets/Editor/Scripts/tools_shelf_actions.py +++ b/Assets/Editor/Scripts/tools_shelf_actions.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/Assets/Editor/UI/removeTranslationFiles.py b/Assets/Editor/UI/removeTranslationFiles.py index 245e5e0042..8f18587a70 100755 --- a/Assets/Editor/UI/removeTranslationFiles.py +++ b/Assets/Editor/UI/removeTranslationFiles.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/Assets/Editor/UI/updateTranslatableText.py b/Assets/Editor/UI/updateTranslatableText.py index 374dd08889..b256e74e37 100755 --- a/Assets/Editor/UI/updateTranslatableText.py +++ b/Assets/Editor/UI/updateTranslatableText.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/Assets/Engine/Libs/MaterialEffects/materialeffects.xml b/Assets/Engine/Libs/MaterialEffects/materialeffects.xml index 04977c9e80..a7f1c43958 100644 --- a/Assets/Engine/Libs/MaterialEffects/materialeffects.xml +++ b/Assets/Engine/Libs/MaterialEffects/materialeffects.xml @@ -11,7 +11,7 @@ 2006-02-22T12:05:03Z 2005-10-12T15:13:39Z 2014-04-08T17:21:06Z - Crytek + Contributors to the Open 3D Engine Project 12.00 diff --git a/Assets/Engine/Scripts/EngineCommon.lua b/Assets/Engine/Scripts/EngineCommon.lua index 388ccdb139..32c54393a4 100644 --- a/Assets/Engine/Scripts/EngineCommon.lua +++ b/Assets/Engine/Scripts/EngineCommon.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/AI/NavigationSeedPoint.lua b/Assets/Engine/Scripts/Entities/AI/NavigationSeedPoint.lua index 634721ec82..a60b6d388f 100644 --- a/Assets/Engine/Scripts/Entities/AI/NavigationSeedPoint.lua +++ b/Assets/Engine/Scripts/Entities/AI/NavigationSeedPoint.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/AI/SmartObject.lua b/Assets/Engine/Scripts/Entities/AI/SmartObject.lua index f4233f154a..effd3ac23b 100644 --- a/Assets/Engine/Scripts/Entities/AI/SmartObject.lua +++ b/Assets/Engine/Scripts/Entities/AI/SmartObject.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/AI/TagPoint.lua b/Assets/Engine/Scripts/Entities/AI/TagPoint.lua index 37fe7b6ea9..0307463d24 100644 --- a/Assets/Engine/Scripts/Entities/AI/TagPoint.lua +++ b/Assets/Engine/Scripts/Entities/AI/TagPoint.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Actor/CActorWrapper.lua b/Assets/Engine/Scripts/Entities/Actor/CActorWrapper.lua index 27091bab64..2b6797435e 100644 --- a/Assets/Engine/Scripts/Entities/Actor/CActorWrapper.lua +++ b/Assets/Engine/Scripts/Entities/Actor/CActorWrapper.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Anim/MannequinObject.lua b/Assets/Engine/Scripts/Entities/Anim/MannequinObject.lua index 947d0553ee..b3c7838e12 100644 --- a/Assets/Engine/Scripts/Entities/Anim/MannequinObject.lua +++ b/Assets/Engine/Scripts/Entities/Anim/MannequinObject.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Default/GeomEntity.lua b/Assets/Engine/Scripts/Entities/Default/GeomEntity.lua index dfaef2bc14..a58af759b3 100644 --- a/Assets/Engine/Scripts/Entities/Default/GeomEntity.lua +++ b/Assets/Engine/Scripts/Entities/Default/GeomEntity.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Default/RopeEntity.lua b/Assets/Engine/Scripts/Entities/Default/RopeEntity.lua index 12d83a2262..559538156f 100644 --- a/Assets/Engine/Scripts/Entities/Default/RopeEntity.lua +++ b/Assets/Engine/Scripts/Entities/Default/RopeEntity.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Environment/WaterVolume.lua b/Assets/Engine/Scripts/Entities/Environment/WaterVolume.lua index 11b3d35c3e..2fd2836f9d 100644 --- a/Assets/Engine/Scripts/Entities/Environment/WaterVolume.lua +++ b/Assets/Engine/Scripts/Entities/Environment/WaterVolume.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Lights/EnvironmentLight.lua b/Assets/Engine/Scripts/Entities/Lights/EnvironmentLight.lua index 6d24ba1c05..9183d19e43 100644 --- a/Assets/Engine/Scripts/Entities/Lights/EnvironmentLight.lua +++ b/Assets/Engine/Scripts/Entities/Lights/EnvironmentLight.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Lights/Light.lua b/Assets/Engine/Scripts/Entities/Lights/Light.lua index 401880429c..daf323f9e8 100644 --- a/Assets/Engine/Scripts/Entities/Lights/Light.lua +++ b/Assets/Engine/Scripts/Entities/Lights/Light.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Others/CameraSource.lua b/Assets/Engine/Scripts/Entities/Others/CameraSource.lua index b17be8c446..01ac7a8989 100644 --- a/Assets/Engine/Scripts/Entities/Others/CameraSource.lua +++ b/Assets/Engine/Scripts/Entities/Others/CameraSource.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Others/CameraTarget.lua b/Assets/Engine/Scripts/Entities/Others/CameraTarget.lua index 913bc23d38..59ce9c82cb 100644 --- a/Assets/Engine/Scripts/Entities/Others/CameraTarget.lua +++ b/Assets/Engine/Scripts/Entities/Others/CameraTarget.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Others/Comment.lua b/Assets/Engine/Scripts/Entities/Others/Comment.lua index bb4978eedb..68c26b0571 100644 --- a/Assets/Engine/Scripts/Entities/Others/Comment.lua +++ b/Assets/Engine/Scripts/Entities/Others/Comment.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Others/ProceduralObject.lua b/Assets/Engine/Scripts/Entities/Others/ProceduralObject.lua index 5d2b946aad..baab0c0da9 100644 --- a/Assets/Engine/Scripts/Entities/Others/ProceduralObject.lua +++ b/Assets/Engine/Scripts/Entities/Others/ProceduralObject.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Others/RigidBody.lua b/Assets/Engine/Scripts/Entities/Others/RigidBody.lua index 451fe8e413..8651bed6a4 100644 --- a/Assets/Engine/Scripts/Entities/Others/RigidBody.lua +++ b/Assets/Engine/Scripts/Entities/Others/RigidBody.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Particle/ParticleEffect.lua b/Assets/Engine/Scripts/Entities/Particle/ParticleEffect.lua index 985ec72856..1a23ae2c5d 100644 --- a/Assets/Engine/Scripts/Entities/Particle/ParticleEffect.lua +++ b/Assets/Engine/Scripts/Entities/Particle/ParticleEffect.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Physics/AnimObject.lua b/Assets/Engine/Scripts/Entities/Physics/AnimObject.lua index 0e098353b8..c1786e6ec9 100644 --- a/Assets/Engine/Scripts/Entities/Physics/AnimObject.lua +++ b/Assets/Engine/Scripts/Entities/Physics/AnimObject.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Physics/AreaBezierVolume.lua b/Assets/Engine/Scripts/Entities/Physics/AreaBezierVolume.lua index a53e70e86e..7f9494577f 100644 --- a/Assets/Engine/Scripts/Entities/Physics/AreaBezierVolume.lua +++ b/Assets/Engine/Scripts/Entities/Physics/AreaBezierVolume.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Physics/BasicEntity.lua b/Assets/Engine/Scripts/Entities/Physics/BasicEntity.lua index 5516c081ca..7502473d72 100644 --- a/Assets/Engine/Scripts/Entities/Physics/BasicEntity.lua +++ b/Assets/Engine/Scripts/Entities/Physics/BasicEntity.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Physics/LivingEntity.lua b/Assets/Engine/Scripts/Entities/Physics/LivingEntity.lua index d47f671b5e..aedd41d71b 100644 --- a/Assets/Engine/Scripts/Entities/Physics/LivingEntity.lua +++ b/Assets/Engine/Scripts/Entities/Physics/LivingEntity.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Physics/RigidBodyEx.lua b/Assets/Engine/Scripts/Entities/Physics/RigidBodyEx.lua index 9484b9fb40..a48ef8fa87 100644 --- a/Assets/Engine/Scripts/Entities/Physics/RigidBodyEx.lua +++ b/Assets/Engine/Scripts/Entities/Physics/RigidBodyEx.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Render/FogVolume.lua b/Assets/Engine/Scripts/Entities/Render/FogVolume.lua index 0a2d1332a1..085f302e88 100644 --- a/Assets/Engine/Scripts/Entities/Render/FogVolume.lua +++ b/Assets/Engine/Scripts/Entities/Render/FogVolume.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Render/GeomCache.lua b/Assets/Engine/Scripts/Entities/Render/GeomCache.lua index 601372bb64..048d04e89c 100644 --- a/Assets/Engine/Scripts/Entities/Render/GeomCache.lua +++ b/Assets/Engine/Scripts/Entities/Render/GeomCache.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Sound/AudioAreaAmbience.lua b/Assets/Engine/Scripts/Entities/Sound/AudioAreaAmbience.lua index 4eef0e0be0..5981c3d301 100644 --- a/Assets/Engine/Scripts/Entities/Sound/AudioAreaAmbience.lua +++ b/Assets/Engine/Scripts/Entities/Sound/AudioAreaAmbience.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Sound/AudioAreaEntity.lua b/Assets/Engine/Scripts/Entities/Sound/AudioAreaEntity.lua index 477128ccb5..958b8e55ea 100644 --- a/Assets/Engine/Scripts/Entities/Sound/AudioAreaEntity.lua +++ b/Assets/Engine/Scripts/Entities/Sound/AudioAreaEntity.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Sound/AudioAreaRandom.lua b/Assets/Engine/Scripts/Entities/Sound/AudioAreaRandom.lua index 75d4a301b4..a44a88870c 100644 --- a/Assets/Engine/Scripts/Entities/Sound/AudioAreaRandom.lua +++ b/Assets/Engine/Scripts/Entities/Sound/AudioAreaRandom.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Sound/AudioTriggerSpot.lua b/Assets/Engine/Scripts/Entities/Sound/AudioTriggerSpot.lua index 6dae66dd7c..f3f2f49577 100644 --- a/Assets/Engine/Scripts/Entities/Sound/AudioTriggerSpot.lua +++ b/Assets/Engine/Scripts/Entities/Sound/AudioTriggerSpot.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Sound/Shared/AudioUtils.lua b/Assets/Engine/Scripts/Entities/Sound/Shared/AudioUtils.lua index b75a0f5125..4a97342d2e 100644 --- a/Assets/Engine/Scripts/Entities/Sound/Shared/AudioUtils.lua +++ b/Assets/Engine/Scripts/Entities/Sound/Shared/AudioUtils.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Triggers/AreaTrigger.lua b/Assets/Engine/Scripts/Entities/Triggers/AreaTrigger.lua index 89c0a3e73f..0c21d6c187 100644 --- a/Assets/Engine/Scripts/Entities/Triggers/AreaTrigger.lua +++ b/Assets/Engine/Scripts/Entities/Triggers/AreaTrigger.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/Triggers/ProximityTrigger.lua b/Assets/Engine/Scripts/Entities/Triggers/ProximityTrigger.lua index cfa2cc1781..ec8e47388e 100644 --- a/Assets/Engine/Scripts/Entities/Triggers/ProximityTrigger.lua +++ b/Assets/Engine/Scripts/Entities/Triggers/ProximityTrigger.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Entities/UI/UiCanvasRefEntity.lua b/Assets/Engine/Scripts/Entities/UI/UiCanvasRefEntity.lua index d3702905fc..26724b8251 100644 --- a/Assets/Engine/Scripts/Entities/UI/UiCanvasRefEntity.lua +++ b/Assets/Engine/Scripts/Entities/UI/UiCanvasRefEntity.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Utils/Components/GameplayUtils.lua b/Assets/Engine/Scripts/Utils/Components/GameplayUtils.lua index 33b9b1430a..62f606a413 100644 --- a/Assets/Engine/Scripts/Utils/Components/GameplayUtils.lua +++ b/Assets/Engine/Scripts/Utils/Components/GameplayUtils.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Utils/Components/InputUtils.lua b/Assets/Engine/Scripts/Utils/Components/InputUtils.lua index 2569befbf9..980bbda952 100644 --- a/Assets/Engine/Scripts/Utils/Components/InputUtils.lua +++ b/Assets/Engine/Scripts/Utils/Components/InputUtils.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Utils/Components/MultiHandlers.lua b/Assets/Engine/Scripts/Utils/Components/MultiHandlers.lua index 0db1ec9ab9..56596df39d 100644 --- a/Assets/Engine/Scripts/Utils/Components/MultiHandlers.lua +++ b/Assets/Engine/Scripts/Utils/Components/MultiHandlers.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Utils/Containers.lua b/Assets/Engine/Scripts/Utils/Containers.lua index 9014a63090..d2905b5399 100644 --- a/Assets/Engine/Scripts/Utils/Containers.lua +++ b/Assets/Engine/Scripts/Utils/Containers.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Utils/EntityUtils.lua b/Assets/Engine/Scripts/Utils/EntityUtils.lua index 36362f9919..0adc4bc281 100644 --- a/Assets/Engine/Scripts/Utils/EntityUtils.lua +++ b/Assets/Engine/Scripts/Utils/EntityUtils.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/Assets/Engine/Scripts/Utils/Math.lua b/Assets/Engine/Scripts/Utils/Math.lua index 660fb17a92..57542dfee3 100644 --- a/Assets/Engine/Scripts/Utils/Math.lua +++ b/Assets/Engine/Scripts/Utils/Math.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/AutomatedTesting/CMakeLists.txt b/AutomatedTesting/CMakeLists.txt index fb1f0320e4..7a7d2b3165 100644 --- a/AutomatedTesting/CMakeLists.txt +++ b/AutomatedTesting/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Editor/Scripts/SettingsRegistry/__init__.py b/AutomatedTesting/Editor/Scripts/SettingsRegistry/__init__.py index ce5d67d66d..e1b5394b94 100755 --- a/AutomatedTesting/Editor/Scripts/SettingsRegistry/__init__.py +++ b/AutomatedTesting/Editor/Scripts/SettingsRegistry/__init__.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Editor/Scripts/SettingsRegistry/settings_registry_example.py b/AutomatedTesting/Editor/Scripts/SettingsRegistry/settings_registry_example.py index 120a487341..0dec2669fe 100755 --- a/AutomatedTesting/Editor/Scripts/SettingsRegistry/settings_registry_example.py +++ b/AutomatedTesting/Editor/Scripts/SettingsRegistry/settings_registry_example.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Editor/Scripts/__init__.py b/AutomatedTesting/Editor/Scripts/__init__.py index ce5d67d66d..e1b5394b94 100755 --- a/AutomatedTesting/Editor/Scripts/__init__.py +++ b/AutomatedTesting/Editor/Scripts/__init__.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/EngineFinder.cmake b/AutomatedTesting/EngineFinder.cmake index 0fee5bf6fc..94460e7c11 100644 --- a/AutomatedTesting/EngineFinder.cmake +++ b/AutomatedTesting/EngineFinder.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/CMakeLists.txt b/AutomatedTesting/Gem/CMakeLists.txt index 6732e0b7c6..e502c06bba 100644 --- a/AutomatedTesting/Gem/CMakeLists.txt +++ b/AutomatedTesting/Gem/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/Code/CMakeLists.txt b/AutomatedTesting/Gem/Code/CMakeLists.txt index 427ee7e66f..280c44fe8b 100644 --- a/AutomatedTesting/Gem/Code/CMakeLists.txt +++ b/AutomatedTesting/Gem/Code/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/Code/Include/AutomatedTesting/AutomatedTestingBus.h b/AutomatedTesting/Gem/Code/Include/AutomatedTesting/AutomatedTestingBus.h index 945e135414..7a1a0db21b 100644 --- a/AutomatedTesting/Gem/Code/Include/AutomatedTesting/AutomatedTestingBus.h +++ b/AutomatedTesting/Gem/Code/Include/AutomatedTesting/AutomatedTestingBus.h @@ -1,5 +1,5 @@ /* - * Copyright (c) Contributors to the Open 3D Engine Project + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * diff --git a/AutomatedTesting/Gem/Code/Platform/Android/platform_android_files.cmake b/AutomatedTesting/Gem/Code/Platform/Android/platform_android_files.cmake index 30503258bc..1fe051b062 100644 --- a/AutomatedTesting/Gem/Code/Platform/Android/platform_android_files.cmake +++ b/AutomatedTesting/Gem/Code/Platform/Android/platform_android_files.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/Code/Platform/Linux/platform_linux_files.cmake b/AutomatedTesting/Gem/Code/Platform/Linux/platform_linux_files.cmake index 30503258bc..1fe051b062 100644 --- a/AutomatedTesting/Gem/Code/Platform/Linux/platform_linux_files.cmake +++ b/AutomatedTesting/Gem/Code/Platform/Linux/platform_linux_files.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/Code/Platform/Mac/platform_mac_files.cmake b/AutomatedTesting/Gem/Code/Platform/Mac/platform_mac_files.cmake index 7a7c055518..b4e92ff6f5 100644 --- a/AutomatedTesting/Gem/Code/Platform/Mac/platform_mac_files.cmake +++ b/AutomatedTesting/Gem/Code/Platform/Mac/platform_mac_files.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake index 3b5129225b..6faf6e663d 100644 --- a/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/Platform/Mac/runtime_dependencies.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake b/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake index 3b5129225b..6faf6e663d 100644 --- a/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake +++ b/AutomatedTesting/Gem/Code/Platform/Mac/tool_dependencies.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/Code/Platform/Windows/platform_windows_files.cmake b/AutomatedTesting/Gem/Code/Platform/Windows/platform_windows_files.cmake index 30503258bc..1fe051b062 100644 --- a/AutomatedTesting/Gem/Code/Platform/Windows/platform_windows_files.cmake +++ b/AutomatedTesting/Gem/Code/Platform/Windows/platform_windows_files.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/Code/Platform/iOS/platform_ios_files.cmake b/AutomatedTesting/Gem/Code/Platform/iOS/platform_ios_files.cmake index d0f06b1753..d43675623c 100644 --- a/AutomatedTesting/Gem/Code/Platform/iOS/platform_ios_files.cmake +++ b/AutomatedTesting/Gem/Code/Platform/iOS/platform_ios_files.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/Code/Source/AutomatedTestingModule.cpp b/AutomatedTesting/Gem/Code/Source/AutomatedTestingModule.cpp index b8c122ec8f..e4534870e2 100644 --- a/AutomatedTesting/Gem/Code/Source/AutomatedTestingModule.cpp +++ b/AutomatedTesting/Gem/Code/Source/AutomatedTestingModule.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) Contributors to the Open 3D Engine Project + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * diff --git a/AutomatedTesting/Gem/Code/Source/AutomatedTestingSystemComponent.cpp b/AutomatedTesting/Gem/Code/Source/AutomatedTestingSystemComponent.cpp index dbe8faf12a..7bd2742d31 100644 --- a/AutomatedTesting/Gem/Code/Source/AutomatedTestingSystemComponent.cpp +++ b/AutomatedTesting/Gem/Code/Source/AutomatedTestingSystemComponent.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) Contributors to the Open 3D Engine Project + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * diff --git a/AutomatedTesting/Gem/Code/Source/AutomatedTestingSystemComponent.h b/AutomatedTesting/Gem/Code/Source/AutomatedTestingSystemComponent.h index ff93c24d15..de9d9ab51d 100644 --- a/AutomatedTesting/Gem/Code/Source/AutomatedTestingSystemComponent.h +++ b/AutomatedTesting/Gem/Code/Source/AutomatedTestingSystemComponent.h @@ -1,5 +1,5 @@ /* - * Copyright (c) Contributors to the Open 3D Engine Project + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * diff --git a/AutomatedTesting/Gem/Code/automatedtesting_files.cmake b/AutomatedTesting/Gem/Code/automatedtesting_files.cmake index ed8551e7d8..f28ae27ca7 100644 --- a/AutomatedTesting/Gem/Code/automatedtesting_files.cmake +++ b/AutomatedTesting/Gem/Code/automatedtesting_files.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/Code/enabled_gems.cmake b/AutomatedTesting/Gem/Code/enabled_gems.cmake index 767e6acafc..4ab914c118 100644 --- a/AutomatedTesting/Gem/Code/enabled_gems.cmake +++ b/AutomatedTesting/Gem/Code/enabled_gems.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # @@ -52,7 +52,7 @@ set(ENABLED_GEMS ) # TODO remove conditional add once AWSNativeSDK libs are fixed for Android and Linux Monolithic release. -set(aws_excluded_platforms Linux Android) +set(aws_excluded_platforms Android) if (NOT (LY_MONOLITHIC_GAME AND ${PAL_PLATFORM_NAME} IN_LIST aws_excluded_platforms)) list(APPEND ENABLED_GEMS AWSCore diff --git a/AutomatedTesting/Gem/Editor/Scripts/__init__.py b/AutomatedTesting/Gem/Editor/Scripts/__init__.py index a3a4055d50..e200fa77d0 100644 --- a/AutomatedTesting/Gem/Editor/Scripts/__init__.py +++ b/AutomatedTesting/Gem/Editor/Scripts/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/Editor/Scripts/bootstrap.py b/AutomatedTesting/Gem/Editor/Scripts/bootstrap.py index 5f784b8b8d..ec639ca075 100644 --- a/AutomatedTesting/Gem/Editor/Scripts/bootstrap.py +++ b/AutomatedTesting/Gem/Editor/Scripts/bootstrap.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/AWS/CMakeLists.txt index 8ba799d638..0d5c1d144a 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/AWS/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/__init__.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/__init__.py index 3a3549d485..5482b53e84 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/__init__.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/__init__.py index 487ceb9103..68fa386ecb 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py index ccafb35900..902666ba10 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_utils.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_utils.py index f6b79e5690..814ec1546a 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_utils.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_waiters.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_waiters.py index da058eb0d9..c56844bbcd 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_waiters.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_waiters.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/__init__.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/__init__.py index 3a3549d485..5482b53e84 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk_utils.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk_utils.py index b2058b372b..532f39df4a 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk_utils.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/cdk/cdk_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/__init__.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/__init__.py index 3a3549d485..5482b53e84 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/test_anonymous_credentials.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/test_anonymous_credentials.py index cf22ac6879..7ab84328fe 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/test_anonymous_credentials.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/test_anonymous_credentials.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/test_password_signin.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/test_password_signin.py index 4a964a5027..dafcb31751 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/test_password_signin.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/client_auth/test_password_signin.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/resource_mappings/__init__.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/resource_mappings/__init__.py index ce5bb8503d..99aac69543 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/resource_mappings/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/resource_mappings/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/resource_mappings/resource_mappings.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/resource_mappings/resource_mappings.py index 871288702e..2d67b0abc7 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/resource_mappings/resource_mappings.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/resource_mappings/resource_mappings.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/__init__.py b/AutomatedTesting/Gem/PythonTests/AWS/__init__.py index 3a3549d485..5482b53e84 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/common/__init__.py b/AutomatedTesting/Gem/PythonTests/AWS/common/__init__.py index 3a3549d485..5482b53e84 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/common/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/common/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/common/aws_credentials.py b/AutomatedTesting/Gem/PythonTests/AWS/common/aws_credentials.py index 5a6f182b14..61523599a8 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/common/aws_credentials.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/common/aws_credentials.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/common/aws_utils.py b/AutomatedTesting/Gem/PythonTests/AWS/common/aws_utils.py index b6f2573497..ca0d14c67c 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/common/aws_utils.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/common/aws_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/common/custom_waiter.py b/AutomatedTesting/Gem/PythonTests/AWS/common/custom_waiter.py index 544a5e5394..6a41b53dfd 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/common/custom_waiter.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/common/custom_waiter.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/AWS/conftest.py b/AutomatedTesting/Gem/PythonTests/AWS/conftest.py index 037b181dcb..15217d4620 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/conftest.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/conftest.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterCapsuleDamage.py b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterCapsuleDamage.py index 0c6a7fd7e2..55dec5e13d 100755 --- a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterCapsuleDamage.py +++ b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterCapsuleDamage.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterCollision.py b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterCollision.py index 0ecb9f2ff4..b9e78330d6 100755 --- a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterCollision.py +++ b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterCollision.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterDamage.py b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterDamage.py index 126a4d0c84..0f670fc779 100755 --- a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterDamage.py +++ b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterDamage.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterImpactSpreadDamage.py b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterImpactSpreadDamage.py index 466cc554cb..b18ac07dcb 100755 --- a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterImpactSpreadDamage.py +++ b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterImpactSpreadDamage.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterRadialDamage.py b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterRadialDamage.py index 31cde279d1..cc8f2185b6 100755 --- a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterRadialDamage.py +++ b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterRadialDamage.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterShearDamage.py b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterShearDamage.py index 6221225209..c31c26d928 100755 --- a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterShearDamage.py +++ b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterShearDamage.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterStressDamage.py b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterStressDamage.py index 6f2729d497..af82c5c3b8 100755 --- a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterStressDamage.py +++ b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterStressDamage.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterTriangleDamage.py b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterTriangleDamage.py index 55a65a57ff..8fba903e5e 100755 --- a/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterTriangleDamage.py +++ b/AutomatedTesting/Gem/PythonTests/Blast/ActorSplitsAfterTriangleDamage.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/Blast/BlastUtils.py b/AutomatedTesting/Gem/PythonTests/Blast/BlastUtils.py index bbc0409a14..95ba71ebb4 100644 --- a/AutomatedTesting/Gem/PythonTests/Blast/BlastUtils.py +++ b/AutomatedTesting/Gem/PythonTests/Blast/BlastUtils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/Blast/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/Blast/CMakeLists.txt index 2ca3af95ff..14dc029c7b 100644 --- a/AutomatedTesting/Gem/PythonTests/Blast/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/Blast/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/Blast/ImportPathHelper.py b/AutomatedTesting/Gem/PythonTests/Blast/ImportPathHelper.py index 002553b096..fd068c3db2 100755 --- a/AutomatedTesting/Gem/PythonTests/Blast/ImportPathHelper.py +++ b/AutomatedTesting/Gem/PythonTests/Blast/ImportPathHelper.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/Blast/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/Blast/TestSuite_Active.py index 925b08a272..d8b769e53f 100755 --- a/AutomatedTesting/Gem/PythonTests/Blast/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/Blast/TestSuite_Active.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/Blast/__init__.py b/AutomatedTesting/Gem/PythonTests/Blast/__init__.py index a3a4055d50..e200fa77d0 100755 --- a/AutomatedTesting/Gem/PythonTests/Blast/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/Blast/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 479db3230a..df21877cd4 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CMakeLists.txt index 84b52b7ccc..638a54fa5d 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentAssetCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentAssetCommands_test.py index fdd545bb94..a55905f65b 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentAssetCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentAssetCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentAssetCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentAssetCommands_test_case.py index 46ec731bcb..598cb41342 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentAssetCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentAssetCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentCommands_test.py index 916130bc91..d73946449c 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentCommands_test_case.py index 4b86e18f0c..1a3c62ae98 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentCommands_test_case_BuildComponentTypeNameList.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentCommands_test_case_BuildComponentTypeNameList.py index ff6b65d495..7057606b7a 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentCommands_test_case_BuildComponentTypeNameList.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentCommands_test_case_BuildComponentTypeNameList.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test.py index 0426334c81..f9b91e60b1 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_case.py index 29d6aadcf1..0fed80420c 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_case_set_none.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_case_set_none.py index 11d776f70b..e8def81b02 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_case_set_none.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_case_set_none.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_case_visibility.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_case_visibility.py index e68ce36923..baf888aea1 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_case_visibility.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_case_visibility.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_containers.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_containers.py index c3f75fd902..f76e23dc46 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_containers.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_containers.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_enum.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_enum.py index b9fd437ccc..caceecce69 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_enum.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentPropertyCommands_test_enum.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentUpdateListProperty_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentUpdateListProperty_test.py index af80a36460..1fd8a85259 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentUpdateListProperty_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ComponentUpdateListProperty_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsBus_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsBus_test.py index 070e2c8242..befa473149 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsBus_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsBus_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsBus_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsBus_test_case.py index bbf268aa68..fed1e706da 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsBus_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsBus_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsCommands_test.py index 0593f16378..e8cc288ed7 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsCommands_test_case.py index 7e8f61e703..712d37545b 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/DisplaySettingsCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorCommandLine_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorCommandLine_test.py index 9edebf9aef..e2a2327057 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorCommandLine_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorCommandLine_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorCommandLine_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorCommandLine_test_case.py index 6e12ffb0fb..933950a7be 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorCommandLine_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorCommandLine_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorScripts/ComponentUpdateListProperty_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorScripts/ComponentUpdateListProperty_test_case.py index 19b4c56111..bbf15e3ae4 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorScripts/ComponentUpdateListProperty_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorScripts/ComponentUpdateListProperty_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorScripts/__init__.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorScripts/__init__.py index ce5bb8503d..99aac69543 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorScripts/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorScripts/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorUtilityCommands_legacy_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorUtilityCommands_legacy_test_case.py index d1586d8947..cb9c57f8ee 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorUtilityCommands_legacy_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorUtilityCommands_legacy_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorUtilityCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorUtilityCommands_test.py index 4b037460e9..d4b3f93f59 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorUtilityCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorUtilityCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorUtilityCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorUtilityCommands_test_case.py index 1c886ce5cd..d6b72f6948 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorUtilityCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorUtilityCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorViewCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorViewCommands_test.py index b010ef75bb..6f1ce58d14 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorViewCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorViewCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorViewCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorViewCommands_test_case.py index 1570b720f4..b80524cd55 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorViewCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EditorViewCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCRUDCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCRUDCommands_test.py index 54d6666eec..23ee8cc74e 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCRUDCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCRUDCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCRUDCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCRUDCommands_test_case.py index 42fa3e4097..319113d3df 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCRUDCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCRUDCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCommands_test.py index e1aed00f90..c213bcb8bd 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCommands_test_case.py index db05dfb614..c2ed344888 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntityCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySearchCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySearchCommands_test.py index a1bb71b3c0..8689dd5685 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySearchCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySearchCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySearchCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySearchCommands_test_case.py index 9c6a6ce1de..8898916579 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySearchCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySearchCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySelectionCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySelectionCommands_test.py index b5a5393028..504cdd45dc 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySelectionCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySelectionCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySelectionCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySelectionCommands_test_case.py index 78acc915eb..5307216409 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySelectionCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/EntitySelectionCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/GameModeCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/GameModeCommands_test.py index 5352965727..f5cd8b4903 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/GameModeCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/GameModeCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/GameModeCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/GameModeCommands_test_case.py index c4589bfe97..1aa83cbe82 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/GameModeCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/GameModeCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelCommands_test.py index 7bda88578f..c16aed368c 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelCommands_test_case.py index 9d33273fef..b283c1b1b0 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelComponentCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelComponentCommands_test.py index 7ddd9ea7c6..9a4a769def 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelComponentCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelComponentCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelComponentCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelComponentCommands_test_case.py index e2fce7a83f..65cca678ec 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelComponentCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelComponentCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelPathsCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelPathsCommands_test.py index a9b8aa6642..fbe81a7222 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelPathsCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelPathsCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelPathsCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelPathsCommands_test_case.py index 522e234fc8..86149187a9 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelPathsCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/LevelPathsCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/MainWindowCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/MainWindowCommands_test.py index 8d21567a26..7a243f85c1 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/MainWindowCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/MainWindowCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/MainWindowCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/MainWindowCommands_test_case.py index 182e31a300..dc96a4b55f 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/MainWindowCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/MainWindowCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectManagerCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectManagerCommands_test.py index d09cba3c2f..b72e2f8461 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectManagerCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectManagerCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectManagerCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectManagerCommands_test_case.py index 6ce97cf84b..fee4f1f154 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectManagerCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectManagerCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectStringRepresentation_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectStringRepresentation_test.py index 7053b03389..5d4c94d166 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectStringRepresentation_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectStringRepresentation_test.py @@ -1,6 +1,6 @@ '' """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectStringRepresentation_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectStringRepresentation_test_case.py index 9a465ab1d0..b3d3ad142b 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectStringRepresentation_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ObjectStringRepresentation_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/PySide_Example_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/PySide_Example_test.py index 4f74d214f4..e3e0c7e0db 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/PySide_Example_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/PySide_Example_test.py @@ -1,6 +1,6 @@ '' """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/PySide_Example_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/PySide_Example_test_case.py index e65ea28895..d50bd872b8 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/PySide_Example_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/PySide_Example_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/TrackViewCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/TrackViewCommands_test.py index 18592eb99f..4e7a8d7953 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/TrackViewCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/TrackViewCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/TrackViewCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/TrackViewCommands_test_case.py index 1226633061..d5d793b53b 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/TrackViewCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/TrackViewCommands_test_case.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewPaneCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewPaneCommands_test.py index 3895723177..80826bac33 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewPaneCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewPaneCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewPaneCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewPaneCommands_test_case.py index 2698996c55..b277074647 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewPaneCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewPaneCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewportTitleDlgCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewportTitleDlgCommands_test.py index 30c57c9e14..45ca1197b2 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewportTitleDlgCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewportTitleDlgCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewportTitleDlgCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewportTitleDlgCommands_test_case.py index 51109ca926..8dba9a1c16 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewportTitleDlgCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/ViewportTitleDlgCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/WaitCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/WaitCommands_test.py index d04a4f6e96..929db4cbcb 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/WaitCommands_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/WaitCommands_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/WaitCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/WaitCommands_test_case.py index 8052bb8dc7..63cdabb9c9 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/WaitCommands_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/WaitCommands_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/__init__.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/__init__.py index ce5bb8503d..99aac69543 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/hydra_utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/hydra_utils.py index 52f9ebb1c5..8d91534c59 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/hydra_utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/hydra_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/layerEntity_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/layerEntity_test.py index 622d9844bf..51724ea509 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/layerEntity_test.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/layerEntity_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/layerEntity_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/layerEntity_test_case.py index f153ea3446..bd5265470c 100755 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/layerEntity_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/layerEntity_test_case.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/README.txt b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/README.txt index b5c02fd67a..b8933bab6b 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/README.txt +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/README.txt @@ -1,4 +1,4 @@ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/__init__.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/__init__.py index a3a4055d50..e200fa77d0 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/__init__.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/__init__.py index ce5bb8503d..99aac69543 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_entity_utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_entity_utils.py index f046a396f2..b452ad163d 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_entity_utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_entity_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_test_helper.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_test_helper.py index cdbefb6144..b6d05a11cc 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_test_helper.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_test_helper.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py index 0aa02c9b8b..2ce73a7dae 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_editor_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py index 0ad9290e23..2583109573 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/hydra_test_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/pyside_component_utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/pyside_component_utils.py index c73acea7a9..f017872c58 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/pyside_component_utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/pyside_component_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/pyside_utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/pyside_utils.py index f558577bca..8f57532a60 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/pyside_utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/pyside_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/utils.py index 93660d2ec3..35f07f99af 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/setup.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/setup.py index 891d8c93c2..1100efcdc6 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/setup.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/setup.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/NvCloth/C18977329_NvCloth_AddClothSimulationToMesh.py b/AutomatedTesting/Gem/PythonTests/NvCloth/C18977329_NvCloth_AddClothSimulationToMesh.py index bd6fcc93cd..85abb9eff5 100755 --- a/AutomatedTesting/Gem/PythonTests/NvCloth/C18977329_NvCloth_AddClothSimulationToMesh.py +++ b/AutomatedTesting/Gem/PythonTests/NvCloth/C18977329_NvCloth_AddClothSimulationToMesh.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/NvCloth/C18977330_NvCloth_AddClothSimulationToActor.py b/AutomatedTesting/Gem/PythonTests/NvCloth/C18977330_NvCloth_AddClothSimulationToActor.py index cd741d26d3..fac5a6264c 100755 --- a/AutomatedTesting/Gem/PythonTests/NvCloth/C18977330_NvCloth_AddClothSimulationToActor.py +++ b/AutomatedTesting/Gem/PythonTests/NvCloth/C18977330_NvCloth_AddClothSimulationToActor.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/NvCloth/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/NvCloth/CMakeLists.txt index cedae0a390..5b26424097 100644 --- a/AutomatedTesting/Gem/PythonTests/NvCloth/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/NvCloth/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/NvCloth/ImportPathHelper.py b/AutomatedTesting/Gem/PythonTests/NvCloth/ImportPathHelper.py index 002553b096..fd068c3db2 100755 --- a/AutomatedTesting/Gem/PythonTests/NvCloth/ImportPathHelper.py +++ b/AutomatedTesting/Gem/PythonTests/NvCloth/ImportPathHelper.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/NvCloth/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/NvCloth/TestSuite_Active.py index 230d99d205..ce3f04b8f1 100755 --- a/AutomatedTesting/Gem/PythonTests/NvCloth/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/NvCloth/TestSuite_Active.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/NvCloth/__init__.py b/AutomatedTesting/Gem/PythonTests/NvCloth/__init__.py index a3a4055d50..e200fa77d0 100755 --- a/AutomatedTesting/Gem/PythonTests/NvCloth/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/NvCloth/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/Platform/Android/PAL_traits_android.cmake b/AutomatedTesting/Gem/PythonTests/Platform/Android/PAL_traits_android.cmake index b9f79c94e0..12a69f2243 100644 --- a/AutomatedTesting/Gem/PythonTests/Platform/Android/PAL_traits_android.cmake +++ b/AutomatedTesting/Gem/PythonTests/Platform/Android/PAL_traits_android.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/Platform/Linux/PAL_traits_linux.cmake b/AutomatedTesting/Gem/PythonTests/Platform/Linux/PAL_traits_linux.cmake index b9f79c94e0..12a69f2243 100644 --- a/AutomatedTesting/Gem/PythonTests/Platform/Linux/PAL_traits_linux.cmake +++ b/AutomatedTesting/Gem/PythonTests/Platform/Linux/PAL_traits_linux.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/Platform/Mac/PAL_traits_mac.cmake b/AutomatedTesting/Gem/PythonTests/Platform/Mac/PAL_traits_mac.cmake index b9f79c94e0..12a69f2243 100644 --- a/AutomatedTesting/Gem/PythonTests/Platform/Mac/PAL_traits_mac.cmake +++ b/AutomatedTesting/Gem/PythonTests/Platform/Mac/PAL_traits_mac.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/Platform/Windows/PAL_traits_windows.cmake b/AutomatedTesting/Gem/PythonTests/Platform/Windows/PAL_traits_windows.cmake index 8b3eeb5233..180fc1d1fd 100644 --- a/AutomatedTesting/Gem/PythonTests/Platform/Windows/PAL_traits_windows.cmake +++ b/AutomatedTesting/Gem/PythonTests/Platform/Windows/PAL_traits_windows.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/Platform/iOS/PAL_traits_ios.cmake b/AutomatedTesting/Gem/PythonTests/Platform/iOS/PAL_traits_ios.cmake index b9f79c94e0..12a69f2243 100644 --- a/AutomatedTesting/Gem/PythonTests/Platform/iOS/PAL_traits_ios.cmake +++ b/AutomatedTesting/Gem/PythonTests/Platform/iOS/PAL_traits_ios.cmake @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test.py index c433215f83..f5bdb73a41 100644 --- a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test.py +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py index c8f03ac2b0..6622c0de68 100644 --- a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/AssetBuilder_test_case.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/CMakeLists.txt index c343f28d6f..a36f90d22e 100644 --- a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/__init__.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/__init__.py index ce5bb8503d..99aac69543 100644 --- a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/bootstrap_tests.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/bootstrap_tests.py index 577c7fa910..2d2169b309 100644 --- a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/bootstrap_tests.py +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/bootstrap_tests.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/export_chunks_builder.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/export_chunks_builder.py index 46cac37d0c..f4c61ab29f 100644 --- a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/export_chunks_builder.py +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/export_chunks_builder.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/mock_asset_builder.py b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/mock_asset_builder.py index 10c93bdd47..e46d57b3d7 100644 --- a/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/mock_asset_builder.py +++ b/AutomatedTesting/Gem/PythonTests/PythonAssetBuilder/mock_asset_builder.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798177_WhiteBox_AddComponentToEntity.py b/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798177_WhiteBox_AddComponentToEntity.py index 4c606ccb43..da98d20204 100755 --- a/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798177_WhiteBox_AddComponentToEntity.py +++ b/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798177_WhiteBox_AddComponentToEntity.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798205_WhiteBox_SetInvisible.py b/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798205_WhiteBox_SetInvisible.py index 962f2a7168..ea1350d9ed 100755 --- a/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798205_WhiteBox_SetInvisible.py +++ b/AutomatedTesting/Gem/PythonTests/WhiteBox/C28798205_WhiteBox_SetInvisible.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/WhiteBox/C29279329_WhiteBox_SetDefaultShape.py b/AutomatedTesting/Gem/PythonTests/WhiteBox/C29279329_WhiteBox_SetDefaultShape.py index 2556214552..ab470f2f8f 100755 --- a/AutomatedTesting/Gem/PythonTests/WhiteBox/C29279329_WhiteBox_SetDefaultShape.py +++ b/AutomatedTesting/Gem/PythonTests/WhiteBox/C29279329_WhiteBox_SetDefaultShape.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/WhiteBox/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/WhiteBox/CMakeLists.txt index fcf2f52e09..a6d5ef0956 100644 --- a/AutomatedTesting/Gem/PythonTests/WhiteBox/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/WhiteBox/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/WhiteBox/FileManagement.py b/AutomatedTesting/Gem/PythonTests/WhiteBox/FileManagement.py index a0494b9915..5bab5983a9 100755 --- a/AutomatedTesting/Gem/PythonTests/WhiteBox/FileManagement.py +++ b/AutomatedTesting/Gem/PythonTests/WhiteBox/FileManagement.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/WhiteBox/ImportPathHelper.py b/AutomatedTesting/Gem/PythonTests/WhiteBox/ImportPathHelper.py index 002553b096..fd068c3db2 100755 --- a/AutomatedTesting/Gem/PythonTests/WhiteBox/ImportPathHelper.py +++ b/AutomatedTesting/Gem/PythonTests/WhiteBox/ImportPathHelper.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/WhiteBox/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/WhiteBox/TestSuite_Active.py index 7cb1e21afb..26b7ee7fa4 100755 --- a/AutomatedTesting/Gem/PythonTests/WhiteBox/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/WhiteBox/TestSuite_Active.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/WhiteBox/__init__.py b/AutomatedTesting/Gem/PythonTests/WhiteBox/__init__.py index a3a4055d50..e200fa77d0 100755 --- a/AutomatedTesting/Gem/PythonTests/WhiteBox/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/WhiteBox/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/assetpipeline/CMakeLists.txt index ecc8f96f5a..29abc336bf 100644 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/__init__.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/__init__.py index ce5d67d66d..e1b5394b94 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/__init__.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/__init__.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/__init__.py index ce5d67d66d..e1b5394b94 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/__init__.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_all_platforms_setup_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_all_platforms_setup_fixture.py index 70eb8f200e..bb1afdb7b7 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_all_platforms_setup_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_all_platforms_setup_fixture.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_config_backup_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_config_backup_fixture.py index e73f737b9b..5a2837dae8 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_config_backup_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_config_backup_fixture.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_config_default_platform_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_config_default_platform_fixture.py index 33aaacb5f1..5b6492b0a0 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_config_default_platform_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_config_default_platform_fixture.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_external_project_setup_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_external_project_setup_fixture.py index 9c6cb4bf27..9bd03cc692 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_external_project_setup_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_external_project_setup_fixture.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_fast_scan_setting_backup_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_fast_scan_setting_backup_fixture.py index 66f0cb9ab7..9973f1ee10 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_fast_scan_setting_backup_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_fast_scan_setting_backup_fixture.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_idle_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_idle_fixture.py index 2a5fc18c08..5af3477e4f 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_idle_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_idle_fixture.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_missing_dependency_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_missing_dependency_fixture.py index 3a7e91b262..538efac531 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_missing_dependency_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_missing_dependency_fixture.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_setup_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_setup_fixture.py index 9d288d5985..7d458e0202 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_setup_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/ap_setup_fixture.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/asset_processor_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/asset_processor_fixture.py index 4dfb65f3b1..8750962049 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/asset_processor_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/asset_processor_fixture.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py index b2dc628c43..f82e197cb8 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/bundler_batch_setup_fixture.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/clear_moveoutput_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/clear_moveoutput_fixture.py index 15cbecdfea..b0fd2d0992 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/clear_moveoutput_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/clear_moveoutput_fixture.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/clear_testingAssets_dir.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/clear_testingAssets_dir.py index 60b7437c71..631970b50c 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/clear_testingAssets_dir.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/clear_testingAssets_dir.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/one_time_log_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/one_time_log_fixture.py index 7f49ceb5c6..5c3713483b 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/one_time_log_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/one_time_log_fixture.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/timeout_option_fixture.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/timeout_option_fixture.py index 1dab821924..306f36d072 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/timeout_option_fixture.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/ap_fixtures/timeout_option_fixture.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt index 1c8a4b17ad..f05aff6db3 100644 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/__init__.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/__init__.py index ce5d67d66d..e1b5394b94 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/__init__.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_builder_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_builder_tests.py index 1ca2d51424..31e387e8a3 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_builder_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_builder_tests.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py index 34051c0614..926f1cc602 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests.py index f771563937..618811cfda 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests2.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests2.py index 9897d67b37..9314c29571 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests2.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_dependency_tests2.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests.py index 4da409accd..bcf8221ce6 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests_2.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests_2.py index d0fe77c68d..0ea6d29380 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests_2.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_batch_tests_2.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests.py index ebddf6d5b6..a03351393a 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests_2.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests_2.py index 82070ecd58..4b03caba62 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests_2.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_processor_gui_tests_2.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_relocator_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_relocator_tests.py index 6b687c267d..f03eddf733 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_relocator_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_relocator_tests.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/C1571774/test_lua_print.lua b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/C1571774/test_lua_print.lua index d289ed4310..a156345563 100644 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/C1571774/test_lua_print.lua +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/C1571774/test_lua_print.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/C1591338/test_lua_print.lua b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/C1591338/test_lua_print.lua index d289ed4310..a156345563 100644 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/C1591338/test_lua_print.lua +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/C1591338/test_lua_print.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/test_ProcessAndDeleteCache_APBatchShouldReprocess/main.lua b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/test_ProcessAndDeleteCache_APBatchShouldReprocess/main.lua index 4ff6ccf76e..631a12422c 100644 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/test_ProcessAndDeleteCache_APBatchShouldReprocess/main.lua +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/test_ProcessAndDeleteCache_APBatchShouldReprocess/main.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/test_ProcessByBothApAndBatch_Md5ShouldMatch/main.lua b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/test_ProcessByBothApAndBatch_Md5ShouldMatch/main.lua index 4ff6ccf76e..631a12422c 100644 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/test_ProcessByBothApAndBatch_Md5ShouldMatch/main.lua +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/assets/test_ProcessByBothApAndBatch_Md5ShouldMatch/main.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/conftest.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/conftest.py index f04bcd9963..32b2910b2a 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/conftest.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/conftest.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/missing_dependency_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/missing_dependency_tests.py index c0aa01964a..d1e51d7422 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/missing_dependency_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/missing_dependency_tests.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/__init__.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/__init__.py index ce5d67d66d..e1b5394b94 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/__init__.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/conftest.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/conftest.py index a30d232b6a..dad417436d 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/conftest.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/conftest.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/fbx_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/fbx_tests.py index 6460d04e48..4a9dbb51c8 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/fbx_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/fbx_tests.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/wwise_bank_dependency_tests/__init__.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/wwise_bank_dependency_tests/__init__.py index ce5d67d66d..e1b5394b94 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/wwise_bank_dependency_tests/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/wwise_bank_dependency_tests/__init__.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/wwise_bank_dependency_tests/bank_info_parser_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/wwise_bank_dependency_tests/bank_info_parser_tests.py index d77aeb36a8..2906835386 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/wwise_bank_dependency_tests/bank_info_parser_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/wwise_bank_dependency_tests/bank_info_parser_tests.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt index cd260447c3..ec150bd186 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/__init__.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/__init__.py index a3a4055d50..e200fa77d0 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/__init__.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/__init__.py index a3a4055d50..e200fa77d0 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py index 10db402b9c..df1910b535 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py index d3e05e9c09..c5090937b8 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_SandboxSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_SandboxSuite.py index 5d18cc6c6e..41859195ee 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_SandboxSuite.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_SandboxSuite.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/__init__.py b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/__init__.py index ce5bb8503d..99aac69543 100755 --- a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/asset_database_utils.py b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/asset_database_utils.py index 63e6f3b0b7..7df225590c 100755 --- a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/asset_database_utils.py +++ b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/asset_database_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/asset_utils.py b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/asset_utils.py index a9cd280c31..83cf35e9f2 100755 --- a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/asset_utils.py +++ b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/asset_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/base.py b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/base.py index b91e088ee9..2e2f794e94 100755 --- a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/base.py +++ b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/base.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/file_utils.py b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/file_utils.py index fbb694e938..44719a33f1 100755 --- a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/file_utils.py +++ b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/file_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/landscape_canvas_utils.py b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/landscape_canvas_utils.py index 1d82995a6e..ff279ebc0a 100755 --- a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/landscape_canvas_utils.py +++ b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/landscape_canvas_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/network_utils.py b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/network_utils.py index 773ab77ffb..f9981d2dac 100755 --- a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/network_utils.py +++ b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/network_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/platform_setting.py b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/platform_setting.py index 07dc9f26b7..f057bd7ffe 100755 --- a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/platform_setting.py +++ b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/platform_setting.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/registry_utils.py b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/registry_utils.py index 315ca4d85d..6e2c13d794 100644 --- a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/registry_utils.py +++ b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/registry_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ @@ -9,12 +9,12 @@ import winreg logger = logging.getLogger(__name__) -LUMBERYARD_SETTINGS_PATH = r'Software\Amazon\Lumberyard\Settings' +LUMBERYARD_SETTINGS_PATH = r'Software\O3DE\O3DE\Settings' def set_ly_registry_value(reg_path, value_name, new_value, value_type=winreg.REG_DWORD): """ Sets the specified value for the specified value_name in the LY registry key. - :param reg_path: A string that identifies the registry path to the desired key (e.g. Software\Amazon\Lumberyard\Settings) + :param reg_path: A string that identifies the registry path to the desired key (e.g. Software\O3DE\O3DE\Settings) :param value_name: A string that identifies the value name (e.g. UndoLevels, ViewportInteractionModel) :param new_value: Value to set on the specified value_name :param value_type: The type of value set. Defaults to a 32-bit number. @@ -40,7 +40,7 @@ def set_ly_registry_value(reg_path, value_name, new_value, value_type=winreg.REG def get_ly_registry_value(reg_path, value_name): """ Gets the current value for an existing value_name in the LY registry key. - :param reg_path: A string that identifies the registry path to the desired key (e.g. Software\Amazon\Lumberyard\Settings) + :param reg_path: A string that identifies the registry path to the desired key (e.g. Software\O3DE\O3DE\Settings) :param value_name: A string that identifies the value name (e.g. UndoLevels, ViewportInteractionModel) :return: Value set for the specified value_name """ @@ -62,7 +62,7 @@ def get_ly_registry_value(reg_path, value_name): def delete_ly_registry_value(reg_path, value_name): """ Deletes the specific registry value_name found in the reg_path key. - :param reg_path: A string that identifies the registry path to the desired key (e.g. Software\Amazon\Lumberyard\Settings) + :param reg_path: A string that identifies the registry path to the desired key (e.g. Software\O3DE\O3DE\Settings) :param value_name: A string that identifies the value name (e.g. UndoLevels, ViewportInteractionModel) :return: None """ diff --git a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/report.py b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/report.py index 0f48863e75..4841a4ad79 100755 --- a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/report.py +++ b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/report.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/screenshot_utils.py b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/screenshot_utils.py index c641b495c0..ac36be4d8c 100755 --- a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/screenshot_utils.py +++ b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/screenshot_utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/windows_registry_setting.py b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/windows_registry_setting.py index 4c3894e1ec..72731e2f1c 100755 --- a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/windows_registry_setting.py +++ b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/windows_registry_setting.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/editor/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/editor/CMakeLists.txt index 0c0d26a208..66cfa13ec3 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/editor/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_SearchFiltering.py b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_SearchFiltering.py index cd7b33fc7b..dbed681f03 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_SearchFiltering.py +++ b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_SearchFiltering.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_TreeNavigation.py b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_TreeNavigation.py index 26597b2ff7..f934886f03 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_TreeNavigation.py +++ b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetBrowser_TreeNavigation.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetPicker_UI_UX.py b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetPicker_UI_UX.py index c0e6f0937f..30b774c88b 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetPicker_UI_UX.py +++ b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/AssetPicker_UI_UX.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/BasicEditorWorkflows_LevelEntityComponentCRUD.py b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/BasicEditorWorkflows_LevelEntityComponentCRUD.py index 08e4e8c7d2..c01b65eeab 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/BasicEditorWorkflows_LevelEntityComponentCRUD.py +++ b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/BasicEditorWorkflows_LevelEntityComponentCRUD.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/ComponentCRUD_Add_Delete_Components.py b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/ComponentCRUD_Add_Delete_Components.py index 2ca2fba6e4..5250dd6978 100755 --- a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/ComponentCRUD_Add_Delete_Components.py +++ b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/ComponentCRUD_Add_Delete_Components.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Docking_BasicDockedTools.py b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Docking_BasicDockedTools.py index cfaf63ba4b..de0624fedb 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Docking_BasicDockedTools.py +++ b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Docking_BasicDockedTools.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/InputBindings_Add_Remove_Input_Events.py b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/InputBindings_Add_Remove_Input_Events.py index 145a3c2305..5b365dd229 100755 --- a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/InputBindings_Add_Remove_Input_Events.py +++ b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/InputBindings_Add_Remove_Input_Events.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_EditMenuOptions.py b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_EditMenuOptions.py index 4ec4e95a8e..26110cd954 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_EditMenuOptions.py +++ b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_EditMenuOptions.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_FileMenuOptions.py b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_FileMenuOptions.py index 127a061725..bc1a37541e 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_FileMenuOptions.py +++ b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_FileMenuOptions.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_ViewMenuOptions.py b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_ViewMenuOptions.py index e66e271c71..7ed08867a9 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_ViewMenuOptions.py +++ b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Menus_ViewMenuOptions.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/__init__.py b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/__init__.py index ce5bb8503d..99aac69543 100755 --- a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/editor/__init__.py b/AutomatedTesting/Gem/PythonTests/editor/__init__.py index ce5bb8503d..99aac69543 100755 --- a/AutomatedTesting/Gem/PythonTests/editor/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/editor/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/editor/conftest.py b/AutomatedTesting/Gem/PythonTests/editor/conftest.py index 2b26370126..73d974640f 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/conftest.py +++ b/AutomatedTesting/Gem/PythonTests/editor/conftest.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ @@ -14,12 +14,12 @@ logger = logging.getLogger(__name__) layout = { - 'path': r'Software\Amazon\O3DE\Editor\fancyWindowLayouts', + 'path': r'Software\O3DE\O3DE\Editor\fancyWindowLayouts', 'value': 'last' } restore_camera = { 'new': 16384, - 'path': r'Software\Amazon\Lumberyard\Editor\AutoHide', + 'path': r'Software\O3DE\O3DE\Editor\AutoHide', 'value': 'ViewportCameraRestoreOnExitGameMode' } diff --git a/AutomatedTesting/Gem/PythonTests/editor/test_AssetBrowser.py b/AutomatedTesting/Gem/PythonTests/editor/test_AssetBrowser.py index addb59ec3b..3389e4087c 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/test_AssetBrowser.py +++ b/AutomatedTesting/Gem/PythonTests/editor/test_AssetBrowser.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/editor/test_AssetPicker.py b/AutomatedTesting/Gem/PythonTests/editor/test_AssetPicker.py index df7b727af4..16150fcc21 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/test_AssetPicker.py +++ b/AutomatedTesting/Gem/PythonTests/editor/test_AssetPicker.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/editor/test_BasicEditorWorkflows.py b/AutomatedTesting/Gem/PythonTests/editor/test_BasicEditorWorkflows.py index 72545fb98d..e290a7e3e9 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/test_BasicEditorWorkflows.py +++ b/AutomatedTesting/Gem/PythonTests/editor/test_BasicEditorWorkflows.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/editor/test_ComponentCRUD.py b/AutomatedTesting/Gem/PythonTests/editor/test_ComponentCRUD.py index dac939a9de..847cc726dd 100755 --- a/AutomatedTesting/Gem/PythonTests/editor/test_ComponentCRUD.py +++ b/AutomatedTesting/Gem/PythonTests/editor/test_ComponentCRUD.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/editor/test_Docking.py b/AutomatedTesting/Gem/PythonTests/editor/test_Docking.py index c61651bf3d..f5f684e4e1 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/test_Docking.py +++ b/AutomatedTesting/Gem/PythonTests/editor/test_Docking.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/editor/test_InputBindings.py b/AutomatedTesting/Gem/PythonTests/editor/test_InputBindings.py index 81efd6a056..ceb2933dd6 100755 --- a/AutomatedTesting/Gem/PythonTests/editor/test_InputBindings.py +++ b/AutomatedTesting/Gem/PythonTests/editor/test_InputBindings.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/editor/test_Menus.py b/AutomatedTesting/Gem/PythonTests/editor/test_Menus.py index 94646fc65b..b45a087c79 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/test_Menus.py +++ b/AutomatedTesting/Gem/PythonTests/editor/test_Menus.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt index 8a37e13e7d..9c16479b9b 100644 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/__init__.py b/AutomatedTesting/Gem/PythonTests/largeworlds/__init__.py index ce5bb8503d..99aac69543 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude.py index 87e0fc583f..b8b640071e 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ComponentAndOverrides_InstancesPlantAtSpecifiedAltitude.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_FilterStageToggle.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_FilterStageToggle.py index ebfd5c1a1c..bbdb925585 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_FilterStageToggle.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_FilterStageToggle.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude.py index 8fe9d5bc6f..5f6c72f481 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AltitudeFilter_ShapeSample_InstancesPlantAtSpecifiedAltitude.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AreaComponentSlices_SliceCreationAndVisibilityToggle.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AreaComponentSlices_SliceCreationAndVisibilityToggle.py index 97257b7b04..c255476445 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AreaComponentSlices_SliceCreationAndVisibilityToggle.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AreaComponentSlices_SliceCreationAndVisibilityToggle.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea.py index 7173d1c423..cea749dc46 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetListCombiner_CombinedDescriptorsExpressInConfiguredArea.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetWeightSelector_InstancesExpressBasedOnWeight.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetWeightSelector_InstancesExpressBasedOnWeight.py index 8f0c37e89e..cfd436792b 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetWeightSelector_InstancesExpressBasedOnWeight.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/AssetWeightSelector_InstancesExpressBasedOnWeight.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/Debugger_DebugCVarsWorks.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/Debugger_DebugCVarsWorks.py index 720db3960d..40fd67d957 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/Debugger_DebugCVarsWorks.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/Debugger_DebugCVarsWorks.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ 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 9b3b641bd8..f6270fac28 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ 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 1eaa440644..960d3a3015 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks.py index 1edc392423..863c8935ba 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_DynamicSliceSpawnerWorks.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_Embedded_E2E.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_Embedded_E2E.py index 0e7b2bc7ad..4b0951acaf 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_Embedded_E2E.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_Embedded_E2E.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_External_E2E.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_External_E2E.py index 9deecc1208..892549d414 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_External_E2E.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/DynamicSliceInstanceSpawner_External_E2E.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/EmptyInstanceSpawner_EmptySpawnerWorks.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/EmptyInstanceSpawner_EmptySpawnerWorks.py index 11a2282935..963a97f3a3 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/EmptyInstanceSpawner_EmptySpawnerWorks.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/EmptyInstanceSpawner_EmptySpawnerWorks.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/InstanceSpawnerPriority_LayerAndSubPriority.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/InstanceSpawnerPriority_LayerAndSubPriority.py index 7d099a075b..3f915b5516 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/InstanceSpawnerPriority_LayerAndSubPriority.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/InstanceSpawnerPriority_LayerAndSubPriority.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlender_E2E_Editor.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlender_E2E_Editor.py index 71c81e5f36..c4dfbbf4fe 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlender_E2E_Editor.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlender_E2E_Editor.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlocker_InstancesBlockedInConfiguredArea.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlocker_InstancesBlockedInConfiguredArea.py index 04f4cb6d4c..cb2d206f18 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlocker_InstancesBlockedInConfiguredArea.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerBlocker_InstancesBlockedInConfiguredArea.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_FilterStageToggle.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_FilterStageToggle.py index e3952a93ce..0224f6bc0a 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_FilterStageToggle.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_FilterStageToggle.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InheritBehaviorFlag.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InheritBehaviorFlag.py index f9a58c44e6..fc060151e9 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InheritBehaviorFlag.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InheritBehaviorFlag.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesPlantInAllSupportedShapes.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesPlantInAllSupportedShapes.py index f3c916836c..e170d13360 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesPlantInAllSupportedShapes.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesPlantInAllSupportedShapes.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesRefreshUsingCorrectViewportCamera.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesRefreshUsingCorrectViewportCamera.py index 654007ec14..c99d180253 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesRefreshUsingCorrectViewportCamera.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/LayerSpawner_InstancesRefreshUsingCorrectViewportCamera.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMesh.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMesh.py index c4098fc9cc..d23f811f58 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMesh.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMesh.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMeshHeightTuning.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMeshHeightTuning.py index 95ccc6ef8e..ad57f80776 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMeshHeightTuning.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshBlocker_InstancesBlockedByMeshHeightTuning.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_DependentOnMeshComponent.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_DependentOnMeshComponent.py index ff56ca936f..1d25121bf6 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_DependentOnMeshComponent.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_DependentOnMeshComponent.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py index 8cb35ab6ca..a0b38ee277 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/MeshSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PhysXColliderSurfaceTagEmitter_E2E_Editor.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PhysXColliderSurfaceTagEmitter_E2E_Editor.py index bd18d0e850..6af05b8d70 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PhysXColliderSurfaceTagEmitter_E2E_Editor.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PhysXColliderSurfaceTagEmitter_E2E_Editor.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_AutoSnapToSurfaceWorks.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_AutoSnapToSurfaceWorks.py index addc2feaf1..bbb869ff7f 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_AutoSnapToSurfaceWorks.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_AutoSnapToSurfaceWorks.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets.py index 594bddffa2..87e6d3b9b3 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/PositionModifier_ComponentAndOverrides_InstancesPlantAtSpecifiedOffsets.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifierOverrides_InstancesRotateWithinRange.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifierOverrides_InstancesRotateWithinRange.py index 75448d360f..a21031abbe 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifierOverrides_InstancesRotateWithinRange.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifierOverrides_InstancesRotateWithinRange.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifier_InstancesRotateWithinRange.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifier_InstancesRotateWithinRange.py index 0c7f52ce7b..78353ef090 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifier_InstancesRotateWithinRange.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/RotationModifier_InstancesRotateWithinRange.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifierOverrides_InstancesProperlyScale.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifierOverrides_InstancesProperlyScale.py index 8b85e13f61..b475c56e5e 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifierOverrides_InstancesProperlyScale.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifierOverrides_InstancesProperlyScale.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifier_InstancesProperlyScale.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifier_InstancesProperlyScale.py index a69ae4d393..2c9380ccbe 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifier_InstancesProperlyScale.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ScaleModifier_InstancesProperlyScale.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ShapeIntersectionFilter_InstancesPlantInAssignedShape.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ShapeIntersectionFilter_InstancesPlantInAssignedShape.py index f1f3bed629..9624ccdc34 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ShapeIntersectionFilter_InstancesPlantInAssignedShape.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/ShapeIntersectionFilter_InstancesPlantInAssignedShape.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment.py index ce1f18983a..8607aece64 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifierOverrides_InstanceSurfaceAlignment.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifier_InstanceSurfaceAlignment.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifier_InstanceSurfaceAlignment.py index 813897047d..f252a13c2a 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifier_InstanceSurfaceAlignment.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeAlignmentModifier_InstanceSurfaceAlignment.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlope.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlope.py index 0bfaeabb45..593591c84b 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlope.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeFilter_ComponentAndOverrides_InstancesPlantOnValidSlope.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeFilter_FilterStageToggle.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeFilter_FilterStageToggle.py index fe57316ec1..c8523dd798 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeFilter_FilterStageToggle.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SlopeFilter_FilterStageToggle.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceDataRefreshes_RemainsStable.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceDataRefreshes_RemainsStable.py index c7203b8614..b930ab6acc 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceDataRefreshes_RemainsStable.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceDataRefreshes_RemainsStable.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected.py index a541090762..76021d9f83 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilterOverrides_MultipleDescriptorOverridesPlantAsExpected.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_BasicSurfaceTagCreation.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_BasicSurfaceTagCreation.py index ed17c9d017..ddf2f30e89 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_BasicSurfaceTagCreation.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_BasicSurfaceTagCreation.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_ExclusionList.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_ExclusionList.py index ab7fa9ec46..613778cbb3 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_ExclusionList.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_ExclusionList.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_InclusionList.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_InclusionList.py index 441072a2ca..55a6d815e3 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_InclusionList.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SurfaceMaskFilter_InclusionList.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorPointDensity.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorPointDensity.py index 87831fc0f1..e4a57916d7 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorPointDensity.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorPointDensity.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorSize.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorSize.py index 04adb48c16..53ee7d6105 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorSize.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/SystemSettings_SectorSize.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/VegetationInstances_DespawnWhenOutOfRange.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/VegetationInstances_DespawnWhenOutOfRange.py index 4296a4342b..df42b9e821 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/VegetationInstances_DespawnWhenOutOfRange.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/VegetationInstances_DespawnWhenOutOfRange.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/__init__.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/__init__.py index ce5bb8503d..99aac69543 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/EditorScripts/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/__init__.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/__init__.py index ce5bb8503d..99aac69543 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AltitudeFilter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AltitudeFilter.py index 9e140d74d7..36a8307c88 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AltitudeFilter.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AltitudeFilter.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AreaComponentSlices.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AreaComponentSlices.py index 6c0fd66b20..ffea660a63 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AreaComponentSlices.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AreaComponentSlices.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AssetListCombiner.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AssetListCombiner.py index 2c3e5ec10a..f5d239771f 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AssetListCombiner.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AssetListCombiner.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AssetWeightSelector.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AssetWeightSelector.py index 917fcd44fc..9f6302cd82 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AssetWeightSelector.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_AssetWeightSelector.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_Debugger.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_Debugger.py index cdaa6f47ad..ed979136e0 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_Debugger.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_Debugger.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DistanceBetweenFilter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DistanceBetweenFilter.py index e2ad2031a4..3c53c51a3c 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DistanceBetweenFilter.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DistanceBetweenFilter.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynVeg_Regressions.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynVeg_Regressions.py index 9f7b8770da..207aa40f90 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynVeg_Regressions.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynVeg_Regressions.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynamicSliceInstanceSpawner.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynamicSliceInstanceSpawner.py index 3d6a113031..053c4ccbfd 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynamicSliceInstanceSpawner.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DynamicSliceInstanceSpawner.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_EmptyInstanceSpawner.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_EmptyInstanceSpawner.py index 5a33ffacb7..88b056445f 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_EmptyInstanceSpawner.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_EmptyInstanceSpawner.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_InstanceSpawnerPriority.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_InstanceSpawnerPriority.py index d0d2bdc2f6..ddbccd751a 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_InstanceSpawnerPriority.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_InstanceSpawnerPriority.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerBlender.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerBlender.py index a1944eff4d..3c16420a30 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerBlender.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerBlender.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerBlocker.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerBlocker.py index 90cdc04313..2902291b9a 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerBlocker.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerBlocker.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerSpawner.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerSpawner.py index 9e060300ad..410bdbafed 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerSpawner.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_LayerSpawner.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_MeshBlocker.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_MeshBlocker.py index 49e720d3a2..e6ef7f53c5 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_MeshBlocker.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_MeshBlocker.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_MeshSurfaceTagEmitter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_MeshSurfaceTagEmitter.py index 1ba2b93b21..b8036bb724 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_MeshSurfaceTagEmitter.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_MeshSurfaceTagEmitter.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_PhysXColliderSurfaceTagEmitter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_PhysXColliderSurfaceTagEmitter.py index 3551f91b00..8a1523f37c 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_PhysXColliderSurfaceTagEmitter.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_PhysXColliderSurfaceTagEmitter.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_PositionModifier.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_PositionModifier.py index bd151197d7..c2a873dffc 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_PositionModifier.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_PositionModifier.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_RotationModifier.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_RotationModifier.py index b79277f0f4..1d892a781b 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_RotationModifier.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_RotationModifier.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_ScaleModifier.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_ScaleModifier.py index 5018da8f73..f05199d2d0 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_ScaleModifier.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_ScaleModifier.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_ShapeIntersectionFilter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_ShapeIntersectionFilter.py index 8c32e6c8e4..dd4c4b8943 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_ShapeIntersectionFilter.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_ShapeIntersectionFilter.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SlopeAlignmentModifier.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SlopeAlignmentModifier.py index 74b265e1a1..d7ab40af35 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SlopeAlignmentModifier.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SlopeAlignmentModifier.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SlopeFilter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SlopeFilter.py index 8cb5a82cbc..5c1f79aaf3 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SlopeFilter.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SlopeFilter.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SurfaceMaskFilter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SurfaceMaskFilter.py index f46d5758e2..dbff206b43 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SurfaceMaskFilter.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SurfaceMaskFilter.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SystemSettings.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SystemSettings.py index fdf27e2beb..644c748da0 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SystemSettings.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_SystemSettings.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientGenerators_Incompatibilities.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientGenerators_Incompatibilities.py index a52b6eff09..32b2466aa7 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientGenerators_Incompatibilities.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientGenerators_Incompatibilities.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientModifiers_Incompatibilities.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientModifiers_Incompatibilities.py index 880f5ea04c..8ca5fed6eb 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientModifiers_Incompatibilities.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientModifiers_Incompatibilities.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin.py index 006e257cdd..0ca5fc2b9e 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_ClearingPinnedEntitySetsPreviewToOrigin.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_DefaultPinnedEntityIsSelf.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_DefaultPinnedEntityIsSelf.py index 9e078543a5..417441a92f 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_DefaultPinnedEntityIsSelf.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientPreviewSettings_DefaultPinnedEntityIsSelf.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSampling_GradientReferencesAddRemoveSuccessfully.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSampling_GradientReferencesAddRemoveSuccessfully.py index 4d3f9d324f..e8c7433e43 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSampling_GradientReferencesAddRemoveSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSampling_GradientReferencesAddRemoveSuccessfully.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_ComponentDependencies.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_ComponentDependencies.py index 6696b1d83c..1d07917588 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_ComponentDependencies.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_ComponentDependencies.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py index 23a7bb9335..e54a3695d8 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientSurfaceTagEmitter_SurfaceTagsAddRemoveSuccessfully.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithExpectedGradients.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithExpectedGradients.py index 11ef85591f..fa1630a012 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithExpectedGradients.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithExpectedGradients.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithSpawners.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithSpawners.py index 5f080c001e..1b97deaf17 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithSpawners.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_ComponentIncompatibleWithSpawners.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_FrequencyZoomCanBeSetBeyondSliderRange.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_FrequencyZoomCanBeSetBeyondSliderRange.py index ec77933424..7535c27010 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_FrequencyZoomCanBeSetBeyondSliderRange.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_FrequencyZoomCanBeSetBeyondSliderRange.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_RequiresShape.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_RequiresShape.py index 2c47d8306b..b5b9496d1e 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_RequiresShape.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/GradientTransform_RequiresShape.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_ProcessedImageAssignedSuccessfully.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_ProcessedImageAssignedSuccessfully.py index 76a977f9eb..c9e9d0504e 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_ProcessedImageAssignedSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_ProcessedImageAssignedSuccessfully.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_RequiresShape.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_RequiresShape.py index 83c8798ecd..8a57c3107b 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_RequiresShape.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/EditorScripts/ImageGradient_RequiresShape.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/__init__.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/__init__.py index ce5bb8503d..99aac69543 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientIncompatibilities.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientIncompatibilities.py index 4fa705f808..2187990ca4 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientIncompatibilities.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientIncompatibilities.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientPreviewSettings.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientPreviewSettings.py index 8c681afd5e..caaa480910 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientPreviewSettings.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientPreviewSettings.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientSampling.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientSampling.py index b760bdb7a2..4aeb8c170e 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientSampling.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientSampling.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientSurfaceTagEmitter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientSurfaceTagEmitter.py index ee377de2e7..473d0170d8 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientSurfaceTagEmitter.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientSurfaceTagEmitter.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientTransform.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientTransform.py index bea751998b..e71592ea58 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientTransform.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_GradientTransform.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_ImageGradient.py b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_ImageGradient.py index 93497766c9..07807c7dd5 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_ImageGradient.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/gradient_signal/test_ImageGradient.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_DependentComponentsAdded.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_DependentComponentsAdded.py index 08401213dc..a772e070f1 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_DependentComponentsAdded.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_DependentComponentsAdded.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityCreatedOnNodeAdd.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityCreatedOnNodeAdd.py index 132c57eb80..4c99ea63c2 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityCreatedOnNodeAdd.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityCreatedOnNodeAdd.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityRemovedOnNodeDelete.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityRemovedOnNodeDelete.py index 0843bac3f8..3a01684979 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityRemovedOnNodeDelete.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/AreaNodes_EntityRemovedOnNodeDelete.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ComponentUpdates_UpdateGraph.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ComponentUpdates_UpdateGraph.py index 0797e5f005..9a6689a548 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ComponentUpdates_UpdateGraph.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ComponentUpdates_UpdateGraph.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/CreateNewGraph.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/CreateNewGraph.py index c01b2552c6..a6d43821e3 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/CreateNewGraph.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/CreateNewGraph.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_DisabledNodeDuplication.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_DisabledNodeDuplication.py index 2593e7413e..63e5e7558f 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_DisabledNodeDuplication.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_DisabledNodeDuplication.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_UndoNodeDelete_SliceEntity.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_UndoNodeDelete_SliceEntity.py index aa641cb722..71ec206b7f 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_UndoNodeDelete_SliceEntity.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/Edit_UndoNodeDelete_SliceEntity.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientMixer_NodeConstruction.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientMixer_NodeConstruction.py index c79cc92fd1..ba48796251 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientMixer_NodeConstruction.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientMixer_NodeConstruction.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityCreatedOnNodeAdd.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityCreatedOnNodeAdd.py index dafedc07d1..c57f3a0e67 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityCreatedOnNodeAdd.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityCreatedOnNodeAdd.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityRemovedOnNodeDelete.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityRemovedOnNodeDelete.py index 9938fcb1f5..0e1538ac7c 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityRemovedOnNodeDelete.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientModifierNodes_EntityRemovedOnNodeDelete.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_DependentComponentsAdded.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_DependentComponentsAdded.py index a931d253db..0a25d60819 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_DependentComponentsAdded.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_DependentComponentsAdded.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityCreatedOnNodeAdd.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityCreatedOnNodeAdd.py index 9fe3f6f68b..17e23db160 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityCreatedOnNodeAdd.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityCreatedOnNodeAdd.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityRemovedOnNodeDelete.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityRemovedOnNodeDelete.py index a0f9745aa1..dc59938fea 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityRemovedOnNodeDelete.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GradientNodes_EntityRemovedOnNodeDelete.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnEntityDelete.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnEntityDelete.py index 136ce16735..b536c2daa3 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnEntityDelete.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnEntityDelete.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnLevelChange.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnLevelChange.py index 3f3317869c..2d6d5c0937 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnLevelChange.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_OnLevelChange.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_TabbedGraph.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_TabbedGraph.py index 8d7eb3bee7..2452101d21 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_TabbedGraph.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphClosed_TabbedGraph.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphUpdates_UpdateComponents.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphUpdates_UpdateComponents.py index d2b8727663..780ac1ca7a 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphUpdates_UpdateComponents.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/GraphUpdates_UpdateComponents.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvasComponent_AddedRemoved.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvasComponent_AddedRemoved.py index 5d20577fa9..ac12d84914 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvasComponent_AddedRemoved.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvasComponent_AddedRemoved.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvas_SliceCreateInstantiate.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvas_SliceCreateInstantiate.py index f8ec6650b4..0996c832fe 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvas_SliceCreateInstantiate.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LandscapeCanvas_SliceCreateInstantiate.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerBlender_NodeConstruction.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerBlender_NodeConstruction.py index 7b1126e548..9ee23b58ff 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerBlender_NodeConstruction.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerBlender_NodeConstruction.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerExtenderNodes_ComponentEntitySync.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerExtenderNodes_ComponentEntitySync.py index f2e132e821..5a4bbed8dc 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerExtenderNodes_ComponentEntitySync.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/LayerExtenderNodes_ComponentEntitySync.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityCreatedOnNodeAdd.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityCreatedOnNodeAdd.py index 5efea232f1..559ba91a25 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityCreatedOnNodeAdd.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityCreatedOnNodeAdd.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityRemovedOnNodeDelete.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityRemovedOnNodeDelete.py index 586119c6f5..f2bb5da674 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityRemovedOnNodeDelete.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/ShapeNodes_EntityRemovedOnNodeDelete.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/SlotConnections_UpdateComponentReferences.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/SlotConnections_UpdateComponentReferences.py index 98c58d6eb6..1f6ffc5926 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/SlotConnections_UpdateComponentReferences.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/SlotConnections_UpdateComponentReferences.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/__init__.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/__init__.py index ce5bb8503d..99aac69543 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/EditorScripts/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/__init__.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/__init__.py index ce5bb8503d..99aac69543 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_AreaNodes.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_AreaNodes.py index 23f2ad0b79..633999205c 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_AreaNodes.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_AreaNodes.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_EditFunctionality.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_EditFunctionality.py index 8619a2dcf4..bb3e1ea81c 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_EditFunctionality.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_EditFunctionality.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py index 0edafe731a..bbca71461c 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GeneralGraphFunctionality.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GradientModifierNodes.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GradientModifierNodes.py index 3335cc5229..7f5e0625c5 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GradientModifierNodes.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GradientModifierNodes.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GradientNodes.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GradientNodes.py index 8aa1da1ff5..b66203c2e2 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GradientNodes.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GradientNodes.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GraphComponentSync.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GraphComponentSync.py index bcb023a830..d5036b24bf 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GraphComponentSync.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_GraphComponentSync.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_ShapeNodes.py b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_ShapeNodes.py index d5a0530903..fceba3de20 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_ShapeNodes.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/landscape_canvas/test_ShapeNodes.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/large_worlds_utils/__init__.py b/AutomatedTesting/Gem/PythonTests/largeworlds/large_worlds_utils/__init__.py index ce5bb8503d..99aac69543 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/large_worlds_utils/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/large_worlds_utils/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/large_worlds_utils/editor_dynveg_test_helper.py b/AutomatedTesting/Gem/PythonTests/largeworlds/large_worlds_utils/editor_dynveg_test_helper.py index 99d9717707..515009cb3a 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/large_worlds_utils/editor_dynveg_test_helper.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/large_worlds_utils/editor_dynveg_test_helper.py @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/physics/AddModifyDelete_Utils.py b/AutomatedTesting/Gem/PythonTests/physics/AddModifyDelete_Utils.py index f812347602..aa62b365c6 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/AddModifyDelete_Utils.py +++ b/AutomatedTesting/Gem/PythonTests/physics/AddModifyDelete_Utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C100000_RigidBody_EnablingGravityWorksPoC.py b/AutomatedTesting/Gem/PythonTests/physics/C100000_RigidBody_EnablingGravityWorksPoC.py index 5b07b285ce..2784e10bb8 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C100000_RigidBody_EnablingGravityWorksPoC.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C100000_RigidBody_EnablingGravityWorksPoC.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C111111_RigidBody_EnablingGravityWorksUsingNotificationsPoC.py b/AutomatedTesting/Gem/PythonTests/physics/C111111_RigidBody_EnablingGravityWorksUsingNotificationsPoC.py index aff3a6f0c6..bec80b64d0 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C111111_RigidBody_EnablingGravityWorksUsingNotificationsPoC.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C111111_RigidBody_EnablingGravityWorksUsingNotificationsPoC.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C12712452_ScriptCanvas_CollisionEvents.py b/AutomatedTesting/Gem/PythonTests/physics/C12712452_ScriptCanvas_CollisionEvents.py index 89f74c8d5c..b6d2b4db99 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C12712452_ScriptCanvas_CollisionEvents.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C12712452_ScriptCanvas_CollisionEvents.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C12712453_ScriptCanvas_MultipleRaycastNode.py b/AutomatedTesting/Gem/PythonTests/physics/C12712453_ScriptCanvas_MultipleRaycastNode.py index 0baa1869ed..33b8688555 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C12712453_ScriptCanvas_MultipleRaycastNode.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C12712453_ScriptCanvas_MultipleRaycastNode.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C12712454_ScriptCanvas_OverlapNodeVerification.py b/AutomatedTesting/Gem/PythonTests/physics/C12712454_ScriptCanvas_OverlapNodeVerification.py index f8c0ad5401..ad90d3520a 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C12712454_ScriptCanvas_OverlapNodeVerification.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C12712454_ScriptCanvas_OverlapNodeVerification.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C12712455_ScriptCanvas_ShapeCastVerification.py b/AutomatedTesting/Gem/PythonTests/physics/C12712455_ScriptCanvas_ShapeCastVerification.py index 6a95371f4c..4554c1035e 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C12712455_ScriptCanvas_ShapeCastVerification.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C12712455_ScriptCanvas_ShapeCastVerification.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C12868578_ForceRegion_DirectionHasNoAffectOnMagnitude.py b/AutomatedTesting/Gem/PythonTests/physics/C12868578_ForceRegion_DirectionHasNoAffectOnMagnitude.py index e28261feac..fb3f31f070 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C12868578_ForceRegion_DirectionHasNoAffectOnMagnitude.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C12868578_ForceRegion_DirectionHasNoAffectOnMagnitude.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C12868580_ForceRegion_SplineModifiedTransform.py b/AutomatedTesting/Gem/PythonTests/physics/C12868580_ForceRegion_SplineModifiedTransform.py index d037e81ac9..94b4643d9d 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C12868580_ForceRegion_SplineModifiedTransform.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C12868580_ForceRegion_SplineModifiedTransform.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C12905527_ForceRegion_MagnitudeDeviation.py b/AutomatedTesting/Gem/PythonTests/physics/C12905527_ForceRegion_MagnitudeDeviation.py index 88210bf007..655952c797 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C12905527_ForceRegion_MagnitudeDeviation.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C12905527_ForceRegion_MagnitudeDeviation.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C12905528_ForceRegion_WithNonTriggerCollider.py b/AutomatedTesting/Gem/PythonTests/physics/C12905528_ForceRegion_WithNonTriggerCollider.py index 106b0db99f..2fc72f6a3b 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C12905528_ForceRegion_WithNonTriggerCollider.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C12905528_ForceRegion_WithNonTriggerCollider.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C13351703_COM_NotIncludeTriggerShapes.py b/AutomatedTesting/Gem/PythonTests/physics/C13351703_COM_NotIncludeTriggerShapes.py index 81a786f8ff..25a875ff08 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C13351703_COM_NotIncludeTriggerShapes.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C13351703_COM_NotIncludeTriggerShapes.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C13352089_RigidBodies_MaxAngularVelocity.py b/AutomatedTesting/Gem/PythonTests/physics/C13352089_RigidBodies_MaxAngularVelocity.py index 38578cbdba..27dbb33f29 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C13352089_RigidBodies_MaxAngularVelocity.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C13352089_RigidBodies_MaxAngularVelocity.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C13508019_Terrain_TerrainTexturePainterWorks.py b/AutomatedTesting/Gem/PythonTests/physics/C13508019_Terrain_TerrainTexturePainterWorks.py index fb135cd332..f4c6c635be 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C13508019_Terrain_TerrainTexturePainterWorks.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C13508019_Terrain_TerrainTexturePainterWorks.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C13895144_Ragdoll_ChangeLevel.py b/AutomatedTesting/Gem/PythonTests/physics/C13895144_Ragdoll_ChangeLevel.py index c21c22f054..21ad19b7db 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C13895144_Ragdoll_ChangeLevel.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C13895144_Ragdoll_ChangeLevel.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C14195074_ScriptCanvas_PostUpdateEvent.py b/AutomatedTesting/Gem/PythonTests/physics/C14195074_ScriptCanvas_PostUpdateEvent.py index a07e5a87df..0d5cc6c5b1 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C14195074_ScriptCanvas_PostUpdateEvent.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C14195074_ScriptCanvas_PostUpdateEvent.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C14654881_CharacterController_SwitchLevels.py b/AutomatedTesting/Gem/PythonTests/physics/C14654881_CharacterController_SwitchLevels.py index a3f0eec073..be6480cd17 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C14654881_CharacterController_SwitchLevels.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C14654881_CharacterController_SwitchLevels.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C14654882_Ragdoll_ragdollAPTest.py b/AutomatedTesting/Gem/PythonTests/physics/C14654882_Ragdoll_ragdollAPTest.py index a5d3935e05..bccd7fd232 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C14654882_Ragdoll_ragdollAPTest.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C14654882_Ragdoll_ragdollAPTest.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C14861498_ConfirmError_NoPxMesh.py b/AutomatedTesting/Gem/PythonTests/physics/C14861498_ConfirmError_NoPxMesh.py index d12b1e2efc..0506390409 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C14861498_ConfirmError_NoPxMesh.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C14861498_ConfirmError_NoPxMesh.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C14861500_DefaultSetting_ColliderShape.py b/AutomatedTesting/Gem/PythonTests/physics/C14861500_DefaultSetting_ColliderShape.py index 5525883839..f9e410f926 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C14861500_DefaultSetting_ColliderShape.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C14861500_DefaultSetting_ColliderShape.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C14861501_PhysXCollider_RenderMeshAutoAssigned.py b/AutomatedTesting/Gem/PythonTests/physics/C14861501_PhysXCollider_RenderMeshAutoAssigned.py index 3c99f35870..afa0173583 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C14861501_PhysXCollider_RenderMeshAutoAssigned.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C14861501_PhysXCollider_RenderMeshAutoAssigned.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C14861502_PhysXCollider_AssetAutoAssigned.py b/AutomatedTesting/Gem/PythonTests/physics/C14861502_PhysXCollider_AssetAutoAssigned.py index 6e7afc6e13..bd35678b07 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C14861502_PhysXCollider_AssetAutoAssigned.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C14861502_PhysXCollider_AssetAutoAssigned.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C14861504_RenderMeshAsset_WithNoPxAsset.py b/AutomatedTesting/Gem/PythonTests/physics/C14861504_RenderMeshAsset_WithNoPxAsset.py index 4d5413a93c..ba7512db0d 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C14861504_RenderMeshAsset_WithNoPxAsset.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C14861504_RenderMeshAsset_WithNoPxAsset.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C14902097_ScriptCanvas_PreUpdateEvent.py b/AutomatedTesting/Gem/PythonTests/physics/C14902097_ScriptCanvas_PreUpdateEvent.py index 119de51ca1..e04d744314 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C14902097_ScriptCanvas_PreUpdateEvent.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C14902097_ScriptCanvas_PreUpdateEvent.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C14902098_ScriptCanvas_PostPhysicsUpdate.py b/AutomatedTesting/Gem/PythonTests/physics/C14902098_ScriptCanvas_PostPhysicsUpdate.py index 05fd44cfe0..c3bd1207ec 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C14902098_ScriptCanvas_PostPhysicsUpdate.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C14902098_ScriptCanvas_PostPhysicsUpdate.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C14976307_Gravity_SetGravityWorks.py b/AutomatedTesting/Gem/PythonTests/physics/C14976307_Gravity_SetGravityWorks.py index a72091942d..6255a0403a 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C14976307_Gravity_SetGravityWorks.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C14976307_Gravity_SetGravityWorks.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C14976308_ScriptCanvas_SetKinematicTargetTransform.py b/AutomatedTesting/Gem/PythonTests/physics/C14976308_ScriptCanvas_SetKinematicTargetTransform.py index b9fd33f178..f0c53968a8 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C14976308_ScriptCanvas_SetKinematicTargetTransform.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C14976308_ScriptCanvas_SetKinematicTargetTransform.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C15096732_Material_DefaultLibraryUpdatedAcrossLevels_after.py b/AutomatedTesting/Gem/PythonTests/physics/C15096732_Material_DefaultLibraryUpdatedAcrossLevels_after.py index dcd789a697..ec71dbb8a3 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C15096732_Material_DefaultLibraryUpdatedAcrossLevels_after.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C15096732_Material_DefaultLibraryUpdatedAcrossLevels_after.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C15096732_Material_DefaultLibraryUpdatedAcrossLevels_before.py b/AutomatedTesting/Gem/PythonTests/physics/C15096732_Material_DefaultLibraryUpdatedAcrossLevels_before.py index ef1351f32a..b774932802 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C15096732_Material_DefaultLibraryUpdatedAcrossLevels_before.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C15096732_Material_DefaultLibraryUpdatedAcrossLevels_before.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C15096735_Materials_DefaultLibraryConsistency.py b/AutomatedTesting/Gem/PythonTests/physics/C15096735_Materials_DefaultLibraryConsistency.py index eac8a5080e..10a47058d7 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C15096735_Materials_DefaultLibraryConsistency.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C15096735_Materials_DefaultLibraryConsistency.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C15096737_Materials_DefaultMaterialLibraryChanges.py b/AutomatedTesting/Gem/PythonTests/physics/C15096737_Materials_DefaultMaterialLibraryChanges.py index 76bf1f5db8..6614e8b0da 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C15096737_Materials_DefaultMaterialLibraryChanges.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C15096737_Materials_DefaultMaterialLibraryChanges.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C15096740_Material_LibraryUpdatedCorrectly.py b/AutomatedTesting/Gem/PythonTests/physics/C15096740_Material_LibraryUpdatedCorrectly.py index d60aa4e467..21b345e6be 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C15096740_Material_LibraryUpdatedCorrectly.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C15096740_Material_LibraryUpdatedCorrectly.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C15308217_NoCrash_LevelSwitch.py b/AutomatedTesting/Gem/PythonTests/physics/C15308217_NoCrash_LevelSwitch.py index 23344bbbd6..f0a40aadb5 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C15308217_NoCrash_LevelSwitch.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C15308217_NoCrash_LevelSwitch.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C15308221_Material_ComponentsInSyncWithLibrary.py b/AutomatedTesting/Gem/PythonTests/physics/C15308221_Material_ComponentsInSyncWithLibrary.py index 5e7143ea2d..1ff9659eff 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C15308221_Material_ComponentsInSyncWithLibrary.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C15308221_Material_ComponentsInSyncWithLibrary.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C15425929_Undo_Redo.py b/AutomatedTesting/Gem/PythonTests/physics/C15425929_Undo_Redo.py index 8978194da7..d8044fed85 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C15425929_Undo_Redo.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C15425929_Undo_Redo.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C15425935_Material_LibraryUpdatedAcrossLevels.py b/AutomatedTesting/Gem/PythonTests/physics/C15425935_Material_LibraryUpdatedAcrossLevels.py index 1093c04b72..689319e767 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C15425935_Material_LibraryUpdatedAcrossLevels.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C15425935_Material_LibraryUpdatedAcrossLevels.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C15556261_PhysXMaterials_CharacterControllerMaterialAssignment.py b/AutomatedTesting/Gem/PythonTests/physics/C15556261_PhysXMaterials_CharacterControllerMaterialAssignment.py index 0e088451fa..4ee2969bfd 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C15556261_PhysXMaterials_CharacterControllerMaterialAssignment.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C15556261_PhysXMaterials_CharacterControllerMaterialAssignment.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C15563573_Material_AddModifyDeleteOnCharacterController.py b/AutomatedTesting/Gem/PythonTests/physics/C15563573_Material_AddModifyDeleteOnCharacterController.py index 3363d27a72..bc2fc7855a 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C15563573_Material_AddModifyDeleteOnCharacterController.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C15563573_Material_AddModifyDeleteOnCharacterController.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C15845879_ForceRegion_HighLinearDampingForce.py b/AutomatedTesting/Gem/PythonTests/physics/C15845879_ForceRegion_HighLinearDampingForce.py index 990acb3a9e..63bf163bb8 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C15845879_ForceRegion_HighLinearDampingForce.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C15845879_ForceRegion_HighLinearDampingForce.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C17411467_AddPhysxRagdollComponent.py b/AutomatedTesting/Gem/PythonTests/physics/C17411467_AddPhysxRagdollComponent.py index 147c447514..b5a74ecb26 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C17411467_AddPhysxRagdollComponent.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C17411467_AddPhysxRagdollComponent.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243580_Joints_Fixed2BodiesConstrained.py b/AutomatedTesting/Gem/PythonTests/physics/C18243580_Joints_Fixed2BodiesConstrained.py index 181e60c00c..82887a58bb 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243580_Joints_Fixed2BodiesConstrained.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243580_Joints_Fixed2BodiesConstrained.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243581_Joints_FixedBreakable.py b/AutomatedTesting/Gem/PythonTests/physics/C18243581_Joints_FixedBreakable.py index 9125ae3c77..645468ea07 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243581_Joints_FixedBreakable.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243581_Joints_FixedBreakable.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243582_Joints_FixedLeadFollowerCollide.py b/AutomatedTesting/Gem/PythonTests/physics/C18243582_Joints_FixedLeadFollowerCollide.py index afa146be29..3f26bd398b 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243582_Joints_FixedLeadFollowerCollide.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243582_Joints_FixedLeadFollowerCollide.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243583_Joints_Hinge2BodiesConstrained.py b/AutomatedTesting/Gem/PythonTests/physics/C18243583_Joints_Hinge2BodiesConstrained.py index 4aa2a62513..34876aa2ba 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243583_Joints_Hinge2BodiesConstrained.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243583_Joints_Hinge2BodiesConstrained.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243584_Joints_HingeSoftLimitsConstrained.py b/AutomatedTesting/Gem/PythonTests/physics/C18243584_Joints_HingeSoftLimitsConstrained.py index f6598dc871..76a7b912df 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243584_Joints_HingeSoftLimitsConstrained.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243584_Joints_HingeSoftLimitsConstrained.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243585_Joints_HingeNoLimitsConstrained.py b/AutomatedTesting/Gem/PythonTests/physics/C18243585_Joints_HingeNoLimitsConstrained.py index 34ed26a1f8..c9c5b57d7f 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243585_Joints_HingeNoLimitsConstrained.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243585_Joints_HingeNoLimitsConstrained.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243586_Joints_HingeLeadFollowerCollide.py b/AutomatedTesting/Gem/PythonTests/physics/C18243586_Joints_HingeLeadFollowerCollide.py index 434fe933f0..173b8a4206 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243586_Joints_HingeLeadFollowerCollide.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243586_Joints_HingeLeadFollowerCollide.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243587_Joints_HingeBreakable.py b/AutomatedTesting/Gem/PythonTests/physics/C18243587_Joints_HingeBreakable.py index 4bd97bd154..0a26ac4255 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243587_Joints_HingeBreakable.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243587_Joints_HingeBreakable.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243588_Joints_Ball2BodiesConstrained.py b/AutomatedTesting/Gem/PythonTests/physics/C18243588_Joints_Ball2BodiesConstrained.py index 500d6bd66e..67aba58945 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243588_Joints_Ball2BodiesConstrained.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243588_Joints_Ball2BodiesConstrained.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py b/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py index ec23149478..4ef72d982a 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243590_Joints_BallNoLimitsConstrained.py b/AutomatedTesting/Gem/PythonTests/physics/C18243590_Joints_BallNoLimitsConstrained.py index b27a5cb8e9..396dc590e3 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243590_Joints_BallNoLimitsConstrained.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243590_Joints_BallNoLimitsConstrained.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243591_Joints_BallLeadFollowerCollide.py b/AutomatedTesting/Gem/PythonTests/physics/C18243591_Joints_BallLeadFollowerCollide.py index 9a335f556b..9f5cf46c05 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243591_Joints_BallLeadFollowerCollide.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243591_Joints_BallLeadFollowerCollide.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243592_Joints_BallBreakable.py b/AutomatedTesting/Gem/PythonTests/physics/C18243592_Joints_BallBreakable.py index 312d0f3dbe..5d41ca47bd 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243592_Joints_BallBreakable.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243592_Joints_BallBreakable.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243593_Joints_GlobalFrameConstrained.py b/AutomatedTesting/Gem/PythonTests/physics/C18243593_Joints_GlobalFrameConstrained.py index ceecb0644e..d282e131bb 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243593_Joints_GlobalFrameConstrained.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243593_Joints_GlobalFrameConstrained.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18977601_Material_FrictionCombinePriority.py b/AutomatedTesting/Gem/PythonTests/physics/C18977601_Material_FrictionCombinePriority.py index 5a25b447da..ff3dc73435 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18977601_Material_FrictionCombinePriority.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18977601_Material_FrictionCombinePriority.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18981526_Material_RestitutionCombinePriority.py b/AutomatedTesting/Gem/PythonTests/physics/C18981526_Material_RestitutionCombinePriority.py index 9c91812f44..76396a6f44 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18981526_Material_RestitutionCombinePriority.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18981526_Material_RestitutionCombinePriority.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C19536274_GetCollisionName_PrintsName.py b/AutomatedTesting/Gem/PythonTests/physics/C19536274_GetCollisionName_PrintsName.py index 40c3edf578..350b2d5114 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C19536274_GetCollisionName_PrintsName.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C19536274_GetCollisionName_PrintsName.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C19536277_GetCollisionName_PrintsNothing.py b/AutomatedTesting/Gem/PythonTests/physics/C19536277_GetCollisionName_PrintsNothing.py index 6d6cf7c700..ad4245c53a 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C19536277_GetCollisionName_PrintsNothing.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C19536277_GetCollisionName_PrintsNothing.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C19578018_ShapeColliderWithNoShapeComponent.py b/AutomatedTesting/Gem/PythonTests/physics/C19578018_ShapeColliderWithNoShapeComponent.py index 3fcb8921be..b58d2a657e 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C19578018_ShapeColliderWithNoShapeComponent.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C19578018_ShapeColliderWithNoShapeComponent.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C19578021_ShapeCollider_CanBeAdded.py b/AutomatedTesting/Gem/PythonTests/physics/C19578021_ShapeCollider_CanBeAdded.py index 47d916a4bf..a793e453f5 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C19578021_ShapeCollider_CanBeAdded.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C19578021_ShapeCollider_CanBeAdded.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C19723164_ShapeColliders_WontCrashEditor.py b/AutomatedTesting/Gem/PythonTests/physics/C19723164_ShapeColliders_WontCrashEditor.py index 12f900b297..89fd62a147 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C19723164_ShapeColliders_WontCrashEditor.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C19723164_ShapeColliders_WontCrashEditor.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py b/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py index bb2d0821cb..940a6d3bca 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C28978033_Ragdoll_WorldBodyBusTests.py b/AutomatedTesting/Gem/PythonTests/physics/C28978033_Ragdoll_WorldBodyBusTests.py index 5016d78b46..3ecde5cc51 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C28978033_Ragdoll_WorldBodyBusTests.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C28978033_Ragdoll_WorldBodyBusTests.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C29032500_EditorComponents_WorldBodyBusWorks.py b/AutomatedTesting/Gem/PythonTests/physics/C29032500_EditorComponents_WorldBodyBusWorks.py index 000223e26d..96f4c70643 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C29032500_EditorComponents_WorldBodyBusWorks.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C29032500_EditorComponents_WorldBodyBusWorks.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C3510642_Terrain_NotCollideWithTerrain.py b/AutomatedTesting/Gem/PythonTests/physics/C3510642_Terrain_NotCollideWithTerrain.py index 66d6131ad0..f225ee1422 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C3510642_Terrain_NotCollideWithTerrain.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C3510642_Terrain_NotCollideWithTerrain.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C3510644_Collider_CollisionGroups.py b/AutomatedTesting/Gem/PythonTests/physics/C3510644_Collider_CollisionGroups.py index 4a2c6e0704..76cb34a1eb 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C3510644_Collider_CollisionGroups.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C3510644_Collider_CollisionGroups.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4044455_Material_libraryChangesInstantly.py b/AutomatedTesting/Gem/PythonTests/physics/C4044455_Material_libraryChangesInstantly.py index 0a1b0b9f2f..b15999a1ae 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4044455_Material_libraryChangesInstantly.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4044455_Material_libraryChangesInstantly.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4044456_Material_FrictionCombine.py b/AutomatedTesting/Gem/PythonTests/physics/C4044456_Material_FrictionCombine.py index badf00832b..0ee96b1818 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4044456_Material_FrictionCombine.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4044456_Material_FrictionCombine.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4044457_Material_RestitutionCombine.py b/AutomatedTesting/Gem/PythonTests/physics/C4044457_Material_RestitutionCombine.py index a9dbcc0259..6c411d6227 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4044457_Material_RestitutionCombine.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4044457_Material_RestitutionCombine.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4044459_Material_DynamicFriction.py b/AutomatedTesting/Gem/PythonTests/physics/C4044459_Material_DynamicFriction.py index 0702de1758..54a7deb30e 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4044459_Material_DynamicFriction.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4044459_Material_DynamicFriction.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4044460_Material_StaticFriction.py b/AutomatedTesting/Gem/PythonTests/physics/C4044460_Material_StaticFriction.py index 5050504782..646ccfebad 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4044460_Material_StaticFriction.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4044460_Material_StaticFriction.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4044461_Material_Restitution.py b/AutomatedTesting/Gem/PythonTests/physics/C4044461_Material_Restitution.py index a115e4f3ee..38f0122e7d 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4044461_Material_Restitution.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4044461_Material_Restitution.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4044694_Material_EmptyLibraryUsesDefault.py b/AutomatedTesting/Gem/PythonTests/physics/C4044694_Material_EmptyLibraryUsesDefault.py index cfc1e706e4..afee06a4e5 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4044694_Material_EmptyLibraryUsesDefault.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4044694_Material_EmptyLibraryUsesDefault.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4044695_PhysXCollider_AddMultipleSurfaceFbx.py b/AutomatedTesting/Gem/PythonTests/physics/C4044695_PhysXCollider_AddMultipleSurfaceFbx.py index 450763ba1e..b562201e73 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4044695_PhysXCollider_AddMultipleSurfaceFbx.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4044695_PhysXCollider_AddMultipleSurfaceFbx.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4044697_Material_PerfaceMaterialValidation.py b/AutomatedTesting/Gem/PythonTests/physics/C4044697_Material_PerfaceMaterialValidation.py index a4b2c2f5cd..f95f8a5230 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4044697_Material_PerfaceMaterialValidation.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4044697_Material_PerfaceMaterialValidation.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4888315_Material_AddModifyDeleteOnCollider.py b/AutomatedTesting/Gem/PythonTests/physics/C4888315_Material_AddModifyDeleteOnCollider.py index 52f62f0d0c..8481548735 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4888315_Material_AddModifyDeleteOnCollider.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4888315_Material_AddModifyDeleteOnCollider.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4925577_Materials_MaterialAssignedToTerrain.py b/AutomatedTesting/Gem/PythonTests/physics/C4925577_Materials_MaterialAssignedToTerrain.py index e30f640d48..9d18131504 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4925577_Materials_MaterialAssignedToTerrain.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4925577_Materials_MaterialAssignedToTerrain.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4925579_Material_AddModifyDeleteOnTerrain.py b/AutomatedTesting/Gem/PythonTests/physics/C4925579_Material_AddModifyDeleteOnTerrain.py index fe44d124a6..f37c1d065e 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4925579_Material_AddModifyDeleteOnTerrain.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4925579_Material_AddModifyDeleteOnTerrain.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4925580_Material_RagdollBonesMaterial.py b/AutomatedTesting/Gem/PythonTests/physics/C4925580_Material_RagdollBonesMaterial.py index c44a606cfc..477648da4c 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4925580_Material_RagdollBonesMaterial.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4925580_Material_RagdollBonesMaterial.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4925582_Material_AddModifyDeleteOnRagdollBones.py b/AutomatedTesting/Gem/PythonTests/physics/C4925582_Material_AddModifyDeleteOnRagdollBones.py index dd68521df9..4f661886d3 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4925582_Material_AddModifyDeleteOnRagdollBones.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4925582_Material_AddModifyDeleteOnRagdollBones.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976194_RigidBody_PhysXComponentIsValid.py b/AutomatedTesting/Gem/PythonTests/physics/C4976194_RigidBody_PhysXComponentIsValid.py index 53ece4ab19..d633207d7f 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976194_RigidBody_PhysXComponentIsValid.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976194_RigidBody_PhysXComponentIsValid.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976195_RigidBodies_InitialLinearVelocity.py b/AutomatedTesting/Gem/PythonTests/physics/C4976195_RigidBodies_InitialLinearVelocity.py index 27b024eb8a..7123ac66d6 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976195_RigidBodies_InitialLinearVelocity.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976195_RigidBodies_InitialLinearVelocity.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976197_RigidBodies_InitialAngularVelocity.py b/AutomatedTesting/Gem/PythonTests/physics/C4976197_RigidBodies_InitialAngularVelocity.py index 0ebd4ae010..cc24bc8390 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976197_RigidBodies_InitialAngularVelocity.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976197_RigidBodies_InitialAngularVelocity.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976199_RigidBodies_LinearDampingObjectMotion.py b/AutomatedTesting/Gem/PythonTests/physics/C4976199_RigidBodies_LinearDampingObjectMotion.py index 82e5a4fc63..2dba8d174a 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976199_RigidBodies_LinearDampingObjectMotion.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976199_RigidBodies_LinearDampingObjectMotion.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976200_RigidBody_AngularDampingObjectRotation.py b/AutomatedTesting/Gem/PythonTests/physics/C4976200_RigidBody_AngularDampingObjectRotation.py index 5b525a4ebd..f7c88f0645 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976200_RigidBody_AngularDampingObjectRotation.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976200_RigidBody_AngularDampingObjectRotation.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976201_RigidBody_MassIsAssigned.py b/AutomatedTesting/Gem/PythonTests/physics/C4976201_RigidBody_MassIsAssigned.py index fd6c9a9647..3b17283309 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976201_RigidBody_MassIsAssigned.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976201_RigidBody_MassIsAssigned.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976202_RigidBody_StopsWhenBelowKineticThreshold.py b/AutomatedTesting/Gem/PythonTests/physics/C4976202_RigidBody_StopsWhenBelowKineticThreshold.py index 30a43f34a6..13d06a3599 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976202_RigidBody_StopsWhenBelowKineticThreshold.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976202_RigidBody_StopsWhenBelowKineticThreshold.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976204_Verify_Start_Asleep_Condition.py b/AutomatedTesting/Gem/PythonTests/physics/C4976204_Verify_Start_Asleep_Condition.py index 8c2ae7cb8b..8193aa4440 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976204_Verify_Start_Asleep_Condition.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976204_Verify_Start_Asleep_Condition.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976206_RigidBodies_GravityEnabledActive.py b/AutomatedTesting/Gem/PythonTests/physics/C4976206_RigidBodies_GravityEnabledActive.py index 1adeeb45dc..394c8466e7 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976206_RigidBodies_GravityEnabledActive.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976206_RigidBodies_GravityEnabledActive.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976207_PhysXRigidBodies_KinematicBehavior.py b/AutomatedTesting/Gem/PythonTests/physics/C4976207_PhysXRigidBodies_KinematicBehavior.py index 1e52521e0d..ddd87a1800 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976207_PhysXRigidBodies_KinematicBehavior.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976207_PhysXRigidBodies_KinematicBehavior.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976209_RigidBody_ComputesCOM.py b/AutomatedTesting/Gem/PythonTests/physics/C4976209_RigidBody_ComputesCOM.py index cc72f7dc89..9591f88175 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976209_RigidBody_ComputesCOM.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976209_RigidBody_ComputesCOM.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976210_COM_ManualSetting.py b/AutomatedTesting/Gem/PythonTests/physics/C4976210_COM_ManualSetting.py index 2950cebcaa..5769f5af09 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976210_COM_ManualSetting.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976210_COM_ManualSetting.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976218_RigidBodies_InertiaObjectsNotComputed.py b/AutomatedTesting/Gem/PythonTests/physics/C4976218_RigidBodies_InertiaObjectsNotComputed.py index f6ee61e63f..02b676a56d 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976218_RigidBodies_InertiaObjectsNotComputed.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976218_RigidBodies_InertiaObjectsNotComputed.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976227_Collider_NewGroup.py b/AutomatedTesting/Gem/PythonTests/physics/C4976227_Collider_NewGroup.py index 0ea4881198..24a15cf656 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976227_Collider_NewGroup.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976227_Collider_NewGroup.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976236_AddPhysxColliderComponent.py b/AutomatedTesting/Gem/PythonTests/physics/C4976236_AddPhysxColliderComponent.py index baef392352..238d2cd346 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976236_AddPhysxColliderComponent.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976236_AddPhysxColliderComponent.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976242_Collision_SameCollisionlayerSameCollisiongroup.py b/AutomatedTesting/Gem/PythonTests/physics/C4976242_Collision_SameCollisionlayerSameCollisiongroup.py index 9a2f0bd7ad..e89c9fc605 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976242_Collision_SameCollisionlayerSameCollisiongroup.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976242_Collision_SameCollisionlayerSameCollisiongroup.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976243_Collision_SameCollisionGroupDiffCollisionLayers.py b/AutomatedTesting/Gem/PythonTests/physics/C4976243_Collision_SameCollisionGroupDiffCollisionLayers.py index 196efd0be0..33b9060032 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976243_Collision_SameCollisionGroupDiffCollisionLayers.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976243_Collision_SameCollisionGroupDiffCollisionLayers.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976244_Collider_SameGroupSameLayerCollision.py b/AutomatedTesting/Gem/PythonTests/physics/C4976244_Collider_SameGroupSameLayerCollision.py index 50f7ceacea..643bf3fe52 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976244_Collider_SameGroupSameLayerCollision.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976244_Collider_SameGroupSameLayerCollision.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4976245_PhysXCollider_CollisionLayerTest.py b/AutomatedTesting/Gem/PythonTests/physics/C4976245_PhysXCollider_CollisionLayerTest.py index 6701fdba06..5b8c23f702 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4976245_PhysXCollider_CollisionLayerTest.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4976245_PhysXCollider_CollisionLayerTest.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4982593_PhysXCollider_CollisionLayerTest.py b/AutomatedTesting/Gem/PythonTests/physics/C4982593_PhysXCollider_CollisionLayerTest.py index 29d9e372bb..8d18f5adb9 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4982593_PhysXCollider_CollisionLayerTest.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4982593_PhysXCollider_CollisionLayerTest.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4982595_Collider_TriggerDisablesCollision.py b/AutomatedTesting/Gem/PythonTests/physics/C4982595_Collider_TriggerDisablesCollision.py index 08f0f0ca58..094db2350a 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4982595_Collider_TriggerDisablesCollision.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4982595_Collider_TriggerDisablesCollision.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4982797_Collider_ColliderOffset.py b/AutomatedTesting/Gem/PythonTests/physics/C4982797_Collider_ColliderOffset.py index 61480afa51..d5b3ef2235 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4982797_Collider_ColliderOffset.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4982797_Collider_ColliderOffset.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4982798_Collider_ColliderRotationOffset.py b/AutomatedTesting/Gem/PythonTests/physics/C4982798_Collider_ColliderRotationOffset.py index 3c7c4939ba..9a90d9487d 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4982798_Collider_ColliderRotationOffset.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4982798_Collider_ColliderRotationOffset.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4982800_PhysXColliderShape_CanBeSelected.py b/AutomatedTesting/Gem/PythonTests/physics/C4982800_PhysXColliderShape_CanBeSelected.py index 2cebd5f195..f7a033e71b 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4982800_PhysXColliderShape_CanBeSelected.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4982800_PhysXColliderShape_CanBeSelected.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4982801_PhysXColliderShape_CanBeSelected.py b/AutomatedTesting/Gem/PythonTests/physics/C4982801_PhysXColliderShape_CanBeSelected.py index b231b68e62..dc07dd9b5b 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4982801_PhysXColliderShape_CanBeSelected.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4982801_PhysXColliderShape_CanBeSelected.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4982802_PhysXColliderShape_CanBeSelected.py b/AutomatedTesting/Gem/PythonTests/physics/C4982802_PhysXColliderShape_CanBeSelected.py index 2a22460a02..3995adeb23 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4982802_PhysXColliderShape_CanBeSelected.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4982802_PhysXColliderShape_CanBeSelected.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C4982803_Enable_PxMesh_Option.py b/AutomatedTesting/Gem/PythonTests/physics/C4982803_Enable_PxMesh_Option.py index 2b0ab6e118..3ddf222fa3 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C4982803_Enable_PxMesh_Option.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C4982803_Enable_PxMesh_Option.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5296614_PhysXMaterial_ColliderShape.py b/AutomatedTesting/Gem/PythonTests/physics/C5296614_PhysXMaterial_ColliderShape.py index 28c5f71f2e..f758c75f2b 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5296614_PhysXMaterial_ColliderShape.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5296614_PhysXMaterial_ColliderShape.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5340400_RigidBody_ManualMomentOfInertia.py b/AutomatedTesting/Gem/PythonTests/physics/C5340400_RigidBody_ManualMomentOfInertia.py index e81c3cfe26..b8694efe2d 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5340400_RigidBody_ManualMomentOfInertia.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5340400_RigidBody_ManualMomentOfInertia.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5689518_PhysXTerrain_CollidesWithPhysXTerrain.py b/AutomatedTesting/Gem/PythonTests/physics/C5689518_PhysXTerrain_CollidesWithPhysXTerrain.py index 0bc268d8ee..31ece7beae 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5689518_PhysXTerrain_CollidesWithPhysXTerrain.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5689518_PhysXTerrain_CollidesWithPhysXTerrain.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5689522_Physxterrain_AddPhysxterrainNoEditorCrash.py b/AutomatedTesting/Gem/PythonTests/physics/C5689522_Physxterrain_AddPhysxterrainNoEditorCrash.py index 00eff5722c..b4a9115626 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5689522_Physxterrain_AddPhysxterrainNoEditorCrash.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5689522_Physxterrain_AddPhysxterrainNoEditorCrash.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5689524_MultipleTerrains_CheckWarningInConsole.py b/AutomatedTesting/Gem/PythonTests/physics/C5689524_MultipleTerrains_CheckWarningInConsole.py index 03c18ae017..b4c7901c52 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5689524_MultipleTerrains_CheckWarningInConsole.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5689524_MultipleTerrains_CheckWarningInConsole.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5689528_Terrain_MultipleTerrainComponents.py b/AutomatedTesting/Gem/PythonTests/physics/C5689528_Terrain_MultipleTerrainComponents.py index 47ea3b94b6..c0d245075e 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5689528_Terrain_MultipleTerrainComponents.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5689528_Terrain_MultipleTerrainComponents.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5689529_Verify_Terrain_RigidBody_Collider_Mesh.py b/AutomatedTesting/Gem/PythonTests/physics/C5689529_Verify_Terrain_RigidBody_Collider_Mesh.py index d2da06af69..b3ed10c69f 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5689529_Verify_Terrain_RigidBody_Collider_Mesh.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5689529_Verify_Terrain_RigidBody_Collider_Mesh.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5689531_Warning_TerrainSliceTerrainComponent.py b/AutomatedTesting/Gem/PythonTests/physics/C5689531_Warning_TerrainSliceTerrainComponent.py index cc43338e66..3935d213b4 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5689531_Warning_TerrainSliceTerrainComponent.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5689531_Warning_TerrainSliceTerrainComponent.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5932040_ForceRegion_CubeExertsWorldForce.py b/AutomatedTesting/Gem/PythonTests/physics/C5932040_ForceRegion_CubeExertsWorldForce.py index 4fc70612e4..ba4836eda1 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5932040_ForceRegion_CubeExertsWorldForce.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5932040_ForceRegion_CubeExertsWorldForce.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies.py b/AutomatedTesting/Gem/PythonTests/physics/C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies.py index f54ba0a891..0cbd82303d 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5932042_PhysXForceRegion_LinearDamping.py b/AutomatedTesting/Gem/PythonTests/physics/C5932042_PhysXForceRegion_LinearDamping.py index cc15b23b07..e48a8d3ef0 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5932042_PhysXForceRegion_LinearDamping.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5932042_PhysXForceRegion_LinearDamping.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5932043_ForceRegion_SimpleDragOnRigidBodies.py b/AutomatedTesting/Gem/PythonTests/physics/C5932043_ForceRegion_SimpleDragOnRigidBodies.py index c5cb305563..7975eaf036 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5932043_ForceRegion_SimpleDragOnRigidBodies.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5932043_ForceRegion_SimpleDragOnRigidBodies.py @@ -1,6 +1,6 @@ # coding=utf-8 """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5932044_ForceRegion_PointForceOnRigidBody.py b/AutomatedTesting/Gem/PythonTests/physics/C5932044_ForceRegion_PointForceOnRigidBody.py index ad104b2289..22c8fabb53 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5932044_ForceRegion_PointForceOnRigidBody.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5932044_ForceRegion_PointForceOnRigidBody.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5932045_ForceRegion_Spline.py b/AutomatedTesting/Gem/PythonTests/physics/C5932045_ForceRegion_Spline.py index cbc65529fc..4bec128c58 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5932045_ForceRegion_Spline.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5932045_ForceRegion_Spline.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5959759_RigidBody_ForceRegionSpherePointForce.py b/AutomatedTesting/Gem/PythonTests/physics/C5959759_RigidBody_ForceRegionSpherePointForce.py index 45eab62c8b..146a7bf456 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5959759_RigidBody_ForceRegionSpherePointForce.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5959759_RigidBody_ForceRegionSpherePointForce.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5959760_PhysXForceRegion_PointForceExertion.py b/AutomatedTesting/Gem/PythonTests/physics/C5959760_PhysXForceRegion_PointForceExertion.py index db341d0985..013edee626 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5959760_PhysXForceRegion_PointForceExertion.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5959760_PhysXForceRegion_PointForceExertion.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5959761_ForceRegion_PhysAssetExertsPointForce.py b/AutomatedTesting/Gem/PythonTests/physics/C5959761_ForceRegion_PhysAssetExertsPointForce.py index 2aa1584799..0e118d43a6 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5959761_ForceRegion_PhysAssetExertsPointForce.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5959761_ForceRegion_PhysAssetExertsPointForce.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5959763_ForceRegion_ForceRegionImpulsesCube.py b/AutomatedTesting/Gem/PythonTests/physics/C5959763_ForceRegion_ForceRegionImpulsesCube.py index 90e974e6d1..eb87e05c4d 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5959763_ForceRegion_ForceRegionImpulsesCube.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5959763_ForceRegion_ForceRegionImpulsesCube.py @@ -1,6 +1,6 @@ # coding=utf-8 """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5959764_ForceRegion_ForceRegionImpulsesCapsule.py b/AutomatedTesting/Gem/PythonTests/physics/C5959764_ForceRegion_ForceRegionImpulsesCapsule.py index 35742175c8..9a5271836d 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5959764_ForceRegion_ForceRegionImpulsesCapsule.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5959764_ForceRegion_ForceRegionImpulsesCapsule.py @@ -1,6 +1,6 @@ # coding=utf-8 """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5959765_ForceRegion_AssetGetsImpulsed.py b/AutomatedTesting/Gem/PythonTests/physics/C5959765_ForceRegion_AssetGetsImpulsed.py index 43e27d8467..ad198e346a 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5959765_ForceRegion_AssetGetsImpulsed.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5959765_ForceRegion_AssetGetsImpulsed.py @@ -1,6 +1,6 @@ # coding=utf-8 """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5959808_ForceRegion_PositionOffset.py b/AutomatedTesting/Gem/PythonTests/physics/C5959808_ForceRegion_PositionOffset.py index c7f336fe28..1b7962160a 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5959808_ForceRegion_PositionOffset.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5959808_ForceRegion_PositionOffset.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5959809_ForceRegion_RotationalOffset.py b/AutomatedTesting/Gem/PythonTests/physics/C5959809_ForceRegion_RotationalOffset.py index 53f1fa2bc6..bdcd128412 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5959809_ForceRegion_RotationalOffset.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5959809_ForceRegion_RotationalOffset.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5959810_ForceRegion_ForceRegionCombinesForces.py b/AutomatedTesting/Gem/PythonTests/physics/C5959810_ForceRegion_ForceRegionCombinesForces.py index 1879465576..4ee29d3d1a 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5959810_ForceRegion_ForceRegionCombinesForces.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5959810_ForceRegion_ForceRegionCombinesForces.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5968759_ForceRegion_ExertsSeveralForcesOnRigidBody.py b/AutomatedTesting/Gem/PythonTests/physics/C5968759_ForceRegion_ExertsSeveralForcesOnRigidBody.py index da6ef46e71..74a2a3e46e 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5968759_ForceRegion_ExertsSeveralForcesOnRigidBody.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5968759_ForceRegion_ExertsSeveralForcesOnRigidBody.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5968760_ForceRegion_CheckNetForceChange.py b/AutomatedTesting/Gem/PythonTests/physics/C5968760_ForceRegion_CheckNetForceChange.py index f10da33537..ed4019abe0 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5968760_ForceRegion_CheckNetForceChange.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5968760_ForceRegion_CheckNetForceChange.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C6032082_Terrain_MultipleResolutionsValid.py b/AutomatedTesting/Gem/PythonTests/physics/C6032082_Terrain_MultipleResolutionsValid.py index 2e7c132444..e4e6a8276c 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C6032082_Terrain_MultipleResolutionsValid.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C6032082_Terrain_MultipleResolutionsValid.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C6090546_ForceRegion_SliceFileInstantiates.py b/AutomatedTesting/Gem/PythonTests/physics/C6090546_ForceRegion_SliceFileInstantiates.py index ba73153fd0..9fdcd08d8f 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C6090546_ForceRegion_SliceFileInstantiates.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C6090546_ForceRegion_SliceFileInstantiates.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C6090547_ForceRegion_ParentChildForceRegions.py b/AutomatedTesting/Gem/PythonTests/physics/C6090547_ForceRegion_ParentChildForceRegions.py index 4a0cedcde6..5c3f2c240a 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C6090547_ForceRegion_ParentChildForceRegions.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C6090547_ForceRegion_ParentChildForceRegions.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C6090550_ForceRegion_WorldSpaceForceNegative.py b/AutomatedTesting/Gem/PythonTests/physics/C6090550_ForceRegion_WorldSpaceForceNegative.py index de698a5d2d..036ca37d00 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C6090550_ForceRegion_WorldSpaceForceNegative.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C6090550_ForceRegion_WorldSpaceForceNegative.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C6090551_ForceRegion_LocalSpaceForceNegative.py b/AutomatedTesting/Gem/PythonTests/physics/C6090551_ForceRegion_LocalSpaceForceNegative.py index 7ab32a8563..b883de48c9 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C6090551_ForceRegion_LocalSpaceForceNegative.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C6090551_ForceRegion_LocalSpaceForceNegative.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C6090552_ForceRegion_LinearDampingNegative.py b/AutomatedTesting/Gem/PythonTests/physics/C6090552_ForceRegion_LinearDampingNegative.py index 7e72a4277a..eab28df6aa 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C6090552_ForceRegion_LinearDampingNegative.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C6090552_ForceRegion_LinearDampingNegative.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C6090553_ForceRegion_SimpleDragForceOnRigidBodies.py b/AutomatedTesting/Gem/PythonTests/physics/C6090553_ForceRegion_SimpleDragForceOnRigidBodies.py index 411dcec5e1..78a08664cf 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C6090553_ForceRegion_SimpleDragForceOnRigidBodies.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C6090553_ForceRegion_SimpleDragForceOnRigidBodies.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C6090554_ForceRegion_PointForceNegative.py b/AutomatedTesting/Gem/PythonTests/physics/C6090554_ForceRegion_PointForceNegative.py index 147b561f11..1ac781fdda 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C6090554_ForceRegion_PointForceNegative.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C6090554_ForceRegion_PointForceNegative.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C6090555_ForceRegion_SplineFollowOnRigidBodies.py b/AutomatedTesting/Gem/PythonTests/physics/C6090555_ForceRegion_SplineFollowOnRigidBodies.py index 66adf2a20c..6f4d600c31 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C6090555_ForceRegion_SplineFollowOnRigidBodies.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C6090555_ForceRegion_SplineFollowOnRigidBodies.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C6131473_StaticSlice_OnDynamicSliceSpawn.py b/AutomatedTesting/Gem/PythonTests/physics/C6131473_StaticSlice_OnDynamicSliceSpawn.py index 3f113c5c19..1053944513 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C6131473_StaticSlice_OnDynamicSliceSpawn.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C6131473_StaticSlice_OnDynamicSliceSpawn.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C6224408_ScriptCanvas_EntitySpawn.py b/AutomatedTesting/Gem/PythonTests/physics/C6224408_ScriptCanvas_EntitySpawn.py index 31afbbcd8c..122c8d51aa 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C6224408_ScriptCanvas_EntitySpawn.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C6224408_ScriptCanvas_EntitySpawn.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C6274125_ScriptCanvas_TriggerEvents.py b/AutomatedTesting/Gem/PythonTests/physics/C6274125_ScriptCanvas_TriggerEvents.py index b347442c6f..86c3929cd2 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C6274125_ScriptCanvas_TriggerEvents.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C6274125_ScriptCanvas_TriggerEvents.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/C6321601_Force_HighValuesDirectionAxes.py b/AutomatedTesting/Gem/PythonTests/physics/C6321601_Force_HighValuesDirectionAxes.py index fc780ec721..282d2a7a2f 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C6321601_Force_HighValuesDirectionAxes.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C6321601_Force_HighValuesDirectionAxes.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/physics/CMakeLists.txt index 334f0c2eaa..a49ca2633b 100644 --- a/AutomatedTesting/Gem/PythonTests/physics/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/physics/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/physics/FileManagement.py b/AutomatedTesting/Gem/PythonTests/physics/FileManagement.py index a0494b9915..5bab5983a9 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/FileManagement.py +++ b/AutomatedTesting/Gem/PythonTests/physics/FileManagement.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/ImportPathHelper.py b/AutomatedTesting/Gem/PythonTests/physics/ImportPathHelper.py index 002553b096..fd068c3db2 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/ImportPathHelper.py +++ b/AutomatedTesting/Gem/PythonTests/physics/ImportPathHelper.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/JointsHelper.py b/AutomatedTesting/Gem/PythonTests/physics/JointsHelper.py index 0450eb6ba5..0461d8fbc0 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/JointsHelper.py +++ b/AutomatedTesting/Gem/PythonTests/physics/JointsHelper.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/Physmaterial_Editor.py b/AutomatedTesting/Gem/PythonTests/physics/Physmaterial_Editor.py index 8a96d5a5f8..f28908dc3b 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/Physmaterial_Editor.py +++ b/AutomatedTesting/Gem/PythonTests/physics/Physmaterial_Editor.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_InDevelopment.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_InDevelopment.py index a04372c30d..fba35bae03 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_InDevelopment.py +++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_InDevelopment.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py index d8796a5116..1895571fa5 100644 --- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py +++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py index 3bc8d80659..445b098f0e 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py +++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py index c7b085b6cb..a934702904 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py +++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Utils.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Utils.py index 8d5a4b239f..f26afa834c 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Utils.py +++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Utils.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Managed_Files.py b/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Managed_Files.py index 038c41a6f6..9db106a82d 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Managed_Files.py +++ b/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Managed_Files.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Physmaterial_Editor.py b/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Physmaterial_Editor.py index 386028cd8c..3c43cecdb2 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Physmaterial_Editor.py +++ b/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Physmaterial_Editor.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/UtilTest_PhysxConfig_Default.py b/AutomatedTesting/Gem/PythonTests/physics/UtilTest_PhysxConfig_Default.py index 75bf4415ee..ed193ecca8 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/UtilTest_PhysxConfig_Default.py +++ b/AutomatedTesting/Gem/PythonTests/physics/UtilTest_PhysxConfig_Default.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/UtilTest_PhysxConfig_Override.py b/AutomatedTesting/Gem/PythonTests/physics/UtilTest_PhysxConfig_Override.py index 75bf4415ee..ed193ecca8 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/UtilTest_PhysxConfig_Override.py +++ b/AutomatedTesting/Gem/PythonTests/physics/UtilTest_PhysxConfig_Override.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Tracer_PicksErrorsAndWarnings.py b/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Tracer_PicksErrorsAndWarnings.py index 0a1e1596c3..1a29cd1522 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Tracer_PicksErrorsAndWarnings.py +++ b/AutomatedTesting/Gem/PythonTests/physics/UtilTest_Tracer_PicksErrorsAndWarnings.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/physics/__init__.py b/AutomatedTesting/Gem/PythonTests/physics/__init__.py index a3a4055d50..e200fa77d0 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/physics/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/prefab/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/prefab/CMakeLists.txt index 0184a8b6d4..94ea4aa481 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/prefab/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py index c367c7e531..73288a3249 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py +++ b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py index 15df6705e9..ee8dcf8956 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py +++ b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/prefab/__init__.py b/AutomatedTesting/Gem/PythonTests/prefab/__init__.py index a3a4055d50..e200fa77d0 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/prefab/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt index 37c37595e9..4ebef2e77c 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleEntities.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleEntities.py index 13b86900c1..b0e3570632 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleEntities.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleEntities.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleGraphs.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleGraphs.py index 492d79bd10..909f7438ce 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleGraphs.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleGraphs.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_Default_UndoRedo.py b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_Default_UndoRedo.py index 229fe7237e..1c2241f49b 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_Default_UndoRedo.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_Default_UndoRedo.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Entity_HappyPath_AddScriptCanvasComponent.py b/AutomatedTesting/Gem/PythonTests/scripting/Entity_HappyPath_AddScriptCanvasComponent.py index 88282ddc1c..13cb6ccf68 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Entity_HappyPath_AddScriptCanvasComponent.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Entity_HappyPath_AddScriptCanvasComponent.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_Default_NewAndOpen.py b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_Default_NewAndOpen.py index 99e91ae7dc..b6ef00486b 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_Default_NewAndOpen.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_Default_NewAndOpen.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_Default_SavePrompt.py b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_Default_SavePrompt.py index 23d185c1da..0961c2b4fd 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_Default_SavePrompt.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_Default_SavePrompt.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Graph_HappyPath_ZoomInZoomOut.py b/AutomatedTesting/Gem/PythonTests/scripting/Graph_HappyPath_ZoomInZoomOut.py index b50626a6e3..1b2b5e9e27 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Graph_HappyPath_ZoomInZoomOut.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Graph_HappyPath_ZoomInZoomOut.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py b/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py index ec3f6c9a55..5dbfc92e10 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NewScriptEventButton_HappyPath_ContainsSCCategory.py b/AutomatedTesting/Gem/PythonTests/scripting/NewScriptEventButton_HappyPath_ContainsSCCategory.py index 6fc4ef2d4c..67949ed18d 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NewScriptEventButton_HappyPath_ContainsSCCategory.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NewScriptEventButton_HappyPath_ContainsSCCategory.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodeCategory_ExpandOnClick.py b/AutomatedTesting/Gem/PythonTests/scripting/NodeCategory_ExpandOnClick.py index 2efd0cd7db..642e9f135a 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodeCategory_ExpandOnClick.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodeCategory_ExpandOnClick.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_HappyPath_VariableRenames.py b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_HappyPath_VariableRenames.py index f9054b645c..4dbac1d214 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_HappyPath_VariableRenames.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_HappyPath_VariableRenames.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_CanSelectNode.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_CanSelectNode.py index 60c09095ff..5cd6a37a79 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_CanSelectNode.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_CanSelectNode.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_ClearSelection.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_ClearSelection.py index 56c98ee40d..b3bc12b9b5 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_ClearSelection.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_ClearSelection.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SearchText_Deletion.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SearchText_Deletion.py index 9d2cdee6d9..9c241083ae 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SearchText_Deletion.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SearchText_Deletion.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py b/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py index 49a79ba8a3..cb112ee370 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Pane_Default_RetainOnSCRestart.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_Default_RetainOnSCRestart.py index 5ebc43419c..87c867d1d2 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Pane_Default_RetainOnSCRestart.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_Default_RetainOnSCRestart.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_DocksProperly.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_DocksProperly.py index ef9efa2208..4952eefc01 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_DocksProperly.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_DocksProperly.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_OpenCloseSuccessfully.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_OpenCloseSuccessfully.py index 1c408d8107..223d1d0b0c 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_OpenCloseSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_OpenCloseSuccessfully.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_ResizesProperly.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_ResizesProperly.py index edddd7b817..9eee529ad2 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_ResizesProperly.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_ResizesProperly.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Pane_PropertiesChanged_RetainsOnRestart.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_PropertiesChanged_RetainsOnRestart.py index 8f2b1d3b64..78a925e9a6 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Pane_PropertiesChanged_RetainsOnRestart.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_PropertiesChanged_RetainsOnRestart.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Pane_Undocked_ClosesSuccessfully.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_Undocked_ClosesSuccessfully.py index f8d72d1189..cf9546f61f 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Pane_Undocked_ClosesSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_Undocked_ClosesSuccessfully.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py index 1ec780e707..601d71d01d 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasTools_Toggle_OpenCloseSuccess.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasTools_Toggle_OpenCloseSuccess.py index 5e5c045320..1f2994677a 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasTools_Toggle_OpenCloseSuccess.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasTools_Toggle_OpenCloseSuccess.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets_ComponentStable.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets_ComponentStable.py index 1d381c2b29..ce7817e986 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets_ComponentStable.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets_ComponentStable.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents_InteractSuccessfully.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents_InteractSuccessfully.py index 2fd72972c0..fb189f8308 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents_InteractSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents_InteractSuccessfully.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities_UseSimultaneously.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities_UseSimultaneously.py index 9256d9b4a0..a547b78e86 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities_UseSimultaneously.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities_UseSimultaneously.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveMethod_UpdatesInSC.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveMethod_UpdatesInSC.py index 34fe71caa2..9ddd81e4e7 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveMethod_UpdatesInSC.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveMethod_UpdatesInSC.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveParameter_ActionsSuccessful.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveParameter_ActionsSuccessful.py index e7b7bba29c..9feefaa41a 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveParameter_ActionsSuccessful.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_AddRemoveParameter_ActionsSuccessful.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_HappyPath_CreatedWithoutError.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_HappyPath_CreatedWithoutError.py index f3c2ccb54b..a74ebb8cb0 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_HappyPath_CreatedWithoutError.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_HappyPath_CreatedWithoutError.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_AllParamDatatypes_CreationSuccess.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_AllParamDatatypes_CreationSuccess.py index 07dc27543d..ee7ec5ebc1 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_AllParamDatatypes_CreationSuccess.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_AllParamDatatypes_CreationSuccess.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_Default_SendReceiveSuccessfully.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_Default_SendReceiveSuccessfully.py index 2f5b73a067..d5897ba09e 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_Default_SendReceiveSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_Default_SendReceiveSuccessfully.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_HappyPath_SendReceiveAcrossMultiple.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_HappyPath_SendReceiveAcrossMultiple.py index eb0edee3da..3dc8b0bd24 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_HappyPath_SendReceiveAcrossMultiple.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_HappyPath_SendReceiveAcrossMultiple.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_ReturnSetType_Successfully.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_ReturnSetType_Successfully.py index 5d4edb94f3..aaca779575 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_ReturnSetType_Successfully.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_ReturnSetType_Successfully.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py index 783b8a3abc..ab22d06eb5 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Sandbox.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Sandbox.py index 94e648e049..9d82b3c8db 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Sandbox.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Sandbox.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_Default_CreateDeleteVars.py b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_Default_CreateDeleteVars.py index b53d2a677c..163cf81812 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_Default_CreateDeleteVars.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_Default_CreateDeleteVars.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_UnpinVariableType_Works.py b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_UnpinVariableType_Works.py index b0277aa042..c66febab25 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_UnpinVariableType_Works.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_UnpinVariableType_Works.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/scripting/__init__.py b/AutomatedTesting/Gem/PythonTests/scripting/__init__.py index ce5bb8503d..99aac69543 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt index 7ef1d56ad1..6e91ae4ea4 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # @@ -38,4 +38,30 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) COMPONENT Sandbox ) -endif() \ No newline at end of file + + ly_add_pytest( + NAME AutomatedTesting::EditorTestWithGPU + TEST_REQUIRES gpu + PATH ${CMAKE_CURRENT_LIST_DIR}/test_Editor_NewExistingLevels_Works.py + TIMEOUT 100 + RUNTIME_DEPENDENCIES + AZ::AssetProcessor + AZ::PythonBindingsExample + Legacy::Editor + AutomatedTesting.GameLauncher + AutomatedTesting.Assets + ) + + ly_add_pytest( + NAME AutomatedTesting::GameLauncherWithGPU + TEST_REQUIRES gpu + PATH ${CMAKE_CURRENT_LIST_DIR}/test_GameLauncher_EnterExitGameMode_Works.py + TIMEOUT 100 + RUNTIME_DEPENDENCIES + AZ::AssetProcessor + AZ::PythonBindingsExample + Legacy::Editor + AutomatedTesting.GameLauncher + AutomatedTesting.Assets + ) +endif() diff --git a/AutomatedTesting/Gem/PythonTests/smoke/Editor_NewExistingLevels_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/Editor_NewExistingLevels_Works.py index 98f08ab9fa..656bca0323 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/Editor_NewExistingLevels_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/Editor_NewExistingLevels_Works.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/smoke/__init__.py b/AutomatedTesting/Gem/PythonTests/smoke/__init__.py index a3a4055d50..e200fa77d0 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetBuilder_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetBuilder_Works.py index 37b1a80f1c..02e36c93f3 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetBuilder_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetBuilder_Works.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetBundlerBatch_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetBundlerBatch_Works.py index f03a56e489..48092accc7 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetBundlerBatch_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetBundlerBatch_Works.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetProcessorBatch_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetProcessorBatch_Works.py index dbb08f8150..ee8da64638 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetProcessorBatch_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AssetProcessorBatch_Works.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AzTestRunner_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AzTestRunner_Works.py index 6d47ba87e7..98955fdfcb 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AzTestRunner_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_AzTestRunner_Works.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_PythonBindingsExample_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_PythonBindingsExample_Works.py index f7b209d5f7..9d9b4fbefe 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_PythonBindingsExample_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_PythonBindingsExample_Works.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_SerializeContextTools_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_SerializeContextTools_Works.py index 715754f229..525598a6dc 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_SerializeContextTools_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_CLITool_SerializeContextTools_Works.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels_Works.py index 56cd0e2f6e..ae14edcae5 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_Editor_NewExistingLevels_Works.py @@ -1,7 +1,10 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT + + +Test should run in both gpu and non gpu """ import pytest diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_LoadLevel_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_LoadLevel_Works.py new file mode 100644 index 0000000000..80da990332 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_LoadLevel_Works.py @@ -0,0 +1,104 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + + +UI Apps: AutomatedTesting.GameLauncher +Launch AutomatedTesting.GameLauncher with Simple level +Test should run in both gpu and non gpu +""" + +import pytest +import psutil + +# Bail on the test if ly_test_tools doesn't exist. +pytest.importorskip("ly_test_tools") +import ly_test_tools.environment.waiter as waiter +from ly_remote_console.remote_console_commands import RemoteConsole as RemoteConsole +from ly_remote_console.remote_console_commands import ( + send_command_and_expect_response as send_command_and_expect_response, +) + + +@pytest.mark.parametrize("launcher_platform", ["windows"]) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.parametrize("level", ["Simple"]) +@pytest.mark.SUITE_sandbox +class TestRemoteConsoleLoadLevelWorks(object): + @pytest.fixture + def remote_console_instance(self, request): + console = RemoteConsole() + + def teardown(): + if console.connected: + console.stop() + + request.addfinalizer(teardown) + + return console + + def test_RemoteConsole_LoadLevel_Works(self, launcher, level, remote_console_instance, launcher_platform): + expected_lines = ['Level system is loading "Simple"'] + + self.launch_and_validate_results_launcher(launcher, level, remote_console_instance, expected_lines) + + def launch_and_validate_results_launcher( + self, + launcher, + level, + remote_console_instance, + expected_lines, + null_renderer=False, + port_listener_timeout=120, + log_monitor_timeout=300, + remote_console_port=4600, + ): + """ + Runs the launcher with the specified level, and monitors Game.log for expected lines. + :param launcher: Configured launcher object to run test against. + :param level: The level to load in the launcher. + :param remote_console_instance: Configured Remote Console object. + :param expected_lines: Expected lines to search log for. + :oaram null_renderer: Specifies the test does not require the renderer. Defaults to True. + :param port_listener_timeout: Timeout for verifying successful connection to Remote Console. + :param log_monitor_timeout: Timeout for monitoring for lines in Game.log + :param remote_console_port: The port used to communicate with the Remote Console. + """ + + def _check_for_listening_port(port): + """ + Checks to see if the connection to the designated port was established. + :param port: Port to listen to. + :return: True if port is listening. + """ + port_listening = False + for conn in psutil.net_connections(): + if "port={}".format(port) in str(conn): + port_listening = True + return port_listening + + if null_renderer: + launcher.args.extend(["-NullRenderer"]) + + # Start the Launcher + with launcher.start(): + + # Ensure Remote Console can be reached + waiter.wait_for( + lambda: _check_for_listening_port(remote_console_port), + port_listener_timeout, + exc=AssertionError("Port {} not listening.".format(remote_console_port)), + ) + remote_console_instance.start(timeout=30) + + # Load the specified level in the launcher + send_command_and_expect_response( + remote_console_instance, f"loadlevel {level}", "LEVEL_LOAD_END", timeout=30 + ) + + # Monitor the console for expected lines + for line in expected_lines: + assert remote_console_instance.expect_log_line( + line, log_monitor_timeout + ), f"Expected line not found: {line}" diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_StaticTools_GenPakShaders_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_StaticTools_GenPakShaders_Works.py index db61f5e031..ec79bb4a15 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_StaticTools_GenPakShaders_Works.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_StaticTools_GenPakShaders_Works.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_UIApps_AssetProcessor_CheckIdle.py b/AutomatedTesting/Gem/PythonTests/smoke/test_UIApps_AssetProcessor_CheckIdle.py index e26b1a3558..d4e11e20cf 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_UIApps_AssetProcessor_CheckIdle.py +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_UIApps_AssetProcessor_CheckIdle.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT diff --git a/AutomatedTesting/Gem/PythonTests/streaming/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/streaming/CMakeLists.txt index 4639aff70e..d6f3f30ba9 100644 --- a/AutomatedTesting/Gem/PythonTests/streaming/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/streaming/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/AutomatedTesting/Gem/PythonTests/streaming/__init__.py b/AutomatedTesting/Gem/PythonTests/streaming/__init__.py index a3a4055d50..e200fa77d0 100755 --- a/AutomatedTesting/Gem/PythonTests/streaming/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/streaming/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/streaming/benchmark/__init__.py b/AutomatedTesting/Gem/PythonTests/streaming/benchmark/__init__.py index a3a4055d50..e200fa77d0 100755 --- a/AutomatedTesting/Gem/PythonTests/streaming/benchmark/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/streaming/benchmark/__init__.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/PythonTests/streaming/benchmark/asset_load_benchmark_test.py b/AutomatedTesting/Gem/PythonTests/streaming/benchmark/asset_load_benchmark_test.py index 8fd20145fc..a2c41f1073 100755 --- a/AutomatedTesting/Gem/PythonTests/streaming/benchmark/asset_load_benchmark_test.py +++ b/AutomatedTesting/Gem/PythonTests/streaming/benchmark/asset_load_benchmark_test.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/Contents.json b/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/Contents.json index f836f07ee7..5ea213954f 100644 --- a/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/Contents.json +++ b/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/Contents.json @@ -1,5 +1,41 @@ { "images" : [ + { + "extent" : "full-screen", + "filename" : "iPhoneLaunchImage1242x2688.png", + "idiom" : "iphone", + "minimum-system-version" : "12.0", + "orientation" : "portrait", + "scale" : "3x", + "subtype" : "2688h" + }, + { + "extent" : "full-screen", + "filename" : "iPhoneLaunchImage2688x1242.png", + "idiom" : "iphone", + "minimum-system-version" : "12.0", + "orientation" : "landscape", + "scale" : "3x", + "subtype" : "2688h" + }, + { + "extent" : "full-screen", + "filename" : "iPhoneLaunchImage828x1792.png", + "idiom" : "iphone", + "minimum-system-version" : "12.0", + "orientation" : "portrait", + "scale" : "2x", + "subtype" : "1792h" + }, + { + "extent" : "full-screen", + "filename" : "iPhoneLaunchImage1792x828.png", + "idiom" : "iphone", + "minimum-system-version" : "12.0", + "orientation" : "landscape", + "scale" : "2x", + "subtype" : "1792h" + }, { "extent" : "full-screen", "idiom" : "iphone", @@ -166,4 +202,4 @@ "version" : 1, "author" : "xcode" } -} \ No newline at end of file +} diff --git a/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/iPhoneLaunchImage1242x2688.png b/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/iPhoneLaunchImage1242x2688.png new file mode 100644 index 0000000000..e190d2b585 --- /dev/null +++ b/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/iPhoneLaunchImage1242x2688.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc79117e25cc7533ccf6724453e3f44a01b4eaaecded6fa826abe897456f36ee +size 405896 diff --git a/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/iPhoneLaunchImage1792x828.png b/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/iPhoneLaunchImage1792x828.png new file mode 100644 index 0000000000..5601f081de --- /dev/null +++ b/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/iPhoneLaunchImage1792x828.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c7191be3bdae09dc621012a26b0c1b9c15de1d567cf65ff1079e00f8636a32a +size 220720 diff --git a/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/iPhoneLaunchImage2688x1242.png b/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/iPhoneLaunchImage2688x1242.png new file mode 100644 index 0000000000..844b23fdd9 --- /dev/null +++ b/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/iPhoneLaunchImage2688x1242.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dfbd362f9cb5f285c23807a032af98150cf5409c514445122683736a3c65008c +size 364976 diff --git a/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/iPhoneLaunchImage828x1792.png b/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/iPhoneLaunchImage828x1792.png new file mode 100644 index 0000000000..9ebb93e39c --- /dev/null +++ b/AutomatedTesting/Gem/Resources/IOSLauncher/Images.xcassets/LaunchImage.launchimage/iPhoneLaunchImage828x1792.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0252b068b232f521ac6eca4a708fad6eaf257d0a66aa03f4f865f6a0b219cfc +size 236433 diff --git a/AutomatedTesting/Levels/AI/NavigationComponentTest/NavigationAgent.lua b/AutomatedTesting/Levels/AI/NavigationComponentTest/NavigationAgent.lua index e0c4d60578..4008a9987c 100644 --- a/AutomatedTesting/Levels/AI/NavigationComponentTest/NavigationAgent.lua +++ b/AutomatedTesting/Levels/AI/NavigationComponentTest/NavigationAgent.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/AutomatedTesting/Levels/AWS/Metrics/Script/Metrics.lua b/AutomatedTesting/Levels/AWS/Metrics/Script/Metrics.lua index dce6522eda..feb806b43f 100644 --- a/AutomatedTesting/Levels/AWS/Metrics/Script/Metrics.lua +++ b/AutomatedTesting/Levels/AWS/Metrics/Script/Metrics.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/AutomatedTesting/LuaScripts/instance_counter_blender.lua b/AutomatedTesting/LuaScripts/instance_counter_blender.lua index 49cf68e67f..efb267b949 100644 --- a/AutomatedTesting/LuaScripts/instance_counter_blender.lua +++ b/AutomatedTesting/LuaScripts/instance_counter_blender.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/AutomatedTesting/Materials/UVs.azsl b/AutomatedTesting/Materials/UVs.azsl index 2894d4de85..8a818bf4d3 100644 --- a/AutomatedTesting/Materials/UVs.azsl +++ b/AutomatedTesting/Materials/UVs.azsl @@ -1,6 +1,6 @@ /* - * Copyright (c) Contributors to the Open 3D Engine Project + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * diff --git a/AutomatedTesting/ShaderLib/scenesrg.srgi b/AutomatedTesting/ShaderLib/scenesrg.srgi index 77a95b2ba6..00ff9d3ce0 100644 --- a/AutomatedTesting/ShaderLib/scenesrg.srgi +++ b/AutomatedTesting/ShaderLib/scenesrg.srgi @@ -1,5 +1,5 @@ /* - * Copyright (c) Contributors to the Open 3D Engine Project + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * diff --git a/AutomatedTesting/ShaderLib/viewsrg.srgi b/AutomatedTesting/ShaderLib/viewsrg.srgi index 014b0a271d..f765abf5b0 100644 --- a/AutomatedTesting/ShaderLib/viewsrg.srgi +++ b/AutomatedTesting/ShaderLib/viewsrg.srgi @@ -1,5 +1,5 @@ /* - * Copyright (c) Contributors to the Open 3D Engine Project + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * diff --git a/AutomatedTesting/Shaders/CommonVS.azsli b/AutomatedTesting/Shaders/CommonVS.azsli index d138970aa8..129800b66d 100644 --- a/AutomatedTesting/Shaders/CommonVS.azsli +++ b/AutomatedTesting/Shaders/CommonVS.azsli @@ -1,6 +1,6 @@ /* - * Copyright (c) Contributors to the Open 3D Engine Project + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * diff --git a/AutomatedTesting/TestAssets/test_chunks_builder.py b/AutomatedTesting/TestAssets/test_chunks_builder.py index d8134fb259..ab9422ebbf 100755 --- a/AutomatedTesting/TestAssets/test_chunks_builder.py +++ b/AutomatedTesting/TestAssets/test_chunks_builder.py @@ -1,5 +1,5 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ diff --git a/AutomatedTesting/test1.lua b/AutomatedTesting/test1.lua index 6846eda0a7..b98529b28e 100644 --- a/AutomatedTesting/test1.lua +++ b/AutomatedTesting/test1.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/AutomatedTesting/test2.lua b/AutomatedTesting/test2.lua index c76d79397d..0a678f256d 100644 --- a/AutomatedTesting/test2.lua +++ b/AutomatedTesting/test2.lua @@ -1,6 +1,6 @@ ---------------------------------------------------------------------------------------------------- -- --- Copyright (c) Contributors to the Open 3D Engine Project +-- Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- diff --git a/CMakeLists.txt b/CMakeLists.txt index 497f56f56d..282b8c03b5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # diff --git a/Code/CMakeLists.txt b/Code/CMakeLists.txt index 91807c8eb0..6dcb99edb4 100644 --- a/Code/CMakeLists.txt +++ b/Code/CMakeLists.txt @@ -1,12 +1,12 @@ # -# Copyright (c) Contributors to the Open 3D Engine Project +# Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # -add_subdirectory(CryEngine) add_subdirectory(Framework) add_subdirectory(LauncherUnified) -add_subdirectory(Sandbox) +add_subdirectory(Legacy) +add_subdirectory(Editor) add_subdirectory(Tools) diff --git a/Code/CryEngine/CMakeLists.txt b/Code/CryEngine/CMakeLists.txt deleted file mode 100644 index 329bbca3fe..0000000000 --- a/Code/CryEngine/CMakeLists.txt +++ /dev/null @@ -1,9 +0,0 @@ -# -# Copyright (c) Contributors to the Open 3D Engine Project -# -# SPDX-License-Identifier: Apache-2.0 OR MIT -# -# - -add_subdirectory(CryCommon) -add_subdirectory(CrySystem) diff --git a/Code/CryEngine/CryCommon/AndroidSpecific.h b/Code/CryEngine/CryCommon/AndroidSpecific.h deleted file mode 100644 index 49c2e5fa46..0000000000 --- a/Code/CryEngine/CryCommon/AndroidSpecific.h +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Specific to Android declarations, inline functions etc. - - -#ifndef CRYINCLUDE_CRYCOMMON_ANDROIDSPECIFIC_H -#define CRYINCLUDE_CRYCOMMON_ANDROIDSPECIFIC_H -#pragma once - -#if defined(__arm__) || defined(__aarch64__) -#define _CPU_ARM -#endif - -#if defined(__aarch64__) -#define PLATFORM_64BIT -#endif - -#if defined(__ARM_NEON__) -#define _CPU_NEON -#endif - -#ifndef MOBILE -#define MOBILE -#endif - -#if (defined(__clang__) && NDK_REV_MAJOR >= 14) || (defined(_CPU_ARM) && defined(PLATFORM_64BIT)) - // The version of clang that NDK r14+ ships with is seemingly generating different (for better or worse) code for the atomic operations - // used in the LocklessLinkedList. In either case, this is causing deadlocks in the job system and crashes from memory stomps in - // the bucket allocator. By defining INTERLOCKED_COMPARE_EXCHANGE_128_NOT_SUPPORTED it will disable the Cry job system as well as - // change the implementation of the LocklessLinkedList to use a mutex in it's operations instead, essentially use the same behaviour - // as iOS. While not ideal to use this as a band-aid on the problem, it does fix it with a negligible performance impact. - // - // Additionally, arm64 processors do not provide a cmpxchg16b (or equivalent) instruction required for _InterlockedCompareExchange128 - #define INTERLOCKED_COMPARE_EXCHANGE_128_NOT_SUPPORTED -#endif - -// Force all allocations to be aligned to TARGET_DEFAULT_ALIGN. -// This is because malloc on Android 32 bit returns memory that is not aligned -// to what some structs/classes need. -#define CRY_FORCE_MALLOC_NEW_ALIGN - -#define DEBUG_BREAK raise(SIGTRAP) -#define RC_EXECUTABLE "rc" -#define USE_CRT 1 -#define SIZEOF_PTR 4 - -////////////////////////////////////////////////////////////////////////// -// Standard includes. -////////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// Define platform independent types. -////////////////////////////////////////////////////////////////////////// -#include "BaseTypes.h" - -typedef signed long long INT64; - -typedef double real; - -typedef uint32 DWORD; -typedef DWORD* LPDWORD; -#if defined(PLATFORM_64BIT) -typedef uint64 DWORD_PTR; -#else -typedef DWORD DWORD_PTR; -#endif -typedef intptr_t INT_PTR, *PINT_PTR; -typedef uintptr_t UINT_PTR, * PUINT_PTR; -typedef char* LPSTR, * PSTR; -typedef uint64 __uint64; -typedef int64 INT64; -typedef uint64 UINT64; - -typedef long LONG_PTR, * PLONG_PTR, * PLONG; -typedef unsigned long ULONG_PTR, * PULONG_PTR; - -typedef unsigned char BYTE; -typedef unsigned short WORD; -typedef void* HWND; -typedef UINT_PTR WPARAM; -typedef LONG_PTR LPARAM; -typedef LONG_PTR LRESULT; -#define PLARGE_INTEGER LARGE_INTEGER * -typedef const char* LPCSTR, * PCSTR; -typedef long long LONGLONG; -typedef ULONG_PTR SIZE_T; -typedef unsigned char byte; - -#define ILINE __forceinline - -#define _A_RDONLY (0x01) -#define _A_SUBDIR (0x10) - -////////////////////////////////////////////////////////////////////////// -// Win32 FileAttributes. -////////////////////////////////////////////////////////////////////////// -#define FILE_ATTRIBUTE_READONLY 0x00000001 -#define FILE_ATTRIBUTE_HIDDEN 0x00000002 -#define FILE_ATTRIBUTE_SYSTEM 0x00000004 -#define FILE_ATTRIBUTE_DIRECTORY 0x00000010 -#define FILE_ATTRIBUTE_ARCHIVE 0x00000020 -#define FILE_ATTRIBUTE_DEVICE 0x00000040 -#define FILE_ATTRIBUTE_NORMAL 0x00000080 -#define FILE_ATTRIBUTE_TEMPORARY 0x00000100 -#define FILE_ATTRIBUTE_SPARSE_FILE 0x00000200 -#define FILE_ATTRIBUTE_REPARSE_POINT 0x00000400 -#define FILE_ATTRIBUTE_COMPRESSED 0x00000800 -#define FILE_ATTRIBUTE_OFFLINE 0x00001000 -#define FILE_ATTRIBUTE_NOT_CONTENT_INDEXED 0x00002000 -#define FILE_ATTRIBUTE_ENCRYPTED 0x00004000 - -#define INVALID_FILE_ATTRIBUTES (-1) - -#define DEFINE_ALIGNED_DATA(type, name, alignment) \ - type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \ - static type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \ - const type __attribute__ ((aligned(alignment))) name; - -#include "LinuxSpecific.h" -// these functions do not exist int the wchar.h header -#undef wscasecomp -#undef wscasencomp -extern int wcsicmp (const wchar_t* s1, const wchar_t* s2); -extern int wcsnicmp (const wchar_t* s1, const wchar_t* s2, size_t count); - -// these are not defined in android-19 and prior -#undef wcsnlen -extern size_t wcsnlen(const wchar_t* str, size_t maxLen); - -#undef stpcpy -extern char* stpcpy(char* dest, const char* str); -// end android-19 - - -#define TARGET_DEFAULT_ALIGN (16U) - -#ifdef _RELEASE - #define __debugbreak() -#else - #define __debugbreak() __builtin_trap() -#endif - -// there is no __finite in android, only variants of isfinite -#undef __finite -#if NDK_REV_MAJOR >= 16 - #define __finite isfinite -#else - #define __finite __isfinite -#endif - -#define S_IWRITE S_IWUSR - -#define ILINE __forceinline -#define _A_RDONLY (0x01) -#define _A_SUBDIR (0x10) -#define _A_HIDDEN (0x02) - - -#include - -#if __ANDROID_API__ == 19 - // The following were apparently introduced in API 21, however in earlier versions of the - // platform specific headers they were defines. In the move to unified headers, the follwoing - // defines were removed from stat.h - #ifndef stat64 - #define stat64 stat - #endif - - #ifndef fstat64 - #define fstat64 fstat - #endif - - #ifndef lstat64 - #define lstat64 lstat - #endif -#endif // __ANDROID_API__ == 19 - - -// std::stoull deosn't exist on android, so we need to define it -namespace std -{ - inline unsigned long long stoull(const std::string& str, size_t* idx = 0, int base = 10) - { - const char* start = str.c_str(); - char* end = nullptr; - unsigned long long result = strtoull(start, &end, base); - if (idx) - { - *idx = end - start; - } - return result; - } -} - -#endif // CRYINCLUDE_CRYCOMMON_ANDROIDSPECIFIC_H diff --git a/Code/CryEngine/CryCommon/AnimKey.h b/Code/CryEngine/CryCommon/AnimKey.h deleted file mode 100644 index 9c5b91ab2d..0000000000 --- a/Code/CryEngine/CryCommon/AnimKey.h +++ /dev/null @@ -1,496 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_ANIMKEY_H -#define CRYINCLUDE_CRYCOMMON_ANIMKEY_H -#pragma once - -#include // <> required for Interfuscator -#include -#include -#include -#include - -enum EAnimKeyFlags -{ - AKEY_SELECTED = 0x01, //! This key is selected in track view. - AKEY_SORT_MARKER = 0x02 //! Internal use to locate a key after a sort. -}; - -//! Interface to animation key. -//! Not real interface though... -//! No virtuals for optimization reason. -struct IKey -{ - float time; - int flags; - - // compare keys. - bool operator<(const IKey& key) const { return time < key.time; } - bool operator==(const IKey& key) const { return time == key.time; } - bool operator>(const IKey& key) const { return time > key.time; } - bool operator<=(const IKey& key) const { return time <= key.time; } - bool operator>=(const IKey& key) const { return time >= key.time; } - bool operator!=(const IKey& key) const { return time != key.time; } - - IKey() - : time(0) - , flags(0) {}; - - virtual ~IKey() = default; -}; - -/** I2DBezierKey used in float tracks. - Its x component actually represents kinda time-warping curve. -*/ -struct I2DBezierKey - : public IKey -{ - Vec2 value; -}; - -/** ITcbKey used in all TCB tracks. -*/ -struct ITcbKey - : public IKey -{ - // Values. - float fval[4]; - // Key controls. - float tens; //!< Key tension value. - float cont; //!< Key continuity value. - float bias; //!< Key bias value. - float easeto; //!< Key ease to value. - float easefrom; //!< Key ease from value. - - //! Protect from direct instantiation of this class. - //! Only derived classes can be created, - ITcbKey() - { - fval[0] = 0; - fval[1] = 0; - fval[2] = 0; - fval[3] = 0; - tens = 0, cont = 0, bias = 0, easeto = 0, easefrom = 0; - }; - - void SetFloat(float val) { fval[0] = val; }; - void SetVec3(const Vec3& val) - { - fval[0] = val.x; - fval[1] = val.y; - fval[2] = val.z; - }; - void SetQuat(const Quat& val) - { - fval[0] = val.v.x; - fval[1] = val.v.y; - fval[2] = val.v.z; - fval[3] = val.w; - }; - - ILINE void SetValue(float val) { SetFloat(val); } - ILINE void SetValue(const Vec3& val) { SetVec3(val); } - ILINE void SetValue(const Quat& val) { SetQuat(val); } - - float GetFloat() const { return *((float*)fval); }; - Vec3 GetVec3() const - { - Vec3 vec; - vec.x = fval[0]; - vec.y = fval[1]; - vec.z = fval[2]; - return vec; - }; - Quat GetQuat() const - { - Quat quat; - quat.v.x = fval[0]; - quat.v.y = fval[1]; - quat.v.z = fval[2]; - quat.w = fval[3]; - return quat; - }; - ILINE void GetValue(float& val) { val = GetFloat(); }; - ILINE void GetValue(Vec3& val) { val = GetVec3(); }; - ILINE void GetValue(Quat& val) { val = GetQuat(); }; -}; - -struct IEventKey - : public IKey -{ - AZStd::string event; - AZStd::string eventValue; - AZStd::string animation; - AZStd::string target; - - union - { - float value; - float duration; - }; - bool bNoTriggerInScrubbing; - - IEventKey() - { - duration = 0; - bNoTriggerInScrubbing = false; - } -}; - -/** ISelectKey used in Camera selection track or Scene node. -*/ -struct ISelectKey - : public IKey -{ - AZStd::string szSelection; //!< Node name. - AZ::EntityId cameraAzEntityId; // will be Invalid for legacy Cameras - float fDuration; - float fBlendTime; - - ISelectKey() - { - fDuration = 0; - fBlendTime = 0; - } -}; - -/** ISequenceKey used in sequence track. -*/ -struct ISequenceKey - : public IKey -{ - AZStd::string szSelection; //!@deprecated : use sequenceEntityId to identify sequences - AZ::EntityId sequenceEntityId; - float fDuration; - float fStartTime; - float fEndTime; - bool bOverrideTimes; - bool bDoNotStop; - - ISequenceKey() - { - fDuration = 0; - fStartTime = 0; - fEndTime = 0; - bOverrideTimes = false; - bDoNotStop = false; // default crysis behaviour - } -}; - -/** ISoundKey used in sound track. -*/ -struct ISoundKey - : public IKey -{ - ISoundKey() - : fDuration(0.0f) - { - customColor.x = Col_TrackviewDefault.r; - customColor.y = Col_TrackviewDefault.g; - customColor.z = Col_TrackviewDefault.b; - } - - AZStd::string sStartTrigger; - AZStd::string sStopTrigger; - float fDuration; - Vec3 customColor; -}; - -/** ITimeRangeKey used in time ranges animation track. -*/ -#define ANIMKEY_TIME_RANGE_END_TIME_UNSET .0f -struct ITimeRangeKey - : public IKey -{ - float m_duration; //!< Duration in seconds of this animation. - float m_startTime; //!< Start time of this animation (Offset from beginning of animation). - float m_endTime; //!< End time of this animation (can be smaller than the duration). - float m_speed; //!< Speed multiplier for this key. - bool m_bLoop; //!< True if time is looping - - ITimeRangeKey() - { - m_duration = 0.0f; - m_endTime = ANIMKEY_TIME_RANGE_END_TIME_UNSET; - m_startTime = 0.0f; - m_speed = 1.0f; - m_bLoop = false; - } - - float GetValidEndTime() const - { - float endTime = m_endTime; - if (endTime == ANIMKEY_TIME_RANGE_END_TIME_UNSET || (!m_bLoop && endTime > m_duration)) - { - endTime = m_duration; - } - return endTime; - } - - float GetValidSpeed() const - { - float speed = m_speed; - if (speed <= 0.0f) - { - speed = 1.0f; - } - return speed; - } - - float GetActualDuration() const - { - return (GetValidEndTime() - m_startTime) / GetValidSpeed(); - } - - // Return true if the input time falls in range of the start/end time for this key. - bool IsInRange(float sequenceTime) const - { - return sequenceTime >= time && sequenceTime <= (time + GetActualDuration()); - } -}; - -/** ICharacterKey used in Character animation track. -*/ -struct ICharacterKey - : public ITimeRangeKey -{ - AZStd::string m_animation; //!< Name of character animation. - bool m_bBlendGap; //!< True if gap to next animation should be blended - bool m_bInPlace; // Play animation in place (Do not move root). - - ICharacterKey() - : ITimeRangeKey() - { - m_bLoop = false; - m_bBlendGap = false; - m_bInPlace = false; - } -}; - -/** IExprKey used in expression animation track. -*/ -struct IExprKey - : public IKey -{ - IExprKey() - { - pszName[0] = 0; - fAmp = 1.0f; - fBlendIn = 0.5f; - fHold = 1.0f; - fBlendOut = 0.5f; - } - char pszName[128]; //!< Name of morph-target - float fAmp; - float fBlendIn; - float fHold; - float fBlendOut; -}; - -/** IConsoleKey used in Console track, triggers console commands and variables. -*/ -struct IConsoleKey - : public IKey -{ - AZStd::string command; -}; - -struct ILookAtKey - : public IKey -{ - AZStd::string szSelection; //!< Node name. - float fDuration; - AZStd::string lookPose; - float smoothTime; - - ILookAtKey() - { - fDuration = 0; - smoothTime = 0.2f; - } -}; - -//! Discrete (non-interpolated) float key. -struct IDiscreteFloatKey - : public IKey -{ - float m_fValue; - - void SetValue(float fValue) - { - m_fValue = fValue; - } - - IDiscreteFloatKey() - { - m_fValue = -1.0f; - } -}; - -//! A key for the capture track. -struct ICaptureKey - : public IKey -{ - friend class AnimSerializer; - - AZStd::string folder; - AZStd::string prefix; - float duration; - float timeStep; - bool once; - - ICaptureKey() - : IKey() - , duration(0.0f) - , timeStep(0.033f) - , once(false) - { - ICVar* pCaptureFolderCVar = gEnv->pConsole->GetCVar("capture_folder"); - if (pCaptureFolderCVar != NULL && pCaptureFolderCVar->GetString()) - { - folder = pCaptureFolderCVar->GetString(); - } - ICVar* pCaptureFilePrefixCVar = gEnv->pConsole->GetCVar("capture_file_prefix"); - if (pCaptureFilePrefixCVar != NULL && pCaptureFilePrefixCVar->GetString()) - { - prefix = pCaptureFilePrefixCVar->GetString(); - } - } - - ICaptureKey(const ICaptureKey& other) - : IKey(other) - , folder(other.folder) - , prefix(other.prefix) - , duration(other.duration) - , timeStep(other.timeStep) - , once(other.once) - { - } -}; - -//! Boolean key. -struct IBoolKey - : public IKey -{ - IBoolKey() {}; -}; - -//! Comment Key. -struct ICommentKey - : public IKey -{ - enum ETextAlign : int - { - eTA_Left = 0, - eTA_Center = BIT(1), - eTA_Right = BIT(2) - }; - - //----------------------------------------------------------------------------- - //! - ICommentKey() - : m_duration(1.f) - , m_size(1.f) - , m_align(eTA_Left) - , m_strFont("default") - , m_color(1.f, 1.f, 1.f, 1.f) - { - } - - //----------------------------------------------------------------------------- - //! - ICommentKey(const ICommentKey& other) - : IKey(other) - , m_strComment(other.m_strComment) - , m_strFont(other.m_strFont) - { - m_duration = other.m_duration; - m_color = other.m_color; - m_size = other.m_size; - m_align = other.m_align; - } - - AZStd::string m_strComment; - float m_duration; - - AZStd::string m_strFont; - AZ::Color m_color; - float m_size; - ETextAlign m_align; -}; - -//----------------------------------------------------------------------------- -//! -struct IScreenFaderKey - : public IKey -{ - //----------------------------------------------------------------------------- - //! - enum EFadeType : int - { - eFT_FadeIn = 0, eFT_FadeOut = 1 - }; - enum EFadeChangeType : int - { - eFCT_Linear = 0, eFCT_Square = 1, eFCT_CubicSquare = 2, eFCT_SquareRoot = 3, eFCT_Sin = 4 - }; - - //----------------------------------------------------------------------------- - //! - IScreenFaderKey() - : IKey() - , m_fadeTime(2.f) - , m_bUseCurColor(true) - , m_fadeType(eFT_FadeOut) - , m_fadeChangeType(eFCT_Linear) - { - m_fadeColor = AZ::Color(.0f, .0f, .0f, 1.0f); - } - - //----------------------------------------------------------------------------- - //! - IScreenFaderKey(const IScreenFaderKey& other) - : IKey(other) - , m_fadeTime(other.m_fadeTime) - , m_bUseCurColor(other.m_bUseCurColor) - , m_fadeType(other.m_fadeType) - , m_fadeChangeType(other.m_fadeChangeType) - { - m_fadeColor = other.m_fadeColor; - m_strTexture = other.m_strTexture; - } - - //----------------------------------------------------------------------------- - //! - float m_fadeTime; - AZ::Color m_fadeColor; - AZStd::string m_strTexture; - bool m_bUseCurColor; - EFadeType m_fadeType; - EFadeChangeType m_fadeChangeType; -}; - -namespace AZ -{ - AZ_TYPE_INFO_SPECIALIZE(IKey, "{680BD51E-C106-4BBF-9A6F-CD551E00519F}"); - AZ_TYPE_INFO_SPECIALIZE(IBoolKey, "{DBF8044F-6E64-403D-807D-F3152F640703}"); - AZ_TYPE_INFO_SPECIALIZE(ICaptureKey, "{93AA8D63-6B1E-4D33-8CC3-C82147BB95CB}"); - AZ_TYPE_INFO_SPECIALIZE(ICharacterKey, "{6D1FB9E2-128C-4B33-84FF-4F696C1F7D53}"); - AZ_TYPE_INFO_SPECIALIZE(ICommentKey, "{99C2234E-A4DD-45D1-90C3-D5AFC54FA47F}"); - AZ_TYPE_INFO_SPECIALIZE(IConsoleKey, "{8C0DCB9B-297D-4AF4-A0D1-F5160E6900E8}"); - AZ_TYPE_INFO_SPECIALIZE(IDiscreteFloatKey, "{469A2B90-E019-4147-A53F-2EB42E179596}"); - AZ_TYPE_INFO_SPECIALIZE(IEventKey, "{F09533AA-9780-494D-9E5C-8CB98266AC5E}"); - AZ_TYPE_INFO_SPECIALIZE(ILookAtKey, "{6F4CED0E-D83A-40E2-B7BF-038D82BC0374}"); - AZ_TYPE_INFO_SPECIALIZE(IScreenFaderKey, "{FA15E27D-603F-4829-925A-E36D75C93964}"); - AZ_TYPE_INFO_SPECIALIZE(ISelectKey, "{FCEADCF5-042E-473B-845F-0778F087B6DC}"); - AZ_TYPE_INFO_SPECIALIZE(ISequenceKey, "{B55294AD-F14E-43AC-B6B5-AC27B377FE00}"); - AZ_TYPE_INFO_SPECIALIZE(ISoundKey, "{452E50CF-B7D0-42D5-A86A-B295682674BB}"); - AZ_TYPE_INFO_SPECIALIZE(ITimeRangeKey, "{17807C95-C7A1-481B-AD94-C54D83928D0B}"); -} -#endif // CRYINCLUDE_CRYCOMMON_ANIMKEY_H diff --git a/Code/CryEngine/CryCommon/AppleSpecific.h b/Code/CryEngine/CryCommon/AppleSpecific.h deleted file mode 100644 index 93b1c974ab..0000000000 --- a/Code/CryEngine/CryCommon/AppleSpecific.h +++ /dev/null @@ -1,595 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Apple specific declarations common amongst its products - -#ifndef CRYINCLUDE_CRYCOMMON_APPLESPECIFIC_H -#define CRYINCLUDE_CRYCOMMON_APPLESPECIFIC_H -#pragma once - -#if defined(__clang__) -#pragma diagnostic ignore "-W#pragma-messages" -#endif - - -#define DEBUG_BREAK __builtin_trap() -#define RC_EXECUTABLE "rc" - -////////////////////////////////////////////////////////////////////////// -// Standard includes. -////////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -// Atomic operations , guaranteed to work across all apple platforms -#include -#include -#include -#include -////////////////////////////////////////////////////////////////////////// - -#define FP16_MESH -#define BOOST_DISABLE_WIN32 - -#ifndef __COUNTER__ -#define __COUNTER__ __LINE__ -#endif - -#ifdef __FUNC__ -#undef __FUNC__ -#endif - -#define __FUNC__ __func__ - -typedef void* LPVOID; -#define VOID void -#define PVOID void* - -typedef unsigned int UINT; -typedef char CHAR; -typedef float FLOAT; - -#define PHYSICS_EXPORTS - -// MSVC compiler-specific keywords -#define __forceinline inline -#define _inline inline -#define __cdecl -#define _cdecl -#define __stdcall -#define _stdcall -#define __fastcall -#define _fastcall -#define IN -#define OUT - -#define MAP_ANONYMOUS MAP_ANON - -////////////////////////////////////////////////////////////////////////// -// Define platform independent types. -////////////////////////////////////////////////////////////////////////// -#include "BaseTypes.h" - -typedef double real; - -typedef uint32 DWORD; -typedef DWORD* LPDWORD; -typedef uint64 DWORD_PTR; -typedef intptr_t INT_PTR, * PINT_PTR; -typedef uintptr_t UINT_PTR, * PUINT_PTR; -typedef char* LPSTR, * PSTR; -typedef char TCHAR; -typedef uint64 __uint64; -#if !defined(__clang__) -typedef int64 __int64; -#endif -typedef int64 INT64; -typedef uint64 UINT64; - -typedef long LONG_PTR, * PLONG_PTR, * PLONG; -typedef unsigned long ULONG_PTR, * PULONG_PTR; - -typedef uint8 BYTE; -typedef uint16 WORD; -typedef void* HWND; -typedef UINT_PTR WPARAM; -typedef LONG_PTR LPARAM; -typedef LONG_PTR LRESULT; -#define PLARGE_INTEGER LARGE_INTEGER * -typedef const char* LPCSTR, * PCSTR; -typedef long long LONGLONG; -typedef ULONG_PTR SIZE_T; -typedef uint8 byte; -#define ILINE __forceinline - -#ifndef MAXUINT -#define MAXUINT ((uint) ~((uint)0)) -#endif - -#ifndef MAXINT -#define MAXINT ((int)(MAXUINT >> 1)) -#endif - -#ifndef _CVTBUFSIZE -#define _CVTBUFSIZE (309+40) /* # of digits in max. dp value + slop */ -#endif - -#ifndef STDMETHODCALLTYPE_DEFINED -#define STDMETHODCALLTYPE_DEFINED -#define STDMETHODCALLTYPE -#endif - -#define _ALIGN(num) \ - __attribute__ ((aligned(num))) \ - AZ_POP_DISABLE_WARNING - -#define _PACK __attribute__ ((packed)) - -// Safe memory freeing -#ifndef SAFE_DELETE -#define SAFE_DELETE(p) { if (p) { delete (p); (p) = NULL; } \ -} -#endif - -#ifndef SAFE_DELETE_ARRAY -#define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p); (p) = NULL; } \ -} -#endif - -#ifndef SAFE_RELEASE -#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p) = NULL; } \ -} -#endif - - -#ifndef SAFE_RELEASE_FORCE -#define SAFE_RELEASE_FORCE(p) { if (p) { (p)->ReleaseForce(); (p) = NULL; } \ -} -#endif - -#define MAKEWORD(a, b) ((WORD)(((BYTE)((DWORD_PTR)(a) & 0xff)) | ((WORD)((BYTE)((DWORD_PTR)(b) & 0xff))) << 8)) -#define MAKELONG(a, b) ((LONG)(((WORD)((DWORD_PTR)(a) & 0xffff)) | ((DWORD)((WORD)((DWORD_PTR)(b) & 0xffff))) << 16)) -#define LOWORD(l) ((WORD)((DWORD_PTR)(l) & 0xffff)) -#define HIWORD(l) ((WORD)((DWORD_PTR)(l) >> 16)) -#define LOBYTE(w) ((BYTE)((DWORD_PTR)(w) & 0xff)) -#define HIBYTE(w) ((BYTE)((DWORD_PTR)(w) >> 8)) - -#define CALLBACK -#define WINAPI - -#ifndef __cplusplus -#ifndef _WCHAR_T_DEFINED -typedef unsigned short wchar_t; -#define TCHAR wchar_t; -#define _WCHAR_T_DEFINED -#endif -#endif -typedef wchar_t WCHAR; // wc, 16-bit UNICODE character -typedef WCHAR* PWCHAR; -typedef WCHAR* LPWCH, * PWCH; -typedef const WCHAR* LPCWCH, * PCWCH; -typedef WCHAR* NWPSTR; -typedef WCHAR* LPWSTR, * PWSTR; -typedef WCHAR* LPUWSTR, * PUWSTR; - -typedef const WCHAR* LPCWSTR, * PCWSTR; -typedef const WCHAR* LPCUWSTR, * PCUWSTR; - -#ifdef UNICODE -typedef LPCWSTR LPCTSTR; -typedef LPWSTR LPTSTR; -#else -typedef LPCSTR LPCTSTR; -typedef LPSTR LPTSTR; -#endif - -typedef DWORD COLORREF; -#define RGB(r,g,b) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16))) - -#define GetRValue(rgb) (LOBYTE(rgb)) -#define GetGValue(rgb) (LOBYTE(((WORD)(rgb)) >> 8)) -#define GetBValue(rgb) (LOBYTE((rgb)>>16)) - -#define MAKEFOURCC(ch0, ch1, ch2, ch3) \ - ((DWORD)(BYTE)(ch0) | ((DWORD)(BYTE)(ch1) << 8) | \ - ((DWORD)(BYTE)(ch2) << 16) | ((DWORD)(BYTE)(ch3) << 24)) -#define FILE_ATTRIBUTE_NORMAL 0x00000080 - -// Conflit with OBJC defined bool type. - -#if defined(IOS) -typedef bool BOOL; -#else -typedef signed char BOOL; -#endif - -typedef int32_t LONG; -typedef unsigned int ULONG; -typedef int HRESULT; - -//typedef int32 __int32; -typedef uint32 __uint32; -typedef int64 __int64; -typedef uint64 __uint64; - -#define TRUE 1 -#define FALSE 0 - -#ifndef MAX_PATH -#define MAX_PATH PATH_MAX -#endif -#ifndef _MAX_PATH -#define _MAX_PATH MAX_PATH -#endif - -#define _PTRDIFF_T_DEFINED 1 - -#define _A_RDONLY (0x01) /* Read only file */ -#define _A_HIDDEN (0x02) /* Hidden file */ -#define _A_SUBDIR (0x10) /* Subdirectory */ - -////////////////////////////////////////////////////////////////////////// -// Win32 FileAttributes. -////////////////////////////////////////////////////////////////////////// -#define FILE_ATTRIBUTE_READONLY 0x00000001 -#define FILE_ATTRIBUTE_HIDDEN 0x00000002 -#define FILE_ATTRIBUTE_SYSTEM 0x00000004 -#define FILE_ATTRIBUTE_DIRECTORY 0x00000010 -#define FILE_ATTRIBUTE_ARCHIVE 0x00000020 -#define FILE_ATTRIBUTE_DEVICE 0x00000040 -#define FILE_ATTRIBUTE_NORMAL 0x00000080 -#define FILE_ATTRIBUTE_TEMPORARY 0x00000100 -#define FILE_ATTRIBUTE_SPARSE_FILE 0x00000200 -#define FILE_ATTRIBUTE_REPARSE_POINT 0x00000400 -#define FILE_ATTRIBUTE_COMPRESSED 0x00000800 -#define FILE_ATTRIBUTE_OFFLINE 0x00001000 -#define FILE_ATTRIBUTE_NOT_CONTENT_INDEXED 0x00002000 -#define FILE_ATTRIBUTE_ENCRYPTED 0x00004000 - -#define INVALID_FILE_ATTRIBUTES (-1) - -#define DEFINE_ALIGNED_DATA(type, name, alignment) \ - type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \ - static type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \ - const type __attribute__ ((aligned(alignment))) name; - -#define BST_UNCHECKED 0x0000 - -#ifndef HRESULT_VALUES_DEFINED -#define HRESULT_VALUES_DEFINED -enum -{ - E_OUTOFMEMORY = 0x8007000E, - E_FAIL = 0x80004005, - E_ABORT = 0x80004004, - E_INVALIDARG = 0x80070057, - E_NOINTERFACE = 0x80004002, - E_NOTIMPL = 0x80004001, - E_UNEXPECTED = 0x8000FFFF -}; -#endif - -#define ERROR_SUCCESS 0L - -enum -{ - IDOK = 1, - IDCANCEL = 2, - IDABORT = 3, - IDRETRY = 4, - IDIGNORE = 5, - IDYES = 6, - IDNO = 7, - IDTRYAGAIN = 10, - IDCONTINUE = 11 -}; - -#define ES_MULTILINE 0x0004L -#define ES_AUTOVSCROLL 0x0040L -#define ES_AUTOHSCROLL 0x0080L -#define ES_WANTRETURN 0x1000L - -#define LB_ERR (-1) - -#define LB_ADDSTRING 0x0180 -#define LB_GETCOUNT 0x018B -#define LB_SETTOPINDEX 0x0197 - -#define MB_OK 0x00000000L -#define MB_OKCANCEL 0x00000001L -#define MB_ABORTRETRYIGNORE 0x00000002L -#define MB_YESNOCANCEL 0x00000003L -#define MB_YESNO 0x00000004L -#define MB_RETRYCANCEL 0x00000005L -#define MB_CANCELTRYCONTINUE 0x00000006L - -#define MB_ICONQUESTION 0x00000020L -#define MB_ICONEXCLAMATION 0x00000030L - -#define MB_ICONERROR 0x00000010L -#define MB_ICONWARNING 0x00000030L -#define MB_ICONINFORMATION 0x00000040L - -#define MB_SETFOREGROUND 0x00010000L - -#define MB_APPLMODAL 0x00000000L - -#define MF_STRING 0x00000000L - -#define MK_LBUTTON 0x0001 -#define MK_RBUTTON 0x0002 -#define MK_SHIFT 0x0004 -#define MK_CONTROL 0x0008 -#define MK_MBUTTON 0x0010 - -#define MK_ALT ( 0x20 ) - -#define SM_MOUSEPRESENT 0x00000000L - -#define SM_CMOUSEBUTTONS 43 - -#define USER_TIMER_MINIMUM 0x0000000A - -#define VK_TAB 0x09 -#define VK_SHIFT 0x10 -#define VK_MENU 0x12 -#define VK_ESCAPE 0x1B -#define VK_SPACE 0x20 -#define VK_DELETE 0x2E - -#define VK_NUMPAD1 0x61 -#define VK_NUMPAD2 0x62 -#define VK_NUMPAD3 0x63 -#define VK_NUMPAD4 0x64 - -#define VK_OEM_COMMA 0xBC // ',' any country -#define VK_OEM_PERIOD 0xBE // '.' any country -#define VK_OEM_3 0xC0 // '`~' for US -#define VK_OEM_4 0xDB // '[{' for US -#define VK_OEM_6 0xDD // ']}' for US - -#define WAIT_TIMEOUT 258L // dderror - -#define WM_MOVE 0x0003 -#define WM_USER 0x0400 - -#define WHEEL_DELTA 120 - -#define WS_CHILD 0x40000000L -#define WS_VISIBLE 0x10000000L - -#define CB_ERR (-1) - -// function renaming -#define _finite std::isfinite -#define _snprintf snprintf -//#define _isnan isnan -#define stricmp strcasecmp -#define _stricmp strcasecmp -#define strnicmp strncasecmp -#define _strnicmp strncasecmp -#define wcsicmp wcscasecmp -#define wcsnicmp wcsncasecmp -//#define memcpy_s(dest,bytes,src,n) memcpy(dest,src,n) -#define _isnan ISNAN -#define _wtof(str) wcstod(str, 0) - - -#define TARGET_DEFAULT_ALIGN (0x8U) - - - -#define _msize malloc_size - - -struct _OVERLAPPED; - -typedef void (* LPOVERLAPPED_COMPLETION_ROUTINE)(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, struct _OVERLAPPED* lpOverlapped); - -typedef struct _OVERLAPPED -{ - void* pCaller;//this is orginally reserved for internal purpose, we store the Caller pointer here - LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine; ////this is orginally ULONG_PTR InternalHigh and reserved for internal purpose - union - { - struct - { - DWORD Offset; - DWORD OffsetHigh; - }; - PVOID Pointer; - }; - DWORD dwNumberOfBytesTransfered; //additional member temporary speciying the number of bytes to be read - /*HANDLE*/ void* hEvent; -} OVERLAPPED, * LPOVERLAPPED; - -typedef struct _SECURITY_ATTRIBUTES -{ - DWORD nLength; - LPVOID lpSecurityDescriptor; - BOOL bInheritHandle; -} SECURITY_ATTRIBUTES, * PSECURITY_ATTRIBUTES, * LPSECURITY_ATTRIBUTES; - -#ifdef __cplusplus - -#define __min(_S, _T) min(_S, _T) -#define __max(_S, _T) max(_S, _T) - -typedef enum -{ - INVALID_HANDLE_VALUE = -1l -}INVALID_HANDLE_VALUE_ENUM; -//for compatibility reason we got to create a class which actually contains an int rather than a void* and make sure it does not get mistreated -template -//U is default type for invalid handle value, T the encapsulated handle type to be used instead of void* (as under windows and never linux) -class CHandle -{ -public: - typedef T HandleType; - typedef void* PointerType; //for compatibility reason to encapsulate a void* as an int - - static const HandleType sciInvalidHandleValue = U; - - CHandle(const CHandle& cHandle) - : m_Value(cHandle.m_Value){} - CHandle(const HandleType cHandle = U) - : m_Value(cHandle){} - CHandle(const PointerType cpHandle) - : m_Value(reinterpret_cast(cpHandle)){} - CHandle(INVALID_HANDLE_VALUE_ENUM) - : m_Value(U){} //to be able to use a common value for all InvalidHandle - types -#if defined(PLATFORM_64BIT) - //treat __null tyope also as invalid handle type - CHandle(long) - : m_Value(U){} //to be able to use a common value for all InvalidHandle - types -#endif - operator HandleType(){ - return m_Value; - } - bool operator!() const{return m_Value == sciInvalidHandleValue; } - const CHandle& operator =(const CHandle& crHandle){m_Value = crHandle.m_Value; return *this; } - const CHandle& operator =(const PointerType cpHandle){m_Value = (HandleType) reinterpret_cast(cpHandle); return *this; } - const bool operator ==(const CHandle& crHandle) const{return m_Value == crHandle.m_Value; } - const bool operator ==(const HandleType cHandle) const{return m_Value == cHandle; } - const bool operator ==(const PointerType cpHandle) const{return m_Value == reinterpret_cast(cpHandle); } - const bool operator !=(const HandleType cHandle) const{return m_Value != cHandle; } - const bool operator !=(const CHandle& crHandle) const{return m_Value != crHandle.m_Value; } - const bool operator !=(const PointerType cpHandle) const{return m_Value != reinterpret_cast(cpHandle); } - const bool operator < (const CHandle& crHandle) const{return m_Value < crHandle.m_Value; } - HandleType Handle() const{return m_Value; } - -private: - HandleType m_Value; //the actual value, remember that file descriptors are ints under linux - - typedef void ReferenceType;//for compatibility reason to encapsulate a void* as an int - //forbid these function which would actually not work on an int - PointerType operator->(); - PointerType operator->() const; - ReferenceType operator*(); - ReferenceType operator*() const; - operator PointerType(); -}; - -typedef CHandle HANDLE; - -typedef HANDLE EVENT_HANDLE; -typedef HANDLE THREAD_HANDLE; - -typedef HANDLE HKEY; -typedef HANDLE HDC; - -typedef HANDLE HBITMAP; - -typedef HANDLE HMENU; - -#endif //__cplusplus - -inline char* _fullpath(char* absPath, const char* relPath, size_t maxLength) -{ - char path[PATH_MAX]; - - if (realpath(relPath, path) == NULL) - { - return NULL; - } - const size_t len = std::min(strlen(path), maxLength - 1); - memcpy(absPath, path, len); - absPath[len] = 0; - return absPath; -} - -typedef union _LARGE_INTEGER -{ - struct - { - DWORD LowPart; - LONG HighPart; - }; - struct - { - DWORD LowPart; - LONG HighPart; - } u; - - long long QuadPart; -} LARGE_INTEGER; - -extern bool QueryPerformanceCounter(LARGE_INTEGER*); -extern bool QueryPerformanceFrequency(LARGE_INTEGER* frequency); - -inline int64 CryGetTicks() -{ - LARGE_INTEGER counter; - QueryPerformanceCounter(&counter); - return counter.QuadPart; -} - -inline int64 CryGetTicksPerSec() -{ - LARGE_INTEGER li; - QueryPerformanceFrequency(&li); - return li.QuadPart; -} -/* - inline uint32 GetTickCount() - { - LARGE_INTEGER count, freq; - QueryPerformanceCounter(&count); - QueryPerformanceFrequency(&freq); - return uint32(count.QuadPart * 1000 / freq.QuadPart); - } - */ - -#ifdef _RELEASE -#define __debugbreak() -#else -#define __debugbreak() ::raise(SIGTRAP) -#endif - -#define __assume(x) -#define _flushall sync - -inline int closesocket(int s) -{ - return ::close(s); -} - -inline int WSAGetLastError() -{ - return errno; -} - -//we take the definition of the pthread_t type directly from the pthread file -#define THREADID_NULL 0 - -template -char (*RtlpNumberOf( T (&)[N] ))[N]; - -#define RTL_NUMBER_OF_V2(A) (sizeof(*RtlpNumberOf(A))) - -#define ARRAYSIZE(A) RTL_NUMBER_OF_V2(A) - -#undef SUCCEEDED -#define SUCCEEDED(x) ((x) >= 0) -#undef FAILED -#define FAILED(x) (!(SUCCEEDED(x))) - -#endif // CRYINCLUDE_CRYCOMMON_APPLESPECIFIC_H diff --git a/Code/CryEngine/CryCommon/BaseTypes.h b/Code/CryEngine/CryCommon/BaseTypes.h deleted file mode 100644 index cbd4f78fcd..0000000000 --- a/Code/CryEngine/CryCommon/BaseTypes.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_BASETYPES_H -#define CRYINCLUDE_CRYCOMMON_BASETYPES_H -#pragma once - -#include "CompileTimeAssert.h" - - -COMPILE_TIME_ASSERT(sizeof(char) == 1); -COMPILE_TIME_ASSERT(sizeof(float) == 4); -COMPILE_TIME_ASSERT(sizeof(int) >= 4); - - -typedef unsigned char uchar; -typedef signed char schar; - -typedef unsigned short ushort; -typedef signed short sshort; - -#if !defined(CLANG_FIX_UINT_REDEF) -typedef unsigned int uint; -#endif -typedef signed int sint; - -typedef unsigned long ulong; -typedef signed long slong; - -typedef unsigned long long ulonglong; -typedef signed long long slonglong; - -COMPILE_TIME_ASSERT(sizeof(uchar) == sizeof(schar)); -COMPILE_TIME_ASSERT(sizeof(ushort) == sizeof(sshort)); -COMPILE_TIME_ASSERT(sizeof(uint) == sizeof(sint)); -COMPILE_TIME_ASSERT(sizeof(ulong) == sizeof(slong)); -COMPILE_TIME_ASSERT(sizeof(ulonglong) == sizeof(slonglong)); - -COMPILE_TIME_ASSERT(sizeof(uchar) <= sizeof(ushort)); -COMPILE_TIME_ASSERT(sizeof(ushort) <= sizeof(uint)); -COMPILE_TIME_ASSERT(sizeof(uint) <= sizeof(ulong)); -COMPILE_TIME_ASSERT(sizeof(ulong) <= sizeof(ulonglong)); - - -typedef schar int8; -typedef schar sint8; -typedef uchar uint8; -COMPILE_TIME_ASSERT(sizeof(uint8) == 1); -COMPILE_TIME_ASSERT(sizeof(sint8) == 1); - -typedef sshort int16; -typedef sshort sint16; -typedef ushort uint16; -COMPILE_TIME_ASSERT(sizeof(uint16) == 2); -COMPILE_TIME_ASSERT(sizeof(sint16) == 2); - -typedef sint int32; -typedef sint sint32; -typedef uint uint32; -COMPILE_TIME_ASSERT(sizeof(uint32) == 4); -COMPILE_TIME_ASSERT(sizeof(sint32) == 4); - -typedef slonglong int64; - -#ifndef O3DE_INT64_DEFINED -#define O3DE_INT64_DEFINED -typedef slonglong sint64; -typedef ulonglong uint64; -COMPILE_TIME_ASSERT(sizeof(uint64) == 8); -COMPILE_TIME_ASSERT(sizeof(sint64) == 8); -#endif - - -typedef float f32; -typedef double f64; -COMPILE_TIME_ASSERT(sizeof(f32) == 4); -COMPILE_TIME_ASSERT(sizeof(f64) == 8); - -#endif // CRYINCLUDE_CRYCOMMON_BASETYPES_H diff --git a/Code/CryEngine/CryCommon/BitFiddling.h b/Code/CryEngine/CryCommon/BitFiddling.h deleted file mode 100644 index 328c883de1..0000000000 --- a/Code/CryEngine/CryCommon/BitFiddling.h +++ /dev/null @@ -1,593 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : various integer bit fiddling hacks - - -#pragma once - -#include "CompileTimeAssert.h" -#include - -// Section dictionary -#if defined(AZ_RESTRICTED_PLATFORM) -#define BITFIDDLING_H_SECTION_TRAITS 1 -#define BITFIDDLING_H_SECTION_INTEGERLOG2 2 -#endif - -// Traits -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION BITFIDDLING_H_SECTION_TRAITS - #include AZ_RESTRICTED_FILE(BitFiddling_h) -#elif defined(LINUX) || defined(APPLE) -#define BITFIDDLING_H_TRAIT_HAS_COUNT_LEADING_ZEROS 1 -#endif - -#if BITFIDDLING_H_TRAIT_HAS_COUNT_LEADING_ZEROS -#define countLeadingZeros32(x) __builtin_clz(x) -#else // Windows implementation -ILINE uint32 countLeadingZeros32(uint32 x) -{ - DWORD result = 32 ^ 31; // assumes result is unmodified if _BitScanReverse returns 0 - _BitScanReverse(&result, x); - PREFAST_SUPPRESS_WARNING(6102); - result ^= 31; // needed because the index is from LSB (whereas all other implementations are from MSB) - return result; -} -#endif - -inline uint32 circularShift(uint32 nbits, uint32 i) -{ - return (i << nbits) | (i >> (32 - nbits)); -} - -template -inline size_t countTrailingZeroes(T v) -{ - size_t n = 0; - - v = ~v & (v - 1); - while (v) - { - ++n; - v >>= 1; - } - - return n; -} - -// this function returns the integer logarithm of various numbers without branching -#define IL2VAL(mask, shift) \ - c |= ((x & mask) != 0) * shift; \ - x >>= ((x & mask) != 0) * shift - -template -inline bool IsPowerOfTwo(TInteger x) -{ - return (x & (x - 1)) == 0; -} - -// compile time version of IsPowerOfTwo, useful for STATIC_CHECK -template -struct IsPowerOfTwoCompileTime -{ - enum - { - IsPowerOfTwo = ((nValue & (nValue - 1)) == 0) - }; -}; - -inline uint32 NextPower2(uint32 n) -{ - n--; - n |= n >> 1; - n |= n >> 2; - n |= n >> 4; - n |= n >> 8; - n |= n >> 16; - n++; - return n; -} - -inline uint8 IntegerLog2(uint8 x) -{ - uint8 c = 0; - IL2VAL(0xf0, 4); - IL2VAL(0xc, 2); - IL2VAL(0x2, 1); - return c; -} -inline uint16 IntegerLog2(uint16 x) -{ - uint16 c = 0; - IL2VAL(0xff00, 8); - IL2VAL(0xf0, 4); - IL2VAL(0xc, 2); - IL2VAL(0x2, 1); - return c; -} - -inline uint32 IntegerLog2(uint32 x) -{ - return 31 - countLeadingZeros32(x); -} - -inline uint64 IntegerLog2(uint64 x) -{ - uint64 c = 0; - IL2VAL(0xffffffff00000000ull, 32); - IL2VAL(0xffff0000u, 16); - IL2VAL(0xff00, 8); - IL2VAL(0xf0, 4); - IL2VAL(0xc, 2); - IL2VAL(0x2, 1); - return c; -} - -#if defined(APPLE) || defined(LINUX) -inline unsigned long int IntegerLog2(unsigned long int x) -{ - #if defined(PLATFORM_64BIT) - return IntegerLog2((uint64)x); - #else - return IntegerLog2((uint32)x); - #endif -} -#endif -#undef IL2VAL - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION BITFIDDLING_H_SECTION_INTEGERLOG2 - #include AZ_RESTRICTED_FILE(BitFiddling_h) -#endif - -template -inline TInteger IntegerLog2_RoundUp(TInteger x) -{ - return 1 + IntegerLog2(x - 1); -} - -static ILINE uint8 BitIndex(uint8 v) -{ - uint32 vv = v; - return aznumeric_caster(31 - countLeadingZeros32(vv)); -} - -static ILINE uint8 BitIndex(uint16 v) -{ - uint32 vv = v; - return aznumeric_caster(31 - countLeadingZeros32(vv)); -} - -static ILINE uint8 BitIndex(uint32 v) -{ - return aznumeric_caster(31 - countLeadingZeros32(v)); -} - -static ILINE uint8 CountBits(uint8 v) -{ - uint8 c = v; - c = ((c >> 1) & 0x55) + (c & 0x55); - c = ((c >> 2) & 0x33) + (c & 0x33); - c = ((c >> 4) & 0x0f) + (c & 0x0f); - return c; -} - -static ILINE uint8 CountBits(uint16 v) -{ - return CountBits((uint8)(v & 0xff)) + - CountBits((uint8)((v >> 8) & 0xff)); -} - -static ILINE uint8 CountBits(uint32 v) -{ - return CountBits((uint8)(v & 0xff)) + - CountBits((uint8)((v >> 8) & 0xff)) + - CountBits((uint8)((v >> 16) & 0xff)) + - CountBits((uint8)((v >> 24) & 0xff)); -} - -// Branchless version of return v < 0 ? alt : v; -ILINE int32 Isel32(int32 v, int32 alt) -{ - return ((static_cast(v) >> 31) & alt) | ((static_cast(~v) >> 31) & v); -} - -template -struct CompileTimeIntegerLog2 -{ - static const uint32 result = 1 + CompileTimeIntegerLog2<(ILOG >> 1)>::result; -}; -template <> -struct CompileTimeIntegerLog2<1> -{ - static const uint32 result = 0; -}; -template <> -struct CompileTimeIntegerLog2<0>; // keep it undefined, we cannot represent "minus infinity" result - -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<1>::result == 0); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<2>::result == 1); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<3>::result == 1); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<4>::result == 2); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<5>::result == 2); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<255>::result == 7); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<256>::result == 8); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2<257>::result == 8); - -template -struct CompileTimeIntegerLog2_RoundUp -{ - static const uint32 result = CompileTimeIntegerLog2::result + ((ILOG & (ILOG - 1)) != 0); -}; -template <> -struct CompileTimeIntegerLog2_RoundUp<0>; // we can return 0, but let's keep it undefined (same as CompileTimeIntegerLog2<0>) - -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<1>::result == 0); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<2>::result == 1); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<3>::result == 2); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<4>::result == 2); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<5>::result == 3); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<255>::result == 8); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<256>::result == 8); -COMPILE_TIME_ASSERT(CompileTimeIntegerLog2_RoundUp<257>::result == 9); - -// Character-to-bitfield mapping - -inline uint32 AlphaBit(char c) -{ - return c >= 'a' && c <= 'z' ? 1 << (c - 'z' + 31) : 0; -} - -inline uint64 AlphaBit64(char c) -{ - return (c >= 'a' && c <= 'z' ? 1U << (c - 'z' + 31) : 0) | - (c >= 'A' && c <= 'Z' ? 1LL << (c - 'Z' + 63) : 0); -} - -inline uint32 AlphaBits(uint32 wc) -{ - // Handle wide multi-char constants, can be evaluated at compile-time. - return AlphaBit((char)wc) - | AlphaBit((char)(wc >> 8)) - | AlphaBit((char)(wc >> 16)) - | AlphaBit((char)(wc >> 24)); -} - -inline uint32 AlphaBits(const char* s) -{ - // Handle string of any length. - uint32 n = 0; - while (*s) - { - n |= AlphaBit(*s++); - } - return n; -} - -inline uint64 AlphaBits64(const char* s) -{ - // Handle string of any length. - uint64 n = 0; - while (*s) - { - n |= AlphaBit64(*s++); - } - return n; -} - -// s should point to a buffer at least 65 chars long -inline void BitsAlpha64(uint64 n, char* s) -{ - for (int i = 0; n != 0; n >>= 1, i++) - { - if (n & 1) - { - *s++ = i < 32 ? static_cast(i + 'z' - 31) : static_cast(i + 'Z' - 63); - } - } - *s++ = '\0'; -} - - -// if hardware doesn't support 3Dc we can convert to DXT5 (different channels are used) -// with almost the same quality but the same memory requirements -inline void ConvertBlock3DcToDXT5(uint8 pDstBlock[16], const uint8 pSrcBlock[16]) -{ - assert(pDstBlock != pSrcBlock); // does not work in place - - // 4x4 block requires 8 bytes in DXT5 or 3DC - - // DXT5: 8 bit alpha0, 8 bit alpha1, 16*3 bit alpha lerp - // 16bit col0, 16 bit col1 (R5G6B5 low byte then high byte), 16*2 bit color lerp - - // 3DC: 8 bit x0, 8 bit x1, 16*3 bit x lerp - // 8 bit y0, 8 bit y1, 16*3 bit y lerp - - for (uint32 dwK = 0; dwK < 8; ++dwK) - { - pDstBlock[dwK] = pSrcBlock[dwK]; - } - for (uint32 dwK = 8; dwK < 16; ++dwK) - { - pDstBlock[dwK] = 0; - } - - // 6 bit green channel (highest bits) - // by using all 3 channels with a slight offset we can get more precision but then a dot product would be needed in PS - // because of bilinear filter we cannot just distribute bits to get perfect result - uint16 colDst0 = (((uint16)pSrcBlock[8] + 2) >> 2) << 5; - uint16 colDst1 = (((uint16)pSrcBlock[9] + 2) >> 2) << 5; - - bool bFlip = colDst0 <= colDst1; - - if (bFlip) - { - uint16 help = colDst0; - colDst0 = colDst1; - colDst1 = help; - } - - bool bEqual = colDst0 == colDst1; - - // distribute bytes by hand to not have problems with endianess - pDstBlock[8 + 0] = (uint8)colDst0; - pDstBlock[8 + 1] = (uint8)(colDst0 >> 8); - pDstBlock[8 + 2] = (uint8)colDst1; - pDstBlock[8 + 3] = (uint8)(colDst1 >> 8); - - uint16* pSrcBlock16 = (uint16*)(pSrcBlock + 10); - uint16* pDstBlock16 = (uint16*)(pDstBlock + 12); - - // distribute 16 3 bit values to 16 2 bit values (loosing LSB) - for (uint32 dwK = 0; dwK < 16; ++dwK) - { - uint32 dwBit0 = dwK * 3 + 0; - uint32 dwBit1 = dwK * 3 + 1; - uint32 dwBit2 = dwK * 3 + 2; - - uint8 hexDataIn = (((pSrcBlock16[(dwBit2 >> 4)] >> (dwBit2 & 0xf)) & 1) << 2) // get HSB - | (((pSrcBlock16[(dwBit1 >> 4)] >> (dwBit1 & 0xf)) & 1) << 1) - | ((pSrcBlock16[(dwBit0 >> 4)] >> (dwBit0 & 0xf)) & 1); // get LSB - - uint8 hexDataOut = 0; - - switch (hexDataIn) - { - case 0: - hexDataOut = 0; - break; // color 0 - case 1: - hexDataOut = 1; - break; // color 1 - - case 2: - hexDataOut = 0; - break; // mostly color 0 - case 3: - hexDataOut = 2; - break; - case 4: - hexDataOut = 2; - break; - case 5: - hexDataOut = 3; - break; - case 6: - hexDataOut = 3; - break; - case 7: - hexDataOut = 1; - break; // mostly color 1 - - default: - assert(0); - } - - if (bFlip) - { - if (hexDataOut < 2) - { - hexDataOut = 1 - hexDataOut; // 0<->1 - } - else - { - hexDataOut = 5 - hexDataOut; // 2<->3 - } - } - - if (bEqual) - { - if (hexDataOut == 3) - { - hexDataOut = 1; - } - } - - pDstBlock16[(dwK >> 3)] |= (hexDataOut << ((dwK & 0x7) << 1)); - } -} - - - - -// is a bit on in a new bit field, but off in an old bit field -static ILINE bool TurnedOnBit(unsigned bit, unsigned oldBits, unsigned newBits) -{ - return (newBits & bit) != 0 && (oldBits & bit) == 0; -} - - - - - - - -inline uint32 cellUtilCountLeadingZero(uint32 x) -{ - uint32 y; - uint32 n = 32; - - y = x >> 16; - if (y != 0) - { - n = n - 16; - x = y; - } - y = x >> 8; - if (y != 0) - { - n = n - 8; - x = y; - } - y = x >> 4; - if (y != 0) - { - n = n - 4; - x = y; - } - y = x >> 2; - if (y != 0) - { - n = n - 2; - x = y; - } - y = x >> 1; - if (y != 0) - { - return n - 2; - } - return n - x; -} - -inline uint32 cellUtilLog2(uint32 x) -{ - return 31 - cellUtilCountLeadingZero(x); -} - - - - -inline void convertSwizzle(uint8*& dst, const uint8*& src, - const uint32 SrcPitch, const uint32 depth, - const uint32 xpos, const uint32 ypos, - const uint32 SciX1, const uint32 SciY1, - const uint32 SciX2, const uint32 SciY2, - const uint32 level) -{ - if (level == 1) - { - switch (depth) - { - case 16: - if (xpos >= SciX1 && xpos < SciX2 && ypos >= SciY1 && ypos < SciY2) - { - // *((uint32*&)dst)++ = ((uint32*)src)[ypos * width + xpos]; - // *((uint32*&)dst)++ = ((uint32*)src)[ypos * width + xpos+1]; - // *((uint32*&)dst)++ = ((uint32*)src)[ypos * width + xpos+2]; - // *((uint32*&)dst)++ = ((uint32*)src)[ypos * width + xpos+3]; - *((uint32*&)dst)++ = *((uint32*)(src + (ypos * SrcPitch + xpos * 16))); - *((uint32*&)dst)++ = *((uint32*)(src + (ypos * SrcPitch + xpos * 16 + 4))); - *((uint32*&)dst)++ = *((uint32*)(src + (ypos * SrcPitch + xpos * 16 + 8))); - *((uint32*&)dst)++ = *((uint32*)(src + (ypos * SrcPitch + xpos * 16 + 12))); - } - else - { - ((uint32*&)dst) += 4; - } - break; - case 8: - if (xpos >= SciX1 && xpos < SciX2 && ypos >= SciY1 && ypos < SciY2) - { - *((uint32*&)dst)++ = *((uint32*)(src + (ypos * SrcPitch + xpos * 8))); - *((uint32*&)dst)++ = *((uint32*)(src + (ypos * SrcPitch + xpos * 8 + 4))); - } - else - { - ((uint32*&)dst) += 2; - } - break; - case 4: - if (xpos >= SciX1 && xpos < SciX2 && ypos >= SciY1 && ypos < SciY2) - { - *((uint32*&)dst) = *((uint32*)(src + (ypos * SrcPitch + xpos * 4))); - } - dst += 4; - break; - case 3: - if (xpos >= SciX1 && xpos < SciX2 && ypos >= SciY1 && ypos < SciY2) - { - *dst++ = src[ypos * SrcPitch + xpos * depth]; - *dst++ = src[ypos * SrcPitch + xpos * depth + 1]; - *dst++ = src[ypos * SrcPitch + xpos * depth + 2]; - } - else - { - dst += 3; - } - break; - case 1: - if (xpos >= SciX1 && xpos < SciX2 && ypos >= SciY1 && ypos < SciY2) - { - *dst++ = src[ypos * SrcPitch + xpos * depth]; - } - else - { - dst++; - } - break; - default: - assert(0); - } - return; - } - else - { - convertSwizzle(dst, src, SrcPitch, depth, xpos, ypos, SciX1, SciY1, SciX2, SciY2, level - 1); - convertSwizzle(dst, src, SrcPitch, depth, xpos + (1U << (level - 2)), ypos, SciX1, SciY1, SciX2, SciY2, level - 1); - convertSwizzle(dst, src, SrcPitch, depth, xpos, ypos + (1U << (level - 2)), SciX1, SciY1, SciX2, SciY2, level - 1); - convertSwizzle(dst, src, SrcPitch, depth, xpos + (1U << (level - 2)), ypos + (1U << (level - 2)), SciX1, SciY1, SciX2, SciY2, level - 1); - } -} - - - - -inline void Linear2Swizzle(uint8* dst, - const uint8* src, - const uint32 SrcPitch, - const uint32 width, - const uint32 height, - const uint32 depth, - const uint32 SciX1, const uint32 SciY1, - const uint32 SciX2, const uint32 SciY2) -{ - src -= SciY1 * SrcPitch + SciX1 * depth; - if (width == height) - { - convertSwizzle(dst, src, SrcPitch, depth, 0, 0, SciX1, SciY1, SciX2, SciY2, cellUtilLog2(width) + 1); - } - else - if (width > height) - { - uint32 baseLevel = cellUtilLog2(width) - (cellUtilLog2(width) - cellUtilLog2(height)); - for (uint32 i = 0; i < (1UL << (cellUtilLog2(width) - cellUtilLog2(height))); i++) - { - convertSwizzle(dst, src, SrcPitch, depth, (1U << baseLevel) * i, 0, SciX1, SciY1, SciX2, SciY2, baseLevel + 1); - } - } - else - // if (width < height)//wtf - { - uint32 baseLevel = cellUtilLog2(height) - (cellUtilLog2(height) - cellUtilLog2(width)); - for (uint32 i = 0; i < (1UL << (cellUtilLog2(height) - cellUtilLog2(width))); i++) - { - convertSwizzle(dst, src, SrcPitch, depth, 0, (1U << baseLevel) * i, SciX1, SciY1, SciX2, SciY2, baseLevel + 1); - } - } -} diff --git a/Code/CryEngine/CryCommon/CMakeLists.txt b/Code/CryEngine/CryCommon/CMakeLists.txt deleted file mode 100644 index 6c00cc5071..0000000000 --- a/Code/CryEngine/CryCommon/CMakeLists.txt +++ /dev/null @@ -1,35 +0,0 @@ -# -# Copyright (c) Contributors to the Open 3D Engine Project -# -# SPDX-License-Identifier: Apache-2.0 OR MIT -# -# - -ly_add_target( - NAME CryCommon STATIC - NAMESPACE Legacy - FILES_CMAKE - crycommon_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - . # Lots of code without CryCommon/ - .. # Dangerous since exports CryEngine's path (client code can do CrySystem/ without depending on that target) - BUILD_DEPENDENCIES - PUBLIC - AZ::AzCore - AZ::AzFramework -) - -if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) - - ly_add_target( - NAME CryCommonMocks HEADERONLY - NAMESPACE Legacy - FILES_CMAKE - crycommon_testing_files.cmake - INCLUDE_DIRECTORIES - INTERFACE - Mocks - ) - -endif() diff --git a/Code/CryEngine/CryCommon/Common_TypeInfo.cpp b/Code/CryEngine/CryCommon/Common_TypeInfo.cpp deleted file mode 100644 index 5d43478c38..0000000000 --- a/Code/CryEngine/CryCommon/Common_TypeInfo.cpp +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "TypeInfo_impl.h" -#include "Cry_Geo.h" - -STRUCT_INFO_T_BEGIN(Vec2_tpl, class, F) -VAR_INFO(x) -VAR_INFO(y) -STRUCT_INFO_T_END(Vec2_tpl, class, F) - -#include "Cry_Vector3.h" - -STRUCT_INFO_T_BEGIN(Vec3_tpl, typename, F) -VAR_INFO(x) -VAR_INFO(y) -VAR_INFO(z) -STRUCT_INFO_T_END(Vec3_tpl, typename, F) - -typedef TFixed TFixedUChar_1_255_0; -STRUCT_INFO_T_INSTANTIATE(Vec3_tpl, TFixedUChar_1_255_0) - -STRUCT_INFO_T_BEGIN(Vec4_tpl, typename, F) -VAR_INFO(x) -VAR_INFO(y) -VAR_INFO(z) -VAR_INFO(w) -STRUCT_INFO_T_END(Vec4_tpl, typename, F) - -STRUCT_INFO_T_INSTANTIATE(Vec4_tpl, short) - -STRUCT_INFO_T_BEGIN(Ang3_tpl, typename, F) -VAR_INFO(x) -VAR_INFO(y) -VAR_INFO(z) -STRUCT_INFO_T_END(Ang3_tpl, typename, F) - -STRUCT_INFO_T_BEGIN(Plane_tpl, typename, F) -VAR_INFO(n) -VAR_INFO(d) -STRUCT_INFO_T_END(Plane_tpl, typename, F) - -//----------------------------------------------------------------- -//#include "Cry_Quat_info.h" -STRUCT_INFO_T_BEGIN(Quat_tpl, typename, F) -VAR_INFO(v) -VAR_INFO(w) -STRUCT_INFO_T_END(Quat_tpl, typename, F) - -STRUCT_INFO_T_INSTANTIATE(Quat_tpl, float) - -STRUCT_INFO_T_BEGIN(QuatT_tpl, typename, F) -VAR_INFO(q) -VAR_INFO(t) -STRUCT_INFO_T_END(QuatT_tpl, typename, F) - -STRUCT_INFO_T_INSTANTIATE(QuatT_tpl, float) - -STRUCT_INFO_T_BEGIN(QuatTS_tpl, typename, F) -VAR_INFO(q) -VAR_INFO(t) -VAR_INFO(s) -STRUCT_INFO_T_END(QuatTS_tpl, typename, F) - -STRUCT_INFO_T_BEGIN(DualQuat_tpl, typename, F) -VAR_INFO(nq) -VAR_INFO(dq) -STRUCT_INFO_T_END(DualQuat_tpl, typename, F) - - -//------------------------------------------------------------ -//#include "Cry_Matrix_info.h" -STRUCT_INFO_T_BEGIN(Matrix33_tpl, typename, F) -VAR_INFO(m00) -VAR_INFO(m01) -VAR_INFO(m02) -VAR_INFO(m10) -VAR_INFO(m11) -VAR_INFO(m12) -VAR_INFO(m20) -VAR_INFO(m21) -VAR_INFO(m22) -STRUCT_INFO_T_END(Matrix33_tpl, typename, F) - -STRUCT_INFO_T_BEGIN(Matrix34_tpl, typename, F) -VAR_INFO(m00) -VAR_INFO(m01) -VAR_INFO(m02) -VAR_INFO(m03) -VAR_INFO(m10) -VAR_INFO(m11) -VAR_INFO(m12) -VAR_INFO(m13) -VAR_INFO(m20) -VAR_INFO(m21) -VAR_INFO(m22) -VAR_INFO(m23) -STRUCT_INFO_T_END(Matrix34_tpl, typename, F) - -STRUCT_INFO_T_INSTANTIATE(Matrix34_tpl, float) - -STRUCT_INFO_T_BEGIN(Matrix44_tpl, typename, F) -VAR_INFO(m00) -VAR_INFO(m01) -VAR_INFO(m02) -VAR_INFO(m03) -VAR_INFO(m10) -VAR_INFO(m11) -VAR_INFO(m12) -VAR_INFO(m13) -VAR_INFO(m20) -VAR_INFO(m21) -VAR_INFO(m22) -VAR_INFO(m23) -VAR_INFO(m30) -VAR_INFO(m31) -VAR_INFO(m32) -VAR_INFO(m33) -STRUCT_INFO_T_END(Matrix44_tpl, typename, F) - - -//#include "Cry_Color_info.h" -STRUCT_INFO_T_BEGIN(Color_tpl, class, T) -VAR_INFO(r) -VAR_INFO(g) -VAR_INFO(b) -VAR_INFO(a) -STRUCT_INFO_T_END(Color_tpl, class, T) - -STRUCT_INFO_T_INSTANTIATE(Color_tpl, unsigned char) - -//#include "Cry_Geo_info.h" -STRUCT_INFO_BEGIN(AABB) -VAR_INFO(min) -VAR_INFO(max) -STRUCT_INFO_END(AABB) - -STRUCT_INFO_BEGIN(RectF) -VAR_INFO(x) -VAR_INFO(y) -VAR_INFO(w) -VAR_INFO(h) -STRUCT_INFO_END(RectF) - -#include "TimeValue_info.h" -#include "CryHalf_info.h" - -// Manually instantiate templates as needed here. -template struct Vec3_tpl; -template struct Vec4_tpl; -template struct Vec2_tpl; -template struct Ang3_tpl; -template struct Plane_tpl; -template struct Matrix33_tpl; -template struct Color_tpl; diff --git a/Code/CryEngine/CryCommon/CompileTimeAssert.h b/Code/CryEngine/CryCommon/CompileTimeAssert.h deleted file mode 100644 index 603aa4cac3..0000000000 --- a/Code/CryEngine/CryCommon/CompileTimeAssert.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -// Inspired by the Boost library's BOOST_STATIC_ASSERT(), -// see http://www.boost.org/doc/libs/1_49_0/doc/html/boost_staticassert/how.html -// or http://www.boost.org/libs/static_assert - -#ifndef CRYINCLUDE_CRYCOMMON_COMPILETIMEASSERT_H -#define CRYINCLUDE_CRYCOMMON_COMPILETIMEASSERT_H -#pragma once - -#if defined(__cplusplus) -/* -template -struct COMPILE_TIME_ASSERT_FAIL; - -template <> -struct COMPILE_TIME_ASSERT_FAIL -{ -}; - -template -struct COMPILE_TIME_ASSERT_TEST -{ - enum { dummy = i }; -}; - -#define COMPILE_TIME_ASSERT_BUILD_NAME2(x, y) x##y -#define COMPILE_TIME_ASSERT_BUILD_NAME1(x, y) COMPILE_TIME_ASSERT_BUILD_NAME2(x, y) -#define COMPILE_TIME_ASSERT_BUILD_NAME(x, y) COMPILE_TIME_ASSERT_BUILD_NAME1(x, y) - -#ifndef __RECODE__ - #define COMPILE_TIME_ASSERT(expr) \ - typedef COMPILE_TIME_ASSERT_TEST)> \ - COMPILE_TIME_ASSERT_BUILD_NAME(compile_time_assert_test_, __LINE__) - // note: for MS Visual Studio we could use __COUNTER__ instead of __LINE__ -#else - #define COMPILE_TIME_ASSERT(expr) -#endif // __RECODE__ - -#else - -#define COMPILE_TIME_ASSERT(expr) -*/ -#endif - -#define COMPILE_TIME_ASSERT_MSG(expr, msg) static_assert(expr, msg) -#define COMPILE_TIME_ASSERT(expr) COMPILE_TIME_ASSERT_MSG(expr, "Compile Time Assert") - - -#endif // CRYINCLUDE_CRYCOMMON_COMPILETIMEASSERT_H diff --git a/Code/CryEngine/CryCommon/CryArray.h b/Code/CryEngine/CryCommon/CryArray.h deleted file mode 100644 index 8a1170a4cf..0000000000 --- a/Code/CryEngine/CryCommon/CryArray.h +++ /dev/null @@ -1,1346 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYARRAY_H -#define CRYINCLUDE_CRYCOMMON_CRYARRAY_H -#pragma once - -#include "CryLegacyAllocator.h" - -//--------------------------------------------------------------------------- -// Convenient iteration macros -#define for_iter(IT, it, b, e) for (IT it = (b), _e = (e); it != _e; ++it) -#define for_container(CT, it, cont) for_iter (CT::iterator, it, (cont).begin(), (cont).end()) - -#define for_ptr(T, it, b, e) for (T* it = (b), * _e = (e); it != _e; ++it) -#define for_array_ptr(T, it, arr) for_ptr (T, it, (arr).begin(), (arr).end()) - -#define for_array(i, arr) for (int i = 0, _e = (arr).size(); i < _e; i++) -#define for_all(cont) for_array (_i, cont) cont[_i] - -//--------------------------------------------------------------------------- -// Stack array helper -#define ALIGNED_STACK_ARRAY(T, name, size, alignment) \ - PREFAST_SUPPRESS_WARNING(6255) \ - T * name = (T*) alloca((size) * sizeof(T) + alignment - 1); \ - name = Align(name, alignment); - -#define STACK_ARRAY(T, name, size) \ - ALIGNED_STACK_ARRAY(T, name, size, alignof(T)) \ - -//--------------------------------------------------------------------------- -// Specify semantics for moving objects. -// If raw_movable() is true, objects will be moved with memmove(). -// If false, with the templated move_init() function. -template -bool raw_movable([[maybe_unused]] T const& dest) -{ - return false; -} - -// This container was written before C++11 and move semantics. As a result, it attempts -// to fake move semantics where possible by constructing over top of existing instances. -// This works great, unless the type being operated on has internal pointers to its own -// memory space (for instance a string with SSO, or COW semantics). -template -struct fake_move_helper -{ - static void move(T& dest, T& source) - { - ::new(&dest) T(source); - source.~T(); - } -}; - -// Override for string to ensure proper construction -template <> -struct fake_move_helper -{ - static void move(string& dest, string& source) - { - ::new((void*)&dest) string(); - dest = source; - source.~string(); - } -}; - -// Generic move function: transfer an existing source object to uninitialized dest address. -// Addresses must not overlap (requirement on caller). -// May be specialized for specific types, to provide a more optimal move. -// For types that can be trivially moved (memcpy), do not specialize move_init, rather specialize raw_movable to return true. -template -void move_init(T& dest, T& source) -{ - assert(&dest != &source); - fake_move_helper::move(dest, source); -} - -/*--------------------------------------------------------------------------- -Public classes: - - Array - StaticArray - DynArray - StaticDynArray - -Support classes are placed in namespaces NArray and NAlloc to reduce global name usage. ----------------------------------------------------------------------------*/ - -namespace NArray -{ - // We should never have these defined as macros. - #undef min - #undef max - - // Define our own min/max here, to avoid including entire . - template - inline T min(T a, T b) - { return a < b ? a : b; } - template - inline T max(T a, T b) - { return a > b ? a : b; } - - // Automatic inference of signed from unsigned int type. - template - struct IntTraits - { - typedef T TSigned; - }; - - template<> - struct IntTraits - { - typedef int TSigned; - }; - template<> - struct IntTraits - { - typedef int64 TSigned; - }; -#if !defined(LINUX) && !defined(APPLE) - template<> - struct IntTraits - { - typedef long TSigned; - }; -#endif - - /*--------------------------------------------------------------------------- - // STORAGE prototype for Array. - struct Storage - { - template - struct Store - { - [const] T* begin() [const]; - I size() const; - }; - }; - ---------------------------------------------------------------------------*/ - - //--------------------------------------------------------------------------- - // ArrayStorage: Default STORAGE Array. - // Simply contains a pointer and count to an existing array, - // performs no allocation or deallocation. - - struct ArrayStorage - { - template - struct Store - { - // Construction. - Store() - : m_aElems(0) - , m_nCount(0) - {} - Store(T* elems, I count) - : m_aElems(elems) - , m_nCount(count) - {} - Store(T* start, T* finish) - : m_aElems(start) - , m_nCount(check_cast(finish - start)) - {} - - void set(T* elems, I count) - { - m_aElems = elems; - m_nCount = count; - } - - // Basic storage. - CONST_VAR_FUNCTION(T * begin(), - { return m_aElems; - }) - inline I size() const - { return m_nCount; } - - // Modifiers, alter range in place. - void erase_front(I count = 1) - { - assert(count >= 0 && count <= m_nCount); - m_nCount -= count; - m_aElems += count; - } - - void erase_back(I count = 1) - { - assert(count >= 0 && count <= m_nCount); - m_nCount -= count; - } - - void resize(I count) - { - assert(count >= 0 && count <= m_nCount); - m_nCount = count; - } - - protected: - T* m_aElems; - I m_nCount; - }; - }; - - //--------------------------------------------------------------------------- - // StaticArrayStorage: STORAGE scheme with a statically sized member array. - - template - struct StaticArrayStorage - { - template - struct Store - { - // Basic storage. - CONST_VAR_FUNCTION(T * begin(), - { return m_aElems; - }) - inline static I size() - { return (I)nSIZE; } - - protected: - T m_aElems[nSIZE]; - }; - }; -}; - -//--------------------------------------------------------------------------- -// Array: Non-growing array. -// S serves as base class, and implements storage scheme: begin(), size() - -template< class T, class I = int, class STORE = NArray::ArrayStorage > -struct Array - : STORE::template Store -{ - typedef typename STORE::template Store S; - - // Tedious redundancy. - using S::size; - using S::begin; - - // STL-compatible typedefs. - typedef T value_type; - typedef T* pointer; - typedef const T* const_pointer; - typedef T& reference; - typedef const T& const_reference; - - typedef T* iterator; - typedef const T* const_iterator; - - typedef I size_type; - typedef typename NArray::IntTraits::TSigned - difference_type; - - typedef Array array; - typedef Array const_array; - - // Construction. - Array() - {} - - // Forward single- and double-argument constructors. - template - explicit Array(const In& i) - : S(i) - {} - - template - Array(const In1& i1, const In2& i2) - : S(i1, i2) - {} - - // Accessors. - inline bool empty() const - { return size() == 0; } - inline size_type size_mem() const - { return size() * sizeof(T); } - - CONST_VAR_FUNCTION(T * data(), - { return begin(); - }) - - CONST_VAR_FUNCTION(T * end(), - { return begin() + size(); - }) - - CONST_VAR_FUNCTION(T * rbegin(), - { return begin() + size() - 1; - }) - - CONST_VAR_FUNCTION(T * rend(), - { return begin() - 1; - }) - - CONST_VAR_FUNCTION(T & front(), - { - assert(!empty()); - return *begin(); - }) - - CONST_VAR_FUNCTION(T & back(), - { - assert(!empty()); - return *rbegin(); - }) - - CONST_VAR_FUNCTION(T & at(size_type i), - { - CRY_ASSERT_TRACE(i >= 0 && i < size(), ("Index %lld is out of range (array size is %lld)", (long long int) i, (long long int) size())); - return begin()[i]; - }) - - CONST_VAR_FUNCTION(T & operator [](size_type i), - { - CRY_ASSERT_TRACE(i >= 0 && i < size(), ("Index %lld is out of range (array size is %lld)", (long long int) i, (long long int) size())); - return begin()[i]; - }) - - // Conversion to canonical array type. - operator array() - { return array(begin(), size()); } - operator const_array() const - { - return const_array(begin(), size()); - } - - // Additional conversion via operator() to full or sub array. - array operator ()(size_type i, size_type count) - { - assert(i >= 0 && i + count <= size()); - return array(begin() + i, count); - } - const_array operator ()(size_type i, size_type count) const - { - assert(i >= 0 && i + count <= size()); - return const_array(begin() + i, count); - } - - array operator ()(size_type i = 0) - { return (*this)(i, size() - i); } - const_array operator ()(size_type i = 0) const - { return (*this)(i, size() - i); } - - // Basic element assignment functions. - - // Copy values to existing elements. - void fill(const T& val) - { - for_array_ptr (T, it, *this) - * it = val; - } - - void copy(const_array source) - { - assert(source.size() >= size()); - const T* s = source.begin(); - for_array_ptr (T, it, *this) - * it = *s++; - } - - // Raw element construct/destruct functions. - iterator init() - { - for_array_ptr (T, it, *this) - new(it) T; - return begin(); - } - iterator init(const T& val) - { - for_array_ptr (T, it, *this) - new(it) T(val); - return begin(); - } - iterator init(const_array source) - { - assert(source.size() >= size()); - assert(source.end() <= begin() || source.begin() >= end()); - const_iterator s = source.begin(); - for_array_ptr (T, it, *this) - new(it) T(*s++); - return begin(); - } - - iterator move_init(array source) - { - assert(source.size() >= size()); - iterator s = source.begin(); - if (s != begin()) - { - if (raw_movable(*s)) - { - memmove(begin(), s, size_mem()); - } - else if (s > begin() || source.end() <= begin()) - { - for_array_ptr (T, it, *this) - ::move_init(*it, *s++); - } - else - { - s += size(); - for (iterator it = end(); it > begin(); ) - { - ::move_init(*--it, *--s); - } - } - } - return begin(); - } - - void destroy() - { - // Destroy in reverse order, to complement construction order. - for (iterator it = rbegin(); it > rend(); --it) - { - it->~T(); - } - } -}; - -// Type-inferring constructor. - -template -inline Array ArrayT(T* elems, I count) -{ - return Array(elems, count); -} - -template -inline Array ArrayT(T* start, T* finish) -{ - return Array(start, finish); -} - -// StaticArray -// A superior alternative to static C arrays. -// Provides standard STL-like Array interface, including bounds-checking. -// standard: Type array[256]; -// structured: StaticArray array; - -template -struct StaticArray - : Array< T, I, NArray::StaticArrayStorage > -{ -}; - -//--------------------------------------------------------------------------- -// Specify allocation for dynamic arrays - -namespace NAlloc -{ - // Multi-purpose allocation function prototype - // pMem = 0, nSize != 0: allocate new mem, nSize = actual amount alloced - // pMem != 0, nSize = 0: deallcate mem - // pMem != 0, nSize != 0: nSize = actual amount allocated - typedef void* (* Allocator)(void* pMem, size_t& nSize, size_t nAlign, bool bSlack); - - // - // Allocation utilities - // - - inline size_t realloc_size(size_t nMinSize) - { - // Choose an efficient realloc size, when growing an existing (non-zero) block. - // Find the next power-of-two, minus a bit of presumed system alloc overhead. - static const size_t nMinAlloc = 32; - static const size_t nOverhead = 16; - static const size_t nDoubleLimit = - sizeof(size_t) < 8 ? 1 << 12 // 32-bit system - : 1 << 16; // >= 64-bit system - - nMinSize += nOverhead; - size_t nAlloc = nMinAlloc; - while (nAlloc < nMinSize) - { - nAlloc <<= 1; - } - if (nAlloc > nDoubleLimit) - { - size_t nAlign = NArray::max(nAlloc >> 3, nDoubleLimit); - nAlloc = Align(nMinSize, nAlign); - } - return nAlloc - nOverhead; - } - - template - T* reallocate(A& allocator, T* old_elems, I old_size, I& new_size, size_t alignment = 1, bool allow_slack = false) - { - T* new_elems; - if (new_size) - { - size_t new_bytes = new_size * sizeof(T); - new_elems = (T*) allocator.alloc(0, new_bytes, alignment, allow_slack); - assert(IsAligned(new_elems, alignment)); - assert(new_bytes >= new_size * sizeof(T)); - new_size = check_cast(new_bytes / sizeof(T)); - } - else - { - new_elems = 0; - } - - if (old_elems) - { - Array old_elems_array(old_elems, old_size); - if (new_elems) - { - // Move elements. - ArrayT(new_elems, NArray::min(old_size, new_size)).move_init(old_elems_array); - } - - // Dealloc old. - old_elems_array.destroy(); // call destructors - size_t zero = 0; - allocator.alloc(old_elems, zero, alignment); - } - - return new_elems; - } - - template - inline size_t get_alloc_size(const A& allocator, const void* pMem, size_t nSize, size_t nAlign) - { - non_const(allocator).alloc((void*)pMem, nSize, nAlign); - return nSize; - } - - struct AllocFunction - { - Allocator m_Function; - - void* alloc(void* pMem, size_t& nSize, size_t nAlign, bool bSlack = false) - { - return m_Function(pMem, nSize, nAlign, bSlack); - } - }; - - // Adds prefix bytes to allocation, preserving alignment - template - struct AllocPrefix - : A - { - void* alloc(void* pMem, size_t& nSize, size_t nAlign, bool bSlack = false) - { - // Adjust pointer and size for prefix bytes - nAlign = NArray::max(nAlign, alignof(Prefix)); - size_t nPrefixSize = Align(sizeof(Prefix), nAlign); - - if (pMem) - { - pMem = (char*)pMem - nPrefixSize; - } - if (nSize) - { - nSize = Align(nSize, nSizeAlign); - nSize += nPrefixSize; - } - - pMem = A::alloc(pMem, nSize, nAlign, bSlack); - - if (nSize) - { - nSize -= nPrefixSize; - } - if (pMem) - { - pMem = (char*)pMem + nPrefixSize; - } - return pMem; - } - }; - - // Stores and retrieves allocator function in memory, for compatibility with diverse allocators - template - struct AllocCompatible - { - void* alloc(void* pMem, size_t& nSize, size_t nAlign, bool bSlack = false) - { - nAlign = NArray::max(nAlign, alignof(Allocator)); - if (pMem) - { - // Retrieve original allocation function, for dealloc or size query - AllocPrefix alloc_prefix; - alloc_prefix.m_Function = ((Allocator*)pMem)[-1]; - return alloc_prefix.alloc(pMem, nSize, nAlign, bSlack); - } - else if (nSize) - { - // Allocate new with this module's base_allocator, storing pointer to function - AllocPrefix alloc_prefix; - pMem = alloc_prefix.alloc(pMem, nSize, nAlign, bSlack); - if (pMem) - { - ((Allocator*)pMem)[-1] = &A::alloc; - } - } - return pMem; - } - }; - - //--------------------------------------------------------------------------- - // Allocators for DynArray. - - // Standard CryModule memory allocation, using aligned versions - struct ModuleAlloc - { - static void* alloc(void* pMem, size_t& nSize, size_t nAlign, bool bSlack = false) - { - if (pMem) - { - if (nSize) - { - // Return memory usage, adding presumed alignment padding - if (nAlign > sizeof(size_t)) - { - nSize += nAlign - sizeof(size_t); - } - } - else - { - // Dealloc - CryModuleMemalignFree(pMem); - } - } - else if (nSize) - { - // Alloc - if (bSlack) - { - nSize = realloc_size(nSize); - } - return CryModuleMemalign(nSize, nAlign); - } - return 0; - } - }; - - // Standard allocator for DynArray stores a compatibility pointer in the memory - typedef AllocCompatible StandardAlloc; -}; - -//--------------------------------------------------------------------------- -// Storage schemes for dynamic arrays -namespace NArray -{ - //--------------------------------------------------------------------------- - // SmallDynStorage: STORAGE scheme for DynArray. - // Array is just a single pointer, size and capacity information stored before the array data. - - template - struct SmallDynStorage - { - template - struct Store - : private A - { - struct Header - { - static const I nCAP_BIT = I(1) << (sizeof(I) * 8 - 1); - - ILINE char* data() const - { - assert(IsAligned(this, sizeof(I))); - return (char*)(this + 1); - } - ILINE bool is_null() const - { return m_nSizeCap == 0; } - ILINE I size() const - { return m_nSizeCap & ~nCAP_BIT; } - - I capacity() const - { - I aligned_bytes = Align(size() * sizeof(T), sizeof(I)); - if (m_nSizeCap & nCAP_BIT) - { - // Capacity stored in word following data - return *(I*)(data() + aligned_bytes); - } - else - { - // Capacity - size < sizeof(I) - return aligned_bytes / sizeof(T); - } - } - - void set_sizes(I s, I c) - { - // Store size, and assert against overflow. - assert(s <= c); - m_nSizeCap = s; - I aligned_bytes = Align(s * sizeof(T), sizeof(I)); - if (c * sizeof(T) >= aligned_bytes + sizeof(I)) - { - // Has extra capacity, more than word-alignment - m_nSizeCap |= nCAP_BIT; - *(I*)(data() + aligned_bytes) = c; - } - assert(size() == s); - assert(capacity() == c); - } - - protected: - I m_nSizeCap; // Store allocation size, with last bit indicating extra capacity. - - public: - - static T* null_header() - { - // m_aElems is never 0, for empty array points to a static empty header. - // Declare a big enough static var to account for alignment. - struct EmptyHeader - { - Header head; - char pad[alignof(T)]; - }; - static EmptyHeader s_EmptyHeader; - - // The actual header pointer can be anywhere in the struct, it's all initialized to 0. - static T* s_EmptyElems = (T*)Align(s_EmptyHeader.pad, alignof(T)); - - return s_EmptyElems; - } - }; - - // Construction. - Store() - { - set_null(); - } - - Store(const A& a) - : A(a) - { - set_null(); - } - - // Basic storage. - CONST_VAR_FUNCTION(T * begin(), - { return m_aElems; - }) - inline I size() const - { return header()->size(); } - inline I capacity() const - { return header()->capacity(); } - size_t get_alloc_size() const - { return is_null() ? 0 : NAlloc::get_alloc_size(allocator(), begin(), capacity() * sizeof(T), alignof(T)); } - - void resize_raw(I new_size, bool allow_slack = false) - { - I new_cap = capacity(); - if (allow_slack ? new_size > new_cap : new_size != new_cap) - { - new_cap = new_size; - m_aElems = NAlloc::reallocate(allocator(), header()->is_null() ? 0 : m_aElems, size(), new_cap, alignof(T), allow_slack); - if (!m_aElems) - { - set_null(); - return; - } - } - header()->set_sizes(new_size, new_cap); - } - - protected: - - T* m_aElems; - - CONST_VAR_FUNCTION(Header * header(), - { - assert(m_aElems); - return ((Header*)m_aElems) - 1; - }) - - void set_null() - { m_aElems = Header::null_header(); } - bool is_null() const - { return header()->is_null(); } - - typedef NAlloc::AllocPrefix AP; - - AP& allocator() - { - COMPILE_TIME_ASSERT(sizeof(AP) == sizeof(A)); - return *(AP*)this; - } - const AP& allocator() const - { - return *(const AP*)this; - } - }; - }; - - //--------------------------------------------------------------------------- - // StaticDynStorage: STORAGE scheme with a statically sized member array. - - template - struct StaticDynStorage - { - template - struct Store - : ArrayStorage::Store - { - Store() - : ArrayStorage::Store((T*)Align(m_aData, alignof(T)), 0) {} - - static I capacity() - { return (I)nSIZE; } - static size_t get_alloc_size() - { return 0; } - - void resize_raw(I new_size, [[maybe_unused]] bool allow_slack = false) - { - // cannot realloc, just set size - assert(new_size >= 0 && new_size <= capacity()); - this->m_nCount = new_size; - } - - protected: - - char m_aData[nSIZE * sizeof(T) + alignof(T) - 1]; // Storage for elems, deferred construction - }; - }; -}; - -// Legacy base class of DynArray, only used for read-only access -#define DynArrayRef DynArray - -//--------------------------------------------------------------------------- -// DynArray: Extension of Array allowing dynamic allocation. -// S specifies storage scheme, as with Array, but adds resize(), capacity(), ... -// A specifies the actual memory allocation function: alloc() - -// NOTE: This version has been re-based on AZStd::vector for correctness and performance -// The original implementation has been retained as LegacyDynArray below, for the few -// cases where we must retain the old internal behavior -template< class T, class I = int, class STORE = NArray::SmallDynStorage<> > -struct DynArray - : public AZStd::vector -{ - typedef AZStd::vector vector_base; - using value_type = typename vector_base::value_type; - using size_type = I; - using iterator = typename vector_base::iterator; - using const_iterator = typename vector_base::const_iterator; - - using vector_base::begin; - using vector_base::end; - - DynArray() - : vector_base::vector() - { - } - - explicit DynArray(size_type numElements) - : vector_base::vector(numElements) - { - } - - DynArray(size_type numElements, const T& value) - : vector_base::vector(numElements, value) - { - } - - // Ignore any specialized allocators, they all pull from the LegacyAllocator now - // Because we mandate that all DynArrays use the StdLegacyAllocator, matching allocators - // isn't meaningful here, so it's factored out - // Note that the STORE/S& is ignored entirely, because we do not support sharing storage - // between 2 DynArrays anymore. LegacyDynArray can still do that, but this feature is no longer used - template >::value>> - explicit DynArray(const S&) - : vector_base::vector() - { - } - - size_type capacity() const - { - return static_cast(vector_base::capacity()); - } - - size_type size() const - { - return static_cast(vector_base::size()); - } - - size_type available() const - { - return capacity() - size(); - } - - size_type get_alloc_size() const - { - return capacity() * sizeof(T); - } - - // Grow array, return iterator to new raw elems. - iterator grow_raw(size_type count = 1, bool /*allow_slack*/ = true) - { - vector_base::resize(size() + count); - return end() - count; - } - - iterator grow(size_type count) - { - return grow_raw(count); - } - iterator grow(size_type count, const T& val) - { - vector_base::reserve(size() + count); - for (size_type idx = 0; idx < count; ++idx) - { - vector_base::push_back(val); - } - return end() - count; - } - - void shrink() - { - // Realloc memory to exact array size. - vector_base::shrink_to_fit(); - } - - void resize(size_type newSize) - { - vector_base::resize(newSize); - } - - void resize(size_type new_size, const T& val) - { - size_type s = size(); - if (new_size > s) - { - grow(new_size - s, val); - } - else - { - pop_back(s - new_size); - } - } - - void assign(const_iterator first, const_iterator last) - { - vector_base::assign(first, last); - } - - void assign(size_type n, const T& val) - { - clear(); - grow(n, val); - } - - iterator push_back() - { - return grow(1); - } - iterator push_back(const T& val) - { - vector_base::push_back(val); - return vector_base::end() - 1; - } - iterator push_back(const DynArray& other) - { - return insert(end(), other.begin(), other.end()); - } - - iterator insert_raw(iterator pos, size_type count = 1) - { - // Grow array, return iterator to inserted raw elems. - assert(pos >= begin() && pos <= end()); - vector_base::insert(pos, count, T()); - return pos; - } - - iterator insert(iterator it, const T& val) - { - vector_base::insert(it, 1, val); - return it; - } - iterator insert(iterator it, size_type count, const T& val) - { - vector_base::insert(it, count, val); - return it; - } - iterator insert(iterator it, const_iterator start, const_iterator finish) - { - vector_base::insert(it, start, finish); - return it; - } - - iterator insert(size_type pos) - { - return insert_raw(begin() + pos); - } - iterator insert(size_type pos, const T& val) - { - iterator it = insert_raw(begin() + pos); - *it = val; - return it; - } - - void pop_back(size_type count = 1, [[maybe_unused]] bool allow_slack = true) - { - // Destroy erased elems, change size without reallocing. - assert(count >= 0 && count <= size()); - for (size_type idx = 0; idx < count; ++idx) - { - vector_base::pop_back(); - } - } - - iterator erase(iterator pos) - { - return vector_base::erase(pos); - } - - iterator erase(iterator start, iterator finish) - { - AZ_Assert(start >= begin() && finish >= start && finish <= end(), "DynArray: Erasure range out of bounds"); - - // Copy over erased elems, destroy those at end. - iterator it = start, e = end(); - while (finish < e) - { - *it++ = *finish++; - } - pop_back(check_cast(finish - it)); - return it; - } - - iterator erase(size_type pos, size_type count = 1) - { - return erase(begin() + pos, begin() + pos + count); - } - - void clear() - { - vector_base::clear(); - vector_base::shrink_to_fit(); - } -}; - -//--------------------------------------------------------------------------- -// Original Cry DynArray -//--------------------------------------------------------------------------- -template< class T, class I = int, class STORE = NArray::SmallDynStorage<> > -struct LegacyDynArray - : Array< T, I, STORE > -{ - typedef LegacyDynArray self_type; - typedef Array super_type; - typedef typename STORE::template Store S; - - // Tedious redundancy for GCC. - using_type(super_type, size_type); - using_type(super_type, iterator); - using_type(super_type, const_iterator); - using_type(super_type, array); - using_type(super_type, const_array); - - using super_type::size; - using super_type::capacity; - using super_type::begin; - using super_type::end; - using super_type::at; - using super_type::copy; - using super_type::init; - using super_type::destroy; - - // - // Construction. - // - LegacyDynArray() - {} - - LegacyDynArray(size_type count) - { - grow(count); - } - LegacyDynArray(size_type count, const T& val) - { - grow(count, val); - } - -#if !defined(_DISALLOW_INITIALIZER_LISTS) - // Initializer-list - LegacyDynArray(std::initializer_list l) - { - push_back(Array(l.begin(), l.size())); - } -#endif - - // Copying from a generic array type. - LegacyDynArray(const_array a) - { - push_back(a); - } - self_type& operator =(const_array a) - { - if (a.begin() >= begin() && a.end() <= end()) - { - // Assigning from (partial) self; remove undesired elements. - erase((T*)a.end(), end()); - erase(begin(), (T*)a.begin()); - } - else - { - // Assert no overlap. - assert(a.end() <= begin() || a.begin() >= end()); - if (a.size() == size()) - { - // If same size, perform element copy. - copy(a); - } - else - { - // If different sizes, destroy then copy init elements. - pop_back(size()); - push_back(a); - } - } - return *this; - } - - // Copy init/assign. - inline LegacyDynArray(const self_type& a) - { - push_back(a()); - } - inline self_type& operator =(const self_type& a) - { - return *this = a(); - } - - // Init/assign from basic storage type. - inline LegacyDynArray(const S& a) - { - push_back(const_array(a.begin(), a.size())); - } - inline self_type& operator =(const S& a) - { - return *this = const_array(a.begin(), a.size()); - } - - inline ~LegacyDynArray() - { - destroy(); - S::resize_raw(0); - } - - void swap(self_type& a) - { - // Swap storage structures, no element copying - S temp = static_cast(*this); - static_cast(*this) = static_cast(a); - static_cast(a) = temp; - } - - inline size_type available() const - { - return capacity() - size(); - } - - // - // Allocation modifiers. - // - - void reserve(size_type count) - { - if (count > capacity()) - { - I s = size(); - S::resize_raw(count, false); - S::resize_raw(s, true); - } - } - - // Grow array, return iterator to new raw elems. - iterator grow_raw(size_type count = 1, bool allow_slack = true) - { - S::resize_raw(size() + count, allow_slack); - return end() - count; - } - Array append_raw(size_type count = 1, bool allow_slack = true) - { - return Array(grow_raw(count, allow_slack), count); - } - - iterator grow(size_type count) - { - return append_raw(count).init(); - } - iterator grow(size_type count, const T& val) - { - return append_raw(count).init(val); - } - - void shrink() - { - // Realloc memory to exact array size. - S::resize_raw(size()); - } - - void resize(size_type new_size) - { - size_type s = size(); - if (new_size > s) - { - append_raw(new_size - s, false).init(); - } - else - { - pop_back(s - new_size, false); - } - } - void resize(size_type new_size, const T& val) - { - size_type s = size(); - if (new_size > s) - { - append_raw(new_size - s, false).init(val); - } - else - { - pop_back(s - new_size, false); - } - } - - void assign(size_type n, const T& val) - { - resize(n); - fill(val); - } - - void assign(const_iterator start, const_iterator finish) - { - *this = const_array(start, finish); - } - - iterator push_back() - { - return grow(1); - } - iterator push_back(const T& val) - { - return grow(1, val); - } - iterator push_back(const_array a) - { - return append_raw(a.size(), false).init(a); - } - - array insert_raw(iterator pos, size_type count = 1) - { - // Grow array, return iterator to inserted raw elems. - assert(pos >= begin() && pos <= end()); - size_t i = pos - begin(); - append_raw(count); - (*this)(i + count).move_init((*this)(i)); - return (*this)(i, count); - } - - iterator insert(iterator it, const T& val) - { - return insert_raw(it, 1).init(val); - } - iterator insert(iterator it, size_type count, const T& val) - { - return insert_raw(it, count).init(val); - } - iterator insert(iterator it, const_iterator start, const_iterator finish) - { - return insert(it, const_array(start, finish)); - } - iterator insert(iterator it, const_array a) - { - return insert_raw(it, a.size()).init(a); - } - - iterator insert(size_type pos) - { - return insert_raw(&at(pos)).init(); - } - iterator insert(size_type pos, const T& val) - { - return insert_raw(&at(pos)).init(val); - } - iterator insert(size_type pos, const_array a) - { - return insert_raw(&at(pos), a.size()).init(a); - } - - void pop_back(size_type count = 1, bool allow_slack = true) - { - // Destroy erased elems, change size without reallocing. - assert(count >= 0 && count <= size()); - size_type new_size = size() - count; - (*this)(new_size).destroy(); - S::resize_raw(new_size, allow_slack); - } - - iterator erase(iterator start, iterator finish) - { - assert(start >= begin() && finish >= start && finish <= end()); - - // Copy over erased elems, destroy those at end. - iterator it = start, e = end(); - while (finish < e) - { - *it++ = *finish++; - } - pop_back(check_cast(finish - it)); - return it; - } - - iterator erase(iterator it) - { - return erase(it, it + 1); - } - - iterator erase(size_type pos, size_type count = 1) - { - return erase(begin() + pos, begin() + pos + count); - } - - void clear() - { - destroy(); - S::resize_raw(0); - } -}; - -template -struct StaticDynArray - : LegacyDynArray< T, I, NArray::StaticDynStorage > -{ -}; - - - - #include "CryPodArray.h" - - -#endif // CRYINCLUDE_CRYCOMMON_CRYARRAY_H diff --git a/Code/CryEngine/CryCommon/CryAssert.h b/Code/CryEngine/CryCommon/CryAssert.h deleted file mode 100644 index 49bbd8a573..0000000000 --- a/Code/CryEngine/CryCommon/CryAssert.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Assert dialog box - -#pragma once - -#include - -//----------------------------------------------------------------------------------------------------- -// Just undef this if you want to use the standard assert function -//----------------------------------------------------------------------------------------------------- - -// if AZ_ENABLE_TRACING is enabled, then calls to AZ_Assert(...) will flow in. This is the case -// even in Profile mode - thus if you want to manage what happens, USE_CRY_ASSERT also needs to be enabled in those cases. -// if USE_CRY_ASSERT is not enabled, but AZ_ENABLE_TRACING is enabled, then the default behavior for assets will occur instead -// which is to throw the DEBUG BREAK exception / signal, which tends to end with application shutdown. -#if defined(AZ_ENABLE_TRACE_ASSERTS) -#define USE_AZ_ASSERT -#endif - -#if !defined (USE_AZ_ASSERT) && defined(AZ_ENABLE_TRACING) -#undef USE_CRY_ASSERT -#define USE_CRY_ASSERT -#endif - -// you can undefine this. It will cause the assert message box to appear anywhere that USE_CRY_ASSERT is enabled -// instead of it only appearing in debug. -// if this is DEFINED then only in debug builds will you see the message box. In other builds, CRY_ASSERTS become CryWarning instead of -// instead (showing no message box, only a warning). -#define CRY_ASSERT_DIALOG_ONLY_IN_DEBUG - -#if defined(FORCE_STANDARD_ASSERT) || defined(USE_AZ_ASSERT) -#undef USE_CRY_ASSERT -#undef CRY_ASSERT_DIALOG_ONLY_IN_DEBUG -#endif - -// Using AZ_Assert for all assert kinds (assert =, CRY_ASSERT, AZ_Assert). -// see Trace::Assert for implementation -#if defined(USE_AZ_ASSERT) - #undef assert - #if !defined(NDEBUG) - #define assert(condition) AZ_Assert(condition, "%s", #condition) - #else - #define assert(condition) - #endif -#endif //defined(USE_AZ_ASSERT) - -//----------------------------------------------------------------------------------------------------- -// Use like this: -// CRY_ASSERT(expression); -// CRY_ASSERT_MESSAGE(expression,"Useful message"); -// CRY_ASSERT_TRACE(expression,("This should never happen because parameter n%d named %s is %f",iParameter,szParam,fValue)); -//----------------------------------------------------------------------------------------------------- - -#if defined(AZ_RESTRICTED_PLATFORM) - #include AZ_RESTRICTED_FILE(CryAssert_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) - #undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(WIN32) || defined(APPLE) || defined(LINUX) - #define CRYASSERT_H_TRAIT_USE_CRY_ASSERT_MESSAGE 1 -#endif - -#if defined(USE_CRY_ASSERT) && CRYASSERT_H_TRAIT_USE_CRY_ASSERT_MESSAGE -void CryAssertTrace(const char*, ...); -bool CryAssert(const char*, const char*, unsigned int, bool*); -void CryDebugBreak(); - - #define CRY_ASSERT(condition) CRY_ASSERT_MESSAGE(condition, NULL) - - #define CRY_ASSERT_MESSAGE(condition, message) CRY_ASSERT_TRACE(condition, (message)) - - #define CRY_ASSERT_TRACE(condition, parenthese_message) \ - do \ - { \ - static bool s_bIgnoreAssert = false; \ - if (!s_bIgnoreAssert && !(condition)) \ - { \ - CryAssertTrace parenthese_message; \ - if (CryAssert(#condition, __FILE__, __LINE__, &s_bIgnoreAssert)) \ - { \ - DEBUG_BREAK; \ - } \ - } \ - } while (0) - - #undef assert - #define assert CRY_ASSERT -#elif !defined(CRY_ASSERT) -#ifndef USE_AZ_ASSERT - #include -#endif //USE_AZ_ASSERT - #define CRY_ASSERT(condition) assert(condition) - #define CRY_ASSERT_MESSAGE(condition, message) assert(condition) - #define CRY_ASSERT_TRACE(condition, parenthese_message) assert(condition) -#endif - -//----------------------------------------------------------------------------------------------------- diff --git a/Code/CryEngine/CryCommon/CryAssert_Android.h b/Code/CryEngine/CryCommon/CryAssert_Android.h deleted file mode 100644 index ccc72f0bd7..0000000000 --- a/Code/CryEngine/CryCommon/CryAssert_Android.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Assert dialog box for android - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYASSERT_ANDROID_H -#define CRYINCLUDE_CRYCOMMON_CRYASSERT_ANDROID_H -#pragma once - -#if defined(USE_CRY_ASSERT) && defined(ANDROID) - -#include - -static char gs_szMessage[MAX_PATH]; - -void CryAssertTrace(const char* szFormat, ...) -{ - if (gEnv == 0) - { - return; - } - - if (!gEnv->bIgnoreAllAsserts) - { - if (szFormat == NULL) - { - gs_szMessage[0] = '\0'; - } - else - { - va_list args; - va_start(args, szFormat); - vsnprintf(gs_szMessage, sizeof(gs_szMessage), szFormat, args); - va_end(args); - } - } -} - -bool CryAssert(const char* szCondition, const char* szFile, unsigned int line, bool* pIgnore) -{ - if (!gEnv) - { - return true; - } - -#if defined(CRY_ASSERT_DIALOG_ONLY_IN_DEBUG) && !defined(AZ_DEBUG_BUILD) - // we are in a non-debug build, so we should turn this into a warning instead. - if ((gEnv) && (gEnv->pLog)) - { - if (!gEnv->bIgnoreAllAsserts) - { - gEnv->pLog->LogWarning("%s(%u): Assertion failed - \"%s\"", szFile, line, szCondition); - } - } - - if (pIgnore) - { - // avoid showing the same one repeatedly. - *pIgnore = true; - } - return false; -#endif - - gEnv->pSystem->OnAssert(szCondition, gs_szMessage, szFile, line); - - if (!gEnv->bNoAssertDialog && !gEnv->bIgnoreAllAsserts) - { - AZ::NativeUI::AssertAction result; - EBUS_EVENT_RESULT(result, AZ::NativeUI::NativeUIRequestBus, DisplayAssertDialog, gs_szMessage); - - switch (result) - { - case AZ::NativeUI::AssertAction::IGNORE_ASSERT: - return false; - case AZ::NativeUI::AssertAction::IGNORE_ALL_ASSERTS: - gEnv->bNoAssertDialog = true; - gEnv->bIgnoreAllAsserts = true; - return false; - case AZ::NativeUI::AssertAction::BREAK: - return true; - default: - break; - } - - return true; - } - else - { - return false; - } -} - -#endif -#endif // CRYINCLUDE_CRYCOMMON_CRYASSERT_ANDROID_H diff --git a/Code/CryEngine/CryCommon/CryAssert_Linux.h b/Code/CryEngine/CryCommon/CryAssert_Linux.h deleted file mode 100644 index 918977734e..0000000000 --- a/Code/CryEngine/CryCommon/CryAssert_Linux.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - - -// Description : -// Assert dialog box for LINUX. The linux assert dialog is based on a -// small ncurses application which writes the choice to a file. This -// was chosen since there is no default UI system on Linux. X11 wasn't -// used due to the possibility of the system running another display -// protocol (e.g.: WayLand, Mir) - -#ifndef CRYINCLUDE_CRYCOMMON_CRYASSERT_LINUX_H -#define CRYINCLUDE_CRYCOMMON_CRYASSERT_LINUX_H -#pragma once - -#if defined(USE_CRY_ASSERT) && defined(LINUX) && !defined(ANDROID) - -static char gs_szMessage[MAX_PATH]; - -void CryAssertTrace(const char* szFormat, ...) -{ - if (gEnv == 0) - { - return; - } - - if (!gEnv->bIgnoreAllAsserts) - { - if (szFormat == NULL) - { - gs_szMessage[0] = '\0'; - } - else - { - va_list args; - va_start(args, szFormat); - vsnprintf(gs_szMessage, sizeof(gs_szMessage), szFormat, args); - va_end(args); - } - } -} - -bool CryAssert(const char* szCondition, const char* szFile, unsigned int line, bool* pIgnore) -{ - if (!gEnv) - { - return false; - } - -#if defined(CRY_ASSERT_DIALOG_ONLY_IN_DEBUG) && !defined(AZ_DEBUG_BUILD) - // we are in a non-debug build, so we should turn this into a warning instead. - if (gEnv->pLog) - { - if (!gEnv->bIgnoreAllAsserts) - { - gEnv->pLog->LogWarning("%s(%u): Assertion failed - \"%s\"", szFile, line, szCondition); - } - } - if (pIgnore) - { - // avoid showing the same one repeatedly. - *pIgnore = true; - } - return false; -#endif - - static const int max_len = 4096; - static char gs_command_str[4096]; - static CryLockT lock; - - gEnv->pSystem->OnAssert(szCondition, gs_szMessage, szFile, line); - - size_t file_len = strlen(szFile); - - if (!gEnv->bNoAssertDialog && !gEnv->bIgnoreAllAsserts) - { - CryAutoLock< CryLockT > lk (lock); - snprintf(gs_command_str, max_len, "xterm -geometry 100x20 -n 'Assert Dialog [Linux Launcher]' -T 'Assert Dialog [Linux Launcher]' -e 'BinLinux/assert_term \"%s\" \"%s\" %d \"%s\"; echo \"$?\" > .assert_return'", - szCondition, (file_len > 60) ? szFile + (file_len - 61) : szFile, line, gs_szMessage); - int ret = system(gs_command_str); - if (ret != 0) - { - CryLogAlways(" Terminal failed to execute"); - return false; - } - - FILE* assert_file = fopen(".assert_return", "r"); - if (!assert_file) - { - CryLogAlways(" Couldn't open assert file"); - return false; - } - int result = -1; - fscanf(assert_file, "%d", &result); - fclose(assert_file); - - switch (result) - { - case 0: - break; - case 1: - *pIgnore = true; - break; - case 2: - gEnv->bIgnoreAllAsserts = true; - break; - case 3: - return true; - break; - case 4: - raise(SIGABRT); - exit(-1); - break; - default: - CryLogAlways(" Unknown result in assert file: %d", result); - return false; - } - } - - - return false; -} - -#endif - -#endif // CRYINCLUDE_CRYCOMMON_CRYASSERT_LINUX_H diff --git a/Code/CryEngine/CryCommon/CryAssert_Mac.h b/Code/CryEngine/CryCommon/CryAssert_Mac.h deleted file mode 100644 index c618fb8c91..0000000000 --- a/Code/CryEngine/CryCommon/CryAssert_Mac.h +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Assert dialog box for Mac OS X - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYASSERT_MAC_H -#define CRYINCLUDE_CRYCOMMON_CRYASSERT_MAC_H -#pragma once - -#if defined(USE_CRY_ASSERT) && defined(MAC) -#include - -static char gs_szMessage[MAX_PATH]; - -void CryAssertTrace(const char* szFormat, ...) -{ - if (gEnv == 0) - { - return; - } - - if (!gEnv->bIgnoreAllAsserts) - { - if (szFormat == NULL) - { - gs_szMessage[0] = '\0'; - } - else - { - va_list args; - va_start(args, szFormat); - vsnprintf(gs_szMessage, sizeof(gs_szMessage), szFormat, args); - va_end(args); - } - } -} - -bool CryAssert(const char* szCondition, const char* szFile, unsigned int line, bool* pIgnore) -{ - if (!gEnv) - { - return false; - } - -#if defined(CRY_ASSERT_DIALOG_ONLY_IN_DEBUG) && !defined(AZ_DEBUG_BUILD) - // we are in a non-debug build, so we should turn this into a warning instead. - if ((gEnv) && (gEnv->pLog)) - { - if (!gEnv->bIgnoreAllAsserts) - { - gEnv->pLog->LogWarning("%s(%u): Assertion failed - \"%s\"", szFile, line, szCondition); - } - } - - if (pIgnore) - { - // avoid showing the same one repeatedly. - *pIgnore = true; - } - return false; -#endif - - static const int max_len = 4096; - static char gs_command_str[4096]; - - static CryLockT lock; - - gEnv->pSystem->OnAssert(szCondition, gs_szMessage, szFile, line); - - size_t file_len = strlen(szFile); - - if (!gEnv->bNoAssertDialog && !gEnv->bIgnoreAllAsserts) - { - AZ::NativeUI::AssertAction result; - EBUS_EVENT_RESULT(result, AZ::NativeUI::NativeUIRequestBus, DisplayAssertDialog, gs_szMessage); - - switch(result) - { - case AZ::NativeUI::AssertAction::IGNORE_ASSERT: - return false; - case AZ::NativeUI::AssertAction::IGNORE_ALL_ASSERTS: - gEnv->bNoAssertDialog = true; - gEnv->bIgnoreAllAsserts = true; - return false; - case AZ::NativeUI::AssertAction::BREAK: - return true; - default: - break; - } - - // For asserts on the Mac always trigger a debug break. Annoying but at least it does not kill the thread like assert() does. - __asm__("int $3"); - } - - - return false; -} - - -#endif - -#endif // CRYINCLUDE_CRYCOMMON_CRYASSERT_MAC_H diff --git a/Code/CryEngine/CryCommon/CryAssert_iOS.h b/Code/CryEngine/CryCommon/CryAssert_iOS.h deleted file mode 100644 index d238a72d72..0000000000 --- a/Code/CryEngine/CryCommon/CryAssert_iOS.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Assert dialog box for Mac OS X - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYASSERT_IOS_H -#define CRYINCLUDE_CRYCOMMON_CRYASSERT_IOS_H -#pragma once - -#if defined(USE_CRY_ASSERT) && (defined(IOS) - -#include - -static char gs_szMessage[MAX_PATH]; - -void CryAssertTrace(const char* szFormat, ...) -{ - if (gEnv == 0) - { - return; - } - - if (!gEnv->bIgnoreAllAsserts) - { - if (szFormat == NULL) - { - gs_szMessage[0] = '\0'; - } - else - { - va_list args; - va_start(args, szFormat); - vsnprintf(gs_szMessage, sizeof(gs_szMessage), szFormat, args); - va_end(args); - } - } -} - -bool CryAssert(const char* szCondition, const char* szFile, unsigned int line, bool* pIgnore) -{ - if (!gEnv) - { - return false; - } - -#if defined(CRY_ASSERT_DIALOG_ONLY_IN_DEBUG) && !defined(AZ_DEBUG_BUILD) - // we are in a non-debug build, so we should turn this into a warning instead. - if ((gEnv) && (gEnv->pLog)) - { - if (!gEnv->bIgnoreAllAsserts) - { - gEnv->pLog->LogWarning("%s(%u): Assertion failed - \"%s\"", szFile, line, szCondition); - } - } - - if (pIgnore) - { - // avoid showing the same one repeatedly. - *pIgnore = true; - } - return false; -#endif - - gEnv->pSystem->OnAssert(szCondition, gs_szMessage, szFile, line); - - if (!gEnv->bNoAssertDialog && !gEnv->bIgnoreAllAsserts) - { - printf("!!ASSERT!!\n\tCondition: %s\n\tMessage : %s\n\tFile : %s\n\tLine : %d", szCondition, gs_szMessage, szFile, line); - - AZ::NativeUI::AssertAction result; - EBUS_EVENT_RESULT(result, AZ::NativeUI::NativeUIRequestBus, DisplayAssertDialog, gs_szMessage); - - switch(result) - { - case AZ::NativeUI::AssertAction::IGNORE_ASSERT: - return false; - case AZ::NativeUI::AssertAction::IGNORE_ALL_ASSERTS: - gEnv->bNoAssertDialog = true; - gEnv->bIgnoreAllAsserts = true; - return false; - case AZ::NativeUI::AssertAction::BREAK: - return true; - default: - break; - } - } - return false; -} - -#endif - -#endif // CRYINCLUDE_CRYCOMMON_CRYASSERT_IOS_H diff --git a/Code/CryEngine/CryCommon/CryAssert_impl.h b/Code/CryEngine/CryCommon/CryAssert_impl.h deleted file mode 100644 index e279b01c6a..0000000000 --- a/Code/CryEngine/CryCommon/CryAssert_impl.h +++ /dev/null @@ -1,468 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Assert dialog box - -#pragma once - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define CRYASSERT_IMPL_H_SECTION_1 1 -#define CRYASSERT_IMPL_H_SECTION_2 2 -#endif - -#if defined(USE_CRY_ASSERT) -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYASSERT_IMPL_H_SECTION_1 - #include AZ_RESTRICTED_FILE(CryAssert_impl_h) -#endif - -#if defined(APPLE) -#if defined(MAC) -#include "CryAssert_Mac.h" -#else -#include "CryAssert_iOS.h" -#endif -#endif - -#if defined(LINUX) -#if defined(ANDROID) -#include "CryAssert_Android.h" -#else -#include "CryAssert_Linux.h" -#endif -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYASSERT_IMPL_H_SECTION_2 - #include AZ_RESTRICTED_FILE(CryAssert_impl_h) -#elif defined(WIN32) - -//----------------------------------------------------------------------------------------------------- - -#include - -#define WIN32_LEAN_AND_MEAN -#include - -//----------------------------------------------------------------------------------------------------- - -#define IDD_DIALOG_ASSERT 101 -#define IDC_CRYASSERT_EDIT_LINE 1000 -#define IDC_CRYASSERT_EDIT_FILE 1001 -#define IDC_CRYASSERT_EDIT_CONDITION 1002 -#define IDC_CRYASSERT_BUTTON_CONTINUE 1003 -#define IDC_CRYASSERT_EDIT_REASON 1004 -#define IDC_CRYASSERT_BUTTON_IGNORE 1005 -#define IDC_CRYASSERT_BUTTON_STOP 1007 -#define IDC_CRYASSERT_BUTTON_BREAK 1008 -#define IDC_CRYASSERT_BUTTON_IGNORE_ALL 1009 - -#define IDC_CRYASSERT_STATIC_TEXT 0 - -#define DLG_TITLE L"Assertion Failed" -#define DLG_FONT L"MS Sans Serif" -#define DLG_ITEM_TEXT_0 L"Continue" -#define DLG_ITEM_TEXT_1 L"Stop" -#define DLG_ITEM_TEXT_2 L"Info" -#define DLG_ITEM_TEXT_3 L"" -#define DLG_ITEM_TEXT_4 L"Line" -#define DLG_ITEM_TEXT_5 L"" -#define DLG_ITEM_TEXT_6 L"File" -#define DLG_ITEM_TEXT_7 L"Condition" -#define DLG_ITEM_TEXT_8 L"" -#define DLG_ITEM_TEXT_9 L"failed" -#define DLG_ITEM_TEXT_10 L"" -#define DLG_ITEM_TEXT_11 L"Reason" -#define DLG_ITEM_TEXT_12 L"Ignore" - -#define DLG_ITEM_TEXT_14 L"Break" -#define DLG_ITEM_TEXT_15 L"Ignore All" - -#define DLG_NB_ITEM 15 - - -template -struct SDlgItem -{ - // If use my struct instead of DLGTEMPLATE, or else (for some strange reason) it is not DWORD aligned !! - DWORD style; - DWORD dwExtendedStyle; - short x; - short y; - short cx; - short cy; - WORD id; - WORD ch; - WORD c; - WCHAR t[iTitleSize]; - WORD dummy; -}; -#define SDLGITEM(TEXT, V) SDlgItem V; - -struct SDlgData -{ - DLGTEMPLATE dlt; - WORD _menu; - WORD _class; - WCHAR _title[sizeof(DLG_TITLE) / 2]; - WORD pointSize; - WCHAR _font[sizeof(DLG_FONT) / 2]; - - SDLGITEM(DLG_ITEM_TEXT_0, i0); - SDLGITEM(DLG_ITEM_TEXT_12, i12); - SDLGITEM(DLG_ITEM_TEXT_15, i15); - SDLGITEM(DLG_ITEM_TEXT_14, i14); - SDLGITEM(DLG_ITEM_TEXT_1, i1); - SDLGITEM(DLG_ITEM_TEXT_2, i2); - SDLGITEM(DLG_ITEM_TEXT_3, i3); - SDLGITEM(DLG_ITEM_TEXT_4, i4); - SDLGITEM(DLG_ITEM_TEXT_5, i5); - SDLGITEM(DLG_ITEM_TEXT_6, i6); - SDLGITEM(DLG_ITEM_TEXT_7, i7); - SDLGITEM(DLG_ITEM_TEXT_8, i8); - SDLGITEM(DLG_ITEM_TEXT_9, i9); - SDLGITEM(DLG_ITEM_TEXT_10, i10); - SDLGITEM(DLG_ITEM_TEXT_11, i11); -}; - -//----------------------------------------------------------------------------------------------------- - -static SDlgData g_dialogRC = -{ - {DS_SETFOREGROUND | DS_MODALFRAME | DS_3DLOOK | DS_SETFONT | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE, 0, DLG_NB_ITEM, 0, 0, 330, 134}, 0, 0, DLG_TITLE, 8, DLG_FONT, - {BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP, 0, 12, 113, 50, 14, IDC_CRYASSERT_BUTTON_CONTINUE, 0xFFFF, 0x0080, DLG_ITEM_TEXT_0, 0}, - {BS_DEFPUSHBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP, 0, 66, 113, 50, 14, IDC_CRYASSERT_BUTTON_IGNORE, 0xFFFF, 0x0080, DLG_ITEM_TEXT_12, 0}, - {BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP, 0, 120, 113, 50, 14, IDC_CRYASSERT_BUTTON_IGNORE_ALL, 0xFFFF, 0x0080, DLG_ITEM_TEXT_15, 0}, - {BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP, 0, 214, 113, 50, 14, IDC_CRYASSERT_BUTTON_BREAK, 0xFFFF, 0x0080, DLG_ITEM_TEXT_14, 0}, - {BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE | WS_TABSTOP, 0, 268, 113, 50, 14, IDC_CRYASSERT_BUTTON_STOP, 0xFFFF, 0x0080, DLG_ITEM_TEXT_1, 0}, - {BS_GROUPBOX | WS_CHILD | WS_VISIBLE, 0, 7, 7, 316, 100, IDC_CRYASSERT_STATIC_TEXT, 0xFFFF, 0x0080, DLG_ITEM_TEXT_2, 0}, - {ES_LEFT | ES_AUTOHSCROLL | ES_READONLY | WS_BORDER | WS_CHILD | WS_VISIBLE, 0, 50, 48, 25, 13, IDC_CRYASSERT_EDIT_LINE, 0xFFFF, 0x0081, DLG_ITEM_TEXT_3, 0}, - {WS_CHILD | WS_VISIBLE, 0, 14, 50, 14, 8, IDC_CRYASSERT_STATIC_TEXT, 0xFFFF, 0x0082, DLG_ITEM_TEXT_4, 0}, - {ES_LEFT | ES_AUTOHSCROLL | ES_READONLY | WS_BORDER | WS_CHILD | WS_VISIBLE, 0, 50, 32, 240, 13, IDC_CRYASSERT_EDIT_FILE, 0xFFFF, 0x0081, DLG_ITEM_TEXT_5, 0}, - {WS_CHILD | WS_VISIBLE, 0, 14, 34, 12, 8, IDC_CRYASSERT_STATIC_TEXT, 0xFFFF, 0x0082, DLG_ITEM_TEXT_6, 0}, - {WS_CHILD | WS_VISIBLE, 0, 13, 18, 30, 8, IDC_CRYASSERT_STATIC_TEXT, 0xFFFF, 0x0082, DLG_ITEM_TEXT_7, 0}, - {ES_LEFT | ES_AUTOHSCROLL | ES_READONLY | WS_BORDER | WS_CHILD | WS_VISIBLE, 0, 50, 16, 240, 13, IDC_CRYASSERT_EDIT_CONDITION, 0xFFFF, 0x0081, DLG_ITEM_TEXT_8, 0}, - {WS_CHILD | WS_VISIBLE, 0, 298, 19, 18, 8, IDC_CRYASSERT_STATIC_TEXT, 0xFFFF, 0x0082, DLG_ITEM_TEXT_9, 0}, - {ES_LEFT | ES_AUTOHSCROLL | ES_READONLY | WS_BORDER | WS_CHILD | WS_VISIBLE, 0, 50, 67, 240, 13, IDC_CRYASSERT_EDIT_REASON, 0xFFFF, 0x0081, DLG_ITEM_TEXT_10, 0}, - {WS_CHILD | WS_VISIBLE, 0, 15, 69, 26, 8, IDC_CRYASSERT_STATIC_TEXT, 0xFFFF, 0x0082, DLG_ITEM_TEXT_11, 0}, -}; - -//----------------------------------------------------------------------------------------------------- - -struct SCryAssertInfo -{ - const char* pszCondition; - const char* pszFile; - const char* pszMessage; - - unsigned int uiLine; - - enum - { - BUTTON_CONTINUE, - BUTTON_IGNORE, - BUTTON_IGNORE_ALL, - BUTTON_BREAK, - BUTTON_STOP, - BUTTON_REPORT_AS_BUG, - } btnChosen; - - unsigned int uiX; - unsigned int uiY; -}; - -//----------------------------------------------------------------------------------------------------- - -static INT_PTR CALLBACK DlgProc(HWND _hDlg, UINT _uiMsg, WPARAM _wParam, LPARAM _lParam) -{ - static SCryAssertInfo* pAssertInfo = NULL; - - const UINT WM_USER_SHOWFILE_MESSAGE = (WM_USER + 0x4000); - - switch (_uiMsg) - { - case WM_INITDIALOG: - { - pAssertInfo = (SCryAssertInfo*) _lParam; - - SetWindowText(GetDlgItem(_hDlg, IDC_CRYASSERT_EDIT_CONDITION), pAssertInfo->pszCondition); - SetWindowText(GetDlgItem(_hDlg, IDC_CRYASSERT_EDIT_FILE), pAssertInfo->pszFile); - - // Want to move the cursor on the file text, so that the end of the file is the first thing visible, - // instead of the beginning, which will be the user's depot, and the same for pretty much every file. - // Have to do this delayed, because if it's done in WM_INITDIALOG, it doesn't work. - // PostMessage will add this to the end of the message queue. - PostMessage(_hDlg, WM_USER_SHOWFILE_MESSAGE, 0, 0); - - char szLine[MAX_PATH]; - sprintf_s(szLine, "%d", pAssertInfo->uiLine); - SetWindowText(GetDlgItem(_hDlg, IDC_CRYASSERT_EDIT_LINE), szLine); - - if (pAssertInfo->pszMessage && pAssertInfo->pszMessage[0] != '\0') - { - SetWindowText(GetDlgItem(_hDlg, IDC_CRYASSERT_EDIT_REASON), pAssertInfo->pszMessage); - } - else - { - SetWindowText(GetDlgItem(_hDlg, IDC_CRYASSERT_EDIT_REASON), "No Reason"); - } - - SetWindowPos(_hDlg, HWND_TOPMOST, pAssertInfo->uiX, pAssertInfo->uiY, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE); - - break; - } - - case WM_USER_SHOWFILE_MESSAGE: - { - // Still have to delay sending this message, or it won't work for some reason. - // Windows does a whole bunch of stuff behind the scenes. Using PostMessage here seems to work better. - PostMessage(GetDlgItem(_hDlg, IDC_CRYASSERT_EDIT_FILE), EM_SETSEL, strlen(pAssertInfo->pszFile), -1); - break; - } - - case WM_COMMAND: - { - switch (LOWORD(_wParam)) - { - case IDCANCEL: - case IDC_CRYASSERT_BUTTON_CONTINUE: - { - pAssertInfo->btnChosen = SCryAssertInfo::BUTTON_CONTINUE; - EndDialog(_hDlg, 0); - break; - } - case IDC_CRYASSERT_BUTTON_IGNORE: - { - pAssertInfo->btnChosen = SCryAssertInfo::BUTTON_IGNORE; - EndDialog(_hDlg, 0); - break; - } - case IDC_CRYASSERT_BUTTON_IGNORE_ALL: - { - pAssertInfo->btnChosen = SCryAssertInfo::BUTTON_IGNORE_ALL; - EndDialog(_hDlg, 0); - break; - } - case IDC_CRYASSERT_BUTTON_BREAK: - { - pAssertInfo->btnChosen = SCryAssertInfo::BUTTON_BREAK; - EndDialog(_hDlg, 0); - break; - } - case IDC_CRYASSERT_BUTTON_STOP: - { - pAssertInfo->btnChosen = SCryAssertInfo::BUTTON_STOP; - EndDialog(_hDlg, 1); - break; - } - default: - break; - } - ; - break; - } - - case WM_DESTROY: - { - if (pAssertInfo) - { - RECT rcWindowBounds; - GetWindowRect(_hDlg, &rcWindowBounds); - pAssertInfo->uiX = rcWindowBounds.left; - pAssertInfo->uiY = rcWindowBounds.top; - } - break; - } - - default: - return FALSE; - } - ; - - return TRUE; -} - -//----------------------------------------------------------------------------------------------------- - -static char gs_szMessage[MAX_PATH]; - -//----------------------------------------------------------------------------------------------------- - -void CryAssertTrace(const char* _pszFormat, ...) -{ - if (gEnv == 0) - { - return; - } - if (!gEnv->bIgnoreAllAsserts) - { - if (NULL == _pszFormat) - { - gs_szMessage[0] = '\0'; - } - else - { - va_list args; - va_start(args, _pszFormat); - vsnprintf_s(gs_szMessage, sizeof(gs_szMessage), _TRUNCATE, _pszFormat, args); - va_end(args); - } - } -} - -//----------------------------------------------------------------------------------------------------- - -static const char* gs_strRegSubKey = "Software\\O3DE\\AssertWindow"; -static const char* gs_strRegXValue = "AssertInfoX"; -static const char* gs_strRegYValue = "AssertInfoY"; - -//----------------------------------------------------------------------------------------------------- - -void RegistryReadUInt32(const char* _strSubKey, const char* _strRegName, unsigned int* _puiValue, unsigned int _uiDefault) -{ - HKEY hKey; - RegCreateKeyEx(HKEY_CURRENT_USER, _strSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, NULL); - - DWORD dwType; - DWORD dwLength = sizeof(DWORD); - - if (ERROR_SUCCESS != RegQueryValueEx(hKey, _strRegName, 0, &dwType, (BYTE*) _puiValue, &dwLength)) - { - *_puiValue = _uiDefault; - } - - RegCloseKey(hKey); -} - -//----------------------------------------------------------------------------------------------------- - -void RegistryWriteUInt32(const char* _strSubKey, const char* _strRegName, unsigned int _uiValue) -{ - HKEY hKey; - RegCreateKeyEx(HKEY_CURRENT_USER, _strSubKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, NULL); - RegSetValueEx (hKey, _strRegName, 0, REG_DWORD, (BYTE*) &_uiValue, sizeof(DWORD)); - RegCloseKey (hKey); -} - -//----------------------------------------------------------------------------------------------------- - -class CCursorShowerWithStack -{ -public: - void StoreCurrentAndShow() - { - m_numberOfShows = 1; - - while (ShowCursor(TRUE) < 0) - { - ++m_numberOfShows; - } - } - - void RevertToPrevious() - { - while (m_numberOfShows > 0) - { - ShowCursor(FALSE); - --m_numberOfShows; - } - } - -private: - int m_numberOfShows; -}; - -bool CryAssert(const char* _pszCondition, const char* _pszFile, unsigned int _uiLine, bool* _pbIgnore) -{ - if (!gEnv) - { - return false; - } - -#if defined(CRY_ASSERT_DIALOG_ONLY_IN_DEBUG) && !defined(AZ_DEBUG_BUILD) - // we are in a non-debug build, so we should turn this into a warning instead. - if ((gEnv) && (gEnv->pLog)) - { - if (!gEnv->bIgnoreAllAsserts) - { - gEnv->pLog->LogWarning("%s(%u): Assertion failed - \"%s\"", _pszFile, _uiLine, _pszCondition); - } - } - - if (_pbIgnore) - { - // avoid showing the same one repeatedly. - *_pbIgnore = true; - } - return false; -#endif - - if (!gEnv->bNoAssertDialog && !gEnv->bIgnoreAllAsserts) - { - SCryAssertInfo assertInfo; - - assertInfo.pszCondition = _pszCondition; - assertInfo.pszFile = _pszFile; - assertInfo.pszMessage = gs_szMessage; - assertInfo.uiLine = _uiLine; - assertInfo.btnChosen = SCryAssertInfo::BUTTON_CONTINUE; - - gEnv->pSystem->SetAssertVisible(true); - RegistryReadUInt32(gs_strRegSubKey, gs_strRegXValue, &assertInfo.uiX, 10); - RegistryReadUInt32(gs_strRegSubKey, gs_strRegYValue, &assertInfo.uiY, 10); - - CCursorShowerWithStack cursorShowerWithStack; - cursorShowerWithStack.StoreCurrentAndShow(); - - DialogBoxIndirectParam(GetModuleHandle(NULL), (DLGTEMPLATE*) &g_dialogRC, GetDesktopWindow(), DlgProc, (LPARAM) &assertInfo); - - cursorShowerWithStack.RevertToPrevious(); - - RegistryWriteUInt32(gs_strRegSubKey, gs_strRegXValue, assertInfo.uiX); - RegistryWriteUInt32(gs_strRegSubKey, gs_strRegYValue, assertInfo.uiY); - gEnv->pSystem->SetAssertVisible(false); - - switch (assertInfo.btnChosen) - { - case SCryAssertInfo::BUTTON_IGNORE: - *_pbIgnore = true; - break; - case SCryAssertInfo::BUTTON_IGNORE_ALL: - gEnv->bIgnoreAllAsserts = true; - break; - case SCryAssertInfo::BUTTON_BREAK: - return true; - case SCryAssertInfo::BUTTON_STOP: - raise(SIGABRT); - exit(-1); - case SCryAssertInfo::BUTTON_REPORT_AS_BUG: - if (gEnv && gEnv->pSystem) - { - const char* pszSafeMessage = (assertInfo.pszMessage && assertInfo.pszMessage[0]) ? assertInfo.pszMessage : ""; - gEnv->pSystem->ReportBug("Assert: %s - %s", assertInfo.pszCondition, pszSafeMessage); - } - break; - } - } - - if (gEnv && gEnv->pSystem) - { - // this also can cause fatal / shutdown behavior: - gEnv->pSystem->OnAssert(_pszCondition, gs_szMessage, _pszFile, _uiLine); - } - - return false; -} - -//----------------------------------------------------------------------------------------------------- - -#endif -#endif - -//----------------------------------------------------------------------------------------------------- diff --git a/Code/CryEngine/CryCommon/CryCommon.cpp b/Code/CryEngine/CryCommon/CryCommon.cpp deleted file mode 100644 index a8caf86bb4..0000000000 --- a/Code/CryEngine/CryCommon/CryCommon.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - - -// This contains compiled code that is used by other projects in the solution. -// Because we don't want static DLL dependencies, the CryCommon project is not compiled into a library. -// Instead, this .cpp file is included in every project which needs it. -// But we also include it in the CryCommon project (disabled in the build), -// so that CryCommon can have the same editable settings as other projects. - -// Set this to 1 to get an output of some pre-defined compiler symbols. - -#if 0 - -#ifdef _WIN32 -#pragma message("_WIN32") -#endif -#ifdef _WIN64 -#pragma message("_WIN64") -#endif - -#ifdef _M_IX86 -#pragma message("_M_IX86") -#endif -#ifdef _M_PPC -#pragma message("_M_PPC") -#endif - -#ifdef _DEBUG -#pragma message("_DEBUG") -#endif - -#ifdef _DLL -#pragma message("_DLL") -#endif -#ifdef _USRDLL -#pragma message("_USRDLL") -#endif -#ifdef _MT -#pragma message("_MT") -#endif - -#endif - -#include - -#include "TypeInfo_impl.h" diff --git a/Code/CryEngine/CryCommon/CryCrc32.h b/Code/CryEngine/CryCommon/CryCrc32.h deleted file mode 100644 index 73c14bacea..0000000000 --- a/Code/CryEngine/CryCommon/CryCrc32.h +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include "BaseTypes.h" - -// CRC-32 -// -// Polynomial: -// 0x04C11DB7 -// x^32 + x^26 + x^23 + x^22 + x^16 + x^12 + x^11 + x^10 + x^8 + x^7 + x^5 + x^4 + x^2 + x + 1 -// -// Validation: -// CCrc32::Compute("123456789") == 0xCBF43926 -// -// Examples of using: -// -// printf("crc32: %08x\n", (unsigned)CCrc32::Compute(ptr, size)); -// -// CCrc32 crc; -// crc.Add(ptr0, size0); -// crc.Add(ptr1, size1); -// printf("crc32: %08x\n", (unsigned)crc.Get()); - -class CCrc32 -{ -public: - static uint32 Compute(const void* const pData, const size_t sizeInBytes) - { - CCrc32 c; - c.Add(pData, sizeInBytes); - return c.Get(); - } - - static uint32 Compute(const char* const szData) - { - CCrc32 c; - c.Add(szData); - return c.Get(); - } - - static uint32 ComputeLowercase(const char* const pData, const size_t sizeInBytes) - { - CCrc32 c; - c.AddLowercase(pData, sizeInBytes); - return c.Get(); - } - - static uint32 ComputeLowercase(const char* const szData) - { - CCrc32 c; - c.AddLowercase(szData); - return c.Get(); - } - - - CCrc32() - : m_crc(0xFFFFffff) - , m_pTable(GetTable()) - { - } - - CCrc32(unsigned int initializer) - : m_crc(initializer) - , m_pTable(GetTable()) - { - } - - void Reset() - { - m_crc = 0xFFFFffff; - } - - uint32 Get() const - { - return ~m_crc; - } - - unsigned int Add(const void* const pData, size_t sizeInBytes) - { - const uint8* p = (const uint8*)pData; - while (sizeInBytes--) - { - m_crc = (m_crc >> 8) ^ m_pTable[(m_crc & 0xFF) ^ (*p++)]; - } - return Get(); - } - - unsigned int Add(const char* szData) - { - while (*szData) - { - m_crc = (m_crc >> 8) ^ m_pTable[(m_crc & 0xFF) ^ uint8(*szData++)]; - } - return Get(); - } - -#if defined(CRY_TMP_ASCII_TO_LOWER) -# error CRY_TMP_ASCII_TO_LOWER already defined -#endif -#define CRY_TMP_ASCII_TO_LOWER(c) uint8(((c) <= 'Z' && (c) >= 'A') ? (c) + ('a' - 'A') : (c)) - - unsigned int AddLowercase(const char* pData, size_t sizeInBytes) - { - while (sizeInBytes--) - { - const uint8 c = *pData++; - m_crc = (m_crc >> 8) ^ m_pTable[(m_crc & 0xFF) ^ CRY_TMP_ASCII_TO_LOWER(c)]; - } - return Get(); - } - - unsigned int AddLowercase(const char* szData) - { - while (*szData) - { - const uint8 c = *szData++; - m_crc = (m_crc >> 8) ^ m_pTable[(m_crc & 0xFF) ^ CRY_TMP_ASCII_TO_LOWER(c)]; - } - return Get(); - } - -#undef CRY_TMP_ASCII_TO_LOWER - -private: - static const uint32* GetTable() - { - static const uint32 table[256] = - { - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, - 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, - 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, - 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, - 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, - 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, - 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, - 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, - 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, - 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, - 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, - 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, - 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, - 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, - 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, - 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, - 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, - 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, - 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, - 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, - 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, - 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, - 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, - 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, - 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, - 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, - 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, - 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, - 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, - 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, - 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, - 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, - 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, - 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, - 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, - 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, - 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, - 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, - 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, - 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, - 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, - 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, - 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, - 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, - 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, - 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, - 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, - 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, - 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, - 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, - 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, - 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, - 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, - 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, - 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, - 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, - 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, - 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D - }; - return &table[0]; - } - -private: - uint32 m_crc; - const uint32* const m_pTable; -}; - -// eof diff --git a/Code/CryEngine/CryCommon/CryCustomTypes.h b/Code/CryEngine/CryCommon/CryCustomTypes.h deleted file mode 100644 index 97ea13f9b4..0000000000 --- a/Code/CryEngine/CryCommon/CryCustomTypes.h +++ /dev/null @@ -1,1203 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Derived CTypeInfos for structs, enums, etc. -// Compressed numerical types and associated TypeInfos - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYCUSTOMTYPES_H -#define CRYINCLUDE_CRYCOMMON_CRYCUSTOMTYPES_H -#pragma once - -#include "CryTypeInfo.h" -#include "CryFixedString.h" -#include -#include -#include - -#define STATIC_CONST(T, name, val) \ - static inline T name() { static T t = val; return t; } - -#define ARRAY_COUNT(arr) (sizeof(arr) / sizeof *(arr)) -#define ARRAY_VAR(arr) ArrayT(&(arr)[0], (int)ARRAY_COUNT(arr)) - -//--------------------------------------------------------------------------- -// String helper function. - -template -inline bool HasString(const T& val, FToString flags, const void* def_data = 0) -{ - if (flags.SkipDefault) - { - if (val == (def_data ? *(const T*)def_data : T())) - { - return false; - } - } - return true; -} - -float NumToFromString(float val, int digits, bool floating, char buffer[], int buf_size); - -template -string NumToString(T val, int min_digits, int max_digits, bool floating) -{ - char buffer[64]; - float f(val); - for (int digits = min_digits; digits < max_digits; digits++) - { - if (T(NumToFromString(f, digits, floating, buffer, 64)) == val) - { - break; - } - } - return buffer; -} - -//--------------------------------------------------------------------------- -// TypeInfo for structs - -struct CStructInfo - : CTypeInfo -{ - CStructInfo(cstr name, size_t size, size_t align, Array vars = Array(), Array templates = Array()); - virtual bool IsType(CTypeInfo const& Info) const; - virtual string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const; - virtual bool FromString(void* data, cstr str, FFromString flags = 0) const; - virtual bool ToValue(const void* data, void* value, const CTypeInfo& typeVal) const; - virtual bool FromValue(void* data, const void* value, const CTypeInfo& typeVal) const; - virtual bool ValueEqual(const void* data, const void* def_data) const; - virtual void SwapEndian(void* pData, size_t nCount, bool bWriting) const; - virtual void GetMemoryUsage(ICrySizer* pSizer, void const* data) const; - - virtual const CVarInfo* NextSubVar(const CVarInfo* pPrev, bool bRecurseBase = false) const; - virtual const CVarInfo* FindSubVar(cstr name) const; - - virtual CTypeInfo const* const* NextTemplateType(CTypeInfo const* const* pPrev) const - { - pPrev = pPrev ? pPrev + 1 : TemplateTypes.begin(); - return pPrev < TemplateTypes.end() ? pPrev : 0; - } - -protected: - Array Vars; - CryStackStringT EndianDesc; // Encodes instructions for endian swapping. - bool HasBitfields; - Array TemplateTypes; - - void MakeEndianDesc(); - size_t AddEndianDesc(cstr desc, size_t dim, size_t elem_size); - bool IsCompatibleType(CTypeInfo const& Info) const; -}; - -//--------------------------------------------------------------------------- -// Template TypeInfo for base types, using global To/FromString functions. - -template -struct TTypeInfo - : CTypeInfo -{ - TTypeInfo(cstr name) - : CTypeInfo(name, sizeof(T), alignof(T)) - {} - - virtual bool ToValue(const void* data, void* value, const CTypeInfo& typeVal) const - { - if (&typeVal == this) - { - return *(T*)value = *(const T*)data, true; - } - return false; - } - virtual bool FromValue(void* data, const void* value, const CTypeInfo& typeVal) const - { - if (&typeVal == this) - { - return *(T*)data = *(const T*)value, true; - } - return false; - } - - virtual string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const - { - if (!HasString(*(const T*)data, flags, def_data)) - { - return string(); - } - return ::ToString(*(const T*)data); - } - virtual bool FromString(void* data, cstr str, FFromString flags = 0) const - { - if (!*str) - { - if (!flags.SkipEmpty) - { - *(T*)data = T(); - } - return true; - } - return ::FromString(*(T*)data, str); - } - virtual bool ValueEqual(const void* data, const void* def_data = 0) const - { - return *(const T*)data == (def_data ? *(const T*)def_data : T()); - } - - virtual void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer, [[maybe_unused]] void const* data) const - {} -}; - -//--------------------------------------------------------------------------- -// Template TypeInfo for modified types (e.g. compressed, range-limited) - -template -struct TProxyTypeInfo - : CTypeInfo -{ - TProxyTypeInfo(cstr name) - : CTypeInfo(name, sizeof(S), alignof(S)) - {} - - virtual bool IsType(CTypeInfo const& Info) const - { return &Info == this || ValTypeInfo().IsType(Info); } - - virtual bool ToValue(const void* data, void* value, const CTypeInfo& typeVal) const - { - if (&typeVal == this) - { - *(S*)value = *(const S*)data; - return true; - } - T val = T(*(const S*)data); - return ValTypeInfo().ToValue(&val, value, typeVal); - } - virtual bool FromValue(void* data, const void* value, const CTypeInfo& typeVal) const - { - if (&typeVal == this) - { - *(S*)data = *(const S*)value; - return true; - } - T val; - if (ValTypeInfo().FromValue(&val, value, typeVal)) - { - *(S*)data = S(val); - return true; - } - return false; - } - - virtual string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const - { - T val = T(*(const S*)data); - T def_val = def_data ? T(*(const S*)def_data) : T(); - return ValTypeInfo().ToString(&val, flags, &def_val); - } - virtual bool FromString(void* data, cstr str, FFromString flags = 0) const - { - T val; - if (!*str) - { - if (!flags.SkipEmpty) - { - *(S*)data = S(); - } - return true; - } - if (!TypeInfo(&val).FromString(&val, str)) - { - return false; - } - *(S*)data = S(val); - return true; - } - - // Forward additional TypeInfo functions. - virtual bool GetLimit(ENumericLimit eLimit, float& fVal) const - { return ValTypeInfo().GetLimit(eLimit, fVal); } - virtual cstr EnumElem(uint nIndex) const - { return ValTypeInfo().EnumElem(nIndex); } - -protected: - - static const CTypeInfo& ValTypeInfo() - { return TypeInfo((T*)0); } -}; - -//--------------------------------------------------------------------------- -// Customisation for string. - -template<> -inline string TTypeInfo::ToString(const void* data, FToString flags, const void* def_data) const -{ - const string& val = *(const string*)data; - if (def_data && flags.SkipDefault) - { - if (val == *(const string*)def_data) - { - return string(); - } - } - return val; -} - -template<> -inline bool TTypeInfo::FromString(void* data, cstr str, FFromString flags) const -{ - if (!*str && flags.SkipEmpty) - { - return true; - } - *(string*)data = str; - return true; -} - -template<> -void TTypeInfo::GetMemoryUsage(ICrySizer* pSizer, void const* data) const; - -//--------------------------------------------------------------------------- -// -// TypeInfo for small integer types. - - -template -struct TIntTraits -{ - static const bool bSIGNED - = T(-1) < T(0); - - static const T nMIN_FACTOR - = bSIGNED ? T(-1) : T(0); - - static const size_t nPOS_BITS - = sizeof(T) * 8 - bSIGNED; - - static const T nMIN = std::numeric_limits::min(); - - static const T nMAX = std::numeric_limits::max(); -}; - -template -struct TIntType -{}; - -template<> -struct TIntType<1> -{ - typedef int8 TType; -}; -template<> -struct TIntType<2> -{ - typedef int16 TType; -}; -template<> -struct TIntType<4> -{ - typedef int32 TType; -}; -template<> -struct TIntType<8> -{ - typedef int64 TType; -}; - -template -inline bool ConvertInt(D& dest, S src) -{ - if constexpr (TIntTraits::nPOS_BITS < TIntTraits::nPOS_BITS) - { - src = clamp_tpl(src, S(TIntTraits::nMIN), S(TIntTraits::nMAX)); - } - else if constexpr (TIntTraits::bSIGNED < TIntTraits::bSIGNED) - { - src = max(src, S(0)); - } - - dest = D(src); - assert(S(dest) == src); - return true; -} - -template -inline bool ConvertInt(D& dest, const void* src, const CTypeInfo& typeSrc) -{ - if (typeSrc.IsType()) - { - switch (typeSrc.Size) - { - case 1: - return ConvertInt(dest, *(const int8*)src); - case 2: - return ConvertInt(dest, *(const int16*)src); - case 4: - return ConvertInt(dest, *(const int32*)src); - case 8: - return ConvertInt(dest, *(const int64*)src); - } - } - else if (typeSrc.IsType()) - { - switch (typeSrc.Size) - { - case 1: - return ConvertInt(dest, *(const uint8*)src); - case 2: - return ConvertInt(dest, *(const uint16*)src); - case 4: - return ConvertInt(dest, *(const uint32*)src); - case 8: - return ConvertInt(dest, *(const uint64*)src); - } - } - return false; -} - -template -inline bool ConvertInt(void* dest, const CTypeInfo& typeDest, S src) -{ - if (typeDest.IsType()) - { - switch (typeDest.Size) - { - case 1: - return ConvertInt(*(int8*)dest, src); - case 2: - return ConvertInt(*(int16*)dest, src); - case 4: - return ConvertInt(*(int32*)dest, src); - case 8: - return ConvertInt(*(int64*)dest, src); - } - } - else if (typeDest.IsType()) - { - switch (typeDest.Size) - { - case 1: - return ConvertInt(*(uint8*)dest, src); - case 2: - return ConvertInt(*(uint16*)dest, src); - case 4: - return ConvertInt(*(uint32*)dest, src); - case 8: - return ConvertInt(*(uint64*)dest, src); - } - } - return false; -} - -template -struct TIntTypeInfo - : TTypeInfo -{ - TIntTypeInfo(cstr name) - : TTypeInfo(name) - {} - - virtual bool IsType(CTypeInfo const& Info) const - { return &Info == this || &Info == (TIntTraits::bSIGNED ? &TypeInfo((int*)0) : &TypeInfo((uint*)0)); } - - virtual bool GetLimit(ENumericLimit eLimit, float& fVal) const - { - if (eLimit == eLimit_Min) - { - return fVal = float(TIntTraits::nMIN), true; - } - if (eLimit == eLimit_Max) - { - return fVal = float(TIntTraits::nMAX), true; - } - if (eLimit == eLimit_Step) - { - return fVal = 1.f, true; - } - return false; - } - - // Override to allow int conversion - virtual bool FromValue(void* data, const void* value, const CTypeInfo& typeVal) const - { return ConvertInt(*(T*)data, value, typeVal); } - virtual bool ToValue(const void* data, void* value, const CTypeInfo& typeVal) const - { return ConvertInt(value, typeVal, *(const T*)data); } -}; - -//--------------------------------------------------------------------------- -// Store any type, such as an enum, in a small int. - -template -struct TRangedType -{ - typedef TRangedType TThis; - - TRangedType(T init = T(nDEFAULT)) - : m_Val(init) - { - CheckRange(m_Val); - } - - operator T() const - { - return m_Val; - } - - CUSTOM_STRUCT_INFO(CCustomInfo) - -protected: - T m_Val; - - static bool HasMin() - { return nMIN > INT_MIN; } - static bool HasMax() - { return nMAX < INT_MAX; } - - static bool CheckRange(T& val) - { - if (HasMin() && val < T(nMIN)) - { - val = T(nMIN); - return false; - } - else if (HasMax() && val > T(nMAX)) - { - val = T(nMAX); - return false; - } - return true; - } - - // Adaptor TypeInfo for specifying limits, and implementing range checking - struct CCustomInfo - : TProxyTypeInfo - { - CCustomInfo() - : TProxyTypeInfo(::TypeInfo((T*) 0).Name) - {} - - virtual bool GetLimit(ENumericLimit eLimit, float& fVal) const - { - if (eLimit == eLimit_Min && HasMin()) - { - return fVal = T(nMIN), true; - } - if (eLimit == eLimit_Max && HasMax()) - { - return fVal = T(nMAX), true; - } - return ::TypeInfo((T*)0).GetLimit(eLimit, fVal); - } - }; -}; - -//--------------------------------------------------------------------------- -// Store any type, such as an enum, in a small int. - -template -struct TSmall -{ - typedef TSmall TThis; - typedef T TValue; - - inline TSmall(T val = T(nDefault)) - { - set(val); - } - void set(T val = T(nDefault)) - { - m_Val = S(val) - S(nOffset); - - // The unary operator+() forces integer promotion to happen and thus - // induces a call to operator T(), which allows the equality operator to work. - assert(+(*this) == val); - } - - inline operator T() const - { return T(T(m_Val) + nOffset); } - inline T operator +() const - { return T(T(m_Val) + nOffset); } - - CUSTOM_STRUCT_INFO(CCustomInfo) - -protected: - S m_Val; - - struct CCustomInfo - : TProxyTypeInfo - { - CCustomInfo() - : TProxyTypeInfo("TSmall<>") - {} - - virtual bool GetLimit(ENumericLimit eLimit, float& fVal) const - { - if (eLimit == eLimit_Min) - { - return fVal = float(TIntTraits::nMIN + nOffset), true; - } - if (eLimit == eLimit_Max) - { - return fVal = float(TIntTraits::nMAX + nOffset), true; - } - if (eLimit == eLimit_Step) - { - return fVal = 1.f, true; - } - return false; - } - }; -}; - -//--------------------------------------------------------------------------- -// Quantise a float linearly in an int. -template::nMAX, bool bTRUNC = false> -struct TFixed -{ - typedef float TValue; - - inline TFixed() - : m_Store(0) - {} - - inline TFixed(float fIn) - { - float fStore = ToStore(fIn); - fStore = clamp_tpl(fStore, float(TIntTraits::nMIN_FACTOR * nQUANT), float(nQUANT)); - m_Store = bTRUNC ? S(fStore) : fStore < 0.f ? S(fStore - 0.5f) : S(fStore + 0.5f); - } - - // Conversion. - inline operator float() const - { return FromStore(m_Store); } - inline float operator +() const - { return FromStore(m_Store); } - inline bool operator !() const - { return !m_Store; } - - inline bool operator ==(const TFixed& x) const - { return m_Store == x.m_Store; } - inline bool operator ==(float x) const - { return m_Store == TFixed(x); } - inline S GetStore() const - { return m_Store; } - - static S GetMaxStore() - { return nQUANT; } - static float GetMaxValue() - { return float(nLIMIT); } - - CUSTOM_STRUCT_INFO(CCustomInfo) - -protected: - S m_Store; - - typedef TFixed TThis; - - static const int nMAX = nLIMIT; - static const int nMIN = TIntTraits::nMIN_FACTOR * nLIMIT; - - static inline float ToStore(float f) - { return f * float(nQUANT) / float(nLIMIT); } - static inline float FromStore(float f) - { return f * float(nLIMIT) / float(nQUANT); } - - // TypeInfo implementation. - struct CCustomInfo - : TProxyTypeInfo - { - CCustomInfo() - : TProxyTypeInfo("TFixed<>") - {} - - virtual bool GetLimit(ENumericLimit eLimit, float& fVal) const - { - if (eLimit == eLimit_Min) - { - return fVal = float(nMIN), true; - } - if (eLimit == eLimit_Max) - { - return fVal = float(nMAX), true; - } - if (eLimit == eLimit_Step) - { - return fVal = FromStore(1.f), true; - } - return false; - } - - // Override ToString: Limit to significant digits. - virtual string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const - { - if (!HasString(*(const S*)data, flags, def_data)) - { - return string(); - } - static int digits = int_ceil(log10f(float(nQUANT))); - return NumToString(*(const TFixed*)data, 1, digits + 3, true); - } - }; -}; - - -// Define the canonical float-to-byte quantisation. -typedef TFixed UnitFloat8; - -#ifdef COMPRESSED_FLOATS - -//--------------------------------------------------------------------------- -// A floating point number, with templated storage size (and sign), and number of exponent bits -template -struct TFloat -{ - typedef float TValue; - - ILINE TFloat() - : m_Store(0) - {} - - ILINE TFloat(float fIn) - : m_Store(FromFloat(fIn)) - {} - - ILINE operator float() const - { return ToFloat(m_Store); } - ILINE float operator +() const - { return ToFloat(m_Store); } - - ILINE bool operator !() const - { return !m_Store; } - - ILINE bool operator ==(TFloat x) const - { return m_Store == x.m_Store; } - ILINE bool operator ==(float x) const - { return float(*this) == x; } - - inline TFloat& operator *=(float x) - { return *this = *this * x; } - - ILINE uint32 partial_float_conversion() const - { return (0 == m_Store) ? 0 : ToFloatCore(m_Store); } - - STATIC_CONST(float, fMAX, ToFloat(TIntTraits::nMAX)); - STATIC_CONST(float, fPOS_MIN, ToFloat(1 << nMANT_BITS)); - STATIC_CONST(float, fMIN, -fMAX() * (float)TIntTraits::bSIGNED); - - CUSTOM_STRUCT_INFO(CCustomInfo) - -protected: - S m_Store; - - typedef TFloat TThis; - - static const S nBITS = sizeof(S) * 8; - static const S nSIGN = TIntTraits::bSIGNED; - static const S nMANT_BITS = nBITS - nEXP_BITS - nSIGN; - static const S nSIGN_MASK = S(nSIGN << (nBITS - 1)); - static const S nMANT_MASK = (S(1) << nMANT_BITS) - 1; - static const S nEXP_MASK = ~S(nMANT_MASK | nSIGN_MASK); - static const int nEXP_MAX = 1 << (nEXP_BITS - 1), - nEXP_MIN = 1 - nEXP_MAX; - - STATIC_CONST(float, fROUNDER, 1.f + fPOS_MIN() * 0.5f); - - static inline S FromFloat(float fIn) - { - COMPILE_TIME_ASSERT(sizeof(S) <= 4); - COMPILE_TIME_ASSERT(nEXP_BITS > 0 && nEXP_BITS <= 8 && nEXP_BITS < sizeof(S) * 8 - 4); - - // Clamp to allowed range. - float fClamped = clamp_tpl(fIn * fROUNDER(), fMIN(), fMAX()); - - // Bit shift to convert from IEEE float32. - uint32 uBits = *(const uint32*)&fClamped; - - // Convert exp. - int32 iExp = (uBits >> 23) & 0xFF; - iExp -= 127 + nEXP_MIN; - IF (iExp < 0, 0) - { - // Underflow. - return 0; - } - - // Reduce mantissa. - uint32 uMant = uBits >> (23 - nMANT_BITS); - - S bits = (uMant & nMANT_MASK) - | (iExp << nMANT_BITS) - | ((uBits >> (32 - nBITS)) & nSIGN_MASK); - - #ifdef _DEBUG - fIn = clamp_tpl(fIn, fMIN(), fMAX()); - float fErr = fabs(ToFloat(bits) - fIn); - float fMaxErr = fabs(fIn) / float(1 << nMANT_BITS); - assert(fErr <= fMaxErr); - #endif - - return bits; - } - - static inline uint32 ToFloatCore(S bits) - { - // Extract FP components. - uint32 uBits = bits & nMANT_MASK, - uExp = (bits & ~nSIGN_MASK) >> nMANT_BITS, - uSign = bits & nSIGN_MASK; - - // Shift to 32-bit. - uBits <<= 23 - nMANT_BITS; - uBits |= (uExp + 127 + nEXP_MIN) << 23; - uBits |= uSign << (32 - nBITS); - - return uBits; - } - - static ILINE float ToFloat(S bits) - { - IF (bits == 0, 0) - { - return 0.f; - } - - uint32 uBits = ToFloatCore(bits); - return *(float*)&uBits; - } - - // TypeInfo implementation. - struct CCustomInfo - : TProxyTypeInfo - { - CCustomInfo() - : TProxyTypeInfo("TFloat<>") - {} - - virtual bool GetLimit(ENumericLimit eLimit, float& fVal) const - { - if (eLimit == eLimit_Min) - { - return fVal = fMIN(), true; - } - if (eLimit == eLimit_Max) - { - return fVal = fMAX(), true; - } - if (eLimit == eLimit_Step) - { - return fVal = fPOS_MIN(), true; - } - return false; - } - - // Override ToString: Limit to significant digits. - virtual string ToString(const void* data, FToString flags = 0, const void* def_data = 0) const - { - if (!HasString(*(const S*)data, flags, def_data)) - { - return string(); - } - static int digits = int_ceil(log10f(1 << nMANT_BITS)); - return NumToString(*(const TFloat*)data, 1, digits + 3, true); - } - }; -}; - -// Canonical float16 types, with range ~= 64K. -typedef TFloat SFloat16; -typedef TFloat UFloat16; - -template -ILINE T partial_float_cast(const SFloat16& s) { return static_cast(s.partial_float_conversion()); } - -template -ILINE T partial_float_cast(const UFloat16& u) { return static_cast(u.partial_float_conversion()); } - -#ifdef _DEBUG - -// Classes for unit tests. -template -void TestValues(T val) -{ - T2 val2 = val; - T2 val2c; - - bool b = TypeInfo(&val2c).FromValue(&val2c, val); - assert(b); - assert(val2 == val2c); - b = TypeInfo(&val2c).ToValue(&val2c, val); - assert(b); - assert(val2 == T2(val)); -} - -template -void TestTypes(T val) -{ - T2 val2 = val; - string s = TypeInfo(&val2).ToString(&val2); - bool b = TypeInfo(&val).FromString(&val, s); - assert(b); - assert(val2 == T2(val)); - - TestValues(val); -} - -template -void TestType(T val) -{ - TestTypes(val); -} - -#endif // _DEBUG - -#endif // COMPRESSED_FLOATS - -//--------------------------------------------------------------------------- -// TypeInfo for enums - -//--------------------------------------------------------------------------- -// Implement data features based on enum definition -/* - interface EnumDef - { - typedef TInt; - uint Count(); - TInt Value(uint i); - cstr Name(uint i); - bool MatchName(uint i, cstr str); - cstr ToName(TInt value); - } const -*/ - -template -struct TEnumInfo - : TIntTypeInfo - , TEnumDef -{ - TEnumInfo(cstr name) - : TIntTypeInfo(name) {} - - virtual cstr EnumElem(uint nIndex) const - { - if (nIndex < TEnumDef::Count()) - { - cstr name = TEnumDef::Name(nIndex); - if (*name != '_') - { - return name; - } - } - return 0; - } - - virtual bool FromValue(void* data, const void* value, const CTypeInfo& typeVal) const - { - TInt val; - if (ConvertInt(val, value, typeVal)) - { - if (TEnumDef::ToName(val)) - { - return *(TInt*)data = val, true; - } - } - return false; - } - - virtual string ToString(const void* data, FToString flags, const void* def_data) const - { - TInt val = *(const TInt*)(data); - if (flags.SkipDefault && val == (def_data ? *(const TInt*)def_data : TInt(0))) - { - return string(); - } - - if (cstr sName = TEnumDef::ToName(val)) - { - return sName; - } - - // Unmatched value, return as number. - return ::ToString(val); - } - - virtual bool FromString(void* data, cstr str, FFromString flags) const - { - if (!*str) - { - if (!flags.SkipEmpty) - { - *(TInt*)data = (TInt)0; - } - return true; - } - - for (int i = 0, count = TEnumDef::Count(); i < count; i++) - { - if (TEnumDef::MatchName(i, str)) - { - return *(TInt*)data = check_cast(TEnumDef::Value(i)), true; - } - } - - // No match, attempt numeric or bool conversion. - if (::FromString(*(TInt*)data, str)) - { - return true; - } - - bool b; - if (::FromString(b, str)) - { - return *(TInt*)data = b, true; - } - - return false; - } -}; - -//--------------------------------------------------------------------------- -// TypeInfo for regular enums - -struct CSimpleEnumDef -{ - void Init(Array names, char* enum_str); - - // TEnumDef implementations - ILINE uint Count() const - { return asNames.size(); } - ILINE static uint Value(uint i) - { return i; } - ILINE cstr Name(uint i) const - { return asNames[i]; } - ILINE bool MatchName(uint i, cstr str) const - { - cstr name = asNames[i]; - if (*name == '_') - { - name++; - } - return azstricmp(name, str) == 0; - } - ILINE cstr ToName(uint value) const - { - if (value < Count()) - { - return asNames[value]; - } - return 0; - } - -protected: - - Array asNames; -}; - -struct CSimpleEnumInfo - : TEnumInfo -{ - CSimpleEnumInfo(cstr name, Array names, char* enum_str) - : TEnumInfo(name) - { - Init(names, enum_str); - } -}; - -// Define a regular small enum with TypeInfo - -#define DEFINE_ENUM_VALUE(EType, E, TInt) \ - TInt Value; \ - ILINE EType(E val = E(0)) \ - : Value(aznumeric_caster(val)) {} \ - ILINE operator E() const { return E(Value); } \ - ILINE E operator +() const { return E(Value); } \ - -#define DEFINE_ENUM(EType, ...) \ - struct EType \ - { \ - enum E { __VA_ARGS__, _count }; \ - typedef uint8 TInt; \ - DEFINE_ENUM_VALUE(EType, E, TInt) \ - ILINE static uint Count() { return _count; } \ - static const CSimpleEnumInfo& TypeInfo() { \ - static cstr names[_count]; \ - static char enum_str[] = #__VA_ARGS__; \ - static CSimpleEnumInfo info( #EType, Array(&names[0], _count), enum_str); \ - return info; \ - } \ - }; - -//--------------------------------------------------------------------------- -// TypeInfo for irregular enums - -struct CEnumDef -{ - typedef int64 TValue; - - struct SElem - { - TValue Value; - cstr Name; - }; - - void Init(Array elems, char* enum_str = 0); - - // TEnumDef implementations - ILINE uint Count() const - { return Elems.size(); } - ILINE TValue Value(uint i) const - { return Elems[i].Value; } - ILINE cstr Name(uint i) const - { return *Elems[i].Name ? Elems[i].Name + nPrefixLength : ""; } - bool MatchName(uint i, cstr str) const; - cstr ToName(TValue val) const; - - struct SInit - { - static LegacyDynArray* s_pElems; - - static void Init(LegacyDynArray& elems) - { - s_pElems = &elems; - } - SInit() - { - TValue val = s_pElems->empty() ? 0 : s_pElems->back().Value + 1; - s_pElems->push_back()->Value = val; - } - SInit(TValue val) - { - s_pElems->push_back()->Value = val; - } - }; - -protected: - - Array Elems; - TValue MinValue; - bool bRegular; - uint nPrefixLength; -}; - -template -struct CEnumInfo - : TEnumInfo -{ - CEnumInfo(cstr name, Array elems, char* enum_str = 0) - : TEnumInfo(name) - { - CEnumDef::Init(elems, enum_str); - } -}; - -struct CEnumDefUuid - : public TTypeInfo -{ - struct SElem - { - AZ::Uuid Value; - cstr Name; - }; - - CEnumDefUuid(cstr name, Array elems, char* enum_str = 0) - : TTypeInfo(name) - { - CEnumDefUuid::Init(elems, enum_str); - } - void Init(Array elems, char* enum_str = 0); - - // TEnumDef implementations - ILINE uint Count() const - { - return Elems.size(); - } - ILINE AZ::Uuid Value(uint i) const - { - return Elems[i].Value; - } - ILINE cstr Name(uint i) const - { - return *Elems[i].Name ? Elems[i].Name + nPrefixLength : ""; - } - bool MatchName(uint i, cstr str) const; - cstr ToName(AZ::Uuid val) const; - - cstr EnumElem(uint nIndex) const override - { - if (nIndex < Count()) - { - cstr name = Name(nIndex); - if (*name != '_') - { - return name; - } - } - return 0; - } - - bool FromValue(void* data, const void* value, const CTypeInfo& typeVal) const override - { - if (&typeVal == this) - { - const AZ::Uuid& valueUuid = *reinterpret_cast(value); - if (ToName(valueUuid)) - { - AZ::Uuid& dataUuid = *reinterpret_cast(data); - dataUuid = valueUuid; - return true; - } - } - return false; - } - - string ToString(const void* data, FToString flags, const void* def_data) const override - { - const AZ::Uuid& uuidData = *reinterpret_cast(data); - const AZ::Uuid& defUuidData = *reinterpret_cast(def_data); - if (flags.SkipDefault && uuidData == (def_data ? defUuidData : AZ::Uuid::CreateNull())) - { - return string(); - } - - if (cstr sName = ToName(uuidData)) - { - return sName; - } - - return string(); - } - - bool FromString(void* data, cstr str, FFromString flags) const override - { - AZ::Uuid& uuidData = *reinterpret_cast(data); - if (!*str) - { - if (!flags.SkipEmpty) - { - uuidData = AZ::Uuid::CreateNull(); - } - return true; - } - - for (int i = 0, count = Count(); i < count; i++) - { - if (MatchName(i, str)) - { - uuidData = Value(i); - return true; - } - } - - return false; - } - -protected: - - Array Elems; - bool bRegular; - uint nPrefixLength; -}; - -#endif // CRYINCLUDE_CRYCOMMON_CRYCUSTOMTYPES_H diff --git a/Code/CryEngine/CryCommon/CryEndian.h b/Code/CryEngine/CryCommon/CryEndian.h deleted file mode 100644 index 554a8e0465..0000000000 --- a/Code/CryEngine/CryCommon/CryEndian.h +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYENDIAN_H -#define CRYINCLUDE_CRYCOMMON_CRYENDIAN_H -#pragma once - -#include - -////////////////////////////////////////////////////////////////////////// -// Endian support -////////////////////////////////////////////////////////////////////////// - -///////////////////////////////////////////////////////////////////////////////////// -// NEED_ENDIAN_SWAP is an older define still used in several places to toggle endian swapping. -// It is only used when reading files which are assumed to be little-endian. -// For legacy support, define it to swap on big endian platforms. -///////////////////////////////////////////////////////////////////////////////////// - -typedef bool EEndian; - -#if defined(SYSTEM_IS_LITTLE_ENDIAN) -# undef SYSTEM_IS_LITTLE_ENDIAN -#endif -#if defined(SYSTEM_IS_BIG_ENDIAN) -# undef SYSTEM_IS_BIG_ENDIAN -#endif - -#if 0 // no big-endian platforms right now, but keep the code - // Big-endian platform -# define SYSTEM_IS_LITTLE_ENDIAN 0 -# define SYSTEM_IS_BIG_ENDIAN 1 -#else -// Little-endian platform -# define SYSTEM_IS_LITTLE_ENDIAN 1 -# define SYSTEM_IS_BIG_ENDIAN 0 -#endif - -#if SYSTEM_IS_BIG_ENDIAN -// Big-endian platform. Swap to/from little. - #define eBigEndian false - #define eLittleEndian true - #define NEED_ENDIAN_SWAP -#else -// Little-endian platform. Swap to/from big. - #define eLittleEndian false - #define eBigEndian true - #undef NEED_ENDIAN_SWAP -#endif - - -enum EEndianness -{ - eEndianness_Little, - eEndianness_Big, -#if SYSTEM_IS_BIG_ENDIAN - eEndianness_Native = eEndianness_Big, - eEndianness_NonNative = eEndianness_Little, -#else - eEndianness_Native = eEndianness_Little, - eEndianness_NonNative = eEndianness_Big, -#endif -}; - - -// Legacy macros -#define GetPlatformEndian() false - -///////////////////////////////////////////////////////////////////////////////////// - -inline bool IsSystemLittleEndian() -{ - const int a = 1; - return 1 == *(const char*)&a; -} - -///////////////////////////////////////////////////////////////////////////////////// - -// SwapEndian function, using TypeInfo. -struct CTypeInfo; -void SwapEndian(const CTypeInfo& Info, size_t nSizeCheck, void* pData, size_t nCount = 1, bool bWriting = false); - -// Default template utilizes TypeInfo. -template -inline void SwapEndianBase(T* t, size_t nCount = 1, bool bWriting = false) -{ - SwapEndian(TypeInfo(t), sizeof(T), t, nCount, bWriting); -} - -///////////////////////////////////////////////////////////////////////////////////// -// SwapEndianBase functions. -// Always swap the data (the functions named SwapEndian swap based on an optional bSwapEndian parameter). -// The bWriting parameter must be specified in general when the output is for writing, -// but it matters only for types with bitfields. - -// Overrides for base types. - -template<> -inline void SwapEndianBase(char* p, size_t nCount, bool bWriting) -{ - (void)p; - (void)nCount; - (void)bWriting; -} - -template<> -inline void SwapEndianBase(uint8* p, size_t nCount, bool bWriting) -{ - (void)p; - (void)nCount; - (void)bWriting; -} - -template<> -inline void SwapEndianBase(int8* p, size_t nCount, bool bWriting) -{ - (void)p; - (void)nCount; - (void)bWriting; -} - -template<> -inline void SwapEndianBase(uint16* p, size_t nCount, bool bWriting) -{ - (void)bWriting; - for (; nCount-- > 0; p++) - { - *p = (uint16) (((*p >> 8) + (*p << 8)) & 0xFFFF); - } -} - -template<> -inline void SwapEndianBase(int16* p, size_t nCount, bool bWriting) -{ - (void)bWriting; - SwapEndianBase((uint16*)p, nCount); -} - -template<> -inline void SwapEndianBase(uint32* p, size_t nCount, bool bWriting) -{ - (void)bWriting; - for (; nCount-- > 0; p++) - { - *p = (*p >> 24) + ((*p >> 8) & 0xFF00) + ((*p & 0xFF00) << 8) + (*p << 24); - } -} - -template<> -inline void SwapEndianBase(int32* p, size_t nCount, bool bWriting) -{ - (void)bWriting; - SwapEndianBase((uint32*)p, nCount); -} - -template<> -inline void SwapEndianBase(float* p, size_t nCount, bool bWriting) -{ - (void)bWriting; - SwapEndianBase((uint32*)p, nCount); -} - -template<> -inline void SwapEndianBase(uint64* p, size_t nCount, bool bWriting) -{ - (void)bWriting; - for (; nCount-- > 0; p++) - { - *p = (*p >> 56) + ((*p >> 40) & 0xFF00) + ((*p >> 24) & 0xFF0000) + ((*p >> 8) & 0xFF000000) - + ((*p & 0xFF000000) << 8) + ((*p & 0xFF0000) << 24) + ((*p & 0xFF00) << 40) + (*p << 56); - } -} - -template<> -inline void SwapEndianBase(int64* p, size_t nCount, bool bWriting) -{ - (void)bWriting; - SwapEndianBase((uint64*)p, nCount); -} - -template<> -inline void SwapEndianBase(double* p, size_t nCount, bool bWriting) -{ - (void)bWriting; - SwapEndianBase((uint64*)p, nCount); -} - -//--------------------------------------------------------------------------- -// SwapEndian functions. -// bSwapEndian argument optional, and defaults to swapping from LittleEndian format. - -template -inline void SwapEndian(T* t, size_t nCount, bool bSwapEndian = eLittleEndian) -{ - if (bSwapEndian) - { - SwapEndianBase(t, nCount); - } -} - -// Specify int and uint as well as size_t, to resolve overload ambiguities. -template -inline void SwapEndian(T* t, int nCount, bool bSwapEndian = eLittleEndian) -{ - if (bSwapEndian) - { - SwapEndianBase(t, nCount); - } -} - -#if defined(PLATFORM_64BIT) -template -inline void SwapEndian(T* t, unsigned int nCount, bool bSwapEndian = eLittleEndian) -{ - if (bSwapEndian) - { - SwapEndianBase(t, nCount); - } -} -#endif - -template -inline void SwapEndian(T& t, bool bSwapEndian = eLittleEndian) -{ - if (bSwapEndian) - { - SwapEndianBase(&t, 1); - } -} - -template -inline T SwapEndianValue(T t, bool bSwapEndian = eLittleEndian) -{ - if (bSwapEndian) - { - SwapEndianBase(&t, 1); - } - return t; -} - -//--------------------------------------------------------------------------- -// Object-oriented data extraction for endian-swapping reading. -template -inline T* StepData(D*& pData, size_t nCount, bool bSwapEndian) -{ - T* Elems = (T*)pData; - SwapEndian(Elems, nCount, bSwapEndian); - pData = (D*)((T*)pData + nCount); - return Elems; -} - -template -inline T* StepData(D*& pData, bool bSwapEndian) -{ - return StepData(pData, 1, bSwapEndian); -} - -template -inline void StepData(T*& Result, D*& pData, size_t nCount, bool bSwapEndian) -{ - Result = StepData(pData, nCount, bSwapEndian); -} - -template -inline void StepDataCopy(T* Dest, D*& pData, size_t nCount, bool bSwapEndian) -{ - memcpy(Dest, pData, nCount * sizeof(T)); - SwapEndian(Dest, nCount, bSwapEndian); - pData = (D*)((T*)pData + nCount); -} - -template -inline void StepDataWrite(D*& pDest, const T* aSrc, size_t nCount, bool bSwapEndian) -{ - memcpy(pDest, aSrc, nCount * sizeof(T)); - if (bSwapEndian) - { - SwapEndianBase((T*)pDest, nCount, true); - } - (T*&)pDest += nCount; -} - -template -inline void StepDataWrite(D*& pDest, const T& Src, bool bSwapEndian) -{ - StepDataWrite(pDest, &Src, 1, bSwapEndian); -} - -#endif // CRYINCLUDE_CRYCOMMON_CRYENDIAN_H diff --git a/Code/CryEngine/CryCommon/CryFile.h b/Code/CryEngine/CryCommon/CryFile.h deleted file mode 100644 index 15c77af3ff..0000000000 --- a/Code/CryEngine/CryCommon/CryFile.h +++ /dev/null @@ -1,437 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : File wrapper. - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYFILE_H -#define CRYINCLUDE_CRYCOMMON_CRYFILE_H -#pragma once - -#include -#include -#include -#include -#include "StringUtils.h" -#include - -////////////////////////////////////////////////////////////////////////// -// Defines for CryEngine filetypes extensions. -////////////////////////////////////////////////////////////////////////// -#define CRY_GEOMETRY_FILE_EXT "cgf" -#define CRY_SKEL_FILE_EXT "chr" //will be a SKEL soon -#define CRY_SKIN_FILE_EXT "skin" -#define CRY_CHARACTER_ANIMATION_FILE_EXT "caf" -#define CRY_CHARACTER_DEFINITION_FILE_EXT "cdf" -#define CRY_CHARACTER_LIST_FILE_EXT "cid" -#define CRY_ANIM_GEOMETRY_FILE_EXT "cga" -#define CRY_ANIM_GEOMETRY_ANIMATION_FILE_EXT "anm" -#define CRY_COMPILED_FILE_EXT "(c)" -#define CRY_BINARY_XML_FILE_EXT "binxml" -#define CRY_XML_FILE_EXT "xml" -#define CRY_CHARACTER_PARAM_FILE_EXT "chrparams" -#define CRY_GEOM_CACHE_FILE_EXT "cax" -////////////////////////////////////////////////////////////////////////// -#define CRYFILE_MAX_PATH 260 -////////////////////////////////////////////////////////////////////////// - -inline const char* CryGetExt(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 ""; -} - -// Summary: -// Checks if specified file name is a character file. -// Summary: -// Checks if specified file name is a character file. -inline bool IsCharacterFile(const char* filename) -{ - const char* ext = CryGetExt(filename); - if (_stricmp(ext, CRY_SKEL_FILE_EXT) == 0 || _stricmp(ext, CRY_SKIN_FILE_EXT) == 0 || _stricmp(ext, CRY_CHARACTER_DEFINITION_FILE_EXT) == 0 || _stricmp(ext, CRY_ANIM_GEOMETRY_FILE_EXT) == 0) - { - return true; - } - else - { - return false; - } -} - -// Description: -// Checks if specified file name is a static geometry file. -inline bool IsStatObjFile(const char* filename) -{ - const char* ext = CryGetExt(filename); - if (_stricmp(ext, CRY_GEOMETRY_FILE_EXT) == 0) - { - return true; - } - else - { - return false; - } -} - -// Summary: -// Wrapper on file system. -class CCryFile -{ -public: - CCryFile(); - CCryFile(AZ::IO::IArchive* pIArchive); // allow an alternative IArchiveinterface - CCryFile(const char* filename, const char* mode); - ~CCryFile(); - - bool Open(const char* filename, const char* mode, int nOpenFlagsEx = 0); - void Close(); - - // Summary: - // Writes data in a file to the current file position. - size_t Write(const void* lpBuf, size_t nSize); - // Summary: - // Reads data from a file at the current file position. - size_t ReadRaw(void* lpBuf, size_t nSize); - // Summary: - // Template version, for automatic size support. - template - inline size_t ReadTypeRaw(T* pDest, size_t nCount = 1) - { - return ReadRaw(pDest, sizeof(T) * nCount); - } - - // Summary: - // Automatic endian-swapping version. - template - inline size_t ReadType(T* pDest, size_t nCount = 1) - { - size_t nRead = ReadRaw(pDest, sizeof(T) * nCount); - SwapEndian(pDest, nCount); - return nRead; - } - - // Summary: - // Retrieves the length of the file. - size_t GetLength(); - - // Summary: - // Moves the current file pointer to the specified position. - size_t Seek(size_t seek, int mode); - // Summary: - // Moves the current file pointer at the beginning of the file. - void SeekToBegin(); - // Summary: - // Moves the current file pointer at the end of the file. - size_t SeekToEnd(); - // Summary: - // Retrieves the current file pointer. - size_t GetPosition(); - - // Summary: - // Tests for end-of-file on a selected file. - bool IsEof(); - - // Summary: - // Flushes any data yet to be written. - void Flush(); - - // Summary: - // Gets a handle to a pack object. - AZ::IO::HandleType GetHandle() const { return m_fileHandle; }; - - // Description: - // Retrieves the filename of the selected file. - const char* GetFilename() const { return m_filename; }; - - // Description: - // Retrieves the filename after adjustment to the real relative to engine root path. - // Example: - // Original filename "textures/red.dds" adjusted filename will look like "game/textures/red.dds" - // Return: - // Adjusted filename, this is a pointer to a static string, copy return value if you want to keep it. - const char* GetAdjustedFilename() const; - - // Summary: - // Checks if file is opened from Archive file. - bool IsInPak() const; - - // Summary: - // Gets path of archive this file is in. - const char* GetPakPath() const; - -private: - char m_filename[CRYFILE_MAX_PATH]; - AZ::IO::HandleType m_fileHandle; - AZ::IO::IArchive* m_pIArchive; -}; - -// Summary: -// CCryFile implementation. -inline CCryFile::CCryFile() -{ - m_fileHandle = AZ::IO::InvalidHandle; - m_pIArchive = gEnv ? gEnv->pCryPak : NULL; -} - -inline CCryFile::CCryFile(AZ::IO::IArchive* pIArchive) -{ - m_fileHandle = AZ::IO::InvalidHandle; - m_pIArchive = pIArchive; -} - -////////////////////////////////////////////////////////////////////////// -inline CCryFile::CCryFile(const char* filename, const char* mode) -{ - m_fileHandle = AZ::IO::InvalidHandle; - m_pIArchive = gEnv ? gEnv->pCryPak : NULL; - Open(filename, mode); -} - -////////////////////////////////////////////////////////////////////////// -inline CCryFile::~CCryFile() -{ - Close(); -} - -////////////////////////////////////////////////////////////////////////// -// Notes: -// For nOpenFlagsEx see IArchive::EFOpenFlags -// See also: -// IArchive::EFOpenFlags -inline bool CCryFile::Open(const char* filename, const char* mode, int nOpenFlagsEx) -{ - char tempfilename[CRYFILE_MAX_PATH] = ""; - cry_strcpy(tempfilename, filename); - -#if !defined (_RELEASE) - if (gEnv && gEnv->IsEditor() && gEnv->pConsole) - { - ICVar* const pCvar = gEnv->pConsole->GetCVar("ed_lowercasepaths"); - if (pCvar) - { - const int lowercasePaths = pCvar->GetIVal(); - if (lowercasePaths) - { - const string lowerString = PathUtil::ToLower(tempfilename); - cry_strcpy(tempfilename, lowerString.c_str()); - } - } - } -#endif - if (m_fileHandle != AZ::IO::InvalidHandle) - { - Close(); - } - cry_strcpy(m_filename, tempfilename); - - if (m_pIArchive) - { - m_fileHandle = m_pIArchive->FOpen(tempfilename, mode, nOpenFlagsEx); - } - else - { - AZ::IO::FileIOBase::GetInstance()->Open(tempfilename, AZ::IO::GetOpenModeFromStringMode(mode), m_fileHandle); - } - - return m_fileHandle != AZ::IO::InvalidHandle; -} - -////////////////////////////////////////////////////////////////////////// -inline void CCryFile::Close() -{ - if (m_fileHandle != AZ::IO::InvalidHandle) - { - if (m_pIArchive) - { - m_pIArchive->FClose(m_fileHandle); - } - else - { - AZ::IO::FileIOBase::GetInstance()->Close(m_fileHandle); - } - m_fileHandle = AZ::IO::InvalidHandle; - m_filename[0] = 0; - } -} - -////////////////////////////////////////////////////////////////////////// -inline size_t CCryFile::Write(const void* lpBuf, size_t nSize) -{ - assert(m_fileHandle != AZ::IO::InvalidHandle); - if (m_pIArchive) - { - return m_pIArchive->FWrite(lpBuf, 1, nSize, m_fileHandle); - } - - if (AZ::IO::FileIOBase::GetInstance()->Write(m_fileHandle, lpBuf, nSize)) - { - return nSize; - } - - return 0; -} - -////////////////////////////////////////////////////////////////////////// -inline size_t CCryFile::ReadRaw(void* lpBuf, size_t nSize) -{ - assert(m_fileHandle != AZ::IO::InvalidHandle); - if (m_pIArchive) - { - return m_pIArchive->FReadRaw(lpBuf, 1, nSize, m_fileHandle); - } - - AZ::u64 bytesRead = 0; - AZ::IO::FileIOBase::GetInstance()->Read(m_fileHandle, lpBuf, nSize, false, &bytesRead); - - return static_cast(bytesRead); -} - -////////////////////////////////////////////////////////////////////////// -inline size_t CCryFile::GetLength() -{ - assert(m_fileHandle != AZ::IO::InvalidHandle); - if (m_pIArchive) - { - return m_pIArchive->FGetSize(m_fileHandle); - } - //long curr = ftell(m_file); - AZ::u64 size = 0; - AZ::IO::FileIOBase::GetInstance()->Size(m_fileHandle, size); - return static_cast(size); -} - -////////////////////////////////////////////////////////////////////////// -inline size_t CCryFile::Seek(size_t seek, int mode) -{ - assert(m_fileHandle != AZ::IO::InvalidHandle); - if (m_pIArchive) - { - return m_pIArchive->FSeek(m_fileHandle, long(seek), mode); - } - - if (AZ::IO::FileIOBase::GetInstance()->Seek(m_fileHandle, seek, AZ::IO::GetSeekTypeFromFSeekMode(mode))) - { - return 0; - } - return 1; -} - -////////////////////////////////////////////////////////////////////////// -inline void CCryFile::SeekToBegin() -{ - Seek(0, SEEK_SET); -} - -////////////////////////////////////////////////////////////////////////// -inline size_t CCryFile::SeekToEnd() -{ - return Seek(0, SEEK_END); -} - -////////////////////////////////////////////////////////////////////////// -inline size_t CCryFile::GetPosition() -{ - assert(m_fileHandle != AZ::IO::InvalidHandle); - if (m_pIArchive) - { - return m_pIArchive->FTell(m_fileHandle); - } - - AZ::u64 tellOffset = 0; - AZ::IO::FileIOBase::GetInstance()->Tell(m_fileHandle, tellOffset); - - return static_cast(tellOffset); -} - -////////////////////////////////////////////////////////////////////////// -inline bool CCryFile::IsEof() -{ - assert(m_fileHandle != AZ::IO::InvalidHandle); - if (m_pIArchive) - { - return m_pIArchive->FEof(m_fileHandle) != 0; - } - - return AZ::IO::FileIOBase::GetInstance()->Eof(m_fileHandle); -} - -////////////////////////////////////////////////////////////////////////// -inline void CCryFile::Flush() -{ - assert(m_fileHandle != AZ::IO::InvalidHandle); - - if (m_pIArchive) - { - m_pIArchive->FFlush(m_fileHandle); - } - - AZ::IO::FileIOBase::GetInstance()->Flush(m_fileHandle); -} - -////////////////////////////////////////////////////////////////////////// -inline bool CCryFile::IsInPak() const -{ - if (m_fileHandle != AZ::IO::InvalidHandle && m_pIArchive) - { - return m_pIArchive->GetFileArchivePath(m_fileHandle) != NULL; - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -inline const char* CCryFile::GetPakPath() const -{ - if (m_fileHandle != AZ::IO::InvalidHandle && m_pIArchive) - { - const char* sPath = m_pIArchive->GetFileArchivePath(m_fileHandle); - if (sPath != NULL) - { - return sPath; - } - } - return ""; -} - - -////////////////////////////////////////////////////////////////////////// -inline const char* CCryFile::GetAdjustedFilename() const -{ - static char szAdjustedFile[AZ::IO::IArchive::MaxPath]; - assert(m_pIArchive); - if (!m_pIArchive) - { - return ""; - } - - // Gets mod path to file. - const char* gameUrl = m_pIArchive->AdjustFileName(m_filename, szAdjustedFile, AZ::IO::IArchive::MaxPath, 0); - - // Returns standard path otherwise. - if (gameUrl != &szAdjustedFile[0]) - { - cry_strcpy(szAdjustedFile, gameUrl); - } - return szAdjustedFile; -} - -#endif // CRYINCLUDE_CRYCOMMON_CRYFILE_H diff --git a/Code/CryEngine/CryCommon/CryFixedString.h b/Code/CryEngine/CryCommon/CryFixedString.h deleted file mode 100644 index f0ba67cd6a..0000000000 --- a/Code/CryEngine/CryCommon/CryFixedString.h +++ /dev/null @@ -1,2336 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Stack-based fixed-size String class, similar to CryString. -// will switch to heap-based allocation when string does no longer fit -// Can easily be substituted instead of CryString. - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYFIXEDSTRING_H -#define CRYINCLUDE_CRYCOMMON_CRYFIXEDSTRING_H -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include "CryString.h" - -#ifndef CRY_STRING_DEBUG -#define CRY_STRING_DEBUG(s) -#endif - -#define UNITTEST_CRYFIXEDSTRING (0) - -template -class CharTraits; - -// traits for char -template <> -class CharTraits -{ -public: - typedef size_t size_type; - typedef char value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - - ILINE int _isspace(value_type c) const - { - return ::isspace((int)c); - } - - ILINE value_type _traits_toupper(value_type c) const - { - return static_cast(toupper(c)); - } - - ILINE value_type _traits_tolower(value_type c) const - { - return static_cast(tolower(c)); - } - - ILINE value_type _ascii_tolower(value_type c) const - { - return (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c; - } - - ILINE value_type _ascii_toupper(value_type c) const - { - return (c >= 'a' && c <= 'z') ? c - 'a' + 'A' : c; - } - - ILINE int _strcmp (const_str a, const_str b) const - { - return ::strcmp(a, b); - } - - ILINE int _strncmp (const_str a, const_str b, size_type n) const - { - return ::strncmp(a, b, n); - } - - ILINE int _stricmp (const_str a, const_str b) const - { - return ::azstricmp(a, b); - } - - ILINE int _strnicmp (const_str a, const_str b, size_type n) const - { - return ::azstrnicmp(a, b, n); - } - - ILINE size_type _strspn(const_str str, const_str strCharSet) const - { - return (str == NULL) ? 0 : (size_type)::strspn(str, strCharSet); - } - - ILINE size_type _strcspn(const_str str, const_str strCharSet) const - { - return (str == NULL) ? 0 : (size_type)::strcspn(str, strCharSet); - } - - static ILINE size_type _strlen(const_str str) - { - return (str == NULL) ? 0 : (size_type)::strlen(str); - } - - ILINE const_str _strchr(const_str str, value_type c) const - { - return (str == NULL) ? 0 : ::strchr(str, c); - } - - ILINE value_type* _strstr(value_type* str, const_str strSearch) const - { - return (str == NULL) ? 0 : (value_type*) ::strstr(str, strSearch); - } - - ILINE void _copy(value_type* dest, const value_type* src, size_type count) - { - memcpy(dest, src, count * sizeof(value_type)); - } - - ILINE void _move(value_type* dest, const value_type* src, size_type count) - { - memmove(dest, src, count * sizeof(value_type)); - } - - ILINE void _set(value_type* dest, value_type ch, size_type count) - { - memset(dest, ch, count * sizeof(value_type)); - } - - ILINE int _vsnprintf(value_type* str, size_type size, const_str format, va_list ap) - { - return ::azvsnprintf(str, size, format, ap); - } -}; - -// traits for wchar_t -template <> -class CharTraits -{ -public: - typedef size_t size_type; - typedef wchar_t value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - - ILINE int _isspace(value_type c) const - { - return iswspace(c); - } - - ILINE value_type _traits_toupper(value_type c) const - { - return towupper(c); - } - - ILINE value_type _traits_tolower(value_type c) const - { - return towlower(c); - } - - ILINE value_type _ascii_tolower(value_type c) const - { - return ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)); - } - - ILINE value_type _ascii_toupper(value_type c) const - { - return ((((c) >= 'a') && ((c) <= 'z')) ? ((c) - 'a' + 'A') : (c)); - } - - ILINE int _strcmp (const_str a, const_str b) const - { - return wcscmp (a, b); - } - - ILINE int _strncmp (const_str a, const_str b, size_type n) const - { - return wcsncmp (a, b, n); - } - - ILINE int _stricmp (const_str a, const_str b) const - { - return azwcsicmp(a, b); - } - - ILINE int _strnicmp (const_str a, const_str b, size_type n) const - { - return azwcsnicmp(a, b, n); - } - - ILINE size_type _strspn(const_str str, const_str strCharSet) const - { - return (str == NULL) ? 0 : (size_type)::wcsspn(str, strCharSet); - } - - ILINE size_type _strcspn(const_str str, const_str strCharSet) const - { - return (str == NULL) ? 0 : (size_type)::wcscspn(str, strCharSet); - } - - static ILINE size_type _strlen(const_str str) - { - return (str == NULL) ? 0 : (size_type)::wcslen(str); - } - - ILINE const_str _strchr(const_str str, value_type c) const - { - return (str == NULL) ? 0 : ::wcschr(str, c); - } - - ILINE value_type* _strstr(value_type* str, const_str strSearch) const - { - return (str == NULL) ? 0 : ::wcsstr(str, strSearch); - } - - ILINE void _copy(value_type* dest, const value_type* src, size_type count) - { - memcpy(dest, src, count * sizeof(value_type)); - } - - ILINE void _move(value_type* dest, const value_type* src, size_type count) - { - memmove(dest, src, count * sizeof(value_type)); - } - - ILINE void _set(value_type* dest, value_type ch, size_type count) - { - wmemset(dest, ch, count); - } - - ILINE int _vsnprintf(value_type* str, size_type size, const_str format, va_list ap) - { - return ::_vsnwprintf_s(str, size + 1, size, format, ap); - } -}; - -template -class CryStackStringT - : public CharTraits -{ -public: - ////////////////////////////////////////////////////////////////////////// - // Types compatible with STL string. - ////////////////////////////////////////////////////////////////////////// - typedef CryStackStringT _Self; - typedef size_t size_type; - typedef T value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - static const size_type MAX_SIZE = S; - - enum _npos_type - { - npos = (size_type) ~0 - }; - - ////////////////////////////////////////////////////////////////////////// - // Constructors - ////////////////////////////////////////////////////////////////////////// - CryStackStringT(); - -public: - - CryStackStringT(const _Self& str); - CryStackStringT(const _Self& str, size_type nOff, size_type nCount); - CryStackStringT(size_type nRepeat, value_type ch); - - // The reason of making this constructor unavailable (for a while) is - // explained in comments in front of the declaration of - // CryStringT::CryStringT(size_type nRepeat, value_type ch) - // (see CryString.h). -private: - CryStackStringT(value_type ch, size_type nRepeat); - -public: - - CryStackStringT(const_str str); - CryStackStringT(const CryStringT& str); - CryStackStringT(const_str str, size_type nLength); - CryStackStringT(const_iterator _First, const_iterator _Last); - ~CryStackStringT(); - - ////////////////////////////////////////////////////////////////////////// - // STL string like interface. - ////////////////////////////////////////////////////////////////////////// - //! Operators. - size_type length() const; - size_type size() const; - bool empty() const; - void clear(); // free up the data - - //! Returns the storage currently allocated to hold the string, a value at least as large as length(). - // Also: capacity is always >= (MAX_SIZE-1) - size_type capacity() const; - - // Sets the capacity of the string to a number at least as great as a specified number. - // nCount = 0 is shrinking string to fit number of characters in it. - // Shrink to fit post-cond: capacity() >= (MAX_SIZE-1) - void reserve(size_type nCount = 0); - - _Self& append(const value_type* _Ptr); - _Self& append(const value_type* _Ptr, size_type nCount); - _Self& append(const _Self& _Str, size_type nOff, size_type nCount); - _Self& append(const _Self& _Str); - _Self& append(size_type nCount, value_type _Ch); - _Self& append(const_iterator _First, const_iterator _Last); - - _Self& assign(const_str _Ptr); - _Self& assign(const_str _Ptr, size_type nCount); - _Self& assign(const _Self& _Str, size_type off, size_type nCount); - _Self& assign(const _Self& _Str); - _Self& assign(size_type nCount, value_type _Ch); - _Self& assign(const_iterator _First, const_iterator _Last); - - value_type at(size_type index) const; - //value_type& at( size_type index ); - - const_iterator begin() const { return m_str; }; - const_iterator end() const { return m_str + length(); }; - - iterator begin() { return m_str; }; - iterator end() { return m_str + length(); }; - - //! cast to C string operator. - operator const_str() const { - return m_str; - } - - //! cast to C string. - const value_type* c_str() const { return m_str; } - const value_type* data() const { return m_str; }; - - ////////////////////////////////////////////////////////////////////////// - // string comparison. - ////////////////////////////////////////////////////////////////////////// - int compare(const _Self& _Str) const; - int compare(size_type _Pos1, size_type _Num1, const _Self& _Str) const; - int compare(size_type _Pos1, size_type _Num1, const _Self& _Str, size_type nOff, size_type nCount) const; - int compare(const value_type* _Ptr) const; - int compare(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2 = npos) const; - - // Case insensitive comparison - int compareNoCase(const _Self& _Str) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const _Self& _Str) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const _Self& _Str, size_type nOff, size_type nCount) const; - int compareNoCase(const value_type* _Ptr) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2 = npos) const; - - // Copies at most a specified number of characters from an indexed position in a source string to a target character array. - size_type copy(value_type* _Ptr, size_type nCount, size_type nOff = 0) const; - - void push_back(value_type _Ch) { _ConcatenateInPlace(&_Ch, 1); } - void resize(size_type nCount, value_type _Ch = ' '); - - //! simple sub-string extraction - _Self substr(size_type pos, size_type count = npos) const; - - // replace part of string. - _Self& replace(value_type chOld, value_type chNew); - _Self& replace(const_str strOld, const_str strNew); - _Self& replace(size_type pos, size_type count, const_str strNew); - _Self& replace(size_type pos, size_type count, const_str strNew, size_type count2); - _Self& replace(size_type pos, size_type count, size_type nNumChars, value_type chNew); - - // insert new elements to string. - _Self& insert(size_type nIndex, value_type ch); - _Self& insert(size_type nIndex, size_type nCount, value_type ch); - _Self& insert(size_type nIndex, const_str pstr); - _Self& insert(size_type nIndex, const_str pstr, size_type nCount); - - //! delete count characters starting at zero-based index - _Self& erase(size_type nIndex, size_type count = npos); - - //! searching (return starting index, or -1 if not found) - //! look for a single character match - //! like "C" strchr - size_type find(value_type ch, size_type pos = 0) const; - //! look for a specific sub-string - //! like "C" strstr - size_type find(const_str subs, size_type pos = 0) const; - size_type rfind(value_type ch, size_type pos = npos) const; - - size_type find_first_of(value_type _Ch, size_type nOff = 0) const; - size_type find_first_of(const_str charSet, size_type nOff = 0) const; - //size_type find_first_of( const value_type* _Ptr,size_type _Off,size_type _Count ) const; - size_type find_first_of(const _Self& _Str, size_type _Off = 0) const; - - size_type find_first_not_of(value_type _Ch, size_type _Off = 0) const; - size_type find_first_not_of(const value_type* _Ptr, size_type _Off = 0) const; - size_type find_first_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const; - size_type find_first_not_of(const _Self& _Str, size_type _Off = 0) const; - - void swap(_Self& _Str); - - ////////////////////////////////////////////////////////////////////////// - // overloaded operators. - ////////////////////////////////////////////////////////////////////////// - // overloaded indexing. - value_type operator[](size_type index) const; - // value_type& operator[]( size_type index ); // same as at() - - // overloaded assignment - _Self& operator=(const _Self& str); - _Self& operator=(value_type ch); - _Self& operator=(const_str str); - _Self& operator=(const CryStringT& str); - - void move(_Self& src); - -#if defined(LINUX) || defined(APPLE) - template - _Self& operator=(const CryStackStringT& str) - { - _Assign(str.c_str(), str.size()); - return *this; - } -#endif - - // string concatenation - _Self& operator+=(const _Self& str); - _Self& operator+=(value_type ch); - _Self& operator+=(const_str str); - _Self& operator+=(const CryStringT& str); - - size_t GetAllocatedMemory() const - { - size_t size = sizeof(*this); - if (m_str != m_strBuf) - { - size += (m_nAllocSize + 1) * sizeof(value_type); - } - return size; - } - - ////////////////////////////////////////////////////////////////////////// - // Extended functions. - // This functions are not in the STL string. - // They have an ATL CString interface. - ////////////////////////////////////////////////////////////////////////// - //! Format string, use (sprintf) - _Self& Format(const value_type* format, ...); - - //! Format string fast, directly formats into string's buffer. - // Make sure there is enough space to hold the string - _Self& FormatFast (const value_type* format, ...); - - //! Converts the string to lower-case. - // This function uses the "C" locale for case-conversion (ie, A-Z only). - _Self& MakeLower(); - - //! Converts the string to upper-case. - // This function uses the "C" locale for case-conversion (ie, A-Z only). - _Self& MakeUpper(); - - _Self& Trim(); - _Self& Trim(value_type ch); - _Self& Trim(const value_type* sCharSet); - - _Self& TrimLeft(); - _Self& TrimLeft(value_type ch); - _Self& TrimLeft(const value_type* sCharSet); - - _Self& TrimRight(); - _Self& TrimRight(value_type ch); - _Self& TrimRight(const value_type* sCharSet); - - _Self SpanIncluding(const_str charSet) const; - _Self SpanExcluding(const_str charSet) const; - _Self Tokenize(const_str charSet, int& nStart) const; - _Self Mid(size_type nFirst, size_type nCount = npos) const { return substr(nFirst, nCount); }; - - _Self Left(size_type count) const; - _Self Right(size_type count) const; - ////////////////////////////////////////////////////////////////////////// - - // public utilities. - static bool _IsValidString(const_str str); - -public: - ////////////////////////////////////////////////////////////////////////// - // Only used for debugging statistics. - ////////////////////////////////////////////////////////////////////////// - static size_t _usedMemory(size_t size) - { - static size_t s_used_memory = 0; - s_used_memory += size; - return s_used_memory; - } - - //private: -public: - size_type m_nLength; - size_type m_nAllocSize; - value_type* m_str; // pointer to ref counted string data - value_type m_strBuf[MAX_SIZE]; - - // implementation helpers - void _AllocData(size_type nLen); - void _FreeData(value_type* pData); - void _Free(); - void _Initialize(); - - void _Concatenate(const_str sStr1, size_type nLen1, const_str sStr2, size_type nLen2); - void _ConcatenateInPlace(const_str sStr, size_type nLen); - void _Assign(const_str sStr, size_type nLen); - void _MakeUnique(); -}; - - -///////////////////////////////////////////////////////////////////////////// -// CryStackStringT Implementation -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -template -inline bool CryStackStringT::_IsValidString(const_str) -{ - return true; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_Assign(const_str sStr, size_type nLen) -{ - // Check if this string is shared (reference count greater then 1) or not enough capacity to store new string. - // Then allocate new string buffer. - if (nLen > capacity()) - { - _Free(); - _AllocData(nLen); - } - // Copy characters from new string to this buffer. - CharTraits::_copy(m_str, sStr, nLen); - // Set new length. - m_nLength = nLen; - // Make null terminated string. - m_str[nLen] = 0; - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_Concatenate(const_str sStr1, size_type nLen1, const_str sStr2, size_type nLen2) -{ - size_type nLen = nLen1 + nLen2; - if (nLen1 * 2 > nLen) - { - nLen = nLen1 * 2; - } - if (nLen != 0) - { - if (nLen < 8) - { - nLen = 8; - } - _AllocData(nLen); - CharTraits::_copy(m_str, sStr1, nLen1); - CharTraits::_copy(m_str + nLen1, sStr2, nLen2); - m_nLength = nLen1 + nLen2; - m_str[nLen1 + nLen2] = 0; - } - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_ConcatenateInPlace(const_str sStr, size_type nLen) -{ - if (nLen != 0) - { - // Check if this string is shared (reference count greater then 1) or not enough capacity to store new string. - // Then allocate new string buffer. - if (length() + nLen > capacity()) - { - value_type* pOldData = m_str; - _Concatenate(m_str, length(), sStr, nLen); - _FreeData(pOldData); - } - else - { - CharTraits::_copy(m_str + length(), sStr, nLen); - m_nLength += nLen; - m_str[m_nLength] = 0; // Make null terminated string. - } - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_MakeUnique() -{ -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_Initialize() -{ - m_strBuf[0] = 0; - m_str = m_strBuf; - m_nLength = 0; - m_nAllocSize = MAX_SIZE - 1; // 0 termination not counted! -} - -// always allocate one extra character for '\0' termination -// assumes [optimistically] that data length will equal allocation length -template -inline void CryStackStringT::_AllocData(size_type nLen) -{ - assert(nLen >= 0); - assert(nLen <= INT_MAX - 1); // max size (enough room for 1 extra) - - if (nLen == 0) - { - _Initialize(); - } - else - { - size_type allocLen = (nLen + 1) * sizeof(value_type); - value_type* pData = m_strBuf; - if (allocLen > MAX_SIZE) - { - pData = (value_type*)CryModuleMalloc(allocLen); - _usedMemory(allocLen); // For statistics. - m_nAllocSize = nLen; - } - else - { - m_nAllocSize = MAX_SIZE - 1; - } - m_nLength = nLen; - m_str = pData; - m_str[nLen] = 0; // null terminated string. - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_Free() -{ - _FreeData(m_str); - _Initialize(); -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::_FreeData(value_type* pData) -{ - if (pData != m_strBuf) - { - size_t allocLen = (m_nAllocSize + 1) * sizeof(value_type); - _usedMemory(-check_cast(allocLen)); // For statistics. - CryModuleFree(pData); - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT() -{ - _Initialize(); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const CryStackStringT& str) -{ - _Initialize(); - _Assign(str.c_str(), str.length()); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const CryStackStringT& str, size_type nOff, size_type nCount) -{ - _Initialize(); - assign(str, nOff, nCount); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const_str str) -{ - _Initialize(); - // Make a copy of C string. - size_type nLen = this->_strlen(str); - if (nLen != 0) - { - _AllocData(nLen); - CharTraits::_copy(m_str, str, nLen); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const CryStringT& str) -{ - _Initialize(); - size_t nLength = str.size(); - if (nLength > 0) - { - _AllocData(nLength); - CharTraits::_copy(m_str, str.c_str(), nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const_str str, size_type nLength) -{ - _Initialize(); - if (nLength > 0) - { - _AllocData(nLength); - CharTraits::_copy(m_str, str, nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -// The reason of making this constructor unavailable (for a while) is -// explained in comments in front of the declaration of -// CryStringT::CryStringT(size_type nRepeat, value_type ch) -// (see CryString.h). -template -inline CryStackStringT::CryStackStringT(size_type nRepeat, value_type ch) -{ - _Initialize(); - if (nRepeat > 0) - { - _AllocData(nRepeat); - CharTraits::_set(m_str, ch, nRepeat); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::CryStackStringT(const_iterator _First, const_iterator _Last) -{ - _Initialize(); - size_type nLength = (size_type)(_Last - _First); - if (nLength > 0) - { - _AllocData(nLength); - CharTraits::_copy(m_str, _First, nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT::~CryStackStringT() -{ - _FreeData(m_str); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::length() const -{ - return m_nLength; -} -template -inline typename CryStackStringT::size_type CryStackStringT::size() const -{ - return m_nLength; -} -template -inline typename CryStackStringT::size_type CryStackStringT::capacity() const -{ - return m_nAllocSize; -} - -template -inline bool CryStackStringT::empty() const -{ - return length() == 0; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::clear() -{ - if (length() == 0) - { - return; - } - _Free(); - assert(length() == 0); -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::reserve(size_type nCount) -{ - // Reserve of 0 is shrinking container to fit number of characters in it.. - if (nCount > capacity()) - { - value_type* pOldData = m_str; - size_type nOldLength = m_nLength; - _AllocData(nCount); - CharTraits::_copy(m_str, pOldData, nOldLength); - m_nLength = nOldLength; - m_str[m_nLength] = 0; - _FreeData(pOldData); - } - else if (nCount == 0) - { - if (length() != capacity()) - { - value_type* pOldData = m_str; - if (pOldData != m_strBuf) // in case we fit into our static buffer, we cannot shrink anyway - { - size_type nOldLength = m_nLength; - _AllocData(m_nLength); - // if (pOldData != m_strBuf || m_str != m_strBuf) // actually always true - // { - CharTraits::_copy(m_str, pOldData, nOldLength); // we can safely use CharTraits::_copy, as we never overlap here (in case of static buffer, we don't shrink anyway) - _FreeData(pOldData); - // } - } - } - } - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(const_str _Ptr) -{ - *this += _Ptr; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(const_str _Ptr, size_type nCount) -{ - _ConcatenateInPlace(_Ptr, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(const CryStackStringT& _Str, size_type off, size_type nCount) -{ - size_type len = _Str.length(); - if (off > len) - { - return *this; - } - if (off + nCount > len) - { - nCount = len - off; - } - _ConcatenateInPlace(_Str.m_str + off, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(const CryStackStringT& _Str) -{ - *this += _Str; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(size_type nCount, value_type _Ch) -{ - if (nCount > 0) - { - if (length() + nCount >= capacity()) - { - value_type* pOldData = m_str; - size_type nOldLength = m_nLength; - _AllocData(length() + nCount); - CharTraits::_copy(m_str, pOldData, nOldLength); - CharTraits::_set(m_str + nOldLength, _Ch, nCount); - _FreeData(pOldData); - } - else - { - size_type nOldLength = length(); - CharTraits::_set(m_str + nOldLength, _Ch, nCount); - m_nLength = nOldLength + nCount; - m_str[length()] = 0; // Make null terminated string. - } - } - CRY_STRING_DEBUG(m_str) - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::append(const_iterator _First, const_iterator _Last) -{ - append(_First, (size_type)(_Last - _First)); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(const_str _Ptr) -{ - *this = _Ptr; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(const_str _Ptr, size_type nCount) -{ - size_type len = this->_strlen(_Ptr); - _Assign(_Ptr, (nCount < len) ? nCount : len); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(const CryStackStringT& _Str, size_type off, size_type nCount) -{ - size_type len = _Str.length(); - if (off > len) - { - return *this; - } - if (off + nCount > len) - { - nCount = len - off; - } - _Assign(_Str.m_str + off, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(const CryStackStringT& _Str) -{ - *this = _Str; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(size_type nCount, value_type _Ch) -{ - if (nCount >= 1) - { - _AllocData(nCount); - CharTraits::_set(m_str, _Ch, nCount); - CRY_STRING_DEBUG(m_str) - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::assign(const_iterator _First, const_iterator _Last) -{ - assign(_First, (size_type)(_Last - _First)); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::value_type CryStackStringT::at(size_type index) const -{ - assert(index >= 0 && index < length()); - return m_str[index]; -} - -/* -inline value_type& CryStackStringT::at( size_type index ) -{ -// same as GetAt -assert( index >= 0 && index < length() ); -return m_str[index]; -} -*/ - -template -inline typename CryStackStringT::value_type CryStackStringT::operator[](size_type index) const -{ - assert(index < length()); - return m_str[index]; -} - - -/* -inline value_type& CryStackStringT::operator[]( size_type index ) -{ -// same as GetAt -assert( index >= 0 && index < length() ); -return m_str[index]; -} -*/ - - -////////////////////////////////////////////////////////////////////////// -template -inline int CryStackStringT::compare(const CryStackStringT& _Str) const -{ - return CharTraits::_strcmp(m_str, _Str.m_str); -} - -template -inline int CryStackStringT::compare(size_type _Pos1, size_type _Num1, const CryStackStringT& _Str) const -{ - return compare(_Pos1, _Num1, _Str.m_str, npos); -} - -template -inline int CryStackStringT::compare(size_type _Pos1, size_type _Num1, const CryStackStringT& _Str, size_type nOff, size_type nCount) const -{ - assert(nOff < _Str.length()); - return compare(_Pos1, _Num1, _Str.m_str + nOff, nCount); -} - -template -inline int CryStackStringT::compare(const value_type* _Ptr) const -{ - return CharTraits::_strcmp(m_str, _Ptr); -} - -template -inline int CryStackStringT::compare(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2) const -{ - assert(_Pos1 < length()); - if (length() - _Pos1 < _Num1) - { - _Num1 = length() - _Pos1; // trim to size - } - int res = _Num1 == 0 ? 0 : CharTraits::_strncmp(m_str + _Pos1, _Ptr, (_Num1 < _Num2) ? _Num1 : _Num2); - return (res != 0 ? res : _Num2 == npos && _Ptr[_Num1] == 0 ? 0 : _Num1 < _Num2 ? -1 : _Num1 == _Num2 ? 0 : +1); -} - -////////////////////////////////////////////////////////////////////////// -template -inline int CryStackStringT::compareNoCase(const CryStackStringT& _Str) const -{ - return CharTraits::_stricmp(m_str, _Str.m_str); -} - -template -inline int CryStackStringT::compareNoCase(size_type _Pos1, size_type _Num1, const CryStackStringT& _Str) const -{ - return compareNoCase(_Pos1, _Num1, _Str.m_str, npos); -} - -template -inline int CryStackStringT::compareNoCase(size_type _Pos1, size_type _Num1, const CryStackStringT& _Str, size_type nOff, size_type nCount) const -{ - assert(nOff < _Str.length()); - return compareNoCase(_Pos1, _Num1, _Str.m_str + nOff, nCount); -} - -template -inline int CryStackStringT::compareNoCase(const value_type* _Ptr) const -{ - return CharTraits::_stricmp(m_str, _Ptr); -} - -template -inline int CryStackStringT::compareNoCase(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2) const -{ - assert(_Pos1 < length()); - if (length() - _Pos1 < _Num1) - { - _Num1 = length() - _Pos1; // trim to size - } - int res = _Num1 == 0 ? 0 : CharTraits::_strnicmp(m_str + _Pos1, _Ptr, (_Num1 < _Num2) ? _Num1 : _Num2); - return (res != 0 ? res : _Num2 == npos && _Ptr[_Num1] == 0 ? 0 : _Num1 < _Num2 ? -1 : _Num1 == _Num2 ? 0 : +1); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::copy(value_type* _Ptr, size_type nCount, size_type nOff) const -{ - assert(nOff < length()); - if (nCount < 0) - { - nCount = 0; - } - if (nOff + nCount > length()) // trim to offset. - { - nCount = length() - nOff; - } - - CharTraits::_copy(_Ptr, m_str + nOff, nCount); - return nCount; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::resize(size_type nCount, value_type _Ch) -{ - _MakeUnique(); - if (nCount > length()) - { - size_type numToAdd = nCount - length(); - append(numToAdd, _Ch); - } - else if (nCount < length()) - { - m_nLength = nCount; - m_str[length()] = 0; // Make null terminated string. - } -} - -////////////////////////////////////////////////////////////////////////// -//! compare helpers -template -inline bool operator==(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) == 0; } -template -inline bool operator==(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) == 0; } -template -inline bool operator==(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) == 0; } -template -inline bool operator!=(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) != 0; } -template -inline bool operator!=(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) != 0; } -template -inline bool operator!=(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) != 0; } -template -inline bool operator<(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) < 0; } -template -inline bool operator<(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) < 0; } -template -inline bool operator<(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) > 0; } -template -inline bool operator>(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) > 0; } -template -inline bool operator>(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) > 0; } -template -inline bool operator>(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) < 0; } -template -inline bool operator<=(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) <= 0; } -template -inline bool operator<=(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) <= 0; } -template -inline bool operator<=(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) >= 0; } -template -inline bool operator>=(const CryStackStringT& s1, const CryStackStringT& s2) -{ return s1.compare(s2) >= 0; } -template -inline bool operator>=(const CryStackStringT& s1, const typename CryStackStringT::value_type* s2) -{ return s1.compare(s2) >= 0; } -template -inline bool operator>=(const typename CryStackStringT::value_type* s1, const CryStackStringT& s2) -{ return s2.compare(s1) <= 0; } - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::operator=(value_type ch) -{ - _Assign(&ch, 1); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT operator+(const CryStackStringT& string1, typename CryStackStringT::value_type ch) -{ - CryStackStringT s(string1); - s.append(1, ch); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT operator+(typename CryStackStringT::value_type ch, const CryStackStringT& str) -{ - CryStackStringT s; - s.reserve(str.size() + 1); - s.append(1, ch); - s.append(str); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT operator+(const CryStackStringT& string1, const CryStackStringT& string2) -{ - CryStackStringT s(string1); - s.append(string2); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT operator+(const CryStackStringT& str1, const typename CryStackStringT::value_type* str2) -{ - CryStackStringT s(str1); - s.append(str2); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT operator+(const typename CryStackStringT::value_type* str1, const CryStackStringT& str2) -{ - assert(str1 == NULL || (CryStackStringT::_IsValidString(str1))); - CryStackStringT s; - s.reserve(CharTraits::_strlen(str1) + str2.size()); - s.append(str1); - s.append(str2); - return s; -} - -template -inline CryStackStringT& CryStackStringT::operator=(const CryStackStringT& str) -{ - _Assign (str.c_str(), str.length()); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator=(const_str str) -{ - assert(str == NULL || _IsValidString(str)); - _Assign(str, this->_strlen(str)); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator=(const CryStringT& str) -{ - _Assign(str.c_str(), str.size()); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator+=(const CryStringT& str) -{ - _ConcatenateInPlace(str.c_str(), str.size()); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator+=(const_str str) -{ - assert(str == NULL || _IsValidString(str)); - _ConcatenateInPlace(str, this->_strlen(str)); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator+=(value_type ch) -{ - _ConcatenateInPlace(&ch, 1); - return *this; -} - -template -inline CryStackStringT& CryStackStringT::operator+=(const CryStackStringT& str) -{ - _ConcatenateInPlace(str.m_str, str.length()); - return *this; -} - -//! find first single character -template -inline typename CryStackStringT::size_type CryStackStringT::find(value_type ch, size_type pos) const -{ - if (!(/*pos >= 0 && */ pos <= length())) - { - return (typename CryStackStringT::size_type)npos; - } - const_str str = CharTraits::_strchr(m_str + pos, ch); - // return npos if not found and index otherwise - return (str == NULL) ? npos : (size_type)(str - m_str); -} - -//! find a sub-string (like strstr) -template -inline typename CryStackStringT::size_type CryStackStringT::find(const_str subs, size_type pos) const -{ - assert(_IsValidString(subs)); - if (!(pos >= 0 && pos <= length())) - { - return npos; - } - - // find first matching substring - const_str str = CharTraits::_strstr(m_str + pos, subs); - - // return npos for not found, distance from beginning otherwise - return (str == NULL) ? npos : (size_type)(str - m_str); -} - -//! find last single character -template -inline typename CryStackStringT::size_type CryStackStringT::rfind(value_type ch, size_type pos) const -{ - const_str str; - if (pos == npos) - { - // find last single character - str = strrchr(m_str, ch); - // return -1 if not found, distance from beginning otherwise - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); - } - else - { - if (pos == npos) - { - pos = length(); - } - if (!(pos >= 0 && pos <= length())) - { - return npos; - } - - value_type tmp = m_str[pos + 1]; - m_str[pos + 1] = 0; - str = strrchr(m_str, ch); - m_str[pos + 1] = tmp; - } - // return -1 if not found, distance from beginning otherwise - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_of(const CryStackStringT& _Str, size_type _Off) const -{ - return find_first_of(_Str.m_str, _Off); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_of(value_type _Ch, size_type nOff) const -{ - if (!(nOff >= 0 && nOff <= length())) - { - return npos; - } - value_type charSet[2] = { _Ch, 0 }; - const_str str = strpbrk(m_str + nOff, charSet); - return (str == NULL) ? -1 : (size_type)(str - m_str); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_of(const_str charSet, size_type nOff) const -{ - assert(_IsValidString(charSet)); - if (!(nOff >= 0 && nOff <= length())) - { - return npos; - } - const_str str = strpbrk(m_str + nOff, charSet); - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -//size_type find_first_not_of(const _Self& __s, size_type __pos = 0) const -//{ return find_first_not_of(__s._M_start, __pos, __s.size()); } - -//size_type find_first_not_of(const _CharT* __s, size_type __pos = 0) const -//{ _STLP_FIX_LITERAL_BUG(__s) return find_first_not_of(__s, __pos, _Traits::length(__s)); } - -//size_type find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const; - -//size_type find_first_not_of(_CharT __c, size_type __pos = 0) const; - - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_not_of(const value_type* _Ptr, size_type _Off) const -{ return find_first_not_of(_Ptr, _Off, this->_strlen(_Ptr)); } - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_not_of(const CryStackStringT& _Str, size_type _Off) const -{ return find_first_not_of(_Str.m_str, _Off); } - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_not_of(value_type _Ch, size_type _Off) const -{ - if (_Off > length()) - { - return npos; - } - else - { - for (const value_type* str = begin() + _Off; str != end(); ++str) - { - if (*str != _Ch) - { - return size_type(str - begin()); // Character found! - } - } - return npos; - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStackStringT::size_type CryStackStringT::find_first_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const -{ - if (_Off > length()) - { - return npos; - } - else - { - const value_type* charsFirst = _Ptr, * charsLast = _Ptr + _Count; - for (const value_type* str = begin() + _Off; str != end(); ++str) - { - const value_type* c; - for (c = charsFirst; c != charsLast; ++c) - { - if (*c == *str) - { - break; - } - } - if (c == charsLast) - { - return size_type(str - begin());// Current character not in char set. - } - } - return npos; - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT CryStackStringT::substr(size_type pos, size_type count) const -{ - if (pos >= length()) - { - return CryStackStringT(); - } - if (count == npos) - { - count = length() - pos; - } - if (pos + count > length()) - { - count = length() - pos; - } - return CryStackStringT(m_str + pos, count); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::erase(size_type nIndex, size_type nCount) -{ - if (nIndex < 0) - { - nIndex = 0; - } - if (nCount < 0 || nCount > length() - nIndex) - { - nCount = length() - nIndex; - } - if (nCount > 0 && nIndex < length()) - { - _MakeUnique(); - size_type nNumToCopy = length() - (nIndex + nCount) + 1; - CharTraits::_move(m_str + nIndex, m_str + nIndex + nCount, nNumToCopy); - m_nLength = length() - nCount; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::insert(size_type nIndex, value_type ch) -{ - return insert(nIndex, 1, ch); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::insert(size_type nIndex, size_type nCount, value_type ch) -{ - _MakeUnique(); - - if (nIndex < 0) - { - nIndex = 0; - } - - size_type nNewLength = length(); - if (nIndex > nNewLength) - { - nIndex = nNewLength; - } - nNewLength += nCount; - - if (capacity() < nNewLength) - { - value_type* pOldData = m_str; - size_type nOldLength = m_nLength; - const_str pstr = m_str; - _AllocData(nNewLength); - CharTraits::_copy(m_str, pstr, nOldLength + 1); - _FreeData(pOldData); - } - - CharTraits::_move(m_str + nIndex + nCount, m_str + nIndex, (nNewLength - nIndex)); - CharTraits::_set(m_str + nIndex, ch, nCount); - m_nLength = nNewLength; - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::insert(size_type nIndex, const_str pstr, size_type nCount) -{ - if (nIndex < 0) - { - nIndex = 0; - } - - size_type nInsertLength = nCount; - size_type nNewLength = length(); - if (nInsertLength > 0) - { - _MakeUnique(); - if (nIndex > nNewLength) - { - nIndex = nNewLength; - } - nNewLength += nInsertLength; - - if (capacity() < nNewLength) - { - value_type* pOldData = m_str; - size_type nOldLength = m_nLength; - const_str pOldStr = m_str; - _AllocData(nNewLength); - CharTraits::_copy(m_str, pOldStr, (nOldLength + 1)); - _FreeData(pOldData); - } - - CharTraits::_move(m_str + nIndex + nInsertLength, m_str + nIndex, (nNewLength - nIndex - nInsertLength + 1)); - CharTraits::_copy(m_str + nIndex, pstr, nInsertLength); - m_nLength = nNewLength; - m_str[length()] = 0; - } - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::insert(size_type nIndex, const_str pstr) -{ - return insert(nIndex, pstr, this->_strlen(pstr)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::replace(size_type pos, size_type count, const_str strNew) -{ - return replace(pos, count, strNew, this->_strlen(strNew)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::replace(size_type pos, size_type count, const_str strNew, size_type count2) -{ - erase(pos, count); - insert(pos, strNew, count2); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::replace(size_type pos, size_type count, size_type nNumChars, value_type chNew) -{ - erase(pos, count); - insert(pos, nNumChars, chNew); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::replace(value_type chOld, value_type chNew) -{ - if (chOld != chNew) - { - _MakeUnique(); - value_type* strend = m_str + length(); - for (value_type* str = m_str; str != strend; ++str) - { - if (*str == chOld) - { - *str = chNew; - } - } - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::replace(const_str strOld, const_str strNew) -{ - size_type nSourceLen = this->_strlen(strOld); - if (nSourceLen == 0) - { - return *this; - } - size_type nReplacementLen = this->_strlen(strNew); - - size_type nCount = 0; - value_type* strStart = m_str; - value_type* strEnd = m_str + length(); - value_type* strTarget; - while (strStart < strEnd) - { - while ((strTarget = CharTraits::_strstr(strStart, strOld)) != NULL) - { - nCount++; - strStart = strTarget + nSourceLen; - } - strStart += this->_strlen(strStart) + 1; - } - - if (nCount > 0) - { - _MakeUnique(); - - size_type nOldLength = length(); - size_type nNewLength = nOldLength + (nReplacementLen - nSourceLen) * nCount; - if (capacity() < nNewLength) - { - value_type* pOldData = m_str; - size_type nPrevLength = m_nLength; - const_str pstr = m_str; - _AllocData(nNewLength); - CharTraits::_copy(m_str, pstr, nPrevLength); - _FreeData(pOldData); - } - strStart = m_str; - strEnd = m_str + length(); - - while (strStart < strEnd) - { - while ((strTarget = CharTraits::_strstr(strStart, strOld)) != NULL) - { - size_type nBalance = nOldLength - ((size_type)(strTarget - m_str) + nSourceLen); - CharTraits::_move(strTarget + nReplacementLen, strTarget + nSourceLen, nBalance); - CharTraits::_copy(strTarget, strNew, nReplacementLen); - strStart = strTarget + nReplacementLen; - strStart[nBalance] = 0; - nOldLength += (nReplacementLen - nSourceLen); - } - strStart += this->_strlen(strStart) + 1; - } - m_nLength = nNewLength; - } - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStackStringT::move(CryStackStringT& str) -{ - memcpy(this, &str, sizeof(*this)); - if (str.m_str == str.m_strBuf) - { - m_str = m_strBuf; - } -} - -template -inline void CryStackStringT::swap(CryStackStringT& _Str) -{ - CryStackStringT temp; - temp.move(*this); - move(_Str); - _Str.move(temp); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::Format(const_str format, ...) -{ - assert(_IsValidString(format)); - - value_type temp[4096]; // Limited to 4096 characters! - va_list argList; - va_start(argList, format); - this->_vsnprintf(temp, 4095, format, argList); - temp[4095] = '\0'; - va_end(argList); - *this = temp; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::FormatFast(const_str format, ...) -{ - assert(_IsValidString(format)); - - va_list argList; - va_start(argList, format); - - int newLength = this->_vsnprintf(m_str, capacity(), format, argList); - if (newLength >= 0) - { - m_nLength = (size_type)newLength; - } - else - { - m_nLength = capacity(); - m_str[capacity()] = '\0'; - } - - va_end(argList); - - return *this; -} - - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::MakeLower() -{ - _MakeUnique(); - for (value_type* s = m_str; *s != 0; s++) - { - *s = this->_ascii_tolower(*s); - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::MakeUpper() -{ - _MakeUnique(); - for (value_type* s = m_str; *s != 0; s++) - { - *s = this->_ascii_toupper(*s); - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::Trim() -{ - return TrimRight().TrimLeft(); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::Trim(value_type ch) -{ - _MakeUnique(); - const value_type chset[2] = { ch, 0 }; - return TrimRight(chset).TrimLeft(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::Trim(const value_type* sCharSet) -{ - _MakeUnique(); - return TrimRight(sCharSet).TrimLeft(sCharSet); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimRight(value_type ch) -{ - const value_type chset[2] = { ch, 0 }; - return TrimRight(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimRight(const value_type* sCharSet) -{ - if (!sCharSet || !(*sCharSet) || length() < 1) - { - return *this; - } - - const value_type* last = m_str + length() - 1; - const value_type* str = last; - while ((str != m_str) && (CharTraits::_strchr(sCharSet, *str) != 0)) - { - str--; - } - - if (str != last) - { - // Just shrink length of the string. - size_type nNewLength = (size_type)(str - m_str) + 1; // m_str can change in _MakeUnique - _MakeUnique(); - m_nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimRight() -{ - if (length() < 1) - { - return *this; - } - - const value_type* last = m_str + length() - 1; - const value_type* str = last; - while ((str != m_str) && (CharTraits::_isspace(*str) != 0)) - { - str--; - } - - if (str != last) // something changed? - { - // Just shrink length of the string. - size_type nNewLength = (size_type)(str - m_str) + 1; // m_str can change in _MakeUnique - _MakeUnique(); - m_nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimLeft(value_type ch) -{ - const value_type chset[2] = { ch, 0 }; - return TrimLeft(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimLeft(const value_type* sCharSet) -{ - if (!sCharSet || !(*sCharSet)) - { - return *this; - } - - const value_type* str = m_str; - while ((*str != 0) && (CharTraits::_strchr(sCharSet, *str) != 0)) - { - str++; - } - - if (str != m_str) - { - size_type nOff = (size_type)(str - m_str); // m_str can change in _MakeUnique - _MakeUnique(); - size_type nNewLength = length() - nOff; - CharTraits::_move(m_str, m_str + nOff, nNewLength + 1); - m_nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT& CryStackStringT::TrimLeft() -{ - const value_type* str = m_str; - while ((*str != 0) && (CharTraits::_isspace(*str) != 0)) - { - str++; - } - - if (str != m_str) - { - size_type nOff = (size_type)(str - m_str); // m_str can change in _MakeUnique - _MakeUnique(); - size_type nNewLength = length() - nOff; - CharTraits::_move(m_str, m_str + nOff, nNewLength + 1); - m_nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -template -inline CryStackStringT CryStackStringT::Right(size_type count) const -{ - if (count == npos) - { - return CryStackStringT(); - } - else if (count > length()) - { - return *this; - } - - return CryStackStringT(m_str + length() - count, count); -} - -template -inline CryStackStringT CryStackStringT::Left(size_type count) const -{ - if (count == npos) - { - return CryStackStringT(); - } - else if (count > length()) - { - count = length(); - } - - return CryStackStringT(m_str, count); -} - -// strspn equivalent -template -inline CryStackStringT CryStackStringT::SpanIncluding(const_str charSet) const -{ - assert(_IsValidString(charSet)); - return Left((size_type)this->_strspn(m_str, charSet)); -} - -// strcspn equivalent -template -inline CryStackStringT CryStackStringT::SpanExcluding(const_str charSet) const -{ - assert(_IsValidString(charSet)); - return Left((size_type)this->_strcspn(m_str, charSet)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStackStringT CryStackStringT::Tokenize(const_str charSet, int& nStart) const -{ - if (nStart < 0) - { - return CryStackStringT(); - } - - if (!charSet) - { - return *this; - } - - const_str sPlace = m_str + nStart; - const_str sEnd = m_str + length(); - if (sPlace < sEnd) - { - int nIncluding = (int)this->_strspn(sPlace, charSet); - - if ((sPlace + nIncluding) < sEnd) - { - sPlace += nIncluding; - int nExcluding = (int)this->_strcspn(sPlace, charSet); - int nFrom = nStart + nIncluding; - nStart = nFrom + nExcluding + 1; - - return substr(nFrom, nExcluding); - } - } - // Return empty string. - nStart = -1; - return CryStackStringT(); -} - -#if defined(_RELEASE) -#define ASSERT_LEN (void)(0) -#define ASSERT_WLEN (void)(0) -#else -#define ASSERT_LEN CRY_ASSERT_TRACE(this->length() <= S, ("String '%s' is %u character(s) longer than MAX_SIZE=%u", this->c_str(), this->length() - S, S)) -#define ASSERT_WLEN CRY_ASSERT_TRACE(this->length() <= S, ("Wide-char string '%ls' is %u character(s) longer than MAX_SIZE=%u", this->c_str(), this->length() - S, S)) -#endif - -// a template specialization for char -template -class CryFixedStringT - : public CryStackStringT -{ -public: - typedef CryStackStringT _parentType; - typedef CryFixedStringT _Self; - typedef size_t size_type; - typedef char value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - static const size_type MAX_SIZE = S; - CryFixedStringT() - : _parentType() {} - CryFixedStringT(const _parentType& str) - : _parentType(str) {ASSERT_LEN; } - CryFixedStringT(const _parentType& str, size_type nOff, size_type nCount) - : _parentType(str, nOff, nCount) {ASSERT_LEN; } - CryFixedStringT(const _Self& str) - : _parentType(str) {ASSERT_LEN; } - CryFixedStringT(const _Self& str, size_type nOff, size_type nCount) - : _parentType(str, nOff, nCount) {ASSERT_LEN; } - CryFixedStringT(size_type nRepeat, value_type ch) - : _parentType(nRepeat, ch) {ASSERT_LEN; } - CryFixedStringT(const_str str) - : _parentType (str) {ASSERT_LEN; } - CryFixedStringT(const_str str, size_type nLength) - : _parentType(str, nLength) {ASSERT_LEN; } - CryFixedStringT(const_iterator _First, const_iterator _Last) - : _parentType(_First, _Last) {ASSERT_LEN; } - - template - _Self& operator=(const CryFixedStringT& str) - { - _parentType::operator = (str); - ASSERT_LEN; - return *this; - } - template - _Self& operator=(const CryStackStringT& str) - { - _parentType::operator = (str); - ASSERT_LEN; - return *this; - } - _Self& operator=(value_type ch) - { - _parentType::operator = (ch); - ASSERT_LEN; - return *this; - } - - void GetMemoryUsage(class ICrySizer* pSizer) const{} -}; - -// a template specialization for a fixed list of CryFixedString [Jan M.] -template -class CCryFixedStringListT -{ -public: - CCryFixedStringListT() - { Clear(); } - - void Clear() - { - m_currentAmount = -1; - for (int a = 0; a < NUM_MAX_ELEMENTS; ++a) - { - m_data[a] = ""; - } - } - - void Add(const char* name) - { - m_data[++m_currentAmount] = name; - if (m_currentAmount == NUM_MAX_ELEMENTS) - { - m_currentAmount = -1; - } - } - - const char* operator[](int index) - { - if (index <= m_currentAmount) - { - return m_data[index].c_str(); - } - return NULL; - } - - ILINE int Size() { return m_currentAmount + 1; } - - CryFixedStringT<32>* GetData(int& amount) - { - amount = m_currentAmount + 1; - return m_data; - } -private: - const static int NUM_MAX_ELEMENTS = maxElements; - CryFixedStringT m_data[NUM_MAX_ELEMENTS]; - int32 m_currentAmount; -}; - -// a template specialization for wchar_t -template -class CryFixedWStringT - : public CryStackStringT -{ -public: - typedef CryStackStringT _parentType; - typedef CryFixedWStringT _Self; - typedef size_t size_type; - typedef wchar_t value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - static const size_type MAX_SIZE = S; - CryFixedWStringT() - : _parentType() {} - CryFixedWStringT(const _parentType& str) - : _parentType(str) {ASSERT_WLEN; } - CryFixedWStringT(const _parentType& str, size_type nOff, size_type nCount) - : _parentType(str, nOff, nCount) {ASSERT_WLEN; } - CryFixedWStringT(const _Self& str) - : _parentType(str) {ASSERT_WLEN; } - CryFixedWStringT(const _Self& str, size_type nOff, size_type nCount) - : _parentType(str, nOff, nCount) {ASSERT_WLEN; } - CryFixedWStringT(size_type nRepeat, value_type ch) - : _parentType(nRepeat, ch) {ASSERT_WLEN; } - CryFixedWStringT(const_str str) - : _parentType (str) {ASSERT_WLEN; } - CryFixedWStringT(const_str str, size_type nLength) - : _parentType(str, nLength) {ASSERT_WLEN; } - CryFixedWStringT(const_iterator _First, const_iterator _Last) - : _parentType(_First, _Last) {ASSERT_WLEN; } - - template - _Self& operator=(const CryFixedWStringT& str) - { - _parentType::operator = (str); - ASSERT_WLEN; - return *this; - } - template - _Self& operator=(const CryStackStringT& str) - { - _parentType::operator = (str); - ASSERT_WLEN; - return *this; - } -}; -#undef ASSERT_LEN -#undef ASSERT_WLEN -typedef CryStackStringT stack_string; - -// Special string type used for specifying file paths. -typedef CryStackStringT CryPathString; - - -#if UNITTEST_CRYFIXEDSTRING - -struct SUnitTest_FixedString -{ - bool UnitAssert(const char* message, const char* value, const char* refValue) - { - int res = strcmp(value, refValue); - CRY_ASSERT_MESSAGE(res == 0, message); - return res == 0; - } - - bool UnitAssert(const char* message, const wchar_t* value, const wchar_t* refValue) - { - int res = wcscmp(value, refValue); - CRY_ASSERT_MESSAGE(res == 0, message); - return res == 0; - } - - bool UnitAssert(const char* message, bool cond) - { - CRY_ASSERT_MESSAGE(cond, message); - return cond; - } - - bool UnitAssert(const char* message, size_t a, size_t b) - { - CRY_ASSERT_MESSAGE(a == b, message); - return a == b; - } - - int UnitTest() - { - CryStackStringT str1; - CryStackStringT str2; - CryStackStringT str3; - CryStackStringT str4; - CryStackStringT str5; - CryStackStringT wstr1; - CryStackStringT wstr2; - CryFixedStringT<100> fixedString100; - CryFixedStringT<200> fixedString200; - - typedef CryStackStringT T; - T* pStr = new T; - * pStr = "adads"; - delete pStr; - - str1 = "abcd"; - UnitAssert ("Assignment1-EnoughSpace", str1, "abcd"); - - str2 = "efg"; - UnitAssert ("Assignment2-EnoughSpace", str2, "efg"); - - str2 = str1; - UnitAssert ("Assignment3-EnoughSpace", str2, "abcd"); - - str3 = str1; - UnitAssert ("Assignment4-NotEnoughSpace", str3, "abcd"); - - str1 += "XY"; - UnitAssert ("Concatenate-EnoughSpace", str1, "abcdXY"); - - str2 += "efghijk"; - UnitAssert ("Concatenate-NotEnoughSpace", str2, "abcdefghijk"); - - str1.replace("bc", ""); - UnitAssert ("Replace-Shrink-EnoughSpace", str1, "adXY"); - - str1.replace("XY", "1234"); - UnitAssert ("Replace-Grow-EnoughSpace", str1, "ad1234"); - - str1.replace("1234", "1234567890"); - UnitAssert ("Replace-Grow-NotEnoughSpace", str1, "ad1234567890"); - - str1.reserve(200); - UnitAssert ("Reserve200-SameString", str1, "ad1234567890"); - UnitAssert ("Reserve200-Capacity", str1.capacity() == 200); - - str1.reserve(0); - UnitAssert ("Reserve0-SameString", str1, "ad1234567890"); - UnitAssert ("Reserve0-Capacity==Length", str1.capacity() == str1.length()); - - str1.erase(7); // doesn't change capacity - UnitAssert ("Erase-SameString", str1, "ad12345"); - - str4.assign("abc"); - UnitAssert ("Str4 Assignment", str4, "abc"); - str4.reserve(9); - UnitAssert ("Str4", str4.capacity() >= 9); // capacity is always >= MAX_SIZE-1 - str4.reserve(0); - UnitAssert ("Str4-Shrink", str4.capacity() >= 9); // capacity is always >= MAX_SIZE-1 - - size_t idx = str1.find("123"); - UnitAssert ("Str1-Find", idx == 2); - - idx = str1.find("123", 3); - UnitAssert ("Str1-Find", idx == str1.npos); - - wstr1 = L"abc"; - UnitAssert ("WStr1-Assign", wstr1, L"abc"); - UnitAssert ("WStr1-CompareCaseGT", wstr1.compare(L"aBc") > 0); - UnitAssert ("WStr1-CompareCaseLT", wstr1.compare(L"babc") < 0); - UnitAssert ("WStr1-CompareNoCase", wstr1.compareNoCase(L"aBc") == 0); - - str1.Format("This is a %s %S with %d params", "mixed", L"string", 3); - str2.Format("This is a %S %s with %d params", L"mixed", "string", 3); - UnitAssert ("Str1-Format1", str1, "This is a mixed string with 3 params"); - UnitAssert ("Str1-Format2", str1, str2); - - wstr1.Format(L"This is a %s %S with %d params", L"mixed", "string", 3); - wstr2.Format(L"This is a %S %s with %d params", "mixed", L"string", 3); - UnitAssert ("WStr1-Format1", wstr1, L"This is a mixed string with 3 params"); - UnitAssert ("WStr1-Format2", wstr1, wstr2); - - str5.FormatFast("%s", "12345"); - UnitAssert ("Str5-FormatFast", str5, "12345"); - - str5.FormatFast("%s", "012345"); - UnitAssert ("Str5-FormatFast-Truncate", str5, "01234"); - - fixedString100 = str5; - str2 = fixedString200; - fixedString200 = fixedString100; - UnitAssert ("FixedString-Test2", fixedString100, "01234"); - UnitAssert ("FixedString-Test1", fixedString100, fixedString200); - - CryStackStringT testStr; - CryFixedStringT<100> testStr2; - CryFixedWStringT<100> testWStr1; - string normalString; - wstring normalWString; - normalString = string(testStr); - normalString = string(testStr2); - normalString.assign(testStr2.c_str()); - // normalString = testStr; // <- must NOT compile, as we don't allow it! - // normalWString = testWStr1; // <- must NOT compile, as we don't allow it! - normalWString = wstring(testWStr1); - return 0; - } -}; -#endif // #if UNITTEST_CRYFIXEDSTRING - -#endif // CRYINCLUDE_CRYCOMMON_CRYFIXEDSTRING_H diff --git a/Code/CryEngine/CryCommon/CryHalf.inl b/Code/CryEngine/CryCommon/CryHalf.inl deleted file mode 100644 index b882e5e079..0000000000 --- a/Code/CryEngine/CryCommon/CryHalf.inl +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRY_HALF_INL -#define CRY_HALF_INL - -#pragma once - - - -typedef uint16 CryHalf; -class ICrySizer; - -typedef union floatint_union -{ - float f; - uint32 i; -} floatint_union; - -__forceinline CryHalf CryConvertFloatToHalf(const float Value) -{ -#if defined(LINUX) || defined(MAC) - asm volatile("" ::: "memory"); -#endif - unsigned int Result; - - unsigned int IValue = ((unsigned int*)(&Value))[0]; - unsigned int Sign = (IValue & 0x80000000U) >> 16U; - IValue = IValue & 0x7FFFFFFFU; // Hack off the sign - - if (IValue > 0x47FFEFFFU) - { - // The number is too large to be represented as a half. Saturate to infinity. - Result = 0x7FFFU; - } - else - { - if (IValue < 0x38800000U) - { - // The number is too small to be represented as a normalized half. - // Convert it to a denormalized value. - unsigned int Shift = 113U - (IValue >> 23U); - IValue = (0x800000U | (IValue & 0x7FFFFFU)) >> Shift; - } - else - { - // Rebias the exponent to represent the value as a normalized half. - IValue += 0xC8000000U; - } - - Result = ((IValue + 0x0FFFU + ((IValue >> 13U) & 1U)) >> 13U) & 0x7FFFU; - } - return (CryHalf)(Result | Sign); -} - -__forceinline float CryConvertHalfToFloat(const CryHalf Value) -{ -#if defined(LINUX) || defined(MAC) - asm volatile("" ::: "memory"); -#endif - unsigned int Mantissa; - unsigned int Exponent; - unsigned int Result; - - Mantissa = (unsigned int)(Value & 0x03FF); - - if ((Value & 0x7C00) != 0) // The value is normalized - { - Exponent = (unsigned int)((Value >> 10) & 0x1F); - } - else if (Mantissa != 0) // The value is denormalized - { - // Normalize the value in the resulting float - Exponent = 1; - - do - { - Exponent--; - Mantissa <<= 1; - } while ((Mantissa & 0x0400) == 0); - - Mantissa &= 0x03FF; - } - else // The value is zero - { - Exponent = (unsigned int)-112; - } - - Result = ((Value & 0x8000) << 16) | // Sign - ((Exponent + 112) << 23) | // Exponent - (Mantissa << 13); // Mantissa - - return *(float*)&Result; -} - -struct CryHalf2 -{ - CryHalf x; - CryHalf y; - - CryHalf2() - { - } - CryHalf2(CryHalf _x, CryHalf _y) - : x(_x) - , y(_y) - { - } - CryHalf2(const CryHalf* const __restrict pArray) - { - x = pArray[0]; - y = pArray[1]; - } - CryHalf2(float _x, float _y) - { - x = CryConvertFloatToHalf(_x); - y = CryConvertFloatToHalf(_y); - } - CryHalf2(const float* const __restrict pArray) - { - x = CryConvertFloatToHalf(pArray[0]); - y = CryConvertFloatToHalf(pArray[1]); - } - CryHalf2& operator= (const CryHalf2& Half2) - { - x = Half2.x; - y = Half2.y; - return *this; - } - - bool operator !=(const CryHalf2& rhs) const - { - return x != rhs.x || y != rhs.y; - } - - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const {} - - AUTO_STRUCT_INFO -}; - -struct CryHalf4 -{ - CryHalf x; - CryHalf y; - CryHalf z; - CryHalf w; - - CryHalf4() - { - } - CryHalf4(CryHalf _x, CryHalf _y, CryHalf _z, CryHalf _w) - : x(_x) - , y(_y) - , z(_z) - , w(_w) - { - } - CryHalf4(const CryHalf* const __restrict pArray) - { - x = pArray[0]; - y = pArray[1]; - z = pArray[2]; - w = pArray[3]; - } - CryHalf4(float _x, float _y, float _z, float _w) - { - x = CryConvertFloatToHalf(_x); - y = CryConvertFloatToHalf(_y); - z = CryConvertFloatToHalf(_z); - w = CryConvertFloatToHalf(_w); - } - CryHalf4(const float* const __restrict pArray) - { - x = CryConvertFloatToHalf(pArray[0]); - y = CryConvertFloatToHalf(pArray[1]); - z = CryConvertFloatToHalf(pArray[2]); - w = CryConvertFloatToHalf(pArray[3]); - } - CryHalf4& operator= (const CryHalf4& Half4) - { - x = Half4.x; - y = Half4.y; - z = Half4.z; - w = Half4.w; - return *this; - } - bool operator !=(const CryHalf4& rhs) const - { - return x != rhs.x || y != rhs.y || z != rhs.z || w != rhs.w; - } - - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const {} - - AUTO_STRUCT_INFO -}; - -#endif // #ifndef CRY_HALF_INL diff --git a/Code/CryEngine/CryCommon/CryHalf_info.h b/Code/CryEngine/CryCommon/CryHalf_info.h deleted file mode 100644 index 4c9f0cf336..0000000000 --- a/Code/CryEngine/CryCommon/CryHalf_info.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYHALF_INFO_H -#define CRYINCLUDE_CRYCOMMON_CRYHALF_INFO_H -#pragma once - -#include "CryHalf.inl" - -STRUCT_INFO_BEGIN(CryHalf2) -STRUCT_VAR_INFO(x, TYPE_INFO(CryHalf)) -STRUCT_VAR_INFO(y, TYPE_INFO(CryHalf)) -STRUCT_INFO_END(CryHalf2) - -STRUCT_INFO_BEGIN(CryHalf4) -STRUCT_VAR_INFO(x, TYPE_INFO(CryHalf)) -STRUCT_VAR_INFO(y, TYPE_INFO(CryHalf)) -STRUCT_VAR_INFO(z, TYPE_INFO(CryHalf)) -STRUCT_VAR_INFO(w, TYPE_INFO(CryHalf)) -STRUCT_INFO_END(CryHalf4) - -#endif // CRYINCLUDE_CRYCOMMON_CRYHALF_INFO_H diff --git a/Code/CryEngine/CryCommon/CryHeaders.h b/Code/CryEngine/CryCommon/CryHeaders.h deleted file mode 100644 index a23d8d6978..0000000000 --- a/Code/CryEngine/CryCommon/CryHeaders.h +++ /dev/null @@ -1,1505 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYHEADERS_H -#define CRYINCLUDE_CRYCOMMON_CRYHEADERS_H -#pragma once - - -#include "BaseTypes.h" -#include "Cry_Math.h" - -#ifdef MAX_SUB_MATERIALS -// This checks that the values are in sync in the different files. -COMPILE_TIME_ASSERT(MAX_SUB_MATERIALS == 128); -#else - #define MAX_SUB_MATERIALS 128 -#endif - -#include "CryEndian.h" - -// Chunk type must fit into uint16 -enum ChunkTypes -{ - ChunkType_ANY = 0, - - ChunkType_Mesh = 0x1000, // was 0xCCCC0000 in chunk files with versions <= 0x745 - ChunkType_Helper, - ChunkType_VertAnim, - ChunkType_BoneAnim, - ChunkType_GeomNameList, // obsolete - ChunkType_BoneNameList, - ChunkType_MtlList, // obsolete - ChunkType_MRM, // obsolete - ChunkType_SceneProps, // obsolete - ChunkType_Light, // obsolete - ChunkType_PatchMesh, // not implemented - ChunkType_Node, - ChunkType_Mtl, // obsolete - ChunkType_Controller, - ChunkType_Timing, - ChunkType_BoneMesh, - ChunkType_BoneLightBinding, // obsolete. describes the lights binded to bones - ChunkType_MeshMorphTarget, // describes a morph target of a mesh chunk - ChunkType_BoneInitialPos, // describes the initial position (4x3 matrix) of each bone; just an array of 4x3 matrices - ChunkType_SourceInfo, // describes the source from which the cgf was exported: source max file, machine and user - ChunkType_MtlName, // material name - ChunkType_ExportFlags, // Special export flags. - ChunkType_DataStream, // Stream data. - ChunkType_MeshSubsets, // Array of mesh subsets. - ChunkType_MeshPhysicsData, // Physicalized mesh data. - - // these are the new compiled chunks for characters - ChunkType_CompiledBones = 0x2000, // was 0xACDC0000 in chunk files with versions <= 0x745 - ChunkType_CompiledPhysicalBones, - ChunkType_CompiledMorphTargets, - ChunkType_CompiledPhysicalProxies, - ChunkType_CompiledIntFaces, - ChunkType_CompiledIntSkinVertices, - ChunkType_CompiledExt2IntMap, - - ChunkType_BreakablePhysics = 0x3000, // was 0xAAFC0000 in chunk files with versions <= 0x745 - ChunkType_FaceMap, // obsolete - ChunkType_MotionParameters, - ChunkType_FootPlantInfo, // obsolete - ChunkType_BonesBoxes, - ChunkType_FoliageInfo, - ChunkType_Timestamp, - ChunkType_GlobalAnimationHeaderCAF, - ChunkType_GlobalAnimationHeaderAIM, - ChunkType_BspTreeData -}; - -enum ECgfStreamType -{ - CGF_STREAM_POSITIONS, - CGF_STREAM_NORMALS, - CGF_STREAM_TEXCOORDS, - CGF_STREAM_COLORS, - CGF_STREAM_COLORS2, - CGF_STREAM_INDICES, - CGF_STREAM_TANGENTS, - CGF_STREAM_DUMMY0_, // used to be CGF_STREAM_SHCOEFFS, dummy is needed to keep existing assets loadable - CGF_STREAM_DUMMY1_, // used to be CGF_STREAM_SHAPEDEFORMATION, dummy is needed to keep existing assets loadable - CGF_STREAM_BONEMAPPING, - CGF_STREAM_FACEMAP, - CGF_STREAM_VERT_MATS, - CGF_STREAM_QTANGENTS, - CGF_STREAM_SKINDATA, - CGF_STREAM_DUMMY2_, // used to be old console specific, dummy is needed to keep existing assets loadable - CGF_STREAM_P3S_C4B_T2S, - CGF_STREAM_NUM_TYPES -}; - -////////////////////////////////////////////////////////////////////////// -enum EPhysicsGeomType -{ - PHYS_GEOM_TYPE_NONE = -1, - PHYS_GEOM_TYPE_DEFAULT = 0x1000 + 0, - PHYS_GEOM_TYPE_NO_COLLIDE = 0x1000 + 1, - PHYS_GEOM_TYPE_OBSTRUCT = 0x1000 + 2, - - PHYS_GEOM_TYPE_DEFAULT_PROXY = 0x1000 + 0x100, // Default physicalization, but only proxy (NoDraw geometry). -}; - -struct CryVertex -{ - Vec3 p; //position - Vec3 n; //normal vector - - AUTO_STRUCT_INFO -}; - -struct CryFace -{ - int v0, v1, v2; //vertex indices - int MatID; //mat ID - - int& operator [] (int i) {return (&v0)[i]; } - int operator [] (int i) const {return (&v0)[i]; } - bool isDegenerate () const {return v0 == v1 || v1 == v2 || v2 == v0; } - - AUTO_STRUCT_INFO -}; - -struct CryUV -{ - float u, v; //texture coordinates - AUTO_STRUCT_INFO -}; - -struct CrySkinVtx -{ - int bVolumetric; - int idx[4]; - float w[4]; - Matrix33 M; - - AUTO_STRUCT_INFO -}; - -////////////////////////////////////////////////////////////////////////// -struct CryLink -{ - int BoneID; - Vec3 offset; - float Blending; - - AUTO_STRUCT_INFO -}; - -struct CryIRGB -{ - unsigned char r, g, b; - AUTO_STRUCT_INFO -}; - -struct NAME_ENTITY -{ - char name[64]; -}; - -struct phys_geometry; - -struct CryBonePhysics -{ - phys_geometry* pPhysGeom; // id of a separate mesh for this bone // MUST not be in File Structures!!! - // additional joint parameters - int flags; - float min[3], max[3]; - float spring_angle[3]; - float spring_tension[3]; - float damping[3]; - float framemtx[3][3]; -}; - -// the compatible between 32- and 64-bits structure -struct CryBonePhysics_Comp -{ - int nPhysGeom; // id of a separate mesh for this bone - // additional joint parameters - int flags; - float min[3], max[3]; - float spring_angle[3]; - float spring_tension[3]; - float damping[3]; - float framemtx[3][3]; - - AUTO_STRUCT_INFO -}; - -#define __copy3(MEMBER) left.MEMBER[0] = right.MEMBER[0]; left.MEMBER[1] = right.MEMBER[1]; left.MEMBER[2] = right.MEMBER[2]; -inline void CopyPhysInfo(CryBonePhysics& left, const CryBonePhysics_Comp& right) -{ - left.pPhysGeom = (phys_geometry*)(INT_PTR)right.nPhysGeom; - left.flags = right.flags; - __copy3(min); - __copy3(max); - __copy3(spring_angle); - __copy3(spring_tension); - __copy3(damping); - __copy3(framemtx[0]); - __copy3(framemtx[1]); - __copy3(framemtx[2]); -} -inline void CopyPhysInfo(CryBonePhysics_Comp& left, const CryBonePhysics& right) -{ - left.nPhysGeom = (int)(INT_PTR)right.pPhysGeom; - left.flags = right.flags; - __copy3(min); - __copy3(max); - __copy3(spring_angle); - __copy3(spring_tension); - __copy3(damping); - __copy3(framemtx[0]); - __copy3(framemtx[1]); - __copy3(framemtx[2]); -} -#undef __copy3 - -struct CryBoneDescData -{ - unsigned int m_nControllerID; // unic id of bone (generated from bone name in the max) - - // [Sergiy] physics info for different lods - // lod 0 is the physics of alive body, lod 1 is the physics of a dead body - CryBonePhysics m_PhysInfo[2]; - float m_fMass; - - Matrix34 m_DefaultW2B; //intitalpose matrix World2Bone - Matrix34 m_DefaultB2W; //intitalpose matrix Bone2World - - enum - { - kBoneNameMaxSize = 256, - }; - char m_arrBoneName[CryBoneDescData::kBoneNameMaxSize]; - - int m_nLimbId; // set by model state class - - // this bone parent is this[m_nOffsetParent], 0 if the bone is root. Normally this is <= 0 - int m_nOffsetParent; - - // The whole hierarchy of bones is kept in one big array that belongs to the ModelState - // Each bone that has children has its own range of bone objects in that array, - // and this points to the beginning of that range and defines the number of bones. - unsigned m_numChildren; - // the beginning of the subarray of children is at this[m_nOffsetChildren] - // this is 0 if there are no children - int m_nOffsetChildren; -}; - -struct CryBoneDescData_Comp -{ - unsigned int m_nControllerID; // unique id of bone (generated from bone name) - - // [Sergiy] physics info for different lods - // lod 0 is the physics of alive body, lod 1 is the physics of a dead body - CryBonePhysics_Comp m_PhysInfo[2]; - float m_fMass; - - Matrix34 m_DefaultW2B; //intitalpose matrix World2Bone - Matrix34 m_DefaultB2W; //intitalpose matrix Bone2World - - char m_arrBoneName[256]; - - int m_nLimbId; // set by model state class - - // this bone parent is this[m_nOffsetParent], 0 if the bone is root. Normally this is <= 0 - int m_nOffsetParent; - - // The whole hierarchy of bones is kept in one big array that belongs to the ModelState - // Each bone that has children has its own range of bone objects in that array, - // and this points to the beginning of that range and defines the number of bones. - unsigned m_numChildren; - // the beginning of the subarray of children is at this[m_nOffsetChildren] - // this is 0 if there are no children - int m_nOffsetChildren; - - AUTO_STRUCT_INFO -}; - -inline void CopyBoneDescData(CryBoneDescData_Comp& left, const CryBoneDescData& right) -{ - left.m_nControllerID = right.m_nControllerID; - - CopyPhysInfo(left.m_PhysInfo[0], right.m_PhysInfo[0]); - CopyPhysInfo(left.m_PhysInfo[1], right.m_PhysInfo[1]); - - left.m_fMass = right.m_fMass; - left.m_DefaultW2B = right.m_DefaultW2B; - left.m_DefaultB2W = right.m_DefaultB2W; - memcpy(left.m_arrBoneName, right.m_arrBoneName, sizeof(left.m_arrBoneName)); - left.m_nLimbId = right.m_nLimbId; - left.m_nOffsetParent = right.m_nOffsetParent; - left.m_numChildren = right.m_numChildren; - left.m_nOffsetChildren = right.m_nOffsetChildren; -} - -struct BONE_ENTITY -{ - int BoneID; - int ParentID; - int nChildren; - - // Id of controller (CRC32 From name of bone). - unsigned int ControllerID; - - char prop[32]; - CryBonePhysics_Comp phys; - - AUTO_STRUCT_INFO -}; - -struct KEY_HEADER -{ - int KeyTime; //in ticks - AUTO_STRUCT_INFO -}; - -struct RANGE_ENTITY -{ - char name[32]; - int start; - int end; - AUTO_STRUCT_INFO -}; - -//======================================== -//Timing Chunk Header -//======================================== -struct TIMING_CHUNK_DESC_0918 -{ - enum - { - VERSION = 0x0918 - }; - - f32 m_SecsPerTick; // seconds/ticks - int32 m_TicksPerFrame; // ticks/Frame - - RANGE_ENTITY global_range; // covers all of the time ranges - int qqqqnSubRanges; - - AUTO_STRUCT_INFO -}; - - -struct SPEED_CHUNK_DESC_2 -{ - enum - { - VERSION = 0x0922 - }; - - float Speed; - float Distance; - float Slope; - uint32 AnimFlags; - f32 MoveDir[3]; - QuatT StartPosition; - AUTO_STRUCT_INFO -}; - - -struct MotionParams905 -{ - uint32 m_nAssetFlags; - uint32 m_nCompression; - - int32 m_nTicksPerFrame; - f32 m_fSecsPerTick; - int32 m_nStart; - int32 m_nEnd; - - f32 m_fMoveSpeed; - f32 m_fTurnSpeed; - f32 m_fAssetTurn; - f32 m_fDistance; - f32 m_fSlope; - - QuatT m_StartLocation; - QuatT m_EndLocation; - - f32 m_LHeelStart, m_LHeelEnd; - f32 m_LToe0Start, m_LToe0End; - f32 m_RHeelStart, m_RHeelEnd; - f32 m_RToe0Start, m_RToe0End; - - MotionParams905() - { - m_nAssetFlags = 0; - m_nCompression = -1; - m_nTicksPerFrame = 0; - m_fSecsPerTick = 0; - m_nStart = 0; - m_nEnd = 0; - - m_fMoveSpeed = -1; - m_fTurnSpeed = -1; - m_fAssetTurn = -1; - m_fDistance = -1; - m_fSlope = -1; - - m_LHeelStart = -1; - m_LHeelEnd = -1; - m_LToe0Start = -1; - m_LToe0End = -1; - m_RHeelStart = -1; - m_RHeelEnd = -1; - m_RToe0Start = -1; - m_RToe0End = -1; - - m_StartLocation.SetIdentity(); - m_EndLocation.SetIdentity(); - } -}; - - -struct CHUNK_MOTION_PARAMETERS -{ - enum - { - VERSION = 0x0925 - }; - - MotionParams905 mp; -}; - - - -struct CHUNK_GAHCAF_INFO -{ - enum - { - VERSION = 0x0971 - }; - enum - { - FILEPATH_SIZE = 256 - }; - - uint32 m_Flags; - char m_FilePath[FILEPATH_SIZE]; - uint32 m_FilePathCRC32; - uint32 m_FilePathDBACRC32; - - f32 m_LHeelStart, m_LHeelEnd; - f32 m_LToe0Start, m_LToe0End; - f32 m_RHeelStart, m_RHeelEnd; - f32 m_RToe0Start, m_RToe0End; - - f32 m_fStartSec; //asset-feature: Start time in seconds. - f32 m_fEndSec; //asset-feature: End time in seconds. - f32 m_fTotalDuration; //asset-feature: asset-feature: total duration in seconds. - uint32 m_nControllers; - - //locator information - QuatT m_StartLocation; - QuatT m_LastLocatorKey; - Vec3 m_vVelocity; //asset-feature: the velocity vector for this asset - f32 m_fDistance; //asset-feature: the absolute distance this objects is moving - f32 m_fSpeed; //asset-feature: speed (meters in second) - f32 m_fSlope; //asset-feature: uphill-downhill measured in degrees - f32 m_fTurnSpeed; //asset-feature: turning speed per second - f32 m_fAssetTurn; //asset-feature: radiant between first and last frame -}; - - - - -struct CHUNK_GAHAIM_INFO -{ - struct VirtualExampleInit2 - { - Vec2 polar; - uint8 i0, i1, i2, i3; - f32 w0, w1, w2, w3; - }; - struct VirtualExample - { - uint8 i0, i1, i2, i3; - int16 v0, v1, v2, v3; - }; - - enum - { - VERSION = 0x0970 - }; - enum - { - XGRID = 17 - }; - enum - { - YGRID = 9 - }; - enum - { - FILEPATH_SIZE = 256 - }; - - uint32 m_Flags; - char m_FilePath[FILEPATH_SIZE]; - uint32 m_FilePathCRC32; - - f32 m_fStartSec; //asset-feature: Start time in seconds. - f32 m_fEndSec; //asset-feature: End time in seconds. - f32 m_fTotalDuration; //asset-feature: asset-feature: total duration in seconds. - - uint32 m_AnimTokenCRC32; - - uint64 m_nExist; - Quat m_MiddleAimPoseRot; - Quat m_MiddleAimPose; - VirtualExample m_PolarGrid[XGRID * YGRID]; - uint32 m_numAimPoses; -}; - - -//======================================== -//Material Chunk Header -//======================================== - -////////////////////////////////////////////////////////////////////////// -#define MTL_NAME_CHUNK_DESC_0800_MAX_SUB_MATERIALS (32) -struct MTL_NAME_CHUNK_DESC_0800 -{ - enum - { - VERSION = 0x0800 - }; - enum EFlags - { - FLAG_MULTI_MATERIAL = 0x0001, // Have sub materials info. - FLAG_SUB_MATERIAL = 0x0002, // This is sub material. - FLAG_SH_COEFFS = 0x0004, // This material should get spherical harmonics coefficients computed. - FLAG_SH_2SIDED = 0x0008, // This material will be used as 2 sided in the sh precomputation - FLAG_SH_AMBIENT = 0x0010, // This material will get an ambient sh term(to not shadow it entirely) - }; - - int nFlags; // see EFlags. - int nFlags2; - char name[128]; //material/shader name - int nPhysicalizeType; - int nSubMaterials; - int nSubMatChunkId[MTL_NAME_CHUNK_DESC_0800_MAX_SUB_MATERIALS]; - int nAdvancedDataChunkId; - float sh_opacity; - int reserve[32]; - - AUTO_STRUCT_INFO -}; - -struct MTL_NAME_CHUNK_DESC_0802 -{ - enum - { - VERSION = 0x0802 - }; - - char name[128]; //material/shader name - int nSubMaterials; - - // Data continues from here. - // 1) if nSubMaterials is 0, this is a single-material: we store physicalization type of the material (int32). - // 2) if nSubMaterials is not 0, this is a multi-material: we store nSubMaterials physicalization types (int32 - // value for each sub-material). After the physicalization types we store chain of ASCIIZ names of sub-materials. - - AUTO_STRUCT_INFO -}; - -//======================================== -//Mesh Chunk Header -//======================================== - -struct MESH_CHUNK_DESC_0745 -{ - // Versions 0x0744 and 0x0745 are *exactly* the same. - // Version number was increased from 0x0744 to 0x0745 just because - // it was the only way to inform *old* (existing) executables that - // NODE_CHUNK_DESC(!) chunk format was changed and cannot be read - // by them (old CLoaderCGF::LoadNodeChunk() didn't check - // NODE_CHUNK_DESC's version number). - enum - { - VERSION = 0x0745 - }; - enum - { - COMPATIBLE_OLD_VERSION = 0x0744 - }; - - enum EFlags1 - { - FLAG1_BONE_INFO = 0x01, - }; - enum EFlags2 - { - FLAG2_HAS_VERTEX_COLOR = 0x01, - FLAG2_HAS_VERTEX_ALPHA = 0x02, - FLAG2_HAS_TOPOLOGY_IDS = 0x04, - }; - unsigned char flags1; - unsigned char flags2; - int nVerts; - int nTVerts; // # of texture vertices (0 or nVerts) - int nFaces; - int VertAnimID; // id of the related vertAnim chunk if present. otherwise it is -1 - - AUTO_STRUCT_INFO -}; - -// Compiled Mesh chunk. -struct MESH_CHUNK_DESC_0801 -{ - // Versions 0x0800 and 0x0801 are *exactly* the same. - // Version number was increased from 0x0800 to 0x0801 just because - // it was the only way to inform *old* (existing) executables that - // NODE_CHUNK_DESC(!) chunk format was changed and cannot be read - // by them (old CLoaderCGF::LoadNodeChunk() didn't check - // NODE_CHUNK_DESC's version number). - enum - { - VERSION = 0x0801 - }; - enum - { - COMPATIBLE_OLD_VERSION = 0x0800 - }; - - enum EFlags - { - MESH_IS_EMPTY = 0x0001, // Empty mesh (no streams are saved) - HAS_TEX_MAPPING_DENSITY = 0x0002, // texMappingDensity contains a valid value - HAS_EXTRA_WEIGHTS = 0x0004, // The weight stream will have weights for influences 5-8 - HAS_FACE_AREA = 0x0008, // geometricMeanFaceArea contains a valid value - }; - - int nFlags; // @see EFlags - int nFlags2; - - // Just for info. - int nVerts; // Number of vertices. - int nIndices; // Number of indices. - int nSubsets; // Number of mesh subsets. - - int nSubsetsChunkId; // Chunk id of subsets. (Must be ChunkType_MeshSubsets) - int nVertAnimID; // id of the related vertAnim chunk if present. otherwise it is -1 - - // ChunkIDs of data streams (Must be ChunkType_DataStream). - int GetStreamChunkID(ECgfStreamType streamType, [[maybe_unused]] int streamIndex) const - { - // Ignore streamIndex since all chunks with version 0x0801 have only one stream per type - return nStreamChunkID[streamType]; - } - int nStreamChunkID[ECgfStreamType::CGF_STREAM_NUM_TYPES]; // Index is one of ECgfStreamType values. - - // Chunk IDs of physical mesh data. (Must be ChunkType_MeshPhysicsData) - int nPhysicsDataChunkId[4]; - - // Bounding box of the mesh. - Vec3 bboxMin; - Vec3 bboxMax; - - float texMappingDensity; - float geometricMeanFaceArea; - int reserved[31]; - AUTO_STRUCT_INFO -}; - -struct MESH_CHUNK_DESC_0802 -{ - // Version 0x0802 adds an additional dimention to the nStreamChunkID array to allow for multiple streams of the same type - enum - { - VERSION = 0x0802 - }; - enum - { - COMPATIBLE_OLD_VERSION = 0x0802 - }; - - enum EFlags - { - MESH_IS_EMPTY = 0x0001, // Empty mesh (no streams are saved) - HAS_TEX_MAPPING_DENSITY = 0x0002, // texMappingDensity contains a valid value - HAS_EXTRA_WEIGHTS = 0x0004, // The weight stream will have weights for influences 5-8 - HAS_FACE_AREA = 0x0008, // geometricMeanFaceArea contains a valid value - }; - - int nFlags; // @see EFlags - int nFlags2; - - // Just for info. - int nVerts; // Number of vertices. - int nIndices; // Number of indices. - int nSubsets; // Number of mesh subsets. - - int nSubsetsChunkId; // Chunk id of subsets. (Must be ChunkType_MeshSubsets) - int nVertAnimID; // id of the related vertAnim chunk if present. otherwise it is -1 - - // ChunkIDs of data streams (Must be ChunkType_DataStream). - int GetStreamChunkID(ECgfStreamType streamType, int streamIndex) const - { - return nStreamChunkID[streamType][streamIndex]; - } - int nStreamChunkID[ECgfStreamType::CGF_STREAM_NUM_TYPES][8]; // [ECgfStreamType value][streamIndex] e.g. [CGF_STREAM_TEXCOORDS][1] to get UV set 1 - - // Chunk IDs of physical mesh data. (Must be ChunkType_MeshPhysicsData) - int nPhysicsDataChunkId[4]; - - // Bounding box of the mesh. - Vec3 bboxMin; - Vec3 bboxMax; - - float texMappingDensity; - float geometricMeanFaceArea; - int reserved[31]; - AUTO_STRUCT_INFO -}; - - -////////////////////////////////////////////////////////////////////////// -// Stream chunk contains data about a mesh data stream (positions, normals, etc...) -////////////////////////////////////////////////////////////////////////// -struct STREAM_DATA_CHUNK_DESC_0800 -{ - enum - { - VERSION = 0x0800 - }; - - enum EFlags { }; // Not implemented. - - int nFlags; - int nStreamType; // Stream type one of ECgfStreamType. - int nCount; // Number of elements. - int nElementSize; // Element Size. - int reserved[2]; - - // Data starts here at the end of the chunk.. - //char streamData[nCount*nElementSize]; - - AUTO_STRUCT_INFO -}; - -struct STREAM_DATA_CHUNK_DESC_0801 -{ - enum - { - VERSION = 0x0801 - }; - - enum EFlags { }; // Not implemented. - - int nFlags; - int nStreamType; // Stream type one of ECgfStreamType. - int nStreamIndex; // To handle multiple streams of the same type - int nCount; // Number of elements. - int nElementSize; // Element Size. - int reserved[2]; - - // Data starts here at the end of the chunk.. - //char streamData[nCount*nElementSize]; - - AUTO_STRUCT_INFO -}; - -////////////////////////////////////////////////////////////////////////// -// Contains array of mesh subsets. -// Each subset holds an info about material id, indices ranges etc... -////////////////////////////////////////////////////////////////////////// -struct MESH_SUBSETS_CHUNK_DESC_0800 -{ - enum - { - VERSION = 0x0800 - }; - - enum EFlags - { - SH_HAS_DECOMPR_MAT = 0x0001, // obsolete - BONEINDICES = 0x0002, - HAS_SUBSET_TEXEL_DENSITY = 0x0004, - }; - - int nFlags; - int nCount; // Number of elements. - int reserved[2]; - - struct MeshSubset - { - int nFirstIndexId; - int nNumIndices; - int nFirstVertId; - int nNumVerts; - int nMatID; // Material sub-object Id. - float fRadius; - Vec3 vCenter; - - AUTO_STRUCT_INFO - }; - - struct MeshBoneIDs - { - uint32 numBoneIDs; - uint16 arrBoneIDs[0x80]; - - AUTO_STRUCT_INFO - }; - - struct MeshSubsetTexelDensity - { - float texelDensity; - - AUTO_STRUCT_INFO - }; - - // Data starts here at the end of the chunk. - //Subset streamData[nCount]; - - MESH_SUBSETS_CHUNK_DESC_0800() - : nFlags(0) - , nCount(0) - { - } - - AUTO_STRUCT_INFO -}; - -////////////////////////////////////////////////////////////////////////// -// Contain array of mesh subsets. -// Each subset holds an info about material id, indices ranges etc... -////////////////////////////////////////////////////////////////////////// -struct MESH_PHYSICS_DATA_CHUNK_DESC_0800 -{ - enum - { - VERSION = 0x0800 - }; - - int nDataSize; // Size of physical data at the end of the chunk. - int nFlags; - int nTetrahedraDataSize; - int nTetrahedraChunkId; // Chunk of physics Tetrahedra data. - int reserved[2]; - - // Data starts here at the end of the chunk. - //char physicsData[nDataSize]; - //char tetrahedraData[nTetrahedraDataSize]; - - AUTO_STRUCT_INFO -}; - - -struct VERTANIM_CHUNK_DESC_0744 -{ - enum - { - VERSION = 0x0744 - }; - - int GeomID; // ID of the related mesh chunk - int nKeys; // # of keys - int nVerts; // # of vertices this object has - int nFaces; // # of faces this object has (for double check purpose) - - AUTO_STRUCT_INFO -}; - -typedef VERTANIM_CHUNK_DESC_0744 VERTANIM_CHUNK_DESC; -#define VERTANIM_CHUNK_DESC_VERSION VERTANIM_CHUNK_DESC_0744::VERSION - -//======================================== -//Bone Anim Chunk Header -//======================================== - -struct BONEANIM_CHUNK_DESC_0290 -{ - enum - { - VERSION = 0x0290 - }; - - int nBones; - - AUTO_STRUCT_INFO -}; - -//======================================== -//Bonelist Chunk Header -//======================================== - -// this structure describes the bone names -// it's followed by numEntities packed \0-terminated strings, the list terminated by double-\0 -struct BONENAMELIST_CHUNK_DESC_0745 -{ - enum - { - VERSION = 0x0745 - }; - - int numEntities; - AUTO_STRUCT_INFO -}; - - -struct COMPILED_BONE_CHUNK_DESC_0800 -{ - enum - { - VERSION = 0x0800 - }; - - char reserved[32]; - AUTO_STRUCT_INFO -}; - -struct COMPILED_PHYSICALBONE_CHUNK_DESC_0800 -{ - enum - { - VERSION = 0x0800 - }; - - char reserved[32]; - AUTO_STRUCT_INFO -}; - -struct COMPILED_PHYSICALPROXY_CHUNK_DESC_0800 -{ - enum - { - VERSION = 0x0800 - }; - - uint32 numPhysicalProxies; - AUTO_STRUCT_INFO -}; - -struct COMPILED_MORPHTARGETS_CHUNK_DESC_0800 -{ - enum - { - VERSION = 0x0800, VERSION1 = 0x801 - }; - - uint32 numMorphTargets; - AUTO_STRUCT_INFO -}; - - -struct COMPILED_INTFACES_CHUNK_DESC_0800 -{ - enum - { - VERSION = 0x0800 - }; - - AUTO_STRUCT_INFO -}; - -struct COMPILED_INTSKINVERTICES_CHUNK_DESC_0800 -{ - enum - { - VERSION = 0x0800 - }; - - char reserved[32]; - AUTO_STRUCT_INFO -}; - -struct COMPILED_EXT2INTMAP_CHUNK_DESC_0800 -{ - enum - { - VERSION = 0x0800 - }; - - AUTO_STRUCT_INFO -}; - -struct COMPILED_BONEBOXES_CHUNK_DESC_0800 -{ - enum - { - VERSION = 0x0800, VERSION1 = 0x801 - }; - - AUTO_STRUCT_INFO -}; - -// Keyframe and Timing Primitives __________________________________________________________________________________________________________________ -struct BaseKey -{ - int time; - AUTO_STRUCT_INFO -}; - -struct BaseTCB -{ - float t, c, b; - float ein, eout; - AUTO_STRUCT_INFO -}; - -struct BaseKey1 - : BaseKey -{ - float val; - AUTO_STRUCT_INFO -}; -struct BaseKey3 - : BaseKey -{ - Vec3 val; - AUTO_STRUCT_INFO -}; -struct BaseKeyQ - : BaseKey -{ - CryQuat val; - AUTO_STRUCT_INFO -}; - -struct CryLin1Key - : BaseKey1 -{ - AUTO_STRUCT_INFO -}; -struct CryLin3Key - : BaseKey3 -{ - AUTO_STRUCT_INFO -}; -struct CryLinQKey - : BaseKeyQ -{ - AUTO_STRUCT_INFO -}; -struct CryTCB1Key - : BaseKey1 - , BaseTCB -{ - AUTO_STRUCT_INFO -}; -struct CryTCB3Key - : BaseKey3 - , BaseTCB -{ - AUTO_STRUCT_INFO -}; -struct CryTCBQKey - : BaseKeyQ - , BaseTCB -{ - AUTO_STRUCT_INFO -}; -struct CryBez1Key - : BaseKey1 -{ - float intan, outtan; - AUTO_STRUCT_INFO -}; -struct CryBez3Key - : BaseKey3 -{ - Vec3 intan, outtan; - AUTO_STRUCT_INFO -}; -struct CryBezQKey - : BaseKeyQ -{ - AUTO_STRUCT_INFO -}; - -struct CryKeyPQLog -{ - int nTime; - Vec3 vPos; - Vec3 vRotLog; // logarithm of the rotation - - // resets to initial position/rotation/time - void reset () - { - nTime = 0; - vPos.x = vPos.y = vPos.z = 0; - vRotLog.x = vRotLog.y = vRotLog.z = 0; - } - - AUTO_STRUCT_INFO -}; - -//======================================== -//Controller Chunk Header -//======================================== -enum CtrlTypes -{ - CTRL_NONE, - CTRL_CRYBONE, - CTRL_LINEER1, CTRL_LINEER3, CTRL_LINEERQ, - CTRL_BEZIER1, CTRL_BEZIER3, CTRL_BEZIERQ, - CTRL_TCB1, CTRL_TCB3, CTRL_TCBQ, - CTRL_BSPLINE_2O, // 2-byte fixed values, open - CTRL_BSPLINE_1O, // 1-byte fixed values, open - CTRL_BSPLINE_2C, // 2-byte fixed values, closed - CTRL_BSPLINE_1C, // 1-byte fixed values, closed - CTRL_CONST // constant position&rotation -}; - -enum CtrlFlags -{ - CTRL_ORT_CYCLE = 0x01, - CTRL_ORT_LOOP = 0x02 -}; - -// Used to store TCB-controllers in .anm files -struct CONTROLLER_CHUNK_DESC_0826 -{ - enum - { - VERSION = 0x0826 - }; - - CtrlTypes type; //one ot the CtrlTypes values - int nKeys; // # of keys this controller has; toatl # of knots (positional and orientational) in the case of B-Spline - - //unsigned short nSubCtrl; // # of sub controllers; not used now/reserved - unsigned int nFlags; // Flags of controller. - //int nSubCtrl; // # of sub controllers; not used now/reserved - - unsigned nControllerId; // unique generated in exporter id based on crc32 of bone name - - AUTO_STRUCT_INFO -}; - -// Format used to store uncompressed sampled animation exported from DCC into .i_caf files (earlier .caf) -struct CONTROLLER_CHUNK_DESC_0827 -{ - enum - { - VERSION = 0x0827 - }; - unsigned numKeys; - unsigned nControllerId; - - AUTO_STRUCT_INFO -}; - -// Unused format (was it introduced to fix missing header in 827?) -struct CONTROLLER_CHUNK_DESC_0828 -{ - enum - { - VERSION = 0x0828 - }; -}; - -struct CONTROLLER_CHUNK_DESC_0829 -{ - enum - { - VERSION = 0x0829 - }; - - enum - { - eKeyTimeRotation = 0, eKeyTimePosition = 1, eKeyTimeScale = 2 - }; - - unsigned int nControllerId; - - uint16 numRotationKeys; - uint16 numPositionKeys; - uint8 RotationFormat; - uint8 RotationTimeFormat; - uint8 PositionFormat; - uint8 PositionKeysInfo; - uint8 PositionTimeFormat; - uint8 TracksAligned; - - AUTO_STRUCT_INFO -}; - -// Added new controller flags field, correspond to v827 and v829 respectively -struct CONTROLLER_CHUNK_DESC_0830 -{ - enum - { - VERSION = 0x830 - }; - - CONTROLLER_CHUNK_DESC_0830(){} - - CONTROLLER_CHUNK_DESC_0830(const CONTROLLER_CHUNK_DESC_0827* oldChunk) - : numKeys(oldChunk->numKeys) - , nControllerId(oldChunk->nControllerId) - , nFlags(0) - {} - - unsigned numKeys; - unsigned nControllerId; - unsigned nFlags; - - AUTO_STRUCT_INFO -}; - -struct CONTROLLER_CHUNK_DESC_0831 -{ - enum - { - VERSION = 0x831 - }; - - CONTROLLER_CHUNK_DESC_0831(){} - - CONTROLLER_CHUNK_DESC_0831(const CONTROLLER_CHUNK_DESC_0829* oldChunk) - : nControllerId(oldChunk->nControllerId) - , nFlags(0) - , numPositionKeys(oldChunk->numPositionKeys) - , numRotationKeys(oldChunk->numRotationKeys) - , RotationFormat(oldChunk->RotationFormat) - , RotationTimeFormat(oldChunk->RotationTimeFormat) - , PositionFormat(oldChunk->PositionFormat) - , PositionKeysInfo(oldChunk->PositionKeysInfo) - , PositionTimeFormat(oldChunk->PositionTimeFormat) - , TracksAligned(oldChunk->TracksAligned) - {} - - enum - { - eKeyTimeRotation = 0, eKeyTimePosition = 1, eKeyTimeScale = 2 - }; - - unsigned int nControllerId; - unsigned int nFlags; - - uint16 numRotationKeys; - uint16 numPositionKeys; - uint8 RotationFormat; - uint8 RotationTimeFormat; - uint8 PositionFormat; - uint8 PositionKeysInfo; - uint8 PositionTimeFormat; - uint8 TracksAligned; - - AUTO_STRUCT_INFO -}; - -struct CONTROLLER_CHUNK_DESC_0905 -{ - enum - { - VERSION = 0x0905 - }; - - uint32 numKeyPos; - uint32 numKeyRot; - uint32 numKeyTime; - uint32 numAnims; - AUTO_STRUCT_INFO -}; - -//======================================== -//Node Chunk Header -//======================================== -struct NODE_CHUNK_DESC_0824 -{ - // Versions 0x0823 and 0x0824 have exactly same layout. - // The only difference between 0x0823 and 0x0824 is that some members - // are now named _obsoleteXXX_ and are not filled/used in 0x0824. - enum - { - VERSION = 0x0824 - }; - enum - { - COMPATIBLE_OLD_VERSION = 0x0823 - }; - - char name[64]; - - int ObjectID; // ID of this node's object chunk (if present) - int ParentID; // chunk ID of the parent Node's chunk - int nChildren; // # of children Nodes - int MatID; // Material chunk No - - uint8 _obsoleteA_[4]; // uint8 IsGroupHead; uint8 IsGroupMember; uint8 _padding_[2]. not used anymore. - - float tm[4][4]; // transformation matrix - - float _obsoleteB_[3]; // position component of the matrix, stored as Vec3. not used anymore. - float _obsoleteC_[4]; // rotation component of the matrix, stored as CryQuat. not used anymore. - float _obsoleteD_[3]; // scale component of the matrix, stored as Vec3. not used anymore. - - int pos_cont_id; // position controller chunk id - int rot_cont_id; // rotation controller chunk id - int scl_cont_id; // scale controller chunk id - - int PropStrLen; // length of the property string - - AUTO_STRUCT_INFO -}; - -//======================================== -//Helper Chunk Header -//======================================== -enum HelperTypes -{ - HP_POINT = 0, - HP_DUMMY = 1, - HP_XREF = 2, - HP_CAMERA = 3, - HP_GEOMETRY = 4 -}; - -struct HELPER_CHUNK_DESC_0744 -{ - enum - { - VERSION = 0x0744 - }; - - HelperTypes type; // one of the HelperTypes values - Vec3 size; // size in local x,y,z axises (for dummy only) - - AUTO_STRUCT_INFO -}; - -typedef HELPER_CHUNK_DESC_0744 HELPER_CHUNK_DESC; -#define HELPER_CHUNK_DESC_VERSION HELPER_CHUNK_DESC::VERSION - - -// ChunkType_MeshMorphTarget - morph target of a mesh chunk -// This chunk contains only the information about the vertices that are changed in the mesh -// This chunk is followed by an array of numMorphVertices structures SMeshMorphTargetVertex, -// immediately followed by the name (null-terminated, variable-length string) of the morph target. -// The string is after the array because of future alignment considerations; it may be padded with 0s. -struct MESHMORPHTARGET_CHUNK_DESC_0001 -{ - enum - { - VERSION = 0x0001 - }; - uint32 nChunkIdMesh; // the chunk id of the mesh chunk (ChunkType_Mesh) for which this morph target is - uint32 numMorphVertices; // number of MORPHED vertices - - AUTO_STRUCT_INFO -}; - - -// an array of these structures follows the MESHMORPHTARGET_CHUNK_DESC_0001 -// there are numMorphVertices of them -struct SMeshMorphTargetVertex -{ - uint32 nVertexId; // vertex index in the original (mesh) array of vertices - Vec3 ptVertex; // the target point of the morph target - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const{} - AUTO_STRUCT_INFO -}; - -struct SMeshMorphTargetHeader -{ - uint32 MeshID; - uint32 NameLength; //size of the name string - uint32 numIntVertices; //type SMeshMorphTargetVertex - uint32 numExtVertices; //type SMeshMorphTargetVertex - - AUTO_STRUCT_INFO -}; - -struct SMeshPhysicalProxyHeader -{ - uint32 ChunkID; - uint32 numPoints; - uint32 numIndices; - uint32 numMaterials; - - AUTO_STRUCT_INFO -}; - -// -// ChunkType_BoneInitialPos - describes the initial position (4x3 matrix) of each bone; just an array of 4x3 matrices -// This structure is followed by -struct BONEINITIALPOS_CHUNK_DESC_0001 -{ - enum - { - VERSION = 0x0001 - }; - // the chunk id of the mesh chunk (ChunkType_Mesh) with bone info for which these bone initial positions are applicable. - // there might be some unused bones here as well. There must be the same number of bones as in the other chunks - they're placed - // in BoneId order. - unsigned nChunkIdMesh; - // this is the number of bone initial pose matrices here - unsigned numBones; - - AUTO_STRUCT_INFO -}; - -// an array of these matrices follows the BONEINITIALPOS_CHUNK_DESC_0001 header -// there are numBones of them -// TO BE REPLACED WITH Matrix43 -struct SBoneInitPosMatrix -{ - float mx[4][3]; - float* operator [] (int i) {return mx[i]; } - const float* operator [] (int i) const {return mx[i]; } - const Vec3& getOrt (int nOrt) const {return *(const Vec3*)(mx[nOrt]); } - - AUTO_STRUCT_INFO -}; - -////////////////////////////////////////////////////////////////////////// -// Custom Attributes chunk description. -////////////////////////////////////////////////////////////////////////// -struct EXPORT_FLAGS_CHUNK_DESC -{ - enum - { - VERSION = 0x0001 - }; - enum EFlags - { - MERGE_ALL_NODES = 0x0001, - HAVE_AUTO_LODS = 0x0002, - USE_CUSTOM_NORMALS = 0x0004, - WANT_F32_VERTICES = 0x0008, - EIGHT_WEIGHTS_PER_VERTEX = 0x0010, - //START: Prevent reprocessing skinning data for skinned CGF - SKINNED_CGF = 0x0020, - //END: Prevent reprocessing skinning data for skinned CGF - }; - enum ESrcFlags - { - FROM_MAX_EXPORTER = 0x0000, - FROM_COLLADA_XSI = 0x1001, - FROM_COLLADA_MAX = 0x1002, - FROM_COLLADA_MAYA = 0x1003, - }; - - unsigned int flags; // @see EFlags - unsigned int rc_version[4]; // Resource compiler version. - char rc_version_string[16]; // Version as a string. - unsigned int assetAuthorTool; - unsigned int authorToolVersion; - unsigned int reserved[30]; - - AUTO_STRUCT_INFO -}; - -struct BREAKABLE_PHYSICS_CHUNK_DESC -{ - enum - { - VERSION = 0x0001 - }; - - unsigned int granularity; - int nMode; - int nRetVtx; - int nRetTets; - int nReserved[10]; - - AUTO_STRUCT_INFO -}; - -struct FOLIAGE_INFO_CHUNK_DESC -{ - enum - { - //START: Add Skinned Geometry (.CGF) export type (for touch bending vegetation) - VERSION = 0x0001, - VERSION2 = 0x0002 - //END: Add Skinned Geometry (.CGF) export type (for touch bending vegetation) - }; - - int nSpines; - int nSpineVtx; - int nSkinnedVtx; - int nBoneIds; - - AUTO_STRUCT_INFO -}; - -struct FOLIAGE_SPINE_SUB_CHUNK -{ - unsigned char nVtx; - char _paddingA_[3]; - float len; - Vec3 navg; - unsigned char iAttachSpine; - unsigned char iAttachSeg; - char _paddingB_[2]; - - AUTO_STRUCT_INFO -}; - -#endif // CRYINCLUDE_CRYCOMMON_CRYHEADERS_H diff --git a/Code/CryEngine/CryCommon/CryHeaders_info.cpp b/Code/CryEngine/CryCommon/CryHeaders_info.cpp deleted file mode 100644 index 4aefe61ee1..0000000000 --- a/Code/CryEngine/CryCommon/CryHeaders_info.cpp +++ /dev/null @@ -1,485 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "TypeInfo_impl.h" -#include "CryHeaders.h" - -STRUCT_INFO_BEGIN(CryVertex) -STRUCT_VAR_INFO(p, TYPE_INFO(Vec3)) -STRUCT_VAR_INFO(n, TYPE_INFO(Vec3)) -STRUCT_INFO_END(CryVertex) - -STRUCT_INFO_BEGIN(CryFace) -STRUCT_VAR_INFO(v0, TYPE_INFO(int)) -STRUCT_VAR_INFO(v1, TYPE_INFO(int)) -STRUCT_VAR_INFO(v2, TYPE_INFO(int)) -STRUCT_VAR_INFO(MatID, TYPE_INFO(int)) -STRUCT_INFO_END(CryFace) - -STRUCT_INFO_BEGIN(CryUV) -STRUCT_VAR_INFO(u, TYPE_INFO(float)) -STRUCT_VAR_INFO(v, TYPE_INFO(float)) -STRUCT_INFO_END(CryUV) - -STRUCT_INFO_BEGIN(CrySkinVtx) -STRUCT_VAR_INFO(bVolumetric, TYPE_INFO(int)) -STRUCT_VAR_INFO(idx, TYPE_INFO_ARRAY(4, TYPE_INFO(int))) -STRUCT_VAR_INFO(w, TYPE_INFO_ARRAY(4, TYPE_INFO(float))) -STRUCT_VAR_INFO(M, TYPE_INFO(Matrix33)) -STRUCT_INFO_END(CrySkinVtx) - -STRUCT_INFO_BEGIN(CryLink) -STRUCT_VAR_INFO(BoneID, TYPE_INFO(int)) -STRUCT_VAR_INFO(offset, TYPE_INFO(Vec3)) -STRUCT_VAR_INFO(Blending, TYPE_INFO(float)) -STRUCT_INFO_END(CryLink) - -STRUCT_INFO_BEGIN(CryIRGB) -STRUCT_VAR_INFO(r, TYPE_INFO(unsigned char)) -STRUCT_VAR_INFO(g, TYPE_INFO(unsigned char)) -STRUCT_VAR_INFO(b, TYPE_INFO(unsigned char)) -STRUCT_INFO_END(CryIRGB) - -STRUCT_INFO_BEGIN(CryBonePhysics_Comp) -STRUCT_VAR_INFO(nPhysGeom, TYPE_INFO(int)) -STRUCT_VAR_INFO(flags, TYPE_INFO(int)) -STRUCT_VAR_INFO(min, TYPE_ARRAY(3, TYPE_INFO(float))) -STRUCT_VAR_INFO(max, TYPE_ARRAY(3, TYPE_INFO(float))) -STRUCT_VAR_INFO(spring_angle, TYPE_ARRAY(3, TYPE_INFO(float))) -STRUCT_VAR_INFO(spring_tension, TYPE_ARRAY(3, TYPE_INFO(float))) -STRUCT_VAR_INFO(damping, TYPE_ARRAY(3, TYPE_INFO(float))) -STRUCT_VAR_INFO(framemtx, TYPE_ARRAY(3, TYPE_ARRAY(3, TYPE_INFO(float)))) -STRUCT_INFO_END(CryBonePhysics_Comp) - -STRUCT_INFO_BEGIN(CryBoneDescData_Comp) -STRUCT_VAR_INFO(m_nControllerID, TYPE_INFO(unsigned int)) -STRUCT_VAR_INFO(m_PhysInfo, TYPE_ARRAY(2, TYPE_INFO(BONE_PHYSICS_COMP))) -STRUCT_VAR_INFO(m_fMass, TYPE_INFO(float)) -STRUCT_VAR_INFO(m_DefaultW2B, TYPE_INFO(Matrix34)) -STRUCT_VAR_INFO(m_DefaultB2W, TYPE_INFO(Matrix34)) -STRUCT_VAR_INFO(m_arrBoneName, TYPE_ARRAY(256, TYPE_INFO(char))) -STRUCT_VAR_INFO(m_nLimbId, TYPE_INFO(int)) -STRUCT_VAR_INFO(m_nOffsetParent, TYPE_INFO(int)) -STRUCT_VAR_INFO(m_numChildren, TYPE_INFO(unsigned int)) -STRUCT_VAR_INFO(m_nOffsetChildren, TYPE_INFO(int)) -STRUCT_INFO_END(CryBoneDescData_Comp) - -STRUCT_INFO_BEGIN(BONE_ENTITY) -STRUCT_VAR_INFO(BoneID, TYPE_INFO(int)) -STRUCT_VAR_INFO(ParentID, TYPE_INFO(int)) -STRUCT_VAR_INFO(nChildren, TYPE_INFO(int)) -STRUCT_VAR_INFO(ControllerID, TYPE_INFO(unsigned int)) -STRUCT_VAR_INFO(prop, TYPE_ARRAY(32, TYPE_INFO(char))) -STRUCT_VAR_INFO(phys, TYPE_INFO(BONE_PHYSICS_COMP)) -STRUCT_INFO_END(BONE_ENTITY) - -ENUM_INFO_BEGIN(ChunkTypes) -ENUM_ELEM_INFO(, ChunkType_ANY) -ENUM_ELEM_INFO(, ChunkType_Mesh) -ENUM_ELEM_INFO(, ChunkType_Helper) -ENUM_ELEM_INFO(, ChunkType_VertAnim) -ENUM_ELEM_INFO(, ChunkType_BoneAnim) -ENUM_ELEM_INFO(, ChunkType_GeomNameList) -ENUM_ELEM_INFO(, ChunkType_BoneNameList) -ENUM_ELEM_INFO(, ChunkType_MtlList) -ENUM_ELEM_INFO(, ChunkType_MRM) -ENUM_ELEM_INFO(, ChunkType_SceneProps) -ENUM_ELEM_INFO(, ChunkType_Light) -ENUM_ELEM_INFO(, ChunkType_PatchMesh) -ENUM_ELEM_INFO(, ChunkType_Node) -ENUM_ELEM_INFO(, ChunkType_Mtl) -ENUM_ELEM_INFO(, ChunkType_Controller) -ENUM_ELEM_INFO(, ChunkType_Timing) -ENUM_ELEM_INFO(, ChunkType_BoneMesh) -ENUM_ELEM_INFO(, ChunkType_BoneLightBinding) -ENUM_ELEM_INFO(, ChunkType_MeshMorphTarget) -ENUM_ELEM_INFO(, ChunkType_BoneInitialPos) -ENUM_ELEM_INFO(, ChunkType_SourceInfo) -ENUM_ELEM_INFO(, ChunkType_MtlName) -ENUM_ELEM_INFO(, ChunkType_ExportFlags) -ENUM_ELEM_INFO(, ChunkType_DataStream) -ENUM_ELEM_INFO(, ChunkType_MeshSubsets) -ENUM_ELEM_INFO(, ChunkType_MeshPhysicsData) -ENUM_ELEM_INFO(, ChunkType_CompiledBones) -ENUM_ELEM_INFO(, ChunkType_CompiledPhysicalBones) -ENUM_ELEM_INFO(, ChunkType_CompiledMorphTargets) -ENUM_ELEM_INFO(, ChunkType_CompiledPhysicalProxies) -ENUM_ELEM_INFO(, ChunkType_CompiledIntFaces) -ENUM_ELEM_INFO(, ChunkType_CompiledIntSkinVertices) -ENUM_ELEM_INFO(, ChunkType_CompiledExt2IntMap) -ENUM_ELEM_INFO(, ChunkType_BreakablePhysics) -ENUM_ELEM_INFO(, ChunkType_FaceMap) -ENUM_ELEM_INFO(, ChunkType_MotionParameters) -ENUM_ELEM_INFO(, ChunkType_FootPlantInfo) -ENUM_ELEM_INFO(, ChunkType_BonesBoxes) -ENUM_ELEM_INFO(, ChunkType_FoliageInfo) -ENUM_INFO_END(ChunkTypes) - -STRUCT_INFO_BEGIN(RANGE_ENTITY) -STRUCT_VAR_INFO(name, TYPE_ARRAY(32, TYPE_INFO(char))) -STRUCT_VAR_INFO(start, TYPE_INFO(int)) -STRUCT_VAR_INFO(end, TYPE_INFO(int)) -STRUCT_INFO_END(RANGE_ENTITY) - -STRUCT_INFO_BEGIN(TIMING_CHUNK_DESC_0918) -STRUCT_VAR_INFO(m_SecsPerTick, TYPE_INFO(float)) -STRUCT_VAR_INFO(m_TicksPerFrame, TYPE_INFO(int)) -STRUCT_VAR_INFO(global_range, TYPE_INFO(RANGE_ENTITY)) -STRUCT_VAR_INFO(qqqqnSubRanges, TYPE_INFO(int)) -STRUCT_INFO_END(TIMING_CHUNK_DESC_0918) - - -STRUCT_INFO_BEGIN(SPEED_CHUNK_DESC_2) -STRUCT_VAR_INFO(Speed, TYPE_INFO(float)) -STRUCT_VAR_INFO(Distance, TYPE_INFO(float)) -STRUCT_VAR_INFO(Slope, TYPE_INFO(float)) -STRUCT_VAR_INFO(AnimFlags, TYPE_INFO(int)) -STRUCT_VAR_INFO(MoveDir, TYPE_ARRAY(3, TYPE_INFO(f32))) -STRUCT_VAR_INFO(StartPosition, TYPE_INFO(QuatT)) -STRUCT_INFO_END(SPEED_CHUNK_DESC_2) - -STRUCT_INFO_BEGIN(MTL_NAME_CHUNK_DESC_0800) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(int)) -STRUCT_VAR_INFO(nFlags2, TYPE_INFO(int)) -STRUCT_VAR_INFO(name, TYPE_ARRAY(128, TYPE_INFO(char))) -STRUCT_VAR_INFO(nPhysicalizeType, TYPE_INFO(int)) -STRUCT_VAR_INFO(nSubMaterials, TYPE_INFO(int)) -STRUCT_VAR_INFO(nSubMatChunkId, TYPE_ARRAY(MTL_NAME_CHUNK_DESC_0800_MAX_SUB_MATERIALS, TYPE_INFO(int))) -STRUCT_VAR_INFO(nAdvancedDataChunkId, TYPE_INFO(int)) -STRUCT_VAR_INFO(sh_opacity, TYPE_INFO(float)) -STRUCT_VAR_INFO(reserve, TYPE_ARRAY(32, TYPE_INFO(int))) -STRUCT_INFO_END(MTL_NAME_CHUNK_DESC_0800) - -STRUCT_INFO_BEGIN(MTL_NAME_CHUNK_DESC_0802) -STRUCT_VAR_INFO(name, TYPE_ARRAY(128, TYPE_INFO(char))) -STRUCT_VAR_INFO(nSubMaterials, TYPE_INFO(int)) -STRUCT_INFO_END(MTL_NAME_CHUNK_DESC_0802) - -STRUCT_INFO_BEGIN(MESH_CHUNK_DESC_0745) -STRUCT_VAR_INFO(flags1, TYPE_INFO(unsigned char)) -STRUCT_VAR_INFO(flags2, TYPE_INFO(unsigned char)) -STRUCT_VAR_INFO(nVerts, TYPE_INFO(int)) -STRUCT_VAR_INFO(nTVerts, TYPE_INFO(int)) -STRUCT_VAR_INFO(nFaces, TYPE_INFO(int)) -STRUCT_VAR_INFO(VertAnimID, TYPE_INFO(int)) -STRUCT_INFO_END(MESH_CHUNK_DESC_0745) - -STRUCT_INFO_BEGIN(MESH_CHUNK_DESC_0801) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(int)) -STRUCT_VAR_INFO(nFlags2, TYPE_INFO(int)) -STRUCT_VAR_INFO(nVerts, TYPE_INFO(int)) -STRUCT_VAR_INFO(nIndices, TYPE_INFO(int)) -STRUCT_VAR_INFO(nSubsets, TYPE_INFO(int)) -STRUCT_VAR_INFO(nSubsetsChunkId, TYPE_INFO(int)) -STRUCT_VAR_INFO(nVertAnimID, TYPE_INFO(int)) -STRUCT_VAR_INFO(nStreamChunkID, TYPE_ARRAY(16, TYPE_INFO(int))) -STRUCT_VAR_INFO(nPhysicsDataChunkId, TYPE_ARRAY(4, TYPE_INFO(int))) -STRUCT_VAR_INFO(bboxMin, TYPE_INFO(Vec3)) -STRUCT_VAR_INFO(bboxMax, TYPE_INFO(Vec3)) -STRUCT_VAR_INFO(texMappingDensity, TYPE_INFO(float)) -STRUCT_VAR_INFO(geometricMeanFaceArea, TYPE_INFO(float)) -STRUCT_VAR_INFO(reserved, TYPE_ARRAY(30, TYPE_INFO(int))) -STRUCT_INFO_END(MESH_CHUNK_DESC_0801) - -STRUCT_INFO_BEGIN(MESH_CHUNK_DESC_0802) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(int)) -STRUCT_VAR_INFO(nFlags2, TYPE_INFO(int)) -STRUCT_VAR_INFO(nVerts, TYPE_INFO(int)) -STRUCT_VAR_INFO(nIndices, TYPE_INFO(int)) -STRUCT_VAR_INFO(nSubsets, TYPE_INFO(int)) -STRUCT_VAR_INFO(nSubsetsChunkId, TYPE_INFO(int)) -STRUCT_VAR_INFO(nVertAnimID, TYPE_INFO(int)) -STRUCT_VAR_INFO(nStreamChunkID, TYPE_ARRAY(16, TYPE_ARRAY(8, TYPE_INFO(int)))) -STRUCT_VAR_INFO(nPhysicsDataChunkId, TYPE_ARRAY(4, TYPE_INFO(int))) -STRUCT_VAR_INFO(bboxMin, TYPE_INFO(Vec3)) -STRUCT_VAR_INFO(bboxMax, TYPE_INFO(Vec3)) -STRUCT_VAR_INFO(texMappingDensity, TYPE_INFO(float)) -STRUCT_VAR_INFO(geometricMeanFaceArea, TYPE_INFO(float)) -STRUCT_VAR_INFO(reserved, TYPE_ARRAY(30, TYPE_INFO(int))) -STRUCT_INFO_END(MESH_CHUNK_DESC_0802) - -STRUCT_INFO_BEGIN(STREAM_DATA_CHUNK_DESC_0800) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(int)) -STRUCT_VAR_INFO(nStreamType, TYPE_INFO(int)) -STRUCT_VAR_INFO(nCount, TYPE_INFO(int)) -STRUCT_VAR_INFO(nElementSize, TYPE_INFO(int)) -STRUCT_VAR_INFO(reserved, TYPE_ARRAY(2, TYPE_INFO(int))) -STRUCT_INFO_END(STREAM_DATA_CHUNK_DESC_0800) - -STRUCT_INFO_BEGIN(STREAM_DATA_CHUNK_DESC_0801) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(int)) -STRUCT_VAR_INFO(nStreamType, TYPE_INFO(int)) -STRUCT_VAR_INFO(nStreamIndex, TYPE_INFO(int)) -STRUCT_VAR_INFO(nCount, TYPE_INFO(int)) -STRUCT_VAR_INFO(nElementSize, TYPE_INFO(int)) -STRUCT_VAR_INFO(reserved, TYPE_ARRAY(2, TYPE_INFO(int))) -STRUCT_INFO_END(STREAM_DATA_CHUNK_DESC_0801) - -STRUCT_INFO_BEGIN(MESH_SUBSETS_CHUNK_DESC_0800::MeshSubset) -STRUCT_VAR_INFO(nFirstIndexId, TYPE_INFO(int)) -STRUCT_VAR_INFO(nNumIndices, TYPE_INFO(int)) -STRUCT_VAR_INFO(nFirstVertId, TYPE_INFO(int)) -STRUCT_VAR_INFO(nNumVerts, TYPE_INFO(int)) -STRUCT_VAR_INFO(nMatID, TYPE_INFO(int)) -STRUCT_VAR_INFO(fRadius, TYPE_INFO(float)) -STRUCT_VAR_INFO(vCenter, TYPE_INFO(Vec3)) -STRUCT_INFO_END(MESH_SUBSETS_CHUNK_DESC_0800::MeshSubset) - -STRUCT_INFO_BEGIN(MESH_SUBSETS_CHUNK_DESC_0800::MeshBoneIDs) -STRUCT_VAR_INFO(numBoneIDs, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(arrBoneIDs, TYPE_ARRAY(128, TYPE_INFO(uint16))) -STRUCT_INFO_END(MESH_SUBSETS_CHUNK_DESC_0800::MeshBoneIDs) - -STRUCT_INFO_BEGIN(MESH_SUBSETS_CHUNK_DESC_0800::MeshSubsetTexelDensity) -STRUCT_VAR_INFO(texelDensity, TYPE_INFO(float)) -STRUCT_INFO_END(MESH_SUBSETS_CHUNK_DESC_0800::MeshSubsetTexelDensity) - - -STRUCT_INFO_BEGIN(MESH_SUBSETS_CHUNK_DESC_0800) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(int)) -STRUCT_VAR_INFO(nCount, TYPE_INFO(int)) -STRUCT_VAR_INFO(reserved, TYPE_ARRAY(2, TYPE_INFO(int))) -STRUCT_INFO_END(MESH_SUBSETS_CHUNK_DESC_0800) - -STRUCT_INFO_BEGIN(MESH_PHYSICS_DATA_CHUNK_DESC_0800) -STRUCT_VAR_INFO(nDataSize, TYPE_INFO(int)) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(int)) -STRUCT_VAR_INFO(nTetrahedraDataSize, TYPE_INFO(int)) -STRUCT_VAR_INFO(nTetrahedraChunkId, TYPE_INFO(int)) -STRUCT_VAR_INFO(reserved, TYPE_ARRAY(2, TYPE_INFO(int))) -STRUCT_INFO_END(MESH_PHYSICS_DATA_CHUNK_DESC_0800) - -STRUCT_INFO_BEGIN(BONEANIM_CHUNK_DESC_0290) -STRUCT_VAR_INFO(nBones, TYPE_INFO(int)) -STRUCT_INFO_END(BONEANIM_CHUNK_DESC_0290) - -STRUCT_INFO_BEGIN(BONENAMELIST_CHUNK_DESC_0745) -STRUCT_VAR_INFO(numEntities, TYPE_INFO(int)) -STRUCT_INFO_END(BONENAMELIST_CHUNK_DESC_0745) - -STRUCT_INFO_BEGIN(COMPILED_BONE_CHUNK_DESC_0800) -STRUCT_VAR_INFO(reserved, TYPE_ARRAY(32, TYPE_INFO(char))) -STRUCT_INFO_END(COMPILED_BONE_CHUNK_DESC_0800) - -STRUCT_INFO_BEGIN(COMPILED_PHYSICALBONE_CHUNK_DESC_0800) -STRUCT_VAR_INFO(reserved, TYPE_ARRAY(32, TYPE_INFO(char))) -STRUCT_INFO_END(COMPILED_PHYSICALBONE_CHUNK_DESC_0800) - -STRUCT_INFO_BEGIN(COMPILED_PHYSICALPROXY_CHUNK_DESC_0800) -STRUCT_VAR_INFO(numPhysicalProxies, TYPE_INFO(uint32)) -STRUCT_INFO_END(COMPILED_PHYSICALPROXY_CHUNK_DESC_0800) - -STRUCT_INFO_BEGIN(COMPILED_MORPHTARGETS_CHUNK_DESC_0800) -STRUCT_VAR_INFO(numMorphTargets, TYPE_INFO(uint32)) -STRUCT_INFO_END(COMPILED_MORPHTARGETS_CHUNK_DESC_0800) - -STRUCT_INFO_BEGIN(COMPILED_INTSKINVERTICES_CHUNK_DESC_0800) -STRUCT_VAR_INFO(reserved, TYPE_ARRAY(32, TYPE_INFO(char))) -STRUCT_INFO_END(COMPILED_INTSKINVERTICES_CHUNK_DESC_0800) - -STRUCT_INFO_BEGIN(BaseKey) -STRUCT_VAR_INFO(time, TYPE_INFO(int)) -STRUCT_INFO_END(BaseKey) - -STRUCT_INFO_BEGIN(BaseTCB) -STRUCT_VAR_INFO(t, TYPE_INFO(float)) -STRUCT_VAR_INFO(c, TYPE_INFO(float)) -STRUCT_VAR_INFO(b, TYPE_INFO(float)) -STRUCT_VAR_INFO(ein, TYPE_INFO(float)) -STRUCT_VAR_INFO(eout, TYPE_INFO(float)) -STRUCT_INFO_END(BaseTCB) - -STRUCT_INFO_BEGIN(BaseKey3) -STRUCT_BASE_INFO(BaseKey) -STRUCT_VAR_INFO(val, TYPE_INFO(Vec3)) -STRUCT_INFO_END(BaseKey3) - -STRUCT_INFO_BEGIN(BaseKeyQ) -STRUCT_BASE_INFO(BaseKey) -STRUCT_VAR_INFO(val, TYPE_INFO(CryQuat)) -STRUCT_INFO_END(BaseKeyQ) - -STRUCT_INFO_BEGIN(CryTCB3Key) -STRUCT_BASE_INFO(BaseKey3) -STRUCT_BASE_INFO(BaseTCB) -STRUCT_INFO_END(CryTCB3Key) - -STRUCT_INFO_BEGIN(CryTCBQKey) -STRUCT_BASE_INFO(BaseKeyQ) -STRUCT_BASE_INFO(BaseTCB) -STRUCT_INFO_END(CryTCBQKey) - -STRUCT_INFO_BEGIN(CryKeyPQLog) -STRUCT_VAR_INFO(nTime, TYPE_INFO(int)) -STRUCT_VAR_INFO(vPos, TYPE_INFO(Vec3)) -STRUCT_VAR_INFO(vRotLog, TYPE_INFO(Vec3)) -STRUCT_INFO_END(CryKeyPQLog) - -ENUM_INFO_BEGIN(CtrlTypes) -ENUM_ELEM_INFO(, CTRL_NONE) -ENUM_ELEM_INFO(, CTRL_CRYBONE) -ENUM_ELEM_INFO(, CTRL_LINEER1) -ENUM_ELEM_INFO(, CTRL_LINEER3) -ENUM_ELEM_INFO(, CTRL_LINEERQ) -ENUM_ELEM_INFO(, CTRL_BEZIER1) -ENUM_ELEM_INFO(, CTRL_BEZIER3) -ENUM_ELEM_INFO(, CTRL_BEZIERQ) -ENUM_ELEM_INFO(, CTRL_TCB1) -ENUM_ELEM_INFO(, CTRL_TCB3) -ENUM_ELEM_INFO(, CTRL_TCBQ) -ENUM_ELEM_INFO(, CTRL_BSPLINE_2O) -ENUM_ELEM_INFO(, CTRL_BSPLINE_1O) -ENUM_ELEM_INFO(, CTRL_BSPLINE_2C) -ENUM_ELEM_INFO(, CTRL_BSPLINE_1C) -ENUM_ELEM_INFO(, CTRL_CONST) -ENUM_INFO_END(CtrlTypes) - -STRUCT_INFO_BEGIN(CONTROLLER_CHUNK_DESC_0826) -STRUCT_VAR_INFO(type, TYPE_INFO(CtrlTypes)) -STRUCT_VAR_INFO(nKeys, TYPE_INFO(int)) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(unsigned int)) -STRUCT_VAR_INFO(nControllerId, TYPE_INFO(unsigned int)) -STRUCT_INFO_END(CONTROLLER_CHUNK_DESC_0826) - -STRUCT_INFO_BEGIN(CONTROLLER_CHUNK_DESC_0827) -STRUCT_VAR_INFO(numKeys, TYPE_INFO(unsigned int)) -STRUCT_VAR_INFO(nControllerId, TYPE_INFO(unsigned int)) -STRUCT_INFO_END(CONTROLLER_CHUNK_DESC_0827) - -STRUCT_INFO_BEGIN(CONTROLLER_CHUNK_DESC_0829) -STRUCT_VAR_INFO(nControllerId, TYPE_INFO(unsigned int)) -STRUCT_VAR_INFO(numRotationKeys, TYPE_INFO(uint16)) -STRUCT_VAR_INFO(numPositionKeys, TYPE_INFO(uint16)) -STRUCT_VAR_INFO(RotationFormat, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(RotationTimeFormat, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(PositionFormat, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(PositionKeysInfo, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(PositionTimeFormat, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(TracksAligned, TYPE_INFO(uint8)) -STRUCT_INFO_END(CONTROLLER_CHUNK_DESC_0829) - -STRUCT_INFO_BEGIN(CONTROLLER_CHUNK_DESC_0830) -STRUCT_VAR_INFO(numKeys, TYPE_INFO(unsigned int)) -STRUCT_VAR_INFO(nFlags, Type_info(unsigned int)) -STRUCT_VAR_INFO(nControllerId, TYPE_INFO(unsigned int)) -STRUCT_INFO_END(CONTROLLER_CHUNK_DESC_0830) - -STRUCT_INFO_BEGIN(CONTROLLER_CHUNK_DESC_0831) -STRUCT_VAR_INFO(nControllerId, TYPE_INFO(unsigned int)) -STRUCT_VAR_INFO(nFlags, Type_info(unsigned int)) -STRUCT_VAR_INFO(numRotationKeys, TYPE_INFO(uint16)) -STRUCT_VAR_INFO(numPositionKeys, TYPE_INFO(uint16)) -STRUCT_VAR_INFO(RotationFormat, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(RotationTimeFormat, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(PositionFormat, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(PositionKeysInfo, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(PositionTimeFormat, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(TracksAligned, TYPE_INFO(uint8)) -STRUCT_INFO_END(CONTROLLER_CHUNK_DESC_0831) - -STRUCT_INFO_BEGIN(CONTROLLER_CHUNK_DESC_0905) -STRUCT_VAR_INFO(numKeyPos, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(numKeyRot, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(numKeyTime, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(numAnims, TYPE_INFO(uint32)) -STRUCT_INFO_END(CONTROLLER_CHUNK_DESC_0905) - -STRUCT_INFO_BEGIN(NODE_CHUNK_DESC_0824) -STRUCT_VAR_INFO(name, TYPE_ARRAY(64, TYPE_INFO(char))) -STRUCT_VAR_INFO(ObjectID, TYPE_INFO(int)) -STRUCT_VAR_INFO(ParentID, TYPE_INFO(int)) -STRUCT_VAR_INFO(nChildren, TYPE_INFO(int)) -STRUCT_VAR_INFO(MatID, TYPE_INFO(int)) -STRUCT_VAR_INFO(_obsoleteA_, TYPE_ARRAY(4, TYPE_INFO(uint8))) -STRUCT_VAR_INFO(tm, TYPE_ARRAY(4, TYPE_ARRAY(4, TYPE_INFO(float)))) -STRUCT_VAR_INFO(_obsoleteB_, TYPE_ARRAY(3, TYPE_INFO(float))) -STRUCT_VAR_INFO(_obsoleteC_, TYPE_ARRAY(4, TYPE_INFO(float))) -STRUCT_VAR_INFO(_obsoleteD_, TYPE_ARRAY(3, TYPE_INFO(float))) -STRUCT_VAR_INFO(pos_cont_id, TYPE_INFO(int)) -STRUCT_VAR_INFO(rot_cont_id, TYPE_INFO(int)) -STRUCT_VAR_INFO(scl_cont_id, TYPE_INFO(int)) -STRUCT_VAR_INFO(PropStrLen, TYPE_INFO(int)) -STRUCT_INFO_END(NODE_CHUNK_DESC_0824) - -ENUM_INFO_BEGIN(HelperTypes) -ENUM_ELEM_INFO(, HP_POINT) -ENUM_ELEM_INFO(, HP_DUMMY) -ENUM_ELEM_INFO(, HP_XREF) -ENUM_ELEM_INFO(, HP_CAMERA) -ENUM_ELEM_INFO(, HP_GEOMETRY) -ENUM_INFO_END(HelperTypes) - -STRUCT_INFO_BEGIN(HELPER_CHUNK_DESC_0744) -STRUCT_VAR_INFO(type, TYPE_INFO(HelperTypes)) -STRUCT_VAR_INFO(size, TYPE_INFO(Vec3)) -STRUCT_INFO_END(HELPER_CHUNK_DESC_0744) - -STRUCT_INFO_BEGIN(MESHMORPHTARGET_CHUNK_DESC_0001) -STRUCT_VAR_INFO(nChunkIdMesh, TYPE_INFO(unsigned int)) -STRUCT_VAR_INFO(numMorphVertices, TYPE_INFO(unsigned int)) -STRUCT_INFO_END(MESHMORPHTARGET_CHUNK_DESC_0001) - -STRUCT_INFO_BEGIN(SMeshMorphTargetVertex) -STRUCT_VAR_INFO(nVertexId, TYPE_INFO(unsigned int)) -STRUCT_VAR_INFO(ptVertex, TYPE_INFO(Vec3)) -STRUCT_INFO_END(SMeshMorphTargetVertex) - -STRUCT_INFO_BEGIN(SMeshMorphTargetHeader) -STRUCT_VAR_INFO(MeshID, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(NameLength, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(numIntVertices, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(numExtVertices, TYPE_INFO(uint32)) -STRUCT_INFO_END(SMeshMorphTargetHeader) - -STRUCT_INFO_BEGIN(SMeshPhysicalProxyHeader) -STRUCT_VAR_INFO(ChunkID, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(numPoints, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(numIndices, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(numMaterials, TYPE_INFO(uint32)) -STRUCT_INFO_END(SMeshPhysicalProxyHeader) - -STRUCT_INFO_BEGIN(BONEINITIALPOS_CHUNK_DESC_0001) -STRUCT_VAR_INFO(nChunkIdMesh, TYPE_INFO(unsigned int)) -STRUCT_VAR_INFO(numBones, TYPE_INFO(unsigned int)) -STRUCT_INFO_END(BONEINITIALPOS_CHUNK_DESC_0001) - -STRUCT_INFO_BEGIN(SBoneInitPosMatrix) -STRUCT_VAR_INFO(mx, TYPE_ARRAY(4, TYPE_ARRAY(3, TYPE_INFO(float)))) -STRUCT_INFO_END(SBoneInitPosMatrix) - -STRUCT_INFO_BEGIN(EXPORT_FLAGS_CHUNK_DESC) -STRUCT_VAR_INFO(flags, TYPE_INFO(unsigned int)) -STRUCT_VAR_INFO(rc_version, TYPE_ARRAY(4, TYPE_INFO(unsigned int))) -STRUCT_VAR_INFO(rc_version_string, TYPE_ARRAY(16, TYPE_INFO(char))) -STRUCT_VAR_INFO(assetAuthorTool, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(authorToolVersion, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(reserved, TYPE_ARRAY(30, TYPE_INFO(unsigned int))) -STRUCT_INFO_END(EXPORT_FLAGS_CHUNK_DESC) - -STRUCT_INFO_BEGIN(BREAKABLE_PHYSICS_CHUNK_DESC) -STRUCT_VAR_INFO(granularity, TYPE_INFO(unsigned int)) -STRUCT_VAR_INFO(nMode, TYPE_INFO(int)) -STRUCT_VAR_INFO(nRetVtx, TYPE_INFO(int)) -STRUCT_VAR_INFO(nRetTets, TYPE_INFO(int)) -STRUCT_VAR_INFO(nReserved, TYPE_ARRAY(10, TYPE_INFO(int))) -STRUCT_INFO_END(BREAKABLE_PHYSICS_CHUNK_DESC) - -STRUCT_INFO_BEGIN(FOLIAGE_INFO_CHUNK_DESC) -STRUCT_VAR_INFO(nSpines, TYPE_INFO(int)) -STRUCT_VAR_INFO(nSpineVtx, TYPE_INFO(int)) -STRUCT_VAR_INFO(nSkinnedVtx, TYPE_INFO(int)) -STRUCT_VAR_INFO(nBoneIds, TYPE_INFO(int)) -STRUCT_INFO_END(FOLIAGE_INFO_CHUNK_DESC) - -STRUCT_INFO_BEGIN(FOLIAGE_SPINE_SUB_CHUNK) -STRUCT_VAR_INFO(nVtx, TYPE_INFO(char)) -STRUCT_VAR_INFO(len, TYPE_INFO(float)) -STRUCT_VAR_INFO(navg, TYPE_INFO(Vec3)) -STRUCT_VAR_INFO(iAttachSpine, TYPE_INFO(unsigned char)) -STRUCT_VAR_INFO(iAttachSeg, TYPE_INFO(unsigned char)) -STRUCT_INFO_END(FOLIAGE_SPINE_SUB_CHUNK) diff --git a/Code/CryEngine/CryCommon/CryLegacyAllocator.h b/Code/CryEngine/CryCommon/CryLegacyAllocator.h deleted file mode 100644 index f8024dac41..0000000000 --- a/Code/CryEngine/CryCommon/CryLegacyAllocator.h +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include "LegacyAllocator.h" - -#include - -//----------------------------------------------------------------------------- -// CryModule allocation API -//----------------------------------------------------------------------------- -#define CryModuleMalloc(size) CryModuleMallocImpl(size, __FILE__, __LINE__) - -inline void* CryModuleMallocImpl(size_t size, const char* file, const int line) -{ - return AZ::AllocatorInstance::Get().Allocate(size, 0, 0, "LegacyAllocator malloc", file, line); -} - -#define CryModuleFree(ptr) CryModuleFreeImpl(ptr, __FILE__, __LINE__) -#define CryModuleMemalignFree(ptr) CryModuleFreeImpl(ptr, __FILE__, __LINE__) - -inline void CryModuleFreeImpl(void* ptr, const char* file, const int line) -{ - - AZ::IAllocator& allocator = AZ::AllocatorInstance::GetAllocator(); - - if (allocator.IsAllocationSourceChanged()) - { - allocator.GetAllocationSource()->DeAllocate(ptr); - } - else - { - static_cast(allocator).DeAllocate(ptr, file, line); - } -} - -#define CryModuleMemalign(size, alignment) CryModuleMemalignImpl(size, alignment, __FILE__, __LINE__) - -inline void* CryModuleMemalignImpl(size_t size, size_t alignment, const char* file, const int line) -{ - return AZ::AllocatorInstance::Get().Allocate(size, alignment, 0, "LegacyAllocator memalign", file, line); -} - -#define CryModuleCalloc(num, size) CryModuleCallocImpl(num, size, __FILE__, __LINE__) - -inline void* CryModuleCallocImpl(size_t num, size_t size, const char* file, const int line) -{ - void* ptr = AZ::AllocatorInstance::Get().Allocate(num * size, 0, 0, "LegacyAllocator calloc", file, line); - ::memset(ptr, 0, num * size); - return ptr; -} - -#define CryModuleRealloc(ptr, size) CryModuleReallocAlignImpl(ptr, size, 0, __FILE__, __LINE__) -#define CryModuleReallocAlign(ptr, size, alignment) CryModuleReallocAlignImpl(ptr, size, alignment, __FILE__, __LINE__) - -inline void* CryModuleReallocAlignImpl(void* prev, size_t size, size_t alignment, const char* file, const int line) -{ - if (!prev) - { - // map realloc(nullptr, ...) -> alloc() so that we can track the location of the initial alloc - return CryModuleMemalignImpl(size, alignment, file, line); - } - if (size == 0) - { - CryModuleFreeImpl(prev, file, line); - return nullptr; - } - // There should not be any code using CryRealloc during static-init time or before the allocators -// are initialized. -#if defined(AZ_MONOLITHIC_BUILD) - if (!AZ::AllocatorInstance::IsReady()) - { - AZ_Assert(false, "CryRealloc/CryReallocAlign cannot be used unless the LegacyAllocator has been initialized"); - return nullptr; - } -#endif - - AZ::IAllocator& allocator = AZ::AllocatorInstance::GetAllocator(); - void *ptr; - - if (allocator.IsAllocationSourceChanged()) - { - ptr = allocator.GetAllocationSource()->ReAllocate(prev, size, 0); - } - else - { - ptr = static_cast(allocator).ReAllocate(prev, size, 0, file, line); - } - - return ptr; -} - -//----------------------------------------------------------------------------- -// CryCrt alloc API -//----------------------------------------------------------------------------- -inline size_t CryCrtSize(void* p) -{ - return AZ::AllocatorInstance::Get().AllocationSize(p); -} - -inline void* CryCrtMalloc(size_t size) -{ - return CryModuleMalloc(size); -} - -inline size_t CryCrtFree(void* p) -{ - size_t size = CryCrtSize(p); - CryModuleFree(p); - return size; -}; - -//----------------------------------------------------------------------------- -// CrySystemCrt alloc API -//----------------------------------------------------------------------------- -inline size_t CrySystemCrtSize(void* p) -{ - return AZ::AllocatorInstance::Get().AllocationSize(p); -} - -inline void* CrySystemCrtMalloc(size_t size) -{ - return AZ::AllocatorInstance::Get().Allocate(size, 0, 0, "AZ::LegacyAllocator"); -} - -inline void* CrySystemCrtRealloc(void* p, size_t size) -{ - // Use LegacyAllocator's special ReAllocate - return AZ::AllocatorInstance::Get().ReAllocate(p, size, 0); -} - -inline size_t CrySystemCrtFree(void* p) -{ - size_t size = CrySystemCrtSize(p); - CryModuleFree(p); - return size; -} - -inline size_t CrySystemCrtGetUsedSpace() -{ - return AZ::AllocatorInstance::Get().NumAllocatedBytes(); -} - -//----------------------------------------------------------------------------- -// CryMalloc API -//----------------------------------------------------------------------------- -inline void* CryMalloc(size_t size, size_t& allocated, size_t alignment) -{ - if (!size) - { - allocated = 0; - return nullptr; - } - - // The original implementation guaranteed 16 byte min alignment - alignment = AZStd::GetMax(alignment, 16); - void* ptr = AZ::AllocatorInstance::Get().Allocate(size, alignment, 0, "CryMalloc", __FILE__, __LINE__); - allocated = AZ::AllocatorInstance::Get().AllocationSize(ptr); - return ptr; -} - -inline void* CryRealloc(void* memblock, size_t size, size_t& allocated, size_t& oldsize, size_t alignment) -{ - oldsize = AZ::AllocatorInstance::Get().AllocationSize(memblock); - void* ptr = AZ::AllocatorInstance::Get().ReAllocate(memblock, size, alignment); - allocated = AZ::AllocatorInstance::Get().AllocationSize(ptr); - return ptr; -} - -inline size_t CryFree(void* p, size_t /*alignment*/) -{ - size_t size = AZ::AllocatorInstance::Get().AllocationSize(p); - AZ::AllocatorInstance::Get().DeAllocate(p, size); - return size; -} - -inline size_t CryGetMemSize(void* memblock, size_t /*sourceSize*/) -{ - return AZ::AllocatorInstance::Get().AllocationSize(memblock); -} - -inline int CryMemoryGetAllocatedSize() -{ - return AZ::AllocatorInstance::Get().NumAllocatedBytes(); -} - -////////////////////////////////////////////////////////////////////////// -inline int CryMemoryGetPoolSize() -{ - return 0; -} - -////////////////////////////////////////////////////////////////////////// -inline int CryStats([[maybe_unused]] char* buf) -{ - return 0; -} - -inline int CryGetUsedHeapSize() -{ - return AZ::AllocatorInstance::Get().NumAllocatedBytes(); -} - -inline int CryGetWastedHeapSize() -{ - return 0; -} - -inline void CryCleanup() -{ - AZ::AllocatorInstance::Get().GarbageCollect(); -} - -inline void CryResetStats(void) -{ -} diff --git a/Code/CryEngine/CryCommon/CryLibrary.cpp b/Code/CryEngine/CryCommon/CryLibrary.cpp deleted file mode 100644 index 42f3ca3d09..0000000000 --- a/Code/CryEngine/CryCommon/CryLibrary.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include - -#if !defined(AZ_RESTRICTED_PLATFORM) && defined(WIN32) - -HMODULE CryLoadLibrary(const char* libName) -{ - HMODULE module = ::LoadLibraryA(libName); - if (module != NULL) - { - // We need to inject the environment first thing so that allocators are available immediately - InjectEnvironmentFunction injectEnv = reinterpret_cast(::GetProcAddress(module, INJECT_ENVIRONMENT_FUNCTION)); - if (injectEnv) - { - auto env = AZ::Environment::GetInstance(); - injectEnv(env); - } - } - - return module; -} - -// Cry code seems to have used void* as their abstraction for HMODULE across -// platforms. -bool CryFreeLibrary(void* lib) -{ - if (lib != NULL) - { - DetachEnvironmentFunction detachEnv = reinterpret_cast(::GetProcAddress((HMODULE)lib, DETACH_ENVIRONMENT_FUNCTION)); - if (detachEnv) - { - detachEnv(); - } - return ::FreeLibrary((HMODULE)lib) != FALSE; - } - return false; -} - -#endif diff --git a/Code/CryEngine/CryCommon/CryLibrary.h b/Code/CryEngine/CryCommon/CryLibrary.h deleted file mode 100644 index 1d06d8ee1b..0000000000 --- a/Code/CryEngine/CryCommon/CryLibrary.h +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - - -/*! - CryLibrary - - Convenience-Macros which abstract the use of DLLs/shared libraries in a platform independent way. - A short explanation of the different macros follows: - - CrySharedLibrarySupported: - This macro can be used to test if the current active platform supports shared library calls. The default - value is false. This gets redefined if a certain platform (WIN32 or LINUX) is desired. - - CrySharedLibraryPrefix: - The default prefix which will get prepended to library names in calls to CryLoadLibraryDefName - (see below). - - CrySharedLibraryExtension: - The default extension which will get appended to library names in calls to CryLoadLibraryDefName - (see below). - - CryLoadLibrary(libName): - Loads a shared library. - - CryLoadLibraryDefName(libName): - Loads a shared library. The platform-specific default library prefix and extension are appended to the libName. - This allows writing of somewhat platform-independent library loading code and is therefore the function - which should be used most of the time, unless some special extensions are used (e.g. for plugins). - - CryGetProcAddress(libHandle, procName): - Import function from the library presented by libHandle. - - CryFreeLibrary(libHandle): - Unload the library presented by libHandle. - - HISTORY: - 03.03.2004 MarcoK - - initial version - - added to CryPlatform -*/ - -#include -#include -#include - -#define INJECT_ENVIRONMENT_FUNCTION "InjectEnvironment" -#define DETACH_ENVIRONMENT_FUNCTION "DetachEnvironment" -using InjectEnvironmentFunction = void(*)(void*); -using DetachEnvironmentFunction = void(*)(); - -#if defined(AZ_RESTRICTED_PLATFORM) - #include AZ_RESTRICTED_FILE(CryLibrary_h) -#elif defined(WIN32) - #if !defined(WIN32_LEAN_AND_MEAN) - #define WIN32_LEAN_AND_MEAN - #endif - #include - - HMODULE CryLoadLibrary(const char* libName); - - // Cry code seems to have used void* as their abstraction for HMODULE across - // platforms. - bool CryFreeLibrary(void* lib); - - #define CRYLIBRARY_H_TRAIT_USE_WINDOWS_DLL 1 -#elif ((defined(LINUX) || AZ_TRAIT_OS_PLATFORM_APPLE)) - #include - #include - #include - #include "platform.h" - #include - -// for compatibility with code written for windows - #define CrySharedLibrarySupported true - #define CrySharedLibraryPrefix "lib" -#if AZ_TRAIT_OS_PLATFORM_APPLE - #include - #define CrySharedLibraryExtension ".dylib" -#else - #define CrySharedLibraryExtension ".so" -#endif - - #define CryGetProcAddress(libHandle, procName) ::dlsym(libHandle, procName) - #define HMODULE void* -static const char* gEnvName("MODULE_PATH"); - -static const char* GetModulePath() -{ - return getenv(gEnvName); -} - -static void SetModulePath(const char* pModulePath) -{ - setenv(gEnvName, pModulePath ? pModulePath : "", true); -} - -// bInModulePath is only ever set to false in RC, because rc needs to load dlls from a $PATH that -// it has modified to include .. -static HMODULE CryLoadLibrary(const char* libName, bool bLazy = false, bool bInModulePath = true) -{ - const char* libPath = nullptr; - char pathBuffer[MAX_PATH] = {0}; - - libPath = libName; - -#if !defined(AZ_PLATFORM_ANDROID) - if (bInModulePath) - { - char exePath[MAX_PATH + 1] = { 0 }; - const char* modulePath = GetModulePath(); - if (!modulePath) - { - modulePath = "."; - #if defined(LINUX) - int len = readlink("/proc/self/exe", exePath, MAX_PATH); - if (len != -1) - { - exePath[len] = 0; - modulePath = dirname(exePath); - } - #elif AZ_TRAIT_OS_PLATFORM_APPLE - uint32_t bufsize = MAX_PATH; - if (_NSGetExecutablePath(exePath, &bufsize) == 0) - { - exePath[bufsize] = 0; - modulePath = dirname(exePath); - } - #endif - } - sprintf_s(pathBuffer, "%s/%s", modulePath, libName); - libPath = pathBuffer; - } -#endif - - HMODULE module; - #if defined(LINUX) && !defined(ANDROID) - module = ::dlopen(libPath, (bLazy ? RTLD_LAZY : RTLD_NOW) | RTLD_DEEPBIND); - #else - module = ::dlopen(libPath, bLazy ? RTLD_LAZY : RTLD_NOW); - #endif - AZ_Warning("LMBR", module, "Can't load library [%s]: %s", libName, dlerror()); - - if (module) - { - // We need to inject the environment first thing so that allocators are available immediately - InjectEnvironmentFunction injectEnv = reinterpret_cast(CryGetProcAddress(module, INJECT_ENVIRONMENT_FUNCTION)); - if (injectEnv) - { - injectEnv(AZ::Environment::GetInstance()); - } - } - - return module; -} - -static bool CryFreeLibrary(void* lib) -{ - if (lib) - { - DetachEnvironmentFunction detachEnv = reinterpret_cast(CryGetProcAddress(lib, DETACH_ENVIRONMENT_FUNCTION)); - if (detachEnv) - { - detachEnv(); - } - return (::dlclose(lib) == 0); - } - return false; -} -#endif - -#if CRYLIBRARY_H_TRAIT_USE_WINDOWS_DLL -#define CrySharedLibrarySupported true -#define CrySharedLibraryPrefix "" -#define CrySharedLibraryExtension ".dll" -#define CryGetProcAddress(libHandle, procName) ::GetProcAddress((HMODULE)(libHandle), procName) -#elif !defined(CrySharedLibrarySupported) -#define CrySharedLibrarySupported false -#define CrySharedLibraryPrefix "" -#define CrySharedLibraryExtension "" -#define CryLoadLibrary(libName) NULL -#define CryGetProcAddress(libHandle, procName) NULL -#define CryFreeLibrary(libHandle) -#define GetModuleHandle(x) 0 -#endif -#define CryLibraryDefName(libName) CrySharedLibraryPrefix libName CrySharedLibraryExtension -#define CryLoadLibraryDefName(libName) CryLoadLibrary(CryLibraryDefName(libName)) diff --git a/Code/CryEngine/CryCommon/CryListenerSet.h b/Code/CryEngine/CryCommon/CryListenerSet.h deleted file mode 100644 index 64b7807055..0000000000 --- a/Code/CryEngine/CryCommon/CryListenerSet.h +++ /dev/null @@ -1,613 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : A simple, intelligent and efficient container for listeners. - -// This is designed to provide a simple & consistent interface and behavior -// for adding, removing and iterating listeners - hopefully avoiding the -// common pitfalls such as duplicated elements, invalid iterators and -// dangling pointers. - - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYLISTENERSET_H -#define CRYINCLUDE_CRYCOMMON_CRYLISTENERSET_H -#pragma once - - -#include -/************************************************************************ - -Core elements: - - * CListenerSet - The collection of listeners. - * CListenerSet::Notifier - The iterator for safely calling listeners in sequence. - - [Where T is a pointer or something with pointer traits] - -Advantages: - - * Greatly reduces the complexity of managing listener collections. - * Can safely add and remove listeners during listener iteration. - * Automatically and safely removes NULL elements. - * Simple interface (but different from an STL collection to avoid confusion). - * Checks to see all listeners have been removed at destruction. - * Low overhead implementation (cheap use of std::vector and minimal heap allocation). - * Can add debug checks as needed - including stack tracing of Add() calls. - * Safe for recursive notification chains. - * Works with vanilla pointers and smart pointers. - * Provides full support for named listeners to aid debugging. - * Listener names tracked during notification to help resolve crashes. - * Designed to ensure names are recorded correctly in crash dump files. - -Named listener support: - - Supplying a name for a listener provides valuable debug information in the following cases: - - * Resolving crashes during listener notification - the name will help trace what listener caused the crash. - * Resolving which listeners are present in the CListenerSet during runtime. - - IMPORTANT: Please ensure heap allocated strings passed in as names are marked as such ie. - - m_listeners.Add(pListener, "MyListener"); // OK: Static string passed. - m_listeners.Add(pListener2, m_myName.c_str(), false); // OK: Heap string passed and marked as non-static. - m_listeners.Add(pListener3, m_myName.c_str(), true); // BAD: Heap string passed and marked as static (potential CRASH). - - Why store names like this? - - * 99% of use cases use static strings - so why allocate memory to make copies of static data? - * Pointers to static strings will *always* survive crash dumps - great for debugging crashes. - * We can enable debug support in QA builds - key for catching rare listener related crashes. - -Example: - - class CMyWorld - { - public: - void AddListener(IMyWorldListener* pListener, const char* szName) { m_listeners.Add(pListener, szName); } - void RemoveListener(IMyWorldListener* pListener) { m_listeners.Remove(pListener); } - - void NotifyListeners(CSomeEvent& event) - { - for (TWorldListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) - { - notifier->OnWorldEvent(event); - } - } - - private: - typedef CListenerSet TWorldListeners; - TWorldListeners m_listeners; - }; - - - // Implements IMyWorldListener - CMyWorldUser::OnWorldEvent(CSomeEvent& event) - { - // OK: Removing a listeners within an event handler - m_pWorld->RemoveListener(this); - - // OK: Notifying listeners within an event handler - m_pWorld->NotifyListeners(CSomeEvent newEvent(USER_REMOVED, this)); - } - - -*************************************************************************/ - -#ifndef _RELEASE - #define CRY_LISTENERSET_DEBUG -#endif - -// Forward decl. -template -class CListenerNotifier; - - -// Main listener collection class used in conjunction with CListenerNotifier. -template -class CListenerSet -{ -public: - // NOTE: No default constructor in favor of forcing users to provide an expectedCapacity - inline CListenerSet(size_t expectedCapacity); - inline /*non-virtual*/ ~CListenerSet(); - - // Appends a listener to the end of the collection. Name is optional but recommended. - inline bool Add(T pListener, const char* name = NULL, bool staticName = true); - - // Removes a listener from the collection. - inline void Remove(T pListener); - - // Removes all listeners from the collection (NOTE: prefer informing listeners to remove themselves) - inline void Clear(bool bFreeMemory = false); - - // Returns true if this contains pListener - inline bool Contains(T pListener) const; - - // Returns number of valid listeners - inline size_t ValidListenerCount() const; - - // Returns true if no valid listeners exist - inline bool Empty() const; - - // Reserves space to help avoid runtime reallocation - inline void Reserve(size_t capacity); - - // Returns the memory size of this object (to support CrySizer) - inline size_t MemSize() const; - - // Returns true if currently in the process of notifying listeners. - inline bool IsNotifying() const; - - // Allow access for Notifier for iteration - friend class CListenerNotifier; - - // Allow TListeners::Notifier style usage - typedef class CListenerNotifier Notifier; - - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddContainer(m_listeners); -#if defined(CRY_LISTENERSET_DEBUG) - pSizer->AddContainer(m_allocatedNames); -#endif - } -private: // DO NOT REMOVE - following methods only to be accessed only via CNotifier - - struct ListenerRecord - { - ListenerRecord() - : m_pListener() {} - ListenerRecord(T pListener, [[maybe_unused]] const char* szName = NULL) - : m_pListener(pListener) -#ifdef CRY_LISTENERSET_DEBUG - , m_szName(szName) -#endif - {} - - bool operator==(const ListenerRecord& other) const { return m_pListener == other.m_pListener; } - bool operator==(const T& other) const { return m_pListener == other; } - - T m_pListener; // The listener reference - -#ifdef CRY_LISTENERSET_DEBUG - const char* m_szName; // Name of tracked listener (owned if pointing to data in m_allocatedNames) -#endif - }; - - typedef std::vector TListenerVec; - typedef std::vector TAllocatedNameVec; - - inline void StartNotificationScope(); - inline void EndNotificationScope(); - - inline void EraseNullElements(); - -private: - TListenerVec m_listeners; // Collection of unique listeners. - size_t m_activeNotifications; // Counts current notifications in progress (cleanup cannot occur unless this is 0). - bool m_cleanupRequired; // Indicates NULL elements in listener. - bool m_freeMemOnCleanup; // Indicates how to clean up. - -#ifdef CRY_LISTENERSET_DEBUG - // Used to delete heap allocated names - inline void DeleteName(const char* name); - - TAllocatedNameVec m_allocatedNames; // Collection of strings pointing at heap allocated (i.e. copied) names (typically empty) -#endif -}; - - -// Helper class used to iterate listeners during listener notification. -template -class CListenerNotifier -{ -public: - ILINE CListenerNotifier(CListenerSet& listeners); - ILINE /*non-virtual*/ ~CListenerNotifier(); - - // True if the current element is ready for iteration - ILINE bool IsValid(); - - // Dereference current listener, MUST only be done after a call to IsValid(). - ILINE T operator->(); - - // Dereference current listener, MUST only be done after a call to IsValid(). - ILINE T operator*(); - - // Move to next valid listener (skipping NULL elements) - ILINE void Next(); - - // Returns the name of the listener (if available) - inline const char* Name() const; - -private: - CListenerSet& m_listenerSet; // ListenerSet being notified - T m_pListener; // Current listener at index (resolved by IsValid(), cleared after each dereference) - size_t m_index; // Current index of element (incremented by next) - -#ifdef CRY_LISTENERSET_DEBUG - const char* m_szName; // Name of the listener (if provided) to aid debugging -#endif -}; - -/******************************************************************************************/ - - - -template -inline CListenerSet::CListenerSet(size_t expectedCapacity) - : m_activeNotifications(0) - , m_cleanupRequired(false) - , m_freeMemOnCleanup(false) -{ - // Reserve the expected capacity to avoid reallocations - m_listeners.reserve(expectedCapacity); -} - -template -inline CListenerSet::~CListenerSet() -{ - // Ensure no notifications are in progress - CRY_ASSERT(m_activeNotifications == 0); - - // Ensure NULL elements were removed at end of last notification - CRY_ASSERT(!m_cleanupRequired); -} - -// Appends a listener to the end of the collection. Name is optional but recommended. -template -inline bool CListenerSet::Add(T pListener, const char* name, [[maybe_unused]] bool staticName) -{ - bool success = false; - - // Ensure the listener exists - CRY_ASSERT(pListener); - - if (pListener) - { - // Ensure the listener is only added once - if (!Contains(pListener)) - { - // Resolve name buffer safe for usage outside of this scope - const char* safeName = name; - -#ifdef CRY_LISTENERSET_DEBUG - // If a name was provided but it's not static data - if (name && !staticName) - { - // Add it to the list of heap allocated names (that we need to later delete) - m_allocatedNames.push_back(name); - safeName = m_allocatedNames.back().c_str(); - } -#endif - - m_listeners.push_back(ListenerRecord(pListener, safeName)); - success = true; - } - } - - return success; -} - -// Removes a listener from the collection. -template -inline void CListenerSet::Remove(T pListener) -{ - typename TListenerVec::iterator endIter(m_listeners.end()); - typename TListenerVec::iterator iter(std::find(m_listeners.begin(), endIter, pListener)); - if (iter != endIter) - { -#ifdef CRY_LISTENERSET_DEBUG - // Delete name if it was heap allocated - if (const char* name = iter->m_szName) - { - DeleteName(name); - } -#endif - - // If no notifications in progress - if (m_activeNotifications == 0) - { - // Just delete the listener entry immediately - m_listeners.erase(iter); - } - else // Notification(s) in progress, cannot re-order listeners - { - // Mark for cleanup - iter->m_pListener = NULL; - - m_cleanupRequired = true; - m_freeMemOnCleanup = false; - } - } - else // The listener is not in the set - { - // TODO: Warn about redundant Remove() - } -} - -// Removes all listeners from the collection (NOTE: prefer informing listeners to remove themselves) -template -inline void CListenerSet::Clear(bool bFreeMemory) -{ - // If no notifications in progress - if (m_activeNotifications == 0) - { - // Simply clear the listeners immediately - if (bFreeMemory) - { - stl::free_container(m_listeners); - } - else - { - m_listeners.clear(); - } - } - else - { - // Mark all listeners for cleanup - std::fill(m_listeners.begin(), m_listeners.end(), ListenerRecord()); - - m_cleanupRequired = true; - m_freeMemOnCleanup = true; - } - -#ifdef CRY_LISTENERSET_DEBUG - // Safe to clear allocated names immediately (no references exist any more) - if (bFreeMemory) - { - stl::free_container(m_allocatedNames); - } - else - { - m_allocatedNames.clear(); - } -#endif -} - -// Returns true if this contains pListener -template -inline bool CListenerSet::Contains(T pListener) const -{ - return stl::find(m_listeners, pListener); -} - -// Returns number of valid listeners -template -inline size_t CListenerSet::ValidListenerCount() const -{ - size_t validCount = m_listeners.size(); - - if (m_cleanupRequired) - { - // Remove the count of NULL elements from the result - validCount = validCount - std::count(m_listeners.begin(), m_listeners.end(), T()); - } - - return validCount; -} - -// Returns true if no valid listeners exist -template -inline bool CListenerSet::Empty() const -{ - return ValidListenerCount() == 0; -} - -// Reserves space to help avoid runtime reallocation -template -inline void CListenerSet::Reserve(size_t capacity) -{ - m_listeners.reserve(capacity); -} - -// Returns the memory size of this object (to support CrySizer) -template -inline size_t CListenerSet::MemSize() const -{ - size_t size = sizeof(CListenerSet) + sizeof(ListenerRecord) * m_listeners.size(); - -#ifdef CRY_LISTENERSET_DEBUG - size += sizeof(typename TAllocatedNameVec::value_type); - for (typename TAllocatedNameVec::const_iterator iter(m_allocatedNames.begin()); iter != m_allocatedNames.end(); ++iter) - { - size += iter->GetAllocatedMemory(); - } -#endif - - return size; -} - -template -inline bool CListenerSet::IsNotifying() const -{ - return m_activeNotifications > 0; -} - -template -inline void CListenerSet::StartNotificationScope() -{ - ++m_activeNotifications; -} - -template -inline void CListenerSet::EndNotificationScope() -{ - // Ensure at least one notification scope was started - CRY_ASSERT(m_activeNotifications > 0); - - // If this is the last notification - if (--m_activeNotifications == 0) - { - EraseNullElements(); - } -} - -template -inline void CListenerSet::EraseNullElements() -{ - // Ensure no modification while notification(s) are ongoing - CRY_ASSERT(m_activeNotifications == 0); - - if (m_cleanupRequired && m_activeNotifications == 0) - { - stl::find_and_erase_all(m_listeners, T()); - if (m_freeMemOnCleanup && m_listeners.empty()) - { - stl::free_container(m_listeners); - } - m_cleanupRequired = false; - m_freeMemOnCleanup = false; - } -} - -#ifdef CRY_LISTENERSET_DEBUG - -// Used to delete heap allocated names -template -inline void CListenerSet::DeleteName(const char* name) -{ - if (!m_allocatedNames.empty()) - { - typename TAllocatedNameVec::iterator endIter(m_allocatedNames.end()); - for (typename TAllocatedNameVec::iterator iter(m_allocatedNames.begin()); iter != endIter; ++iter) - { - // Is this the source string? - if (iter->c_str() == name) - { - // Delete it - m_allocatedNames.erase(iter); - break; - } - } - } -} - -#endif // defined CRY_LISTENERSET_DEBUG - - -/******************************************************************************************/ - - - -template -ILINE CListenerNotifier::CListenerNotifier(CListenerSet& listeners) - : m_listenerSet(listeners) - , m_pListener() - , m_index(0) -#ifdef CRY_LISTENERSET_DEBUG - , m_szName() -#endif -{ - // Flag iteration to listener set to ensure no erase is attempted during iteration - m_listenerSet.StartNotificationScope(); - - // If first element is NULL, move to next valid element - if (!IsValid()) - { - Next(); - } -} - -template -ILINE CListenerNotifier::~CListenerNotifier() -{ - // Erases any NULL elements from listeners - m_listenerSet.EndNotificationScope(); -} - -// True if the current element is ready for iteration -template -ILINE bool CListenerNotifier::IsValid() -{ - if (!m_pListener) - { - // Always check with original collection - if (m_index < m_listenerSet.m_listeners.size()) - { - const typename CListenerSet::ListenerRecord & record(m_listenerSet.m_listeners[m_index]); - m_pListener = record.m_pListener; - -#ifdef CRY_LISTENERSET_DEBUG - m_szName = record.m_szName; -#endif - } - } - - return m_pListener != NULL; -} - -// Dereference current listener, MUST only be done after a call to IsReady(). -template -ILINE T CListenerNotifier::operator->() -{ - return operator*(); -} - -// Dereference current listener, MUST only be done after a call to IsReady(). -template -ILINE T CListenerNotifier::operator*() -{ - // Ensure IsReady() was called and its return value checked - CRY_ASSERT(m_pListener); - - // Clear cached listener pointer to force a IsReady() call before this can be called again. - // This is done as the listener could be removed during any call to its own event handlers - // resulting in m_pListener becoming a dangling pointer. - T pListener(m_pListener); - m_pListener = T(); - return pListener; -} - -// Move to next valid listener -template -ILINE void CListenerNotifier::Next() -{ - size_t index = m_index; - typename CListenerSet::ListenerRecord * pNextRecord = NULL; - m_pListener = NULL; // Always assume there's no next, let the code below prove otherwise! - - const size_t listenerCount = m_listenerSet.m_listeners.size(); - while (++index < listenerCount) - { - typename CListenerSet::ListenerRecord & record(m_listenerSet.m_listeners[index]); - - // Is this element valid? - if (record.m_pListener) - { - pNextRecord = &record; - break; - } - // Else move to next element - } - - if (pNextRecord) - { - m_pListener = pNextRecord->m_pListener; -#ifdef CRY_LISTENERSET_DEBUG - m_szName = pNextRecord->m_szName; -#endif - } - - m_index = index; -} - -// Returns the name of the listener (if available) -template -inline const char* CListenerNotifier::Name() const -{ -#ifdef CRY_LISTENERSET_DEBUG - return m_szName; -#else - return NULL; -#endif -} - - -#endif // CRYINCLUDE_CRYCOMMON_CRYLISTENERSET_H diff --git a/Code/CryEngine/CryCommon/CryName.h b/Code/CryEngine/CryCommon/CryName.h deleted file mode 100644 index 966ed38c80..0000000000 --- a/Code/CryEngine/CryCommon/CryName.h +++ /dev/null @@ -1,563 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYNAME_H -#define CRYINCLUDE_CRYCOMMON_CRYNAME_H -#pragma once - -#include -#include -#include -#include -#include - -class CNameTable; - - -struct INameTable -{ - virtual ~INameTable(){} - - // Name entry header, immediately after this header in memory starts actual string data. - struct SNameEntry - { - enum - { - TAG = 0xdeadbeef - }; - - int nTag; // tag to ensure that this is actually a name entry - // Reference count of this string. - int nRefCount; - // Current length of string. - int nLength; - // Size of memory allocated at the end of this class. - int nAllocSize; - // Here in memory starts character buffer of size nAllocSize. - //char data[nAllocSize] - - const char* GetStr() { return (char*)(this + 1); } - void AddRef() { nRefCount++; /*InterlockedIncrement(&_header()->nRefCount);*/}; - int Release() { return --nRefCount; }; - int GetMemoryUsage() { return sizeof(SNameEntry) + strlen(GetStr()); } - int GetLength(){return nLength; } - }; - - - // Finds an existing name table entry, or creates a new one if not found. - virtual INameTable::SNameEntry* GetEntry(const char* str) = 0; - // Only finds an existing name table entry, return 0 if not found. - virtual INameTable::SNameEntry* FindEntry(const char* str) = 0; - // Release existing name table entry. - virtual void Release(SNameEntry* pEntry) = 0; - virtual int GetMemoryUsage() = 0; - virtual int GetNumberOfEntries() = 0; - - // Output all names from the table to log. - virtual void LogNames() = 0; - - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; -}; - -////////////////////////////////////////////////////////////////////////// -class CNameTable - : public INameTable -{ -private: - typedef AZStd::unordered_map, stl::equality_string_caseless > NameMap; - NameMap m_nameMap; - -public: - CNameTable() - { - // Ensure that SNameEntry is an aligned size - static_assert(sizeof(INameTable::SNameEntry) % sizeof(void*) == 0, "SNameEntry must be an aligned size"); - } - - ~CNameTable() - { - for (NameMap::iterator it = m_nameMap.begin(); it != m_nameMap.end(); ++it) - { - CryModuleFree(it->second); - } - } - - // Only finds an existing name table entry, return 0 if not found. - virtual INameTable::SNameEntry* FindEntry(const char* str) - { - SNameEntry* pEntry = stl::find_in_map(m_nameMap, str, 0); - return pEntry; - } - - // Finds an existing name table entry, or creates a new one if not found. - virtual INameTable::SNameEntry* GetEntry(const char* str) - { - SNameEntry* pEntry = FindEntry(str); - if (!pEntry) - { - // Create a new entry. - unsigned int nLen = strlen(str); - unsigned int allocLen = sizeof(SNameEntry) + (nLen + 1) * sizeof(char); - pEntry = (SNameEntry*)CryModuleMalloc(allocLen); - assert(pEntry != NULL); - pEntry->nTag = SNameEntry::TAG; - pEntry->nRefCount = 0; - pEntry->nLength = nLen; - pEntry->nAllocSize = allocLen; - // Copy string to the end of name entry. - char* pEntryStr = const_cast(pEntry->GetStr()); - memcpy(pEntryStr, str, nLen + 1); - // put in map. - //m_nameMap.insert( NameMap::value_type(pEntry->GetStr(),pEntry) ); - m_nameMap[pEntry->GetStr()] = pEntry; - } - return pEntry; - } - - // Release existing name table entry. - virtual void Release(SNameEntry* pEntry) - { - assert(pEntry); - m_nameMap.erase(pEntry->GetStr()); - CryModuleFree(pEntry); - } - virtual int GetMemoryUsage() - { - int nSize = 0; - NameMap::iterator it; - int n = 0; - for (it = m_nameMap.begin(); it != m_nameMap.end(); it++) - { - nSize += strlen(it->first); - nSize += it->second->GetMemoryUsage(); - n++; - } - nSize += n * 8; - - return nSize; - } - virtual void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - pSizer->AddContainer(m_nameMap); - } - virtual int GetNumberOfEntries() - { - return m_nameMap.size(); - } - - // Log all names inside CryName table. - virtual void LogNames() - { - NameMap::iterator it; - for (it = m_nameMap.begin(); it != m_nameMap.end(); ++it) - { - SNameEntry* pNameEntry = it->second; - CryLog("[%4d] %s", pNameEntry->nLength, pNameEntry->GetStr()); - } - } -}; - -/////////////////////////////////////////////////////////////////////////////// -// Class CCryName. -////////////////////////////////////////////////////////////////////////// -class CCryName -{ -public: - CCryName(); - CCryName(const CCryName& n); - explicit CCryName(const char* s); - CCryName(const char* s, bool bOnlyFind); - ~CCryName(); - - CCryName& operator=(const CCryName& n); - CCryName& operator=(const char* s); - - bool operator==(const CCryName& n) const; - bool operator!=(const CCryName& n) const; - - bool operator==(const char* s) const; - bool operator!=(const char* s) const; - - bool operator<(const CCryName& n) const; - bool operator>(const CCryName& n) const; - - bool empty() const { return !m_str || !m_str[0]; } - void reset() { _release(m_str); m_str = 0; } - void addref() { _addref(m_str); } - - const char* c_str() const - { - return (m_str) ? m_str : ""; - } - int length() const { return _length(); }; - - static bool find(const char* str) { return GetNameTable()->FindEntry(str) != 0; } - void GetMemoryUsage(ICrySizer* pSizer) const - { - //pSizer->AddObject(m_str); - pSizer->AddObject(GetNameTable()); // cause for slowness? - } - static int GetMemoryUsage() - { -#ifdef USE_STATIC_NAME_TABLE - CNameTable* pTable = GetNameTable(); -#else - INameTable* pTable = GetNameTable(); -#endif - return pTable->GetMemoryUsage(); - } - static int GetNumberOfEntries() - { -#ifdef USE_STATIC_NAME_TABLE - CNameTable* pTable = GetNameTable(); -#else - INameTable* pTable = GetNameTable(); -#endif - return pTable->GetNumberOfEntries(); - } - - // Compare functor for sorting CCryNames lexically. - struct CmpLex - { - bool operator () (const CCryName& n1, const CCryName& n2) const - { - return strcmp(n1.c_str(), n2.c_str()) < 0; - } - }; - -private: - typedef INameTable::SNameEntry SNameEntry; - -#ifdef USE_STATIC_NAME_TABLE - static CNameTable* GetNameTable() - { - // Note: can not use a 'static CNameTable sTable' here, because that - // implies a static destruction order depenency - the name table is - // accessed from static destructor calls. - static CNameTable* table = NULL; - - if (table == NULL) - { - table = new CNameTable(); - } - return table; - } -#else - //static INameTable* GetNameTable() { return GetISystem()->GetINameTable(); } - static INameTable* GetNameTable() - { - assert(gEnv && gEnv->pNameTable); - return gEnv->pNameTable; - } -#endif - - SNameEntry* _entry(const char* pBuffer) const - { - CRY_ASSERT(pBuffer); - CRY_ASSERT((((SNameEntry*)pBuffer) - 1)->nTag == SNameEntry::TAG); - return ((SNameEntry*)pBuffer) - 1; - } - void _release(const char* pBuffer) - { - if (pBuffer && _entry(pBuffer)->Release() <= 0 && gEnv) - { - GetNameTable()->Release(_entry(pBuffer)); - } - } - int _length() const { return (m_str) ? _entry(m_str)->nLength : 0; }; - void _addref(const char* pBuffer) - { - if (pBuffer) - { - _entry(pBuffer)->AddRef(); - } - } - - - const char* m_str; -}; - -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// CryName -////////////////////////////////////////////////////////////////////////// -inline CCryName::CCryName() -{ - m_str = 0; -} - -////////////////////////////////////////////////////////////////////////// -inline CCryName::CCryName(const CCryName& n) -{ - _addref(n.m_str); - m_str = n.m_str; -} - -////////////////////////////////////////////////////////////////////////// -inline CCryName::CCryName(const char* s) -{ - m_str = 0; - *this = s; -} - -////////////////////////////////////////////////////////////////////////// -inline CCryName::CCryName(const char* s, [[maybe_unused]] bool bOnlyFind) -{ - assert(s); - m_str = 0; - if (*s) // if not empty - { - SNameEntry* pNameEntry = GetNameTable()->FindEntry(s); - if (pNameEntry) - { - m_str = pNameEntry->GetStr(); - _addref(m_str); - } - } -} - -inline CCryName::~CCryName() -{ - _release(m_str); -} - -////////////////////////////////////////////////////////////////////////// -inline CCryName& CCryName::operator=(const CCryName& n) -{ - if (m_str != n.m_str) - { - _release(m_str); - m_str = n.m_str; - _addref(m_str); - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -inline CCryName& CCryName::operator=(const char* s) -{ - assert(s); - const char* pBuf = 0; - if (s && *s) // if not empty - { - pBuf = GetNameTable()->GetEntry(s)->GetStr(); - } - if (m_str != pBuf) - { - _release(m_str); - m_str = pBuf; - _addref(m_str); - } - return *this; -} - - -////////////////////////////////////////////////////////////////////////// -inline bool CCryName::operator==(const CCryName& n) const -{ - return m_str == n.m_str; -} - -inline bool CCryName::operator!=(const CCryName& n) const -{ - return !(*this == n); -} - -inline bool CCryName::operator==(const char* str) const -{ - return m_str && _stricmp(m_str, str) == 0; -} - -inline bool CCryName::operator!=(const char* str) const -{ - if (!m_str) - { - return true; - } - return _stricmp(m_str, str) != 0; -} - -inline bool CCryName::operator<(const CCryName& n) const -{ - return m_str < n.m_str; -} - -inline bool CCryName::operator>(const CCryName& n) const -{ - return m_str > n.m_str; -} - -inline bool operator==(const string& s, const CCryName& n) -{ - return n == s; -} -inline bool operator!=(const string& s, const CCryName& n) -{ - return n != s; -} - -inline bool operator==(const char* s, const CCryName& n) -{ - return n == s; -} -inline bool operator!=(const char* s, const CCryName& n) -{ - return n != s; -} - - -/////////////////////////////////////////////////////////////////////////////// -// Class CCryNameCRC. -////////////////////////////////////////////////////////////////////////// -class CCryNameCRC -{ -public: - CCryNameCRC(); - CCryNameCRC(const CCryNameCRC& n); - CCryNameCRC(const char* s); - CCryNameCRC(const char* s, bool bOnlyFind); - explicit CCryNameCRC(uint32 n) { m_nID = n; } // We use "explicit" to prevent comparison of strings with ints due to implicit conversion. - ~CCryNameCRC(); - - CCryNameCRC& operator=(const CCryNameCRC& n); - CCryNameCRC& operator=(const char* s); - - bool operator==(const CCryNameCRC& n) const; - bool operator!=(const CCryNameCRC& n) const; - - bool operator==(const char* s) const; - bool operator!=(const char* s) const; - - bool operator<(const CCryNameCRC& n) const; - bool operator>(const CCryNameCRC& n) const; - - bool empty() const { return m_nID == 0; } - void reset() { m_nID = 0; } - uint32 get() const { return m_nID; } - void add(int nAdd) { m_nID += nAdd; } - - AUTO_STRUCT_INFO - - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { /*nothing*/} -private: - - uint32 m_nID; -}; - -////////////////////////////////////////////////////////////////////////// -// CCryNameCRC -////////////////////////////////////////////////////////////////////////// -inline CCryNameCRC::CCryNameCRC() -{ - m_nID = 0; -} - -////////////////////////////////////////////////////////////////////////// -inline CCryNameCRC::CCryNameCRC(const CCryNameCRC& n) -{ - m_nID = n.m_nID; -} - -////////////////////////////////////////////////////////////////////////// -inline CCryNameCRC::CCryNameCRC(const char* s) -{ - m_nID = 0; - *this = s; -} - -inline CCryNameCRC::~CCryNameCRC() -{ - m_nID = 0; -} - -////////////////////////////////////////////////////////////////////////// -inline CCryNameCRC& CCryNameCRC::operator=(const CCryNameCRC& n) -{ - m_nID = n.m_nID; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -inline CCryNameCRC& CCryNameCRC::operator=(const char* s) -{ - assert(s); - if (*s) // if not empty - { - m_nID = CCrc32::ComputeLowercase(s); - } - return *this; -} - - -////////////////////////////////////////////////////////////////////////// -inline bool CCryNameCRC::operator==(const CCryNameCRC& n) const -{ - return m_nID == n.m_nID; -} - -inline bool CCryNameCRC::operator!=(const CCryNameCRC& n) const -{ - return !(*this == n); -} - -inline bool CCryNameCRC::operator==(const char* str) const -{ - assert(str); - if (*str) // if not empty - { - uint32 nID = CCrc32::ComputeLowercase(str); - return m_nID == nID; - } - return m_nID == 0; -} - -inline bool CCryNameCRC::operator!=(const char* str) const -{ - if (!m_nID) - { - return true; - } - if (*str) // if not empty - { - uint32 nID = CCrc32::ComputeLowercase(str); - return m_nID != nID; - } - return false; -} - -inline bool CCryNameCRC::operator<(const CCryNameCRC& n) const -{ - return m_nID < n.m_nID; -} - -inline bool CCryNameCRC::operator>(const CCryNameCRC& n) const -{ - return m_nID > n.m_nID; -} - -inline bool operator==(const string& s, const CCryNameCRC& n) -{ - return n == s; -} -inline bool operator!=(const string& s, const CCryNameCRC& n) -{ - return n != s; -} - -inline bool operator==(const char* s, const CCryNameCRC& n) -{ - return n == s; -} -inline bool operator!=(const char* s, const CCryNameCRC& n) -{ - return n != s; -} - -#endif // CRYINCLUDE_CRYCOMMON_CRYNAME_H diff --git a/Code/CryEngine/CryCommon/CryPath.h b/Code/CryEngine/CryCommon/CryPath.h deleted file mode 100644 index f3f64fe43d..0000000000 --- a/Code/CryEngine/CryCommon/CryPath.h +++ /dev/null @@ -1,618 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Defines namespace PathUtil for operations on files paths. - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYPATH_H -#define CRYINCLUDE_CRYCOMMON_CRYPATH_H -#pragma once - -#include -#include -#include - -#include "platform.h" - -#define UNIX_PATH_SEP_STR "/" -#define UNIX_PATH_SEP_CHR '/' -#define DOS_PATH_SEP_STR "\\" -#define DOS_PATH_SEP_CHR '\\' - -#if AZ_LEGACY_CRYCOMMON_TRAIT_USE_UNIX_PATHS -#define CRY_NATIVE_PATH_SEPSTR UNIX_PATH_SEP_STR -#else -#define CRY_NATIVE_PATH_SEPSTR DOS_PATH_SEP_STR -#endif - -namespace PathUtil -{ - const static int maxAliasLength = 32; - inline string GetLocalizationFolder() - { - return gEnv->pCryPak->GetLocalizationFolder(); - } - - inline string GetLocalizationRoot() - { - return gEnv->pCryPak->GetLocalizationRoot(); - } - - //! Convert a path to the uniform form. - inline string ToUnixPath(const string& strPath) - { - if (strPath.find(DOS_PATH_SEP_CHR) != string::npos) - { - string path = strPath; - path.replace(DOS_PATH_SEP_CHR, UNIX_PATH_SEP_CHR); - return path; - } - return strPath; - } - - //! Convert a path to the uniform form in place on stack - inline void ToUnixPath(stack_string& rConv) - { - const char* const cpEnd = &(rConv.c_str()[rConv.size()]); - char* __restrict pC = rConv.begin(); - while (pC != cpEnd) - { - char c = *pC; - if (c == DOS_PATH_SEP_CHR) - { - c = UNIX_PATH_SEP_CHR; - } - *pC++ = c; - } - } - - //! Convert a path to the DOS form. - inline string ToDosPath(const string& strPath) - { - if (strPath.find(UNIX_PATH_SEP_CHR) != string::npos) - { - string path = strPath; - path.replace(UNIX_PATH_SEP_CHR, DOS_PATH_SEP_CHR); - return path; - } - return strPath; - } - - //! Convert a path to the Native form. - inline string ToNativePath(const string& strPath) - { -#if AZ_LEGACY_CRYCOMMON_TRAIT_USE_UNIX_PATHS - return ToUnixPath(strPath); -#else - return ToDosPath(strPath); -#endif - } - - //! Convert a path to lowercase form - inline string ToLower(const string& strPath) - { - string path = strPath; - path.MakeLower(); - return path; - } - - - //! Split full file name to path and filename - //! @param filepath [IN] Full file name including path. - //! @param path [OUT] Extracted file path. - //! @param filename [OUT] Extracted file (without extension). - //! @param ext [OUT] Extracted files extension. - inline void Split(const string& filepath, string& path, string& filename, string& fext) - { - path = filename = fext = string(); - if (filepath.empty()) - { - return; - } - const char* str = filepath.c_str(); - const char* pext = str + filepath.length() - 1; - const char* p; - for (p = str + filepath.length() - 1; p >= str; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - path = filepath.substr(0, p - str + 1); - filename = filepath.substr(p - str + 1, pext - p); - return; - case '.': - // there's an extension in this file name - fext = filepath.substr(p - str + 1); - pext = p; - break; - } - } - filename = filepath.substr(p - str + 1, pext - p); - } - - //! Split full file name to path and filename - //! @param filepath [IN] Full file name inclusing path. - //! @param path [OUT] Extracted file path. - //! @param file [OUT] Extracted file (with extension). - inline void Split(const string& filepath, string& path, string& file) - { - string fext; - Split(filepath, path, file, fext); - file += fext; - } - - // Extract extension from full specified file path - // Returns - // pointer to the extension (without .) or pointer to an empty 0-terminated string - inline 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 ""; - } - - //! Extract path from full specified file path. - inline string GetPath(const string& filepath) - { - const char* str = filepath.c_str(); - for (const char* p = str + filepath.length() - 1; p >= str; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - return filepath.substr(0, p - str + 1); - } - } - return ""; - } - - //! Extract path from full specified file path. - inline string GetPath(const char* filepath) - { - return GetPath(string(filepath)); - } - - //! Extract path from full specified file path. - inline stack_string GetPath(const stack_string& filepath) - { - const char* str = filepath.c_str(); - for (const char* p = str + filepath.length() - 1; p >= str; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - return filepath.substr(0, p - str + 1); - } - } - return ""; - } - - //! Extract file name with extension from full specified file path. - inline string GetFile(const string& filepath) - { - const char* str = filepath.c_str(); - for (const char* p = str + filepath.length() - 1; p >= str; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - return filepath.substr(p - str + 1); - } - } - return filepath; - } - - inline 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. - inline void RemoveExtension(string& filepath) - { - const char* str = filepath.c_str(); - for (const char* p = str + filepath.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; - case '.': - // there's an extension in this file name - filepath = filepath.substr(0, p - str); - return; - } - } - // it seems the file name is a pure name, without path or extension - } - - //! Replace extension for given file. - inline void RemoveExtension(stack_string& filepath) - { - const char* str = filepath.c_str(); - for (const char* p = str + filepath.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; - case '.': - // there's an extension in this file name - filepath = filepath.substr(0, p - str); - return; - } - } - // it seems the file name is a pure name, without path or extension - } - - //! Extract file name without extension from full specified file path. - inline string GetFileName(const string& filepath) - { - string file = filepath; - RemoveExtension(file); - return GetFile(file); - } - - //! Removes the trailing slash or backslash from a given path. - inline string RemoveSlash(const string& path) - { - if (path.empty() || (path[path.length() - 1] != '/' && path[path.length() - 1] != '\\')) - { - return path; - } - return path.substr(0, path.length() - 1); - } - - //! get slash - inline string GetSlash() - { - return CRY_NATIVE_PATH_SEPSTR; - } - - //! add a backslash if needed - inline string AddSlash(const string& path) - { - if (path.empty() || path[path.length() - 1] == '/') - { - return path; - } - if (path[path.length() - 1] == '\\') - { - return path.substr(0, path.length() - 1) + "/"; - } - return path + "/"; - } - - //! add a backslash if needed - inline stack_string AddSlash(const stack_string& path) - { - if (path.empty() || path[path.length() - 1] == '/') - { - return path; - } - if (path[path.length() - 1] == '\\') - { - return path.substr(0, path.length() - 1) + "/"; - } - return path + "/"; - } - - //! add a backslash if needed - inline string AddSlash(const char* path) - { - return AddSlash(string(path)); - } - - inline stack_string ReplaceExtension(const stack_string& filepath, const char* ext) - { - stack_string str = filepath; - if (ext != 0) - { - RemoveExtension(str); - if (ext[0] != 0 && ext[0] != '.') - { - str += "."; - } - str += ext; - } - return str; - } - - //! Replace extension for given file. - inline string ReplaceExtension(const string& filepath, const char* ext) - { - string str = filepath; - if (ext != 0) - { - RemoveExtension(str); - if (ext[0] != 0 && ext[0] != '.') - { - str += "."; - } - str += ext; - } - return str; - } - - //! Replace extension for given file. - inline string ReplaceExtension(const char* filepath, const char* ext) - { - return ReplaceExtension(string(filepath), ext); - } - - //! Makes a fully specified file path from path and file name. - inline string Make(const string& path, const string& file) - { - return AddSlash(path) + file; - } - - //! Makes a fully specified file path from path and file name. - inline string Make(const string& dir, const string& filename, const string& ext) - { - string path = ReplaceExtension(filename, ext); - path = AddSlash(dir) + path; - return path; - } - - //! Makes a fully specified file path from path and file name. - inline string Make(const string& dir, const string& filename, const char* ext) - { - return Make(dir, filename, string(ext)); - } - - //! Makes a fully specified file path from path and file name. - inline stack_string Make(const stack_string& path, const stack_string& file) - { - return AddSlash(path) + file; - } - - //! Makes a fully specified file path from path and file name. - inline stack_string Make(const stack_string& dir, const stack_string& filename, const stack_string& ext) - { - stack_string path = ReplaceExtension(filename, ext); - path = AddSlash(dir) + path; - return path; - } - - //! Makes a fully specified file path from path and file name. - inline string Make(const char* path, const string& file) - { - return Make(string(path), file); - } - - //! Makes a fully specified file path from path and file name. - inline string Make(const string& path, const char* file) - { - return Make(path, string(file)); - } - - //! Makes a fully specified file path from path and file name. - inline string Make(const char path[], const char file[]) - { - return Make(string(path), string(file)); - } - - //! Makes a fully specified file path from path and file name. - inline string Make(const char* path, const char* file, const char* ext) - { - return Make(string(path), string(file), string(ext)); - } - - //! Makes a fully specified file path from path and file name. - inline string MakeFullPath(const string& relativePath) - { - return relativePath; - } - - inline string GetParentDirectory (const string& strFilePath, int nGeneration = 1) - { - for (const char* p = strFilePath.c_str() + strFilePath.length() - 2; // -2 is for the possible trailing slash: there always must be some trailing symbol which is the file/directory name for which we should get the parent - p >= strFilePath.c_str(); - --p) - { - switch (*p) - { - case ':': - return string (strFilePath.c_str(), p); - case '/': - case '\\': - // we've reached a path separator - return everything before it. - if (!--nGeneration) - { - return string(strFilePath.c_str(), p); - } - break; - } - } - // it seems the file name is a pure name, without path or extension - return string(); - } - - template - inline CryStackStringT GetParentDirectoryStackString(const CryStackStringT& strFilePath, int nGeneration = 1) - { - for (const char* p = strFilePath.c_str() + strFilePath.length() - 2; // -2 is for the possible trailing slash: there always must be some trailing symbol which is the file/directory name for which we should get the parent - p >= strFilePath.c_str(); - --p) - { - switch (*p) - { - case ':': - return CryStackStringT (strFilePath.c_str(), p); - case '/': - case '\\': - // we've reached a path separator - return everything before it. - if (!--nGeneration) - { - return CryStackStringT(strFilePath.c_str(), p); - } - break; - } - } - // it seems the file name is a pure name, without path or extension - return CryStackStringT(); - } - - ////////////////////////////////////////////////////////////////////////// - // Description: - // Make a game correct path out of any input path. - inline stack_string MakeGamePath(const stack_string& path) - { - stack_string relativePath(ToUnixPath(path)); - - if ((!gEnv) || (!gEnv->pFileIO)) - { - return relativePath; - } - unsigned int index = 0; - if (relativePath.length() && relativePath[index] == '@') // already aliased - { - if (relativePath.compareNoCase(0, 9, "@assets@/") == 0) - { - return relativePath.substr(9); // assets is assumed. - } - return relativePath; - } - - const char* rootValue = gEnv->pFileIO->GetAlias("@root@"); - if (rootValue) - { - stack_string rootPath(ToUnixPath(rootValue)); - if ( - (rootPath.size() > 0) && - (rootPath.size() < relativePath.size()) && - (relativePath.compareNoCase(0, rootPath.size(), rootPath) == 0) - ) - { - stack_string chopped_string = relativePath.substr(rootPath.size()); - stack_string rooted = stack_string("@root@") + chopped_string; - return rooted; - } - } - - - - return relativePath; - } - - ////////////////////////////////////////////////////////////////////////// - // Description: - // Make a game correct path out of any input path. - inline string MakeGamePath(const string& path) - { - stack_string stackPath(path.c_str()); - return MakeGamePath(stackPath).c_str(); - } - - // returns true if the string matches the wildcard - inline bool MatchWildcard (const char* szString, const char* szWildcard) - { - const char* pString = szString, * pWildcard = szWildcard; - // skip the obviously the same starting substring - while (*pWildcard && *pWildcard != '*' && *pWildcard != '?') - { - if (*pString != *pWildcard) - { - return false; // must be exact match unless there's a wildcard character in the wildcard string - } - else - { - ++pString, ++pWildcard; - } - } - - if (!*pString) - { - // this will only match if there are no non-wild characters in the wildcard - for (; *pWildcard; ++pWildcard) - { - if (*pWildcard != '*' && *pWildcard != '?') - { - return false; - } - } - return true; - } - - switch (*pWildcard) - { - case '\0': - return false; // the only way to match them after the leading non-wildcard characters is !*pString, which was already checked - - // we have a wildcard with wild character at the start. - case '*': - { - // merge consecutive ? and *, since they are equivalent to a single * - while (*pWildcard == '*' || *pWildcard == '?') - { - ++pWildcard; - } - - if (!*pWildcard) - { - return true; // the rest of the string doesn't matter: the wildcard ends with * - } - for (; *pString; ++pString) - { - if (MatchWildcard(pString, pWildcard)) - { - return true; - } - } - - return false; - } - case '?': - return MatchWildcard(pString + 1, pWildcard + 1) || MatchWildcard(pString, pWildcard + 1); - default: - assert (0); - return false; - } - } -}; - -#endif // CRYINCLUDE_CRYCOMMON_CRYPATH_H diff --git a/Code/CryEngine/CryCommon/CryPodArray.h b/Code/CryEngine/CryCommon/CryPodArray.h deleted file mode 100644 index 17198b2437..0000000000 --- a/Code/CryEngine/CryCommon/CryPodArray.h +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Simple POD types container - -#ifndef CRYINCLUDE_CRYCOMMON_CRYPODARRAY_H -#define CRYINCLUDE_CRYCOMMON_CRYPODARRAY_H -#pragma once - -#include - -////////////////////////////////////////////////////////////////////////// -// POD Array -// vector like class (random access O(1)) without construction/destructor/copy constructor/assignment handling -// over-allocation allows safe prefetching where required without worrying about memory page boundaries -////////////////////////////////////////////////////////////////////////// -template -class PodArray -{ - AZStd::vector m_elements; - -public: - typedef T value_type; - typedef T* iterator; - typedef const T* const_iterator; - - ////////////////////////////////////////////////////////////////////////// - // STL compatible interface - ////////////////////////////////////////////////////////////////////////// - void resize(size_t numElements) - { - m_elements.resize(numElements); - } - ////////////////////////////////////////////////////////////////////////// - ILINE void reserve(unsigned numElements) { m_elements.reserve(numElements); } - ILINE void push_back(const T& rElement) { m_elements.push_back(rElement); } - ILINE size_t size() const { return m_elements.size(); } - ILINE size_t capacity() const { return m_elements.capacity(); } - - ILINE void clear() { m_elements.clear(); } - ILINE T* begin() { return m_elements.begin(); } - ILINE T* end() { return m_elements.end(); } - ILINE const T* begin() const { return m_elements.begin(); } - ILINE const T* end() const { return m_elements.end(); } - ILINE bool empty() const { return m_elements.empty(); } - - ILINE const T& front() const { return m_elements.front(); } - ILINE T& front() { return m_elements.front(); } - - ILINE const T& back() const { return m_elements.back(); } - ILINE T& back() { return m_elements.back(); } - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - PodArray() - : m_elements() - { - } - PodArray(int elem_count, int nNewCount = 0) - { - m_elements.reserve(elem_count); - m_elements.resize(nNewCount); - } - PodArray(const PodArray& from) - : m_elements(from.m_elements) - { - } - ~PodArray() - { - } - - void Reset() { m_elements.clear(); } - void Free() - { - m_elements.clear(); - m_elements.shrink_to_fit(); - } - - ILINE void Clear() - { - m_elements.clear(); - } - - int Find(const T& p) - { - const auto it = AZStd::find(m_elements.begin(), m_elements.end(), p); - if (it != m_elements.end()) - { - return static_cast(AZStd::distance(m_elements.begin(), it)); - } - return -1; - } - - inline void AddList(const PodArray& lstAnother) - { - AZStd::copy(lstAnother.m_elements.begin(), lstAnother.m_elements.end(), AZStd::back_inserter(m_elements)); - } - - inline void AddList(T* pAnotherArray, int nAnotherCount) - { - AZStd::copy(pAnotherArray, pAnotherArray + nAnotherCount, AZStd::back_inserter(m_elements)); - } - - ILINE void Add(const T& p) - { - m_elements.push_back(p); - } - - ILINE T& AddNew() - { - m_elements.emplace_back(); - return m_elements.back(); - } - - void InsertBefore(const T& p, const unsigned int nBefore) - { - m_elements.insert(m_elements.begin() + nBefore, p); - } - - void CheckAllocated(int elem_count) - { - if (m_elements.size() < elem_count) - { - m_elements.resize(elem_count); - } - } - - void PreAllocate(int elem_count, int nNewCount = -1) - { - m_elements.reserve(elem_count); - if (nNewCount >= 0) - { - m_elements.resize(nNewCount); - } - } - - inline void Delete(const int nElemId, const int nElemCount = 1) - { - AZ_Assert(nElemId >= 0 && nElemId + nElemCount <= size(), "Index out of bounds"); - m_elements.erase(m_elements.begin() + nElemId, m_elements.begin() + nElemId + nElemCount); - } - - inline void DeleteFastUnsorted(const int nElemId, const int nElemCount = 1) - { - AZ_Assert(nElemId >= 0 && nElemId + nElemCount <= size(), "Index out of bounds"); - m_elements.erase(m_elements.begin() + nElemId, m_elements.begin() + nElemId + nElemCount); - } - - inline bool Delete(const T& del) - { - const size_t numElements = m_elements.size(); - m_elements.erase(std::remove(m_elements.begin(), m_elements.end(), del), m_elements.end()); - return numElements != m_elements.size(); - } - - ILINE int Count() const { return m_elements.size(); } - ILINE unsigned int Size() const { return m_elements.size(); } - - ILINE int IsEmpty() const { return m_elements.empty(); } - - ILINE const T& operator [] (int i) const { return m_elements[i]; } - ILINE T& operator [] (int i) { return m_elements[i]; } - ILINE const T& GetAt(int i) const { return m_elements[i]; } - ILINE T& GetAt(int i) { return m_elements[i]; } - ILINE const T* Get(int i) const { return &m_elements[i]; } - ILINE T* Get(int i) { return &m_elements[i]; } - ILINE const T* GetElements() const { return m_elements.data(); } - ILINE T* GetElements() { return m_elements.data(); } - - ILINE unsigned int GetDataSize() const { return m_elements.size() * sizeof(T); } - - const T& Last() const { return m_elements.back(); } - T& Last() { return m_elements.back(); } - - ILINE void DeleteLast() - { - assert(!m_elements.empty()); - m_elements.pop_back(); - } - - PodArray& operator=(const PodArray& source_list) - { - m_elements = source_list.m_elements; - return *this; - } - - ////////////////////////////////////////////////////////////////////////// - // Return true if arrays have the same data. - bool Compare(const PodArray& l) const - { - return m_elements == l.m_elements; - } - - // for statistics - ILINE size_t ComputeSizeInMemory() const - { - return (sizeof(*this) + sizeof(T) * m_elements.capacity()) + overAllocBytes; - } - - ILINE void RemoveIf(AZStd::function testFunc) - { - m_elements.erase(AZStd::remove_if(m_elements.begin(), m_elements.end(), testFunc), m_elements.end()); - } -}; - -#endif // CRYINCLUDE_CRYCOMMON_CRYPODARRAY_H diff --git a/Code/CryEngine/CryCommon/CryRandomInternal.h b/Code/CryEngine/CryCommon/CryRandomInternal.h deleted file mode 100644 index 48441cdba8..0000000000 --- a/Code/CryEngine/CryCommon/CryRandomInternal.h +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include // std::swap() -#include // std::numeric_limits -#include // std::make_unsigned -#include "BaseTypes.h" // uint32, uint64 -#include "CompileTimeAssert.h" -#include "Cry_Vector2.h" -#include "Cry_Vector3.h" -#include "Cry_Vector4.h" - - -namespace CryRandom_Internal -{ - template - struct BoundedRandomUint - { - COMPILE_TIME_ASSERT(std::numeric_limits::is_integer); - COMPILE_TIME_ASSERT(!std::numeric_limits::is_signed); - COMPILE_TIME_ASSERT(sizeof(T) == size); - COMPILE_TIME_ASSERT(sizeof(T) <= sizeof(uint32)); - - inline static T Get(R& randomGenerator, const T maxValue) - { - const uint32 r = randomGenerator.GenerateUint32(); - // Note that the computation below is biased. An alternative computation - // (also biased): uint32((uint64)r * ((uint64)maxValue + 1)) >> 32) - return (T)((uint64)r % ((uint64)maxValue + 1)); - } - }; - - template - struct BoundedRandomUint - { - COMPILE_TIME_ASSERT(std::numeric_limits::is_integer); - COMPILE_TIME_ASSERT(!std::numeric_limits::is_signed); - COMPILE_TIME_ASSERT(sizeof(T) == sizeof(uint64)); - - inline static T Get(R& randomGenerator, const T maxValue) - { - const uint64 r = randomGenerator.GenerateUint64(); - if (maxValue >= (std::numeric_limits::max)()) - { - return r; - } - // Note that the computation below is biased. - return (T)(r % ((uint64)maxValue + 1)); - } - }; - - ////////////////////////////////////////////////////////////////////////// - - template ::is_integer> - struct BoundedRandom; - - template - struct BoundedRandom - { - COMPILE_TIME_ASSERT(std::numeric_limits::is_integer); - typedef typename std::make_unsigned::type UT; - COMPILE_TIME_ASSERT(sizeof(T) == sizeof(UT)); - COMPILE_TIME_ASSERT(std::numeric_limits::is_integer); - COMPILE_TIME_ASSERT(!std::numeric_limits::is_signed); - - inline static T Get(R& randomGenerator, T minValue, T maxValue) - { - if (minValue > maxValue) - { - std::swap(minValue, maxValue); - } - return (T)((UT)minValue + (UT)BoundedRandomUint::Get(randomGenerator, (UT)(maxValue - minValue))); - } - }; - - template - struct BoundedRandom - { - COMPILE_TIME_ASSERT(!std::numeric_limits::is_integer); - - inline static T Get(R& randomGenerator, const T minValue, const T maxValue) - { - return minValue + (maxValue - minValue) * randomGenerator.GenerateFloat(); - } - }; - - ////////////////////////////////////////////////////////////////////////// - - template - struct BoundedRandomComponentwise; - - template - struct BoundedRandomComponentwise - { - inline static VT Get(R& randomGenerator, const VT& minValue, const VT& maxValue) - { - const T x = BoundedRandom::Get(randomGenerator, minValue.x, maxValue.x); - const T y = BoundedRandom::Get(randomGenerator, minValue.y, maxValue.y); - return VT(x, y); - } - }; - - template - struct BoundedRandomComponentwise - { - inline static VT Get(R& randomGenerator, const VT& minValue, const VT& maxValue) - { - const T x = BoundedRandom::Get(randomGenerator, minValue.x, maxValue.x); - const T y = BoundedRandom::Get(randomGenerator, minValue.y, maxValue.y); - const T z = BoundedRandom::Get(randomGenerator, minValue.z, maxValue.z); - return VT(x, y, z); - } - }; - - template - struct BoundedRandomComponentwise - { - inline static VT Get(R& randomGenerator, const VT& minValue, const VT& maxValue) - { - const T x = BoundedRandom::Get(randomGenerator, minValue.x, maxValue.x); - const T y = BoundedRandom::Get(randomGenerator, minValue.y, maxValue.y); - const T z = BoundedRandom::Get(randomGenerator, minValue.z, maxValue.z); - const T w = BoundedRandom::Get(randomGenerator, minValue.w, maxValue.w); - return VT(x, y, z, w); - } - }; - - ////////////////////////////////////////////////////////////////////////// - - template - inline VT GetRandomUnitVector(R& randomGenerator) - { - typedef typename VT::value_type T; - COMPILE_TIME_ASSERT(!std::numeric_limits::is_integer); - - VT res; - T lenSquared; - - do - { - res = BoundedRandomComponentwise::Get(randomGenerator, VT(-1), VT(1)); - lenSquared = res.GetLengthSquared(); - } while (lenSquared > 1); - - if (lenSquared >= (std::numeric_limits::min)()) - { - return res * isqrt_tpl(lenSquared); - } - - res = VT(ZERO); - res.x = 1; - return res; - } -} // namespace CryRandom_Internal - -// eof diff --git a/Code/CryEngine/CryCommon/CrySizer.h b/Code/CryEngine/CryCommon/CrySizer.h deleted file mode 100644 index be8bd71460..0000000000 --- a/Code/CryEngine/CryCommon/CrySizer.h +++ /dev/null @@ -1,586 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Declaration and definition of the CrySizer class, which is used to -// calculate the memory usage by the subsystems and components, to help -// the artists keep the memory budged low. - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYSIZER_H -#define CRYINCLUDE_CRYCOMMON_CRYSIZER_H -#pragma once - - -////////////////////////////////////////////////////////////////////////// - -// common containers for overloads -#include - -#include "Cry_Math.h" -#include -#include -#include -#include -#include -#include -#include - -// forward declarations for overloads -struct AABB; -struct SVF_P3F; -struct SVF_P3F_C4B_T2F; -struct SVF_P3F_C4B_T2S; -struct SVF_P3S_C4B_T2S; -struct SPipTangents; - -#ifdef WIN64 -#include // workaround for Amd64 compiler -#endif - -namespace AZ -{ - class Vector3; -} - -// flags applicable to the ICrySizer (retrieved via getFlags() method) -// -enum ICrySizerFlagsEnum -{ - // if this flag is set, during getSize(), the subsystem must count all the objects - // it uses in the other subsystems also - CSF_RecurseSubsystems = 1 << 0, - - CSF_Reserved1 = 1 << 1, - CSF_Reserved2 = 1 << 2 -}; - -////////////////////////////////////////////////////////////////////////// -// Helper functions to calculate size of the std containers. -////////////////////////////////////////////////////////////////////////// -namespace stl -{ - template - inline size_t size_of_map(const Map& m) - { - if (!m.empty()) - { - return m.size() * sizeof(typename Map::value_type) + m.size() * sizeof(MapLikeStruct); - } - return 0; - } - template - inline size_t size_of_set(const Map& m) - { - if (!m.empty()) - { - return m.size() * sizeof(typename Map::value_type) + m.size() * sizeof(MapLikeStruct); - } - return 0; - } - template - inline size_t size_of_list(const List& c) - { - if (!c.empty()) - { - return c.size() * sizeof(typename List::value_type) + c.size() * sizeof(void*) * 2; // sizeof stored type + 2 pointers prev,next - } - return 0; - } - template - inline size_t size_of_deque(const Deque& c) - { - if (!c.empty()) - { - return c.size() * sizeof(typename Deque::value_type); - } - return 0; - } -}; - -////////////////////////////////////////////////////////////////////////// -// interface ICrySizer -// USAGE -// An instance of this class is passed down to each and every component in the system. -// Every component it's passed to optionally pushes its name on top of the -// component name stack (thus ensuring that all the components calculated down -// the tree will be assigned the correct subsystem/component name) -// Every component must Add its size with one of the Add* functions, and Add the -// size of all its subcomponents recursively -// In order to push the component/system name on the name stack, the clients must -// use the SIZER_COMPONENT_NAME macro or CrySizerComponentNameHelper class: -// -// void X::getSize (ICrySizer* pSizer) -// { -// SIZER_COMPONENT_NAME(pSizer, X); -// if (!pSizer->Add (this)) -// return; -// pSizer->Add (m_arrMySimpleArray); -// pSizer->Add (m_setMySimpleSet); -// m_pSubobject->getSize (pSizer); -// } -// -// The Add* functions return bool. If they return true, then the object has been added -// to the set for the first time, and you should go on recursively adding all its children. -// If it returns false, then you can spare time and rather not go on into recursion; -// however it doesn't reflect on the results: an object that's added more than once is -// counted only once. -// -// WARNING: -// If you have an array (pointer), you should Add its size with addArray -class ICrySizer -{ -public: - virtual ~ICrySizer(){} - // this class is used to push/pop the name to/from the stack automatically - // (to exclude stack overruns or underruns at runtime) - friend class CrySizerComponentNameHelper; - - virtual void Release() = 0; - - // Return total calculated size. - virtual size_t GetTotalSize() = 0; - - // Return total objects added. - virtual size_t GetObjectCount() = 0; - - // Resets the counting. - virtual void Reset() = 0; - - virtual void End() = 0; - - // adds an object identified by the unique pointer (it needs not be - // the actual object position in the memory, though it would be nice, - // but it must be unique throughout the system and unchanging for this object) - // nCount parameter is only used for counting number of objects, it doesnt affect the size of the object. - // RETURNS: true if the object has actually been added (for the first time) - // and calculated - virtual bool AddObject (const void* pIdentifier, size_t nSizeBytes, int nCount = 1) = 0; - - template - bool AddObjectSize(const Type* pObj) - { - return AddObject(pObj, sizeof *pObj); - } - - //////////////////////////////////////////////////////////////////////////////////////// - // temp dummy function while checking in the CrySizer changes, will be removed soon - - template - void AddObject(const Type& rObj) - { - (void)rObj; - } - - template - void AddObject(Type* pObj) - { - if (pObj) - { - //forward to reference object to allow function overload - this->AddObject(*pObj); - } - } - - // overloads for smart_ptr and other common objects - template - void AddObject(const _smart_ptr& rObj) { this->AddObject(rObj.get()); } - template - void AddObject(const AZStd::shared_ptr& rObj) { this->AddObject(rObj.get()); } - template - void AddObject(const std::shared_ptr& rObj) { this->AddObject(rObj.get()); } - template - void AddObject(const std::unique_ptr& rObj) { this->AddObject(rObj.get()); } - template - void AddObject(const std::pair& rPair) - { - this->AddObject(rPair.first); - this->AddObject(rPair.second); - } - template - void AddObject(const AZStd::pair& rPair) - { - this->AddObject(rPair.first); - this->AddObject(rPair.second); - } - void AddObject(const string& rString) {this->AddObject(rString.c_str(), rString.capacity()); } - void AddObject(const CryStringT& rString) {this->AddObject(rString.c_str(), rString.capacity()); } - void AddObject(const CryFixedStringT<32>&){} - void AddObject(const wchar_t&) {} - void AddObject(const char&) {} - void AddObject(const unsigned char&) {} - void AddObject(const signed char&) {} - void AddObject(const short&) {} - void AddObject(const unsigned short&) {} - void AddObject(const int&) {} - void AddObject(const unsigned int&) {} - void AddObject(const long&) {} - void AddObject(const unsigned long&) {} - void AddObject(const float&) {} - void AddObject(const bool&) {} - void AddObject(const unsigned long long&) {} - void AddObject(const long long&) {} - void AddObject(const double&) {} - void AddObject(const Vec2&) {} - void AddObject(const Vec3&) {} - void AddObject(const Vec4&) {} - void AddObject(const Ang3&) {} - void AddObject(const Matrix34&) {} - void AddObject(const Quat&) {} - void AddObject(const QuatT&) {} - void AddObject(const QuatTS&) {} - void AddObject(const ColorF&) {} - void AddObject(const AABB&) {} - void AddObject(const SVF_P3F&) {} - void AddObject(const SVF_P3F_C4B_T2F&) {} - void AddObject(const SVF_P3F_C4B_T2S&) {} - void AddObject(const SVF_P3S_C4B_T2S&) {} - void AddObject(const SPipTangents&) {} - void AddObject([[maybe_unused]] const AZ::Vector3& rObj) {} - void AddObject(void*) {} - - // overloads for container, will automaticly traverse the content - template - void AddObject(const std::list& rList) - { - // dummy struct to get correct element size - struct Dummy - { - void* a; - void* b; - T t; - }; - - for (typename std::list::const_iterator it = rList.begin(); it != rList.end(); ++it) - { - if (this->AddObject(&(*it), sizeof(Dummy))) - { - this->AddObject(*it); - } - } - } - template - void AddObject([[maybe_unused]] const AZStd::unordered_map& rVector) - { - - } - - template - void AddObject(const std::vector& rVector) - { - if (rVector.empty()) - { - this->AddObject(&rVector, rVector.capacity() * sizeof(T)); - return; - } - - if (!this->AddObject(&rVector[0], rVector.capacity() * sizeof(T))) - { - return; - } - - for (typename std::vector::const_iterator it = rVector.begin(); it != rVector.end(); ++it) - { - this->AddObject(*it); - } - } - - template - void AddObject(const std::deque& rVector) - { - for (typename std::deque::const_iterator it = rVector.begin(); it != rVector.end(); ++it) - { - if (this->AddObject(&(*it), sizeof(T))) - { - this->AddObject(*it); - } - } - } - - template - void AddObject(const DynArray& rVector) - { - if (rVector.empty()) - { - this->AddObject(rVector.begin(), rVector.get_alloc_size()); - return; - } - - if (!this->AddObject(rVector.begin(), rVector.get_alloc_size())) - { - return; - } - - for (typename DynArray::const_iterator it = rVector.begin(); it != rVector.end(); ++it) - { - this->AddObject(*it); - } - } - - template - void AddObject(const PodArray& rVector) - { - if (!this->AddObject(rVector.begin(), rVector.capacity() * sizeof(T))) - { - return; - } - - for (typename PodArray::const_iterator it = rVector.begin(); it != rVector.end(); ++it) - { - this->AddObject(*it); - } - } - - template - void AddObject(const std::map& rVector) - { - // dummy struct to get correct element size - struct Dummy - { - void* a; - void* b; - void* c; - void* d; - K k; - T t; - }; - - for (typename std::map::const_iterator it = rVector.begin(); it != rVector.end(); ++it) - { - if (this->AddObject(&(*it), sizeof(Dummy))) - { - this->AddObject(it->first); - this->AddObject(it->second); - } - } - } - - template - void AddObject(const std::set& rVector) - { - // dummy struct to get correct element size - struct Dummy - { - void* a; - void* b; - void* c; - void* d; - T t; - }; - - for (typename std::set::const_iterator it = rVector.begin(); it != rVector.end(); ++it) - { - if (this->AddObject(&(*it), sizeof(Dummy))) - { - this->AddObject(*it); - } - } - } - - template - void AddObject (const std::multimap& rContainer) - { - AddContainer(rContainer); - } - //////////////////////////////////////////////////////////////////////////////////////// - template - bool Add (const T* pId, size_t num) - { - return AddObject(pId, num * sizeof(T)); - } - - template - bool Add (const T& rObject) - { - return AddObject (&rObject, sizeof(T)); - } - - bool Add (const char* szText) - { - return AddObject(szText, strlen(szText) + 1); - } - - template - bool AddString (const StringCls& strText) - { - if (!strText.empty()) - { - return AddObject (strText.c_str(), strText.size()); - } - else - { - return false; - } - } -#ifdef _XSTRING_ - template - bool Add (const std::basic_string& strText) - { - AddString (strText); - return true; - } -#endif - - #ifndef NOT_USE_CRY_STRING - bool Add (const string& strText) - { - AddString(strText); - return true; - } - #endif - - - // Template helper function to add generic stl container - template - bool AddContainer (const Container& rContainer) - { - if (rContainer.capacity()) - { - return AddObject (&rContainer, rContainer.capacity() * sizeof(typename Container::value_type)); - } - return false; - } - template - bool AddHashMap(const Container& rContainer) - { - if (!rContainer.empty()) - { - return AddObject (&(*rContainer.begin()), rContainer.size() * sizeof(typename Container::value_type)); - } - return false; - } - - // Specialization of the AddContainer for the std::list - template - bool AddContainer (const std::list& rContainer) - { - if (!rContainer.empty()) - { - return AddObject(&(*rContainer.begin()), stl::size_of_list(rContainer)); - } - return false; - } - // Specialization of the AddContainer for the std::deque - template - bool AddContainer (const std::deque& rContainer) - { - if (!rContainer.empty()) - { - return AddObject(&(*rContainer.begin()), stl::size_of_deque(rContainer)); - } - return false; - } - // Specialization of the AddContainer for the std::map - template - bool AddContainer (const std::map& rContainer) - { - if (!rContainer.empty()) - { - return AddObject(&(*rContainer.begin()), stl::size_of_map(rContainer)); - } - return false; - } - // Specialization of the AddContainer for the std::multimap - template - bool AddContainer (const std::multimap& rContainer) - { - if (!rContainer.empty()) - { - return AddObject(&(*rContainer.begin()), stl::size_of_map(rContainer)); - } - return false; - } - // Specialization of the AddContainer for the std::set - template - bool AddContainer (const std::set& rContainer) - { - if (!rContainer.empty()) - { - return AddObject(&(*rContainer.begin()), stl::size_of_set(rContainer)); - } - return false; - } - - // Specialization of the AddContainer for the AZStd::unordered_map - template - bool AddContainer(const AZStd::unordered_map& rContainer) - { - if (!rContainer.empty()) - { - return AddObject(&(*rContainer.begin()), rContainer.size() * sizeof(typename AZStd::unordered_map::value_type)); - } - else - { - return false; - } - } - - void Test() - { - std::map mymap; - AddContainer(mymap); - } - - // returns the flags - unsigned GetFlags() const {return m_nFlags; } - -protected: - // these functions must operate on the component name stack - // they are to be only accessible from within class CrySizerComponentNameHelper - // which should be used through macro SIZER_COMPONENT_NAME - virtual void Push (const char* szComponentName) = 0; - // pushes the name that is the name of the previous component . (dot) this name - virtual void PushSubcomponent (const char* szSubcomponentName) = 0; - virtual void Pop () = 0; - - unsigned m_nFlags; -}; - -////////////////////////////////////////////////////////////////////////// -// This is on-stack class that is only used to push/pop component names -// to/from the sizer name stack. -// -// USAGE: -// -// Create an instance of this class at the start of a function, before -// calling Add* methods of the sizer interface. Everything added in the -// function and below will be considered this component, unless -// explicitly set otherwise. -// -class CrySizerComponentNameHelper -{ -public: - // pushes the component name on top of the name stack of the given sizer - CrySizerComponentNameHelper (ICrySizer* pSizer, const char* szComponentName, bool bSubcomponent) - : m_pSizer(pSizer) - { - if (bSubcomponent) - { - pSizer->PushSubcomponent (szComponentName); - } - else - { - pSizer->Push (szComponentName); - } - } - - // pops the component name off top of the name stack of the sizer - ~CrySizerComponentNameHelper() - { - m_pSizer->Pop(); - } - -protected: - ICrySizer* m_pSizer; -}; - -// use this to push (and automatically pop) the sizer component name at the beginning of the -// getSize() function -#define SIZER_COMPONENT_NAME(pSizerPointer, szComponentName) PREFAST_SUPPRESS_WARNING(6246) CrySizerComponentNameHelper AZ_JOIN(sizerHelper, __LINE__)(pSizerPointer, szComponentName, false) -#define SIZER_SUBCOMPONENT_NAME(pSizerPointer, szComponentName) PREFAST_SUPPRESS_WARNING(6246) CrySizerComponentNameHelper AZ_JOIN(sizerHelper, __LINE__)(pSizerPointer, szComponentName, true) - -#endif // CRYINCLUDE_CRYCOMMON_CRYSIZER_H diff --git a/Code/CryEngine/CryCommon/CryString.h b/Code/CryEngine/CryCommon/CryString.h deleted file mode 100644 index 1a6487e373..0000000000 --- a/Code/CryEngine/CryCommon/CryString.h +++ /dev/null @@ -1,2522 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Custom reference counted string class. -// Can easily be substituted instead of string - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYSTRING_H -#define CRYINCLUDE_CRYCOMMON_CRYSTRING_H -#pragma once - -#include -#include - -#if !defined(NOT_USE_CRY_STRING) - -#include -#include -#include -#include -#include -#include "LegacyAllocator.h" - -#define CRY_STRING - -// forward declaration of CryStackString -template -class CryStackStringT; - - -class CConstCharWrapper; //forward declaration for special const char * without memory allocations - -//extern void CryDebugStr( const char *format,... ); -//#define CRY_STRING_DEBUG(s) { if (*s) CryDebugStr( "[%6d] %s",_usedMemory(0),(s) );} -#define CRY_STRING_DEBUG(s) - -class CryStringAllocator - : public AZ::SimpleSchemaAllocator -{ -public: - AZ_TYPE_INFO(CryStringAllocator, "{763DFC83-8A6E-4FD9-B6BC-BBF56E93E4EE}"); - - using Base = AZ::SimpleSchemaAllocator; - using Descriptor = Base::Descriptor; - - CryStringAllocator() - : Base("CryStringAllocator", "Allocator for CryString") - { - Descriptor desc; - desc.m_systemChunkSize = 4 * 1024 * 1024; // grow by 4 MB at a time - desc.m_subAllocator = &AZ::AllocatorInstance::Get(); - Create(desc); - } -}; - -////////////////////////////////////////////////////////////////////////// -// CryStringT class. -////////////////////////////////////////////////////////////////////////// -template -class CryStringT -{ -public: - ////////////////////////////////////////////////////////////////////////// - // Types compatible with STL string. - ////////////////////////////////////////////////////////////////////////// - typedef CryStringT _Self; - typedef size_t size_type; - typedef T value_type; - typedef const value_type* const_str; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef pointer iterator; - typedef const_pointer const_iterator; - - enum _npos_type - { - npos = (size_type) ~0 - }; - - ////////////////////////////////////////////////////////////////////////// - // Constructors - ////////////////////////////////////////////////////////////////////////// - CryStringT(); - -protected: - CryStringT(const CConstCharWrapper& str); //ctor for strings without memory allocations - friend class CConstCharWrapper; -public: - - CryStringT(const _Self& str); - CryStringT(const _Self& str, size_type nOff, size_type nCount); - - // Before September 2012 this constructor looked like this: - // explicit CryStringT( value_type ch, size_type nRepeat = 1 ); - // It was very error-prone, because the matching constructor - // std::string constructor is different: - // std::string( size_type nRepeat, value_type ch ); - // - // To prevent hard-to-catch bugs, we removed all calls of this - // constructor in the existing CryEngine code (in September 2012) - // and started using proper order of parameters (matching std::). - // - // To catch calls using the reversed arguments in other projects, - // we retain the previous function with reversed arguments, - // and declare it private. - CryStringT(size_type nRepeat, value_type ch); -private: - CryStringT(value_type ch, size_type nRepeat); - -public: - - CryStringT(const_str str); - CryStringT(const_str str, size_type nLength); - CryStringT(const_iterator _First, const_iterator _Last); - ~CryStringT(); - - ////////////////////////////////////////////////////////////////////////// - // STL string like interface. - ////////////////////////////////////////////////////////////////////////// - //! Operators. - size_type length() const; - size_type size() const; - bool empty() const; - void clear(); // free up the data - - //! Returns the storage currently allocated to hold the string, a value at least as large as length(). - size_type capacity() const; - - // Sets the capacity of the string to a number at least as great as a specified number. - // nCount = 0 is shrinking string to fit number of characters in it. - void reserve(size_type nCount = 0); - - _Self& append(const value_type* _Ptr); - _Self& append(const value_type* _Ptr, size_type nCount); - _Self& append(const _Self& _Str, size_type nOff, size_type nCount); - _Self& append(const _Self& _Str); - _Self& append(size_type nCount, value_type _Ch); - _Self& append(const_iterator _First, const_iterator _Last); - - _Self& assign(const_str _Ptr); - _Self& assign(const_str _Ptr, size_type nCount); - _Self& assign(const _Self& _Str, size_type off, size_type nCount); - _Self& assign(const _Self& _Str); - _Self& assign(size_type nCount, value_type _Ch); - _Self& assign(const_iterator _First, const_iterator _Last); - - value_type at(size_type index) const; - - const_iterator begin() const { return m_str; }; - const_iterator end() const { return m_str + length(); }; - - iterator begin() { return m_str; }; - iterator end() { return m_str + length(); }; - - // Following functions are commented out because they provide direct write access to - // the string and such access doesn't work properly with our current reference-count - // implementation. - // If you really need write access to your string's elements, please consider - // using CryStackStringT<> instead of CryString<>. Alternatively, you can modify - // your string by multiple calls of erase() and append(). - // Note: If you need *linear memory read* access to your string's elements, use data() - // or c_str(). If you need *linear memory write* access to your string's elements, - // use a non-string class (std::vector<>, DynArray<>, etc.) instead of CryString<>. - //value_type& at( size_type index ); - //iterator begin() { return m_str; }; - //iterator end() { return m_str+length(); }; - - //! cast to C string operator. - operator const_str() const { - return m_str; - } - - //! cast to C string. - const value_type* c_str() const { return m_str; } - const value_type* data() const { return m_str; }; - - ////////////////////////////////////////////////////////////////////////// - // string comparison. - ////////////////////////////////////////////////////////////////////////// - int compare(const _Self& _Str) const; - int compare(size_type _Pos1, size_type _Num1, const _Self& _Str) const; - int compare(size_type _Pos1, size_type _Num1, const _Self& _Str, size_type nOff, size_type nCount) const; - int compare(const char* _Ptr) const; - int compare(const wchar_t* _Ptr) const; - int compare(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2 = npos) const; - - // Case insensitive comparison - int compareNoCase(const _Self& _Str) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const _Self& _Str) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const _Self& _Str, size_type nOff, size_type nCount) const; - int compareNoCase(const value_type* _Ptr) const; - int compareNoCase(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2 = npos) const; - - // Copies at most a specified number of characters from an indexed position in a source string to a target character array. - size_type copy(value_type* _Ptr, size_type nCount, size_type nOff = 0) const; - - void push_back(value_type _Ch) { _ConcatenateInPlace(&_Ch, 1); } - void resize(size_type nCount, value_type _Ch = ' '); - - //! simple sub-string extraction - _Self substr(size_type pos, size_type count = npos) const; - - // replace part of string. - _Self& replace(value_type chOld, value_type chNew); - _Self& replace(const_str strOld, const_str strNew); - _Self& replace(size_type pos, size_type count, const_str strNew); - _Self& replace(size_type pos, size_type count, const_str strNew, size_type count2); - _Self& replace(size_type pos, size_type count, size_type nNumChars, value_type chNew); - - // insert new elements to string. - _Self& insert(size_type nIndex, value_type ch); - _Self& insert(size_type nIndex, size_type nCount, value_type ch); - _Self& insert(size_type nIndex, const_str pstr); - _Self& insert(size_type nIndex, const_str pstr, size_type nCount); - - //! delete count characters starting at zero-based index - _Self& erase(size_type nIndex, size_type count = npos); - - //! searching (return starting index, or -1 if not found) - //! look for a single character match - //! like "C" strchr - size_type find(value_type ch, size_type pos = 0) const; - //! look for a specific sub-string - //! like "C" strstr - size_type find(const_str subs, size_type pos = 0) const; - size_type rfind(value_type ch, size_type pos = npos) const; - size_type rfind(const _Self& subs, size_type pos = 0) const; - - size_type find_first_of(value_type _Ch, size_type nOff = 0) const; - size_type find_first_of(const_str charSet, size_type nOff = 0) const; - //size_type find_first_of( const value_type* _Ptr,size_type _Off,size_type _Count ) const; - size_type find_first_of(const _Self& _Str, size_type _Off = 0) const; - - size_type find_first_not_of(value_type _Ch, size_type _Off = 0) const; - size_type find_first_not_of(const value_type* _Ptr, size_type _Off = 0) const; - size_type find_first_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const; - size_type find_first_not_of(const _Self& _Str, size_type _Off = 0) const; - - size_type find_last_of(value_type _Ch, size_type _Off = npos) const; - size_type find_last_of(const value_type* _Ptr, size_type _Off = npos) const; - size_type find_last_of(const value_type* _Ptr, size_type _Off, size_type _Count) const; - size_type find_last_of(const _Self& _Str, size_type _Off = npos) const; - - size_type find_last_not_of(value_type _Ch, size_type _Off = npos) const; - size_type find_last_not_of(const value_type* _Ptr, size_type _Off = npos) const; - size_type find_last_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const; - size_type find_last_not_of(const _Self& _Str, size_type _Off = npos) const; - - - void swap(_Self& _Str); - - ////////////////////////////////////////////////////////////////////////// - // overloaded operators. - ////////////////////////////////////////////////////////////////////////// - // overloaded indexing. - //value_type operator[]( size_type index ) const; // same as at() - // value_type& operator[]( size_type index ); // same as at() - - // overloaded assignment - _Self& operator=(const _Self& str); - _Self& operator=(value_type ch); - _Self& operator=(const_str str); - - template - CryStringT(const CryStackStringT& str); - -protected: - // we prohibit an implicit conversion from CryStackString to make user aware of allocation! - // -> use string(stackedString) instead - // as the private statement seems to be ignored (VS C++), we add a compile time error, see below - template - _Self& operator=(const CryStackStringT& str) - { - // we add a compile-time error as the Visual C++ compiler seems to ignore the private statement? -#if defined(__clang__) - //CLANG_TODO: clang verifies things differently -#else - static_assert(false, "Use explicit string assignment when assigning from_StackString"); -#endif - // not reached, as above will generate a compile time error - _Assign(str.c_str(), str.length()); - return *this; - } - -public: - // string concatenation - _Self& operator+=(const _Self& str); - _Self& operator+=(value_type ch); - _Self& operator+=(const_str str); - - //template friend CryStringT operator+( const CryStringT& str1, const CryStringT& str2 ); - //template friend CryStringT operator+( const CryStringT& str, value_type ch ); - //template friend CryStringT operator+( value_type ch, const CryStringT& str ); - //template friend CryStringT operator+( const CryStringT& str1, const_str str2 ); - //template friend CryStringT operator+( const_str str1, const CryStringT& str2 ); - - size_t GetAllocatedMemory() const - { - StrHeader* header = _header(); - if (header == _emptyHeader()) - { - return 0; - } - return sizeof(StrHeader) + (header->nAllocSize + 1) * sizeof(value_type); - } - - ////////////////////////////////////////////////////////////////////////// - // Extended functions. - // This functions are not in the STL string. - // They have an ATL CString interface. - ////////////////////////////////////////////////////////////////////////// - //! Format string, use (sprintf) - _Self& Format(const value_type* format, ...); - - //! Converts the string to lower-case - // This function uses the "C" locale for case-conversion (ie, A-Z only) - _Self& MakeLower(); - - //! Converts the string to upper-case - // This function uses the "C" locale for case-conversion (ie, A-Z only) - _Self& MakeUpper(); - - _Self& Trim(); - _Self& Trim(value_type ch); - _Self& Trim(const value_type* sCharSet); - - _Self& TrimLeft(); - _Self& TrimLeft(value_type ch); - _Self& TrimLeft(const value_type* sCharSet); - - _Self& TrimRight(); - _Self& TrimRight(value_type ch); - _Self& TrimRight(const value_type* sCharSet); - - _Self SpanIncluding(const_str charSet) const; - _Self SpanExcluding(const_str charSet) const; - _Self Tokenize(const_str charSet, int& nStart) const; - _Self Mid(size_type nFirst, size_type nCount = npos) const { return substr(nFirst, nCount); }; - - _Self Left(size_type count) const; - _Self Right(size_type count) const; - ////////////////////////////////////////////////////////////////////////// - - // public utilities. - static size_type _strlen(const_str str); - static size_type _strnlen(const_str str, size_type maxLen); - static const_str _strchr(const_str str, value_type c); - static const_str _strrchr(const_str str, value_type c); - static value_type* _strstr(value_type* str, const_str strSearch); - static bool _IsValidString(const_str str); - -#if defined(WIN32) || defined(WIN64) - static int _vscpf(const_str format, va_list args); -#endif - static int _vsnpf(value_type* buf, int cnt, const_str format, va_list args); - - -public: - ////////////////////////////////////////////////////////////////////////// - // Only used for debugging statistics. - ////////////////////////////////////////////////////////////////////////// - static size_t _usedMemory(ptrdiff_t size) - { - static size_t s_used_memory = 0; - s_used_memory += size; - return s_used_memory; - } - -protected: - value_type* m_str; // pointer to ref counted string data - - // String header. Immediately after this header in memory starts actual string data. - struct StrHeader - { - int nRefCount; - int nLength; - int nAllocSize; // Size of memory allocated at the end of this class. - - value_type* GetChars() { return (value_type*)(this + 1); } - void AddRef() { nRefCount++; /*InterlockedIncrement(&_header()->nRefCount);*/}; - int Release() { return --nRefCount; }; - }; - static StrHeader* _emptyHeader() - { - // Define 2 static buffers in a row. The 2nd is a dummy object to hold a single empty char string. - static StrHeader sEmptyStringBuffer[2] = { - {-1, 0, 0}, {0, 0, 0} - }; - return &sEmptyStringBuffer[0]; - } - - // implementation helpers - StrHeader* _header() const; - - void _AllocData(size_type nLen); - static void _FreeData(StrHeader* pData); - void _Free(); - void _Initialize(); - - void _Concatenate(const_str sStr1, size_type nLen1, const_str sStr2, size_type nLen2); - void _ConcatenateInPlace(const_str sStr, size_type nLen); - void _Assign(const_str sStr, size_type nLen); - void _MakeUnique(); - - static void _copy(value_type* dest, const value_type* src, size_type count); - static void _move(value_type* dest, const value_type* src, size_type count); - static void _set(value_type* dest, value_type ch, size_type count); -}; - -// Variant of CryStringT which does not share memory with other strings. -template -class CryStringLocalT - : public CryStringT -{ -public: - typedef CryStringT BaseType; - typedef typename BaseType::const_str const_str; - typedef typename BaseType::value_type value_type; - typedef typename BaseType::size_type size_type; - typedef typename BaseType::iterator iterator; - - CryStringLocalT() - {} - CryStringLocalT(const CryStringLocalT& str) - : BaseType(str.c_str()) - {} - CryStringLocalT(const BaseType& str) - : BaseType(str.c_str()) - {} - template - CryStringLocalT(const CryStackStringT& str) - : BaseType(str.c_str()) - {} - CryStringLocalT(const_str str) - : BaseType(str) - {} - CryStringLocalT(const_str str, size_t len) - : BaseType(str, len) - {} - CryStringLocalT(const_str begin, const_str end) - : BaseType(begin, end) - {} - CryStringLocalT(size_type nRepeat, value_type ch) - : BaseType(nRepeat, ch) - {} - - CryStringLocalT(const typename CryStringT::_Self& str, size_type nOff, size_type nCount) - : BaseType(str, nOff, nCount) - {} - - CryStringLocalT& operator=(const BaseType& str) - { - BaseType::operator=(str.c_str()); - return *this; - } - CryStringLocalT& operator=(const CryStringLocalT& str) - { - BaseType::operator=(str.c_str()); - return *this; - } - CryStringLocalT& operator=(const_str str) - { - BaseType::operator=(str); - return *this; - } - iterator begin() { return BaseType::m_str; } - using BaseType::begin; // const version - iterator end() { return BaseType::m_str + BaseType::length(); } - using BaseType::end; // const version -}; - -typedef CryStringLocalT CryStringLocal; - - -// wrapper class for creation of strings without memory allocation -// it creates a string with pointer pointing to const char* location -// destructor sets the string to empty -// NOTE: never copy a string from it, just use it as function parameters instead of const char* itself -class CConstCharWrapper -{ -public: - //passing *this is safe since the char pointer is already set and therefore is the this-ptr constructed complete enough -#pragma warning (push) -#pragma warning (disable : 4355) - CConstCharWrapper(const char* const cpString) - : cpChar(cpString) - , str(*this){AZ_Assert(cpString, "c-string parameter cannot be nullptr"); } //create stack string -#pragma warning (pop) - ~CConstCharWrapper(){str.m_str = CryStringT::_emptyHeader()->GetChars(); }//reset string - operator const CryStringT&() const { - return str; - } //cast operator to const string reference -private: - const char* const cpChar; - CryStringT str; - - char* GetCharPointer() const {return const_cast(cpChar); } //access function for string ctor - - friend class CryStringT; //both are bidirectional friends to avoid any other accesses -}; - - -//macro needed because compiler somehow cannot find the cast operator when not invoked directly -#define CONST_TEMP_STRING(a) ((const string&)CConstCharWrapper(a)) - -///////////////////////////////////////////////////////////////////////////// -// CryStringT Implementation -////////////////////////////////////////////////////////////////////////// - -template -inline typename CryStringT::StrHeader * CryStringT::_header() const -{ - AZ_Assert(m_str != nullptr, "string header is nullptr"); - return ((StrHeader*)m_str) - 1; -} - -template -inline typename CryStringT::size_type CryStringT::_strlen(const_str str) -{ - return (str == NULL) ? 0 : (size_type)::strlen(str); -} - -template <> -inline CryStringT::size_type CryStringT::_strlen(const_str str) -{ - return (str == NULL) ? 0 : (size_type)::wcslen(str); -} - -template -inline typename CryStringT::size_type CryStringT::_strnlen(const_str str, size_type maxLen) -{ - size_type len = 0; - if (str) - { - while (len < maxLen && *str != '\0') - { - len++; - str++; - } - } - return len; -} - -template -inline typename CryStringT::const_str CryStringT::_strchr(const_str str, value_type c) -{ - return (str == NULL) ? 0 : ::strchr(str, c); -} - -template <> -inline CryStringT::const_str CryStringT::_strchr(const_str str, value_type c) -{ - return (str == NULL) ? 0 : ::wcschr(str, c); -} - -template -inline typename CryStringT::const_str CryStringT::_strrchr(const_str str, value_type c) -{ - return (str == NULL) ? 0 : ::strrchr(str, c); -} - -template <> -inline CryStringT::const_str CryStringT::_strrchr(const_str str, value_type c) -{ - return (str == NULL) ? 0 : ::wcsrchr(str, c); -} - -template -inline typename CryStringT::value_type * CryStringT::_strstr(value_type * str, const_str strSearch) -{ - return (str == NULL) ? 0 : (value_type*)::strstr(str, strSearch); -} - -template <> -inline CryStringT::value_type * CryStringT::_strstr(value_type * str, const_str strSearch) -{ - return (str == NULL) ? 0 : ::wcsstr(str, strSearch); -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_copy(value_type* dest, const value_type* src, size_type count) -{ - if (dest != src) - { - memcpy(dest, src, count * sizeof(value_type)); - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_move(value_type* dest, const value_type* src, size_type count) -{ - memmove(dest, src, count * sizeof(value_type)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_set(value_type* dest, value_type ch, size_type count) -{ - static_assert(sizeof(value_type) == sizeof(T)); - static_assert(sizeof(value_type) == 1); - memset(dest, ch, count); -} - -////////////////////////////////////////////////////////////////////////// -template <> -inline void CryStringT::_set(value_type* dest, value_type ch, size_type count) -{ - static_assert(sizeof(value_type) == sizeof(wchar_t)); - wmemset(dest, ch, count); -} - -#if defined(WIN32) || defined(WIN64) - -template<> -inline int CryStringT::_vscpf(const_str format, va_list args) -{ - return _vscprintf(format, args); -} - -template<> -inline int CryStringT::_vscpf(const_str format, va_list args) -{ - return _vscwprintf(format, args); -} - -template<> -inline int CryStringT::_vsnpf(value_type* buf, int cnt, const_str format, va_list args) -{ - return azvsnprintf(buf, cnt, format, args); -} - -template<> -inline int CryStringT::_vsnpf(value_type* buf, int cnt, const_str format, va_list args) -{ - return azvsnwprintf(buf, cnt, format, args); -} - -#else - -template<> -inline int CryStringT::_vsnpf(value_type* buf, int cnt, const_str format, va_list args) -{ - return vsnprintf(buf, cnt, format, args); -} - -template<> -inline int CryStringT::_vsnpf(value_type* buf, int cnt, const_str format, va_list args) -{ - return vswprintf(buf, cnt, format, args); -} - -#endif - -////////////////////////////////////////////////////////////////////////// -template -inline bool CryStringT::_IsValidString(const_str) -{ - /* - if (str == NULL) - return false; - int nLength = _strlen(str); - return !::IsBadStringPtrA(str, nLength); - */ - return true; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_Assign(const_str sStr, size_type nLen) -{ - // Check if this string is shared (reference count greater then 1) or not enough capacity to store new string. - // Then allocate new string buffer. - if (_header()->nRefCount > 1 || nLen > capacity()) - { - _Free(); - _AllocData(nLen); - } - // Copy characters from new string to this buffer. - _copy(m_str, sStr, nLen); - // Set new length. - _header()->nLength = aznumeric_cast(nLen); - // Make null terminated string. - m_str[nLen] = 0; - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_Concatenate(const_str sStr1, size_type nLen1, const_str sStr2, size_type nLen2) -{ - size_type nLen = nLen1 + nLen2; - - if (nLen1 * 2 > nLen) - { - nLen = nLen1 * 2; - } - - if (nLen != 0) - { - if (nLen < 8) - { - nLen = 8; - } - - _AllocData(nLen); - _copy(m_str, sStr1, nLen1); - _copy(m_str + nLen1, sStr2, nLen2); - _header()->nLength = aznumeric_cast(nLen1 + nLen2); - m_str[nLen1 + nLen2] = 0; - } - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_ConcatenateInPlace(const_str sStr, size_type nLen) -{ - if (nLen != 0) - { - // Check if this string is shared (reference count greater then 1) or not enough capacity to store new string. - // Then allocate new string buffer. - if (_header()->nRefCount > 1 || length() + nLen > capacity()) - { - StrHeader* pOldData = _header(); - _Concatenate(m_str, length(), sStr, nLen); - _FreeData(pOldData); - } - else - { - _copy(m_str + length(), sStr, nLen); - _header()->nLength = aznumeric_cast(_header()->nLength + nLen); - m_str[_header()->nLength] = 0; // Make null terminated string. - } - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_MakeUnique() -{ - if (_header()->nRefCount > 1) - { - // If string is shared, make a copy of string buffer. - StrHeader* pOldData = _header(); - // This will not free header because reference count is greater then 1. - _Free(); - // Allocate a new string buffer. - _AllocData(pOldData->nLength); - // Full copy of null terminated string. - _copy(m_str, pOldData->GetChars(), pOldData->nLength + 1); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_Initialize() -{ - m_str = _emptyHeader()->GetChars(); -} - -// always allocate one extra character for '\0' termination -// assumes [optimistically] that data length will equal allocation length -template -inline void CryStringT::_AllocData(size_type nLen) -{ - AZ_Assert(nLen <= (std::numeric_limits::max)() - 1, "New string allocation size %zu is greater than the max allowed size of %d", - nLen, (std::numeric_limits::max)() - 1); // max size (enough room for 1 extra) - - if (nLen == 0) - { - _Initialize(); - } - else - { - size_type allocLen = sizeof(StrHeader) + (nLen + 1) * sizeof(value_type); - - StrHeader* pData = (StrHeader*)azmalloc(allocLen, 32, CryStringAllocator); - - _usedMemory(allocLen); // For statistics. - pData->nRefCount = 1; - m_str = pData->GetChars(); - pData->nLength = aznumeric_cast(nLen); - pData->nAllocSize = aznumeric_cast(nLen); - m_str[nLen] = 0; // null terminated string. - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_Free() -{ - if (_header()->nRefCount >= 0) // Not empty string. - { - _FreeData(_header()); - _Initialize(); - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::_FreeData(StrHeader* pData) -{ - //Cry uses -1 to represent strings on the stack. - if (pData->nRefCount < 0) - { - return; - } - - if (pData->nRefCount == 0 || pData->Release() <= 0) - { - azfree((void*)pData, CryStringAllocator); - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT() -{ - _Initialize(); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(const CryStringT& str) -{ - AZ_Assert(str._header()->nRefCount != 0, "Reference count input cry string should be greater than 0"); - if (str._header()->nRefCount >= 0) - { - m_str = str.m_str; - _header()->AddRef(); - } - else - { - _Initialize(); - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(const CryStringT& str, size_type nOff, size_type nCount) -{ - _Initialize(); - assign(str, nOff, nCount); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(const_str str) -{ - _Initialize(); - // Make a copy of C string. - size_type nLen = _strlen(str); - if (nLen != 0) - { - _AllocData(nLen); - _copy(m_str, str, nLen); - CRY_STRING_DEBUG(m_str) - } -} - -template -inline CryStringT::CryStringT(const CConstCharWrapper& str) -{ - _Initialize(); - m_str = const_cast(str.GetCharPointer()); -} - -template -template -inline CryStringT::CryStringT(const CryStackStringT& str) -{ - _Initialize(); - const size_type nLength = str.length(); - if (nLength > 0) - { - _AllocData(nLength); - _copy(m_str, str, nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(const_str str, size_type nLength) -{ - _Initialize(); - if (nLength > 0) - { - _AllocData(nLength); - _copy(m_str, str, nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(size_type nRepeat, value_type ch) -{ - _Initialize(); - if (nRepeat > 0) - { - _AllocData(nRepeat); - _set(m_str, ch, nRepeat); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::CryStringT(const_iterator _First, const_iterator _Last) -{ - _Initialize(); - size_type nLength = (size_type)(_Last - _First); - if (nLength > 0) - { - _AllocData(nLength); - _copy(m_str, _First, nLength); - CRY_STRING_DEBUG(m_str) - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT::~CryStringT() -{ - _FreeData(_header()); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::length() const -{ - return _header()->nLength; -} -template -inline typename CryStringT::size_type CryStringT::size() const -{ - return _header()->nLength; -} -template -inline typename CryStringT::size_type CryStringT::capacity() const -{ - return _header()->nAllocSize; -} - -template -inline bool CryStringT::empty() const -{ - return length() == 0; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::clear() -{ - if (length() == 0) - { - return; - } - if (_header()->nRefCount >= 0) - { - _Free(); - } - else - { - resize(0); - } - AZ_Assert(length() == 0, "Cleared string should have a length of 0"); - AZ_Assert(_header()->nRefCount < 0 || capacity() == 0, - "Cleared string should have a reference count or capacity of 0"); -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::reserve(size_type nCount) -{ - // Reserve of 0 is shrinking container to fit number of characters in it.. - if (nCount > capacity()) - { - StrHeader* pOldData = _header(); - _AllocData(nCount); - _copy(m_str, pOldData->GetChars(), pOldData->nLength); - _header()->nLength = pOldData->nLength; - m_str[pOldData->nLength] = 0; - _FreeData(pOldData); - } - else if (nCount == 0) - { - if (length() != capacity()) - { - StrHeader* pOldData = _header(); - _AllocData(length()); - _copy(m_str, pOldData->GetChars(), pOldData->nLength); - _FreeData(pOldData); - } - } - CRY_STRING_DEBUG(m_str) -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(const_str _Ptr) -{ - *this += _Ptr; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(const_str _Ptr, size_type nCount) -{ - _ConcatenateInPlace(_Ptr, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(const CryStringT& _Str, size_type off, size_type nCount) -{ - size_type len = _Str.length(); - if (off > len) - { - return *this; - } - if (off + nCount > len) - { - nCount = len - off; - } - _ConcatenateInPlace(_Str.m_str + off, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(const CryStringT& _Str) -{ - *this += _Str; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(size_type nCount, value_type _Ch) -{ - if (nCount > 0) - { - if (_header()->nRefCount > 1 || length() + nCount > capacity()) - { - StrHeader* pOldData = _header(); - _AllocData(length() + nCount); - _copy(m_str, pOldData->GetChars(), pOldData->nLength); - _set(m_str + pOldData->nLength, _Ch, nCount); - _FreeData(pOldData); - } - else - { - size_type nOldLength = length(); - _set(m_str + nOldLength, _Ch, nCount); - _header()->nLength = aznumeric_cast(nOldLength + nCount); - m_str[length()] = 0; // Make null terminated string. - } - } - CRY_STRING_DEBUG(m_str) - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::append(const_iterator _First, const_iterator _Last) -{ - append(_First, (size_type)(_Last - _First)); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(const_str _Ptr) -{ - *this = _Ptr; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(const_str _Ptr, size_type nCount) -{ - size_type len = _strnlen(_Ptr, nCount); - _Assign(_Ptr, len); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(const CryStringT& _Str, size_type off, size_type nCount) -{ - size_type len = _Str.length(); - if (off > len) - { - return *this; - } - if (off + nCount > len) - { - nCount = len - off; - } - _Assign(_Str.m_str + off, nCount); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(const CryStringT& _Str) -{ - *this = _Str; - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(size_type nCount, value_type _Ch) -{ - if (nCount >= 1) - { - _AllocData(nCount); - _set(m_str, _Ch, nCount); - CRY_STRING_DEBUG(m_str) - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::assign(const_iterator _First, const_iterator _Last) -{ - assign(_First, (size_type)(_Last - _First)); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::value_type CryStringT::at(size_type index) const -{ - AZ_Assert(index >= 0 && index < length(), "index into CryString is out of range"); - return m_str[index]; -} - -////////////////////////////////////////////////////////////////////////// -template -inline int CryStringT::compare(const CryStringT& _Str) const -{ - return compare(_Str.m_str); -} - -template -inline int CryStringT::compare(size_type _Pos1, size_type _Num1, const CryStringT& _Str) const -{ - return compare(_Pos1, _Num1, _Str.m_str, npos); -} - -template -inline int CryStringT::compare(size_type _Pos1, size_type _Num1, const CryStringT& _Str, size_type nOff, size_type nCount) const -{ - AZ_Assert(nOff < _Str.length(), "Offset into input string is larger than the index range"); - return compare(_Pos1, _Num1, _Str.m_str + nOff, nCount); -} - -template -inline int CryStringT::compare(const char* _Ptr) const -{ - return strcmp(m_str, _Ptr); -} - -template -inline int CryStringT::compare(const wchar_t* _Ptr) const -{ - return wcscmp(m_str, _Ptr); -} - -template -inline int CryStringT::compare(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2) const -{ - AZ_Assert(_Pos1 < length(), "position index to compare is larger than the length of this string"); - if (length() - _Pos1 < _Num1) - { - _Num1 = length() - _Pos1; // trim to size - } - int res = _Num1 == 0 ? 0 : strncmp(m_str + _Pos1, _Ptr, (_Num1 < _Num2) ? _Num1 : _Num2); - return (res != 0 ? res : _Num2 == npos && _Ptr[_Num1] == 0 ? 0 : _Num1 < _Num2 ? -1 : _Num1 == _Num2 ? 0 : +1); -} - -////////////////////////////////////////////////////////////////////////// -template -inline int CryStringT::compareNoCase(const CryStringT& _Str) const -{ - return _stricmp(m_str, _Str.m_str); -} - -template -inline int CryStringT::compareNoCase(size_type _Pos1, size_type _Num1, const CryStringT& _Str) const -{ - return compareNoCase(_Pos1, _Num1, _Str.m_str, npos); -} - -template -inline int CryStringT::compareNoCase(size_type _Pos1, size_type _Num1, const CryStringT& _Str, size_type nOff, size_type nCount) const -{ - AZ_Assert(nOff < _Str.length(), "offset to start comparison within input string is larger than the string index range"); - return compareNoCase(_Pos1, _Num1, _Str.m_str + nOff, nCount); -} - -template -inline int CryStringT::compareNoCase(const value_type* _Ptr) const -{ - return _stricmp(m_str, _Ptr); -} - -template -inline int CryStringT::compareNoCase(size_type _Pos1, size_type _Num1, const value_type* _Ptr, size_type _Num2) const -{ - AZ_Assert(_Pos1 < length(), "Position to start case-insensitive search is larger the indexable range"); - if (length() - _Pos1 < _Num1) - { - _Num1 = length() - _Pos1; // trim to size - } - int res = _Num1 == 0 ? 0 : _strnicmp(m_str + _Pos1, _Ptr, (_Num1 < _Num2) ? _Num1 : _Num2); - return (res != 0 ? res : _Num2 == npos && _Ptr[_Num1] == 0 ? 0 : _Num1 < _Num2 ? -1 : _Num1 == _Num2 ? 0 : +1); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::copy(value_type* _Ptr, size_type nCount, size_type nOff) const -{ - AZ_Assert(nOff < length(), "Offset to copy from string to output address is outside the indexable range"); - if (nCount < 0) - { - nCount = 0; - } - if (nOff + nCount > length()) // trim to offset. - { - nCount = length() - nOff; - } - - _copy(_Ptr, m_str + nOff, nCount); - return nCount; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::resize(size_type nCount, value_type _Ch) -{ - _MakeUnique(); - if (nCount > length()) - { - size_type numToAdd = nCount - length(); - append(numToAdd, _Ch); - } - else if (nCount < length()) - { - _header()->nLength = nCount; - m_str[length()] = 0; // Make null terminated string. - } -} - -////////////////////////////////////////////////////////////////////////// -//! compare helpers -template -inline bool operator==(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) == 0; } -template -inline bool operator==(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) == 0; } -template -inline bool operator==(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) == 0; } -template -inline bool operator!=(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) != 0; } -template -inline bool operator!=(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) != 0; } -template -inline bool operator!=(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) != 0; } -template -inline bool operator<(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) < 0; } -template -inline bool operator<(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) < 0; } -template -inline bool operator<(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) > 0; } -template -inline bool operator>(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) > 0; } -template -inline bool operator>(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) > 0; } -template -inline bool operator>(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) < 0; } -template -inline bool operator<=(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) <= 0; } -template -inline bool operator<=(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) <= 0; } -template -inline bool operator<=(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) >= 0; } -template -inline bool operator>=(const CryStringT& s1, const CryStringT& s2) -{ return s1.compare(s2) >= 0; } -template -inline bool operator>=(const CryStringT& s1, const typename CryStringT::value_type* s2) -{ return s1.compare(s2) >= 0; } -template -inline bool operator>=(const typename CryStringT::value_type* s1, const CryStringT& s2) -{ return s2.compare(s1) <= 0; } - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::operator=(value_type ch) -{ - _Assign(&ch, 1); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT operator+(const CryStringT& string1, typename CryStringT::value_type ch) -{ - CryStringT s(string1); - s.append(1, ch); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT operator+(typename CryStringT::value_type ch, const CryStringT& str) -{ - CryStringT s; - s.reserve(str.size() + 1); - s.append(1, ch); - s.append(str); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT operator+(const CryStringT& string1, const CryStringT& string2) -{ - CryStringT s(string1); - s.append(string2); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT operator+(const CryStringT& str1, const typename CryStringT::value_type* str2) -{ - CryStringT s(str1); - s.append(str2); - return s; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT operator+(const typename CryStringT::value_type* str1, const CryStringT& str2) -{ - AZ_Assert(str1 == nullptr || CryStringT::_IsValidString(str1), "Input string is not valid"); - CryStringT s; - s.reserve(CryStringT::_strlen(str1) + str2.size()); - s.append(str1); - s.append(str2); - return s; -} - -template -inline CryStringT& CryStringT::operator=(const CryStringT& str) -{ - if (m_str != str.m_str) - { - if (_header()->nRefCount < 0) - { - // Empty string. - // _Assign( str.m_str,str.length() ); - if (str._header()->nRefCount < 0) - { - ; // two empty strings... - } - else - { - m_str = str.m_str; - _header()->AddRef(); - } - } - else if (str._header()->nRefCount < 0) - { - // If source string is empty. - _Free(); - m_str = str.m_str; - } - else - { - // Copy string reference. - _Free(); - m_str = str.m_str; - _header()->AddRef(); - } - } - return *this; -} - -template -inline CryStringT& CryStringT::operator=(const_str str) -{ - AZ_Assert(str == nullptr || _IsValidString(str), "Input string is not valid"); - _Assign(str, _strlen(str)); - return *this; -} - -template -inline CryStringT& CryStringT::operator+=(const_str str) -{ - AZ_Assert(str == nullptr || _IsValidString(str), "Input string is not valid"); - _ConcatenateInPlace(str, _strlen(str)); - return *this; -} - -template -inline CryStringT& CryStringT::operator+=(value_type ch) -{ - _ConcatenateInPlace(&ch, 1); - return *this; -} - -template -inline CryStringT& CryStringT::operator+=(const CryStringT& str) -{ - _ConcatenateInPlace(str.m_str, str.length()); - return *this; -} - -//! find first single character -template -inline typename CryStringT::size_type CryStringT::find(value_type ch, size_type pos) const -{ - if (!(pos >= 0 && pos <= length())) - { - return (typename CryStringT::size_type)npos; - } - const_str str = _strchr(m_str + pos, ch); - // return npos if not found and index otherwise - return (str == NULL) ? npos : (size_type)(str - m_str); -} - -//! find a sub-string (like strstr) -template -inline typename CryStringT::size_type CryStringT::find(const_str subs, size_type pos) const -{ - AZ_Assert(_IsValidString(subs), "Input string is not valid"); - if (!(pos >= 0 && pos <= length())) - { - return npos; - } - - // find first matching substring - const_str str = _strstr(m_str + pos, subs); - - // return npos for not found, distance from beginning otherwise - return (str == NULL) ? npos : (size_type)(str - m_str); -} - -//! find last single character -template -inline typename CryStringT::size_type CryStringT::rfind(value_type ch, size_type pos) const -{ - const_str str; - if (pos == npos) - { - // find last single character - str = _strrchr(m_str, ch); - // return -1 if not found, distance from beginning otherwise - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); - } - else - { - if (pos == npos) - { - pos = length(); - } - if (!(pos >= 0 && pos <= length())) - { - return npos; - } - - value_type tmp = m_str[pos + 1]; - m_str[pos + 1] = 0; - str = _strrchr(m_str, ch); - m_str[pos + 1] = tmp; - } - // return -1 if not found, distance from beginning otherwise - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -template -inline typename CryStringT::size_type CryStringT::rfind(const CryStringT& subs, size_type pos) const -{ - size_type res = npos; - for (int i = (int)size(); i >= (int)pos; --i) - { - size_type findRes = find(subs, i); - if (findRes != npos) - { - res = findRes; - break; - } - } - return res; -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_of(const CryStringT& _Str, size_type _Off) const -{ - return find_first_of(_Str.m_str, _Off); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_of(value_type _Ch, size_type nOff) const -{ - if (!(nOff >= 0 && nOff <= length())) - { - return npos; - } - value_type charSet[2] = { _Ch, 0 }; - const_str str = strpbrk(m_str + nOff, charSet); - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_of(const_str charSet, size_type nOff) const -{ - AZ_Assert(_IsValidString(charSet), "input c-string must not be nullptr"); - if (!(nOff >= 0 && nOff <= length())) - { - return npos; - } - const_str str = strpbrk(m_str + nOff, charSet); - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -template <> -inline CryStringT::size_type CryStringT::find_first_of(const_str charSet, size_type nOff) const -{ - AZ_Assert(_IsValidString(charSet), "input c-string must not be nullptr"); - if (!(nOff >= 0 && nOff <= length())) - { - return npos; - } - const_str str = wcspbrk(m_str + nOff, charSet); - return (str == NULL) ? (size_type) - 1 : (size_type)(str - m_str); -} - -//size_type find_first_not_of(const _Self& __s, size_type __pos = 0) const -//{ return find_first_not_of(__s._M_start, __pos, __s.size()); } - -//size_type find_first_not_of(const _CharT* __s, size_type __pos = 0) const -//{ _STLP_FIX_LITERAL_BUG(__s) return find_first_not_of(__s, __pos, _Traits::length(__s)); } - -//size_type find_first_not_of(const _CharT* __s, size_type __pos, size_type __n) const; - -//size_type find_first_not_of(_CharT __c, size_type __pos = 0) const; - - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_not_of(const value_type* _Ptr, size_type _Off) const -{ return find_first_not_of(_Ptr, _Off, _strlen(_Ptr)); } - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_not_of(const CryStringT& _Str, size_type _Off) const -{ return find_first_not_of(_Str.m_str, _Off); } - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_not_of(value_type _Ch, size_type _Off) const -{ - if (_Off > length()) - { - return npos; - } - else - { - for (const value_type* str = begin() + _Off; str != end(); ++str) - { - if (*str != _Ch) - { - return size_type(str - begin()); // Character found! - } - } - return npos; - } -} - -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_first_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const -{ - if (_Off > length()) - { - return npos; - } - else - { - const value_type* charsFirst = _Ptr, * charsLast = _Ptr + _Count; - for (const value_type* str = begin() + _Off; str != end(); ++str) - { - const value_type* c; - for (c = charsFirst; c != charsLast; ++c) - { - if (*c == *str) - { - break; - } - } - if (c == charsLast) - { - return size_type(str - begin());// Current character not in char set. - } - } - return npos; - } -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_of(value_type _Ch, size_type _Off) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - // From the character at the offset position, going to to the direction of the first character. - for (const value_type* str = begin() + _Off; true; --str) - { - // We found a character in the string which matches the input character. - if (*str == _Ch) - { - return size_type(str - begin()); // Character found! - } - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - - // We found nothing. - return npos; -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_of(const value_type* _Ptr, size_type _Off) const -{ - // This function is actually a convenience alias... - // BTW: what will happeb if wchar_t is used here? - return find_last_of(_Ptr, _Off, _strlen(_Ptr)); -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_of(const value_type* _Ptr, size_type _Off, size_type _Count) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - // From the character at the offset position, going to to the direction of the first character. - const value_type* charsFirst = _Ptr, * charsLast = _Ptr + _Count; - for (const value_type* str = begin() + _Off; true; --str) - { - const value_type* c; - // For every character in the character set. - for (c = charsFirst; c != charsLast; ++c) - { - // If the current character matches any of the charcaters in the input string... - if (*c == *str) - { - // This is the value we must return. - return size_type(str - begin()); - } - } - - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - // We couldn't find any character of the input string in the current string. - return npos; -} -///////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_of(const _Self& strCharSet, size_type _Off) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - - // From the character at the offset position, going to to the direction of the first character. - for (const value_type* str = begin() + _Off; true; --str) - { - // We check every character of the input string. - for (const value_type* strInputCharacter = strCharSet.begin(); strInputCharacter != strCharSet.end(); ++strInputCharacter) - { - // If any character matches. - if (*str == *strInputCharacter) - { - // We return the position where we found it. - return size_type(str - begin()); // Character found! - } - } - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - - // As we couldn't find any matching character...we return the appropriate value. - return npos; -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_not_of(value_type _Ch, size_type _Off) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - - // From the character at the offset position, going to to the direction of the first character. - for (const value_type* str = begin() + _Off; true; --str) - { - // If the current character being analyzed is different of the input character. - if (*str != _Ch) - { - // We found the last item which is not the input character before the given offset. - return size_type(str - begin()); // Character found! - } - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - - // As we couldn't find any matching character...we return the appropriate value. - return npos; -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_not_of(const value_type* _Ptr, size_type _Off) const -{ - // This function is actually a convenience alias... - // BTW: what will happeb if wchar_t is used here? - return find_last_not_of(_Ptr, _Off, _strlen(_Ptr)); -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_not_of(const value_type* _Ptr, size_type _Off, size_type _Count) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - - // From the character at the offset position, going to to the direction of the first character. - const value_type* charsFirst = _Ptr, * charsLast = _Ptr + _Count; - for (const value_type* str = begin() + _Off; true; --str) - { - bool boFoundAny(false); - const value_type* c; - // For every character in the character set. - for (c = charsFirst; c != charsLast; ++c) - { - // If the current character matches any of the charcaters in the input string... - if (*c == *str) - { - // So we signal it was found and stop this search. - boFoundAny = true; - break; - } - } - - // Using a different solution of the other similar methods - // to make it easier to read. - // If the character being analyzed is not in the set... - if (!boFoundAny) - { - //.. we return the position where we found it. - return size_type(str - begin()); - } - - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - // We couldn't find any character of the input string not in the character set. - return npos; -} -////////////////////////////////////////////////////////////////////////// -template -inline typename CryStringT::size_type CryStringT::find_last_not_of(const _Self& _Str, size_type _Off) const -{ - size_type nLenght(length()); - // Empty strings, always return npos (same semantic as std::string). - if (nLenght == 0) - { - return npos; - } - - // If the offset is is bigger than the size of the string - if (_Off >= nLenght) - { - // We set it to the size of the string -1, so we will not do bad pointer operations nor we will - // test the null terminating character. - _Off = nLenght - 1; - } - - - // From the character at the offset position, going to to the direction of the first character. - for (const value_type* str = begin() + _Off; true; --str) - { - bool boFoundAny(false); - for (const value_type* strInputCharacter = _Str.begin(); strInputCharacter != _Str.end(); ++strInputCharacter) - { - // The character matched one of the character set... - if (*strInputCharacter == *str) - { - // So we signal it was found and stop this search. - boFoundAny = true; - break; - } - } - - // Using a different solution of the other similar methods - // to make it easier to read. - // If the character being analyzed is not in the set... - if (!boFoundAny) - { - //.. we return the position where we found it. - return size_type(str - begin()); - } - - // If the next element will be begin()-1, then we should stop. - if (str == begin()) - { - break; - } - } - - // As we couldn't find any matching character...we return the appropriate value. - return npos; -} -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT CryStringT::substr(size_type pos, size_type count) const -{ - if (pos >= length()) - { - return CryStringT(); - } - if (count == npos) - { - count = length() - pos; - } - if (pos + count > length()) - { - count = length() - pos; - } - return CryStringT(m_str + pos, count); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::erase(size_type nIndex, size_type nCount) -{ - if (nIndex < 0) - { - nIndex = 0; - } - if (nCount < 0 || nCount > length() - nIndex) - { - nCount = length() - nIndex; - } - if (nCount > 0 && nIndex < length()) - { - _MakeUnique(); - size_type nNumToCopy = length() - (nIndex + nCount) + 1; - _move(m_str + nIndex, m_str + nIndex + nCount, nNumToCopy); - _header()->nLength = length() - nCount; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::insert(size_type nIndex, value_type ch) -{ - return insert(nIndex, 1, ch); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::insert(size_type nIndex, size_type nCount, value_type ch) -{ - _MakeUnique(); - - if (nIndex < 0) - { - nIndex = 0; - } - - size_type nNewLength = length(); - if (nIndex > nNewLength) - { - nIndex = nNewLength; - } - nNewLength += nCount; - - if (capacity() < nNewLength) - { - StrHeader* pOldData = _header(); - const_str pstr = m_str; - _AllocData(nNewLength); - _copy(m_str, pstr, pOldData->nLength + 1); - _FreeData(pOldData); - } - - _move(m_str + nIndex + nCount, m_str + nIndex, (nNewLength - nIndex - nCount) + 1); - _set(m_str + nIndex, ch, nCount); - _header()->nLength = nNewLength; - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::insert(size_type nIndex, const_str pstr, size_type nCount) -{ - if (nIndex < 0) - { - nIndex = 0; - } - - size_type nInsertLength = nCount; - size_type nNewLength = length(); - if (nInsertLength > 0) - { - _MakeUnique(); - if (nIndex > nNewLength) - { - nIndex = nNewLength; - } - nNewLength += nInsertLength; - - if (capacity() < nNewLength) - { - StrHeader* pOldData = _header(); - const_str pOldStr = m_str; - _AllocData(nNewLength); - _copy(m_str, pOldStr, (pOldData->nLength + 1)); - _FreeData(pOldData); - } - - _move(m_str + nIndex + nInsertLength, m_str + nIndex, (nNewLength - nIndex - nInsertLength + 1)); - _copy(m_str + nIndex, pstr, nInsertLength); - _header()->nLength = nNewLength; - m_str[length()] = 0; - } - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::insert(size_type nIndex, const_str pstr) -{ - return insert(nIndex, pstr, _strlen(pstr)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::replace(size_type pos, size_type count, const_str strNew) -{ - return replace(pos, count, strNew, _strlen(strNew)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::replace(size_type pos, size_type count, const_str strNew, size_type count2) -{ - erase(pos, count); - insert(pos, strNew, count2); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::replace(size_type pos, size_type count, size_type nNumChars, value_type chNew) -{ - erase(pos, count); - insert(pos, nNumChars, chNew); - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::replace(value_type chOld, value_type chNew) -{ - if (chOld != chNew) - { - _MakeUnique(); - value_type* strend = m_str + length(); - for (value_type* str = m_str; str != strend; ++str) - { - if (*str == chOld) - { - *str = chNew; - } - } - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::replace(const_str strOld, const_str strNew) -{ - size_type nSourceLen = _strlen(strOld); - if (nSourceLen == 0) - { - return *this; - } - size_type nReplacementLen = _strlen(strNew); - - size_type nCount = 0; - value_type* strStart = m_str; - value_type* strEnd = m_str + length(); - value_type* strTarget; - while (strStart < strEnd) - { - while ((strTarget = _strstr(strStart, strOld)) != NULL) - { - nCount++; - strStart = strTarget + nSourceLen; - } - strStart += _strlen(strStart) + 1; - } - - if (nCount > 0) - { - _MakeUnique(); - - size_type nOldLength = length(); - size_type nNewLength = nOldLength + (nReplacementLen - nSourceLen) * nCount; - if (capacity() < nNewLength || _header()->nRefCount > 1) - { - StrHeader* pOldData = _header(); - const_str pstr = m_str; - _AllocData(nNewLength); - _copy(m_str, pstr, pOldData->nLength); - _FreeData(pOldData); - } - strStart = m_str; - strEnd = m_str + length(); - - while (strStart < strEnd) - { - while ((strTarget = _strstr(strStart, strOld)) != NULL) - { - size_type nBalance = nOldLength - ((size_type)(strTarget - m_str) + nSourceLen); - _move(strTarget + nReplacementLen, strTarget + nSourceLen, nBalance); - _copy(strTarget, strNew, nReplacementLen); - strStart = strTarget + nReplacementLen; - strStart[nBalance] = 0; - nOldLength += (nReplacementLen - nSourceLen); - } - strStart += _strlen(strStart) + 1; - } - _header()->nLength = nNewLength; - } - CRY_STRING_DEBUG(m_str) - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline void CryStringT::swap(CryStringT& _Str) -{ - value_type* temp = _Str.m_str; - _Str.m_str = m_str; - m_str = temp; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::Format(const_str format, ...) -{ - AZ_Assert(_IsValidString(format), "format c-string must not be nullptr"); - -#if defined(WIN32) || defined(WIN64) - va_list argList; - va_start(argList, format); - int n = _vscpf(format, argList); - if (n < 0) - { - n = 0; - } - resize(n); //this will actually allocate n+1 elements to accommodate the null terminator - _vsnpf(m_str, n, format, argList); - va_end(argList); - return *this; -#else - value_type temp[4096]; // Limited to 4096 characters! - va_list argList; - va_start(argList, format); - _vsnpf(temp, 4096, format, argList); - temp[4095] = '\0'; - va_end(argList); - *this = temp; - return *this; -#endif -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::MakeLower() -{ - _MakeUnique(); - for (value_type* s = m_str; *s != 0; s++) - { - const value_type c = *s; - *s = (c >= 'A' && c <= 'Z') ? c - 'A' + 'a' : c; // ASCII only, standard "C" locale - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::MakeUpper() -{ - _MakeUnique(); - for (value_type* s = m_str; *s != 0; s++) - { - const value_type c = *s; - *s = (c >= 'a' && c <= 'z') ? c - 'a' + 'A' : c; // ASCII only, standard "C" locale - } - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::Trim() -{ - return TrimRight().TrimLeft(); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::Trim(value_type ch) -{ - _MakeUnique(); - const value_type chset[2] = { ch, 0 }; - return TrimRight(chset).TrimLeft(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::Trim(const value_type* sCharSet) -{ - _MakeUnique(); - return TrimRight(sCharSet).TrimLeft(sCharSet); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimRight(value_type ch) -{ - const value_type chset[2] = { ch, 0 }; - return TrimRight(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimRight(const value_type* sCharSet) -{ - if (!sCharSet || !(*sCharSet) || length() < 1) - { - return *this; - } - - const value_type* last = m_str + length() - 1; - const value_type* str = last; - while ((str != m_str) && (_strchr(sCharSet, *str) != 0)) - { - str--; - } - - if (str != last) - { - // Just shrink length of the string. - size_type nNewLength = (size_type)(str - m_str) + 1; // m_str can change in _MakeUnique - _MakeUnique(); - _header()->nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimRight() -{ - if (length() < 1) - { - return *this; - } - - const value_type* last = m_str + length() - 1; - const value_type* str = last; - while ((str != m_str) && (isspace((unsigned char)*str) != 0)) - { - str--; - } - - if (str != last) // something changed? - { - // Just shrink length of the string. - size_type nNewLength = (size_type)(str - m_str) + 1; // m_str can change in _MakeUnique - _MakeUnique(); - _header()->nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimLeft(value_type ch) -{ - const value_type chset[2] = { ch, 0 }; - return TrimLeft(chset); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimLeft(const value_type* sCharSet) -{ - if (!sCharSet || !(*sCharSet)) - { - return *this; - } - - const value_type* str = m_str; - while ((*str != 0) && (_strchr(sCharSet, *str) != 0)) - { - str++; - } - - if (str != m_str) - { - size_type nOff = (size_type)(str - m_str); // m_str can change in _MakeUnique - _MakeUnique(); - size_type nNewLength = length() - nOff; - _move(m_str, m_str + nOff, nNewLength + 1); - _header()->nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT& CryStringT::TrimLeft() -{ - const value_type* str = m_str; - while ((*str != 0) && (isspace((unsigned char)*str) != 0)) - { - str++; - } - - if (str != m_str) - { - size_type nOff = (size_type)(str - m_str); // m_str can change in _MakeUnique - _MakeUnique(); - size_type nNewLength = length() - nOff; - _move(m_str, m_str + nOff, nNewLength + 1); - _header()->nLength = nNewLength; - m_str[nNewLength] = 0; - } - - return *this; -} - -template -inline CryStringT CryStringT::Right(size_type count) const -{ - if (count == npos) - { - return CryStringT(); - } - else if (count > length()) - { - return *this; - } - - return CryStringT(m_str + length() - count, count); -} - -template -inline CryStringT CryStringT::Left(size_type count) const -{ - if (count == npos) - { - return CryStringT(); - } - else if (count > length()) - { - count = length(); - } - - return CryStringT(m_str, count); -} - -// strspn equivalent -template -inline CryStringT CryStringT::SpanIncluding(const_str charSet) const -{ - AZ_Assert(_IsValidString(charSet), "input c-string must not be nullptr"); - return Left((size_type)strspn(m_str, charSet)); -} - -// strcspn equivalent -template -inline CryStringT CryStringT::SpanExcluding(const_str charSet) const -{ - AZ_Assert(_IsValidString(charSet), "input c-string must not be nullptr"); - return Left((size_type)strcspn(m_str, charSet)); -} - -////////////////////////////////////////////////////////////////////////// -template -inline CryStringT CryStringT::Tokenize(const_str charSet, int& nStart) const -{ - if (nStart < 0) - { - return CryStringT(); - } - - if (!charSet) - { - return *this; - } - - const_str sPlace = m_str + nStart; - const_str sEnd = m_str + length(); - if (sPlace < sEnd) - { - int nIncluding = (int)strspn(sPlace, charSet); - - if ((sPlace + nIncluding) < sEnd) - { - sPlace += nIncluding; - int nExcluding = (int)strcspn(sPlace, charSet); - int nFrom = nStart + nIncluding; - nStart = nFrom + nExcluding + 1; - - return substr(nFrom, nExcluding); - } - } - // Return empty string. - nStart = -1; - return CryStringT(); -} - -////////////////////////////////////////////////////////////////////////// -// This code prevents std::string compiling in Win32 with STLPort -////////////////////////////////////////////////////////////////////////// -#if defined(WIN32) && !defined(WIN64) && defined(_STLP_BEGIN_NAMESPACE) && !defined(DONT_BAN_STD_STRING) -#define CRYINCLUDE_STLP_STRING_FWD_H -#define CRYINCLUDE_STLP_INTERNAL_STRING_H -namespace std -{ - //const char* __get_c_string( const CryStringT &str ) { return str.c_str(); }; - class string - { - // std::string must not be used if CryString included. - // Use string instead. - }; -} -////////////////////////////////////////////////////////////////////////// -#endif // WIN64 - -typedef CryStringT string; -typedef CryStringT wstring; - -#else // !defined(NOT_USE_CRY_STRING) - -#include // STL string -typedef std::string string; -typedef std::wstring wstring; - -#endif // !defined(NOT_USE_CRY_STRING) - -namespace AZStd -{ - template <> - struct hash<::string> - { - typedef ::string argument_type; - typedef size_t result_type; - inline result_type operator()(const argument_type& value) const - { - return hash_string(value.c_str(), value.length()); - } - - static size_t hash_string(const char* str, size_t length) - { - size_t hash = 14695981039346656037ULL; - const size_t fnvPrime = 1099511628211ULL; - const char* cptr = str; - for (; length; --length) - { - hash ^= static_cast(*cptr++); - hash *= fnvPrime; - } - return hash; - } - }; -} - -#endif // CRYINCLUDE_CRYCOMMON_CRYSTRING_H diff --git a/Code/CryEngine/CryCommon/CrySystemBus.h b/Code/CryEngine/CryCommon/CrySystemBus.h deleted file mode 100644 index 93085f8819..0000000000 --- a/Code/CryEngine/CryCommon/CrySystemBus.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#ifndef CRYINCLUDE_CRYCOMMON_CRYSYSTEMBUS_H -#define CRYINCLUDE_CRYCOMMON_CRYSYSTEMBUS_H -#pragma once - -#include - -struct ISystem; -struct SSystemInitParams; - -/*! - * Events from CrySystem - */ -class CrySystemEvents - : public AZ::EBusTraits -{ -public: - //! ISystem has been created and is about to initialize. - virtual void OnCrySystemPreInitialize(ISystem&, const SSystemInitParams&) {} - - //! ISystem and IConsole has been created but the cfg files have not been parsed - virtual void OnCrySystemCVarRegistry() {} - - //! ISystem has been created and initialized. - virtual void OnCrySystemInitialized(ISystem&, const SSystemInitParams&) {} - - //! In-Editor systems have been created and initialized. - virtual void OnCryEditorInitialized() {} - - //! Editor has started a level export - virtual void OnCryEditorBeginLevelExport() {} - - //! Editor has finished a level export - virtual void OnCryEditorEndLevelExport(bool /*success*/) {} - - //! ISystem is about to begin shutting down - virtual void OnCrySystemShutdown(ISystem&) {} - - //! ISystem has shut down. - virtual void OnCrySystemPostShutdown() {} - - //! Sent when a new level is being created. - virtual void OnCryEditorBeginCreate() {} - - //! Sent after a new level has been created. - virtual void OnCryEditorEndCreate() {} - - //! Sent when a level is about to be loaded. - virtual void OnCryEditorBeginLoad() {} - - //! Sent after a level has been loaded. - virtual void OnCryEditorEndLoad() {} - - //! Sent when the document is about to close. - virtual void OnCryEditorCloseScene() {} - - //! Sent when the document is closed. - virtual void OnCryEditorSceneClosed() {} -}; -using CrySystemEventBus = AZ::EBus; - -/*! - * Requests to CrySystem - */ -class CrySystemRequests - : public AZ::EBusTraits -{ -public: - //! Get CrySystem - virtual ISystem* GetCrySystem() = 0; -}; -using CrySystemRequestBus = AZ::EBus; - -#endif // CRYINCLUDE_CRYCOMMON_CRYSYSTEMBUS_H diff --git a/Code/CryEngine/CryCommon/CryThread.h b/Code/CryEngine/CryCommon/CryThread.h deleted file mode 100644 index 7506f6767d..0000000000 --- a/Code/CryEngine/CryCommon/CryThread.h +++ /dev/null @@ -1,823 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Public include file for the multi-threading API. - - -#pragma once - - -// Include basic multithread primitives. -#include "MultiThread.h" -#include "BitFiddling.h" -#include -////////////////////////////////////////////////////////////////////////// -// Lock types: -// -// CRYLOCK_FAST -// A fast potentially (non-recursive) mutex. -// CRYLOCK_RECURSIVE -// A recursive mutex. -////////////////////////////////////////////////////////////////////////// -enum CryLockType -{ - CRYLOCK_FAST = 1, - CRYLOCK_RECURSIVE = 2, -}; - -#define CRYLOCK_HAVE_FASTLOCK 1 - -///////////////////////////////////////////////////////////////////////////// -// -// Primitive locks and conditions. -// -// Primitive locks are represented by instance of class CryLockT -// -// -template -class CryLockT -{ - /* Unsupported lock type. */ -}; - -////////////////////////////////////////////////////////////////////////// -// Typedefs. -////////////////////////////////////////////////////////////////////////// -typedef CryLockT CryCriticalSection; -typedef CryLockT CryCriticalSectionNonRecursive; -////////////////////////////////////////////////////////////////////////// - - -////////////////////////////////////////////////////////////////////////// -// -// CryAutoCriticalSection implements a helper class to automatically -// lock critical section in constructor and release on destructor. -// -////////////////////////////////////////////////////////////////////////// -template -class CryAutoLock -{ -private: - LockClass* m_pLock; - - CryAutoLock(); - CryAutoLock(const CryAutoLock&); - CryAutoLock& operator = (const CryAutoLock&); - -public: - CryAutoLock(LockClass& Lock) - : m_pLock(&Lock) { m_pLock->Lock(); } - CryAutoLock(const LockClass& Lock) - : m_pLock(const_cast(&Lock)) { m_pLock->Lock(); } - ~CryAutoLock() { m_pLock->Unlock(); } -}; - -////////////////////////////////////////////////////////////////////////// -// -// CryOptionalAutoLock implements a helper class to automatically -// lock critical section (if needed) in constructor and release on destructor. -// -////////////////////////////////////////////////////////////////////////// -template -class CryOptionalAutoLock -{ -private: - LockClass* m_Lock; - bool m_bLockAcquired; - - CryOptionalAutoLock(); - CryOptionalAutoLock(const CryOptionalAutoLock&); - CryOptionalAutoLock& operator = (const CryOptionalAutoLock&); - -public: - CryOptionalAutoLock(LockClass& Lock, bool acquireLock) - : m_Lock(&Lock) - , m_bLockAcquired(false) - { - if (acquireLock) - { - Acquire(); - } - } - ~CryOptionalAutoLock() - { - Release(); - } - void Release() - { - if (m_bLockAcquired) - { - m_Lock->Unlock(); - m_bLockAcquired = false; - } - } - void Acquire() - { - if (!m_bLockAcquired) - { - m_Lock->Lock(); - m_bLockAcquired = true; - } - } -}; - -////////////////////////////////////////////////////////////////////////// -// -// CryAutoSet implements a helper class to automatically -// set and reset value in constructor and release on destructor. -// -////////////////////////////////////////////////////////////////////////// -template -class CryAutoSet -{ -private: - ValueClass* m_pValue; - - CryAutoSet(); - CryAutoSet(const CryAutoSet&); - CryAutoSet& operator = (const CryAutoSet&); - -public: - CryAutoSet(ValueClass& value) - : m_pValue(&value) { *m_pValue = (ValueClass)1; } - ~CryAutoSet() { *m_pValue = (ValueClass)0; } -}; - -////////////////////////////////////////////////////////////////////////// -// -// Auto critical section is the most commonly used type of auto lock. -// -////////////////////////////////////////////////////////////////////////// -typedef CryAutoLock CryAutoCriticalSection; - -#define AUTO_LOCK_T(Type, lock) PREFAST_SUPPRESS_WARNING(6246); CryAutoLock __AutoLock(lock) -#define AUTO_LOCK(lock) AUTO_LOCK_T(CryCriticalSection, lock) -#define AUTO_LOCK_CS(csLock) CryAutoCriticalSection __AL__##csLock(csLock) - -///////////////////////////////////////////////////////////////////////////// -// -// Threads. - -// Base class for runnable objects. -// -// A runnable is an object with a Run() and a Cancel() method. The Run() -// method should perform the runnable's job. The Cancel() method may be -// called by another thread requesting early termination of the Run() method. -// The runnable may ignore the Cancel() call, the default implementation of -// Cancel() does nothing. -class CryRunnable -{ -public: - virtual ~CryRunnable() { } - virtual void Run() = 0; - virtual void Cancel() { } -}; - -// Class holding information about a thread. -// -// A reference to the thread information can be obtained by calling GetInfo() -// on the CrySimpleThread (or derived class) instance. -// -// NOTE: -// If the code is compiled with NO_THREADINFO defined, then the GetInfo() -// method will return a reference to a static dummy instance of this -// structure. It is currently undecided if NO_THREADINFO will be defined for -// release builds! - -struct CryThreadInfo -{ - // The symbolic name of the thread. - // - // You may set this name directly or through the SetName() method of - // CrySimpleThread (or derived class). - AZStd::string m_Name; - - - // A thread identification number. - // The number is unique but architecture specific. Do not assume anything - // about that number except for being unique. - // - // This field is filled when the thread is started (i.e. before the Run() - // method or thread routine is called). It is advised that you do not - // change this number manually. - uint32 m_ID; -}; - -// Simple thread class. -// -// CrySimpleThread is a simple wrapper around a system thread providing -// nothing but system-level functionality of a thread. There are two typical -// ways to use a simple thread: -// -// 1. Derive from the CrySimpleThread class and provide an implementation of -// the Run() (and optionally Cancel()) methods. -// 2. Specify a runnable object when the thread is started. The default -// runnable type is CryRunnable. -// -// The Runnable class specfied as the template argument must provide Run() -// and Cancel() methods compatible with the following signatures: -// -// void Runnable::Run(); -// void Runnable::Cancel(); -// -// If the Runnable does not support cancellation, then the Cancel() method -// should do nothing. -// -// The same instance of CrySimpleThread may be used for multiple thread -// executions /in sequence/, i.e. it is valid to re-start the thread by -// calling Start() after the thread has been joined by calling WaitForThread(). -template -class CrySimpleThread; - -// Standard thread class. -// -// The class provides a lock (mutex) and an associated condition variable. If -// you don't need the lock, then you should used CrySimpleThread instead of -// CryThread. -template -class CryThread; - -/////////////////////////////////////////////////////////////////////////////// -// Include architecture specific code. -#if AZ_LEGACY_CRYCOMMON_TRAIT_USE_PTHREADS -#include -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(WIN32) || defined(WIN64) -#include -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) - #include AZ_RESTRICTED_FILE(CryThread_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -// Put other platform specific includes here! -#include -#endif - -#if !defined _CRYTHREAD_CONDLOCK_GLITCH -typedef CryLockT CryMutex; -#endif // !_CRYTHREAD_CONDLOCK_GLITCH - -// The the architecture specific code does not define a class CryRWLock, then -// a default implementation is provided here. -#if !defined _CRYTHREAD_HAVE_RWLOCK && !defined _CRYTHREAD_CONDLOCK_GLITCH -class CryRWLock -{ - CryCriticalSection m_lockExclusiveAccess; - CryCriticalSection m_lockSharedAccessComplete; - CryConditionVariable m_condSharedAccessComplete; - - int m_nSharedAccessCount; - int m_nCompletedSharedAccessCount; - bool m_bExclusiveAccess; - - CryRWLock(const CryRWLock&); - CryRWLock& operator= (const CryRWLock&); - - void AdjustSharedAccessCount() - { - m_nSharedAccessCount -= m_nCompletedSharedAccessCount; - m_nCompletedSharedAccessCount = 0; - } - -public: - CryRWLock() - : m_nSharedAccessCount(0) - , m_nCompletedSharedAccessCount(0) - , m_bExclusiveAccess(false) - { } - - void RLock() - { - m_lockExclusiveAccess.Lock(); - if (++m_nSharedAccessCount == INT_MAX) - { - m_lockSharedAccessComplete.Lock(); - AdjustSharedAccessCount(); - m_lockSharedAccessComplete.Unlock(); - } - m_lockExclusiveAccess.Unlock(); - } - - bool TryRLock() - { - if (!m_lockExclusiveAccess.TryLock()) - { - return false; - } - if (++m_nSharedAccessCount == INT_MAX) - { - m_lockSharedAccessComplete.Lock(); - AdjustSharedAccessCount(); - m_lockSharedAccessComplete.Unlock(); - } - m_lockExclusiveAccess.Unlock(); - return true; - } - - void RUnlock() - { - Unlock(); - } - - void WLock() - { - m_lockExclusiveAccess.Lock(); - m_lockSharedAccessComplete.Lock(); - assert(!m_bExclusiveAccess); - AdjustSharedAccessCount(); - if (m_nSharedAccessCount > 0) - { - m_nCompletedSharedAccessCount -= m_nSharedAccessCount; - do - { - m_condSharedAccessComplete.Wait(m_lockSharedAccessComplete); - } - while (m_nCompletedSharedAccessCount < 0); - m_nSharedAccessCount = 0; - } - m_bExclusiveAccess = true; - } - - bool TryWLock() - { - if (!m_lockExclusiveAccess.TryLock()) - { - return false; - } - if (!m_lockSharedAccessComplete.TryLock()) - { - m_lockExclusiveAccess.Unlock(); - return false; - } - assert(!m_bExclusiveAccess); - AdjustSharedAccessCount(); - if (m_nSharedAccessCount > 0) - { - m_lockSharedAccessComplete.Unlock(); - m_lockExclusiveAccess.Unlock(); - return false; - } - else - { - m_bExclusiveAccess = true; - } - return true; - } - - void WUnlock() - { - Unlock(); - } - - void Unlock() - { - if (!m_bExclusiveAccess) - { - m_lockSharedAccessComplete.Lock(); - if (++m_nCompletedSharedAccessCount == 0) - { - m_condSharedAccessComplete.NotifySingle(); - } - m_lockSharedAccessComplete.Unlock(); - } - else - { - m_bExclusiveAccess = false; - m_lockSharedAccessComplete.Unlock(); - m_lockExclusiveAccess.Unlock(); - } - } -}; -#endif // !defined _CRYTHREAD_HAVE_RWLOCK - -// Thread class. -// -// CryThread is an extension of CrySimpleThread providing a lock (mutex) and a -// condition variable per instance. -template -class CryThread - : public CrySimpleThread -{ - CryMutex m_Lock; - CryConditionVariable m_Cond; - - CryThread(const CryThread&); - void operator = (const CryThread&); - -public: - CryThread() { } - void Lock() { m_Lock.Lock(); } - bool TryLock() { return m_Lock.TryLock(); } - void Unlock() { m_Lock.Unlock(); } - void Wait() { m_Cond.Wait(m_Lock); } - // Timed wait on the associated condition. - // - // The 'milliseconds' parameter specifies the relative timeout in - // milliseconds. The method returns true if a notification was received and - // false if the specified timeout expired without receiving a notification. - // - // UNIX note: the method will _not_ return if the calling thread receives a - // signal. Instead the call is re-started with the _original_ timeout - // value. This misfeature may be fixed in the future. - bool TimedWait(uint32 milliseconds) - { - return m_Cond.TimedWait(m_Lock, milliseconds); - } - void Notify() { m_Cond.Notify(); } - void NotifySingle() { m_Cond.NotifySingle(); } - CryMutex& GetLock() { return m_Lock; } -}; - -////////////////////////////////////////////////////////////////////////// -// -// Sync primitive for multiple reads and exclusive locking change access -// -// Desc: -// Useful in case if you have rarely modified object that needs -// to be read quite often from different threads but still -// need to be exclusively modified sometimes -// Debug functionality: -// Can be used for debug-only lock calls, which verify that no -// simultaneous access is attempted. -// Use the bDebug argument of LockRead or LockModify, -// or use the DEBUG_READLOCK or DEBUG_MODIFYLOCK macros. -// There is no overhead in release builds, if you use the macros, -// and the lock definition is inside #ifdef _DEBUG. -////////////////////////////////////////////////////////////////////////// - -class CryReadModifyLock -{ -public: - CryReadModifyLock() - : m_modifyCount(0) - , m_readCount(0) - { - SetDebugLocked(false); - } - - bool LockRead(bool bTry = false, cstr strDebug = 0, bool bDebug = false) const - { - if (!WriteLock(bTry, bDebug, strDebug)) // wait until write unlocked - { - return false; - } - CryInterlockedIncrement(&m_readCount); // increment read counter - m_writeLock.Unlock(); - return true; - } - void UnlockRead() const - { - SetDebugLocked(false); - const int counter = CryInterlockedDecrement(&m_readCount); // release read - assert(counter >= 0); - if (m_writeLock.TryLock()) - { - m_writeLock.Unlock(); - } - else - if (counter == 0 && m_modifyCount) - { - m_ReadReleased.Set(); // signal the final read released - } - } - bool LockModify(bool bTry = false, cstr strDebug = 0, bool bDebug = false) const - { - if (!WriteLock(bTry, bDebug, strDebug)) - { - return false; - } - CryInterlockedIncrement(&m_modifyCount); // increment write counter (counter is for nested cases) - while (m_readCount) - { - m_ReadReleased.Wait(); // wait for all threads finish read operation - } - return true; - } - void UnlockModify() const - { - SetDebugLocked(false); -#if !defined(NDEBUG) - int counter = -#endif - CryInterlockedDecrement(&m_modifyCount); // decrement write counter - assert(counter >= 0); - m_writeLock.Unlock(); // release exclusive lock - } - -protected: - mutable volatile int m_readCount; - mutable volatile int m_modifyCount; - mutable CryEvent m_ReadReleased; - mutable CryCriticalSection m_writeLock; - mutable bool m_debugLocked; - mutable const char* m_debugLockStr; - - void SetDebugLocked([[maybe_unused]] bool b, [[maybe_unused]] const char* str = 0) const - { -#ifdef _DEBUG - m_debugLocked = b; - m_debugLockStr = str; -#endif - } - - bool WriteLock(bool bTry, [[maybe_unused]] bool bDebug, [[maybe_unused]] const char* strDebug) const - { - if (!m_writeLock.TryLock()) - { -#ifdef _DEBUG - assert(!m_debugLocked); - assert(!bDebug); -#endif - if (bTry) - { - return false; - } - m_writeLock.Lock(); - } -#ifdef _DEBUG - if (!m_readCount && !m_modifyCount) // not yet locked - { - SetDebugLocked(bDebug, strDebug); - } -#endif - return true; - } -}; - -// Auto-locking classes. -template -class AutoLockRead -{ -protected: - const T& m_lock; -public: - AutoLockRead(const T& lock, cstr strDebug = 0) - : m_lock(lock) { m_lock.LockRead(bDEBUG, strDebug, bDEBUG); } - ~AutoLockRead() - { m_lock.UnlockRead(); } -}; - -template -class AutoLockModify -{ -protected: - const T& m_lock; -public: - AutoLockModify(const T& lock, cstr strDebug = 0) - : m_lock(lock) { m_lock.LockModify(bDEBUG, strDebug, bDEBUG); } - ~AutoLockModify() - { m_lock.UnlockModify(); } -}; - -#define AUTO_READLOCK(p) PREFAST_SUPPRESS_WARNING(6246) AutoLockRead AZ_JOIN(__readlock, __LINE__)(p, __FUNC__) -#define AUTO_READLOCK_PROT(p) PREFAST_SUPPRESS_WARNING(6246) AutoLockRead AZ_JOIN(__readlock_prot, __LINE__)(p, __FUNC__) -#define AUTO_MODIFYLOCK(p) PREFAST_SUPPRESS_WARNING(6246) AutoLockModify AZ_JOIN(__modifylock, __LINE__)(p, __FUNC__) - -#if defined(_DEBUG) - #define DEBUG_READLOCK(p) AutoLockRead AZ_JOIN(__readlock, __LINE__)(p, __FUNC__) - #define DEBUG_MODIFYLOCK(p) AutoLockModify AZ_JOIN(__modifylock, __LINE__)(p, __FUNC__) -#else - #define DEBUG_READLOCK(p) - #define DEBUG_MODIFYLOCK(p) -#endif - -// producer consumer queue implementations, but here instead of MultiThread_Container.h -// since they requiere platform specific code, and including windows.h in a very common -// header file leads to all kinds of problems -namespace CryMT -{ - ////////////////////////////////////////////////////////////////////////// - // Producer/Consumer Queue for 1 to 1 thread communication - // Realized with only volatile variables and memory barriers - // *warning* this producer/consumer queue is only thread safe in a 1 to 1 situation - // and doesn't provide any yields or similar to prevent spinning - ////////////////////////////////////////////////////////////////////////// - template - class SingleProducerSingleConsumerQueue - : public CryMT::detail::SingleProducerSingleConsumerQueueBase - { - public: - SingleProducerSingleConsumerQueue(); - ~SingleProducerSingleConsumerQueue(); - - void Init(size_t nSize); - - void Push(const T& rObj); - void Pop(T* pResult); - uint32 Size() { return (m_nProducerIndex - m_nComsumerIndex); } - uint32 BufferSize() { return m_nBufferSize; } - uint32 FreeCount() { return (m_nBufferSize - (m_nProducerIndex - m_nComsumerIndex)); } - - private: - T* m_arrBuffer; - uint32 m_nBufferSize; - - volatile uint32 m_nProducerIndex _ALIGN(16); - volatile uint32 m_nComsumerIndex _ALIGN(16); - } _ALIGN(128); - - /////////////////////////////////////////////////////////////////////////////// - template - inline SingleProducerSingleConsumerQueue::SingleProducerSingleConsumerQueue() - : m_arrBuffer(NULL) - , m_nBufferSize(0) - , m_nProducerIndex(0) - , m_nComsumerIndex(0) - {} - - /////////////////////////////////////////////////////////////////////////////// - template - inline SingleProducerSingleConsumerQueue::~SingleProducerSingleConsumerQueue() - { - CryModuleMemalignFree(m_arrBuffer); - m_nBufferSize = 0; - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void SingleProducerSingleConsumerQueue::Init(size_t nSize) - { - assert(m_arrBuffer == NULL); - assert(m_nBufferSize == 0); - assert((nSize & (nSize - 1)) == 0); - - m_arrBuffer = alias_cast(CryModuleMemalign(nSize * sizeof(T), 16)); - m_nBufferSize = nSize; - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void SingleProducerSingleConsumerQueue::Push(const T& rObj) - { - assert(m_arrBuffer != NULL); - assert(m_nBufferSize != 0); - SingleProducerSingleConsumerQueueBase::Push((void*)&rObj, m_nProducerIndex, m_nComsumerIndex, m_nBufferSize, m_arrBuffer, sizeof(T)); - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void SingleProducerSingleConsumerQueue::Pop(T* pResult) - { - assert(m_arrBuffer != NULL); - assert(m_nBufferSize != 0); - SingleProducerSingleConsumerQueueBase::Pop(pResult, m_nProducerIndex, m_nComsumerIndex, m_nBufferSize, m_arrBuffer, sizeof(T)); - } - - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - // Producer/Consumer Queue for N to 1 thread communication - // lockfree implemenation, to copy with multiple producers, - // a internal producer refcount is managed, the queue is empty - // as soon as there are no more producers and no new elements - ////////////////////////////////////////////////////////////////////////// - template - class N_ProducerSingleConsumerQueue - : public CryMT::detail::N_ProducerSingleConsumerQueueBase - { - public: - N_ProducerSingleConsumerQueue(); - ~N_ProducerSingleConsumerQueue(); - - void Init(size_t nSize); - - void Push(const T& rObj); - bool Pop(T* pResult); - - // needs to be called before using, assumes that there is at least one producer - // so the first one doesn't need to call AddProducer, but he has to deregister itself - void SetRunningState(); - - // to correctly track when the queue is empty(and no new jobs will be added), refcount the producer - void AddProducer(); - void RemoveProducer(); - - uint32 Size() { return (m_nProducerIndex - m_nComsumerIndex); } - uint32 BufferSize() { return m_nBufferSize; } - uint32 FreeCount() { return (m_nBufferSize - (m_nProducerIndex - m_nComsumerIndex)); } - - private: - T* m_arrBuffer; - volatile uint32* m_arrStates; - uint32 m_nBufferSize; - - volatile uint32 m_nProducerIndex; - volatile uint32 m_nComsumerIndex; - volatile uint32 m_nRunning; - volatile uint32 m_nProducerCount; - } _ALIGN(128); - - /////////////////////////////////////////////////////////////////////////////// - template - inline N_ProducerSingleConsumerQueue::N_ProducerSingleConsumerQueue() - : m_arrBuffer(NULL) - , m_arrStates(NULL) - , m_nBufferSize(0) - , m_nProducerIndex(0) - , m_nComsumerIndex(0) - , m_nRunning(0) - , m_nProducerCount(0) - {} - - /////////////////////////////////////////////////////////////////////////////// - template - inline N_ProducerSingleConsumerQueue::~N_ProducerSingleConsumerQueue() - { - CryModuleMemalignFree(m_arrBuffer); - CryModuleMemalignFree((void*)m_arrStates); - m_nBufferSize = 0; - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void N_ProducerSingleConsumerQueue::Init(size_t nSize) - { - assert(m_arrBuffer == NULL); - assert(m_arrStates == NULL); - assert(m_nBufferSize == 0); - assert((nSize & (nSize - 1)) == 0); - - m_arrBuffer = alias_cast(CryModuleMemalign(nSize * sizeof(T), 16)); - m_arrStates = alias_cast(CryModuleMemalign(nSize * sizeof(uint32), 16)); - memset((void*)m_arrStates, 0, sizeof(uint32) * nSize); - m_nBufferSize = nSize; - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void N_ProducerSingleConsumerQueue::SetRunningState() - { -#if !defined(_RELEASE) - if (m_nRunning == 1) - { - __debugbreak(); - } -#endif - m_nRunning = 1; - m_nProducerCount = 1; - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void N_ProducerSingleConsumerQueue::AddProducer() - { - assert(m_arrBuffer != NULL); - assert(m_arrStates != NULL); - assert(m_nBufferSize != 0); -#if !defined(_RELEASE) - if (m_nRunning == 0) - { - __debugbreak(); - } -#endif - CryInterlockedIncrement((volatile int*)&m_nProducerCount); - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void N_ProducerSingleConsumerQueue::RemoveProducer() - { - assert(m_arrBuffer != NULL); - assert(m_arrStates != NULL); - assert(m_nBufferSize != 0); -#if !defined(_RELEASE) - if (m_nRunning == 0) - { - __debugbreak(); - } -#endif - if (CryInterlockedDecrement((volatile int*)&m_nProducerCount) == 0) - { - m_nRunning = 0; - } - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void N_ProducerSingleConsumerQueue::Push(const T& rObj) - { - assert(m_arrBuffer != NULL); - assert(m_arrStates != NULL); - assert(m_nBufferSize != 0); - CryMT::detail::N_ProducerSingleConsumerQueueBase::Push((void*)&rObj, m_nProducerIndex, m_nComsumerIndex, m_nRunning, m_arrBuffer, m_nBufferSize, sizeof(T), m_arrStates); - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline bool N_ProducerSingleConsumerQueue::Pop(T* pResult) - { - assert(m_arrBuffer != NULL); - assert(m_arrStates != NULL); - assert(m_nBufferSize != 0); - return CryMT::detail::N_ProducerSingleConsumerQueueBase::Pop(pResult, m_nProducerIndex, m_nComsumerIndex, m_nRunning, m_arrBuffer, m_nBufferSize, sizeof(T), m_arrStates); - } -} //namespace CryMT - -// Include all multithreading containers. -#include "MultiThread_Containers.h" diff --git a/Code/CryEngine/CryCommon/CryThreadImpl.h b/Code/CryEngine/CryCommon/CryThreadImpl.h deleted file mode 100644 index 1928ee0774..0000000000 --- a/Code/CryEngine/CryCommon/CryThreadImpl.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - - -#include - -// Include architecture specific code. -#if defined(LINUX) || defined(APPLE) -#include -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(WIN32) || defined(WIN64) -#include -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) - #include AZ_RESTRICTED_FILE(CryThreadImpl_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -// Put other platform specific includes here! -#endif diff --git a/Code/CryEngine/CryCommon/CryThreadImpl_pthreads.h b/Code/CryEngine/CryCommon/CryThreadImpl_pthreads.h deleted file mode 100644 index a8895f5bbc..0000000000 --- a/Code/CryEngine/CryCommon/CryThreadImpl_pthreads.h +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYTHREADIMPL_PTHREADS_H -#define CRYINCLUDE_CRYCOMMON_CRYTHREADIMPL_PTHREADS_H -#pragma once - - -#include "CryThread_pthreads.h" - -#if PLATFORM_SUPPORTS_THREADLOCAL -THREADLOCAL CrySimpleThreadSelf -* CrySimpleThreadSelf::m_Self = NULL; -#else -TLS_DEFINE(CrySimpleThreadSelf*, g_CrySimpleThreadSelf) -#endif - - -////////////////////////////////////////////////////////////////////////// -// CryEvent(Timed) implementation -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -void CryEventTimed::Reset() -{ - m_lockNotify.Lock(); - m_flag = false; - m_lockNotify.Unlock(); -} - -////////////////////////////////////////////////////////////////////////// -void CryEventTimed::Set() -{ - m_lockNotify.Lock(); - m_flag = true; - m_cond.Notify(); - m_lockNotify.Unlock(); -} - -////////////////////////////////////////////////////////////////////////// -void CryEventTimed::Wait() -{ - m_lockNotify.Lock(); - if (!m_flag) - { - m_cond.Wait(m_lockNotify); - } - m_flag = false; - m_lockNotify.Unlock(); -} - -////////////////////////////////////////////////////////////////////////// -bool CryEventTimed::Wait(const uint32 timeoutMillis) -{ - bool bResult = true; - m_lockNotify.Lock(); - if (!m_flag) - { - bResult = m_cond.TimedWait(m_lockNotify, timeoutMillis); - } - m_flag = false; - m_lockNotify.Unlock(); - return bResult; -} - -/////////////////////////////////////////////////////////////////////////////// -// CryCriticalSection implementation -/////////////////////////////////////////////////////////////////////////////// -typedef CryLockT TCritSecType; - -void CryDeleteCriticalSection(void* cs) -{ - delete ((TCritSecType*)cs); -} - -void CryEnterCriticalSection(void* cs) -{ - ((TCritSecType*)cs)->Lock(); -} - -bool CryTryCriticalSection(void* cs) -{ - return false; -} - -void CryLeaveCriticalSection(void* cs) -{ - ((TCritSecType*)cs)->Unlock(); -} - -void CryCreateCriticalSectionInplace(void* pCS) -{ - new (pCS) TCritSecType; -} - -void CryDeleteCriticalSectionInplace(void*) -{ -} - -void* CryCreateCriticalSection() -{ - return (void*) new TCritSecType; -} - -#if AZ_TRAIT_SKIP_CRYINTERLOCKED -#elif defined(INTERLOCKED_COMPARE_EXCHANGE_128_NOT_SUPPORTED) -////////////////////////////////////////////////////////////////////////// -void CryInterlockedPushEntrySList(SLockFreeSingleLinkedListHeader& list, SLockFreeSingleLinkedListEntry& element) -{ - AZStd::lock_guard lock(list.mutex); - - element.pNext = list.pNext; - list.pNext = &element; -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedPopEntrySList(SLockFreeSingleLinkedListHeader& list) -{ - AZStd::lock_guard lock(list.mutex); - - SLockFreeSingleLinkedListEntry* returnValue = list.pNext; - if (list.pNext) - { - list.pNext = list.pNext->pNext; - } - return returnValue; -} - -////////////////////////////////////////////////////////////////////////// -void CryInitializeSListHead(SLockFreeSingleLinkedListHeader& list) -{ - AZStd::lock_guard lock(list.mutex); - - list.pNext = NULL; -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedFlushSList(SLockFreeSingleLinkedListHeader& list) -{ - AZStd::lock_guard lock(list.mutex); - - SLockFreeSingleLinkedListEntry* returnValue = list.pNext; - list.pNext = nullptr; - return returnValue; -} - -#elif defined(LINUX32) -////////////////////////////////////////////////////////////////////////// -// Implementation for Linux32 with gcc using uint64 -////////////////////////////////////////////////////////////////////////// -void CryInterlockedPushEntrySList(SLockFreeSingleLinkedListHeader& list, SLockFreeSingleLinkedListEntry& element) -{ - uint32 curSetting[2]; - uint32 newSetting[2]; - uint32 newPointer = (uint32) & element; - do - { - curSetting[0] = (uint32)list.pNext; - curSetting[1] = list.salt; - element.pNext = (SLockFreeSingleLinkedListEntry*)curSetting[0]; - newSetting[0] = newPointer; // new pointer - newSetting[1] = curSetting[1] + 1; // new salt - } - while (false == __sync_bool_compare_and_swap((volatile uint64*)&list.pNext, *(uint64*)&curSetting[0], *(uint64*)&newSetting[0])); -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedPopEntrySList(SLockFreeSingleLinkedListHeader& list) -{ - uint32 curSetting[2]; - uint32 newSetting[2]; - do - { - curSetting[1] = list.salt; - curSetting[0] = (uint32)list.pNext; - if (curSetting[0] == 0) - { - return NULL; - } - newSetting[0] = *(uint32*)curSetting[0]; // new pointer - newSetting[1] = curSetting[1] + 1; // new salt - } - while (false == __sync_bool_compare_and_swap((volatile uint64*)&list.pNext, *(uint64*)&curSetting[0], *(uint64*)&newSetting[0])); - return (void*)curSetting[0]; -} - -////////////////////////////////////////////////////////////////////////// -void CryInitializeSListHead(SLockFreeSingleLinkedListHeader& list) -{ - list.salt = 0; - list.pNext = NULL; -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedFlushSList(SLockFreeSingleLinkedListHeader& list) -{ - uint32 curSetting[2]; - uint32 newSetting[2]; - uint32 newSalt; - uint32 newPointer; - do - { - curSetting[1] = list.salt; - curSetting[0] = (uint32)list.pNext; - if (curSetting[0] == 0) - { - return NULL; - } - newSetting[0] = 0; - newSetting[1] = curSetting[1] + 1; - } - while (false == __sync_bool_compare_and_swap((volatile uint64*)&list.pNext, *(uint64*)&curSetting[0], *(uint64*)&newSetting[0])); - return (void*)curSetting[0]; -} -#else -// This implementation get's used on multiple platforms that support uint128 compare and swap. - -////////////////////////////////////////////////////////////////////////// -// LINUX64 Implementation of Lockless Single Linked List -////////////////////////////////////////////////////////////////////////// -typedef __uint128_t uint128; - -////////////////////////////////////////////////////////////////////////// -// Implementation for Linux64 with gcc using __int128_t -////////////////////////////////////////////////////////////////////////// -void CryInterlockedPushEntrySList(SLockFreeSingleLinkedListHeader& list, SLockFreeSingleLinkedListEntry& element) -{ - uint64 curSetting[2]; - uint64 newSetting[2]; - uint64 newPointer = (uint64) & element; - do - { - curSetting[0] = (uint64)list.pNext; - curSetting[1] = list.salt; - element.pNext = (SLockFreeSingleLinkedListEntry*)curSetting[0]; - newSetting[0] = newPointer; // new pointer - newSetting[1] = curSetting[1] + 1; // new salt - } - // while (false == __sync_bool_compare_and_swap( (volatile uint128*)&list.pNext,*(uint128*)&curSetting[0],*(uint128*)&newSetting[0] )); - while (0 == _InterlockedCompareExchange128((volatile int64*)&list.pNext, (int64)newSetting[1], (int64)newSetting[0], (int64*)&curSetting[0])); -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedPopEntrySList(SLockFreeSingleLinkedListHeader& list) -{ - uint64 curSetting[2]; - uint64 newSetting[2]; - do - { - curSetting[1] = list.salt; - curSetting[0] = (uint64)list.pNext; - if (curSetting[0] == 0) - { - return NULL; - } - newSetting[0] = *(uint64*)curSetting[0]; // new pointer - newSetting[1] = curSetting[1] + 1; // new salt - } - //while (false == __sync_bool_compare_and_swap( (volatile uint128*)&list.pNext,*(uint128*)&curSetting[0],*(uint128*)&newSetting[0] )); - while (0 == _InterlockedCompareExchange128((volatile int64*)&list.pNext, (int64)newSetting[1], (int64)newSetting[0], (int64*)&curSetting[0])); - return (void*)curSetting[0]; -} - -////////////////////////////////////////////////////////////////////////// -void CryInitializeSListHead(SLockFreeSingleLinkedListHeader& list) -{ - list.salt = 0; - list.pNext = NULL; -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedFlushSList(SLockFreeSingleLinkedListHeader& list) -{ - uint64 curSetting[2]; - uint64 newSetting[2]; - uint64 newSalt; - uint64 newPointer; - do - { - curSetting[1] = list.salt; - curSetting[0] = (uint64)list.pNext; - if (curSetting[0] == 0) - { - return NULL; - } - newSetting[0] = 0; - newSetting[1] = curSetting[1] + 1; - } - // while (false == __sync_bool_compare_and_swap( (volatile uint128*)&list.pNext,*(uint128*)&curSetting[0],*(uint128*)&newSetting[0] )); - while (0 == _InterlockedCompareExchange128((volatile int64*)&list.pNext, (int64)newSetting[1], (int64)newSetting[0], (int64*)&curSetting[0])); - return (void*)curSetting[0]; -} -////////////////////////////////////////////////////////////////////////// -#endif - -#endif // CRYINCLUDE_CRYCOMMON_CRYTHREADIMPL_PTHREADS_H diff --git a/Code/CryEngine/CryCommon/CryThreadImpl_windows.h b/Code/CryEngine/CryCommon/CryThreadImpl_windows.h deleted file mode 100644 index 1dd8dd4c26..0000000000 --- a/Code/CryEngine/CryCommon/CryThreadImpl_windows.h +++ /dev/null @@ -1,598 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif - -#include -#include -#include // for CreateSemaphore -struct SThreadNameDesc -{ - DWORD dwType; - LPCSTR szName; - DWORD dwThreadID; - DWORD dwFlags; -}; - -THREADLOCAL CrySimpleThreadSelf* CrySimpleThreadSelf::m_Self = NULL; - -////////////////////////////////////////////////////////////////////////// -CryEvent::CryEvent() -{ - m_handle = (void*)CreateEvent(NULL, FALSE, FALSE, NULL); -} - -////////////////////////////////////////////////////////////////////////// -CryEvent::~CryEvent() -{ - CloseHandle(m_handle); -} - -////////////////////////////////////////////////////////////////////////// -void CryEvent::Reset() -{ - ResetEvent(m_handle); -} - -////////////////////////////////////////////////////////////////////////// -void CryEvent::Set() -{ - SetEvent(m_handle); -} - -////////////////////////////////////////////////////////////////////////// -void CryEvent::Wait() const -{ - WaitForSingleObject(m_handle, INFINITE); -} - -////////////////////////////////////////////////////////////////////////// -bool CryEvent::Wait(const uint32 timeoutMillis) const -{ - if (WaitForSingleObject(m_handle, timeoutMillis) == WAIT_TIMEOUT) - { - return false; - } - return true; -} - -////////////////////////////////////////////////////////////////////////// -// CryLock_WinMutex -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -CryLock_WinMutex::CryLock_WinMutex() - : m_hdl(CreateMutex(NULL, FALSE, NULL)) {} -CryLock_WinMutex::~CryLock_WinMutex() -{ - CloseHandle(m_hdl); -} - -////////////////////////////////////////////////////////////////////////// -void CryLock_WinMutex::Lock() -{ - WaitForSingleObject(m_hdl, INFINITE); -} - -////////////////////////////////////////////////////////////////////////// -void CryLock_WinMutex::Unlock() -{ - ReleaseMutex(m_hdl); -} - -////////////////////////////////////////////////////////////////////////// -bool CryLock_WinMutex::TryLock() -{ - return WaitForSingleObject(m_hdl, 0) != WAIT_TIMEOUT; -} - -////////////////////////////////////////////////////////////////////////// -// CryLock_CritSection -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -CryLock_CritSection::CryLock_CritSection() -{ - InitializeCriticalSection((CRITICAL_SECTION*)&m_cs); -} - -////////////////////////////////////////////////////////////////////////// -CryLock_CritSection::~CryLock_CritSection() -{ - DeleteCriticalSection((CRITICAL_SECTION*)&m_cs); -} - -////////////////////////////////////////////////////////////////////////// -void CryLock_CritSection::Lock() -{ - EnterCriticalSection((CRITICAL_SECTION*)&m_cs); -} - -////////////////////////////////////////////////////////////////////////// -void CryLock_CritSection::Unlock() -{ - LeaveCriticalSection((CRITICAL_SECTION*)&m_cs); -} - -////////////////////////////////////////////////////////////////////////// -bool CryLock_CritSection::TryLock() -{ - return TryEnterCriticalSection((CRITICAL_SECTION*)&m_cs) != FALSE; -} - -////////////////////////////////////////////////////////////////////////// -// most of this is taken from http://www.cs.wustl.edu/~schmidt/win32-cv-1.html -////////////////////////////////////////////////////////////////////////// -CryConditionVariable::CryConditionVariable() -{ - m_waitersCount = 0; - m_wasBroadcast = 0; - m_sema = CreateSemaphore(NULL, 0, 0x7fffffff, NULL); - InitializeCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock); - m_waitersDone = CreateEvent(NULL, FALSE, FALSE, NULL); -} - -////////////////////////////////////////////////////////////////////////// -CryConditionVariable::~CryConditionVariable() -{ - CloseHandle(m_sema); - DeleteCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock); - CloseHandle(m_waitersDone); -} - -////////////////////////////////////////////////////////////////////////// -void CryConditionVariable::Wait(LockType& lock) -{ - EnterCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock); - m_waitersCount++; - LeaveCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock); - - SignalObjectAndWait(lock._get_win32_handle(), m_sema, INFINITE, FALSE); - - EnterCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock); - m_waitersCount--; - bool lastWaiter = m_wasBroadcast && m_waitersCount == 0; - LeaveCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock); - - if (lastWaiter) - { - SignalObjectAndWait(m_waitersDone, lock._get_win32_handle(), INFINITE, FALSE); - } - else - { - WaitForSingleObject(lock._get_win32_handle(), INFINITE); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CryConditionVariable::TimedWait(LockType& lock, uint32 millis) -{ - EnterCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock); - m_waitersCount++; - LeaveCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock); - - bool ok = true; - if (WAIT_TIMEOUT == SignalObjectAndWait(lock._get_win32_handle(), m_sema, millis, FALSE)) - { - ok = false; - } - - EnterCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock); - m_waitersCount--; - bool lastWaiter = m_wasBroadcast && m_waitersCount == 0; - LeaveCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock); - - if (lastWaiter) - { - SignalObjectAndWait(m_waitersDone, lock._get_win32_handle(), INFINITE, FALSE); - } - else - { - WaitForSingleObject(lock._get_win32_handle(), INFINITE); - } - - return ok; -} - -////////////////////////////////////////////////////////////////////////// -void CryConditionVariable::NotifySingle() -{ - EnterCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock); - bool haveWaiters = m_waitersCount > 0; - LeaveCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock); - if (haveWaiters) - { - ReleaseSemaphore(m_sema, 1, 0); - } -} - -////////////////////////////////////////////////////////////////////////// -void CryConditionVariable::Notify() -{ - EnterCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock); - bool haveWaiters = false; - if (m_waitersCount > 0) - { - m_wasBroadcast = 1; - haveWaiters = true; - } - if (haveWaiters) - { - ReleaseSemaphore(m_sema, m_waitersCount, 0); - LeaveCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock); - WaitForSingleObject(m_waitersDone, INFINITE); - m_wasBroadcast = 0; - } - else - { - LeaveCriticalSection((CRITICAL_SECTION*)&m_waitersCountLock); - } -} - -////////////////////////////////////////////////////////////////////////// -CrySemaphore::CrySemaphore(int nMaximumCount, int nInitialCount) -{ - m_Semaphore = (void*)CreateSemaphore(NULL, nInitialCount, nMaximumCount, NULL); -} - -////////////////////////////////////////////////////////////////////////// -CrySemaphore::~CrySemaphore() -{ - CloseHandle((HANDLE)m_Semaphore); -} - -////////////////////////////////////////////////////////////////////////// -void CrySemaphore::Acquire() -{ - WaitForSingleObject((HANDLE)m_Semaphore, INFINITE); -} - -////////////////////////////////////////////////////////////////////////// -void CrySemaphore::Release() -{ - ReleaseSemaphore((HANDLE)m_Semaphore, 1, NULL); -} - -////////////////////////////////////////////////////////////////////////// -CryFastSemaphore::CryFastSemaphore(int nMaximumCount, int nInitialCount) - : m_Semaphore(nMaximumCount) - , m_nCounter(nInitialCount) -{ -} - -////////////////////////////////////////////////////////////////////////// -CryFastSemaphore::~CryFastSemaphore() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CryFastSemaphore::Acquire() -{ - int nCount = ~0; - do - { - nCount = *const_cast(&m_nCounter); - } while (CryInterlockedCompareExchange(alias_cast(&m_nCounter), nCount - 1, nCount) != nCount); - - // if the count would have been 0 or below, go to kernel semaphore - if ((nCount - 1) < 0) - { - m_Semaphore.Acquire(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CryFastSemaphore::Release() -{ - int nCount = ~0; - do - { - nCount = *const_cast(&m_nCounter); - } while (CryInterlockedCompareExchange(alias_cast(&m_nCounter), nCount + 1, nCount) != nCount); - - // wake up kernel semaphore if we have waiter - if (nCount < 0) - { - m_Semaphore.Release(); - } -} - -////////////////////////////////////////////////////////////////////////// -CryRWLock::CryRWLock() -{ - STATIC_ASSERT(sizeof(m_Lock) == sizeof(PSRWLOCK), "RWLock-pointer has invalid size"); - InitializeSRWLock(reinterpret_cast(&m_Lock)); -} - -////////////////////////////////////////////////////////////////////////// -CryRWLock::~CryRWLock() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CryRWLock::RLock() -{ - AcquireSRWLockShared(reinterpret_cast(&m_Lock)); -} - -////////////////////////////////////////////////////////////////////////// -#if defined(_CRYTHREAD_WANT_TRY_RWLOCK) -bool CryRWLock::TryRLock() -{ - return TryAcquireSRWLockShared(reinterpret_cast(&m_Lock)) != 0; -} -#endif - -////////////////////////////////////////////////////////////////////////// -void CryRWLock::RUnlock() -{ - ReleaseSRWLockShared(reinterpret_cast(&m_Lock)); -} - -////////////////////////////////////////////////////////////////////////// -void CryRWLock::WLock() -{ - AcquireSRWLockExclusive(reinterpret_cast(&m_Lock)); -} - -////////////////////////////////////////////////////////////////////////// -#if defined(_CRYTHREAD_WANT_TRY_RWLOCK) -bool CryRWLock::TryWLock() -{ - return TryAcquireSRWLockExclusive(reinterpret_cast(&m_Lock)) != 0; -} -#endif - -////////////////////////////////////////////////////////////////////////// -void CryRWLock::WUnlock() -{ - ReleaseSRWLockExclusive(reinterpret_cast(&m_Lock)); -} - -////////////////////////////////////////////////////////////////////////// -void CryRWLock::Lock() -{ - WLock(); -} - -////////////////////////////////////////////////////////////////////////// -#if defined(_CRYTHREAD_WANT_TRY_RWLOCK) -bool CryRWLock::TryLock() -{ - return TryWLock(); -} -#endif - -////////////////////////////////////////////////////////////////////////// -void CryRWLock::Unlock() -{ - WUnlock(); -} - -////////////////////////////////////////////////////////////////////////// -CrySimpleThreadSelf::CrySimpleThreadSelf() - : m_thread(NULL) - , m_threadId(0) -{ -} - -////////////////////////////////////////////////////////////////////////// -void CrySimpleThreadSelf::WaitForThread() -{ - assert(m_thread); - PREFAST_ASSUME(m_thread); - if (GetCurrentThreadId() != m_threadId) - { - WaitForSingleObject((HANDLE)m_thread, INFINITE); - } -} - -CrySimpleThreadSelf::~CrySimpleThreadSelf() -{ - if (m_thread) - { - CloseHandle(m_thread); - } -} - -void CrySimpleThreadSelf::StartThread(unsigned (__stdcall * func)(void*), void* argList) -{ -#if defined(AZ_RESTRICTED_PLATFORM) - #include AZ_RESTRICTED_FILE(CryThreadImpl_windows_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - m_thread = (void*)_beginthreadex(NULL, 0, func, argList, CREATE_SUSPENDED, &m_threadId); -#endif - assert(m_thread); - PREFAST_ASSUME(m_thread); - ResumeThread((HANDLE)m_thread); -} - - -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -void CryInterlockedPushEntrySList(SLockFreeSingleLinkedListHeader& list, SLockFreeSingleLinkedListEntry& element) -{ - STATIC_CHECK(sizeof(SLockFreeSingleLinkedListHeader) == sizeof(SLIST_HEADER), CRY_INTERLOCKED_SLIST_HEADER_HAS_WRONG_SIZE); - STATIC_CHECK(sizeof(SLockFreeSingleLinkedListEntry) >= sizeof(SLIST_ENTRY), CRY_INTERLOCKED_SLIST_ENTRY_HAS_WRONG_SIZE); - - assert(IsAligned(&list, MEMORY_ALLOCATION_ALIGNMENT) && "LockFree SingleLink List Header has wrong Alignment"); - assert(IsAligned(&element, MEMORY_ALLOCATION_ALIGNMENT) && "LockFree SingleLink List Entry has wrong Alignment"); - InterlockedPushEntrySList(alias_cast(&list), alias_cast(&element)); -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedPopEntrySList(SLockFreeSingleLinkedListHeader& list) -{ - STATIC_CHECK(sizeof(SLockFreeSingleLinkedListHeader) == sizeof(SLIST_HEADER), CRY_INTERLOCKED_SLIST_HEADER_HAS_WRONG_SIZE); - - assert(IsAligned(&list, MEMORY_ALLOCATION_ALIGNMENT) && "LockFree SingleLink List Header has wrong Alignment"); - return reinterpret_cast(InterlockedPopEntrySList(alias_cast(&list))); -} - -////////////////////////////////////////////////////////////////////////// -void CryInitializeSListHead(SLockFreeSingleLinkedListHeader& list) -{ - assert(IsAligned(&list, MEMORY_ALLOCATION_ALIGNMENT) && "LockFree SingleLink List Header has wrong Alignment"); - - STATIC_CHECK(sizeof(SLockFreeSingleLinkedListHeader) == sizeof(SLIST_HEADER), CRY_INTERLOCKED_SLIST_HEADER_HAS_WRONG_SIZE); - InitializeSListHead(alias_cast(&list)); -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedFlushSList(SLockFreeSingleLinkedListHeader& list) -{ - assert(IsAligned(&list, MEMORY_ALLOCATION_ALIGNMENT) && "LockFree SingleLink List Header has wrong Alignment"); - - STATIC_CHECK(sizeof(SLockFreeSingleLinkedListHeader) == sizeof(SLIST_HEADER), CRY_INTERLOCKED_SLIST_HEADER_HAS_WRONG_SIZE); - return InterlockedFlushSList(alias_cast(&list)); -} - -/////////////////////////////////////////////////////////////////////////////// -// base class for lock less Producer/Consumer queue, due platforms specific they -// are implemeted in CryThead_platform.h -namespace CryMT { - namespace detail { - /////////////////////////////////////////////////////////////////////////////// - void SingleProducerSingleConsumerQueueBase::Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize) - { - // spin if queue is full - int iter = 0; - while (rProducerIndex - rComsumerIndex == nBufferSize) - { - CryLowLatencySleep(iter++ > 10 ? 1 : 0); - } - - MemoryBarrier(); - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = rProducerIndex % nBufferSize; - - memcpy(pBuffer + (nIndex * nObjectSize), pObj, nObjectSize); - MemoryBarrier(); - rProducerIndex += 1; - MemoryBarrier(); - } - - /////////////////////////////////////////////////////////////////////////////// - void SingleProducerSingleConsumerQueueBase::Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize) - { - MemoryBarrier(); - // busy-loop if queue is empty - int iter = 0; - while (rProducerIndex - rComsumerIndex == 0) - { - CryLowLatencySleep(iter++ > 10 ? 1 : 0); - } - - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = rComsumerIndex % nBufferSize; - - memcpy(pObj, pBuffer + (nIndex * nObjectSize), nObjectSize); - MemoryBarrier(); - rComsumerIndex += 1; - MemoryBarrier(); - } - - /////////////////////////////////////////////////////////////////////////////// - void N_ProducerSingleConsumerQueueBase::Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, [[maybe_unused]] volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates) - { - MemoryBarrier(); - uint32 nProducerIndex; - uint32 nComsumerIndex; - - int iter = 0; - do - { - nProducerIndex = rProducerIndex; - nComsumerIndex = rComsumerIndex; - - if (nProducerIndex - nComsumerIndex == nBufferSize) - { - CryLowLatencySleep(iter++ > 10 ? 1 : 0); - if (iter > 20) // 10 spins + 10 ms wait - { - uint32 nSizeToAlloc = sizeof(SFallbackList) + nObjectSize - 1; - SFallbackList* pFallbackEntry = (SFallbackList*)CryModuleMemalign(nSizeToAlloc, 128); - memcpy(pFallbackEntry->object, pObj, nObjectSize); - MemoryBarrier(); - CryInterlockedPushEntrySList(fallbackList, pFallbackEntry->nextEntry); - return; - } - continue; - } - - if (CryInterlockedCompareExchange(alias_cast(&rProducerIndex), nProducerIndex + 1, nProducerIndex) == nProducerIndex) - { - break; - } - } while (true); - - MemoryBarrier(); - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = nProducerIndex % nBufferSize; - - memcpy(pBuffer + (nIndex * nObjectSize), pObj, nObjectSize); - MemoryBarrier(); - arrStates[nIndex] = 1; - MemoryBarrier(); - } - - /////////////////////////////////////////////////////////////////////////////// - bool N_ProducerSingleConsumerQueueBase::Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates) - { - MemoryBarrier(); - - // busy-loop if queue is empty - int iter = 0; - if (rRunning && rProducerIndex - rComsumerIndex == 0) - { - while (rRunning && rProducerIndex - rComsumerIndex == 0) - { - CryLowLatencySleep(iter++ > 10 ? 1 : 0); - } - } - - if (rRunning == 0 && rProducerIndex - rComsumerIndex == 0) - { - SFallbackList* pFallback = (SFallbackList*)CryInterlockedPopEntrySList(fallbackList); - IF (pFallback, 0) - { - memcpy(pObj, pFallback->object, nObjectSize); - CryModuleMemalignFree(pFallback); - return true; - } - // if the queue was empty, make sure we really are empty - return false; - } - - iter = 0; - while (arrStates[rComsumerIndex % nBufferSize] == 0) - { - CryLowLatencySleep(iter++ > 10 ? 1 : 0); - } - - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = rComsumerIndex % nBufferSize; - - memcpy(pObj, pBuffer + (nIndex * nObjectSize), nObjectSize); - MemoryBarrier(); - arrStates[nIndex] = 0; - MemoryBarrier(); - rComsumerIndex += 1; - MemoryBarrier(); - - return true; - } - } // namespace detail -} // namespace CryMT diff --git a/Code/CryEngine/CryCommon/CryThread_dummy.h b/Code/CryEngine/CryCommon/CryThread_dummy.h deleted file mode 100644 index ea9804c6eb..0000000000 --- a/Code/CryEngine/CryCommon/CryThread_dummy.h +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYTHREAD_DUMMY_H -#define CRYINCLUDE_CRYCOMMON_CRYTHREAD_DUMMY_H -#pragma once - -#include - -////////////////////////////////////////////////////////////////////////// -CryEvent::CryEvent() {} -CryEvent::~CryEvent() {} -void CryEvent::Reset() {} -void CryEvent::Set() {} -void CryEvent::Wait() const {} -bool CryEvent::Wait(const uint32 timeoutMillis) const {} -typedef CryEvent CryEventTimed; - -////////////////////////////////////////////////////////////////////////// -class _DummyLock -{ -public: - _DummyLock(); - - void Lock(); - bool TryLock(); - void Unlock(); - -#if defined(AZ_DEBUG_BUILD) - bool IsLocked(); -#endif -}; - -template<> -class CryLock - : public _DummyLock -{ - CryLock(const CryLock&); - void operator = (const CryLock&); - -public: - CryLock(); -}; - -template<> -class CryLock - : public _DummyLock -{ - CryLock(const CryLock&); - void operator = (const CryLock&); - -public: - CryLock(); -}; - -template<> -class CryCondLock - : public CryLock -{ -}; - -template<> -class CryCondLock - : public CryLock -{ -}; - -template<> -class CryCond< CryLock > -{ - typedef CryLock LockT; - CryCond(const CryCond&); - void operator = (const CryCond&); - -public: - CryCond(); - - void Notify(); - void NotifySingle(); - void Wait(LockT&); - bool TimedWait(LockT &, uint32); -}; - -template<> -class CryCond< CryLock > -{ - typedef CryLock LockT; - CryCond(const CryCond&); - void operator = (const CryCond&); - -public: - CryCond(); - - void Notify(); - void NotifySingle(); - void Wait(LockT&); - bool TimedWait(LockT &, uint32); -}; - -class _DummyRWLock -{ -public: - _DummyRWLock() { } - - void RLock(); - bool TryRLock(); - void WLock(); - bool TryWLock(); - void Lock() { WLock(); } - bool TryLock() { return TryWLock(); } - void Unlock(); -}; - -template -class CrySimpleThread - : public CryRunnable -{ -public: - typedef void (* ThreadFunction)(void*); - - CrySimpleThread(); - virtual ~CrySimpleThread(); -#if !defined(NO_THREADINFO) - CryThreadInfo& GetInfo(); -#endif - const char* GetName(); - void SetName(const char*); - - virtual void Run(); - virtual void Cancel(); - virtual void Start(Runnable&, unsigned = 0, const char* = NULL); - virtual void Start(unsigned = 0, const char* = NULL); - void StartFunction(ThreadFunction, void* = NULL, unsigned = 0); - - void Exit(); - void Join(); - unsigned SetCpuMask(unsigned); - unsigned GetCpuMask(); - - void Stop(); - bool IsStarted() const; - bool IsRunning() const; -}; - -#endif // CRYINCLUDE_CRYCOMMON_CRYTHREAD_DUMMY_H - diff --git a/Code/CryEngine/CryCommon/CryThread_pthreads.h b/Code/CryEngine/CryCommon/CryThread_pthreads.h deleted file mode 100644 index b1d40dc10f..0000000000 --- a/Code/CryEngine/CryCommon/CryThread_pthreads.h +++ /dev/null @@ -1,1328 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include - - -#include -#include -#include -#include -#include - -#include -#include -#include - -// Section dictionary -#if defined(AZ_RESTRICTED_PLATFORM) -#define CRYTHREAD_PTHREADS_H_SECTION_REGISTER_THREAD 1 -#define CRYTHREAD_PTHREADS_H_SECTION_TRAITS 2 -#define CRYTHREAD_PTHREADS_H_SECTION_PTHREADCOND 3 -#define CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_CONSTRUCT 4 -#define CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_DESTROY 5 -#define CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_ACQUIRE 6 -#define CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_RELEASE 7 -#define CRYTHREAD_PTHREADS_H_SECTION_TRY_RLOCK 8 -#define CRYTHREAD_PTHREADS_H_SECTION_TRY_WLOCK 9 -#define CRYTHREAD_PTHREADS_H_SECTION_START_RUNNABLE 10 -#define CRYTHREAD_PTHREADS_H_SECTION_START_CPUMASK 11 -#define CRYTHREAD_PTHREADS_H_SECTION_START_CPUMASK_POSTCREATE 12 -#define CRYTHREAD_PTHREADS_H_SECTION_SETCPUMASK 13 -#define CRYTHREAD_PTHREADS_H_SECTION_START_RUNNABLE_CPUMASK_POSTCREATE 14 -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_REGISTER_THREAD - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) - #undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#endif - -#if !defined(RegisterThreadName) - #define RegisterThreadName(id, name) - #define UnRegisterThreadName(id) -#endif - -#if defined(APPLE) || defined(ANDROID) -// PTHREAD_MUTEX_FAST_NP is only defined by Pthreads-w32, thus not on MAC - #define PTHREAD_MUTEX_FAST_NP PTHREAD_MUTEX_NORMAL -#endif - -// Define LARGE_THREAD_STACK to use larger than normal per-thread stack -#if defined(_DEBUG) && (defined(MAC) || defined(LINUX) || defined(AZ_PLATFORM_IOS)) -#define LARGE_THREAD_STACK -#endif - -#if defined(LINUX) -#undef RegisterThreadName -ILINE void RegisterThreadName(pthread_t id, const char* name) -{ - if ((!name) || (!id)) - { - return; - } - int ret; - // pthread names on linux are limited to 16 char - if (strlen(name) >= 16) - { - char thread_name[16]; - memcpy(thread_name, name, 15); - thread_name[15] = 0; - ret = pthread_setname_np(id, thread_name); - } - else - { - ret = pthread_setname_np(id, name); - } - if (ret != 0) - { - CryLog("Failed to set thread name for %" PRI_THREADID ", name: %s", id, name); - } -} -#endif - -#if !defined _CRYTHREAD_HAVE_LOCK -template -class _PthreadCond; -template -class _PthreadLockBase; - -template -class _PthreadLockAttr -{ - friend class _PthreadLockBase; - -protected: - _PthreadLockAttr() - { - pthread_mutexattr_init(&m_Attr); - pthread_mutexattr_settype(&m_Attr, PthreadMutexType); - } - ~_PthreadLockAttr() - { - pthread_mutexattr_destroy(&m_Attr); - } - pthread_mutexattr_t m_Attr; -}; - -template -class _PthreadLockBase -{ -protected: - static pthread_mutexattr_t& GetAttr() - { - static _PthreadLockAttr m_Attr; - return m_Attr.m_Attr; - } -}; - -template -class _PthreadLock - : public _PthreadLockBase -{ - friend class _PthreadCond; - - //#if defined(_DEBUG) -public: - //#endif - pthread_mutex_t m_Lock; - -public: - _PthreadLock() - : LockCount(0) - { - pthread_mutex_init( - &m_Lock, - &_PthreadLockBase::GetAttr()); - } - ~_PthreadLock() { pthread_mutex_destroy(&m_Lock); } - - void Lock() { pthread_mutex_lock(&m_Lock); CryInterlockedIncrement(&LockCount); } - - bool TryLock() - { - const int rc = pthread_mutex_trylock(&m_Lock); - if (0 == rc) - { - CryInterlockedIncrement(&LockCount); - return true; - } - return false; - } - - void Unlock() { CryInterlockedDecrement(&LockCount); pthread_mutex_unlock(&m_Lock); } - - // Get the POSIX pthread_mutex_t. - // Warning: - // This method will not be available in the Win32 port of CryThread. - pthread_mutex_t& Get_pthread_mutex_t() { return m_Lock; } - - bool IsLocked() - { -#if defined(LINUX) || defined(APPLE) - // implementation taken from CrysisWars - return LockCount > 0; -#else - return true; -#endif - } - -private: - volatile int LockCount; -}; - -#if defined CRYLOCK_HAVE_FASTLOCK - #if defined(_DEBUG) && defined(PTHREAD_MUTEX_ERRORCHECK_NP) -template<> -class CryLockT - : public _PthreadLock, PTHREAD_MUTEX_ERRORCHECK_NP> - #else -template<> -class CryLockT - : public _PthreadLock, PTHREAD_MUTEX_FAST_NP> - #endif -{ - CryLockT(const CryLockT&); - void operator = (const CryLockT&); - -public: - CryLockT() { } -}; -#endif // CRYLOCK_HAVE_FASTLOCK - -template<> -class CryLockT - : public _PthreadLock, PTHREAD_MUTEX_RECURSIVE> -{ - CryLockT(const CryLockT&); - void operator = (const CryLockT&); - -public: - CryLockT() { } -}; - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_TRAITS - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#else -#if !defined(LINUX) && !defined(APPLE) -#define CRYTHREAD_PTHREADS_H_TRAIT_DEFINE_CRYMUTEX 1 -#endif -#if !defined(LINUX) && !defined(APPLE) -#define CRYTHREAD_PTHREADS_H_TRAIT_SET_THREAD_NAME 1 -#endif -#endif - -#if CRYTHREAD_PTHREADS_H_TRAIT_DEFINE_CRYMUTEX -#if defined CRYLOCK_HAVE_FASTLOCK -class CryMutex - : public CryLockT -{ -}; -#else -class CryMutex - : public CryLockT -{ -}; -#endif -#endif // CRYTHREAD_PTHREADS_TRAIT_DEFINE_CRYMUTEX - -template -class _PthreadCond -{ - pthread_cond_t m_Cond; - -public: - _PthreadCond() { pthread_cond_init(&m_Cond, NULL); } - ~_PthreadCond() { pthread_cond_destroy(&m_Cond); } - void Notify() { pthread_cond_broadcast(&m_Cond); } - void NotifySingle() { pthread_cond_signal(&m_Cond); } - void Wait(LockClass& Lock) { pthread_cond_wait(&m_Cond, &Lock.m_Lock); } - bool TimedWait(LockClass& Lock, uint32 milliseconds) - { - struct timeval now; - struct timespec timeout; - int err; - - gettimeofday(&now, NULL); - while (true) - { - timeout.tv_sec = now.tv_sec + milliseconds / 1000; - uint64 nsec = (uint64)now.tv_usec * 1000 + (uint64)milliseconds * 1000000; - if (nsec >= 1000000000) - { - timeout.tv_sec += (long)(nsec / 1000000000); - nsec %= 1000000000; - } - timeout.tv_nsec = (long)nsec; -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_PTHREADCOND - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) - #undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - err = pthread_cond_timedwait(&m_Cond, &Lock.m_Lock, &timeout); - if (err == EINTR) - { - // Interrupted by a signal. - continue; - } - else if (err == ETIMEDOUT) - { - return false; - } -#endif - else - { - assert(err == 0); - } - break; - } - return true; - } - - // Get the POSIX pthread_cont_t. - // Warning: - // This method will not be available in the Win32 port of CryThread. - pthread_cond_t& Get_pthread_cond_t() { return m_Cond; } -}; - -#if AZ_LEGACY_CRYCOMMON_TRAIT_USE_PTHREADS -template -class CryConditionVariableT - : public _PthreadCond -{ -}; - -#if defined CRYLOCK_HAVE_FASTTLOCK -template<> -class CryConditionVariableT< CryLockT > - : public _PthreadCond< CryLockT > -{ - typedef CryLockT LockClass; - CryConditionVariableT(const CryConditionVariableT&); - CryConditionVariableT& operator = (const CryConditionVariableT&); - -public: - CryConditionVariableT() { } -}; -#endif // CRYLOCK_HAVE_FASTLOCK - -template<> -class CryConditionVariableT< CryLockT > - : public _PthreadCond< CryLockT > -{ - typedef CryLockT LockClass; - CryConditionVariableT(const CryConditionVariableT&); - CryConditionVariableT& operator = (const CryConditionVariableT&); - -public: - CryConditionVariableT() { } -}; - -#if !defined(_CRYTHREAD_CONDLOCK_GLITCH) -typedef CryConditionVariableT< CryLockT > CryConditionVariable; -#else -typedef CryConditionVariableT< CryLockT > CryConditionVariable; -#endif - -#define _CRYTHREAD_HAVE_LOCK 1 - -#else // LINUX MAC - -#if defined CRYLOCK_HAVE_FASTLOCK -template<> -class CryConditionVariable - : public _PthreadCond< CryLockT > -{ - typedef CryLockT LockClass; - CryConditionVariable(const CryConditionVariable&); - CryConditionVariable& operator = (const CryConditionVariable&); - -public: - CryConditionVariable() { } -}; -#endif // CRYLOCK_HAVE_FASTLOCK - -template<> -class CryConditionVariable - : public _PthreadCond< CryLockT > -{ - typedef CryLockT LockClass; - CryConditionVariable(const CryConditionVariable&); - CryConditionVariable& operator = (const CryConditionVariable&); - -public: - CryConditionVariable() { } -}; - -#define _CRYTHREAD_HAVE_LOCK 1 - -#endif // LINUX MAC -#endif // !defined _CRYTHREAD_HAVE_LOCK - -////////////////////////////////////////////////////////////////////////// -// Platform independet wrapper for a counting semaphore -class CrySemaphore -{ -public: - CrySemaphore(int nMaximumCount, int nInitialCount = 0); - ~CrySemaphore(); - - void Acquire(); - void Release(); - -private: -#if defined(APPLE) - // Apple only supports named semaphores so have to use sem_open/unlink/sem_close instead - // of sem_open/sem_destroy, passing in this array for the name. - char m_semaphoreName[L_tmpnam]; -#endif - sem_t* m_Semaphore; -}; - -////////////////////////////////////////////////////////////////////////// -inline CrySemaphore::CrySemaphore(int nMaximumCount, int nInitialCount) -{ -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_CONSTRUCT - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) - #undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(APPLE) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wdeprecated-declarations" - tmpnam(m_semaphoreName); -# pragma clang diagnostic pop - m_Semaphore = sem_open(m_semaphoreName, O_CREAT | O_EXCL, 0644, nInitialCount); -#else - m_Semaphore = new sem_t; - sem_init(m_Semaphore, 0, nInitialCount); -#endif -} - -////////////////////////////////////////////////////////////////////////// -inline CrySemaphore::~CrySemaphore() -{ -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_DESTROY - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) - #undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(APPLE) - sem_close(m_Semaphore); - sem_unlink(m_semaphoreName); -#else - sem_destroy(m_Semaphore); - delete m_Semaphore; -#endif -} - -////////////////////////////////////////////////////////////////////////// -inline void CrySemaphore::Acquire() -{ -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_ACQUIRE - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) - #undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - while (sem_wait(m_Semaphore) != 0 && errno == EINTR) - { - ; - } -#endif -} - -////////////////////////////////////////////////////////////////////////// -inline void CrySemaphore::Release() -{ -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_SEMAPHORE_RELEASE - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) - #undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - sem_post(m_Semaphore); -#endif -} - -////////////////////////////////////////////////////////////////////////// -// Platform independet wrapper for a counting semaphore -// except that this version uses C-A-S only until a blocking call is needed -// -> No kernel call if there are object in the semaphore - -class CryFastSemaphore -{ -public: - CryFastSemaphore(int nMaximumCount, int nInitialCount = 0); - ~CryFastSemaphore(); - void Acquire(); - void Release(); - -private: - CrySemaphore m_Semaphore; - volatile int32 m_nCounter; -}; - -////////////////////////////////////////////////////////////////////////// -inline CryFastSemaphore::CryFastSemaphore(int nMaximumCount, int nInitialCount) - : m_Semaphore(nMaximumCount) - , m_nCounter(nInitialCount) -{ -} - -////////////////////////////////////////////////////////////////////////// -inline CryFastSemaphore::~CryFastSemaphore() -{ -} - -///////////////////////////////////////////////////////////////////////// -inline void CryFastSemaphore::Acquire() -{ - int nCount = ~0; - do - { - nCount = *const_cast(&m_nCounter); - } while (CryInterlockedCompareExchange(alias_cast(&m_nCounter), nCount - 1, nCount) != nCount); - - // if the count would have been 0 or below, go to kernel semaphore - if ((nCount - 1) < 0) - { - m_Semaphore.Acquire(); - } -} - -////////////////////////////////////////////////////////////////////////// -inline void CryFastSemaphore::Release() -{ - int nCount = ~0; - do - { - nCount = *const_cast(&m_nCounter); - } while (CryInterlockedCompareExchange(alias_cast(&m_nCounter), nCount + 1, nCount) != nCount); - - // wake up kernel semaphore if we have waiter - if (nCount < 0) - { - m_Semaphore.Release(); - } -} - -////////////////////////////////////////////////////////////////////////// -#if !defined _CRYTHREAD_HAVE_RWLOCK -class CryRWLock -{ - pthread_rwlock_t m_Lock; - - CryRWLock(const CryRWLock&); - CryRWLock& operator= (const CryRWLock&); - -public: - CryRWLock() { pthread_rwlock_init(&m_Lock, NULL); } - ~CryRWLock() { pthread_rwlock_destroy(&m_Lock); } - void RLock() { pthread_rwlock_rdlock(&m_Lock); } - bool TryRLock() - { -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_TRY_RLOCK - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) - #undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - return pthread_rwlock_tryrdlock(&m_Lock) != EBUSY; -#endif - } - void RUnlock() { Unlock(); } - void WLock() { pthread_rwlock_wrlock(&m_Lock); } - bool TryWLock() - { -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_TRY_RLOCK - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) - #undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - return pthread_rwlock_trywrlock(&m_Lock) != EBUSY; -#endif - } - void WUnlock() { Unlock(); } - void Lock() { WLock(); } - bool TryLock() { return TryWLock(); } - void Unlock() { pthread_rwlock_unlock(&m_Lock); } -}; - -// Indicate that this implementation header provides an implementation for -// CryRWLock. -#define _CRYTHREAD_HAVE_RWLOCK 1 -#endif // !defined _CRYTHREAD_HAVE_RWLOCK - - -//////////////////////////////////////////////////////////////////////////////// -// Provide TLS implementation using pthreads for those platforms without __thread -//////////////////////////////////////////////////////////////////////////////// - -struct SCryPthreadTLSBase -{ - SCryPthreadTLSBase(void (*pDestructor)(void*)) - { - pthread_key_create(&m_kKey, pDestructor); - } - - ~SCryPthreadTLSBase() - { - pthread_key_delete(m_kKey); - } - - void* GetSpecific() - { - return pthread_getspecific(m_kKey); - } - - void SetSpecific(const void* pValue) - { - pthread_setspecific(m_kKey, pValue); - } - - pthread_key_t m_kKey; -}; - -template -struct SCryPthreadTLSImpl{}; - -template -struct SCryPthreadTLSImpl - : private SCryPthreadTLSBase -{ - SCryPthreadTLSImpl() - : SCryPthreadTLSBase(NULL) - { - } - - T Get() - { - void* pSpecific(GetSpecific()); - return *reinterpret_cast(&pSpecific); - } - - void Set(const T& kValue) - { - SetSpecific(*reinterpret_cast(&kValue)); - } -}; - -template -struct SCryPthreadTLSImpl - : private SCryPthreadTLSBase -{ - SCryPthreadTLSImpl() - : SCryPthreadTLSBase(&Destroy) - { - } - - T* GetPtr() - { - T* pPtr(static_cast(GetSpecific())); - if (pPtr == NULL) - { - pPtr = new T(); - SetSpecific(pPtr); - } - return pPtr; - } - - static void Destroy(void* pPointer) - { - delete static_cast(pPointer); - } - - const T& Get() - { - return *GetPtr(); - } - - void Set(const T& kValue) - { - *GetPtr() = kValue; - } -}; - -template -struct SCryPthreadTLS - : SCryPthreadTLSImpl -{ -}; - - -////////////////////////////////////////////////////////////////////////// -// CryEvent(Timed) represent a synchronization event -////////////////////////////////////////////////////////////////////////// -class CryEventTimed -{ -public: - ILINE CryEventTimed(){m_flag = false; } - ILINE ~CryEventTimed(){} - - // Reset the event to the unsignalled state. - void Reset(); - // Set the event to the signalled state. - void Set(); - // Access a HANDLE to wait on. - void* GetHandle() const { return NULL; }; - // Wait indefinitely for the object to become signalled. - void Wait(); - // Wait, with a time limit, for the object to become signalled. - bool Wait(const uint32 timeoutMillis); - -private: - // Lock for synchronization of notifications. - CryCriticalSection m_lockNotify; -#if defined(LINUX) || defined(APPLE) - CryConditionVariableT< CryLockT > m_cond; -#else - CryConditionVariable m_cond; -#endif - volatile bool m_flag; -}; - -typedef CryEventTimed CryEvent; - -#if !PLATFORM_SUPPORTS_THREADLOCAL -TLS_DECLARE(class CrySimpleThreadSelf*, g_CrySimpleThreadSelf); -#endif - -class CrySimpleThreadSelf -{ -protected: -#if PLATFORM_SUPPORTS_THREADLOCAL - - static CrySimpleThreadSelf* GetSelf() - { - return m_Self; - } - - static void SetSelf(CrySimpleThreadSelf* pSelf) - { - m_Self = pSelf; - } -private: - static THREADLOCAL CrySimpleThreadSelf* m_Self; - -#else - - static CrySimpleThreadSelf* GetSelf() - { - return TLS_GET(CrySimpleThreadSelf*, g_CrySimpleThreadSelf); - } - - static void SetSelf(CrySimpleThreadSelf* pSelf) - { - TLS_SET(g_CrySimpleThreadSelf, pSelf); - } - -#endif -}; - -template -class CrySimpleThread - : public CryRunnable - , protected CrySimpleThreadSelf -{ -public: - typedef void (* ThreadFunction)(void*); - typedef CryRunnable RunnableT; - - const volatile bool& GetStartedState() const { return m_bIsStarted; } - -private: -#if !defined(NO_THREADINFO) - CryThreadInfo m_Info; -#endif - pthread_t m_ThreadID; - unsigned m_CpuMask; - Runnable* m_Runnable; - struct - { - ThreadFunction m_ThreadFunction; - void* m_ThreadParameter; - } m_ThreadFunction; - volatile bool m_bIsStarted; - volatile bool m_bIsRunning; - -protected: - virtual void Terminate() - { - // This method must be empty. - // Derived classes overriding Terminate() are not required to call this - // method. - } - -private: -#if !defined(NO_THREADINFO) - static void SetThreadInfo(CrySimpleThread* self) - { - pthread_t thread = pthread_self(); - self->m_Info.m_ID = (uint32)(TRUNCATE_PTR)thread; -#if defined(APPLE) - pthread_setname_np(self->m_Info.m_Name.c_str()); -#endif - } -#else - static void SetThreadInfo(CrySimpleThread* self) { } -#endif - - static void* PthreadRunRunnable(void* thisPtr) - { - CrySimpleThread* const self = (CrySimpleThread*)thisPtr; - SetSelf(self); - self->m_bIsStarted = true; - self->m_bIsRunning = true; - SetThreadInfo(self); - self->m_Runnable->Run(); - self->m_bIsRunning = false; - self->Terminate(); - SetSelf(NULL); - return NULL; - } - - static void* PthreadRunThis(void* thisPtr) - { - CrySimpleThread* const self = (CrySimpleThread*)thisPtr; - SetSelf(self); - self->m_bIsStarted = true; - self->m_bIsRunning = true; - SetThreadInfo(self); - self->Run(); - self->m_bIsRunning = false; - self->Terminate(); - SetSelf(NULL); - return NULL; - } - - CrySimpleThread(const CrySimpleThread&); - void operator = (const CrySimpleThread&); - -public: - CrySimpleThread() - : m_CpuMask(0) - , m_bIsStarted(false) - , m_bIsRunning(false) - { - m_ThreadFunction.m_ThreadFunction = NULL; - m_ThreadFunction.m_ThreadParameter = NULL; -#if !defined(NO_THREADINFO) - m_Info.m_Name = ""; - m_Info.m_ID = 0; -#endif - memset(&m_ThreadID, 0, sizeof m_ThreadID); - m_Runnable = NULL; - } - - virtual ~CrySimpleThread() - { - if (IsStarted()) - { - // Note: We don't want to cache a pointer to ISystem and/or ILog to - // gain more freedom on when the threading classes are used (e.g. - // threads may be started very early in the initialization). - ISystem* pSystem = GetISystem(); - ILog* pLog = NULL; - if (pSystem != NULL) - { - pLog = pSystem->GetILog(); - } - if (pLog != NULL) - { - pLog->LogError("Runaway thread %s", GetName()); - } - Cancel(); - WaitForThread(); - } - } - -#if !defined(NO_THREADINFO) - CryThreadInfo& GetInfo() { return m_Info; } - const char* GetName() - { - return m_Info.m_Name.c_str(); - } - - // Set the name of the called thread. - // - // WIN32: - // If the thread is started, then the VC debugger is informed about the new - // thread name. If the thread is not started, then the VC debugger will be - // informed lated when the thread is started through one of the Start() - // methods. - // - // If the parameter Name is NULL, then the name of the thread is kept - // unchanged. This may be used to sent the current thread name to the VC - // debugger. - void SetName(const char* Name) - { - if (Name != NULL) - { - if (m_ThreadID) - { - RegisterThreadName(m_ThreadID, Name); - } - m_Info.m_Name = Name; - } -#if defined(WIN32) - if (IsStarted()) - { - // The VC debugger gets the information about a thread's name through - // the exception 0x406D1388. - struct - { - DWORD Type; - const char* Name; - DWORD ID; - DWORD Flags; - } Info = { 0x1000, NULL, 0, 0 }; - Info.ID = (DWORD)m_Info.m_ID; - __try - { - RaiseException( - 0x406D1388, 0, sizeof Info / sizeof(DWORD), (ULONG_PTR*)&Info); - } - __except (EXCEPTION_CONTINUE_EXECUTION) - { - } - } -#endif - } -#else -#if !defined(NO_THREADINFO) - CryThreadInfo& GetInfo() - { - static CryThreadInfo dummyInfo = { "", 0 }; - return dummyInfo; - } -#endif - const char* GetName() { return ""; } - void SetName(const char* Name) { } -#endif - - virtual void Run() - { - // This Run() implementation supports the void StartFunction() method. - // However, code using this class (or derived classes) should eventually - // be refactored to use one of the other Start() methods. This code will - // be removed some day and the default implementation of Run() will be - // empty. - if (m_ThreadFunction.m_ThreadFunction != NULL) - { - m_ThreadFunction.m_ThreadFunction(m_ThreadFunction.m_ThreadParameter); - } - } - - // Cancel the running thread. - // - // If the thread class is implemented as a derived class of CrySimpleThread, - // then the derived class should provide an appropriate implementation for - // this method. Calling the base class implementation is _not_ required. - // - // If the thread was started by specifying a Runnable (template argument), - // then the Cancel() call is passed on to the specified runnable. - // - // If the thread was started using the StartFunction() method, then the - // caller must find other means to inform the thread about the cancellation - // request. - virtual void Cancel() - { - if (IsStarted() && m_Runnable != NULL) - { - UnRegisterThreadName(m_ThreadID); - m_Runnable->Cancel(); - } - } - - virtual void Start(Runnable& runnable, unsigned cpuMask = 0, const char* name = NULL, int32 StackSize = (SIMPLE_THREAD_STACK_SIZE_KB * 1024)) - { -#if defined(LARGE_THREAD_STACK) - StackSize *= 4;//debug code needs a lot more than profile -#endif - assert(m_ThreadID == 0); - pthread_attr_t threadAttr; - pthread_attr_init(&threadAttr); - pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_JOINABLE); - pthread_attr_setstacksize(&threadAttr, StackSize); - if (name) - { - this->m_Info.m_Name = name; - } -#if CRYTHREAD_PTHREADS_H_TRAIT_SET_THREAD_NAME - threadAttr.name = (char*)name; -#endif - m_CpuMask = cpuMask; -#if defined(PTHREAD_NPTL) - if (cpuMask != ~0 && cpuMask != 0) - { - cpu_set_t cpuSet; - CPU_ZERO(&cpuSet); - for (int cpu = 0; cpu < sizeof(cpuMask) * 8; ++cpu) - { - if (cpuMask & (1 << cpu)) - { - CPU_SET(cpu, &cpuSet); - } - } - pthread_attr_setaffinity_np(&threadAttr, sizeof cpuSet, &cpuSet); - } -#elif defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_START_RUNNABLE - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif - m_Runnable = &runnable; - int err = pthread_create( - &m_ThreadID, - &threadAttr, - PthreadRunRunnable, - this); - pthread_attr_destroy(&threadAttr); - RegisterThreadName(m_ThreadID, name); -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_START_RUNNABLE_CPUMASK_POSTCREATE - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif - assert(err == 0); - } - - virtual void Start(unsigned cpuMask = 0, const char* name = NULL, int32 Priority = THREAD_PRIORITY_NORMAL, int32 StackSize = (SIMPLE_THREAD_STACK_SIZE_KB * 1024)) - { -#if defined(LARGE_THREAD_STACK) - StackSize *= 4;//debug code needs a lot more than profile -#endif - assert(m_ThreadID == 0); - pthread_attr_t threadAttr; - sched_param schedParam; - pthread_attr_init(&threadAttr); - pthread_attr_getschedparam(&threadAttr, &schedParam); - schedParam.sched_priority = Priority; - pthread_attr_setschedparam(&threadAttr, &schedParam); - pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_JOINABLE); - pthread_attr_setstacksize(&threadAttr, StackSize); - if (name) - { - this->m_Info.m_Name = name; - } -#if CRYTHREAD_PTHREADS_H_TRAIT_SET_THREAD_NAME - threadAttr.name = (char*)name; -#endif - m_CpuMask = cpuMask; -#if defined(PTHREAD_NPTL) - if (cpuMask != ~0 && cpuMask != 0) - { - cpu_set_t cpuSet; - CPU_ZERO(&cpuSet); - for (int cpu = 0; cpu < sizeof(cpuMask) * 8; ++cpu) - { - if (cpuMask & (1 << cpu)) - { - CPU_SET(cpu, &cpuSet); - } - } - pthread_attr_setaffinity_np(&threadAttr, sizeof cpuSet, &cpuSet); - } -#elif defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_START_CPUMASK - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif - int err = pthread_create( - &m_ThreadID, - &threadAttr, - PthreadRunThis, - this); - pthread_attr_destroy(&threadAttr); - RegisterThreadName(m_ThreadID, name); -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_START_CPUMASK_POSTCREATE - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif - assert(err == 0); - } - - void StartFunction( - ThreadFunction threadFunction, - void* threadParameter = NULL, - unsigned cpuMask = 0 - ) - { - m_ThreadFunction.m_ThreadFunction = threadFunction; - m_ThreadFunction.m_ThreadParameter = threadParameter; - Start(cpuMask); - } - - static CrySimpleThread* Self() - { - return reinterpret_cast*>(GetSelf()); - } - - void Exit() - { - assert(m_ThreadID == pthread_self()); - m_bIsRunning = false; - Terminate(); - SetSelf(NULL); - pthread_exit(NULL); - UnRegisterThreadName(m_ThreadID); - } - - void WaitForThread() - { - if (pthread_self() != m_ThreadID) - { - int err = pthread_join(m_ThreadID, NULL); - assert(err == 0); - } - m_bIsStarted = false; - memset(&m_ThreadID, 0, sizeof m_ThreadID); - } - - unsigned SetCpuMask(unsigned cpuMask) - { - int oldCpuMask = m_CpuMask; - if (cpuMask == m_CpuMask) - { - return oldCpuMask; - } - m_CpuMask = cpuMask; -#if defined(PTHREAD_NPTL) - cpu_set_t cpuSet; - CPU_ZERO(&cpuSet); - if (cpuMask != ~0 && cpuMask != 0) - { - for (int cpu = 0; cpu < sizeof(cpuMask) * 8; ++cpu) - { - if (cpuMask & (1 << cpu)) - { - CPU_SET(cpu, &cpuSet); - } - } - else - { - CPU_ZERO(&cpuSet); - for (int cpu = 0; i < sizeof(cpuSet) * 8; ++cpu) - { - CPU_SET(cpu, &cpuSet); - } - } - pthread_attr_setaffinity_np(&threadAttr, sizeof cpuSet, &cpuSet); -#elif defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_SETCPUMASK - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif - return oldCpuMask; - } - - unsigned GetCpuMask() { return m_CpuMask; } - - void Stop() - { - m_bIsStarted = false; - } - - bool IsStarted() const { return m_bIsStarted; } - bool IsRunning() const { return m_bIsRunning; } - }; - -#include "MemoryAccess.h" - - /////////////////////////////////////////////////////////////////////////////// - // base class for lock less Producer/Consumer queue, due platforms specific they - // are implemeted in CryThead_platform.h - namespace CryMT { - namespace detail { - /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// - class SingleProducerSingleConsumerQueueBase - { - public: - SingleProducerSingleConsumerQueueBase() - {} - - void Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize); - void Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize); - }; - - /////////////////////////////////////////////////////////////////////////////// - inline void SingleProducerSingleConsumerQueueBase::Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize) - { - MemoryBarrier(); - // spin if queue is full - int iter = 0; - while (rProducerIndex - rComsumerIndex == nBufferSize) - { - Sleep(iter++ > 10 ? 1 : 0); - } - - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = rProducerIndex % nBufferSize; - memcpy(pBuffer + (nIndex * nObjectSize), pObj, nObjectSize); - - MemoryBarrier(); - rProducerIndex += 1; - MemoryBarrier(); - } - - /////////////////////////////////////////////////////////////////////////////// - inline void SingleProducerSingleConsumerQueueBase::Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize) - { - MemoryBarrier(); - // busy-loop if queue is empty - int iter = 0; - while (rProducerIndex - rComsumerIndex == 0) - { - Sleep(iter++ > 10 ? 1 : 0); - } - - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = rComsumerIndex % nBufferSize; - - memcpy(pObj, pBuffer + (nIndex * nObjectSize), nObjectSize); - - MemoryBarrier(); - rComsumerIndex += 1; - MemoryBarrier(); - } - - - /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// - class N_ProducerSingleConsumerQueueBase - { - public: - N_ProducerSingleConsumerQueueBase() - { - CryInitializeSListHead(fallbackList); - } - - void Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates); - bool Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates); - - SLockFreeSingleLinkedListHeader fallbackList; - struct SFallbackList - { - SLockFreeSingleLinkedListEntry nextEntry; - char alignment_padding[128 - sizeof(SLockFreeSingleLinkedListEntry)]; - char object[1]; // struct will be overallocated with enough memory for the object - }; - }; - - /////////////////////////////////////////////////////////////////////////////// - inline void N_ProducerSingleConsumerQueueBase::Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates) - { - MemoryBarrier(); - uint32 nProducerIndex; - uint32 nComsumerIndex; - - int iter = 0; - do - { - nProducerIndex = rProducerIndex; - nComsumerIndex = rComsumerIndex; - - if (nProducerIndex - nComsumerIndex == nBufferSize) - { - Sleep(iter++ > 10 ? 1 : 0); - if (iter > 20) // 10 spins + 10 ms wait - { - uint32 nSizeToAlloc = sizeof(SFallbackList) + nObjectSize - 1; - SFallbackList* pFallbackEntry = (SFallbackList*)CryModuleMemalign(nSizeToAlloc, 128); - memcpy(pFallbackEntry->object, pObj, nObjectSize); - CryInterlockedPushEntrySList(fallbackList, pFallbackEntry->nextEntry); - return; - } - continue; - } - - if (CryInterlockedCompareExchange(alias_cast(&rProducerIndex), nProducerIndex + 1, nProducerIndex) == nProducerIndex) - { - break; - } - } while (true); - - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = nProducerIndex % nBufferSize; - - memcpy(pBuffer + (nIndex * nObjectSize), pObj, nObjectSize); - - MemoryBarrier(); - arrStates[nIndex] = 1; - MemoryBarrier(); - } - - /////////////////////////////////////////////////////////////////////////////// - inline bool N_ProducerSingleConsumerQueueBase::Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates) - { - MemoryBarrier(); - // busy-loop if queue is empty - int iter = 0; - do - { - SFallbackList* pFallback = (SFallbackList*)CryInterlockedPopEntrySList(fallbackList); - IF (pFallback, 0) - { - memcpy(pObj, pFallback->object, nObjectSize); - CryModuleMemalignFree(pFallback); - return true; - } - - if (iter > 10) - { - Sleep(iter > 100 ? 1 : 0); - } - iter++; - } while (rRunning && rProducerIndex - rComsumerIndex == 0); - - if (rRunning == 0 && rProducerIndex - rComsumerIndex == 0) - { - // if the queue was empty, make sure we really are empty - SFallbackList* pFallback = (SFallbackList*)CryInterlockedPopEntrySList(fallbackList); - IF (pFallback, 0) - { - memcpy(pObj, pFallback->object, nObjectSize); - CryModuleMemalignFree(pFallback); - return true; - } - return false; - } - - iter = 0; - while (arrStates[rComsumerIndex % nBufferSize] == 0) - { - Sleep(iter++ > 10 ? 1 : 0); - } - - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = rComsumerIndex % nBufferSize; - - memcpy(pObj, pBuffer + (nIndex * nObjectSize), nObjectSize); - - MemoryBarrier(); - arrStates[nIndex] = 0; - MemoryBarrier(); - rComsumerIndex += 1; - MemoryBarrier(); - - return true; - } - } // namespace detail - } // namespace CryMT diff --git a/Code/CryEngine/CryCommon/CryThread_windows.h b/Code/CryEngine/CryCommon/CryThread_windows.h deleted file mode 100644 index ae8068801e..0000000000 --- a/Code/CryEngine/CryCommon/CryThread_windows.h +++ /dev/null @@ -1,464 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define CRYTHREAD_WINDOWS_H_SECTION_1 1 -#define CRYTHREAD_WINDOWS_H_SECTION_2 2 -#endif - -////////////////////////////////////////////////////////////////////////// -// CryEvent represent a synchronization event -////////////////////////////////////////////////////////////////////////// -class CryEvent -{ -public: - CryEvent(); - ~CryEvent(); - - // Reset the event to the unsignalled state. - void Reset(); - // Set the event to the signalled state. - void Set(); - // Access a HANDLE to wait on. - void* GetHandle() const { return m_handle; }; - // Wait indefinitely for the object to become signalled. - void Wait() const; - // Wait, with a time limit, for the object to become signalled. - bool Wait(const uint32 timeoutMillis) const; - -private: - CryEvent(const CryEvent&); - CryEvent& operator = (const CryEvent&); - -private: - void* m_handle; -}; - -typedef CryEvent CryEventTimed; - -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// from winnt.h -struct CRY_CRITICAL_SECTION -{ - void* DebugInfo; - long LockCount; - long RecursionCount; - threadID OwningThread; - void* LockSemaphore; - unsigned long* SpinCount; // force size on 64-bit systems when packed -}; - -////////////////////////////////////////////////////////////////////////// - -// kernel mutex - don't use... use CryMutex instead -class CryLock_WinMutex -{ -public: - CryLock_WinMutex(); - ~CryLock_WinMutex(); - - void Lock(); - void Unlock(); - bool TryLock(); - - void* _get_win32_handle() { return m_hdl; } - -private: - CryLock_WinMutex(const CryLock_WinMutex&); - CryLock_WinMutex& operator = (const CryLock_WinMutex&); - -private: - void* m_hdl; -}; - -// critical section... don't use... use CryCriticalSection instead -class CryLock_CritSection -{ -public: - CryLock_CritSection(); - ~CryLock_CritSection(); - - void Lock(); - void Unlock(); - bool TryLock(); - - bool IsLocked() - { - return m_cs.RecursionCount > 0 && m_cs.OwningThread == CryGetCurrentThreadId(); - } - -private: - CryLock_CritSection(const CryLock_CritSection&); - CryLock_CritSection& operator = (const CryLock_CritSection&); - -private: - CRY_CRITICAL_SECTION m_cs; -}; - -template <> -class CryLockT - : public CryLock_CritSection -{ -}; -template <> -class CryLockT - : public CryLock_CritSection -{ -}; -class CryMutex - : public CryLock_WinMutex -{ -}; -#define _CRYTHREAD_CONDLOCK_GLITCH 1 - -////////////////////////////////////////////////////////////////////////// -class CryConditionVariable -{ -public: - typedef CryMutex LockType; - - CryConditionVariable(); - ~CryConditionVariable(); - void Wait(LockType& lock); - bool TimedWait(LockType& lock, uint32 millis); - void NotifySingle(); - void Notify(); - -private: - CryConditionVariable(const CryConditionVariable&); - CryConditionVariable& operator = (const CryConditionVariable&); - -private: - int m_waitersCount; - CRY_CRITICAL_SECTION m_waitersCountLock; - void* m_sema; - void* m_waitersDone; - size_t m_wasBroadcast; -}; - -////////////////////////////////////////////////////////////////////////// -// Platform independet wrapper for a counting semaphore -class CrySemaphore -{ -public: - CrySemaphore(int nMaximumCount, int nInitialCount = 0); - ~CrySemaphore(); - void Acquire(); - void Release(); - -private: - void* m_Semaphore; -}; - -////////////////////////////////////////////////////////////////////////// -// Platform independet wrapper for a counting semaphore -// except that this version uses C-A-S only until a blocking call is needed -// -> No kernel call if there are object in the semaphore -class CryFastSemaphore -{ -public: - CryFastSemaphore(int nMaximumCount, int nInitialCount = 0); - ~CryFastSemaphore(); - void Acquire(); - void Release(); - -private: - CrySemaphore m_Semaphore; - volatile int32 m_nCounter; -}; - -////////////////////////////////////////////////////////////////////////// -#if !defined(_CRYTHREAD_HAVE_RWLOCK) -class CryRWLock -{ - void* /*SRWLOCK*/ m_Lock; - - CryRWLock(const CryRWLock&); - CryRWLock& operator= (const CryRWLock&); - -public: - CryRWLock(); - ~CryRWLock(); - - void RLock(); - void RUnlock(); - - void WLock(); - void WUnlock(); - - void Lock(); - void Unlock(); - -#if defined(_CRYTHREAD_WANT_TRY_RWLOCK) - // Enabling TryXXX requires Windows 7 or newer - bool TryRLock(); - bool TryWLock(); - bool TryLock(); -#endif -}; - -// Indicate that this implementation header provides an implementation for -// CryRWLock. -#define _CRYTHREAD_HAVE_RWLOCK 1 -#endif - -////////////////////////////////////////////////////////////////////////// -class CrySimpleThreadSelf -{ -public: - CrySimpleThreadSelf(); - void WaitForThread(); - virtual ~CrySimpleThreadSelf(); -protected: - void StartThread(unsigned (__stdcall * func)(void*), void* argList); - static THREADLOCAL CrySimpleThreadSelf* m_Self; -private: - CrySimpleThreadSelf(const CrySimpleThreadSelf&); - CrySimpleThreadSelf& operator = (const CrySimpleThreadSelf&); -protected: - void* m_thread; - uint32 m_threadId; -}; - -template -class CrySimpleThread - : public CryRunnable - , public CrySimpleThreadSelf -{ -public: - typedef void (* ThreadFunction)(void*); - typedef CryRunnable RunnableT; - - void SetName(const char* Name) - { - m_name = Name; - } - const char* GetName() { return m_name; } - - const volatile bool& GetStartedState() const { return m_bIsStarted; } - -private: - Runnable* m_Runnable; - struct - { - ThreadFunction m_ThreadFunction; - void* m_ThreadParameter; - } m_ThreadFunction; - volatile bool m_bIsStarted; - volatile bool m_bIsRunning; - volatile bool m_bCreatedThread; - string m_name; - -protected: - virtual void Terminate() - { - // This method must be empty. - // Derived classes overriding Terminate() are not required to call this - // method. - } - -private: - static unsigned __stdcall RunRunnable(void* thisPtr) - { -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_WINDOWS_H_SECTION_1 - #include AZ_RESTRICTED_FILE(CryThread_windows_h) -#endif - CrySimpleThread* const self = (CrySimpleThread*)thisPtr; - self->m_bIsStarted = true; - self->m_bIsRunning = true; - - self->m_Runnable->Run(); - self->m_bIsRunning = false; - self->m_bCreatedThread = false; - self->Terminate(); - return 0; - } - - static unsigned __stdcall RunThis(void* thisPtr) - { -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_WINDOWS_H_SECTION_2 - #include AZ_RESTRICTED_FILE(CryThread_windows_h) -#endif - CrySimpleThread* const self = (CrySimpleThread*)thisPtr; - self->m_bIsStarted = true; - self->m_bIsRunning = true; - - self->Run(); - self->m_bIsRunning = false; - self->m_bCreatedThread = false; - self->Terminate(); - return 0; - } - - CrySimpleThread(const CrySimpleThread&); - void operator = (const CrySimpleThread&); - -public: - CrySimpleThread() - : m_bIsStarted(false) - , m_bIsRunning(false) - , m_bCreatedThread(false) - { - m_thread = NULL; - m_Runnable = NULL; - } - void* GetHandle() { return m_thread; } - - virtual ~CrySimpleThread() - { - if (IsStarted()) - { - if (gEnv && gEnv->pLog) - { - gEnv->pLog->LogError("Runaway thread %p '%s'", m_thread, m_name.c_str()); - } - } - - if (m_bCreatedThread) - { - Cancel(); - WaitForThread(); - } - } - - virtual void Run() - { - // This Run() implementation supports the void StartFunction() method. - // However, code using this class (or derived classes) should eventually - // be refactored to use one of the other Start() methods. This code will - // be removed some day and the default implementation of Run() will be - // empty. - if (m_ThreadFunction.m_ThreadFunction != NULL) - { - m_ThreadFunction.m_ThreadFunction(m_ThreadFunction.m_ThreadParameter); - } - } - - // Cancel the running thread. - // - // If the thread class is implemented as a derived class of CrySimpleThread, - // then the derived class should provide an appropriate implementation for - // this method. Calling the base class implementation is _not_ required. - // - // If the thread was started by specifying a Runnable (template argument), - // then the Cancel() call is passed on to the specified runnable. - // - // If the thread was started using the StartFunction() method, then the - // caller must find other means to inform the thread about the cancellation - // request. - virtual void Cancel() - { - if (IsStarted() && m_Runnable != NULL) - { - m_Runnable->Cancel(); - } - } - - virtual void Start(Runnable& runnable, [[maybe_unused]] unsigned cpuMask = 0, const char* = NULL, int32 = 0) - { - if (m_bCreatedThread) - { - // Don't start thread more than once! - return; - } - m_Runnable = &runnable; - m_bCreatedThread = true; - StartThread(RunRunnable, this); - } - - virtual void Start([[maybe_unused]] unsigned cpuMask = 0, const char* = NULL, int32 = 0, int32 = 0) - { - if (m_bCreatedThread) - { - // Don't start thread more than once! - return; - } - m_bCreatedThread = true; - StartThread(RunThis, this); - } - - void StartFunction( - ThreadFunction threadFunction, - void* threadParameter = NULL - ) - { - m_ThreadFunction.m_ThreadFunction = threadFunction; - m_ThreadFunction.m_ThreadParameter = threadParameter; - Start(); - } - - static CrySimpleThread* Self() - { - return reinterpret_cast*>(m_Self); - } - - void Exit() - { - assert(!"implemented"); - } - - void Stop() - { - m_bIsStarted = false; - } - - bool IsStarted() const { return m_bIsStarted; } - bool IsRunning() const { return m_bIsRunning; } -}; - -/////////////////////////////////////////////////////////////////////////////// -// base class for lock less Producer/Consumer queue, due platforms specific they -// are implemented in CryThead_platform.h -namespace CryMT { - namespace detail { - /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// - class SingleProducerSingleConsumerQueueBase - { - public: - SingleProducerSingleConsumerQueueBase() - {} - - void Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize); - void Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize); - }; - - - /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// - class N_ProducerSingleConsumerQueueBase - { - public: - N_ProducerSingleConsumerQueueBase() - { - CryInitializeSListHead(fallbackList); - } - - void Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates); - bool Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates); - - private: - SLockFreeSingleLinkedListHeader fallbackList; - struct SFallbackList - { - SLockFreeSingleLinkedListEntry nextEntry; - char alignment_padding[128 - sizeof(SLockFreeSingleLinkedListEntry)]; - char object[1]; // struct will be overallocated with enough memory for the object - }; - }; - } // namespace detail -} // namespace CryMT diff --git a/Code/CryEngine/CryCommon/CryTypeInfo.cpp b/Code/CryEngine/CryCommon/CryTypeInfo.cpp deleted file mode 100644 index 78dc92e9d1..0000000000 --- a/Code/CryEngine/CryCommon/CryTypeInfo.cpp +++ /dev/null @@ -1,1468 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Implementation of TypeInfo classes and functions. - -#include -#include "CryTypeInfo.h" -#include "CryCustomTypes.h" -#include "Cry_Math.h" -#include "CrySizer.h" -#include "CryEndian.h" -#include "TypeInfo_impl.h" - -// Traits -#if defined(AZ_RESTRICTED_PLATFORM) - #include AZ_RESTRICTED_FILE(CryTypeInfo_cpp) -#elif defined(LINUX) || defined(APPLE) -#define CRYTYPEINFO_CPP_TRAIT_DEFINE_LTOA_S 1 -#endif - -#if CRYTYPEINFO_CPP_TRAIT_DEFINE_LTOA_S - -char* _ltoa_s(long value, char* string, size_t size, int32 radix) -{ - if (10 == radix) - { - sprintf_s(string, size, "%ld", value); - } - else - { - sprintf_s(string, size, "%lx", value); - } - return(string); -} - - -char* _i64toa_s(int64 value, char* string, size_t size, int32 radix) -{ - if (10 == radix) - { - sprintf_s(string, size, "%llu", (unsigned long long)value); - } - else - { - sprintf_s(string, size, "%llx", (unsigned long long)value); - } - return(string); -} - -char* _ultoa_s(uint32 value, char* string, size_t size, int32 radix) -{ - if (10 == radix) - { - sprintf_s(string, size, "%.d", value); - } - else - { - sprintf_s(string, size, "%.x", value); - } - return(string); -} - -#endif //LINUX || MAC - -////////////////////////////////////////////////////////////////////// -// Case-insensitive comparison helpers. - -class StrNoCase -{ -public: - inline StrNoCase(cstr str) - : m_Str(str) {} - inline bool operator == (cstr str) const { return azstricmp(m_Str, str) == 0; } - inline bool operator != (cstr str) const { return azstricmp(m_Str, str) != 0; } -private: - cstr m_Str; -}; - -// Default Endian swap function, forwards to TypeInfo. -void SwapEndian(const CTypeInfo& Info, [[maybe_unused]] size_t nSizeCheck, void* data, size_t nCount, bool bWriting) -{ - assert(nSizeCheck == Info.Size); - Info.SwapEndian(data, nCount, bWriting); -} - -////////////////////////////////////////////////////////////////////// -// Basic TypeInfo implementations. - -// Basic type infos. - -DEFINE_TYPE_INFO(void, CTypeInfo, ("void", 0, 0)) - -TYPE_INFO_BASIC(bool) -TYPE_INFO_BASIC(char) -TYPE_INFO_BASIC(wchar_t) - -TYPE_INFO_INT(signed char) -TYPE_INFO_INT(unsigned char) -TYPE_INFO_INT(short) -TYPE_INFO_INT(unsigned short) -TYPE_INFO_INT(int) -TYPE_INFO_INT(unsigned int) -TYPE_INFO_INT(long) -TYPE_INFO_INT(unsigned long) -TYPE_INFO_INT(int64) -TYPE_INFO_INT(uint64) - -TYPE_INFO_BASIC(float) -TYPE_INFO_BASIC(double) - -TYPE_INFO_BASIC(string) - - -const CTypeInfo&PtrTypeInfo() -{ - static CTypeInfo Info(TYPE_INFO_NAME(void*), sizeof(void*), alignof(void*)); - return Info; -} - -////////////////////////////////////////////////////////////////////// -// Basic type info implementations. - -// String conversion functions needed by TypeInfo. - -// bool -string ToString(bool const& val) -{ - static string sTrue = "true", sFalse = "false"; - return val ? sTrue : sFalse; -} - -bool FromString(bool& val, cstr s) -{ - if (!strcmp(s, "0") || !azstricmp(s, "false")) - { - val = false; - return true; - } - if (!strcmp(s, "1") || !azstricmp(s, "true")) - { - val = true; - return true; - } - return false; -} - -// int64 -string ToString(int64 const& val) -{ - char buffer[64]; - _i64toa_s(val, buffer, sizeof(buffer), 10); - return buffer; -} -// uint64 -string ToString(uint64 const& val) -{ - char buffer[64]; - sprintf_s(buffer, "%" PRIu64, val); - return buffer; -} - - - -// long -string ToString(long const& val) -{ - char buffer[64]; - _ltoa_s(val, buffer, sizeof(buffer), 10); - return buffer; -} - -// ulong -string ToString(unsigned long const& val) -{ - char buffer[64]; - _ultoa_s(val, buffer, sizeof(buffer), 10); - return buffer; -} - -template -bool ClampedIntFromString(T& val, const char* s) -{ - bool signbit = *s == '-'; - s += signbit; - if (signbit && !TIntTraits::bSIGNED) - { - // Negative number on unsigned. - val = T(0); - return true; - } - - uint digit = (uint8) * s - '0'; - if (digit > 9) - { - // No digits. - return false; - } - - // Extract digits until overflow. - T v = static_cast(digit); - while ((digit = (uint8) * ++s - '0') <= 9) - { - T vnew = static_cast(v * 10 + digit); - if (vnew < v) - { - // Overflow. - if (signbit) - { - val = TIntTraits::nMIN; - } - else - { - val = TIntTraits::nMAX; - } - return true; - } - v = vnew; - } - - val = signbit ? ~v + 1 : v; - return true; -} - -bool FromString(int64& val, const char* s) { return ClampedIntFromString(val, s); } -bool FromString(uint64& val, const char* s) { return ClampedIntFromString(val, s); } - -bool FromString(long& val, const char* s) { return ClampedIntFromString(val, s); } -bool FromString(unsigned long& val, const char* s) { return ClampedIntFromString(val, s); } - -string ToString(int const& val) { return ToString(long(val)); } -bool FromString(int& val, const char* s) { return ClampedIntFromString(val, s); } - -string ToString(unsigned int const& val) { return ToString((unsigned long)(val)); } -bool FromString(unsigned int& val, const char* s) { return ClampedIntFromString(val, s); } - -string ToString(short const& val) { return ToString(long(val)); } -bool FromString(short& val, const char* s) { return ClampedIntFromString(val, s); } - -string ToString(unsigned short const& val) { return ToString((unsigned long)(val)); } -bool FromString(unsigned short& val, const char* s) { return ClampedIntFromString(val, s); } - -string ToString(char const& val) { return ToString(long(val)); } -bool FromString(char& val, const char* s) { return ClampedIntFromString(val, s); } - -string ToString(wchar_t const& val) { return ToString(long(val)); } -bool FromString(wchar_t& val, const char* s) { return ClampedIntFromString(val, s); } - -string ToString(signed char const& val) { return ToString(long(val)); } -bool FromString(signed char& val, const char* s) { return ClampedIntFromString(val, s); } - -string ToString(unsigned char const& val) { return ToString((unsigned long)(val)); } -bool FromString(unsigned char& val, const char* s) { return ClampedIntFromString(val, s); } - -string ToString(const AZ::Uuid& val) -{ - return val.ToString(); -} - -bool FromString(AZ::Uuid& val, const char* s) -{ - val = AZ::Uuid(s); - return true; -} - -float NumToFromString(float val, int digits, bool floating, char buffer[], int buf_size) -{ - assert(buf_size >= 32); - if (floating) - { - if (val >= powf(10.f, float(digits))) - { - sprintf_s(buffer, buf_size, "%.0f", val); - } - else - { - sprintf_s(buffer, buf_size, "%.*g", digits, val); - } - } - else - { - sprintf_s(buffer, buf_size, "%.*f", digits, float(val)); - } -#if !defined(NDEBUG) - int readCount = -#endif - azsscanf(buffer, "%g", &val); - assert(readCount == 1); - return val; -} - -// double -string ToString(double const& val) -{ - char buffer[64]; - sprintf_s(buffer, "%.16g", val); - return buffer; -} -bool FromString(double& val, const char* s) -{ - return azsscanf(s, "%lg", &val) == 1; -} - -// float -string ToString(float const& val) -{ - char buffer[64]; - for (int digits = 7; digits < 10; digits++) - { - if (NumToFromString(val, digits, true, buffer, 64) == val) - { - break; - } - } - return buffer; -} - -bool FromString(float& val, const char* s) -{ - return azsscanf(s, "%g", &val) == 1; -} - - - -// string override. -template <> -void TTypeInfo::GetMemoryUsage(ICrySizer* pSizer, void const* data) const -{ - // CRAIG: just a temp hack to try and get things working -#if !defined(LINUX) && !defined(APPLE) - pSizer->AddString(*(string*)data); -#endif -} - -#if defined(TEST_TYPEINFO) && defined(_DEBUG) - -struct STypeInfoTest -{ - STypeInfoTest() - { - TestType(string("well")); - - TestType(true); - - TestType(int8(-0x12)); - TestType(uint8(0x87)); - TestType(int16(-0x1234)); - TestType(uint16(0x8765)); - TestType(int32(-0x12345678)); - TestType(uint32(0x87654321)); - TestType(int64(-0x123456789ABCDEF0LL)); - TestType(uint64(0xFEDCBA9876543210LL)); - - TestType(float(1234.5678)); - TestType(float(12345678)); - TestType(float(12345678e-20)); - TestType(float(12345678e20)); - - TestType(double(987654321.0123456789)); - TestType(double(9876543210123456789.0)); - TestType(double(9876543210123456789e-40)); - TestType(double(9876543210123456789e40)); - } -}; -static STypeInfoTest _TypeInfoTest; - -#endif //TEST_TYPEINFO - - -////////////////////////////////////////////////////////////////////// -// CTypeInfo implementation - -//--------------------------------------------------------------------------- -// Endian helper functions. - -void CTypeInfo::SwapEndian(void* pData, size_t nCount, [[maybe_unused]] bool bWriting) const -{ - switch (Size) - { - case 1: - break; - case 2: - ::SwapEndianBase((uint16*)pData, nCount); - break; - case 4: - ::SwapEndianBase((uint32*)pData, nCount); - break; - case 8: - ::SwapEndianBase((uint64*)pData, nCount); - break; - default: - assert(0); - } -} - -// If attr name is found, return pointer to start of value text; else 0. -static cstr FindAttr(cstr attrs, cstr name) -{ - size_t name_len = strlen(name); - while (attrs) - { - attrs = strchr(attrs, '<'); - if (!attrs) - { - return 0; - } - - attrs++; - size_t attr_len = strcspn(attrs, "=>"); - if (attr_len == name_len && _strnicmp(attrs, name, name_len) == 0) - { - attrs += attr_len; - if (*attrs == '=') - { - ++attrs; - } - return attrs; - } - attrs += attr_len; - if (*attrs == '=') - { - attrs = strchr(attrs + 1, '>'); - } - } - return 0; -} - -bool CTypeInfo::CVarInfo::GetAttr(cstr name) const -{ - return FindAttr(Attrs, name) != 0; -} - -bool CTypeInfo::CVarInfo::GetAttr(cstr name, string& val) const -{ - cstr valstr = FindAttr(Attrs, name); - if (!valstr) - { - return false; - } - - // Find attr delimiter. - cstr end = strchr(valstr, '>'); - if (!end) - { - return false; - } - - // Strip quotes. - if (*valstr == '"') - { - valstr++; - if (end - valstr > 1 && end[-1] == '"') - { - end--; - } - } - val = string(valstr, end - valstr); - return true; -} - -bool CTypeInfo::CVarInfo::GetAttr(cstr name, float& val) const -{ - cstr valstr = FindAttr(Attrs, name); - if (!valstr) - { - return false; - } - val = (float)atof(valstr); - return true; -} - -cstr CTypeInfo::CVarInfo::GetComment() const -{ - cstr send = strrchr(Attrs, '>'); - if (send) - { - do - { - ++send; - } while (*send == ' '); - return send; - } - else - { - return Attrs; - } -} - -////////////////////////////////////////////////////////////////////// -// CStructInfo implementation - -inline cstr DisplayName(cstr name) -{ - // Skip prefixes in Name. - cstr dname = name; - while (islower((unsigned char)*dname) || *dname == '_') - { - dname++; - } - if (isupper((unsigned char)*dname)) - { - return dname; - } - else - { - return name; - } -} - -CStructInfo::CStructInfo(cstr name, size_t size, size_t align, Array vars, Array templates) - : CTypeInfo(name, size, align) - , Vars(vars) - , TemplateTypes(templates) - , HasBitfields(false) -{ - // Process and validate offsets and sizes. - if (Vars.size() > 0) - { - size = 0; - int bitoffset = 0; - - for (int i = 0; i < Vars.size(); i++) - { - CStructInfo::CVarInfo& var = Vars[i]; - - // Convert name. - var.Name = DisplayName(var.Name); - - if (var.bBitfield) - { - HasBitfields = true; - if (bitoffset > 0) - { - // Continuing bitfield. - var.Offset = Vars[i - 1].Offset; - var.BitWordWidth = Vars[i - 1].BitWordWidth; - - if (bitoffset + var.ArrayDim > var.GetSize() * 8) - { - // Overflows word, start on next one. - bitoffset = 0; - size += var.GetSize(); - } - } - - if (bitoffset == 0) - { - var.Offset = check_cast(size); - - // Detect real word size of bitfield, from offset of next field. - size_t next_offset = Size; - for (int j = i + 1; j < Vars.size(); j++) - { - if (!Vars[j].bBitfield) - { - next_offset = Vars[j].Offset; - break; - } - } - assert(next_offset > size); - size_t wordsize = min(next_offset - size, var.Type.Size); - size = next_offset; - switch (wordsize) - { - case 1: - var.BitWordWidth = 0; - break; - case 2: - var.BitWordWidth = 1; - break; - case 4: - var.BitWordWidth = 2; - break; - case 8: - var.BitWordWidth = 3; - break; - default: - assert(0); - } - } - - assert(var.ArrayDim <= var.GetSize() * 8); - var.BitOffset = bitoffset; - bitoffset += var.ArrayDim; - } - else - { - bitoffset = 0; - if (var.Offset >= size) - { - size = var.Offset + var.GetSize(); - } - } - } - assert(Align(size, Alignment) == Align(Size, Alignment)); - } -} - -size_t EndianDescSize(cstr desc) -{ - // Iterate the endian descriptor. - size_t nSize = 0; - for (; *desc; desc++) - { - size_t count = *desc & 0x3F; - size_t nType = *(uint8*)desc >> 6; - nSize += count << nType; - } - return nSize; -} - -size_t CStructInfo::AddEndianDesc(cstr desc, size_t dim, size_t elem_size) -{ - if (dim == 0) - { - return 0; - } - - size_t endian_size = EndianDescSize(desc); - size_t total_size = elem_size * (dim - 1) + endian_size; - - if (desc[1] || (endian_size < elem_size && dim > 1)) - { - // Composite endian descriptor, replicate it. - assert(endian_size <= elem_size); - assert(elem_size - endian_size < 0x40); - while (dim-- > 0) - { - EndianDesc += (cstr)desc; - if (dim > 1 && endian_size < elem_size) - { - EndianDesc += char(0x40 | (elem_size - endian_size)); - } - } - } - else - { - // Single endian component. Replicate using count field. - size_t subdim = desc[0] & 0x3F; - dim *= subdim; - if (!EndianDesc.empty()) - { - // Combine with previous component if possible. - char prevdesc = *(EndianDesc.end() - 1); - if ((prevdesc & ~0x3F) == (desc[0] & ~0x3F)) - { - // Combine with previous char. - size_t maxdim = min(dim, size_t(0x3F - (prevdesc & 0x3F))); - prevdesc += check_cast(maxdim); - EndianDesc.erase(EndianDesc.length() - 1, 1); - EndianDesc.append(1, prevdesc); - dim -= maxdim; - } - } - for (; dim > 0x3F; dim -= 0x3F) - { - EndianDesc += desc[0] | 0x3F; - } - if (dim > 0) - { - EndianDesc += check_cast((desc[0] & ~0x3F) | dim); - } - } - - return total_size; -} - -bool CStructInfo::FromValue(void* data, const void* value, const CTypeInfo& typeVal) const -{ - if (IsCompatibleType(typeVal)) - { - bool bOK = true; - int i = 0; - for AllSubVars(pToVar, typeVal) - { - if (!Vars[i].Type.FromValue(Vars[i].GetAddress(data), pToVar->GetAddress(value), pToVar->Type)) - { - bOK = false; - } - i++; - } - return bOK; - } - - // Check all subclasses. - for (int i = 0; i < Vars.size() && Vars[i].IsBaseClass(); i++) - { - if (Vars[i].Type.FromValue(Vars[i].GetAddress(data), value, typeVal)) - { - return true; - } - } - return false; -} - -bool CStructInfo::ToValue(const void* data, void* value, const CTypeInfo& typeVal) const -{ - if (IsCompatibleType(typeVal)) - { - bool bOK = true; - int i = 0; - for AllSubVars(pToVar, typeVal) - { - if (!Vars[i].Type.ToValue(Vars[i].GetAddress(data), pToVar->GetAddress(value), pToVar->Type)) - { - bOK = false; - } - i++; - } - return bOK; - } - - // Check all subclasses. - for (int i = 0; i < Vars.size() && Vars[i].IsBaseClass(); i++) - { - if (Vars[i].Type.ToValue(Vars[i].GetAddress(data), value, typeVal)) - { - return true; - } - } - return false; -} - -// Parse structs as comma-separated values. - -/* , 1, ,2 1,2 - - Top 1 ,2 1,2 ; strip trail commas - Child Named 1 (,2) (1,2) ; strip trail commas, paren if internal commas - Nameless , 1, ,2 1,2 ; -*/ - -static void StripCommas(string& str) -{ - size_t nLast = str.size(); - while (nLast > 0 && str[nLast - 1] == ',') - { - nLast--; - } - str.resize(nLast); -} - -string CStructInfo::ToString(const void* data, FToString flags, const void* def_data) const -{ - string str; // Return str. - - for (int i = 0; i < Vars.size(); i++) - { - // Handling of empty values: Skip trailing empty values. - // If there are intermediate empty values, replace them with non-empty ones. - const CVarInfo& var = Vars[i]; - - if (!var.IsInline()) - { - // Named sub var or struct. - if (!flags.NamedFields && i > 0) - { - str += ","; - } - - string substr = var.ToString(data, FToString(flags).Sub(0), def_data); - - if (flags.SkipDefault && substr.empty()) - { - continue; - } - - if (flags.NamedFields) - { - if (*str) - { - str += ","; - } - if (*var.Name) - { - str += var.Name; - str += "="; - } - } - if (substr.find(',') != string::npos || substr.find('=') != string::npos) - { - // Encase nested composite types in parens. - str += "("; - str += substr; - str += ")"; - } - else - { - str += substr; - } - } - else - { - // Nameless base struct. Treat children as inline. - str += var.ToString(data, FToString(flags).Sub(1), def_data); - } - } - - if (flags.SkipDefault && !flags.Sub) - { - StripCommas(str); - } - return str; -} - -// Retrieve and return one subelement from src, advancing the pointer. -// Copy to tempstr if necessary. - -typedef CryStackStringT CTempStr; - -void ParseElement(cstr& src, cstr& varname, cstr& val, CTempStr& tempstr) -{ - varname = val = 0; - - while (*src == ' ') - { - src++; - } - if (!*src) - { - return; - } - - // Find end of var assignment. - int nest = 0; - cstr eq = 0; - - cstr end; - for (end = src; *end; end++) - { - if (*end == '(') - { - nest++; - } - else if (*end == ')') - { - nest--; - } - else if (nest == 0) - { - if (*end == '=' && !eq) - { - eq = end; - } - else if (*end == ',') - { - break; - } - } - } - - // Advance src past element. - val = src; - src = end; - - if (*src == ',') - { - src++; - } - - if (eq) - { - varname = val; - val = eq + 1; - } - - PREFAST_ASSUME(val); - if (*val == '(' && end[-1] == ')') - { - // Remove parens. - val++; - end--; - } - - if (eq) - { - if (*end) - { - // Must copy sub string to temp. - val = (cstr)tempstr + (val - varname); - eq = (cstr)tempstr + (eq - varname); - varname = tempstr.assign(varname, end); - non_const(*eq) = 0; - } - else - { - // Copy just varname to temp, return val in place. - varname = tempstr.assign(varname, eq); - } - } - else if (*end) - { - // Must copy sub string to temp. - val = tempstr.assign(val, end); - } - - // Else can return val without copying. -} - -bool CStructInfo::FromString(void* data, cstr str, FFromString flags) const -{ - if (!flags.SkipEmpty) - { - // Initialise all to default - for (int i = 0; i < Vars.size(); i++) - { - Vars[i].FromString(data, ""); - } - } - - CTempStr tempstr; - const CVarInfo* pVar = 0; - int nErrors = 0; - - while (*str) - { - cstr varname, val; - ParseElement(str, varname, val, tempstr); - - if (varname) - { - pVar = FindSubVar(varname); - } - else - { - pVar = NextSubVar(pVar, true); - } - if (pVar) - { - if (*val || !flags.SkipEmpty) - { - nErrors += !pVar->FromString(data, val, flags); - } - } - else - { - nErrors++; - } - } - - return !nErrors; -} - -bool CStructInfo::ValueEqual(const void* data, const void* def_data) const -{ - for (int i = 0; i < Vars.size(); i++) - { - const CVarInfo& var = Vars[i]; - if (!var.Type.ValueEqual((char*)data + var.Offset, (def_data ? (char*)def_data + var.Offset : 0))) - { - return false; - } - } - return true; -} - -void CStructInfo::SwapEndian(void* data, size_t nCount, bool bWriting) const -{ - non_const(*this).MakeEndianDesc(); - - if (EndianDesc.length() == 1 && !HasBitfields && EndianDescSize(EndianDesc) == Size) - { - // Optimised array swap. - size_t nElems = (EndianDesc[0u] & 0x3F) * nCount; - switch (EndianDesc[0u] & 0xC0) - { - case 0: // Skip bytes - break; - case 0x40: // Swap 2 bytes - ::SwapEndianBase((uint16*)data, nElems); - break; - case 0x80: // Swap 4 bytes - ::SwapEndianBase((uint32*)data, nElems); - break; - case 0xC0: // Swap 8 bytes - ::SwapEndianBase((uint64*)data, nElems); - break; - } - return; - } - - for (; nCount-- > 0; data = (char*)data + Size) - { - // First swap bits. - // Iterate the endian descriptor. - void* step = data; - for (cstr desc = EndianDesc; *desc; desc++) - { - size_t nElems = *desc & 0x3F; - switch (*desc & 0xC0) - { - case 0: // Skip bytes - step = (uint8*)step + nElems; - break; - case 0x40: // Swap 2 bytes - ::SwapEndianBase((uint16*)step, nElems); - step = (uint16*)step + nElems; - break; - case 0x80: // Swap 4 bytes - ::SwapEndianBase((uint32*)step, nElems); - step = (uint32*)step + nElems; - break; - case 0xC0: // Swap 8 bytes - ::SwapEndianBase((uint64*)step, nElems); - step = (uint64*)step + nElems; - break; - } - } - - // Then bitfields if needed. - if (HasBitfields) - { - uint64 uOrigBits = 0, uNewBits = 0; - for (int i = 0; i < Vars.size(); i++) - { - CVarInfo const& var = Vars[i]; - if (var.bBitfield) - { - // Reverse location of all bitfields in word. - size_t nWordBits = var.GetElemSize() * 8; - assert(nWordBits <= 64); - if (var.BitOffset == 0) - { - // Initialise bitfield swapping. - var.Type.ToValue(var.GetAddress(data), uOrigBits); - uNewBits = 0; - } - size_t nSrcOffset = (GetPlatformEndian() == eLittleEndian) == bWriting ? var.BitOffset : nWordBits - var.GetBits() - var.BitOffset; - size_t nDstOffset = nWordBits - var.GetBits() - nSrcOffset; - - uint64 uFieldVal = uOrigBits >> nSrcOffset; - uFieldVal &= ((1 << var.GetBits()) - 1); - uNewBits |= uFieldVal << nDstOffset; - var.Type.FromValue(var.GetAddress(data), uNewBits); - } - } - } - } -} - -void CStructInfo::MakeEndianDesc() -{ - if (!EndianDesc.empty()) - { - return; - } - - size_t last_offset = 0; - for (int i = 0; i < Vars.size(); i++) - { - CVarInfo const& var = Vars[i]; - bool bUnionAlias = var.bBitfield ? var.BitOffset > 0 : var.Offset < last_offset; - if (!bUnionAlias) - { - // Add endian desc for member. - cstr subdesc = 0; - if (var.Type.HasSubVars()) - { - // Struct-computed endian desc. - CStructInfo const& infoSub = static_cast(var.Type); - non_const(infoSub).MakeEndianDesc(); - subdesc = infoSub.EndianDesc; - if (!*subdesc) - { - // No swapping. - continue; - } - } - else - { - // Basic type. - switch (var.GetElemSize()) - { - case 0: - case 1: - continue; // No swapping needed. - case 2: - subdesc = "\x41"; - break; - case 4: - subdesc = "\x81"; - break; - case 8: - subdesc = "\xC1"; - break; - default: - assert(0); - } - } - - // Apply any padding to current offset. - assert(last_offset <= var.Offset); - if (last_offset < var.Offset) - { - last_offset += AddEndianDesc("\x01", var.Offset - last_offset, 1); - } - last_offset += AddEndianDesc(subdesc, var.GetDim(), var.GetElemSize()); - } - } -} - -void CStructInfo::GetMemoryUsage(ICrySizer* pSizer, void const* data) const -{ - for (int i = 0; i < Vars.size(); i++) - { - Vars[i].Type.GetMemoryUsage(pSizer, (char*)data + Vars[i].Offset); - } -} - -const CTypeInfo::CVarInfo* CStructInfo::NextSubVar(const CVarInfo* pPrev, bool bRecurseBase) const -{ - if (pPrev >= Vars.begin() && pPrev < Vars.end()) - { - // pPrev is within this struct's vars - if (++pPrev < Vars.end()) - { - return pPrev; - } - return 0; - } - - if (Vars.empty()) - { - return 0; - } - - if (bRecurseBase) - { - // Recurse into inline base structs - const CVarInfo* pBase = Vars.begin(); - if (pBase->IsInline()) - { - if (const CVarInfo* pNext = pBase->Type.NextSubVar(pPrev, true)) - { - return pNext; - } - if (++pBase < Vars.end()) - { - return pBase; - } - return 0; - } - } - - if (!pPrev) - { - // Return first var - return Vars.begin(); - } - - return 0; -} - -const CTypeInfo::CVarInfo* CStructInfo::FindSubVar(cstr name) const -{ - static int s_nLast = 0; - int nSize = Vars.size(); - if (s_nLast >= nSize) - { - s_nLast = 0; - } - - for (int i = s_nLast, iEnd = s_nLast + nSize; i < iEnd; i++) - { - int v = i >= nSize ? i - nSize : i; - const CVarInfo& var = Vars[v]; - if (var.Type.Size > 0 && StrNoCase(var.GetName()) == name) - { - s_nLast = v; - return &var; - } - if (var.IsBaseClass()) - { - if (const CVarInfo* pSubVar = var.Type.FindSubVar(name)) - { - return pSubVar; - } - } - } - return 0; -} - -bool CStructInfo::IsCompatibleType(CTypeInfo const& Info) const -{ - if (this == &Info) - { - return true; - } - - if (!TemplateTypes.empty() && Info.IsTemplate() && strcmp(Name, Info.Name) == 0) - { - CTypeInfo const* const* pA = NextTemplateType(0); - CTypeInfo const* const* pB = Info.NextTemplateType(0); - - while (pA && pB && (*pA)->IsType(**pB)) - { - pA = Info.NextTemplateType(pA); - pB = Info.NextTemplateType(pB); - } - return !pA && !pB; - } - - return false; -} - -bool CStructInfo::IsType(CTypeInfo const& Info) const -{ - if (IsCompatibleType(Info)) - { - return true; - } - - // Check all subclasses. - for (int i = 0; i < Vars.size() && Vars[i].IsBaseClass(); i++) - { - if (Vars[i].Type.IsType(Info)) - { - return true; - } - } - return false; -} - -////////////////////////////////////////////////////////////////////// -// CSimpleEnumDef implementation - -cstr ParseNextEnum(char*& rs) -{ - char* s = rs; - while (isspace(*s)) - { - s++; - } - if (!*s) - { - return 0; - } - - cstr se = s; - while (isalnum(*s) || *s == '_') - { - s++; - } - - if (*s == ',') - { - *s++ = 0; - } - else if (*s) - { - *s++ = 0; - while (*s && *s != ',') - { - s++; - } - if (*s) - { - s++; - } - } - rs = s; - return se; -} - -void CSimpleEnumDef::Init(Array names, char* enum_str) -{ - asNames = names; - - // Split copy of enums string into elements, store in array. - int i = 0; - while (cstr se = ParseNextEnum(enum_str)) - { - asNames[i++] = se; - } -} - -////////////////////////////////////////////////////////////////////// -// CEnumDef implementation - -void CEnumDef::Init(Array elems, char* enum_str) -{ - Elems = elems; - MinValue = 0; - bRegular = true; - nPrefixLength = 0; - - if (enum_str) - { - // Parse enum names from str - int i = 0; - while (cstr se = ParseNextEnum(enum_str)) - { - Elems[i++].Name = se; - } - } - - // Analyse names and values. - if (!elems.empty()) - { - cstr sPrefix = ""; - MinValue = Elems[0].Value; - for (int i = 0; i < elems.size(); i++) - { - if (Elems[i].Value != i + Elems[0].Value) - { - bRegular = false; - } - MinValue = min(MinValue, Elems[i].Value); - - // Find common prefix. - cstr sElem = Elems[i].Name; - if (*sElem) - { - if (!*sPrefix) - { - sPrefix = sElem; - nPrefixLength = static_cast(strlen(sPrefix)); - } - else - { - uint p = 0; - while (p < nPrefixLength && sElem[p] == sPrefix[p]) - { - p++; - } - nPrefixLength = p; - } - } - } - - // Ensure prefix is on underscore boundary. - while (nPrefixLength > 0 && sPrefix[nPrefixLength - 1] != '_') - { - nPrefixLength--; - } - } -} - -bool CEnumDef::MatchName(uint i, cstr str) const -{ - cstr name = Elems[i].Name; - if (*name && nPrefixLength) - { - if (azstricmp(name + nPrefixLength, str) == 0) - { - return true; - } - } - if (*name == '_') - { - name++; - } - return azstricmp(name, str) == 0; -} - -cstr CEnumDef::ToName(TValue value) const -{ - // Find matching element. - if (bRegular) - { - TValue index = value - MinValue; - if (index >= 0 && index < Elems.size()) - { - return Name((uint)index); - } - } - else - { - for (int i = 0; i < Elems.size(); i++) - { - if (Elems[i].Value == value) - { - return Name(i); - } - } - } - - // No match - return 0; -} - -LegacyDynArray* CEnumDef::SInit::s_pElems = 0; - -void CEnumDefUuid::Init(Array elems, char* enum_str) -{ - Elems = elems; - bRegular = false; - nPrefixLength = 0; - - if (enum_str) - { - // Parse enum names from str - int i = 0; - while (cstr se = ParseNextEnum(enum_str)) - { - Elems[i++].Name = se; - } - } - - // Analyse names and values. - if (!elems.empty()) - { - cstr sPrefix = ""; - for (int i = 0; i < elems.size(); i++) - { - // Find common prefix. - cstr sElem = Elems[i].Name; - if (*sElem) - { - if (!*sPrefix) - { - sPrefix = sElem; - nPrefixLength = static_cast(strlen(sPrefix)); - } - else - { - uint p = 0; - while (p < nPrefixLength && sElem[p] == sPrefix[p]) - { - p++; - } - nPrefixLength = p; - } - } - } - - // Ensure prefix is on underscore boundary. - while (nPrefixLength > 0 && sPrefix[nPrefixLength - 1] != '_') - { - nPrefixLength--; - } - } -} - -bool CEnumDefUuid::MatchName(uint i, cstr str) const -{ - cstr name = Elems[i].Name; - if (*name && nPrefixLength) - { - if (azstricmp(name + nPrefixLength, str) == 0) - { - return true; - } - } - if (*name == '_') - { - name++; - } - return azstricmp(name, str) == 0; -} - -cstr CEnumDefUuid::ToName(AZ::Uuid value) const -{ - // Find matching element. - for (int i = 0; i < Elems.size(); ++i) - { - if (Elems[i].Value == value) - { - return Elems[i].Name; - } - } - // No match - return 0; -} diff --git a/Code/CryEngine/CryCommon/CryTypeInfo.h b/Code/CryEngine/CryCommon/CryTypeInfo.h deleted file mode 100644 index 849e8c6bf0..0000000000 --- a/Code/CryEngine/CryCommon/CryTypeInfo.h +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Declaration of CTypeInfo and related types. - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYTYPEINFO_H -#define CRYINCLUDE_CRYCOMMON_CRYTYPEINFO_H -#pragma once - -#include -#include "CryArray.h" -#include "Options.h" -#include "CryString.h" -#include "TypeInfo_decl.h" - -class ICrySizer; - -class CCryName; -string ToString(CCryName const& val); -bool FromString(CCryName& val, const char* s); - -//--------------------------------------------------------------------------- -// Specify options for converting data to/from strings -struct FToString -{ - OPT_STRUCT(FToString) - OPT_VAR(bool, SkipDefault) // Omit default values on writing. - OPT_VAR(bool, NamedFields) // Add Name= text to sub-values. - OPT_VAR(bool, Sub) // Write sub-structures (internal usage). -}; - -struct FFromString -{ - OPT_STRUCT(FFromString) - OPT_VAR(bool, SkipEmpty) // Do not set values from empty strings (otherwise, set to zero). -}; - -// Specify which limits a variable has -enum ENumericLimit -{ - eLimit_Min, - eLimit_Max, - eLimit_SoftMin, - eLimit_SoftMax, - eLimit_MinIsInfinite, - eLimit_Step, -}; - -//--------------------------------------------------------------------------- -// Type info base class, and default implementation - -struct CTypeInfo -{ - cstr Name; - size_t Size; - size_t Alignment; - - CTypeInfo(cstr name, size_t size, size_t align) - : Name(name) - , Size(size) - , Alignment(align) {} - - virtual ~CTypeInfo() - {} - - // - // Inheritance. - // - virtual bool IsType(CTypeInfo const& Info) const - { return this == &Info; } - - template - bool IsType() const - { return IsType(TypeInfo((T*)0)); } - - // - // Data access interface. - // - - // Convert value to string. - virtual string ToString([[maybe_unused]] const void* data, [[maybe_unused]] FToString flags = 0, [[maybe_unused]] const void* def_data = 0) const - { return ""; } - - // Write value from string, return success. - virtual bool FromString([[maybe_unused]] void* data, [[maybe_unused]] cstr str, [[maybe_unused]] FFromString flags = 0) const - { return false; } - - // Read and write values of a specified type. - virtual bool ToValue([[maybe_unused]] const void* data, [[maybe_unused]] void* value, [[maybe_unused]] const CTypeInfo& typeVal) const - { return false; } - - virtual bool FromValue([[maybe_unused]] void* data, [[maybe_unused]] const void* value, [[maybe_unused]] const CTypeInfo& typeVal) const - { return false; } - - // Templated interface to above functions. - template - bool ToValue(const void* data, T& value) const - { return ToValue(data, &value, TypeInfo(&value)); } - template - bool FromValue(void* data, const T& value) const - { return FromValue(data, &value, TypeInfo(&value)); } - - virtual bool ValueEqual(const void* data, const void* def_data = 0) const - { return ToString(data, FToString().SkipDefault(1), def_data).empty(); } - - virtual bool GetLimit([[maybe_unused]] ENumericLimit eLimit, [[maybe_unused]] float& fVal) const - { return false; } - - // Convert numeric formats from big-to-little endian or vice versa. - // Swaps bitfield order as well (which may be separate from integer bit order). - virtual void SwapEndian(void* pData, size_t nCount, bool bWriting) const; - - // Track memory used by any internal structures (not counting object size itself). - // Add to CrySizer as needed, return remaining mem count. - virtual void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer, [[maybe_unused]] const void* data) const - {} - - // - // Structure interface. - // - struct CVarInfo - { - const CTypeInfo& Type; // Info for type of variable. - cstr Name; // Display name of variable. - cstr Attrs; // Var-specific attribute string, of form: - // "" for each attr, concatenated. - // Remaining text considered as comment. - uint32 Offset; // Offset in bytes from struct start. - uint32 ArrayDim : 22, // Number of array elements, or bits if bitfield. - bBaseClass : 1, // Sub-var is actually a base class. - bBitfield : 1, // Var is a bitfield, ArrayDim is number of bits. - BitOffset : 6, // Additional offset in bits for bitfields. - // Bit offset is computed in declaration order; on some platforms, it goes high to low. - BitWordWidth : 2; // Width of bitfield = 1 byte << BitWordWidth - - - // Accessors. - cstr GetName() const { return Name; } - size_t GetDim() const { return bBitfield ? 1 : ArrayDim; } - size_t GetSize() const { return bBitfield ? (size_t)1 << BitWordWidth : Type.Size* ArrayDim; } - size_t GetElemSize() const { return bBitfield ? (size_t)1 << BitWordWidth : Type.Size; } - size_t GetBits() const { return bBitfield ? ArrayDim : ArrayDim* Type.Size* 8; } - bool IsBaseClass() const { return bBaseClass; } - bool IsInline() const - { - if (bBaseClass && Offset == 0) - { - const CVarInfo* pFirst = Type.NextSubVar(0); - if (pFirst) - { - return pFirst->IsBaseClass(); - } - } - return false; - } - - bool GetLimit(ENumericLimit eLimit, float& fVal) const - { - return Type.GetLimit(eLimit, fVal); - } - - // Useful functions. - void* GetAddress(void* base) const - { - return (char*)base + Offset; - } - const void* GetAddress(const void* base) const - { - return (const char*)base + Offset; - } - bool FromString(void* base, cstr str, FFromString flags = 0) const - { - assert(!bBitfield); - return Type.FromString((char*)base + Offset, str, flags); - } - string ToString(const void* base, FToString flags = 0, const void* def_base = 0) const - { - assert(!bBitfield); - return Type.ToString((const char*)base + Offset, flags, def_base ? (const char*)def_base + Offset : 0); - } - - // Attribute access. Not fast. - bool GetAttr(cstr name) const; - bool GetAttr(cstr name, float& val) const; - bool GetAttr(cstr name, string& val) const; - - // Comment, excluding attributes. - cstr GetComment() const; - }; - - // Structure var iteration. - virtual CVarInfo const* NextSubVar([[maybe_unused]] CVarInfo const* pPrev, [[maybe_unused]] bool bRecurseBase = false) const - { return 0; } - inline bool HasSubVars() const - { return NextSubVar(0) != 0; } - #define AllSubVars(pVar, Info) \ - (const CTypeInfo::CVarInfo* pVar = (Info).NextSubVar(0); pVar; pVar = (Info).NextSubVar(pVar)) - - // Named var search. - virtual const CVarInfo* FindSubVar([[maybe_unused]] cstr name) const - { return 0; } - - virtual CTypeInfo const* const* NextTemplateType([[maybe_unused]] CTypeInfo const* const* pPrev) const - { return 0; } - inline bool IsTemplate() const - { return NextTemplateType(0) != 0; } - - // - // String enumeration interface. - // Return sequential strings in enumeration, then 0 when out of range. - // String/int conversion is handled by ToString/FromString. - // - virtual cstr EnumElem([[maybe_unused]] uint nIndex) const { return 0; } -}; - - -#endif // CRYINCLUDE_CRYCOMMON_CRYTYPEINFO_H diff --git a/Code/CryEngine/CryCommon/CryVersion.h b/Code/CryEngine/CryCommon/CryVersion.h deleted file mode 100644 index 70a1a1bf28..0000000000 --- a/Code/CryEngine/CryCommon/CryVersion.h +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Defines File version structure. - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYVERSION_H -#define CRYINCLUDE_CRYCOMMON_CRYVERSION_H -#pragma once - -////////////////////////////////////////////////////////////////////////// -/** This class keeps file version information. -*/ -struct SFileVersion -{ - int v[4]; - - SFileVersion() - { - v[0] = v[1] = v[2] = v[3] = 0; - } - SFileVersion(const int vers[]) - { - v[0] = vers[0]; - v[1] = vers[1]; - v[2] = vers[2]; - v[3] = 1; - } - - void Set(const char* s) - { - v[0] = v[1] = v[2] = v[3] = 0; - - char t[50]; - const size_t len = (std::min)(strlen(s), sizeof(t) - 1); - memcpy(t, s, len); - t[len] = 0; - - char* p; - char* next = nullptr; - [[maybe_unused]] size_t strmax = sizeof(t); - p = azstrtok(t, &strmax, ".", &next); - if (!p) - { - return; - } - v[3] = atoi(p); - p = azstrtok(nullptr, &strmax, ".", &next); - if (!p) - { - return; - } - v[2] = atoi(p); - p = azstrtok(nullptr, &strmax, ".", &next); - if (!p) - { - return; - } - v[1] = atoi(p); - p = azstrtok(nullptr, &strmax, ".", &next); - if (!p) - { - return; - } - v[0] = atoi(p); - } - - explicit SFileVersion(const char* s) - { - Set(s); - } - - bool operator <(const SFileVersion& v2) const - { - if (v[3] < v2.v[3]) - { - return true; - } - if (v[3] > v2.v[3]) - { - return false; - } - - if (v[2] < v2.v[2]) - { - return true; - } - if (v[2] > v2.v[2]) - { - return false; - } - - if (v[1] < v2.v[1]) - { - return true; - } - if (v[1] > v2.v[1]) - { - return false; - } - - if (v[0] < v2.v[0]) - { - return true; - } - if (v[0] > v2.v[0]) - { - return false; - } - return false; - } - bool operator ==(const SFileVersion& v1) const - { - if (v[0] == v1.v[0] && v[1] == v1.v[1] && - v[2] == v1.v[2] && v[3] == v1.v[3]) - { - return true; - } - return false; - } - bool operator >(const SFileVersion& v1) const - { - return !(*this < v1); - } - bool operator >=(const SFileVersion& v1) const - { - return (*this == v1) || (*this > v1); - } - bool operator <=(const SFileVersion& v1) const - { - return (*this == v1) || (*this < v1); - } - - int& operator[](int i) { return v[i]; } - int operator[](int i) const { return v[i]; } - - template - void ToShortString(char(&buffer)[size]) const - { - sprintf_s(buffer, size, "%d.%d.%d", v[2], v[1], v[0]); - } - - void ToShortString(char* s, size_t bufferSize) const - { - sprintf_s(s, bufferSize, "%d.%d.%d", v[2], v[1], v[0]); - } - - template - void ToString(char(&buffer)[size]) const - { - sprintf_s(buffer, size, "%d.%d.%d.%d", v[3], v[2], v[1], v[0]); - } - - void ToString(char* s, size_t bufferSize) const - { - sprintf_s(s, bufferSize, "%d.%d.%d.%d", v[3], v[2], v[1], v[0]); - } -}; - -#endif // CRYINCLUDE_CRYCOMMON_CRYVERSION_H diff --git a/Code/CryEngine/CryCommon/CryWindows.h b/Code/CryEngine/CryCommon/CryWindows.h deleted file mode 100644 index 3d57f6a24e..0000000000 --- a/Code/CryEngine/CryCommon/CryWindows.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Specific header to handle Windows.h include - - -#ifndef CRYINCLUDE_CRYCOMMON_CRYWINDOWS_H -#define CRYINCLUDE_CRYCOMMON_CRYWINDOWS_H -#pragma once - - -#if defined(WIN32) || defined(WIN64) - -#ifndef FULL_WINDOWS_HEADER - #define WIN32_LEAN_AND_MEAN -#endif - -#include - -#undef GetCommandLine -#undef GetObject -#undef PlaySound -#undef GetClassName -#undef DrawText -#undef GetCharWidth -#undef GetUserName -#undef LoadLibrary -#undef RegisterClass - -#undef min -#undef max - -#undef NOMINMAX -#undef WIN32_LEAN_AND_MEAN -#undef FULL_WINDOWS_HEADER - -#endif - -#endif // CRYINCLUDE_CRYCOMMON_CRYWINDOWS_H diff --git a/Code/CryEngine/CryCommon/Cry_Camera.h b/Code/CryEngine/CryCommon/Cry_Camera.h deleted file mode 100644 index b10134350c..0000000000 --- a/Code/CryEngine/CryCommon/Cry_Camera.h +++ /dev/null @@ -1,2428 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Common Camera class implementation - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_CAMERA_H -#define CRYINCLUDE_CRYCOMMON_CRY_CAMERA_H -#pragma once - - -//DOC-IGNORE-BEGIN -#include -#include -#include -#include -//DOC-IGNORE-END - -////////////////////////////////////////////////////////////////////// -#define CAMERA_MIN_NEAR 0.001f -#define DEFAULT_NEAR 0.2f -#define DEFAULT_FAR 1024.0f -#define DEFAULT_FOV (75.0f * gf_PI / 180.0f) -#define MIN_FOV 0.0000001f - -////////////////////////////////////////////////////////////////////// - -enum -{ - FR_PLANE_NEAR, - FR_PLANE_FAR, - FR_PLANE_RIGHT, - FR_PLANE_LEFT, - FR_PLANE_TOP, - FR_PLANE_BOTTOM, - FRUSTUM_PLANES -}; - -////////////////////////////////////////////////////////////////////// - -enum cull -{ - CULL_EXCLUSION, // The whole object is outside of frustum. - CULL_OVERLAP, // The object & frustum overlap. - CULL_INCLUSION // The whole object is inside frustum. -}; - -class CameraViewParameters -{ -public: - CameraViewParameters(); - - void LookAt(const Vec3& Eye, const Vec3& ViewRefPt, const Vec3& ViewUp); - void Perspective(float Yfov, float Aspect, float Ndist, float Fdist); - void Frustum(float l, float r, float b, float t, float Ndist, float Fdist); - const Vec3& wCOP() const; - Vec3 ViewDir() const; - Vec3 ViewDirOffAxis() const; - - float* GetXform_Screen2Obj(float* M, int WW, int WH) const; - float* GetXform_Obj2Screen(float* M, int WW, int WH) const; - - float* GetModelviewMatrix(float* M) const; - float* GetProjectionMatrix(float* M) const; - float* GetViewportMatrix(float* M, int WW, int WH) const; - - void SetModelviewMatrix(const float* M); - - void GetLookAtParams(Vec3* Eye, Vec3* ViewRefPt, Vec3* ViewUp) const; - void GetPerspectiveParams(float* Yfov, float* Xfov, float* Aspect, float* Ndist, float* Fdist) const; - void GetFrustumParams(float* l, float* r, float* b, float* t, float* Ndist, float* Fdist) const; - - float* GetInvModelviewMatrix(float* M) const; - float* GetInvProjectionMatrix(float* M) const; - float* GetInvViewportMatrix(float* M, int WW, int WH) const; - - Vec3 WorldToCam(const Vec3& wP) const; - float WorldToCamZ(const Vec3& wP) const; - Vec3 CamToWorld(const Vec3& cP) const; - - void LoadIdentityXform(); - void Xform(const float M[16]); - - void Translate(const Vec3& trans); - void Rotate(const float M[9]); - - void GetPixelRay(float sx, float sy, int ww, int wh, Vec3* Start, Vec3* Dir) const; - - void CalcVerts(Vec3* V) const; - void CalcTileVerts(Vec3* V, f32 nPosX, f32 nPosY, f32 nGridSizeX, f32 nGridSizeY) const; - void CalcRegionVerts(Vec3* V, const Vec2& vMin, const Vec2& vMax) const; - void CalcTiledRegionVerts(Vec3* V, Vec2& vMin, Vec2& vMax, f32 nPosX, f32 nPosY, f32 nGridSizeX, f32 nGridSizeY) const; - - Vec3 vX, vY, vZ; - Vec3 vOrigin; - float fWL, fWR, fWB, fWT; - float fNear, fFar; -}; - -inline float* Frustum16fv(float* M, float l, float r, float b, float t, float n, float f) -{ - M[0] = (2 * n) / (r - l); - M[4] = 0; - M[8] = (r + l) / (r - l); - M[12] = 0; - M[1] = 0; - M[5] = (2 * n) / (t - b); - M[9] = (t + b) / (t - b); - M[13] = 0; - M[2] = 0; - M[6] = 0; - M[10] = -(f + n) / (f - n); - M[14] = (-2 * f * n) / (f - n); - M[3] = 0; - M[7] = 0; - M[11] = -1; - M[15] = 0; - - return M; -} - -inline float* Viewing16fv(float* M, const Vec3 X, const Vec3 Y, const Vec3 Z, const Vec3 O) -{ - M[0] = X.x; - M[4] = X.y; - M[8] = X.z; - M[12] = -X | O; - M[1] = Y.x; - M[5] = Y.y; - M[9] = Y.z; - M[13] = -Y | O; - M[2] = Z.x; - M[6] = Z.y; - M[10] = Z.z; - M[14] = -Z | O; - M[3] = 0; - M[7] = 0; - M[11] = 0; - M[15] = 1; - return M; -} - - -inline CameraViewParameters::CameraViewParameters() -{ - vX.Set(1, 0, 0); - vY.Set(0, 1, 0); - vZ.Set(0, 0, 1); - vOrigin.Set(0, 0, 0); - fNear = 1.4142f; - fFar = 10; - fWL = -1; - fWR = 1; - fWT = 1; - fWB = -1; -} - -inline void CameraViewParameters::LookAt(const Vec3& Eye, const Vec3& ViewRefPt, const Vec3& ViewUp) -{ - vZ = Eye - ViewRefPt; - vZ.NormalizeSafe(); - vX = ViewUp % vZ; - vX.NormalizeSafe(); - vY = vZ % vX; - vY.NormalizeSafe(); - vOrigin = Eye; -} - -inline void CameraViewParameters::Perspective(float Yfov, float Aspect, float Ndist, float Fdist) -{ - fNear = Ndist; - fFar = Fdist; - fWT = tanf(Yfov * 0.5f) * fNear; - fWB = -fWT; - fWR = fWT * Aspect; - fWL = -fWR; -} - -inline void CameraViewParameters::Frustum(float l, float r, float b, float t, float Ndist, float Fdist) -{ - fNear = Ndist; - fFar = Fdist; - fWR = r; - fWL = l; - fWB = b; - fWT = t; -} - - -inline void CameraViewParameters::GetLookAtParams(Vec3* Eye, Vec3* ViewRefPt, Vec3* ViewUp) const -{ - *Eye = vOrigin; - *ViewRefPt = vOrigin - vZ; - *ViewUp = vY; -} - -inline void CameraViewParameters::GetPerspectiveParams(float* Yfov, float* Xfov, float* Aspect, float* Ndist, float* Fdist) const -{ - *Yfov = atanf(fWT / fNear) * 57.29578f * 2.0f; - *Xfov = atanf(fWR / fNear) * 57.29578f * 2.0f; - *Aspect = fWT / fWR; - *Ndist = fNear; - *Fdist = fFar; -} - -inline void CameraViewParameters::GetFrustumParams(float* l, float* r, float* b, float* t, float* Ndist, float* Fdist) const -{ - *l = fWL; - *r = fWR; - *b = fWB; - *t = fWT; - *Ndist = fNear; - *Fdist = fFar; -} - -inline const Vec3& CameraViewParameters::wCOP() const -{ - return(vOrigin); -} - -inline Vec3 CameraViewParameters::ViewDir() const -{ - return(-vZ); -} - -inline Vec3 CameraViewParameters::ViewDirOffAxis() const -{ - float fX = (fWL + fWR) * 0.5f, fY = (fWT + fWB) * 0.5f; // MIDPOINT ON VIEWPLANE WINDOW - Vec3 ViewDir = vX * fX + vY * fY - vZ * fNear; - ViewDir.Normalize(); - return ViewDir; -} - -inline Vec3 CameraViewParameters::WorldToCam(const Vec3& wP) const -{ - Vec3 sP(wP - vOrigin); - Vec3 cP(vX | sP, vY | sP, vZ | sP); - return cP; -} - -inline float CameraViewParameters::WorldToCamZ(const Vec3& wP) const -{ - Vec3 sP(wP - vOrigin); - float zdist = vZ | sP; - return zdist; -} - -inline Vec3 CameraViewParameters::CamToWorld(const Vec3& cP) const -{ - Vec3 wP(vX * cP.x + vY * cP.y + vZ * cP.z + vOrigin); - return wP; -} - -inline void CameraViewParameters::LoadIdentityXform() -{ - vX.Set(1, 0, 0); - vY.Set(0, 1, 0); - vZ.Set(0, 0, 1); - vOrigin.Set(0, 0, 0); -} - -inline void CameraViewParameters::Xform(const float M[16]) -{ - vX.Set(vX.x * M[0] + vX.y * M[4] + vX.z * M[8], - vX.x * M[1] + vX.y * M[5] + vX.z * M[9], - vX.x * M[2] + vX.y * M[6] + vX.z * M[10]); - vY.Set(vY.x * M[0] + vY.y * M[4] + vY.z * M[8], - vY.x * M[1] + vY.y * M[5] + vY.z * M[9], - vY.x * M[2] + vY.y * M[6] + vY.z * M[10]); - vZ.Set(vZ.x * M[0] + vZ.y * M[4] + vZ.z * M[8], - vZ.x * M[1] + vZ.y * M[5] + vZ.z * M[9], - vZ.x * M[2] + vZ.y * M[6] + vZ.z * M[10]); - vOrigin.Set(vOrigin.x * M[0] + vOrigin.y * M[4] + vOrigin.z * M[8] + M[12], - vOrigin.x * M[1] + vOrigin.y * M[5] + vOrigin.z * M[9] + M[13], - vOrigin.x * M[2] + vOrigin.y * M[6] + vOrigin.z * M[10] + M[14]); - - float Scale = vX.GetLength(); - vX /= Scale; - vY /= Scale; - vZ /= Scale; - - fWL *= Scale; - fWR *= Scale; - fWB *= Scale; - fWT *= Scale; - fNear *= Scale; - fFar *= Scale; -}; - -inline void CameraViewParameters::Translate(const Vec3& trans) -{ - vOrigin += trans; -} - -inline void CameraViewParameters::Rotate(const float M[9]) -{ - vX.Set(vX.x * M[0] + vX.y * M[3] + vX.z * M[6], - vX.x * M[1] + vX.y * M[4] + vX.z * M[7], - vX.x * M[2] + vX.y * M[5] + vX.z * M[8]); - vY.Set(vY.x * M[0] + vY.y * M[3] + vY.z * M[6], - vY.x * M[1] + vY.y * M[4] + vY.z * M[7], - vY.x * M[2] + vY.y * M[5] + vY.z * M[8]); - vZ.Set(vZ.x * M[0] + vZ.y * M[3] + vZ.z * M[6], - vZ.x * M[1] + vZ.y * M[4] + vZ.z * M[7], - vZ.x * M[2] + vZ.y * M[5] + vZ.z * M[8]); -} - -inline float* CameraViewParameters::GetModelviewMatrix(float* M) const -{ - Viewing16fv(M, vX, vY, vZ, vOrigin); - return M; -} - -inline float* CameraViewParameters::GetProjectionMatrix(float* M) const -{ - Frustum16fv(M, fWL, fWR, fWB, fWT, fNear, fFar); - return(M); -} - -inline void CameraViewParameters::GetPixelRay(float sx, float sy, int ww, int wh, Vec3* Start, Vec3* Dir) const -{ - Vec3 wTL = vOrigin + (vX * fWL) + (vY * fWT) - (vZ * fNear); // FIND LOWER-LEFT - Vec3 dX = (vX * (fWR - fWL)) / (float)ww; // WORLD WIDTH OF PIXEL - Vec3 dY = (vY * (fWT - fWB)) / (float)wh; // WORLD HEIGHT OF PIXEL - wTL += (dX * sx - dY * sy); // INCR TO WORLD PIXEL - wTL += (dX * 0.5f - dY * 0.5f); // INCR TO PIXEL CNTR - *Start = vOrigin; - *Dir = wTL - vOrigin; -} - -inline void CameraViewParameters::CalcVerts(Vec3* V) const -{ - float NearZ = -fNear; - V[0].Set(fWR, fWT, NearZ); - V[1].Set(fWL, fWT, NearZ); - V[2].Set(fWL, fWB, NearZ); - V[3].Set(fWR, fWB, NearZ); - - float FarZ = -fFar, FN = fFar / fNear; - float fwL = fWL * FN, fwR = fWR * FN, fwB = fWB * FN, fwT = fWT * FN; - V[4].Set(fwR, fwT, FarZ); - V[5].Set(fwL, fwT, FarZ); - V[6].Set(fwL, fwB, FarZ); - V[7].Set(fwR, fwB, FarZ); - - for (int i = 0; i < 8; i++) - { - V[i] = CamToWorld(V[i]); - } -} - -inline void CameraViewParameters::CalcTileVerts(Vec3* V, f32 nPosX, f32 nPosY, f32 nGridSizeX, f32 nGridSizeY) const -{ - float NearZ = -fNear; - - float TileWidth = abs(fWR - fWL) / nGridSizeX; - float TileHeight = abs(fWT - fWB) / nGridSizeY; - float TileL = fWL + TileWidth * nPosX; - float TileR = fWL + TileWidth * (nPosX + 1); - float TileB = fWB + TileHeight * nPosY; - float TileT = fWB + TileHeight * (nPosY + 1); - - V[0].Set(TileR, TileT, NearZ); - V[1].Set(TileL, TileT, NearZ); - V[2].Set(TileL, TileB, NearZ); - V[3].Set(TileR, TileB, NearZ); - - float FarZ = -fFar, FN = fFar / fNear; - float fwL = fWL * FN, fwR = fWR * FN, fwB = fWB * FN, fwT = fWT * FN; - - float TileFarWidth = abs(fwR - fwL) / nGridSizeX; - float TileFarHeight = abs(fwT - fwB) / nGridSizeY; - float TileFarL = fwL + TileFarWidth * nPosX; - float TileFarR = fwL + TileFarWidth * (nPosX + 1); - float TileFarB = fwB + TileFarHeight * nPosY; - float TileFarT = fwB + TileFarHeight * (nPosY + 1); - - V[4].Set(TileFarR, TileFarT, FarZ); - V[5].Set(TileFarL, TileFarT, FarZ); - V[6].Set(TileFarL, TileFarB, FarZ); - V[7].Set(TileFarR, TileFarB, FarZ); - - for (int i = 0; i < 8; i++) - { - V[i] = CamToWorld(V[i]); - } -} - -inline void CameraViewParameters::CalcTiledRegionVerts(Vec3* V, Vec2& vMin, Vec2& vMax, f32 nPosX, f32 nPosY, f32 nGridSizeX, f32 nGridSizeY) const -{ - float NearZ = -fNear; - - Vec2 vTileMin, vTileMax; - - vMin.x = max(vMin.x, nPosX / nGridSizeX); - vMax.x = min(vMax.x, (nPosX + 1) / nGridSizeX); - - vMin.y = max(vMin.y, nPosY / nGridSizeY); - vMax.y = min(vMax.y, (nPosY + 1) / nGridSizeY); - - vTileMin.x = abs(fWR - fWL) * vMin.x; - vTileMin.y = abs(fWT - fWB) * vMin.y; - vTileMax.x = abs(fWR - fWL) * vMax.x; - vTileMax.y = abs(fWT - fWB) * vMax.y; - - - float TileL = fWL + vTileMin.x; - float TileR = fWL + vTileMax.x; - float TileB = fWB + vTileMin.y; - float TileT = fWB + vTileMax.y; - - V[0].Set(TileR, TileT, NearZ); - V[1].Set(TileL, TileT, NearZ); - V[2].Set(TileL, TileB, NearZ); - V[3].Set(TileR, TileB, NearZ); - - float FarZ = -fFar, FN = fFar / fNear; - float fwL = fWL * FN, fwR = fWR * FN, fwB = fWB * FN, fwT = fWT * FN; - - Vec2 vTileFarMin, vTileFarMax; - - vTileFarMin.x = abs(fwR - fwL) * vMin.x; - vTileFarMin.y = abs(fwT - fwB) * vMin.y; - vTileFarMax.x = abs(fwR - fwL) * vMax.x; - vTileFarMax.y = abs(fwT - fwB) * vMax.y; - - - float TileFarL = fwL + vTileFarMin.x; - float TileFarR = fwL + vTileFarMax.x; - float TileFarB = fwB + vTileFarMin.y; - float TileFarT = fwB + vTileFarMax.y; - - V[4].Set(TileFarR, TileFarT, FarZ); - V[5].Set(TileFarL, TileFarT, FarZ); - V[6].Set(TileFarL, TileFarB, FarZ); - V[7].Set(TileFarR, TileFarB, FarZ); - - for (int i = 0; i < 8; i++) - { - V[i] = CamToWorld(V[i]); - } -} - - -inline void CameraViewParameters::CalcRegionVerts(Vec3* V, const Vec2& vMin, const Vec2& vMax) const -{ - float NearZ = -fNear; - - Vec2 vTileMin, vTileMax; - - vTileMin.x = abs(fWR - fWL) * vMin.x; - vTileMin.y = abs(fWT - fWB) * vMin.y; - vTileMax.x = abs(fWR - fWL) * vMax.x; - vTileMax.y = abs(fWT - fWB) * vMax.y; - - float TileL = fWL + vTileMin.x; - float TileR = fWL + vTileMax.x; - float TileB = fWB + vTileMin.y; - float TileT = fWB + vTileMax.y; - - V[0].Set(TileR, TileT, NearZ); - V[1].Set(TileL, TileT, NearZ); - V[2].Set(TileL, TileB, NearZ); - V[3].Set(TileR, TileB, NearZ); - - float FarZ = -fFar, FN = fFar / fNear; - float fwL = fWL * FN, fwR = fWR * FN, fwB = fWB * FN, fwT = fWT * FN; - - Vec2 vTileFarMin, vTileFarMax; - - vTileFarMin.x = abs(fwR - fwL) * vMin.x; - vTileFarMin.y = abs(fwT - fwB) * vMin.y; - vTileFarMax.x = abs(fwR - fwL) * vMax.x; - vTileFarMax.y = abs(fwT - fwB) * vMax.y; - - float TileFarL = fwL + vTileFarMin.x; - float TileFarR = fwL + vTileFarMax.x; - float TileFarB = fwB + vTileFarMin.y; - float TileFarT = fwB + vTileFarMax.y; - - V[4].Set(TileFarR, TileFarT, FarZ); - V[5].Set(TileFarL, TileFarT, FarZ); - V[6].Set(TileFarL, TileFarB, FarZ); - V[7].Set(TileFarR, TileFarB, FarZ); - - for (int i = 0; i < 8; i++) - { - V[i] = CamToWorld(V[i]); - } -} - -/////////////////////////////////////////////////////////////////////////////// -// Implements essential operations like calculation of a view-matrix and -// frustum-culling with simple geometric primitives (Point, Sphere, AABB, OBB). -// All calculation are based on the CryENGINE coordinate-system -// -// We are using a "right-handed" coordinate systems, where the positive X-Axis points -// to the right, the positive Y-Axis points away from the viewer and the positive -// Z-Axis points up. The following illustration shows our coordinate system. -// -//
-//  z-axis
-//    ^
-//    |
-//    |   y-axis
-//    |  /
-//    | /
-//    |/
-//    +---------------->   x-axis
-// 
-// -// This same system is also used in 3D-Studio-MAX. It is not unusual for 3D-APIs like D3D9 or -// OpenGL to use a different coordinate system. Currently in D3D9 we use a coordinate system -// in which the X-Axis points to the right, the Y-Axis points down and the Z-Axis points away -// from the viewer. To convert from the CryEngine system into D3D9 we are just doing a clockwise -// rotation of pi/2 about the X-Axis. This conversion happens in the renderer. -// -// The 6 DOFs (degrees-of-freedom) are stored in one single 3x4 matrix ("m_Matrix"). The 3 -// orientation-DOFs are stored in the 3x3 part and the 3 position-DOFs are stored in the translation- -// vector. You can use the member-functions "GetMatrix()" or "SetMatrix(Matrix34(orientation,positon))" -// to change or access the 6 DOFs. -// -// There are helper-function in Cry_Math.h to create the orientation: -// -// This function builds a 3x3 orientation matrix using a view-direction and a radiant to rotate about Y-axis. -// Matrix33 orientation=Matrix33::CreateOrientation( Vec3(0,1,0), 0 ); -// -// This function builds a 3x3 orientation matrix using Yaw-Pitch-Roll angles. -// Matrix33 orientation=CCamera::CreateOrientationYPR( Ang3(1.234f,0.342f,0) ); -// -/////////////////////////////////////////////////////////////////////////////// -class CCamera -{ -public: - ILINE static Matrix33 CreateOrientationYPR(const Ang3& ypr); - ILINE static Ang3 CreateAnglesYPR(const Matrix33& m); - ILINE static Ang3 CreateAnglesYPR(const Vec3& vdir, f32 r = 0); - ILINE static Vec3 CreateViewdir(const Ang3& ypr); - ILINE static Vec3 CreateViewdir(const Matrix33& m) { return m.GetColumn1(); }; - - ILINE void SetMatrix(const Matrix34& mat) { assert(mat.IsOrthonormal()); m_Matrix = mat; UpdateFrustum(); }; - ILINE void SetMatrixNoUpdate(const Matrix34& mat) { assert(mat.IsOrthonormal()); m_Matrix = mat; }; - ILINE const Matrix34& GetMatrix() const { return m_Matrix; }; - ILINE Vec3 GetViewdir() const { return m_Matrix.GetColumn1(); }; - - ILINE void SetEntityRotation(const Quat& entityRot) { m_entityRot = entityRot; } - ILINE Quat GetEntityRotation() { return m_entityRot; } - ILINE void SetEntityPos(const Vec3& entityPos) { m_entityPos = entityPos; } - ILINE Vec3 GetEntityPos() const { return m_entityPos; }; - - ILINE Matrix34 GetViewMatrix() const { return m_Matrix.GetInverted(); }; - ILINE Vec3 GetPosition() const { return m_Matrix.GetTranslation(); } - ILINE void SetPosition(const Vec3& p) { m_Matrix.SetTranslation(p); UpdateFrustum(); } - ILINE void SetPositionNoUpdate(const Vec3& p) { m_Matrix.SetTranslation(p); } - ILINE bool Project(const Vec3& p, Vec3& result, Vec2i topLeft = Vec2i(0, 0), Vec2i widthHeight = Vec2i(0, 0)) const; - ILINE bool Unproject(const Vec3& viewportPos, Vec3& result, Vec2i topLeft = Vec2i(0, 0), Vec2i widthHeight = Vec2i(0, 0)) const; - ILINE void CalcScreenBounds(int* vOut, const AABB* pAABB, int nWidth, int nHeight) const; - ILINE Vec3 GetUp() const { return m_Matrix.GetColumn2(); } - - //------------------------------------------------------------ - - void SetFrustum(int nWidth, int nHeight, f32 FOV = DEFAULT_FOV, f32 nearplane = DEFAULT_NEAR, f32 farplane = DEFAULT_FAR, f32 fPixelAspectRatio = 1.0f); - ILINE void SetAsymmetry(float l, float r, float b, float t) { m_asymLeft = l; m_asymRight = r; m_asymBottom = b; m_asymTop = t; UpdateFrustum(); } - - ILINE int GetViewSurfaceX() const { return m_Width; } - ILINE int GetViewSurfaceZ() const { return m_Height; } - ILINE f32 GetFov() const { return m_fov; } - ILINE float GetHorizontalFov() const; - ILINE f32 GetNearPlane() const { return m_edge_nlt.y; } - ILINE f32 GetFarPlane() const { return m_edge_flt.y; } - ILINE f32 GetProjRatio() const { return(m_ProjectionRatio); } - ILINE f32 GetAngularResolution() const { return m_Height / m_fov; } - ILINE f32 GetPixelAspectRatio() const { return m_PixelAspectRatio; } - - ILINE Vec3 GetEdgeP() const { return m_edge_plt; } - ILINE Vec3 GetEdgeN() const { return m_edge_nlt; } - ILINE Vec3 GetEdgeF() const { return m_edge_flt; } - - ILINE f32 GetAsymL() const { return m_asymLeft; } - ILINE f32 GetAsymR() const { return m_asymRight; } - ILINE f32 GetAsymB() const { return m_asymBottom; } - ILINE f32 GetAsymT() const { return m_asymTop; } - - ILINE const Vec3& GetNPVertex(int nId) const; //get near-plane vertices - ILINE const Vec3& GetFPVertex(int nId) const; //get far-plane vertices - ILINE const Vec3& GetPPVertex(int nId) const; //get projection-plane vertices - - ILINE const Plane_tpl* GetFrustumPlane(int numplane) const { return &m_fp[numplane]; } - - ////////////////////////////////////////////////////////////////////////// - // Z-Buffer ranges. - // This values are defining near/far clipping plane, it only used to specify z-buffer range. - // Use it only when you want to override default z-buffer range. - // Valid values for are: 0 <= zrange <= 1 - ////////////////////////////////////////////////////////////////////////// - ILINE void SetZRange(float zmin, float zmax) - { - // Clamp to 0-1 range. - m_zrangeMin = min(1.0f, max(0.0f, zmin)); - m_zrangeMax = min(1.0f, max(0.0f, zmax)); - }; - ILINE float GetZRangeMin() const { return m_zrangeMin; } - ILINE float GetZRangeMax() const { return m_zrangeMax; } - ////////////////////////////////////////////////////////////////////////// - - //----------------------------------------------------------------------------------- - //-------- Frustum-Culling ---------------------------- - //----------------------------------------------------------------------------------- - - //Check if a point lies within camera's frustum - bool IsPointVisible(const Vec3& p) const; - - //sphere-frustum test - bool IsSphereVisible_F(const ::Sphere& s) const; - uint8 IsSphereVisible_FH(const ::Sphere& s) const; //this is going to be the exact version of sphere-culling - - // AABB-frustum test - // Fast - bool IsAABBVisible_F(const ::AABB& aabb) const; - uint8 IsAABBVisible_FH(const ::AABB& aabb, bool* pAllInside) const; - uint8 IsAABBVisible_FH(const ::AABB& aabb) const; - - // Exact - bool IsAABBVisible_E(const ::AABB& aabb) const; - uint8 IsAABBVisible_EH(const ::AABB& aabb, bool* pAllInside) const; - uint8 IsAABBVisible_EH(const ::AABB& aabb) const; - - // Multi-camera - bool IsAABBVisible_EHM(const ::AABB& aabb, bool* pAllInside) const; - bool IsAABBVisible_EM(const ::AABB& aabb) const; - bool IsAABBVisible_FM(const ::AABB& aabb) const; - - //OBB-frustum test - bool IsOBBVisible_F(const Vec3& wpos, const OBB& obb) const; - uint8 IsOBBVisible_FH(const Vec3& wpos, const OBB& obb) const; - bool IsOBBVisible_E(const Vec3& wpos, const OBB& obb, f32 uscale) const; - uint8 IsOBBVisible_EH(const Vec3& wpos, const OBB& obb, f32 uscale) const; - - //## constructor/destructor - CCamera() - { - m_Matrix.SetIdentity(); - m_asymRight = 0; - m_asymLeft = 0; - m_asymBottom = 0; - m_asymTop = 0; - SetFrustum(640, 480); - m_zrangeMin = 0.0f; - m_zrangeMax = 1.0f; - m_pMultiCamera = NULL; - m_pPortal = NULL; - m_JustActivated = 0; - m_nPosX = m_nPosY = m_nSizeX = m_nSizeY = 0; - m_entityPos = Vec3(0, 0, 0); - m_entityRot = Quat(0, 0, 0, 1); - } - ~CCamera() {} - - void GetFrustumVertices(Vec3* pVerts) const; - void GetFrustumVerticesCam(Vec3* pVerts) const; - - void SetJustActivated(const bool justActivated) {m_JustActivated = (int)justActivated; } - bool IsJustActivated() const {return m_JustActivated != 0; } - - void SetViewPort(int nPosX, int nPosY, int nSizeX, int nSizeY) - { - m_nPosX = nPosX; - m_nPosY = nPosY; - m_nSizeX = nSizeX; - m_nSizeY = nSizeY; - } - - void GetViewPort(int& nPosX, int& nPosY, int& nSizeX, int& nSizeY) const - { - nPosX = m_nPosX; - nPosY = m_nPosY; - nSizeX = m_nSizeX; - nSizeY = m_nSizeY; - } - - void UpdateFrustum(); - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { /*nothing*/} - - CameraViewParameters m_viewParameters; - -private: - bool AdditionalCheck(const AABB& aabb) const; - bool AdditionalCheck(const Vec3& wpos, const OBB& obb, f32 uscale) const; - - Matrix34 m_Matrix; // world space-matrix - - f32 m_fov; // vertical fov in radiants [0..1*PI[ - int m_Width; // surface width-resolution - int m_Height; // surface height-resolution - f32 m_ProjectionRatio; // ratio between width and height of view-surface - f32 m_PixelAspectRatio; // accounts for aspect ratio and non-square pixels - - Quat m_entityRot; //The rotation of this camera's entity (does not include HMD orientation) - Vec3 m_entityPos; //The position of this camera's entity (does not include HMD position or stereo offsets) - - Vec3 m_edge_nlt; // this is the left/upper vertex of the near-plane - Vec3 m_edge_plt; // this is the left/upper vertex of the projection-plane - Vec3 m_edge_flt; // this is the left/upper vertex of the far-clip-plane - - f32 m_asymLeft, m_asymRight, m_asymBottom, m_asymTop; // Shift to create asymmetric frustum (only used for GPU culling of tessellated objects) - f32 m_asymLeftProj, m_asymRightProj, m_asymBottomProj, m_asymTopProj; - f32 m_asymLeftFar, m_asymRightFar, m_asymBottomFar, m_asymTopFar; - - //usually we update these values every frame (they depend on m_Matrix) - Vec3 m_cltp, m_crtp, m_clbp, m_crbp; //this are the 4 vertices of the projection-plane in cam-space - Vec3 m_cltn, m_crtn, m_clbn, m_crbn; //this are the 4 vertices of the near-plane in cam-space - Vec3 m_cltf, m_crtf, m_clbf, m_crbf; //this are the 4 vertices of the farclip-plane in cam-space - - Plane_tpl m_fp [FRUSTUM_PLANES]; // - uint32 m_idx1[FRUSTUM_PLANES], m_idy1[FRUSTUM_PLANES], m_idz1[FRUSTUM_PLANES]; // - uint32 m_idx2[FRUSTUM_PLANES], m_idy2[FRUSTUM_PLANES], m_idz2[FRUSTUM_PLANES]; // - - // Near Far range of the z-buffer to use for this camera. - float m_zrangeMin; - float m_zrangeMax; - - int m_nPosX, m_nPosY, m_nSizeX, m_nSizeY; - - //------------------------------------------------------------------------ - //--- OLD STUFF - //------------------------------------------------------------------------ -public: - - void SetFrustumVertices(Vec3* arrvVerts) - { - m_clbp = arrvVerts[0]; - m_cltp = arrvVerts[1]; - m_crtp = arrvVerts[2]; - m_crbp = arrvVerts[3]; - } - inline void SetFrustumPlane(int i, const Plane_tpl& plane) - { - m_fp[i] = plane; - //do not break strict aliasing rules, use union instead of reinterpret_casts - union f32_u - { - float floatVal; - uint32 uintVal; - }; - - { - f32_u ux; - ux.floatVal = m_fp[i].n.x; - f32_u uy; - uy.floatVal = m_fp[i].n.y; - f32_u uz; - uz.floatVal = m_fp[i].n.z; - uint32 bitX = ux.uintVal >> 31; - uint32 bitY = uy.uintVal >> 31; - uint32 bitZ = uz.uintVal >> 31; - m_idx1[i] = bitX * 3 + 0; - m_idx2[i] = (1 - bitX) * 3 + 0; - m_idy1[i] = bitY * 3 + 1; - m_idy2[i] = (1 - bitY) * 3 + 1; - m_idz1[i] = bitZ * 3 + 2; - m_idz2[i] = (1 - bitZ) * 3 + 2; - } - } - - inline Ang3 GetAngles() const { return CreateAnglesYPR(Matrix33(m_Matrix)); } - void SetAngles(const Ang3& angles) { SetMatrix(Matrix34::CreateRotationXYZ(angles)); } - - - struct IVisArea* m_pPortal; // pointer to portal used to create this camera - struct ScissorInfo - { - ScissorInfo() { x1 = y1 = x2 = y2 = 0; } - uint16 x1, y1, x2, y2; - }; - ScissorInfo m_ScissorInfo; - class PodArray* m_pMultiCamera; // maybe used for culling instead of this camera - - Vec3 m_OccPosition; //Position for calculate occlusions (needed for portals rendering) - inline const Vec3& GetOccPos() const { return(m_OccPosition); } - - int m_JustActivated; //Camera activated in this frame, used for disabling motion blur effect at camera changes in movies -}; - -inline float CCamera::GetHorizontalFov() const -{ - float fFractionVert = tanf(m_fov * 0.5f); - float fFractionHoriz = fFractionVert * GetProjRatio(); - float fHorizFov = atanf(fFractionHoriz) * 2; - - return fHorizFov; -} - - -// Description -// This function builds a 3x3 orientation matrix using YPR-angles -// Rotation order for the orientation-matrix is Z-X-Y. (Zaxis=YAW / Xaxis=PITCH / Yaxis=ROLL) -// -//
-//  COORDINATE-SYSTEM
-//
-//  z-axis
-//    ^
-//    |
-//    |  y-axis
-//    |  /
-//    | /
-//    |/
-//    +--------------->   x-axis
-// 
-// -// Example: -// Matrix33 orientation=CCamera::CreateOrientationYPR( Ang3(1,2,3) ); -inline Matrix33 CCamera::CreateOrientationYPR(const Ang3& ypr) -{ - f32 sz, cz; - sincos_tpl(ypr.x, &sz, &cz); //Zaxis = YAW - f32 sx, cx; - sincos_tpl(ypr.y, &sx, &cx); //Xaxis = PITCH - f32 sy, cy; - sincos_tpl(ypr.z, &sy, &cy); //Yaxis = ROLL - Matrix33 c; - c.m00 = cy * cz - sy * sz * sx; - c.m01 = -sz * cx; - c.m02 = sy * cz + cy * sz * sx; - c.m10 = cy * sz + sy * sx * cz; - c.m11 = cz * cx; - c.m12 = sy * sz - cy * sx * cz; - c.m20 = -sy * cx; - c.m21 = sx; - c.m22 = cy * cx; - return c; -} - -// Description -//
-//   x-YAW
-//   y-PITCH (negative=looking down / positive=looking up)
-//   z-ROLL
-//   
-// Note: If we are looking along the z-axis, its not possible to specify the x and z-angle -inline Ang3 CCamera::CreateAnglesYPR(const Matrix33& m) -{ - assert(m.IsOrthonormal()); - float l = Vec3(m.m01, m.m11, 0.0f).GetLength(); - if (l > 0.0001) - { - return Ang3(atan2f(-m.m01 / l, m.m11 / l), atan2f(m.m21, l), atan2f(-m.m20 / l, m.m22 / l)); - } - else - { - return Ang3(0, atan2f(m.m21, l), 0); - } -} - -// Description -//
-//x-YAW
-//y-PITCH (negative=looking down / positive=looking up)
-//z-ROLL (its not possile to extract a "roll" from a view-vector)
-// 
-// Note: if we are looking along the z-axis, its not possible to specify the rotation about the z-axis -ILINE Ang3 CCamera::CreateAnglesYPR(const Vec3& vdir, f32 r) -{ - assert((fabs_tpl(1 - (vdir | vdir))) < 0.001); //check if unit-vector - f32 l = Vec3(vdir.x, vdir.y, 0.0f).GetLength(); //check if not zero - if (l > 0.0001) - { - return Ang3(atan2f(-vdir.x / l, vdir.y / l), atan2f(vdir.z, l), r); - } - else - { - return Ang3(0, atan2f(vdir.z, l), r); - } -} - -// Description -//
-//x=yaw
-//y=pitch
-//z=roll (we ignore this element, since its not possible to convert the roll-component into a vector)
-// 
-ILINE Vec3 CCamera::CreateViewdir(const Ang3& ypr) -{ - assert(ypr.IsInRangePI()); //all angles need to be in range between -pi and +pi - f32 sz, cz; - sincos_tpl(ypr.x, &sz, &cz); //YAW - f32 sx, cx; - sincos_tpl(ypr.y, &sx, &cx); //PITCH - return Vec3(-sz * cx, cz * cx, sx); //calculate the view-direction -} - -// Description -//
-//p=world space position
-//result=spreen space pos
-//retval=is visible on screen
-// 
-ILINE bool CCamera::Project(const Vec3& p, Vec3& result, Vec2i topLeft, Vec2i widthHeight) const -{ - Matrix44A mProj, mView; - Vec4 in, transformed, projected; - - mathMatrixPerspectiveFov(&mProj, GetFov(), GetProjRatio(), GetNearPlane(), GetFarPlane()); - - mathMatrixLookAt(&mView, GetPosition(), GetPosition() + GetViewdir(), GetUp()); - - int pViewport[4] = {0, 0, GetViewSurfaceX(), GetViewSurfaceZ()}; - - if (!topLeft.IsZero() || !widthHeight.IsZero()) - { - pViewport[0] = topLeft.x; - pViewport[1] = topLeft.y; - pViewport[2] = widthHeight.x; - pViewport[3] = widthHeight.y; - } - - in.x = p.x; - in.y = p.y; - in.z = p.z; - in.w = 1.0f; - mathVec4Transform((f32*)&transformed, (f32*)&mView, (f32*)&in); - - bool visible = transformed.z < 0.0f; - - mathVec4Transform((f32*)&projected, (f32*)&mProj, (f32*)&transformed); - - if (projected.w == 0.0f) - { - result = Vec3(0.f, 0.f, 0.f); - return false; - } - - projected.x /= projected.w; - projected.y /= projected.w; - projected.z /= projected.w; - - visible = visible && (fabs_tpl(projected.x) <= 1.0f) && (fabs_tpl(projected.y) <= 1.0f); - - //output coords - result.x = pViewport[0] + (1 + projected.x) * pViewport[2] / 2; - result.y = pViewport[1] + (1 - projected.y) * pViewport[3] / 2; //flip coords for y axis - result.z = projected.z; - - return visible; -} - -ILINE bool CCamera::Unproject(const Vec3& viewportPos, Vec3& result, Vec2i topLeft, Vec2i widthHeight) const -{ - Matrix44A mProj, mView; - - mathMatrixPerspectiveFov(&mProj, GetFov(), GetProjRatio(), GetNearPlane(), GetFarPlane()); - mathMatrixLookAt(&mView, GetPosition(), GetPosition() + GetViewdir(), Vec3(0, 0, 1)); - - int viewport[4] = {0, 0, GetViewSurfaceX(), GetViewSurfaceZ()}; - - if (!topLeft.IsZero() || !widthHeight.IsZero()) - { - viewport[0] = topLeft.x; - viewport[1] = topLeft.y; - viewport[2] = widthHeight.x; - viewport[3] = widthHeight.y; - } - - Vec4 vIn; - vIn.x = (viewportPos.x - viewport[0]) * 2 / viewport[2] - 1.0f; - vIn.y = (viewportPos.y - viewport[1]) * 2 / viewport[3] - 1.0f; - vIn.z = viewportPos.z; - vIn.w = 1.0; - - Matrix44A m; - const float* proj = mProj.GetData(); - const float* view = mView.GetData(); - float* mdata = m.GetData(); - for (int i = 0; i < 4; i++) - { - float ai0 = proj[i], ai1 = proj[4 + i], ai2 = proj[8 + i], ai3 = proj[12 + i]; - mdata[i] = ai0 * view[0] + ai1 * view[1] + ai2 * view[2] + ai3 * view[3]; - mdata[4 + i] = ai0 * view[4] + ai1 * view[5] + ai2 * view[6] + ai3 * view[7]; - mdata[8 + i] = ai0 * view[8] + ai1 * view[9] + ai2 * view[10] + ai3 * view[11]; - mdata[12 + i] = ai0 * view[12] + ai1 * view[13] + ai2 * view[14] + ai3 * view[15]; - } - - m.Invert(); - if (!m.IsValid()) - { - return false; - } - - Vec4 vOut = vIn * m; - if (vOut.w == 0.0) - { - return false; - } - - result = Vec3(vOut.x / vOut.w, vOut.y / vOut.w, vOut.z / vOut.w); - - return true; -} - -ILINE void CCamera::CalcScreenBounds(int* vOut, const AABB* pAABB, int nWidth, int nHeight) const -{ - Matrix44A mProj, mView, mVP; - mathMatrixPerspectiveFov(&mProj, GetFov(), GetProjRatio(), GetNearPlane(), GetFarPlane()); - mathMatrixLookAt(&mView, GetPosition(), GetPosition() + GetViewdir(), GetMatrix().GetColumn2()); - mVP = mView * mProj; - - Vec3 verts[8]; - - Vec2i topLeft = Vec2i(0, 0); - Vec2i widthHeight = Vec2i(nWidth, nHeight); - float pViewport[4] = {0.0f, 0.0f, (float)widthHeight.x, (float)widthHeight.y}; - - float x0 = 9999.9f, x1 = -9999.9f, y0 = 9999.9f, y1 = -9999.9f; - float fIntersect = 1.0f; - - Vec3 vDir = GetViewdir(); - Vec3 vPos = GetPosition(); - float d = vPos.Dot(vDir); - - verts[0] = Vec3(pAABB->min.x, pAABB->min.y, pAABB->min.z); - verts[1] = Vec3(pAABB->max.x, pAABB->min.y, pAABB->min.z); - verts[2] = Vec3(pAABB->min.x, pAABB->max.y, pAABB->min.z); - verts[3] = Vec3(pAABB->max.x, pAABB->max.y, pAABB->min.z); - verts[4] = Vec3(pAABB->min.x, pAABB->min.y, pAABB->max.z); - verts[5] = Vec3(pAABB->max.x, pAABB->min.y, pAABB->max.z); - verts[6] = Vec3(pAABB->min.x, pAABB->max.y, pAABB->max.z); - verts[7] = Vec3(pAABB->max.x, pAABB->max.y, pAABB->max.z); - - for (int i = 0; i < 8; i++) - { - float fDist = verts[i].Dot(vDir) - d; - fDist = (float)fsel(fDist, 0.0f, -fDist); - - //Project(verts[i],vertsOut[i], topLeft, widthHeight); - - Vec3 result = Vec3(0.0f, 0.0f, 0.0f); - Vec4 transformed, projected, vIn; - - vIn = Vec4(verts[i].x, verts[i].y, verts[i].z, 1.0f); - - mathVec4Transform((f32*)&projected, (f32*)&mVP, (f32*)&vIn); - - fIntersect = (float)fsel(-projected.w, 0.0f, 1.0f); - - if (!fzero(fIntersect) && !fzero(projected.w)) - { - projected.x /= projected.w; - projected.y /= projected.w; - projected.z /= projected.w; - - //output coords - result.x = pViewport[0] + (1.0f + projected.x) * pViewport[2] / 2.0f; - result.y = pViewport[1] + (1.0f - projected.y) * pViewport[3] / 2.0f; //flip coords for y axis - result.z = projected.z; - } - else - { - vOut[0] = topLeft.x; - vOut[1] = topLeft.y; - vOut[2] = widthHeight.x; - vOut[3] = widthHeight.y; - return; - } - - x0 = min(x0, result.x); - x1 = max(x1, result.x); - y0 = min(y0, result.y); - y1 = max(y1, result.y); - } - - vOut[0] = (int)max(0.0f, min(pViewport[2], x0)); - vOut[1] = (int)max(0.0f, min(pViewport[3], y0)); - vOut[2] = (int)max(0.0f, min(pViewport[2], x1)); - vOut[3] = (int)max(0.0f, min(pViewport[3], y1)); -} - -//--------------------------------------------------------------------------- -//--------------------------------------------------------------------------- -//--------------------------------------------------------------------------- -//--------------------------------------------------------------------------- -inline void CCamera::SetFrustum(int nWidth, int nHeight, f32 FOV, f32 nearplane, f32 farplane, f32 fPixelAspectRatio) -{ - assert (nearplane >= CAMERA_MIN_NEAR); //check if near-plane is valid - assert (farplane >= 0.1f); //check if far-plane is valid - assert (farplane >= nearplane); //check if far-plane bigger then near-plane - assert (FOV >= MIN_FOV && FOV < gf_PI); //check if specified FOV is valid - - m_fov = FOV; - - m_Width = nWidth; //surface x-resolution - m_Height = nHeight; //surface z-resolution - - f32 fWidth = (((f32)nWidth) / fPixelAspectRatio); - f32 fHeight = (f32) nHeight; - m_ProjectionRatio = fWidth / fHeight; // projection ratio (1.0 for square pixels) - - m_PixelAspectRatio = fPixelAspectRatio; - - //------------------------------------------------------------------------- - //--- calculate the Left/Top edge of the Projection-Plane in EYE-SPACE --- - //------------------------------------------------------------------------- - f32 projLeftTopX = -fWidth * 0.5f; - f32 projLeftTopY = static_cast((1.0f / tan_tpl(m_fov * 0.5f)) * (fHeight * 0.5f)); - f32 projLeftTopZ = fHeight * 0.5f; - - m_edge_plt.x = projLeftTopX; - m_edge_plt.y = projLeftTopY; - m_edge_plt.z = projLeftTopZ; - - assert(fabs(acos_tpl(Vec3d(0, m_edge_plt.y, m_edge_plt.z).GetNormalized().y) * 2 - m_fov) < 0.001); - - float invProjLeftTopY = 1.0f / projLeftTopY; - - //Apply asym shift to the camera frustum - Necessary for properly culling tessellated objects in VR - //These are applied in UpdateFrustum to the camera space frustum planes - //Can't apply asym shift to frustum edges here. That would only apply to the top left corner - //rather than the whole frustum. It would also interfere with shadow map application - - //m_asym is at the near plane, we want it at the projection plane too - m_asymLeftProj = (m_asymLeft / nearplane) * projLeftTopY; - m_asymTopProj = (m_asymTop / nearplane) * projLeftTopY; - m_asymRightProj = (m_asymRight / nearplane) * projLeftTopY; - m_asymBottomProj = (m_asymBottom / nearplane) * projLeftTopY; - - //Also want m_asym at the far plane - m_asymLeftFar = m_asymLeftProj * (farplane * invProjLeftTopY); - m_asymTopFar = m_asymTopProj * (farplane * invProjLeftTopY); - m_asymRightFar = m_asymRightProj * (farplane * invProjLeftTopY); - m_asymBottomFar = m_asymBottomProj * (farplane * invProjLeftTopY); - - m_edge_nlt.x = nearplane * projLeftTopX * invProjLeftTopY; - m_edge_nlt.y = nearplane; - m_edge_nlt.z = nearplane * projLeftTopZ * invProjLeftTopY; - - //calculate the left/upper edge of the far-plane (=not rotated) - m_edge_flt.x = projLeftTopX * (farplane * invProjLeftTopY); - m_edge_flt.y = farplane; - m_edge_flt.z = projLeftTopZ * (farplane * invProjLeftTopY); - - UpdateFrustum(); -} - -/*! - * - * Updates all parameters required by the render-engine: - * - * 3d-view-frustum and all matrices - * - */ -inline void CCamera::UpdateFrustum() -{ - //------------------------------------------------------------------- - //--- calculate frustum-edges of projection-plane in CAMERA-SPACE --- - //------------------------------------------------------------------- - Matrix33 m33 = Matrix33(m_Matrix); - m_cltp = m33 * Vec3(+m_edge_plt.x + m_asymLeftProj, +m_edge_plt.y, +m_edge_plt.z + m_asymTopProj); - m_crtp = m33 * Vec3(-m_edge_plt.x + m_asymRightProj, +m_edge_plt.y, +m_edge_plt.z + m_asymTopProj); - m_clbp = m33 * Vec3(+m_edge_plt.x + m_asymLeftProj, +m_edge_plt.y, -m_edge_plt.z + m_asymBottomProj); - m_crbp = m33 * Vec3(-m_edge_plt.x + m_asymRightProj, +m_edge_plt.y, -m_edge_plt.z + m_asymBottomProj); - - m_cltn = m33 * Vec3(+m_edge_nlt.x + m_asymLeft, +m_edge_nlt.y, +m_edge_nlt.z + m_asymTop); - m_crtn = m33 * Vec3(-m_edge_nlt.x + m_asymRight, +m_edge_nlt.y, +m_edge_nlt.z + m_asymTop); - m_clbn = m33 * Vec3(+m_edge_nlt.x + m_asymLeft, +m_edge_nlt.y, -m_edge_nlt.z + m_asymBottom); - m_crbn = m33 * Vec3(-m_edge_nlt.x + m_asymRight, +m_edge_nlt.y, -m_edge_nlt.z + m_asymBottom); - - m_cltf = m33 * Vec3(+m_edge_flt.x + m_asymLeftFar, +m_edge_flt.y, +m_edge_flt.z + m_asymTopFar); - m_crtf = m33 * Vec3(-m_edge_flt.x + m_asymRightFar, +m_edge_flt.y, +m_edge_flt.z + m_asymTopFar); - m_clbf = m33 * Vec3(+m_edge_flt.x + m_asymLeftFar, +m_edge_flt.y, -m_edge_flt.z + m_asymBottomFar); - m_crbf = m33 * Vec3(-m_edge_flt.x + m_asymRightFar, +m_edge_flt.y, -m_edge_flt.z + m_asymBottomFar); - - //------------------------------------------------------------------------------- - //--- calculate the six frustum-planes using the frustum edges in world-space --- - //------------------------------------------------------------------------------- - m_fp[FR_PLANE_NEAR ] = Plane_tpl::CreatePlane(m_crtn + GetPosition(), m_cltn + GetPosition(), m_crbn + GetPosition()); - m_fp[FR_PLANE_RIGHT ] = Plane_tpl::CreatePlane(m_crbf + GetPosition(), m_crtf + GetPosition(), GetPosition()); - m_fp[FR_PLANE_LEFT ] = Plane_tpl::CreatePlane(m_cltf + GetPosition(), m_clbf + GetPosition(), GetPosition()); - m_fp[FR_PLANE_TOP ] = Plane_tpl::CreatePlane(m_crtf + GetPosition(), m_cltf + GetPosition(), GetPosition()); - m_fp[FR_PLANE_BOTTOM] = Plane_tpl::CreatePlane(m_clbf + GetPosition(), m_crbf + GetPosition(), GetPosition()); - m_fp[FR_PLANE_FAR ] = Plane_tpl::CreatePlane(m_crtf + GetPosition(), m_crbf + GetPosition(), m_cltf + GetPosition()); //clip-plane - - uint32 rh = m_Matrix.IsOrthonormalRH(); - if (rh == 0) - { - m_fp[FR_PLANE_NEAR ] = -m_fp[FR_PLANE_NEAR ]; - m_fp[FR_PLANE_RIGHT ] = -m_fp[FR_PLANE_RIGHT ]; - m_fp[FR_PLANE_LEFT ] = -m_fp[FR_PLANE_LEFT ]; - m_fp[FR_PLANE_TOP ] = -m_fp[FR_PLANE_TOP ]; - m_fp[FR_PLANE_BOTTOM] = -m_fp[FR_PLANE_BOTTOM]; - m_fp[FR_PLANE_FAR ] = -m_fp[FR_PLANE_FAR ]; //clip-plane - } - - union f32_u - { - float floatVal; - uint32 uintVal; - }; - - for (int i = 0; i < FRUSTUM_PLANES; i++) - { - f32_u ux; - ux.floatVal = m_fp[i].n.x; - f32_u uy; - uy.floatVal = m_fp[i].n.y; - f32_u uz; - uz.floatVal = m_fp[i].n.z; - uint32 bitX = ux.uintVal >> 31; - uint32 bitY = uy.uintVal >> 31; - uint32 bitZ = uz.uintVal >> 31; - m_idx1[i] = bitX * 3 + 0; - m_idx2[i] = (1 - bitX) * 3 + 0; - m_idy1[i] = bitY * 3 + 1; - m_idy2[i] = (1 - bitY) * 3 + 1; - m_idz1[i] = bitZ * 3 + 2; - m_idz2[i] = (1 - bitZ) * 3 + 2; - } - m_OccPosition = GetPosition(); -} - -// Summary -// Return frustum vertices in world space -// Description -// Takes pointer to array of 8 elements -inline void CCamera::GetFrustumVertices(Vec3* pVerts) const -{ - Matrix33 m33 = Matrix33(m_Matrix); - - /* - The frustum array contains points in the following order - - frustum[0] = far left top - frustum[1] = far left bottom - frustum[2] = far right bottom - frustum[3] = far right top - - frustum[4] = near left top - frustum[5] = near left bottom - frustum[6] = near right bottom - frustum[7] = near right top - */ - - int i = 0; - - pVerts[i++] = m33 * Vec3(+m_edge_flt.x, +m_edge_flt.y, +m_edge_flt.z) + GetPosition(); - pVerts[i++] = m33 * Vec3(+m_edge_flt.x, +m_edge_flt.y, -m_edge_flt.z) + GetPosition(); - pVerts[i++] = m33 * Vec3(-m_edge_flt.x, +m_edge_flt.y, -m_edge_flt.z) + GetPosition(); - pVerts[i++] = m33 * Vec3(-m_edge_flt.x, +m_edge_flt.y, +m_edge_flt.z) + GetPosition(); - - pVerts[i++] = m33 * Vec3(+m_edge_nlt.x, +m_edge_nlt.y, +m_edge_nlt.z) + GetPosition(); - pVerts[i++] = m33 * Vec3(+m_edge_nlt.x, +m_edge_nlt.y, -m_edge_nlt.z) + GetPosition(); - pVerts[i++] = m33 * Vec3(-m_edge_nlt.x, +m_edge_nlt.y, -m_edge_nlt.z) + GetPosition(); - pVerts[i++] = m33 * Vec3(-m_edge_nlt.x, +m_edge_nlt.y, +m_edge_nlt.z) + GetPosition(); -} - -inline void CCamera::GetFrustumVerticesCam(Vec3* pVerts) const -{ - int i = 0; - - //near plane - pVerts[i++] = Vec3(+m_edge_nlt.x, +m_edge_nlt.y, +m_edge_nlt.z); - pVerts[i++] = Vec3(+m_edge_nlt.x, +m_edge_nlt.y, -m_edge_nlt.z); - pVerts[i++] = Vec3(-m_edge_nlt.x, +m_edge_nlt.y, -m_edge_nlt.z); - pVerts[i++] = Vec3(-m_edge_nlt.x, +m_edge_nlt.y, +m_edge_nlt.z); - - //far plane - pVerts[i++] = Vec3(+m_edge_flt.x, +m_edge_flt.y, +m_edge_flt.z); - pVerts[i++] = Vec3(+m_edge_flt.x, +m_edge_flt.y, -m_edge_flt.z); - pVerts[i++] = Vec3(-m_edge_flt.x, +m_edge_flt.y, -m_edge_flt.z); - pVerts[i++] = Vec3(-m_edge_flt.x, +m_edge_flt.y, +m_edge_flt.z); -} - -//get near-plane vertices -ILINE const Vec3& CCamera::GetNPVertex(int nId) const -{ - switch (nId) - { - case 0: - return m_clbn; - case 1: - return m_cltn; - case 2: - return m_crtn; - case 3: - return m_crbn; - } - assert(0); - return m_clbn; -} -//get far-plane vertices -ILINE const Vec3& CCamera::GetFPVertex(int nId) const -{ - switch (nId) - { - case 0: - return m_clbf; - case 1: - return m_cltf; - case 2: - return m_crtf; - case 3: - return m_crbf; - } - assert(0); - return m_clbf; -} -ILINE const Vec3& CCamera::GetPPVertex(int nId) const -{ - switch (nId) - { - case 0: - return m_clbp; - case 1: - return m_cltp; - case 2: - return m_crtp; - case 3: - return m_crbp; - } - assert(0); - return m_clbp; -} - - - - -// Description -// Check if a point lies within camera's frustum -// -// Example -// u8 InOut=camera.IsPointVisible(point); -// -// return values -// CULL_EXCLUSION = point outside of frustum -// CULL_INTERSECT = point inside of frustum -inline bool CCamera::IsPointVisible(const Vec3& p) const -{ - if ((m_fp[FR_PLANE_NEAR ] | p) > 0) - { - return CULL_EXCLUSION; - } - if ((m_fp[FR_PLANE_RIGHT ] | p) > 0) - { - return CULL_EXCLUSION; - } - if ((m_fp[FR_PLANE_LEFT ] | p) > 0) - { - return CULL_EXCLUSION; - } - if ((m_fp[FR_PLANE_TOP ] | p) > 0) - { - return CULL_EXCLUSION; - } - if ((m_fp[FR_PLANE_BOTTOM] | p) > 0) - { - return CULL_EXCLUSION; - } - if ((m_fp[FR_PLANE_FAR ] | p) > 0) - { - return CULL_EXCLUSION; - } - return CULL_OVERLAP; -} - - - - - - - - -// Description -// Conventional method to check if a sphere and the camera-frustum overlap -// The center of the sphere is assumed to be in world-space. -// -// Example -// u8 InOut=camera.IsSphereVisible_F(sphere); -// -// return values -// CULL_EXCLUSION = sphere outside of frustum (very fast rejection-test) -// CULL_INTERSECT = sphere and frustum intersects or sphere in completely inside frustum -inline bool CCamera::IsSphereVisible_F(const ::Sphere& s) const -{ - if ((m_fp[0] | s.center) > s.radius) - { - return CULL_EXCLUSION; - } - if ((m_fp[1] | s.center) > s.radius) - { - return CULL_EXCLUSION; - } - if ((m_fp[2] | s.center) > s.radius) - { - return CULL_EXCLUSION; - } - if ((m_fp[3] | s.center) > s.radius) - { - return CULL_EXCLUSION; - } - if ((m_fp[4] | s.center) > s.radius) - { - return CULL_EXCLUSION; - } - if ((m_fp[5] | s.center) > s.radius) - { - return CULL_EXCLUSION; - } - return CULL_OVERLAP; -} - -// Description -// Conventional method to check if a sphere and the camera-frustum overlap, or -// if the sphere is completely inside the camera-frustum. The center of the -// sphere is assumed to be in world-space. -// -// Example -// u8 InOut=camera.IsSphereVisible_FH(sphere); -// -// return values -// CULL_EXCLUSION = sphere outside of frustum (very fast rejection-test) -// CULL_INTERSECT = sphere intersects the borders of the frustum, further checks necessary -// CULL_INCLUSION = sphere is complete inside the frustum, no further checks necessary -inline uint8 CCamera::IsSphereVisible_FH(const ::Sphere& s) const -{ - f32 nc, rc, lc, tc, bc, cc; - if ((nc = m_fp[0] | s.center) > s.radius) - { - return CULL_EXCLUSION; - } - if ((rc = m_fp[1] | s.center) > s.radius) - { - return CULL_EXCLUSION; - } - if ((lc = m_fp[2] | s.center) > s.radius) - { - return CULL_EXCLUSION; - } - if ((tc = m_fp[3] | s.center) > s.radius) - { - return CULL_EXCLUSION; - } - if ((bc = m_fp[4] | s.center) > s.radius) - { - return CULL_EXCLUSION; - } - if ((cc = m_fp[5] | s.center) > s.radius) - { - return CULL_EXCLUSION; - } - - //now we have to check if it is completely in frustum - f32 r = -s.radius; - if (nc > r) - { - return CULL_OVERLAP; - } - if (lc > r) - { - return CULL_OVERLAP; - } - if (rc > r) - { - return CULL_OVERLAP; - } - if (tc > r) - { - return CULL_OVERLAP; - } - if (bc > r) - { - return CULL_OVERLAP; - } - if (cc > r) - { - return CULL_OVERLAP; - } - return CULL_INCLUSION; -} - - - - - -// Description -// Simple approach to check if an AABB and the camera-frustum overlap. The AABB -// is assumed to be in world-space. This is a very fast method, just one single -// dot-product is necessary to check an AABB against a plane. Actually there -// is no significant speed-different between culling a sphere or an AABB. -// -// Example -// bool InOut=camera.IsAABBVisible_F(aabb); -// -// return values -// CULL_EXCLUSION = AABB outside of frustum (very fast rejection-test) -// CULL_OVERLAP = AABB either intersects the borders of the frustum or is totally inside - -inline bool CCamera::IsAABBVisible_F(const AABB& aabb) const -{ - const f32* p = &aabb.min.x; - uint32 x, y, z; - x = m_idx1[0]; - y = m_idy1[0]; - z = m_idz1[0]; - if ((m_fp[0] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_EXCLUSION; - } - x = m_idx1[1]; - y = m_idy1[1]; - z = m_idz1[1]; - if ((m_fp[1] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_EXCLUSION; - } - x = m_idx1[2]; - y = m_idy1[2]; - z = m_idz1[2]; - if ((m_fp[2] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_EXCLUSION; - } - x = m_idx1[3]; - y = m_idy1[3]; - z = m_idz1[3]; - if ((m_fp[3] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_EXCLUSION; - } - x = m_idx1[4]; - y = m_idy1[4]; - z = m_idz1[4]; - if ((m_fp[4] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_EXCLUSION; - } - x = m_idx1[5]; - y = m_idy1[5]; - z = m_idz1[5]; - if ((m_fp[5] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_EXCLUSION; - } - return CULL_OVERLAP; -} - - -// Description -// Hierarchical approach to check if an AABB and the camera-frustum overlap, or if the AABB -// is totally inside the camera-frustum. The AABB is assumed to be in world-space. -// -// Example -// int InOut=camera.IsAABBVisible_FH(aabb); -// -// return values -// CULL_EXCLUSION = AABB outside of frustum (very fast rejection-test) -// CULL_OVERLAP = AABB intersects the borders of the frustum, further checks necessary -// CULL_INCLUSION = AABB is complete inside the frustum, no further checks necessary - -inline uint8 CCamera::IsAABBVisible_FH(const AABB& aabb, bool* pAllInside) const -{ - assert(pAllInside && *pAllInside == false); - if (IsAABBVisible_F(aabb) == CULL_EXCLUSION) - { - return CULL_EXCLUSION; - } - const f32* p = &aabb.min.x; - uint32 x, y, z; - x = m_idx2[0]; - y = m_idy2[0]; - z = m_idz2[0]; - if ((m_fp[0] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_OVERLAP; - } - x = m_idx2[1]; - y = m_idy2[1]; - z = m_idz2[1]; - if ((m_fp[1] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_OVERLAP; - } - x = m_idx2[2]; - y = m_idy2[2]; - z = m_idz2[2]; - if ((m_fp[2] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_OVERLAP; - } - x = m_idx2[3]; - y = m_idy2[3]; - z = m_idz2[3]; - if ((m_fp[3] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_OVERLAP; - } - x = m_idx2[4]; - y = m_idy2[4]; - z = m_idz2[4]; - if ((m_fp[4] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_OVERLAP; - } - x = m_idx2[5]; - y = m_idy2[5]; - z = m_idz2[5]; - if ((m_fp[5] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_OVERLAP; - } - *pAllInside = true; - return CULL_INCLUSION; -} - -// Description -// Hierarchical approach to check if an AABB and the camera-frustum overlap, or if the AABB -// is totally inside the camera-frustum. The AABB is assumed to be in world-space. -// -// Example -// int InOut=camera.IsAABBVisible_FH(aabb); -// -// return values -// CULL_EXCLUSION = AABB outside of frustum (very fast rejection-test) -// CULL_OVERLAP = AABB intersects the borders of the frustum, further checks necessary -// CULL_INCLUSION = AABB is complete inside the frustum, no further checks necessary -inline uint8 CCamera::IsAABBVisible_FH(const AABB& aabb) const -{ - if (IsAABBVisible_F(aabb) == CULL_EXCLUSION) - { - return CULL_EXCLUSION; - } - const f32* p = &aabb.min.x; - uint32 x, y, z; - x = m_idx2[0]; - y = m_idy2[0]; - z = m_idz2[0]; - if ((m_fp[0] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_OVERLAP; - } - x = m_idx2[1]; - y = m_idy2[1]; - z = m_idz2[1]; - if ((m_fp[1] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_OVERLAP; - } - x = m_idx2[2]; - y = m_idy2[2]; - z = m_idz2[2]; - if ((m_fp[2] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_OVERLAP; - } - x = m_idx2[3]; - y = m_idy2[3]; - z = m_idz2[3]; - if ((m_fp[3] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_OVERLAP; - } - x = m_idx2[4]; - y = m_idy2[4]; - z = m_idz2[4]; - if ((m_fp[4] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_OVERLAP; - } - x = m_idx2[5]; - y = m_idy2[5]; - z = m_idz2[5]; - if ((m_fp[5] | Vec3(p[x], p[y], p[z])) > 0) - { - return CULL_OVERLAP; - } - return CULL_INCLUSION; -} - - -// Description -// This function checks if an AABB and the camera-frustum overlap. The AABB is assumed to be in world-space. -// This test can reject even such AABBs that overlap a frustum-plane far outside the view-frustum. -// IMPORTANT: -// This function is only useful if you really need exact-culling. -// It's about 30% slower then "IsAABBVisible_F(aabb)" -// -// Example: -// int InOut=camera.IsAABBVisible_E(aabb); -// -// return values: -// CULL_EXCLUSION = AABB outside of frustum (very fast rejection-test) -// CULL_OVERLAP = AABB either intersects the borders of the frustum or is totally inside -inline bool CCamera::IsAABBVisible_E(const AABB& aabb) const -{ - uint8 o = IsAABBVisible_FH(aabb); - if (o == CULL_EXCLUSION) - { - return CULL_EXCLUSION; - } - if (o == CULL_INCLUSION) - { - return CULL_OVERLAP; - } - return AdditionalCheck(aabb); //result is either "exclusion" or "overlap" -} - -// Description: -// Improved approach to check if an AABB and the camera-frustum overlap, or if the AABB -// is totally inside the camera-frustum. The AABB is assumed to be in world-space. This -// test can reject even such AABBs that overlap a frustum-plane far outside the view-frustum. -// IMPORTANT: -// This function is only useful if you really need exact-culling. -// It's about 30% slower then "IsAABBVisible_FH(aabb)" -// -// Example: -// int InOut=camera.IsAABBVisible_EH(aabb); -// -// return values: -// CULL_EXCLUSION = AABB outside of frustum (very fast rejection-test) -// CULL_OVERLAP = AABB intersects the borders of the frustum, further checks necessary -// CULL_INCLUSION = AABB is complete inside the frustum, no further checks necessary -inline uint8 CCamera::IsAABBVisible_EH(const AABB& aabb, bool* pAllInside) const -{ - uint8 o = IsAABBVisible_FH(aabb, pAllInside); - if (o == CULL_EXCLUSION) - { - return CULL_EXCLUSION; - } - if (o == CULL_INCLUSION) - { - return CULL_INCLUSION; - } - return AdditionalCheck(aabb); //result is either "exclusion" or "overlap" -} - -// Description: -// Improved approach to check if an AABB and the camera-frustum overlap, or if the AABB -// is totally inside the camera-frustum. The AABB is assumed to be in world-space. This -// test can reject even such AABBs that overlap a frustum-plane far outside the view-frustum. -// IMPORTANT: -// This function is only useful if you really need exact-culling. -// It's about 30% slower then "IsAABBVisible_FH(aabb)" -// -// Example: -// int InOut=camera.IsAABBVisible_EH(aabb); -// -// return values: -// CULL_EXCLUSION = AABB outside of frustum (very fast rejection-test) -// CULL_OVERLAP = AABB intersects the borders of the frustum, further checks necessary -// CULL_INCLUSION = AABB is complete inside the frustum, no further checks necessary -inline uint8 CCamera::IsAABBVisible_EH(const AABB& aabb) const -{ - uint8 o = IsAABBVisible_FH(aabb); - if (o == CULL_EXCLUSION) - { - return CULL_EXCLUSION; - } - if (o == CULL_INCLUSION) - { - return CULL_INCLUSION; - } - return AdditionalCheck(aabb); //result is either "exclusion" or "overlap" -} - -// Description: -// Makes culling taking into account presence of m_pMultiCamera -// If m_pMultiCamera exists - object is visible if at least one of cameras see's it -// -// return values: -// true - box visible -// true - not visible -inline bool CCamera::IsAABBVisible_EHM(const AABB& aabb, bool* pAllInside) const -{ - assert(pAllInside && *pAllInside == false); - - if (!m_pMultiCamera) // use main camera - { - return IsAABBVisible_EH(aabb, pAllInside) != CULL_EXCLUSION; - } - - bool bVisible = false; - - for (int i = 0; i < m_pMultiCamera->Count(); i++) - { - bool bAllIn = false; - - if (m_pMultiCamera->GetAt(i).IsAABBVisible_EH(aabb, &bAllIn)) - { - bVisible = true; - - // don't break here always because another camera may include bbox completely - if (bAllIn) - { - *pAllInside = true; - break; - } - } - } - - return bVisible; -} - -// Description: -// Makes culling taking into account presence of m_pMultiCamera -// If m_pMultiCamera exists - object is visible if at least one of cameras see's it -// -// return values: -// true - box visible -// true - not visible -ILINE bool CCamera::IsAABBVisible_EM(const AABB& aabb) const -{ - if (!m_pMultiCamera) // use main camera - { - return IsAABBVisible_E(aabb) != CULL_EXCLUSION; - } - - // check several parallel cameras - object is visible if at least one camera see's it - - for (int i = 0; i < m_pMultiCamera->Count(); i++) - { - if (m_pMultiCamera->GetAt(i).IsAABBVisible_E(aabb)) - { - return true; - } - } - - return false; -} - - -// Description: -// Makes culling taking into account presence of m_pMultiCamera -// If m_pMultiCamera exists - object is visible if at least one of cameras see's it -// -// return values: -// true - box visible -// true - not visible -ILINE bool CCamera::IsAABBVisible_FM(const AABB& aabb) const -{ - PrefetchLine(&aabb, sizeof(AABB)); - - if (!m_pMultiCamera) // use main camera - { - return IsAABBVisible_F(aabb) != CULL_EXCLUSION; - } - - // check several parallel cameras - object is visible if at least one camera see's it - - for (int i = 0; i < m_pMultiCamera->Count(); i++) - { - if (m_pMultiCamera->GetAt(i).IsAABBVisible_F(aabb)) - { - return true; - } - } - - return false; -} - - - - -// Description -// Fast check if an OBB and the camera-frustum overlap, using the separating-axis-theorem (SAT) -// The center of the OOBB is assumed to be in world-space. -// NOTE: even if the OBB is totally inside the frustum, this function returns CULL_OVERLAP -// For hierarchical frustum-culling this function is not perfect. -// -// Example: -// bool InOut=camera.IsOBBVisibleFast(obb); -// -// return values: -// CULL_EXCLUSION = OBB outside of frustum (very fast rejection-test) -// CULL_OVERLAP = OBB and frustum intersects or OBB in totally inside frustum -inline bool CCamera::IsOBBVisible_F(const Vec3& wpos, const OBB& obb) const -{ - CRY_ASSERT(obb.m33.IsOrthonormalRH(0.001f)); - - //transform the obb-center into world-space - Vec3 p = obb.m33 * obb.c + wpos; - - //extract the orientation-vectors from the columns of the 3x3 matrix - //and scale them by the half-lengths - Vec3 ax = obb.m33.GetColumn0() * obb.h.x; - Vec3 ay = obb.m33.GetColumn1() * obb.h.y; - Vec3 az = obb.m33.GetColumn2() * obb.h.z; - - //we project the axes of the OBB onto the normal of each of the 6 planes. - //If the absolute value of the distance from the center of the OBB to the plane - //is larger then the "radius" of the OBB, then the OBB is outside the frustum. - f32 t; - if ((t = m_fp[0] | p) > 0.0f) - { - if (t > (fabsf(m_fp[0].n | ax) + fabsf(m_fp[0].n | ay) + fabsf(m_fp[0].n | az))) - { - return CULL_EXCLUSION; - } - } - if ((t = m_fp[1] | p) > 0.0f) - { - if (t > (fabsf(m_fp[1].n | ax) + fabsf(m_fp[1].n | ay) + fabsf(m_fp[1].n | az))) - { - return CULL_EXCLUSION; - } - } - if ((t = m_fp[2] | p) > 0.0f) - { - if (t > (fabsf(m_fp[2].n | ax) + fabsf(m_fp[2].n | ay) + fabsf(m_fp[2].n | az))) - { - return CULL_EXCLUSION; - } - } - if ((t = m_fp[3] | p) > 0.0f) - { - if (t > (fabsf(m_fp[3].n | ax) + fabsf(m_fp[3].n | ay) + fabsf(m_fp[3].n | az))) - { - return CULL_EXCLUSION; - } - } - if ((t = m_fp[4] | p) > 0.0f) - { - if (t > (fabsf(m_fp[4].n | ax) + fabsf(m_fp[4].n | ay) + fabsf(m_fp[4].n | az))) - { - return CULL_EXCLUSION; - } - } - if ((t = m_fp[5] | p) > 0.0f) - { - if (t > (fabsf(m_fp[5].n | ax) + fabsf(m_fp[5].n | ay) + fabsf(m_fp[5].n | az))) - { - return CULL_EXCLUSION; - } - } - - //probably the OBB is visible! - //With this test we can't be sure if the OBB partially visible or totally included or - //totally outside the frustum but still intersecting one of the 6 planes (=worst case) - return CULL_OVERLAP; -} - -ILINE uint8 CCamera::IsOBBVisible_FH([[maybe_unused]] const Vec3& wpos, [[maybe_unused]] const OBB& obb) const -{ - //not implemented yet - return CULL_EXCLUSION; -} - -// Description: -// This function checks if an OBB and the camera-frustum overlap. -// This test can reject even such OBBs that overlap a frustum-plane -// far outside the view-frustum. -// IMPORTANT: It is about 10% slower then "IsOBBVisibleFast(obb)" -// -// Example: -// int InOut=camera.IsOBBVisible_E(OBB); -// -// return values: -// CULL_EXCLUSION = OBB outside of frustum (very fast rejection-test) -// CULL_OVERLAP = OBB intersects the borders of the frustum or is totally inside -inline bool CCamera::IsOBBVisible_E(const Vec3& wpos, const OBB& obb, f32 uscale = 1.0f) const -{ - assert(obb.m33.IsOrthonormalRH(0.001f)); - - //transform the obb-center into world-space - Vec3 p = obb.m33 * obb.c * uscale + wpos; - - //extract the orientation-vectors from the columns of the 3x3 matrix - //and scale them by the half-lengths - Vec3 ax = obb.m33.GetColumn0() * obb.h.x * uscale; - Vec3 ay = obb.m33.GetColumn1() * obb.h.y * uscale; - Vec3 az = obb.m33.GetColumn2() * obb.h.z * uscale; - - //we project the axes of the OBB onto the normal of each of the 6 planes. - //If the absolute value of the distance from the center of the OBB to the plane - //is larger then the "radius" of the OBB, then the OBB is outside the frustum. - f32 t0, t1, t2, t3, t4, t5; - bool mt0, mt1, mt2, mt3, mt4, mt5; - mt0 = (t0 = m_fp[0] | p) > 0.0f; - if (mt0) - { - if (t0 > (fabsf(m_fp[0].n | ax) + fabsf(m_fp[0].n | ay) + fabsf(m_fp[0].n | az))) - { - return CULL_EXCLUSION; - } - } - mt1 = (t1 = m_fp[1] | p) > 0.0f; - if (mt1) - { - if (t1 > (fabsf(m_fp[1].n | ax) + fabsf(m_fp[1].n | ay) + fabsf(m_fp[1].n | az))) - { - return CULL_EXCLUSION; - } - } - mt2 = (t2 = m_fp[2] | p) > 0.0f; - if (mt2) - { - if (t2 > (fabsf(m_fp[2].n | ax) + fabsf(m_fp[2].n | ay) + fabsf(m_fp[2].n | az))) - { - return CULL_EXCLUSION; - } - } - mt3 = (t3 = m_fp[3] | p) > 0.0f; - if (mt3) - { - if (t3 > (fabsf(m_fp[3].n | ax) + fabsf(m_fp[3].n | ay) + fabsf(m_fp[3].n | az))) - { - return CULL_EXCLUSION; - } - } - mt4 = (t4 = m_fp[4] | p) > 0.0f; - if (mt4) - { - if (t4 > (fabsf(m_fp[4].n | ax) + fabsf(m_fp[4].n | ay) + fabsf(m_fp[4].n | az))) - { - return CULL_EXCLUSION; - } - } - mt5 = (t5 = m_fp[5] | p) > 0.0f; - if (mt5) - { - if (t5 > (fabsf(m_fp[5].n | ax) + fabsf(m_fp[5].n | ay) + fabsf(m_fp[5].n | az))) - { - return CULL_EXCLUSION; - } - } - - //if obb-center is in view-frustum, then stop further calculation - if (!(mt0 | mt1 | mt2 | mt3 | mt4 | mt5)) - { - return CULL_OVERLAP; - } - - return AdditionalCheck(wpos, obb, uscale); -} - - -// Description: -// Improved approach to check if an OBB and the camera-frustum intersect, or if the OBB -// is totally inside the camera-frustum. The bounding-box of the OBB is assumed to be -// in world-space. This test can reject even such OBBs that intersect a frustum-plane far -// outside the view-frustum -// -// Example: -// int InOut=camera.IsOBBVisible_EH(obb); -// -// return values: -// CULL_EXCLUSION = OBB outside of frustum (very fast rejection-test) -// CULL_OVERLAP = OBB intersects the borders of the frustum, further checks necessary -// CULL_INCLUSION = OBB is complete inside the frustum, no further checks necessary -inline uint8 CCamera::IsOBBVisible_EH(const Vec3& wpos, const OBB& obb, f32 uscale = 1.0f) const -{ - assert(obb.m33.IsOrthonormalRH(0.001f)); - //transform the obb-center into world-space - Vec3 p = obb.m33 * obb.c * uscale + wpos; - - //extract the orientation-vectors from the columns of the 3x3 matrix - //and scale them by the half-lengths - Vec3 ax = obb.m33.GetColumn0() * obb.h.x * uscale; - Vec3 ay = obb.m33.GetColumn1() * obb.h.y * uscale; - Vec3 az = obb.m33.GetColumn2() * obb.h.z * uscale; - - //we project the axes of the OBB onto the normal of each of the 6 planes. - //If the absolute value of the distance from the center of the OBB to the plane - //is larger then the "radius" of the OBB, then the OBB is outside the frustum. - f32 t0, t1, t2, t3, t4, t5; - bool mt0, mt1, mt2, mt3, mt4, mt5; - if (mt0 = (t0 = m_fp[0] | p) > 0.0f) - { - if (t0 > (fabsf(m_fp[0].n | ax) + fabsf(m_fp[0].n | ay) + fabsf(m_fp[0].n | az))) - { - return CULL_EXCLUSION; - } - } - if (mt1 = (t1 = m_fp[1] | p) > 0.0f) - { - if (t1 > (fabsf(m_fp[1].n | ax) + fabsf(m_fp[1].n | ay) + fabsf(m_fp[1].n | az))) - { - return CULL_EXCLUSION; - } - } - if (mt2 = (t2 = m_fp[2] | p) > 0.0f) - { - if (t2 > (fabsf(m_fp[2].n | ax) + fabsf(m_fp[2].n | ay) + fabsf(m_fp[2].n | az))) - { - return CULL_EXCLUSION; - } - } - if (mt3 = (t3 = m_fp[3] | p) > 0.0f) - { - if (t3 > (fabsf(m_fp[3].n | ax) + fabsf(m_fp[3].n | ay) + fabsf(m_fp[3].n | az))) - { - return CULL_EXCLUSION; - } - } - if (mt4 = (t4 = m_fp[4] | p) > 0.0f) - { - if (t4 > (fabsf(m_fp[4].n | ax) + fabsf(m_fp[4].n | ay) + fabsf(m_fp[4].n | az))) - { - return CULL_EXCLUSION; - } - } - if (mt5 = (t5 = m_fp[5] | p) > 0.0f) - { - if (t5 > (fabsf(m_fp[5].n | ax) + fabsf(m_fp[5].n | ay) + fabsf(m_fp[5].n | az))) - { - return CULL_EXCLUSION; - } - } - - //check if obb-center is in view-frustum - if (!(mt0 | mt1 | mt2 | mt3 | mt4 | mt5)) - { - //yes, it is! - //and now check if OBB is totally included - if (-t0 < (fabsf(m_fp[0].n | ax) + fabsf(m_fp[0].n | ay) + fabsf(m_fp[0].n | az))) - { - return CULL_OVERLAP; - } - if (-t1 < (fabsf(m_fp[1].n | ax) + fabsf(m_fp[1].n | ay) + fabsf(m_fp[1].n | az))) - { - return CULL_OVERLAP; - } - if (-t2 < (fabsf(m_fp[2].n | ax) + fabsf(m_fp[2].n | ay) + fabsf(m_fp[2].n | az))) - { - return CULL_OVERLAP; - } - if (-t3 < (fabsf(m_fp[3].n | ax) + fabsf(m_fp[3].n | ay) + fabsf(m_fp[3].n | az))) - { - return CULL_OVERLAP; - } - if (-t4 < (fabsf(m_fp[4].n | ax) + fabsf(m_fp[4].n | ay) + fabsf(m_fp[4].n | az))) - { - return CULL_OVERLAP; - } - if (-t5 < (fabsf(m_fp[5].n | ax) + fabsf(m_fp[5].n | ay) + fabsf(m_fp[5].n | az))) - { - return CULL_OVERLAP; - } - return CULL_INCLUSION; - } - return AdditionalCheck(wpos, obb, uscale); -} - -//------------------------------------------------------------------------------ -//--- ADDITIONAL-TEST --- -//------------------------------------------------------------------------------ - -extern _MS_ALIGN(64) uint32 BoxSides[]; - -// Description: -// A box can easily straddle one of the view-frustum planes far -// outside the view-frustum and in this case the previous test would -// return CULL_OVERLAP. -// -// Note: With this check, we make sure the AABB is really not visble -NO_INLINE_WEAK bool CCamera::AdditionalCheck(const AABB& aabb) const -{ - Vec3d m = (aabb.min + aabb.max) * 0.5; - uint32 o = 1; //will be reset to 0 if center is outside - o &= isneg(m_fp[0] | m); - o &= isneg(m_fp[2] | m); - o &= isneg(m_fp[3] | m); - o &= isneg(m_fp[4] | m); - o &= isneg(m_fp[5] | m); - o &= isneg(m_fp[1] | m); - if (o) - { - return CULL_OVERLAP; //if obb-center is in view-frustum, then stop further calculation - } - Vec3d vmin(aabb.min - GetPosition()); //AABB in camera-space - Vec3d vmax(aabb.max - GetPosition()); //AABB in camera-space - - uint32 frontx8 = 0; // make the flags using the fact that the upper bit in f32 is its sign - - union f64_u - { - f64 floatVal; - int64 intVal; - }; - f64_u uminx, uminy, uminz, umaxx, umaxy, umaxz; - uminx.floatVal = vmin.x; - uminy.floatVal = vmin.y; - uminz.floatVal = vmin.z; - umaxx.floatVal = vmax.x; - umaxy.floatVal = vmax.y; - umaxz.floatVal = vmax.z; - - frontx8 |= (-uminx.intVal >> 0x3f) & 0x008; //if (AABB.min.x>0.0f) frontx8|=0x008; - frontx8 |= (umaxx.intVal >> 0x3f) & 0x010; //if (AABB.max.x<0.0f) frontx8|=0x010; - frontx8 |= (-uminy.intVal >> 0x3f) & 0x020; //if (AABB.min.y>0.0f) frontx8|=0x020; - frontx8 |= (umaxy.intVal >> 0x3f) & 0x040; //if (AABB.max.y<0.0f) frontx8|=0x040; - frontx8 |= (-uminz.intVal >> 0x3f) & 0x080; //if (AABB.min.z>0.0f) frontx8|=0x080; - frontx8 |= (umaxz.intVal >> 0x3f) & 0x100; //if (AABB.max.z<0.0f) frontx8|=0x100; - - //check if camera is inside the aabb - if (frontx8 == 0) - { - return CULL_OVERLAP; //AABB is patially visible - } - Vec3d v[8] = { - Vec3d(vmin.x, vmin.y, vmin.z), - Vec3d(vmax.x, vmin.y, vmin.z), - Vec3d(vmin.x, vmax.y, vmin.z), - Vec3d(vmax.x, vmax.y, vmin.z), - Vec3d(vmin.x, vmin.y, vmax.z), - Vec3d(vmax.x, vmin.y, vmax.z), - Vec3d(vmin.x, vmax.y, vmax.z), - Vec3d(vmax.x, vmax.y, vmax.z) - }; - - //--------------------------------------------------------------------- - //--- find the silhouette-vertices of the AABB --- - //--------------------------------------------------------------------- - uint32 p0 = BoxSides[frontx8 + 0]; - uint32 p1 = BoxSides[frontx8 + 1]; - uint32 p2 = BoxSides[frontx8 + 2]; - uint32 p3 = BoxSides[frontx8 + 3]; - uint32 p4 = BoxSides[frontx8 + 4]; - uint32 p5 = BoxSides[frontx8 + 5]; - uint32 sideamount = BoxSides[frontx8 + 7]; - - if (sideamount == 4) - { - //-------------------------------------------------------------------------- - //--- we take the 4 vertices of projection-plane in cam-space, --- - //----- and clip them against the 4 side-frustum-planes of the AABB - - //-------------------------------------------------------------------------- - Vec3d s0 = v[p0] % v[p1]; - if ((s0 | m_cltp) > 0 && (s0 | m_crtp) > 0 && (s0 | m_crbp) > 0 && (s0 | m_clbp) > 0) - { - return CULL_EXCLUSION; - } - Vec3d s1 = v[p1] % v[p2]; - if ((s1 | m_cltp) > 0 && (s1 | m_crtp) > 0 && (s1 | m_crbp) > 0 && (s1 | m_clbp) > 0) - { - return CULL_EXCLUSION; - } - Vec3d s2 = v[p2] % v[p3]; - if ((s2 | m_cltp) > 0 && (s2 | m_crtp) > 0 && (s2 | m_crbp) > 0 && (s2 | m_clbp) > 0) - { - return CULL_EXCLUSION; - } - Vec3d s3 = v[p3] % v[p0]; - if ((s3 | m_cltp) > 0 && (s3 | m_crtp) > 0 && (s3 | m_crbp) > 0 && (s3 | m_clbp) > 0) - { - return CULL_EXCLUSION; - } - } - - if (sideamount == 6) - { - //-------------------------------------------------------------------------- - //--- we take the 4 vertices of projection-plane in cam-space, --- - //--- and clip them against the 6 side-frustum-planes of the AABB --- - //-------------------------------------------------------------------------- - Vec3d s0 = v[p0] % v[p1]; - if ((s0 | m_cltp) > 0 && (s0 | m_crtp) > 0 && (s0 | m_crbp) > 0 && (s0 | m_clbp) > 0) - { - return CULL_EXCLUSION; - } - Vec3d s1 = v[p1] % v[p2]; - if ((s1 | m_cltp) > 0 && (s1 | m_crtp) > 0 && (s1 | m_crbp) > 0 && (s1 | m_clbp) > 0) - { - return CULL_EXCLUSION; - } - Vec3d s2 = v[p2] % v[p3]; - if ((s2 | m_cltp) > 0 && (s2 | m_crtp) > 0 && (s2 | m_crbp) > 0 && (s2 | m_clbp) > 0) - { - return CULL_EXCLUSION; - } - Vec3d s3 = v[p3] % v[p4]; - if ((s3 | m_cltp) > 0 && (s3 | m_crtp) > 0 && (s3 | m_crbp) > 0 && (s3 | m_clbp) > 0) - { - return CULL_EXCLUSION; - } - Vec3d s4 = v[p4] % v[p5]; - if ((s4 | m_cltp) > 0 && (s4 | m_crtp) > 0 && (s4 | m_crbp) > 0 && (s4 | m_clbp) > 0) - { - return CULL_EXCLUSION; - } - Vec3d s5 = v[p5] % v[p0]; - if ((s5 | m_cltp) > 0 && (s5 | m_crtp) > 0 && (s5 | m_crbp) > 0 && (s5 | m_clbp) > 0) - { - return CULL_EXCLUSION; - } - } - return CULL_OVERLAP; //AABB is patially visible -} - -//------------------------------------------------------------------------------ -//--- ADDITIONAL-TEST --- -//------------------------------------------------------------------------------ - -// Description: -// A box can easily straddle one of the view-frustum planes far -// outside the view-frustum and in this case the previous test would -// return CULL_OVERLAP. -// Note: -// With this check, we make sure the OBB is really not visible -NO_INLINE_WEAK bool CCamera::AdditionalCheck(const Vec3& wpos, const OBB& obb, f32 uscale) const -{ - Vec3 CamInOBBSpace = wpos - GetPosition(); - Vec3 iCamPos = -CamInOBBSpace * obb.m33; - uint32 front8 = 0; - AABB aabb = AABB((obb.c - obb.h) * uscale, (obb.c + obb.h) * uscale); - if (iCamPos.x < aabb.min.x) - { - front8 |= 0x008; - } - if (iCamPos.x > aabb.max.x) - { - front8 |= 0x010; - } - if (iCamPos.y < aabb.min.y) - { - front8 |= 0x020; - } - if (iCamPos.y > aabb.max.y) - { - front8 |= 0x040; - } - if (iCamPos.z < aabb.min.z) - { - front8 |= 0x080; - } - if (iCamPos.z > aabb.max.z) - { - front8 |= 0x100; - } - - if (front8 == 0) - { - return CULL_OVERLAP; - } - - //the transformed OBB-vertices in cam-space - Vec3 v[8] = { - obb.m33 * Vec3(aabb.min.x, aabb.min.y, aabb.min.z) + CamInOBBSpace, - obb.m33 * Vec3(aabb.max.x, aabb.min.y, aabb.min.z) + CamInOBBSpace, - obb.m33 * Vec3(aabb.min.x, aabb.max.y, aabb.min.z) + CamInOBBSpace, - obb.m33 * Vec3(aabb.max.x, aabb.max.y, aabb.min.z) + CamInOBBSpace, - obb.m33 * Vec3(aabb.min.x, aabb.min.y, aabb.max.z) + CamInOBBSpace, - obb.m33 * Vec3(aabb.max.x, aabb.min.y, aabb.max.z) + CamInOBBSpace, - obb.m33 * Vec3(aabb.min.x, aabb.max.y, aabb.max.z) + CamInOBBSpace, - obb.m33 * Vec3(aabb.max.x, aabb.max.y, aabb.max.z) + CamInOBBSpace - }; - - //--------------------------------------------------------------------- - //--- find the silhouette-vertices of the OBB --- - //--------------------------------------------------------------------- - uint32 p0 = BoxSides[front8 + 0]; - uint32 p1 = BoxSides[front8 + 1]; - uint32 p2 = BoxSides[front8 + 2]; - uint32 p3 = BoxSides[front8 + 3]; - uint32 p4 = BoxSides[front8 + 4]; - uint32 p5 = BoxSides[front8 + 5]; - uint32 sideamount = BoxSides[front8 + 7]; - - if (sideamount == 4) - { - //-------------------------------------------------------------------------- - //--- we take the 4 vertices of projection-plane in cam-space, --- - //----- and clip them against the 4 side-frustum-planes of the OBB - - //-------------------------------------------------------------------------- - Vec3 s0 = v[p0] % v[p1]; - if (((s0 | m_cltp) >= 0) && ((s0 | m_crtp) >= 0) && ((s0 | m_crbp) >= 0) && ((s0 | m_clbp) >= 0)) - { - return CULL_EXCLUSION; - } - Vec3 s1 = v[p1] % v[p2]; - if (((s1 | m_cltp) >= 0) && ((s1 | m_crtp) >= 0) && ((s1 | m_crbp) >= 0) && ((s1 | m_clbp) >= 0)) - { - return CULL_EXCLUSION; - } - Vec3 s2 = v[p2] % v[p3]; - if (((s2 | m_cltp) >= 0) && ((s2 | m_crtp) >= 0) && ((s2 | m_crbp) >= 0) && ((s2 | m_clbp) >= 0)) - { - return CULL_EXCLUSION; - } - Vec3 s3 = v[p3] % v[p0]; - if (((s3 | m_cltp) >= 0) && ((s3 | m_crtp) >= 0) && ((s3 | m_crbp) >= 0) && ((s3 | m_clbp) >= 0)) - { - return CULL_EXCLUSION; - } - } - - if (sideamount == 6) - { - //-------------------------------------------------------------------------- - //--- we take the 4 vertices of projection-plane in cam-space, --- - //--- and clip them against the 6 side-frustum-planes of the OBB --- - //-------------------------------------------------------------------------- - Vec3 s0 = v[p0] % v[p1]; - if (((s0 | m_cltp) >= 0) && ((s0 | m_crtp) >= 0) && ((s0 | m_crbp) >= 0) && ((s0 | m_clbp) >= 0)) - { - return CULL_EXCLUSION; - } - Vec3 s1 = v[p1] % v[p2]; - if (((s1 | m_cltp) >= 0) && ((s1 | m_crtp) >= 0) && ((s1 | m_crbp) >= 0) && ((s1 | m_clbp) >= 0)) - { - return CULL_EXCLUSION; - } - Vec3 s2 = v[p2] % v[p3]; - if (((s2 | m_cltp) >= 0) && ((s2 | m_crtp) >= 0) && ((s2 | m_crbp) >= 0) && ((s2 | m_clbp) >= 0)) - { - return CULL_EXCLUSION; - } - Vec3 s3 = v[p3] % v[p4]; - if (((s3 | m_cltp) >= 0) && ((s3 | m_crtp) >= 0) && ((s3 | m_crbp) >= 0) && ((s3 | m_clbp) >= 0)) - { - return CULL_EXCLUSION; - } - Vec3 s4 = v[p4] % v[p5]; - if (((s4 | m_cltp) >= 0) && ((s4 | m_crtp) >= 0) && ((s4 | m_crbp) >= 0) && ((s4 | m_clbp) >= 0)) - { - return CULL_EXCLUSION; - } - Vec3 s5 = v[p5] % v[p0]; - if (((s5 | m_cltp) >= 0) && ((s5 | m_crtp) >= 0) && ((s5 | m_crbp) >= 0) && ((s5 | m_clbp) >= 0)) - { - return CULL_EXCLUSION; - } - } - //now we are 100% sure that the OBB is visible on the screen - return CULL_OVERLAP; -} - -#endif // CRYINCLUDE_CRYCOMMON_CRY_CAMERA_H diff --git a/Code/CryEngine/CryCommon/Cry_Color.h b/Code/CryEngine/CryCommon/Cry_Color.h deleted file mode 100644 index 7a1a971450..0000000000 --- a/Code/CryEngine/CryCommon/Cry_Color.h +++ /dev/null @@ -1,1215 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : 4D Color template. - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_COLOR_H -#define CRYINCLUDE_CRYCOMMON_CRY_COLOR_H -#pragma once - -#include -#include -#include - -ILINE float FClamp(float X, float Min, float Max) -{ - return X < Min ? Min : X < Max ? X : Max; -} - -template -struct Color_tpl; - -typedef Color_tpl ColorB; // [ 0, 255] -typedef Color_tpl ColorF; // [0.0, 1.0] - -////////////////////////////////////////////////////////////////////////////////////////////// -// RGBA Color structure. -////////////////////////////////////////////////////////////////////////////////////////////// -template -struct Color_tpl -{ - T r, g, b, a; - - ILINE Color_tpl() {}; - - ILINE Color_tpl(T _x, T _y, T _z, T _w); - ILINE Color_tpl(T _x, T _y, T _z); - - /* inline Color_tpl(const Color_tpl & v) { - r = v.r; g = v.g; b = v.b; a = v.a; - }*/ - - // works together with pack_abgr8888 - ILINE Color_tpl(const unsigned int abgr); - ILINE Color_tpl(const f32 c); - ILINE Color_tpl(const ColorF& c); - ILINE Color_tpl(const ColorF& c, float fAlpha); - ILINE Color_tpl(const Vec3& c, float fAlpha); - ILINE Color_tpl(const Vec4& c); - - void Clamp(float Min = 0, float Max = 1.0f) - { - r = ::FClamp(r, Min, Max); - g = ::FClamp(g, Min, Max); - b = ::FClamp(b, Min, Max); - a = ::FClamp(a, Min, Max); - } - void ScaleCol (float f) - { - r = static_cast(r * f); - g = static_cast(g * f); - b = static_cast(b * f); - } - - float Luminance() const - { - return r * 0.30f + g * 0.59f + b * 0.11f; - } - - ILINE float Max() const - { - return max(r, max(b, g)); - } - - float NormalizeCol (ColorF& out) const - { - float max = Max(); - - if (max == 0) - { - return 0; - } - - out = *this / max; - - return max; - } - - ILINE Color_tpl(const Vec3& vVec) - { - r = (T)vVec.x; - g = (T)vVec.y; - b = (T)vVec.z; - a = (T)1.f; - } - - ILINE Color_tpl& operator = (const Vec3& v) { r = (T)v.x; g = (T)v.y; b = (T)v.z; a = (T)1.0f; return *this; } - ILINE Color_tpl& operator = (const Color_tpl& c) { r = (T)c.r; g = (T)c.g; b = (T)c.b; a = (T)c.a; return *this; } - - ILINE T& operator [] (int index) { assert(index >= 0 && index <= 3); return ((T*)this)[index]; } - ILINE T operator [] (int index) const { assert(index >= 0 && index <= 3); return ((T*)this)[index]; } - - ILINE void Set(float fR, float fG, float fB, float fA = 1.0f) - { - r = static_cast(fR); - g = static_cast(fG); - b = static_cast(fB); - a = static_cast(fA); - } - - ILINE void set(T _x, T _y = 0, T _z = 0, T _w = 0) - { - r = _x; - g = _y; - b = _z; - a = _w; - } - ILINE void set(T _x, T _y = 0, T _z = 0) - { - r = _x; - g = _y; - b = _z; - a = 1; - } - ILINE Color_tpl operator + () const - { - return *this; - } - ILINE Color_tpl operator - () const - { - return Color_tpl(-r, -g, -b, -a); - } - - ILINE Color_tpl& operator += (const Color_tpl& v) - { - T _r = r, _g = g, _b = b, _a = a; - _r += v.r; - _g += v.g; - _b += v.b; - _a += v.a; - r = _r; - g = _g; - b = _b; - a = _a; - return *this; - } - ILINE Color_tpl& operator -= (const Color_tpl& v) - { - r -= v.r; - g -= v.g; - b -= v.b; - a -= v.a; - return *this; - } - ILINE Color_tpl& operator *= (const Color_tpl& v) - { - r *= v.r; - g *= v.g; - b *= v.b; - a *= v.a; - return *this; - } - ILINE Color_tpl& operator /= (const Color_tpl& v) - { - r /= v.r; - g /= v.g; - b /= v.b; - a /= v.a; - return *this; - } - ILINE Color_tpl& operator *= (T s) - { - r *= s; - g *= s; - b *= s; - a *= s; - return *this; - } - ILINE Color_tpl& operator /= (T s) - { - s = 1.0f / s; - r *= s; - g *= s; - b *= s; - a *= s; - return *this; - } - - ILINE Color_tpl operator + (const Color_tpl& v) const - { - return Color_tpl(r + v.r, g + v.g, b + v.b, a + v.a); - } - ILINE Color_tpl operator - (const Color_tpl& v) const - { - return Color_tpl(r - v.r, g - v.g, b - v.b, a - v.a); - } - ILINE Color_tpl operator * (const Color_tpl& v) const - { - return Color_tpl(r * v.r, g * v.g, b * v.b, a * v.a); - } - ILINE Color_tpl operator / (const Color_tpl& v) const - { - return Color_tpl(r / v.r, g / v.g, b / v.b, a / v.a); - } - ILINE Color_tpl operator * (T s) const - { - return Color_tpl(r * s, g * s, b * s, a * s); - } - ILINE Color_tpl operator / (T s) const - { - s = 1.0f / s; - return Color_tpl(r * s, g * s, b * s, a * s); - } - - ILINE bool operator == (const Color_tpl& v) const - { - return (r == v.r) && (g == v.g) && (b == v.b) && (a == v.a); - } - ILINE bool operator != (const Color_tpl& v) const - { - return (r != v.r) || (g != v.g) || (b != v.b) || (a != v.a); - } - - ILINE unsigned char pack_rgb332() const; - ILINE unsigned short pack_argb4444() const; - ILINE unsigned short pack_rgb555() const; - ILINE unsigned short pack_rgb565() const; - ILINE unsigned int pack_bgr888() const; - ILINE unsigned int pack_rgb888() const; - ILINE unsigned int pack_abgr8888() const; - ILINE unsigned int pack_argb8888() const; - inline Vec4 toVec4() const { return Vec4(r, g, b, a); } - inline Vec3 toVec3() const { return Vec3(r, g, b); } - inline void toFloat4(f32* out) const; - - inline void toHSV(f32& h, f32& s, f32& v) const; - inline void fromHSV(f32 h, f32 s, f32 v); - - inline void clamp(T bottom = 0.0f, T top = 1.0f); - - inline void maximum(const Color_tpl& ca, const Color_tpl& cb); - inline void minimum(const Color_tpl& ca, const Color_tpl& cb); - inline void abs(); - - inline void adjust_contrast(T c); - inline void adjust_saturation(T s); - inline void adjust_luminance(float newLum); - - inline void lerpFloat(const Color_tpl& ca, const Color_tpl& cb, float s); - inline void negative(const Color_tpl& c); - inline void grey(const Color_tpl& c); - - // helper function - maybe we can improve the integration - static inline uint32 ComputeAvgCol_Fast(const uint32 dwCol0, const uint32 dwCol1) - { - uint32 dwHalfCol0 = (dwCol0 / 2) & 0x7f7f7f7f; // each component /2 - uint32 dwHalfCol1 = (dwCol1 / 2) & 0x7f7f7f7f; // each component /2 - - return dwHalfCol0 + dwHalfCol1; - } - - // mCIE: adjusted to compensate problems of DXT compression (extra bit in green channel causes green/purple artifacts) - // explained in CryEngine wiki: ColorSpaces - Color_tpl RGB2mCIE() const - { - Color_tpl in = *this; - - // to get grey chrominance for dark colors - in.r += 0.000001f; - in.g += 0.000001f; - in.b += 0.000001f; - - float RGBSum = in.r + in.g + in.b; - - float fInv = 1.0f / RGBSum; - - float RNorm = 3 * 10.0f / 31.0f * in.r * fInv; - float GNorm = 3 * 21.0f / 63.0f * in.g * fInv; - float Scale = RGBSum / 3.0f; - - // test grey - // out.r = 10.0f/31.0f; // 1/3 = 10/30 Red range 0..30, 31 unused - // out.g = 21.0f/63.0f; // 1/3 = 21/63 Green range 0..63 - - RNorm = max(0.0f, min(1.0f, RNorm)); - GNorm = max(0.0f, min(1.0f, GNorm)); - - return Color_tpl(RNorm, GNorm, Scale); - } - - // mCIE: adjusted to compensate problems of DXT compression (extra bit in green channel causes green/purple artefacts) - // explained in CryEngine wiki: ColorSpaces - Color_tpl mCIE2RGB() const - { - Color_tpl out = *this; - - float fScale = out.b; // Blue range 0..31 - - // test grey - // out.r = 10.0f/31.0f; // 1/3 = 10/30 Red range 0..30, 31 unused - // out.g = 21.0f/63.0f; // 1/3 = 21/63 Green range 0..63 - - out.r *= 31.0f / 30.0f; // - out.g *= 63.0f / 63.0f; // - out.b = 0.999f - out.r - out.g; - - float s = 3.0f * fScale; - - out.r *= s; - out.g *= s; - out.b *= s; - - out.Clamp(); - - return out; - } - - void rgb2srgb() - { - for (int i = 0; i < 3; i++) - { - T& c = (*this)[i]; - - if (c < 0.0031308f) - { - c = 12.92f * c; - } - else - { - c = 1.055f * pow(c, 1.0f / 2.4f) - 0.055f; - } - } - } - - void srgb2rgb() - { - for (int i = 0; i < 3; i++) - { - T& c = (*this)[i]; - - if (c <= 0.040448643f) - { - c = c / 12.92f; - } - else - { - c = pow((c + 0.055f) / 1.055f, 2.4f); - } - } - } - - void GetMemoryUsage([[maybe_unused]] class ICrySizer* pSizer) const { /*nothing*/} - - AZStd::array GetAsArray() const - { - AZStd::array primitiveArray = { { r, g, b, a } }; - return primitiveArray; - } - - AUTO_STRUCT_INFO -}; - - -////////////////////////////////////////////////////////////////////////////////////////////// -// template specialization -/////////////////////////////////////////////// - -template<> -ILINE Color_tpl::Color_tpl(f32 _x, f32 _y, f32 _z, f32 _w) -{ - r = _x; - g = _y; - b = _z; - a = _w; -} - -template<> -ILINE Color_tpl::Color_tpl(f32 _x, f32 _y, f32 _z) -{ - r = _x; - g = _y; - b = _z; - a = 1.f; -} - -template<> -ILINE Color_tpl::Color_tpl(uint8 _x, uint8 _y, uint8 _z, uint8 _w) -{ - r = _x; - g = _y; - b = _z; - a = _w; -} - -template<> -ILINE Color_tpl::Color_tpl(uint8 _x, uint8 _y, uint8 _z) -{ - r = _x; - g = _y; - b = _z; - a = 255; -} - -//----------------------------------------------------------------------------- - -template<> -ILINE Color_tpl::Color_tpl(const unsigned int abgr) -{ - r = (abgr & 0xff) / 255.0f; - g = ((abgr >> 8) & 0xff) / 255.0f; - b = ((abgr >> 16) & 0xff) / 255.0f; - a = ((abgr >> 24) & 0xff) / 255.0f; -} - -template<> -ILINE Color_tpl::Color_tpl(const unsigned int c) -{ - *(unsigned int*)(&r) = c; -} //use this with RGBA8 macro! - -//----------------------------------------------------------------------------- - -template<> -ILINE Color_tpl::Color_tpl(const float c) -{ - r = c; - g = c; - b = c; - a = c; -} -template<> -ILINE Color_tpl::Color_tpl(const float c) -{ - r = (uint8)(c * 255); - g = (uint8)(c * 255); - b = (uint8)(c * 255); - a = (uint8)(c * 255); -} -//----------------------------------------------------------------------------- - -template<> -ILINE Color_tpl::Color_tpl(const ColorF& c) -{ - r = c.r; - g = c.g; - b = c.b; - a = c.a; -} -template<> -ILINE Color_tpl::Color_tpl(const ColorF& c) -{ - r = (uint8)(c.r * 255); - g = (uint8)(c.g * 255); - b = (uint8)(c.b * 255); - a = (uint8)(c.a * 255); -} - -template<> -ILINE Color_tpl::Color_tpl(const ColorF& c, float fAlpha) -{ - r = c.r; - g = c.g; - b = c.b; - a = fAlpha; -} - -template<> -ILINE Color_tpl::Color_tpl(const Vec3& c, float fAlpha) -{ - r = c.x; - g = c.y; - b = c.z; - a = fAlpha; -} - -template<> -ILINE Color_tpl::Color_tpl(const Vec4& c) -{ - r = c.x; - g = c.y; - b = c.z; - a = c.w; -} - -template<> -ILINE Color_tpl::Color_tpl(const ColorF& c, float fAlpha) -{ - r = (uint8)(c.r * 255); - g = (uint8)(c.g * 255); - b = (uint8)(c.b * 255); - a = (uint8)(fAlpha * 255); -} -template<> -ILINE Color_tpl::Color_tpl(const Vec3& c, float fAlpha) -{ - r = (uint8)(c.x * 255); - g = (uint8)(c.y * 255); - b = (uint8)(c.z * 255); - a = (uint8)(fAlpha * 255); -} - -template<> -ILINE Color_tpl::Color_tpl(const Vec4& c) -{ - r = (uint8)(c.x * 255); - g = (uint8)(c.y * 255); - b = (uint8)(c.z * 255); - a = (uint8)(c.w * 255); -} - -template<> -inline void Color_tpl::toFloat4(f32* out) const -{ - out[0] = r / 255.0f; - out[1] = g / 255.0f; - out[2] = b / 255.0f; - out[3] = a / 255.0f; -} - -template<> -inline void Color_tpl::toFloat4(f32* out) const -{ - out[0] = r; - out[1] = g; - out[2] = b; - out[3] = a; -} - -////////////////////////////////////////////////////////////////////////////////////////////// -// functions implementation -/////////////////////////////////////////////// - -/////////////////////////////////////////////// -/*template -inline Color_tpl::Color_tpl(const T *p_elts) -{ -r = p_elts[0]; g = p_elts[1]; b = p_elts[2]; a = p_elts[3]; -}*/ - -/////////////////////////////////////////////// -/////////////////////////////////////////////// -template -ILINE Color_tpl operator * (T s, const Color_tpl& v) -{ - return Color_tpl(v.r * s, v.g * s, v.b * s, v.a * s); -} - -/////////////////////////////////////////////// -template -ILINE unsigned char Color_tpl::pack_rgb332() const -{ - unsigned char cr; - unsigned char cg; - unsigned char cb; - if constexpr (sizeof(r) == 1) // char and unsigned char - { - cr = (unsigned char)r; - cg = (unsigned char)g; - cb = (unsigned char)b; - } - else if constexpr (sizeof(r) == 2) // short and unsigned short - { - cr = (unsigned short)(r) >> 8; - cg = (unsigned short)(g) >> 8; - cb = (unsigned short)(b) >> 8; - } - else // float or double - { - cr = (unsigned char)(r * 255.0f); - cg = (unsigned char)(g * 255.0f); - cb = (unsigned char)(b * 255.0f); - } - return ((cr >> 5) << 5) | ((cg >> 5) << 2) | (cb >> 5); -} - -/////////////////////////////////////////////// -template -ILINE unsigned short Color_tpl::pack_argb4444() const -{ - unsigned char cr; - unsigned char cg; - unsigned char cb; - unsigned char ca; - if constexpr (sizeof(r) == 1) // char and unsigned char - { - cr = (unsigned char)r; - cg = (unsigned char)g; - cb = (unsigned char)b; - ca = (unsigned char)a; - } - else if constexpr (sizeof(r) == 2) // short and unsigned short - { - cr = (unsigned short)(r) >> 8; - cg = (unsigned short)(g) >> 8; - cb = (unsigned short)(b) >> 8; - ca = (unsigned short)(a) >> 8; - } - else // float or double - { - cr = (unsigned char)(r * 255.0f); - cg = (unsigned char)(g * 255.0f); - cb = (unsigned char)(b * 255.0f); - ca = (unsigned char)(a * 255.0f); - } - return ((ca >> 4) << 12) | ((cr >> 4) << 8) | ((cg >> 4) << 4) | (cb >> 4); -} - -/////////////////////////////////////////////// -template -ILINE unsigned short Color_tpl::pack_rgb555() const -{ - unsigned char cr; - unsigned char cg; - unsigned char cb; - if constexpr (sizeof(r) == 1) // char and unsigned char - { - cr = (unsigned char)r; - cg = (unsigned char)g; - cb = (unsigned char)b; - } - else if constexpr (sizeof(r) == 2) // short and unsigned short - { - cr = (unsigned short)(r) >> 8; - cg = (unsigned short)(g) >> 8; - cb = (unsigned short)(b) >> 8; - } - else // float or double - { - cr = (unsigned char)(r * 255.0f); - cg = (unsigned char)(g * 255.0f); - cb = (unsigned char)(b * 255.0f); - } - return ((cr >> 3) << 10) | ((cg >> 3) << 5) | (cb >> 3); -} - -/////////////////////////////////////////////// -template -ILINE unsigned short Color_tpl::pack_rgb565() const -{ - unsigned short cr; - unsigned short cg; - unsigned short cb; - if constexpr (sizeof(r) == 1) // char and unsigned char - { - cr = (unsigned short)r; - cg = (unsigned short)g; - cb = (unsigned short)b; - } - else if constexpr (sizeof(r) == 2) // short and unsigned short - { - cr = (unsigned short)(r) >> 8; - cg = (unsigned short)(g) >> 8; - cb = (unsigned short)(b) >> 8; - } - else // float or double - { - cr = (unsigned short)(r * 255.0f); - cg = (unsigned short)(g * 255.0f); - cb = (unsigned short)(b * 255.0f); - } - return ((cr >> 3) << 11) | ((cg >> 2) << 5) | (cb >> 3); -} - -/////////////////////////////////////////////// -template -ILINE unsigned int Color_tpl::pack_bgr888() const -{ - unsigned char cr; - unsigned char cg; - unsigned char cb; - if constexpr (sizeof(r) == 1) // char and unsigned char - { - cr = (unsigned char)r; - cg = (unsigned char)g; - cb = (unsigned char)b; - } - else if constexpr (sizeof(r) == 2) // short and unsigned short - { - cr = (unsigned short)(r) >> 8; - cg = (unsigned short)(g) >> 8; - cb = (unsigned short)(b) >> 8; - } - else // float or double - { - cr = (unsigned char)(r * 255.0f); - cg = (unsigned char)(g * 255.0f); - cb = (unsigned char)(b * 255.0f); - } - return (cb << 16) | (cg << 8) | cr; -} - -/////////////////////////////////////////////// -template -ILINE unsigned int Color_tpl::pack_rgb888() const -{ - unsigned char cr; - unsigned char cg; - unsigned char cb; - if constexpr (sizeof(r) == 1) // char and unsigned char - { - cr = (unsigned char)r; - cg = (unsigned char)g; - cb = (unsigned char)b; - } - else if constexpr (sizeof(r) == 2) // short and unsigned short - { - cr = (unsigned short)(r) >> 8; - cg = (unsigned short)(g) >> 8; - cb = (unsigned short)(b) >> 8; - } - else // float or double - { - cr = (unsigned char)(r * 255.0f); - cg = (unsigned char)(g * 255.0f); - cb = (unsigned char)(b * 255.0f); - } - return (cr << 16) | (cg << 8) | cb; -} - -/////////////////////////////////////////////// -template -ILINE unsigned int Color_tpl::pack_abgr8888() const -{ - unsigned char cr; - unsigned char cg; - unsigned char cb; - unsigned char ca; - if constexpr (sizeof(r) == 1) // char and unsigned char - { - cr = (unsigned char)r; - cg = (unsigned char)g; - cb = (unsigned char)b; - ca = (unsigned char)a; - } - else if constexpr (sizeof(r) == 2) // short and unsigned short - { - cr = (unsigned short)(r) >> 8; - cg = (unsigned short)(g) >> 8; - cb = (unsigned short)(b) >> 8; - ca = (unsigned short)(a) >> 8; - } - else // float or double - { - cr = (unsigned char)(r * 255.0f); - cg = (unsigned char)(g * 255.0f); - cb = (unsigned char)(b * 255.0f); - ca = (unsigned char)(a * 255.0f); - } - return (ca << 24) | (cb << 16) | (cg << 8) | cr; -} - - -/////////////////////////////////////////////// -template -ILINE unsigned int Color_tpl::pack_argb8888() const -{ - unsigned char cr; - unsigned char cg; - unsigned char cb; - unsigned char ca; - if constexpr (sizeof(r) == 1) // char and unsigned char - { - cr = (unsigned char)r; - cg = (unsigned char)g; - cb = (unsigned char)b; - ca = (unsigned char)a; - } - else if constexpr (sizeof(r) == 2) // short and unsigned short - { - cr = (unsigned short)(r) >> 8; - cg = (unsigned short)(g) >> 8; - cb = (unsigned short)(b) >> 8; - ca = (unsigned short)(a) >> 8; - } - else // float or double - { - cr = (unsigned char)(r * 255.0f); - cg = (unsigned char)(g * 255.0f); - cb = (unsigned char)(b * 255.0f); - ca = (unsigned char)(a * 255.0f); - } - return (ca << 24) | (cr << 16) | (cg << 8) | cb; -} - -/////////////////////////////////////////////// -template -inline void Color_tpl::toHSV(f32& h, f32& s, f32& v) const -{ - f32 red, green, blue; - if constexpr (sizeof(this->r) == 1) // 8bit integer - { - red = this->r * (1.0f / f32(0xff)); - green = this->g * (1.0f / f32(0xff)); - blue = this->b * (1.0f / f32(0xff)); - } - else if constexpr (sizeof(this->r) == 2) // 16bit integer - { - red = this->r * (1.0f / f32(0xffff)); - green = this->g * (1.0f / f32(0xffff)); - blue = this->b * (1.0f / f32(0xffff)); - } - else // floating point - { - red = this->r; - green = this->g; - blue = this->b; - } - - if ((blue > green) && (blue > red)) - { - if (!::iszero(v = blue)) - { - const f32 min = red < green ? red : green; - const f32 delta = v - min; - if (!::iszero(delta)) - { - s = delta / v; - h = (240.0f / 360.0f) + (red - green) / delta * (60.0f / 360.0f); - } - else - { - s = 0.0f; - h = (240.0f / 360.0f) + (red - green) * (60.0f / 360.0f); - } - if (h < 0.0f) - { - h += 1.0f; - } - } - else - { - s = 0.0f; - h = 0.0f; - } - } - else if (green > red) - { - if (!::iszero(v = green)) - { - const f32 min = red < blue ? red : blue; - const f32 delta = v - min; - if (!::iszero(delta)) - { - s = delta / v; - h = (120.0f / 360.0f) + (blue - red) / delta * (60.0f / 360.0f); - } - else - { - s = 0.0f; - h = (120.0f / 360.0f) + (blue - red) * (60.0f / 360.0f); - } - if (h < 0.0f) - { - h += 1.0f; - } - } - else - { - s = 0.0f; - h = 0.0f; - } - } - else - { - if (!::iszero(v = red)) - { - const f32 min = green < blue ? green : blue; - const f32 delta = v - min; - if (!::iszero(delta)) - { - s = delta / v; - h = (green - blue) / delta * (60.0f / 360.0f); - } - else - { - s = 0.0f; - h = (green - blue) * (60.0f / 360.0f); - } - if (h < 0.0f) - { - h += 1.0f; - } - } - else - { - s = 0.0f; - h = 0.0f; - } - } -} - -/////////////////////////////////////////////// -template -inline void Color_tpl::fromHSV(f32 h, f32 s, f32 v) -{ - f32 red, green, blue; - if (::iszero(v)) - { - red = 0.0f; - green = 0.0f; - blue = 0.0f; - } - else if (::iszero(s)) - { - red = v; - green = v; - blue = v; - } - else - { - const f32 hi = h * 6.0f; - const int32 i = (int32)::floor(hi); - const f32 f = hi - i; - - const f32 v0 = v * (1.0f - s); - const f32 v1 = v * (1.0f - s * f); - const f32 v2 = v * (1.0f - s * (1.0f - f)); - - switch (i) - { - case 0: - red = v; - green = v2; - blue = v0; - break; - case 1: - red = v1; - green = v; - blue = v0; - break; - case 2: - red = v0; - green = v; - blue = v2; - break; - case 3: - red = v0; - green = v1; - blue = v; - break; - case 4: - red = v2; - green = v0; - blue = v; - break; - case 5: - red = v; - green = v0; - blue = v1; - break; - - case 6: - red = v; - green = v2; - blue = v0; - break; - case -1: - red = v; - green = v0; - blue = v1; - break; - default: - red = 0.0f; - green = 0.0f; - blue = 0.0f; - break; - } - } - - if constexpr (sizeof(this->r) == 1) // 8bit integer - { - this->r = red * f32(0xff); - this->g = green * f32(0xff); - this->b = blue * f32(0xff); - } - else if constexpr (sizeof(this->r) == 2) // 16bit integer - { - this->r = red * f32(0xffff); - this->g = green * f32(0xffff); - this->b = blue * f32(0xffff); - } - else // floating point - { - this->r = red; - this->g = green; - this->b = blue; - } -} - -/////////////////////////////////////////////// -template -inline void Color_tpl::clamp(T bottom, T top) -{ - r = min(top, max(bottom, r)); - g = min(top, max(bottom, g)); - b = min(top, max(bottom, b)); - a = min(top, max(bottom, a)); -} - -/////////////////////////////////////////////// -template -inline void Color_tpl::maximum(const Color_tpl& ca, const Color_tpl& cb) -{ - r = max(ca.r, cb.r); - g = max(ca.g, cb.g); - b = max(ca.b, cb.b); - a = max(ca.a, cb.a); -} - -/////////////////////////////////////////////// -template -inline void Color_tpl::minimum(const Color_tpl& ca, const Color_tpl& cb) -{ - r = min(ca.r, cb.r); - g = min(ca.g, cb.g); - b = min(ca.b, cb.b); - a = min(ca.a, cb.a); -} - -/////////////////////////////////////////////// -template -inline void Color_tpl::abs() -{ - r = fabs_tpl(r); - g = fabs_tpl(g); - b = fabs_tpl(b); - a = fabs_tpl(a); -} - -/////////////////////////////////////////////// -template -inline void Color_tpl::adjust_contrast(T c) -{ - r = 0.5f + c * (r - 0.5f); - g = 0.5f + c * (g - 0.5f); - b = 0.5f + c * (b - 0.5f); - a = 0.5f + c * (a - 0.5f); -} - -/////////////////////////////////////////////// -template -inline void Color_tpl::adjust_saturation(T s) -{ - // Approximate values for each component's contribution to luminance. - // Based upon the NTSC standard described in ITU-R Recommendation BT.709. - T grey = r * 0.2125f + g * 0.7154f + b * 0.0721f; - r = grey + s * (r - grey); - g = grey + s * (g - grey); - b = grey + s * (b - grey); - a = grey + s * (a - grey); -} - -/////////////////////////////////////////////// -template -inline void Color_tpl::adjust_luminance(float newLum) -{ - // Optimized yet equivalent version of replacing luminance in XYZ space. - // Color and luminance are expected to be linear. - - Color_tpl colF(r, g, b, a); - - float lum = colF.r * 0.212671f + colF.g * 0.715160f + colF.b * 0.072169f; - if (iszero(lum)) - { - return; - } - - *this = Color_tpl(colF * newLum / lum); -} - -/////////////////////////////////////////////// -template -inline void Color_tpl::lerpFloat(const Color_tpl& ca, const Color_tpl& cb, float s) -{ - r = (T)(ca.r + s * (cb.r - ca.r)); - g = (T)(ca.g + s * (cb.g - ca.g)); - b = (T)(ca.b + s * (cb.b - ca.b)); - a = (T)(ca.a + s * (cb.a - ca.a)); -} - -/////////////////////////////////////////////// -template -inline void Color_tpl::negative([[maybe_unused]] const Color_tpl& c) -{ - r = T(1.0f) - r; - g = T(1.0f) - g; - b = T(1.0f) - b; - a = T(1.0f) - a; -} - -/////////////////////////////////////////////// -template -inline void Color_tpl::grey([[maybe_unused]] const Color_tpl& c) -{ - T m = (r + g + b) / T(3); - - r = m; - g = m; - b = m; -} - -////////////////////////////////////////////////////////////////////////////////////////////// -//#define RGBA8(r,g,b,a) (ColorB((uint8)(r),(uint8)(g),(uint8)(b),(uint8)(a))) -#if defined(NEED_ENDIAN_SWAP) - #define RGBA8(a, b, g, r) ((uint32)(((uint8)(r) | ((uint16)((uint8)(g)) << 8)) | (((uint32)(uint8)(b)) << 16)) | (((uint32)(uint8)(a)) << 24)) -#else - #define RGBA8(r, g, b, a) ((uint32)(((uint8)(r) | ((uint16)((uint8)(g)) << 8)) | (((uint32)(uint8)(b)) << 16)) | (((uint32)(uint8)(a)) << 24)) -#endif -#define Col_Black ColorF (0.000f, 0.000f, 0.000f) // 0xFF000000 RGB: 0, 0, 0 -#define Col_White ColorF (1.000f, 1.000f, 1.000f) // 0xFFFFFFFF RGB: 255, 255, 255 -#define Col_Aquamarine ColorF (0.498f, 1.000f, 0.831f) // 0xFF7FFFD4 RGB: 127, 255, 212 -#define Col_Azure ColorF (0.000f, 0.498f, 1.000f) // 0xFF007FFF RGB: 0, 127, 255 -#define Col_Blue ColorF (0.000f, 0.000f, 1.000f) // 0xFF0000FF RGB: 0, 0, 255 -#define Col_BlueViolet ColorF (0.541f, 0.169f, 0.886f) // 0xFF8A2BE2 RGB: 138, 43, 226 -#define Col_Brown ColorF (0.647f, 0.165f, 0.165f) // 0xFFA52A2A RGB: 165, 42, 42 -#define Col_CadetBlue ColorF (0.373f, 0.620f, 0.627f) // 0xFF5F9EA0 RGB: 95, 158, 160 -#define Col_Coral ColorF (1.000f, 0.498f, 0.314f) // 0xFFFF7F50 RGB: 255, 127, 80 -#define Col_CornflowerBlue ColorF (0.392f, 0.584f, 0.929f) // 0xFF6495ED RGB: 100, 149, 237 -#define Col_Cyan ColorF (0.000f, 1.000f, 1.000f) // 0xFF00FFFF RGB: 0, 255, 255 -#define Col_DarkGray ColorF (0.663f, 0.663f, 0.663f) // 0xFFA9A9A9 RGB: 169, 169, 169 -#define Col_DarkGrey ColorF (0.663f, 0.663f, 0.663f) // 0xFFA9A9A9 RGB: 169, 169, 169 -#define Col_DarkGreen ColorF (0.000f, 0.392f, 0.000f) // 0xFF006400 RGB: 0, 100, 0 -#define Col_DarkOliveGreen ColorF (0.333f, 0.420f, 0.184f) // 0xFF556B2F RGB: 85, 107, 47 -#define Col_DarkOrchid ColorF (0.600f, 0.196f, 0.800f) // 0xFF9932CC RGB: 153, 50, 204 -#define Col_DarkSlateBlue ColorF (0.282f, 0.239f, 0.545f) // 0xFF483D8B RGB: 72, 61, 139 -#define Col_DarkSlateGray ColorF (0.184f, 0.310f, 0.310f) // 0xFF2F4F4F RGB: 47, 79, 79 -#define Col_DarkSlateGrey ColorF (0.184f, 0.310f, 0.310f) // 0xFF2F4F4F RGB: 47, 79, 79 -#define Col_DarkTurquoise ColorF (0.000f, 0.808f, 0.820f) // 0xFF00CED1 RGB: 0, 206, 209 -#define Col_DarkWood ColorF (0.050f, 0.010f, 0.005f) // 0xFF0D0301 RGB: 13, 3, 1 -#define Col_DeepPink ColorF (1.000f, 0.078f, 0.576f) // 0xFFFF1493 RGB: 255, 20, 147 -#define Col_DimGray ColorF (0.412f, 0.412f, 0.412f) // 0xFF696969 RGB: 105, 105, 105 -#define Col_DimGrey ColorF (0.412f, 0.412f, 0.412f) // 0xFF696969 RGB: 105, 105, 105 -#define Col_FireBrick ColorF (0.698f, 0.133f, 0.133f) // 0xFFB22222 RGB: 178, 34, 34 -#define Col_ForestGreen ColorF (0.133f, 0.545f, 0.133f) // 0xFF228B22 RGB: 34, 139, 34 -#define Col_Gold ColorF (1.000f, 0.843f, 0.000f) // 0xFFFFD700 RGB: 255, 215, 0 -#define Col_Goldenrod ColorF (0.855f, 0.647f, 0.125f) // 0xFFDAA520 RGB: 218, 165, 32 -#define Col_Gray ColorF (0.502f, 0.502f, 0.502f) // 0xFF808080 RGB: 128, 128, 128 -#define Col_Grey ColorF (0.502f, 0.502f, 0.502f) // 0xFF808080 RGB: 128, 128, 128 -#define Col_Green ColorF (0.000f, 0.502f, 0.000f) // 0xFF008000 RGB: 0, 128, 0 -#define Col_GreenYellow ColorF (0.678f, 1.000f, 0.184f) // 0xFFADFF2F RGB: 173, 255, 47 -#define Col_IndianRed ColorF (0.804f, 0.361f, 0.361f) // 0xFFCD5C5C RGB: 205, 92, 92 -#define Col_Khaki ColorF (0.941f, 0.902f, 0.549f) // 0xFFF0E68C RGB: 240, 230, 140 -#define Col_LightBlue ColorF (0.678f, 0.847f, 0.902f) // 0xFFADD8E6 RGB: 173, 216, 230 -#define Col_LightGray ColorF (0.827f, 0.827f, 0.827f) // 0xFFD3D3D3 RGB: 211, 211, 211 -#define Col_LightGrey ColorF (0.827f, 0.827f, 0.827f) // 0xFFD3D3D3 RGB: 211, 211, 211 -#define Col_LightSteelBlue ColorF (0.690f, 0.769f, 0.871f) // 0xFFB0C4DE RGB: 176, 196, 222 -#define Col_LightWood ColorF (0.600f, 0.240f, 0.100f) // 0xFF993D1A RGB: 153, 61, 26 -#define Col_Lime ColorF (0.000f, 1.000f, 0.000f) // 0xFF00FF00 RGB: 0, 255, 0 -#define Col_LimeGreen ColorF (0.196f, 0.804f, 0.196f) // 0xFF32CD32 RGB: 50, 205, 50 -#define Col_Magenta ColorF (1.000f, 0.000f, 1.000f) // 0xFFFF00FF RGB: 255, 0, 255 -#define Col_Maroon ColorF (0.502f, 0.000f, 0.000f) // 0xFF800000 RGB: 128, 0, 0 -#define Col_MedianWood ColorF (0.300f, 0.120f, 0.030f) // 0xFF4D1F09 RGB: 77, 31, 9 -#define Col_MediumAquamarine ColorF (0.400f, 0.804f, 0.667f) // 0xFF66CDAA RGB: 102, 205, 170 -#define Col_MediumBlue ColorF (0.000f, 0.000f, 0.804f) // 0xFF0000CD RGB: 0, 0, 205 -#define Col_MediumForestGreen ColorF (0.420f, 0.557f, 0.137f) // 0xFF6B8E23 RGB: 107, 142, 35 -#define Col_MediumGoldenrod ColorF (0.918f, 0.918f, 0.678f) // 0xFFEAEAAD RGB: 234, 234, 173 -#define Col_MediumOrchid ColorF (0.729f, 0.333f, 0.827f) // 0xFFBA55D3 RGB: 186, 85, 211 -#define Col_MediumSeaGreen ColorF (0.235f, 0.702f, 0.443f) // 0xFF3CB371 RGB: 60, 179, 113 -#define Col_MediumSlateBlue ColorF (0.482f, 0.408f, 0.933f) // 0xFF7B68EE RGB: 123, 104, 238 -#define Col_MediumSpringGreen ColorF (0.000f, 0.980f, 0.604f) // 0xFF00FA9A RGB: 0, 250, 154 -#define Col_MediumTurquoise ColorF (0.282f, 0.820f, 0.800f) // 0xFF48D1CC RGB: 72, 209, 204 -#define Col_MediumVioletRed ColorF (0.780f, 0.082f, 0.522f) // 0xFFC71585 RGB: 199, 21, 133 -#define Col_MidnightBlue ColorF (0.098f, 0.098f, 0.439f) // 0xFF191970 RGB: 25, 25, 112 -#define Col_Navy ColorF (0.000f, 0.000f, 0.502f) // 0xFF000080 RGB: 0, 0, 128 -#define Col_NavyBlue ColorF (0.137f, 0.137f, 0.557f) // 0xFF23238E RGB: 35, 35, 142 -#define Col_Orange ColorF (1.000f, 0.647f, 0.000f) // 0xFFFFA500 RGB: 255, 165, 0 -#define Col_OrangeRed ColorF (1.000f, 0.271f, 0.000f) // 0xFFFF4500 RGB: 255, 69, 0 -#define Col_Orchid ColorF (0.855f, 0.439f, 0.839f) // 0xFFDA70D6 RGB: 218, 112, 214 -#define Col_PaleGreen ColorF (0.596f, 0.984f, 0.596f) // 0xFF98FB98 RGB: 152, 251, 152 -#define Col_Pink ColorF (1.000f, 0.753f, 0.796f) // 0xFFFFC0CB RGB: 255, 192, 203 -#define Col_Plum ColorF (0.867f, 0.627f, 0.867f) // 0xFFDDA0DD RGB: 221, 160, 221 -#define Col_Red ColorF (1.000f, 0.000f, 0.000f) // 0xFFFF0000 RGB: 255, 0, 0 -#define Col_Salmon ColorF (0.980f, 0.502f, 0.447f) // 0xFFFA8072 RGB: 250, 128, 114 -#define Col_SeaGreen ColorF (0.180f, 0.545f, 0.341f) // 0xFF2E8B57 RGB: 46, 139, 87 -#define Col_Sienna ColorF (0.627f, 0.322f, 0.176f) // 0xFFA0522D RGB: 160, 82, 45 -#define Col_SkyBlue ColorF (0.529f, 0.808f, 0.922f) // 0xFF87CEEB RGB: 135, 206, 235 -#define Col_SlateBlue ColorF (0.416f, 0.353f, 0.804f) // 0xFF6A5ACD RGB: 106, 90, 205 -#define Col_SpringGreen ColorF (0.000f, 1.000f, 0.498f) // 0xFF00FF7F RGB: 0, 255, 127 -#define Col_SteelBlue ColorF (0.275f, 0.510f, 0.706f) // 0xFF4682B4 RGB: 70, 130, 180 -#define Col_Tan ColorF (0.824f, 0.706f, 0.549f) // 0xFFD2B48C RGB: 210, 180, 140 -#define Col_Thistle ColorF (0.847f, 0.749f, 0.847f) // 0xFFD8BFD8 RGB: 216, 191, 216 -#define Col_Transparent ColorF (0.0f, 0.0f, 0.0f, 0.0f) // 0x00000000 RGB: 0, 0, 0 -#define Col_Turquoise ColorF (0.251f, 0.878f, 0.816f) // 0xFF40E0D0 RGB: 64, 224, 208 -#define Col_Violet ColorF (0.933f, 0.510f, 0.933f) // 0xFFEE82EE RGB: 238, 130, 238 -#define Col_VioletRed ColorF (0.800f, 0.196f, 0.600f) // 0xFFCC3299 RGB: 204, 50, 153 -#define Col_Wheat ColorF (0.961f, 0.871f, 0.702f) // 0xFFF5DEB3 RGB: 245, 222, 179 -#define Col_Yellow ColorF (1.000f, 1.000f, 0.000f) // 0xFFFFFF00 RGB: 255, 255, 0 -#define Col_YellowGreen ColorF (0.604f, 0.804f, 0.196f) // 0xFF9ACD32 RGB: 154, 205, 50 -#define Col_TrackviewDefault ColorF (0.187820792f, 0.187820792f, 1.0f) - -#define Clr_Empty ColorF(0.0f, 0.0f, 0.0f, 1.0f) -#define Clr_Dark ColorF(0.15f, 0.15f, 0.15f, 1.0f) -#define Clr_White ColorF(1.0f, 1.0f, 1.0f, 1.0f) -#define Clr_WhiteTrans ColorF(1.0f, 1.0f, 1.0f, 0.0f) -#define Clr_Full ColorF(1.0f, 1.0f, 1.0f, 1.0f) -#define Clr_Neutral ColorF(1.0f, 1.0f, 1.0f, 1.0f) -#define Clr_Transparent ColorF(0.0f, 0.0f, 0.0f, 0.0f) -#define Clr_FrontVector ColorF(0.0f, 0.0f, 0.5f, 1.0f) -#define Clr_Static ColorF(127.0f / 255.0f, 127.0f / 255.0f, 0.0f, 0.0f) -#define Clr_Median ColorF(0.5f, 0.5f, 0.5f, 0.0f) -#define Clr_MedianHalf ColorF(0.5f, 0.5f, 0.5f, 0.5f) -#define Clr_FarPlane ColorF(1.0f, 0.0f, 0.0f, 0.0f) -#define Clr_FarPlane_R ColorF(bReverseDepth ? 0.0f : 1.0f, 0.0f, 0.0f, 0.0f) -#define Clr_Unknown ColorF(0.0f, 0.0f, 0.0f, 0.0f) -#define Clr_Unused ColorF(0.0f, 0.0f, 0.0f, 0.0f) -#define Clr_Debug ColorF(1.0f, 0.0f, 0.0f, 1.0f) - -#endif // CRYINCLUDE_CRYCOMMON_CRY_COLOR_H - - diff --git a/Code/CryEngine/CryCommon/Cry_Geo.h b/Code/CryEngine/CryCommon/Cry_Geo.h deleted file mode 100644 index cb3061529a..0000000000 --- a/Code/CryEngine/CryCommon/Cry_Geo.h +++ /dev/null @@ -1,1183 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Common structures for geometry computations - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_GEO_H -#define CRYINCLUDE_CRYCOMMON_CRY_GEO_H -#pragma once - -#include "Cry_Math.h" -/////////////////////////////////////////////////////////////////////////////// -// Forward declarations // -/////////////////////////////////////////////////////////////////////////////// - -struct Ray; -template -struct Lineseg_tpl; -template -struct Triangle_tpl; - -struct AABB; -template -struct OBB_tpl; - -struct Sphere; -struct AAEllipsoid; -struct Ellipsoid; -struct Cone; - -//----------------------------------------------------- - - -/////////////////////////////////////////////////////////////////////////////// -// Definitions // -/////////////////////////////////////////////////////////////////////////////// - -// -// Random geometry generation functions. -// - -enum EGeomForm -{ - GeomForm_Vertices, - GeomForm_Edges, - GeomForm_Surface, - GeomForm_Volume, - - MaxGeomForm -}; -AUTO_TYPE_INFO(EGeomForm) - -enum EGeomType -{ - GeomType_None, - GeomType_BoundingBox, - GeomType_Physics, - GeomType_Render, -}; -AUTO_TYPE_INFO(EGeomType) - -struct PosNorm -{ - Vec3 vPos; - Vec3 vNorm; - - void zero() - { - vPos.zero(); - vNorm.zero(); - } - - // transform by matrix, etc - void operator <<= (Matrix34 const& mx) - { - vPos = mx * vPos; - vNorm = Matrix33(mx) * vNorm; - } - void operator <<= (QuatTS const& qts) - { - vPos = qts * vPos; - vNorm = qts.q * vNorm; - } - void operator <<= (DualQuat const& dq) - { - vPos = dq * vPos; - vNorm = dq.nq * vNorm; - } -}; - -struct RectF -{ - float x, y, w, h; - RectF() - : x(0) - , y(0) - , w(1) - , h(1) - { - } - AUTO_STRUCT_INFO -}; - -struct RectI -{ - int x, y, w, h; - RectI() - : x(0) - , y(0) - , w(1) - , h(1) - { - } - RectI(int inX, int inY, int inW, int inH) - : x(inX) - , y(inY) - , w(inW) - , h(inH) - { - } - _inline void Add(RectI rcAdd) - { - int x2 = x + w; - int y2 = y + h; - int x22 = rcAdd.x + rcAdd.w; - int y22 = rcAdd.y + rcAdd.h; - x = min(x, rcAdd.x); - y = min(y, rcAdd.y); - x2 = max(x2, x22); - y2 = max(y2, y22); - w = x2 - x; - h = y2 - y; - } - _inline void Add(int inX, int inY, int inW, int inH) - { - Add(RectI(inX, inY, inW, inH)); - } -}; - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct Line -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -struct Line -{ - Vec3 pointonline; - Vec3 direction; //caution: the direction is important for any intersection test - - //default Line constructor (without initialisation) - inline Line(void) {} - inline Line(const Vec3& o, const Vec3& d) { pointonline = o; direction = d; } - inline void operator () (const Vec3& o, const Vec3& d) { pointonline = o; direction = d; } - - ~Line(void) {}; -}; - - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct Ray -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -struct Ray -{ - Vec3 origin; - Vec3 direction; - - //default Ray constructor (without initialisation) - inline Ray(void) {} - inline Ray(const Vec3& o, const Vec3& d) { origin = o; direction = d; } - inline void operator () (const Vec3& o, const Vec3& d) { origin = o; direction = d; } - - ~Ray(void) {}; -}; - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct Lineseg -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -template -struct Lineseg_tpl -{ - Vec3_tpl start; - Vec3_tpl end; - - //default Lineseg constructor (without initialisation) - inline Lineseg_tpl(void) {} - inline Lineseg_tpl(const Vec3_tpl& s, const Vec3_tpl& e) { start = s; end = e; } - inline void operator () (const Vec3_tpl& s, const Vec3_tpl& e) { start = s; end = e; } - - Vec3 GetPoint(F t) const {return t * end + (F(1.0) - t) * start; } - - ~Lineseg_tpl(void) {}; -}; - -typedef Lineseg_tpl Lineseg; -typedef Lineseg_tpl Linesegr; - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct Triangle -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -template -struct Triangle_tpl -{ - Vec3_tpl v0, v1, v2; - - //default Lineseg constructor (without initialisation) - ILINE Triangle_tpl(void) {} - ILINE Triangle_tpl(const Vec3_tpl& a, const Vec3_tpl& b, const Vec3_tpl& c) { v0 = a; v1 = b; v2 = c; } - ILINE void operator () (const Vec3_tpl& a, const Vec3_tpl& b, const Vec3_tpl& c) { v0 = a; v1 = b; v2 = c; } - - ~Triangle_tpl(void) {}; - - Vec3_tpl GetNormal() const - { - return ((v1 - v0) ^ (v2 - v0)).GetNormalized(); - } - - F GetArea() const - { - return 0.5f * (v1 - v0).Cross(v2 - v0).GetLength(); - } -}; - - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct Cone -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -struct Cone -{ - Vec3 mTip; - Vec3 mDir; - Vec3 mBase; - - float mHeight; - float mBaseRadius; - - Cone() {} - Cone(const Vec3& tip, const Vec3& dir, float height, float baseRadius) - : mTip(tip) - , mDir(dir) - , mBase(tip + dir * height) - , mHeight(height) - , mBaseRadius(baseRadius) {} -}; - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct AABB -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -struct AABB -{ - Vec3 min; - Vec3 max; - - /// default AABB constructor (without initialisation) - ILINE AABB() - {} - enum type_reset - { - RESET - }; - // AABB aabb(RESET) generates a reset aabb - ILINE AABB(type_reset) - { Reset(); } - ILINE explicit AABB(float radius) - { max = Vec3(radius); min = -max; } - ILINE explicit AABB(const Vec3& v) - { min = max = v; } - ILINE AABB(const Vec3& v, float radius) - { Vec3 ext(radius); min = v - ext; max = v + ext; } - ILINE AABB(const Vec3& vmin, const Vec3& vmax) - { min = vmin; max = vmax; } - ILINE AABB(const AABB& aabb) - { - min.x = aabb.min.x; - min.y = aabb.min.y; - min.z = aabb.min.z; - max.x = aabb.max.x; - max.y = aabb.max.y; - max.z = aabb.max.z; - } - inline AABB(const Vec3* points, int num) - { - Reset(); - for (int i = 0; i < num; i++) - { - Add(points[i]); - } - } - - //! Reset Bounding box before calculating bounds. - //! These values ensure that Add() functions work correctly for Reset bbs, without additional comparisons. - ILINE void Reset() - { min = Vec3(1e15f); max = Vec3(-1e15f); } - - ILINE bool IsReset() const - { return min.x > max.x; } - - ILINE float IsResetSel(float ifReset, float ifNotReset) const - { return (float)fsel(max.x - min.x, ifNotReset, ifReset); } - - //! Check if bounding box is empty (Zero volume). - ILINE bool IsEmpty() const - { return min == max; } - - //! Check if bounding box has valid, non zero volume - ILINE bool IsNonZero() const - { return min.x < max.x && min.y < max.y && min.z < max.z; } - - ILINE Vec3 GetCenter() const - { return (min + max) * 0.5f; } - - ILINE Vec3 GetSize() const - { return (max - min) * IsResetSel(0.0f, 1.0f); } - - ILINE float GetRadius() const - { return IsResetSel(0.0f, (max - min).GetLengthFloat() * 0.5f); } - - ILINE float GetRadiusSqr() const - { return IsResetSel(0.0f, ((max - min) * 0.5f).GetLengthSquaredFloat()); } - - ILINE float GetVolume() const - { return IsResetSel(0.0f, (max.x - min.x) * (max.y - min.y) * (max.z - min.z)); } - - ILINE void Add(const Vec3& v) - { - min.CheckMin(v); - max.CheckMax(v); - } - - inline void Add(const Vec3& v, float radius) - { - Vec3 ext(radius); - min.CheckMin(v - ext); - max.CheckMax(v + ext); - } - - ILINE void Add(const AABB& bb) - { - min.CheckMin(bb.min); - max.CheckMax(bb.max); - } - - inline void Move(const Vec3& v) - { - const float moveMult = IsResetSel(0.0f, 1.0f); - const Vec3 vMove = v * moveMult; - min += vMove; - max += vMove; - } - - inline void Expand(Vec3 const& v) - { - if (!IsReset()) - { - min -= v; - max += v; - } - } - - // Augment the box on all sides by a box. - inline void Augment(AABB const& bb) - { - if (!IsReset() && !bb.IsReset()) - { - Add(min + bb.min); - Add(max + bb.max); - } - } - - void ClipToBox(AABB const& bb) - { - min.CheckMax(bb.min); - max.CheckMin(bb.max); - } - - void ClipMoveToBox(AABB const& bb) - { - for (int a = 0; a < 3; a++) - { - if (max[a] - min[a] > bb.max[a] - bb.min[a]) - { - min[a] = bb.min[a]; - max[a] = bb.max[a]; - } - else if (min[a] < bb.min[a]) - { - max[a] += bb.min[a] - min[a]; - min[a] = bb.min[a]; - } - else if (max[a] > bb.max[a]) - { - min[a] += bb.max[a] - max[a]; - max[a] = bb.max[a]; - } - } - } - - //! Check if this bounding box overlap with bounding box of sphere. - bool IsOverlapSphereBounds(const Vec3& pos, float radius) const - { - assert(min.IsValid()); - assert(max.IsValid()); - assert(pos.IsValid()); - - if (pos.x > min.x && pos.x < max.x && pos.y > min.y && pos.y < max.y && pos.z > min.z && pos.z < max.z) - { - return true; - } - - if (pos.x + radius < min.x) - { - return false; - } - if (pos.y + radius < min.y) - { - return false; - } - if (pos.z + radius < min.z) - { - return false; - } - if (pos.x - radius > max.x) - { - return false; - } - if (pos.y - radius > max.y) - { - return false; - } - if (pos.z - radius > max.z) - { - return false; - } - return true; - } - - //! Check if this bounding box contain sphere within itself. - bool IsContainSphere(const Vec3& pos, float radius) const - { - assert(min.IsValid()); - assert(max.IsValid()); - assert(pos.IsValid()); - if (pos.x - radius < min.x) - { - return false; - } - if (pos.y - radius < min.y) - { - return false; - } - if (pos.z - radius < min.z) - { - return false; - } - if (pos.x + radius > max.x) - { - return false; - } - if (pos.y + radius > max.y) - { - return false; - } - if (pos.z + radius > max.z) - { - return false; - } - return true; - } - - //! Check if this bounding box contains a point within itself. - bool IsContainPoint(const Vec3& pos) const - { - assert(min.IsValid()); - assert(max.IsValid()); - assert(pos.IsValid()); - if (pos.x < min.x) - { - return false; - } - if (pos.y < min.y) - { - return false; - } - if (pos.z < min.z) - { - return false; - } - if (pos.x > max.x) - { - return false; - } - if (pos.y > max.y) - { - return false; - } - if (pos.z > max.z) - { - return false; - } - return true; - } - - float GetDistanceSqr(Vec3 const& v) const - { - Vec3 vNear = v; - vNear.CheckMax(min); - vNear.CheckMin(max); - return vNear.GetSquaredDistance(v); - } - - float GetDistance(Vec3 const& v) const - { - return sqrt(GetDistanceSqr(v)); - } - - bool ContainsBox(AABB const& b) const - { - assert(min.IsValid()); - assert(max.IsValid()); - assert(b.min.IsValid()); - assert(b.max.IsValid()); - return min.x <= b.min.x && min.y <= b.min.y && min.z <= b.min.z - && max.x >= b.max.x && max.y >= b.max.y && max.z >= b.max.z; - } - - bool ContainsBox2D(AABB const& b) const - { - assert(min.IsValid()); - assert(max.IsValid()); - assert(b.min.IsValid()); - assert(b.max.IsValid()); - return min.x <= b.min.x && min.y <= b.min.y - && max.x >= b.max.x && max.y >= b.max.y; - } - - - // Check two bounding boxes for intersection. - inline bool IsIntersectBox(const AABB& b) const - { - assert(min.IsValid()); - assert(max.IsValid()); - assert(b.min.IsValid()); - assert(b.max.IsValid()); - // Check for intersection on X axis. - if ((min.x > b.max.x) || (b.min.x > max.x)) - { - return false; - } - // Check for intersection on Y axis. - if ((min.y > b.max.y) || (b.min.y > max.y)) - { - return false; - } - // Check for intersection on Z axis. - if ((min.z > b.max.z) || (b.min.z > max.z)) - { - return false; - } - // Boxes overlap in all 3 axises. - return true; - } - - /*! - * calculate the new bounds of a transformed AABB - * - * Example: - * AABB aabb = AABB::CreateAABBfromOBB(m34,aabb); - * - * return values: - * expanded AABB in world-space - */ - ILINE void SetTransformedAABB(const Matrix34& m34, const AABB& aabb) - { - if (aabb.IsReset()) - { - Reset(); - } - else - { - Matrix33 m33; - m33.m00 = fabs_tpl(m34.m00); - m33.m01 = fabs_tpl(m34.m01); - m33.m02 = fabs_tpl(m34.m02); - m33.m10 = fabs_tpl(m34.m10); - m33.m11 = fabs_tpl(m34.m11); - m33.m12 = fabs_tpl(m34.m12); - m33.m20 = fabs_tpl(m34.m20); - m33.m21 = fabs_tpl(m34.m21); - m33.m22 = fabs_tpl(m34.m22); - - Vec3 sz = m33 * ((aabb.max - aabb.min) * 0.5f); - Vec3 pos = m34 * ((aabb.max + aabb.min) * 0.5f); - min = pos - sz; - max = pos + sz; - } - } - ILINE static AABB CreateTransformedAABB(const Matrix34& m34, const AABB& aabb) - { AABB taabb; taabb.SetTransformedAABB(m34, aabb); return taabb; } - - - - ILINE void SetTransformedAABB(const QuatT& qt, const AABB& aabb) - { - if (aabb.IsReset()) - { - Reset(); - } - else - { - Matrix33 m33 = Matrix33(qt.q); - m33.m00 = fabs_tpl(m33.m00); - m33.m01 = fabs_tpl(m33.m01); - m33.m02 = fabs_tpl(m33.m02); - m33.m10 = fabs_tpl(m33.m10); - m33.m11 = fabs_tpl(m33.m11); - m33.m12 = fabs_tpl(m33.m12); - m33.m20 = fabs_tpl(m33.m20); - m33.m21 = fabs_tpl(m33.m21); - m33.m22 = fabs_tpl(m33.m22); - Vec3 sz = m33 * ((aabb.max - aabb.min) * 0.5f); - Vec3 pos = qt * ((aabb.max + aabb.min) * 0.5f); - min = pos - sz; - max = pos + sz; - } - } - ILINE static AABB CreateTransformedAABB(const QuatT& qt, const AABB& aabb) - { AABB taabb; taabb.SetTransformedAABB(qt, aabb); return taabb; } - - - //create an AABB using just the extensions of the OBB and ignore the orientation. - template - ILINE void SetAABBfromOBB(const OBB_tpl& obb) - { min = obb.c - obb.h; max = obb.c + obb.h; } - template - ILINE static AABB CreateAABBfromOBB(const OBB_tpl& obb) - { return AABB(obb.c - obb.h, obb.c + obb.h); } - - /*! - * converts an OBB into an tight fitting AABB - * - * Example: - * AABB aabb = AABB::CreateAABBfromOBB(wposition,obb,1.0f); - * - * return values: - * expanded AABB in world-space - */ - template - ILINE void SetAABBfromOBB(const Vec3& wpos, const OBB_tpl& obb, f32 scaling = 1.0f) - { - Vec3 pos = obb.m33 * obb.c * scaling + wpos; - Vec3 sz = obb.m33.GetFabs() * obb.h * scaling; - min = pos - sz; - max = pos + sz; - } - template - ILINE static AABB CreateAABBfromOBB(const Vec3& wpos, const OBB_tpl& obb, f32 scaling = 1.0f) - { AABB taabb; taabb.SetAABBfromOBB(wpos, obb, scaling); return taabb; } - - /* Converts a Cone into a tight fitting AABB */ - ILINE static AABB CreateAABBfromCone(const Cone& c) - { - // Construct AABB for cone base - Vec3 baseX = Vec3(1.f - c.mDir.x * c.mDir.x, c.mDir.x * c.mDir.y, c.mDir.x * c.mDir.z).GetNormalized() * c.mBaseRadius; - Vec3 baseY = Vec3(c.mDir.y * c.mDir.x, 1.f - c.mDir.y * c.mDir.y, c.mDir.y * c.mDir.z).GetNormalized() * c.mBaseRadius; - Vec3 baseZ = Vec3(c.mDir.z * c.mDir.x, c.mDir.z * c.mDir.y, 1.f - c.mDir.z * c.mDir.z).GetNormalized() * c.mBaseRadius; - - Vec3 aabbMax = Vec3(baseX.x, baseY.y, baseZ.z).abs(); - Vec3 aabbMin = -aabbMax; - - AABB result(aabbMin, aabbMax); - result.Move(c.mBase); - - // add tip - result.Add(c.mTip); - return result; - } - - AUTO_STRUCT_INFO -}; - -ILINE bool IsEquivalent(const AABB& a, const AABB& b, float epsilon = VEC_EPSILON) -{ - return IsEquivalent(a.min, b.min, epsilon) && IsEquivalent(a.max, b.max, epsilon); -} - - - - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct OBB -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -template -struct OBB_tpl -{ - Matrix33 m33; //orientation vectors - Vec3 h; //half-length-vector - Vec3 c; //center of obb - - //default OBB constructor (without initialisation) - inline OBB_tpl() {} - - ILINE void SetOBB(const Matrix33& matrix, const Vec3& hlv, const Vec3& center) { m33 = matrix; h = hlv; c = center; } - ILINE static OBB_tpl CreateOBB(const Matrix33& m33, const Vec3& hlv, const Vec3& center) { OBB_tpl obb; obb.m33 = m33; obb.h = hlv; obb.c = center; return obb; } - - ILINE void SetOBBfromAABB(const Matrix33& mat33, const AABB& aabb) - { - m33 = mat33; - h = (aabb.max - aabb.min) * 0.5f; //calculate the half-length-vectors - c = (aabb.max + aabb.min) * 0.5f; //the center is relative to the PIVOT - } - ILINE void SetOBBfromAABB(const Quat& q, const AABB& aabb) - { - m33 = Matrix33(q); - h = (aabb.max - aabb.min) * 0.5f; //calculate the half-length-vectors - c = (aabb.max + aabb.min) * 0.5f; //the center is relative to the PIVOT - } - ILINE static OBB_tpl CreateOBBfromAABB(const Matrix33& m33, const AABB& aabb) { OBB_tpl obb; obb.SetOBBfromAABB(m33, aabb); return obb; } - ILINE static OBB_tpl CreateOBBfromAABB(const Quat& q, const AABB& aabb) { OBB_tpl obb; obb.SetOBBfromAABB(q, aabb); return obb; } - - ~OBB_tpl(void) {}; -}; - - - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct Sphere -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -struct Sphere -{ - Vec3 center; - float radius; - - Sphere() {} - Sphere(const Vec3& c, float r) - : center(c) - , radius(r) {} - void operator()(const Vec3& c, float r) { center = c; radius = r; } -}; - -struct HWVSphere -{ - hwvec3 center; - simdf radius; - - ILINE HWVSphere(const hwvec3& c, const simdf& r) - { - center = c; - radius = r; - } - - ILINE HWVSphere(const ::Sphere& sp) - { - center = HWVLoadVecUnaligned(&sp.center); - radius = SIMDFLoadFloat(sp.radius); - } -}; - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct AAEllipsoid -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -struct AAEllipsoid -{ - Vec3 center; - Vec3 radius_vec; - - //default AAEllipsoid constructor (without initialisation) - inline AAEllipsoid(void) {} - inline AAEllipsoid(const Vec3& c, const Vec3& rv) { radius_vec = rv; center = c; } - inline void operator () (const Vec3& c, const Vec3& rv) { radius_vec = rv; center = c; } - - ~AAEllipsoid(void) {}; -}; - - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct Ellipsoid -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -struct Ellipsoid -{ - Matrix34 ExtensionPos; - - //default Ellipsoid constructor (without initialisation) - inline Ellipsoid(void) {} - inline Ellipsoid(const Matrix34& ep) { ExtensionPos = ep; } - inline void operator () (const Matrix34& ep) { ExtensionPos = ep; } - - ~Ellipsoid(void) {}; -}; - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct TRect -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -template -struct TRect_tpl -{ - typedef Vec2_tpl Vec; - - Vec Min, Max; - - inline TRect_tpl() {} - inline TRect_tpl(Num x1, Num y1, Num x2, Num y2) - : Min(x1, y1) - , Max(x2, y2) {} - inline TRect_tpl(const TRect_tpl& rc) - : Min(rc.Min) - , Max(rc.Max) {} - inline TRect_tpl(const Vec& min, const Vec& max) - : Min(min) - , Max(max) {} - - inline TRect_tpl operator * (Num k) const - { - return TRect_tpl(Min.x * k, Min.y * k, Max.x * k, Max.y * k); - } - inline TRect_tpl operator / (Num k) const - { - return TRect_tpl(Min.x / k, Min.y / k, Max.x / k, Max.y / k); - } - - inline bool IsEmpty() const { return Max.x < Min.x && Max.y < Min.y; } - inline TRect_tpl& SetEmpty() { Max = Vec(-1, -1); Min = Vec(0, 0); return *this; } - - inline Vec GetDim() const { return Max - Min; } - inline Num GetWidth() const { return Max.x - Min.x; } - inline Num GetHeight() const { return Max.y - Min.y; } - - inline bool IsEqual(const TRect_tpl& rc) const { return Min.x == rc.Min.x && Min.y == rc.Min.y && Max.x == rc.Max.x && Max.y == rc.Max.y; } - - inline bool InRect(const TRect_tpl& rc) const { return rc.Min.x >= Min.x && rc.Max.x <= Max.x && rc.Min.y >= Min.y && rc.Max.y <= Max.y; } - inline bool InRect(Vec pt) const { return pt.x >= Min.x && pt.x <= Max.x && pt.y >= Min.y && pt.y <= Max.y; } - inline Vec& IntoRect(Vec& pt) const - { - if (pt.x < Min.x) - { - pt.x = Min.x; - } - else if (pt.x > Max.x) - { - pt.x = Max.x; - } - if (pt.y < Min.y) - { - pt.y = Min.y; - } - else if (pt.y > Max.y) - { - pt.y = Max.y; - } - return pt; - } - - inline bool Intersects(const TRect_tpl& rc) const - { - return !IsEmpty() && !rc.IsEmpty() && - !(Min.x > rc.Max.x || Max.x < rc.Min.x || - Min.y > rc.Max.y || Max.y < rc.Min.y); - } - - inline TRect_tpl& DoUnite(const TRect_tpl& rc) - { - if (IsEmpty()) - { - Min = rc.Min; - Max = rc.Max; - return *this; - } - if (rc.IsEmpty()) - { - return *this; - } - if (Min.x > rc.Min.x) - { - Min.x = rc.Min.x; - } - if (Min.y > rc.Min.y) - { - Min.y = rc.Min.y; - } - if (Max.x < rc.Max.x) - { - Max.x = rc.Max.x; - } - if (Max.y < rc.Max.y) - { - Max.y = rc.Max.y; - } - return *this; - } - - inline TRect_tpl& DoIntersect(const TRect_tpl& rc) - { - if (IsEmpty()) - { - return *this; - } - if (rc.IsEmpty()) - { - return SetEmpty(); - } - if (Min.x < rc.Min.x) - { - Min.x = rc.Min.x; - } - if (Min.y < rc.Min.y) - { - Min.y = rc.Min.y; - } - if (Max.x > rc.Max.x) - { - Max.x = rc.Max.x; - } - if (Max.y > rc.Max.y) - { - Max.y = rc.Max.y; - } - - if (Min.x == Max.x || Min.y == Max.y) - { - return SetEmpty(); - } - - return *this; - } - - inline TRect_tpl GetSubRect(const TRect_tpl& rc) const - { - if (IsEmpty()) - { - return *this; - } - if (rc.IsEmpty()) - { - return rc; - } - return TRect_tpl(Min.x + rc.Min.x * GetWidth(), - Min.y + rc.Min.y * GetHeight(), - Min.x + rc.Max.x * GetWidth(), - Min.y + rc.Max.y * GetHeight()); - } - - inline TRect_tpl GetSubRectInv(const TRect_tpl& rcSub) const - { - if (IsEmpty()) - { - return *this; - } - if (rcSub.IsEmpty()) - { - return rcSub; - } - return TRect_tpl((rcSub.Min.x - Min.x) / GetWidth(), - (rcSub.Min.y - Min.y) / GetHeight(), - (rcSub.Max.x - Min.x) / GetWidth(), - (rcSub.Max.y - Min.y) / GetHeight()); - } -}; - -typedef TRect_tpl Rectf; -typedef TRect_tpl Recti; - -typedef Triangle_tpl Triangle; -typedef Triangle_tpl Triangle_f64; -typedef OBB_tpl OBB; - -////////////////////////////////////////////////////////////////////////// -// Manage linear and rotational 3D velocity in a class -class Velocity3 -{ -public: - Vec3 vLin, vRot; - - Velocity3() - {} - Velocity3(type_zero) - : vLin(ZERO) - , vRot(ZERO) {} - Velocity3(Vec3 const& lin) - : vLin(lin) - , vRot(ZERO) {} - Velocity3(Vec3 const& lin, Vec3 const& rot) - : vLin(lin) - , vRot(rot) {} - - void FromDelta(QuatT const& loc0, QuatT const& loc1, float fTime) - { - float fInvT = 1.f / fTime; - vLin = (loc1.t - loc0.t) * fInvT; - vRot = Quat::log(loc1.q * loc0.q.GetInverted()) * fInvT; - } - - Vec3 VelocityAt(Vec3 const& vPosRel) const - { return vLin + (vRot % vPosRel); } - - void operator += (Velocity3 const& vv) - { - vLin += vv.vLin; - vRot += vv.vRot; - } - void operator *= (float f) - { - vLin *= f; - vRot *= f; - } - void Interp(Velocity3 const& vv, float f) - { - vLin += (vv.vLin - vLin) * f; - vRot += (vv.vRot - vRot) * f; - } -}; - -////////////////////////////////////////////////////////////////////////// -#include "Cry_GeoDistance.h" -#include "Cry_GeoOverlap.h" -#include "Cry_GeoIntersect.h" - - - - - - - - - - -///////////////////////////////////////////////////////////////////////// -//this is some special engine stuff, should be moved to a better location -///////////////////////////////////////////////////////////////////////// - -// for bbox's checks and calculations -#define MAX_BB +99999.0f -#define MIN_BB -99999.0f - -//! checks if this has been set to minBB -inline bool IsMinBB(const Vec3& v) -{ - if (v.x <= MIN_BB) - { - return (true); - } - if (v.y <= MIN_BB) - { - return (true); - } - if (v.z <= MIN_BB) - { - return (true); - } - return (false); -} - -//! checks if this has been set to maxBB -inline bool IsMaxBB(const Vec3& v) -{ - if (v.x >= MAX_BB) - { - return (true); - } - if (v.y >= MAX_BB) - { - return (true); - } - if (v.z >= MAX_BB) - { - return (true); - } - return (false); -} - -inline Vec3 SetMaxBB(void) { return Vec3(MAX_BB, MAX_BB, MAX_BB); } -inline Vec3 SetMinBB(void) { return Vec3(MIN_BB, MIN_BB, MIN_BB); } - -inline void AddToBounds (const Vec3& v, Vec3& mins, Vec3& maxs) -{ - if (v.x < mins.x) - { - mins.x = v.x; - } - if (v.x > maxs.x) - { - maxs.x = v.x; - } - if (v.y < mins.y) - { - mins.y = v.y; - } - if (v.y > maxs.y) - { - maxs.y = v.y; - } - if (v.z < mins.z) - { - mins.z = v.z; - } - if (v.z > maxs.z) - { - maxs.z = v.z; - } -} - - -//////////////////////////////////////////////////////////////// -//! calc the area of a polygon giving a list of vertices and normal -inline float CalcArea(const Vec3* vertices, int numvertices, const Vec3& normal) -{ - Vec3 csum(0, 0, 0); - - int n = numvertices; - for (int i = 0, j = 1; i <= n - 2; i++, j++) - { - csum.x += vertices[i].y * vertices[j].z - vertices[i].z * vertices[j].y; - csum.y += vertices[i].z * vertices[j].x - vertices[i].x * vertices[j].z; - csum.z += vertices[i].x * vertices[j].y - vertices[i].y * vertices[j].x; - } - - csum.x += vertices[n - 1].y * vertices[0].z - vertices[n - 1].z * vertices[0].y; - csum.y += vertices[n - 1].z * vertices[0].x - vertices[n - 1].x * vertices[0].z; - csum.z += vertices[n - 1].x * vertices[0].y - vertices[n - 1].y * vertices[0].x; - - float area = 0.5f * (float)fabs(normal | csum); - return (area); -} - - - -#endif // CRYINCLUDE_CRYCOMMON_CRY_GEO_H diff --git a/Code/CryEngine/CryCommon/Cry_GeoDistance.h b/Code/CryEngine/CryCommon/Cry_GeoDistance.h deleted file mode 100644 index 615c0f1c08..0000000000 --- a/Code/CryEngine/CryCommon/Cry_GeoDistance.h +++ /dev/null @@ -1,1693 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Common distance-computations - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_GEODISTANCE_H -#define CRYINCLUDE_CRYCOMMON_CRY_GEODISTANCE_H -#pragma once - -#include -#include -#include - -#ifdef max -#undef max -#endif - -namespace Intersect -{ - bool Lineseg_Triangle(const Lineseg& lineseg, const Vec3& v0, const Vec3& v1, const Vec3& v2, Vec3& output, float* outT); -} - -namespace Distance { - template - ILINE F Point_Point(const Vec3_tpl& p1, const Vec3_tpl& p2) - { - return sqrt_tpl(square(p1.x - p2.x) + square(p1.y - p2.y) + square(p1.z - p2.z)); - } - - template - ILINE F Point_PointSq(const Vec3_tpl& p1, const Vec3_tpl& p2) - { - return square(p1.x - p2.x) + square(p1.y - p2.y) + square(p1.z - p2.z); - } - - template - ILINE F Point_Point2DSq(const Vec3_tpl& p1, const Vec3_tpl& p2) - { - return square(p1.x - p2.x) + square(p1.y - p2.y); - } - - template - ILINE F Point_Point2D(const Vec3_tpl& p1, const Vec3_tpl& p2) - { - return sqrt_tpl(square(p1.x - p2.x) + square(p1.y - p2.y)); - } - - // Description: - // Distance: Origin_Triangle2D. - // Calculate the closest distance of a triangle in XY-plane to the coordinate origin. - // it is assumed that the z-values of the triangle are all in the same plane. - // Return Value: - // The 3d-position of the closest point on the triangle. - // Example: - // Vec3 result = Distance::Origin_Triangle2D( triangle ); - template - ILINE Vec3_tpl Origin_Triangle2D(const Triangle_tpl& t) - { - Vec3_tpl a = t.v0; - Vec3_tpl b = t.v1; - Vec3_tpl c = t.v2; - //check if (0,0,0) is inside or in fron of any triangle sides. - uint32 flag = ((a.x * (a.y - b.y) - a.y * (a.x - b.x)) < 0) | (((b.x * (b.y - c.y) - b.y * (b.x - c.x)) < 0) << 1) | (((c.x * (c.y - a.y) - c.y * (c.x - a.x)) < 0) << 2); - switch (flag) - { - case 0: - return Vec3_tpl(0, 0, a.z); //center is inside of triangle - case 1: - if ((a | (b - a)) > 0.0f) - { - flag = 5; - } - else if ((b | (a - b)) > 0.0f) - { - flag = 3; - } - break; - case 2: - if ((b | (c - b)) > 0.0f) - { - flag = 3; - } - else if ((c | (b - c)) > 0.0f) - { - flag = 6; - } - break; - case 3: - return b; //vertex B is closed - case 4: - if ((c | (a - c)) > 0.0f) - { - flag = 6; - } - else if ((a | (c - a)) > 0.0f) - { - flag = 5; - } - break; - case 5: - return a; //vertex A is closed - case 6: - return c; //vertex C is closed - } - //check again using expanded area - switch (flag) - { - case 1: - { - Vec3_tpl n = (b - a).GetNormalized(); - return n * (-a | n) + a; - } - case 2: - { - Vec3_tpl n = (c - b).GetNormalized(); - return n * (-b | n) + b; - } - case 3: - return b; - case 4: - { - Vec3_tpl n = (a - c).GetNormalized(); - return n * (-c | n) + c; - } - case 5: - return a; - case 6: - return c; - } - return Vec3_tpl(0, 0, 0); - } - - ILINE hwvec3 Origin_Triangle2D(const hwvec3& a, const hwvec3& b, const hwvec3& c) - { - const hwvec3 vZero = HWV3Zero(); - const hwvec3 aNeg = HWV3Negate(a); - const hwvec3 bNeg = HWV3Negate(b); - const hwvec3 cNeg = HWV3Negate(c); - - const hwvec3 vASubB = HWVSub(a, b); - const hwvec3 vBSubA = HWVSub(b, a); - const hwvec3 vASubC = HWVSub(a, c); - const hwvec3 vCSubA = HWVSub(c, a); - const hwvec3 vBSubC = HWVSub(b, c); - const hwvec3 vCSubB = HWVSub(c, b); - - HWV4PermuteControl(vSwapXY, HWV_PERMUTE_0Y, HWV_PERMUTE_0X, HWV_PERMUTE_0Z, HWV_PERMUTE_0W); - - const hwvec3 aPerm = HWV3PermuteWord(a, a, vSwapXY); - const hwvec3 vACombined = HWVMultiply(aPerm, vASubB); - - //Yes, this is the right way around, check the non-vectorized version below :) - const simdf vAY = HWV3SplatXToSIMDF(vACombined); - const simdf vAX = HWV3SplatYToSIMDF(vACombined); - - - const hwvec3 bPerm = HWV3PermuteWord(b, b, vSwapXY); - const hwvec3 vBCombined = HWVMultiply(bPerm, vBSubC); - - const simdf vBY = HWV3SplatXToSIMDF(vBCombined); - const simdf vBX = HWV3SplatYToSIMDF(vBCombined); - - - const hwvec3 cPerm = HWV3PermuteWord(c, c, vSwapXY); - const hwvec3 vCCombined = HWVMultiply(cPerm, vCSubA); - - const simdf vCY = HWV3SplatXToSIMDF(vCCombined); - const simdf vCX = HWV3SplatYToSIMDF(vCCombined); - - - //check if (0,0,0) is inside or in front of any triangle sides. - bool subflag0 = SIMDFLessThanB(vAX, vAY); - bool subflag1 = SIMDFLessThanB(vBX, vBY); - bool subflag2 = SIMDFLessThanB(vCX, vCY); - - uint32 flag = ((uint32)subflag0) | ((uint32)(subflag1 << 1)) | ((uint32)(subflag2 << 2)); - - switch (flag) - { - case 0: - { - HWV4PermuteControl(selectz, HWV_PERMUTE_1X, HWV_PERMUTE_1Y, HWV_PERMUTE_0Z, HWV_PERMUTE_1W); - return HWV3PermuteWord(a, vZero, selectz); //center is inside of triangle - } - case 1: - { - if (SIMDFLessThanB(HWV3AsSIMDF(vZero), HWV3Dot(a, vBSubA))) - { - flag = 5; - } - else if (SIMDFLessThanB(HWV3AsSIMDF(vZero), HWV3Dot(b, vASubB))) - { - flag = 3; - } - break; - } - case 2: - { - if (SIMDFLessThanB(HWV3AsSIMDF(vZero), HWV3Dot(b, vCSubB))) - { - flag = 3; - } - else if (SIMDFLessThanB(HWV3AsSIMDF(vZero), HWV3Dot(c, vBSubC))) - { - flag = 6; - } - break; - } - case 3: - return b; //vertex B is closed - case 4: - { - if (SIMDFLessThanB(HWV3AsSIMDF(vZero), HWV3Dot(c, vASubC))) - { - flag = 6; - } - else if (SIMDFLessThanB(HWV3AsSIMDF(vZero), HWV3Dot(a, vCSubA))) - { - flag = 5; - } - break; - } - case 5: - return a; //vertex A is closed - case 6: - return c; //vertex C is closed - } - - switch (flag) - { - case 1: - { - //hwvec3 n = HWV3Normalize(vBSubA); - simdf nLengthSq = HWV3Dot(vBSubA, vBSubA); - simdf invLengthSq = SIMDFReciprocal(nLengthSq); - return HWVMultiplySIMDFAdd(vBSubA, SIMDFMult(HWV3Dot(aNeg, vBSubA), invLengthSq), a); - } - case 2: - { - simdf nLengthSq = HWV3Dot(vCSubB, vCSubB); - simdf invLengthSq = SIMDFReciprocal(nLengthSq); - return HWVMultiplySIMDFAdd(vCSubB, SIMDFMult(HWV3Dot(bNeg, vCSubB), invLengthSq), b); - } - case 3: - return b; - case 4: - { - simdf nLengthSq = HWV3Dot(vASubC, vASubC); - simdf invLengthSq = SIMDFReciprocal(nLengthSq); - return HWVMultiplySIMDFAdd(vASubC, SIMDFMult(HWV3Dot(cNeg, vASubC), invLengthSq), c); - } - case 5: - return a; - case 6: - return c; - } - - // switch (flag) { - // case 1: { Vec3_tpl n=(b-a).GetNormalized(); return n*(-a|n)+a; } - // case 2: { Vec3_tpl n=(c-b).GetNormalized(); return n*(-b|n)+b; } - // case 3: return b; - // case 4: { Vec3_tpl n=(a-c).GetNormalized(); return n*(-c|n)+c; } - // case 5: return a; - // case 6: return c; - // } - - return vZero; - } - - - // Description: - // Distance: Point_Triangle. - // Calculate the closest distance of a point to a triangle in 3d-space. - // Return value: - // The squared distance. - // Example: - // float result = Distance::Point_Triangle( pos, triangle ); - template - ILINE F Point_TriangleSq(const Vec3_tpl& p, const Triangle_tpl& t) - { - //translate triangle into origin - Vec3_tpl a = t.v0 - p; - Vec3_tpl b = t.v1 - p; - Vec3_tpl c = t.v2 - p; - //transform triangle into XY-plane to simplify the test - Matrix33_tpl r33 = Matrix33_tpl::CreateRotationV0V1(((b - a) % (a - c)).GetNormalized(), Vec3(0, 0, 1)); - Vec3_tpl h = Origin_Triangle2D(Triangle_tpl(r33 * a, r33 * b, r33 * c)); - return (h | h); //return squared distance - } - - inline simdf Point_TriangleByPointsSq(const hwvec3& p, const hwvec3& t0, const hwvec3& t1, const hwvec3& t2) - { - //translate triangle into origin - - HWV3Constant(kUp, 0.0f, 0.0f, 1.0f); - - const hwvec3 a = HWVSub(t0, p); - const hwvec3 b = HWVSub(t1, p); - const hwvec3 c = HWVSub(t2, p); - - const hwvec3 baDiff = HWVSub(b, a); - const hwvec3 acDiff = HWVSub(a, c); - - const hwvec3 cross = HWVCross(baDiff, acDiff); - - const hwvec3 crossNormalized = HWV3Normalize(cross); - - hwmtx33 r33 = HWMtx33CreateRotationV0V1(crossNormalized, kUp); - - hwmtx33 r33opt = HWMtx33GetOptimized(r33); - - //transform triangle into XY-plane to simplify the test - const hwvec3 aRot = HWMtx33RotateVecOpt(r33opt, a); - const hwvec3 bRot = HWMtx33RotateVecOpt(r33opt, b); - const hwvec3 cRot = HWMtx33RotateVecOpt(r33opt, c); - - hwvec3 h = Origin_Triangle2D(aRot, bRot, cRot); - - return HWV3Dot(h, h); - } - - template - ILINE F Point_Triangle(const Vec3_tpl& p, const Triangle_tpl& t) - { - return sqrt_tpl(Point_TriangleSq(p, t)); - } - - // Description: - // Distance: Point_Triangle. - // Calculate the closest distance of a point to a triangle in 3d-space. - // The function returns the squared distance and the 3d-position of the - // closest point on the triangle. - // Example: - // float result = Distance::Point_Triangle( pos, triangle, output ); - template - ILINE F Point_TriangleSq(const Vec3_tpl& p, const Triangle_tpl& t, Vec3_tpl& output) - { - //translate triangle into origin - Vec3_tpl a = t.v0 - p; - Vec3_tpl b = t.v1 - p; - Vec3_tpl c = t.v2 - p; - //transform triangle into XY-plane to simplify the test - Matrix33_tpl r33 = Matrix33_tpl::CreateRotationV0V1(((b - a) % (a - c)).GetNormalized(), Vec3_tpl(0, 0, 1)); - Vec3_tpl h = Origin_Triangle2D(Triangle_tpl(r33 * a, r33 * b, r33 * c)); - output = h * r33 + p; - return (h | h); //return squared distance - } - - template - ILINE F Point_Triangle(const Vec3_tpl& p, const Triangle_tpl& t, Vec3_tpl& output) - { - return sqrt_tpl(Point_TriangleSq(p, t, output)); - } - - // Description: - // Squared distance from point to triangle, optionally returning the triangle position in - // parameteric form. - template - ILINE F Point_TriangleSq(const Vec3_tpl& point, const Triangle_tpl& triangle, F* pT0, F* pT1) - { - Vec3 diff = triangle.v0 - point; - const Vec3 edge0 = triangle.v1 - triangle.v0; - const Vec3 edge1 = triangle.v2 - triangle.v0; - F fA00 = edge0.GetLengthSquared(); - F fA01 = edge0.Dot(edge1); - F fA11 = edge1.GetLengthSquared(); - F fB0 = diff.Dot(edge0); - F fB1 = diff.Dot(edge1); - F fC = diff.GetLengthSquared(); - F fDet = abs(fA00 * fA11 - fA01 * fA01); - F fS = fA01 * fB1 - fA11 * fB0; - F fT = fA01 * fB0 - fA00 * fB1; - F fSqrDist; - - if (fS + fT <= fDet) - { - if (fS < (F)0.0) - { - if (fT < (F)0.0) // region 4 - { - if (fB0 < (F)0.0) - { - fT = (F)0.0; - if (-fB0 >= fA00) - { - fS = (F)1.0; - fSqrDist = fA00 + ((F)2.0) * fB0 + fC; - } - else - { - fS = -fB0 / fA00; - fSqrDist = fB0 * fS + fC; - } - } - else - { - fS = (F)0.0; - if (fB1 >= (F)0.0) - { - fT = (F)0.0; - fSqrDist = fC; - } - else if (-fB1 >= fA11) - { - fT = (F)1.0; - fSqrDist = fA11 + ((F)2.0) * fB1 + fC; - } - else - { - fT = -fB1 / fA11; - fSqrDist = fB1 * fT + fC; - } - } - } - else // region 3 - { - fS = (F)0.0; - if (fB1 >= (F)0.0) - { - fT = (F)0.0; - fSqrDist = fC; - } - else if (-fB1 >= fA11) - { - fT = (F)1.0; - fSqrDist = fA11 + ((F)2.0) * fB1 + fC; - } - else - { - fT = -fB1 / fA11; - fSqrDist = fB1 * fT + fC; - } - } - } - else if (fT < (F)0.0) // region 5 - { - fT = (F)0.0; - if (fB0 >= (F)0.0) - { - fS = (F)0.0; - fSqrDist = fC; - } - else if (-fB0 >= fA00) - { - fS = (F)1.0; - fSqrDist = fA00 + ((F)2.0) * fB0 + fC; - } - else - { - fS = -fB0 / fA00; - fSqrDist = fB0 * fS + fC; - } - } - else // region 0 - { - // minimum at interior point - F fInvDet = ((F)1.0) / fDet; - fS *= fInvDet; - fT *= fInvDet; - fSqrDist = fS * (fA00 * fS + fA01 * fT + ((F)2.0) * fB0) + - fT * (fA01 * fS + fA11 * fT + ((F)2.0) * fB1) + fC; - } - } - else - { - F fTmp0, fTmp1, fNumer, fDenom; - - if (fS < (F)0.0) // region 2 - { - fTmp0 = fA01 + fB0; - fTmp1 = fA11 + fB1; - if (fTmp1 > fTmp0) - { - fNumer = fTmp1 - fTmp0; - fDenom = fA00 - 2.0f * fA01 + fA11; - if (fNumer >= fDenom) - { - fS = (F)1.0; - fT = (F)0.0; - fSqrDist = fA00 + ((F)2.0) * fB0 + fC; - } - else - { - fS = fNumer / fDenom; - fT = (F)1.0 - fS; - fSqrDist = fS * (fA00 * fS + fA01 * fT + 2.0f * fB0) + - fT * (fA01 * fS + fA11 * fT + ((F)2.0) * fB1) + fC; - } - } - else - { - fS = (F)0.0; - if (fTmp1 <= (F)0.0) - { - fT = (F)1.0; - fSqrDist = fA11 + ((F)2.0) * fB1 + fC; - } - else if (fB1 >= (F)0.0) - { - fT = (F)0.0; - fSqrDist = fC; - } - else - { - fT = -fB1 / fA11; - fSqrDist = fB1 * fT + fC; - } - } - } - else if (fT < (F)0.0) // region 6 - { - fTmp0 = fA01 + fB1; - fTmp1 = fA00 + fB0; - if (fTmp1 > fTmp0) - { - fNumer = fTmp1 - fTmp0; - fDenom = fA00 - ((F)2.0) * fA01 + fA11; - if (fNumer >= fDenom) - { - fT = (F)1.0; - fS = (F)0.0; - fSqrDist = fA11 + ((F)2.0) * fB1 + fC; - } - else - { - fT = fNumer / fDenom; - fS = (F)1.0 - fT; - fSqrDist = fS * (fA00 * fS + fA01 * fT + ((F)2.0) * fB0) + - fT * (fA01 * fS + fA11 * fT + ((F)2.0) * fB1) + fC; - } - } - else - { - fT = (F)0.0; - if (fTmp1 <= (F)0.0) - { - fS = (F)1.0; - fSqrDist = fA00 + ((F)2.0) * fB0 + fC; - } - else if (fB0 >= (F)0.0) - { - fS = (F)0.0; - fSqrDist = fC; - } - else - { - fS = -fB0 / fA00; - fSqrDist = fB0 * fS + fC; - } - } - } - else // region 1 - { - fNumer = fA11 + fB1 - fA01 - fB0; - if (fNumer <= (F)0.0) - { - fS = (F)0.0; - fT = (F)1.0; - fSqrDist = fA11 + ((F)2.0) * fB1 + fC; - } - else - { - fDenom = fA00 - 2.0f * fA01 + fA11; - if (fNumer >= fDenom) - { - fS = (F)1.0; - fT = (F)0.0; - fSqrDist = fA00 + ((F)2.0) * fB0 + fC; - } - else - { - fS = fNumer / fDenom; - fT = (F)1.0 - fS; - fSqrDist = fS * (fA00 * fS + fA01 * fT + ((F)2.0) * fB0) + - fT * (fA01 * fS + fA11 * fT + ((F)2.0) * fB1) + fC; - } - } - } - } - - if (pT0) - { - *pT0 = fS; - } - - if (pT1) - { - *pT1 = fT; - } - - return abs(fSqrDist); - } - - // Description: - // Distance from point to triangle, optionally returning the triangle position in - // parameteric form. - template - ILINE F Point_Triangle(const Vec3_tpl& point, const Triangle_tpl& triangle, F* pT0, F* pT1) - { - return sqrt_tpl(Point_TriangleSq(point, triangle, pT0, pT1)); - } - - //---------------------------------------------------------------------------------- - /// Returns squared distance from a point to a line segment and also the "t value" (from 0 to 1) of the - /// closest point on the line segment - //---------------------------------------------------------------------------------- - template - ILINE F Point_LinesegSq(const Vec3_tpl& p, const Lineseg& lineseg, F& fT) - { - Vec3_tpl diff = p - lineseg.start; - Vec3_tpl dir = lineseg.end - lineseg.start; - fT = diff.Dot(dir); - - if (fT <= 0.0f) - { - fT = 0.0f; - } - else - { - F fSqrLen = dir.GetLengthSquared(); - if (fT >= fSqrLen) - { - fT = 1.0f; - diff -= dir; - } - else - { - fT /= fSqrLen; - diff -= fT * dir; - } - } - - return diff.GetLengthSquared(); - } - - /// Returns distance from a point to a line segment and also the "t value" (from 0 to 1) of the - /// closest point on the line segment - template - ILINE F Point_Lineseg(const Vec3_tpl& p, const Lineseg& lineseg, F& fT) - { - return sqrt_tpl(Point_LinesegSq(p, lineseg, fT)); - } - - - //---------------------------------------------------------------------------------- - /// Returns squared distance from a point to a line segment, ignoring the z coordinates - //---------------------------------------------------------------------------------- - template - ILINE F Point_Lineseg2DSq(const Vec3_tpl& p, const Lineseg& lineseg) - { - F dspx = p.x - lineseg.start.x, dspy = p.y - lineseg.start.y; - F dsex = lineseg.end.x - lineseg.start.x, dsey = lineseg.end.y - lineseg.start.y; - - F denom = (dsex * dsex + dsey * dsey); - F t; - if (denom > 1e-7) - { - t = (F)(dspx * dsex + dspy * dsey) / denom; - t = clamp_tpl(t, 0.0f, 1.0f); - } - else - { - t = 0; - } - - F dx = dsex * t - dspx; - F dy = dsey * t - dspy; - - return dx * dx + dy * dy; - } - - //---------------------------------------------------------------------------------- - /// Returns squared distance from a point to a line segment and also the "t value" (from 0 to 1) of the - /// closest point on the line segment, ignoring the z coordinates - //---------------------------------------------------------------------------------- - template - ILINE F Point_Lineseg2DSq(Vec3_tpl p, Lineseg lineseg, F& fT) - { - p.z = 0.0f; - lineseg.start.z = 0.0f; - lineseg.end.z = 0.0f; - return Point_LinesegSq(p, lineseg, fT); - } - - /// Returns distance from a point to a line segment, ignoring the z coordinates - template - ILINE F Point_Lineseg2D(const Vec3_tpl& p, const Lineseg& lineseg, F& fT) - { - return sqrt_tpl(Point_Lineseg2DSq(p, lineseg, fT)); - } - - /// Returns the squared distance from a point to a line as defined by two points (for accuracy - /// in some situations), and also the closest position on the line - template - ILINE F Point_LineSq(const Vec3_tpl& vPoint, - const Vec3_tpl& vLineStart, const Vec3_tpl& vLineEnd, Vec3_tpl& linePt) - { - Vec3_tpl dir; - Vec3_tpl pointVector; - - if ((vPoint - vLineStart).GetLengthSquared() > (vPoint - vLineEnd).GetLengthSquared()) - { - dir = vLineStart - vLineEnd; - pointVector = vPoint - vLineEnd; - linePt = vLineEnd; - } - else - { - dir = vLineEnd - vLineStart; - pointVector = vPoint - vLineStart; - linePt = vLineStart; - } - - F dirLen2 = dir.GetLengthSquared(); - if (dirLen2 <= 0.0f) - { - return pointVector.GetLengthSquared(); - } - dir /= sqrt_tpl(dirLen2); - - F t0 = pointVector.Dot(dir); - linePt += t0 * dir; - return (vPoint - linePt).GetLengthSquared(); - } - - /// Returns the distance from a point to a line as defined by two points (for accuracy - /// in some situations) - template - ILINE F Point_Line(const Vec3_tpl& vPoint, - const Vec3_tpl& vLineStart, const Vec3_tpl& vLineEnd, Vec3_tpl& linePt) - { - return sqrt_tpl(Point_LineSq(vPoint, vLineStart, vLineEnd, linePt)); - } - - /// In 2D. The returned linePt will have 0 z value - template - ILINE F Point_Line2DSq(Vec3_tpl vPoint, - Vec3_tpl vLineStart, Vec3_tpl vLineEnd, Vec3_tpl& linePt) - { - vPoint.z = 0.0f; - vLineStart.z = 0.0f; - vLineEnd.z = 0.0f; - return Point_LineSq(vPoint, vLineStart, vLineEnd, linePt); - } - - /// In 2D. The returned linePt will have 0 z value - template - ILINE F Point_Line2D(const Vec3_tpl& vPoint, - const Vec3_tpl& vLineStart, const Vec3_tpl& vLineEnd, Vec3_tpl& linePt) - { - return sqrt_tpl(Point_Line2DSq(vPoint, vLineStart, vLineEnd, linePt)); - } - - - /// Returns squared distance from a point to a polygon _edge_, together with the closest point on - /// the edge of the polygon. Can use the same point in/out - template - inline F Point_Polygon2DSq(const Vec3_tpl p, const VecContainer& polygon, Vec3_tpl& polyPos, Vec3_tpl* pNormal = NULL) - { - typename VecContainer::const_iterator li = polygon.begin(); - typename VecContainer::const_iterator liend = polygon.end(); - polyPos.x = polyPos.y = polyPos.z = 0.f; - float bestDist = std::numeric_limits::max(); - for (; li != liend; ++li) - { - typename VecContainer::const_iterator linext = li; - ++linext; - if (linext == liend) - { - linext = polygon.begin(); - } - const Vec3_tpl& l0 = *li; - const Vec3_tpl& l1 = *linext; - - float f; - float thisDist = Distance::Point_Lineseg2DSq(p, Lineseg(l0, l1), f); - if (thisDist < bestDist) - { - bestDist = thisDist; - polyPos = l0 + f * (l1 - l0); - if (pNormal) - { - Vec3_tpl vPolyseg = l1 - l0; - Vec3_tpl vIntSeg = (polyPos - p); - pNormal->x = vPolyseg.y; - pNormal->y = -vPolyseg.x; - pNormal->z = 0; - pNormal->NormalizeSafe(); - // returns the normal towards the start point of the intersecting segment - if ((vIntSeg.Dot(*pNormal)) > 0) - { - pNormal->x = -pNormal->x; - pNormal->y = -pNormal->y; - } - } - } - } - return bestDist; - } - - //---------------------------------------------------------------------------------- - /// Calculate squared distance between two line segments - //---------------------------------------------------------------------------------- - template - ILINE F Lineseg_Lineseg2DSq(const Lineseg& seg0, const Lineseg& seg1) - { - const F Epsilon = (F)0.0000001; - - Vec3_tpl delta = seg1.start - seg0.start; - - Vec3_tpl dir0 = seg0.end - seg0.start; - Vec3_tpl dir1 = seg1.end - seg1.start; - - F det = dir0.x * dir1.y - dir0.y * dir1.x; - F det0 = delta.x * dir1.y - delta.y * dir1.x; - F det1 = delta.x * dir0.y - delta.y * dir0.x; - - F absDet = fabs_tpl(det); - - if (absDet >= Epsilon) - { - F invDet = (F)1.0 / det; - - F a = det0 * invDet; - F b = det1 * invDet; - - if ((a <= (F)1.0) && (a >= (F)0.0) && (b <= (F)1.0) && (b >= (F)0.0)) - { - return (F)0.0; - } - } - - return min(Distance::Point_Lineseg2DSq(seg0.start, seg1), min(Distance::Point_Lineseg2DSq(seg0.end, seg1), - min(Distance::Point_Lineseg2DSq(seg1.start, seg0), Distance::Point_Lineseg2DSq(seg1.end, seg0)))); - } - - /// Returns squared distance from a lineseg to a polygon, together with the closest point on - /// the edge of the polygon. Can use the same point in/out - template - inline float Lineseg_Polygon2DSq(const Lineseg& line, const VecContainer& polygon) - { - typename VecContainer::const_iterator li = polygon.begin(); - typename VecContainer::const_iterator liend = polygon.end(); - - float bestDistSq = std::numeric_limits::max(); - for (; li != liend; ++li) - { - typename VecContainer::const_iterator linext = li; - ++linext; - if (linext == liend) - { - linext = polygon.begin(); - } - - float thisDistSq = Distance::Lineseg_Lineseg2DSq(line, Lineseg(*li, *linext)); - if (thisDistSq < bestDistSq) - { - bestDistSq = thisDistSq; - } - } - - return bestDistSq; - } - - /// Returns distance from a point to a polygon _edge_, together with the closest point on - /// the edge of the polygon - template - inline F Point_Polygon2D(const Vec3_tpl p, const VecContainer& polygon, Vec3_tpl& polyPos, Vec3_tpl* pNormal = NULL) - { - return sqrt_tpl(Point_Polygon2DSq(p, polygon, polyPos, pNormal)); - } - - - //! \brief Get the distance squared from a point to an OBB. - //! \param point Vec3 indicating the point to test - //! \param obb OBB indicating the Obb to test - //! \return float Closest distance squared from the point to the obb. - template - AZ_INLINE F Point_OBBSq(const Vec3_tpl& point, const OBB& obb) - { - F distanceSquared = 0; - const Vec3 v = point - obb.c; // box center to point - for (int i = 0; i < 3; ++i) - { - F d = v.Dot(obb.m33.GetColumn(i)); - F ex = 0; - F halfLength = obb.h[i]; - if (d < -halfLength) - { - ex = d + halfLength; - } - else if (d > halfLength) - { - ex = d - halfLength; - } - distanceSquared += sqr(ex); - } - - return distanceSquared; - } - - //! \brief Get the distance squared from a Point to a Cylinder. - //! \param point AZ::Vector3 The point to test distance against the cylinder - //! \param cylinderAxisEndA AZ::Vector3 One end of the cylinder axis (centered in the circle) - //! \param cylinderAxisEndB AZ::Vector3 Other end of the cylinder axis (centered in the circle) - //! \param radius float Radius of the cylinder - //! \return float Closest distance squared from the point to the cylinder. - AZ_INLINE float Point_CylinderSq( - const AZ::Vector3& point, - const AZ::Vector3& cylinderAxisEndA, - const AZ::Vector3& cylinderAxisEndB, - float radius - ) - { - // Use the cylinder axis' center point to determine distance by - // splitting into Voronoi regions and using symmetry. - // The regions are: - // - Inside - // - Beyond cylinder radius but between two disc ends. - // - Within cylinder radius but beyond two disc ends. - // - Beyond cylinder radius and beyond two disc ends. - - const AZ::Vector3 cylinderAxis = cylinderAxisEndB - cylinderAxisEndA; - float halfLength = cylinderAxis.GetLength() * 0.5f; - const AZ::Vector3 cylinderAxisUnit = cylinderAxis.GetNormalized(); - - // get the center of the axis and the vector from center to the test point - const AZ::Vector3 centerPoint = (cylinderAxis * 0.5) + cylinderAxisEndA; - const AZ::Vector3 pointToCenter = point - centerPoint; - - // distance point is from center (projected onto axis) - // the abs here takes advantage of symmetry. - float x = fabsf(pointToCenter.Dot(cylinderAxisUnit)); - - // squared distance from point to center (hypotenuse) - float n2 = pointToCenter.GetLengthSq(); - - // squared distance from point to center perpendicular to axis (pythagorean) - float y2 = n2 - sqr(x); - - float distanceSquared = 0.f; - - if (x < halfLength) // point is between the two ends - { - if (y2 > sqr(radius)) // point is outside of radius - { - distanceSquared = sqr(sqrtf(y2) - radius); - } - // else point is inside cylinder, distance is zero. - } - else if (y2 < sqr(radius)) - { - // point is within radius - // point projects into a disc at either end, grab the "parallel" distance only - distanceSquared = sqr(x - halfLength); - } - else - { - // point is outside of radius - // point projects onto the edge of the disc, grab distance in two directions, - // combine "parallel" and "perpendicular" distances. - distanceSquared = sqr(sqrtf(y2) - radius) + sqr(x - halfLength); - } - - return distanceSquared; - } - - //---------------------------------------------------------------------------------- - // Distance: Point_AABB - //---------------------------------------------------------------------------------- - // Calculate the closest distance of a point to a AABB in 3d-space. - // The function returns the squared distance. - // optionally the closest point on the hull is calculated - // - // Example: - // float result = Distance::Point_AABBSq( pos, aabb ); - //---------------------------------------------------------------------------------- - template - ILINE F Point_AABBSq(const Vec3_tpl& vPoint, const AABB& aabb) - { - F fDist2 = 0; - - F min0Diff = (F)aabb.min[0] - (F)vPoint[0]; - fDist2 = (F)fsel(min0Diff, fDist2 + sqr(min0Diff), fDist2); - F max0Diff = (F)vPoint[0] - (F)aabb.max[0]; - fDist2 = (F)fsel(max0Diff, fDist2 + sqr(max0Diff), fDist2); - - F min1Diff = (F)aabb.min[1] - (F)vPoint[1]; - fDist2 = (F)fsel(min1Diff, fDist2 + sqr(min1Diff), fDist2); - F max1Diff = (F)vPoint[1] - (F)aabb.max[1]; - fDist2 = (F)fsel(max1Diff, fDist2 + sqr(max1Diff), fDist2); - - F min2Diff = (F)aabb.min[2] - (F)vPoint[2]; - fDist2 = (F)fsel(min2Diff, fDist2 + sqr(min2Diff), fDist2); - F max2Diff = (F)vPoint[2] - (F)aabb.max[2]; - fDist2 = (F)fsel(max2Diff, fDist2 + sqr(max2Diff), fDist2); - - return fDist2; - } - - template - ILINE F Point_AABBSq(const Vec3_tpl& vPoint, const AABB& aabb, Vec3_tpl& vClosest) - { - F fDist2 = Point_AABBSq(vPoint, aabb); - - vClosest = vPoint; - if (!iszero(fDist2)) - { - // vPoint is outside the AABB - vClosest.x = max(vClosest.x, aabb.min.x); - vClosest.x = min(vClosest.x, aabb.max.x); - vClosest.y = max(vClosest.y, aabb.min.y); - vClosest.y = min(vClosest.y, aabb.max.y); - vClosest.z = max(vClosest.z, aabb.min.z); - vClosest.z = min(vClosest.z, aabb.max.z); - } - else - { - // vPoint is inside the AABB - uint16 nSubBox = 0; - F fHalf = 2; - - F fMiddleX = ((aabb.max.x - aabb.min.x) / fHalf) + aabb.min.x; - F fMiddleY = ((aabb.max.y - aabb.min.y) / fHalf) + aabb.min.y; - F fMiddleZ = ((aabb.max.z - aabb.min.z) / fHalf) + aabb.min.z; - - if (vPoint.x < fMiddleX) - { - nSubBox |= 0x001; // Is Left - } - if (vPoint.y < fMiddleY) - { - nSubBox |= 0x010; // Is Rear - } - if (vPoint.z < fMiddleZ) - { - nSubBox |= 0x100; // Is Low - } - F fDistanceToX = 0; - F fDistanceToY = 0; - F fDistanceToZ = 0; - - F fNewX, fNewY, fNewZ; - - switch (nSubBox & 0xFFF) - { - case 0x000: - // Is Right/Front/Top - fDistanceToX = aabb.max.x - vPoint.x; - fDistanceToY = aabb.max.y - vPoint.y; - fDistanceToZ = aabb.max.z - vPoint.z; - - fNewX = aabb.max.x; - fNewY = aabb.max.y; - fNewZ = aabb.max.z; - - break; - case 0x001: - // Is Left/Front/Top - fDistanceToX = vPoint.x - aabb.min.x; - fDistanceToY = aabb.max.y - vPoint.y; - fDistanceToZ = aabb.max.z - vPoint.z; - - fNewX = aabb.min.x; - fNewY = aabb.max.y; - fNewZ = aabb.max.z; - - break; - case 0x010: - // Is Right/Rear/Top - fDistanceToX = aabb.max.x - vPoint.x; - fDistanceToY = vPoint.y - aabb.min.y; - fDistanceToZ = aabb.max.z - vPoint.z; - - fNewX = aabb.max.x; - fNewY = aabb.min.y; - fNewZ = aabb.max.z; - - break; - case 0x011: - // Is Left/Rear/Top - fDistanceToX = vPoint.x - aabb.min.x; - fDistanceToY = vPoint.y - aabb.min.y; - fDistanceToZ = aabb.max.z - vPoint.z; - - fNewX = aabb.min.x; - fNewY = aabb.min.y; - fNewZ = aabb.max.z; - - break; - case 0x100: - // Is Right/Front/Low - fDistanceToX = aabb.max.x - vPoint.x; - fDistanceToY = aabb.max.y - vPoint.y; - fDistanceToZ = vPoint.z - aabb.min.z; - - fNewX = aabb.max.x; - fNewY = aabb.max.y; - fNewZ = aabb.min.z; - - break; - case 0x101: - // Is Left/Front/Low - fDistanceToX = vPoint.x - aabb.min.x; - fDistanceToY = aabb.max.y - vPoint.y; - fDistanceToZ = vPoint.z - aabb.min.z; - - fNewX = aabb.min.x; - fNewY = aabb.max.y; - fNewZ = aabb.min.z; - - break; - case 0x110: - // Is Right/Rear/Low - fDistanceToX = aabb.max.x - vPoint.x; - fDistanceToY = vPoint.y - aabb.min.y; - fDistanceToZ = vPoint.z - aabb.min.z; - - fNewX = aabb.max.x; - fNewY = aabb.min.y; - fNewZ = aabb.min.z; - - break; - case 0x111: - // Is Left/Rear/Low - fDistanceToX = vPoint.x - aabb.min.x; - fDistanceToY = vPoint.y - aabb.min.y; - fDistanceToZ = vPoint.z - aabb.min.z; - - fNewX = aabb.min.x; - fNewY = aabb.min.y; - fNewZ = aabb.min.z; - - break; - default: - fNewX = fNewY = fNewZ = 0; - break; - } - - if (fDistanceToX < fDistanceToY && fDistanceToX < fDistanceToZ) - { - vClosest.x = fNewX; - } - - if (fDistanceToY < fDistanceToX && fDistanceToY < fDistanceToZ) - { - vClosest.y = fNewY; - } - - if (fDistanceToZ < fDistanceToX && fDistanceToZ < fDistanceToY) - { - vClosest.z = fNewZ; - } - - fDist2 = vClosest.GetSquaredDistance(vPoint); - } - return fDist2; - } - - //---------------------------------------------------------------------------------- - // Distance: Sphere_Triangle - //---------------------------------------------------------------------------------- - // Calculate the closest distance of a sphere to a triangle in 3d-space. - // The function returns the squared distance. If sphere and triangle overlaps, - // the returned distance is 0 - // - // Example: - // float result = Distance::Point_TriangleSq( pos, triangle ); - //---------------------------------------------------------------------------------- - template - ILINE F Sphere_TriangleSq(const ::Sphere& s, const Triangle_tpl& t) - { - F sqdistance = Distance::Point_TriangleSq(s.center, t) - (s.radius * s.radius); - if (sqdistance < 0) - { - sqdistance = 0; - } - return sqdistance; - } - - template - ILINE F Sphere_TriangleSq(const ::Sphere& s, const Triangle_tpl& t, Vec3_tpl& output) - { - F sqdistance = Distance::Point_TriangleSq(s.center, t, output) - (s.radius * s.radius); - if (sqdistance < 0) - { - sqdistance = 0; - } - return sqdistance; - } - - //---------------------------------------------------------------------------------- - /// Calculate squared distance between two line segments, along with the optional - /// parameters of the closest points - //---------------------------------------------------------------------------------- - template - ILINE F Lineseg_LinesegSq(const Lineseg& seg0, const Lineseg seg1, F* t0, F* t1) - { - Vec3 diff = seg0.start - seg1.start; - Vec3 delta0 = seg0.end - seg0.start; - Vec3 delta1 = seg1.end - seg1.start; - F fA00 = delta0.GetLengthSquared(); - F fA01 = -delta0.Dot(delta1); - F fA11 = delta1.GetLengthSquared(); - F fB0 = diff.Dot(delta0); - F fC = diff.GetLengthSquared(); - F fDet = abs(fA00 * fA11 - fA01 * fA01); - F fB1, fS, fT, fSqrDist, fTmp; - - if (fDet > (F) 0.0) - { - // line segments are not parallel - fB1 = -diff.Dot(delta1); - fS = fA01 * fB1 - fA11 * fB0; - fT = fA01 * fB0 - fA00 * fB1; - - if (fS >= (F)0.0) - { - if (fS <= fDet) - { - if (fT >= (F)0.0) - { - if (fT <= fDet) // region 0 (interior) - { - // minimum at two interior points of 3D lines - F fInvDet = ((F)1.0) / fDet; - fS *= fInvDet; - fT *= fInvDet; - fSqrDist = fS * (fA00 * fS + fA01 * fT + ((F)2.0) * fB0) + - fT * (fA01 * fS + fA11 * fT + ((F)2.0) * fB1) + fC; - } - else // region 3 (side) - { - fT = (F)1.0; - fTmp = fA01 + fB0; - if (fTmp >= (F)0.0) - { - fS = (F)0.0; - fSqrDist = fA11 + ((F)2.0) * fB1 + fC; - } - else if (-fTmp >= fA00) - { - fS = (F)1.0; - fSqrDist = fA00 + fA11 + fC + ((F)2.0) * (fB1 + fTmp); - } - else - { - fS = -fTmp / fA00; - fSqrDist = fTmp * fS + fA11 + ((F)2.0) * fB1 + fC; - } - } - } - else // region 7 (side) - { - fT = (F)0.0; - if (fB0 >= (F)0.0) - { - fS = (F)0.0; - fSqrDist = fC; - } - else if (-fB0 >= fA00) - { - fS = (F)1.0; - fSqrDist = fA00 + ((F)2.0) * fB0 + fC; - } - else - { - fS = -fB0 / fA00; - fSqrDist = fB0 * fS + fC; - } - } - } - else - { - if (fT >= (F)0.0) - { - if (fT <= fDet) // region 1 (side) - { - fS = (F)1.0; - fTmp = fA01 + fB1; - if (fTmp >= (F)0.0) - { - fT = (F)0.0; - fSqrDist = fA00 + ((F)2.0) * fB0 + fC; - } - else if (-fTmp >= fA11) - { - fT = (F)1.0; - fSqrDist = fA00 + fA11 + fC + ((F)2.0) * (fB0 + fTmp); - } - else - { - fT = -fTmp / fA11; - fSqrDist = fTmp * fT + fA00 + ((F)2.0) * fB0 + fC; - } - } - else // region 2 (corner) - { - fTmp = fA01 + fB0; - if (-fTmp <= fA00) - { - fT = (F)1.0; - if (fTmp >= (F)0.0) - { - fS = (F)0.0; - fSqrDist = fA11 + ((F)2.0) * fB1 + fC; - } - else - { - fS = -fTmp / fA00; - fSqrDist = fTmp * fS + fA11 + ((F)2.0) * fB1 + fC; - } - } - else - { - fS = (F)1.0; - fTmp = fA01 + fB1; - if (fTmp >= (F)0.0) - { - fT = (F)0.0; - fSqrDist = fA00 + ((F)2.0) * fB0 + fC; - } - else if (-fTmp >= fA11) - { - fT = (F)1.0; - fSqrDist = fA00 + fA11 + fC + - ((F)2.0) * (fB0 + fTmp); - } - else - { - fT = -fTmp / fA11; - fSqrDist = fTmp * fT + fA00 + ((F)2.0) * fB0 + fC; - } - } - } - } - else // region 8 (corner) - { - if (-fB0 < fA00) - { - fT = (F)0.0; - if (fB0 >= (F)0.0) - { - fS = (F)0.0; - fSqrDist = fC; - } - else - { - fS = -fB0 / fA00; - fSqrDist = fB0 * fS + fC; - } - } - else - { - fS = (F)1.0; - fTmp = fA01 + fB1; - if (fTmp >= (F)0.0) - { - fT = (F)0.0; - fSqrDist = fA00 + ((F)2.0) * fB0 + fC; - } - else if (-fTmp >= fA11) - { - fT = (F)1.0; - fSqrDist = fA00 + fA11 + fC + ((F)2.0) * (fB0 + fTmp); - } - else - { - fT = -fTmp / fA11; - fSqrDist = fTmp * fT + fA00 + ((F)2.0) * fB0 + fC; - } - } - } - } - } - else - { - if (fT >= (F)0.0) - { - if (fT <= fDet) // region 5 (side) - { - fS = (F)0.0; - if (fB1 >= (F)0.0) - { - fT = (F)0.0; - fSqrDist = fC; - } - else if (-fB1 >= fA11) - { - fT = (F)1.0; - fSqrDist = fA11 + ((F)2.0) * fB1 + fC; - } - else - { - fT = -fB1 / fA11; - fSqrDist = fB1 * fT + fC; - } - } - else // region 4 (corner) - { - fTmp = fA01 + fB0; - if (fTmp < (F)0.0) - { - fT = (F)1.0; - if (-fTmp >= fA00) - { - fS = (F)1.0; - fSqrDist = fA00 + fA11 + fC + ((F)2.0) * (fB1 + fTmp); - } - else - { - fS = -fTmp / fA00; - fSqrDist = fTmp * fS + fA11 + ((F)2.0) * fB1 + fC; - } - } - else - { - fS = (F)0.0; - if (fB1 >= (F)0.0) - { - fT = (F)0.0; - fSqrDist = fC; - } - else if (-fB1 >= fA11) - { - fT = (F)1.0; - fSqrDist = fA11 + ((F)2.0) * fB1 + fC; - } - else - { - fT = -fB1 / fA11; - fSqrDist = fB1 * fT + fC; - } - } - } - } - else // region 6 (corner) - { - if (fB0 < (F)0.0) - { - fT = (F)0.0; - if (-fB0 >= fA00) - { - fS = (F)1.0; - fSqrDist = fA00 + ((F)2.0) * fB0 + fC; - } - else - { - fS = -fB0 / fA00; - fSqrDist = fB0 * fS + fC; - } - } - else - { - fS = (F)0.0; - if (fB1 >= (F)0.0) - { - fT = (F)0.0; - fSqrDist = fC; - } - else if (-fB1 >= fA11) - { - fT = (F)1.0; - fSqrDist = fA11 + ((F)2.0) * fB1 + fC; - } - else - { - fT = -fB1 / fA11; - fSqrDist = fB1 * fT + fC; - } - } - } - } - } - else - { - // line segments are parallel - if (fA01 > (F)0.0) - { - // direction vectors form an obtuse angle - if (fB0 >= (F)0.0) - { - fS = (F)0.0; - fT = (F)0.0; - fSqrDist = fC; - } - else if (-fB0 <= fA00) - { - fS = -fB0 / fA00; - fT = (F)0.0; - fSqrDist = fB0 * fS + fC; - } - else - { - fB1 = -diff.Dot(delta1); - fS = (F)1.0; - fTmp = fA00 + fB0; - if (-fTmp >= fA01) - { - fT = (F)1.0; - fSqrDist = fA00 + fA11 + fC + ((F)2.0) * (fA01 + fB0 + fB1); - } - else - { - fT = -fTmp / fA01; - fSqrDist = fA00 + ((F)2.0) * fB0 + fC + fT * (fA11 * fT + - ((F)2.0) * (fA01 + fB1)); - } - } - } - else - { - // direction vectors form an acute angle - if (-fB0 >= fA00) - { - fS = (F)1.0; - fT = (F)0.0; - fSqrDist = fA00 + ((F)2.0) * fB0 + fC; - } - else if (fB0 <= (F)0.0) - { - fS = -fB0 / fA00; - fT = (F)0.0; - fSqrDist = fB0 * fS + fC; - } - else - { - fB1 = -diff.Dot(delta1); - fS = (F)0.0; - if (fB0 >= -fA01) - { - fT = (F)1.0; - fSqrDist = fA11 + ((F)2.0) * fB1 + fC; - } - else - { - fT = -fB0 / fA01; - fSqrDist = fC + fT * (((F)2.0) * fB1 + fA11 * fT); - } - } - } - } - - if (t0) - { - *t0 = fS; - } - - if (t1) - { - *t1 = fT; - } - - return abs(fSqrDist); - } - - /// Calculate distance between two line segments, along with the optional - /// parameters of the closest points - template - ILINE F Lineseg_Lineseg(const Lineseg& seg0, const Lineseg seg1, F* s, F* t) - { - return sqrt_tpl(Lineseg_LinesegSq(seg0, seg1, s, t)); - } - - //---------------------------------------------------------------------------------- - /// Squared distance from line segment to triangle. Optionally returns the parameters - /// describing the closest points - //---------------------------------------------------------------------------------- - template - ILINE F Lineseg_TriangleSq(const Lineseg_tpl& seg, const Triangle_tpl& triangle, - F* segT, F* triT0, F* triT1) - { - Vec3_tpl intersection; - if (Intersect::Lineseg_Triangle(seg, triangle.v0, triangle.v1, triangle.v2, intersection, segT)) - { - if (triT0 || triT1) - { - const Vec3_tpl v0v1 = triangle.v1 - triangle.v0; - Lineseg_tpl projPtOnV0V2(intersection, intersection - v0v1); - Lineseg_tpl v0v2(triangle.v0, triangle.v2); - Lineseg_LinesegSq(projPtOnV0V2, v0v2, triT0, triT1); - } - return 0.0f; - } - - // compare segment to all three edges of the triangle - F s, t, u; - F distEdgeSq = Distance::Lineseg_LinesegSq(seg, Lineseg(triangle.v0, triangle.v1), &s, &t); - F distSq = distEdgeSq; - if (segT) - { - *segT = s; - } - if (triT0) - { - *triT0 = t; - } - if (triT1) - { - *triT1 = 0.0f; - } - - distEdgeSq = Distance::Lineseg_LinesegSq(seg, Lineseg(triangle.v0, triangle.v2), &s, &t); - if (distEdgeSq < distSq) - { - distSq = distEdgeSq; - if (segT) - { - *segT = s; - } - if (triT0) - { - *triT0 = 0.0f; - } - if (triT1) - { - *triT1 = t; - } - } - distEdgeSq = Distance::Lineseg_LinesegSq(seg, Lineseg(triangle.v1, triangle.v2), &s, &t); - if (distEdgeSq < distSq) - { - distSq = distEdgeSq; - if (segT) - { - *segT = s; - } - if (triT0) - { - *triT0 = 1.0f - t; - } - if (triT1) - { - *triT1 = t; - } - } - - // compare segment end points to triangle interior - F startTriSq = Distance::Point_TriangleSq(seg.start, triangle, &t, &u); - if (startTriSq < distSq) - { - distSq = startTriSq; - if (segT) - { - *segT = 0.0f; - } - if (triT0) - { - *triT0 = t; - } - if (triT1) - { - *triT1 = u; - } - } - F endTriSq = Distance::Point_TriangleSq(seg.end, triangle, &t, &u); - if (endTriSq < distSq) - { - distSq = endTriSq; - if (segT) - { - *segT = 1.0f; - } - if (triT0) - { - *triT0 = t; - } - if (triT1) - { - *triT1 = u; - } - } - return distSq; - } - - /// Distance from line segment to triangle. Optionally returns the parameters - /// describing the closest points - template - ILINE F Lineseg_Triangle(const Lineseg_tpl& seg, const Triangle_tpl& triangle, - F* segT, F* triT0, F* triT1) - { - return sqrt_tpl(Lineseg_TriangleSq(seg, triangle, segT, triT0, triT1)); - } -} //namespace Distance - - -#endif // CRYINCLUDE_CRYCOMMON_CRY_GEODISTANCE_H diff --git a/Code/CryEngine/CryCommon/Cry_GeoIntersect.h b/Code/CryEngine/CryCommon/Cry_GeoIntersect.h deleted file mode 100644 index f3afba461f..0000000000 --- a/Code/CryEngine/CryCommon/Cry_GeoIntersect.h +++ /dev/null @@ -1,958 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Common intersection-tests - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_GEOINTERSECT_H -#define CRYINCLUDE_CRYCOMMON_CRY_GEOINTERSECT_H -#pragma once - - -#include - -namespace Intersect { - inline bool Ray_Plane(const Ray& ray, const Plane_tpl& plane, Vec3& output, bool bSingleSidePlane = true) - { - float cosine = plane.n | ray.direction; - - //REJECTION 1: if "line-direction" is perpendicular to "plane-normal", an intersection is not possible! That means ray is parallel - // to the plane - //REJECTION 2: if bSingleSidePlane == true we deal with single-sided planes. That means - // if "line-direction" is pointing in the same direction as "the plane-normal", - // an intersection is not possible! - if ((cosine == 0.0f) || // normal is orthogonal to vector, cant intersect - (bSingleSidePlane && (cosine > 0.0f))) // we are trying to find an intersection in the same direction as the plane normal - { - return false; - } - - float numer = plane.DistFromPlane(ray.origin); - float fLength = -numer / cosine; - output = ray.origin + (ray.direction * fLength); - //skip, if cutting-point is "behind" ray.origin - if (fLength < 0.0f) - { - return false; - } - - return true; //intersection occurred - } - - inline bool Line_Plane(const Line& line, const Plane_tpl& plane, Vec3& output, bool bSingleSidePlane = true) - { - float cosine = plane.n | line.direction; - - //REJECTION 1: if "line-direction" is perpendicular to "plane-normal", an intersection is not possible! That means ray is parallel - // to the plane - //REJECTION 2: if bSingleSidePlane == true we deal with single-sided planes. That means - // if "line-direction" is pointing in the same direction as "the plane-normal", - // an intersection is not possible! - if ((cosine == 0.0f) || // normal is orthogonal to vector, cant intersect - (bSingleSidePlane && (cosine > 0.0f))) // we are trying to find an intersection in the same direction as the plane normal - { - return false; - } - - //an intersection is possible: calculate the exact point! - float perpdist = plane | line.pointonline; - float pd_c = -perpdist / cosine; - output = line.pointonline + (line.direction * pd_c); - - return true; //intersection occurred - } - - // Algorithm description: - // http://softsurfer.com/Archive/algorithm_0104/algorithm_0104B.htm#Line-Plane%20Intersection - template - inline bool Segment_Plane(const Lineseg_tpl& segment, const Plane_tpl& plane, Vec3_tpl& vOutput, bool bSingleSidePlane = true) - { - Vec3_tpl vSegment = segment.end - segment.start; - T planeNormalDotSegment = plane.n | vSegment; - - //REJECTION 1: if "line-direction" is perpendicular to "plane-normal", an intersection is not possible! That means ray is parallel - // to the plane - //REJECTION 2: if bSingleSidePlane == true we deal with single-sided planes. That means - // if "line-direction" is pointing in the same direction as "the plane-normal", - // an intersection is not possible! - if ((planeNormalDotSegment == T(0)) || // normal is orthogonal to vector, cant intersect - (bSingleSidePlane && (planeNormalDotSegment > T(0)))) // we are trying to find an intersection in the same direction as the plane normal - { - return false; - } - - // n Dot (segment.start - closest_point_in_plane) = 1 * DistFromPlane(segment.start) * cos(0) = DistFromPlane(segment.start) - T distanceToStart = plane.DistFromPlane(segment.start); - T scale = -distanceToStart / planeNormalDotSegment; - vOutput = segment.start + (vSegment * scale); - - // skip, if segment start and ends in one side of the plane - if ((scale < T(0)) || (scale > T(1))) - { - return false; - } - - return true; //intersection occurred - } - - /// Intersection between two line segments in 2D (ignoring z coordinate). The two parametric - /// values are set to between 0 and 1 if intersection occurs. If intersection does not occur - /// their values will indicate the parametric values for intersection of the lines extended - /// beyond the segment lengths. Parallel lines will result in a negative result, but the parametric - /// values will both be equal to 0.5 - template - inline bool Lineseg_Lineseg2D(const Lineseg_tpl& lineA, const Lineseg_tpl& lineB, F& outA, F& outB) - { - const F Epsilon = (F)0.0000001; - - Vec3_tpl delta = lineB.start - lineA.start; - - Vec3_tpl dirA = lineA.end - lineA.start; - Vec3_tpl dirB = lineB.end - lineB.start; - - F det = dirA.x * dirB.y - dirA.y * dirB.x; - F detA = delta.x * dirB.y - delta.y * dirB.x; - F detB = delta.x * dirA.y - delta.y * dirA.x; - - F absDet = fabs_tpl(det); - - if (absDet >= Epsilon) - { - F invDet = (F)1.0 / det; - - F a = detA * invDet; - F b = detB * invDet; - outA = a; - outB = b; - - if ((a > (F)1.0) || (a < (F)0.0) || (b > (F)1.0) || (b < (F)0.0)) - { - return false; - } - } - else - { - outA = outB = (F)0.5; - - return false; - } - - return true; - } - - /// Calculates the intersection between a line segment and a polygon, in 2D (i.e. - /// ignoring z coordinate). The VecContainer should be a container of Vec3 such - /// that we can traverse it using iterators. intersectionPoint is set to the intersection - /// point or the end of the segment, if no intersection. - template - inline bool Lineseg_Polygon2D(const Lineseg& lineseg, VecIterator polygonBegin, VecIterator polygonEnd, Vec3& intersectionPoint, Vec3* pNormal = NULL, bool bForceNormalOutwards = false) - { - intersectionPoint = lineseg.end; - bool gotIntersection = false; - - float tmin = 1.0f; - - VecIterator iend = polygonEnd; - VecIterator li, linext; - Lineseg intersectSegment; - for (li = polygonBegin; li != iend; ++li) - { - linext = li; - ++linext; - if (linext == iend) - { - linext = polygonBegin; - } - Lineseg segmentPoly(*li, *linext); - float s, t; - if (Intersect::Lineseg_Lineseg2D(lineseg, segmentPoly, s, t)) - { - if (s < 0.00001f || s > 0.99999f || t < 0.00001f || t > 0.99999f) - { - continue; - } - if (s < tmin) - { - tmin = s; - gotIntersection = true; - intersectSegment = segmentPoly; - } - } - } - - intersectionPoint = lineseg.start + tmin * (lineseg.end - lineseg.start); - - if (pNormal && gotIntersection) - { - Vec3 vPolyseg = intersectSegment.end - intersectSegment.start; - Vec3 vIntSeg = (lineseg.end - lineseg.start); - pNormal->x = vPolyseg.y; - pNormal->y = -vPolyseg.x; - pNormal->z = 0; - pNormal->NormalizeSafe(); - // returns the normal towards the start point of the intersecting segment (if it's not forced to be outwards) - if (!bForceNormalOutwards && vIntSeg.Dot(*pNormal) > 0) - { - pNormal->x = -pNormal->x; - pNormal->y = -pNormal->y; - } - } - return gotIntersection; - } - - template - inline bool Lineseg_Polygon2D(const Lineseg& lineseg, const VecContainer& polygon, Vec3& intersectionPoint, Vec3* pNormal = NULL, bool bForceNormalOutwards = false) - { - return Lineseg_Polygon2D(lineseg, polygon.begin(), polygon.end(), intersectionPoint, pNormal, bForceNormalOutwards); - } - - /* - * calculates intersection between a line and a triangle. - * IMPORTANT: this is a single-sided intersection test. That means its not enough - * that the triangle and line overlap, its also important that the triangle - * is "visible" when you are looking along the line-direction. - * - * If you need a double-sided test, you'll have to call this function twice with - * reversed order of triangle vertices. - * - * return values - * if there is an intertection the functions return "true" and stores the - * 3d-intersection point in "output". if the function returns "false" the value in - * "output" is undefined - * - */ - inline bool Line_Triangle(const Line& line, const Vec3& v0, const Vec3& v1, const Vec3& v2, Vec3& output) - { - const float Epsilon = 0.0000001f; - - Vec3 edgeA = v1 - v0; - Vec3 edgeB = v2 - v0; - - Vec3 dir = line.direction; - - Vec3 p = dir.Cross(edgeA); - Vec3 t = line.pointonline - v0; - Vec3 q = t.Cross(edgeB); - - float dot = edgeB.Dot(p); - - float u = t.Dot(p); - float v = dir.Dot(q); - - float DotGreaterThanEpsilon = dot - Epsilon; - float VGreaterEqualThanZero = v; - float UGreaterEqualThanZero = u; - float UVLessThanDot = dot - (u + v); - float ULessThanDot = dot - u; - - float UVGreaterEqualThanZero = (float)fsel(VGreaterEqualThanZero, UGreaterEqualThanZero, VGreaterEqualThanZero); - float UUVLessThanDot = (float)fsel(UVLessThanDot, ULessThanDot, UVLessThanDot); - float BothGood = (float)fsel(UVGreaterEqualThanZero, UUVLessThanDot, UVGreaterEqualThanZero); - float AllGood = (float)fsel(DotGreaterThanEpsilon, BothGood, DotGreaterThanEpsilon); - - if (AllGood < 0.0f) - { - return false; - } - - float dt = edgeA.Dot(q) / dot; - - Vec3 result = (dir * dt) + line.pointonline; - output = result; - - return true; - } - - - - /* - * calculates intersection between a ray and a triangle. - * IMPORTANT: this is a single-sided intersection test. That means its not sufficient - * that the triangle and rayt overlap, its also important that the triangle - * is "visible" when you from the origin along the ray-direction. - * - * If you need a double-sided test, you'll have to call this function twice with - * reversed order of triangle vertices. - * - * return values - * if there is an intertection the functions return "true" and stores the - * 3d-intersection point in "output". if the function returns "false" the value in - * "output" is undefined - */ - inline bool Ray_Triangle(const Ray& ray, const Vec3& v0, const Vec3& v1, const Vec3& v2, Vec3& output) - { - const float Epsilon = 0.0000001f; - - Vec3 edgeA = v1 - v0; - Vec3 edgeB = v2 - v0; - - Vec3 dir = ray.direction; - - Vec3 p = dir.Cross(edgeA); - Vec3 t = ray.origin - v0; - Vec3 q = t.Cross(edgeB); - - float dot = edgeB.Dot(p); - - float u = t.Dot(p); - float v = dir.Dot(q); - - float DotGreaterThanEpsilon = dot - Epsilon; - float VGreaterEqualThanZero = v; - float UGreaterEqualThanZero = u; - float UVLessThanDot = dot - (u + v); - float ULessThanDot = dot - u; - - float UVGreaterEqualThanZero = (float)fsel(VGreaterEqualThanZero, UGreaterEqualThanZero, VGreaterEqualThanZero); - float UUVLessThanDot = (float)fsel(UVLessThanDot, ULessThanDot, UVLessThanDot); - float BothGood = (float)fsel(UVGreaterEqualThanZero, UUVLessThanDot, UVGreaterEqualThanZero); - float AllGood = (float)fsel(DotGreaterThanEpsilon, BothGood, DotGreaterThanEpsilon); - - if (AllGood < 0.0f) - { - return false; - } - - float dt = edgeA.Dot(q) / dot; - - Vec3 result = (dir * dt) + ray.origin; - output = result; - - float AfterStart = (result - ray.origin).Dot(dir); - - return AfterStart >= 0.0f; - } - - - - /* - * Description: - * Calculates intersection between a line-segment and a triangle. - * Remarks: - * IMPORTANT: this is a single-sided intersection test. That means its not sufficient - * that the triangle and line-segment overlap, its also important that the triangle - * is "visible" when you are looking along the linesegment from "start" to "end". - * Notes: - * If you need a double-sided test, you'll have to call this function twice with - * reversed order of triangle vertices. - * - * Return value: - * If there is an intertection the the functions return "true" and stores the - * 3d-intersection point in "output". if the function returns "false" the value in - * "output" is undefined. If pT is non-zero then if there is an intersection the "t-value" - * (from 0-1) is also returned (unmodified if there is no intersection). - */ - inline bool Lineseg_Triangle(const Lineseg& lineseg, const Vec3& v0, const Vec3& v1, const Vec3& v2, Vec3& output, - float* outT = 0) - { - const float Epsilon = 0.0000001f; - - Vec3 edgeA = v1 - v0; - Vec3 edgeB = v2 - v0; - - Vec3 dir = lineseg.end - lineseg.start; - - Vec3 p = dir.Cross(edgeA); - Vec3 t = lineseg.start - v0; - Vec3 q = t.Cross(edgeB); - - float dot = edgeB.Dot(p); - - float u = t.Dot(p); - float v = dir.Dot(q); - - float DotGreaterThanEpsilon = dot - Epsilon; - float VGreaterEqualThanZero = v; - float UGreaterEqualThanZero = u; - float UVLessThanDot = dot - (u + v); - float ULessThanDot = dot - u; - - float UVGreaterEqualThanZero = (float)fsel(VGreaterEqualThanZero, UGreaterEqualThanZero, VGreaterEqualThanZero); - float UUVLessThanDot = (float)fsel(UVLessThanDot, ULessThanDot, UVLessThanDot); - float BothGood = (float)fsel(UVGreaterEqualThanZero, UUVLessThanDot, UVGreaterEqualThanZero); - float AllGood = (float)fsel(DotGreaterThanEpsilon, BothGood, DotGreaterThanEpsilon); - - if (AllGood < 0.0f) - { - return false; - } - - float dt = edgeA.Dot(q) / dot; - - Vec3 result = (dir * dt) + lineseg.start; - output = result; - - float AfterStart = (result - lineseg.start).Dot(dir); - float BeforeEnd = -(result - lineseg.end).Dot(dir); - float Within = (float)fsel(AfterStart, BeforeEnd, AfterStart); - - if (outT) - { - *outT = dt; - } - - return Within >= 0.0f; - } - - - - - //---------------------------------------------------------------------------------- - // Ray_AABB - // - // just ONE intersection point is calculated, and thats the entry point - - // Lineseg and AABB are assumed to be in the same space - // - //--- 0x00 = no intersection (output undefined) -------------------------- - //--- 0x01 = intersection (intersection point in output) -------------- - //--- 0x02 = start of Lineseg is inside the AABB (ls.start is output) - //---------------------------------------------------------------------------------- - inline uint8 Ray_AABB(const Ray& ray, const AABB& aabb, Vec3& output1) - { - uint8 cflags; - float cosine; - Vec3 cut; - //-------------------------------------------------------------------------------------- - //---- check if "ray.origin" is inside of AABB --------------------------- - //-------------------------------------------------------------------------------------- - cflags = (ray.origin.x >= aabb.min.x) << 0; - cflags |= (ray.origin.x <= aabb.max.x) << 1; - cflags |= (ray.origin.y >= aabb.min.y) << 2; - cflags |= (ray.origin.y <= aabb.max.y) << 3; - cflags |= (ray.origin.z >= aabb.min.z) << 4; - cflags |= (ray.origin.z <= aabb.max.z) << 5; - if (cflags == 0x3f) - { - output1 = ray.origin; - return 0x02; - } - - //-------------------------------------------------------------------------------------- - //---- check intersection with planes ------------------------------ - //-------------------------------------------------------------------------------------- - for (int i = 0; i < 3; i++) - { - if ((ray.direction[i] > 0) && (ray.origin[i] < aabb.min[i])) - { - cosine = (-ray.origin[i] + aabb.min[i]) / ray.direction[i]; - cut[i] = aabb.min[i]; - cut[incm3(i)] = ray.origin[incm3(i)] + (ray.direction[incm3(i)] * cosine); - cut[decm3(i)] = ray.origin[decm3(i)] + (ray.direction[decm3(i)] * cosine); - if ((cut[incm3(i)] > aabb.min[incm3(i)]) && (cut[incm3(i)] < aabb.max[incm3(i)]) && (cut[decm3(i)] > aabb.min[decm3(i)]) && (cut[decm3(i)] < aabb.max[decm3(i)])) - { - output1 = cut; - return 0x01; - } - } - if ((ray.direction[i] < 0) && (ray.origin[i] > aabb.max[i])) - { - cosine = (+ray.origin[i] - aabb.max[i]) / ray.direction[i]; - cut[i] = aabb.max[i]; - cut[incm3(i)] = ray.origin[incm3(i)] - (ray.direction[incm3(i)] * cosine); - cut[decm3(i)] = ray.origin[decm3(i)] - (ray.direction[decm3(i)] * cosine); - if ((cut[incm3(i)] > aabb.min[incm3(i)]) && (cut[incm3(i)] < aabb.max[incm3(i)]) && (cut[decm3(i)] > aabb.min[decm3(i)]) && (cut[decm3(i)] < aabb.max[decm3(i)])) - { - output1 = cut; - return 0x01; - } - } - } - return 0x00;//no intersection - } - - - - //---------------------------------------------------------------------------------- - // Ray_OBB - // - // just ONE intersection point is calculated, and thats the entry point - - // Lineseg and OBB are assumed to be in the same space - // - //--- 0x00 = no intersection (output undefined) ---- - //--- 0x01 = intersection (intersection point in output) -------------- - //--- 0x02 = start of Lineseg is inside the OBB (ls.start is output) - //---------------------------------------------------------------------------------- - inline uint8 Ray_OBB(const Ray& ray, const Vec3& pos, const OBB& obb, Vec3& output1) - { - AABB aabb(obb.c - obb.h, obb.c + obb.h); - Ray aray((ray.origin - pos) * obb.m33, ray.direction * obb.m33); - - uint8 cflags; - float cosine; - Vec3 cut; - //-------------------------------------------------------------------------------------- - //---- check if "aray.origin" is inside of AABB --------------------------- - //-------------------------------------------------------------------------------------- - cflags = (aray.origin.x > aabb.min.x) << 0; - cflags |= (aray.origin.x < aabb.max.x) << 1; - cflags |= (aray.origin.y > aabb.min.y) << 2; - cflags |= (aray.origin.y < aabb.max.y) << 3; - cflags |= (aray.origin.z > aabb.min.z) << 4; - cflags |= (aray.origin.z < aabb.max.z) << 5; - if (cflags == 0x3f) - { - output1 = aray.origin; - return 0x02; - } - - //-------------------------------------------------------------------------------------- - //---- check intersection with planes ------------------------------ - //-------------------------------------------------------------------------------------- - for (int i = 0; i < 3; i++) - { - if ((aray.direction[i] > 0) && (aray.origin[i] < aabb.min[i])) - { - cosine = (-aray.origin[i] + aabb.min[i]) / aray.direction[i]; - cut[i] = aabb.min[i]; - cut[incm3(i)] = aray.origin[incm3(i)] + (aray.direction[incm3(i)] * cosine); - cut[decm3(i)] = aray.origin[decm3(i)] + (aray.direction[decm3(i)] * cosine); - if ((cut[incm3(i)] > aabb.min[incm3(i)]) && (cut[incm3(i)] < aabb.max[incm3(i)]) && (cut[decm3(i)] > aabb.min[decm3(i)]) && (cut[decm3(i)] < aabb.max[decm3(i)])) - { - output1 = obb.m33 * cut + pos; - return 0x01; - } - } - if ((aray.direction[i] < 0) && (aray.origin[i] > aabb.max[i])) - { - cosine = (+aray.origin[i] - aabb.max[i]) / aray.direction[i]; - cut[i] = aabb.max[i]; - cut[incm3(i)] = aray.origin[incm3(i)] - (aray.direction[incm3(i)] * cosine); - cut[decm3(i)] = aray.origin[decm3(i)] - (aray.direction[decm3(i)] * cosine); - if ((cut[incm3(i)] > aabb.min[incm3(i)]) && (cut[incm3(i)] < aabb.max[incm3(i)]) && (cut[decm3(i)] > aabb.min[decm3(i)]) && (cut[decm3(i)] < aabb.max[decm3(i)])) - { - output1 = obb.m33 * cut + pos; - return 0x01; - } - } - } - return 0x00;//no intersection - } - - //---------------------------------------------------------------------------------- - // Lineseg_AABB - // - // just ONE intersection point is calculated, and thats the entry point - - // Lineseg and AABB are assumed to be in the same space - // - //--- 0x00 = no intersection (output undefined) -------------------------- - //--- 0x01 = intersection (intersection point in output) -------------- - //--- 0x02 = start of Lineseg is inside the AABB (ls.start is output) - //---------------------------------------------------------------------------------- - inline uint8 Lineseg_AABB(const Lineseg& ls, const AABB& aabb, Vec3& output1) - { - uint8 cflags; - float cosine; - Vec3 cut; - Vec3 lnormal = (ls.start - ls.end).GetNormalized(); - //-------------------------------------------------------------------------------------- - //---- check if "ls.start" is inside of AABB --------------------------- - //-------------------------------------------------------------------------------------- - cflags = (ls.start.x > aabb.min.x) << 0; - cflags |= (ls.start.x < aabb.max.x) << 1; - cflags |= (ls.start.y > aabb.min.y) << 2; - cflags |= (ls.start.y < aabb.max.y) << 3; - cflags |= (ls.start.z > aabb.min.z) << 4; - cflags |= (ls.start.z < aabb.max.z) << 5; - if (cflags == 0x3f) - { - //ls.start is inside of aabb - output1 = ls.start; - return 0x02; - } - - //-------------------------------------------------------------------------------------- - //---- check intersection with x-planes ------------------------------ - //-------------------------------------------------------------------------------------- - if (lnormal.x) - { - if ((ls.start.x < aabb.min.x) && (ls.end.x > aabb.min.x)) - { - cosine = (-ls.start.x + (+aabb.min.x)) / lnormal.x; - cut(aabb.min.x, ls.start.y + (lnormal.y * cosine), ls.start.z + (lnormal.z * cosine)); - //check if cut-point is inside YZ-plane border - if ((cut.y > aabb.min.y) && (cut.y < aabb.max.y) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z)) - { - output1 = cut; - return 0x01; - } - } - if ((ls.start.x > aabb.max.x) && (ls.end.x < aabb.max.x)) - { - cosine = (+ls.start.x + (-aabb.max.x)) / lnormal.x; - cut(aabb.max.x, ls.start.y - (lnormal.y * cosine), ls.start.z - (lnormal.z * cosine)); - //check if cut-point is inside YZ-plane border - if ((cut.y > aabb.min.y) && (cut.y < aabb.max.y) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z)) - { - output1 = cut; - return 0x01; - } - } - } - //-------------------------------------------------------------------------------------- - //---- check intersection with z-planes ------------------------------ - //-------------------------------------------------------------------------------------- - if (lnormal.z) - { - if ((ls.start.z < aabb.min.z) && (ls.end.z > aabb.min.z)) - { - cosine = (-ls.start.z + (+aabb.min.z)) / lnormal.z; - cut(ls.start.x + (lnormal.x * cosine), ls.start.y + (lnormal.y * cosine), aabb.min.z); - //check if cut-point is inside XY-plane border - if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.y > aabb.min.y) && (cut.y < aabb.max.y)) - { - output1 = cut; - return 0x01; - } - } - if ((ls.start.z > aabb.max.z) && (ls.end.z < aabb.max.z)) - { - cosine = (+ls.start.z + (-aabb.max.z)) / lnormal.z; - cut(ls.start.x - (lnormal.x * cosine), ls.start.y - (lnormal.y * cosine), aabb.max.z); - //check if cut-point is inside XY-plane border - if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.y > aabb.min.y) && (cut.y < aabb.max.y)) - { - output1 = cut; - return 0x01; - } - } - } - //-------------------------------------------------------------------------------------- - //---- check intersection with y-planes ------------------------------ - //-------------------------------------------------------------------------------------- - if (lnormal.y) - { - if ((ls.start.y < aabb.min.y) && (ls.end.y > aabb.min.y)) - { - cosine = (-ls.start.y + (+aabb.min.y)) / lnormal.y; - cut(ls.start.x + (lnormal.x * cosine), aabb.min.y, ls.start.z + (lnormal.z * cosine)); - //check if cut-point is inside XZ-plane border - if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z)) - { - output1 = cut; - return 0x01; - } - } - if ((ls.start.y > aabb.max.y) && (ls.end.y < aabb.max.y)) - { - cosine = (+ls.start.y + (-aabb.max.y)) / lnormal.y; - cut(ls.start.x - (lnormal.x * cosine), aabb.max.y, ls.start.z - (lnormal.z * cosine)); - //check if cut-point is inside XZ-plane border - if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z)) - { - output1 = cut; - return 0x01; - } - } - } - //no intersection - return 0x00; - } - - - - //---------------------------------------------------------------------------------- - // Lineseg_OBB - // - // just ONE intersection point is calculated, and thats the entry point - - // Lineseg and OBB are assumed to be in the same space - // - //--- 0x00 = no intersection (output undefined) -------------------------- - //--- 0x01 = intersection (intersection point in output) -------------- - //--- 0x02 = start of Lineseg is inside the OBB (ls.start is output) - //---------------------------------------------------------------------------------- - inline uint8 Lineseg_OBB(const Lineseg& lseg, const Vec3& pos, const OBB& obb, Vec3& output1) - { - AABB aabb(obb.c - obb.h, obb.c + obb.h); - Lineseg ls((lseg.start - pos) * obb.m33, (lseg.end - pos) * obb.m33); - - uint8 cflags; - float cosine; - Vec3 cut; - Vec3 lnormal = (ls.start - ls.end).GetNormalized(); - //-------------------------------------------------------------------------------------- - //---- check if "ls.start" is inside of AABB --------------------------- - //-------------------------------------------------------------------------------------- - cflags = (ls.start.x > aabb.min.x) << 0; - cflags |= (ls.start.x < aabb.max.x) << 1; - cflags |= (ls.start.y > aabb.min.y) << 2; - cflags |= (ls.start.y < aabb.max.y) << 3; - cflags |= (ls.start.z > aabb.min.z) << 4; - cflags |= (ls.start.z < aabb.max.z) << 5; - if (cflags == 0x3f) - { - //ls.start is inside of aabb - output1 = obb.m33 * ls.start + pos; - return 0x02; - } - - //-------------------------------------------------------------------------------------- - //---- check intersection with x-planes ------------------------------ - //-------------------------------------------------------------------------------------- - if (lnormal.x) - { - if ((ls.start.x < aabb.min.x) && (ls.end.x > aabb.min.x)) - { - cosine = (-ls.start.x + (+aabb.min.x)) / lnormal.x; - cut(aabb.min.x, ls.start.y + (lnormal.y * cosine), ls.start.z + (lnormal.z * cosine)); - //check if cut-point is inside YZ-plane border - if ((cut.y > aabb.min.y) && (cut.y < aabb.max.y) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z)) - { - output1 = obb.m33 * cut + pos; - return 0x01; - } - } - if ((ls.start.x > aabb.max.x) && (ls.end.x < aabb.max.x)) - { - cosine = (+ls.start.x + (-aabb.max.x)) / lnormal.x; - cut(aabb.max.x, ls.start.y - (lnormal.y * cosine), ls.start.z - (lnormal.z * cosine)); - //check if cut-point is inside YZ-plane border - if ((cut.y > aabb.min.y) && (cut.y < aabb.max.y) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z)) - { - output1 = obb.m33 * cut + pos; - return 0x01; - } - } - } - //-------------------------------------------------------------------------------------- - //---- check intersection with z-planes ------------------------------ - //-------------------------------------------------------------------------------------- - if (lnormal.z) - { - if ((ls.start.z < aabb.min.z) && (ls.end.z > aabb.min.z)) - { - cosine = (-ls.start.z + (+aabb.min.z)) / lnormal.z; - cut(ls.start.x + (lnormal.x * cosine), ls.start.y + (lnormal.y * cosine), aabb.min.z); - //check if cut-point is inside XY-plane border - if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.y > aabb.min.y) && (cut.y < aabb.max.y)) - { - output1 = obb.m33 * cut + pos; - return 0x01; - } - } - if ((ls.start.z > aabb.max.z) && (ls.end.z < aabb.max.z)) - { - cosine = (+ls.start.z + (-aabb.max.z)) / lnormal.z; - cut(ls.start.x - (lnormal.x * cosine), ls.start.y - (lnormal.y * cosine), aabb.max.z); - //check if cut-point is inside XY-plane border - if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.y > aabb.min.y) && (cut.y < aabb.max.y)) - { - output1 = obb.m33 * cut + pos; - return 0x01; - } - } - } - //-------------------------------------------------------------------------------------- - //---- check intersection with y-planes ------------------------------ - //-------------------------------------------------------------------------------------- - if (lnormal.y) - { - if ((ls.start.y < aabb.min.y) && (ls.end.y > aabb.min.y)) - { - cosine = (-ls.start.y + (+aabb.min.y)) / lnormal.y; - cut(ls.start.x + (lnormal.x * cosine), aabb.min.y, ls.start.z + (lnormal.z * cosine)); - //check if cut-point is inside XZ-plane border - if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z)) - { - output1 = obb.m33 * cut + pos; - return 0x01; - } - } - if ((ls.start.y > aabb.max.y) && (ls.end.y < aabb.max.y)) - { - cosine = (+ls.start.y + (-aabb.max.y)) / lnormal.y; - cut(ls.start.x - (lnormal.x * cosine), aabb.max.y, ls.start.z - (lnormal.z * cosine)); - //check if cut-point is inside XZ-plane border - if ((cut.x > aabb.min.x) && (cut.x < aabb.max.x) && (cut.z > aabb.min.z) && (cut.z < aabb.max.z)) - { - output1 = obb.m33 * cut + pos; - return 0x01; - } - } - } - //no intersection - return 0x00; - } - - - - //---------------------------------------------------------------------------------- - //--- 0x00 = no intersection -------------------------- - //--- 0x01 = not possible -- - //--- 0x02 = not possible -- - //--- 0x03 = two intersection, lineseg has ENTRY and EXIT point -- - //---------------------------------------------------------------------------------- - - inline unsigned char Line_Sphere(const Line& line, const ::Sphere& s, Vec3& i0, Vec3& i1) - { - Vec3 end = line.pointonline + line.direction; - - float a = line.direction | line.direction; - float b = (line.direction | (line.pointonline - s.center)) * 2.0f; - float c = ((line.pointonline - s.center) | (line.pointonline - s.center)) - (s.radius * s.radius); - - float desc = (b * b) - (4 * a * c); - - unsigned char intersection = 0; - if (desc >= 0.0f) - { - float lamba0 = (-b - sqrt_tpl(desc)) / (2.0f * a); - //_stprintf(d3dApp.token,"lamba0: %20.12f",lamba0); - //d3dApp.m_pFont->DrawText( 2, d3dApp.PrintY, D3DCOLOR_ARGB(255,255,255,0), d3dApp.token ); d3dApp.PrintY+=20; - i0 = line.pointonline + ((end - line.pointonline) * lamba0); - intersection = 1; - - float lamba1 = (-b + sqrt_tpl(desc)) / (2.0f * a); - //_stprintf(d3dApp.token,"lamba1: %20.12f",lamba1); - //d3dApp.m_pFont->DrawText( 2, d3dApp.PrintY, D3DCOLOR_ARGB(255,255,255,0), d3dApp.token ); d3dApp.PrintY+=20; - i1 = line.pointonline + ((end - line.pointonline) * lamba1); - intersection |= 2; - } - - return intersection; - } - - - - //---------------------------------------------------------------------------------- - //--- 0x00 = no intersection -------------------------- - //--- 0x01 = not possible -- - //--- 0x02 = one intersection, lineseg has just an EXIT point but no ENTRY point (ls.start is inside the sphere) -- - //--- 0x03 = two intersection, lineseg has ENTRY and EXIT point -- - //---------------------------------------------------------------------------------- - - inline unsigned char Ray_Sphere(const Ray& ray, const ::Sphere& s, Vec3& i0, Vec3& i1) - { - Vec3 end = ray.origin + ray.direction; - float a = ray.direction | ray.direction; - float b = (ray.direction | (ray.origin - s.center)) * 2.0f; - float c = ((ray.origin - s.center) | (ray.origin - s.center)) - (s.radius * s.radius); - - float desc = (b * b) - (4 * a * c); - - unsigned char intersection = 0; - if (desc >= 0.0f) - { - float lamba0 = (-b - sqrt_tpl(desc)) / (2.0f * a); - // _stprintf(d3dApp.token,"lamba0: %20.12f",lamba0); - // d3dApp.m_pFont->DrawText( 2, d3dApp.PrintY, D3DCOLOR_ARGB(255,255,255,0), d3dApp.token ); d3dApp.PrintY+=20; - if (lamba0 > 0.0f) - { - i0 = ray.origin + ((end - ray.origin) * lamba0); - intersection = 1; - } - - float lamba1 = (-b + sqrt_tpl(desc)) / (2.0f * a); - // _stprintf(d3dApp.token,"lamba1: %20.12f",lamba1); - // d3dApp.m_pFont->DrawText( 2, d3dApp.PrintY, D3DCOLOR_ARGB(255,255,255,0), d3dApp.token ); d3dApp.PrintY+=20; - if (lamba1 > 0.0f) - { - i1 = ray.origin + ((end - ray.origin) * lamba1); - intersection |= 2; - } - } - return intersection; - } - - inline bool Ray_SphereFirst(const Ray& ray, const ::Sphere& s, Vec3& intPoint) - { - Vec3 p2; - unsigned char res = Ray_Sphere(ray, s, intPoint, p2); - if (res == 2) - { - intPoint = p2; - } - if (res > 1) - { - return true; - } - return false; - } - - - - //---------------------------------------------------------------------------------- - //--- 0x00 = no intersection -------------------------- - //--- 0x01 = one intersection, lineseg has just an ENTRY point but no EXIT point (ls.end is inside the sphere) -- - //--- 0x02 = one intersection, lineseg has just an EXIT point but no ENTRY point (ls.start is inside the sphere) -- - //--- 0x03 = two intersection, lineseg has ENTRY and EXIT point -- - //---------------------------------------------------------------------------------- - inline unsigned char Lineseg_Sphere(const Lineseg& ls, const ::Sphere& s, Vec3& i0, Vec3& i1) - { - Vec3 dir = (ls.end - ls.start); - - float a = dir | dir; - if (a == 0.0f) - { - return 0; - } - - float b = (dir | (ls.start - s.center)) * 2.0f; - float c = ((ls.start - s.center) | (ls.start - s.center)) - (s.radius * s.radius); - float desc = (b * b) - (4 * a * c); - - unsigned char intersection = 0; - if (desc >= 0.0f) - { - float lamba0 = (-b - sqrt_tpl(desc)) / (2.0f * a); - if (lamba0 > 0.0f) - { - i0 = ls.start + ((ls.end - ls.start) * lamba0); - //skip, if 1st cutting-point is "in front" of ls.end - if (((i0 - ls.end) | dir) > 0) - { - return 0; - } - intersection = 0x01; - } - - float lamba1 = (-b + sqrt_tpl(desc)) / (2.0f * a); - if (lamba1 > 0.0f) - { - i1 = ls.start + ((ls.end - ls.start) * lamba1); - //skip, if 2nd cutting-point is "in front" of ls.end (=ls.end is inside sphere) - if (((i1 - ls.end) | dir) > 0) - { - return intersection; - } - intersection |= 0x02; - } - } - return intersection; - } - - - inline bool Lineseg_SphereFirst(const Lineseg& lineseg, const ::Sphere& s, Vec3& intPoint) - { - Vec3 p2; - uint8 res = Lineseg_Sphere(lineseg, s, intPoint, p2); - if (res == 2) - { - intPoint = p2; - } - if (res > 1) - { - return true; - } - return false; - } -}; //CIntersect - - - - - - - - - - - - - - -#endif // CRYINCLUDE_CRYCOMMON_CRY_GEOINTERSECT_H diff --git a/Code/CryEngine/CryCommon/Cry_GeoOverlap.h b/Code/CryEngine/CryCommon/Cry_GeoOverlap.h deleted file mode 100644 index 3c469aacf0..0000000000 --- a/Code/CryEngine/CryCommon/Cry_GeoOverlap.h +++ /dev/null @@ -1,2039 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Common overlap-tests - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_GEOOVERLAP_H -#define CRYINCLUDE_CRYCOMMON_CRY_GEOOVERLAP_H -#pragma once - -#include -#include - -namespace Distance -{ - template - ILINE F Point_TriangleSq(const Vec3_tpl& p, const Triangle_tpl& t); - template - ILINE F Point_Lineseg2DSq(Vec3_tpl p, Lineseg lineseg, F& fT); - simdf Point_TriangleByPointsSq(const hwvec3& p, const hwvec3& t0, const hwvec3& t1, const hwvec3& t2); -} - - -namespace Overlap { - ILINE void FINDMINMAX(const f32 x0, const f32 x1, const f32 x2, f32& min_value, f32& max_value) - { - min_value = max_value = x0; - min_value = min(x1, min_value); - max_value = max(x1, max_value); - min_value = min(x2, min_value); - max_value = max(x2, max_value); - } - - inline bool Lineseg_AABB2D(const Lineseg&, const AABB&); - ILINE bool AABB_AABB2D(const AABB&, const AABB&); - - //////////////////////////////////////////////////////////////// - // Checks if the point is inside an AABB - /* inline bool Point_AABB(const Vec3 &p, const Vec3 &mins,const Vec3 &maxs) - { - if ((p.x>=mins.x && p.x<=maxs.x) && (p.y>=mins.y && p.y<=maxs.y) && (p.z>=mins.z && p.z<=maxs.z)) return (true); - return (false); - }*/ - - // Description: - // Checks if the point is inside an AABB - // The min value of the AABB is inclusive - // The max value of the AABB is exclusive - ILINE bool Point_AABB(const Vec3& p, const AABB& aabb) - { - return ((p.x >= aabb.min.x && p.x < aabb.max.x) && (p.y >= aabb.min.y && p.y < aabb.max.y) && (p.z >= aabb.min.z && p.z < aabb.max.z)); - } - - // Description: - // Checks if the point is inside a 2D AABB - // The min value of the AABB is inclusive - // The max value of the AABB is exclusive - template - ILINE bool Point_AABB2D(const PtType& p, const AABB& aabb) - { - return ((p.x >= aabb.min.x && p.x < aabb.max.x) && (p.y >= aabb.min.y && p.y < aabb.max.y)); - } - - // Description: - // Checks if the point is inside an AABB - // The min and max value of the AABB is inclusive - ILINE bool Point_AABB_MaxInclusive(const Vec3& p, const AABB& aabb) - { - return ((p.x >= aabb.min.x && p.x <= aabb.max.x) && (p.y >= aabb.min.y && p.y <= aabb.max.y) && (p.z >= aabb.min.z && p.z <= aabb.max.z)); - } - - // Description: - // Checks if the point is inside a 2D AABB - // The min and max value of the AABB is inclusive - template - ILINE bool Point_AABB2D_MaxInclusive(const PtType& p, const AABB& aabb) - { - return ((p.x >= aabb.min.x && p.x <= aabb.max.x) && (p.y >= aabb.min.y && p.y <= aabb.max.y)); - } - - // Description: - // Checks if a point is inside an OBB. - // Example: - // bool result=Overlap::Point_OBB( point, obb ); - ILINE bool Point_OBB(const Vec3& p, const Vec3& wpos, const OBB& obb) - { - AABB aabb = AABB(obb.c - obb.h, obb.c + obb.h); - Vec3 t = (p - wpos) * obb.m33; - return ((t.x >= aabb.min.x && t.x <= aabb.max.x) && (t.y >= aabb.min.y && t.y <= aabb.max.y) && (t.z >= aabb.min.z && t.z <= aabb.max.z)); - } - - // Description: - // Checks if a point is inside a sphere. - // Example: - // bool result=Overlap::Point_Sphere( point, sphere ); - ILINE bool Point_Sphere(const Vec3& p, const ::Sphere& s) - { - Vec3 distc = p - s.center; - f32 sqrad = s.radius * s.radius; - return (sqrad > (distc | distc)); - } - - /// Two line segments, in 2D (ignore z) - inline bool Lineseg_Lineseg2D(const Lineseg& lineA, const Lineseg& lineB) - { - const float Epsilon = 0.0000001f; - - Vec3 delta = lineB.start - lineA.start; - - Vec3 dirA = lineA.end - lineA.start; - Vec3 dirB = lineB.end - lineB.start; - - float det = dirA.x * dirB.y - dirA.y * dirB.x; - float detA = delta.x * dirB.y - delta.y * dirB.x; - float detB = delta.x * dirA.y - delta.y * dirA.x; - - float absDet = fabs_tpl(det); - - if (absDet >= Epsilon) - { - float invDet = 1.0f / det; - - float a = detA * invDet; - float b = detB * invDet; - - if ((a > 1.0f) || (a < 0.0f) || (b > 1.0f) || (b < 0.0f)) - { - return false; - } - } - else - { - return false; - } - - return true; - } - - - - /// Check if a point is within a polygon, in 2D (i.e. ignoring z coordinate) - /// The VecContainer should be a container of Vec3_tpl such that we can traverse - /// it using iterators. - /// - /// This works by checking all the lines that start/end above/below the point - /// and counting how many have the point on the right/left side. If the - /// point is inside, then left/right counts should be odd - if outside then - /// even. If it's on the edge then this algorithm will return an arbitrary - /// result. This is basically the same as casting a ray horizontally and - /// counting the intersections. - /// Don't mess with putting tolerances etc in this code, or chaning the < - /// to <= etc in case you're worried about the "ray" going through a vertex. - /// the only issue is when the point is on the edge - if you're worried about - /// that then use the separate function that indicates if a point is within - /// a certain tolerance of an edge. - template - inline bool Point_Polygon2D(const PtType& p, const VecContainer& polygon, const AABB* pAABBPolygon = 0) - { - if (pAABBPolygon && !Overlap::Point_AABB2D(p, *pAABBPolygon)) - { - return false; - } - - int count = 0; - - typename VecContainer::const_iterator li, linext; - typename VecContainer::const_iterator liend = polygon.end(); - for (li = polygon.begin(); li != liend; ++li) - { - linext = li; - ++linext; - if (linext == liend) - { - linext = polygon.begin(); - } - const PtType& l0 = *li; - const PtType& l1 = *linext; - - if ((((l1.y <= p.y) && (p.y < l0.y)) || - ((l0.y <= p.y) && (p.y < l1.y))) && - (p.x < (l0.x - l1.x) * (p.y - l1.y) / (l0.y - l1.y) + l1.x)) - { - count = !count; - } - } - return (0 != count); - } - - template - inline bool Point_Polygon2D(const PtType& p, const PtType* polygon, size_t vertexCount, const AABB* pAABBPolygon = 0) - { - if (pAABBPolygon && !Overlap::Point_AABB2D(p, *pAABBPolygon)) - { - return false; - } - - bool count = false; - - for (size_t i = 0; i < vertexCount; ++i) - { - const PtType l0 = polygon[i % vertexCount]; - const PtType l1 = polygon[(i + 1) % vertexCount]; - - if ((((l1.y <= p.y) && (p.y < l0.y)) || - ((l0.y <= p.y) && (p.y < l1.y))) && - (p.x < (l0.x - l1.x) * (p.y - l1.y) / (l0.y - l1.y) + l1.x)) - { - count = !count; - } - } - - return count; - } - - - template - inline bool Circle_Polygon2D(const Vec3_tpl& p, F radius, const VecContainer& polygon) - { - if (Overlap::Point_Polygon2D(p, polygon)) - { - return true; - } - typename VecContainer::const_iterator li, linext; - typename VecContainer::const_iterator liend = polygon.end(); - for (li = polygon.begin(); li != liend; ++li) - { - linext = li; - ++linext; - if (linext == liend) - { - linext = polygon.begin(); - } - const Vec3_tpl& l0 = *li; - const Vec3_tpl& l1 = *linext; - float junk; - if (Distance::Point_Lineseg2DSq(p, Lineseg(l0, l1), junk) < square(radius)) - { - return true; - } - } - return false; - } - /// Checks if a line segment overlaps a polygon (defined by a container of sorted - /// points) in 2D (ignoring z). If you know the polygon AABB pass it in (z is ignored) - template - inline bool Lineseg_Polygon2D(const Lineseg& lineseg, - const VecContainer& polygon, - const AABB* pAABBPolygon = 0) - { - if (pAABBPolygon && !Overlap::Lineseg_AABB2D(lineseg, *pAABBPolygon)) - { - return false; - } - - typename VecContainer::const_iterator it; - for (it = polygon.begin(); it != polygon.end(); ++it) - { - typename VecContainer::const_iterator itNext = it; - ++itNext; - if (itNext == polygon.end()) - { - itNext = polygon.begin(); - } - - Lineseg polySeg(*it, *itNext); - if (Lineseg_Lineseg2D(lineseg, polySeg)) - { - return true; - } - } - return false; - } - - /// Checks for overlap of two polygons in 2D (ignoring z) - template - inline bool Polygon_Polygon2D(const VecContainerA& polygonA, const VecContainerB& polygonB, - const AABB* pAABBA = 0, const AABB* pAABBB = 0) - { - const typename VecContainerA::const_iterator itEndA = polygonA.end(); - const typename VecContainerB::const_iterator itEndB = polygonB.end(); - typename VecContainerA::const_iterator itA; - typename VecContainerB::const_iterator itB; - - AABB aabbA, aabbB; - if (!pAABBA) - { - pAABBA = &aabbA; - aabbA.Reset(); - for (itA = polygonA.begin(); itA != itEndA; ++itA) - { - aabbA.Add(*itA); - } - } - if (!pAABBB) - { - pAABBB = &aabbB; - aabbB.Reset(); - for (itB = polygonB.begin(); itB != itEndB; ++itB) - { - aabbB.Add(*itB); - } - } - - // AABB - if (!Overlap::AABB_AABB2D(*pAABBA, *pAABBB)) - { - return false; - } - - // points of A in B - for (itA = polygonA.begin(); itA != itEndA; ++itA) - { - if (Point_Polygon2D(*itA, polygonB, pAABBB)) - { - return true; - } - } - // points of B in A - for (itB = polygonB.begin(); itB != itEndB; ++itB) - { - if (Point_Polygon2D(*itB, polygonA, pAABBA)) - { - return true; - } - } - // segments of one A against B - for (itA = polygonA.begin(); itA != itEndA; ++itA) - { - typename VecContainerA::const_iterator itNext = itA; - ++itNext; - if (itNext == itEndA) - { - itNext = polygonA.begin(); - } - if (Lineseg_Polygon2D(Lineseg(*itA, *itNext), polygonB, pAABBB)) - { - return true; - } - } - return false; - } - - - /// Checks if a triangle (defined by three vertices) overlaps a polygon (defined - /// by a container of sorted points), all in 2D only (ignoring z). - template - inline bool Triangle_Polygon2D(const Vec3_tpl& p0, const Vec3_tpl& p1, const Vec3_tpl& p2, - const VecContainer& polygon) - { - // Check for triangle points within the poly - if (Point_Polygon2D(p0, polygon)) - { - return true; - } - if (Point_Polygon2D(p1, polygon)) - { - return true; - } - if (Point_Polygon2D(p2, polygon)) - { - return true; - } - - // check the poly points against the triangle - static std::vector triangle; - triangle.clear(); - triangle.push_back(p0); - triangle.push_back(p1); - triangle.push_back(p2); - - typename VecContainer::const_iterator it; - for (it = polygon.begin(); it != polygon.end(); ++it) - { - if (Point_Polygon2D(*it, triangle)) - { - return true; - } - } - - // finally check the edges - if (Overlap::Lineseg_Polygon2D(Lineseg(p0, p1), polygon)) - { - return true; - } - if (Overlap::Lineseg_Polygon2D(Lineseg(p1, p2), polygon)) - { - return true; - } - if (Overlap::Lineseg_Polygon2D(Lineseg(p2, p0), polygon)) - { - return true; - } - return false; - } - - //----------------------------------------------------------------------------------------- - - - //! check if a Lineseg and a Sphere overlap - inline bool Lineseg_Sphere(const Lineseg& ls, const ::Sphere& s) - { - float radius2 = s.radius * s.radius; - - //check if one of the two edpoints of the line is inside the sphere - Vec3 diff = ls.end - s.center; - if (diff.x * diff.x + diff.y * diff.y + diff.z * diff.z <= radius2) - { - return true; - } - - Vec3 AC = s.center - ls.start; - if (AC.x * AC.x + AC.y * AC.y + AC.z * AC.z <= radius2) - { - return true; - } - - //check distance from the sphere to the line - Vec3 AB = ls.end - ls.start; - - float r = (AC.x * AB.x + AC.y * AB.y + AC.z * AB.z) / (AB.x * AB.x + AB.y * AB.y + AB.z * AB.z); - - //projection falls outside the line - if (r < 0 || r > 1) - { - return false; - } - - //check if the distance from the line to the center of the sphere is less than radius - Vec3 point = ls.start + r * AB; - if ((point.x - s.center.x) * (point.x - s.center.x) + (point.y - s.center.y) * (point.y - s.center.y) + (point.z - s.center.z) * (point.z - s.center.z) > radius2) - { - return false; - } - - return true; - } - - - /*! - * we use the SEPARATING AXIS TEST to check if a Linesegment overlap an AABB. - * - * Example: - * bool result=Overlap::Lineseg_AABB( ls, pos,aabb ); - */ - inline bool Lineseg_AABB (const Lineseg& ls, const AABB& aabb) - { - //calculate the half-length-vectors of the AABB - Vec3 h = (aabb.max - aabb.min) * 0.5f; - //"t" is the transfer-vector from one center to the other - Vec3 t = (ls.start + ls.end) * 0.5f - (aabb.max + aabb.min) * 0.5f; - //calculate line-direction - Vec3 ld = (ls.end - ls.start) * 0.5f; - if (fabsf(t.x) > (h.x + fabsf(ld.x))) - { - return 0; - } - if (fabsf(t.y) > (h.y + fabsf(ld.y))) - { - return 0; - } - if (fabsf(t.z) > (h.z + fabsf(ld.z))) - { - return 0; - } - if (fabsf(t.z * ld.y - t.y * ld.z) > (fabsf(h.y * ld.z) + fabsf(h.z * ld.y))) - { - return 0; - } - if (fabsf(t.x * ld.z - t.z * ld.x) > (fabsf(h.x * ld.z) + fabsf(h.z * ld.x))) - { - return 0; - } - if (fabsf(t.y * ld.x - t.x * ld.y) > (fabsf(h.x * ld.y) + fabsf(h.y * ld.x))) - { - return 0; - } - return 1; //no separating axis found, objects overlap - } - - /// 2D seaparating axis test - ignores z - inline bool Lineseg_AABB2D (const Lineseg& ls, const AABB& aabb) - { - //calculate the half-length-vectors of the AABB - Vec3 h = (aabb.max - aabb.min) * 0.5f; - //"t" is the transfer-vector from one center to the other - Vec3 t = (ls.start + ls.end) * 0.5f - (aabb.max + aabb.min) * 0.5f; - //calculate line-direction - Vec3 ld = (ls.end - ls.start) * 0.5f; - if (fabsf(t.x) > (h.x + fabsf(ld.x))) - { - return 0; - } - if (fabsf(t.y) > (h.y + fabsf(ld.y))) - { - return 0; - } - if (fabsf(t.y * ld.x - t.x * ld.y) > (fabsf(h.x * ld.y) + fabsf(h.y * ld.x))) - { - return 0; - } - return 1; //no separating axis found, objects overlap - } - - - - /*! - * we use the SEPARATING AXIS TEST to check if two OBB's overlap. - * - * Example: - * bool result=Overlap::Lineseg_OBB( lineseg, pos,obb ); - */ - inline bool Lineseg_OBB (const Lineseg& ls, const Vec3& pos, const OBB& obb) - { - //the new center-position of Lineseg and OBB in world-space - Vec3 wposobb = obb.m33 * obb.c + pos; - Vec3 wposls = (ls.start + ls.end) * 0.5f; - //"t" is the transfer-vector from one center to the other - Vec3 t = (wposls - wposobb) * obb.m33; - //calculate line-direction in local obb-space - Vec3 ld = ((ls.end - ls.start) * obb.m33) * 0.5f; - if (fabsf(t.x) > (obb.h.x + fabsf(ld.x))) - { - return 0; - } - if (fabsf(t.y) > (obb.h.y + fabsf(ld.y))) - { - return 0; - } - if (fabsf(t.z) > (obb.h.z + fabsf(ld.z))) - { - return 0; - } - if (fabsf(t.z * ld.y - t.y * ld.z) > (fabsf(obb.h.y * ld.z) + fabsf(obb.h.z * ld.y))) - { - return 0; - } - if (fabsf(t.x * ld.z - t.z * ld.x) > (fabsf(obb.h.x * ld.z) + fabsf(obb.h.z * ld.x))) - { - return 0; - } - if (fabsf(t.y * ld.x - t.x * ld.y) > (fabsf(obb.h.x * ld.y) + fabsf(obb.h.y * ld.x))) - { - return 0; - } - return 1; //no separating axis found, objects overlap - } - - - - - /*! - * - * overlap-test between a line and a triangle. - * IMPORTANT: this is a single-sided test. That means its not enough - * that the triangle and line overlap, its also important that the triangle - * is "visible" when you are looking along the line-direction. - * - * If you need a double-sided test, you'll have to call this function twice with - * reversed order of triangle vertices. - * - * return values - * return "true" if line and triangle overlap. - * - */ - inline bool Line_Triangle(const Line& line, const Vec3& v0, const Vec3& v1, const Vec3& v2) - { - const float Epsilon = 0.0000001f; - - Vec3 edgeA = v1 - v0; - Vec3 edgeB = v2 - v0; - - Vec3 dir = line.direction; - - Vec3 p = dir.Cross(edgeA); - Vec3 t = line.pointonline - v0; - Vec3 q = t.Cross(edgeB); - - float dot = edgeB.Dot(p); - - float u = t.Dot(p); - float v = dir.Dot(q); - - float DotGreaterThanEpsilon = dot - Epsilon; - float VGreaterEqualThanZero = v; - float UGreaterEqualThanZero = u; - float UVLessThanDot = dot - (u + v); - float ULessThanDot = dot - u; - - float UVGreaterEqualThanZero = (float)fsel(VGreaterEqualThanZero, UGreaterEqualThanZero, VGreaterEqualThanZero); - float UUVLessThanDot = (float)fsel(UVLessThanDot, ULessThanDot, UVLessThanDot); - float BothGood = (float)fsel(UVGreaterEqualThanZero, UUVLessThanDot, UVGreaterEqualThanZero); - float AllGood = (float)fsel(DotGreaterThanEpsilon, BothGood, DotGreaterThanEpsilon); - - return AllGood >= 0.0f; - } - - - /*! - * - * overlap-test between a ray and a triangle. - * IMPORTANT: this is a single-sided test. That means its not sufficient - * that the triangle and ray overlap, its also important that the triangle - * is "visible" when you are looking from the origin along the ray-direction. - * - * If you need a double-sided test, you'll have to call this function twice with - * reversed order of triangle vertices. - * - * return values - * return "true" if ray and triangle overlap. - */ - inline bool Ray_Triangle(const Ray& ray, const Vec3& v0, const Vec3& v1, const Vec3& v2) - { - const float Epsilon = 0.0000001f; - - Vec3 edgeA = v1 - v0; - Vec3 edgeB = v2 - v0; - - Vec3 dir = ray.direction; - - Vec3 p = dir.Cross(edgeA); - Vec3 t = ray.origin - v0; - Vec3 q = t.Cross(edgeB); - - float dot = edgeB.Dot(p); - - float u = t.Dot(p); - float v = dir.Dot(q); - - float DotGreaterThanEpsilon = dot - Epsilon; - float VGreaterEqualThanZero = v; - float UGreaterEqualThanZero = u; - float UVLessThanDot = dot - (u + v); - float ULessThanDot = dot - u; - - float UVGreaterEqualThanZero = (float)fsel(VGreaterEqualThanZero, UGreaterEqualThanZero, VGreaterEqualThanZero); - float UUVLessThanDot = (float)fsel(UVLessThanDot, ULessThanDot, UVLessThanDot); - float BothGood = (float)fsel(UVGreaterEqualThanZero, UUVLessThanDot, UVGreaterEqualThanZero); - float AllGood = (float)fsel(DotGreaterThanEpsilon, BothGood, DotGreaterThanEpsilon); - - if (AllGood < 0.0f) - { - return false; - } - - float dt = edgeA.Dot(q) / dot; - - Vec3 result = (dir * dt) + ray.origin; - - float AfterStart = (result - ray.origin).Dot(dir); - - return AfterStart >= 0.0f; - } - - /*! - * - * overlap-test between line-segment and a triangle. - * IMPORTANT: this is a single-sided test. That means its not sufficient - * that the triangle and line-segment overlap, its also important that the triangle - * is "visible" when you are looking along the linesegment from "start" to "end". - * - * If you need a double-sided test, you'll have to call this function twice with - * reversed order of triangle vertices. - * - * return values - * return "true" if linesegment and triangle overlap. - */ - inline bool Lineseg_Triangle(const Lineseg& lineseg, const Vec3& v0, const Vec3& v1, const Vec3& v2) - { - const float Epsilon = 0.0000001f; - - Vec3 edgeA = v1 - v0; - Vec3 edgeB = v2 - v0; - - Vec3 dir = lineseg.end - lineseg.start; - - Vec3 p = dir.Cross(edgeA); - Vec3 t = lineseg.start - v0; - Vec3 q = t.Cross(edgeB); - - float dot = edgeB.Dot(p); - - float u = t.Dot(p); - float v = dir.Dot(q); - - float DotGreaterThanEpsilon = dot - Epsilon; - float VGreaterEqualThanZero = v; - float UGreaterEqualThanZero = u; - float UVLessThanDot = dot - (u + v); - float ULessThanDot = dot - u; - - float UVGreaterEqualThanZero = (float)fsel(VGreaterEqualThanZero, UGreaterEqualThanZero, VGreaterEqualThanZero); - float UUVLessThanDot = (float)fsel(UVLessThanDot, ULessThanDot, UVLessThanDot); - float BothGood = (float)fsel(UVGreaterEqualThanZero, UUVLessThanDot, UVGreaterEqualThanZero); - float AllGood = (float)fsel(DotGreaterThanEpsilon, BothGood, DotGreaterThanEpsilon); - - if (AllGood < 0.0f) - { - return false; - } - - float dt = edgeA.Dot(q) / dot; - - Vec3 result = (dir * dt) + lineseg.start; - - float AfterStart = (result - lineseg.start).Dot(dir); - float BeforeEnd = -(result - lineseg.end).Dot(dir); - float Within = (float)fsel(AfterStart, BeforeEnd, AfterStart); - - return Within >= 0.0f; - } - - /*---------------------------------------------------------------------------------- - * Sphere_AABB - * Sphere and AABB are assumed to be in the same space - * - * Example: - * bool result=Overlap::Sphere_AABB_Inside( sphere, aabb ); - * - * 0 = no overlap - * 1 = overlap - *----------------------------------------------------------------------------------*/ - ILINE bool Sphere_AABB(const ::Sphere& s, const AABB& aabb) - { - Vec3 center(s.center); - - Vec3 aabb_min(aabb.min); - Vec3 aabb_max(aabb.max); - - float radiusSq = s.radius * s.radius; - - float x = (float)fsel(aabb_min.x - center.x, center.x - aabb_min.x, fsel(center.x - aabb_max.x, center.x - aabb_max.x, 0.0f)); - float y = (float)fsel(aabb_min.y - center.y, center.y - aabb_min.y, fsel(center.y - aabb_max.y, center.y - aabb_max.y, 0.0f)); - float z = (float)fsel(aabb_min.z - center.z, center.z - aabb_min.z, fsel(center.z - aabb_max.z, center.z - aabb_max.z, 0.0f)); - - return (x * x + y * y + z * z) < radiusSq; - } - - // As Sphere_AABB but ignores z parts - ILINE bool Sphere_AABB2D(const ::Sphere& s, const AABB& aabb) - { - Vec3 center(s.center); - - Vec3 aabb_min(aabb.min); - Vec3 aabb_max(aabb.max); - - float radiusSq = s.radius * s.radius; - - float x = (float)fsel(aabb_min.x - center.x, center.x - aabb_min.x, fsel(center.x - aabb_max.x, center.x - aabb_max.x, 0.0f)); - float y = (float)fsel(aabb_min.y - center.y, center.y - aabb_min.y, fsel(center.y - aabb_max.y, center.y - aabb_max.y, 0.0f)); - - return (x * x + y * y) < radiusSq; - } - - - /*! - * - * conventional method to check if a Sphere and an AABB overlap, - * or if the Sphere is completely inside the AABB. - * Sphere and AABB are assumed to be in the same space - * - * Example: - * bool result=Overlap::Sphere_AABB_Inside( sphere, aabb ); - * - * return values: - * 0x00 = no overlap - * 0x01 = Sphere and AABB overlap - * 0x02 = Sphere in inside AABB - */ - ILINE char Sphere_AABB_Inside(const ::Sphere& s, const AABB& aabb) - { - if (Sphere_AABB(s, aabb)) - { - Vec3 amin = aabb.min - s.center; - Vec3 amax = aabb.max - s.center; - if (amin.x >= (-s.radius)) - { - return 1; - } - if (amin.y >= (-s.radius)) - { - return 1; - } - if (amin.z >= (-s.radius)) - { - return 1; - } - if (amax.x <= (+s.radius)) - { - return 1; - } - if (amax.y <= (+s.radius)) - { - return 1; - } - if (amax.z <= (+s.radius)) - { - return 1; - } - //yes, its inside - return 2; - } - return 0; - } - - //---------------------------------------------------------------------------------- - // Sphere_OBB - // VERY IMPORTANT: Sphere is assumed to be in the space of the OBB, otherwise it won't work - // - //--- 0 = no overlap --------------------------- - //--- 1 = overlap ----------------- - //---------------------------------------------------------------------------------- - inline bool Sphere_OBB(const ::Sphere& s, const OBB& obb) - { - //first we transform the sphere-center into the AABB-space of the OBB - Vec3 SphereInOBBSpace = s.center * obb.m33; - //the rest ist the same as the "Overlap::Sphere_AABB" calculation - float quatradius = s.radius * s.radius; - Vec3 quat(0, 0, 0); - AABB aabb = AABB(obb.c - obb.h, obb.c + obb.h); - if (SphereInOBBSpace.x < aabb.min.x) - { - quat.x = SphereInOBBSpace.x - aabb.min.x; - } - else if (SphereInOBBSpace.x > aabb.max.x) - { - quat.x = SphereInOBBSpace.x - aabb.max.x; - } - if (SphereInOBBSpace.y < aabb.min.y) - { - quat.y = SphereInOBBSpace.y - aabb.min.y; - } - else if (SphereInOBBSpace.y > aabb.max.y) - { - quat.y = SphereInOBBSpace.y - aabb.max.y; - } - if (SphereInOBBSpace.z < aabb.min.z) - { - quat.z = SphereInOBBSpace.z - aabb.min.z; - } - else if (SphereInOBBSpace.z > aabb.max.z) - { - quat.z = SphereInOBBSpace.z - aabb.max.z; - } - return((quat | quat) < quatradius); - } - - - //---------------------------------------------------------------------------------- - // Sphere_Sphere overlap test - // - //--- 0 = no overlap --------------------------- - //--- 1 = overlap ----------------- - //---------------------------------------------------------------------------------- - inline bool Sphere_Sphere(const ::Sphere& s1, const ::Sphere& s2) - { - Vec3 distc = s1.center - s2.center; - f32 sqrad = (s1.radius + s2.radius) * (s1.radius + s2.radius); - return (sqrad > (distc | distc)); - } - - ILINE bool HWVSphere_HWVSphere(const HWVSphere& s1, const HWVSphere& s2) - { - simdf fTotalRadius = SIMDFAdd(s1.radius, s2.radius); - hwvec3 distc = HWVSub(s1.center, s2.center); - simdf fTotalRadiusSqr = SIMDFMult(fTotalRadius, fTotalRadius); - simdf fDistanceSqr = HWV3Dot(distc, distc); - return SIMDFLessThanEqualB(fDistanceSqr, fTotalRadiusSqr); - } - - //---------------------------------------------------------------------------------- - // Sphere_Triangle overlap test - // - //--- 0 = no overlap --------------------------- - //--- 1 = overlap ----------------- - //---------------------------------------------------------------------------------- - template - ILINE bool Sphere_Triangle(const ::Sphere& s, const Triangle_tpl& t) - { - //create a "bouding sphere" around triangle for fast rejection test - Vec3_tpl middle = (t.v0 + t.v1 + t.v2) * (1 / 3.0f); - Vec3_tpl ov0 = t.v0 - middle; - Vec3_tpl ov1 = t.v1 - middle; - Vec3_tpl ov2 = t.v2 - middle; - F SqRad0 = (ov0 | ov0); - F SqRad1 = (ov1 | ov1); - F SqRad2 = (ov2 | ov2); - - SqRad0 = (F)fsel(SqRad0 - SqRad1, SqRad0, SqRad1); - SqRad0 = (F)fsel(SqRad0 - SqRad2, SqRad0, SqRad2); - - //first simple rejection-test... - if (Sphere_Sphere(s, ::Sphere(middle, sqrt_tpl(SqRad0))) == 0) - { - return 0; //overlap not possible - } - //...and now the hardcore-test! - if ((s.radius * s.radius) < Distance::Point_TriangleSq(s.center, t)) - { - return 0; - } - return 1; //sphere and triangle are overlapping - } - - ILINE bool HWVSphere_TriangleFromPoints(const HWVSphere& s, const hwvec3& t0, const hwvec3& t1, const hwvec3& t2) - { - //create a "bounding sphere" around triangle for fast rejection test - SIMDFConstant(fOneThird, 1.0f / 3.0f); - - hwvec3 middle = HWVMultiplySIMDF(HWVAdd(t0, HWVAdd(t1, t2)), fOneThird); - - hwvec3 ov0 = HWVSub(t0, middle); - hwvec3 ov1 = HWVSub(t1, middle); - hwvec3 ov2 = HWVSub(t2, middle); - - simdf SqRad0 = HWV3Dot(ov0, ov0); - simdf SqRad1 = HWV3Dot(ov1, ov1); - simdf SqRad2 = HWV3Dot(ov2, ov2); - - SqRad0 = SIMDFMax(SqRad0, SqRad1); - SqRad0 = SIMDFMax(SqRad0, SqRad2); - - //first simple rejection-test... - //if( HWVSphere_HWVSphere(s, HWVSphere(middle, SIMDFSqrtEstFast(SqRad0)))==0 ) - if (HWVSphere_HWVSphere(s, HWVSphere(middle, SIMDFSqrtEst(SqRad0))) == 0) - { - return 0; //overlap not possible - } - else - { - //...and now the hardcore-test! - simdf fRadiusSq = SIMDFMult(s.radius, s.radius); - simdf fDistToTriangleSq = Distance::Point_TriangleByPointsSq(s.center, t0, t1, t2); - - return SIMDFLessThanEqualB(fDistToTriangleSq, fRadiusSq); - } - } - - /*! - * - * we use the SEPARATING AXIS TEST to check if a triangle and AABB overlap. - * - * Example: - * bool result=Overlap::AABB_Triangle( pos,aabb, tv0,tv1,tv2 ); - * - */ - inline bool AABB_Triangle (const AABB& aabb, const Vec3& tv0, const Vec3& tv1, const Vec3& tv2) - { - //------ convert AABB into half-length AABB ----------- - Vec3 h = (aabb.max - aabb.min) * 0.5f; //calculate the half-length-vectors - Vec3 c = (aabb.max + aabb.min) * 0.5f; //the center is relative to the PIVOT - - //move everything so that the boxcenter is in (0,0,0) - Vec3 v0 = tv0 - c; - Vec3 v1 = tv1 - c; - Vec3 v2 = tv2 - c; - - //compute triangle edges - Vec3 e0 = v1 - v0; - Vec3 e1 = v2 - v1; - Vec3 e2 = v0 - v2; - - //-------------------------------------------------------------------------------------- - // use SEPARATING AXIS THEOREM to test overlap between AABB and triangle - // cross-product(edge from triangle, {x,y,z}-direction), this are 3x3=9 tests - //-------------------------------------------------------------------------------------- - float min, max, p0, p1, p2, rad, fex, fey, fez; - fex = fabsf(e0.x); - fey = fabsf(e0.y); - fez = fabsf(e0.z); - - //AXISTEST_X01(e0.z, e0.y, fez, fey); - p0 = e0.z * v0.y - e0.y * v0.z; - p2 = e0.z * v2.y - e0.y * v2.z; - if (p0 < p2) - { - min = p0; - max = p2; - } - else - { - min = p2; - max = p0; - } - rad = fez * h.y + fey * h.z; - if (min > rad || max < -rad) - { - return 0; - } - - //AXISTEST_Y02(e0.z, e0.x, fez, fex); - p0 = -e0.z * v0.x + e0.x * v0.z; - p2 = -e0.z * v2.x + e0.x * v2.z; - if (p0 < p2) - { - min = p0; - max = p2; - } - else - { - min = p2; - max = p0; - } - rad = fez * h.x + fex * h.z; - if (min > rad || max < -rad) - { - return 0; - } - - //AXISTEST_Z12(e0.y, e0.x, fey, fex); - p1 = e0.y * v1.x - e0.x * v1.y; - p2 = e0.y * v2.x - e0.x * v2.y; - if (p2 < p1) - { - min = p2; - max = p1; - } - else - { - min = p1; - max = p2; - } - rad = fey * h.x + fex * h.y; - if (min > rad || max < -rad) - { - return 0; - } - - //----------------------------------------------- - - fex = fabsf(e1.x); - fey = fabsf(e1.y); - fez = fabsf(e1.z); - //AXISTEST_X01(e1.z, e1.y, fez, fey); - p0 = e1.z * v0.y - e1.y * v0.z; - p2 = e1.z * v2.y - e1.y * v2.z; - if (p0 < p2) - { - min = p0; - max = p2; - } - else - { - min = p2; - max = p0; - } - rad = fez * h.y + fey * h.z; - if (min > rad || max < -rad) - { - return 0; - } - - //AXISTEST_Y02(e1.z, e1.x, fez, fex); - p0 = -e1.z * v0.x + e1.x * v0.z; - p2 = -e1.z * v2.x + e1.x * v2.z; - if (p0 < p2) - { - min = p0; - max = p2; - } - else - { - min = p2; - max = p0; - } - rad = fez * h.x + fex * h.z; - if (min > rad || max < -rad) - { - return 0; - } - - //AXISTEST_Z0(e1.y, e1.x, fey, fex); - p0 = e1.y * v0.x - e1.x * v0.y; - p1 = e1.y * v1.x - e1.x * v1.y; - if (p0 < p1) - { - min = p0; - max = p1; - } - else - { - min = p1; - max = p0; - } - rad = fey * h.x + fex * h.y; - if (min > rad || max < -rad) - { - return 0; - } - - //----------------------------------------------- - - fex = fabsf(e2.x); - fey = fabsf(e2.y); - fez = fabsf(e2.z); - //AXISTEST_X2(e2.z, e2.y, fez, fey); - p0 = e2.z * v0.y - e2.y * v0.z; - p1 = e2.z * v1.y - e2.y * v1.z; - if (p0 < p1) - { - min = p0; - max = p1; - } - else - { - min = p1; - max = p0; - } - rad = fez * h.y + fey * h.z; - if (min > rad || max < -rad) - { - return 0; - } - - //AXISTEST_Y1(e2.z, e2.x, fez, fex); - p0 = -e2.z * v0.x + e2.x * v0.z; - p1 = -e2.z * v1.x + e2.x * v1.z; - if (p0 < p1) - { - min = p0; - max = p1; - } - else - { - min = p1; - max = p0; - } - rad = fez * h.x + fex * h.z; - if (min > rad || max < -rad) - { - return 0; - } - - //AXISTEST_Z12(e2.y, e2.x, fey, fex); - p1 = e2.y * v1.x - e2.x * v1.y; - p2 = e2.y * v2.x - e2.x * v2.y; - if (p2 < p1) - { - min = p2; - max = p1; - } - else - { - min = p1; - max = p2; - } - rad = fey * h.x + fex * h.y; - if (min > rad || max < -rad) - { - return 0; - } - - //the {x,y,z}-directions (actually, since we use the AABB of the triangle we don't even need to test these) - //first test overlap in the {x,y,z}-directions - //find min, max of the triangle each direction, and test for overlap in that direction -- - //this is equivalent to testing a minimal AABB around the triangle against the AABB - AABB taabb; - FINDMINMAX(v0.x, v1.x, v2.x, taabb.min.x, taabb.max.x); - FINDMINMAX(v0.y, v1.y, v2.y, taabb.min.y, taabb.max.y); - FINDMINMAX(v0.z, v1.z, v2.z, taabb.min.z, taabb.max.z); - - //test in X-direction - FINDMINMAX(v0.x, v1.x, v2.x, taabb.min.x, taabb.max.x); - if (taabb.min.x > h.x || taabb.max.x < -h.x) - { - return 0; - } - - //test in Y-direction - FINDMINMAX(v0.y, v1.y, v2.y, taabb.min.y, taabb.max.y); - if (taabb.min.y > h.y || taabb.max.y < -h.y) - { - return 0; - } - - //test in Z-direction - FINDMINMAX(v0.z, v1.z, v2.z, taabb.min.z, taabb.max.z); - if (taabb.min.z > h.z || taabb.max.z < -h.z) - { - return 0; - } - - //test if the box intersects the plane of the triangle - //compute plane equation of triangle: normal*x+d=0 - Plane_tpl plane = Plane_tpl::CreatePlane((e0 % e1), v0); - - Vec3 vmin, vmax; - if (plane.n.x > 0.0f) - { - vmin.x = -h.x; - vmax.x = +h.x; - } - else - { - vmin.x = +h.x; - vmax.x = -h.x; - } - if (plane.n.y > 0.0f) - { - vmin.y = -h.y; - vmax.y = +h.y; - } - else - { - vmin.y = +h.y; - vmax.y = -h.y; - } - if (plane.n.z > 0.0f) - { - vmin.z = -h.z; - vmax.z = +h.z; - } - else - { - vmin.z = +h.z; - vmax.z = -h.z; - } - if ((plane | vmin) > 0.0f) - { - return 0; - } - if ((plane | vmax) < 0.0f) - { - return 0; - } - return 1; - } - - - - /*! - * - * we use the SEPARATING AXIS TEST to check if a triangle and an OBB overlaps. - * - * Example: - * bool result=Overlap::OBB_Trinagle( pos1,obb1, tv0,tv1,tv2 ); - * - */ - inline bool OBB_Triangle(const Vec3& pos, const OBB& obb, const Vec3& tv0, const Vec3& tv1, const Vec3& tv2) - { - Vec3 p = obb.m33 * obb.c + pos; //the new center-position in world-space - - //move everything so that the boxcenter is in (0,0,0) - Vec3 v0 = (tv0 - p) * obb.m33; //pre-transform - Vec3 v1 = (tv1 - p) * obb.m33; //pre-transform - Vec3 v2 = (tv2 - p) * obb.m33; //pre-transform - - - //compute triangle edges - Vec3 e0 = v1 - v0; - Vec3 e1 = v2 - v1; - Vec3 e2 = v0 - v2; - - //-------------------------------------------------------------------------------------- - // use SEPARATING AXIS THEOREM to test intersection between AABB and triangle - // cross-product(edge from triangle, {x,y,z}-direction), this are 3x3=9 tests - //-------------------------------------------------------------------------------------- - float min, max, p0, p1, p2, rad, fex, fey, fez; - fex = fabsf(e0.x); - fey = fabsf(e0.y); - fez = fabsf(e0.z); - - //AXISTEST_X01(e0.z, e0.y, fez, fey); - p0 = e0.z * v0.y - e0.y * v0.z; - p2 = e0.z * v2.y - e0.y * v2.z; - if (p0 < p2) - { - min = p0; - max = p2; - } - else - { - min = p2; - max = p0; - } - rad = fez * obb.h.y + fey * obb.h.z; - if (min > rad || max < -rad) - { - return 0; - } - - //AXISTEST_Y02(e0.z, e0.x, fez, fex); - p0 = -e0.z * v0.x + e0.x * v0.z; - p2 = -e0.z * v2.x + e0.x * v2.z; - if (p0 < p2) - { - min = p0; - max = p2; - } - else - { - min = p2; - max = p0; - } - rad = fez * obb.h.x + fex * obb.h.z; - if (min > rad || max < -rad) - { - return 0; - } - - //AXISTEST_Z12(e0.y, e0.x, fey, fex); - p1 = e0.y * v1.x - e0.x * v1.y; - p2 = e0.y * v2.x - e0.x * v2.y; - if (p2 < p1) - { - min = p2; - max = p1; - } - else - { - min = p1; - max = p2; - } - rad = fey * obb.h.x + fex * obb.h.y; - if (min > rad || max < -rad) - { - return 0; - } - - //----------------------------------------------- - - fex = fabsf(e1.x); - fey = fabsf(e1.y); - fez = fabsf(e1.z); - //AXISTEST_X01(e1.z, e1.y, fez, fey); - p0 = e1.z * v0.y - e1.y * v0.z; - p2 = e1.z * v2.y - e1.y * v2.z; - if (p0 < p2) - { - min = p0; - max = p2; - } - else - { - min = p2; - max = p0; - } - rad = fez * obb.h.y + fey * obb.h.z; - if (min > rad || max < -rad) - { - return 0; - } - - //AXISTEST_Y02(e1.z, e1.x, fez, fex); - p0 = -e1.z * v0.x + e1.x * v0.z; - p2 = -e1.z * v2.x + e1.x * v2.z; - if (p0 < p2) - { - min = p0; - max = p2; - } - else - { - min = p2; - max = p0; - } - rad = fez * obb.h.x + fex * obb.h.z; - if (min > rad || max < -rad) - { - return 0; - } - - //AXISTEST_Z0(e1.y, e1.x, fey, fex); - p0 = e1.y * v0.x - e1.x * v0.y; - p1 = e1.y * v1.x - e1.x * v1.y; - if (p0 < p1) - { - min = p0; - max = p1; - } - else - { - min = p1; - max = p0; - } - rad = fey * obb.h.x + fex * obb.h.y; - if (min > rad || max < -rad) - { - return 0; - } - - //----------------------------------------------- - - fex = fabsf(e2.x); - fey = fabsf(e2.y); - fez = fabsf(e2.z); - //AXISTEST_X2(e2.z, e2.y, fez, fey); - p0 = e2.z * v0.y - e2.y * v0.z; - p1 = e2.z * v1.y - e2.y * v1.z; - if (p0 < p1) - { - min = p0; - max = p1; - } - else - { - min = p1; - max = p0; - } - rad = fez * obb.h.y + fey * obb.h.z; - if (min > rad || max < -rad) - { - return 0; - } - - //AXISTEST_Y1(e2.z, e2.x, fez, fex); - p0 = -e2.z * v0.x + e2.x * v0.z; - p1 = -e2.z * v1.x + e2.x * v1.z; - if (p0 < p1) - { - min = p0; - max = p1; - } - else - { - min = p1; - max = p0; - } - rad = fez * obb.h.x + fex * obb.h.z; - if (min > rad || max < -rad) - { - return 0; - } - - //AXISTEST_Z12(e2.y, e2.x, fey, fex); - p1 = e2.y * v1.x - e2.x * v1.y; - p2 = e2.y * v2.x - e2.x * v2.y; - if (p2 < p1) - { - min = p2; - max = p1; - } - else - { - min = p1; - max = p2; - } - rad = fey * obb.h.x + fex * obb.h.y; - if (min > rad || max < -rad) - { - return 0; - } - - //the {x,y,z}-directions (actually, since we use the AABB of the triangle we don't even need to test these) - //first test overlap in the {x,y,z}-directions - //find min, max of the triangle each direction, and test for overlap in that direction -- - //this is equivalent to testing a minimal AABB around the triangle against the AABB - AABB taabb; - FINDMINMAX(v0.x, v1.x, v2.x, taabb.min.x, taabb.max.x); - FINDMINMAX(v0.y, v1.y, v2.y, taabb.min.y, taabb.max.y); - FINDMINMAX(v0.z, v1.z, v2.z, taabb.min.z, taabb.max.z); - - // test in X-direction - FINDMINMAX(v0.x, v1.x, v2.x, taabb.min.x, taabb.max.x); - if (taabb.min.x > obb.h.x || taabb.max.x < -obb.h.x) - { - return 0; - } - - // test in Y-direction - FINDMINMAX(v0.y, v1.y, v2.y, taabb.min.y, taabb.max.y); - if (taabb.min.y > obb.h.y || taabb.max.y < -obb.h.y) - { - return 0; - } - - // test in Z-direction - FINDMINMAX(v0.z, v1.z, v2.z, taabb.min.z, taabb.max.z); - if (taabb.min.z > obb.h.z || taabb.max.z < -obb.h.z) - { - return 0; - } - - //test if the box overlaps the plane of the triangle - //compute plane equation of triangle: normal*x+d=0 - Plane_tpl plane = Plane_tpl::CreatePlane((e0 % e1), v0); - - Vec3 vmin, vmax; - if (plane.n.x > 0.0f) - { - vmin.x = -obb.h.x; - vmax.x = +obb.h.x; - } - else - { - vmin.x = +obb.h.x; - vmax.x = -obb.h.x; - } - if (plane.n.y > 0.0f) - { - vmin.y = -obb.h.y; - vmax.y = +obb.h.y; - } - else - { - vmin.y = +obb.h.y; - vmax.y = -obb.h.y; - } - if (plane.n.z > 0.0f) - { - vmin.z = -obb.h.z; - vmax.z = +obb.h.z; - } - else - { - vmin.z = +obb.h.z; - vmax.z = -obb.h.z; - } - if ((plane | vmin) > 0.0f) - { - return 0; - } - if ((plane | vmax) < 0.0f) - { - return 0; - } - return 1; - } - - - - - - - - - - /*! - * - * conventional method to check if two AABB's overlap. - * both AABBs are assumed to be in the same space - * - * Example: - * bool result=Overlap::AABB_AABB( aabb1, aabb2 ); - * - */ - ILINE bool AABB_AABB(const AABB& aabb1, const AABB& aabb2) - { - if (aabb1.min.x >= aabb2.max.x) - { - return 0; - } - if (aabb1.min.y >= aabb2.max.y) - { - return 0; - } - if (aabb1.min.z >= aabb2.max.z) - { - return 0; - } - if (aabb1.max.x <= aabb2.min.x) - { - return 0; - } - if (aabb1.max.y <= aabb2.min.y) - { - return 0; - } - if (aabb1.max.z <= aabb2.min.z) - { - return 0; - } - return 1; //the aabb's overlap - } - - /// AABB overlap test - but ignores z values - ILINE bool AABB_AABB2D(const AABB& aabb1, const AABB& aabb2) - { - if (aabb1.min.x >= aabb2.max.x) - { - return 0; - } - if (aabb1.min.y >= aabb2.max.y) - { - return 0; - } - if (aabb1.max.x <= aabb2.min.x) - { - return 0; - } - if (aabb1.max.y <= aabb2.min.y) - { - return 0; - } - return 1; //the aabb's overlap - } - - - /*! - * - * Conventional method to check if two AABB's overlap. - * Both AABBs are in local object space. Used the position-vector - * to translate them into world-space - * - * Example: - * bool result=Overlap::AABB_AABB( pos1,aabb1, pos2,aabb2 ); - * - */ - ILINE bool AABB_AABB(const Vec3& pos1, const AABB& aabb1, const Vec3& pos2, const AABB& aabb2) - { - AABB waabb1(aabb1.min + pos1, aabb1.max + pos1); - AABB waabb2(aabb2.min + pos2, aabb2.max + pos2); - return AABB_AABB(waabb1, waabb2); - } - - - /*! - * - * conventional method to check if two AABB's overlap - * or if AABB1 is comletely inside AABB2. - * both AABBs are assumed to be in the same space - * - * Example: - * bool result=Overlap::AABB_AABB_Inside( aabb1, aabb2 ); - * - * return values: - * 0x00 = no overlap - * 0x01 = both AABBs one overlap - * 0x02 = AABB1 in inside AABB2 - */ - ILINE char AABB_AABB_Inside(const AABB& aabb1, const AABB& aabb2) - { - if (AABB_AABB(aabb1, aabb2)) - { - if (aabb1.min.x <= aabb2.min.x) - { - return 1; - } - if (aabb1.min.y <= aabb2.min.y) - { - return 1; - } - if (aabb1.min.z <= aabb2.min.z) - { - return 1; - } - if (aabb1.max.x >= aabb2.max.x) - { - return 1; - } - if (aabb1.max.y >= aabb2.max.y) - { - return 1; - } - if (aabb1.max.z >= aabb2.max.z) - { - return 1; - } - //yes, its inside - return 2; - } - return 0; - } - - - /*! - * - * we use the SEPARATING AXIS TEST to check if and AABB and an OBB overlap. - * - * Example: - * bool result=Overlap::AABB_OBB( aabb, pos,obb ); - * - */ - inline bool AABB_OBB (const AABB& aabb, const Vec3& pos, const OBB& obb) - { - Vec3 h = (aabb.max - aabb.min) * 0.5f; //calculate the half-length-vectors - Vec3 c = (aabb.max + aabb.min) * 0.5f; //the center in world-space - - //"t" is the transfer-vector from one center to the other - Vec3 t = obb.m33 * obb.c + pos - c; - - f32 ra, rb; - - //-------------------------------------------------------------------------- - //-- we use the vectors "1,0,0","0,1,0" and "0,0,1" as separating axis - //-------------------------------------------------------------------------- - rb = fabsf(obb.m33.m00 * obb.h.x) + fabsf(obb.m33.m01 * obb.h.y) + fabsf(obb.m33.m02 * obb.h.z); - if (fabsf(t.x) > (fabsf(h.x) + rb)) - { - return 0; - } - rb = fabsf(obb.m33.m10 * obb.h.x) + fabsf(obb.m33.m11 * obb.h.y) + fabsf(obb.m33.m12 * obb.h.z); - if (fabsf(t.y) > (fabsf(h.y) + rb)) - { - return 0; - } - rb = fabsf(obb.m33.m20 * obb.h.x) + fabsf(obb.m33.m21 * obb.h.y) + fabsf(obb.m33.m22 * obb.h.z); - if (fabsf(t.z) > (fabsf(h.z) + rb)) - { - return 0; - } - - //-------------------------------------------------------------------------- - //-- we use the orientation-vectors "Mx","My" and "Mz" as separating axis - //-------------------------------------------------------------------------- - ra = fabsf(obb.m33.m00 * h.x) + fabsf(obb.m33.m10 * h.y) + fabsf(obb.m33.m20 * h.z); - if (fabsf(t | Vec3(obb.m33.m00, obb.m33.m10, obb.m33.m20)) > (ra + obb.h.x)) - { - return 0; - } - ra = fabsf(obb.m33.m01 * h.x) + fabsf(obb.m33.m11 * h.y) + fabsf(obb.m33.m21 * h.z); - if (fabsf(t | Vec3(obb.m33.m01, obb.m33.m11, obb.m33.m21)) > (ra + obb.h.y)) - { - return 0; - } - ra = fabsf(obb.m33.m02 * h.x) + fabsf(obb.m33.m12 * h.y) + fabsf(obb.m33.m22 * h.z); - if (fabsf(t | Vec3(obb.m33.m02, obb.m33.m12, obb.m33.m22)) > (ra + obb.h.z)) - { - return 0; - } - - //--------------------------------------------------------------------- - //---- using 9 cross products we generate new separating axis - //--------------------------------------------------------------------- - const float e0 = h.x + h.y + h.z, e1 = obb.h.x + obb.h.y + obb.h.z, e = (e0 + e1 - fabsf(e0 - e1)) * 0.0001f; - ra = h.y * fabsf(obb.m33.m20) + h.z * fabsf(obb.m33.m10); - rb = obb.h.y * fabsf(obb.m33.m02) + obb.h.z * fabsf(obb.m33.m01); - if (fabsf(t.z * obb.m33.m10 - t.y * obb.m33.m20) > (ra + rb) + e) - { - return 0; - } - ra = h.y * fabsf(obb.m33.m21) + h.z * fabsf(obb.m33.m11); - rb = obb.h.x * fabsf(obb.m33.m02) + obb.h.z * fabsf(obb.m33.m00); - if (fabsf(t.z * obb.m33.m11 - t.y * obb.m33.m21) > (ra + rb) + e) - { - return 0; - } - ra = h.y * fabsf(obb.m33.m22) + h.z * fabsf(obb.m33.m12); - rb = obb.h.x * fabsf(obb.m33.m01) + obb.h.y * fabsf(obb.m33.m00); - if (fabsf(t.z * obb.m33.m12 - t.y * obb.m33.m22) > (ra + rb) + e) - { - return 0; - } - - - ra = h.x * fabsf(obb.m33.m20) + h.z * fabsf(obb.m33.m00); - rb = obb.h.y * fabsf(obb.m33.m12) + obb.h.z * fabsf(obb.m33.m11); - if (fabsf(t.x * obb.m33.m20 - t.z * obb.m33.m00) > (ra + rb) + e) - { - return 0; - } - ra = h.x * fabsf(obb.m33.m21) + h.z * fabsf(obb.m33.m01); - rb = obb.h.x * fabsf(obb.m33.m12) + obb.h.z * fabsf(obb.m33.m10); - if (fabsf(t.x * obb.m33.m21 - t.z * obb.m33.m01) > (ra + rb) + e) - { - return 0; - } - ra = h.x * fabsf(obb.m33.m22) + h.z * fabsf(obb.m33.m02); - rb = obb.h.x * fabsf(obb.m33.m11) + obb.h.y * fabsf(obb.m33.m10); - if (fabsf(t.x * obb.m33.m22 - t.z * obb.m33.m02) > (ra + rb) + e) - { - return 0; - } - - - ra = h.x * fabsf(obb.m33.m10) + h.y * fabsf(obb.m33.m00); - rb = obb.h.y * fabsf(obb.m33.m22) + obb.h.z * fabsf(obb.m33.m21); - if (fabsf(t.y * obb.m33.m00 - t.x * obb.m33.m10) > (ra + rb) + e) - { - return 0; - } - ra = h.x * fabsf(obb.m33.m11) + h.y * fabsf(obb.m33.m01); - rb = obb.h.x * fabsf(obb.m33.m22) + obb.h.z * fabsf(obb.m33.m20); - if (fabsf(t.y * obb.m33.m01 - t.x * obb.m33.m11) > (ra + rb) + e) - { - return 0; - } - ra = h.x * fabsf(obb.m33.m12) + h.y * fabsf(obb.m33.m02); - rb = obb.h.x * fabsf(obb.m33.m21) + obb.h.y * fabsf(obb.m33.m20); - if (fabsf(t.y * obb.m33.m02 - t.x * obb.m33.m12) > (ra + rb) + e) - { - return 0; - } - - //no separating axis found, we have an intersection - return 1; - } - - /*! - * - * we use the SEPARATING AXIS TEST to check if two OBB's overlap. - * - * Example: - * bool result=Overlap::OBB_OBB( pos1,obb1, pos2,obb2 ); - * - */ - inline bool OBB_OBB (const Vec3& pos1, const OBB& obb1, const Vec3& pos2, const OBB& obb2) - { - //tranform obb2 in local space of obb1 - Matrix33 M = obb1.m33.T() * obb2.m33; - - //the new center-position in world-space - Vec3 p1 = obb1.m33 * obb1.c + pos1; - Vec3 p2 = obb2.m33 * obb2.c + pos2; - - //"t" is the transfer-vector from one center to the other - Vec3 t = (p2 - p1) * obb1.m33; - - float ra, rb; - - //-------------------------------------------------------------------------- - //-- we use the vectors "1,0,0","0,1,0" and "0,0,1" as separating axis - //-------------------------------------------------------------------------- - rb = fabsf(M.m00 * obb2.h.x) + fabsf(M.m01 * obb2.h.y) + fabsf(M.m02 * obb2.h.z); - if (fabsf(t.x) > (fabsf(obb1.h.x) + rb)) - { - return 0; - } - rb = fabsf(M.m10 * obb2.h.x) + fabsf(M.m11 * obb2.h.y) + fabsf(M.m12 * obb2.h.z); - if (fabsf(t.y) > (fabsf(obb1.h.y) + rb)) - { - return 0; - } - rb = fabsf(M.m20 * obb2.h.x) + fabsf(M.m21 * obb2.h.y) + fabsf(M.m22 * obb2.h.z); - if (fabsf(t.z) > (fabsf(obb1.h.z) + rb)) - { - return 0; - } - - //-------------------------------------------------------------------------- - //-- we use the orientation-vectors "Mx","My" and "Mz" as separating axis - //-------------------------------------------------------------------------- - ra = fabsf(M.m00 * obb1.h.x) + fabsf(M.m10 * obb1.h.y) + fabsf(M.m20 * obb1.h.z); - if (fabsf(t | Vec3(M.m00, M.m10, M.m20)) > (ra + obb2.h.x)) - { - return 0; - } - ra = fabsf(M.m01 * obb1.h.x) + fabsf(M.m11 * obb1.h.y) + fabsf(M.m21 * obb1.h.z); - if (fabsf(t | Vec3(M.m01, M.m11, M.m21)) > (ra + obb2.h.y)) - { - return 0; - } - ra = fabsf(M.m02 * obb1.h.x) + fabsf(M.m12 * obb1.h.y) + fabsf(M.m22 * obb1.h.z); - if (fabsf(t | Vec3(M.m02, M.m12, M.m22)) > (ra + obb2.h.z)) - { - return 0; - } - - //--------------------------------------------------------------------- - //---- using 9 cross products we generate new separating axis - //--------------------------------------------------------------------- - ra = obb1.h.y * fabsf(M.m20) + obb1.h.z * fabsf(M.m10); - rb = obb2.h.y * fabsf(M.m02) + obb2.h.z * fabsf(M.m01); - if (fabsf(t.z * M.m10 - t.y * M.m20) > (ra + rb)) - { - return 0; - } - ra = obb1.h.y * fabsf(M.m21) + obb1.h.z * fabsf(M.m11); - rb = obb2.h.x * fabsf(M.m02) + obb2.h.z * fabsf(M.m00); - if (fabsf(t.z * M.m11 - t.y * M.m21) > (ra + rb)) - { - return 0; - } - ra = obb1.h.y * fabsf(M.m22) + obb1.h.z * fabsf(M.m12); - rb = obb2.h.x * fabsf(M.m01) + obb2.h.y * fabsf(M.m00); - if (fabsf(t.z * M.m12 - t.y * M.m22) > (ra + rb)) - { - return 0; - } - - - ra = obb1.h.x * fabsf(M.m20) + obb1.h.z * fabsf(M.m00); - rb = obb2.h.y * fabsf(M.m12) + obb2.h.z * fabsf(M.m11); - if (fabsf(t.x * M.m20 - t.z * M.m00) > (ra + rb)) - { - return 0; - } - ra = obb1.h.x * fabsf(M.m21) + obb1.h.z * fabsf(M.m01); - rb = obb2.h.x * fabsf(M.m12) + obb2.h.z * fabsf(M.m10); - if (fabsf(t.x * M.m21 - t.z * M.m01) > (ra + rb)) - { - return 0; - } - ra = obb1.h.x * fabsf(M.m22) + obb1.h.z * fabsf(M.m02); - rb = obb2.h.x * fabsf(M.m11) + obb2.h.y * fabsf(M.m10); - if (fabsf(t.x * M.m22 - t.z * M.m02) > (ra + rb)) - { - return 0; - } - - - ra = obb1.h.x * fabsf(M.m10) + obb1.h.y * fabsf(M.m00); - rb = obb2.h.y * fabsf(M.m22) + obb2.h.z * fabsf(M.m21); - if (fabsf(t.y * M.m00 - t.x * M.m10) > (ra + rb)) - { - return 0; - } - ra = obb1.h.x * fabsf(M.m11) + obb1.h.y * fabsf(M.m01); - rb = obb2.h.x * fabsf(M.m22) + obb2.h.z * fabsf(M.m20); - if (fabsf(t.y * M.m01 - t.x * M.m11) > (ra + rb)) - { - return 0; - } - ra = obb1.h.x * fabsf(M.m12) + obb1.h.y * fabsf(M.m02); - rb = obb2.h.x * fabsf(M.m21) + obb2.h.y * fabsf(M.m20); - if (fabsf(t.y * M.m02 - t.x * M.m12) > (ra + rb)) - { - return 0; - } - - return 1; //no separating axis found, we have an overlap - } - - - - - - -#define PLANE_X 0 -#define PLANE_Y 1 -#define PLANE_Z 2 -#define PLANE_NON_AXIAL 3 - - //! check if the point is inside a triangle - inline bool PointInTriangle(const Vec3& point, const Vec3& v0, const Vec3& v1, const Vec3& v2, const Vec3& normal) - { - float xt, yt; - Vec3 nn; - - int p1, p2; - - nn = normal; - nn.x = (float)fabs(nn.x); - nn.y = (float)fabs(nn.y); - nn.z = (float)fabs(nn.z); - - if ((nn.x >= nn.y) && (nn.x >= nn.z)) - { - xt = point.y; - yt = point.z; - p1 = PLANE_Y; - p2 = PLANE_Z; - } - else - if ((nn.y >= nn.x) && (nn.y >= nn.z)) - { - xt = point.x; - yt = point.z; - p1 = PLANE_X; - p2 = PLANE_Z; - } - else - { - xt = point.x; - yt = point.y; - p1 = PLANE_X; - p2 = PLANE_Y; - } - - float Ax, Ay, Bx, By; - float s; - - bool front = false; - bool back = false; - - - Ax = (v0)[p1]; - Bx = (v1)[p1]; - Ay = (v0)[p2]; - By = (v1)[p2]; - - s = ((Ay - yt) * (Bx - Ax) - (Ax - xt) * (By - Ay)); - - if (s >= 0) - { - if (back) - { - return (false); - } - front = true; - } - else - { - if (front) - { - return (false); - } - back = true; - } - - Ax = (v1)[p1]; - Bx = (v2)[p1]; - Ay = (v1)[p2]; - By = (v2)[p2]; - - s = ((Ay - yt) * (Bx - Ax) - (Ax - xt) * (By - Ay)); - - if (s >= 0) - { - if (back) - { - return (false); - } - front = true; - } - else - { - if (front) - { - return (false); - } - back = true; - } - - Ax = (v2)[p1]; - Bx = (v0)[p1]; - Ay = (v2)[p2]; - By = (v0)[p2]; - - s = ((Ay - yt) * (Bx - Ax) - (Ax - xt) * (By - Ay)); - - if (s >= 0) - { - if (back) - { - return (false); - } - front = true; - } - else - { - if (front) - { - return (false); - } - back = true; - } - - return (true); - } -} - - - -#endif // CRYINCLUDE_CRYCOMMON_CRY_GEOOVERLAP_H diff --git a/Code/CryEngine/CryCommon/Cry_HWMatrix.h b/Code/CryEngine/CryCommon/Cry_HWMatrix.h deleted file mode 100644 index 63973dc26f..0000000000 --- a/Code/CryEngine/CryCommon/Cry_HWMatrix.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Scalar implementation of hardware vector based matrix - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_HWMATRIX_H -#define CRYINCLUDE_CRYCOMMON_CRY_HWMATRIX_H -#pragma once - -struct hwmtx33 -{ - hwvec3 m0, m1, m2; -}; - -ILINE void HWMtx33LoadAligned(hwmtx33& out, const Matrix34A& inMtx) -{ - out.m0 = HWVLoadVecAligned(reinterpret_cast(&inMtx.m00)); - out.m1 = HWVLoadVecAligned(reinterpret_cast(&inMtx.m10)); - out.m2 = HWVLoadVecAligned(reinterpret_cast(&inMtx.m20)); -} - -ILINE hwvec3 HWMtx33RotateVec(const hwmtx33& m, const hwvec3& v) -{ - return Vec3((m.m0[0] * v.x) + (m.m0[1] * v.y) + (m.m0[2] * v.z), - (m.m1[0] * v.x) + (m.m1[1] * v.y) + (m.m1[2] * v.z), - (m.m2[0] * v.x) + (m.m2[1] * v.y) + (m.m2[2] * v.z)); -} - -ILINE hwvec3 HWMtx33RotateVecOpt(const hwmtx33& m, const hwvec3& v) -{ - return HWMtx33RotateVec(m, v); -} - -ILINE hwmtx33 HWMtx33CreateRotationV0V1(const hwvec3& v0, const hwvec3& v1) -{ - assert((fabs_tpl(1 - (v0 | v0))) < 0.01); //check if unit-vector - assert((fabs_tpl(1 - (v1 | v1))) < 0.01); //check if unit-vector - hwmtx33 m; - float dot = v0 | v1; - if (dot < -0.9999f) - { - Vec3 axis = v0.GetOrthogonal().GetNormalized(); - m.m0[0] = (2.0f * axis.x * axis.x - 1); - m.m0[1] = (2.0f * axis.x * axis.y); - m.m0[2] = (2.0f * axis.x * axis.z); - m.m1[0] = (2.0f * axis.y * axis.x); - m.m1[1] = (2.0f * axis.y * axis.y - 1); - m.m1[2] = (2.0f * axis.y * axis.z); - m.m2[0] = (2.0f * axis.z * axis.x); - m.m2[1] = (2.0f * axis.z * axis.y); - m.m2[2] = (2.0f * axis.z * axis.z - 1); - } - else - { - Vec3 v = v0 % v1; - f32 h = 1.0f / (1.0f + dot); - m.m0[0] = (dot + h * v.x * v.x); - m.m0[1] = (h * v.x * v.y - v.z); - m.m0[2] = (h * v.x * v.z + v.y); - m.m1[0] = (h * v.x * v.y + v.z); - m.m1[1] = (dot + h * v.y * v.y); - m.m1[2] = (h * v.y * v.z - v.x); - m.m2[0] = (h * v.x * v.z - v.y); - m.m2[1] = (h * v.y * v.z + v.x); - m.m2[2] = (dot + h * v.z * v.z); - } - - return m; -} - -//Returns a matrix optimized for this platform's matrix ops, in this case, not doing a thing; -ILINE hwmtx33 HWMtx33GetOptimized(const hwmtx33& m) -{ - return (hwmtx33)m; -} - -#endif // CRYINCLUDE_CRYCOMMON_CRY_HWMATRIX_H - diff --git a/Code/CryEngine/CryCommon/Cry_HWVector3.h b/Code/CryEngine/CryCommon/Cry_HWVector3.h deleted file mode 100644 index 6cc1e043d8..0000000000 --- a/Code/CryEngine/CryCommon/Cry_HWVector3.h +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description: Hardware vector class - scalar implementation - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_HWVECTOR3_H -#define CRYINCLUDE_CRYCOMMON_CRY_HWVECTOR3_H -#pragma once - - -#define HWV_PERMUTE_0X 0 -#define HWV_PERMUTE_0Y 1 -#define HWV_PERMUTE_0Z 2 -#define HWV_PERMUTE_0W 3 -#define HWV_PERMUTE_1X 4 -#define HWV_PERMUTE_1Y 5 -#define HWV_PERMUTE_1Z 6 -#define HWV_PERMUTE_1W 7 - -typedef Vec3 hwvec3; -typedef Vec4 hwvec4; -typedef float simdf; -typedef Vec4 hwvec4fconst; -typedef int hwvec4i[4]; - -#define HWV3Constant(name, f0, f1, f2) const Vec3 name(f0, f1, f2) -#define SIMDFConstant(name, f0) const simdf name = f0 -#define HWV4PermuteControl(name, i0, i1, i2, i3) static const hwvec4i name = {i0, i1, i2, i3}; -#define SIMDFAsVec3(a) (hwvec3)a -#define HWV3AsSIMDF(a) (simdf)a.x - -ILINE hwvec3 HWVLoadVecUnaligned(const Vec3* pLoadFrom) -{ - return *pLoadFrom; -} - -ILINE hwvec3 HWVLoadVecAligned(const Vec4A* pLoadFrom) -{ - return Vec3(pLoadFrom->x, pLoadFrom->y, pLoadFrom->z); -} - -ILINE void HWVSaveVecUnaligned(Vec3* pSaveTo, const hwvec3& pLoadFrom) -{ - *pSaveTo = pLoadFrom; -} - -ILINE void HWVSaveVecAligned(Vec4* pSaveTo, const hwvec4& pLoadFrom) -{ - *pSaveTo = pLoadFrom; -} - -ILINE hwvec3 HWVAdd(const hwvec3& a, const hwvec3& b) -{ - return hwvec3(a.x + b.x, a.y + b.y, a.z + b.z); -} - -ILINE hwvec3 HWVMultiply(const hwvec3& a, const hwvec3& b) -{ - return hwvec3(a.x * b.x, a.y * b.y, a.z * b.z); -} - -ILINE hwvec3 HWVMultiplySIMDF(const hwvec3& a, const simdf& b) -{ - return hwvec3(a.x * b, a.y * b, a.z * b); -} - -ILINE hwvec3 HWVMultiplyAdd(const hwvec3& a, const hwvec3& b, const hwvec3& c) -{ - return hwvec3((a.x * b.x) + c.x, (a.y * b.y) + c.y, (a.z * b.z) + c.z); -} - -ILINE hwvec3 HWVMultiplySIMDFAdd(const hwvec3& a, const simdf& b, const hwvec3& c) -{ - return hwvec3((a.x * b) + c.x, (a.y * b) + c.y, (a.z * b) + c.z); -} - -ILINE hwvec3 HWVSub(const hwvec3& a, const hwvec3& b) -{ - return (a - b); -} - -ILINE hwvec3 HWVCross(const hwvec3& a, const hwvec3& b) -{ - return hwvec3((a.y * b.z) - (a.z * b.y) - , (a.z * b.x) - (a.x * b.z) - , (a.x * b.y) - (a.y * b.x)); -} - -ILINE simdf HWV3Dot(const hwvec3& a, const hwvec3& b) -{ - return (a.x * b.x) + (a.y * b.y) + (a.z * b.z); -} - -ILINE hwvec3 HWVMax(const hwvec3& a, const hwvec3& b) -{ - return Vec3(a.x > b.x ? a.x : b.x, - a.y > b.y ? a.y : b.y, - a.z > b.z ? a.z : b.z); -} - -ILINE hwvec3 HWVMin(const hwvec3& a, const hwvec3& b) -{ - return Vec3(a.x < b.x ? a.x : b.x, - a.y < b.y ? a.y : b.y, - a.z < b.z ? a.z : b.z); -} - -ILINE hwvec3 HWVClamp(const hwvec3& a, const hwvec3& min, const hwvec3& max) -{ - return HWVMax(min, HWVMin(a, max)); -} - -ILINE hwvec3 HWV3Normalize(const hwvec3& a) -{ - float fInvLen = isqrt_safe_tpl((a.x * a.x) + (a.y * a.y) + (a.z * a.z)); - return Vec3(a.x * fInvLen, a.y * fInvLen, a.z * fInvLen); -} - -ILINE hwvec3 HWVGetOrthogonal(const hwvec3& a) -{ - hwvec3 result = a; - - //int i = isneg(square(0.9f)*a.GetLengthSquared()-(a.x*a.x)); - int i = isneg(square(0.9f) * a.GetLengthSquared() - a.x * a.x); - result[i] = 0; - result[incm3(i)] = a[decm3(i)]; - result[decm3(i)] = -a[incm3(i)]; - return result; -} - -ILINE simdf HWV3SplatXToSIMDF(const hwvec3& a) -{ - return a.x; -} - -ILINE simdf HWV3SplatYToSIMDF(const hwvec3& a) -{ - return a.y; -} - -ILINE hwvec3 HWV3PermuteWord(const hwvec3& a, const hwvec3& b, const hwvec4i& p) -{ - hwvec3 selection[2] = {a, b}; - float* fSelection = (float*)selection; - return Vec3(fSelection[p[0]], fSelection[p[1]], fSelection[p[2]]); -} - -ILINE hwvec3 HWV3Zero() -{ - return Vec3(0.0f, 0.0f, 0.0f); -} - -ILINE hwvec4 HWV4Zero() -{ - return Vec4(0.0f, 0.0f, 0.0f, 0.0f); -} - - -ILINE hwvec3 HWV3Negate(const hwvec3& a) -{ - return Vec3(-a.x, -a.y, -a.z); -} - -ILINE hwvec3 HWVSelect(const hwvec3& a, const hwvec3& b, const hwvec3& control) -{ - return Vec3(control[0] > 0.0f ? b[0] : a[0], - control[1] > 0.0f ? b[1] : a[1], - control[2] > 0.0f ? b[2] : a[2]); -} - -ILINE hwvec3 HWVSelectSIMDF(const hwvec3& a, const hwvec3& b, const bool& control) -{ - return control ? b : a; -} - -ILINE simdf HWV3LengthSq(const hwvec3& a) -{ - return a.len2(); -} - - -////////////////////////////////////////////////// -//SIMDF functions for float stored in HWVEC4 data -////////////////////////////////////////////////// - -ILINE simdf SIMDFLoadFloat(const float& f) -{ - return f; -} - -ILINE void SIMDFSaveFloat(float* f, const simdf& a) -{ - *f = a; -} - -ILINE bool SIMDFGreaterThan(const simdf& a, const simdf& b) -{ - return (a > b); -} - -ILINE bool SIMDFLessThanEqualB(const simdf& a, const simdf& b) -{ - return (a <= b); -} - -ILINE bool SIMDFLessThanEqual(const simdf& a, const simdf& b) -{ - return (a <= b); -} - -ILINE bool SIMDFLessThanB(const simdf& a, const simdf& b) -{ - return (a < b); -} - -ILINE bool SIMDFLessThan(const simdf& a, const simdf& b) -{ - return (a < b); -} - -ILINE simdf SIMDFAdd(const simdf& a, const simdf& b) -{ - return a + b; -} - -ILINE simdf SIMDFMult(const simdf& a, const simdf& b) -{ - return a * b; -} - -ILINE simdf SIMDFReciprocal(const simdf& a) -{ - return 1.0f / a; -} - -ILINE simdf SIMDFSqrt(const simdf& a) -{ - return sqrt_tpl(a); -} - -ILINE simdf SIMDFSqrtEst(const simdf& a) -{ - return sqrt_tpl(a); -} - -ILINE simdf SIMDFSqrtEstFast(const simdf& a) -{ - return sqrt_tpl(a); -} - -ILINE simdf SIMDFMax(const simdf& a, const simdf& b) -{ - return max(a, b); -} - -ILINE simdf SIMDFMin(const simdf& a, const simdf& b) -{ - return min(a, b); -} - -ILINE simdf SIMDFClamp(const simdf& a, const simdf& min, const simdf& max) -{ - return clamp_tpl(a, min, max); -} - -ILINE simdf SIMDFAbs(const simdf& a) -{ - return fabsf(a); -} - -#endif // CRYINCLUDE_CRYCOMMON_CRY_HWVECTOR3_H diff --git a/Code/CryEngine/CryCommon/Cry_Math.h b/Code/CryEngine/CryCommon/Cry_Math.h deleted file mode 100644 index 315e96ecd9..0000000000 --- a/Code/CryEngine/CryCommon/Cry_Math.h +++ /dev/null @@ -1,732 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Common math class - - -#pragma once - -//======================================================================================== - -#include -#include "Cry_ValidNumber.h" -#include // eLittleEndian -#include -#include -#include -/////////////////////////////////////////////////////////////////////////////// -// Forward declarations // -/////////////////////////////////////////////////////////////////////////////// -template -struct Vec2_tpl; -template -struct Vec3_tpl; -template -struct Vec4_tpl; - -template -struct Ang3_tpl; -template -struct Plane_tpl; -template -struct AngleAxis_tpl; -template -struct Quat_tpl; -template -struct QuatT_tpl; -template -struct DualQuat_tpl; -template -struct QuatTS_tpl; -template -struct QuatTNS_tpl; - -template -struct Diag33_tpl; -template -struct Matrix33_tpl; -template -struct Matrix34_tpl; -template -struct Matrix44_tpl; - - -/////////////////////////////////////////////////////////////////////////////// -// Definitions // -/////////////////////////////////////////////////////////////////////////////// -const f32 gf_PI = f32(3.14159265358979323846264338327950288419716939937510); -const f64 g_PI = 3.14159265358979323846264338327950288419716939937510; // pi - -const f32 gf_PI2 = f32(3.14159265358979323846264338327950288419716939937510 * 2.0); -const f64 g_PI2 = 3.14159265358979323846264338327950288419716939937510 * 2.0; // 2*pi - -const f64 sqrt2 = 1.4142135623730950488016887242097; -const f64 sqrt3 = 1.7320508075688772935274463415059; - -const f32 gf_halfPI = f32(1.57079632679489661923132169163975144209858469968755); - -#ifndef MAX -#define MAX(a, b) (((a) > (b)) ? (a) : (b)) -#endif -#ifndef MIN -#define MIN(a, b) (((a) < (b)) ? (a) : (b)) -#endif - -#define VEC_EPSILON (0.05f) -#define RAD_EPSILON (0.01f) -#define DEG2RAD(a) ((a) * (gf_PI / 180.0f)) -#define RAD2DEG(a) ((a) * (180.0f / gf_PI)) -#define DEG2COS(a) (cos_tpl((a) * (gf_PI / 180.0f))) -#define COS2DEG(a) (acos_tpl(a) * (180.0f / gf_PI)) -#define RAD2HCOS(a) (cos_tpl((a * 0.5f))) -#define HCOS2RAD(a) (acos_tpl(a) * 2.0f) -#define DEG2HCOS(a) (cos_tpl((a * 0.5f) * (gf_PI / 180.0f))) -#define DEG2HSIN(a) (sin_tpl((a * 0.5f) * (gf_PI / 180.0f))) -#define HCOS2DEG(a) (acos_tpl(a) * 2.0f * (180.0f / gf_PI)) -#define SIGN_MASK(x) ((intptr_t)(x) >> ((sizeof(size_t) * 8) - 1)) -#define TANGENT30 0.57735026918962576450914878050196f // tan(30) -#define TANGENT30_2 0.57735026918962576450914878050196f * 2 // 2*tan(30) -#define LN2 0.69314718055994530941723212145818f // ln(2) - - - - - -ILINE f32 fsel(const f32 _a, const f32 _b, const f32 _c) { return (_a < 0.0f) ? _c : _b; } -ILINE f64 fsel(const f64 _a, const f64 _b, const f64 _c) { return (_a < 0.0f) ? _c : _b; } -ILINE f32 fself(const f32 _a, const f32 _b, const f32 _c) { return (_a < 0.0f) ? _c : _b; } -ILINE f32 fsels(const f32 _a, const f32 _b, const f32 _c) { return (_a < 0.0f) ? _c : _b; } -ILINE f32 fres(const f32 _a) { return 1.f / _a; } -template -ILINE T isel(int c, T a, T b) { return (c < 0) ? b : a; } -template -ILINE T isel(int64 c, T a, T b) { return (c < 0) ? b : a; } -template -ILINE T iselnz(int c, T a, T b) { return c ? a : b; } -template -ILINE T iselnz(uint32 c, T a, T b) { return c ? a : b; } -template -ILINE T iselnz(int64 c, T a, T b) { return c ? a : b; } -template -ILINE T iselnz(uint64 c, T a, T b) { return c ? a : b; } -//provides fast way of checking against 0 (saves fcmp) -ILINE bool fzero(const float& val) { return val == 0.0f; } -ILINE bool fzero(float* pVal) { return *pVal == 0.0f; } - - - -////////////////////////////////////////////////////////////////////////// -// Define min/max -////////////////////////////////////////////////////////////////////////// -#ifdef min -#undef min -#endif //min - -#ifdef max -#undef max -#endif //max - - -// Bring min and max from std namespace to global scope. -template -ILINE T min(const T& a, const T& b) { return b < a ? b : a; } -template -ILINE T max(const T& a, const T& b) { return a < b ? b : a; } -template -ILINE const T& min(const T& a, const T& b, _Compare comp) { return comp(b, a) ? b : a; } -template -ILINE const T& max(const T& a, const T& b, _Compare comp) { return comp(a, b) ? b : a; } -ILINE int min_branchless(int a, int b) { int diff = a - b; int mask = diff >> 31; return (b & (~mask)) | (a & mask); } - -template -ILINE T clamp_tpl(T X, T Min, T Max) { return X < Min ? Min : X < Max ? X : Max; } -template -ILINE void Limit(T& val, const T& min, const T& max) -{ - if (val < min) - { - val = min; - } - else if (val > max) - { - val = max; - } -} -template -ILINE T Lerp(const T& a, const T& b, float s) { return T(a + (b - a) * s); } - - - -//------------------------------------------- -//-- the portability functions for CPU_X86 -//------------------------------------------- - -#if defined(_CPU_SSE) -#include -#endif - -ILINE f32 fabs_tpl(f32 op) { return op < 0.0f ? -op : op; } -ILINE f64 fabs_tpl(f64 op) { return fabs(op); } -ILINE int32 fabs_tpl(int32 op) { int32 mask = op >> 31; return op + mask ^ mask; } - -ILINE f32 floor_tpl(f32 op) {return floorf(op); } -ILINE f64 floor_tpl(f64 op) {return floor(op); } -ILINE int32 floor_tpl(int32 op) {return op; } - -ILINE f32 ceil_tpl(f32 op) {return ceilf(op); } -ILINE f64 ceil_tpl(f64 op) {return ceil(op); } -ILINE int32 ceil_tpl(int32 op) {return op; } - -ILINE f32 fmod_tpl(f32 x, f32 y) {return (f32)fmodf(x, y); } -ILINE f64 fmod_tpl(f64 x, f64 y) {return (f32)fmod(x, y); } - -ILINE void sincos_tpl (f32 angle, f32* pSin, f32* pCos) { *pSin = f32(sin(angle)); *pCos = f32(cos(angle)); } -ILINE void sincos_tpl (f64 angle, f64* pSin, f64* pCos) { *pSin = f64(sin(angle)); *pCos = f64(cos(angle)); } - -ILINE f32 cos_tpl(f32 op) { return cosf(op); } -ILINE f64 cos_tpl(f64 op) { return cos(op); } - -ILINE f32 sin_tpl(f32 op) { return sinf(op); } -ILINE f64 sin_tpl(f64 op) { return sin(op); } - -ILINE f32 acos_tpl(f32 op) { return acosf(clamp_tpl(op, -1.0f, +1.0f)); } -ILINE f64 acos_tpl(f64 op) { return acos(clamp_tpl(op, -1.0, +1.0)); } - -ILINE f32 asin_tpl(f32 op) { return asinf(clamp_tpl(op, -1.0f, +1.0f)); } -ILINE f64 asin_tpl(f64 op) { return asin(clamp_tpl(op, -1.0, +1.0)); } - -ILINE f32 atan_tpl(f32 op) { return atanf(op); } -ILINE f64 atan_tpl(f64 op) { return atan(op); } - -ILINE f32 atan2_tpl(f32 op1, f32 op2) { return atan2f(op1, op2); } -ILINE f64 atan2_tpl(f64 op1, f64 op2) { return atan2(op1, op2); } - -ILINE f32 tan_tpl(f32 op) {return tanf(op); } -ILINE f64 tan_tpl(f64 op) {return tan(op); } - -ILINE f32 exp_tpl(f32 op) { return expf(op); } -ILINE f64 exp_tpl(f64 op) { return exp(op); } - -ILINE f32 log_tpl(f32 op) { return logf(op); } -ILINE f64 log_tpl(f64 op) { return log(op); } - -ILINE f32 pow_tpl(f32 x, f32 y) {return (f32) pow((f64)x, (f64)y); } -ILINE f64 pow_tpl(f64 x, f64 y) {return pow(x, y); } - -#if defined(_CPU_SSE) -ILINE f32 sqrt_tpl(f32 op) -{ - __m128 s = _mm_sqrt_ss(_mm_set_ss(op)); - float r; - _mm_store_ss(&r, s); - return r; -} -ILINE f64 sqrt_tpl(f64 op) -{ - return sqrt(op); -} - -ILINE f32 sqrt_fast_tpl(f32 op) -{ - return sqrt_tpl(op); -} -ILINE f64 sqrt_fast_tpl(f64 op) -{ - return sqrt_tpl(op); -} - -ILINE f32 isqrt_tpl(f32 op) -{ - __m128 value = _mm_set_ss(op); - __m128 oneHalf = _mm_set_ss(0.5f); - __m128 threeHalfs = _mm_set_ss(1.5f); - __m128 simdRecipSqrt = _mm_rsqrt_ss(value); - __m128 inverseMult = _mm_mul_ps(_mm_mul_ss(_mm_mul_ss(value, simdRecipSqrt), simdRecipSqrt), oneHalf); - __m128 inverseInner = _mm_sub_ps(threeHalfs, inverseMult); - __m128 newtonIteration1 = _mm_mul_ss(simdRecipSqrt, inverseInner); - float r; - _mm_store_ss(&r, newtonIteration1); - return r; -} -ILINE f64 isqrt_tpl(f64 op) -{ - return 1.0 / sqrt(op); -} - -ILINE f32 isqrt_fast_tpl(f32 op) -{ - return isqrt_tpl(op); -} -ILINE f64 isqrt_fast_tpl(f64 op) -{ - return isqrt_tpl(op); -} - -ILINE f32 isqrt_safe_tpl(f32 value) -{ - return isqrt_tpl(value + (std::numeric_limits::min)()); -} - -ILINE f64 isqrt_safe_tpl(f64 value) -{ - return isqrt_tpl(value + (std::numeric_limits::min)()); -} -#elif defined (__ARM_NEON__) -#include "arm_neon.h" - -template -float isqrt_helper(float f) -{ - float32x2_t v = vdup_n_f32(f); - float32x2_t r = vrsqrte_f32(v); - // n+1 newton iterations because initial approximation is crude - for (int i = 0; i <= n; ++i) - { - r = vrsqrts_f32(v * r, r) * r; - } - return vget_lane_f32(r, 0); -} - -ILINE f32 sqrt_tpl(f32 op) { return op != 0.0f ? op* isqrt_helper<1>(op) : op; } -ILINE f64 sqrt_tpl(f64 op) { return sqrt(op); } - -ILINE f32 sqrt_fast_tpl(f32 op) { return op != 0.0f ? op* isqrt_helper<0>(op) : op; } -ILINE f64 sqrt_fast_tpl(f64 op) { return sqrt(op); } - -ILINE f32 isqrt_tpl(f32 op) { return isqrt_helper<1>(op); } -ILINE f64 isqrt_tpl(f64 op) { return 1.0 / sqrt(op); } - -ILINE f32 isqrt_fast_tpl(f32 op) { return isqrt_helper<0>(op); } -ILINE f64 isqrt_fast_tpl(f64 op) { return 1.0 / sqrt(op); } - -ILINE f32 isqrt_safe_tpl(f32 op) { return isqrt_helper<1>(op + FLT_MIN); } -ILINE f64 isqrt_safe_tpl(f64 op) { return 1.0 / sqrt(op + DBL_MIN); } -#else -#error unsupported CPU -#endif - -ILINE int32 int_round(f32 f) { return f < 0.f ? int32(f - 0.5f) : int32(f + 0.5f); } -ILINE int32 pos_round(f32 f) { return int32(f + 0.5f); } -ILINE int64 int_round(f64 f) { return f < 0.0 ? int64(f - 0.5) : int64(f + 0.5); } -ILINE int64 pos_round(f64 f) { return int64(f + 0.5); } - -ILINE int32 int_ceil(f32 f) { int32 i = int32(f); return (f > f32(i)) ? i + 1 : i; } -ILINE int64 int_ceil(f64 f) { int64 i = int64(f); return (f > f64(i)) ? i + 1 : i; } - -ILINE float ufrac8_to_float(float u) { return u * (1.f / 255.f); } -ILINE float ifrac8_to_float(float i) { return i * (1.f / 127.f); } -ILINE uint8 float_to_ufrac8(float f) { int i = pos_round(f * 255.f); assert(i >= 0 && i < 256); return uint8(i); } -ILINE int8 float_to_ifrac8(float f) { int i = int_round(f * 127.f); assert(abs(i) <= 127); return int8(i); } - - - -template -ILINE F sqr(const F& op) { return op * op; } -template -ILINE F sqr(const Vec2_tpl& op) { return op | op; } -template -ILINE F sqr(const Vec3_tpl& op) { return op | op; } -template -ILINE F sqr_signed(const F& op) { return op * fabs_tpl(op); } -template -ILINE F cube(const F& op) { return op * op * op; } - -template -ILINE F square(F fOp) { return(fOp * fOp); } -ILINE float div_min(float n, float d, float m) { return n * d < m * d * d ? n / d : m; } - - -// Utility functions for returning -1 if input is negative and non-zero, returns positive 1 otherwise -// Uses extensive bit shifting for performance reasons. -ILINE int32 sgnnz(f64 x) -{ - union - { - f32 f; - int32 i; - } u; - u.f = (f32)x; - return ((u.i >> 31) << 1) + 1; -} -ILINE int32 sgnnz(f32 x) -{ - union - { - f32 f; - int32 i; - } u; - u.f = x; - return ((u.i >> 31) << 1) + 1; -} -ILINE int32 sgnnz(int32 x) { return ((x >> 31) << 1) + 1; } -ILINE f32 fsgnnz(f32 x) -{ - union - { - f32 f; - int32 i; - } u; - u.f = x; - u.i = (u.i & 0x80000000) | 0x3f800000; - return u.f; -} - -ILINE int32 isneg(f32 x) -{ - union - { - f32 f; - uint32 i; - } u; - u.f = x; - return (int32)(u.i >> 31); -} -ILINE int32 isneg(f64 x) -{ - union - { - f32 f; - uint32 i; - } u; - u.f = (f32)x; - return (int32)(u.i >> 31); -} -ILINE int32 isneg(int32 x) { return (int32)((uint32)x >> 31); } - - - - - -ILINE int32 sgn(f64 x) -{ - union - { - f32 f; - int32 i; - } u; - u.f = (f32)x; - return (u.i >> 31) + ((u.i - 1) >> 31) + 1; -} -ILINE int32 sgn(f32 x) -{ - union - { - f32 f; - int32 i; - } u; - u.f = x; - return (u.i >> 31) + ((u.i - 1) >> 31) + 1; -} -ILINE int32 sgn(int32 x) { return (x >> 31) + ((x - 1) >> 31) + 1; } -ILINE f32 fsgnf(f32 x) { return f32(sgn(x)); } - -ILINE int32 isnonneg(f32 x) -{ - union - { - f32 f; - uint32 i; - } u; - u.f = x; - return (int32)(u.i >> 31 ^ 1); -} -ILINE int32 isnonneg(f64 x) -{ - union - { - f32 f; - uint32 i; - } u; - u.f = (f32)x; - return (int32)(u.i >> 31 ^ 1); -} -ILINE int32 isnonneg(int32 x) { return (int32)((uint32)x >> 31 ^ 1); } - - - -ILINE int32 getexp(f32 x) { return (int32)(*(uint32*)&x >> 23 & 0x0FF) - 127; } -ILINE int32 getexp(f64 x) { return (int32)(*((uint32*)&x + 1) >> 20 & 0x7FF) - 1023; } -ILINE f32& setexp(f32& x, int32 iexp) { (*(uint32*)& x &= ~(0x0FF << 23)) |= (iexp + 127) << 23; return x; } -ILINE f64& setexp(f64& x, int32 iexp) { (*((uint32*)&x + 1) &= ~(0x7FF << 20)) |= (iexp + 1023) << 20; return x; } - - -ILINE int32 iszero(f32 x) -{ - union - { - f32 f; - int32 i; - } u; - u.f = x; - u.i &= 0x7FFFFFFF; - return -(u.i >> 31 ^ (u.i - 1) >> 31); -} -ILINE int32 iszero(f64 x) -{ - union - { - f32 f; - int32 i; - } u; - u.f = (f32)x; - u.i &= 0x7FFFFFFF; - return -((u.i >> 31) ^ (u.i - 1) >> 31); -} -ILINE int32 iszero(int32 x) { return -(x >> 31 ^ (x - 1) >> 31); } -#if defined(PLATFORM_64BIT) && !defined(__clang__) -ILINE int64 iszero(__int64 x) { return -(x >> 63 ^ (x - 1) >> 63); } -#endif -#if defined(PLATFORM_64BIT) && defined(__clang__) && !defined(LINUX) -ILINE int64 iszero(int64_t x) { return -(x >> 63 ^ (x - 1) >> 63); } -#endif -#if defined(PLATFORM_64BIT) && (defined(LINUX) || defined(APPLE)) -ILINE int64 iszero(long int x) { return -(x >> 63 ^ (x - 1) >> 63); } -#endif - -ILINE float if_neg_else(float test, float val_neg, float val_nonneg) { return (float)fsel(test, val_nonneg, val_neg); } -ILINE float if_pos_else(float test, float val_pos, float val_nonpos) { return (float)fsel(-test, val_nonpos, val_pos); } -template -ILINE int32 inrange(F x, F end1, F end2) { return isneg(fabs_tpl(end1 + end2 - x * (F)2) - fabs_tpl(end1 - end2)); } -template -ILINE F cond_select(int32 bFirst, F op1, F op2) { F arg[2] = { op1, op2 }; return arg[bFirst ^ 1]; } - -template -ILINE int32 idxmax3(const F* pdata) -{ - int32 imax = isneg(pdata[0] - pdata[1]); - imax |= isneg(pdata[imax] - pdata[2]) << 1; - return imax & (2 | (imax >> 1 ^ 1)); -} -template -ILINE int32 idxmax3(const Vec3_tpl& vec) -{ - int32 imax = isneg(vec.x - vec.y); - imax |= isneg(vec[imax] - vec.z) << 1; - return imax & (2 | (imax >> 1 ^ 1)); -} -template -ILINE int32 idxmin3(const F* pdata) -{ - int32 imin = isneg(pdata[1] - pdata[0]); - imin |= isneg(pdata[2] - pdata[imin]) << 1; - return imin & (2 | (imin >> 1 ^ 1)); -} -template -ILINE int32 idxmin3(const Vec3_tpl& vec) -{ - int32 imin = isneg(vec.y - vec.x); - imin |= isneg(vec.z - vec[imin]) << 1; - return imin & (2 | (imin >> 1 ^ 1)); -} -// Approximation of exp(-x) -ILINE float approxExp(float x) { return fres(1.f + x); } -// Approximation of 1.f - exp(-x) -ILINE float approxOneExp(float x) { return x * fres(1.f + x); } - - -ILINE int ilog2(uint64 x) // if x==1<> 23) - 127; -#endif -} - - -static int32 inc_mod3[] = {1, 2, 0}, dec_mod3[] = {2, 0, 1}; -#ifdef PHYSICS_EXPORTS -#define incm3(i) inc_mod3[i] -#define decm3(i) dec_mod3[i] -#else -ILINE int32 incm3(int32 i) { return i + 1 & (i - 2) >> 31; } -ILINE int32 decm3(int32 i) { return i - 1 + ((i - 1) >> 31 & 3); } -#endif - - -////////////////////////////////////////////////////////////////////////// -enum type_zero -{ - ZERO -}; -enum type_min -{ - VMIN -}; -enum type_max -{ - VMAX -}; -enum type_identity -{ - IDENTITY -}; - -#include "Cry_Vector2.h" -#include "Cry_Vector3.h" -#include "Cry_Vector4.h" -#include "Cry_MatrixDiag.h" -#include "Cry_Matrix33.h" -#include "Cry_Matrix34.h" -#include "Cry_Matrix44.h" -#include "Cry_Quat.h" -#include "Cry_HWVector3.h" -#include "Cry_HWMatrix.h" -#include "Cry_XOptimise.h" - -////////////////////////////////////////////////////////////////////////// - -/// This function relaxes a value (val) towards a desired value (to) whilst maintaining continuity -/// of val and its rate of change (valRate). timeDelta is the time between this call and the previous one. -/// The caller would normally keep val and valRate as working variables, and smoothTime is normally -/// a fixed parameter. The to/timeDelta values can change. -/// -/// Implementation details: -/// -/// This is a critically damped spring system. A linear spring is attached between "val" and "to" that -/// drags "val" to "to". At the same time a damper between the two removes oscillations; it's tweaked -/// so it doesn't dampen more than necessary. In combination this gives smooth ease-in and ease-out behavior. -/// -/// smoothTime can be interpreted in a couple of ways: -/// - it's the "expected time to reach the target when at maximum velocity" (the target will, however, not be reached -/// in that time because the speed will decrease the closer it gets to the target) -/// - it's the 'lag time', how many seconds "val" lags behind "to". If your -/// target has a certain speed, the lag distance is simply the smoothTime times that speed. -/// - it's 2/omega, where omega is the spring's natural frequency (or less formally a measure of the spring stiffness) -/// -/// The implementation is stable for varying timeDelta, but for performance reasons it uses a polynomial approximation -/// to the exponential function. The approximation works well (within 0.1% of accuracy) when smoothTime > 2*deltaTime, -/// which is usually the case. (but it might be troublesome when you want a stiff spring or have frame hikes!) -/// The implementation handles cases where smoothTime==0 separately and reliably. In that case the target will be -/// reached immediately, and valRate is updated appropriately. -/// -/// Based on "Critically Damped Ease-In/Ease-Out Smoothing", Thomas Lowe, Game Programming Gems IV -/// - - -template -ILINE void SmoothCD( - T& val, ///< in/out: value to be smoothed - T& valRate, ///< in/out: rate of change of the value - const float timeDelta, ///< in: time interval - const T& to, ///< in: the target value - const float smoothTime) ///< in: timescale for smoothing -{ - if (smoothTime > 0.0f) - { - const float omega = 2.0f / smoothTime; - const float x = omega * timeDelta; - const float exp = 1.0f / (1.0f + x + 0.48f * x * x + 0.235f * x * x * x); - const T change = (val - to); - const T temp = (T)((valRate + change * omega) * timeDelta); - valRate = (T)((valRate - temp * omega) * exp); - val = (T)(to + (change + temp) * exp); - } - else if (timeDelta > 0.0f) - { - valRate = (T)((to - val) / timeDelta); - val = to; - } - else - { - val = to; - T zeroizeAmount = valRate; - valRate -= zeroizeAmount; // zero it... - } -} - - -template -ILINE void SmoothCDWithMaxRate( - T& val, ///< in/out: value to be smoothed - T& valRate, ///< in/out: rate of change of the value - const float timeDelta, ///< in: time interval - const T& to, ///< in: the target value - const float smoothTime, ///< in: timescale for smoothing - const T& maxValRate) ///< in: maximum allowed rate of change -{ - if (smoothTime > 0.0f) - { - const float omega = 2.0f / smoothTime; - const float x = omega * timeDelta; - const float exp = 1.0f / (1.0f + x + 0.48f * x * x + 0.235f * x * x * x); - const T unclampedChange = val - to; - const T maxChange = maxValRate * smoothTime; - const T clampedChange = clamp_tpl(unclampedChange, -maxChange, maxChange); - const T clampedTo = val - clampedChange; - const T temp = (T)((valRate + clampedChange * omega) * timeDelta); - valRate = (T)((valRate - temp * omega) * exp); - val = (T)(clampedTo + (clampedChange + temp) * exp); - } - else if (timeDelta > 0.0f) - { - const T unclampedRate = (T)((to - val) / timeDelta); - valRate = clamp_tpl(unclampedRate, -maxValRate, maxValRate); - val += valRate * timeDelta; - } - else - { - val = to; - T zeroizeAmount = valRate; - valRate -= zeroizeAmount; // zero it... - } -} - -// Smoothes linear blending into cubic (b-spline) with 0-derivatives -// near 0 and 1 -inline f32 SmoothBlendValue (const f32 fBlend) -{ - const f32 fBlendAdj = fBlend - 0.5f; - return (f32)fsel(-fBlend, 0.f, fsel(fBlend - 1.f, 1.f, 0.5f - 2.f * (fBlendAdj * fBlendAdj * fBlendAdj) + 1.5f * fBlendAdj)); -} - -// function for safe comparsion of floating point values -ILINE bool fcmp(f32 fA, f32 fB, f32 fEpsilon = FLT_EPSILON) -{ - return fabs(fA - fB) <= fEpsilon; -} - -//! Given an arbitrary unit vector this function will compute two axes to build the orthonormal basis. -//! \param n Unit 3D vector -//! \param[out] b1 Orthonormal axis vector -//! \param[out] b2 Orthonormal axis vector -inline void GetBasisVectors(const Vec3& n, Vec3& b1, Vec3& b2) -{ - if (n.z < FLT_EPSILON - 1.0f) - { - b1 = Vec3(0.0f, -1.0f, 0.0f); - b2 = Vec3(-1.0f, 0.0f, 0.0f); - return; - } - - const float a = 1.0f / (1.0f + n.z); - const float b = -n.x * n.y * a; - b1 = Vec3(1.0f - n.x * n.x * a, b, -n.x); - b2 = Vec3(b, 1.0f - n.y * n.y * a, -n.y); -} diff --git a/Code/CryEngine/CryCommon/Cry_Matrix33.h b/Code/CryEngine/CryCommon/Cry_Matrix33.h deleted file mode 100644 index cdde89b5ff..0000000000 --- a/Code/CryEngine/CryCommon/Cry_Matrix33.h +++ /dev/null @@ -1,1572 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Common matrix class - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_MATRIX33_H -#define CRYINCLUDE_CRYCOMMON_CRY_MATRIX33_H -#pragma once - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct Matrix33_tpl -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -template -struct Matrix33_tpl -{ - F m00, m01, m02; - F m10, m11, m12; - F m20, m21, m22; - - //--------------------------------------------------------------------------------- - -#ifdef _DEBUG - ILINE Matrix33_tpl() - { - if constexpr (sizeof(F) == 4) - { - uint32* p = alias_cast(&m00); - p[0] = F32NAN; - p[1] = F32NAN; - p[2] = F32NAN; - p[3] = F32NAN; - p[4] = F32NAN; - p[5] = F32NAN; - p[6] = F32NAN; - p[7] = F32NAN; - p[8] = F32NAN; - } - if constexpr (sizeof(F) == 8) - { - uint64* p = alias_cast(&m00); - p[0] = F64NAN; - p[1] = F64NAN; - p[2] = F64NAN; - p[3] = F64NAN; - p[4] = F64NAN; - p[5] = F64NAN; - p[6] = F64NAN; - p[7] = F64NAN; - p[8] = F64NAN; - } - } -#else - ILINE Matrix33_tpl(){}; -#endif - - //set matrix to Identity - ILINE Matrix33_tpl(type_identity) - { - m00 = 1; - m01 = 0; - m02 = 0; - m10 = 0; - m11 = 1; - m12 = 0; - m20 = 0; - m21 = 0; - m22 = 1; - } - //set matrix to Zero - ILINE Matrix33_tpl(type_zero) - { - m00 = 0; - m01 = 0; - m02 = 0; - m10 = 0; - m11 = 0; - m12 = 0; - m20 = 0; - m21 = 0; - m22 = 0; - } - - - //ASSIGNMENT OPERATOR of identical Matrix33 types. - //The assignment operator has precedence over assignment constructor - //Matrix33 m; m=m33; - ILINE Matrix33_tpl& operator = (const Matrix33_tpl& m) - { - assert(m.IsValid()); - m00 = m.m00; - m01 = m.m01; - m02 = m.m02; - m10 = m.m10; - m11 = m.m11; - m12 = m.m12; - m20 = m.m20; - m21 = m.m21; - m22 = m.m22; - return *this; - } - - - //-------------------------------------------------------------------- - //---- implementation of the constructors --- - //-------------------------------------------------------------------- - - //CONSTRUCTOR for identical float-types. It initializes a Matrix33 with 9 floats. - //Matrix33(0,1,2, 3,4,5, 6,7,8); - explicit ILINE Matrix33_tpl(F x00, F x01, F x02, F x10, F x11, F x12, F x20, F x21, F x22) - { - m00 = x00; - m01 = x01; - m02 = x02; - m10 = x10; - m11 = x11; - m12 = x12; - m20 = x20; - m21 = x21; - m22 = x22; - } - //CONSTRUCTOR for different float-types. It initializes a Matrix33 with 9 floats. - //Matrix33(0.0,1.0,2.0, 3.0,4.0,5.0, 6.0,7.0,8.0); - template - explicit ILINE Matrix33_tpl(F1 x00, F1 x01, F1 x02, F1 x10, F1 x11, F1 x12, F1 x20, F1 x21, F1 x22) - { - m00 = F(x00); - m01 = F(x01); - m02 = F(x02); - m10 = F(x10); - m11 = F(x11); - m12 = F(x12); - m20 = F(x20); - m21 = F(x21); - m22 = F(x22); - } - - - //CONSTRUCTOR for identical float-types. It initializes a Matrix33 with 3 vectors stored in the columns. - //Matrix33(v0,v1,v2); - explicit ILINE Matrix33_tpl(const Vec3_tpl&vx, const Vec3_tpl&vy, const Vec3_tpl&vz) - { - m00 = vx.x; - m01 = vy.x; - m02 = vz.x; - m10 = vx.y; - m11 = vy.y; - m12 = vz.y; - m20 = vx.z; - m21 = vy.z; - m22 = vz.z; - } - //CONSTRUCTOR for different float-types. It initializes a Matrix33 with 3 vectors stored in the columns and converts between floats/doubles. - //Matrix33r(v0,v1,v2); - template - explicit ILINE Matrix33_tpl(const Vec3_tpl&vx, const Vec3_tpl&vy, const Vec3_tpl&vz) - { - m00 = F(vx.x); - m01 = F(vy.x); - m02 = F(vz.x); - m10 = F(vx.y); - m11 = F(vy.y); - m12 = F(vz.y); - m20 = F(vx.z); - m21 = F(vy.z); - m22 = F(vz.z); - } - - - - - - //CONSTRUCTOR for identical float-types. It converts a Diag33 into a Matrix33. - //Matrix33(diag33); - ILINE Matrix33_tpl(const Diag33_tpl&d) - { - assert(d.IsValid()); - m00 = d.x; - m01 = 0; - m02 = 0; - m10 = 0; - m11 = d.y; - m12 = 0; - m20 = 0; - m21 = 0; - m22 = d.z; - } - //CONSTRUCTOR for different float-types. It converts a Diag33 into a Matrix33 and also converts between double/float. - //Matrix33(diag33); - template - ILINE Matrix33_tpl(const Diag33_tpl&d) - { - assert(d.IsValid()); - m00 = F(d.x); - m01 = 0; - m02 = 0; - m10 = 0; - m11 = F(d.y); - m12 = 0; - m20 = 0; - m21 = 0; - m22 = F(d.z); - } - - - - //CONSTRUCTOR for identical float-types - //Matrix33 m=m33; - ILINE Matrix33_tpl(const Matrix33_tpl&m) - { - assert(m.IsValid()); - m00 = m.m00; - m01 = m.m01; - m02 = m.m02; - m10 = m.m10; - m11 = m.m11; - m12 = m.m12; - m20 = m.m20; - m21 = m.m21; - m22 = m.m22; - } - //CONSTRUCTOR for different float-types which converts between double/float - //Matrix33 m=m33r; - template - ILINE Matrix33_tpl(const Matrix33_tpl&m) - { - assert(m.IsValid()); - m00 = F(m.m00); - m01 = F(m.m01); - m02 = F(m.m02); - m10 = F(m.m10); - m11 = F(m.m11); - m12 = F(m.m12); - m20 = F(m.m20); - m21 = F(m.m21); - m22 = F(m.m22); - } - - - - //CONSTRUCTOR for identical float-types. It converts a Matrix34 into a Matrix33. - //Needs to be 'explicit' because we loose the translation vector in the conversion process - //Matrix33(m34); - explicit ILINE Matrix33_tpl(const Matrix34_tpl&m) - { - assert(m.IsValid()); - m00 = m.m00; - m01 = m.m01; - m02 = m.m02; - m10 = m.m10; - m11 = m.m11; - m12 = m.m12; - m20 = m.m20; - m21 = m.m21; - m22 = m.m22; - } - //CONSTRUCTOR for different float-types. It converts a Matrix34 into a Matrix33 and converts between double/float. - //Needs to be 'explicit' because we loose the translation vector in the conversion process - //Matrix33(m34r); - template - explicit ILINE Matrix33_tpl(const Matrix34_tpl&m) - { - assert(m.IsValid()); - m00 = F(m.m00); - m01 = F(m.m01); - m02 = F(m.m02); - m10 = F(m.m10); - m11 = F(m.m11); - m12 = F(m.m12); - m20 = F(m.m20); - m21 = F(m.m21); - m22 = F(m.m22); - } - - - - - //CONSTRUCTOR for identical float-types. It converts a Matrix44 into a Matrix33. - //Needs to be 'explicit' because we loose the translation vector and the 3rd row in the conversion process - //Matrix33(m44); - explicit ILINE Matrix33_tpl(const Matrix44_tpl&m) - { - assert(m.IsValid()); - m00 = m.m00; - m01 = m.m01; - m02 = m.m02; - m10 = m.m10; - m11 = m.m11; - m12 = m.m12; - m20 = m.m20; - m21 = m.m21; - m22 = m.m22; - } - //CONSTRUCTOR for different float-types. It converts a Matrix44 into a Matrix33 and converts between double/float. - //Needs to be 'explicit' because we loose the translation vector and the 3rd row in the conversion process - //Matrix33(m44r); - template - explicit ILINE Matrix33_tpl(const Matrix44_tpl&m) - { - assert(m.IsValid()); - m00 = F(m.m00); - m01 = F(m.m01); - m02 = F(m.m02); - m10 = F(m.m10); - m11 = F(m.m11); - m12 = F(m.m12); - m20 = F(m.m20); - m21 = F(m.m21); - m22 = F(m.m22); - } - - //CONSTRUCTOR for identical float-types. It converts a Quat into a Matrix33. - //Needs to be 'explicit' because we loose fp-precision in the conversion process - //Matrix33(quat); - explicit ILINE Matrix33_tpl(const Quat_tpl&q) - { - assert(q.IsValid(0.05f)); - Vec3_tpl v2 = q.v + q.v; - F xx = 1 - v2.x * q.v.x; - F yy = v2.y * q.v.y; - F xw = v2.x * q.w; - F xy = v2.y * q.v.x; - F yz = v2.z * q.v.y; - F yw = v2.y * q.w; - F xz = v2.z * q.v.x; - F zz = v2.z * q.v.z; - F zw = v2.z * q.w; - m00 = 1 - yy - zz; - m01 = xy - zw; - m02 = xz + yw; - m10 = xy + zw; - m11 = xx - zz; - m12 = yz - xw; - m20 = xz - yw; - m21 = yz + xw; - m22 = xx - yy; - } - - //CONSTRUCTOR for different float-types. It converts a Quat into a Matrix33 and converts between double/float. - //Needs to be 'explicit' because we loose fp-precision in the conversion process - //Matrix33(quatr); - template - explicit ILINE Matrix33_tpl(const Quat_tpl&q) - { - assert(q.IsValid(0.05f)); - Vec3_tpl v2 = q.v + q.v; - F1 xx = 1 - v2.x * q.v.x; - F1 yy = v2.y * q.v.y; - F1 xw = v2.x * q.w; - F1 xy = v2.y * q.v.x; - F1 yz = v2.z * q.v.y; - F1 yw = v2.y * q.w; - F1 xz = v2.z * q.v.x; - F1 zz = v2.z * q.v.z; - F1 zw = v2.z * q.w; - m00 = F(1 - yy - zz); - m01 = F(xy - zw); - m02 = F(xz + yw); - m10 = F(xy + zw); - m11 = F(xx - zz); - m12 = F(yz - xw); - m20 = F(xz - yw); - m21 = F(yz + xw); - m22 = F(xx - yy); - } - - - //CONSTRUCTOR for identical float-types. It converts a Euler Angle into a Matrix33. - //Needs to be 'explicit' because we loose fp-precision in the conversion process - //Matrix33(Ang3(1,2,3)); - explicit ILINE Matrix33_tpl(const Ang3_tpl&ang) - { - assert(ang.IsValid()); - SetRotationXYZ(ang); - } - //CONSTRUCTOR for different float-types. It converts a Euler Angle into a Matrix33 and converts between double/float. . - //Needs to be 'explicit' because we loose fp-precision in the conversion process - //Matrix33(Ang3r(1,2,3)); - template - explicit ILINE Matrix33_tpl(const Ang3_tpl&ang) - { - assert(ang.IsValid()); - SetRotationXYZ(Ang3_tpl(F(ang.x), F(ang.y), F(ang.z))); - } - - - - - //Bracket OPERATOR: initializes a Matrix33 with 9 floats. - //Matrix33 m; m(0,1,2, 3,4,5, 6,7,8); - ILINE void operator () (F x00, F x01, F x02, F x10, F x11, F x12, F x20, F x21, F x22) - { - m00 = x00; - m01 = x01; - m02 = x02; - m10 = x10; - m11 = x11; - m12 = x12; - m20 = x20; - m21 = x21; - m22 = x22; - assert(IsValid()); - } - - - //--------------------------------------------------------------------------------------- - - ILINE void SetIdentity(void) - { - m00 = 1; - m01 = 0; - m02 = 0; - m10 = 0; - m11 = 1; - m12 = 0; - m20 = 0; - m21 = 0; - m22 = 1; - } - - ILINE static Matrix33_tpl CreateIdentity() - { - Matrix33_tpl m33; - m33.SetIdentity(); - return m33; - } - - ILINE void SetZero() - { - m00 = 0; - m01 = 0; - m02 = 0; - m10 = 0; - m11 = 0; - m12 = 0; - m20 = 0; - m21 = 0; - m22 = 0; - } - - - /*! - * Create a rotation matrix around an arbitrary axis (Eulers Theorem). - * The axis is specified as a normalized Vec3. The angle is assumed to be in radians. - * - * Example: - * Matrix34 m34; - * Vec3 axis=GetNormalized( Vec3(-1.0f,-0.3f,0.0f) ); - * m34.SetRotationAA( rad, axis ); - */ - ILINE void SetRotationAA(F angle, const Vec3_tpl axis) - { - F s, c; - sincos_tpl(angle, &s, &c); - SetRotationAA(c, s, axis); - } - ILINE static Matrix33_tpl CreateRotationAA(const F rad, const Vec3_tpl& axis) - { - Matrix33_tpl m33; - m33.SetRotationAA(rad, axis); - return m33; - } - - - ILINE void SetRotationAA(F c, F s, const Vec3_tpl& axis) - { - assert(axis.IsUnit(0.001f)); - F mc = 1 - c; - m00 = mc * axis.x * axis.x + c; - m01 = mc * axis.x * axis.y - axis.z * s; - m02 = mc * axis.x * axis.z + axis.y * s; - m10 = mc * axis.y * axis.x + axis.z * s; - m11 = mc * axis.y * axis.y + c; - m12 = mc * axis.y * axis.z - axis.x * s; - m20 = mc * axis.z * axis.x - axis.y * s; - m21 = mc * axis.z * axis.y + axis.x * s; - m22 = mc * axis.z * axis.z + c; - } - ILINE static Matrix33_tpl CreateRotationAA(F c, F s, const Vec3_tpl& axis) - { - Matrix33_tpl m33; - m33.SetRotationAA(c, s, axis); - return m33; - } - - ILINE void SetRotationAA(const Vec3_tpl axis) - { - F angle = axis.GetLength(); - if (angle == F(0)) - { - SetIdentity(); - } - else - { - SetRotationAA(angle, axis / angle); - } - } - ILINE static Matrix33_tpl CreateRotationAA(const Vec3_tpl& axis) - { - Matrix33_tpl m33; - m33.SetRotationAA(axis); - return m33; - } - - - - /*! - * - * Create rotation-matrix about X axis using an angle. - * The angle is assumed to be in radians. - * - * Example: - * Matrix m33; - * m33.SetRotationX(0.5f); - */ - ILINE void SetRotationX(const f32 rad) - { - F s, c; - sincos_tpl(rad, &s, &c); - m00 = 1.0f; - m01 = 0.0f; - m02 = 0.0f; - m10 = 0.0f; - m11 = c; - m12 = -s; - m20 = 0.0f; - m21 = s; - m22 = c; - } - ILINE static Matrix33_tpl CreateRotationX(const f32 rad) - { - Matrix33_tpl m33; - m33.SetRotationX(rad); - return m33; - } - - ILINE void SetRotationY(const f32 rad) - { - F s, c; - sincos_tpl(rad, &s, &c); - m00 = c; - m01 = 0; - m02 = s; - m10 = 0; - m11 = 1; - m12 = 0; - m20 = -s; - m21 = 0; - m22 = c; - } - ILINE static Matrix33_tpl CreateRotationY(const f32 rad) - { - Matrix33_tpl m33; - m33.SetRotationY(rad); - return m33; - } - - ILINE void SetRotationZ(const f32 rad) - { - F s, c; - sincos_tpl(rad, &s, &c); - m00 = c; - m01 = -s; - m02 = 0.0f; - m10 = s; - m11 = c; - m12 = 0.0f; - m20 = 0.0f; - m21 = 0.0f; - m22 = 1.0f; - } - ILINE static Matrix33_tpl CreateRotationZ(const f32 rad) - { - Matrix33_tpl m33; - m33.SetRotationZ(rad); - return m33; - } - - ILINE void SetRotationXYZ(const Ang3_tpl& rad) - { - assert(rad.IsValid()); - F sx, cx; - sincos_tpl(rad.x, &sx, &cx); - F sy, cy; - sincos_tpl(rad.y, &sy, &cy); - F sz, cz; - sincos_tpl(rad.z, &sz, &cz); - F sycz = (sy * cz), sysz = (sy * sz); - m00 = cy * cz; - m01 = sycz * sx - cx * sz; - m02 = sycz * cx + sx * sz; - m10 = cy * sz; - m11 = sysz * sx + cx * cz; - m12 = sysz * cx - sx * cz; - m20 = -sy; - m21 = cy * sx; - m22 = cy * cx; - } - ILINE static Matrix33_tpl CreateRotationXYZ(const Ang3_tpl& rad) - { - assert(rad.IsValid()); - Matrix33_tpl m33; - m33.SetRotationXYZ(rad); - return m33; - } - - - - - /*! - * Creates a rotation matrix that rotates the vector "v0" into "v1". - * - * a) If both vectors are exactly parallel it returns an identity-matrix - * b) CAUTION: If both vectors are exactly diametrical it returns a matrix that rotates - * pi-radians about a "random" axis that is orthogonal to v0. - * c) CAUTION: If both vectors are almost diametrical we have to normalize - * a very small vector and the result is inaccurate. It is recommended to use this - * function with 64-bit precision. - */ - ILINE void SetRotationV0V1(const Vec3_tpl& v0, const Vec3_tpl& v1) - { - assert((fabs_tpl(1 - (v0 | v0))) < 0.01); //check if unit-vector - assert((fabs_tpl(1 - (v1 | v1))) < 0.01); //check if unit-vector - F dot = v0 | v1; - if (dot < F(-0.9999f)) - { - Vec3d axis = v0.GetOrthogonal().GetNormalized(); - m00 = F(2 * axis.x * axis.x - 1); - m01 = F(2 * axis.x * axis.y); - m02 = F(2 * axis.x * axis.z); - m10 = F(2 * axis.y * axis.x); - m11 = F(2 * axis.y * axis.y - 1); - m12 = F(2 * axis.y * axis.z); - m20 = F(2 * axis.z * axis.x); - m21 = F(2 * axis.z * axis.y); - m22 = F(2 * axis.z * axis.z - 1); - } - else - { - Vec3_tpl v = v0 % v1; - F h = 1 / (1 + dot); - m00 = F(dot + h * v.x * v.x); - m01 = F(h * v.x * v.y - v.z); - m02 = F(h * v.x * v.z + v.y); - m10 = F(h * v.x * v.y + v.z); - m11 = F(dot + h * v.y * v.y); - m12 = F(h * v.y * v.z - v.x); - m20 = F(h * v.x * v.z - v.y); - m21 = F(h * v.y * v.z + v.x); - m22 = F(dot + h * v.z * v.z); - } - } - ILINE static Matrix33_tpl CreateRotationV0V1(const Vec3_tpl& v0, const Vec3_tpl& v1) - { - Matrix33_tpl m33; - m33.SetRotationV0V1(v0, v1); - return m33; - } - - - - - - - /*! - * - * \param vdir normalized view direction. - * \param roll radiant to rotate about Y-axis. - * - * Given a view-direction and a radiant to rotate about Y-axis, this function builds a 3x3 look-at matrix - * using only simple vector arithmetic. This function is always using the implicit up-vector Vec3(0,0,1). - * The view-direction is always stored in column(1). - * IMPORTANT: The view-vector is assumed to be normalized, because all trig-values for the orientation are being - * extracted directly out of the vector. This function must NOT be called with a view-direction - * that is close to Vec3(0,0,1) or Vec3(0,0,-1). If one of these rules is broken, the function returns a matrix - * with an undefined rotation about the Z-axis. - * - * Rotation order for the look-at-matrix is Z-X-Y. (Zaxis=YAW / Xaxis=PITCH / Yaxis=ROLL) - * - * COORDINATE-SYSTEM - * - * z-axis - * ^ - * | - * | y-axis - * | / - * | / - * |/ - * +---------------> x-axis - * - * Example: - * Matrix33 orientation=Matrix33::CreateRotationVDir( Vec3(0,1,0), 0 ); - */ - ILINE void SetRotationVDir(const Vec3_tpl& vdir) - { - assert((fabs_tpl(1 - (vdir | vdir))) < 0.01); //check if unit-vector - //set default initialisation for up-vector - m00 = 1; - m01 = 0; - m02 = 0; - m10 = 0; - m11 = 0; - m12 = -vdir.z; - m20 = 0; - m21 = vdir.z; - m22 = 0; - //calculate look-at matrix - F l = sqrt(vdir.x * vdir.x + vdir.y * vdir.y); - if (l > F(0.00001)) - { - F xl = -vdir.x / l; - F yl = vdir.y / l; - m00 = F(yl); - m01 = F(vdir.x); - m02 = F(xl * vdir.z); - m10 = F(xl); - m11 = F(vdir.y); - m12 = F(-vdir.z * yl); - m20 = 0; - m21 = F(vdir.z); - m22 = F(l); - } - } - ILINE static Matrix33_tpl CreateRotationVDir(const Vec3_tpl vdir) - { - Matrix33_tpl m33; - m33.SetRotationVDir(vdir); - return m33; - } - - - //look-at matrix with roll - ILINE void SetRotationVDir(const Vec3_tpl& vdir, F roll) - { - SetRotationVDir(vdir); - F s, c; - sincos_tpl(roll, &s, &c); - F x00 = m00, x10 = m10; - m00 = m00 * c - m02 * s; - m02 = x00 * s + m02 * c; - m10 = m10 * c - m12 * s; - m12 = x10 * s + m12 * c; - m20 = -m22 * s; - m22 = m22 * c; - } - ILINE static Matrix33_tpl CreateRotationVDir(const Vec3_tpl& vdir, F roll) - { - Matrix33_tpl m33; - m33.SetRotationVDir(vdir, roll); - return m33; - } - - - //! calculate 2 vector that form a orthogonal base with a given input vector (by M.M.) - //! /param invDirection input direction (has to be normalized) - //! /param outvA first output vector that is perpendicular to the input direction - //! /param outvB second output vector that is perpendicular the input vector and the first output vector - ILINE static Matrix33_tpl CreateOrthogonalBase(const Vec3& invDirection) - { - Vec3 outvA; - if (invDirection.z < -0.5f || invDirection.z > 0.5f) - { - outvA = Vec3(invDirection.z, invDirection.y, -invDirection.x); - } - else - { - outvA = Vec3(invDirection.y, -invDirection.x, invDirection.z); - } - Vec3 outvB = (invDirection % outvA).GetNormalized(); - outvA = (invDirection % outvB).GetNormalized(); - return CreateFromVectors(invDirection, outvA, outvB); - } - - - ////////////////////////////////////////////////////////////////////////// - ILINE static Matrix33_tpl CreateOrientation(const Vec3_tpl& dir, const Vec3_tpl& up, float rollAngle) - { - // LookAt transform. - Vec3 xAxis, yAxis, zAxis; - Vec3 upVector = up; - if (dir.IsZeroFast()) - { - Matrix33_tpl tm; - tm.SetIdentity(); - return tm; - } - yAxis = dir.GetNormalized(); - - if (yAxis.x == 0 && yAxis.y == 0 && up.IsEquivalent(Vec3_tpl(0, 0, 1.0f))) - { - upVector.Set(-yAxis.z, 0, 0); - } - - xAxis = (upVector % yAxis).GetNormalized(); - zAxis = (xAxis % yAxis).GetNormalized(); - - Matrix33_tpl tm; - tm.SetFromVectors(xAxis, yAxis, zAxis); - - if (rollAngle != 0) - { - Matrix33_tpl RollMtx; - RollMtx.SetRotationY(rollAngle); - tm = tm * RollMtx; - } - return tm; - } - - - /*! - * Direct-Matrix-Slerp: for the sake of completeness, I have included the following expression - * for Spherical-Linear-Interpolation without using quaternions. This is much faster then converting - * both matrices into quaternions in order to do a quaternion slerp and then converting the slerped - * quaternion back into a matrix. - * This is a high-precision calculation. Given two orthonormal 3x3 matrices this function calculates - * the shortest possible interpolation-path between the two rotations. The interpolation curve forms - * a great arc on the rotation sphere (geodesic). Not only does Slerp follow a great arc it follows - * the shortest great arc. Furthermore Slerp has constant angular velocity. All in all Slerp is the - * optimal interpolation curve between two rotations. - * - * STABILITY PROBLEM: There are two singularities at angle=0 and angle=PI. At 0 the interpolation-axis - * is arbitrary, which means any axis will produce the same result because we have no rotation. Thats - * why I'm using (1,0,0). At PI the rotations point away from each other and the interpolation-axis - * is unpredictable. In this case I'm also using the axis (1,0,0). If the angle is ~0 or ~PI, then we - * have to normalize a very small vector and this can cause numerical instability. The quaternion-slerp - * has exactly the same problems. - * Ivo - * Example: - * Matrix33 slerp=Matrix33::CreateSlerp( m,n,0.333f ); - */ - ILINE void SetSlerp(const Matrix33_tpl& m, const Matrix33_tpl& n, F t) - { - assert(m.IsValid()); - assert(n.IsValid()); - //calculate delta-rotation between m and n (=39 flops) - Matrix33_tpl d, i; - d.m00 = m.m00 * n.m00 + m.m10 * n.m10 + m.m20 * n.m20; - d.m01 = m.m00 * n.m01 + m.m10 * n.m11 + m.m20 * n.m21; - d.m02 = m.m00 * n.m02 + m.m10 * n.m12 + m.m20 * n.m22; - d.m10 = m.m01 * n.m00 + m.m11 * n.m10 + m.m21 * n.m20; - d.m11 = m.m01 * n.m01 + m.m11 * n.m11 + m.m21 * n.m21; - d.m12 = m.m01 * n.m02 + m.m11 * n.m12 + m.m21 * n.m22; - d.m20 = d.m01 * d.m12 - d.m02 * d.m11; - d.m21 = d.m02 * d.m10 - d.m00 * d.m12; - d.m22 = d.m00 * d.m11 - d.m01 * d.m10; - assert(d.IsOrthonormalRH(0.0001f)); - - Vec3_tpl axis(d.m21 - d.m12, d.m02 - d.m20, d.m10 - d.m01); - F l = sqrt(axis | axis); - if (l > F(0.00001)) - { - axis /= l; - } - else - { - axis(1, 0, 0); - } - i.SetRotationAA(acos(clamp_tpl((d.m00 + d.m11 + d.m22 - 1) * 0.5f, F(-1), F(+1))) * t, axis); //angle interpolation and calculation of new delta-matrix (=26 flops) - - //final concatenation (=39 flops) - m00 = F(m.m00 * i.m00 + m.m01 * i.m10 + m.m02 * i.m20); - m01 = F(m.m00 * i.m01 + m.m01 * i.m11 + m.m02 * i.m21); - m02 = F(m.m00 * i.m02 + m.m01 * i.m12 + m.m02 * i.m22); - m10 = F(m.m10 * i.m00 + m.m11 * i.m10 + m.m12 * i.m20); - m11 = F(m.m10 * i.m01 + m.m11 * i.m11 + m.m12 * i.m21); - m12 = F(m.m10 * i.m02 + m.m11 * i.m12 + m.m12 * i.m22); - m20 = m01 * m12 - m02 * m11; - m21 = m02 * m10 - m00 * m12; - m22 = m00 * m11 - m01 * m10; - assert(this->IsOrthonormalRH(0.0001f)); - } - ILINE static Matrix33_tpl CreateSlerp(const Matrix33_tpl m, const Matrix33_tpl n, F t) - { - Matrix33_tpl m33; - m33.SetSlerp(m, n, t); - return m33; - } - - - ILINE void SetScale(const Vec3_tpl& s) - { - m00 = s.x; - m01 = 0; - m02 = 0; - m10 = 0; - m11 = s.y; - m12 = 0; - m20 = 0; - m21 = 0; - m22 = s.z; - } - ILINE static Matrix33_tpl CreateScale(const Vec3_tpl& s) { Matrix33_tpl m; m.SetScale(s); return m; } - - - //NOTE: all vectors are stored in columns - ILINE void SetFromVectors(const Vec3_tpl& vx, const Vec3_tpl& vy, const Vec3_tpl& vz) - { - m00 = vx.x; - m01 = vy.x; - m02 = vz.x; - m10 = vx.y; - m11 = vy.y; - m12 = vz.y; - m20 = vx.z; - m21 = vy.z; - m22 = vz.z; - } - ILINE static Matrix33_tpl CreateFromVectors(const Vec3_tpl& vx, const Vec3_tpl& vy, const Vec3_tpl& vz) { Matrix33_tpl dst; dst.SetFromVectors(vx, vy, vz); return dst; } - - - - - ILINE void Transpose() // in-place transposition - { - F t; - t = m01; - m01 = m10; - m10 = t; - t = m02; - m02 = m20; - m20 = t; - t = m12; - m12 = m21; - m21 = t; - } - ILINE Matrix33_tpl GetTransposed() const - { - Matrix33_tpl dst; - dst.m00 = m00; - dst.m01 = m10; - dst.m02 = m20; - dst.m10 = m01; - dst.m11 = m11; - dst.m12 = m21; - dst.m20 = m02; - dst.m21 = m12; - dst.m22 = m22; - return dst; - } - ILINE Matrix33_tpl T() const { return GetTransposed(); } - - ILINE Matrix33_tpl& Fabs() - { - m00 = fabs_tpl(m00); - m01 = fabs_tpl(m01); - m02 = fabs_tpl(m02); - m10 = fabs_tpl(m10); - m11 = fabs_tpl(m11); - m12 = fabs_tpl(m12); - m20 = fabs_tpl(m20); - m21 = fabs_tpl(m21); - m22 = fabs_tpl(m22); - return *this; - } - ILINE Matrix33_tpl GetFabs() const { Matrix33_tpl m = *this; m.Fabs(); return m; } - - - ILINE void Adjoint(void) - { - //rescue members - Matrix33_tpl m = *this; - //calculate the adjoint-matrix - m00 = m.m11 * m.m22 - m.m12 * m.m21; - m01 = m.m12 * m.m20 - m.m10 * m.m22; - m02 = m.m10 * m.m21 - m.m11 * m.m20; - m10 = m.m21 * m.m02 - m.m22 * m.m01; - m11 = m.m22 * m.m00 - m.m20 * m.m02; - m12 = m.m20 * m.m01 - m.m21 * m.m00; - m20 = m.m01 * m.m12 - m.m02 * m.m11; - m21 = m.m02 * m.m10 - m.m00 * m.m12; - m22 = m.m00 * m.m11 - m.m01 * m.m10; - } - ILINE Matrix33_tpl GetAdjoint() const { Matrix33_tpl dst = *this; dst.Adjoint(); return dst; } - - - - /*! - * - * calculate a real inversion of a Matrix33. - * an inverse-matrix is an UnDo-matrix for all kind of transformations - * NOTE: if the return value of Invert33() is zero, then the inversion failed! - * - * Example 1: - * Matrix33 im33; - * bool st=i33.Invert(); - * assert(st); - * - * Example 2: - * matrix33 im33=Matrix33::GetInverted(m33); - */ - ILINE bool Invert(void) - { - //rescue members - Matrix33_tpl m = *this; - //calculate the cofactor-matrix (=transposed adjoint-matrix) - m00 = m.m22 * m.m11 - m.m12 * m.m21; - m01 = m.m02 * m.m21 - m.m22 * m.m01; - m02 = m.m12 * m.m01 - m.m02 * m.m11; - m10 = m.m12 * m.m20 - m.m22 * m.m10; - m11 = m.m22 * m.m00 - m.m02 * m.m20; - m12 = m.m02 * m.m10 - m.m12 * m.m00; - m20 = m.m10 * m.m21 - m.m20 * m.m11; - m21 = m.m20 * m.m01 - m.m00 * m.m21; - m22 = m.m00 * m.m11 - m.m10 * m.m01; - // calculate determinant - F det = (m.m00 * m00 + m.m10 * m01 + m.m20 * m02); - if (fabs_tpl(det) < 1E-20f) - { - return 0; - } - //divide the cofactor-matrix by the determinant - F idet = (F)1.0 / det; - m00 *= idet; - m01 *= idet; - m02 *= idet; - m10 *= idet; - m11 *= idet; - m12 *= idet; - m20 *= idet; - m21 *= idet; - m22 *= idet; - return 1; - } - ILINE Matrix33_tpl GetInverted() const - { - Matrix33_tpl dst = *this; - dst.Invert(); - return dst; - } - - ILINE Vec3_tpl TransformVector(const Vec3_tpl& v) const - { - return Vec3_tpl(m00 * v.x + m01 * v.y + m02 * v.z, m10 * v.x + m11 * v.y + m12 * v.z, m20 * v.x + m21 * v.y + m22 * v.z); - } - - - - //! make a right-handed orthonormal matrix. - ILINE void OrthonormalizeFast() - { - Vec3 x = Vec3(m00, m10, m20).GetNormalized(); - Vec3 y = (Vec3(m02, m12, m22) % x).GetNormalized(); - Vec3 z = (x % y); - m00 = x.x; - m01 = y.x; - m02 = z.x; - m10 = x.y; - m11 = y.y; - m12 = z.y; - m20 = x.z; - m21 = y.z; - m22 = z.z; - } - - ILINE f32 Determinant() const - { - return (m00 * m11 * m22) + (m01 * m12 * m20) + (m02 * m10 * m21) - (m02 * m11 * m20) - (m00 * m12 * m21) - (m01 * m10 * m22); - } - - //-------------------------------------------------------------------------------- - //---- helper functions to access matrix-members ------------ - //-------------------------------------------------------------------------------- - F* GetData() { return &m00; } - const F* GetData() const { return &m00; } - - ILINE F operator () (uint32 i, uint32 j) const { assert ((i < 3) && (j < 3)); const F* const p_data = (const F*)(&m00); return p_data[i * 3 + j]; } - ILINE F& operator () (uint32 i, uint32 j) { assert ((i < 3) && (j < 3)); F* p_data = (F*)(&m00); return p_data[i * 3 + j]; } - ILINE void SetRow(int i, const Vec3_tpl& v) { assert(i < 3); F* p = (F*)(&m00); p[0 + 3 * i] = v.x; p[1 + 3 * i] = v.y; p[2 + 3 * i] = v.z; } - ILINE Vec3_tpl GetRow(int i) const { assert(i < 3); const F* const p = (const F*)(&m00); return Vec3_tpl(p[0 + 3 * i], p[1 + 3 * i], p[2 + 3 * i]); } - ILINE void SetColumn(int i, const Vec3_tpl& v) { assert(i < 3); F* p = (F*)(&m00); p[i + 3 * 0] = v.x; p[i + 3 * 1] = v.y; p[i + 3 * 2] = v.z; } - ILINE Vec3_tpl GetColumn(int i) const { assert(i < 3); const F* const p = (const F*)(&m00); return Vec3_tpl(p[i + 3 * 0], p[i + 3 * 1], p[i + 3 * 2]); } - - - ILINE Vec3_tpl GetColumn0() const { return Vec3_tpl (m00, m10, m20); } - ILINE Vec3_tpl GetColumn1() const { return Vec3_tpl (m01, m11, m21); } - ILINE Vec3_tpl GetColumn2() const { return Vec3_tpl (m02, m12, m22); } - ILINE void SetColumn0(const Vec3_tpl& v) { m00 = v.x; m10 = v.y; m20 = v.z; } - ILINE void SetColumn1(const Vec3_tpl& v) { m01 = v.x; m11 = v.y; m21 = v.z; } - ILINE void SetColumn2(const Vec3_tpl& v) { m02 = v.x; m12 = v.y; m22 = v.z; } - - ILINE Matrix33_tpl& operator *= (F op) - { - m00 *= op; - m01 *= op; - m02 *= op; - m10 *= op; - m11 *= op; - m12 *= op; - m20 *= op; - m21 *= op; - m22 *= op; - return *this; - } - - ILINE Matrix33_tpl& operator /= (F op) - { - F iop = (F)1.0 / op; - m00 *= iop; - m01 *= iop; - m02 *= iop; - m10 *= iop; - m11 *= iop; - m12 *= iop; - m20 *= iop; - m21 *= iop; - m22 *= iop; - return *this; - } - - ILINE static bool IsEquivalent(const Matrix33_tpl& m0, const Matrix33_tpl& m1, F e = VEC_EPSILON) - { - return ( - (fabs_tpl(m0.m00 - m1.m00) <= e) && (fabs_tpl(m0.m01 - m1.m01) <= e) && (fabs_tpl(m0.m02 - m1.m02) <= e) && - (fabs_tpl(m0.m10 - m1.m10) <= e) && (fabs_tpl(m0.m11 - m1.m11) <= e) && (fabs_tpl(m0.m12 - m1.m12) <= e) && - (fabs_tpl(m0.m20 - m1.m20) <= e) && (fabs_tpl(m0.m21 - m1.m21) <= e) && (fabs_tpl(m0.m22 - m1.m22) <= e) - ); - } - - ILINE bool IsIdentity(F e) const - { - return ( - (fabs_tpl((F)1 - m00) <= e) && (fabs_tpl(m01) <= e) && (fabs_tpl(m02) <= e) && - (fabs_tpl(m10) <= e) && (fabs_tpl((F)1 - m11) <= e) && (fabs_tpl(m12) <= e) && - (fabs_tpl(m20) <= e) && (fabs_tpl(m21) <= e) && (fabs_tpl((F)1 - m22) <= e) - ); - } - - ILINE bool IsIdentity() const - { - return 0 == (fabs_tpl((F)1 - m00) + fabs_tpl(m01) + fabs_tpl(m02) + fabs_tpl(m10) + fabs_tpl((F)1 - m11) + fabs_tpl(m12) + fabs_tpl(m20) + fabs_tpl(m21) + fabs_tpl((F)1 - m22)); - } - ILINE int IsZero() const - { - return 0 == (fabs_tpl(m00) + fabs_tpl(m01) + fabs_tpl(m02) + fabs_tpl(m10) + fabs_tpl(m11) + fabs_tpl(m12) + fabs_tpl(m20) + fabs_tpl(m21) + fabs_tpl(m22)); - } - - //check if we have an orthonormal-base (general case, works even with reflection matrices) - ILINE int IsOrthonormal(F threshold = 0.001) const - { - f32 d0 = fabs_tpl(GetColumn0() | GetColumn1()); - if (d0 > threshold) - { - return 0; - } - f32 d1 = fabs_tpl(GetColumn0() | GetColumn2()); - if (d1 > threshold) - { - return 0; - } - f32 d2 = fabs_tpl(GetColumn1() | GetColumn2()); - if (d2 > threshold) - { - return 0; - } - int a = (fabs_tpl(1 - (GetColumn0() | GetColumn0()))) < threshold; - int b = (fabs_tpl(1 - (GetColumn1() | GetColumn1()))) < threshold; - int c = (fabs_tpl(1 - (GetColumn2() | GetColumn2()))) < threshold; - return a & b & c; - } - - //check if we have an orthonormal-base (assuming we are using a right-handed coordinate system) - ILINE int IsOrthonormalRH(F threshold = 0.002) const - { - Vec3_tpl x = GetColumn0(); - Vec3_tpl y = GetColumn1(); - Vec3_tpl z = GetColumn2(); - bool a = x.IsEquivalent(y % z, threshold); - bool b = y.IsEquivalent(z % x, threshold); - bool c = z.IsEquivalent(x % y, threshold); - a &= x.IsUnit(0.01f); - b &= y.IsUnit(0.01f); - c &= z.IsUnit(0.01f); - return a & b & c; - } - - ////////////////////////////////////////////////////////////////////////// - // Remove uniform scale from matrix. - ILINE void NoScale() - { - *this /= GetColumn(0).GetLength(); - } - - ILINE bool IsValid() const - { - if (!NumberValid(m00)) - { - return false; - } - if (!NumberValid(m01)) - { - return false; - } - if (!NumberValid(m02)) - { - return false; - } - if (!NumberValid(m10)) - { - return false; - } - if (!NumberValid(m11)) - { - return false; - } - if (!NumberValid(m12)) - { - return false; - } - if (!NumberValid(m20)) - { - return false; - } - if (!NumberValid(m21)) - { - return false; - } - if (!NumberValid(m22)) - { - return false; - } - return true; - } - - - AUTO_STRUCT_INFO -}; - -/////////////////////////////////////////////////////////////////////////////// -// Typedefs // -/////////////////////////////////////////////////////////////////////////////// - -typedef Matrix33_tpl Matrix33; //always 32 bit -typedef Matrix33_tpl Matrix33d; //always 64 bit -typedef Matrix33_tpl Matrix33r; //variable float precision. depending on the target system it can be between 32, 64 or 80 bit -typedef _MS_ALIGN(16) Matrix33_tpl _ALIGN (16) Matrix33A; - -//---------------------------------------------------------------------------------- -//---------------------------------------------------------------------------------- -//---------------------------------------------------------------------------------- -//------------- implementation of Matrix33 ------------------------------ -//---------------------------------------------------------------------------------- -//---------------------------------------------------------------------------------- -//---------------------------------------------------------------------------------- - -template -ILINE Matrix33_tpl operator*(const Matrix33_tpl& l, const Diag33_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix33_tpl res; - res.m00 = l.m00 * r.x; - res.m01 = l.m01 * r.y; - res.m02 = l.m02 * r.z; - res.m10 = l.m10 * r.x; - res.m11 = l.m11 * r.y; - res.m12 = l.m12 * r.z; - res.m20 = l.m20 * r.x; - res.m21 = l.m21 * r.y; - res.m22 = l.m22 * r.z; - return res; -} -template -ILINE Matrix33_tpl& operator *= (Matrix33_tpl& l, const Diag33_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - l.m00 *= r.x; - l.m01 *= r.y; - l.m02 *= r.z; - l.m10 *= r.x; - l.m11 *= r.y; - l.m12 *= r.z; - l.m20 *= r.x; - l.m21 *= r.y; - l.m22 *= r.z; - return l; -} - -//Matrix33 operations with another Matrix33 -template -ILINE Matrix33_tpl operator * (const Matrix33_tpl& l, const Matrix33_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix33_tpl m; - m.m00 = l.m00 * r.m00 + l.m01 * r.m10 + l.m02 * r.m20; - m.m01 = l.m00 * r.m01 + l.m01 * r.m11 + l.m02 * r.m21; - m.m02 = l.m00 * r.m02 + l.m01 * r.m12 + l.m02 * r.m22; - m.m10 = l.m10 * r.m00 + l.m11 * r.m10 + l.m12 * r.m20; - m.m11 = l.m10 * r.m01 + l.m11 * r.m11 + l.m12 * r.m21; - m.m12 = l.m10 * r.m02 + l.m11 * r.m12 + l.m12 * r.m22; - m.m20 = l.m20 * r.m00 + l.m21 * r.m10 + l.m22 * r.m20; - m.m21 = l.m20 * r.m01 + l.m21 * r.m11 + l.m22 * r.m21; - m.m22 = l.m20 * r.m02 + l.m21 * r.m12 + l.m22 * r.m22; - return m; -} - - -/*! -* -* Implements the multiplication operator: Matrix34=Matrix33*Matrix34 -* -* Matrix33 and Matrix34 are specified in collumn order for a right-handed coordinate-system. -* AxB = operation B followed by operation A. -* A multiplication takes 36 muls and 24 adds. -* -* Example: -* Matrix33 m33=Matrix33::CreateRotationX(1.94192f);; -* Matrix34 m34=Matrix34::CreateRotationZ(3.14192f); -* Matrix34 result=m33*m34; -* -*/ -template -ILINE Matrix34_tpl operator * (const Matrix33_tpl& l, const Matrix34_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix34_tpl m; - m.m00 = l.m00 * r.m00 + l.m01 * r.m10 + l.m02 * r.m20; - m.m10 = l.m10 * r.m00 + l.m11 * r.m10 + l.m12 * r.m20; - m.m20 = l.m20 * r.m00 + l.m21 * r.m10 + l.m22 * r.m20; - m.m01 = l.m00 * r.m01 + l.m01 * r.m11 + l.m02 * r.m21; - m.m11 = l.m10 * r.m01 + l.m11 * r.m11 + l.m12 * r.m21; - m.m21 = l.m20 * r.m01 + l.m21 * r.m11 + l.m22 * r.m21; - m.m02 = l.m00 * r.m02 + l.m01 * r.m12 + l.m02 * r.m22; - m.m12 = l.m10 * r.m02 + l.m11 * r.m12 + l.m12 * r.m22; - m.m22 = l.m20 * r.m02 + l.m21 * r.m12 + l.m22 * r.m22; - m.m03 = l.m00 * r.m03 + l.m01 * r.m13 + l.m02 * r.m23; - m.m13 = l.m10 * r.m03 + l.m11 * r.m13 + l.m12 * r.m23; - m.m23 = l.m20 * r.m03 + l.m21 * r.m13 + l.m22 * r.m23; - return m; -} - -/*! -* -* Implements the multiplication operator: Matrix44=Matrix33*Matrix44 -* -* Matrix33 and Matrix44 are specified in collumn order for a right-handed coordinate-system. -* AxB = operation B followed by operation A. -* A multiplication takes 36 muls and 24 adds. -* -* Example: -* Matrix33 m33=Matrix33::CreateRotationX(1.94192f);; -* Matrix44 m44=Matrix33::CreateRotationZ(3.14192f); -* Matrix44 result=m33*m44; -* -*/ -template -ILINE Matrix44_tpl operator * (const Matrix33_tpl& l, const Matrix44_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix44_tpl m; - m.m00 = l.m00 * r.m00 + l.m01 * r.m10 + l.m02 * r.m20; - m.m10 = l.m10 * r.m00 + l.m11 * r.m10 + l.m12 * r.m20; - m.m20 = l.m20 * r.m00 + l.m21 * r.m10 + l.m22 * r.m20; - m.m30 = r.m30; - m.m01 = l.m00 * r.m01 + l.m01 * r.m11 + l.m02 * r.m21; - m.m11 = l.m10 * r.m01 + l.m11 * r.m11 + l.m12 * r.m21; - m.m21 = l.m20 * r.m01 + l.m21 * r.m11 + l.m22 * r.m21; - m.m31 = r.m31; - m.m02 = l.m00 * r.m02 + l.m01 * r.m12 + l.m02 * r.m22; - m.m12 = l.m10 * r.m02 + l.m11 * r.m12 + l.m12 * r.m22; - m.m22 = l.m20 * r.m02 + l.m21 * r.m12 + l.m22 * r.m22; - m.m32 = r.m32; - m.m03 = l.m00 * r.m03 + l.m01 * r.m13 + l.m02 * r.m23; - m.m13 = l.m10 * r.m03 + l.m11 * r.m13 + l.m12 * r.m23; - m.m23 = l.m20 * r.m03 + l.m21 * r.m13 + l.m22 * r.m23; - m.m33 = r.m33; - return m; -} - -template -ILINE Matrix33_tpl& operator *= (Matrix33_tpl& l, const Matrix33_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix33_tpl tmp; - tmp.m00 = l.m00 * r.m00 + l.m01 * r.m10 + l.m02 * r.m20; - tmp.m01 = l.m00 * r.m01 + l.m01 * r.m11 + l.m02 * r.m21; - tmp.m02 = l.m00 * r.m02 + l.m01 * r.m12 + l.m02 * r.m22; - tmp.m10 = l.m10 * r.m00 + l.m11 * r.m10 + l.m12 * r.m20; - tmp.m11 = l.m10 * r.m01 + l.m11 * r.m11 + l.m12 * r.m21; - tmp.m12 = l.m10 * r.m02 + l.m11 * r.m12 + l.m12 * r.m22; - tmp.m20 = l.m20 * r.m00 + l.m21 * r.m10 + l.m22 * r.m20; - tmp.m21 = l.m20 * r.m01 + l.m21 * r.m11 + l.m22 * r.m21; - tmp.m22 = l.m20 * r.m02 + l.m21 * r.m12 + l.m22 * r.m22; - l = tmp; - return l; -} - - -template -ILINE Matrix33_tpl operator+(const Matrix33_tpl& l, const Matrix33_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix33_tpl res; - res.m00 = l.m00 + r.m00; - res.m01 = l.m01 + r.m01; - res.m02 = l.m02 + r.m02; - res.m10 = l.m10 + r.m10; - res.m11 = l.m11 + r.m11; - res.m12 = l.m12 + r.m12; - res.m20 = l.m20 + r.m20; - res.m21 = l.m21 + r.m21; - res.m22 = l.m22 + r.m22; - return res; -} -template -ILINE Matrix33_tpl& operator+=(Matrix33_tpl& l, const Matrix33_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - l.m00 += r.m00; - l.m01 += r.m01; - l.m02 += r.m02; - l.m10 += r.m10; - l.m11 += r.m11; - l.m12 += r.m12; - l.m20 += r.m20; - l.m21 += r.m21; - l.m22 += r.m22; - return l; -} - - - - -template -ILINE Matrix33_tpl operator - (const Matrix33_tpl& l, const Matrix33_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix33_tpl res; - res.m00 = l.m00 - r.m00; - res.m01 = l.m01 - r.m01; - res.m02 = l.m02 - r.m02; - res.m10 = l.m10 - r.m10; - res.m11 = l.m11 - r.m11; - res.m12 = l.m12 - r.m12; - res.m20 = l.m20 - r.m20; - res.m21 = l.m21 - r.m21; - res.m22 = l.m22 - r.m22; - return res; -} -template -ILINE Matrix33_tpl& operator-=(Matrix33_tpl& l, const Matrix33_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - l.m00 -= r.m00; - l.m01 -= r.m01; - l.m02 -= r.m02; - l.m10 -= r.m10; - l.m11 -= r.m11; - l.m12 -= r.m12; - l.m20 -= r.m20; - l.m21 -= r.m21; - l.m22 -= r.m22; - return l; -} - - - - -template -ILINE Matrix33_tpl operator*(const Matrix33_tpl& m, F op) -{ - assert(m.IsValid()); - Matrix33_tpl res; - res.m00 = m.m00 * op; - res.m01 = m.m01 * op; - res.m02 = m.m02 * op; - res.m10 = m.m10 * op; - res.m11 = m.m11 * op; - res.m12 = m.m12 * op; - res.m20 = m.m20 * op; - res.m21 = m.m21 * op; - res.m22 = m.m22 * op; - return res; -} -template -ILINE Matrix33_tpl operator/(const Matrix33_tpl& src, F op) { return src * ((F)1.0 / op); } - -//post-multiply -template -ILINE Vec3_tpl operator*(const Matrix33_tpl& m, const Vec3_tpl& p) -{ - assert(m.IsValid()); - assert(p.IsValid()); - Vec3_tpl tp; - tp.x = F1(m.m00 * p.x + m.m01 * p.y + m.m02 * p.z); - tp.y = F1(m.m10 * p.x + m.m11 * p.y + m.m12 * p.z); - tp.z = F1(m.m20 * p.x + m.m21 * p.y + m.m22 * p.z); - return tp; -} - -//pre-multiply -template -ILINE Vec3_tpl operator*(const Vec3_tpl& p, const Matrix33_tpl& m) -{ - assert(m.IsValid()); - assert(p.IsValid()); - Vec3_tpl tp; - tp.x = F1(p.x * m.m00 + p.y * m.m10 + p.z * m.m20); - tp.y = F1(p.x * m.m01 + p.y * m.m11 + p.z * m.m21); - tp.z = F1(p.x * m.m02 + p.y * m.m12 + p.z * m.m22); - return tp; -} - -//post-multiply -template -ILINE Vec2_tpl operator*(const Matrix33_tpl& m, const Vec2_tpl& v) -{ - assert(m.IsValid()); - assert(v.IsValid()); - return Vec2_tpl(v.x * m.m00 + v.y * m.m01, v.x * m.m10 + v.y * m.m11); -} - -//pre-multiply -template -ILINE Vec2_tpl operator*(const Vec2_tpl& v, const Matrix33_tpl& m) -{ - assert(m.IsValid()); - assert(v.IsValid()); - return Vec2_tpl(v.x * m.m00 + v.y * m.m10, v.x * m.m01 + v.y * m.m11); -} - -template -ILINE Matrix33_tpl& crossproduct_matrix(const Vec3_tpl& v, Matrix33_tpl& m) -{ - m.m00 = 0; - m.m01 = -v.z; - m.m02 = v.y; - m.m10 = v.z; - m.m11 = 0; - m.m12 = -v.x; - m.m20 = -v.y; - m.m21 = v.x; - m.m22 = 0; - return m; -} - -template -ILINE Matrix33_tpl& dotproduct_matrix(const Vec3_tpl& v, const Vec3_tpl& op, Matrix33_tpl& m) -{ - m.m00 = v.x * op.x; - m.m10 = v.y * op.x; - m.m20 = v.z * op.x; - m.m01 = v.x * op.y; - m.m11 = v.y * op.y; - m.m21 = v.z * op.y; - m.m02 = v.x * op.z; - m.m12 = v.y * op.z; - m.m22 = v.z * op.z; - return m; -} - - -#endif // CRYINCLUDE_CRYCOMMON_CRY_MATRIX33_H - diff --git a/Code/CryEngine/CryCommon/Cry_Matrix34.h b/Code/CryEngine/CryCommon/Cry_Matrix34.h deleted file mode 100644 index 9f5deeaf17..0000000000 --- a/Code/CryEngine/CryCommon/Cry_Matrix34.h +++ /dev/null @@ -1,1462 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Common matrix class - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_MATRIX34_H -#define CRYINCLUDE_CRYCOMMON_CRY_MATRIX34_H -#pragma once - - - - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct Matrix34_tpl -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -template -struct Matrix34_tpl -{ - F m00, m01, m02, m03; - F m10, m11, m12, m13; - F m20, m21, m22, m23; - - //default constructor -#if defined(_DEBUG) - ILINE Matrix34_tpl() - { - if constexpr (sizeof(F) == 4) - { - uint32* p = (uint32*)&m00; - p[ 0] = F32NAN; - p[ 1] = F32NAN; - p[ 2] = F32NAN; - p[ 3] = F32NAN; - p[ 4] = F32NAN; - p[ 5] = F32NAN; - p[ 6] = F32NAN; - p[ 7] = F32NAN; - p[ 8] = F32NAN; - p[ 9] = F32NAN; - p[10] = F32NAN; - p[11] = F32NAN; - } - if constexpr (sizeof(F) == 8) - { - uint64* p = (uint64*)&m00; - p[ 0] = F64NAN; - p[ 1] = F64NAN; - p[ 2] = F64NAN; - p[ 3] = F64NAN; - p[ 4] = F64NAN; - p[ 5] = F64NAN; - p[ 6] = F64NAN; - p[ 7] = F64NAN; - p[ 8] = F64NAN; - p[ 9] = F64NAN; - p[10] = F64NAN; - p[11] = F64NAN; - } - } -#else - ILINE Matrix34_tpl(){}; -#endif - - //set matrix to Identity - ILINE Matrix34_tpl(type_identity) - { - m00 = 1; - m01 = 0; - m02 = 0; - m03 = 0; - m10 = 0; - m11 = 1; - m12 = 0; - m13 = 0; - m20 = 0; - m21 = 0; - m22 = 1; - m23 = 0; - } - - //set matrix to Zero - ILINE Matrix34_tpl(type_zero) - { - m00 = 0; - m01 = 0; - m02 = 0; - m03 = 0; - m10 = 0; - m11 = 0; - m12 = 0; - m13 = 0; - m20 = 0; - m21 = 0; - m22 = 0; - m23 = 0; - } - - //ASSIGNMENT OPERATOR of identical Matrix33 types. - //The assignment operator has precedence over assignment constructor - //Matrix34 m; m=m34; - ILINE Matrix34_tpl& operator = (const Matrix34_tpl& m) - { - assert(m.IsValid()); - m00 = m.m00; - m01 = m.m01; - m02 = m.m02; - m03 = m.m03; - m10 = m.m10; - m11 = m.m11; - m12 = m.m12; - m13 = m.m13; - m20 = m.m20; - m21 = m.m21; - m22 = m.m22; - m23 = m.m23; - return *this; - } - - - - - //-------------------------------------------------------------------- - //---- implementation of the constructors --- - //-------------------------------------------------------------------- - - - //CONSTRUCTOR for identical float-types. It initialises a matrix34 with 12 floats. - ILINE Matrix34_tpl(F v00, F v01, F v02, F v03, F v10, F v11, F v12, F v13, F v20, F v21, F v22, F v23) - { - m00 = v00; - m01 = v01; - m02 = v02; - m03 = v03; - m10 = v10; - m11 = v11; - m12 = v12; - m13 = v13; - m20 = v20; - m21 = v21; - m22 = v22; - m23 = v23; - } - //CONSTRUCTOR for different float-types. It initialises a matrix34 with 12 floats. - template - ILINE Matrix34_tpl(F1 v00, F1 v01, F1 v02, F1 v03, F1 v10, F1 v11, F1 v12, F1 v13, F1 v20, F1 v21, F1 v22, F1 v23) - { - m00 = F(v00); - m01 = F(v01); - m02 = F(v02); - m03 = F(v03); - m10 = F(v10); - m11 = F(v11); - m12 = F(v12); - m13 = F(v13); - m20 = F(v20); - m21 = F(v21); - m22 = F(v22); - m23 = F(v23); - } - - - //CONSTRUCTOR for identical float-types. It converts a Matrix33 into a Matrix34. - //Matrix34(m33); - ILINE Matrix34_tpl(const Matrix33_tpl&m) - { - assert(m.IsValid()); - m00 = m.m00; - m01 = m.m01; - m02 = m.m02; - m03 = 0; - m10 = m.m10; - m11 = m.m11; - m12 = m.m12; - m13 = 0; - m20 = m.m20; - m21 = m.m21; - m22 = m.m22; - m23 = 0; - } - //CONSTRUCTOR for different float-types. It converts a Matrix33 into a Matrix34 and also converts between double/float. - //Matrix34(Matrix33); - template - ILINE Matrix34_tpl(const Matrix33_tpl&m) - { - assert(m.IsValid()); - m00 = F(m.m00); - m01 = F(m.m01); - m02 = F(m.m02); - m03 = 0; - m10 = F(m.m10); - m11 = F(m.m11); - m12 = F(m.m12); - m13 = 0; - m20 = F(m.m20); - m21 = F(m.m21); - m22 = F(m.m22); - m23 = 0; - } - - - //CONSTRUCTOR for identical float-types. It converts a Matrix33 with a translation-vector into a Matrix34. - //Matrix34(m33,Vec3(1,2,3)); - ILINE Matrix34_tpl(const Matrix33_tpl&m, const Vec3_tpl&t) - { - assert(m.IsValid()); - assert(t.IsValid()); - m00 = m.m00; - m01 = m.m01; - m02 = m.m02; - m03 = t.x; - m10 = m.m10; - m11 = m.m11; - m12 = m.m12; - m13 = t.y; - m20 = m.m20; - m21 = m.m21; - m22 = m.m22; - m23 = t.z; - } - //CONSTRUCTOR for different float-types. It converts a Matrix33 with a translation-vector into a Matrix34 and also converts between double/float. - //Matrix34(Matrix33r,Vec3d(1,2,3)); - template - ILINE Matrix34_tpl(const Matrix33_tpl&m, const Vec3_tpl&t) - { - assert(m.IsValid()); - assert(t.IsValid()); - m00 = F(m.m00); - m01 = F(m.m01); - m02 = F(m.m02); - m03 = F(t.x); - m10 = F(m.m10); - m11 = F(m.m11); - m12 = F(m.m12); - m13 = F(t.y); - m20 = F(m.m20); - m21 = F(m.m21); - m22 = F(m.m22); - m23 = F(t.z); - } - - - - //CONSTRUCTOR for identical float types - //Matrix34 m=m34; - ILINE Matrix34_tpl(const Matrix34_tpl&m) - { - assert(m.IsValid()); - m00 = m.m00; - m01 = m.m01; - m02 = m.m02; - m03 = m.m03; - m10 = m.m10; - m11 = m.m11; - m12 = m.m12; - m13 = m.m13; - m20 = m.m20; - m21 = m.m21; - m22 = m.m22; - m23 = m.m23; - } - //CONSTRUCTOR for different float-types. - //Matrix34 m=m34d; - template - ILINE Matrix34_tpl(const Matrix34_tpl&m) - { - assert(m.IsValid()); - m00 = F(m.m00); - m01 = F(m.m01); - m02 = F(m.m02); - m03 = F(m.m03); - m10 = F(m.m10); - m11 = F(m.m11); - m12 = F(m.m12); - m13 = F(m.m13); - m20 = F(m.m20); - m21 = F(m.m21); - m22 = F(m.m22); - m23 = F(m.m23); - } - - - //CONSTRUCTOR for identical float-types. It converts a Matrix44 into a Matrix34. - //Needs to be 'explicit' because we loose the translation vector in the conversion process - //Matrix34(m44); - ILINE explicit Matrix34_tpl(const Matrix44_tpl&m) - { - assert(m.IsValid()); - m00 = m.m00; - m01 = m.m01; - m02 = m.m02; - m03 = m.m03; - m10 = m.m10; - m11 = m.m11; - m12 = m.m12; - m13 = m.m13; - m20 = m.m20; - m21 = m.m21; - m22 = m.m22; - m23 = m.m23; - } - //CONSTRUCTOR for different float types. It converts a Matrix44 into a Matrix34 and converts between double/float. - //Needs to be 'explicit' because we loose the translation vector in the conversion process - //Matrix34(m44r); - template - ILINE explicit Matrix34_tpl(const Matrix44_tpl&m) - { - assert(m.IsValid()); - m00 = F(m.m00); - m01 = F(m.m01); - m02 = F(m.m02); - m03 = F(m.m03); - m10 = F(m.m10); - m11 = F(m.m11); - m12 = F(m.m12); - m13 = F(m.m13); - m20 = F(m.m20); - m21 = F(m.m21); - m22 = F(m.m22); - m23 = F(m.m23); - } - - //CONSTRUCTOR for identical float-types. It converts a Quat into a Matrix34. - //Needs to be 'explicit' because we loose float-precision in the conversion process - //Matrix34(QuatT); - explicit ILINE Matrix34_tpl(const Quat_tpl&q) - { - *this = Matrix33_tpl(q); - } - //CONSTRUCTOR for different float-types. It converts a Quat into a Matrix34. - //Needs to be 'explicit' because we loose float-precision in the conversion process - //Matrix34(QuatTd); - template - explicit ILINE Matrix34_tpl(const Quat_tpl&q) - { - *this = Matrix33_tpl(q); - } - - - - //CONSTRUCTOR for identical float-types. It converts a QuatT into a Matrix34. - //Needs to be 'explicit' because we loose float-precision in the conversion process - //Matrix34(QuatT); - explicit ILINE Matrix34_tpl(const QuatT_tpl &q) - { - *this = Matrix34_tpl(Matrix33_tpl(q.q), q.t); - } - //CONSTRUCTOR for different float-types. It converts a QuatT into a Matrix34. - //Needs to be 'explicit' because we loose float-precision in the conversion process - //Matrix34(QuatT); - template - ILINE explicit Matrix34_tpl(const QuatT_tpl q) - { - *this = Matrix34_tpl(Matrix33_tpl(q.q), q.t); - } - - - - - //CONSTRUCTOR for identical float-types. It converts a QuatTS into a Matrix34. - //Needs to be 'explicit' because we loose float-precision in the conversion process - //Matrix34(QuatT); - explicit ILINE Matrix34_tpl(const QuatTS_tpl &q) - { - assert(q.q.IsValid()); - Vec3_tpl v2 = q.q.v + q.q.v; - F xx = 1 - v2.x * q.q.v.x; - F yy = v2.y * q.q.v.y; - F xw = v2.x * q.q.w; - F xy = v2.y * q.q.v.x; - F yz = v2.z * q.q.v.y; - F yw = v2.y * q.q.w; - F xz = v2.z * q.q.v.x; - F zz = v2.z * q.q.v.z; - F zw = v2.z * q.q.w; - m00 = (1 - yy - zz) * q.s; - m01 = (xy - zw) * q.s; - m02 = (xz + yw) * q.s; - m03 = q.t.x; - m10 = (xy + zw) * q.s; - m11 = (xx - zz) * q.s; - m12 = (yz - xw) * q.s; - m13 = q.t.y; - m20 = (xz - yw) * q.s; - m21 = (yz + xw) * q.s; - m22 = (xx - yy) * q.s; - m23 = q.t.z; - } - //CONSTRUCTOR for different float-types. It converts a QuatTS into a Matrix34. - //Needs to be 'explicit' because we loose float-precision in the conversion process - //Matrix34(QuatT); - template - ILINE explicit Matrix34_tpl(const QuatTS_tpl &q) - { - assert(q.q.IsValid()); - Vec3_tpl v2 = q.q.v + q.q.v; - F1 xx = 1 - v2.x * q.q.v.x; - F1 yy = v2.y * q.q.v.y; - F1 xw = v2.x * q.q.w; - F1 xy = v2.y * q.q.v.x; - F1 yz = v2.z * q.q.v.y; - F1 yw = v2.y * q.q.w; - F1 xz = v2.z * q.q.v.x; - F1 zz = v2.z * q.q.v.z; - F1 zw = v2.z * q.q.w; - m00 = F((1 - yy - zz) * q.s); - m01 = F((xy - zw) * q.s); - m02 = F((xz + yw) * q.s); - m03 = F(q.t.x); - m10 = F((xy + zw) * q.s); - m11 = F((xx - zz) * q.s); - m12 = F((yz - xw) * q.s); - m13 = F(q.t.y); - m20 = F((xz - yw) * q.s); - m21 = F((yz + xw) * q.s); - m22 = F((xx - yy) * q.s); - m23 = F(q.t.z); - } - - - - - //CONSTRUCTOR for identical float-types. It converts a QuatTNS into a Matrix34. - //Needs to be 'explicit' because we loose float-precision in the conversion process - //Matrix34(QuatT); - explicit ILINE Matrix34_tpl(const QuatTNS_tpl &q) - { - assert(q.q.IsValid()); - Vec3_tpl v2 = q.q.v + q.q.v; - F xx = 1 - v2.x * q.q.v.x; - F yy = v2.y * q.q.v.y; - F xw = v2.x * q.q.w; - F xy = v2.y * q.q.v.x; - F yz = v2.z * q.q.v.y; - F yw = v2.y * q.q.w; - F xz = v2.z * q.q.v.x; - F zz = v2.z * q.q.v.z; - F zw = v2.z * q.q.w; - m00 = (1 - yy - zz) * q.s.x; - m01 = (xy - zw) * q.s.y; - m02 = (xz + yw) * q.s.z; - m03 = q.t.x; - m10 = (xy + zw) * q.s.x; - m11 = (xx - zz) * q.s.y; - m12 = (yz - xw) * q.s.z; - m13 = q.t.y; - m20 = (xz - yw) * q.s.x; - m21 = (yz + xw) * q.s.y; - m22 = (xx - yy) * q.s.z; - m23 = q.t.z; - } - //CONSTRUCTOR for different float-types. It converts a QuatTNS into a Matrix34. - //Needs to be 'explicit' because we loose float-precision in the conversion process - //Matrix34(QuatT); - template - ILINE explicit Matrix34_tpl(const QuatTNS_tpl &q) - { - assert(q.q.IsValid()); - Vec3_tpl v2 = q.q.v + q.q.v; - F1 xx = 1 - v2.x * q.q.v.x; - F1 yy = v2.y * q.q.v.y; - F1 xw = v2.x * q.q.w; - F1 xy = v2.y * q.q.v.x; - F1 yz = v2.z * q.q.v.y; - F1 yw = v2.y * q.q.w; - F1 xz = v2.z * q.q.v.x; - F1 zz = v2.z * q.q.v.z; - F1 zw = v2.z * q.q.w; - m00 = F((1 - yy - zz) * q.s.x); - m01 = F((xy - zw) * q.s.y); - m02 = F((xz + yw) * q.s.z); - m03 = F(q.t.x); - m10 = F((xy + zw) * q.s.x); - m11 = F((xx - zz) * q.s.y); - m12 = F((yz - xw) * q.s.z); - m13 = F(q.t.y); - m20 = F((xz - yw) * q.s.x); - m21 = F((yz + xw) * q.s.y); - m22 = F((xx - yy) * q.s.z); - m23 = F(q.t.z); - } - - - - - //CONSTRUCTOR for identical float-types. It converts a DualQuat into a Matrix34. - //Needs to be 'explicit' because we loose float-precision in the conversion process - //Matrix34(QuatT); - ILINE explicit Matrix34_tpl(const DualQuat_tpl &q) - { - assert((fabs_tpl(1 - (q.nq | q.nq))) < 0.01); //check if unit-quaternion - Vec3_tpl t = (q.nq.w * q.dq.v - q.dq.w * q.nq.v + q.nq.v % q.dq.v); //perfect for HLSL - Vec3_tpl v2 = q.nq.v + q.nq.v; - F xx = 1 - v2.x * q.nq.v.x; - F yy = v2.y * q.nq.v.y; - F xw = v2.x * q.nq.w; - F xy = v2.y * q.nq.v.x; - F yz = v2.z * q.nq.v.y; - F yw = v2.y * q.nq.w; - F xz = v2.z * q.nq.v.x; - F zz = v2.z * q.nq.v.z; - F zw = v2.z * q.nq.w; - m00 = 1 - yy - zz; - m01 = xy - zw; - m02 = xz + yw; - m03 = t.x + t.x; - m10 = xy + zw; - m11 = xx - zz; - m12 = yz - xw; - m13 = t.y + t.y; - m20 = xz - yw; - m21 = yz + xw; - m22 = xx - yy; - m23 = t.z + t.z; - } - //CONSTRUCTOR for different float-types. It converts a DualQuat into a Matrix34. - //Needs to be 'explicit' because we loose float-precision in the conversion process - //Matrix34(QuatT); - template - ILINE explicit Matrix34_tpl(const DualQuat_tpl &q) - { - assert((fabs_tpl(1 - (q.nq | q.nq))) < 0.01); //check if unit-quaternion - Vec3_tpl t = (q.nq.w * q.dq.v - q.dq.w * q.nq.v + q.nq.v % q.dq.v); //perfect for HLSL - Vec3_tpl v2 = q.nq.v + q.nq.v; - F1 xx = 1 - v2.x * q.nq.v.x; - F1 yy = v2.y * q.nq.v.y; - F1 xw = v2.x * q.nq.w; - F1 xy = v2.y * q.nq.v.x; - F1 yz = v2.z * q.nq.v.y; - F1 yw = v2.y * q.nq.w; - F1 xz = v2.z * q.nq.v.x; - F1 zz = v2.z * q.nq.v.z; - F1 zw = v2.z * q.nq.w; - m00 = F(1 - yy - zz); - m01 = F(xy - zw); - m02 = F(xz + yw); - m03 = F(t.x + t.x); - m10 = F(xy + zw); - m11 = F(xx - zz); - m12 = F(yz - xw); - m13 = F(t.y + t.y); - m20 = F(xz - yw); - m21 = F(yz + xw); - m22 = F(xx - yy); - m23 = F(t.z + t.z); - } - - - - - - - //apply scaling to the columns of the matrix. - ILINE void ScaleColumn(const Vec3_tpl& s) - { - m00 *= s.x; - m01 *= s.y; - m02 *= s.z; - m10 *= s.x; - m11 *= s.y; - m12 *= s.z; - m20 *= s.x; - m21 *= s.y; - m22 *= s.z; - } - - /*! - * - * Initializes the Matrix34 with the identity. - * - */ - void SetIdentity(void) - { - m00 = 1.0f; - m01 = 0.0f; - m02 = 0.0f; - m03 = 0.0f; - m10 = 0.0f; - m11 = 1.0f; - m12 = 0.0f; - m13 = 0.0f; - m20 = 0.0f; - m21 = 0.0f; - m22 = 1.0f; - m23 = 0.0f; - } - - ILINE static Matrix34_tpl CreateIdentity(void) - { - Matrix34_tpl m; - m.SetIdentity(); - return m; - } - - ILINE bool IsIdentity() const - { - return 0 == (fabs_tpl((F)1 - m00) + fabs_tpl(m01) + fabs_tpl(m02) + fabs_tpl(m03) + fabs_tpl(m10) + fabs_tpl((F)1 - m11) + fabs_tpl(m12) + fabs_tpl(m13) + fabs_tpl(m20) + fabs_tpl(m21) + fabs_tpl((F)1 - m22)) + fabs_tpl(m23); - } - - ILINE int IsZero() const - { - return 0 == (fabs_tpl(m00) + fabs_tpl(m01) + fabs_tpl(m02) + fabs_tpl(m03) + fabs_tpl(m10) + fabs_tpl(m11) + fabs_tpl(m12) + fabs_tpl(m13) + fabs_tpl(m20) + fabs_tpl(m21) + fabs_tpl(m22)) + fabs_tpl(m23); - } - - /*! - * Create a rotation matrix around an arbitrary axis (Eulers Theorem). - * The axis is specified as an normalized Vec3. The angle is assumed to be in radians. - * This function also assumes a translation-vector and stores it in the right column. - * - * Example: - * Matrix34 m34; - * Vec3 axis=GetNormalized( Vec3(-1.0f,-0.3f,0.0f) ); - * m34.SetRotationAA( 3.14314f, axis, Vec3(5,5,5) ); - */ - ILINE void SetRotationAA(const F rad, const Vec3_tpl& axis, const Vec3_tpl& t = Vec3(ZERO)) - { - *this = Matrix33_tpl::CreateRotationAA(rad, axis); - this->SetTranslation(t); - } - ILINE static Matrix34_tpl CreateRotationAA(const F rad, const Vec3_tpl& axis, const Vec3_tpl& t = Vec3(ZERO)) - { - Matrix34_tpl m34; - m34.SetRotationAA(rad, axis, t); - return m34; - } - - ILINE void SetRotationAA(const Vec3_tpl& rot, const Vec3_tpl& t = Vec3(ZERO)) - { - *this = Matrix33_tpl::CreateRotationAA(rot); - this->SetTranslation(t); - } - ILINE static Matrix34_tpl CreateRotationAA(const Vec3_tpl& rot, const Vec3_tpl& t = Vec3(ZERO)) - { - Matrix34_tpl m34; - m34.SetRotationAA(rot, t); - return m34; - } - - - /*! - * Create rotation-matrix about X axis using an angle. - * The angle is assumed to be in radians. - * The translation-vector is set to zero. - * - * Example: - * Matrix34 m34; - * m34.SetRotationX(0.5f); - */ - ILINE void SetRotationX(const f32 rad, const Vec3_tpl& t = Vec3(ZERO)) - { - *this = Matrix33_tpl::CreateRotationX(rad); - this->SetTranslation(t); - } - ILINE static Matrix34_tpl CreateRotationX(const f32 rad, const Vec3_tpl& t = Vec3(ZERO)) - { - Matrix34_tpl m34; - m34.SetRotationX(rad, t); - return m34; - } - - /*! - * Create rotation-matrix about Y axis using an angle. - * The angle is assumed to be in radians. - * The translation-vector is set to zero. - * - * Example: - * Matrix34 m34; - * m34.SetRotationY(0.5f); - */ - ILINE void SetRotationY(const f32 rad, const Vec3_tpl& t = Vec3(ZERO)) - { - *this = Matrix33_tpl::CreateRotationY(rad); - this->SetTranslation(t); - } - ILINE static Matrix34_tpl CreateRotationY(const f32 rad, const Vec3_tpl& t = Vec3(ZERO)) - { - Matrix34_tpl m34; - m34.SetRotationY(rad, t); - return m34; - } - - /*! - * Create rotation-matrix about Z axis using an angle. - * The angle is assumed to be in radians. - * The translation-vector is set to zero. - * - * Example: - * Matrix34 m34; - * m34.SetRotationZ(0.5f); - */ - ILINE void SetRotationZ(const f32 rad, const Vec3_tpl& t = Vec3(ZERO)) - { - *this = Matrix33_tpl::CreateRotationZ(rad); - this->SetTranslation(t); - } - ILINE static Matrix34_tpl CreateRotationZ(const f32 rad, const Vec3_tpl& t = Vec3(ZERO)) - { - Matrix34_tpl m34; - m34.SetRotationZ(rad, t); - return m34; - } - - - /*! - * - * Convert three Euler angle to mat33 (rotation order:XYZ) - * The Euler angles are assumed to be in radians. - * The translation-vector is set to zero. - * - * Example 1: - * Matrix34 m34; - * m34.SetRotationXYZ( Ang3(0.5f,0.2f,0.9f), translation ); - * - * Example 2: - * Matrix34 m34=Matrix34::CreateRotationXYZ( Ang3(0.5f,0.2f,0.9f), translation ); - */ - ILINE void SetRotationXYZ(const Ang3_tpl& rad, const Vec3_tpl& t = Vec3(ZERO)) - { - assert(rad.IsValid()); - assert(t.IsValid()); - *this = Matrix33_tpl::CreateRotationXYZ(rad); - this->SetTranslation(t); - } - ILINE static Matrix34_tpl CreateRotationXYZ(const Ang3_tpl& rad, const Vec3_tpl& t = Vec3(ZERO)) - { - assert(rad.IsValid()); - assert(t.IsValid()); - Matrix34_tpl m34; - m34.SetRotationXYZ(rad, t); - return m34; - } - - - ILINE void SetRotationAA(F c, F s, Vec3_tpl axis, const Vec3_tpl& t = Vec3(ZERO)) - { - assert(axis.IsValid()); - assert(t.IsValid()); - *this = Matrix33_tpl::CreateRotationAA(c, s, axis); - m03 = t.x; - m13 = t.y; - m23 = t.z; - } - ILINE static Matrix34_tpl CreateRotationAA(F c, F s, Vec3_tpl axis, const Vec3_tpl& t = Vec3(ZERO)) - { - Matrix34_tpl m34; - m34.SetRotationAA(c, s, axis, t); - return m34; - } - - ILINE void SetTranslationMat(const Vec3_tpl& v) - { - m00 = 1.0f; - m01 = 0.0f; - m02 = 0.0f; - m03 = v.x; - m10 = 0.0f; - m11 = 1.0f; - m12 = 0.0f; - m13 = v.y; - m20 = 0.0f; - m21 = 0.0f; - m22 = 1.0f; - m23 = v.z; - } - ILINE static Matrix34_tpl CreateTranslationMat(const Vec3_tpl& v) - { - Matrix34_tpl m34; - m34.SetTranslationMat(v); - return m34; - } - - - //NOTE: all vectors are stored in columns - ILINE void SetFromVectors(const Vec3& vx, const Vec3& vy, const Vec3& vz, const Vec3& pos) - { - m00 = vx.x; - m01 = vy.x; - m02 = vz.x; - m03 = pos.x; - m10 = vx.y; - m11 = vy.y; - m12 = vz.y; - m13 = pos.y; - m20 = vx.z; - m21 = vy.z; - m22 = vz.z; - m23 = pos.z; - } - ILINE static Matrix34_tpl CreateFromVectors(const Vec3_tpl& vx, const Vec3_tpl& vy, const Vec3_tpl& vz, const Vec3_tpl& pos) - { - Matrix34_tpl m; - m.SetFromVectors(vx, vy, vz, pos); - return m; - } - - void InvertFast() - { // in-place transposition - assert(IsOrthonormal()); - F t; - Vec3 v(m03, m13, m23); - t = m01; - m01 = m10; - m10 = t; - m03 = -v.x * m00 - v.y * m01 - v.z * m20; - t = m02; - m02 = m20; - m20 = t; - m13 = -v.x * m10 - v.y * m11 - v.z * m21; - t = m12; - m12 = m21; - m21 = t; - m23 = -v.x * m20 - v.y * m21 - v.z * m22; - } - - Matrix34_tpl GetInvertedFast() const - { - assert(IsOrthonormal()); - Matrix34_tpl dst; - dst.m00 = m00; - dst.m01 = m10; - dst.m02 = m20; - dst.m03 = -m03 * m00 - m13 * m10 - m23 * m20; - dst.m10 = m01; - dst.m11 = m11; - dst.m12 = m21; - dst.m13 = -m03 * m01 - m13 * m11 - m23 * m21; - dst.m20 = m02; - dst.m21 = m12; - dst.m22 = m22; - dst.m23 = -m03 * m02 - m13 * m12 - m23 * m22; - return dst; - } - - //! transforms a vector. the translation is not beeing considered - ILINE Vec3_tpl TransformVector(const Vec3_tpl& v) const - { - assert(v.IsValid()); - return Vec3_tpl(m00 * v.x + m01 * v.y + m02 * v.z, m10 * v.x + m11 * v.y + m12 * v.z, m20 * v.x + m21 * v.y + m22 * v.z); - } - //! transforms a point and add translation vector - ILINE Vec3_tpl TransformPoint(const Vec3_tpl& p) const - { - assert(p.IsValid()); - return Vec3_tpl(m00 * p.x + m01 * p.y + m02 * p.z + m03, m10 * p.x + m11 * p.y + m12 * p.z + m13, m20 * p.x + m21 * p.y + m22 * p.z + m23); - } - - //! Remove scale from matrix. - void OrthonormalizeFast() - { - Vec3_tpl x(m00, m10, m20); - Vec3_tpl y(m01, m11, m21); - Vec3_tpl z; - x = x.GetNormalized(); - z = (x % y).GetNormalized(); - y = (z % x).GetNormalized(); - m00 = x.x; - m10 = x.y; - m20 = x.z; - m01 = y.x; - m11 = y.y; - m21 = y.z; - m02 = z.x; - m12 = z.y; - m22 = z.z; - } - - - //determinant is ambiguous: only the upper-left-submatrix's determinant is calculated - ILINE f32 Determinant() const - { - return (m00 * m11 * m22) + (m01 * m12 * m20) + (m02 * m10 * m21) - (m02 * m11 * m20) - (m00 * m12 * m21) - (m01 * m10 * m22); - } - - - //-------------------------------------------------------------------------------- - //---- helper functions to access matrix-members ------------ - //-------------------------------------------------------------------------------- - - F* GetData() { return &m00; } - const F* GetData() const { return &m00; } - - ILINE F operator () (uint32 i, uint32 j) const { assert ((i < 3) && (j < 4)); F* p_data = (F*)(&m00); return p_data[i * 4 + j]; } - ILINE F& operator () (uint32 i, uint32 j) { assert ((i < 3) && (j < 4)); F* p_data = (F*)(&m00); return p_data[i * 4 + j]; } - - ILINE void SetRow(int i, const Vec3_tpl& v) { assert(i < 3); F* p = (F*)(&m00); p[0 + 4 * i] = v.x; p[1 + 4 * i] = v.y; p[2 + 4 * i] = v.z; } - - ILINE const Vec3_tpl& GetRow(int i) const { assert(i < 3); return *(const Vec3_tpl*)(&m00 + 4 * i); } - ILINE const Vec4_tpl& GetRow4(int i) const { assert(i < 3); return *(const Vec4_tpl*)(&m00 + 4 * i); } - - ILINE void SetColumn(int i, const Vec3_tpl& v) { assert(i < 4); F* p = (F*)(&m00); p[i + 4 * 0] = v.x; p[i + 4 * 1] = v.y; p[i + 4 * 2] = v.z; } - ILINE Vec3_tpl GetColumn(int i) const { assert(i < 4); F* p = (F*)(&m00); return Vec3(p[i + 4 * 0], p[i + 4 * 1], p[i + 4 * 2]); } - ILINE Vec3_tpl GetColumn0() const { return Vec3_tpl(m00, m10, m20); } - ILINE Vec3_tpl GetColumn1() const { return Vec3_tpl(m01, m11, m21); } - ILINE Vec3_tpl GetColumn2() const { return Vec3_tpl(m02, m12, m22); } - ILINE Vec3_tpl GetColumn3() const { return Vec3_tpl(m03, m13, m23); } - - - ILINE void SetTranslation(const Vec3_tpl& t) { m03 = t.x; m13 = t.y; m23 = t.z; } - ILINE Vec3_tpl GetTranslation() const { return Vec3_tpl(m03, m13, m23); } - ILINE void ScaleTranslation (F s) { m03 *= s; m13 *= s; m23 *= s; } - ILINE Matrix34_tpl AddTranslation(const Vec3_tpl& t) { m03 += t.x; m13 += t.y; m23 += t.z; return *this; } - - ILINE void SetRotation33(const Matrix33_tpl& m33) - { - m00 = m33.m00; - m01 = m33.m01; - m02 = m33.m02; - m10 = m33.m10; - m11 = m33.m11; - m12 = m33.m12; - m20 = m33.m20; - m21 = m33.m21; - m22 = m33.m22; - } - - ILINE void GetRotation33(Matrix33_tpl& m33) const - { - m33.m00 = m00; - m33.m01 = m01; - m33.m02 = m02; - m33.m10 = m10; - m33.m11 = m11; - m33.m12 = m12; - m33.m20 = m20; - m33.m21 = m21; - m33.m22 = m22; - } - - //check if we have an orthonormal-base (general case, works even with reflection matrices) - int IsOrthonormal(F threshold = 0.001) const - { - f32 d0 = fabs_tpl(GetColumn0() | GetColumn1()); - if (d0 > threshold) - { - return 0; - } - f32 d1 = fabs_tpl(GetColumn0() | GetColumn2()); - if (d1 > threshold) - { - return 0; - } - f32 d2 = fabs_tpl(GetColumn1() | GetColumn2()); - if (d2 > threshold) - { - return 0; - } - int a = (fabs_tpl(1 - (GetColumn0() | GetColumn0()))) < threshold; - int b = (fabs_tpl(1 - (GetColumn1() | GetColumn1()))) < threshold; - int c = (fabs_tpl(1 - (GetColumn2() | GetColumn2()))) < threshold; - return a & b & c; - } - - //check if we have an orthonormal-base (assuming we are using a right-handed coordinate system) - int IsOrthonormalRH(F threshold = 0.001) const - { - int a = Vec3_tpl::IsEquivalent(GetColumn0(), GetColumn1() % GetColumn2(), threshold); - int b = Vec3_tpl::IsEquivalent(GetColumn1(), GetColumn2() % GetColumn0(), threshold); - int c = Vec3_tpl::IsEquivalent(GetColumn2(), GetColumn0() % GetColumn1(), threshold); - return a & b & c; - } - bool static IsEquivalent(const Matrix34_tpl& m0, const Matrix34_tpl& m1, F e = VEC_EPSILON) - { - return ( - (fabs_tpl(m0.m00 - m1.m00) <= e) && (fabs_tpl(m0.m01 - m1.m01) <= e) && (fabs_tpl(m0.m02 - m1.m02) <= e) && (fabs_tpl(m0.m03 - m1.m03) <= e) && - (fabs_tpl(m0.m10 - m1.m10) <= e) && (fabs_tpl(m0.m11 - m1.m11) <= e) && (fabs_tpl(m0.m12 - m1.m12) <= e) && (fabs_tpl(m0.m13 - m1.m13) <= e) && - (fabs_tpl(m0.m20 - m1.m20) <= e) && (fabs_tpl(m0.m21 - m1.m21) <= e) && (fabs_tpl(m0.m22 - m1.m22) <= e) && (fabs_tpl(m0.m23 - m1.m23) <= e) - ); - } - - bool IsValid() const - { - if (!NumberValid(m00)) - { - return false; - } - if (!NumberValid(m01)) - { - return false; - } - if (!NumberValid(m02)) - { - return false; - } - if (!NumberValid(m03)) - { - return false; - } - if (!NumberValid(m10)) - { - return false; - } - if (!NumberValid(m11)) - { - return false; - } - if (!NumberValid(m12)) - { - return false; - } - if (!NumberValid(m13)) - { - return false; - } - if (!NumberValid(m20)) - { - return false; - } - if (!NumberValid(m21)) - { - return false; - } - if (!NumberValid(m22)) - { - return false; - } - if (!NumberValid(m23)) - { - return false; - } - return true; - } - - - bool IsDegenerate(float epsilon = FLT_EPSILON) const - { - //check the basis vectors for 0 vector - return GetColumn0().len2() < epsilon - || GetColumn1().len2() < epsilon - || GetColumn2().len2() < epsilon; - } - - /*! - * Create a matrix with SCALING, ROTATION and TRANSLATION (in this order). - * - * Example 1: - * Matrix m34; - * m34.SetMatrix( Vec3(1,2,3), quat, Vec3(11,22,33) ); - */ - ILINE void Set(const Vec3_tpl& s, const Quat_tpl& q, const Vec3_tpl& t = Vec3(ZERO)) - { - assert(s.IsValid()); - assert(q.IsUnit(0.1f)); - assert(t.IsValid()); - F vxvx = q.v.x * q.v.x; - F vzvz = q.v.z * q.v.z; - F vyvy = q.v.y * q.v.y; - F vxvy = q.v.x * q.v.y; - F vxvz = q.v.x * q.v.z; - F vyvz = q.v.y * q.v.z; - F svx = q.w * q.v.x; - F svy = q.w * q.v.y; - F svz = q.w * q.v.z; - m00 = (1 - (vyvy + vzvz) * 2) * s.x; - m01 = (vxvy - svz) * 2 * s.y; - m02 = (vxvz + svy) * 2 * s.z; - m03 = t.x; - m10 = (vxvy + svz) * 2 * s.x; - m11 = (1 - (vxvx + vzvz) * 2) * s.y; - m12 = (vyvz - svx) * 2 * s.z; - m13 = t.y; - m20 = (vxvz - svy) * 2 * s.x; - m21 = (vyvz + svx) * 2 * s.y; - m22 = (1 - (vxvx + vyvy) * 2) * s.z; - m23 = t.z; - } - ILINE static Matrix34_tpl Create(const Vec3_tpl& s, const Quat_tpl& q, const Vec3_tpl& t = Vec3(ZERO)) - { - Matrix34_tpl m34; - m34.Set(s, q, t); - return m34; - } - Matrix34_tpl(const Vec3_tpl& s, const Quat_tpl& q, const Vec3_tpl& t = Vec3(ZERO)) - { - Set(s, q, t); - } - - - /*! - * Create scaling-matrix. - * The translation-vector is set to zero. - * - * Example 1: - * Matrix m34; - * m34.SetScale( Vec3(0.5f, 1.0f, 2.0f) ); - * Example 2: - * Matrix34 m34 = Matrix34::CreateScale( Vec3(0.5f, 1.0f, 2.0f) ); - */ - ILINE void SetScale(const Vec3_tpl& s, const Vec3_tpl& t = Vec3(ZERO)) - { - *this = Matrix33::CreateScale(s); - this->SetTranslation(t); - } - ILINE static Matrix34_tpl CreateScale(const Vec3_tpl& s, const Vec3_tpl& t = Vec3(ZERO)) - { - Matrix34_tpl m34; - m34.SetScale(s, t); - return m34; - } - - - ILINE Matrix44_tpl GetTransposed() const - { - Matrix44_tpl tmp; - tmp.m00 = m00; - tmp.m01 = m10; - tmp.m02 = m20; - tmp.m03 = 0; - tmp.m10 = m01; - tmp.m11 = m11; - tmp.m12 = m21; - tmp.m13 = 0; - tmp.m20 = m02; - tmp.m21 = m12; - tmp.m22 = m22; - tmp.m23 = 0; - tmp.m30 = m03; - tmp.m31 = m13; - tmp.m32 = m23; - tmp.m33 = 1; - return tmp; - } - - /*! - * calculate a real inversion of a Matrix34 - * an inverse-matrix is an UnDo-matrix for all kind of transformations - * - * Example 1: - * Matrix34 im34; im34.Invert(); - * - * Example 2: - * Matrix34 im34 = m34.GetInverted(); - */ - void Invert(void) - { - //rescue members - Matrix34_tpl m = *this; - // calculate 12 cofactors - m00 = m.m22 * m.m11 - m.m12 * m.m21; - m10 = m.m12 * m.m20 - m.m22 * m.m10; - m20 = m.m10 * m.m21 - m.m20 * m.m11; - m01 = m.m02 * m.m21 - m.m22 * m.m01; - m11 = m.m22 * m.m00 - m.m02 * m.m20; - m21 = m.m20 * m.m01 - m.m00 * m.m21; - m02 = m.m12 * m.m01 - m.m02 * m.m11; - m12 = m.m02 * m.m10 - m.m12 * m.m00; - m22 = m.m00 * m.m11 - m.m10 * m.m01; - m03 = (m.m22 * m.m13 * m.m01 + m.m02 * m.m23 * m.m11 + m.m12 * m.m03 * m.m21) - (m.m12 * m.m23 * m.m01 + m.m22 * m.m03 * m.m11 + m.m02 * m.m13 * m.m21); - m13 = (m.m12 * m.m23 * m.m00 + m.m22 * m.m03 * m.m10 + m.m02 * m.m13 * m.m20) - (m.m22 * m.m13 * m.m00 + m.m02 * m.m23 * m.m10 + m.m12 * m.m03 * m.m20); - m23 = (m.m20 * m.m11 * m.m03 + m.m00 * m.m21 * m.m13 + m.m10 * m.m01 * m.m23) - (m.m10 * m.m21 * m.m03 + m.m20 * m.m01 * m.m13 + m.m00 * m.m11 * m.m23); - // calculate determinant - F det = m.m00 * m00 + m.m10 * m01 + m.m20 * m02; - assert(fabs_tpl(det) > (F)0.00000001); - F rcpDet = 1.0f / det; - // calculate matrix inverse/ - m00 *= rcpDet; - m01 *= rcpDet; - m02 *= rcpDet; - m03 *= rcpDet; - m10 *= rcpDet; - m11 *= rcpDet; - m12 *= rcpDet; - m13 *= rcpDet; - m20 *= rcpDet; - m21 *= rcpDet; - m22 *= rcpDet; - m23 *= rcpDet; - } - ILINE Matrix34_tpl GetInverted() const - { - Matrix34_tpl dst = *this; - dst.Invert(); - return dst; - } - - /*! - * Name: ReflectMat34 - * Description: reflect a rotation matrix with respect to a plane. - * - * Example: - * Vec3 normal( 0.0f,-1.0f, 0.0f); - * Vec3 pos(0,1000,0); - * Matrix34 m34=CreateReflectionMat( pos, normal ); - */ - ILINE static Matrix34_tpl CreateReflectionMat (const Vec3_tpl& p, const Vec3_tpl& n) - { - Matrix34_tpl m; - F vxy = -2.0f * n.x * n.y; - F vxz = -2.0f * n.x * n.z; - F vyz = -2.0f * n.y * n.z; - F pdotn = 2.0f * (p | n); - m.m00 = 1.0f - 2.0f * n.x * n.x; - m.m01 = vxy; - m.m02 = vxz; - m.m03 = pdotn * n.x; - m.m10 = vxy; - m.m11 = 1.0f - 2.0f * n.y * n.y; - m.m12 = vyz; - m.m13 = pdotn * n.y; - m.m20 = vxz; - m.m21 = vyz; - m.m22 = 1.0f - 2.0f * n.z * n.z; - m.m23 = pdotn * n.z; - return m; - } - - AUTO_STRUCT_INFO -}; - -/////////////////////////////////////////////////////////////////////////////// -// Typedefs // -/////////////////////////////////////////////////////////////////////////////// - -typedef Matrix34_tpl Matrix34; //always 32 bit -typedef Matrix34_tpl Matrix34d;//always 64 bit -typedef Matrix34_tpl Matrix34r;//variable float precision. depending on the target system it can be between 32, 64 or bit -typedef _MS_ALIGN(16) Matrix34_tpl _ALIGN (16) Matrix34A; - -//---------------------------------------------------------------------------------- -//---------------------------------------------------------------------------------- -//---------------------------------------------------------------------------------- -//------------- implementation of Matrix34 ------------------------------ -//---------------------------------------------------------------------------------- -//---------------------------------------------------------------------------------- -//---------------------------------------------------------------------------------- - -//! multiply all matrix's values by f and return the matrix -template -ILINE Matrix34_tpl operator * (const Matrix34_tpl& m, const f32 f) -{ - assert(m.IsValid()); - Matrix34_tpl r; - r.m00 = m.m00 * f; - r.m01 = m.m01 * f; - r.m02 = m.m02 * f; - r.m03 = m.m03 * f; - r.m10 = m.m10 * f; - r.m11 = m.m11 * f; - r.m12 = m.m12 * f; - r.m13 = m.m13 * f; - r.m20 = m.m20 * f; - r.m21 = m.m21 * f; - r.m22 = m.m22 * f; - r.m23 = m.m23 * f; - return r; -} - -/*! -* multiplication of Matrix34 by a (column) Vec3. -* This function transforms the given input Vec3 -* into the coordinate system defined by this matrix. -* -* Example: -* Matrix34 m34; -* Vec3 vector(44,55,66); -* Vec3 result = m34*vector; -*/ -template -ILINE Vec3_tpl operator * (const Matrix34_tpl& m, const Vec3_tpl& p) -{ - assert(m.IsValid()); - assert(p.IsValid()); - Vec3_tpl tp; - tp.x = m.m00 * p.x + m.m01 * p.y + m.m02 * p.z + m.m03; - tp.y = m.m10 * p.x + m.m11 * p.y + m.m12 * p.z + m.m13; - tp.z = m.m20 * p.x + m.m21 * p.y + m.m22 * p.z + m.m23; - return tp; -} - - -template -ILINE Matrix34_tpl operator*(const Matrix34_tpl& l, const Diag33_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix34_tpl m; - m.m00 = l.m00 * r.x; - m.m01 = l.m01 * r.y; - m.m02 = l.m02 * r.z; - m.m03 = l.m03; - m.m10 = l.m10 * r.x; - m.m11 = l.m11 * r.y; - m.m12 = l.m12 * r.z; - m.m13 = l.m13; - m.m20 = l.m20 * r.x; - m.m21 = l.m21 * r.y; - m.m22 = l.m22 * r.z; - m.m23 = l.m23; - return m; -} -template -ILINE Matrix34_tpl& operator *= (Matrix34_tpl& l, const Diag33_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - l.m00 *= r.x; - l.m01 *= r.y; - l.m02 *= r.z; - l.m10 *= r.x; - l.m11 *= r.y; - l.m12 *= r.z; - l.m20 *= r.x; - l.m21 *= r.y; - l.m22 *= r.z; - return l; -} -template -ILINE Matrix34_tpl operator + (const Matrix34_tpl& l, const Matrix34_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix34_tpl m; - m.m00 = l.m00 + r.m00; - m.m01 = l.m01 + r.m01; - m.m02 = l.m02 + r.m02; - m.m03 = l.m03 + r.m03; - m.m10 = l.m10 + r.m10; - m.m11 = l.m11 + r.m11; - m.m12 = l.m12 + r.m12; - m.m13 = l.m13 + r.m13; - m.m20 = l.m20 + r.m20; - m.m21 = l.m21 + r.m21; - m.m22 = l.m22 + r.m22; - m.m23 = l.m23 + r.m23; - return m; -} -template -ILINE Matrix34_tpl& operator += (Matrix34_tpl& l, const Matrix34_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - l.m00 += r.m00; - l.m01 += r.m01; - l.m02 += r.m02; - l.m03 += r.m03; - l.m10 += r.m10; - l.m11 += r.m11; - l.m12 += r.m12; - l.m13 += r.m13; - l.m20 += r.m20; - l.m21 += r.m21; - l.m22 += r.m22; - l.m23 += r.m23; - return l; -} - -/*! -* Implements the multiplication operator: Matrix34=Matrix34*Matrix33 -* -* Matrix33 and Matrix44 are specified in collumn order for a right-handed coordinate-system. -* AxB = operation B followed by operation A. -* A multiplication takes 27 muls and 24 adds. -* -* Example: -* Matrix34 m34=Matrix33::CreateRotationX(1.94192f);; -* Matrix33 m33=Matrix34::CreateRotationZ(3.14192f); -* Matrix34 result=m34*m33; -*/ -template -ILINE Matrix34_tpl operator * (const Matrix34_tpl& l, const Matrix33_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix34_tpl m; - m.m00 = l.m00 * r.m00 + l.m01 * r.m10 + l.m02 * r.m20; - m.m10 = l.m10 * r.m00 + l.m11 * r.m10 + l.m12 * r.m20; - m.m20 = l.m20 * r.m00 + l.m21 * r.m10 + l.m22 * r.m20; - m.m01 = l.m00 * r.m01 + l.m01 * r.m11 + l.m02 * r.m21; - m.m11 = l.m10 * r.m01 + l.m11 * r.m11 + l.m12 * r.m21; - m.m21 = l.m20 * r.m01 + l.m21 * r.m11 + l.m22 * r.m21; - m.m02 = l.m00 * r.m02 + l.m01 * r.m12 + l.m02 * r.m22; - m.m12 = l.m10 * r.m02 + l.m11 * r.m12 + l.m12 * r.m22; - m.m22 = l.m20 * r.m02 + l.m21 * r.m12 + l.m22 * r.m22; - m.m03 = l.m03; - m.m13 = l.m13; - m.m23 = l.m23; - return m; -} - - - -/*! -* Implements the multiplication operator: Matrix34=Matrix34*Matrix34 -* -* Matrix34 is specified in collumn order. -* AxB = rotation B followed by rotation A. -* This operation takes 36 mults and 27 adds. -* -* Example: -* Matrix34 m34=Matrix34::CreateRotationX(1.94192f, Vec3(11,22,33));; -* Matrix34 m34=Matrix33::CreateRotationZ(3.14192f); -* Matrix34 result=m34*m34; -*/ -template -ILINE Matrix34_tpl operator * (const Matrix34_tpl& l, const Matrix34_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix34_tpl m; - m.m00 = l.m00 * r.m00 + l.m01 * r.m10 + l.m02 * r.m20; - m.m10 = l.m10 * r.m00 + l.m11 * r.m10 + l.m12 * r.m20; - m.m20 = l.m20 * r.m00 + l.m21 * r.m10 + l.m22 * r.m20; - m.m01 = l.m00 * r.m01 + l.m01 * r.m11 + l.m02 * r.m21; - m.m11 = l.m10 * r.m01 + l.m11 * r.m11 + l.m12 * r.m21; - m.m21 = l.m20 * r.m01 + l.m21 * r.m11 + l.m22 * r.m21; - m.m02 = l.m00 * r.m02 + l.m01 * r.m12 + l.m02 * r.m22; - m.m12 = l.m10 * r.m02 + l.m11 * r.m12 + l.m12 * r.m22; - m.m22 = l.m20 * r.m02 + l.m21 * r.m12 + l.m22 * r.m22; - m.m03 = l.m00 * r.m03 + l.m01 * r.m13 + l.m02 * r.m23 + l.m03; - m.m13 = l.m10 * r.m03 + l.m11 * r.m13 + l.m12 * r.m23 + l.m13; - m.m23 = l.m20 * r.m03 + l.m21 * r.m13 + l.m22 * r.m23 + l.m23; - return m; -} - -/*! -* Implements the multiplication operator: Matrix44=Matrix34*Matrix44 -* -* Matrix44 and Matrix34 are specified in collumn order. -* AxB = rotation B followed by rotation A. -* This operation takes 48 mults and 36 adds. -* -* Example: -* Matrix34 m34=Matrix33::CreateRotationX(1.94192f);; -* Matrix44 m44=Matrix33::CreateRotationZ(3.14192f); -* Matrix44 result=m34*m44; -*/ -template -ILINE Matrix44_tpl operator * (const Matrix34_tpl& l, const Matrix44_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix44_tpl m; - m.m00 = l.m00 * r.m00 + l.m01 * r.m10 + l.m02 * r.m20 + l.m03 * r.m30; - m.m10 = l.m10 * r.m00 + l.m11 * r.m10 + l.m12 * r.m20 + l.m13 * r.m30; - m.m20 = l.m20 * r.m00 + l.m21 * r.m10 + l.m22 * r.m20 + l.m23 * r.m30; - m.m30 = r.m30; - m.m01 = l.m00 * r.m01 + l.m01 * r.m11 + l.m02 * r.m21 + l.m03 * r.m31; - m.m11 = l.m10 * r.m01 + l.m11 * r.m11 + l.m12 * r.m21 + l.m13 * r.m31; - m.m21 = l.m20 * r.m01 + l.m21 * r.m11 + l.m22 * r.m21 + l.m23 * r.m31; - m.m31 = r.m31; - m.m02 = l.m00 * r.m02 + l.m01 * r.m12 + l.m02 * r.m22 + l.m03 * r.m32; - m.m12 = l.m10 * r.m02 + l.m11 * r.m12 + l.m12 * r.m22 + l.m13 * r.m32; - m.m22 = l.m20 * r.m02 + l.m21 * r.m12 + l.m22 * r.m22 + l.m23 * r.m32; - m.m32 = r.m32; - m.m03 = l.m00 * r.m03 + l.m01 * r.m13 + l.m02 * r.m23 + l.m03 * r.m33; - m.m13 = l.m10 * r.m03 + l.m11 * r.m13 + l.m12 * r.m23 + l.m13 * r.m33; - m.m23 = l.m20 * r.m03 + l.m21 * r.m13 + l.m22 * r.m23 + l.m23 * r.m33; - m.m33 = r.m33; - return m; -} - -#endif // CRYINCLUDE_CRYCOMMON_CRY_MATRIX34_H - diff --git a/Code/CryEngine/CryCommon/Cry_Matrix44.h b/Code/CryEngine/CryCommon/Cry_Matrix44.h deleted file mode 100644 index ef996daaae..0000000000 --- a/Code/CryEngine/CryCommon/Cry_Matrix44.h +++ /dev/null @@ -1,874 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Common matrix class - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_MATRIX44_H -#define CRYINCLUDE_CRYCOMMON_CRY_MATRIX44_H -#pragma once - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct Matrix44_tpl -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -template -struct Matrix44_tpl -{ - F m00, m01, m02, m03; - F m10, m11, m12, m13; - F m20, m21, m22, m23; - F m30, m31, m32, m33; - - //--------------------------------------------------------------------------------- - -#if defined(_DEBUG) - ILINE Matrix44_tpl() - { - if constexpr (sizeof(F) == 4) - { - uint32* p = (uint32*)&m00; - p[ 0] = F32NAN; - p[ 1] = F32NAN; - p[ 2] = F32NAN; - p[ 3] = F32NAN; - p[ 4] = F32NAN; - p[ 5] = F32NAN; - p[ 6] = F32NAN; - p[ 7] = F32NAN; - p[ 8] = F32NAN; - p[ 9] = F32NAN; - p[10] = F32NAN; - p[11] = F32NAN; - p[12] = F32NAN; - p[13] = F32NAN; - p[14] = F32NAN; - p[15] = F32NAN; - } - if constexpr (sizeof(F) == 8) - { - uint64* p = (uint64*)&m00; - p[ 0] = F64NAN; - p[ 1] = F64NAN; - p[ 2] = F64NAN; - p[ 3] = F64NAN; - p[ 4] = F64NAN; - p[ 5] = F64NAN; - p[ 6] = F64NAN; - p[ 7] = F64NAN; - p[ 8] = F64NAN; - p[ 9] = F64NAN; - p[10] = F64NAN; - p[11] = F64NAN; - p[12] = F64NAN; - p[13] = F64NAN; - p[14] = F64NAN; - p[15] = F64NAN; - } - } -#else - ILINE Matrix44_tpl(){}; -#endif - - //initialize with zeros - ILINE Matrix44_tpl(type_zero) - { - m00 = 0; - m01 = 0; - m02 = 0; - m03 = 0; - m10 = 0; - m11 = 0; - m12 = 0; - m13 = 0; - m20 = 0; - m21 = 0; - m22 = 0; - m23 = 0; - m30 = 0; - m31 = 0; - m32 = 0; - m33 = 0; - } - - - //ASSIGNMENT OPERATOR of identical Matrix44 types. - //The assignment operator has precedence over assignment constructor - //Matrix44 m; m=m44; - ILINE Matrix44_tpl& operator = (const Matrix44_tpl& m) - { - assert(m.IsValid()); - m00 = m.m00; - m01 = m.m01; - m02 = m.m02; - m03 = m.m03; - m10 = m.m10; - m11 = m.m11; - m12 = m.m12; - m13 = m.m13; - m20 = m.m20; - m21 = m.m21; - m22 = m.m22; - m23 = m.m23; - m30 = m.m30; - m31 = m.m31; - m32 = m.m32; - m33 = m.m33; - return *this; - } - - - - //-------------------------------------------------------------------- - //---- implementation of the constructors --- - //-------------------------------------------------------------------- - ILINE Matrix44_tpl(F v00, F v01, F v02, F v03, - F v10, F v11, F v12, F v13, - F v20, F v21, F v22, F v23, - F v30, F v31, F v32, F v33) - { - m00 = v00; - m01 = v01; - m02 = v02; - m03 = v03; - m10 = v10; - m11 = v11; - m12 = v12; - m13 = v13; - m20 = v20; - m21 = v21; - m22 = v22; - m23 = v23; - m30 = v30; - m31 = v31; - m32 = v32; - m33 = v33; - } - - - - - - - //CONSTRUCTOR for different types. It converts a Matrix33 into a Matrix44. - //Matrix44(m33); - ILINE Matrix44_tpl(const Matrix33_tpl&m) - { - assert(m.IsValid()); - m00 = m.m00; - m01 = m.m01; - m02 = m.m02; - m03 = 0; - m10 = m.m10; - m11 = m.m11; - m12 = m.m12; - m13 = 0; - m20 = m.m20; - m21 = m.m21; - m22 = m.m22; - m23 = 0; - m30 = 0; - m31 = 0; - m32 = 0; - m33 = 1; - } - //CONSTRUCTOR for different types. It converts a Matrix33 into a Matrix44 and also converts between double/float. - //Matrix44(Matrix33); - template - ILINE Matrix44_tpl(const Matrix33_tpl&m) - { - assert(m.IsValid()); - m00 = F(m.m00); - m01 = F(m.m01); - m02 = F(m.m02); - m03 = 0; - m10 = F(m.m10); - m11 = F(m.m11); - m12 = F(m.m12); - m13 = 0; - m20 = F(m.m20); - m21 = F(m.m21); - m22 = F(m.m22); - m23 = 0; - m30 = 0; - m31 = 0; - m32 = 0; - m33 = 1; - } - - - //CONSTRUCTOR for different types. It converts a Matrix34 into a Matrix44. - //Matrix44(m34); - ILINE Matrix44_tpl(const Matrix34_tpl&m) - { - assert(m.IsValid()); - m00 = m.m00; - m01 = m.m01; - m02 = m.m02; - m03 = m.m03; - m10 = m.m10; - m11 = m.m11; - m12 = m.m12; - m13 = m.m13; - m20 = m.m20; - m21 = m.m21; - m22 = m.m22; - m23 = m.m23; - m30 = 0; - m31 = 0; - m32 = 0; - m33 = 1; - } - //CONSTRUCTOR for different types. It converts a Matrix34 into a Matrix44 and also converts between double/float. - //Matrix44(Matrix34); - template - ILINE Matrix44_tpl(const Matrix34_tpl&m) - { - assert(m.IsValid()); - m00 = F(m.m00); - m01 = F(m.m01); - m02 = F(m.m02); - m03 = F(m.m03); - m10 = F(m.m10); - m11 = F(m.m11); - m12 = F(m.m12); - m13 = F(m.m13); - m20 = F(m.m20); - m21 = F(m.m21); - m22 = F(m.m22); - m23 = F(m.m23); - m30 = 0; - m31 = 0; - m32 = 0; - m33 = 1; - } - - - //CONSTRUCTOR for identical types - //Matrix44 m=m44; - ILINE Matrix44_tpl(const Matrix44_tpl&m) - { - assert(m.IsValid()); - m00 = m.m00; - m01 = m.m01; - m02 = m.m02; - m03 = m.m03; - m10 = m.m10; - m11 = m.m11; - m12 = m.m12; - m13 = m.m13; - m20 = m.m20; - m21 = m.m21; - m22 = m.m22; - m23 = m.m23; - m30 = m.m30; - m31 = m.m31; - m32 = m.m32; - m33 = m.m33; - } - //CONSTRUCTOR for identical types which converts between double/float - //Matrix44 m=m44r; - //Matrix44r m=m44; - template - ILINE Matrix44_tpl(const Matrix44_tpl&m) - { - assert(m.IsValid()); - m00 = F(m.m00); - m01 = F(m.m01); - m02 = F(m.m02); - m03 = F(m.m03); - m10 = F(m.m10); - m11 = F(m.m11); - m12 = F(m.m12); - m13 = F(m.m13); - m20 = F(m.m20); - m21 = F(m.m21); - m22 = F(m.m22); - m23 = F(m.m23); - m30 = F(m.m30); - m31 = F(m.m31); - m32 = F(m.m32); - m33 = F(m.m33); - } - - //--------------------------------------------------------------------- - - //! multiply all m1 matrix's values by f and return the matrix - friend ILINE Matrix44_tpl operator * (const Matrix44_tpl& m, const f32 f) - { - assert(m.IsValid()); - Matrix44_tpl r; - r.m00 = m.m00 * f; - r.m01 = m.m01 * f; - r.m02 = m.m02 * f; - r.m03 = m.m03 * f; - r.m10 = m.m10 * f; - r.m11 = m.m11 * f; - r.m12 = m.m12 * f; - r.m13 = m.m13 * f; - r.m20 = m.m20 * f; - r.m21 = m.m21 * f; - r.m22 = m.m22 * f; - r.m23 = m.m23 * f; - r.m30 = m.m30 * f; - r.m31 = m.m31 * f; - r.m32 = m.m32 * f; - r.m33 = m.m33 * f; - return r; - } - - //! add all m matrix's values and return the matrix - friend ILINE Matrix44_tpl operator + (const Matrix44_tpl& mm0, const Matrix44_tpl& mm1) - { - assert(mm0.IsValid()); - assert(mm1.IsValid()); - Matrix44_tpl r; - r.m00 = mm0.m00 + mm1.m00; - r.m01 = mm0.m01 + mm1.m01; - r.m02 = mm0.m02 + mm1.m02; - r.m03 = mm0.m03 + mm1.m03; - r.m10 = mm0.m10 + mm1.m10; - r.m11 = mm0.m11 + mm1.m11; - r.m12 = mm0.m12 + mm1.m12; - r.m13 = mm0.m13 + mm1.m13; - r.m20 = mm0.m20 + mm1.m20; - r.m21 = mm0.m21 + mm1.m21; - r.m22 = mm0.m22 + mm1.m22; - r.m23 = mm0.m23 + mm1.m23; - r.m30 = mm0.m30 + mm1.m30; - r.m31 = mm0.m31 + mm1.m31; - r.m32 = mm0.m32 + mm1.m32; - r.m33 = mm0.m33 + mm1.m33; - return r; - } - - ILINE void SetIdentity() - { - m00 = 1; - m01 = 0; - m02 = 0; - m03 = 0; - m10 = 0; - m11 = 1; - m12 = 0; - m13 = 0; - m20 = 0; - m21 = 0; - m22 = 1; - m23 = 0; - m30 = 0; - m31 = 0; - m32 = 0; - m33 = 1; - } - ILINE Matrix44_tpl(type_identity) { SetIdentity(); } - - - ILINE void Transpose() - { - Matrix44_tpl tmp = *this; - m00 = tmp.m00; - m01 = tmp.m10; - m02 = tmp.m20; - m03 = tmp.m30; - m10 = tmp.m01; - m11 = tmp.m11; - m12 = tmp.m21; - m13 = tmp.m31; - m20 = tmp.m02; - m21 = tmp.m12; - m22 = tmp.m22; - m23 = tmp.m32; - m30 = tmp.m03; - m31 = tmp.m13; - m32 = tmp.m23; - m33 = tmp.m33; - } - ILINE Matrix44_tpl GetTransposed() const - { - Matrix44_tpl tmp; - tmp.m00 = m00; - tmp.m01 = m10; - tmp.m02 = m20; - tmp.m03 = m30; - tmp.m10 = m01; - tmp.m11 = m11; - tmp.m12 = m21; - tmp.m13 = m31; - tmp.m20 = m02; - tmp.m21 = m12; - tmp.m22 = m22; - tmp.m23 = m32; - tmp.m30 = m03; - tmp.m31 = m13; - tmp.m32 = m23; - tmp.m33 = m33; - return tmp; - } - - /*! - * - * Calculate a real inversion of a Matrix44. - * - * Uses Cramer's Rule which is faster (branchless) but numerically more unstable - * than other methods like Gaussian Elimination. - * - * Example 1: - * Matrix44 im44; im44.Invert(); - * - * Example 2: - * Matrix44 im44 = m33.GetInverted(); - */ - void Invert(void) - { - F tmp[12]; - Matrix44_tpl m = *this; - - // Calculate pairs for first 8 elements (cofactors) - tmp[0] = m.m22 * m.m33; - tmp[1] = m.m32 * m.m23; - tmp[2] = m.m12 * m.m33; - tmp[3] = m.m32 * m.m13; - tmp[4] = m.m12 * m.m23; - tmp[5] = m.m22 * m.m13; - tmp[6] = m.m02 * m.m33; - tmp[7] = m.m32 * m.m03; - tmp[8] = m.m02 * m.m23; - tmp[9] = m.m22 * m.m03; - tmp[10] = m.m02 * m.m13; - tmp[11] = m.m12 * m.m03; - - // Calculate first 8 elements (cofactors) - m00 = tmp[0] * m.m11 + tmp[3] * m.m21 + tmp[ 4] * m.m31; - m00 -= tmp[1] * m.m11 + tmp[2] * m.m21 + tmp[ 5] * m.m31; - m01 = tmp[1] * m.m01 + tmp[6] * m.m21 + tmp[ 9] * m.m31; - m01 -= tmp[0] * m.m01 + tmp[7] * m.m21 + tmp[ 8] * m.m31; - m02 = tmp[2] * m.m01 + tmp[7] * m.m11 + tmp[10] * m.m31; - m02 -= tmp[3] * m.m01 + tmp[6] * m.m11 + tmp[11] * m.m31; - m03 = tmp[5] * m.m01 + tmp[8] * m.m11 + tmp[11] * m.m21; - m03 -= tmp[4] * m.m01 + tmp[9] * m.m11 + tmp[10] * m.m21; - m10 = tmp[1] * m.m10 + tmp[2] * m.m20 + tmp[ 5] * m.m30; - m10 -= tmp[0] * m.m10 + tmp[3] * m.m20 + tmp[ 4] * m.m30; - m11 = tmp[0] * m.m00 + tmp[7] * m.m20 + tmp[ 8] * m.m30; - m11 -= tmp[1] * m.m00 + tmp[6] * m.m20 + tmp[ 9] * m.m30; - m12 = tmp[3] * m.m00 + tmp[6] * m.m10 + tmp[11] * m.m30; - m12 -= tmp[2] * m.m00 + tmp[7] * m.m10 + tmp[10] * m.m30; - m13 = tmp[4] * m.m00 + tmp[9] * m.m10 + tmp[10] * m.m20; - m13 -= tmp[5] * m.m00 + tmp[8] * m.m10 + tmp[11] * m.m20; - - // Calculate pairs for second 8 elements (cofactors) - tmp[ 0] = m.m20 * m.m31; - tmp[ 1] = m.m30 * m.m21; - tmp[ 2] = m.m10 * m.m31; - tmp[ 3] = m.m30 * m.m11; - tmp[ 4] = m.m10 * m.m21; - tmp[ 5] = m.m20 * m.m11; - tmp[ 6] = m.m00 * m.m31; - tmp[ 7] = m.m30 * m.m01; - tmp[ 8] = m.m00 * m.m21; - tmp[ 9] = m.m20 * m.m01; - tmp[10] = m.m00 * m.m11; - tmp[11] = m.m10 * m.m01; - - // Calculate second 8 elements (cofactors) - m20 = tmp[ 0] * m.m13 + tmp[ 3] * m.m23 + tmp[ 4] * m.m33; - m20 -= tmp[ 1] * m.m13 + tmp[ 2] * m.m23 + tmp[ 5] * m.m33; - m21 = tmp[ 1] * m.m03 + tmp[ 6] * m.m23 + tmp[ 9] * m.m33; - m21 -= tmp[ 0] * m.m03 + tmp[ 7] * m.m23 + tmp[ 8] * m.m33; - m22 = tmp[ 2] * m.m03 + tmp[ 7] * m.m13 + tmp[10] * m.m33; - m22 -= tmp[ 3] * m.m03 + tmp[ 6] * m.m13 + tmp[11] * m.m33; - m23 = tmp[ 5] * m.m03 + tmp[ 8] * m.m13 + tmp[11] * m.m23; - m23 -= tmp[ 4] * m.m03 + tmp[ 9] * m.m13 + tmp[10] * m.m23; - m30 = tmp[ 2] * m.m22 + tmp[ 5] * m.m32 + tmp[ 1] * m.m12; - m30 -= tmp[ 4] * m.m32 + tmp[ 0] * m.m12 + tmp[ 3] * m.m22; - m31 = tmp[ 8] * m.m32 + tmp[ 0] * m.m02 + tmp[ 7] * m.m22; - m31 -= tmp[ 6] * m.m22 + tmp[ 9] * m.m32 + tmp[ 1] * m.m02; - m32 = tmp[ 6] * m.m12 + tmp[11] * m.m32 + tmp[ 3] * m.m02; - m32 -= tmp[10] * m.m32 + tmp[ 2] * m.m02 + tmp[ 7] * m.m12; - m33 = tmp[10] * m.m22 + tmp[ 4] * m.m02 + tmp[ 9] * m.m12; - m33 -= tmp[ 8] * m.m12 + tmp[11] * m.m22 + tmp[ 5] * m.m02; - - // Calculate determinant - F det = (m.m00 * m00 + m.m10 * m01 + m.m20 * m02 + m.m30 * m03); - //if (fabs_tpl(det)<0.0001f) assert(0); - - // Divide the cofactor-matrix by the determinant - F idet = (F)1.0 / det; - m00 *= idet; - m01 *= idet; - m02 *= idet; - m03 *= idet; - m10 *= idet; - m11 *= idet; - m12 *= idet; - m13 *= idet; - m20 *= idet; - m21 *= idet; - m22 *= idet; - m23 *= idet; - m30 *= idet; - m31 *= idet; - m32 *= idet; - m33 *= idet; - } - - ILINE Matrix44_tpl GetInverted() const - { - Matrix44_tpl dst = *this; - dst.Invert(); - return dst; - } - - - ILINE f32 Determinant() const - { - //determinant is ambiguous: only the upper-left-submatrix's determinant is calculated - return (m00 * m11 * m22) + (m01 * m12 * m20) + (m02 * m10 * m21) - (m02 * m11 * m20) - (m00 * m12 * m21) - (m01 * m10 * m22); - } - - //! transform a vector - ILINE Vec3 TransformVector(const Vec3& b) const - { - assert(b.IsValid()); - Vec3 v; - v.x = m00 * b.x + m01 * b.y + m02 * b.z; - v.y = m10 * b.x + m11 * b.y + m12 * b.z; - v.z = m20 * b.x + m21 * b.y + m22 * b.z; - return v; - } - //! transform a point - ILINE Vec3 TransformPoint(const Vec3& b) const - { - assert(b.IsValid()); - Vec3 v; - v.x = m00 * b.x + m01 * b.y + m02 * b.z + m03; - v.y = m10 * b.x + m11 * b.y + m12 * b.z + m13; - v.z = m20 * b.x + m21 * b.y + m22 * b.z + m23; - return v; - } - - - //-------------------------------------------------------------------------------- - //---- helper functions to access matrix-members ------------ - //-------------------------------------------------------------------------------- - ILINE F* GetData() { return &m00; } - ILINE const F* GetData() const { return &m00; } - - ILINE F operator () (uint32 i, uint32 j) const { assert ((i < 4) && (j < 4)); F* p_data = (F*)(&m00); return p_data[i * 4 + j]; } - ILINE F& operator () (uint32 i, uint32 j) { assert ((i < 4) && (j < 4)); F* p_data = (F*)(&m00); return p_data[i * 4 + j]; } - - ILINE void SetRow(int i, const Vec3_tpl& v) { assert(i < 4); F* p = (F*)(&m00); p[0 + 4 * i] = v.x; p[1 + 4 * i] = v.y; p[2 + 4 * i] = v.z; } - ILINE void SetRow4(int i, const Vec4_tpl& v) { assert(i < 4); F* p = (F*)(&m00); p[0 + 4 * i] = v.x; p[1 + 4 * i] = v.y; p[2 + 4 * i] = v.z; p[3 + 4 * i] = v.w; } - ILINE const Vec3_tpl& GetRow(int i) const { assert(i < 4); return *(const Vec3_tpl*)(&m00 + 4 * i); } - - ILINE void SetColumn(int i, const Vec3_tpl& v) { assert(i < 4); F* p = (F*)(&m00); p[i + 4 * 0] = v.x; p[i + 4 * 1] = v.y; p[i + 4 * 2] = v.z; } - ILINE Vec3_tpl GetColumn(int i) const { assert(i < 4); F* p = (F*)(&m00); return Vec3(p[i + 4 * 0], p[i + 4 * 1], p[i + 4 * 2]); } - ILINE Vec4_tpl GetColumn4(int i) const { assert(i < 4); F* p = (F*)(&m00); return Vec4(p[i + 4 * 0], p[i + 4 * 1], p[i + 4 * 2], p[i + 4 * 3]); } - - ILINE Vec3 GetTranslation() const { return Vec3(m03, m13, m23); } - ILINE void SetTranslation(const Vec3& t) { m03 = t.x; m13 = t.y; m23 = t.z; } - - bool IsValid() const - { - if (!NumberValid(m00)) - { - return false; - } - if (!NumberValid(m01)) - { - return false; - } - if (!NumberValid(m02)) - { - return false; - } - if (!NumberValid(m03)) - { - return false; - } - if (!NumberValid(m10)) - { - return false; - } - if (!NumberValid(m11)) - { - return false; - } - if (!NumberValid(m12)) - { - return false; - } - if (!NumberValid(m13)) - { - return false; - } - if (!NumberValid(m20)) - { - return false; - } - if (!NumberValid(m21)) - { - return false; - } - if (!NumberValid(m22)) - { - return false; - } - if (!NumberValid(m23)) - { - return false; - } - if (!NumberValid(m30)) - { - return false; - } - if (!NumberValid(m31)) - { - return false; - } - if (!NumberValid(m32)) - { - return false; - } - if (!NumberValid(m33)) - { - return false; - } - return true; - } - static bool IsEquivalent(const Matrix44_tpl& m0, const Matrix44_tpl& m1, F e = VEC_EPSILON) - { - return ( - (fabs_tpl(m0.m00 - m1.m00) <= e) && (fabs_tpl(m0.m01 - m1.m01) <= e) && (fabs_tpl(m0.m02 - m1.m02) <= e) && (fabs_tpl(m0.m03 - m1.m03) <= e) && - (fabs_tpl(m0.m10 - m1.m10) <= e) && (fabs_tpl(m0.m11 - m1.m11) <= e) && (fabs_tpl(m0.m12 - m1.m12) <= e) && (fabs_tpl(m0.m13 - m1.m13) <= e) && - (fabs_tpl(m0.m20 - m1.m20) <= e) && (fabs_tpl(m0.m21 - m1.m21) <= e) && (fabs_tpl(m0.m22 - m1.m22) <= e) && (fabs_tpl(m0.m23 - m1.m23) <= e) && - (fabs_tpl(m0.m30 - m1.m30) <= e) && (fabs_tpl(m0.m31 - m1.m31) <= e) && (fabs_tpl(m0.m32 - m1.m32) <= e) && (fabs_tpl(m0.m33 - m1.m33) <= e) - ); - } - - AUTO_STRUCT_INFO -}; - -/////////////////////////////////////////////////////////////////////////////// -// Typedefs // -/////////////////////////////////////////////////////////////////////////////// - -typedef Matrix44_tpl Matrix44; //always 32 bit -typedef Matrix44_tpl Matrix44d; //always 64 bit -typedef Matrix44_tpl Matrix44r; //variable float precision. depending on the target system it can be between 32, 64 or 80 bit -typedef _MS_ALIGN(16) Matrix44_tpl _ALIGN (16) Matrix44A; - -//---------------------------------------------------------------------------------- -//---------------------------------------------------------------------------------- -//---------------------------------------------------------------------------------- -//------------- implementation of Matrix44 ------------------------------ -//---------------------------------------------------------------------------------- -//---------------------------------------------------------------------------------- -//---------------------------------------------------------------------------------- - -/*! -* Implements the multiplication operator: Matrix44=Matrix44*Matrix33diag -* -* Matrix44 and Matrix33diag are specified in collumn order. -* AxB = operation B followed by operation A. -* This operation takes 12 mults. -* -* Example: -* Matrix33diag diag(1,2,3); -* Matrix44 m44=CreateRotationZ33(3.14192f); -* Matrix44 result=m44*diag; -*/ -template -ILINE Matrix44_tpl operator * (const Matrix44_tpl& l, const Diag33_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix44_tpl m; - m.m00 = l.m00 * r.x; - m.m01 = l.m01 * r.y; - m.m02 = l.m02 * r.z; - m.m03 = l.m03; - m.m10 = l.m10 * r.x; - m.m11 = l.m11 * r.y; - m.m12 = l.m12 * r.z; - m.m13 = l.m13; - m.m20 = l.m20 * r.x; - m.m21 = l.m21 * r.y; - m.m22 = l.m22 * r.z; - m.m23 = l.m23; - m.m30 = l.m30 * r.x; - m.m31 = l.m31 * r.y; - m.m32 = l.m32 * r.z; - m.m33 = l.m33; - return m; -} -template -ILINE Matrix44_tpl& operator *= (Matrix44_tpl& l, const Diag33_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - l.m00 *= r.x; - l.m01 *= r.y; - l.m02 *= r.z; - l.m10 *= r.x; - l.m11 *= r.y; - l.m12 *= r.z; - l.m20 *= r.x; - l.m21 *= r.y; - l.m22 *= r.z; - l.m30 *= r.x; - l.m31 *= r.y; - l.m32 *= r.z; - return l; -} - - -/*! -* Implements the multiplication operator: Matrix44=Matrix44*Matrix33 -* -* Matrix44 and Matrix33 are specified in collumn order. -* AxB = rotation B followed by rotation A. -* This operation takes 48 mults and 24 adds. -* -* Example: -* Matrix33 m34=CreateRotationX33(1.94192f);; -* Matrix44 m44=CreateRotationZ33(3.14192f); -* Matrix44 result=m44*m33; -*/ -template -ILINE Matrix44_tpl operator * (const Matrix44_tpl& l, const Matrix33_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix44_tpl m; - m.m00 = l.m00 * r.m00 + l.m01 * r.m10 + l.m02 * r.m20; - m.m10 = l.m10 * r.m00 + l.m11 * r.m10 + l.m12 * r.m20; - m.m20 = l.m20 * r.m00 + l.m21 * r.m10 + l.m22 * r.m20; - m.m30 = l.m30 * r.m00 + l.m31 * r.m10 + l.m32 * r.m20; - m.m01 = l.m00 * r.m01 + l.m01 * r.m11 + l.m02 * r.m21; - m.m11 = l.m10 * r.m01 + l.m11 * r.m11 + l.m12 * r.m21; - m.m21 = l.m20 * r.m01 + l.m21 * r.m11 + l.m22 * r.m21; - m.m31 = l.m30 * r.m01 + l.m31 * r.m11 + l.m32 * r.m21; - m.m02 = l.m00 * r.m02 + l.m01 * r.m12 + l.m02 * r.m22; - m.m12 = l.m10 * r.m02 + l.m11 * r.m12 + l.m12 * r.m22; - m.m22 = l.m20 * r.m02 + l.m21 * r.m12 + l.m22 * r.m22; - m.m32 = l.m30 * r.m02 + l.m31 * r.m12 + l.m32 * r.m22; - m.m03 = l.m03; - m.m13 = l.m13; - m.m23 = l.m23; - m.m33 = l.m33; - return m; -} - - -/*! -* Implements the multiplication operator: Matrix44=Matrix44*Matrix34 -* -* Matrix44 and Matrix34 are specified in collumn order. -* AxB = rotation B followed by rotation A. -* This operation takes 48 mults and 36 adds. -* -* Example: -* Matrix34 m34=CreateRotationX33(1.94192f);; -* Matrix44 m44=CreateRotationZ33(3.14192f); -* Matrix44 result=m44*m34; -*/ -template -ILINE Matrix44_tpl operator * (const Matrix44_tpl& l, const Matrix34_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix44_tpl m; - m.m00 = l.m00 * r.m00 + l.m01 * r.m10 + l.m02 * r.m20; - m.m10 = l.m10 * r.m00 + l.m11 * r.m10 + l.m12 * r.m20; - m.m20 = l.m20 * r.m00 + l.m21 * r.m10 + l.m22 * r.m20; - m.m30 = l.m30 * r.m00 + l.m31 * r.m10 + l.m32 * r.m20; - m.m01 = l.m00 * r.m01 + l.m01 * r.m11 + l.m02 * r.m21; - m.m11 = l.m10 * r.m01 + l.m11 * r.m11 + l.m12 * r.m21; - m.m21 = l.m20 * r.m01 + l.m21 * r.m11 + l.m22 * r.m21; - m.m31 = l.m30 * r.m01 + l.m31 * r.m11 + l.m32 * r.m21; - m.m02 = l.m00 * r.m02 + l.m01 * r.m12 + l.m02 * r.m22; - m.m12 = l.m10 * r.m02 + l.m11 * r.m12 + l.m12 * r.m22; - m.m22 = l.m20 * r.m02 + l.m21 * r.m12 + l.m22 * r.m22; - m.m32 = l.m30 * r.m02 + l.m31 * r.m12 + l.m32 * r.m22; - m.m03 = l.m00 * r.m03 + l.m01 * r.m13 + l.m02 * r.m23 + l.m03; - m.m13 = l.m10 * r.m03 + l.m11 * r.m13 + l.m12 * r.m23 + l.m13; - m.m23 = l.m20 * r.m03 + l.m21 * r.m13 + l.m22 * r.m23 + l.m23; - m.m33 = l.m30 * r.m03 + l.m31 * r.m13 + l.m32 * r.m23 + l.m33; - return m; -} - - -/*! -* Implements the multiplication operator: Matrix44=Matrix44*Matrix44 -* -* Matrix44 and Matrix34 are specified in collumn order. -* AxB = rotation B followed by rotation A. -* This operation takes 48 mults and 36 adds. -* -* Example: -* Matrix44 m44=CreateRotationX33(1.94192f);; -* Matrix44 m44=CreateRotationZ33(3.14192f); -* Matrix44 result=m44*m44; -*/ -template -ILINE Matrix44_tpl operator * (const Matrix44_tpl& l, const Matrix44_tpl& r) -{ - assert(l.IsValid()); - assert(r.IsValid()); - Matrix44_tpl res; - res.m00 = l.m00 * r.m00 + l.m01 * r.m10 + l.m02 * r.m20 + l.m03 * r.m30; - res.m10 = l.m10 * r.m00 + l.m11 * r.m10 + l.m12 * r.m20 + l.m13 * r.m30; - res.m20 = l.m20 * r.m00 + l.m21 * r.m10 + l.m22 * r.m20 + l.m23 * r.m30; - res.m30 = l.m30 * r.m00 + l.m31 * r.m10 + l.m32 * r.m20 + l.m33 * r.m30; - res.m01 = l.m00 * r.m01 + l.m01 * r.m11 + l.m02 * r.m21 + l.m03 * r.m31; - res.m11 = l.m10 * r.m01 + l.m11 * r.m11 + l.m12 * r.m21 + l.m13 * r.m31; - res.m21 = l.m20 * r.m01 + l.m21 * r.m11 + l.m22 * r.m21 + l.m23 * r.m31; - res.m31 = l.m30 * r.m01 + l.m31 * r.m11 + l.m32 * r.m21 + l.m33 * r.m31; - res.m02 = l.m00 * r.m02 + l.m01 * r.m12 + l.m02 * r.m22 + l.m03 * r.m32; - res.m12 = l.m10 * r.m02 + l.m11 * r.m12 + l.m12 * r.m22 + l.m13 * r.m32; - res.m22 = l.m20 * r.m02 + l.m21 * r.m12 + l.m22 * r.m22 + l.m23 * r.m32; - res.m32 = l.m30 * r.m02 + l.m31 * r.m12 + l.m32 * r.m22 + l.m33 * r.m32; - res.m03 = l.m00 * r.m03 + l.m01 * r.m13 + l.m02 * r.m23 + l.m03 * r.m33; - res.m13 = l.m10 * r.m03 + l.m11 * r.m13 + l.m12 * r.m23 + l.m13 * r.m33; - res.m23 = l.m20 * r.m03 + l.m21 * r.m13 + l.m22 * r.m23 + l.m23 * r.m33; - res.m33 = l.m30 * r.m03 + l.m31 * r.m13 + l.m32 * r.m23 + l.m33 * r.m33; - return res; -} - -//post-multiply -template -ILINE Vec4_tpl operator*(const Matrix44_tpl& m, const Vec4_tpl& v) -{ - assert(m.IsValid()); - assert(v.IsValid()); - return Vec4_tpl(v.x * m.m00 + v.y * m.m01 + v.z * m.m02 + v.w * m.m03, - v.x * m.m10 + v.y * m.m11 + v.z * m.m12 + v.w * m.m13, - v.x * m.m20 + v.y * m.m21 + v.z * m.m22 + v.w * m.m23, - v.x * m.m30 + v.y * m.m31 + v.z * m.m32 + v.w * m.m33); -} - -//pre-multiply -template -ILINE Vec4_tpl operator*(const Vec4_tpl& v, const Matrix44_tpl& m) -{ - assert(m.IsValid()); - assert(v.IsValid()); - return Vec4_tpl(v.x * m.m00 + v.y * m.m10 + v.z * m.m20 + v.w * m.m30, - v.x * m.m01 + v.y * m.m11 + v.z * m.m21 + v.w * m.m31, - v.x * m.m02 + v.y * m.m12 + v.z * m.m22 + v.w * m.m32, - v.x * m.m03 + v.y * m.m13 + v.z * m.m23 + v.w * m.m33); -} - - -#endif // CRYINCLUDE_CRYCOMMON_CRY_MATRIX44_H - diff --git a/Code/CryEngine/CryCommon/Cry_MatrixDiag.h b/Code/CryEngine/CryCommon/Cry_MatrixDiag.h deleted file mode 100644 index dd3a182e03..0000000000 --- a/Code/CryEngine/CryCommon/Cry_MatrixDiag.h +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Common matrix class - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_MATRIXDIAG_H -#define CRYINCLUDE_CRYCOMMON_CRY_MATRIXDIAG_H -#pragma once - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct Diag33_tpl -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -template -struct Diag33_tpl -{ - F x, y, z; - -#ifdef _DEBUG - ILINE Diag33_tpl() - { - if constexpr (sizeof(F) == 4) - { - uint32* p = alias_cast(&x); - p[0] = F32NAN; - p[1] = F32NAN; - p[2] = F32NAN; - } - if constexpr (sizeof(F) == 8) - { - uint64* p = alias_cast(&x); - p[0] = F64NAN; - p[1] = F64NAN; - p[2] = F64NAN; - } - } -#else - ILINE Diag33_tpl() {}; -#endif - - - Diag33_tpl(F dx, F dy, F dz) { x = dx; y = dy; z = dz; } - Diag33_tpl(const Vec3_tpl& v) { x = v.x; y = v.y; z = v.z; } - template - const Diag33_tpl& operator=(const Vec3_tpl& v) { x = v.x; y = v.y; z = v.z; return *this; } - Diag33_tpl& operator=(const Diag33_tpl& diag) { x = diag.x; y = diag.y; z = diag.z; return *this; } - template - Diag33_tpl& operator=(const Diag33_tpl& diag) { x = diag.x; y = diag.y; z = diag.z; return *this; } - - const void SetIdentity() { x = y = z = 1; } - Diag33_tpl(type_identity) { x = y = z = 1; } - - const Diag33_tpl& zero() { x = y = z = 0; return *this; } - - Diag33_tpl& fabs() { x = fabs_tpl(x); y = fabs_tpl(y); z = fabs_tpl(z); return *this; } - - Diag33_tpl& invert() // in-place inversion - { - F det = determinant(); - if (det == 0) - { - return *this; - } - det = (F)1.0 / det; - F oldata[3]; - oldata[0] = x; - oldata[1] = y; - oldata[2] = z; - x = oldata[1] * oldata[2] * det; - y = oldata[0] * oldata[2] * det; - z = oldata[0] * oldata[1] * det; - return *this; - } - - /*! - * Linear-Interpolation between Diag33(lerp) - * - * Example: - * Diag33 r=Diag33::CreateLerp( p, q, 0.345f ); - */ - ILINE void SetLerp(const Diag33_tpl& p, const Diag33_tpl& q, F t) - { - x = p.x * (1.0f - t) + q.x * t; - y = p.y * (1.0f - t) + q.y * t; - z = p.z * (1.0f - t) + q.z * t; - } - ILINE static Diag33_tpl CreateLerp(const Diag33_tpl& p, const Diag33_tpl& q, F t) - { - Diag33_tpl d; - d.x = p.x * (1.0f - t) + q.x * t; - d.y = p.y * (1.0f - t) + q.y * t; - d.z = p.z * (1.0f - t) + q.z * t; - return d; - } - - F determinant() const { return x * y * z; } - - ILINE bool IsValid() const - { - if (!NumberValid(x)) - { - return false; - } - if (!NumberValid(y)) - { - return false; - } - if (!NumberValid(z)) - { - return false; - } - return true; - } -}; - -/////////////////////////////////////////////////////////////////////////////// -// Typedefs // -/////////////////////////////////////////////////////////////////////////////// - -typedef Diag33_tpl Diag33; //always 32 bit -typedef Diag33_tpl Diag33d;//always 64 bit -typedef Diag33_tpl Diag33r;//variable float precision. depending on the target system it can be between 32, 64 or 80 bit - - -template -Diag33_tpl operator*(const Diag33_tpl& l, const Diag33_tpl& r) -{ - return Diag33_tpl(l.x * r.x, l.y * r.y, l.z * r.z); -} - -template -Matrix33_tpl operator*(const Diag33_tpl& l, const Matrix33_tpl& r) -{ - Matrix33_tpl res; - res.m00 = r.m00 * l.x; - res.m01 = r.m01 * l.x; - res.m02 = r.m02 * l.x; - res.m10 = r.m10 * l.y; - res.m11 = r.m11 * l.y; - res.m12 = r.m12 * l.y; - res.m20 = r.m20 * l.z; - res.m21 = r.m21 * l.z; - res.m22 = r.m22 * l.z; - return res; -} -template -Matrix34_tpl operator*(const Diag33_tpl& l, const Matrix34_tpl& r) -{ - Matrix34_tpl m; - m.m00 = l.x * r.m00; - m.m01 = l.x * r.m01; - m.m02 = l.x * r.m02; - m.m03 = l.x * r.m03; - m.m10 = l.y * r.m10; - m.m11 = l.y * r.m11; - m.m12 = l.y * r.m12; - m.m13 = l.y * r.m13; - m.m20 = l.z * r.m20; - m.m21 = l.z * r.m21; - m.m22 = l.z * r.m22; - m.m23 = l.z * r.m23; - return m; -} - -template -Vec3_tpl operator *(const Diag33_tpl& mtx, const Vec3_tpl& vec) -{ - return Vec3_tpl(mtx.x * vec.x, mtx.y * vec.y, mtx.z * vec.z); -} - -template -Vec3_tpl operator *(const Vec3_tpl& vec, const Diag33_tpl& mtx) -{ - return Vec3_tpl(mtx.x * vec.x, mtx.y * vec.y, mtx.z * vec.z); -} - - - -#endif // CRYINCLUDE_CRYCOMMON_CRY_MATRIXDIAG_H - diff --git a/Code/CryEngine/CryCommon/Cry_Quat.h b/Code/CryEngine/CryCommon/Cry_Quat.h deleted file mode 100644 index 5765e56d5f..0000000000 --- a/Code/CryEngine/CryCommon/Cry_Quat.h +++ /dev/null @@ -1,2228 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Common quaternion class - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_QUAT_H -#define CRYINCLUDE_CRYCOMMON_CRY_QUAT_H -#pragma once - -#include - -//---------------------------------------------------------------------- -// Quaternion -//---------------------------------------------------------------------- -template -struct Quat_tpl -{ - Vec3_tpl v; - F w; - - //------------------------------- - - //constructors -#if defined(_DEBUG) - ILINE Quat_tpl() - { - if constexpr (sizeof(F) == 4) - { - uint32* p = alias_cast(&v.x); - p[0] = F32NAN; - p[1] = F32NAN; - p[2] = F32NAN; - p[3] = F32NAN; - } - if constexpr (sizeof(F) == 8) - { - uint64* p = alias_cast(&v.x); - p[0] = F64NAN; - p[1] = F64NAN; - p[2] = F64NAN; - p[3] = F64NAN; - } - } -#else - ILINE Quat_tpl() {} -#endif - - //initialize with zeros - ILINE Quat_tpl(type_zero) - { - w = 0, v.x = 0, v.y = 0, v.z = 0; - } - ILINE Quat_tpl(type_identity) - { - w = 1, v.x = 0, v.y = 0, v.z = 0; - } - - //ASSIGNMENT OPERATOR of identical Quat types. - //The assignment operator has precedence over assignment constructor - //Quat q; q=q0; - ILINE Quat_tpl& operator = (const Quat_tpl& src) - { - v.x = src.v.x; - v.y = src.v.y; - v.z = src.v.z; - w = src.w; - assert(IsValid()); - return *this; - } - - - //CONSTRUCTOR to initialize a Quat from 4 floats - //Quat q(1,0,0,0); - ILINE Quat_tpl(F qw, F qx, F qy, F qz) - { - w = qw; - v.x = qx; - v.y = qy; - v.z = qz; - assert(IsValid()); - } - //CONSTRUCTOR to initialize a Quat with a scalar and a vector - //Quat q(1,Vec3(0,0,0)); - ILINE Quat_tpl(F scalar, const Vec3_tpl &vector) - { - v = vector; - w = scalar; - assert(IsValid()); - }; - - - //CONSTRUCTOR for identical types - //Quat q=q0; - ILINE Quat_tpl(const Quat_tpl&q) - { - w = q.w; - v.x = q.v.x; - v.y = q.v.y; - v.z = q.v.z; - assert(IsValid()); - } - - //CONSTRUCTOR for AZ::Quaternion - explicit ILINE Quat_tpl(const AZ::Quaternion& q) - { - w = q.GetW(); - v.x = q.GetX(); - v.y = q.GetY(); - v.z = q.GetZ(); - assert(IsValid()); - } - - //CONSTRUCTOR for identical types which converts between double/float - //Quat q32=q64; - //Quatr q64=q32; - template - ILINE Quat_tpl(const Quat_tpl&q) - { - assert(q.IsValid()); - w = F(q.w); - v.x = F(q.v.x); - v.y = F(q.v.y); - v.z = F(q.v.z); - } - - - - - - - - //CONSTRUCTOR for different types. It converts a Euler Angle into a Quat. - //Needs to be 'explicit' because we loose fp-precision in the conversion process - //Quat(Ang3(1,2,3)); - explicit ILINE Quat_tpl(const Ang3_tpl&ang) - { - assert(ang.IsValid()); - SetRotationXYZ(ang); - } - //CONSTRUCTOR for different types. It converts a Euler Angle into a Quat and converts between double/float. . - //Needs to be 'explicit' because we loose fp-precision in the conversion process - //Quat(Ang3r(1,2,3)); - template - explicit ILINE Quat_tpl(const Ang3_tpl&ang) - { - assert(ang.IsValid()); - SetRotationXYZ(Ang3_tpl(F(ang.x), F(ang.y), F(ang.z))); - } - - - //CONSTRUCTOR for different types. It converts a Matrix33 into a Quat. - //Needs to be 'explicit' because we loose fp-precision in the conversion process - //Quat(m33); - explicit ILINE Quat_tpl(const Matrix33_tpl&m) - { - assert(m.IsOrthonormalRH(0.1f)); - F s, p, tr = m.m00 + m.m11 + m.m22; - w = 1, v.x = 0, v.y = 0, v.z = 0; - if (tr > 0) - { - s = sqrt_tpl(tr + 1.0f), p = 0.5f / s, w = s * 0.5f, v.x = (m.m21 - m.m12) * p, v.y = (m.m02 - m.m20) * p, v.z = (m.m10 - m.m01) * p; - } - else if ((m.m00 >= m.m11) && (m.m00 >= m.m22)) - { - s = sqrt_tpl(m.m00 - m.m11 - m.m22 + 1.0f), p = 0.5f / s, w = (m.m21 - m.m12) * p, v.x = s * 0.5f, v.y = (m.m10 + m.m01) * p, v.z = (m.m20 + m.m02) * p; - } - else if ((m.m11 >= m.m00) && (m.m11 >= m.m22)) - { - s = sqrt_tpl(m.m11 - m.m22 - m.m00 + 1.0f), p = 0.5f / s, w = (m.m02 - m.m20) * p, v.x = (m.m01 + m.m10) * p, v.y = s * 0.5f, v.z = (m.m21 + m.m12) * p; - } - else if ((m.m22 >= m.m00) && (m.m22 >= m.m11)) - { - s = sqrt_tpl(m.m22 - m.m00 - m.m11 + 1.0f), p = 0.5f / s, w = (m.m10 - m.m01) * p, v.x = (m.m02 + m.m20) * p, v.y = (m.m12 + m.m21) * p, v.z = s * 0.5f; - } - } - //CONSTRUCTOR for different types. It converts a Matrix33 into a Quat and converts between double/float. - //Needs to be 'explicit' because we loose fp-precision the conversion process - //Quat(m33r); - //Quatr(m33); - template - explicit ILINE Quat_tpl(const Matrix33_tpl&m) - { - assert(m.IsOrthonormalRH(0.1f)); - F1 s, p, tr = m.m00 + m.m11 + m.m22; - w = 1, v.x = 0, v.y = 0, v.z = 0; - if (tr > 0) - { - s = sqrt_tpl(tr + 1.0f), p = 0.5f / s, w = F(s * 0.5), v.x = F((m.m21 - m.m12) * p), v.y = F((m.m02 - m.m20) * p), v.z = F((m.m10 - m.m01) * p); - } - else if ((m.m00 >= m.m11) && (m.m00 >= m.m22)) - { - s = sqrt_tpl(m.m00 - m.m11 - m.m22 + 1.0f), p = 0.5f / s, w = F((m.m21 - m.m12) * p), v.x = F(s * 0.5), v.y = F((m.m10 + m.m01) * p), v.z = F((m.m20 + m.m02) * p); - } - else if ((m.m11 >= m.m00) && (m.m11 >= m.m22)) - { - s = sqrt_tpl(m.m11 - m.m22 - m.m00 + 1.0f), p = 0.5f / s, w = F((m.m02 - m.m20) * p), v.x = F((m.m01 + m.m10) * p), v.y = F(s * 0.5), v.z = F((m.m21 + m.m12) * p); - } - else if ((m.m22 >= m.m00) && (m.m22 >= m.m11)) - { - s = sqrt_tpl(m.m22 - m.m00 - m.m11 + 1.0f), p = 0.5f / s, w = F((m.m10 - m.m01) * p), v.x = F((m.m02 + m.m20) * p), v.y = F((m.m12 + m.m21) * p), v.z = F(s * 0.5); - } - } - - //CONSTRUCTOR for different types. It converts a Matrix34 into a Quat. - //Needs to be 'explicit' because we loose fp-precision in the conversion process - //Quat(m34); - explicit ILINE Quat_tpl(const Matrix34_tpl&m) - { - *this = Quat_tpl(Matrix33_tpl(m)); - } - //CONSTRUCTOR for different types. It converts a Matrix34 into a Quat and converts between double/float. - //Needs to be 'explicit' because we loose fp-precision the conversion process - //Quat(m34r); - //Quatr(m34); - template - explicit ILINE Quat_tpl(const Matrix34_tpl&m) - { - *this = Quat_tpl(Matrix33_tpl(m)); - } - - - - - - /*! - * invert quaternion. - * - * Example 1: - * Quat q=Quat::CreateRotationXYZ(Ang3(1,2,3)); - * Quat result = !q; - * Quat result = GetInverted(q); - * q.Invert(); - */ - ILINE Quat_tpl operator ! () const { return Quat_tpl(w, -v); } - ILINE void Invert(void) { *this = !*this; } - ILINE Quat_tpl GetInverted() const { return !(*this); } - //flip quaternion. don't confuse this with quaternion-inversion. - ILINE Quat_tpl operator - () const { return Quat_tpl(-w, -v); }; - //multiplication by a scalar - void operator *= (F op) { w *= op; v *= op; } - - // Exact compare of 2 quats. - ILINE bool operator==(const Quat_tpl& q) const { return (v == q.v) && (w == q.w); } - ILINE bool operator!=(const Quat_tpl& q) const { return !(*this == q); } - - - - - //A quaternion is a compressed matrix. Thus there is no problem extracting the rows & columns. - ILINE Vec3_tpl GetColumn(uint32 i) - { - if (i == 0) - { - return GetColumn0(); - } - if (i == 1) - { - return GetColumn1(); - } - if (i == 2) - { - return GetColumn2(); - } - assert(0); //bad index - return Vec3(ZERO); - } - - ILINE Vec3_tpl GetColumn0() const {return Vec3_tpl(2 * (v.x * v.x + w * w) - 1, 2 * (v.y * v.x + v.z * w), 2 * (v.z * v.x - v.y * w)); } - ILINE Vec3_tpl GetColumn1() const {return Vec3_tpl(2 * (v.x * v.y - v.z * w), 2 * (v.y * v.y + w * w) - 1, 2 * (v.z * v.y + v.x * w)); } - ILINE Vec3_tpl GetColumn2() const {return Vec3_tpl(2 * (v.x * v.z + v.y * w), 2 * (v.y * v.z - v.x * w), 2 * (v.z * v.z + w * w) - 1); } - ILINE Vec3_tpl GetRow0() const {return Vec3_tpl(2 * (v.x * v.x + w * w) - 1, 2 * (v.x * v.y - v.z * w), 2 * (v.x * v.z + v.y * w)); } - ILINE Vec3_tpl GetRow1() const {return Vec3_tpl(2 * (v.y * v.x + v.z * w), 2 * (v.y * v.y + w * w) - 1, 2 * (v.y * v.z - v.x * w)); } - ILINE Vec3_tpl GetRow2() const {return Vec3_tpl(2 * (v.z * v.x - v.y * w), 2 * (v.z * v.y + v.x * w), 2 * (v.z * v.z + w * w) - 1); } - - // These are just copy & pasted components of the GetColumn1() above. - ILINE F GetFwdX() const { return (2 * (v.x * v.y - v.z * w)); } - ILINE F GetFwdY() const { return (2 * (v.y * v.y + w * w) - 1); } - ILINE F GetFwdZ() const { return (2 * (v.z * v.y + v.x * w)); } - ILINE F GetRotZ() const { return atan2_tpl(-GetFwdX(), GetFwdY()); } - - - - /*! - * set identity quaternion - * - * Example: - * Quat q=Quat::CreateIdentity(); - * or - * q.SetIdentity(); - * or - * Quat p=Quat(IDENTITY); - */ - ILINE void SetIdentity(void) - { - w = 1; - v.x = 0; - v.y = 0; - v.z = 0; - } - ILINE static Quat_tpl CreateIdentity(void) - { - return Quat_tpl(1, 0, 0, 0); - } - - - - - // Description: - // Check if identity quaternion. - ILINE bool IsIdentity() const - { - return w == 1 && v.x == 0 && v.y == 0 && v.z == 0; - } - - ILINE bool IsUnit(F e = VEC_EPSILON) const - { - return fabs_tpl(1 - (w * w + v.x * v.x + v.y * v.y + v.z * v.z)) < e; - } - - ILINE bool IsValid([[maybe_unused]] F e = VEC_EPSILON) const - { - if (!v.IsValid()) - { - return false; - } - if (!NumberValid(w)) - { - return false; - } - //if (!IsUnit(e)) return false; - return true; - } - - - - ILINE void SetRotationAA(F rad, const Vec3_tpl& axis) - { - F s, c; - sincos_tpl(rad * (F)0.5, &s, &c); - SetRotationAA(c, s, axis); - } - ILINE static Quat_tpl CreateRotationAA(F rad, const Vec3_tpl& axis) - { - Quat_tpl q; - q.SetRotationAA(rad, axis); - return q; - } - - ILINE void SetRotationAA(F cosha, F sinha, const Vec3_tpl& axis) - { - assert(axis.IsUnit(0.001f)); - w = cosha; - v = axis * sinha; - } - ILINE static Quat_tpl CreateRotationAA(F cosha, F sinha, const Vec3_tpl& axis) - { - Quat_tpl q; - q.SetRotationAA(cosha, sinha, axis); - return q; - } - - - - - /*! - * Create rotation-quaternion that around the fixed coordinate axes. - * - * Example: - * Quat q=Quat::CreateRotationXYZ( Ang3(1,2,3) ); - * or - * q.SetRotationXYZ( Ang3(1,2,3) ); - */ - ILINE void SetRotationXYZ(const Ang3_tpl& a) - { - assert(a.IsValid()); - F sx, cx; - sincos_tpl(F(a.x * F(0.5)), &sx, &cx); - F sy, cy; - sincos_tpl(F(a.y * F(0.5)), &sy, &cy); - F sz, cz; - sincos_tpl(F(a.z * F(0.5)), &sz, &cz); - w = cx * cy * cz + sx * sy * sz; - v.x = cz * cy * sx - sz * sy * cx; - v.y = cz * sy * cx + sz * cy * sx; - v.z = sz * cy * cx - cz * sy * sx; - } - ILINE static Quat_tpl CreateRotationXYZ(const Ang3_tpl& a) - { - assert(a.IsValid()); - Quat_tpl q; - q.SetRotationXYZ(a); - return q; - } - - /*! - * Create rotation-quaternion that about the x-axis. - * - * Example: - * Quat q=Quat::CreateRotationX( radiant ); - * or - * q.SetRotationX( Ang3(1,2,3) ); - */ - ILINE void SetRotationX(f32 r) - { - F s, c; - sincos_tpl(F(r * F(0.5)), &s, &c); - w = c; - v.x = s; - v.y = 0; - v.z = 0; - } - ILINE static Quat_tpl CreateRotationX(f32 r) - { - Quat_tpl q; - q.SetRotationX(r); - return q; - } - - - /*! - * Create rotation-quaternion that about the y-axis. - * - * Example: - * Quat q=Quat::CreateRotationY( radiant ); - * or - * q.SetRotationY( radiant ); - */ - ILINE void SetRotationY(f32 r) - { - F s, c; - sincos_tpl(F(r * F(0.5)), &s, &c); - w = c; - v.x = 0; - v.y = s; - v.z = 0; - } - ILINE static Quat_tpl CreateRotationY(f32 r) - { - Quat_tpl q; - q.SetRotationY(r); - return q; - } - - - /*! - * Create rotation-quaternion that about the z-axis. - * - * Example: - * Quat q=Quat::CreateRotationZ( radiant ); - * or - * q.SetRotationZ( radiant ); - */ - ILINE void SetRotationZ(f32 r) - { - F s, c; - sincos_tpl(F(r * F(0.5)), &s, &c); - w = c; - v.x = 0; - v.y = 0; - v.z = s; - } - ILINE static Quat_tpl CreateRotationZ(f32 r) - { - Quat_tpl q; - q.SetRotationZ(r); - return q; - } - - - - /*! - * - * Create rotation-quaternion that rotates from one vector to another. - * Both vectors are assumed to be normalized. - * - * Example: - * Quat q=Quat::CreateRotationV0V1( v0,v1 ); - * q.SetRotationV0V1( v0,v1 ); - */ - ILINE void SetRotationV0V1(const Vec3_tpl& v0, const Vec3_tpl& v1) - { - assert(v0.IsUnit(0.01f)); - assert(v1.IsUnit(0.01f)); - F dot = v0.x * v1.x + v0.y * v1.y + v0.z * v1.z + F(1.0); - if (dot > F(0.0001)) - { - F vx = v0.y * v1.z - v0.z * v1.y; - F vy = v0.z * v1.x - v0.x * v1.z; - F vz = v0.x * v1.y - v0.y * v1.x; - F d = isqrt_tpl(dot * dot + vx * vx + vy * vy + vz * vz); - w = F(dot * d); - v.x = F(vx * d); - v.y = F(vy * d); - v.z = F(vz * d); - return; - } - w = 0; - v = v0.GetOrthogonal().GetNormalized(); - } - ILINE static Quat_tpl CreateRotationV0V1(const Vec3_tpl& v0, const Vec3_tpl& v1) { Quat_tpl q; q.SetRotationV0V1(v0, v1); return q; } - - - - - - - /*! - * - * \param vdir normalized view direction. - * \param roll radiant to rotate about Y-axis. - * - * Given a view-direction and a radiant to rotate about Y-axis, this function builds a 3x3 look-at quaternion - * using only simple vector arithmetic. This function is always using the implicit up-vector Vec3(0,0,1). - * The view-direction is always stored in column(1). - * IMPORTANT: The view-vector is assumed to be normalized, because all trig-values for the orientation are being - * extracted directly out of the vector. This function must NOT be called with a view-direction - * that is close to Vec3(0,0,1) or Vec3(0,0,-1). If one of these rules is broken, the function returns a quaternion - * with an undefined rotation about the Z-axis. - * - * Rotation order for the look-at-quaternion is Z-X-Y. (Zaxis=YAW / Xaxis=PITCH / Yaxis=ROLL) - * - * COORDINATE-SYSTEM - * - * z-axis - * ^ - * | - * | y-axis - * | / - * | / - * |/ - * +---------------> x-axis - * - * Example: - * Quat LookAtQuat=Quat::CreateRotationVDir( Vec3(0,1,0) ); - * or - * Quat LookAtQuat=Quat::CreateRotationVDir( Vec3(0,1,0), 0.333f ); - */ - ILINE void SetRotationVDir(const Vec3_tpl& vdir) - { - assert(vdir.IsUnit(0.01f)); - //set default initialization for up-vector - w = F(0.70710676908493042); - v.x = F(vdir.z * 0.70710676908493042); - v.y = F(0.0); - v.z = F(0.0); - F l = sqrt_tpl(vdir.x * vdir.x + vdir.y * vdir.y); - if (l > F(0.00001)) - { - //calculate LookAt quaternion - Vec3_tpl hv = Vec3_tpl (vdir.x / l, vdir.y / l + 1.0f, l + 1.0f); - F r = sqrt_tpl(hv.x * hv.x + hv.y * hv.y); - F s = sqrt_tpl(hv.z * hv.z + vdir.z * vdir.z); - //generate the half-angle sine&cosine - F hacos0 = 0.0; - F hasin0 = -1.0; - if (r > F(0.00001)) - { - hacos0 = hv.y / r; - hasin0 = -hv.x / r; - } //yaw - F hacos1 = hv.z / s; - F hasin1 = vdir.z / s; //pitch - w = F(hacos0 * hacos1); - v.x = F(hacos0 * hasin1); - v.y = F(hasin0 * hasin1); - v.z = F(hasin0 * hacos1); - } - } - ILINE static Quat_tpl CreateRotationVDir(const Vec3_tpl& vdir) { Quat_tpl q; q.SetRotationVDir(vdir); return q; } - - - ILINE void SetRotationVDir(const Vec3_tpl& vdir, F r) - { - SetRotationVDir(vdir); - F sy, cy; - sincos_tpl(r * (F)0.5, &sy, &cy); - F vx = v.x, vy = v.y; - v.x = F(vx * cy - v.z * sy); - v.y = F(w * sy + vy * cy); - v.z = F(v.z * cy + vx * sy); - w = F(w * cy - vy * sy); - } - ILINE static Quat_tpl CreateRotationVDir(const Vec3_tpl& vdir, F roll) { Quat_tpl q; q.SetRotationVDir(vdir, roll); return q; } - - - - - /*! - * normalize quaternion. - * - * Example 1: - * Quat q; q.Normalize(); - * - * Example 2: - * Quat q=Quat(1,2,3,4); - * Quat qn=q.GetNormalized(); - */ - ILINE void Normalize(void) - { - F d = isqrt_tpl(w * w + v.x * v.x + v.y * v.y + v.z * v.z); - w *= d; - v.x *= d; - v.y *= d; - v.z *= d; - } - ILINE Quat_tpl GetNormalized() const - { - Quat_tpl t = *this; - t.Normalize(); - return t; - } - - - ILINE void NormalizeSafe(void) - { - F d = w * w + v.x * v.x + v.y * v.y + v.z * v.z; - if (d > 1e-8f) - { - d = isqrt_tpl(d); - w *= d; - v.x *= d; - v.y *= d; - v.z *= d; - } - else - { - SetIdentity(); - } - } - ILINE Quat_tpl GetNormalizedSafe() const - { - Quat_tpl t = *this; - t.NormalizeSafe(); - return t; - } - - - ILINE void NormalizeFast(void) - { - assert(this->IsValid()); - F fInvLen = isqrt_fast_tpl(v.x * v.x + v.y * v.y + v.z * v.z + w * w); - v.x *= fInvLen; - v.y *= fInvLen; - v.z *= fInvLen; - w *= fInvLen; - } - ILINE Quat_tpl GetNormalizedFast() const - { - Quat_tpl t = *this; - t.NormalizeFast(); - return t; - } - - - /*! - * get length of quaternion. - * - * Example 1: - * f32 l=q.GetLength(); - */ - ILINE F GetLength() const - { - return sqrt_tpl(w * w + v.x * v.x + v.y * v.y + v.z * v.z); - } - - ILINE static bool IsEquivalent(const Quat_tpl& q1, const Quat_tpl& q2, F qe = RAD_EPSILON) - { - Quat_tpl q1r = q1; - Quat_tpl q2r = q2; - f64 rad = acos(min(1.0, fabs_tpl(q1r.v.x * q2r.v.x + q1r.v.y * q2r.v.y + q1r.v.z * q2r.v.z + q1r.w * q2r.w))); - bool qdif = rad <= qe; - return qdif; - } - - - // Exponent of Quaternion. - ILINE static Quat_tpl exp(const Vec3_tpl& v) - { - F lensqr = v.len2(); - if (lensqr > F(0)) - { - F len = sqrt_tpl(lensqr); - F s, c; - sincos_tpl(len, &s, &c); - s /= len; - return Quat_tpl(c, v.x * s, v.y * s, v.z * s); - } - return Quat_tpl (IDENTITY); - } - - // logarithm of a quaternion, imaginary part (the real part of the logarithm is always 0) - ILINE static Vec3_tpl log (const Quat_tpl& q) - { - assert(q.IsValid()); - F lensqr = q.v.len2(); - if (lensqr > 0.0f) - { - F len = sqrt_tpl(lensqr); - F angle = atan2_tpl(len, q.w) / len; - return q.v * angle; - } - // logarithm of a quaternion, imaginary part (the real part of the logarithm is always 0) - return Vec3_tpl(0, 0, 0); - } - - - ////////////////////////////////////////////////////////////////////////// - //! Logarithm of Quaternion difference. - ILINE static Quat_tpl LnDif(const Quat_tpl& q1, const Quat_tpl& q2) - { - return Quat_tpl(0, log(q2 / q1)); - } - - - - - /*! - * linear-interpolation between quaternions (lerp) - * - * Example: - * CQuaternion result,p,q; - * result=qlerp( p, q, 0.5f ); - */ - ILINE void SetNlerp(const Quat_tpl& p, const Quat_tpl& tq, F t) - { - Quat_tpl q = tq; - assert(p.IsValid()); - assert(q.IsValid()); - if ((p | q) < 0) - { - q = -q; - } - v.x = p.v.x * (1.0f - t) + q.v.x * t; - v.y = p.v.y * (1.0f - t) + q.v.y * t; - v.z = p.v.z * (1.0f - t) + q.v.z * t; - w = p.w * (1.0f - t) + q.w * t; - Normalize(); - } - - ILINE static Quat_tpl CreateNlerp(const Quat_tpl& p, const Quat_tpl& tq, F t) - { - Quat_tpl d; - d.SetNlerp(p, tq, t); - return d; - } - - - /*! - * linear-interpolation between quaternions (nlerp) - * in this case we convert the t-value into a 1d cubic spline to get closer to Slerp - * - * Example: - * Quat result,p,q; - * result.SetNlerpCubic( p, q, 0.5f ); - */ - ILINE void SetNlerpCubic(const Quat_tpl& p, const Quat_tpl& tq, F t) - { - Quat_tpl q = tq; - assert((fabs_tpl(1 - (p | p))) < 0.001); //check if unit-quaternion - assert((fabs_tpl(1 - (q | q))) < 0.001); //check if unit-quaternion - F cosine = (p | q); - if (cosine < 0) - { - q = -q; - } - F k = (1 - fabs_tpl(cosine)) * F(0.4669269); - F s = 2 * k * t * t * t - 3 * k * t * t + (1 + k) * t; - v.x = p.v.x * (1.0f - s) + q.v.x * s; - v.y = p.v.y * (1.0f - s) + q.v.y * s; - v.z = p.v.z * (1.0f - s) + q.v.z * s; - w = p.w * (1.0f - s) + q.w * s; - Normalize(); - } - ILINE static Quat_tpl CreateNlerpCubic(const Quat_tpl& p, const Quat_tpl& tq, F t) - { - Quat_tpl d; - d.SetNlerpCubic(p, tq, t); - return d; - } - - - /*! - * spherical-interpolation between quaternions (geometrical slerp) - * - * Example: - * Quat result,p,q; - * result.SetSlerp( p, q, 0.5f ); - */ - ILINE void SetSlerp(const Quat_tpl& tp, const Quat_tpl& tq, F t) - { - assert(tp.IsValid()); - assert(tq.IsUnit()); - Quat_tpl p = tp, q = tq; - Quat_tpl q2; - - F cosine = (p | q); - if (cosine < 0.0f) - { - cosine = -cosine; - q = -q; - } //take shortest arc - if (cosine > 0.9999f) - { - SetNlerp(p, q, t); - return; - } - // from now on, a division by 0 is not possible any more - q2.w = q.w - p.w * cosine; - q2.v.x = q.v.x - p.v.x * cosine; - q2.v.y = q.v.y - p.v.y * cosine; - q2.v.z = q.v.z - p.v.z * cosine; - F sine = sqrt(q2 | q2); - - // Actually you can divide by 0 right here. - assert(sine != 0.0000f); - - F s, c; - sincos_tpl(atan2_tpl(sine, cosine) * t, &s, &c); - w = F(p.w * c + q2.w * s / sine); - v.x = F(p.v.x * c + q2.v.x * s / sine); - v.y = F(p.v.y * c + q2.v.y * s / sine); - v.z = F(p.v.z * c + q2.v.z * s / sine); - } - - ILINE static Quat_tpl CreateSlerp(const Quat_tpl& p, const Quat_tpl& tq, F t) - { - Quat_tpl d; - d.SetSlerp(p, tq, t); - return d; - } - - /*! - * spherical-interpolation between quaternions (algebraic slerp_a) - * I have included this function just for the sake of completeness, because - * its the only useful application to check if exp & log really work. - * Both slerp-functions are returning the same result. - * - * Example: - * Quat result,p,q; - * result.SetExpSlerp( p,q,0.3345f ); - */ - ILINE void SetExpSlerp(const Quat_tpl& p, const Quat_tpl& tq, F t) - { - assert((fabs_tpl(1 - (p | p))) < 0.001); //check if unit-quaternion - assert((fabs_tpl(1 - (tq | tq))) < 0.001); //check if unit-quaternion - Quat_tpl q = tq; - if ((p | q) < 0) - { - q = -q; - } - *this = p * exp(log(!p * q) * t); //algebraic slerp (1) - //...and some more exp-slerp-functions producing all the same result - //*this = exp( log (p* !q) * (1-t)) * q; //algebraic slerp (2) - //*this = exp( log (q* !p) * t) * p; //algebraic slerp (3) - //*this = q * exp( log (!q*p) * (1-t)); //algebraic slerp (4) - } - ILINE static Quat_tpl CreateExpSlerp(const Quat_tpl& p, const Quat_tpl& q, F t) - { - Quat_tpl d; - d.SetExpSlerp(p, q, t); - return d; - } - - - //! squad(p,a,b,q,t) = slerp( slerp(p,q,t),slerp(a,b,t), 2(1-t)t). - ILINE void SetSquad(const Quat_tpl& p, const Quat_tpl& a, const Quat_tpl& b, const Quat_tpl& q, F t) - { - SetSlerp(CreateSlerp(p, q, t), CreateSlerp(a, b, t), 2.0f * (1.0f - t) * t); - } - - ILINE static Quat_tpl CreateSquad(const Quat_tpl& p, const Quat_tpl& a, const Quat_tpl& b, const Quat_tpl& q, F t) - { - Quat_tpl d; - d.SetSquad(p, a, b, q, t); - return d; - } - - - //useless, please delete - ILINE Quat_tpl GetScaled(F scale) const - { - return CreateNlerp(IDENTITY, *this, scale); - } - - - AUTO_STRUCT_INFO -}; - - -/////////////////////////////////////////////////////////////////////////////// -// Typedefs // -/////////////////////////////////////////////////////////////////////////////// - -#ifndef MAX_API_NUM -typedef Quat_tpl Quat; //always 32 bit -typedef Quat_tpl Quatd; //always 64 bit -typedef Quat_tpl Quatr; //variable float precision. depending on the target system it can be between 32, 64 or 80 bit -#endif - -typedef Quat_tpl CryQuat; -typedef Quat_tpl quaternionf; -typedef Quat_tpl quaternion; - -// alligned versions -#ifndef MAX_API_NUM -typedef DEFINE_ALIGNED_DATA (Quat, QuatA, 16); // typedef __declspec(align(16)) Quat_tpl CryQuatA; -typedef DEFINE_ALIGNED_DATA (Quatd, QuatrA, 32); // typedef __declspec(align(16)) Quat_tpl quaternionfA; -#endif - - - -/*! -* -* The "inner product" or "dot product" operation. -* -* calculate the "inner product" between two Quaternion. -* If both Quaternion are unit-quaternions, the result is the cosine: p*q=cos(angle) -* -* Example: -* Quat p(1,0,0,0),q(1,0,0,0); -* f32 cosine = ( p | q ); -* -*/ -template -ILINE F1 operator | (const Quat_tpl& q, const Quat_tpl& p) -{ - assert(q.v.IsValid()); - assert(p.v.IsValid()); - return (q.v.x * p.v.x + q.v.y * p.v.y + q.v.z * p.v.z + q.w * p.w); -} - - -/*! -* -* Implements the multiplication operator: Qua=QuatA*QuatB -* -* AxB = operation B followed by operation A. -* A multiplication takes 16 muls and 12 adds. -* -* Example 1: -* Quat p(1,0,0,0),q(1,0,0,0); -* Quat result=p*q; -* -* Example 2: (self-multiplication) -* Quat p(1,0,0,0),q(1,0,0,0); -* Quat p*=q; -*/ -template -Quat_tpl ILINE operator * (const Quat_tpl& q, const Quat_tpl& p) -{ - assert(q.IsValid()); - assert(p.IsValid()); - return Quat_tpl - ( - q.w * p.w - (q.v.x * p.v.x + q.v.y * p.v.y + q.v.z * p.v.z), - q.v.y * p.v.z - q.v.z * p.v.y + q.w * p.v.x + q.v.x * p.w, - q.v.z * p.v.x - q.v.x * p.v.z + q.w * p.v.y + q.v.y * p.w, - q.v.x * p.v.y - q.v.y * p.v.x + q.w * p.v.z + q.v.z * p.w - ); -} -template -ILINE void operator *= (Quat_tpl& q, const Quat_tpl& p) -{ - assert(q.IsValid()); - assert(p.IsValid()); - F1 s0 = q.w; - q.w = q.w * p.w - (q.v | p.v); - q.v = p.v * s0 + q.v * p.w + (q.v % p.v); -} - -/*! -* Implements the multiplication operator: QuatT=Quat*Quatpos -* -* AxB = operation B followed by operation A. -* A multiplication takes 31 muls and 27 adds (=58 float operations). -* -* Example: -* Quat quat = Quat::CreateRotationX(1.94192f);; -* QuatT quatpos = QuatT::CreateRotationZ(3.14192f,Vec3(11,22,33)); -* QuatT qp = quat*quatpos; -*/ -template -ILINE QuatT_tpl operator * (const Quat_tpl& q, const QuatT_tpl& p) -{ - return QuatT_tpl(q * p.q, q * p.t); -} - - - -/*! -* division operator -* -* Example 1: -* Quat p(1,0,0,0),q(1,0,0,0); -* Quat result=p/q; -* -* Example 2: (self-division) -* Quat p(1,0,0,0),q(1,0,0,0); -* Quat p/=q; -*/ -template -ILINE Quat_tpl operator / (const Quat_tpl& q, const Quat_tpl& p) -{ - return (!p * q); -} -template -ILINE void operator /= (Quat_tpl& q, const Quat_tpl& p) -{ - q = (!p * q); -} - - -/*! -* addition operator -* -* Example: -* Quat p(1,0,0,0),q(1,0,0,0); -* Quat result=p+q; -* -* Example:(self-addition operator) -* Quat p(1,0,0,0),q(1,0,0,0); -* Quat p-=q; -*/ -template -ILINE Quat_tpl operator + (const Quat_tpl& q, const Quat_tpl& p) -{ - return Quat_tpl(q.w + p.w, q.v + p.v); -} -template -ILINE void operator += (Quat_tpl& q, const Quat_tpl& p) -{ - q.w += p.w; - q.v += p.v; -} - - - -/*! -* subtraction operator -* -* Example: -* Quat p(1,0,0,0),q(1,0,0,0); -* Quat result=p-q; -* -* Example: (self-subtraction operator) -* Quat p(1,0,0,0),q(1,0,0,0); -* Quat p-=q; -* -*/ -template -ILINE Quat_tpl operator - (const Quat_tpl& q, const Quat_tpl& p) -{ - return Quat_tpl(q.w - p.w, q.v - p.v); -} -template -ILINE void operator -= (Quat_tpl& q, const Quat_tpl& p) -{ - q.w -= p.w; - q.v -= p.v; -} - - -//! Scale quaternion free function. -template -ILINE Quat_tpl operator * (F t, const Quat_tpl& q) -{ - return Quat_tpl(t * q.w, t * q.v); -}; - - -template -ILINE Quat_tpl operator * (const Quat_tpl& q, F2 t) -{ - return Quat_tpl(q.w * t, q.v * t); -}; -template -ILINE Quat_tpl operator / (const Quat_tpl& q, F2 t) -{ - return Quat_tpl(q.w / t, q.v / t); -}; - - -/*! -* -* post-multiply of a quaternion and a Vec3 (3D rotations with quaternions) -* -* Example: -* Quat q(1,0,0,0); -* Vec3 v(33,44,55); -* Vec3 result = q*v; -*/ -template -ILINE Vec3_tpl operator * (const Quat_tpl& q, const Vec3_tpl& v) -{ - assert(v.IsValid()); - assert(q.IsValid()); - //muls=15 / adds=15 - Vec3_tpl out, r2; - r2.x = (q.v.y * v.z - q.v.z * v.y) + q.w * v.x; - r2.y = (q.v.z * v.x - q.v.x * v.z) + q.w * v.y; - r2.z = (q.v.x * v.y - q.v.y * v.x) + q.w * v.z; - out.x = (r2.z * q.v.y - r2.y * q.v.z); - out.x += out.x + v.x; - out.y = (r2.x * q.v.z - r2.z * q.v.x); - out.y += out.y + v.y; - out.z = (r2.y * q.v.x - r2.x * q.v.y); - out.z += out.z + v.z; - return out; -} - - -/*! -* pre-multiply of a quaternion and a Vec3 (3D rotations with quaternions) -* -* Example: -* Quat q(1,0,0,0); -* Vec3 v(33,44,55); -* Vec3 result = v*q; -*/ -template -ILINE Vec3_tpl operator * (const Vec3_tpl& v, const Quat_tpl& q) -{ - assert(v.IsValid()); - assert(q.IsValid()); - //muls=15 / adds=15 - Vec3_tpl out, r2; - r2.x = (q.v.z * v.y - q.v.y * v.z) + q.w * v.x; - r2.y = (q.v.x * v.z - q.v.z * v.x) + q.w * v.y; - r2.z = (q.v.y * v.x - q.v.x * v.y) + q.w * v.z; - out.x = (r2.y * q.v.z - r2.z * q.v.y); - out.x += out.x + v.x; - out.y = (r2.z * q.v.x - r2.x * q.v.z); - out.y += out.y + v.y; - out.z = (r2.x * q.v.y - r2.y * q.v.x); - out.z += out.z + v.z; - return out; -} - - - -template -ILINE Quat_tpl operator % (const Quat_tpl& q, const Quat_tpl& tp) -{ - Quat_tpl p = tp; - if ((p | q) < 0) - { - p = -p; - } - return Quat_tpl(q.w + p.w, q.v + p.v); -} -template -ILINE void operator %= (Quat_tpl& q, const Quat_tpl& tp) -{ - Quat_tpl p = tp; - if ((p | q) < 0) - { - p = -p; - } - q = Quat_tpl(q.w + p.w, q.v + p.v); -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//---------------------------------------------------------------------- -// Quaternion with translation vector -//---------------------------------------------------------------------- -template -struct QuatT_tpl -{ - Quat_tpl q; //this is the quaternion - Vec3_tpl t; //this is the translation vector and a scalar (for uniform scaling?) - - ILINE QuatT_tpl(){} - - //initialize with zeros - ILINE QuatT_tpl(type_zero) - { - q.w = 0, q.v.x = 0, q.v.y = 0, q.v.z = 0, t.x = 0, t.y = 0, t.z = 0; - } - ILINE QuatT_tpl(type_identity) - { - q.w = 1, q.v.x = 0, q.v.y = 0, q.v.z = 0, t.x = 0, t.y = 0, t.z = 0; - } - - ILINE QuatT_tpl(const Vec3_tpl& _t, const Quat_tpl& _q) { q = _q; t = _t; } - - //CONSTRUCTOR: implement the copy/casting/assignment constructor: - template - ILINE QuatT_tpl(const QuatT_tpl& qt) - : q(qt.q) - , t(qt.t) {} - - //convert unit DualQuat back to QuatT - ILINE QuatT_tpl(const DualQuat_tpl& qd) - { - //copy quaternion part - q = qd.nq; - //convert translation vector: - t = (qd.nq.w * qd.dq.v - qd.dq.w * qd.nq.v + qd.nq.v % qd.dq.v) * 2; //perfect for HLSL - } - - explicit ILINE QuatT_tpl(const QuatTS_tpl& qts) - : q(qts.q) - , t(qts.t) {} - - explicit ILINE QuatT_tpl(const Matrix34_tpl& m) - { - q = Quat_tpl(Matrix33(m)); - t = m.GetTranslation(); - } - - ILINE QuatT_tpl(const Quat_tpl& quat, const Vec3_tpl& trans) - { - q = quat; - t = trans; - } - - ILINE void SetIdentity() - { - q.w = 1; - q.v.x = 0; - q.v.y = 0; - q.v.z = 0; - t.x = 0; - t.y = 0; - t.z = 0; - } - - ILINE bool IsIdentity() const - { - return (q.IsIdentity() && t.IsZero()); - } - - /*! - * Convert three Euler angle to mat33 (rotation order:XYZ) - * The Euler angles are assumed to be in radians. - * The translation-vector is set to zero by default. - * - * Example 1: - * QuatT qp; - * qp.SetRotationXYZ( Ang3(0.5f,0.2f,0.9f), translation ); - * - * Example 2: - * QuatT qp=QuatT::CreateRotationXYZ( Ang3(0.5f,0.2f,0.9f), translation ); - */ - ILINE void SetRotationXYZ(const Ang3_tpl& rad, const Vec3_tpl& trans = Vec3(ZERO)) - { - assert(rad.IsValid()); - assert(trans.IsValid()); - q.SetRotationXYZ(rad); - t = trans; - } - ILINE static QuatT_tpl CreateRotationXYZ(const Ang3_tpl& rad, const Vec3_tpl& trans = Vec3(ZERO)) - { - assert(rad.IsValid()); - assert(trans.IsValid()); - QuatT_tpl qp; - qp.SetRotationXYZ(rad, trans); - return qp; - } - - - - ILINE void SetRotationAA(F cosha, F sinha, const Vec3_tpl axis, const Vec3_tpl& trans = Vec3(ZERO)) - { - q.SetRotationAA(cosha, sinha, axis); - t = trans; - } - ILINE static QuatT_tpl CreateRotationAA(F cosha, F sinha, const Vec3_tpl axis, const Vec3_tpl& trans = Vec3(ZERO)) - { - QuatT_tpl qt; - qt.SetRotationAA(cosha, sinha, axis, trans); - return qt; - } - - - ILINE void Invert() - { // in-place transposition - assert(q.IsValid()); - t = -t * q; - q = !q; - } - ILINE QuatT_tpl GetInverted() const - { - assert(q.IsValid()); - QuatT_tpl qpos; - qpos.q = !q; - qpos.t = -t * q; - return qpos; - } - - ILINE void SetTranslation(const Vec3_tpl& trans) { t = trans; } - - ILINE Vec3_tpl GetColumn0() const {return q.GetColumn0(); } - ILINE Vec3_tpl GetColumn1() const {return q.GetColumn1(); } - ILINE Vec3_tpl GetColumn2() const {return q.GetColumn2(); } - ILINE Vec3_tpl GetColumn3() const {return t; } - ILINE Vec3_tpl GetRow0() const { return q.GetRow0(); } - ILINE Vec3_tpl GetRow1() const { return q.GetRow1(); } - ILINE Vec3_tpl GetRow2() const { return q.GetRow2(); } - - ILINE static bool IsEquivalent(const QuatT_tpl& qt1, const QuatT_tpl& qt2, F qe = RAD_EPSILON, F ve = VEC_EPSILON) - { - real rad = acos(min(1.0f, fabs_tpl(qt1.q | qt2.q))); - bool qdif = rad <= qe; - bool vdif = fabs_tpl(qt1.t.x - qt2.t.x) <= ve && fabs_tpl(qt1.t.y - qt2.t.y) <= ve && fabs_tpl(qt1.t.z - qt2.t.z) <= ve; - return (qdif && vdif); - } - - ILINE bool IsValid() const - { - if (!t.IsValid()) - { - return false; - } - if (!q.IsValid()) - { - return false; - } - return true; - } - - /*! - * linear-interpolation between quaternions (lerp) - * - * Example: - * CQuaternion result,p,q; - * result=qlerp( p, q, 0.5f ); - */ - ILINE void SetNLerp(const QuatT_tpl& p, const QuatT_tpl& tq, F ti) - { - assert(p.q.IsValid()); - assert(tq.q.IsValid()); - Quat_tpl d = tq.q; - if ((p.q | d) < 0) - { - d = -d; - } - Vec3_tpl vDiff = d.v - p.q.v; - q.v = p.q.v + (vDiff * ti); - q.w = p.q.w + ((d.w - p.q.w) * ti); - q.Normalize(); - vDiff = tq.t - p.t; - t = p.t + (vDiff * ti); - } - ILINE static QuatT_tpl CreateNLerp(const QuatT_tpl& p, const QuatT_tpl& q, F t) - { - QuatT_tpl d; - d.SetNLerp(p, q, t); - return d; - } - - //NOTE: all vectors are stored in columns - ILINE void SetFromVectors(const Vec3& vx, const Vec3& vy, const Vec3& vz, const Vec3& pos) - { - Matrix34 m34; - m34.m00 = vx.x; - m34.m01 = vy.x; - m34.m02 = vz.x; - m34.m03 = pos.x; - m34.m10 = vx.y; - m34.m11 = vy.y; - m34.m12 = vz.y; - m34.m13 = pos.y; - m34.m20 = vx.z; - m34.m21 = vy.z; - m34.m22 = vz.z; - m34.m23 = pos.z; - *this = QuatT_tpl(m34); - } - ILINE static QuatT_tpl CreateFromVectors(const Vec3_tpl& vx, const Vec3_tpl& vy, const Vec3_tpl& vz, const Vec3_tpl& pos) - { - QuatT_tpl qt; - qt.SetFromVectors(vx, vy, vz, pos); - return qt; - } - - QuatT_tpl GetScaled(F scale) - { - return QuatT_tpl(t * scale, q.GetScaled(scale)); - } - - AUTO_STRUCT_INFO -}; - -typedef QuatT_tpl QuatT; //always 32 bit -typedef QuatT_tpl QuatTd;//always 64 bit -typedef QuatT_tpl QuatTr;//variable float precision. depending on the target system it can be between 32, 64 or bit - -// alligned versions -typedef DEFINE_ALIGNED_DATA (QuatT, QuatTA, 32); //wastest 4byte per quatT // typedef __declspec(align(16)) Quat_tpl QuatTA; -typedef DEFINE_ALIGNED_DATA (QuatTd, QuatTrA, 16); // typedef __declspec(align(16)) Quat_tpl QuatTrA; - - -/*! -* -* Implements the multiplication operator: QuatT=Quatpos*Quat -* -* AxB = operation B followed by operation A. -* A multiplication takes 16 muls and 12 adds (=28 float operations). -* -* Example: -* Quat quat = Quat::CreateRotationX(1.94192f);; -* QuatT quatpos = QuatT::CreateRotationZ(3.14192f,Vec3(11,22,33)); -* QuatT qp = quatpos*quat; -*/ -template -ILINE QuatT_tpl operator * (const QuatT_tpl& p, const Quat_tpl& q) -{ - assert(p.IsValid()); - assert(q.IsValid()); - return QuatT_tpl(p.q * q, p.t); -} - -/*! -* Implements the multiplication operator: QuatT=QuatposA*QuatposB -* -* AxB = operation B followed by operation A. -* A multiplication takes 31 muls and 30 adds (=61 float operations). -* -* Example: -* QuatT quatposA = QuatT::CreateRotationX(1.94192f,Vec3(77,55,44)); -* QuatT quatposB = QuatT::CreateRotationZ(3.14192f,Vec3(11,22,33)); -* QuatT qp = quatposA*quatposB; -*/ -template -ILINE QuatT_tpl operator * (const QuatT_tpl& q, const QuatT_tpl& p) -{ - assert(q.IsValid()); - assert(p.IsValid()); - return QuatT_tpl(q.q * p.q, q.q * p.t + q.t); -} - - - -/*! -* post-multiply of a QuatT and a Vec3 (3D rotations with quaternions) -* -* Example: -* Quat q(1,0,0,0); -* Vec3 v(33,44,55); -* Vec3 result = q*v; -*/ -template -Vec3_tpl operator * (const QuatT_tpl& q, const Vec3_tpl& v) -{ - assert(v.IsValid()); - assert(q.IsValid()); - //muls=15 / adds=15+3 - Vec3_tpl out, r2; - r2.x = (q.q.v.y * v.z - q.q.v.z * v.y) + q.q.w * v.x; - r2.y = (q.q.v.z * v.x - q.q.v.x * v.z) + q.q.w * v.y; - r2.z = (q.q.v.x * v.y - q.q.v.y * v.x) + q.q.w * v.z; - out.x = (r2.z * q.q.v.y - r2.y * q.q.v.z); - out.x += out.x + v.x + q.t.x; - out.y = (r2.x * q.q.v.z - r2.z * q.q.v.x); - out.y += out.y + v.y + q.t.y; - out.z = (r2.y * q.q.v.x - r2.x * q.q.v.y); - out.z += out.z + v.z + q.t.z; - return out; -} - - - - - - - - - - - - - - - - -//---------------------------------------------------------------------- -// Quaternion with translation vector and scale -// Similar to QuatT, but s is not ignored. -// Most functions then differ, so we don't inherit. -//---------------------------------------------------------------------- -template -struct QuatTS_tpl -{ - Quat_tpl q; - Vec3_tpl t; - F s; - - //constructors -#if defined(_DEBUG) - ILINE QuatTS_tpl() - { - if constexpr (sizeof(F) == 4) - { - uint32* p = alias_cast(&q.v.x); - p[0] = F32NAN; - p[1] = F32NAN; - p[2] = F32NAN; - p[3] = F32NAN; - p[4] = F32NAN; - p[5] = F32NAN; - p[6] = F32NAN; - p[7] = F32NAN; - } - if constexpr (sizeof(F) == 8) - { - uint64* p = alias_cast(&q.v.x); - p[0] = F64NAN; - p[1] = F64NAN; - p[2] = F64NAN; - p[3] = F64NAN; - p[4] = F64NAN; - p[5] = F64NAN; - p[6] = F64NAN; - p[7] = F64NAN; - } - } -#else - ILINE QuatTS_tpl(){} -#endif - - ILINE QuatTS_tpl(const Quat_tpl& quat, const Vec3_tpl& trans, F scale = 1) { q = quat; t = trans; s = scale; } - ILINE QuatTS_tpl(type_identity) { SetIdentity(); } - - //CONSTRUCTOR: implement the copy/casting/assignment constructor: - template - ILINE QuatTS_tpl(const QuatTS_tpl& qts) - : q(qts.q) - , t(qts.t) - , s(qts.s) {} - - ILINE QuatTS_tpl& operator = (const QuatT_tpl& qt) - { - q = qt.q; - t = qt.t; - s = 1.0f; - return *this; - } - ILINE QuatTS_tpl(const QuatT_tpl& qp) { q = qp.q; t = qp.t; s = 1.0f; } - - - ILINE void SetIdentity() - { - q.SetIdentity(); - t = Vec3(ZERO); - s = 1; - } - - explicit ILINE QuatTS_tpl(const Matrix34_tpl& m) - { - t = m.GetTranslation(); - - // The determinant of a matrix is the volume spanned by its base vectors. - // We need an approximate length scale, so we calculate the cube root of the determinant. - s = pow(m.Determinant(), F(1.0 / 3.0)); - - // Orthonormalize using X and Z as anchors. - const Vec3_tpl& r0 = m.GetRow(0); - const Vec3_tpl& r2 = m.GetRow(2); - - const Vec3_tpl v0 = r0.GetNormalized(); - const Vec3_tpl v1 = (r2 % r0).GetNormalized(); - const Vec3_tpl v2 = (v0 % v1); - - Matrix33_tpl m3; - m3.SetRow(0, v0); - m3.SetRow(1, v1); - m3.SetRow(2, v2); - - q = Quat_tpl(m3); - } - - void Invert() - { - s = 1 / s; - q = !q; - t = q * t * -s; - } - QuatTS_tpl GetInverted() const - { - QuatTS_tpl inv; - inv.s = 1 / s; - inv.q = !q; - inv.t = inv.q * t * -inv.s; - return inv; - } - - - /*! - * linear-interpolation between quaternions (nlerp) - * - * Example: - * CQuaternion result,p,q; - * result=qlerp( p, q, 0.5f ); - */ - ILINE void SetNLerp(const QuatTS_tpl& p, const QuatTS_tpl& tq, F ti) - { - assert(p.q.IsValid()); - assert(tq.q.IsValid()); - Quat_tpl d = tq.q; - if ((p.q | d) < 0) - { - d = -d; - } - Vec3_tpl vDiff = d.v - p.q.v; - q.v = p.q.v + (vDiff * ti); - q.w = p.q.w + ((d.w - p.q.w) * ti); - q.Normalize(); - - vDiff = tq.t - p.t; - t = p.t + (vDiff * ti); - - s = p.s + ((tq.s - p.s) * ti); - } - - ILINE static QuatTS_tpl CreateNLerp(const QuatTS_tpl& p, const QuatTS_tpl& q, F t) - { - QuatTS_tpl d; - d.SetNLerp(p, q, t); - return d; - } - - - - ILINE static bool IsEquivalent(const QuatTS_tpl& qts1, const QuatTS_tpl& qts2, F qe = RAD_EPSILON, F ve = VEC_EPSILON) - { - f64 rad = acos(min(1.0f, fabs_tpl(qts1.q | qts2.q))); - bool qdif = rad <= qe; - bool vdif = fabs_tpl(qts1.t.x - qts2.t.x) <= ve && fabs_tpl(qts1.t.y - qts2.t.y) <= ve && fabs_tpl(qts1.t.z - qts2.t.z) <= ve; - bool sdif = fabs_tpl(qts1.s - qts2.s) <= ve; - return (qdif && vdif && sdif); - } - - - bool IsValid(F e = VEC_EPSILON) const - { - if (!q.v.IsValid()) - { - return false; - } - if (!NumberValid(q.w)) - { - return false; - } - if (!q.IsUnit(e)) - { - return false; - } - if (!t.IsValid()) - { - return false; - } - if (!NumberValid(s)) - { - return false; - } - return true; - } - - ILINE Vec3_tpl GetColumn0() const {return q.GetColumn0(); } - ILINE Vec3_tpl GetColumn1() const {return q.GetColumn1(); } - ILINE Vec3_tpl GetColumn2() const {return q.GetColumn2(); } - ILINE Vec3_tpl GetColumn3() const {return t; } - ILINE Vec3_tpl GetRow0() const { return q.GetRow0(); } - ILINE Vec3_tpl GetRow1() const { return q.GetRow1(); } - ILINE Vec3_tpl GetRow2() const { return q.GetRow2(); } - - AUTO_STRUCT_INFO -}; - -typedef QuatTS_tpl QuatTS; //always 64 bit -typedef QuatTS_tpl QuatTSd;//always 64 bit -typedef QuatTS_tpl QuatTSr;//variable float precision. depending on the target system it can be between 32, 64 or 80 bit - -// alligned versions -typedef DEFINE_ALIGNED_DATA (QuatTS, QuatTSA, 16); // typedef __declspec(align(16)) Quat_tpl QuatTSA; -typedef DEFINE_ALIGNED_DATA (QuatTSd, QuatTSrA, 64); // typedef __declspec(align(16)) QuatTS_tpl QuatTSrA; - -template -ILINE QuatTS_tpl operator * (const QuatTS_tpl& a, const Quat_tpl& b) -{ - return QuatTS_tpl(a.q * b, a.t, a.s); -} - - -template -ILINE QuatTS_tpl operator * (const QuatTS_tpl& a, const QuatT_tpl& b) -{ - return QuatTS_tpl(a.q * b.q, a.q * (b.t * a.s) + a.t, a.s); -} -template -ILINE QuatTS_tpl operator * (const QuatT_tpl& a, const QuatTS_tpl& b) -{ - return QuatTS_tpl(a.q * b.q, a.q * b.t + a.t, b.s); -} -template -ILINE QuatTS_tpl operator * (const Quat_tpl& a, const QuatTS_tpl& b) -{ - return QuatTS_tpl(a * b.q, a * b.t, b.s); -} - -/*! -* Implements the multiplication operator: QuatTS=QuatTS*QuatTS -*/ -template -ILINE QuatTS_tpl operator * (const QuatTS_tpl& a, const QuatTS_tpl& b) -{ - assert(a.IsValid()); - assert(b.IsValid()); - return QuatTS_tpl(a.q * b.q, a.q * (b.t * a.s) + a.t, a.s * b.s); -} - -/*! -* post-multiply of a QuatT and a Vec3 (3D rotations with quaternions) -*/ -template -ILINE Vec3_tpl operator * (const QuatTS_tpl& q, const Vec3_tpl& v) -{ - assert(q.IsValid()); - assert(v.IsValid()); - return q.q * v * q.s + q.t; -} - - -//---------------------------------------------------------------------- -// Quaternion with translation vector and non-uniform scale -//---------------------------------------------------------------------- -template -struct QuatTNS_tpl -{ - Quat_tpl q; - Vec3_tpl t; - Vec3_tpl s; - - //constructors -#if defined(_DEBUG) - ILINE QuatTNS_tpl() - { - if constexpr (sizeof(F) == 4) - { - uint32* p = alias_cast(&q.v.x); - p[0] = F32NAN; - p[1] = F32NAN; - p[2] = F32NAN; - p[3] = F32NAN; - p[4] = F32NAN; - p[5] = F32NAN; - p[6] = F32NAN; - p[7] = F32NAN; - p[8] = F32NAN; - p[9] = F32NAN; - } - if constexpr (sizeof(F) == 8) - { - uint64* p = alias_cast(&q.v.x); - p[0] = F64NAN; - p[1] = F64NAN; - p[2] = F64NAN; - p[3] = F64NAN; - p[4] = F64NAN; - p[5] = F64NAN; - p[6] = F64NAN; - p[7] = F64NAN; - p[8] = F64NAN; - p[9] = F64NAN; - } - } -#else - ILINE QuatTNS_tpl() {}; -#endif - - ILINE QuatTNS_tpl(const Quat_tpl& quat, const Vec3_tpl& trans, const Vec3_tpl& scale = Vec3_tpl(1)) { q = quat; t = trans; s = scale; } - ILINE QuatTNS_tpl(type_identity) { SetIdentity(); } - - //CONSTRUCTOR: implement the copy/casting/assignment constructor: - template - ILINE QuatTNS_tpl(const QuatTS_tpl& qts) - : q(qts.q) - , t(qts.t) - , s(qts.s) - { - } - - ILINE QuatTNS_tpl& operator = (const QuatT_tpl& qt) - { - q = qt.q; - t = qt.t; - s = Vec3_tpl(1); - return *this; - } - ILINE QuatTNS_tpl(const QuatT_tpl& qp) { q = qp.q; t = qp.t; s = Vec3_tpl(1); } - - - ILINE void SetIdentity() - { - q.SetIdentity(); - t = Vec3_tpl(ZERO); - s = Vec3_tpl(1); - } - - explicit ILINE QuatTNS_tpl(const Matrix34_tpl& m) - { - t = m.GetTranslation(); - - // Lengths of base vectors equates to scaling in matrix - s.x = m.GetColumn0().GetLength(); - s.y = m.GetColumn1().GetLength(); - s.z = m.GetColumn2().GetLength(); - - // Orthonormalize using X and Z as anchors. - const Vec3_tpl& r0 = m.GetRow(0); - const Vec3_tpl& r2 = m.GetRow(2); - - const Vec3_tpl v0 = r0.GetNormalized(); - const Vec3_tpl v1 = (r2 % r0).GetNormalized(); - const Vec3_tpl v2 = (v0 % v1); - - Matrix33_tpl m3; - m3.SetRow(0, v0); - m3.SetRow(1, v1); - m3.SetRow(2, v2); - - q = Quat_tpl(m3); - } - - void Invert() - { - s = Vec3_tpl(1) / s; - q = !q; - t = q * t * -s; - } - QuatTNS_tpl GetInverted() const - { - QuatTNS_tpl inv; - inv.s = Vec3_tpl(1) / s; - inv.q = !q; - inv.t = inv.q * t * -inv.s; - return inv; - } - - - /*! - * linear-interpolation between quaternions (nlerp) - * - * Example: - * CQuaternion result,p,q; - * result=qlerp( p, q, 0.5f ); - */ - ILINE void SetNLerp(const QuatTNS_tpl& p, const QuatTNS_tpl& tq, F ti) - { - assert(p.q.IsValid()); - assert(tq.q.IsValid()); - Quat_tpl d = tq.q; - if ((p.q | d) < 0) - { - d = -d; - } - Vec3_tpl vDiff = d.v - p.q.v; - q.v = p.q.v + (vDiff * ti); - q.w = p.q.w + ((d.w - p.q.w) * ti); - q.Normalize(); - - vDiff = tq.t - p.t; - t = p.t + (vDiff * ti); - - s = p.s + ((tq.s - p.s) * ti); - } - - ILINE static QuatTNS_tpl CreateNLerp(const QuatTNS_tpl& p, const QuatTNS_tpl& q, F t) - { - QuatTNS_tpl d; - d.SetNLerp(p, q, t); - return d; - } - - - - ILINE static bool IsEquivalent(const QuatTNS_tpl& qts1, const QuatTNS_tpl& qts2, F qe = RAD_EPSILON, F ve = VEC_EPSILON) - { - real rad = acos(min(1.0f, fabs_tpl(qts1.q | qts2.q))); - bool qdif = rad <= qe; - bool vdif = fabs_tpl(qts1.t.x - qts2.t.x) <= ve && fabs_tpl(qts1.t.y - qts2.t.y) <= ve && fabs_tpl(qts1.t.z - qts2.t.z) <= ve; - bool sdif = fabs_tpl(qts1.s.x - qts2.s.x) <= ve && fabs_tpl(qts1.s.y - qts2.s.y) <= ve && fabs_tpl(qts1.s.z - qts2.s.z) <= ve; - return (qdif && vdif && sdif); - } - - - bool IsValid(F e = VEC_EPSILON) const - { - if (!q.v.IsValid()) - { - return false; - } - if (!NumberValid(q.w)) - { - return false; - } - if (!q.IsUnit(e)) - { - return false; - } - if (!t.IsValid()) - { - return false; - } - if (!NumberValid(s.x)) - { - return false; - } - if (!NumberValid(s.y)) - { - return false; - } - if (!NumberValid(s.z)) - { - return false; - } - return true; - } - - ILINE Vec3_tpl GetColumn0() const {return q.GetColumn0(); } - ILINE Vec3_tpl GetColumn1() const {return q.GetColumn1(); } - ILINE Vec3_tpl GetColumn2() const {return q.GetColumn2(); } - ILINE Vec3_tpl GetColumn3() const {return t; } - ILINE Vec3_tpl GetRow0() const { return q.GetRow0(); } - ILINE Vec3_tpl GetRow1() const { return q.GetRow1(); } - ILINE Vec3_tpl GetRow2() const { return q.GetRow2(); } - - AUTO_STRUCT_INFO -}; - -typedef QuatTNS_tpl QuatTNS; -typedef QuatTNS_tpl QuatTNSr; -typedef QuatTNS_tpl QuatTNS_f64; - -// alligned versions -typedef DEFINE_ALIGNED_DATA (QuatTNS, QuatTNSA, 16); -typedef DEFINE_ALIGNED_DATA (QuatTNSr, QuatTNSrA, 64); -typedef DEFINE_ALIGNED_DATA (QuatTNS_f64, QuatTNS_f64A, 64); - -template -ILINE QuatTNS_tpl operator * (const QuatTNS_tpl& a, const Quat_tpl& b) -{ - return QuatTNS_tpl(a.q * b, a.t, a.s); -} - -template -ILINE QuatTNS_tpl operator * (const Quat_tpl& a, const QuatTNS_tpl& b) -{ - return QuatTNS_tpl(a * b.q, a * b.t, b.s); -} - -template -ILINE QuatTNS_tpl operator * (const QuatTNS_tpl& a, const QuatT_tpl& b) -{ - return QuatTNS_tpl(a.q * b.q, a.q * Vec3_tpl(b.x * a.s.x, b.y * a.s.y, b.z * a.s.z) + a.t, a.s); -} - -template -ILINE QuatTNS_tpl operator * (const QuatT_tpl& a, const QuatTNS_tpl& b) -{ - return QuatTNS_tpl(a.q * b.q, a.q * b.t + a.t, b.s); -} - -/*! -* Implements the multiplication operator: QuatTNS=QuatTNS*QuatTNS -*/ -template -ILINE QuatTNS_tpl operator * (const QuatTNS_tpl& a, const QuatTNS_tpl& b) -{ - assert(a.IsValid()); - assert(b.IsValid()); - return QuatTNS_tpl( - a.q * b.q, - a.q * Vec3_tpl(b.t.x * a.s.x, b.t.y * a.s.y, b.t.z * a.s.z) + a.t, - Vec3_tpl(a.s.x * b.s.x, a.s.y * b.s.y, a.s.z * b.s.z) - ); -} - -/*! -* post-multiply of a QuatTNS and a Vec3 (3D rotations with quaternions) -*/ -template -ILINE Vec3_tpl operator * (const QuatTNS_tpl& q, const Vec3_tpl& v) -{ - assert(q.IsValid()); - assert(v.IsValid()); - return q.q * Vec3_tpl(v.x * q.s.x, v.y * q.s.y, v.z * q.s.z) + q.t; -} - -//---------------------------------------------------------------------- -// Dual Quaternion -//---------------------------------------------------------------------- -template -struct DualQuat_tpl -{ - Quat_tpl nq; - Quat_tpl dq; - - ILINE DualQuat_tpl() {} - - ILINE DualQuat_tpl(const Quat_tpl& q, const Vec3_tpl& t) - { - //copy the quaternion part - nq = q; - //convert the translation into a dual quaternion part - dq.w = -0.5f * (t.x * q.v.x + t.y * q.v.y + t.z * q.v.z); - dq.v.x = 0.5f * (t.x * q.w + t.y * q.v.z - t.z * q.v.y); - dq.v.y = 0.5f * (-t.x * q.v.z + t.y * q.w + t.z * q.v.x); - dq.v.z = 0.5f * (t.x * q.v.y - t.y * q.v.x + t.z * q.w); - } - - ILINE DualQuat_tpl(const QuatT_tpl& qt) - { - //copy the quaternion part - nq = qt.q; - //convert the translation into a dual quaternion part - dq.w = -0.5f * (qt.t.x * qt.q.v.x + qt.t.y * qt.q.v.y + qt.t.z * qt.q.v.z); - dq.v.x = 0.5f * (qt.t.x * qt.q.w - qt.t.z * qt.q.v.y + qt.t.y * qt.q.v.z); - dq.v.y = 0.5f * (qt.t.y * qt.q.w - qt.t.x * qt.q.v.z + qt.t.z * qt.q.v.x); - dq.v.z = 0.5f * (qt.t.x * qt.q.v.y - qt.t.y * qt.q.v.x + qt.t.z * qt.q.w); - } - - explicit ILINE DualQuat_tpl( const Matrix34_tpl& m34 ) - { - // non-dual part (just copy q0): - nq = Quat_tpl(m34); - f32 tx = m34.m03; - f32 ty = m34.m13; - f32 tz = m34.m23; - - // dual part: - dq.w = -0.5f * (tx * nq.v.x + ty * nq.v.y + tz * nq.v.z); - dq.v.x = 0.5f * (tx * nq.w + ty * nq.v.z - tz * nq.v.y); - dq.v.y = 0.5f * (-tx * nq.v.z + ty * nq.w + tz * nq.v.x); - dq.v.z = 0.5f * (tx * nq.v.y - ty * nq.v.x + tz * nq.w); - } - - - ILINE DualQuat_tpl(type_identity) - { - SetIdentity(); - } - - ILINE DualQuat_tpl(type_zero) - { - SetZero(); - } - - template - ILINE DualQuat_tpl(const DualQuat_tpl& QDual) - : nq(QDual.nq) - , dq(QDual.dq) {} - - ILINE void SetIdentity() - { - nq.SetIdentity(); - dq.w = 0.0f; - dq.v.x = 0.0f; - dq.v.y = 0.0f; - dq.v.z = 0.0f; - } - - ILINE void SetZero() - { - nq.w = 0.0f; - nq.v.x = 0.0f; - nq.v.y = 0.0f; - nq.v.z = 0.0f; - dq.w = 0.0f; - dq.v.x = 0.0f; - dq.v.y = 0.0f; - dq.v.z = 0.0f; - } - - ILINE void Normalize() - { - // Normalize both components so that nq is unit - F norm = isqrt_safe_tpl(nq.v.len2() + sqr(nq.w)); - nq *= norm; - dq *= norm; - } - - AUTO_STRUCT_INFO -}; - -#ifndef MAX_API_NUM -typedef DualQuat_tpl DualQuat; //always 32 bit -typedef DualQuat_tpl DualQuatd;//always 64 bit -typedef DualQuat_tpl DualQuatr;//variable float precision. depending on the target system it can be between 32, 64 or 80 bit -#else -typedef DualQuat_tpl CryDualQuat; -#endif - -template -ILINE DualQuat_tpl operator*(const DualQuat_tpl& l, const F2 r) -{ - DualQuat_tpl dual; - dual.nq.w = l.nq.w * r; - dual.nq.v.x = l.nq.v.x * r; - dual.nq.v.y = l.nq.v.y * r; - dual.nq.v.z = l.nq.v.z * r; - - dual.dq.w = l.dq.w * r; - dual.dq.v.x = l.dq.v.x * r; - dual.dq.v.y = l.dq.v.y * r; - dual.dq.v.z = l.dq.v.z * r; - return dual; -} - -template -ILINE DualQuat_tpl operator+(const DualQuat_tpl& l, const DualQuat_tpl& r) -{ - DualQuat_tpl dual; - dual.nq.w = l.nq.w + r.nq.w; - dual.nq.v.x = l.nq.v.x + r.nq.v.x; - dual.nq.v.y = l.nq.v.y + r.nq.v.y; - dual.nq.v.z = l.nq.v.z + r.nq.v.z; - - dual.dq.w = l.dq.w + r.dq.w; - dual.dq.v.x = l.dq.v.x + r.dq.v.x; - dual.dq.v.y = l.dq.v.y + r.dq.v.y; - dual.dq.v.z = l.dq.v.z + r.dq.v.z; - return dual; -} - -template -ILINE void operator += (DualQuat_tpl& l, const DualQuat_tpl& r) -{ - l.nq.w += r.nq.w; - l.nq.v.x += r.nq.v.x; - l.nq.v.y += r.nq.v.y; - l.nq.v.z += r.nq.v.z; - - l.dq.w += r.dq.w; - l.dq.v.x += r.dq.v.x; - l.dq.v.y += r.dq.v.y; - l.dq.v.z += r.dq.v.z; -} - -template -ILINE Vec3_tpl operator*(const DualQuat_tpl& dq, const Vec3_tpl& v) -{ - F2 t; - const F2 ax = dq.nq.v.y * v.z - dq.nq.v.z * v.y + dq.nq.w * v.x; - const F2 ay = dq.nq.v.z * v.x - dq.nq.v.x * v.z + dq.nq.w * v.y; - const F2 az = dq.nq.v.x * v.y - dq.nq.v.y * v.x + dq.nq.w * v.z; - F2 x = dq.dq.v.x * dq.nq.w - dq.nq.v.x * dq.dq.w + dq.nq.v.y * dq.dq.v.z - dq.nq.v.z * dq.dq.v.y; - x += x; - t = (az * dq.nq.v.y - ay * dq.nq.v.z); - x += t + t + v.x; - F2 y = dq.dq.v.y * dq.nq.w - dq.nq.v.y * dq.dq.w + dq.nq.v.z * dq.dq.v.x - dq.nq.v.x * dq.dq.v.z; - y += y; - t = (ax * dq.nq.v.z - az * dq.nq.v.x); - y += t + t + v.y; - F2 z = dq.dq.v.z * dq.nq.w - dq.nq.v.z * dq.dq.w + dq.nq.v.x * dq.dq.v.y - dq.nq.v.y * dq.dq.v.x; - z += z; - t = (ay * dq.nq.v.x - ax * dq.nq.v.y); - z += t + t + v.z; - return Vec3_tpl(x, y, z); -} - -template -ILINE DualQuat_tpl operator*(const DualQuat_tpl& a, const DualQuat_tpl& b) -{ - DualQuat_tpl dual; - - dual.nq.v.x = a.nq.v.y * b.nq.v.z - a.nq.v.z * b.nq.v.y + a.nq.w * b.nq.v.x + a.nq.v.x * b.nq.w; - dual.nq.v.y = a.nq.v.z * b.nq.v.x - a.nq.v.x * b.nq.v.z + a.nq.w * b.nq.v.y + a.nq.v.y * b.nq.w; - dual.nq.v.z = a.nq.v.x * b.nq.v.y - a.nq.v.y * b.nq.v.x + a.nq.w * b.nq.v.z + a.nq.v.z * b.nq.w; - dual.nq.w = a.nq.w * b.nq.w - (a.nq.v.x * b.nq.v.x + a.nq.v.y * b.nq.v.y + a.nq.v.z * b.nq.v.z); - - //dual.dq = a.nq*b.dq + a.dq*b.nq; - dual.dq.v.x = a.nq.v.y * b.dq.v.z - a.nq.v.z * b.dq.v.y + a.nq.w * b.dq.v.x + a.nq.v.x * b.dq.w; - dual.dq.v.y = a.nq.v.z * b.dq.v.x - a.nq.v.x * b.dq.v.z + a.nq.w * b.dq.v.y + a.nq.v.y * b.dq.w; - dual.dq.v.z = a.nq.v.x * b.dq.v.y - a.nq.v.y * b.dq.v.x + a.nq.w * b.dq.v.z + a.nq.v.z * b.dq.w; - dual.dq.w = a.nq.w * b.dq.w - (a.nq.v.x * b.dq.v.x + a.nq.v.y * b.dq.v.y + a.nq.v.z * b.dq.v.z); - - dual.dq.v.x += a.dq.v.y * b.nq.v.z - a.dq.v.z * b.nq.v.y + a.dq.w * b.nq.v.x + a.dq.v.x * b.nq.w; - dual.dq.v.y += a.dq.v.z * b.nq.v.x - a.dq.v.x * b.nq.v.z + a.dq.w * b.nq.v.y + a.dq.v.y * b.nq.w; - dual.dq.v.z += a.dq.v.x * b.nq.v.y - a.dq.v.y * b.nq.v.x + a.dq.w * b.nq.v.z + a.dq.v.z * b.nq.w; - dual.dq.w += a.dq.w * b.nq.w - (a.dq.v.x * b.nq.v.x + a.dq.v.y * b.nq.v.y + a.dq.v.z * b.nq.v.z); - - return dual; -} - - -#endif // CRYINCLUDE_CRYCOMMON_CRY_QUAT_H - - diff --git a/Code/CryEngine/CryCommon/Cry_ValidNumber.h b/Code/CryEngine/CryCommon/Cry_ValidNumber.h deleted file mode 100644 index af6e560455..0000000000 --- a/Code/CryEngine/CryCommon/Cry_ValidNumber.h +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_VALIDNUMBER_H -#define CRYINCLUDE_CRYCOMMON_CRY_VALIDNUMBER_H -#pragma once - -//-------------------------------------------------------------------------------- - -// http://www.psc.edu/general/software/packages/ieee/ieee.html - -/* - The IEEE standard for floating point arithmetic - """""""""""""""""""""""""""""""""""""""""""""""" - - Single Precision - """"""""""""""""" - - The IEEE single precision floating point standard representation requires a 32 bit word, - which may be represented as numbered from 0 to 31, left to right. - The first bit is the sign bit, S, - the next eight bits are the exponent bits, 'E', - and the final 23 bits are the fraction 'F': - - S EEEEEEEE FFFFFFFFFFFFFFFFFFFFFFF - 0 1 8 9 31 - - The value V represented by the word may be determined as follows: - - * If E=255 and F is nonzero, then V=NaN ("Not a number") - * If E=255 and F is zero and S is 1, then V=-Infinity - * If E=255 and F is zero and S is 0, then V=Infinity - * If 0(x)) -#define FloatU32ExpMask (0xFF << 23) -#define FloatU32FracMask ((1 << 23) - 1) -#define FloatU32SignMask (1 << 31) -#define F32NAN (0x7F800001) // Produces rock solid fp-exceptions. -#define F32NAN_SAFE (FloatU32ExpMask | FloatU32FracMask) // This one is not triggering an fp-exception. - -#define DoubleU64(x) (*((uint64*) &(x))) -#define DoubleU64ExpMask ((uint64)255 << 55) -#define DoubleU64FracMask (((uint64)1 << 55) - (uint64)1) -#define DoubleU64SignMask ((uint64)1 << 63) -#if defined(__GNUC__) - #define F64NAN (0x7FF0000000000001ULL) // Produces rock solid fp-exceptions. -#else - #define F64NAN (0x7FF0000000000001) // Produces rock solid fp-exceptions. -#endif -#define F64NAN_SAFE (DoubleU64ExpMask | DoubleU64FracMask) // This one is not triggering an fp-exception. - -//-------------------------------------------------------------------------------- - -ILINE bool NumberValid(const float& x) -{ - return ((FloatU32(x) & FloatU32ExpMask) != FloatU32ExpMask); -} - -ILINE bool NumberNAN(const float& x) -{ - return (((FloatU32(x) & FloatU32ExpMask) == FloatU32ExpMask) && - ((FloatU32(x) & FloatU32FracMask) != 0)); -} - -ILINE bool NumberINF(const float& x) -{ - return (((FloatU32(x) & FloatU32ExpMask) == FloatU32ExpMask) && - ((FloatU32(x) & FloatU32FracMask) == 0)); -} - -ILINE bool NumberDEN(const float& x) -{ - return (((FloatU32(x) & FloatU32ExpMask) == 0) && - ((FloatU32(x) & FloatU32FracMask) != 0)); -} - -//-------------------------------------------------------------------------------- - -ILINE bool NumberValid(const double& x) -{ - return ((DoubleU64(x) & DoubleU64ExpMask) != DoubleU64ExpMask); -} - -ILINE bool NumberNAN(const double& x) -{ - return (((DoubleU64(x) & DoubleU64ExpMask) == DoubleU64ExpMask) && - ((DoubleU64(x) & DoubleU64FracMask) != 0)); -} - -ILINE bool NumberINF(const double& x) -{ - return (((DoubleU64(x) & DoubleU64ExpMask) == DoubleU64ExpMask) && - ((DoubleU64(x) & DoubleU64FracMask) == 0)); -} - -ILINE bool NumberDEN(const double& x) -{ - return (((DoubleU64(x) & DoubleU64ExpMask) == 0) && - ((DoubleU64(x) & DoubleU64FracMask) != 0)); -} - -//-------------------------------------------------------------------------------- - - -ILINE bool NumberValid([[maybe_unused]] const int8 x) -{ - return true; //integers are always valid -} -ILINE bool NumberValid([[maybe_unused]] const uint8 x) -{ - return true; //integers are always valid -} -ILINE bool NumberValid([[maybe_unused]] const int16 x) -{ - return true; //integers are always valid -} -ILINE bool NumberValid([[maybe_unused]] const uint16 x) -{ - return true; //integers are always valid -} -ILINE bool NumberValid([[maybe_unused]] const int32 x) -{ - return true; //integers are always valid -} -ILINE bool NumberValid([[maybe_unused]] const uint32 x) -{ - return true; //integers are always valid -} -ILINE bool NumberValid([[maybe_unused]] const int64 x) -{ - return true; //integers are always valid -} -ILINE bool NumberValid([[maybe_unused]] const uint64 x) -{ - return true; //integers are always valid -} - - -#endif // CRYINCLUDE_CRYCOMMON_CRY_VALIDNUMBER_H diff --git a/Code/CryEngine/CryCommon/Cry_Vector2.h b/Code/CryEngine/CryCommon/Cry_Vector2.h deleted file mode 100644 index c09db3e0f6..0000000000 --- a/Code/CryEngine/CryCommon/Cry_Vector2.h +++ /dev/null @@ -1,384 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Common matrix class - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_VECTOR2_H -#define CRYINCLUDE_CRYCOMMON_CRY_VECTOR2_H -#pragma once - -#include -#include "Cry_Math.h" - -template -struct Vec2_tpl -{ - typedef F value_type; - enum - { - component_count = 2 - }; - - F x, y; - -#ifdef _DEBUG - ILINE Vec2_tpl() - { - if constexpr (sizeof(F) == 4) - { - uint32* p = alias_cast(&x); - p[0] = F32NAN; - p[1] = F32NAN; - } - if constexpr (sizeof(F) == 8) - { - uint64* p = alias_cast(&x); - p[0] = F64NAN; - p[1] = F64NAN; - } - } -#else - ILINE Vec2_tpl() {} -#endif - - ILINE Vec2_tpl(type_zero) - : x(0) - , y(0) {} - ILINE Vec2_tpl(F vx, F vy) { x = vx; y = vy; } - explicit ILINE Vec2_tpl(F m) { x = y = m; } - - ILINE Vec2_tpl& set(F nx, F ny) { x = F(nx); y = F(ny); return *this; } - - - template - ILINE Vec2_tpl(const Vec2_tpl& src) { x = F(src.x); y = F(src.y); } - template - ILINE explicit Vec2_tpl(const Vec3_tpl& src) { x = F(src.x); y = F(src.y); } - template - ILINE explicit Vec2_tpl(const F1* psrc) { x = F(psrc[0]); y = F(psrc[1]); } - - explicit ILINE Vec2_tpl(const Vec3_tpl& v) - : x((F)v.x) - , y((F)v.y) { assert(this->IsValid()); } - - ILINE Vec2_tpl& operator=(const Vec2_tpl& src) { x = src.x; y = src.y; return *this; } - //template Vec2_tpl& operator=(const Vec2_tpl& src) { x=F(src.x); y=F(src.y); return *this; } - //template Vec2_tpl& operator=(const Vec3_tpl& src) { x=F(src.x); y=F(src.y); return *this; } - - ILINE int operator!() const { return x == 0 && y == 0; } - - // The default Normalize function is in fact "safe". 0 vectors remain unchanged. - Vec2_tpl& Normalize() - { - F fInvLen = isqrt_safe_tpl(x * x + y * y); - x *= fInvLen; - y *= fInvLen; - return *this; - } - - // Normalize if non-0, otherwise set to specified "safe" value. - Vec2_tpl& NormalizeSafe(const struct Vec2_tpl& safe = Vec2_tpl(0, 0)) - { - F fLen2 = x * x + y * y; - if (fLen2 > 0.0f) - { - F fInvLen = isqrt_tpl(fLen2); - x *= fInvLen; - y *= fInvLen; - } - else - { - *this = safe; - } - return *this; - } - - Vec2_tpl GetNormalized() const - { - F fInvLen = isqrt_safe_tpl(x * x + y * y); - return *this * fInvLen; - } - - Vec2_tpl GetNormalizedSafe(const struct Vec2_tpl& safe = Vec2_tpl(1, 0)) const - { - F fLen2 = x * x + y * y; - if (fLen2 > 0.0f) - { - F fInvLen = isqrt_tpl(fLen2); - return *this * fInvLen; - } - else - { - return safe; - } - } - - ILINE bool IsEquivalent(const Vec2_tpl& v1, F epsilon = VEC_EPSILON) const - { - assert(v1.IsValid()); - assert(this->IsValid()); - return ((fabs_tpl(x - v1.x) <= epsilon) && (fabs_tpl(y - v1.y) <= epsilon)); - } - - ILINE static bool IsEquivalent(const Vec2_tpl& v0, const Vec2_tpl& v1, F epsilon = VEC_EPSILON) - { - assert(v0.IsValid()); - assert(v1.IsValid()); - return ((fabs_tpl(v0.x - v1.x) <= epsilon) && (fabs_tpl(v0.y - v1.y) <= epsilon)); - } - - - ILINE F GetLength() const - { - return sqrt_tpl(x * x + y * y); - } - - ILINE F GetLengthSquared() const - { - return x * x + y * y; - } - - ILINE F GetLength2() const - { - return x * x + y * y; - } - - void SetLength(F fLen) - { - F fLenMe = GetLength2(); - if (fLenMe < 0.00001f * 0.00001f) - { - return; - } - fLenMe = fLen * isqrt_tpl(fLenMe); - x *= fLenMe; - y *= fLenMe; - } - - ILINE F area() const { return x * y; } - - ILINE F& operator[](int idx) { return *((F*)&x + idx); } - ILINE F operator[](int idx) const { return *((F*)&x + idx); } - ILINE operator F*() { return &x; } - ILINE Vec2_tpl& flip() { x = -x; y = -y; return *this; } - ILINE Vec2_tpl& zero() { x = y = 0; return *this; } - ILINE Vec2_tpl rot90ccw() const { return Vec2_tpl(-y, x); } - ILINE Vec2_tpl rot90cw() const { return Vec2_tpl(y, -x); } - - #ifdef quotient_h - quotient_tpl fake_atan2() const - { - quotient_tpl res; - int quad = -(signnz(x * x - y * y) - 1 >> 1); // hope the optimizer will remove complement shifts and adds - if (quad) - { - res.x = -y; - res.y = x; - } - else - { - res.x = x; - res.y = y; - } - int sgny = signnz(res.y); - quad |= 1 - sgny; //(res.y<0)<<1; - res.x *= sgny; - res.y *= sgny; - res += 1 + (quad << 1); - return res; - } - #endif - ILINE F atan2() const { return atan2_tpl(y, x); } - - ILINE Vec2_tpl operator-() const { return Vec2_tpl(-x, -y); } - - ILINE Vec2_tpl operator*(F k) const { return Vec2_tpl(x * k, y * k); } - ILINE Vec2_tpl& operator*=(F k) { x *= k; y *= k; return *this; } - ILINE Vec2_tpl operator/(F k) const { return *this * ((F)1.0 / k); } - ILINE Vec2_tpl& operator/=(F k) { return *this *= ((F)1.0 / k); } - - // bool operator==(const Vec2_tpl &vec) { return x == vec.x && y == vec.y; } - ILINE bool operator!=(const Vec2_tpl& vec) { return !(*this == vec); } - - ILINE friend bool operator==(const Vec2_tpl& left, const Vec2_tpl& right) { return left.x == right.x && left.y == right.y; } - ILINE friend bool operator!=(const Vec2_tpl& left, const Vec2_tpl& right) { return !(left == right); } - - ILINE bool IsZero(F e = (F)0.0) const - { - return (fabs_tpl(x) <= e) && (fabs_tpl(y) <= e); - } - - // IsZeroSlow would be a better name [5/20/2010 evgeny] - ILINE bool IsZeroFast(F e = (F)0.0003) const - { - return (fabs_tpl(x) + fabs_tpl(y)) <= e; - } - - ILINE F Dot(const Vec2_tpl& rhs) const {return x * rhs.x + y * rhs.y; } - /// returns a vector perpendicular to this one (this->Cross(newVec) points "up") - ILINE Vec2_tpl Perp() const {return Vec2_tpl(-y, x); } - - // The size of the "paralell-trapets" area spanned by the two vectors. - ILINE F Cross (const Vec2_tpl& v) const - { - return float (x * v.y - y * v.x); - } - - /*! - * Linear-Interpolation between Vec3 (lerp) - * - * Example: - * Vec3 r=Vec3::CreateLerp( p, q, 0.345f ); - */ - ILINE void SetLerp(const Vec2_tpl& p, const Vec2_tpl& q, F t) { *this = p * (1.0f - t) + q * t; } - ILINE static Vec2_tpl CreateLerp(const Vec2_tpl& p, const Vec2_tpl& q, F t) { return p * (1.0f - t) + q * t; } - - - /*! - * Spherical-Interpolation between 3d-vectors (geometrical slerp) - * both vectors are assumed to be normalized. - * - * Example: - * Vec3 r=Vec3::CreateSlerp( p, q, 0.5674f ); - */ - void SetSlerp(const Vec2_tpl& p, const Vec2_tpl& q, F t) - { - assert((fabs_tpl(1 - (p | p))) < 0.005); //check if unit-vector - assert((fabs_tpl(1 - (q | q))) < 0.005); //check if unit-vector - // calculate cosine using the "inner product" between two vectors: p*q=cos(radiant) - F cosine = (p | q); - //we explore the special cases where the both vectors are very close together, - //in which case we approximate using the more economical LERP and avoid "divisions by zero" since sin(Angle) = 0 as Angle=0 - if (cosine >= (F)0.99) - { - SetLerp(p, q, t); //perform LERP: - this->Normalize(); - } - else - { - //perform SLERP: because of the LERP-check above, a "division by zero" is not possible - F rad = acos_tpl(cosine); - F scale_0 = sin_tpl((1 - t) * rad); - F scale_1 = sin_tpl(t * rad); - *this = (p * scale_0 + q * scale_1) / sin_tpl(rad); - this->Normalize(); - } - } - ILINE static Vec2_tpl CreateSlerp(const Vec2_tpl& p, const Vec2_tpl& q, F t) - { - Vec2_tpl v; - v.SetSlerp(p, q, t); - return v; - } - - bool IsValid() const - { - if (!NumberValid(x)) - { - return false; - } - if (!NumberValid(y)) - { - return false; - } - return true; - } - - ILINE F GetDistance(const Vec2_tpl& vec1) const - { - return sqrt_tpl((x - vec1.x) * (x - vec1.x) + (y - vec1.y) * (y - vec1.y)); - } - - AUTO_STRUCT_INFO -}; - -/////////////////////////////////////////////////////////////////////////////// -// Typedefs // -/////////////////////////////////////////////////////////////////////////////// - -typedef Vec2_tpl Vec2; // always 32 bit -typedef Vec2_tpl Vec2d; // always 64 bit -typedef Vec2_tpl Vec2i; -typedef Vec2_tpl Vec2ui; -typedef Vec2_tpl Vec2r; // variable float precision. depending on the target system it can be 32, 64 or 80 bit - -typedef Vec2_tpl vector2f; -#if defined(LINUX64) -typedef Vec2_tpl vector2l; -#else -typedef Vec2_tpl vector2l; -#endif -typedef Vec2_tpl vector2df; -typedef Vec2_tpl vector2d; -typedef Vec2_tpl vector2di; -typedef Vec2_tpl vector2dui; - -template -Vec2_tpl operator*(F op1, const Vec2_tpl& op2) {return Vec2_tpl(op1 * op2.x, op1 * op2.y); } - -template -F1 operator*(const Vec2_tpl& op1, const Vec2_tpl& op2) { return op1.x * op2.x + op1.y * op2.y; } // dot product -template -F1 operator|(const Vec2_tpl& op1, const Vec2_tpl& op2) { return op1.x * op2.x + op1.y * op2.y; } // dot product - -template -F1 operator^(const Vec2_tpl& op1, const Vec2_tpl& op2) { return op1.x * op2.y - op1.y * op2.x; } // cross product - -template -Vec2_tpl operator+(const Vec2_tpl& op1, const Vec2_tpl& op2) -{ - return Vec2_tpl(op1.x + op2.x, op1.y + op2.y); -} -template -Vec2_tpl operator-(const Vec2_tpl& op1, const Vec2_tpl& op2) -{ - return Vec2_tpl(op1.x - op2.x, op1.y - op2.y); -} - -template -Vec2_tpl& operator+=(Vec2_tpl& op1, const Vec2_tpl& op2) -{ - op1.x += op2.x; - op1.y += op2.y; - return op1; -} -template -Vec2_tpl& operator-=(Vec2_tpl& op1, const Vec2_tpl& op2) -{ - op1.x -= op2.x; - op1.y -= op2.y; - return op1; -} - -template -bool operator==(const Vec2_tpl& left, const Vec2_tpl& right) -{ - return left.x == right.x && left.y == right.y; -} - - -template<> -ILINE Vec2 clamp_tpl(Vec2 X, Vec2 Min, Vec2 Max) -{ - return Vec2(clamp_tpl(X.x, Min.x, Max.x), clamp_tpl(X.y, Min.y, Max.y)); -} - - -// declare common constants. Must be done after the class for compiler conformance -// (msvc and clang handle instantiation differently) -const Vec2_tpl Vec2_Zero(0, 0); -const Vec2_tpl Vec2_OneX(1, 0); -const Vec2_tpl Vec2_OneY(0, 1); -const Vec2_tpl Vec2_One(1, 1); - -namespace AZ -{ - AZ_TYPE_INFO_SPECIALIZE(Vec2, "{844131BA-9565-42F3-8482-6F65A6D5FC59}"); -} -#endif // CRYINCLUDE_CRYCOMMON_CRY_VECTOR2_H diff --git a/Code/CryEngine/CryCommon/Cry_Vector3.h b/Code/CryEngine/CryCommon/Cry_Vector3.h deleted file mode 100644 index 6e75503fb4..0000000000 --- a/Code/CryEngine/CryCommon/Cry_Vector3.h +++ /dev/null @@ -1,1429 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Common vector class - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_VECTOR3_H -#define CRYINCLUDE_CRYCOMMON_CRY_VECTOR3_H -#pragma once - - -#include "CryEndian.h" -#include - -template -struct VecPrecisionValues -{ - ILINE static bool CheckGreater(const T value) - { - return value > 0; - } -}; - -template<> -struct VecPrecisionValues -{ - ILINE static bool CheckGreater(const float value) - { - return value > FLT_EPSILON; - } -}; - - -template -struct Vec3s_tpl -{ - F x, y, z; - - ILINE Vec3s_tpl(F vx, F vy, F vz) - : x(vx) - , y(vy) - , z(vz){} - ILINE F& operator [] (int32 index) { assert(index >= 0 && index <= 2); return ((F*)this)[index]; } - ILINE F operator [] (int32 index) const { assert(index >= 0 && index <= 2); return ((F*)this)[index]; } -}; - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// class Vec3_tpl -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -template -struct Vec3_tpl -{ - typedef F value_type; - enum - { - component_count = 3 - }; - - F x, y, z; - -#if defined(_DEBUG) - ILINE Vec3_tpl() - { - if constexpr (sizeof(F) == 4) - { - uint32* p = alias_cast(&x); - p[0] = F32NAN; - p[1] = F32NAN; - p[2] = F32NAN; - } - if constexpr (sizeof(F) == 8) - { - uint64* p = alias_cast(&x); - p[0] = F64NAN; - p[1] = F64NAN; - p[2] = F64NAN; - } - } -#else - ILINE Vec3_tpl() {}; -#endif - - /*! - * template specialization to initialize a vector - * - * Example: - * Vec3 v0=Vec3(ZERO); - * Vec3 v1=Vec3(MIN); - * Vec3 v2=Vec3(MAX); - */ - Vec3_tpl(type_zero) - : x(0) - , y(0) - , z(0) {} - Vec3_tpl(type_min); - Vec3_tpl(type_max); - - /*! - * constructors and bracket-operator to initialize a vector - * - * Example: - * Vec3 v0=Vec3(1,2,3); - * Vec3 v1(1,2,3); - * v2.Set(1,2,3); - */ - ILINE Vec3_tpl(F vx, F vy, F vz) - : x(vx) - , y(vy) - , z(vz){ assert(this->IsValid()); } - ILINE void operator () (F vx, F vy, F vz) { x = vx; y = vy; z = vz; assert(this->IsValid()); } - ILINE Vec3_tpl& Set(const F xval, const F yval, const F zval) { x = xval; y = yval; z = zval; assert(this->IsValid()); return *this; } - - explicit ILINE Vec3_tpl(F f) - : x(f) - , y(f) - , z(f) { assert(this->IsValid()); } - - explicit ILINE Vec3_tpl(const AZ::Vector3& v) - { - x = v.GetX(); - y = v.GetY(); - z = v.GetZ(); - } - - /*! - * the copy/casting/assignement constructor - * - * Example: - * Vec3 v0=v1; - * Vec3 v0=Vec3(angle); - * Vec3 v0=Vec3(vector4); - */ - ILINE Vec3_tpl(const Vec3_tpl& v) { x = v.x; y = v.y; z = v.z; } - template - ILINE Vec3_tpl(const Vec3_tpl&v) { - x = F(v.x); - y = F(v.y); - z = F(v.z); - assert(IsValid()); - } - - ILINE Vec3_tpl(const Vec2_tpl&v) { - x = v.x; - y = v.y; - z = 0; - assert(IsValid()); - } - template - ILINE Vec3_tpl(const Vec2_tpl&v) { - x = F(v.x); - y = F(v.y); - z = 0; - assert(IsValid()); - } - - explicit ILINE Vec3_tpl(const Ang3_tpl&v) { - x = v.x; - y = v.y; - z = v.z; - assert(IsValid()); - } - template - explicit ILINE Vec3_tpl(const Ang3_tpl&v) { - x = v.x; - y = v.y; - z = v.z; - assert(IsValid()); - } - - explicit ILINE Vec3_tpl(const Vec4_tpl &v) { - x = F(v.x); - y = F(v.y); - z = F(v.z); - } - template - explicit ILINE Vec3_tpl(const Vec4_tpl &v) { - x = F(v.x); - y = F(v.y); - z = F(v.z); - } - - - - - /*! - * overloaded arithmetic operator - * - * Example: - * Vec3 v0=v1*4; - */ - ILINE Vec3_tpl operator * (F k) const - { - const Vec3_tpl v = *this; - return Vec3_tpl(v.x * k, v.y * k, v.z * k); - } - ILINE Vec3_tpl operator / (F k) const - { - k = (F)1.0 / k; - return Vec3_tpl(x * k, y * k, z * k); - } - ILINE friend Vec3_tpl operator * (F f, const Vec3_tpl& vec) - { - return Vec3_tpl((F)(f * vec.x), (F)(f * vec.y), (F)(f * vec.z)); - } - - ILINE Vec3_tpl& operator *= (F k) - { - x *= k; - y *= k; - z *= k; - return *this; - } - ILINE Vec3_tpl& operator /= (F k) - { - k = (F)1.0 / k; - x *= k; - y *= k; - z *= k; - return *this; - } - - ILINE Vec3_tpl operator - (void) const - { - return Vec3_tpl(-x, -y, -z); - } - ILINE Vec3_tpl& Flip() - { - x = -x; - y = -y; - z = -z; - return *this; - } - - - /*! - * bracked-operator - * - * Example: - * uint32 t=v[0]; - */ - ILINE F& operator [] (int32 index) { assert(index >= 0 && index <= 2); return ((F*)this)[index]; } - ILINE F operator [] (int32 index) const { assert(index >= 0 && index <= 2); return ((F*)this)[index]; } - - - /*! - * functions and operators to compare vector - * - * Example: - * if (v0==v1) dosomething; - */ - ILINE bool operator==(const Vec3_tpl& vec) - { - return x == vec.x && y == vec.y && z == vec.z; - } - ILINE bool operator!=(const Vec3_tpl& vec) - { - return !(*this == vec); - } - - ILINE friend bool operator ==(const Vec3_tpl& v0, const Vec3_tpl& v1) - { - return ((v0.x == v1.x) && (v0.y == v1.y) && (v0.z == v1.z)); - } - ILINE friend bool operator !=(const Vec3_tpl& v0, const Vec3_tpl& v1) - { - return !(v0 == v1); - } - - ILINE bool IsZero(F e = (F) 0.0) const - { - return (fabs_tpl(x) <= e) && (fabs_tpl(y) <= e) && (fabs_tpl(z) <= e); - } - - ILINE bool IsZeroFast(F e = (F) 0.0003) const - { - return (fabs_tpl(x) + fabs_tpl(y) + fabs_tpl(z)) <= e; - } - - // Chebyshev distance (axis aligned) - ILINE bool IsEquivalent(const Vec3_tpl& v1, F epsilon = VEC_EPSILON) const - { - assert(v1.IsValid()); - assert(this->IsValid()); - return ((fabs_tpl(x - v1.x) <= epsilon) && (fabs_tpl(y - v1.y) <= epsilon) && (fabs_tpl(z - v1.z) <= epsilon)); - } - ILINE static bool IsEquivalent(const Vec3_tpl& v0, const Vec3_tpl& v1, F epsilon = VEC_EPSILON) - { - assert(v0.IsValid()); - assert(v1.IsValid()); - return ((fabs_tpl(v0.x - v1.x) <= epsilon) && (fabs_tpl(v0.y - v1.y) <= epsilon) && (fabs_tpl(v0.z - v1.z) <= epsilon)); - } - - // Euclidean distance L2 - ILINE bool IsEquivalentL2(const Vec3_tpl& v1, F epsilon = VEC_EPSILON) const - { - assert(v1.IsValid()); - assert(this->IsValid()); - return (*this - v1).GetLengthSquared() <= (epsilon * epsilon); - } - ILINE static bool IsEquivalentL2(const Vec3_tpl& v0, const Vec3_tpl& v1, F epsilon = VEC_EPSILON) - { - assert(v0.IsValid()); - assert(v1.IsValid()); - return (v0 - v1).GetLengthSquared() <= (epsilon * epsilon); - } - - ILINE bool IsUnit(F epsilon = VEC_EPSILON) const - { - return (fabs_tpl(1 - GetLengthSquared()) <= epsilon); - } - - bool IsValid() const - { - if (!NumberValid(x)) - { - return false; - } - if (!NumberValid(y)) - { - return false; - } - if (!NumberValid(z)) - { - return false; - } - return true; - } - - //! force vector length by normalizing it - ILINE void SetLength(F fLen) - { - F fLenMe = GetLengthSquared(); - if (fLenMe < 0.00001f * 0.00001f) - { - return; - } - fLenMe = fLen * isqrt_tpl(fLenMe); - x *= fLenMe; - y *= fLenMe; - z *= fLenMe; - } - - ILINE void ClampLength(F maxLength) - { - F sqrLength = GetLengthSquared(); - if (sqrLength > (maxLength * maxLength)) - { - F scale = maxLength * isqrt_tpl(sqrLength); - x *= scale; - y *= scale; - z *= scale; - } - } - - //! calculate the length of the vector - ILINE F GetLength() const - { - return sqrt_tpl(x * x + y * y + z * z); - } - - ILINE F GetLengthFloat() const - { - return GetLength(); - } - - ILINE F GetLengthFast() const - { - return sqrt_fast_tpl(x * x + y * y + z * z); - } - - //! calculate the squared length of the vector - ILINE F GetLengthSquared() const - { - return x * x + y * y + z * z; - } - - ILINE F GetLengthSquaredFloat() const - { - return GetLengthSquared(); - } - - //! calculate the length of the vector ignoring the z component - ILINE F GetLength2D() const - { - return sqrt_tpl(x * x + y * y); - } - - //! calculate the squared length of the vector ignoring the z component - ILINE F GetLengthSquared2D() const - { - return x * x + y * y; - } - - ILINE F GetDistance(const Vec3_tpl& vec1) const - { - return sqrt_tpl((x - vec1.x) * (x - vec1.x) + (y - vec1.y) * (y - vec1.y) + (z - vec1.z) * (z - vec1.z)); - } - ILINE F GetSquaredDistance (const Vec3_tpl& v) const - { - return (x - v.x) * (x - v.x) + (y - v.y) * (y - v.y) + (z - v.z) * (z - v.z); - } - ILINE F GetSquaredDistance2D (const Vec3_tpl& v) const - { - return (x - v.x) * (x - v.x) + (y - v.y) * (y - v.y); - } - - //! Normalize the vector. - // The default Normalize function is in fact "safe". 0 vectors remain unchanged. - ILINE void Normalize() - { - assert(this->IsValid()); - F fInvLen = isqrt_safe_tpl(x * x + y * y + z * z); - x *= fInvLen; - y *= fInvLen; - z *= fInvLen; - } - - //! May be faster and less accurate. - ILINE void NormalizeFast() - { - assert(this->IsValid()); - F fInvLen = isqrt_fast_tpl(x * x + y * y + z * z); - x *= fInvLen; - y *= fInvLen; - z *= fInvLen; - } - - //! Normalize the vector to a scale. - ILINE void Normalize(F scale) - { - assert(this->IsValid()); - F fInvLen = isqrt_safe_tpl(x * x + y * y + z * z) * scale; - x *= fInvLen; - y *= fInvLen; - z *= fInvLen; - } - ILINE void NormalizeFast(F scale) - { - assert(this->IsValid()); - F fInvLen = isqrt_fast_tpl(x * x + y * y + z * z) * scale; - x *= fInvLen; - y *= fInvLen; - z *= fInvLen; - } - - //! Normalize the vector. - // check for null vector - set to the passed in vector (which should be normalised!) if it is null vector - // returns the original length of the vector - ILINE F NormalizeSafe(const struct Vec3_tpl& safe = Vec3_tpl(0, 0, 0)) - { - assert(this->IsValid()); - F fLen2 = x * x + y * y + z * z; - IF (VecPrecisionValues::CheckGreater(fLen2), 1) - { - F fInvLen = isqrt_tpl(fLen2); - x *= fInvLen; - y *= fInvLen; - z *= fInvLen; - return F(1) / fInvLen; - } - else - { - *this = safe; - return F(0); - } - } - - ILINE Vec3_tpl GetNormalizedFloat() const - { - return GetNormalized(); - } - - //! Return a normalized vector. - ILINE Vec3_tpl GetNormalized() const - { - F fInvLen = isqrt_safe_tpl(x * x + y * y + z * z); - return *this * fInvLen; - } - - //! Return a normalized vector. - ILINE Vec3_tpl GetNormalizedFast() const - { - F fInvLen = isqrt_fast_tpl(x * x + y * y + z * z); - return *this * fInvLen; - } - - //! Return a safely normalized vector - returns safe vector (should be normalised) if original is zero length. - ILINE Vec3_tpl GetNormalizedSafe(const struct Vec3_tpl& safe = Vec3_tpl(1, 0, 0)) const - { - F fLen2 = x * x + y * y + z * z; - IF (VecPrecisionValues::CheckGreater(fLen2), 1) - { - F fInvLen = isqrt_tpl(fLen2); - return *this * fInvLen; - } - else - { - return safe; - } - } - - //! Return a safely normalized vector - returns safe vector (should be normalised) if original is zero length. - ILINE Vec3_tpl GetNormalizedSafeFloat(const struct Vec3_tpl& safe = Vec3_tpl(1, 0, 0)) const - { - return GetNormalizedSafe(safe); - } - - //! Return a normalized and scaled vector. - ILINE Vec3_tpl GetNormalized(F scale) const - { - F fInvLen = isqrt_safe_tpl(x * x + y * y + z * z); - return *this * (fInvLen * scale); - } - ILINE Vec3_tpl GetNormalizedFast(F scale) const - { - F fInvLen = isqrt_fast_tpl(x * x + y * y + z * z); - return *this * (fInvLen * scale); - } - - //! Permutate coordinates so that z goes to new_z slot. - ILINE Vec3_tpl GetPermutated(int new_z) const { return Vec3_tpl(*(&x + inc_mod3[new_z]), *(&x + dec_mod3[new_z]), *(&x + new_z)); } - - //! Returns volume of a box with this vector as diagonal. - ILINE F GetVolume() const { return x * y * z; } - - //! Returns a vector that consists of absolute values of this one's coordinates. - ILINE Vec3_tpl abs() const - { - return Vec3_tpl(fabs_tpl(x), fabs_tpl(y), fabs_tpl(z)); - } - - //! Check for min bounds. - ILINE void CheckMin(const Vec3_tpl other) - { - x = min(other.x, x); - y = min(other.y, y); - z = min(other.z, z); - } - //! Check for max bounds. - ILINE void CheckMax(const Vec3_tpl other) - { - x = max(other.x, x); - y = max(other.y, y); - z = max(other.z, z); - } - - - - /*! - * Sets a vector orthogonal to the input vector. - * - * Example: - * Vec3 v; - * v.SetOrthogonal( i ); - */ - ILINE void SetOrthogonal(const Vec3_tpl& v) - { - sqr(F(0.9)) * (v | v) - v.x * v.x < 0 ? (x = -v.z, y = 0, z = v.x) : (x = 0, y = v.z, z = -v.y); - } - //! Returns a vector orthogonal to this one. - ILINE Vec3_tpl GetOrthogonal() const - { - return sqr(F(0.9)) * (x * x + y * y + z * z) - x * x < 0 ? Vec3_tpl(-z, 0, x) : Vec3_tpl(0, z, -y); - } - - /*! - * Project a point/vector on a (virtual) plane - * Consider we have a plane going through the origin. - * Because d=0 we need just the normal. The vector n is assumed to be a unit-vector. - * - * Example: - * Vec3 result=Vec3::CreateProjection( incident, normal ); - */ - ILINE void SetProjection(const Vec3_tpl& i, const Vec3_tpl& n) - { - *this = i - n * (n | i); - } - ILINE static Vec3_tpl CreateProjection(const Vec3_tpl& i, const Vec3_tpl& n) - { - return i - n * (n | i); - } - - /*! - * Calculate a reflection vector. Vec3 n is assumed to be a unit-vector. - * - * Example: - * Vec3 result=Vec3::CreateReflection( incident, normal ); - */ - ILINE void SetReflection(const Vec3_tpl& i, const Vec3_tpl& n) - { - *this = (n * (i | n) * 2) - i; - } - ILINE static Vec3_tpl CreateReflection(const Vec3_tpl& i, const Vec3_tpl& n) - { - return (n * (i | n) * 2) - i; - } - - /*! - * Linear-Interpolation between Vec3 (lerp) - * - * Example: - * Vec3 r=Vec3::CreateLerp( p, q, 0.345f ); - */ - ILINE void SetLerp(const Vec3_tpl& p, const Vec3_tpl& q, F t) - { - const Vec3_tpl diff = q - p; - *this = p + (diff * t); - } - ILINE static Vec3_tpl CreateLerp(const Vec3_tpl& p, const Vec3_tpl& q, F t) - { - const Vec3_tpl diff = q - p; - return p + (diff * t); - } - - - /*! - * Spherical-Interpolation between 3d-vectors (geometrical slerp) - * both vectors are assumed to be normalized. - * - * Example: - * Vec3 r=Vec3::CreateSlerp( p, q, 0.5674f ); - */ - void SetSlerp(const Vec3_tpl& p, const Vec3_tpl& q, F t) - { - assert(p.IsUnit(0.005f)); - assert(q.IsUnit(0.005f)); - // calculate cosine using the "inner product" between two vectors: p*q=cos(radiant) - F cosine = clamp_tpl((p | q), F(-1), F(1)); - //we explore the special cases where the both vectors are very close together, - //in which case we approximate using the more economical LERP and avoid "divisions by zero" since sin(Angle) = 0 as Angle=0 - if (cosine >= (F)0.99) - { - SetLerp(p, q, t); //perform LERP: - Normalize(); - } - else - { - //perform SLERP: because of the LERP-check above, a "division by zero" is not possible - F rad = acos_tpl(cosine); - F scale_0 = sin_tpl((1 - t) * rad); - F scale_1 = sin_tpl(t * rad); - *this = (p * scale_0 + q * scale_1) / sin_tpl(rad); - Normalize(); - } - } - ILINE static Vec3_tpl CreateSlerp(const Vec3_tpl& p, const Vec3_tpl& q, F t) - { - Vec3_tpl v; - v.SetSlerp(p, q, t); - return v; - } - - - - - /*! - * Quadratic-Interpolation between vectors v0,v1,v2. - * This is repeated linear interpolation from 3 points and the resulting curve is a parabola. - * If t is in the range [0...1], then the curve goes only through v0 and v2. - * - * Example: - * Vec3 ip; ip.SetQuadraticCurve( v0,v1,v2, 0.345f ); - */ - ILINE void SetQuadraticCurve(const Vec3_tpl& v0, const Vec3_tpl& v1, const Vec3_tpl& v2, F t1) - { - F t0 = 1.0f - t1; - *this = t0 * t0 * v0 + t0 * t1 * 2.0f * v1 + t1 * t1 * v2; - } - ILINE static Vec3_tpl CreateQuadraticCurve(const Vec3_tpl& v0, const Vec3_tpl& v1, const Vec3_tpl& v2, F t) - { - Vec3_tpl ip; - ip.SetQuadraticCurve(v0, v1, v2, t); - return ip; - } - - /*! - * Cubic-Interpolation between vectors v0,v1,v2,v3. - * This is repeated linear interpolation from 4 points. - * If t is in the range [0...1], then the curve goes only through v0 and v3. - * - * Example: - * Vec3 ip; ip.SetCubicCurve( v0,v1,v2,v3, 0.345f ); - */ - ILINE void SetCubicCurve(const Vec3_tpl& v0, const Vec3_tpl& v1, const Vec3_tpl& v2, const Vec3_tpl& v3, F t1) - { - F t0 = 1.0f - t1; - *this = t0 * t0 * t0 * v0 + 3 * t0 * t0 * t1 * v1 + 3 * t0 * t1 * t1 * v2 + t1 * t1 * t1 * v3; - } - ILINE static Vec3_tpl CreateCubicCurve(const Vec3_tpl& v0, const Vec3_tpl& v1, const Vec3_tpl& v2, const Vec3_tpl& v3, F t) - { - Vec3_tpl ip; - ip.SetCubicCurve(v0, v1, v2, v3, t); - return ip; - } - - /*! - * Spline-Interpolation between vectors v0,v1,v2. - * This is a variation of a quadratic curve. - * If t is in the range [0...1], then the spline goes through all 3 points - * - * Example: - * Vec3 ip; ip.SetSplineInterpolation( v0,v1,v2, 0.345f ); - */ - ILINE void SetQuadraticSpline(const Vec3_tpl& v0, const Vec3_tpl& v1, const Vec3_tpl& v2, F t) - { - SetQuadraticCurve(v0, v1 - (v0 * 0.5f + v1 + v2 * 0.5f - v1 * 2.0f), v2, t); - } - ILINE static Vec3_tpl CreateQuadraticSpline(const Vec3_tpl& v0, const Vec3_tpl& v1, const Vec3_tpl& v2, F t) - { - Vec3_tpl ip; - ip.SetQuadraticSpline(v0, v1, v2, t); - return ip; - } - - /*! - * Rotate a vector using angle&axis. - * - * Example: - * Vec3 r=v.GetRotated(axis,angle); - */ - ILINE Vec3_tpl GetRotated(const Vec3_tpl& axis, F angle) const - { - return GetRotated(axis, cos_tpl(angle), sin_tpl(angle)); - } - ILINE Vec3_tpl GetRotated(const Vec3_tpl& axis, F cosa, F sina) const - { - Vec3_tpl zax = axis * (*this | axis); - Vec3_tpl xax = *this - zax; - Vec3_tpl yax = axis % xax; - return xax * cosa + yax * sina + zax; - } - - /*! - * Rotate a vector around a center using angle&axis. - * - * Example: - * Vec3 r=v.GetRotated(axis,angle); - */ - ILINE Vec3_tpl GetRotated(const Vec3_tpl& center, const Vec3_tpl& axis, F angle) const - { - return center + (*this - center).GetRotated(axis, angle); - } - ILINE Vec3_tpl GetRotated(const Vec3_tpl& center, const Vec3_tpl& axis, F cosa, F sina) const - { - return center + (*this - center).GetRotated(axis, cosa, sina); - } - - /*! - * Component wise multiplication of two vectors. - */ - ILINE Vec3_tpl CompMul(const Vec3_tpl rhs) const - { - return(Vec3_tpl(x * rhs.x, y * rhs.y, z * rhs.z)); - } - - //! Three methods for a "dot-product" operation. - ILINE F Dot (const Vec3_tpl v) const - { - return x * v.x + y * v.y + z * v.z; - } - //! Two methods for a "cross-product" operation. - ILINE Vec3_tpl Cross (const Vec3_tpl vec2) const - { - return Vec3_tpl(y * vec2.z - z * vec2.y, z * vec2.x - x * vec2.z, x * vec2.y - y * vec2.x); - } - - //f32* fptr=vec; - DEPRECATED operator F* () { return (F*)this; } - template - explicit DEPRECATED Vec3_tpl(const T* src) { x = F(src[0]); y = F(src[1]); z = F(src[2]); } - - ILINE Vec3_tpl& zero() { x = y = z = 0; return *this; } - ILINE F len() const - { - return sqrt_tpl(x * x + y * y + z * z); - } - ILINE F len2() const - { - return x * x + y * y + z * z; - } - - ILINE Vec3_tpl& normalize() - { - F len2 = x * x + y * y + z * z; - if (len2 > (F)1e-20f) - { - F rlen = isqrt_tpl(len2); - x *= rlen; - y *= rlen; - z *= rlen; - } - else - { - Set(0, 0, 1); - } - return *this; - } - ILINE Vec3_tpl normalized() const - { - F len2 = x * x + y * y + z * z; - if (len2 > (F)1e-20f) - { - F rlen = isqrt_tpl(len2); - return Vec3_tpl(x * rlen, y * rlen, z * rlen); - } - else - { - return Vec3_tpl(0, 0, 1); - } - } - - //vector subtraction - template - ILINE Vec3_tpl sub(const Vec3_tpl& v) const - { - return Vec3_tpl(x - v.x, y - v.y, z - v.z); - } - //vector scale - template - ILINE Vec3_tpl scale(const F1 k) const - { - return Vec3_tpl(x * k, y * k, z * k); - } - - //vector dot product - template - ILINE F1 dot(const Vec3_tpl& v) const - { - return (F1)(x * v.x + y * v.y + z * v.z); - } - //vector cross product - template - ILINE Vec3_tpl cross(const Vec3_tpl& v) const - { - return Vec3_tpl(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x); - } - - AUTO_STRUCT_INFO -}; - -// dot product (2 versions) -template -ILINE F1 operator * (const Vec3_tpl& v0, const Vec3_tpl& v1) -{ - return v0.Dot(v1); -} -template -ILINE F1 operator | (const Vec3_tpl& v0, const Vec3_tpl& v1) -{ - return v0.Dot(v1); -} -// cross product (2 versions) -template -ILINE Vec3_tpl operator ^ (const Vec3_tpl& v0, const Vec3_tpl& v1) -{ - return v0.Cross(v1); -} -template -ILINE Vec3_tpl operator % (const Vec3_tpl& v0, const Vec3_tpl& v1) -{ - return v0.Cross(v1); -} - - -//vector addition -template -ILINE Vec3_tpl operator + (const Vec3_tpl& v0, const Vec3_tpl& v1) -{ - return Vec3_tpl(static_cast(v0.x + v1.x), static_cast(v0.y + v1.y), static_cast(v0.z + v1.z)); -} -//vector addition -template -ILINE Vec3_tpl operator + (const Vec2_tpl& v0, const Vec3_tpl& v1) -{ - return Vec3_tpl(v0.x + v1.x, v0.y + v1.y, v1.z); -} -//vector addition -template -ILINE Vec3_tpl operator + (const Vec3_tpl& v0, const Vec2_tpl& v1) -{ - return Vec3_tpl(v0.x + v1.x, v0.y + v1.y, v0.z); -} - -//vector subtraction -template -ILINE Vec3_tpl operator - (const Vec3_tpl& v0, const Vec3_tpl& v1) -{ - return Vec3_tpl((F1)(v0.x - v1.x), (F1)(v0.y - v1.y), (F1)(v0.z - v1.z)); -} -template -ILINE Vec3_tpl operator - (const Vec2_tpl& v0, const Vec3_tpl& v1) -{ - return Vec3_tpl(v0.x - v1.x, v0.y - v1.y, 0.0f - v1.z); -} -template -ILINE Vec3_tpl operator - (const Vec3_tpl& v0, const Vec2_tpl& v1) -{ - return Vec3_tpl(v0.x - v1.x, v0.y - v1.y, v0.z); -} - - -//--------------------------------------------------------------------------- - - -//vector self-addition -template -ILINE Vec3_tpl& operator += (Vec3_tpl& v0, const Vec3_tpl& v1) -{ - v0 = v0 + v1; - return v0; -} -//vector self-subtraction -template -ILINE Vec3_tpl& operator -= (Vec3_tpl& v0, const Vec3_tpl& v1) -{ - v0 = v0 - v1; - return v0; -} -template -ILINE Vec3_tpl operator / (const Vec3_tpl& v0, const Vec3_tpl& v1) -{ - return Vec3_tpl(v0.x / v1.x, v0.y / v1.y, v0.z / v1.z); -} - -template -ILINE bool IsEquivalent(const Vec3_tpl& v0, const Vec3_tpl& v1, f32 epsilon = VEC_EPSILON) -{ - return ((fabs_tpl(v0.x - v1.x) <= epsilon) && (fabs_tpl(v0.y - v1.y) <= epsilon) && (fabs_tpl(v0.z - v1.z) <= epsilon)); -} - - -/////////////////////////////////////////////////////////////////////////////// -// Typedefs // -/////////////////////////////////////////////////////////////////////////////// -typedef Vec3_tpl Vec3; // always 32 bit - -typedef Vec3_tpl Vec3d; // always 64 bit -typedef Vec3_tpl Vec3i; -typedef Vec3_tpl Vec3ui; -typedef Vec3_tpl Vec3r; // variable float precision. depending on the target system it can be 32, 64 or 80 bit - -template<> -inline Vec3_tpl::Vec3_tpl(type_min) { x = y = z = -1.7E308; } -template<> -inline Vec3_tpl::Vec3_tpl(type_max) { x = y = z = 1.7E308; } -template<> -inline Vec3_tpl::Vec3_tpl(type_min) { x = y = z = -3.3E38f; } -template<> -inline Vec3_tpl::Vec3_tpl(type_max) { x = y = z = 3.3E38f; } - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct Ang3_tpl -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -template -struct Ang3_tpl -{ - F x, y, z; - -#if defined(_DEBUG) - ILINE Ang3_tpl() - { - if constexpr (sizeof(F) == 4) - { - uint32* p = alias_cast(&x); - p[0] = F32NAN; - p[1] = F32NAN; - p[2] = F32NAN; - } - if constexpr (sizeof(F) == 8) - { - uint64* p = alias_cast(&x); - p[0] = F64NAN; - p[1] = F64NAN; - p[2] = F64NAN; - } - } -#else - ILINE Ang3_tpl() {}; -#endif - - - Ang3_tpl(type_zero) { x = y = z = 0; } - - void operator () (F vx, F vy, F vz) { x = vx; y = vy; z = vz; }; - ILINE Ang3_tpl(F vx, F vy, F vz) { - x = vx; - y = vy; - z = vz; - } - - explicit ILINE Ang3_tpl(const Vec3_tpl& v) - : x((F)v.x) - , y((F)v.y) - , z((F)v.z) { assert(this->IsValid()); } - - ILINE bool operator==(const Ang3_tpl& vec) { return x == vec.x && y == vec.y && z == vec.z; } - ILINE bool operator!=(const Ang3_tpl& vec) { return !(*this == vec); } - - ILINE Ang3_tpl operator * (F k) const { return Ang3_tpl(x * k, y * k, z * k); } - ILINE Ang3_tpl operator / (F k) const { k = (F)1.0 / k; return Ang3_tpl(x * k, y * k, z * k); } - - - ILINE Ang3_tpl& operator *= (F k) { x *= k; y *= k; z *= k; return *this; } - //explicit ILINE Ang3_tpl& operator = (const Vec3_tpl& v) { x=v.x; y=v.y; z=v.z; return *this; } - - ILINE Ang3_tpl operator - (void) const { return Ang3_tpl(-x, -y, -z); } - - ILINE friend bool operator ==(const Ang3_tpl& v0, const Ang3_tpl& v1) - { - return ((v0.x == v1.x) && (v0.y == v1.y) && (v0.z == v1.z)); - } - ILINE void Set(F xval, F yval, F zval) { x = xval; y = yval; z = zval; } - - ILINE bool IsEquivalent(const Ang3_tpl& v1, F epsilon = VEC_EPSILON) const - { - return ((fabs_tpl(x - v1.x) <= epsilon) && (fabs_tpl(y - v1.y) <= epsilon) && (fabs_tpl(z - v1.z) <= epsilon)); - } - ILINE bool IsInRangePI() const - { - F pi = (F)(gf_PI + 0.001); //we need this to fix fp-precision problem - return ((x > -pi) && (x < pi) && (y > -pi) && (y < pi) && (z > -pi) && (z < pi)); - } - - //! Normalize angle to -pi and +pi range. - ILINE void RangePI() - { - const F modX = fmod(x + gf_PI, gf_PI2); - x = if_neg_else(modX, modX + gf_PI, modX - gf_PI); - - const F modY = fmod(y + gf_PI, gf_PI2); - y = if_neg_else(modY, modY + gf_PI, modY - gf_PI); - - const F modZ = fmod(z + gf_PI, gf_PI2); - z = if_neg_else(modZ, modZ + gf_PI, modZ - gf_PI); - } - - //! Convert unit Quat to Euler Angles (xyz). - template - explicit Ang3_tpl(const Quat_tpl& q) - { - assert(q.IsValid()); - y = F(asin_tpl(max((F)-1.0, min((F)1.0, -(q.v.x * q.v.z - q.w * q.v.y) * 2)))); - if (fabs_tpl(fabs_tpl(y) - (F)((F)g_PI * (F)0.5)) < (F)0.01) - { - x = F(0); - z = F(atan2_tpl(-2 * (q.v.x * q.v.y - q.w * q.v.z), 1 - (q.v.x * q.v.x + q.v.z * q.v.z) * 2)); - } - else - { - x = F(atan2_tpl((q.v.y * q.v.z + q.w * q.v.x) * 2, 1 - (q.v.x * q.v.x + q.v.y * q.v.y) * 2)); - z = F(atan2_tpl((q.v.x * q.v.y + q.w * q.v.z) * 2, 1 - (q.v.z * q.v.z + q.v.y * q.v.y) * 2)); - } - } - - //! Convert Matrix33 to Euler Angles (xyz). - template - explicit Ang3_tpl(const Matrix33_tpl& m) - { - assert(m.IsOrthonormalRH(0.001f)); - y = (F)asin_tpl(max((F)-1.0, min((F)1.0, -m.m20))); - if (fabs_tpl(fabs_tpl(y) - (F)((F)g_PI * (F)0.5)) < (F)0.01) - { - x = F(0); - z = F(atan2_tpl(-m.m01, m.m11)); - } - else - { - x = F(atan2_tpl(m.m21, m.m22)); - z = F(atan2_tpl(m.m10, m.m00)); - } - } - - //! Convert Matrix34 to Euler Angles (xyz). - template - explicit Ang3_tpl(const Matrix34_tpl& m) - { - assert(m.IsOrthonormalRH(0.001f)); - y = F(asin_tpl(max((F)-1.0, min((F)1.0, -m.m20)))); - if (fabs_tpl(fabs_tpl(y) - (F)((F)g_PI * (F)0.5)) < (F)0.01) - { - x = F(0); - z = F(atan2_tpl(-m.m01, m.m11)); - } - else - { - x = F(atan2_tpl(m.m21, m.m22)); - z = F(atan2_tpl(m.m10, m.m00)); - } - } - - //! Convert Matrix44 to Euler Angles (xyz). - template - explicit Ang3_tpl(const Matrix44_tpl& m) - { - assert(Matrix33(m).IsOrthonormalRH(0.001f)); - y = F(asin_tpl(max((F)-1.0, min((F)1.0, -m.m20)))); - if (fabs_tpl(fabs_tpl(y) - (F)((F)g_PI * (F)0.5)) < (F)0.01) - { - x = F(0); - z = F(atan2_tpl(-m.m01, m.m11)); - } - else - { - x = F(atan2_tpl(m.m21, m.m22)); - z = F(atan2_tpl(m.m10, m.m00)); - } - } - - template - static ILINE F CreateRadZ(const Vec2_tpl& v0, const Vec2_tpl& v1) - { - F cz = v0.x * v1.y - v0.y * v1.x; - F c = v0.x * v1.x + v0.y * v1.y; - return F(atan2_tpl(cz, c)); - } - - template - static ILINE F CreateRadZ(const Vec3_tpl& v0, const Vec3_tpl& v1) - { - F cz = v0.x * v1.y - v0.y * v1.x; - F c = v0.x * v1.x + v0.y * v1.y; - return F(atan2_tpl(cz, c)); - } - - template - ILINE static Ang3_tpl GetAnglesXYZ(const Quat_tpl& q) { return Ang3_tpl(q); } - template - ILINE void SetAnglesXYZ(const Quat_tpl& q) { *this = Ang3_tpl(q); } - - template - ILINE static Ang3_tpl GetAnglesXYZ(const Matrix33_tpl& m) { return Ang3_tpl(m); } - template - ILINE void SetAnglesXYZ(const Matrix33_tpl& m) { *this = Ang3_tpl(m); } - - template - ILINE static Ang3_tpl GetAnglesXYZ(const Matrix34_tpl& m) { return Ang3_tpl(m); } - template - ILINE void SetAnglesXYZ(const Matrix34_tpl& m) { *this = Ang3_tpl(m); } - - //--------------------------------------------------------------- - ILINE F& operator [] (int index) { assert(index >= 0 && index <= 2); return ((F*)this)[index]; } - ILINE F operator [] (int index) const { assert(index >= 0 && index <= 2); return ((F*)this)[index]; } - - - bool IsValid() const - { - if (!NumberValid(x)) - { - return false; - } - if (!NumberValid(y)) - { - return false; - } - if (!NumberValid(z)) - { - return false; - } - return true; - } - - AUTO_STRUCT_INFO -}; - -typedef Ang3_tpl Ang3; -typedef Ang3_tpl Ang3r; -typedef Ang3_tpl Ang3_f64; - -//--------------------------------------- - -//vector addition -template -ILINE Ang3_tpl operator + (const Ang3_tpl& v0, const Ang3_tpl& v1) -{ - return Ang3_tpl(v0.x + v1.x, v0.y + v1.y, v0.z + v1.z); -} -//vector subtraction -template -ILINE Ang3_tpl operator - (const Ang3_tpl& v0, const Ang3_tpl& v1) -{ - return Ang3_tpl(v0.x - v1.x, v0.y - v1.y, v0.z - v1.z); -} - -//--------------------------------------- - -//vector self-addition -template -ILINE Ang3_tpl& operator += (Ang3_tpl& v0, const Ang3_tpl& v1) -{ - v0 = v0 + v1; - return v0; -} -//vector self-subtraction -template -ILINE Ang3_tpl& operator -= (Ang3_tpl& v0, const Ang3_tpl& v1) -{ - v0 = v0 - v1; - return v0; -} - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// struct CAngleAxis -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -template -struct AngleAxis_tpl -{ - //! storage for the Angle&Axis coordinates. - F angle; - Vec3_tpl axis; - - // default quaternion constructor - AngleAxis_tpl(void) { }; - AngleAxis_tpl(F a, F ax, F ay, F az) { angle = a; axis.x = ax; axis.y = ay; axis.z = az; } - AngleAxis_tpl(F a, const Vec3_tpl& n) { angle = a; axis = n; } - void operator () (F a, const Vec3_tpl& n) { angle = a; axis = n; } - AngleAxis_tpl(const AngleAxis_tpl& aa); //CAngleAxis aa=angleaxis - const Vec3_tpl operator * (const Vec3_tpl& v) const; - - AngleAxis_tpl(const Quat_tpl& q) - { - angle = acos_tpl(q.w) * 2; - axis = q.v; - axis.Normalize(); - F s = sin_tpl(angle * (F)0.5); - if (s == 0) - { - angle = 0; - axis.x = 0; - axis.y = 0; - axis.z = 1; - } - } -}; - -typedef AngleAxis_tpl AngleAxis; -typedef AngleAxis_tpl AngleAxis_f64; - -template -ILINE const Vec3_tpl AngleAxis_tpl::operator * (const Vec3_tpl& v) const -{ - Vec3_tpl origin = axis * (axis | v); - return origin + (v - origin) * cos_tpl(angle) + (axis % v) * sin_tpl(angle); -} - - - - - - - - - - - - - - - - - -////////////////////////////////////////////////////////////////////// -template -struct Plane_tpl -{ - //plane-equation: n.x*x + n.y*y + n.z*z + d > 0 is in front of the plane - Vec3_tpl n; //!< normal - F d; //!< distance - - //---------------------------------------------------------------- - -#if defined(_DEBUG) - ILINE Plane_tpl() - { - if constexpr (sizeof(F) == 4) - { - uint32* p = alias_cast(&n.x); - p[0] = F32NAN; - p[1] = F32NAN; - p[2] = F32NAN; - p[3] = F32NAN; - } - if constexpr (sizeof(F) == 8) - { - uint64* p = alias_cast(&n.x); - p[0] = F64NAN; - p[1] = F64NAN; - p[2] = F64NAN; - p[3] = F64NAN; - } - } -#else - ILINE Plane_tpl() {}; -#endif - - - ILINE Plane_tpl(const Plane_tpl& p) { n = p.n; d = p.d; } - ILINE Plane_tpl(const Vec3_tpl& normal, const F& distance) { n = normal; d = distance; } - - //! set normal and dist for this plane and then calculate plane type - ILINE void Set(const Vec3_tpl& vNormal, const F fDist) - { - n = vNormal; - d = fDist; - } - - ILINE void SetPlane(const Vec3_tpl& normal, const Vec3_tpl& point) - { - n = normal; - d = -(point | normal); - } - ILINE static Plane_tpl CreatePlane(const Vec3_tpl& normal, const Vec3_tpl& point) - { - return Plane_tpl(normal, -(point | normal)); - } - - ILINE Plane_tpl operator - (void) const { return Plane_tpl(-n, -d); } - - /*! - * Constructs the plane by tree given Vec3s (=triangle) with a right-hand (anti-clockwise) winding - * - * Example 1: - * Vec3 v0(1,2,3),v1(4,5,6),v2(6,5,6); - * Plane_tpl plane; - * plane.SetPlane(v0,v1,v2); - * - * Example 2: - * Vec3 v0(1,2,3),v1(4,5,6),v2(6,5,6); - * Plane_tpl plane=Plane_tpl::CreatePlane(v0,v1,v2); - */ - ILINE void SetPlane(const Vec3_tpl& v0, const Vec3_tpl& v1, const Vec3_tpl& v2) - { - n = ((v1 - v0) % (v2 - v0)).GetNormalized(); //vector cross-product - d = -(n | v0); //calculate d-value - } - ILINE static Plane_tpl CreatePlane(const Vec3_tpl& v0, const Vec3_tpl& v1, const Vec3_tpl& v2) - { - Plane_tpl p; - p.SetPlane(v0, v1, v2); - return p; - } - - /*! - * Computes signed distance from point to plane. - * This is the standard plane-equation: d=Ax*By*Cz+D. - * The normal-vector is assumed to be normalized. - * - * Example: - * Vec3 v(1,2,3); - * Plane_tpl plane=CalculatePlane(v0,v1,v2); - * f32 distance = plane|v; - */ - ILINE F operator | (const Vec3_tpl& point) const { return (n | point) + d; } - ILINE F DistFromPlane(const Vec3_tpl& vPoint) const { return (n * vPoint + d); } - - ILINE Plane_tpl operator - (const Plane_tpl& p) const { return Plane_tpl(n - p.n, d - p.d); } - ILINE Plane_tpl operator + (const Plane_tpl& p) const { return Plane_tpl(n + p.n, d + p.d); } - ILINE void operator -= (const Plane_tpl& p) { d -= p.d; n -= p.n; } - ILINE Plane_tpl operator * (F s) const { return Plane_tpl(n * s, d * s); } - ILINE Plane_tpl operator / (F s) const { return Plane_tpl(n / s, d / s); } - - //! check for equality between two planes - friend bool operator ==(const Plane_tpl& p1, const Plane_tpl& p2) - { - if (fabsf(p1.n.x - p2.n.x) > 0.0001f) - { - return (false); - } - if (fabsf(p1.n.y - p2.n.y) > 0.0001f) - { - return (false); - } - if (fabsf(p1.n.z - p2.n.z) > 0.0001f) - { - return (false); - } - if (fabsf(p1.d - p2.d) < 0.01f) - { - return(true); - } - return (false); - } - - Vec3_tpl MirrorVector(const Vec3_tpl& i) { return n * (2 * (n | i)) - i; } - Vec3_tpl MirrorPosition(const Vec3_tpl& i) { return i - n * (2 * ((n | i) + d)); } - - ILINE bool IsValid() const { return !n.IsZeroFast(); } //A plane with a zero normal isn't valid. - - AUTO_STRUCT_INFO -}; - -typedef Plane_tpl Plane; //always 32 bit -typedef Plane_tpl Planed;//always 64 bit -typedef Plane_tpl Planer;//variable float precision. depending on the target system it can be between 32, 64 or 80 bit - - -// declare common constants. Must be done after the class for compiler conformance -// (msvc and clang handle instantiation differently) -const Vec3_tpl Vec3_Zero(0, 0, 0); -const Vec3_tpl Vec3_OneX(1, 0, 0); -const Vec3_tpl Vec3_OneY(0, 1, 0); -const Vec3_tpl Vec3_OneZ(0, 0, 1); -const Vec3_tpl Vec3_One(1, 1, 1); - -namespace AZ -{ - AZ_TYPE_INFO_SPECIALIZE(Vec3, "{DFA993FB-4E92-4A13-BDB3-4E9285A5346F}"); -} -#endif // CRYINCLUDE_CRYCOMMON_CRY_VECTOR3_H diff --git a/Code/CryEngine/CryCommon/Cry_Vector4.h b/Code/CryEngine/CryCommon/Cry_Vector4.h deleted file mode 100644 index 90354ab6f1..0000000000 --- a/Code/CryEngine/CryCommon/Cry_Vector4.h +++ /dev/null @@ -1,279 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Common vector class - - -#pragma once - - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -// class Vec4_tpl -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// - -template -struct Vec4_tpl -{ - typedef F value_type; - enum - { - component_count = 4 - }; - - F x, y, z, w; - -#if defined(_DEBUG) - ILINE Vec4_tpl() - { - if constexpr (sizeof(F) == 4) - { - uint32* p = alias_cast(&x); - p[0] = F32NAN; - p[1] = F32NAN; - p[2] = F32NAN; - p[3] = F32NAN; - } - if constexpr (sizeof(F) == 8) - { - uint64* p = alias_cast(&x); - p[0] = F64NAN; - p[1] = F64NAN; - p[2] = F64NAN; - p[3] = F64NAN; - } - } -#else - ILINE Vec4_tpl() {} -#endif - - template - ILINE Vec4_tpl& operator = (const Vec4_tpl& v1) - { - x = F(v1.x); - y = F(v1.y); - z = F(v1.z); - w = F(v1.w); - return (*this); - } - - ILINE Vec4_tpl(F vx, F vy, F vz, F vw) { x = vx; y = vy; z = vz; w = vw; } - ILINE Vec4_tpl(const Vec3_tpl& v, F vw) { x = v.x; y = v.y; z = v.z; w = vw; } - explicit ILINE Vec4_tpl(F m) { x = y = z = w = m; } - ILINE Vec4_tpl(type_zero) { x = y = z = w = F(0); } - - ILINE void operator () (F vx, F vy, F vz, F vw) { x = vx; y = vy; z = vz; w = vw; } - ILINE void operator () (const Vec3_tpl& v, F vw) { x = v.x; y = v.y; z = v.z; w = vw; } - - ILINE F& operator [] (int index) { assert(index >= 0 && index <= 3); return ((F*)this)[index]; } - ILINE F operator [] (int index) const { assert(index >= 0 && index <= 3); return ((F*)this)[index]; } - template - ILINE Vec4_tpl(const Vec4_tpl& v) - : x((F)v.x) - , y((F)v.y) - , z((F)v.z) - , w((F)v.w) { assert(this->IsValid()); } - - ILINE Vec4_tpl& zero() { x = y = z = w = 0; return *this; } - - ILINE bool IsEquivalent(const Vec4_tpl& v1, F epsilon = VEC_EPSILON) const - { - assert(v1.IsValid()); - assert(this->IsValid()); - return ((fabs_tpl(x - v1.x) <= epsilon) && (fabs_tpl(y - v1.y) <= epsilon) && (fabs_tpl(z - v1.z) <= epsilon) && (fabs_tpl(w - v1.w) <= epsilon)); - } - - - ILINE Vec4_tpl& operator=(const Vec4_tpl& src) - { - x = src.x; - y = src.y; - z = src.z; - w = src.w; - return *this; - } - - ILINE Vec4_tpl operator * (F k) const - { - return Vec4_tpl(x * k, y * k, z * k, w * k); - } - ILINE Vec4_tpl operator / (F k) const - { - k = (F)1.0 / k; - return Vec4_tpl(x * k, y * k, z * k, w * k); - } - - ILINE Vec4_tpl& operator *= (F k) - { - x *= k; - y *= k; - z *= k; - w *= k; - return *this; - } - ILINE Vec4_tpl& operator /= (F k) - { - k = (F)1.0 / k; - x *= k; - y *= k; - z *= k; - w *= k; - return *this; - } - - ILINE void operator += (const Vec4_tpl& v) - { - x += v.x; - y += v.y; - z += v.z; - w += v.w; - } - - ILINE void operator -= (const Vec4_tpl& v) - { - x -= v.x; - y -= v.y; - z -= v.z; - w -= v.w; - } - - - ILINE F Dot (const Vec4_tpl& vec2) const - { - return x * vec2.x + y * vec2.y + z * vec2.z + w * vec2.w; - } - - ILINE F GetLength() const - { - return sqrt_tpl(Dot(*this)); - } - - ILINE F GetLengthSquared() const - { - return Dot(*this); - } - - - bool IsValid() const - { - if (!NumberValid(x)) - { - return false; - } - if (!NumberValid(y)) - { - return false; - } - if (!NumberValid(z)) - { - return false; - } - if (!NumberValid(w)) - { - return false; - } - return true; - } - - /*! - * functions and operators to compare vector - * - * Example: - * if (v0==v1) dosomething; - */ - ILINE bool operator==(const Vec4_tpl& vec) - { - return x == vec.x && y == vec.y && z == vec.z && w == vec.w; - } - ILINE bool operator!=(const Vec4_tpl& vec) { return !(*this == vec); } - - ILINE friend bool operator ==(const Vec4_tpl& v0, const Vec4_tpl& v1) - { - return ((v0.x == v1.x) && (v0.y == v1.y) && (v0.z == v1.z) && (v0.w == v1.w)); - } - ILINE friend bool operator !=(const Vec4_tpl& v0, const Vec4_tpl& v1) { return !(v0 == v1); } - - //! normalize the vector - // The default Normalize function is in fact "safe". 0 vectors remain unchanged. - ILINE void Normalize() - { - assert(this->IsValid()); - F fInvLen = isqrt_safe_tpl(x * x + y * y + z * z + w * w); - x *= fInvLen; - y *= fInvLen; - z *= fInvLen; - w *= fInvLen; - } - - //! may be faster and less accurate - ILINE void NormalizeFast() - { - assert(this->IsValid()); - F fInvLen = isqrt_fast_tpl(x * x + y * y + z * z + w * w); - x *= fInvLen; - y *= fInvLen; - z *= fInvLen; - w *= fInvLen; - } - - ILINE void SetLerp(const Vec4_tpl& p, const Vec4_tpl& q, F t) { *this = p * (1.0f - t) + q * t; } - ILINE static Vec4_tpl CreateLerp(const Vec4_tpl& p, const Vec4_tpl& q, F t) { return p * (1.0f - t) + q * t; } - - AUTO_STRUCT_INFO -}; - - -typedef Vec4_tpl Vec4; // always 32 bit -typedef Vec4_tpl Vec4d; // always 64 bit -typedef Vec4_tpl Vec4i; -typedef Vec4_tpl Vec4ui; -typedef Vec4_tpl Vec4r; // variable float precision. depending on the target system it can be 32, 64 or 80 bit - -#if defined(WIN32) || defined(WIN64) || defined(LINUX) || defined(APPLE) -typedef Vec4_tpl Vec4A; -#elif defined(AZ_RESTRICTED_PLATFORM) - #include AZ_RESTRICTED_FILE(Cry_Vector4_h) -#endif - -//vector self-addition -template -ILINE Vec4_tpl& operator += (Vec4_tpl& v0, const Vec4_tpl& v1) -{ - v0 = v0 + v1; - return v0; -} - -//vector addition -template -ILINE Vec4_tpl operator + (const Vec4_tpl& v0, const Vec4_tpl& v1) -{ - return Vec4_tpl(v0.x + v1.x, v0.y + v1.y, v0.z + v1.z, v0.w + v1.w); -} -//vector subtraction -template -ILINE Vec4_tpl operator - (const Vec4_tpl& v0, const Vec4_tpl& v1) -{ - return Vec4_tpl(v0.x - v1.x, v0.y - v1.y, v0.z - v1.z, v0.w - v1.w); -} - -//vector multiplication -template -ILINE Vec4_tpl operator * (const Vec4_tpl v0, const Vec4_tpl& v1) -{ - return Vec4_tpl(v0.x * v1.x, v0.y * v1.y, v0.z * v1.z, v0.w * v1.w); -} - -//vector division -template -ILINE Vec4_tpl operator / (const Vec4_tpl& v0, const Vec4_tpl& v1) -{ - return Vec4_tpl(v0.x / v1.x, v0.y / v1.y, v0.z / v1.z, v0.w / v1.w); -} diff --git a/Code/CryEngine/CryCommon/Cry_XOptimise.h b/Code/CryEngine/CryCommon/Cry_XOptimise.h deleted file mode 100644 index 02d91e39ac..0000000000 --- a/Code/CryEngine/CryCommon/Cry_XOptimise.h +++ /dev/null @@ -1,565 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Misc mathematical functions - - -#ifndef CRYINCLUDE_CRYCOMMON_CRY_XOPTIMISE_H -#define CRYINCLUDE_CRYCOMMON_CRY_XOPTIMISE_H -#pragma once - -#include - - - - -inline float AngleMod(float a) -{ - a = (float)((360.0 / 65536) * ((int)(a * (65536 / 360.0)) & 65535)); - return a; -} - -inline float AngleModRad(float a) -{ - a = (float)((gf_PI2 / 65536) * ((int)(a * (65536 / gf_PI2)) & 65535)); - return a; -} -inline unsigned short Degr2Word(float f) -{ - return (unsigned short)(AngleMod(f) / 360.0f * 65536.0f); -} -inline float Word2Degr(unsigned short s) -{ - return (float)s / 65536.0f * 360.0f; -} - -#if defined(_CPU_X86) -ILINE float __fastcall Ffabs(float f) -{ - *((unsigned*) &f) &= ~0x80000000; - return (f); -} -#else -inline float Ffabs(float x) { return fabsf(x); } -#endif - - - -#define mathMatrixRotationZ(pOut, angle) (*(Matrix44*)pOut) = GetTransposed44(Matrix44(Matrix34::CreateRotationZ(angle))) -#define mathMatrixRotationY(pOut, angle) (*(Matrix44*)pOut) = GetTransposed44(Matrix44(Matrix34::CreateRotationY(angle))) -#define mathMatrixRotationX(pOut, angle) (*(Matrix44*)pOut) = GetTransposed44(Matrix44(Matrix34::CreateRotationX(angle))) -#define mathMatrixTranslation(pOut, x, y, z) (*(Matrix44*)pOut) = GetTransposed44(Matrix44(Matrix34::CreateTranslationMat(Vec3(x, y, z)))) -#define mathMatrixScaling(pOut, sx, sy, sz) (*(Matrix44*)pOut) = GetTransposed44(Matrix44(Matrix34::CreateScale(Vec3(sx, sy, sz)))) - -template -inline void ExchangeVals(T& X, T& Y) -{ - const T Tmp = X; - X = Y; - Y = Tmp; -} - - -inline void mathMatrixPerspectiveFov(Matrix44A* pMatr, f32 fovY, f32 Aspect, f32 zn, f32 zf) -{ - f32 yScale = 1.0f / tan_tpl(fovY / 2.0f); - f32 xScale = yScale / Aspect; - - f32 m22 = f32(f64(zf) / (f64(zn) - f64(zf))); - f32 m32 = f32(f64(zn) * f64(zf) / (f64(zn) - f64(zf))); - - (*pMatr)(0, 0) = xScale; - (*pMatr)(0, 1) = 0; - (*pMatr)(0, 2) = 0; - (*pMatr)(0, 3) = 0; - (*pMatr)(1, 0) = 0; - (*pMatr)(1, 1) = yScale; - (*pMatr)(1, 2) = 0; - (*pMatr)(1, 3) = 0; - (*pMatr)(2, 0) = 0; - (*pMatr)(2, 1) = 0; - (*pMatr)(2, 2) = m22; - (*pMatr)(2, 3) = -1.0f; - (*pMatr)(3, 0) = 0; - (*pMatr)(3, 1) = 0; - (*pMatr)(3, 2) = m32; - (*pMatr)(3, 3) = 0; -} - - - -inline void mathMatrixOrtho(Matrix44A* pMatr, f32 w, f32 h, f32 zn, f32 zf) -{ - f32 m22 = f32(1.0 / (f64(zn) - f64(zf))); - f32 m32 = f32(f64(zn) / (f64(zn) - f64(zf))); - - (*pMatr)(0, 0) = 2.0f / w; - (*pMatr)(0, 1) = 0; - (*pMatr)(0, 2) = 0; - (*pMatr)(0, 3) = 0; - (*pMatr)(1, 0) = 0; - (*pMatr)(1, 1) = 2.0f / h; - (*pMatr)(1, 2) = 0; - (*pMatr)(1, 3) = 0; - (*pMatr)(2, 0) = 0; - (*pMatr)(2, 1) = 0; - (*pMatr)(2, 2) = m22; - (*pMatr)(2, 3) = 0; - (*pMatr)(3, 0) = 0; - (*pMatr)(3, 1) = 0; - (*pMatr)(3, 2) = m32; - (*pMatr)(3, 3) = 1; -} - -inline void mathMatrixOrthoOffCenter(Matrix44A* pMatr, f32 l, f32 r, f32 b, f32 t, f32 zn, f32 zf) -{ - f32 m22 = f32(1.0 / (f64(zn) - f64(zf))); - f32 m32 = f32(f64(zn) / (f64(zn) - f64(zf))); - - (*pMatr)(0, 0) = 2.0f / (r - l); - (*pMatr)(0, 1) = 0; - (*pMatr)(0, 2) = 0; - (*pMatr)(0, 3) = 0; - (*pMatr)(1, 0) = 0; - (*pMatr)(1, 1) = 2.0f / (t - b); - (*pMatr)(1, 2) = 0; - (*pMatr)(1, 3) = 0; - (*pMatr)(2, 0) = 0; - (*pMatr)(2, 1) = 0; - (*pMatr)(2, 2) = m22; - (*pMatr)(2, 3) = 0; - (*pMatr)(3, 0) = (l + r) / (l - r); - (*pMatr)(3, 1) = (t + b) / (b - t); - (*pMatr)(3, 2) = m32; - (*pMatr)(3, 3) = 1.0f; -} - - -inline void mathMatrixOrthoOffCenterLH(Matrix44A* pMatr, f32 l, f32 r, f32 b, f32 t, f32 zn, f32 zf) -{ - f32 m22 = f32(1.0 / (f64(zf) - f64(zn))); - f32 m32 = f32(f64(zn) / (f64(zn) - f64(zf))); - - (*pMatr)(0, 0) = 2.0f / (r - l); - (*pMatr)(0, 1) = 0; - (*pMatr)(0, 2) = 0; - (*pMatr)(0, 3) = 0; - (*pMatr)(1, 0) = 0; - (*pMatr)(1, 1) = 2.0f / (t - b); - (*pMatr)(1, 2) = 0; - (*pMatr)(1, 3) = 0; - (*pMatr)(2, 0) = 0; - (*pMatr)(2, 1) = 0; - (*pMatr)(2, 2) = m22; - (*pMatr)(2, 3) = 0; - (*pMatr)(3, 0) = (l + r) / (l - r); - (*pMatr)(3, 1) = (t + b) / (b - t); - (*pMatr)(3, 2) = m32; - (*pMatr)(3, 3) = 1.0f; -} - - -inline void mathMatrixPerspectiveOffCenter(Matrix44A* pMatr, f32 l, f32 r, f32 b, f32 t, f32 zn, f32 zf) -{ - f32 m22 = f32(f64(zf) / (f64(zn) - f64(zf))); - f32 m32 = f32(f64(zn) * f64(zf) / (f64(zn) - f64(zf))); - - (*pMatr)(0, 0) = 2 * zn / (r - l); - (*pMatr)(0, 1) = 0; - (*pMatr)(0, 2) = 0; - (*pMatr)(0, 3) = 0; - (*pMatr)(1, 0) = 0; - (*pMatr)(1, 1) = 2 * zn / (t - b); - (*pMatr)(1, 2) = 0; - (*pMatr)(1, 3) = 0; - (*pMatr)(2, 0) = (l + r) / (r - l); - (*pMatr)(2, 1) = (t + b) / (t - b); - (*pMatr)(2, 2) = m22; - (*pMatr)(2, 3) = -1; - (*pMatr)(3, 0) = 0; - (*pMatr)(3, 1) = 0; - (*pMatr)(3, 2) = m32; - (*pMatr)(3, 3) = 0; -} - -inline void mathMatrixPerspectiveOffCenterReverseDepth(Matrix44A* pMatr, f32 l, f32 r, f32 b, f32 t, f32 zn, f32 zf) -{ - f32 m22 = f32(-f64(zn) / (f64(zn) - f64(zf))); - f32 m32 = f32(-f64(zn) * f64(zf) / (f64(zn) - f64(zf))); - - (*pMatr)(0, 0) = 2 * zn / (r - l); - (*pMatr)(0, 1) = 0; - (*pMatr)(0, 2) = 0; - (*pMatr)(0, 3) = 0; - (*pMatr)(1, 0) = 0; - (*pMatr)(1, 1) = 2 * zn / (t - b); - (*pMatr)(1, 2) = 0; - (*pMatr)(1, 3) = 0; - (*pMatr)(2, 0) = (l + r) / (r - l); - (*pMatr)(2, 1) = (t + b) / (t - b); - (*pMatr)(2, 2) = m22; - (*pMatr)(2, 3) = -1; - (*pMatr)(3, 0) = 0; - (*pMatr)(3, 1) = 0; - (*pMatr)(3, 2) = m32; - (*pMatr)(3, 3) = 0; -} - -//RH -inline void mathMatrixLookAt(Matrix44A* pMatr, const Vec3& Eye, const Vec3& At, const Vec3& Up) -{ - Vec3 vLightDir = (Eye - At); - Vec3 zaxis = vLightDir.GetNormalized(); - Vec3 xaxis = (Up.Cross(zaxis)).GetNormalized(); - Vec3 yaxis = zaxis.Cross(xaxis); - - (*pMatr)(0, 0) = xaxis.x; - (*pMatr)(0, 1) = yaxis.x; - (*pMatr)(0, 2) = zaxis.x; - (*pMatr)(0, 3) = 0; - (*pMatr)(1, 0) = xaxis.y; - (*pMatr)(1, 1) = yaxis.y; - (*pMatr)(1, 2) = zaxis.y; - (*pMatr)(1, 3) = 0; - (*pMatr)(2, 0) = xaxis.z; - (*pMatr)(2, 1) = yaxis.z; - (*pMatr)(2, 2) = zaxis.z; - (*pMatr)(2, 3) = 0; - (*pMatr)(3, 0) = -xaxis.Dot(Eye); - (*pMatr)(3, 1) = -yaxis.Dot(Eye); - (*pMatr)(3, 2) = -zaxis.Dot(Eye); - (*pMatr)(3, 3) = 1; -} - -inline bool mathMatrixPerspectiveFovInverse(Matrix44_tpl* pResult, const Matrix44A* pProjFov) -{ - if ((*pProjFov)(0, 1) == 0.0f && (*pProjFov)(0, 2) == 0.0f && (*pProjFov)(0, 3) == 0.0f && - (*pProjFov)(1, 0) == 0.0f && (*pProjFov)(1, 2) == 0.0f && (*pProjFov)(1, 3) == 0.0f && - (*pProjFov)(3, 0) == 0.0f && (*pProjFov)(3, 1) == 0.0f && (*pProjFov)(3, 2) != 0.0f) - { - (*pResult)(0, 0) = 1.0 / (*pProjFov).m00; - (*pResult)(0, 1) = 0; - (*pResult)(0, 2) = 0; - (*pResult)(0, 3) = 0; - (*pResult)(1, 0) = 0; - (*pResult)(1, 1) = 1.0 / (*pProjFov).m11; - (*pResult)(1, 2) = 0; - (*pResult)(1, 3) = 0; - (*pResult)(2, 0) = 0; - (*pResult)(2, 1) = 0; - (*pResult)(2, 2) = 0; - (*pResult)(2, 3) = 1.0 / (*pProjFov).m32; - (*pResult)(3, 0) = (*pProjFov).m20 / (*pProjFov).m00; - (*pResult)(3, 1) = (*pProjFov).m21 / (*pProjFov).m11; - (*pResult)(3, 2) = -1; - (*pResult)(3, 3) = (*pProjFov).m22 / (*pProjFov).m32; - - return true; - } - - return false; -} - -template -inline void mathMatrixLookAtInverse(Matrix44_tpl* pResult, const Matrix44_tpl* pLookAt) -{ - (*pResult)(0, 0) = (*pLookAt).m00; - (*pResult)(0, 1) = (*pLookAt).m10; - (*pResult)(0, 2) = (*pLookAt).m20; - (*pResult)(0, 3) = (*pLookAt).m03; - (*pResult)(1, 0) = (*pLookAt).m01; - (*pResult)(1, 1) = (*pLookAt).m11; - (*pResult)(1, 2) = (*pLookAt).m21; - (*pResult)(1, 3) = (*pLookAt).m13; - (*pResult)(2, 0) = (*pLookAt).m02; - (*pResult)(2, 1) = (*pLookAt).m12; - (*pResult)(2, 2) = (*pLookAt).m22; - (*pResult)(2, 3) = (*pLookAt).m23; - - (*pResult)(3, 0) = T_out(-(f64((*pLookAt).m00) * f64((*pLookAt).m30) + f64((*pLookAt).m01) * f64((*pLookAt).m31) + f64((*pLookAt).m02) * f64((*pLookAt).m32))); - (*pResult)(3, 1) = T_out(-(f64((*pLookAt).m10) * f64((*pLookAt).m30) + f64((*pLookAt).m11) * f64((*pLookAt).m31) + f64((*pLookAt).m12) * f64((*pLookAt).m32))); - (*pResult)(3, 2) = T_out(-(f64((*pLookAt).m20) * f64((*pLookAt).m30) + f64((*pLookAt).m21) * f64((*pLookAt).m31) + f64((*pLookAt).m22) * f64((*pLookAt).m32))); - (*pResult)(3, 3) = (*pLookAt).m33; -}; - -inline void mathVec4Transform(f32 out[4], const f32 m[16], const f32 in[4]) -{ -#define M(row, col) m[col * 4 + row] - out[0] = M(0, 0) * in[0] + M(0, 1) * in[1] + M(0, 2) * in[2] + M(0, 3) * in[3]; - out[1] = M(1, 0) * in[0] + M(1, 1) * in[1] + M(1, 2) * in[2] + M(1, 3) * in[3]; - out[2] = M(2, 0) * in[0] + M(2, 1) * in[1] + M(2, 2) * in[2] + M(2, 3) * in[3]; - out[3] = M(3, 0) * in[0] + M(3, 1) * in[1] + M(3, 2) * in[2] + M(3, 3) * in[3]; -#undef M -} - -//fix: replace by 3x4 Matrix transformation and move to crymath -inline void mathVec3Transform(f32 out[4], const f32 m[16], const f32 in[3]) -{ -#define M(row, col) m[col * 4 + row] - out[0] = M(0, 0) * in[0] + M(0, 1) * in[1] + M(0, 2) * in[2] + M(0, 3) * 1.0f; - out[1] = M(1, 0) * in[0] + M(1, 1) * in[1] + M(1, 2) * in[2] + M(1, 3) * 1.0f; - out[2] = M(2, 0) * in[0] + M(2, 1) * in[1] + M(2, 2) * in[2] + M(2, 3) * 1.0f; - out[3] = M(3, 0) * in[0] + M(3, 1) * in[1] + M(3, 2) * in[2] + M(3, 3) * 1.0f; -#undef M -} - -#define mathVec3TransformF(pOut, pV, pM) mathVec3Transform((f32*)pOut, (const f32*)pM, (f32*)pV) -#define mathVec4TransformF(pOut, pV, pM) mathVec4Transform((f32*)pOut, (const f32*)pM, (f32*)pV) -#define mathVec3NormalizeF(pOut, pV) (*(Vec3*)pOut) = (((Vec3*)pV)->GetNormalizedSafe()) -#define mathVec2NormalizeF(pOut, pV) (*(Vec2*)pOut) = (((Vec2*)pV)->GetNormalizedSafe()) - - -//fix replace viewport by int16 array -//fix for d3d viewport -inline f32 mathVec3Project(Vec3* pvWin, const Vec3* pvObj, const int32 pViewport[4], const Matrix44A* pProjection, const Matrix44A* pView, const Matrix44A* pWorld) -{ - Vec4 in, out; - - in.x = pvObj->x; - in.y = pvObj->y; - in.z = pvObj->z; - in.w = 1.0f; - mathVec4Transform((f32*)&out, (f32*)pWorld, (f32*)&in); - mathVec4Transform((f32*)&in, (f32*)pView, (f32*)&out); - mathVec4Transform((f32*)&out, (f32*)pProjection, (f32*)&in); - - if (out.w == 0.0f) - { - return 0.f; - } - - out.x /= out.w; - out.y /= out.w; - out.z /= out.w; - - //output coords - pvWin->x = pViewport[0] + (1 + out.x) * pViewport[2] / 2; - pvWin->y = pViewport[1] + (1 - out.y) * pViewport[3] / 2; //flip coords for y axis - - //FIX: update fViewportMinZ fViewportMaxZ support for Viewport everywhere - float fViewportMinZ = 0, fViewportMaxZ = 1.0f; - - pvWin->z = fViewportMinZ + out.z * (fViewportMaxZ - fViewportMinZ); - - return out.w; -} - -inline Vec3* mathVec3UnProject(Vec3* pvObj, const Vec3* pvWin, const int32 pViewport[4], const Matrix44A* pProjection, const Matrix44A* pView, const Matrix44A* pWorld, [[maybe_unused]] int32 OptFlags) -{ - Matrix44A m, mA; - Vec4 in, out; - - //FIX: update fViewportMinZ fViewportMaxZ support for Viewport everywhere - float fViewportMinZ = 0, fViewportMaxZ = 1.0f; - - in.x = (pvWin->x - pViewport[0]) * 2 / pViewport[2] - 1.0f; - in.y = 1.0f - ((pvWin->y - pViewport[1]) * 2 / pViewport[3]); //flip coords for y axis - in.z = (pvWin->z - fViewportMinZ) / (fViewportMaxZ - fViewportMinZ); - in.w = 1.0f; - - //prepare inverse projection matrix - mA = ((*pWorld) * (*pView)) * (*pProjection); - m = mA.GetInverted(); - - mathVec4Transform((f32*)&out, m.GetData(), (f32*)&in); - if (out.w == 0.0f) - { - return NULL; - } - - pvObj->x = out.x / out.w; - pvObj->y = out.y / out.w; - pvObj->z = out.z / out.w; - - return pvObj; -} - - -inline Vec3* mathVec3ProjectArray(Vec3* pOut, uint32 OutStride, const Vec3* pV, uint32 VStride, const int32 pViewport[4], const Matrix44A* pProjection, const Matrix44A* pView, const Matrix44A* pWorld, uint32 n, int32) -{ - Matrix44A m; - Vec4 in, out; - - int8* pOutT = (int8*)pOut; - int8* pInT = (int8*)pV; - - Vec3* pvWin; - Vec3* pvObj; - - //FIX: update fViewportMinZ fViewportMaxZ support for Viewport everywhere - float fViewportMinZ = 0, fViewportMaxZ = 1.0f; - - m = ((*pWorld) * (*pView)) * (*pProjection); - - for (uint32 i = 0; i < n; i++) - { - pvObj = (Vec3*)pInT; - pvWin = (Vec3*)pOutT; - - in.x = pvObj->x; - in.y = pvObj->y; - in.z = pvObj->z; - in.w = 1.0f; - - mathVec4Transform((f32*)&out, m.GetData(), (f32*)&in); - - if (out.w == 0.0f) - { - return NULL; - } - - float fInvW = 1.0f / out.w; - out.x *= fInvW; - out.y *= fInvW; - out.z *= fInvW; - - //output coords - pvWin->x = pViewport[0] + (1 + out.x) * pViewport[2] / 2; - pvWin->y = pViewport[1] + (1 - out.y) * pViewport[3] / 2; //flip coords for y axis - - pvWin->z = fViewportMinZ + out.z * (fViewportMaxZ - fViewportMinZ); - - pOutT += OutStride; - pInT += VStride; - } - - return pOut; -} - - -inline Vec3* mathVec3UnprojectArray(Vec3* pOut, uint32 OutStride, const Vec3* pV, uint32 VStride, const int32 pViewport[4], const Matrix44* pProjection, const Matrix44* pView, const Matrix44* pWorld, uint32 n, [[maybe_unused]] int32 OptFlags) -{ - Vec4 in, out; - Matrix44 m, mA; - - int8* pOutT = (int8*)pOut; - int8* pInT = (int8*)pV; - - Vec3* pvWin; - Vec3* pvObj; - - //FIX: update fViewportMinZ fViewportMaxZ support for Viewport everywhere - float fViewportMinZ = 0, fViewportMaxZ = 1.0f; - - mA = ((*pWorld) * (*pView)) * (*pProjection); - m = mA.GetInverted(); - - for (uint32 i = 0; i < n; i++) - { - pvWin = (Vec3*)pInT; - pvObj = (Vec3*)pOutT; - - in.x = (pvWin->x - pViewport[0]) * 2 / pViewport[2] - 1.0f; - in.y = 1.0f - ((pvWin->y - pViewport[1]) * 2 / pViewport[3]); //flip coords for y axis - in.z = (pvWin->z - fViewportMinZ) / (fViewportMaxZ - fViewportMinZ); - in.w = 1.0f; - - mathVec4Transform((f32*)&out, m.GetData(), (f32*)&in); - - assert(out.w != 0.0f); - - if (out.w == 0.0f) - { - return NULL; - } - - pvObj->x = out.x / out.w; - pvObj->y = out.y / out.w; - pvObj->z = out.z / out.w; - - pOutT += OutStride; - pInT += VStride; - } - - return pOut; -} - - - - -/***************************************************** -MISC FUNCTIONS -*****************************************************/ - -////////////////////////////////////////////////////////////////////////// -#if defined(_CPU_X86) -inline int fastftol_positive(float f) -{ - int i; - - f -= 0.5f; -#if defined(_MSC_VER) - __asm fld [f] - __asm fistp [i] -#elif defined(__GNUC__) - __asm__ ("fld %[f]\n fistpl %[i]" : [i] "+m" (i) : [f] "m" (f)); -#else -#error -#endif - return i; -} -#else -inline int fastftol_positive (float f) -{ - assert(f >= 0.f); - return (int)floorf(f); -} -#endif - - - -////////////////////////////////////////////////////////////////////////// -#if defined(_CPU_X86) -inline int fastround_positive(float f) -{ - int i; - assert(f >= 0.f); -#if defined(_MSC_VER) - __asm fld [f] - __asm fistp [i] -#elif defined(__GNUC__) - __asm__ ("fld %[f]\n fistpl %[i]" : [i] "+m" (i) : [f] "m" (f)); -#else -#error -#endif - return i; -} -#else -inline int fastround_positive(float f) -{ - assert(f >= 0.f); - return (int) (f + 0.5f); -} -#endif - - - -////////////////////////////////////////////////////////////////////////// -#if defined(_CPU_X86) -ILINE int __fastcall FtoI(float x) -{ - int t; -#if defined(_MSC_VER) - __asm - { - fld x - fistp t - } -#elif defined(__GNUC__) - __asm__ ("fld %[x]\n fistpl %[t]" : [t] "+m" (t) : [x] "m" (x)); -#else -#error -#endif - return t; -} -#else -inline int FtoI(float x) { return (int)x; } -#endif - -#endif // CRYINCLUDE_CRYCOMMON_CRY_XOPTIMISE_H - diff --git a/Code/CryEngine/CryCommon/FrameProfiler.h b/Code/CryEngine/CryCommon/FrameProfiler.h deleted file mode 100644 index 4a8614b8c1..0000000000 --- a/Code/CryEngine/CryCommon/FrameProfiler.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include - -#define SUBSYSTEM_DEFINES \ - X(PROFILE_ANY, "Any") \ - X(PROFILE_RENDERER, "Renderer") \ - X(PROFILE_3DENGINE, "3DEngine") \ - X(PROFILE_PARTICLE, "Particle") \ - X(PROFILE_AI, "AI") \ - X(PROFILE_ANIMATION, "Animation") \ - X(PROFILE_MOVIE, "Movie") \ - X(PROFILE_ENTITY, "Entity") \ - X(PROFILE_UI, "UI") \ - X(PROFILE_NETWORK, "Network") \ - X(PROFILE_PHYSICS, "Physics") \ - X(PROFILE_SCRIPT, "Script") \ - X(PROFILE_SCRIPT_CFUNC, "Script C Functions") \ - X(PROFILE_AUDIO, "Audio") \ - X(PROFILE_EDITOR, "Editor") \ - X(PROFILE_SYSTEM, "System") \ - X(PROFILE_ACTION, "Action") \ - X(PROFILE_GAME, "Game") \ - X(PROFILE_INPUT, "Input") \ - X(PROFILE_SYNC, "Sync") \ - X(PROFILE_NETWORK_TRAFFIC, "Network Traffic") \ - X(PROFILE_DEVICE, "Device") - -#define X(Subsystem, SubsystemName) Subsystem, -enum EProfiledSubsystem -{ - SUBSYSTEM_DEFINES - PROFILE_LAST_SUBSYSTEM -}; -#undef X - -static_assert(static_cast(PROFILE_LAST_SUBSYSTEM) == AZ::Debug::ProfileCategory::LegacyLast, "Mismatched AZ and Legacy profile categories"); -#include - - - -#define FUNCTION_PROFILER_LEGACYONLY(pISystem, subsystem) - -#define FUNCTION_PROFILER(pISystem, subsystem) \ - AZ_PROFILE_FUNCTION(static_cast(subsystem)); - -#define FUNCTION_PROFILER_FAST(pISystem, subsystem, bProfileEnabled) \ - AZ_PROFILE_FUNCTION(static_cast(subsystem)); - -#define FUNCTION_PROFILER_ALWAYS(pISystem, subsystem) \ - AZ_PROFILE_FUNCTION(static_cast(subsystem)); - -#define FRAME_PROFILER_LEGACYONLY(szProfilerName, pISystem, subsystem) - -#define FRAME_PROFILER(szProfilerName, pISystem, subsystem) \ - AZ_PROFILE_SCOPE(static_cast(subsystem), szProfilerName); - -#define FRAME_PROFILER_FAST(szProfilerName, pISystem, subsystem, bProfileEnabled) \ - AZ_PROFILE_SCOPE(static_cast(subsystem), szProfilerName); - -#define FUNCTION_PROFILER_SYS(subsystem) \ - FUNCTION_PROFILER(gEnv->pSystem, PROFILE_##subsystem) - -#define STALL_PROFILER(cause) - diff --git a/Code/CryEngine/CryCommon/FunctorBaseFunction.h b/Code/CryEngine/CryCommon/FunctorBaseFunction.h deleted file mode 100644 index 42677bf194..0000000000 --- a/Code/CryEngine/CryCommon/FunctorBaseFunction.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Implementation of the common function template specializations. - - -#ifndef CRYINCLUDE_CRYCOMMON_FUNCTORBASEFUNCTION_H -#define CRYINCLUDE_CRYCOMMON_FUNCTORBASEFUNCTION_H -#pragma once - - -#include "IFunctorBase.h" - -////////////////////////////////////////////////////////////////////////// -// Return type void -// No arguments. -template<> -class TFunctor - : public IFunctorBase -{ -public: - typedef void (* TFunctionType)(); - - TFunctor(TFunctionType pFunction) - : m_pfnFunction(pFunction){} - - virtual void Call() - { - m_pfnFunction(); - } -private: - TFunctionType m_pfnFunction; -}; -////////////////////////////////////////////////////////////////////////// - - -////////////////////////////////////////////////////////////////////////// -// Return type void -// 1 argument. -template -class TFunctor - : public IFunctorBase -{ -public: - typedef void (* TFunctionType)(tArgument1); - - TFunctor(TFunctionType pFunction, tArgument1 Argument1) - : m_pfnFunction(pFunction) - , m_tArgument1(Argument1){} - - virtual void Call() - { - m_pfnFunction(m_tArgument1); - } -private: - TFunctionType m_pfnFunction; - tArgument1 m_tArgument1; -}; -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// Return type void -// 2 arguments. -template -class TFunctor - : public IFunctorBase -{ -public: - typedef void (* TFunctionType)(tArgument1, tArgument2); - - TFunctor(TFunctionType pFunction, const tArgument1& Argument1, const tArgument2& Argument2) - : m_pfnFunction(pFunction) - , m_tArgument1(Argument1) - , m_tArgument2(Argument2){} - - virtual void Call() - { - m_pfnFunction(m_tArgument1, m_tArgument2); - } -private: - TFunctionType m_pfnFunction; - tArgument1 m_tArgument1; - tArgument2 m_tArgument2; -}; -////////////////////////////////////////////////////////////////////////// - -#endif // CRYINCLUDE_CRYCOMMON_FUNCTORBASEFUNCTION_H diff --git a/Code/CryEngine/CryCommon/FunctorBaseMember.h b/Code/CryEngine/CryCommon/FunctorBaseMember.h deleted file mode 100644 index 1d85e7fff1..0000000000 --- a/Code/CryEngine/CryCommon/FunctorBaseMember.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Implementation of the member function template specializations. - -#ifndef CRYINCLUDE_CRYCOMMON_FUNCTORBASEMEMBER_H -#define CRYINCLUDE_CRYCOMMON_FUNCTORBASEMEMBER_H -#pragma once - - -#include "IFunctorBase.h" - -////////////////////////////////////////////////////////////////////////// -// Return type void -// No Arguments -template -class TFunctor - : public IFunctorBase -{ -public: - typedef void (tCalleeType::* TMemberFunctionType)(); - - TFunctor(tCalleeType* pCallee, TMemberFunctionType pMemberFunction) - : m_pCalee(pCallee) - , m_pfnMemberFunction(pMemberFunction){} - - virtual void Call() - { - (m_pCalee->*m_pfnMemberFunction)(); - } -private: - tCalleeType* m_pCalee; - TMemberFunctionType m_pfnMemberFunction; -}; -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// Return type void -// 1 argument. -template -class TFunctor - : public IFunctorBase -{ -public: - typedef void (tCalleeType::* TMemberFunctionType)(tArgument1); - - TFunctor(tCalleeType* pCallee, TMemberFunctionType pMemberFunction, const tArgument1& Argument1) - : m_pCalee(pCallee) - , m_pfnMemberFunction(pMemberFunction) - , m_tArgument1(Argument1){} - - virtual void Call() - { - (m_pCalee->*m_pfnMemberFunction)(m_tArgument1); - } -private: - tCalleeType* m_pCalee; - TMemberFunctionType m_pfnMemberFunction; - tArgument1 m_tArgument1; -}; -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// Return type void -// 2 arguments. -template -class TFunctor - : public IFunctorBase -{ -public: - typedef void (tCalleeType::* TMemberFunctionType)(tArgument1, tArgument2); - - TFunctor(tCalleeType* pCallee, TMemberFunctionType pMemberFunction, const tArgument1& Argument1, const tArgument2& Argument2) - : m_pCalee(pCallee) - , m_pfnMemberFunction(pMemberFunction) - , m_tArgument1(Argument1) - , m_tArgument2(Argument2){} - - virtual void Call() - { - (m_pCalee->*m_pfnMemberFunction)(m_tArgument1, m_tArgument2); - } -private: - tCalleeType* m_pCalee; - TMemberFunctionType m_pfnMemberFunction; - tArgument1 m_tArgument1; - tArgument2 m_tArgument2; -}; -////////////////////////////////////////////////////////////////////////// - -#endif // CRYINCLUDE_CRYCOMMON_FUNCTORBASEMEMBER_H diff --git a/Code/CryEngine/CryCommon/HMDBus.h b/Code/CryEngine/CryCommon/HMDBus.h deleted file mode 100644 index 3c92278c26..0000000000 --- a/Code/CryEngine/CryCommon/HMDBus.h +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -struct IRenderAuxGeom; - -namespace AZ -{ - namespace VR - { - /** - * Bus for reacting to events triggered by the VR systems - */ - class VREvents : public AZ::EBusTraits - { - public: - virtual ~VREvents() {} - - /** - * Event triggered when an HMD initializes successfully - */ - virtual void OnHMDInitialized() {} - - /** - * Event triggered when an HMD shuts down - */ - virtual void OnHMDShutdown() {} - }; - - using VREventBus = AZ::EBus; - - /// - /// Device initialization bus. Each HMD device SDK should connect to this bus during startup in order to be initialized by the LY engine. - /// Any devices that successfully initialize will be connected to the HMDDeviceBus for actual use in VR rendering. - /// - class HMDInitBus : public AZ::EBusTraits - { - public: - - virtual ~HMDInitBus() {} - - /// - /// Attempt to initialize this device. If initialization is initially successful (device exists and is able to startup) then this device should connect to the - /// HMDDeviceRequestBus in order to be used as an HMD from the main Open 3D Engine system. - /// - /// @return If true, initialization fully succeeded. - /// - virtual bool AttemptInit() = 0; - - /// - /// Shutdown this device and destroy any internal context/state information that it may contain. Once this function has returned, the device should be in a - /// totally clean state and able to re-initialized if necessary. - /// - virtual void Shutdown() = 0; - - /// - /// Priority values for the HMD to set. A higher priority value means that the HMD will be be initialized before - /// other HMDs with lower priority values. - /// - enum HMDInitPriority - { - kNullVR = -100, - kLowest = 0, - kMiddle = 50, - kHighest = 100 - }; - - /// - /// Specify the initialization priority for this HMD device. Typically SDKs that have only one device that they support (e.g. Oculus) should have the highest - /// priority so that other VR Gems don't take the device context. For example, OpenVR is capable of driving an Oculus Rift and if initialized first will control - /// the device as opposed to the Oculus runtime. - /// - virtual HMDInitPriority GetInitPriority() const = 0; - }; - - using HMDInitRequestBus = AZ::EBus; - - /// - /// HMD device bus used to communicate with the rest of the engine. Every device supported by the engine lives in its own GEM and supports this bus. A device - /// wraps the underlying SDK into a single object for easy use by the rest of the system. Every device created should register with the EBus in order to be picked up as - /// a usable device during initialization via the EBus function BusConnect(). - /// - class HMDDeviceBus - : public AZ::EBusTraits - { - public: - - ////////////////////////////////////////////////////////////////////////// - // EBus Traits - static const EBusHandlerPolicy HandlerPolicy = EBusHandlerPolicy::Multiple; - static const EBusAddressPolicy AddressPolicy = EBusAddressPolicy::Single; - using MutexType = AZStd::recursive_mutex; - ////////////////////////////////////////////////////////////////////////// - - virtual ~HMDDeviceBus() {} - - /// - /// Simple texture descriptor to pass to the device during render target creation. - /// - struct TextureDesc - { - uint32 width; - uint32 height; - }; - - /// - /// Get per-eye camera info from the device. The specific info to get is defined in the EyeCameraInfo struct. This function can be used to setup - /// rendering cameras per-eye. Note that each eye may have different projection matrix information. - /// - /// @param eye The specific eye to get camera data for. - /// @param nearPlane Near distance for the main render camera. - /// @param farPlane Far distance for the main render camera. - /// @param cameraInfo Returned camera information for this particular eye. - /// - virtual void GetPerEyeCameraInfo([[maybe_unused]] const EStereoEye eye, [[maybe_unused]] const float nearPlane, [[maybe_unused]] const float farPlane, [[maybe_unused]] PerEyeCameraInfo& cameraInfo) {} - - /// - /// Update the HMD's internal state and handle events - /// This is NOT where tracking is updated. This is for game-time - /// events such as controllers connecting/disconnecting or - /// certain compositor events being triggered. - /// - virtual void UpdateInternalState() {} - - /// - /// Create the render targets for a rendering device. Note that this will create all necessary render targets but the render targets will be destroyed one at a time in DestroyRenderTargets. - /// - /// @param renderDevice The render device to use when creating the render target. - /// @param desc TextureDesc object denoting texture options to use during creation. - /// @param eyeCount The number of HMDRenderTargets to be created in this function. - /// @param renderTargets Array of pointers to HMDRenderTargets of size eyeCount created upon successful return of this function. See struct RenderTarget for more info. - /// - /// @returns If true, the render targets were successfully created. - /// - virtual bool CreateRenderTargets([[maybe_unused]] void* renderDevice, [[maybe_unused]] const TextureDesc& desc, [[maybe_unused]] size_t eyeCount, [[maybe_unused]] HMDRenderTarget* renderTargets[]) { return false; } - - /// - /// Destroy the passed-in render target. Any device-specific texture data will be cleaned up after this function has finished executing. - /// - virtual void DestroyRenderTarget([[maybe_unused]] HMDRenderTarget& renderTarget) {} - - /// - /// Take care of any frame preparations that may be necessary BEFORE rendering begins on either eye. This could be things like synchronization, - /// clearing old state, etc. - /// - virtual void PrepareFrame() {} - - /// - /// Retrieve the latest tracking state that was cached since the last call - /// to UpdateTrackingStates. - /// - /// TODO: Differentiate between tracking states viable for rendering and - /// tracking states viable for game simulation. - /// - virtual TrackingState* GetTrackingState() { return nullptr; } - - /// - /// Per-eye target to submit to the device for final composition and rendering. - /// - struct EyeTarget - { - void* renderTarget; ///< The device render target. - Vec2i viewportPosition; ///< Position of the viewport pertaining to this render target. - Vec2i viewportSize; ///< Size of the viewport pertaining to this render target. - }; - - /// - /// Submit a new frame to the HMD device. Each eye should be fully rendered by this point. The device will automatically correlate the proper - /// tracking information with this frame. - /// - /// @param left A reference to the left EyeTarget to present - /// @param right A reference to the right EyeTarget to present - /// - virtual void SubmitFrame([[maybe_unused]] const EyeTarget& left, [[maybe_unused]] const EyeTarget& right) {} - - /// - /// Recent the current pose for the HMD based on the current direction that the viewer is looking. - /// - virtual void RecenterPose() {} - - /// - /// Set the current tracking level of the HMD. Supported tracking levels are defined in struct TrackingLevel. - /// - /// @param level The tracking level we want to use with this HMD - /// - virtual void SetTrackingLevel([[maybe_unused]] const AZ::VR::HMDTrackingLevel level) {} - - /// - /// Write any HMD info to the console/log file(s). At a minimum this function should print the info contained in the HMDDeviceInfo object. - /// - virtual void OutputHMDInfo() {} - - /// - /// Enable/disable debugging for this device. The device can decide what the most appropriate debugging information is - /// displayed to the user (e.g. HMD position, performance info, latency timing, etc.). - /// - /// @param enable Set to true to enable debugging - /// - virtual void EnableDebugging([[maybe_unused]] bool enable) {} - - /// - /// Draw any custom debug info for this device. This function is invoked by the HMDDebugger. - /// - /// @param transform Local to world-space transform. - /// @param auxGeom A pointer to the auxiliary geometry renderer - /// - virtual void DrawDebugInfo([[maybe_unused]] const AZ::Transform& transform, [[maybe_unused]] IRenderAuxGeom* auxGeom) {} - - /// - /// Get the device info object for this particular HMD. See struct HMDDeviceInfo for more details. - /// - /// @return A pointer to this HMD's HMDDeviceInfo struct - /// - virtual HMDDeviceInfo* GetDeviceInfo() { return nullptr; } - - /// - /// Get whether or not the HMD has been initialized. The HMD has been initialized when it has fully established an interface - /// with its necessary SDK and is ready to be used. - /// - /// @return True if the device has been initialized and is usable - /// - virtual bool IsInitialized() { return false; } - - /// - /// Get the play space of the device, if exists - /// - /// @return True if the device has been initialized and is usable - /// - virtual const Playspace* GetPlayspace() { return nullptr; } - - /// - /// Ask the HMD to update its internal tracking state; must be called once per frame. - /// Must be called from the render thread (the same thread that the device submits on). - /// This will calculate the internal tracking states fit for rendering the upcoming frame. - /// - virtual void UpdateTrackingStates() {} - - /// - /// Retrieves the current index into the VR system's swapchain that should be used. - /// This only really need to be overridden by VR implementations that keep track - /// of an internal swapchain like Oculus. OpenVR will handle swapchains - /// internally and can just return 0. - /// - virtual AZ::u32 GetSwapchainIndex([[maybe_unused]] const EStereoEye& eye) { return 0; } - - protected: - }; - - using HMDDeviceRequestBus = AZ::EBus; - - /// - /// Bus to define HMD debugging. This includes visualization of any HMD-specific objects as well as any - /// VR performance metrics displayed in the HMD. - /// - class HMDDebuggerBus - : public AZ::EBusTraits - { - public: - - virtual ~HMDDebuggerBus() {} - - /// - /// Enable/disable the debugger. - /// - /// @param enable Pass in true to enable info debugging - /// - virtual void EnableInfo(bool enable) = 0; - - /// - /// Enable/disable the camera debugger. - /// - /// @param enable Pass in true to enable camera debugging - /// - virtual void EnableCamera(bool enable) = 0; - }; - - using HMDDebuggerRequestBus = AZ::EBus; - - } // namespace VR -} // namespace AZ diff --git a/Code/CryEngine/CryCommon/HeapAllocator.h b/Code/CryEngine/CryCommon/HeapAllocator.h deleted file mode 100644 index a033c57287..0000000000 --- a/Code/CryEngine/CryCommon/HeapAllocator.h +++ /dev/null @@ -1,456 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_HEAPALLOCATOR_H -#define CRYINCLUDE_CRYCOMMON_HEAPALLOCATOR_H -#pragma once - - -#include "Synchronization.h" -#include "Options.h" - -#include - -//--------------------------------------------------------------------------- -#define bMEM_ACCESS_CHECK 0 -#define bMEM_HEAP_CHECK 0 - -namespace stl -{ - class HeapSysAllocator - { - public: - static void* SysAlloc(size_t nSize) - { return CryModuleMalloc(nSize); } - static void SysDealloc(void* ptr) - { CryModuleFree(ptr); } - }; - - class GlobalHeapSysAllocator - { - public: - static void* SysAlloc(size_t nSize) - { - return CryModuleMalloc(nSize); - } - static void SysDealloc(void* ptr) - { - CryModuleFree(ptr); - } - }; - - // Round up to next multiple of nAlign. Handles any positive integer. - inline size_t RoundUpTo(size_t nSize, size_t nAlign) - { - assert(nAlign > 0); - nSize += nAlign - 1; - return nSize - nSize % nAlign; - } - - /*--------------------------------------------------------------------------- - HeapAllocator - A memory pool that can allocate arbitrary amounts of memory of arbitrary size - and alignment. The heap may be freed all at once. Individual block deallocation - is not provided. - - Usable as a base class to implement more general-purpose allocators that - track, free, and reuse individual memory blocks. - - The class can optionally support multi-threading, using the second - template parameter. By default it is multithread-safe. - See Synchronization.h. - - Allocation details: Maintains a linked list of pages. - All pages after first are in order of most free memory first. - Allocations are from the smallest free page available. - - ---------------------------------------------------------------------------*/ - - struct SMemoryUsage - { - size_t nAlloc, nUsed; - - SMemoryUsage(size_t _nAlloc = 0, size_t _nUsed = 0) - : nAlloc(_nAlloc) - , nUsed(_nUsed) - { - Validate(); - } - - size_t nFree() const - { - return nAlloc - nUsed; - } - void Validate() const - { - assert(nUsed <= nAlloc); - } - void Clear() - { - nAlloc = nUsed = 0; - } - - void operator += (SMemoryUsage const& op) - { - nAlloc += op.nAlloc; - nUsed += op.nUsed; - } - }; - - ////////////////////////////////////////////////////////////////////////// - struct FHeap - { - OPT_STRUCT(FHeap) - OPT_VAR(size_t, PageSize); // Pages allocated at this size, or multiple thereof if needed. - OPT_VAR(bool, SinglePage) // Only 1 page allowed (fixed alloc) - OPT_VAR(bool, FreeWhenEmpty) // Release all memory when no longer used - }; - - template - class HeapAllocator - : public FHeap - , public L - , private SysAl - { - public: - - typedef AutoLock Lock; - - enum - { - DefaultAlignment = sizeof(void*) - }; - enum - { - DefaultPageSize = 0x1000 - }; - - private: - - struct PageNode - { - PageNode* pNext; - char* pEndAlloc; - char* pEndUsed; - - char* StartUsed() const - { - return (char*)(this + 1); - } - - PageNode(size_t nAlloc) - { - pNext = 0; - pEndAlloc = (char*)this + nAlloc; - pEndUsed = StartUsed(); - } - - void* Allocate(size_t nSize, size_t nAlign) - { - // Align current mem. - char* pNew = Align(pEndUsed, nAlign); - if (pNew + nSize > pEndAlloc) - { - return 0; - } - pEndUsed = pNew + nSize; - return pNew; - } - - bool CanAllocate(size_t nSize, size_t nAlign) - { - return Align(pEndUsed, nAlign) + nSize <= pEndAlloc; - } - - void Reset() - { - pEndUsed = StartUsed(); - } - - size_t GetMemoryAlloc() const - { - return pEndAlloc - (char*)this; - } - size_t GetMemoryUsed() const - { - return pEndUsed - StartUsed(); - } - size_t GetMemoryFree() const - { - return pEndAlloc - pEndUsed; - } - - void Validate() const - { - assert(pEndAlloc >= (char*)this); - assert(pEndUsed >= StartUsed() && pEndUsed <= pEndAlloc); - } - - bool CheckPtr(void* ptr) const - { - return (char*)ptr >= StartUsed() && (char*)ptr < pEndUsed; - } - }; - - public: - - HeapAllocator(FHeap opts = 0) - : FHeap(opts) - , _pPageList(0) - { - PageSize = max(Align(PageSize, DefaultPageSize), DefaultPageSize); - } - - ~HeapAllocator() - { - Clear(); - } - - // - // Raw memory allocation. - // - void* Allocate(const Lock& lock, size_t nSize, size_t nAlign = DefaultAlignment) - { - for (;; ) - { - // Try allocating from head page first. - if (_pPageList) - { - if (void* ptr = _pPageList->Allocate(nSize, nAlign)) - { - _TotalMem.nUsed += nSize; - return ptr; - } - - if (_pPageList->pNext && _pPageList->pNext->GetMemoryFree() > _pPageList->GetMemoryFree()) - { - SortPage(lock, _pPageList); - Validate(lock); - - // Try allocating from new head, which has the most free memory. - // If this fails, we know no further pages will succeed. - if (void* ptr = _pPageList->Allocate(nSize, nAlign)) - { - _TotalMem.nUsed += nSize; - return ptr; - } - } - if (SinglePage) - { - return 0; - } - } - - // Allocate the new page of the required size. - size_t nAllocSize = Align(sizeof(PageNode), nAlign) + nSize; - nAllocSize = RoundUpTo(nAllocSize, PageSize); - - void* pAlloc = this->SysAlloc(nAllocSize); - PageNode* pPageNode = new(pAlloc) PageNode(nAllocSize); - - // Insert at head of list. - pPageNode->pNext = _pPageList; - _pPageList = pPageNode; - - _TotalMem.nAlloc += nAllocSize; - - Validate(lock); - } - } - - void Deallocate([[maybe_unused]] const Lock& lock, [[maybe_unused]] void* ptr, size_t nSize) - { - // Just to maintain counts, can't reuse memory. - assert(CheckPtr(lock, ptr)); - assert(_TotalMem.nUsed >= nSize); - _TotalMem.nUsed -= nSize; - } - - // - // Templated type allocation. - // - template - T* New(size_t nAlign = 0) - { - void* pMemory = Allocate(Lock(*this), sizeof(T), nAlign ? nAlign : alignof(T)); - return pMemory ? new(pMemory) T : 0; - } - - template - T* NewArray(size_t nCount, size_t nAlign = 0) - { - void* pMemory = Allocate(Lock(*this), sizeof(T) * nCount, nAlign ? nAlign : alignof(T)); - return pMemory ? new(pMemory) T[nCount] : 0; - } - - // - // Maintenance. - // - SMemoryUsage GetTotalMemory(const Lock&) - { - return _TotalMem; - } - SMemoryUsage GetTotalMemory() - { - Lock lock(*this); - return _TotalMem; - } - - // Facility to defer freeing of dead pages during memory release calls. - struct FreeMemLock - : Lock - { - struct PageNode* _pPageList; - - FreeMemLock(L& lock) - : Lock(lock) - , _pPageList(0) {} - - ~FreeMemLock() - { - while (_pPageList != 0) - { - // Read the "next" pointer before deleting. - PageNode* pNext = _pPageList->pNext; - - // Delete the current page. - SysAl::SysDealloc(_pPageList); - - // Move to the next page in the list. - _pPageList = pNext; - } - } - }; - - void Clear(FreeMemLock& lock) - { - // Remove the pages from the object. - Validate(lock); - lock._pPageList = _pPageList; - _pPageList = 0; - _TotalMem.Clear(); - } - - void Clear() - { - FreeMemLock lock(*this); - Clear(lock); - } - - void Reset(const Lock& lock) - { - // Reset all pages, allowing memory re-use. - Validate(lock); - size_t nPrevSize = ~0; - for (PageNode** ppPage = &_pPageList; *ppPage; ) - { - (*ppPage)->Reset(); - if ((*ppPage)->GetMemoryAlloc() > nPrevSize) - { - // Move page to sorted location near beginning. - SortPage(lock, *ppPage); - - // ppPage is now next page, so continue loop. - continue; - } - nPrevSize = (*ppPage)->GetMemoryAlloc(); - ppPage = &(*ppPage)->pNext; - } - _TotalMem.nUsed = 0; - Validate(lock); - } - - void Reset() - { - Reset(Lock(*this)); - } - - // - // Validation. - // - bool CheckPtr(const Lock&, void* ptr) const - { - if (!ptr) - { - return true; - } - for (PageNode* pNode = _pPageList; pNode; pNode = pNode->pNext) - { - if (pNode->CheckPtr(ptr)) - { - return true; - } - } - return false; - } - - void Validate(const Lock&) const - { - #ifdef _DEBUG - // Check page validity, and memory counts. - SMemoryUsage MemCheck; - - for (PageNode* pPage = _pPageList; pPage; pPage = pPage->pNext) - { - pPage->Validate(); - if (pPage != _pPageList && pPage->pNext) - { - assert(pPage->GetMemoryFree() >= pPage->pNext->GetMemoryFree()); - } - MemCheck.nAlloc += pPage->GetMemoryAlloc(); - MemCheck.nUsed += pPage->GetMemoryUsed(); - } - assert(MemCheck.nAlloc == _TotalMem.nAlloc); - assert(MemCheck.nUsed >= _TotalMem.nUsed); - #endif - - #if bMEM_HEAP_CHECK - static int nCount = 0, nInterval = 0; - if (nCount++ >= nInterval) - { - nInterval++; - nCount = 0; - } - #endif - } - - void GetMemoryUsage(ICrySizer* pSizer) const - { - Lock lock(non_const(*this)); - for (PageNode* pNode = _pPageList; pNode; pNode = pNode->pNext) - { - pSizer->AddObject(pNode, pNode->GetMemoryAlloc()); - } - } - - private: - - void SortPage(const Lock&, PageNode*& rpPage) - { - // Unlink rpPage. - PageNode* pPage = rpPage; - rpPage = pPage->pNext; - - // Insert into list based on free memory. - PageNode** ppBefore = &_pPageList; - while (*ppBefore && (*ppBefore)->GetMemoryFree() > pPage->GetMemoryFree()) - { - ppBefore = &(*ppBefore)->pNext; - } - - // Link before rpList. - pPage->pNext = *ppBefore; - *ppBefore = pPage; - } - - PageNode* _pPageList; // All allocated pages. - SMemoryUsage _TotalMem; // Track memory allocated and used. - }; -} - -#endif // CRYINCLUDE_CRYCOMMON_HEAPALLOCATOR_H diff --git a/Code/CryEngine/CryCommon/HeightmapUpdateNotificationBus.h b/Code/CryEngine/CryCommon/HeightmapUpdateNotificationBus.h deleted file mode 100644 index 980318ac58..0000000000 --- a/Code/CryEngine/CryCommon/HeightmapUpdateNotificationBus.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include -#include - -namespace AZ -{ - /** - * the EBus is used to request information about potential vegetation surfaces - */ - class HeightmapUpdateNotification - : public AZ::EBusTraits - { - public: - //////////////////////////////////////////////////////////////////////// - // EBusTraits - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - //////////////////////////////////////////////////////////////////////// - - // Occurs when the terrain height map is modified. - virtual void HeightmapModified(const AZ::Aabb& bounds) = 0; - }; - - typedef AZ::EBus HeightmapUpdateNotificationBus; -} diff --git a/Code/CryEngine/CryCommon/IAudioInterfacesCommonData.h b/Code/CryEngine/CryCommon/IAudioInterfacesCommonData.h deleted file mode 100644 index afd31ee048..0000000000 --- a/Code/CryEngine/CryCommon/IAudioInterfacesCommonData.h +++ /dev/null @@ -1,578 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include -#include -#include -#include -#include -#include - - -#define AUDIO_BIT(x) (1 << (x)) -#define AUDIO_TRIGGER_IMPL_ID_NUM_RESERVED 100// IDs below that value are used for the CATLTriggerImpl_Internal - - -namespace Audio -{ - /////////////////////////////////////////////////////////////////////////////////////////////////// - typedef AZ::u64 TATLIDType; - typedef AZ::u32 TATLEnumFlagsType; - typedef TATLIDType TAudioObjectID; - typedef TATLIDType TAudioControlID; - typedef TATLIDType TAudioSwitchStateID; - typedef TATLIDType TAudioEnvironmentID; - typedef TATLIDType TAudioPreloadRequestID; - typedef TATLIDType TAudioEventID; - typedef TATLIDType TAudioFileEntryID; - typedef TATLIDType TAudioTriggerImplID; - typedef TATLIDType TAudioTriggerInstanceID; - typedef TATLIDType TAudioProxyID; - typedef TATLIDType TAudioSourceId; - typedef TATLIDType TAudioFileId; - typedef TATLIDType TAudioFileCollectionId; - typedef TATLIDType TAudioFileLanguageId; - -#define INVALID_AUDIO_OBJECT_ID (static_cast(0)) -#define GLOBAL_AUDIO_OBJECT_ID (static_cast(1)) -#define INVALID_AUDIO_CONTROL_ID (static_cast(0)) -#define INVALID_AUDIO_SWITCH_STATE_ID (static_cast(0)) -#define INVALID_AUDIO_ENVIRONMENT_ID (static_cast(0)) -#define INVALID_AUDIO_PRELOAD_REQUEST_ID (static_cast(0)) -#define INVALID_AUDIO_EVENT_ID (static_cast(0)) -#define INVALID_AUDIO_FILE_ENTRY_ID (static_cast(0)) -#define INVALID_AUDIO_TRIGGER_IMPL_ID (static_cast(0)) -#define INVALID_AUDIO_TRIGGER_INSTANCE_ID (static_cast(0)) -#define INVALID_AUDIO_ENUM_FLAG_TYPE (static_cast(0)) -#define ALL_AUDIO_REQUEST_SPECIFIC_TYPE_FLAGS (static_cast(-1)) -#define INVALID_AUDIO_PROXY_ID (static_cast(0)) -#define DEFAULT_AUDIO_PROXY_ID (static_cast(1)) -#define INVALID_AUDIO_SOURCE_ID (static_cast(0)) -#define INVALID_AUDIO_FILE_ID (static_cast(0)) -#define INVALID_AUDIO_FILE_COLLECTION_ID (static_cast(0)) -#define INVALID_AUDIO_FILE_LANGUAGE_ID (static_cast(0)) - - /////////////////////////////////////////////////////////////////////////////////////////////////// - // - // Summary: - // An enum that lists possible statuses of an AudioRequest. - // Used as a return type for many function used by the AudioSystem internally, - // and also for most of the IAudioSystemImplementation calls. - /////////////////////////////////////////////////////////////////////////////////////////////////// - enum EAudioRequestStatus : TATLEnumFlagsType - { - eARS_NONE = 0, - eARS_SUCCESS = 1, - eARS_PARTIAL_SUCCESS = 2, - eARS_FAILURE = 3, - eARS_PENDING = 4, - eARS_FAILURE_INVALID_OBJECT_ID = 5, - eARS_FAILURE_INVALID_CONTROL_ID = 6, - eARS_FAILURE_INVALID_REQUEST = 7, - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - //! Converts a boolean value to an EAudioRequestStatus. - //! @param result The boolean value to convert. - //! @return eARS_SUCCESS if result is true, eARS_FAILURE otherwise. - inline EAudioRequestStatus BoolToARS(bool result) - { - return result ? eARS_SUCCESS : eARS_FAILURE; - } - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct SATLWorldPosition - { - SATLWorldPosition() - : m_transform(AZ::Matrix3x4::CreateIdentity()) - {} - - SATLWorldPosition(const AZ::Vector3& rPos) - : m_transform(AZ::Matrix3x4::CreateIdentity()) - { - m_transform.SetTranslation(rPos); - } - - SATLWorldPosition(const AZ::Transform& rTransform) - : m_transform(AZ::Matrix3x4::CreateFromTransform(rTransform)) - {} - - SATLWorldPosition(const AZ::Matrix3x4& rTransform) - : m_transform(rTransform) - { - } - - inline AZ::Vector3 GetPositionVec() const - { - return m_transform.GetTranslation(); - } - - inline AZ::Vector3 GetUpVec() const - { - return m_transform.GetBasisZ(); - } - - inline AZ::Vector3 GetForwardVec() const - { - return m_transform.GetBasisY(); - } - - inline AZ::Vector3 GetRightVec() const - { - return m_transform.GetBasisX(); - } - - inline void NormalizeForwardVec() - { - auto forward = GetForwardVec(); - if (forward.IsZero()) - { - m_transform.SetBasisY(AZ::Vector3::CreateAxisY()); - } - else - { - forward.Normalize(); - m_transform.SetBasisY(forward); - } - } - - inline void NormalizeUpVec() - { - auto up = GetUpVec(); - if (up.IsZero()) - { - m_transform.SetBasisZ(AZ::Vector3::CreateAxisZ()); - } - else - { - up.Normalize(); - m_transform.SetBasisZ(up); - } - } - - private: - AZ::Matrix3x4 m_transform; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - enum EAudioAssetType : TATLEnumFlagsType - { - eAAT_STREAM = 1, - eAAT_SOURCE = 2, - eAAT_NONE = 3, - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - enum EAudioCodecType : TATLEnumFlagsType - { - eACT_PCM = 1, - eACT_ADPCM = 2, - eACT_XMA = 3, - eACT_VORBIS = 4, - eACT_XWMA = 5, - eACT_AAC = 6, - eACT_STREAM_PCM = 7, - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - enum EAudioRequestFlags : TATLEnumFlagsType - { - eARF_NONE = 0, // assumes Lowest priority - eARF_PRIORITY_NORMAL = AUDIO_BIT(0), // will be processed if no high priority requests are pending - eARF_PRIORITY_HIGH = AUDIO_BIT(1), // will be processed first - eARF_EXECUTE_BLOCKING = AUDIO_BIT(2), // blocks main thread until the request has been fully handled - eARF_SYNC_CALLBACK = AUDIO_BIT(3), // callback (ATL's NotifyListener) will happen on the main thread - eARF_SYNC_FINISHED_CALLBACK = AUDIO_BIT(4), // "finished trigger instance" callback will happen on the main thread - eARF_THREAD_SAFE_PUSH = AUDIO_BIT(5), // use when pushing a request from a non-main thread, e.g. AK::EventManager or AudioThread - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - enum EAudioRequestType : TATLEnumFlagsType - { - eART_NONE = 0, - eART_AUDIO_MANAGER_REQUEST = 1, - eART_AUDIO_CALLBACK_MANAGER_REQUEST = 2, - eART_AUDIO_OBJECT_REQUEST = 3, - eART_AUDIO_LISTENER_REQUEST = 4, - eART_AUDIO_ALL_REQUESTS = static_cast<TATLEnumFlagsType>(-1), - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - enum EAudioRequestResult : TATLEnumFlagsType - { - eARR_NONE = 0, - eARR_SUCCESS = 1, - eARR_FAILURE = 2, - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - enum EAudioEventState : TATLEnumFlagsType - { - eAES_NONE = 0, - eAES_PLAYING = 1, - eAES_PLAYING_DELAYED = 2, - eAES_LOADING = 3, - eAES_UNLOADING = 4, - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - enum class ObstructionType : TATLEnumFlagsType - { - Ignore = 0, - SingleRay, - MultiRay, - Count, - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - enum class PanningMode - { - Speakers, - Headphones, - }; - - - /////////////////////////////////////////////////////////////////////////////////////////////////// - enum class AudioInputSourceType - { - Unsupported, // Unsupported type - //OggFile, // Audio Input from an Ogg file - //OpusFile, // Audio Input from an Opus file - PcmFile, // Audio Input from a raw PCM file - WavFile, // Audio Input from a Wav file - Microphone, // Audio Input from a Microphone - Synthesis, // Audio Input that is synthesized (user-provided systhesis function) - ExternalStream, // Audio Input from a stream source (video stream, network stream, etc) - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - enum class AudioInputSampleType - { - Unsupported, // Unsupported type - Int, // Integer type, probably don't need to differentiate signed vs unsigned - Float, // Floating poitn type - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - enum class MultiPositionBehaviorType - { - Separate, // Sound positions are treated separately as individual point sources, i.e. like torches along a wall. - Blended, // Sound positions are blended together as a 'spread out' sound, i.e. like a river. - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - using MultiPositionVec = AZStd::vector<AZ::Vector3>; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct MultiPositionParams - { - MultiPositionVec m_positions; - MultiPositionBehaviorType m_type; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct SAudioInputConfig - { - SAudioInputConfig() - : m_sourceId(INVALID_AUDIO_SOURCE_ID) - , m_sampleRate(0) - , m_numChannels(0) - , m_bitsPerSample(0) - , m_bufferSize(0) - , m_sampleType(AudioInputSampleType::Unsupported) - , m_autoUnloadFile(false) - {} - - SAudioInputConfig(AudioInputSourceType sourceType, const char* filename, bool autoUnloadFile = true) - : m_sourceId(INVALID_AUDIO_SOURCE_ID) - , m_sampleRate(0) - , m_numChannels(0) - , m_bitsPerSample(0) - , m_bufferSize(0) - , m_sourceType(sourceType) - , m_sampleType(AudioInputSampleType::Unsupported) - , m_sourceFilename(filename) - , m_autoUnloadFile(autoUnloadFile) - {} - - SAudioInputConfig( - AudioInputSourceType sourceType, - AZ::u32 sampleRate, - AZ::u32 numChannels, - AZ::u32 bitsPerSample, - AudioInputSampleType sampleType) - : m_sourceId(INVALID_AUDIO_SOURCE_ID) - , m_sampleRate(sampleRate) - , m_numChannels(numChannels) - , m_bitsPerSample(bitsPerSample) - , m_sourceType(sourceType) - , m_sampleType(sampleType) - , m_autoUnloadFile(false) - {} - - void SetBufferSizeFromFrameCount(AZ::u32 frameCount) - { - m_bufferSize = (m_numChannels * frameCount * (m_bitsPerSample >> 3)); - } - - AZ::u32 GetSampleCountFromBufferSize() const - { - AZ_Assert(m_bitsPerSample >= 8, "Bits Per Sample is set too low!\n"); - return m_bufferSize / (m_bitsPerSample >> 3); - } - - TAudioSourceId m_sourceId; // This is set later after the source is created - AZ::u32 m_sampleRate; // 44100, 48000, ... - AZ::u32 m_numChannels; // 1 = Mono, 2 = Stereo - AZ::u32 m_bitsPerSample; // e.g. 16, 32 - AZ::u32 m_bufferSize; // Size in bytes - AudioInputSourceType m_sourceType; // File, Synthesis, Microphone, ... - AudioInputSampleType m_sampleType; // Int, Float - AZStd::string m_sourceFilename; - bool m_autoUnloadFile; // For file types, specifies whether file should unload after playback finishes - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct AudioStreamData - { - AudioStreamData() - {} - - AudioStreamData(AZ::u8* buffer, AZStd::size_t dataSize) - : m_data(buffer) - , m_sizeBytes(dataSize) - {} - - AZ::u8* m_data = nullptr; // points to start of raw data - union { - AZStd::size_t m_sizeBytes = 0; // in bytes - AZStd::size_t m_offsetBytes; // if using this structure as a read/write bookmark, use this alias - }; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct AudioStreamMultiTrackData - { - AudioStreamMultiTrackData() - { - m_data[0] = m_data[1] = m_data[2] = m_data[3] = m_data[4] = m_data[5] = nullptr; - } - - const void* m_data[6]; // 6 channels max - union { - AZStd::size_t m_sizeBytes = 0; // size in bytes of each track - AZStd::size_t m_offsetBytes; // if using this structure as a read/write bookmark, use this alias - }; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct SAudioRequestDataBase - { - explicit SAudioRequestDataBase(const EAudioRequestType eType = eART_NONE) - : eRequestType(eType) - {} - - virtual ~SAudioRequestDataBase() {} - - const EAudioRequestType eRequestType; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct SAudioSourceInfo - { - TAudioSourceId m_sourceId; - TAudioFileId m_fileId; - TAudioFileCollectionId m_languageId; - TAudioFileLanguageId m_collectionId; - EAudioCodecType m_codecType; - - SAudioSourceInfo() - : m_sourceId(INVALID_AUDIO_SOURCE_ID) - , m_fileId(INVALID_AUDIO_FILE_ID) - , m_languageId(INVALID_AUDIO_FILE_LANGUAGE_ID) - , m_collectionId(INVALID_AUDIO_FILE_COLLECTION_ID) - , m_codecType(eACT_STREAM_PCM) - {} - - SAudioSourceInfo(TAudioSourceId sourceId) - : m_sourceId(sourceId) - , m_fileId(INVALID_AUDIO_FILE_ID) - , m_languageId(INVALID_AUDIO_FILE_LANGUAGE_ID) - , m_collectionId(INVALID_AUDIO_FILE_COLLECTION_ID) - , m_codecType(eACT_STREAM_PCM) - {} - - SAudioSourceInfo( - TAudioSourceId sourceId, - TAudioFileId fileId, - TAudioFileLanguageId languageId, - TAudioFileCollectionId collectionId, - EAudioCodecType codecType) - : m_sourceId(sourceId) - , m_fileId(fileId) - , m_languageId(languageId) - , m_collectionId(collectionId) - , m_codecType(codecType) - {} - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct SAudioCallBackInfos - { - struct UserData - { - UserData(void* userData) - : m_pUserData(userData) - {} - - UserData(uint64_t userData) - : m_userData(userData) - {} - - UserData& operator=(void* userData) - { - m_pUserData = userData; - return *this; - } - - UserData& operator=(uint64_t userData) - { - m_userData = userData; - return *this; - } - - operator void*() const - { - return m_pUserData; - } - - operator uint64_t() const - { - return m_userData; - } - - bool operator==(void* const userData) - { - return this->m_pUserData == userData; - } - - bool operator==(uint64_t userData) - { - return this->m_userData == userData; - } - - union - { - void* m_pUserData; - uint64_t m_userData; - }; - }; - - SAudioCallBackInfos(const SAudioCallBackInfos& rOther) - : pObjectToNotify(rOther.pObjectToNotify) - , pUserData(rOther.pUserData) - , pUserDataOwner(rOther.pUserDataOwner) - , nRequestFlags(rOther.nRequestFlags) - { - } - - explicit SAudioCallBackInfos( - void* const pPassedObjectToNotify = nullptr, - UserData pPassedUserData = nullptr, - void* const pPassedUserDataOwner = nullptr, - const TATLEnumFlagsType nPassedRequestFlags = eARF_PRIORITY_NORMAL) - : pObjectToNotify(pPassedObjectToNotify) - , pUserData(pPassedUserData) - , pUserDataOwner(pPassedUserDataOwner) - , nRequestFlags(nPassedRequestFlags) - { - } - - static const SAudioCallBackInfos& GetEmptyObject() - { - static SAudioCallBackInfos emptyInstance; - return emptyInstance; - } - - void* const pObjectToNotify; - UserData pUserData; - void* const pUserDataOwner; - const TATLEnumFlagsType nRequestFlags; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct SAudioRequest - { - SAudioRequest() - : nFlags(eARF_NONE) - , nAudioObjectID(INVALID_AUDIO_OBJECT_ID) - , pOwner(nullptr) - , pUserData(nullptr) - , pUserDataOwner(nullptr) - , pData(nullptr) - {} - - ~SAudioRequest() {} - - SAudioRequest(const SAudioRequest& other) = delete; - SAudioRequest& operator=(const SAudioRequest& other) = delete; - - TATLEnumFlagsType nFlags; - TAudioObjectID nAudioObjectID; - void* pOwner; - void* pUserData; - void* pUserDataOwner; - SAudioRequestDataBase* pData; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct SAudioRequestInfo - { - explicit SAudioRequestInfo( - const EAudioRequestResult ePassedResult, - void* const pPassedOwner, - void* const pPassedUserData, - void* const pPassedUserDataOwner, - const EAudioRequestType ePassedAudioRequestType, - const TATLEnumFlagsType nPassedSpecificAudioRequest, - const TAudioControlID nPassedAudioControlID, - const TAudioObjectID nPassedAudioObjectID, - const TAudioEventID passedAudioEventID) - : eResult(ePassedResult) - , pOwner(pPassedOwner) - , pUserData(pPassedUserData) - , pUserDataOwner(pPassedUserDataOwner) - , eAudioRequestType(ePassedAudioRequestType) - , nSpecificAudioRequest(nPassedSpecificAudioRequest) - , nAudioControlID(nPassedAudioControlID) - , nAudioObjectID(nPassedAudioObjectID) - , audioEventID(passedAudioEventID) - {} - - const EAudioRequestResult eResult; - void* const pOwner; - void* const pUserData; - void* const pUserDataOwner; - const EAudioRequestType eAudioRequestType; - const TATLEnumFlagsType nSpecificAudioRequest; - const TAudioControlID nAudioControlID; - const TAudioObjectID nAudioObjectID; - const TAudioEventID audioEventID; - }; - -} // namespace Audio - - -namespace AZ -{ - AZ_TYPE_INFO_SPECIALIZE(Audio::MultiPositionBehaviorType, "{96851568-74F9-4EEC-9195-82DCF701EEEF}"); - AZ_TYPE_INFO_SPECIALIZE(Audio::ObstructionType, "{8C056768-40E2-4B2D-AF01-9F7A6817BAAA}"); -} // namespace AZ - diff --git a/Code/CryEngine/CryCommon/IAudioSystem.h b/Code/CryEngine/CryCommon/IAudioSystem.h deleted file mode 100644 index 5248015b2b..0000000000 --- a/Code/CryEngine/CryCommon/IAudioSystem.h +++ /dev/null @@ -1,1070 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include <IAudioInterfacesCommonData.h> - -#include <AzCore/Component/Component.h> -#include <AzCore/EBus/EBus.h> -#include <AzCore/Math/Crc.h> -#include <AzCore/Math/Vector3.h> -#include <AzCore/std/parallel/mutex.h> - -// External forward declarations. -struct IVisArea; -struct ICVar; -struct SSystemInitParams; - -namespace Audio -{ - // Internal forward declarations. - struct SAudioRequest; - - - enum EATLDataScope : TATLEnumFlagsType - { - eADS_NONE = 0, - eADS_GLOBAL = 1, - eADS_LEVEL_SPECIFIC = 2, - eADS_ALL = 3, - }; - - enum EAudioManagerRequestType : TATLEnumFlagsType - { - eAMRT_NONE = 0, - eAMRT_INIT_AUDIO_IMPL = AUDIO_BIT(0), - eAMRT_RELEASE_AUDIO_IMPL = AUDIO_BIT(1), - eAMRT_RESERVE_AUDIO_OBJECT_ID = AUDIO_BIT(2), - eAMRT_CREATE_SOURCE = AUDIO_BIT(5), - eAMRT_DESTROY_SOURCE = AUDIO_BIT(6), - eAMRT_PARSE_CONTROLS_DATA = AUDIO_BIT(7), - eAMRT_PARSE_PRELOADS_DATA = AUDIO_BIT(8), - eAMRT_CLEAR_CONTROLS_DATA = AUDIO_BIT(9), - eAMRT_CLEAR_PRELOADS_DATA = AUDIO_BIT(10), - eAMRT_PRELOAD_SINGLE_REQUEST = AUDIO_BIT(11), - eAMRT_UNLOAD_SINGLE_REQUEST = AUDIO_BIT(12), - eAMRT_UNLOAD_AFCM_DATA_BY_SCOPE = AUDIO_BIT(13), - eAMRT_REFRESH_AUDIO_SYSTEM = AUDIO_BIT(14), - eAMRT_LOSE_FOCUS = AUDIO_BIT(15), - eAMRT_GET_FOCUS = AUDIO_BIT(16), - eAMRT_MUTE_ALL = AUDIO_BIT(17), - eAMRT_UNMUTE_ALL = AUDIO_BIT(18), - eAMRT_STOP_ALL_SOUNDS = AUDIO_BIT(19), - eAMRT_DRAW_DEBUG_INFO = AUDIO_BIT(20), - eAMRT_CHANGE_LANGUAGE = AUDIO_BIT(21), - eAMRT_SET_AUDIO_PANNING_MODE = AUDIO_BIT(22), - }; - - enum EAudioCallbackManagerRequestType : TATLEnumFlagsType - { - eACMRT_NONE = 0, - eACMRT_REPORT_STARTED_EVENT = AUDIO_BIT(0), - eACMRT_REPORT_FINISHED_EVENT = AUDIO_BIT(1), - eACMRT_REPORT_FINISHED_TRIGGER_INSTANCE = AUDIO_BIT(2), - }; - - enum EAudioListenerRequestType : TATLEnumFlagsType - { - eALRT_NONE = 0, - eALRT_SET_POSITION = AUDIO_BIT(0), - }; - - enum EAudioObjectRequestType : TATLEnumFlagsType - { - eAORT_NONE = 0, - eAORT_PREPARE_TRIGGER = AUDIO_BIT(0), - eAORT_UNPREPARE_TRIGGER = AUDIO_BIT(1), - eAORT_EXECUTE_TRIGGER = AUDIO_BIT(2), - eAORT_STOP_TRIGGER = AUDIO_BIT(3), - eAORT_STOP_ALL_TRIGGERS = AUDIO_BIT(4), - eAORT_SET_POSITION = AUDIO_BIT(5), - eAORT_SET_RTPC_VALUE = AUDIO_BIT(6), - eAORT_SET_SWITCH_STATE = AUDIO_BIT(7), - eAORT_SET_ENVIRONMENT_AMOUNT = AUDIO_BIT(8), - eAORT_RESET_ENVIRONMENTS = AUDIO_BIT(9), - eAORT_RESET_RTPCS = AUDIO_BIT(10), - eAORT_RELEASE_OBJECT = AUDIO_BIT(11), - eAORT_EXECUTE_SOURCE_TRIGGER = AUDIO_BIT(12), - eAORT_SET_MULTI_POSITIONS = AUDIO_BIT(13), - }; - - enum EAudioObjectObstructionCalcType : TATLEnumFlagsType - { - eAOOCT_IGNORE = 0, - eAOOCT_SINGLE_RAY = 1, - eAOOCT_MULTI_RAY = 2, - }; - - enum EAudioControlType : TATLEnumFlagsType - { - eACT_NONE = 0, - eACT_AUDIO_OBJECT = 1, - eACT_TRIGGER = 2, - eACT_RTPC = 3, - eACT_SWITCH = 4, - eACT_SWITCH_STATE = 5, - eACT_PRELOAD = 6, - eACT_ENVIRONMENT = 7, - }; - - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template <typename T> - AZ_FORCE_INLINE T AudioStringToID(const char* const source) - { - return static_cast<T>(AZ::Crc32(source)); - } - - - /////////////////////////////////////////////////////////////////////////////////////////////////// - // Function Callback Typedefs - using AudioRequestCallbackType = void(*)(const SAudioRequestInfo* const); - using TriggerFinishedCallbackType = void(*)(const TAudioObjectID, const TAudioControlID, void* const); - - - /////////////////////////////////////////////////////////////////////////////////////////////////// - // Audio Manager Requests - /////////////////////////////////////////////////////////////////////////////////////////////////// - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct SAudioManagerRequestDataBase - : public SAudioRequestDataBase - { - explicit SAudioManagerRequestDataBase(const EAudioManagerRequestType ePassedType = eAMRT_NONE) - : SAudioRequestDataBase(eART_AUDIO_MANAGER_REQUEST) - , eType(ePassedType) - {} - - ~SAudioManagerRequestDataBase() override {} - - const EAudioManagerRequestType eType; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template <EAudioManagerRequestType T> - struct SAudioManagerRequestData - : public SAudioManagerRequestDataBase - { - SAudioManagerRequestData() - : SAudioManagerRequestDataBase(T) - {} - - ~SAudioManagerRequestData() override {} - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioManagerRequestData<eAMRT_INIT_AUDIO_IMPL> - : public SAudioManagerRequestDataBase - { - SAudioManagerRequestData() - : SAudioManagerRequestDataBase(eAMRT_INIT_AUDIO_IMPL) - {} - - ~SAudioManagerRequestData<eAMRT_INIT_AUDIO_IMPL>() override {} - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioManagerRequestData<eAMRT_RELEASE_AUDIO_IMPL> : public SAudioManagerRequestDataBase - { - SAudioManagerRequestData() - : SAudioManagerRequestDataBase(eAMRT_RELEASE_AUDIO_IMPL) - {} - - ~SAudioManagerRequestData<eAMRT_RELEASE_AUDIO_IMPL>() override {} - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioManagerRequestData<eAMRT_RESERVE_AUDIO_OBJECT_ID> - : public SAudioManagerRequestDataBase - { - SAudioManagerRequestData(TAudioObjectID* const pPassedObjectID, const char* const sPassedObjectName = nullptr) - : SAudioManagerRequestDataBase(eAMRT_RESERVE_AUDIO_OBJECT_ID) - , pObjectID(pPassedObjectID) - , sObjectName(sPassedObjectName) - {} - - ~SAudioManagerRequestData<eAMRT_RESERVE_AUDIO_OBJECT_ID>()override {} - - TAudioObjectID* const pObjectID; - const char* const sObjectName; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioManagerRequestData<eAMRT_CREATE_SOURCE> - : public SAudioManagerRequestDataBase - { - SAudioManagerRequestData(const SAudioInputConfig& sourceConfig) - : SAudioManagerRequestDataBase(eAMRT_CREATE_SOURCE) - , m_sourceConfig(sourceConfig) - {} - - ~SAudioManagerRequestData<eAMRT_CREATE_SOURCE>() override {} - - SAudioInputConfig m_sourceConfig; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioManagerRequestData<eAMRT_DESTROY_SOURCE> - : public SAudioManagerRequestDataBase - { - SAudioManagerRequestData(TAudioSourceId sourceId) - : SAudioManagerRequestDataBase(eAMRT_DESTROY_SOURCE) - , m_sourceId(sourceId) - {} - - ~SAudioManagerRequestData<eAMRT_DESTROY_SOURCE>() override {} - - const TAudioSourceId m_sourceId; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioManagerRequestData<eAMRT_PARSE_CONTROLS_DATA> - : public SAudioManagerRequestDataBase - { - SAudioManagerRequestData(const char* const sControlsFolderPath, const EATLDataScope ePassedDataScope) - : SAudioManagerRequestDataBase(eAMRT_PARSE_CONTROLS_DATA) - , sFolderPath(sControlsFolderPath) - , eDataScope(ePassedDataScope) - {} - - ~SAudioManagerRequestData<eAMRT_PARSE_CONTROLS_DATA>()override {} - - const char* const sFolderPath; - const EATLDataScope eDataScope; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioManagerRequestData<eAMRT_PARSE_PRELOADS_DATA> - : public SAudioManagerRequestDataBase - { - SAudioManagerRequestData(const char* const sControlsFolderPath, const EATLDataScope ePassedDataScope) - : SAudioManagerRequestDataBase(eAMRT_PARSE_PRELOADS_DATA) - , sFolderPath(sControlsFolderPath) - , eDataScope(ePassedDataScope) - {} - - ~SAudioManagerRequestData<eAMRT_PARSE_PRELOADS_DATA>()override {} - - const char* const sFolderPath; - const EATLDataScope eDataScope; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioManagerRequestData<eAMRT_CLEAR_CONTROLS_DATA> - : public SAudioManagerRequestDataBase - { - explicit SAudioManagerRequestData(const EATLDataScope ePassedDataScope = eADS_NONE) - : SAudioManagerRequestDataBase(eAMRT_CLEAR_CONTROLS_DATA) - , eDataScope(ePassedDataScope) - {} - - ~SAudioManagerRequestData<eAMRT_CLEAR_CONTROLS_DATA>()override {} - - const EATLDataScope eDataScope; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioManagerRequestData<eAMRT_CLEAR_PRELOADS_DATA> - : public SAudioManagerRequestDataBase - { - explicit SAudioManagerRequestData(const EATLDataScope ePassedDataScope = eADS_NONE) - : SAudioManagerRequestDataBase(eAMRT_CLEAR_PRELOADS_DATA) - , eDataScope(ePassedDataScope) - {} - - ~SAudioManagerRequestData<eAMRT_CLEAR_PRELOADS_DATA>()override {} - - const EATLDataScope eDataScope; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioManagerRequestData<eAMRT_PRELOAD_SINGLE_REQUEST> - : public SAudioManagerRequestDataBase - { - explicit SAudioManagerRequestData(const TAudioPreloadRequestID nRequestID = INVALID_AUDIO_PRELOAD_REQUEST_ID, const bool bPassedAutoLoadOnly = false) - : SAudioManagerRequestDataBase(eAMRT_PRELOAD_SINGLE_REQUEST) - , nPreloadRequestID(nRequestID) - , bAutoLoadOnly(bPassedAutoLoadOnly) - {} - - ~SAudioManagerRequestData<eAMRT_PRELOAD_SINGLE_REQUEST>()override {} - - const TAudioPreloadRequestID nPreloadRequestID; - const bool bAutoLoadOnly; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioManagerRequestData<eAMRT_UNLOAD_SINGLE_REQUEST> - : public SAudioManagerRequestDataBase - { - explicit SAudioManagerRequestData(const TAudioPreloadRequestID nRequestID = INVALID_AUDIO_PRELOAD_REQUEST_ID) - : SAudioManagerRequestDataBase(eAMRT_UNLOAD_SINGLE_REQUEST) - , nPreloadRequestID(nRequestID) - {} - - ~SAudioManagerRequestData<eAMRT_UNLOAD_SINGLE_REQUEST>()override {} - - const TAudioPreloadRequestID nPreloadRequestID; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioManagerRequestData<eAMRT_UNLOAD_AFCM_DATA_BY_SCOPE> - : public SAudioManagerRequestDataBase - { - SAudioManagerRequestData(const EATLDataScope eScope = eADS_NONE) - : SAudioManagerRequestDataBase(eAMRT_UNLOAD_AFCM_DATA_BY_SCOPE) - , eDataScope(eScope) - {} - - ~SAudioManagerRequestData<eAMRT_UNLOAD_AFCM_DATA_BY_SCOPE>()override {} - - const EATLDataScope eDataScope; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioManagerRequestData<eAMRT_REFRESH_AUDIO_SYSTEM> - : public SAudioManagerRequestDataBase - { - SAudioManagerRequestData(const char* const controlsPath, const char* const levelName, TAudioPreloadRequestID preloadId) - : SAudioManagerRequestDataBase(eAMRT_REFRESH_AUDIO_SYSTEM) - , m_controlsPath(controlsPath) - , m_levelName(levelName) - , m_levelPreloadId(preloadId) - {} - - ~SAudioManagerRequestData<eAMRT_REFRESH_AUDIO_SYSTEM>()override {} - - const char* const m_controlsPath; - const char* const m_levelName; - const TAudioPreloadRequestID m_levelPreloadId = INVALID_AUDIO_PRELOAD_REQUEST_ID; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioManagerRequestData<eAMRT_CHANGE_LANGUAGE> - : public SAudioManagerRequestDataBase - { - SAudioManagerRequestData() - : SAudioManagerRequestDataBase(eAMRT_CHANGE_LANGUAGE) - {} - - ~SAudioManagerRequestData<eAMRT_CHANGE_LANGUAGE>()override {} - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioManagerRequestData<eAMRT_SET_AUDIO_PANNING_MODE> - : public SAudioManagerRequestDataBase - { - explicit SAudioManagerRequestData(PanningMode panningMode) - : SAudioManagerRequestDataBase(eAMRT_SET_AUDIO_PANNING_MODE) - , m_panningMode(panningMode) - {} - - ~SAudioManagerRequestData<eAMRT_SET_AUDIO_PANNING_MODE>() override {} - - const PanningMode m_panningMode; - }; - - - /////////////////////////////////////////////////////////////////////////////////////////////////// - // Audio Callback Manager Requests - /////////////////////////////////////////////////////////////////////////////////////////////////// - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct SAudioCallbackManagerRequestDataBase - : public SAudioRequestDataBase - { - explicit SAudioCallbackManagerRequestDataBase(const EAudioCallbackManagerRequestType ePassedType = eACMRT_NONE) - : SAudioRequestDataBase(eART_AUDIO_CALLBACK_MANAGER_REQUEST) - , eType(ePassedType) - {} - - ~SAudioCallbackManagerRequestDataBase() override {} - - const EAudioCallbackManagerRequestType eType; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template <EAudioCallbackManagerRequestType T> - struct SAudioCallbackManagerRequestData - : public SAudioCallbackManagerRequestDataBase - { - SAudioCallbackManagerRequestData() - : SAudioCallbackManagerRequestDataBase(T) - {} - - ~SAudioCallbackManagerRequestData() override {} - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioCallbackManagerRequestData<eACMRT_REPORT_STARTED_EVENT> - : public SAudioCallbackManagerRequestDataBase - { - SAudioCallbackManagerRequestData(TAudioEventID const nPassedEventID) - : SAudioCallbackManagerRequestDataBase(eACMRT_REPORT_STARTED_EVENT) - , nEventID(nPassedEventID) - {} - - ~SAudioCallbackManagerRequestData<eACMRT_REPORT_STARTED_EVENT>() override {} - - const TAudioEventID nEventID; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioCallbackManagerRequestData<eACMRT_REPORT_FINISHED_EVENT> - : public SAudioCallbackManagerRequestDataBase - { - SAudioCallbackManagerRequestData(const TAudioEventID nPassedEventID, const bool bPassedSuccess) - : SAudioCallbackManagerRequestDataBase(eACMRT_REPORT_FINISHED_EVENT) - , nEventID(nPassedEventID) - , bSuccess(bPassedSuccess) - {} - - ~SAudioCallbackManagerRequestData<eACMRT_REPORT_FINISHED_EVENT>()override {} - - const TAudioEventID nEventID; - const bool bSuccess; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioCallbackManagerRequestData<eACMRT_REPORT_FINISHED_TRIGGER_INSTANCE> - : public SAudioCallbackManagerRequestDataBase - { - SAudioCallbackManagerRequestData(TAudioControlID const nPassedControlID) - : SAudioCallbackManagerRequestDataBase(eACMRT_REPORT_FINISHED_TRIGGER_INSTANCE) - , nAudioTriggerID(nPassedControlID) - {} - - ~SAudioCallbackManagerRequestData<eACMRT_REPORT_FINISHED_TRIGGER_INSTANCE>()override {} - - const TAudioControlID nAudioTriggerID; - }; - - - - /////////////////////////////////////////////////////////////////////////////////////////////////// - // Audio Object Requests - /////////////////////////////////////////////////////////////////////////////////////////////////// - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct SAudioObjectRequestDataBase - : public SAudioRequestDataBase - { - explicit SAudioObjectRequestDataBase(const EAudioObjectRequestType ePassedType = eAORT_NONE) - : SAudioRequestDataBase(eART_AUDIO_OBJECT_REQUEST) - , eType(ePassedType) - {} - - ~SAudioObjectRequestDataBase() override {} - - const EAudioObjectRequestType eType; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template <EAudioObjectRequestType T> - struct SAudioObjectRequestData - : public SAudioObjectRequestDataBase - { - SAudioObjectRequestData() - : SAudioObjectRequestDataBase(T) - {} - - ~SAudioObjectRequestData() override {} - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioObjectRequestData<eAORT_EXECUTE_TRIGGER> - : public SAudioObjectRequestDataBase - { - SAudioObjectRequestData() - : SAudioObjectRequestDataBase(eAORT_EXECUTE_TRIGGER) - , nTriggerID(INVALID_AUDIO_CONTROL_ID) - , fTimeUntilRemovalInMS(0.0f) - {} - - SAudioObjectRequestData(const TAudioControlID nPassedTriggerID, const float fPassedTimeUntilRemovalInMS) - : SAudioObjectRequestDataBase(eAORT_EXECUTE_TRIGGER) - , nTriggerID(nPassedTriggerID) - , fTimeUntilRemovalInMS(fPassedTimeUntilRemovalInMS) - {} - - ~SAudioObjectRequestData<eAORT_EXECUTE_TRIGGER>()override {} - - TAudioControlID nTriggerID; - float fTimeUntilRemovalInMS; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioObjectRequestData<eAORT_PREPARE_TRIGGER> - : public SAudioObjectRequestDataBase - { - SAudioObjectRequestData() - : SAudioObjectRequestDataBase(eAORT_PREPARE_TRIGGER) - , nTriggerID(INVALID_AUDIO_CONTROL_ID) - {} - - explicit SAudioObjectRequestData(const TAudioControlID nPassedTriggerID) - : SAudioObjectRequestDataBase(eAORT_PREPARE_TRIGGER) - , nTriggerID(nPassedTriggerID) - {} - - ~SAudioObjectRequestData<eAORT_PREPARE_TRIGGER>()override {} - - TAudioControlID nTriggerID; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioObjectRequestData<eAORT_UNPREPARE_TRIGGER> - : public SAudioObjectRequestDataBase - { - SAudioObjectRequestData() - : SAudioObjectRequestDataBase(eAORT_UNPREPARE_TRIGGER) - , nTriggerID(INVALID_AUDIO_CONTROL_ID) - {} - - explicit SAudioObjectRequestData(const TAudioControlID nPassedTriggerID) - : SAudioObjectRequestDataBase(eAORT_UNPREPARE_TRIGGER) - , nTriggerID(nPassedTriggerID) - {} - - ~SAudioObjectRequestData<eAORT_UNPREPARE_TRIGGER>()override {} - - TAudioControlID nTriggerID; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioObjectRequestData<eAORT_STOP_TRIGGER> - : public SAudioObjectRequestDataBase - { - SAudioObjectRequestData() - : SAudioObjectRequestDataBase(eAORT_STOP_TRIGGER) - , nTriggerID(INVALID_AUDIO_CONTROL_ID) - {} - - explicit SAudioObjectRequestData(const TAudioControlID nPassedTriggerID) - : SAudioObjectRequestDataBase(eAORT_STOP_TRIGGER) - , nTriggerID(nPassedTriggerID) - {} - - ~SAudioObjectRequestData<eAORT_STOP_TRIGGER>()override {} - - TAudioControlID nTriggerID; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioObjectRequestData<eAORT_STOP_ALL_TRIGGERS> - : public SAudioObjectRequestDataBase - { - SAudioObjectRequestData() - : SAudioObjectRequestDataBase(eAORT_STOP_ALL_TRIGGERS) - , m_filterByOwner(false) - {} - - SAudioObjectRequestData(bool filterByOwner) - : SAudioObjectRequestDataBase(eAORT_STOP_ALL_TRIGGERS) - , m_filterByOwner(filterByOwner) - {} - - ~SAudioObjectRequestData<eAORT_STOP_ALL_TRIGGERS>()override {} - - const bool m_filterByOwner; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioObjectRequestData<eAORT_SET_POSITION> - : public SAudioObjectRequestDataBase - { - SAudioObjectRequestData() - : SAudioObjectRequestDataBase(eAORT_SET_POSITION) - , oPosition() - {} - - explicit SAudioObjectRequestData(const SATLWorldPosition& oPassedPosition) - : SAudioObjectRequestDataBase(eAORT_SET_POSITION) - , oPosition(oPassedPosition) - {} - - ~SAudioObjectRequestData<eAORT_SET_POSITION>()override {} - - SATLWorldPosition oPosition; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioObjectRequestData<eAORT_SET_RTPC_VALUE> - : public SAudioObjectRequestDataBase - { - SAudioObjectRequestData() - : SAudioObjectRequestDataBase(eAORT_SET_RTPC_VALUE) - , nControlID(INVALID_AUDIO_CONTROL_ID) - , fValue(0.0f) - {} - - SAudioObjectRequestData(const TAudioControlID nPassedControlID, const float fPassedValue) - : SAudioObjectRequestDataBase(eAORT_SET_RTPC_VALUE) - , nControlID(nPassedControlID) - , fValue(fPassedValue) - {} - - ~SAudioObjectRequestData<eAORT_SET_RTPC_VALUE>()override {} - - TAudioControlID nControlID; - float fValue; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioObjectRequestData<eAORT_SET_SWITCH_STATE> - : public SAudioObjectRequestDataBase - { - SAudioObjectRequestData() - : SAudioObjectRequestDataBase(eAORT_SET_SWITCH_STATE) - , nSwitchID(INVALID_AUDIO_CONTROL_ID) - , nStateID(INVALID_AUDIO_SWITCH_STATE_ID) - {} - - SAudioObjectRequestData(const TAudioControlID nPassedControlID, const TAudioSwitchStateID nPassedStateID) - : SAudioObjectRequestDataBase(eAORT_SET_SWITCH_STATE) - , nSwitchID(nPassedControlID) - , nStateID(nPassedStateID) - {} - - ~SAudioObjectRequestData<eAORT_SET_SWITCH_STATE>()override {} - - TAudioControlID nSwitchID; - TAudioSwitchStateID nStateID; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioObjectRequestData<eAORT_SET_ENVIRONMENT_AMOUNT> - : public SAudioObjectRequestDataBase - { - SAudioObjectRequestData() - : SAudioObjectRequestDataBase(eAORT_SET_ENVIRONMENT_AMOUNT) - , nEnvironmentID(INVALID_AUDIO_ENVIRONMENT_ID) - , fAmount(1.0f) - {} - - SAudioObjectRequestData(const TAudioEnvironmentID nPassedEnvironmentID, const float fPassedAmount) - : SAudioObjectRequestDataBase(eAORT_SET_ENVIRONMENT_AMOUNT) - , nEnvironmentID(nPassedEnvironmentID) - , fAmount(fPassedAmount) - {} - - ~SAudioObjectRequestData<eAORT_SET_ENVIRONMENT_AMOUNT>()override {} - - TAudioEnvironmentID nEnvironmentID; - float fAmount; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioObjectRequestData<eAORT_RESET_ENVIRONMENTS> - : public SAudioObjectRequestDataBase - { - SAudioObjectRequestData() - : SAudioObjectRequestDataBase(eAORT_RESET_ENVIRONMENTS) - {} - - ~SAudioObjectRequestData<eAORT_RESET_ENVIRONMENTS>()override {} - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioObjectRequestData<eAORT_RESET_RTPCS> - : public SAudioObjectRequestDataBase - { - SAudioObjectRequestData() - : SAudioObjectRequestDataBase(eAORT_RESET_RTPCS) - {} - - ~SAudioObjectRequestData<eAORT_RESET_RTPCS>() override {} - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioObjectRequestData<eAORT_RELEASE_OBJECT> - : public SAudioObjectRequestDataBase - { - SAudioObjectRequestData() - : SAudioObjectRequestDataBase(eAORT_RELEASE_OBJECT) - {} - - ~SAudioObjectRequestData<eAORT_RELEASE_OBJECT>()override {} - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioObjectRequestData<eAORT_EXECUTE_SOURCE_TRIGGER> - : public SAudioObjectRequestDataBase - { - SAudioObjectRequestData() - : SAudioObjectRequestDataBase(eAORT_EXECUTE_SOURCE_TRIGGER) - , m_triggerId(INVALID_AUDIO_CONTROL_ID) - {} - - SAudioObjectRequestData( - TAudioControlID triggerId, - const SAudioSourceInfo& sourceInfo) - : SAudioObjectRequestDataBase(eAORT_EXECUTE_SOURCE_TRIGGER) - , m_triggerId(triggerId) - , m_sourceInfo(sourceInfo) - {} - - ~SAudioObjectRequestData<eAORT_EXECUTE_SOURCE_TRIGGER>()override {} - - TAudioControlID m_triggerId; - SAudioSourceInfo m_sourceInfo; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template <> - struct SAudioObjectRequestData<eAORT_SET_MULTI_POSITIONS> - : public SAudioObjectRequestDataBase - { - SAudioObjectRequestData() - : SAudioObjectRequestDataBase(eAORT_SET_MULTI_POSITIONS) - {} - - SAudioObjectRequestData(const MultiPositionParams& params) - : SAudioObjectRequestDataBase(eAORT_SET_MULTI_POSITIONS) - , m_params(params) - {} - - ~SAudioObjectRequestData<eAORT_SET_MULTI_POSITIONS>() override {} - - MultiPositionParams m_params; - }; - - - /////////////////////////////////////////////////////////////////////////////////////////////////// - // Audio Listener Requests - /////////////////////////////////////////////////////////////////////////////////////////////////// - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct SAudioListenerRequestDataBase - : public SAudioRequestDataBase - { - explicit SAudioListenerRequestDataBase(const EAudioListenerRequestType ePassedType = eALRT_NONE) - : SAudioRequestDataBase(eART_AUDIO_LISTENER_REQUEST) - , eType(ePassedType) - {} - - ~SAudioListenerRequestDataBase() override {} - - const EAudioListenerRequestType eType; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<EAudioListenerRequestType T> - struct SAudioListenerRequestData - : public SAudioListenerRequestDataBase - { - SAudioListenerRequestData() - : SAudioListenerRequestDataBase(T) - {} - - ~SAudioListenerRequestData() override {} - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - template<> - struct SAudioListenerRequestData<eALRT_SET_POSITION> - : public SAudioListenerRequestDataBase - { - SAudioListenerRequestData() - : SAudioListenerRequestDataBase(eALRT_SET_POSITION) - {} - - explicit SAudioListenerRequestData(const SATLWorldPosition& oWorldPosition) - : SAudioListenerRequestDataBase(eALRT_SET_POSITION) - , oNewPosition(oWorldPosition) - {} - - ~SAudioListenerRequestData<eALRT_SET_POSITION>()override {} - - SATLWorldPosition oNewPosition; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct SAudioSystemInfo - { - SAudioSystemInfo() - : nCountUsedAudioTriggers(0) - , nCountUnusedAudioTriggers(0) - , nCountUsedAudioEvents(0) - , nCountUnusedAudioEvents(0) - {} - - AZStd::size_t nCountUsedAudioTriggers; - AZStd::size_t nCountUnusedAudioTriggers; - AZStd::size_t nCountUsedAudioEvents; - AZStd::size_t nCountUnusedAudioEvents; - - AZ::Vector3 oListenerPos; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct IAudioProxy - { - virtual ~IAudioProxy() = default; - - virtual void Initialize(const char* sObjectName, bool bInitAsync = true) = 0; - virtual void Release() = 0; - virtual void Reset() = 0; - - virtual void ExecuteSourceTrigger(TAudioControlID nTriggerID, const SAudioSourceInfo& rSourceInfo, const SAudioCallBackInfos& rCallbackInfos = SAudioCallBackInfos::GetEmptyObject()) = 0; - virtual void ExecuteTrigger(TAudioControlID nTriggerID, const SAudioCallBackInfos& rCallbackInfos = SAudioCallBackInfos::GetEmptyObject()) = 0; - virtual void StopAllTriggers() = 0; - virtual void StopTrigger(TAudioControlID nTriggerID) = 0; - virtual void SetSwitchState(TAudioControlID nSwitchID, TAudioSwitchStateID nStateID) = 0; - virtual void SetRtpcValue(TAudioControlID nRtpcID, float fValue) = 0; - virtual void SetObstructionCalcType(EAudioObjectObstructionCalcType eObstructionType) = 0; - virtual void SetPosition(const SATLWorldPosition& rPosition) = 0; - virtual void SetPosition(const AZ::Vector3& rPosition) = 0; - virtual void SetMultiplePositions(const MultiPositionParams& params) = 0; - virtual void SetEnvironmentAmount(TAudioEnvironmentID nEnvironmentID, float fAmount) = 0; - virtual void SetCurrentEnvironments() = 0; - virtual void ResetRtpcValues() = 0; - virtual TAudioObjectID GetAudioObjectID() const = 0; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - class AudioPreloadNotifications - : public AZ::EBusTraits - { - public: - virtual ~AudioPreloadNotifications() = default; - - /////////////////////////////////////////////////////////////////////////////////////////////// - // EBusTraits - PreloadID Address, Multiple Handler - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - using BusIdType = TAudioPreloadRequestID; - using MutexType = AZStd::recursive_mutex; - /////////////////////////////////////////////////////////////////////////////////////////////// - - virtual void OnAudioPreloadCached() = 0; - virtual void OnAudioPreloadUncached() = 0; - }; - - using AudioPreloadNotificationBus = AZ::EBus<AudioPreloadNotifications>; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - class AudioSystemRequests - : public AZ::EBusTraits - { - public: - virtual ~AudioSystemRequests() = default; - - /////////////////////////////////////////////////////////////////////////////////////////////// - // EBusTraits - Single Bus Address, Single Handler - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - /////////////////////////////////////////////////////////////////////////////////////////////// - - virtual bool Initialize() = 0; - virtual void Release() = 0; - virtual void ExternalUpdate() = 0; - - virtual void PushRequest(const SAudioRequest& rAudioRequestData) = 0; - virtual void PushRequestBlocking(const SAudioRequest& audioRequestData) = 0; - - virtual void AddRequestListener( - AudioRequestCallbackType callBack, - void* objectToListenTo, - EAudioRequestType requestType = eART_AUDIO_ALL_REQUESTS, - TATLEnumFlagsType specificRequestMask = ALL_AUDIO_REQUEST_SPECIFIC_TYPE_FLAGS) = 0; - virtual void RemoveRequestListener( - AudioRequestCallbackType callBack, - void* requestOwner) = 0; - - virtual TAudioControlID GetAudioTriggerID(const char* sAudioTriggerName) const = 0; - virtual TAudioControlID GetAudioRtpcID(const char* sAudioRtpcName) const = 0; - virtual TAudioControlID GetAudioSwitchID(const char* sAudioSwitchName) const = 0; - virtual TAudioSwitchStateID GetAudioSwitchStateID(TAudioControlID nSwitchID, const char* sAudioSwitchStateName) const = 0; - virtual TAudioPreloadRequestID GetAudioPreloadRequestID(const char* sAudioPreloadRequestName) const = 0; - virtual TAudioEnvironmentID GetAudioEnvironmentID(const char* sAudioEnvironmentName) const = 0; - - virtual bool ReserveAudioListenerID(TAudioObjectID& rAudioObjectID) = 0; - virtual bool ReleaseAudioListenerID(TAudioObjectID nAudioObjectID) = 0; - virtual bool SetAudioListenerOverrideID(TAudioObjectID nAudioObjectID) = 0; - - virtual void GetInfo(SAudioSystemInfo& rAudioSystemInfo) = 0; - virtual const char* GetControlsPath() const = 0; - virtual void UpdateControlsPath() = 0; - virtual void RefreshAudioSystem(const char* levelName) = 0; - - virtual IAudioProxy* GetFreeAudioProxy() = 0; - virtual void FreeAudioProxy(IAudioProxy* pIAudioProxy) = 0; - - virtual TAudioSourceId CreateAudioSource(const SAudioInputConfig& sourceConfig) = 0; - virtual void DestroyAudioSource(TAudioSourceId sourceId) = 0; - - virtual const char* GetAudioControlName(EAudioControlType controlType, TATLIDType atlID) const = 0; - virtual const char* GetAudioSwitchStateName(TAudioControlID switchID, TAudioSwitchStateID stateID) const = 0; - }; - - using AudioSystemRequestBus = AZ::EBus<AudioSystemRequests>; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct AudioTriggerNotifications - : public AZ::EBusTraits - { - virtual ~AudioTriggerNotifications() = default; - - /////////////////////////////////////////////////////////////////////////////////////////////// - // EBusTraits - Address by ID, Multiple Handler, Mutex, Queued - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - static const bool EnableEventQueue = true; - using MutexType = AZStd::recursive_mutex; - using BusIdType = Audio::TAudioControlID; - /////////////////////////////////////////////////////////////////////////////////////////////// - - virtual void ReportDurationInfo(TAudioEventID, float /*duration*/, float /*estimatedDuration*/) = 0; - }; - - using AudioTriggerNotificationBus = AZ::EBus<AudioTriggerNotifications>; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - class AudioSystemThreadSafeRequests - : public AZ::EBusTraits - { - public: - virtual ~AudioSystemThreadSafeRequests() = default; - - /////////////////////////////////////////////////////////////////////////////////////////////// - // EBusTraits - Single Bus Address, Single Handler, Mutex, Queued - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const bool EnableEventQueue = true; - using MutexType = AZStd::recursive_mutex; - /////////////////////////////////////////////////////////////////////////////////////////////// - - virtual void PushRequestThreadSafe(const SAudioRequest& audioRequestData) = 0; - }; - - using AudioSystemThreadSafeRequestBus = AZ::EBus<AudioSystemThreadSafeRequests>; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - struct IAudioSystem - : public AudioSystemRequestBus::Handler - , public AudioSystemThreadSafeRequestBus::Handler - { - ~IAudioSystem() override = default; - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - class AudioStreamingRequests - : public AZ::EBusTraits - { - public: - virtual ~AudioStreamingRequests() = default; - - /////////////////////////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - Single Bus, Single Handler - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - using BusIdType = TAudioSourceId; - using MutexType = AZStd::recursive_mutex; - /////////////////////////////////////////////////////////////////////////////////////////////// - - /////////////////////////////////////////////////////////////////////////////////////////////// - // <title ReadStreamingInput> - // Summary: - // Load streaming input into the ATL-specific audio input - // Arguments: - // data - Buffer of data to load into the input device's internal buffer - /////////////////////////////////////////////////////////////////////////////////////////////// - virtual AZStd::size_t ReadStreamingInput(const AudioStreamData& data) = 0; - - /////////////////////////////////////////////////////////////////////////////////////////////// - // <title ReadStreamingMultiTrackInput> - // Summary: - // Load streaming multi-track input into the ATL-specific audio input - // Arguments: - // data - Buffers of multi-track data to load into the input device's internal buffer - // Return value: - // The number of frames loaded into the internal buffer - /////////////////////////////////////////////////////////////////////////////////////////////// - virtual AZStd::size_t ReadStreamingMultiTrackInput(AudioStreamMultiTrackData& data) = 0; - }; - - using AudioStreamingRequestBus = AZ::EBus<AudioStreamingRequests>; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - namespace Gem - { - /////////////////////////////////////////////////////////////////////////////////////////////// - // Used for initializing and releasing the audio system (AudioSystem/ATL) code. - class AudioSystemGemRequests - : public AZ::EBusTraits - { - public: - /////////////////////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - /////////////////////////////////////////////////////////////////////////////////////////// - - // Interface methods - virtual bool Initialize(const SSystemInitParams* initParams) = 0; - virtual void Release() = 0; - }; - - using AudioSystemGemRequestBus = AZ::EBus<AudioSystemGemRequests>; - - - /////////////////////////////////////////////////////////////////////////////////////////////// - // Used for initializing and releasing the audio engine (middleware layer) code. - class AudioEngineGemRequests - : public AZ::EBusTraits - { - public: - /////////////////////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - /////////////////////////////////////////////////////////////////////////////////////////// - - // Interface methods - virtual bool Initialize() = 0; - virtual void Release() = 0; - }; - - using AudioEngineGemRequestBus = AZ::EBus<AudioEngineGemRequests>; - - } // namespace Gem - -} // namespace Audio diff --git a/Code/CryEngine/CryCommon/ICmdLine.h b/Code/CryEngine/CryCommon/ICmdLine.h deleted file mode 100644 index 3a9ccedfee..0000000000 --- a/Code/CryEngine/CryCommon/ICmdLine.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : This is the interface to access command line arguments. -// This will avoid the need to parse command line in multiple -// places and thus reduce unnecessary code duplication - - -#ifndef CRYINCLUDE_CRYCOMMON_ICMDLINE_H -#define CRYINCLUDE_CRYCOMMON_ICMDLINE_H -#pragma once - -// The type of command line argument -enum ECmdLineArgType -{ - // Description: - // Argument was not preceeded by anything - eCLAT_Normal = 0, - // Description: - // Argument was preceeded by a minus sign '-' - eCLAT_Pre, - // Description: - // Argument was preceeded by a plus signe '+' - eCLAT_Post, - // Description: - // Argument is the executable filename - eCLAT_Executable, -}; - -// Container for a command line Argument -class ICmdLineArg -{ -public: - // <interfuscator:shuffle> - virtual ~ICmdLineArg(){} - // Description: - // Retrieve the name of the argument. - // Return Value: - // The name of the argument. - virtual const char* GetName() const = 0; - - // Description: - // Retrieve the value of the argument. - // Return Value: - // The value of the argument as a null-terminated string. - virtual const char* GetValue() const = 0; - - // Description: - // Retrieve the type of argument. - // Return Value: - // The type of argument. - // See Also: - // ECmdLineArgType - virtual const ECmdLineArgType GetType() const = 0; - - // Description: - // Retrieve the value of the argument. - // Return Value: - // The value of the argument as float number. - virtual const float GetFValue() const = 0; - - // Description: - // Retrieve the value of the argument. - // Return Value: - // The value of the argument as integer number. - virtual const int GetIValue() const = 0; - // </interfuscator:shuffle> -}; - -// Command line interface -class ICmdLine -{ -public: - // <interfuscator:shuffle> - virtual ~ICmdLine(){} - // Description: - // Returns the n-th command line argument. - // Arguments: - // n - 0 returns executable name, otherwise returns n-th argument. - // Return Value: - // Pointer to the command line argument at index specified by idx. - // See Also: - // ICmdLineArg - virtual const ICmdLineArg* GetArg(int n) const = 0; - - // Description: - // Returns the number of command line arguments. - // Return Value: - // The number of command line arguments. - virtual int GetArgCount() const = 0; - - // Description: - // Finds an argument in the command line. - // Arguments: - // name - the name of the argument to find, excluding any '+' or '-' - // Return Value: - // 0 when if the argument was not found. - // Pointer to a ICmdLineArg class containing the specified argument. - // See Also: - // ICmdLineArg - virtual const ICmdLineArg* FindArg(const ECmdLineArgType ArgType, const char* name, bool caseSensitive = false) const = 0; - // </interfuscator:shuffle> -}; - -#endif // CRYINCLUDE_CRYCOMMON_ICMDLINE_H diff --git a/Code/CryEngine/CryCommon/IConsole.h b/Code/CryEngine/CryCommon/IConsole.h deleted file mode 100644 index 7306c027c9..0000000000 --- a/Code/CryEngine/CryCommon/IConsole.h +++ /dev/null @@ -1,688 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_ICONSOLE_H -#define CRYINCLUDE_CRYCOMMON_ICONSOLE_H -#pragma once - -#include <CryCommon/platform.h> - -struct SFunctor; - -struct ConsoleBind; - -struct ICVar; -class ITexture; -class ICrySizer; -struct ISystem; - -#define CVAR_INT 1 -#define CVAR_FLOAT 2 -#define CVAR_STRING 3 - -// By default, cvars registered as const, read-only, or cheat cannot be modified in release builds for security. -// The common practice has been to hard-code the default values of all these 'const' cvars before generating a release build. -// However, this is restrictive because the cannot be modified at run-time in release, and so cannot differ between (or during) levels. -// If you wish, you can disable this restriction by defining ALLOW_CONST_CVAR_MODIFICATIONS 1 (which is the default for non-release builds), -// thus allowing const/read-only/cheat cvars to be set at run-time in release, and removing the need to explicitly hard-code your default values for release builds. -#if defined(_RELEASE) -#define ALLOW_AUDIT_CVARS 0 -#define ALLOW_CONST_CVAR_MODIFICATIONS AZ_TRAIT_CVARS_ENABLED_FOR_RELEASE_BUILDS -#define LOG_CVAR_INFRACTIONS 0 -#define LOG_CVAR_USAGE 0 -#else -#define ALLOW_AUDIT_CVARS 1 -#define ALLOW_CONST_CVAR_MODIFICATIONS 1 -#define LOG_CVAR_INFRACTIONS 1 -#define LOG_CVAR_USAGE 1 -#endif // defined(_RELEASE) - -#define CVAR_GROUPS_ARE_PRIVILEGED 1 // allows cvar groups to manipulate const/cheat cvars (turn off to log group cvar manipulation) -#define LOG_CVAR_INFRACTIONS_CALLSTACK (LOG_CVAR_INFRACTIONS && 0) // logs the callstack when certain cvar issues arise; helpful in tracking down where the problem originated - -// If this flag is set during registering a console variable, and the variable exists, -// then the variable will store its value in memory given by src -#define CVF_CHANGE_SOURCE (1u << 16) - -// Flags used by ICVar -enum EVarFlags -{ - VF_NULL = 0x00000000, // just to have one recognizable spot where the flags are located in the Register call - VF_CHEAT = 0x00000002, // stays in the default state when cheats are disabled - VF_DEV_ONLY = 0x00000004, // cvar is only registered with the console in non release builds - VF_DEDI_ONLY = 0x00000008, // cvar is only registered with the console in non release or dedicated server builds - VF_NET_SYNCED = 0x00000080, // synchronised between server and client(s); server authorative - VF_DUMPTODISK = 0x00000100, - VF_READONLY = 0x00000800, // can not be changed by the user - VF_REQUIRE_LEVEL_RELOAD = 0x00001000, - VF_REQUIRE_APP_RESTART = 0x00002000, - VF_WARNING_NOTUSED = 0x00004000, // shows warning that this var was not used in config file - VF_COPYNAME = 0x00008000, // otherwise the const char * to the name will be stored without copying the memory - VF_MODIFIED = 0x00010000, // Set when variable value modified. - VF_WASINCONFIG = 0x00020000, // Set when variable was present in config file. - VF_BITFIELD = 0x00040000, // Allow bitfield setting syntax. - VF_RESTRICTEDMODE = 0x00080000, // is visible and usable in restricted (normal user) console mode - VF_INVISIBLE = 0x00100000, // Invisible to the user in console - VF_ALWAYSONCHANGE = 0x00200000, // Always accept variable value and call on change callback even if variable value didnt change - VF_BLOCKFRAME = 0x00400000, // Blocks the execution of console commands for one frame - VF_CONST_CVAR = 0x00800000, // Set if it is a const cvar not to be set inside cfg-files - VF_CHEAT_ALWAYS_CHECK = 0x01000000, // This variable is critical to check in every hash, since it's extremely vulnerable - VF_CHEAT_NOCHECK = 0x02000000, // This variable is set as VF_CHEAT but doesn't have to be checked/hashed since it's harmless to hack - VF_SYSSPEC_OVERWRITE = 0x04000000, // This variable is specified by system.cfg with the intention to overwrite all subsequent settings - VF_CVARGRP_IGNOREINREALVAL = 0x08000000, // This variable will be ignored when cvar group's real val is checked (Needed for cvars which are in a group but change in various situations) - VF_RESETTABLE = 0x10000000, // This variable will be reset when a commanded reset to defaults occurs - VF_RENDERER_CVAR = 0x20000000, // The update of this variable will be done in render thread - VF_DEPRECATED = 0x40000000, // Deprecated cvars use default values which cannot be modified outside the code - VF_EXPERIMENTAL = 0x80000000, // This variable is used by WIP or experimental feature -}; - -struct ICVarDumpSink -{ - // <interfuscator:shuffle> - virtual ~ICVarDumpSink(){} - virtual void OnElementFound(ICVar* pCVar) = 0; - // </interfuscator:shuffle> -}; - -struct IKeyBindDumpSink -{ - // <interfuscator:shuffle> - virtual ~IKeyBindDumpSink(){} - virtual void OnKeyBindFound(const char* sBind, const char* sCommand) = 0; - // </interfuscator:shuffle> -}; - -struct IOutputPrintSink -{ - // <interfuscator:shuffle> - virtual ~IOutputPrintSink(){} - virtual void Print(const char* inszText) = 0; - // </interfuscator:shuffle> -}; - -// Callback class to derive from when you want to receive callbacks when console var changes. -struct IConsoleVarSink -{ - // <interfuscator:shuffle> - virtual ~IConsoleVarSink(){} - // Called by Console before changing console var value, to validate if var can be changed. - // Return value: true if ok to change value, false if should not change value. - virtual bool OnBeforeVarChange(ICVar* pVar, const char* sNewValue) = 0; - // Called by Console after variable has changed value - virtual void OnAfterVarChange(ICVar* pVar) = 0; - // </interfuscator:shuffle> -}; - -#if defined(GetCommandLine) -#undef GetCommandLine -#endif - -// Interface to the arguments of the console command. -struct IConsoleCmdArgs -{ - // <interfuscator:shuffle> - virtual ~IConsoleCmdArgs(){} - // Gets number of arguments supplied to the command (including the command itself) - virtual int GetArgCount() const = 0; - // Gets argument by index, nIndex must be in 0 <= nIndex < GetArgCount() - virtual const char* GetArg(int nIndex) const = 0; - // Gets complete command line - virtual const char* GetCommandLine() const = 0; - // </interfuscator:shuffle> -}; - -// Interface to the arguments of the console command. -struct IConsoleArgumentAutoComplete -{ - // <interfuscator:shuffle> - virtual ~IConsoleArgumentAutoComplete(){} - // Gets number of matches for the argument to auto complete. - virtual int GetCount() const = 0; - // Gets argument value by index, nIndex must be in 0 <= nIndex < GetCount() - virtual const char* GetValue(int nIndex) const = 0; - // </interfuscator:shuffle> -}; - -// This a definition of the console command function that can be added to console with AddCommand. -typedef void (* ConsoleCommandFunc)(IConsoleCmdArgs*); - -// This a definition of the callback function that is called when variable change. -typedef void (* ConsoleVarFunc)(ICVar*); - -/* Summary: Interface to the engine console. - - Description: - The engine console allow to manipulate the internal engine parameters - and to invoke commands. - This interface allow external modules to integrate their functionalities - into the console as commands or variables. - - IMPLEMENTATIONS NOTES: - The console takes advantage of the script engine to store the console variables, - this mean that all variables visible through script and console. -*/ -struct IConsole -{ - // <interfuscator:shuffle> - virtual ~IConsole(){} - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Deletes the console - virtual void Release() = 0; - - // Initialize this instance of engine console - // Arguments: - // pSystem - an instance of ISystem - virtual void Init(ISystem* pSystem) = 0; - // Create a new console variable that store the value in a string - // Arguments: - // sName - console variable name - // sValue - default value - // nFlags - user defined flag, this parameter is used by other subsystems and doesn't affect the console variable (basically of user data) - // help - help text that is shown when you use <sName> ? in the console - // Return: - // pointer to the interface ICVar - virtual ICVar* RegisterString(const char* sName, const char* sValue, int nFlags, const char* help = "", ConsoleVarFunc pChangeFunc = 0) = 0; - // Create a new console variable that store the value in a int - // Arguments: - // sName - console variable name - // iValue - default value - // nFlags - user defined flag, this parameter is used by other subsystems and doesn't affect the console variable (basically of user data) - // help - help text that is shown when you use <sName> ? in the console - // Return: - // pointer to the interface ICVar - virtual ICVar* RegisterInt(const char* sName, int iValue, int nFlags, const char* help = "", ConsoleVarFunc pChangeFunc = 0) = 0; - // Create a new console variable that store the value in a int64 - // Arguments: - // sName - console variable name - // iValue - default value - // nFlags - user defined flag, this parameter is used by other subsystems and doesn't affect the console variable (basically of user data) - // help - help text that is shown when you use <sName> ? in the console - // Return: - // pointer to the interface ICVar - virtual ICVar* RegisterInt64(const char* sName, int64 iValue, int nFlags, const char* help = "", ConsoleVarFunc pChangeFunc = 0) = 0; - // Create a new console variable that store the value in a float - // Arguments: - // sName - console variable name - // fValue - default value - // nFlags - user defined flag, this parameter is used by other subsystems and doesn't affect the console variable (basically of user data) - // help - help text that is shown when you use <sName> ? in the console - // Return: - // pointer to the interface ICVar - virtual ICVar* RegisterFloat(const char* sName, float fValue, int nFlags, const char* help = "", ConsoleVarFunc pChangeFunc = 0) = 0; - - // Create a new console variable that will update the user defined float - // Arguments: - // sName - console variable name - // src - pointer to the memory that will be updated - // nFlags - user defined flag, this parameter is used by other subsystems and doesn't affect the console variable (basically of user data) - // help - help text that is shown when you use <sName> ? in the console - // allowModify - allow modification through config vars, prevents missing modifications in release mode - // Return: - // pointer to the interface ICVar - virtual ICVar* Register(const char* name, float* src, float defaultvalue, int nFlags = 0, const char* help = "", ConsoleVarFunc pChangeFunc = 0, bool allowModify = true) = 0; - // Create a new console variable that will update the user defined integer - // Arguments: - // sName - console variable name - // src - pointer to the memory that will be updated - // nFlags - user defined flag, this parameter is used by other subsystems and doesn't affect the console variable (basically of user data) - // help - help text that is shown when you use <sName> ? in the console - // allowModify - allow modification through config vars, prevents missing modifications in release mode - // Return: - // pointer to the interface ICVar - virtual ICVar* Register(const char* name, int* src, int defaultvalue, int nFlags = 0, const char* help = "", ConsoleVarFunc pChangeFunc = 0, bool allowModify = true) = 0; - - // Create a new console variable that will update the user defined pointer to null terminated string - // Arguments: - // sName - console variable name - // src - pointer to the memory that will be updated - // nFlags - user defined flag, this parameter is used by other subsystems and doesn't affect the console variable (basically of user data) - // help - help text that is shown when you use <sName> ? in the console - // allowModify - allow modification through config vars, prevents missing modifications in release mode - // Return: - // pointer to the interface ICVar - virtual ICVar* Register(const char* name, const char** src, const char* defaultvalue, int nFlags = 0, const char* help = "", ConsoleVarFunc pChangeFunc = 0, bool allowModify = true) = 0; - - // Registers an existing console variable - // Should only be used with static duration objects, object is never freed - // Arguments: - // pVar - the existing console variable - // Return: - // pointer to the interface ICVar (that was passed in) - virtual ICVar* Register(ICVar* pVar) = 0; - - // ! Remove a variable from the console - // @param sVarName console variable name - // @param bDelete if true the variable is deleted - // @see ICVar - virtual void UnregisterVariable(const char* sVarName, bool bDelete = false) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Set the y coordinate where the console will stop to scroll when is dropped - // @param value y in screen coordinates - virtual void SetScrollMax(int value) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // add output sink (clases which are interested in the output) - order is not guaranteed - // @param inpSink must not be 0 and is not allowed to be added twice - virtual void AddOutputPrintSink(IOutputPrintSink* inpSink) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // remove output sink (clases which are interested in the output) - order is not guaranteed - // @param inpSink must not be 0 and has to be added before - virtual void RemoveOutputPrintSink(IOutputPrintSink* inpSink) = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // show/hide the console - // @param specifies if the window must be (true=show,false=hide) - // @param specifies iRequestScrollMax <=0 if not used, otherwise it sets SetScrollMax temporary to the given value - virtual void ShowConsole(bool show, int iRequestScrollMax = -1) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Dump all console-variables to a callback-interface - // @param Callback callback-interface which needs to be called for each element - virtual void DumpCVars(ICVarDumpSink* pCallback, unsigned int nFlagsFilter = 0) = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Bind a console command to a key - // @param sCmd console command that must be executed - // @param sRes name of the key to invoke the command - virtual void CreateKeyBind(const char* sCmd, const char* sRes) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Sets the background-image - // @param pImage background-image - virtual void SetImage(ITexture* pImage, bool bDeleteCurrent) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Retrieves the background-image - // @return background-image - virtual ITexture* GetImage() = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Sets static/scroll background-mode - // @param bStatic true if static - virtual void StaticBackground(bool bStatic) = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Sets the loading-background-image - // @param pImage background-image - virtual void SetLoadingImage(const char* szFilename) = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Iterate through the lines - used for dedicated server (truncated if needed) - // @param indwLineNo 0.. counted from the last printed line on - // @param outszBuffer pointer to the destination string buffer (zero terminated afterwards), must not be 0 - // @param indwBufferSize 1.. size of the buffer - // @return true=line was returned, false=there are no more lines - - virtual bool GetLineNo(int indwLineNo, char* outszBuffer, int indwBufferSize) const = 0; - - // @return current number of lines in the console - virtual int GetLineCount() const = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Retrieve a console variable by name - not case sensitive - // @param name variable name - // @return a pointer to the ICVar interface, NULL if is not found - // @see ICVar - virtual ICVar* GetCVar(const char* name) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Read a value from a configuration file (.ini) and return the value - // @param szVarName variable name - // @param szFileName source configuration file - // @param def_val default value (if the variable is not found into the file) - // @return the variable value - virtual char* GetVariable(const char* szVarName, const char* szFileName, const char* def_val) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Read a value from a configuration file (.ini) and return the value - // @param szVarName variable name - // @param szFileName source configuration file - // @param def_val default value (if the variable is not found into the file) - // @return the variable value - virtual float GetVariable(const char* szVarName, const char* szFileName, float def_val) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Print a string in the console and go to the new line - // @param s the string to print - virtual void PrintLine(const char* s) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Append a string in the last console line - // @param s the string to print - virtual void PrintLinePlus(const char* s) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Retrieve the status of the console (active/not active) - // @return the variable value(true = active/false = not active) - virtual bool GetStatus() = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Clear the console text - virtual void Clear() = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Update the console - virtual void Update() = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Draw the console - virtual void Draw() = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Description: - // Register a new console command. - // Arguments: - // sCommand - Command name. - // func - Pointer to the console command function to be called when command is invoked. - // nFlags - Bitfield consist of VF_ flags (e.g. VF_CHEAT) - // sHelp - Help string, will be displayed when typing in console "command ?". - // Return - // True if successful, false otherwise. - virtual bool AddCommand(const char* sCommand, ConsoleCommandFunc func, int nFlags = 0, const char* sHelp = NULL) = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Description: - // Register a new console command that execute script function. - // EG "Game.Connect(%1)" the symbol "%1" will be replaced with the command parameter 1 - // writing in the console "connect 127.0.0.1" will invoke Game.Connect("127.0.0.1") - // Arguments: - // sCommand - Command name. - // sScriptFunc - Script function to be executed when command is invoked. - // nFlags - Bitfield consist of VF_ flags (e.g. VF_CHEAT) - // sHelp - Help string, will be displayed when typing in console "command ?". - // Return - // True if successful, false otherwise. - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - virtual bool AddCommand(const char* sName, const char* sScriptFunc, int nFlags = 0, const char* sHelp = NULL) = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Description: - // Removes a console command which was previously registered with AddCommand. - // Arguments: - // sCommand - Command name - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - virtual void RemoveCommand(const char* sName) = 0; - - // Execute a string in the console - // Arguments: - // command - console command e.g. "map testy" - no leading slash - // bSilentMode - true=suppresses log in error case and logging the command to the console - // bDeferExecution - true=the command is stored in special fifo that allows delayed execution - // by using wait_seconds and wait_frames commands - // - virtual void ExecuteString(const char* command, bool bSilentMode = false, bool bDeferExecution = false) = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Print a message into the log and abort the execution of the application - // @param message error string to print in the log - virtual void Exit(const char* command, ...) PRINTF_PARAMS(2, 3) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Return true if the console is opened - // @return the variable value(true = opened/false = closed) - virtual bool IsOpened() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Auto completion. - ////////////////////////////////////////////////////////////////////////// - virtual int GetNumVars() = 0; - - virtual int GetNumVisibleVars() = 0; - - // Arguments: - // szPrefix - 0 or prefix e.g. "sys_spec_" - // Return - // used size - virtual size_t GetSortedVars(const char** pszArray, size_t numItems, const char* szPrefix = 0) = 0; - virtual const char* AutoComplete(const char* substr) = 0; - virtual const char* AutoCompletePrev(const char* substr) = 0; - virtual const char* ProcessCompletion(const char* szInputBuffer) = 0; - virtual void RegisterAutoComplete(const char* sVarOrCommand, IConsoleArgumentAutoComplete* pArgAutoComplete) = 0; - virtual void UnRegisterAutoComplete(const char* sVarOrCommand) = 0; - // - virtual void ResetAutoCompletion() = 0; - ////////////////////////////////////////////////////////////////////////// - - // Calculation of the memory used by the whole console system - virtual void GetMemoryUsage (ICrySizer* pSizer) const = 0; - - // Function related to progress bar - virtual void ResetProgressBar(int nProgressRange) = 0; - // Function related to progress bar - virtual void TickProgressBar() = 0; - - // Arguments: - // szLine - must not be 0 - virtual void SetInputLine(const char* szLine) = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Dump all key bindings to a callback-interface - // @param Callback callback-interface which needs to be called for each element - virtual void DumpKeyBinds(IKeyBindDumpSink* pCallback) = 0; - virtual const char* FindKeyBind(const char* sCmd) const = 0; - - ////////////////////////////////////////////////////////////////////////// - // Hashing of cvars (for anti-cheat). Separates setting of range, calculation, - // and retrieval of result so calculation can be done at a known safe point - // (e.g end of frame) when we know cvars won't be modified or in temporary state - - // Get Number of cvars that can be hashed - virtual int GetNumCheatVars() = 0; - // Set the range of cvars - virtual void SetCheatVarHashRange(size_t firstVar, size_t lastVar) = 0; - // Calculate the hash from current cvars - virtual void CalcCheatVarHash() = 0; - // Since hash is calculated async, check if it's completed - virtual bool IsHashCalculated() = 0; - // Get the hash calculated - virtual uint64 GetCheatVarHash() = 0; - virtual void PrintCheatVars(bool bUseLastHashRange) = 0; - virtual char* GetCheatVarAt(uint32 nOffset) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Console variable sink. - // Adds a new console variables sink callback. - virtual void AddConsoleVarSink(IConsoleVarSink* pSink) = 0; - //! Removes a console variables sink callback. - virtual void RemoveConsoleVarSink(IConsoleVarSink* pSink) = 0; - - ////////////////////////////////////////////////////////////////////////// - // History - ////////////////////////////////////////////////////////////////////////// - - // \param bUpOrDown true=after pressed "up", false=after pressed "down" - // \return 0 if there is no history line or pointer to the null terminated history line - virtual const char* GetHistoryElement(bool bUpOrDown) = 0; - //! \param szCommand must not be 0 - virtual void AddCommandToHistory(const char* szCommand) = 0; - - ////////////////////////////////////////////////////////////////////////// - // - virtual void LoadConfigVar(const char* sVariable, const char* sValue) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Enable or disable the activation key (tilde by default). - // This is useful when user is in a text field and want to be able to enter the default key. - // bEnable=true console will show - // bEnable=false console will no show - virtual void EnableActivationKey(bool bEnable) = 0; - - - // </interfuscator:shuffle> - - virtual void SetClientDataProbeString(const char* pName, const char* pValue) = 0; -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// Description: -// This interface for the remote console -struct IRemoteConsoleListener -{ - virtual ~IRemoteConsoleListener() {} - - virtual void OnConsoleCommand([[maybe_unused]] const char* cmd) {}; - virtual void OnGameplayCommand([[maybe_unused]] const char* cmd) {}; -}; - -struct IRemoteConsole -{ - virtual ~IRemoteConsole() {}; - - virtual void RegisterConsoleVariables() = 0; - virtual void UnregisterConsoleVariables() = 0; - - virtual void Start() = 0; - virtual void Stop() = 0; - virtual bool IsStarted() const = 0; - - virtual void AddLogMessage(const char* log) = 0; - virtual void AddLogWarning(const char* log) = 0; - virtual void AddLogError(const char* log) = 0; - - virtual void Update() = 0; - - virtual void RegisterListener(IRemoteConsoleListener* pListener, const char* name) = 0; - virtual void UnregisterListener(IRemoteConsoleListener* pListener) = 0; -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// Description: -// This interface is the 1:1 "C++ representation" -// of a console variable. -// Note: -// A console variable is accessible in C++ trough -// this interface and in all scripts as global variable -// (with the same name of the variable in the console) -struct ICVar -{ - enum EConsoleLogMode - { - eCLM_Off, // off - eCLM_ConsoleAndFile, // normal info to console and file - eCLM_FileOnly, // normal info to file only - eCLM_FullInfo // full info to file only - }; - - // <interfuscator:shuffle> - // TODO make protected; - virtual ~ICVar() {} - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // delete the variable - // NOTE: the variable will automatically unregister itself from the console - virtual void Release() = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Return the integer value of the variable - // @return the value - virtual int GetIVal() const = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Return the 64-bit integer value of the variable - // @return the value - virtual int64 GetI64Val() const = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Return the float value of the variable - // @return the value - virtual float GetFVal() const = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Return the string value of the variable, don't store pointer as multiple calls to this function might return same memory ptr - // @return the value - virtual const char* GetString() const = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Return the data probe string value of the variable, don't store pointer as multiple calls to this function might return same memory ptr - // @return the value - virtual const char* GetDataProbeString() const = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Reset the CVar to its default value if possible - virtual void Reset() {} - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // set the string value of the variable - // @param s string representation the value - virtual void Set(const char* s) = 0; - - // Force to set the string value of the variable - can be called - // from inside code only - // @param s string representation the value - virtual void ForceSet(const char* s) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // set the float value of the variable - // @param s float representation the value - virtual void Set(float f) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // set the float value of the variable - // @param s integer representation the value - virtual void Set(int i) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // clear the specified bits in the flag field - virtual void ClearFlags (int flags) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // return the variable's flags - // @return the variable's flags - // See Also: EVarFlags - virtual int GetFlags() const = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Set the variable's flags - // See Also: EVarFlags - virtual int SetFlags(int flags) = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // return the primary variable's type - // @return the primary variable's type e.g. CVAR_INT, CVAR_FLOAT, CVAR_STRING - virtual int GetType() = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // return the variable's name - // @return the variable's name - virtual const char* GetName() const = 0; - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // return the variable's help text - // @return the variable's help text, can be 0 if no help is available - virtual const char* GetHelp() = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // return if the variable may be modified in config files - // @return if the variable may be modified in config files - virtual bool IsConstCVar() const = 0; - - ////////////////////////////////////////////////////////////////////////// - // Set a new on change function callback. - // Deprecated function. The functor should be preferred. - virtual void SetOnChangeCallback(ConsoleVarFunc pChangeFunc) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Adds a new on change functor to the list. - // It will add from index 1 on (0 is reserved). - // Returns an ID to use when getting or removing the functor - virtual uint64 AddOnChangeFunctor(const SFunctor& pChangeFunctor) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Returns the number of registered on change functos. - virtual uint64 GetNumberOfOnChangeFunctors() const = 0; - - ////////////////////////////////////////////////////////////////////////// - // Returns the functors with the specified id. - virtual const SFunctor& GetOnChangeFunctor(uint64 nFunctorId) const = 0; - - ////////////////////////////////////////////////////////////////////////// - // Removes an on change functor - // returns true if removal was successful. - virtual bool RemoveOnChangeFunctor(uint64 nFunctorId) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Get the current callback function. - virtual ConsoleVarFunc GetOnChangeCallback() const = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // - virtual void GetMemoryUsage(class ICrySizer* pSizer) const = 0; - - ////////////////////////////////////////////////////////////////////////// - // only useful for CVarGroups, other types return GetIVal() - // CVarGroups set multiple other CVars and this function returns - // the integer value the CVarGroup should have, when looking at the controlled cvars - // Returns: - // value that would represent the state, -1 if the state cannot be found - virtual int GetRealIVal() const = 0; - - virtual void SetLimits(float min, float max) = 0; - virtual void GetLimits(float& min, float& max) = 0; - virtual bool HasCustomLimits() = 0; - - // only useful for CVarGroups - // log difference between expected state and real state - virtual void DebugLog([[maybe_unused]] const int iExpectedValue, [[maybe_unused]] const EConsoleLogMode mode) const {} - // </interfuscator:shuffle> - - // Set the data probe string value of the variable - virtual void SetDataProbeString(const char* pDataProbeString) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMON_ICONSOLE_H diff --git a/Code/CryEngine/CryCommon/IEntityRenderState.h b/Code/CryEngine/CryCommon/IEntityRenderState.h deleted file mode 100644 index bd18a7407e..0000000000 --- a/Code/CryEngine/CryCommon/IEntityRenderState.h +++ /dev/null @@ -1,787 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_IENTITYRENDERSTATE_H -#define CRYINCLUDE_CRYCOMMON_IENTITYRENDERSTATE_H -#pragma once - -#include <IRenderer.h> -#include <limits> -#include <AzCore/Component/EntityId.h> - -namespace AZ -{ - class Vector2; -} - -struct IMaterial; -struct IVisArea; -struct SRenderingPassInfo; -struct SRendItemSorter; -struct SFrameLodInfo; -struct pe_params_area; -struct pe_articgeomparams; - -// @NOTE: When removing an item from this enum, replace it with a dummy - ID's from this enum are stored in data and should not change. -enum EERType -{ - eERType_NotRenderNode, - eERType_Dummy_10, - eERType_Dummy8, - eERType_Light, - eERType_Cloud, - eERType_TerrainSystem, // used to be eERType_Dummy_1 which used to be eERType_VoxelObject, preserve order for compatibility - eERType_FogVolume, - eERType_Decal, - eERType_Dummy_6, // used to be eERType_ParticleEmitter, preserve order for compatibility - eERType_WaterVolume, - eERType_Dummy_5, // used to be eERType_WaterWave, preserve order for compatibility - eERType_Dummy_7, // used to be eERType_Road, preserve order for compatibility - eERType_DistanceCloud, - eERType_VolumeObject, - eERType_Dummy_0, // used to be eERType_AutoCubeMap, preserve order for compatibility - eERType_Rope, - eERType_PrismObject, - eERType_Dummy_2, // used to be eERType_IsoMesh, preserve order for compatibility - eERType_Dummy_4, - eERType_RenderComponent, - eERType_GameEffect, - eERType_BreakableGlass, - eERType_Dummy_3, // used to be eERType_LightShape, preserve order for compatibility - eERType_Dummy_9, - eERType_GeomCache, - eERType_StaticMeshRenderComponent, - eERType_DynamicMeshRenderComponent, - eERType_SkinnedMeshRenderComponent, - eERType_TypesNum, // MUST BE AT END TOTAL NUMBER OF ERTYPES -}; - -enum ERNListType -{ - eRNListType_Unknown, - eRNListType_DecalsAndRoads, - eRNListType_ListsNum, - eRNListType_First = eRNListType_Unknown, // This should be the last member - // And it counts on eRNListType_Unknown - // being the first enum element. -}; - -enum EOcclusionObjectType -{ - eoot_OCCLUDER, - eoot_OCEAN, - eoot_OCCELL, - eoot_OCCELL_OCCLUDER, - eoot_OBJECT, - eoot_OBJECT_TO_LIGHT, - eoot_TERRAIN_NODE, - eoot_PORTAL, -}; - -// RenderNode flags - -#define ERF_GOOD_OCCLUDER BIT(0) -#define ERF_PROCEDURAL BIT(1) -#define ERF_CLONE_SOURCE BIT(2) // set if this object was cloned from another one -#define ERF_CASTSHADOWMAPS BIT(3) // if you ever set this flag, be sure also to set ERF_HAS_CASTSHADOWMAPS -#define ERF_RENDER_ALWAYS BIT(4) -#define ERF_DYNAMIC_DISTANCESHADOWS BIT(5) -#define ERF_HIDABLE BIT(6) -#define ERF_HIDABLE_SECONDARY BIT(7) -#define ERF_HIDDEN BIT(8) -#define ERF_SELECTED BIT(9) -#define ERF_PROCEDURAL_ENTITY BIT(10) // this is an object generated at runtime which has a limited lifetime (matches procedural entity) -#define ERF_OUTDOORONLY BIT(11) -#define ERF_NODYNWATER BIT(12) -#define ERF_EXCLUDE_FROM_TRIANGULATION BIT(13) -#define ERF_REGISTER_BY_BBOX BIT(14) -#define ERF_STATIC_INSTANCING BIT(15) -#define ERF_VOXELIZE_STATIC BIT(16) -#define ERF_NO_PHYSICS BIT(17) -#define ERF_NO_DECALNODE_DECALS BIT(18) -#define ERF_REGISTER_BY_POSITION BIT(19) -#define ERF_COMPONENT_ENTITY BIT(20) -#define ERF_RECVWIND BIT(21) -#define ERF_COLLISION_PROXY BIT(22) // Collision proxy is a special object that is only visible in editor -// and used for physical collisions with player and vehicles. -#define ERF_LOD_BBOX_BASED BIT(23) // Lod changes based on bounding boxes. -#define ERF_SPEC_BIT0 BIT(24) // Bit0 of min config specification. -#define ERF_SPEC_BIT1 BIT(25) // Bit1 of min config specification. -#define ERF_SPEC_BIT2 BIT(26) // Bit2 of min config specification. -#define ERF_SPEC_BITS_MASK (ERF_SPEC_BIT0 | ERF_SPEC_BIT1 | ERF_SPEC_BIT2) // Bit mask of the min spec bits. -#define ERF_SPEC_BITS_SHIFT (24) // Bit offset of the ERF_SPEC_BIT0. -#define ERF_RAYCAST_PROXY BIT(27) // raycast proxy is only used for raycasting -#define ERF_HUD BIT(28) // Hud object that can avoid some visibility tests -#define ERF_RAIN_OCCLUDER BIT(29) // Is used for rain occlusion map -#define ERF_HAS_CASTSHADOWMAPS BIT(30) // at one point had ERF_CASTSHADOWMAPS set -#define ERF_ACTIVE_LAYER BIT(31) // the node is on a currently active layer - -struct IShadowCaster -{ - // <interfuscator:shuffle> - virtual ~IShadowCaster(){} - virtual bool HasOcclusionmap([[maybe_unused]] int nLod, [[maybe_unused]] IRenderNode* pLightOwner) { return false; } - virtual CLodValue ComputeLod(int wantedLod, [[maybe_unused]] const SRenderingPassInfo& passInfo) { return CLodValue(wantedLod); } - virtual void Render(const SRendParams& RendParams, const SRenderingPassInfo& passInfo) = 0; - virtual const AABB GetBBoxVirtual() = 0; - virtual void FillBBox(AABB& aabb) = 0; - virtual EERType GetRenderNodeType() = 0; - virtual bool IsRenderNode() { return true; } - // </interfuscator:shuffle> - uint8 m_cStaticShadowLod; -}; - -// Optional filter function for octree queries to perform custom filtering of the results. -// return true to keep the render node, false to filter it out. -using ObjectTreeQueryFilterCallback = AZStd::function<bool(IRenderNode*, EERType)>; - -struct IOctreeNode -{ -public: - virtual ~IOctreeNode() {}; - - virtual void GetObjectsByType(PodArray<IRenderNode*>& lstObjects, EERType objType, const AABB* pBBox, ObjectTreeQueryFilterCallback filterCallback = nullptr) = 0; - - struct CVisArea* m_pVisArea; -}; - -struct SLodDistDissolveTransitionState -{ - float fStartDist; - int8 nOldLod; - int8 nNewLod; - bool bFarside; -}; - -struct SLightInfo -{ - bool operator == (const SLightInfo& other) const - { return other.vPos.IsEquivalent(vPos, 0.1f) && fabs(other.fRadius - fRadius) < 0.1f; } - Vec3 vPos; - float fRadius; - bool bAffecting; -}; - -struct IRenderNode - : public IShadowCaster -{ - enum EInternalFlags - { - DECAL_OWNER = BIT(0), // Owns some decals. - REQUIRES_NEAREST_CUBEMAP = BIT(1), // Pick nearest cube map - UPDATE_DECALS = BIT(2), // The node changed geometry - decals must be updated. - REQUIRES_FORWARD_RENDERING = BIT(3), // Special shadow processing needed. - WAS_INVISIBLE = BIT(4), // Was invisible last frame. - WAS_IN_VISAREA = BIT(5), // Was inside vis-ares last frame. - WAS_FARAWAY = BIT(6), // Was considered 'far away' for the purposes of physics deactivation. - HAS_OCCLUSION_PROXY = BIT(7) // This node has occlusion proxy. - }; - - IRenderNode() - { - m_dwRndFlags = 0; - m_fViewDistanceMultiplier = static_cast<float>(IRenderNode::VIEW_DISTANCE_MULTIPLIER_MAX); // By default object is not limited by distance. - m_ucLodRatio = 100; - m_pOcNode = 0; - m_fWSMaxViewDist = 0; - m_nInternalFlags = 0; - m_nMaterialLayers = 0; - m_pRNTmpData = NULL; - m_pPrev = m_pNext = NULL; - m_nSID = 0; - m_cShadowLodBias = 0; - m_cStaticShadowLod = 0; - } - - virtual bool CanExecuteRenderAsJob() { return false; } - - // <interfuscator:shuffle> - // Debug info about object. - virtual const char* GetName() const = 0; - virtual const char* GetEntityClassName() const = 0; - virtual string GetDebugString([[maybe_unused]] char type = 0) const { return ""; } - virtual float GetImportance() const { return 1.f; } - - // Description: - // Releases IRenderNode. - virtual void ReleaseNode([[maybe_unused]] bool bImmediate = false) { delete this; } - - - virtual IRenderNode* Clone() const { return NULL; } - - // Description: - // Sets render node transformation matrix. - virtual void SetMatrix([[maybe_unused]] const Matrix34& mat) {} - - // Description: - // Gets local bounds of the render node. - virtual void GetLocalBounds(AABB& bbox) { AABB WSBBox(GetBBox()); bbox = AABB(WSBBox.min - GetPos(true), WSBBox.max - GetPos(true)); } - - virtual Vec3 GetPos(bool bWorldOnly = true) const = 0; - virtual const AABB GetBBox() const = 0; - virtual void FillBBox(AABB& aabb) { aabb = GetBBox(); } - virtual void SetBBox(const AABB& WSBBox) = 0; - - virtual void SetScale([[maybe_unused]] const Vec3& scale) {} - - //Get the scales assuming the scale is uniform or per column as needed. - virtual float GetUniformScale() { return 1.0f; } - virtual float GetColumnScale([[maybe_unused]] int column) { return 1.0f; } - - // Summary: - // Changes the world coordinates position of this node by delta - // Don't forget to call this base function when overriding it. - virtual void OffsetPosition(const Vec3& delta) = 0; - - // Return true when the node is initialized and ready to render - virtual bool IsReady() const { return true; } - - // Summary: - // Renders node geometry - virtual void Render(const struct SRendParams& EntDrawParams, const SRenderingPassInfo& passInfo) = 0; - - // Hides/disables node in renderer. - virtual void Hide(bool bHide) { SetRndFlags(ERF_HIDDEN, bHide); } - bool IsHidden() const { return (GetRndFlags() & ERF_HIDDEN) != 0; } - - // Gives access to object components. - virtual struct IStatObj* GetEntityStatObj(unsigned int nPartId = 0, unsigned int nSubPartId = 0, Matrix34A* pMatrix = NULL, bool bReturnOnlyVisible = false); - virtual _smart_ptr<IMaterial> GetEntitySlotMaterial([[maybe_unused]] unsigned int nPartId, [[maybe_unused]] bool bReturnOnlyVisible = false, [[maybe_unused]] bool* pbDrawNear = NULL) { return NULL; } - virtual void SetEntityStatObj([[maybe_unused]] unsigned int nSlot, [[maybe_unused]] IStatObj* pStatObj, [[maybe_unused]] const Matrix34A* pMatrix = NULL) {}; - virtual int GetSlotCount() const { return 1; } - - // Summary: - // Returns IRenderMesh of the object. - virtual struct IRenderMesh* GetRenderMesh([[maybe_unused]] int nLod) { return 0; }; - - // Description: - // Allows to adjust default lod distance settings, - // if fLodRatio is 100 - default lod distance is used. - virtual void SetLodRatio(int nLodRatio) { m_ucLodRatio = static_cast<unsigned char>(min(255, max(0, nLodRatio))); } - - // Summary: - // Gets material layers mask. - virtual uint8 GetMaterialLayers() const { return m_nMaterialLayers; } - - - // Summary - // Physicalizes if it isn't already. - virtual void CheckPhysicalized() {}; - - // Summary: - // Physicalizes node. - virtual void Physicalize([[maybe_unused]] bool bInstant = false) {} - - virtual ~IRenderNode() { assert(!m_pRNTmpData); }; - - // Summary: - // Sets override material for this instance. - virtual void SetMaterial(_smart_ptr<IMaterial> pMat) = 0; - // Summary: - // Queries override material of this instance. - virtual _smart_ptr<IMaterial> GetMaterial(Vec3* pHitPos = NULL) = 0; - virtual _smart_ptr<IMaterial> GetMaterialOverride() = 0; - virtual void GetMaterials(AZStd::vector<_smart_ptr<IMaterial>>& materials) - { - _smart_ptr<IMaterial> currentMaterial = GetMaterialOverride(); - if (!currentMaterial) - { - currentMaterial = GetMaterial(); - } - if (currentMaterial) - { - materials.push_back(currentMaterial); - } - } - - // Used by the editor during export - virtual void SetCollisionClassIndex([[maybe_unused]] int tableIndex) {} - - virtual int GetEditorObjectId() { return 0; } - virtual void SetEditorObjectId([[maybe_unused]] int nEditorObjectId) {} - virtual void SetStatObjGroupIndex([[maybe_unused]] int nVegetationGroupIndex) { } - virtual int GetStatObjGroupId() const { return -1; } - virtual void SetLayerId([[maybe_unused]] uint16 nLayerId) { } - virtual uint16 GetLayerId() { return 0; } - virtual float GetMaxViewDist() = 0; - - virtual EERType GetRenderNodeType() = 0; - virtual bool IsAllocatedOutsideOf3DEngineDLL() - { - return GetRenderNodeType() == eERType_RenderComponent || - GetRenderNodeType() == eERType_StaticMeshRenderComponent || - GetRenderNodeType() == eERType_DynamicMeshRenderComponent || - GetRenderNodeType() == eERType_SkinnedMeshRenderComponent; - } - virtual void Dephysicalize([[maybe_unused]] bool bKeepIfReferenced = false) {} - virtual void Dematerialize() {} - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - - virtual void Precache() {}; - - virtual const AABB GetBBoxVirtual() { return GetBBox(); } - - // virtual float GetLodForDistance(float fDistance) { return 0; } - - virtual void OnRenderNodeBecomeVisible([[maybe_unused]] const SRenderingPassInfo& passInfo) {} - virtual void OnPhysAreaChange() {} - - virtual bool IsMovableByGame() const { return false; } - - virtual uint8 GetSortPriority() { return 0; } - - // Types of voxelization for objects and lights - enum EVoxelGIMode : int - { - VM_None = 0, // No voxelization - VM_Static, // Incremental or asynchronous lazy voxelization - VM_Dynamic, // Real-time every-frame voxelization on GPU - }; - - virtual EVoxelGIMode GetVoxelGIMode() { return VM_None; } - virtual void SetDesiredVoxelGIMode([[maybe_unused]] EVoxelGIMode voxelMode) {} - - virtual void SetMinSpec(int nMinSpec) { m_dwRndFlags &= ~ERF_SPEC_BITS_MASK; m_dwRndFlags |= (nMinSpec << ERF_SPEC_BITS_SHIFT) & ERF_SPEC_BITS_MASK; }; - - // Description: - // Allows to adjust default max view distance settings, - // if fMaxViewDistRatio is 1.0f - default max view distance is used. - virtual void SetViewDistanceMultiplier(float fViewDistanceMultiplier); - // </interfuscator:shuffle> - - void CopyIRenderNodeData(IRenderNode* pDest) const - { - pDest->m_fWSMaxViewDist = m_fWSMaxViewDist; - pDest->m_dwRndFlags = m_dwRndFlags; - //pDest->m_pOcNode = m_pOcNode; // Removed to stop the registering from earlying out. - pDest->m_fViewDistanceMultiplier = m_fViewDistanceMultiplier; - pDest->m_ucLodRatio = m_ucLodRatio; - pDest->m_cShadowLodBias = m_cShadowLodBias; - pDest->m_cStaticShadowLod = m_cStaticShadowLod; - pDest->m_nInternalFlags = m_nInternalFlags; - pDest->m_nMaterialLayers = m_nMaterialLayers; - //pDestBrush->m_pRNTmpData //If this is copied from the source render node, there are two - // pointers to the same data, and if either is deleted, there will - // be a crash when the dangling pointer is used on the other - } - - // Rendering flags. - ILINE void SetRndFlags(unsigned int dwFlags) { m_dwRndFlags = dwFlags; } - ILINE void SetRndFlags(unsigned int dwFlags, bool bEnable) - { - if (bEnable) - { - SetRndFlags(m_dwRndFlags | dwFlags); - } - else - { - SetRndFlags(m_dwRndFlags & (~dwFlags)); - } - } - ILINE unsigned int GetRndFlags() const { return m_dwRndFlags; } - - // Object draw frames (set if was drawn). - ILINE void SetDrawFrame(int nFrameID, int nRecursionLevel) - { - assert(m_pRNTmpData); - int* pDrawFrames = (int*)m_pRNTmpData; - pDrawFrames[nRecursionLevel] = nFrameID; - } - - ILINE int GetDrawFrame(int nRecursionLevel = 0) const - { - IF (!m_pRNTmpData, 0) - { - return 0; - } - - int* pDrawFrames = (int*)m_pRNTmpData; - return pDrawFrames[nRecursionLevel]; - } - - // Returns: - // Current VisArea or null if in outdoors or entity was not registered in 3dengine. - ILINE IVisArea* GetEntityVisArea() const { return m_pOcNode ? (IVisArea*)(m_pOcNode->m_pVisArea) : NULL; } - - // Summary: - // Makes object visible at any distance. - ILINE void SetViewDistUnlimited() { SetViewDistanceMultiplier(100.0f); } - - // Summary: - // Retrieves the view distance settings. - ILINE float GetViewDistanceMultiplier() const - { - return m_fViewDistanceMultiplier; - } - - // Summary: - // Returns lod distance ratio. - ILINE int GetLodRatio() const { return m_ucLodRatio; } - - // Summary: - // Returns lod distance ratio - ILINE float GetLodRatioNormalized() const { return 0.01f * m_ucLodRatio; } - - virtual bool GetLodDistances([[maybe_unused]] const SFrameLodInfo& frameLodInfo, [[maybe_unused]] float* distances) const { return false; } - - // Returns distance for first lod change, not factoring in distance multiplier or lod ratio - virtual float GetFirstLodDistance() const { return FLT_MAX; } - - // Description: - // Bias value to add to the regular lod - virtual void SetShadowLodBias(int8 nShadowLodBias) { m_cShadowLodBias = nShadowLodBias; } - - // Summary: - // Returns lod distance ratio. - ILINE int GetShadowLodBias() const { return m_cShadowLodBias; } - - // Summary: - // Sets material layers mask. - ILINE void SetMaterialLayers(uint8 nMtlLayers) { m_nMaterialLayers = nMtlLayers; } - - ILINE int GetMinSpec() const { return (m_dwRndFlags & ERF_SPEC_BITS_MASK) >> ERF_SPEC_BITS_SHIFT; }; - - static const ERNListType GetRenderNodeListId(const EERType eRType) - { - switch (eRType) - { - case eERType_Decal: - return eRNListType_DecalsAndRoads; - default: - return eRNListType_Unknown; - } - } - - virtual AZ::EntityId GetEntityId() { return AZ::EntityId(); } - - ////////////////////////////////////////////////////////////////////////// - // Variables - ////////////////////////////////////////////////////////////////////////// - -public: - - // Every sector has linked list of IRenderNode objects. - IRenderNode* m_pNext, * m_pPrev; - - // Current objects tree cell. - IOctreeNode* m_pOcNode; - - // Pointer to temporary data allocated only for currently visible objects. - struct CRNTmpData* m_pRNTmpData; - - // Max view distance. - float m_fWSMaxViewDist; - - // Render flags. - int m_dwRndFlags; - - // Shadow LOD bias - // Set to SHADOW_LODBIAS_DISABLE to disable any shadow lod overrides for this rendernode - static const int8 SHADOW_LODBIAS_DISABLE = -128; - int8 m_cShadowLodBias; - - // Segment Id - int m_nSID; - - // Max view distance settings. - static const int VIEW_DISTANCE_MULTIPLIER_MAX = 100; - float m_fViewDistanceMultiplier; - - // LOD settings. - unsigned char m_ucLodRatio; - - // Flags for render node internal usage, one or more bits from EInternalFlags. - unsigned char m_nInternalFlags; - - // Material layers bitmask -> which material layers are active. - unsigned char m_nMaterialLayers; -}; - -inline void IRenderNode::SetViewDistanceMultiplier(float fViewDistanceMultiplier) -{ - fViewDistanceMultiplier = CLAMP(fViewDistanceMultiplier, 0.0f, 100.0f); - if (fabs(m_fViewDistanceMultiplier - fViewDistanceMultiplier) > FLT_EPSILON) - { - m_fViewDistanceMultiplier = fViewDistanceMultiplier; - } -} - - -/////////////////////////////////////////////////////////////////////////////// -inline IStatObj* IRenderNode::GetEntityStatObj([[maybe_unused]] unsigned int nPartId, [[maybe_unused]] unsigned int nSubPartId, [[maybe_unused]] Matrix34A* pMatrix, [[maybe_unused]] bool bReturnOnlyVisible) -{ - return 0; -} - - -//We must use interfaces instead of unsafe type casts and unnecessary includes - -struct ILightSource - : public IRenderNode -{ - // <interfuscator:shuffle> - virtual void SetLightProperties(const CDLight& light) = 0; - virtual CDLight& GetLightProperties() = 0; - virtual const Matrix34& GetMatrix() = 0; - virtual struct ShadowMapFrustum* GetShadowFrustum(int nId = 0) = 0; - virtual bool IsLightAreasVisible() = 0; - virtual void SetCastingException(IRenderNode* pNotCaster) = 0; - virtual void SetName(const char* name) = 0; - // </interfuscator:shuffle> -}; - -struct SCloudMovementProperties -{ - bool m_autoMove; - Vec3 m_speed; - Vec3 m_spaceLoopBox; - float m_fadeDistance; -}; - -// Summary: -// ICloudRenderNode is an interface to the Cloud Render Node object. -struct ICloudRenderNode - : public IRenderNode -{ - // <interfuscator:shuffle> - // Description: - // Loads a cloud from a cloud description XML file. - virtual bool LoadCloud(const char* sCloudFilename) = 0; - virtual bool LoadCloudFromXml(XmlNodeRef cloudNode) = 0; - virtual void SetMovementProperties(const SCloudMovementProperties& properties) = 0; - // </interfuscator:shuffle> -}; - -// Summary: -// IVoxelObject is an interface to the Voxel Object Render Node object. -struct IVoxelObject - : public IRenderNode -{ - // <interfuscator:shuffle> - virtual void SetCompiledData(void* pData, int nSize, uint8 ucChildId, EEndian eEndian) = 0; - virtual void SetObjectName(const char* pName) = 0; - virtual void SetMatrix(const Matrix34& mat) = 0; - virtual bool ResetTransformation() = 0; - virtual void InterpolateVoxelData() = 0; - virtual void SetFlags(int nFlags) = 0; - virtual void Regenerate() = 0; - virtual void CopyHM() = 0; - virtual bool IsEmpty() = 0; - // </interfuscator:shuffle> -}; - -// Summary: -// IFogVolumeRenderNode is an interface to the Fog Volume Render Node object. -struct SFogVolumeProperties -{ - // Common parameters. - // Center position & rotation values are taken from the entity matrix. - - int m_volumeType; - Vec3 m_size; - ColorF m_color; - bool m_useGlobalFogColor; - bool m_ignoresVisAreas; - bool m_affectsThisAreaOnly; - float m_globalDensity; - float m_densityOffset; - float m_softEdges; - float m_fHDRDynamic; // 0 to get the same results in LDR, <0 to get darker, >0 to get brighter. - float m_nearCutoff; - - float m_heightFallOffDirLong; // Height based fog specifics. - float m_heightFallOffDirLati; // Height based fog specifics. - float m_heightFallOffShift; // Height based fog specifics. - float m_heightFallOffScale; // Height based fog specifics. - - float m_rampStart; - float m_rampEnd; - float m_rampInfluence; - float m_windInfluence; - float m_densityNoiseScale; - float m_densityNoiseOffset; - float m_densityNoiseTimeFrequency; - Vec3 m_densityNoiseFrequency; -}; - -struct IFogVolumeRenderNode - : public IRenderNode -{ - // <interfuscator:shuffle> - virtual void SetFogVolumeProperties(const SFogVolumeProperties& properties) = 0; - virtual const Matrix34& GetMatrix() const = 0; - - virtual void FadeGlobalDensity(float fadeTime, float newGlobalDensity) = 0; - // </interfuscator:shuffle> -}; - -// LY renderer system spec levels. -enum class EngineSpec : AZ::u32 -{ - Low = 1, - Medium, - High, - VeryHigh, - Never = UINT_MAX, -}; - -struct SDecalProperties -{ - SDecalProperties() - { - m_projectionType = ePlanar; - m_sortPrio = 0; - m_deferred = false; - m_pos = Vec3(0.0f, 0.0f, 0.0f); - m_normal = Vec3(0.0f, 0.0f, 1.0f); - m_explicitRightUpFront = Matrix33::CreateIdentity(); - m_radius = 1.0f; - m_depth = 1.0f; - m_opacity = 1.0f; - m_angleAttenuation = 1.0f; - m_maxViewDist = 8000.0f; - m_minSpec = EngineSpec::Low; - } - - enum EProjectionType : int - { - ePlanar, - eProjectOnTerrain, - eProjectOnTerrainAndStaticObjects - }; - - EProjectionType m_projectionType; - uint8 m_sortPrio; - uint8 m_deferred; - Vec3 m_pos; - Vec3 m_normal; - Matrix33 m_explicitRightUpFront; - float m_radius; - float m_depth; - const char* m_pMaterialName; - float m_opacity; - float m_angleAttenuation; - float m_maxViewDist; - EngineSpec m_minSpec; -}; - -// Description: -// IDecalRenderNode is an interface to the Decal Render Node object. -struct IDecalRenderNode - : public IRenderNode -{ - // <interfuscator:shuffle> - virtual void SetDecalProperties(const SDecalProperties& properties) = 0; - virtual const SDecalProperties* GetDecalProperties() const = 0; - virtual const Matrix34& GetMatrix() = 0; - virtual void CleanUpOldDecals() = 0; - // </interfuscator:shuffle> -}; - -// Description: -// IWaterVolumeRenderNode is an interface to the Water Volume Render Node object. -struct IWaterVolumeRenderNode - : public IRenderNode -{ - enum EWaterVolumeType - { - eWVT_Unknown, - eWVT_Ocean, - eWVT_Area, - eWVT_River - }; - - // <interfuscator:shuffle> - // Description: - // Sets if the render node is attached to a parent entity - // This must be called right after the object construction if it is the case - // Only supported for Areas (not rivers or ocean) - virtual void SetAreaAttachedToEntity() = 0; - - virtual void SetFogDensity(float fogDensity) = 0; - virtual float GetFogDensity() const = 0; - virtual void SetFogColor(const Vec3& fogColor) = 0; - virtual void SetFogColorAffectedBySun(bool enable) = 0; - virtual void SetFogShadowing(float fogShadowing) = 0; - - virtual void SetCapFogAtVolumeDepth(bool capFog) = 0; - virtual void SetVolumeDepth(float volumeDepth) = 0; - virtual void SetStreamSpeed(float streamSpeed) = 0; - - virtual void SetCaustics(bool caustics) = 0; - virtual void SetCausticIntensity(float causticIntensity) = 0; - virtual void SetCausticTiling(float causticTiling) = 0; - virtual void SetCausticHeight(float causticHeight) = 0; - virtual void SetAuxPhysParams(pe_params_area*) = 0; - - virtual void CreateOcean(uint64 volumeID, /* TBD */ bool keepSerializationParams = false) = 0; - virtual void CreateArea(uint64 volumeID, const Vec3* pVertices, unsigned int numVertices, const Vec2& surfUVScale, const Plane_tpl<f32>& fogPlane, bool keepSerializationParams = false, int nSID = -1) = 0; - virtual void CreateRiver(uint64 volumeID, const Vec3* pVertices, unsigned int numVertices, float uTexCoordBegin, float uTexCoordEnd, const Vec2& surfUVScale, const Plane_tpl<f32>& fogPlane, bool keepSerializationParams = false, int nSID = -1) = 0; - virtual void CreateRiver(uint64 volumeID, const AZStd::vector<AZ::Vector3>& verticies, const AZ::Transform& transform, float uTexCoordBegin, float uTexCoordEnd, const AZ::Vector2& surfUVScale, const AZ::Plane& fogPlane, bool keepSerializationParams = false, int nSID = -1) = 0; - - virtual void SetAreaPhysicsArea(const Vec3* pVertices, unsigned int numVertices, bool keepSerializationParams = false) = 0; - virtual void SetRiverPhysicsArea(const Vec3* pVertices, unsigned int numVertices, bool keepSerializationParams = false) = 0; - virtual void SetRiverPhysicsArea(const AZStd::vector<AZ::Vector3>& verticies, const AZ::Transform& transform, bool keepSerializationParams = false) = 0; - - // </interfuscator:shuffle> - - // This flag is used to account for legacy entities which used to serialize the node without parent objects. - // Now there are runtime components which spawn the rendering node, however we need to support legacy code as well. - // Remove this flag when legacy entities are removed entirely - bool m_hasToBeSerialised = true; -}; - -// Description: -// IDistanceCloudRenderNode is an interface to the Distance Cloud Render Node object. -struct SDistanceCloudProperties -{ - Vec3 m_pos; - float m_sizeX; - float m_sizeY; - float m_rotationZ; - const char* m_pMaterialName; -}; - -struct IDistanceCloudRenderNode - : public IRenderNode -{ - virtual void SetProperties(const SDistanceCloudProperties& properties) = 0; -}; - -struct SVolumeObjectProperties -{ -}; - -struct SVolumeObjectMovementProperties -{ - bool m_autoMove; - Vec3 m_speed; - Vec3 m_spaceLoopBox; - float m_fadeDistance; -}; - -// Description: -// IVolumeObjectRenderNode is an interface to the Volume Object Render Node object. -struct IVolumeObjectRenderNode - : public IRenderNode -{ - // <interfuscator:shuffle> - virtual void LoadVolumeData(const char* filePath) = 0; - virtual void SetProperties(const SVolumeObjectProperties& properties) = 0; - virtual void SetMovementProperties(const SVolumeObjectMovementProperties& properties) = 0; - // </interfuscator:shuffle> -}; - -#if !defined(EXCLUDE_DOCUMENTATION_PURPOSE) -struct IPrismRenderNode - : public IRenderNode -{ -}; -#endif // EXCLUDE_DOCUMENTATION_PURPOSE - -#endif // CRYINCLUDE_CRYCOMMON_IENTITYRENDERSTATE_H diff --git a/Code/CryEngine/CryCommon/IEntityRenderState_info.cpp b/Code/CryEngine/CryCommon/IEntityRenderState_info.cpp deleted file mode 100644 index 89876fb91a..0000000000 --- a/Code/CryEngine/CryCommon/IEntityRenderState_info.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "TypeInfo_impl.h" -#include <IEntityRenderState.h> // <> required for Interfuscator - -ENUM_INFO_BEGIN(EERType) -ENUM_ELEM_INFO(, eERType_NotRenderNode) -ENUM_ELEM_INFO(, eERType_Dummy_10) -ENUM_ELEM_INFO(, eERType_Light) -ENUM_ELEM_INFO(, eERType_Cloud) -ENUM_ELEM_INFO(, eERType_TerrainSystem) -ENUM_ELEM_INFO(, eERType_FogVolume) -ENUM_ELEM_INFO(, eERType_Decal) -ENUM_ELEM_INFO(, eERType_Dummy_6) -ENUM_ELEM_INFO(, eERType_WaterVolume) -ENUM_ELEM_INFO(, eERType_Dummy_7) -ENUM_ELEM_INFO(, eERType_DistanceCloud) -ENUM_ELEM_INFO(, eERType_VolumeObject) -ENUM_ELEM_INFO(, eERType_Dummy_0) -ENUM_ELEM_INFO(, eERType_Rope) -ENUM_ELEM_INFO(, eERType_PrismObject) -ENUM_ELEM_INFO(, eERType_Dummy_2) -ENUM_ELEM_INFO(, eERType_Dummy_4) -ENUM_ELEM_INFO(, eERType_RenderComponent) -ENUM_ELEM_INFO(, eERType_StaticMeshRenderComponent) -ENUM_ELEM_INFO(, eERType_DynamicMeshRenderComponent) -ENUM_ELEM_INFO(, eERType_SkinnedMeshRenderComponent) -ENUM_ELEM_INFO(, eERType_GameEffect) -ENUM_ELEM_INFO(, eERType_BreakableGlass) -ENUM_ELEM_INFO(, eERType_Dummy_3) -ENUM_ELEM_INFO(, eERType_Dummy_9) -ENUM_ELEM_INFO(, eERType_GeomCache) -ENUM_ELEM_INFO(, eERType_TypesNum) -ENUM_INFO_END(EERType) diff --git a/Code/CryEngine/CryCommon/IFont.h b/Code/CryEngine/CryCommon/IFont.h deleted file mode 100644 index e22c33eb09..0000000000 --- a/Code/CryEngine/CryCommon/IFont.h +++ /dev/null @@ -1,374 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : CryFont interface. - - -#ifndef CRYINCLUDE_CRYCOMMON_IFONT_H -#define CRYINCLUDE_CRYCOMMON_IFONT_H -#pragma once - -#include <Cry_Math.h> -#include <Cry_Color.h> -#include <CryString.h> -#include <smartptr.h> - -#include <AzCore/std/smart_ptr/shared_ptr.h> -#include <AzCore/EBus/EBus.h> - -struct ISystem; -class ICrySizer; - -struct ICryFont; -struct IFFont; -struct FontFamily; - -struct SVF_P2F_C4B_T2F_F4B; - -extern "C" -#ifdef CRYFONT_EXPORTS -DLL_EXPORT -#else -DLL_IMPORT -#endif -ICryFont * CreateCryFontInterface(ISystem * pSystem); - -typedef ICryFont*(* PFNCREATECRYFONTINTERFACE)(ISystem* pSystem); -typedef AZStd::shared_ptr<FontFamily> FontFamilyPtr; - -namespace IFFontConstants -{ - //! The default scale applied to individual glyphs when rendering to the font texture. - //! - //! This is a "best guess" to try and fit all glyphs of a font within the - //! bounds of a font texture slot. This value can be defined on a per-font - //! basis via the "sizeratio" *.font XML attribute. - const float defaultSizeRatio = 0.8f; -} - -////////////////////////////////////////////////////////////////////////////////////////////// -struct ICryFont -{ - static const int defaultGlyphSizeX = -1; //!< Default glyph size indicates that glyphs in the font texture - //!< should be rendered at the maximum resolution supported by - //!< the font texture's glyph cell/slot configuration (configured - //!< via font XML). - - static const int defaultGlyphSizeY = -1; //!< Default glyph size indicates that glyphs in the font texture - //!< should be rendered at the maximum resolution supported by - //!< the font texture's glyph cell/slot configuration (configured - //!< via font XML). - - // <interfuscator:shuffle> - virtual ~ICryFont(){} - // - virtual void Release() = 0; - // Summary: - // Creates a named font (case insensitive) - virtual IFFont* NewFont(const char* pFontName) = 0; - // Summary: - // Gets a named font (case insensitive) - virtual IFFont* GetFont(const char* pFontName) const = 0; - - //! \brief Loads and initializes a Font Family from a *.fontfamily file - //! \param pFontFamilyName Name of font family to load (or name of a *.fontfamily file) - virtual FontFamilyPtr LoadFontFamily(const char* pFontFamilyName) = 0; - - // Summary: - // Gets font family (case insensitive) - virtual FontFamilyPtr GetFontFamily(const char* pFontFamilyName) = 0; - - //! \brief Adds the characters in the given string to all of the font textures within the font family. - //! All font styles within the given font family (bold, italic, etc.) will have the given - //! characters added to their font textures. - //! - //! \param pFontFamily The font family to add the characters to. - //! \param pChars String of characters to add to font textures (UTF-8 supported). - //! \param glyphSizeX Width (in pixels) of the characters to be rendered at in the font texture. - //! \param glyphSizeY Height (in pixels) of the characters to be rendered at in the font texture. - virtual void AddCharsToFontTextures(FontFamilyPtr pFontFamily, const char* pChars, int glyphSizeX = defaultGlyphSizeX, int glyphSizeY = defaultGlyphSizeY) = 0; - - // Summary: - // Puts the objects used in this module into the sizer interface - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - // Summary: - // All font names separated by , - // Example: - // "console,default,hud" - virtual string GetLoadedFontNames() const = 0; - - //! \brief Called when the g_language (current language) setting changes. - //! - //! Mainly used to reload font family resources for the new language. - virtual void OnLanguageChanged() = 0; - - //! \brief Reload all fonts - virtual void ReloadAllFonts() = 0; - - // </interfuscator:shuffle> -}; - -////////////////////////////////////////////////////////////////////////////////////////////// -#define TTFFLAG_SMOOTH_NONE 0x00000000 // No smooth. -#define TTFFLAG_SMOOTH_BLUR 0x00000001 // Smooth by blurring it. -#define TTFFLAG_SMOOTH_SUPERSAMPLE 0x00000002 // Smooth by rendering the characters into a bigger texture, and then resize it to the normal size using bilinear filtering. - -#define TTFFLAG_SMOOTH_MASK 0x0000000f // Mask for retrieving. -#define TTFFLAG_SMOOTH_SHIFT 0 // Shift amount for retrieving. - -#define TTFLAG_SMOOTH_AMOUNT_2X 0x00010000 // Blur / supersample [2x] -#define TTFLAG_SMOOTH_AMOUNT_4X 0x00020000 // Blur / supersample [4x] - -#define TTFFLAG_SMOOTH_AMOUNT_MASK 0x000f0000 // Mask for retrieving. -#define TTFFLAG_SMOOTH_AMOUNT_SHIFT 16 // Shift amount for retrieving. - - -#define TTFFLAG_CREATE(smooth, amount) ((((smooth) << TTFFLAG_SMOOTH_SHIFT) & TTFFLAG_SMOOTH_MASK) | (((amount) << TTFFLAG_SMOOTH_AMOUNT_SHIFT) & TTFFLAG_SMOOTH_AMOUNT_MASK)) -#define TTFFLAG_GET_SMOOTH(flag) (((flag) & TTFLAG_SMOOTH_MASK) >> TTFFLAG_SMOOTH_SHIFT) -#define TTFFLAG_GET_SMOOTH_AMOUNT(flag) (((flag) & TTFLAG_SMOOTH_SMOUNT_MASK) >> TTFFLAG_SMOOTH_AMOUNT_SHIFT) - -////////////////////////////////////////////////////////////////////////// -struct STextDrawContext -{ - unsigned int m_fxIdx; - - Vec2 m_size; - Vec2i m_requestSize; - float m_widthScale; - float m_lineSpacing; - - float m_clipX; - float m_clipY; - float m_clipWidth; - float m_clipHeight; - - int m_drawTextFlags; - - bool m_proportional; - bool m_sizeIn800x600; - bool m_clippingEnabled; - bool m_framed; - - ColorB m_colorOverride; - - Matrix34 m_transform; - - int m_baseState; - bool m_overrideViewProjMatrices; - bool m_kerningEnabled; - bool m_processSpecialChars; - bool m_pixelAligned; //!< toggles whether rendering is pixel aligned - - float m_tracking; //!< extra space between characters in pixels (prior to any transform) - - STextDrawContext() - : m_fxIdx(0) - , m_size(16.0f, 16.0f) - , m_requestSize(static_cast<int32>(m_size.x), static_cast<int32>(m_size.y)) - , m_widthScale(1.0f) - , m_lineSpacing(0.f) - , m_clipX(0) - , m_clipY(0) - , m_clipWidth(0) - , m_clipHeight(0) - , m_proportional(true) - , m_sizeIn800x600(true) - , m_clippingEnabled(false) - , m_framed(false) - , m_colorOverride(0, 0, 0, 0) - , m_drawTextFlags(0) - , m_transform(IDENTITY) - , m_baseState(-1) // indicates not set, would like to set to GS_DEPTHFUNC_LEQUAL but header dependencies preclude that - , m_overrideViewProjMatrices(true) // the old behavior that overrides the currently set view and projection matrices - , m_kerningEnabled(true) - , m_processSpecialChars(true) - , m_pixelAligned(true) - , m_tracking(0.0f) - { - } - - void Reset() { *this = STextDrawContext(); } - void SetEffect(unsigned int fxIdx) { m_fxIdx = fxIdx; } - void SetSize(const Vec2& size) { m_size = size; } - void SetCharWidthScale(float widthScale) { m_widthScale = widthScale; } - void SetClippingRect(float x, float y, float width, float height) { m_clipX = x; m_clipY = y; m_clipWidth = width; m_clipHeight = height; } - void SetProportional(bool proportional) { m_proportional = proportional; } - void SetSizeIn800x600(bool sizeIn800x600) { m_sizeIn800x600 = sizeIn800x600; } - void EnableClipping(bool enable) { m_clippingEnabled = enable; } - void EnableFrame(bool enable) { m_framed = enable; } - void SetColor(const ColorF& col) { m_colorOverride = col; } - void SetFlags(int flags) { m_drawTextFlags = flags; } - void SetTransform(const Matrix34& transform) { m_transform = transform; } - void SetBaseState(int baseState) { m_baseState = baseState; } - void SetOverrideViewProjMatrices(bool overrideViewProjMatrices) { m_overrideViewProjMatrices = overrideViewProjMatrices; } - void SetLineSpacing(float lineSpacing) { m_lineSpacing = lineSpacing; } - - float GetCharWidth() const { return m_size.x; } - float GetCharHeight() const { return m_size.y; } - float GetCharWidthScale() const { return m_widthScale; } - int GetFlags() const { return m_drawTextFlags; } - float GetLineSpacing() const { return m_lineSpacing; } - - bool IsColorOverridden() const { return m_colorOverride.a != 0; } -}; - -////////////////////////////////////////////////////////////////////////////////////////////// -struct IFFont -{ - // <interfuscator:shuffle> - virtual ~IFFont() {} - - // We don't derive from CBaseResource currently, that could be an enhancement - virtual int32 AddRef() = 0; - virtual int32 Release() = 0; - - //! \brief Loads a font from a TTF file. - //! \param pFontFilePath Path to font file - //! \param width Desired width of font texture. - //! \param height Desired width of font texture. - //! \param widthNumSlots Number of character slots across the width (X-axis) of the font texture - //! \param heightNumSlots Number of character slots across the height (Y-axis) of the font texture - //! \param flags Flags governing font, such as smoothness (see TTFFLAG_CREATE). - //! \param sizeRatio Scale to apply to the font size when storing glyphs in font texture slots. - virtual bool Load(const char* pFontFilePath, unsigned int width, unsigned int height, unsigned int widthNumSlots, unsigned int heightNumSlots, unsigned int flags, float sizeRatio) = 0; - - //! \brief Loads a font from a XML file. - //! \param pXMLFile Path to font XML file - virtual bool Load(const char* pXMLFile) = 0; - - // Summary: - // Frees internally memory internally allocated by Load(). - virtual void Free() = 0; - - // Summary: - // Draws a formatted string (UTF-8). - virtual void DrawString(float x, float y, const char* pStr, const bool asciiMultiLine, const STextDrawContext& ctx) = 0; - - // Summary: - // Draws a formatted string (UTF-8), taking z into account. - virtual void DrawString(float x, float y, float z, const char* pStr, const bool asciiMultiLine, const STextDrawContext& ctx) = 0; - - // Summary: - // Computes the text size (UTF-8). - virtual Vec2 GetTextSize(const char* pStr, const bool asciiMultiLine, const STextDrawContext& ctx) = 0; - - // Description: - // Computes virtual text-length (UTF-8) (because of special chars...). - virtual size_t GetTextLength(const char* pStr, const bool asciiMultiLine) const = 0; - - // Description: - // Wraps text based on specified maximum line width (UTF-8) - virtual void WrapText(string& result, float maxWidth, const char* pStr, const STextDrawContext& ctx) = 0; - - // Description: - // Puts the memory used by this font into the given sizer. - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - - // Description: - // useful for special feature rendering interleaved with fonts (e.g. box behind the text) - virtual void GetGradientTextureCoord(float& minU, float& minV, float& maxU, float& maxV) const = 0; - - virtual unsigned int GetEffectId(const char* pEffectName) const = 0; - virtual unsigned int GetNumEffects() const = 0; - virtual const char* GetEffectName(unsigned int effectId) const = 0; - virtual Vec2 GetMaxEffectOffset(unsigned int effectId) const = 0; - virtual bool DoesEffectHaveTransparency(unsigned int effectId) const = 0; - - //! \brief Adds the given UTF-8 string of chars to this font's font texture. - //! \param pChars String of UTF-8 chars to add to font texture - //! \param glyphSizeX Width (in pixels) of the characters to be rendered at in the font texture. - //! \param glyphSizeY Height (in pixels) of the characters to be rendered at in the font texture. - virtual void AddCharsToFontTexture(const char* pChars, int glyphSizeX = ICryFont::defaultGlyphSizeX, int glyphSizeY = ICryFont::defaultGlyphSizeY) = 0; - - //! \brief Returns XY kerning offsets (positive or negative) for two given glyphs. - //! - //! Kerning values are only returned for fonts that have a 'kern' table defined. - //! Even fonts that do have a 'kern' defined do not define kerning values for all - //! possible combination of characters. Zero values will be returned for those - //! cases. - virtual Vec2 GetKerning(uint32_t leftGlyph, uint32_t rightGlyph, const STextDrawContext& ctx) const = 0; - - //! \brief Returns the ascender of the font - virtual float GetAscender(const STextDrawContext& ctx) const = 0; - - //! \brief Returns the y offset from the top to the baseline - virtual float GetBaseline(const STextDrawContext& ctx) const = 0; - - //! \brief Returns the scaling applied to glyphs before being rendered to the font texture from FreeType. - virtual float GetSizeRatio() const = 0; - - //! \brief Get the number of quads required to render the text string - //! This is an upper limit. Due to clipping the rendering of the text string might actually use less quads. - virtual uint32 GetNumQuadsForText(const char* pStr, const bool asciiMultiLine, const STextDrawContext& ctx) = 0; - - //! \brief Write the quads for the text into the given vertex and index buffers - //! The actual number of quads written to the buffer is returned - virtual uint32 WriteTextQuadsToBuffers(SVF_P2F_C4B_T2F_F4B* verts, uint16* indices, uint32 maxQuads, - float x, float y, float z, const char* pStr, const bool asciiMultiLine, const STextDrawContext& ctx) = 0; - - //! \brief get the font texture for this font, will return -1 if there is no valid font texture - virtual int GetFontTextureId() = 0; - - //! \brief get the font texture version for this font. Incremented each time the texture is changed - virtual uint32 GetFontTextureVersion() = 0; - - // </interfuscator:shuffle> -}; - -////////////////////////////////////////////////////////////////////////////////////////////// -//! Correlates several font files to define a family of fonts, specifically for styling. -struct FontFamily -{ - FontFamily() - : normal(nullptr) - , bold(nullptr) - , italic(nullptr) - , boldItalic(nullptr) - { - } - - FontFamily(const FontFamily&) = delete; - FontFamily(const FontFamily&&) = delete; - FontFamily& operator=(const FontFamily&) = delete; - FontFamily& operator=(const FontFamily&&) = delete; - - string familyName; - IFFont* normal; - IFFont* bold; - IFFont* italic; - IFFont* boldItalic; - -}; - -////////////////////////////////////////////////////////////////////////// -struct IFFont_RenderProxy -{ - // <interfuscator:shuffle> - virtual ~IFFont_RenderProxy() {} - virtual void RenderCallback(float x, float y, float z, const char* pStr, const bool asciiMultiLine, const STextDrawContext& ctx) = 0; - // </interfuscator:shuffle> -}; - -////////////////////////////////////////////////////////////////////////// -//! Simple bus that notifies listeners of font changes -class FontNotifications - : public AZ::EBusTraits -{ -public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - - virtual ~FontNotifications() = default; - - virtual void OnFontsReloaded() = 0; - - virtual void OnFontTextureUpdated(IFFont* /*font*/) {} -}; - -using FontNotificationBus = AZ::EBus<FontNotifications>; - -#endif // CRYINCLUDE_CRYCOMMON_IFONT_H diff --git a/Code/CryEngine/CryCommon/IFunctorBase.h b/Code/CryEngine/CryCommon/IFunctorBase.h deleted file mode 100644 index 89fe3f9d55..0000000000 --- a/Code/CryEngine/CryCommon/IFunctorBase.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Base header for multi DLL functors. - - -#ifndef CRYINCLUDE_CRYCOMMON_IFUNCTORBASE_H -#define CRYINCLUDE_CRYCOMMON_IFUNCTORBASE_H -#pragma once - - -// Base class for functor storage. -// Not intended for direct usage. -class IFunctorBase -{ -public: - IFunctorBase() - : m_nReferences(0){} - virtual ~IFunctorBase(){}; - virtual void Call() = 0; - - void AddRef() - { - CryInterlockedIncrement(&m_nReferences); - } - - void Release() - { - if (CryInterlockedDecrement(&m_nReferences) <= 0) - { - delete this; - } - } - -protected: - volatile int m_nReferences; -}; - -// Base Template for specialization. -// Not intended for direct usage. -template<typename tType> -class TFunctor - : public IFunctorBase -{ -}; - -#endif // CRYINCLUDE_CRYCOMMON_IFUNCTORBASE_H diff --git a/Code/CryEngine/CryCommon/IGem.h b/Code/CryEngine/CryCommon/IGem.h deleted file mode 100644 index 9e3a3192b0..0000000000 --- a/Code/CryEngine/CryCommon/IGem.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include "platform.h" -#include "ISystem.h" -#include "CrySystemBus.h" - -#include <AzCore/Module/Module.h> - - -/** - * CryHooksModule is an AZ::Module with common hooks into CryEngine systems. - * - Sets gEnv once CrySystem has initialized. - * - Registers as a CrySystem event handler. - */ -class CryHooksModule - : public AZ::Module - , protected CrySystemEventBus::Handler - , protected ISystemEventListener -{ -public: - AZ_RTTI(CryHooksModule, "{BD896D16-6F7D-4EA6-A532-0A9E6BF3C089}", AZ::Module); - CryHooksModule() - : Module() - { - CrySystemEventBus::Handler::BusConnect(); - } - - ~CryHooksModule() override - { - CrySystemEventBus::Handler::BusDisconnect(); - - if (gEnv && gEnv->pSystem && gEnv->pSystem->GetISystemEventDispatcher()) - { - gEnv->pSystem->GetISystemEventDispatcher()->RemoveListener(this); - } - } - -protected: - - void OnCrySystemPreInitialize(ISystem& system, const SSystemInitParams& systemInitParams) override - { - (void)systemInitParams; - -#if !defined(AZ_MONOLITHIC_BUILD) - // When module is linked dynamically, we must set our gEnv pointer. - // When module is linked statically, we'll share the application's gEnv pointer. - gEnv = system.GetGlobalEnvironment(); -#else - (void)system; -#endif - } - - void OnCrySystemInitialized(ISystem& system, const SSystemInitParams& systemInitParams) override - { - (void)systemInitParams; - - system.GetISystemEventDispatcher()->RegisterListener(this); - } - - void OnCrySystemPostShutdown() override - { -#if !defined(AZ_MONOLITHIC_BUILD) - gEnv = nullptr; -#endif - } - - void OnSystemEvent(ESystemEvent /*event*/, UINT_PTR /*wparam*/, UINT_PTR /*lparam*/) override {} -}; diff --git a/Code/CryEngine/CryCommon/IIndexedMesh.h b/Code/CryEngine/CryCommon/IIndexedMesh.h deleted file mode 100644 index 744bfebc1d..0000000000 --- a/Code/CryEngine/CryCommon/IIndexedMesh.h +++ /dev/null @@ -1,2300 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_IINDEXEDMESH_H -#define CRYINCLUDE_CRYCOMMON_IINDEXEDMESH_H -#pragma once - -#include "CryHeaders.h" -#include "Cry_Color.h" -#include "StlUtils.h" -#include "CryEndian.h" -#include <CrySizer.h> -#include <Cry_Geo.h> // for AABB -#include <VertexFormats.h> -#include <Vertex.h> -#include <AzCore/Casting/numeric_cast.h> - -// Description: -// 2D Texture coordinates used by CMesh. -struct SMeshTexCoord -{ - SMeshTexCoord() {} - -private: - float s, t; - -public: - explicit SMeshTexCoord(float x, float y) - { - s = x; - t = y; - } - - explicit SMeshTexCoord(const Vec2f16& other) - { - const Vec2 uv = other.ToVec2(); - - s = uv.x; - t = uv.y; - } - - explicit SMeshTexCoord(const Vec2& other) - { - s = other.x; - t = other.y; - } - - explicit SMeshTexCoord(const Vec4& other) - { - s = other.x; - t = other.y; - } - - void ExportTo(Vec2f16& other) const - { - other = Vec2f16(s, t); - } - - void ExportTo(float& others, float& othert) const - { - others = s; - othert = t; - } - - bool operator ==(const SMeshTexCoord& other) const - { - return (s == other.s) && (t == other.t); - } - - bool operator !=(const SMeshTexCoord& other) const - { - return !(*this == other); - } - - bool operator <(const SMeshTexCoord& other) const - { - return (s != other.s) ? (s < other.s) : (t < other.t); - } - - bool IsEquivalent(const Vec2& other, float epsilon = 0.003f) const - { - return - (fabs_tpl(s - other.x) <= epsilon) && - (fabs_tpl(t - other.y) <= epsilon); - } - - bool IsEquivalent(const SMeshTexCoord& other, float epsilon = 0.00005f) const - { - return - (fabs_tpl(s - other.s) <= epsilon) && - (fabs_tpl(t - other.t) <= epsilon); - } - - ILINE Vec2 GetUV() const - { - return Vec2(s, t); - } - - void GetUV(Vec2& otheruv) const - { - otheruv = GetUV(); - } - - void GetUV(Vec4& otheruv) const - { - otheruv = Vec4(s, t, 0.0f, 1.0f); - } - - void Lerp(const SMeshTexCoord& other, float pos) - { - Vec2 texA; - Vec2 texB; - this->GetUV(); - other.GetUV(); - - texA.SetLerp(texA, texB, pos); - - *this = SMeshTexCoord(texA); - } - - AUTO_STRUCT_INFO -}; - -// Description: -// RGBA Color description structure used by CMesh. -struct SMeshColor -{ - SMeshColor() {} - -private: - uint8 r, g, b, a; - -public: - explicit SMeshColor(uint8 otherr, uint8 otherg, uint8 otherb, uint8 othera) - { - r = otherr; - g = otherg; - b = otherb; - a = othera; - } - - explicit SMeshColor(const Vec4& otherc) - { - r = aznumeric_caster(FtoI(otherc.x)); - g = aznumeric_caster(FtoI(otherc.y)); - b = aznumeric_caster(FtoI(otherc.z)); - a = aznumeric_caster(FtoI(otherc.w)); - } - - void TransferRGBTo(SMeshColor& other) const - { - other.r = r; - other.g = g; - other.b = b; - } - - void TransferATo(SMeshColor& other) const - { - other.a = a; - } - - void MaskA(uint8 maska) - { - a &= maska; - } - - bool operator ==(const SMeshColor& other) const - { - return (r == other.r) && (g == other.g) && (b == other.b) && (a == other.a); - } - - bool operator !=(const SMeshColor& other) const - { - return !(*this == other); - } - - bool operator <(const SMeshColor& other) const - { - return (r != other.r) ? (r < other.r) : (g != other.g) ? (g < other.g) : (b != other.b) ? (b < other.b) : (a < other.a); - } - - ILINE ColorB GetRGBA() const - { - return ColorB(r, g, b, a); - } - - void GetRGBA(ColorB& otherc) const - { - otherc = GetRGBA(); - } - - void GetRGBA(Vec4& otherc) const - { - otherc = Vec4(r, g, b, a); - } - - void Lerp(const SMeshColor& other, float pos) - { - Vec4 clrA; - Vec4 clrB; - this->GetRGBA(clrA); - other.GetRGBA(clrB); - - clrA.SetLerp(clrA, clrB, pos); - - *this = SMeshColor(clrA); - } - - AUTO_STRUCT_INFO -}; - - -// Description: -// Defines a single triangle face in the CMesh topology. -struct SMeshFace -{ - int v[3]; // indices to vertex, normals and optionally tangent basis arrays - unsigned char nSubset; // index to mesh subsets array. - - AUTO_STRUCT_INFO -}; - -// Description: -// 3D Normal Vector used by CMesh. -struct SMeshNormal -{ - SMeshNormal() {} - -private: - Vec3 Normal; - -public: - explicit SMeshNormal(const Vec3& othern) - { - Normal = othern; - } - - bool operator ==(const SMeshNormal& othern) const - { - return (Normal.x == othern.Normal.x) && (Normal.y == othern.Normal.y) && (Normal.z == othern.Normal.z); - } - - bool operator !=(const SMeshNormal& othern) const - { - return !(*this == othern); - } - - bool operator <(const SMeshNormal& othern) const - { - return (Normal.x != othern.Normal.x) ? (Normal.x < othern.Normal.x) : (Normal.y != othern.Normal.y) ? (Normal.y < othern.Normal.y) : (Normal.z < othern.Normal.z); - } - - bool IsEquivalent(const Vec3& othern, float epsilon = 0.00005f) const - { - return - Normal.IsEquivalent(othern, epsilon); - } - - bool IsEquivalent(const SMeshNormal& othern, float epsilon = 0.00005f) const - { - return - IsEquivalent(othern.Normal, epsilon); - } - - ILINE Vec3 GetN() const - { - return Normal; - } - - void GetN(Vec3& othern) const - { - othern = GetN(); - } - - void RotateBy(const Matrix33& rot) - { - Normal = rot * Normal; - } - - void RotateSafelyBy(const Matrix33& rot) - { - Normal = rot * Normal; - // normalize in case "rot" wasn't length-preserving - Normal.Normalize(); - } - - void RotateBy(const Matrix34& trn) - { - Normal = trn.TransformVector(Normal); - } - - void RotateSafelyBy(const Matrix34& trn) - { - Normal = trn.TransformVector(Normal); - // normalize in case "trn" wasn't length-preserving - Normal.Normalize(); - } - - void Slerp(const SMeshNormal& other, float pos) - { - Vec3 nrmA = this->GetN(); - Vec3 nrmB = other.GetN(); - - nrmA.Normalize(); - nrmB.Normalize(); - - nrmA.SetSlerp(nrmA, nrmB, pos); - - *this = SMeshNormal(nrmA); - } - - AUTO_STRUCT_INFO -}; - - -// Description: -// Mesh tangents (tangent space normals). -struct SMeshTangents -{ - SMeshTangents() {} - -private: - Vec4sf Tangent; - Vec4sf Bitangent; - -public: - explicit SMeshTangents(const Vec4sf& othert, const Vec4sf& otherb) - { - Tangent = othert; - Bitangent = otherb; - } - - explicit SMeshTangents(const SPipTangents& other) - { - Tangent = other.Tangent; - Bitangent = other.Bitangent; - } - - explicit SMeshTangents(const Vec4& othert, const Vec4& otherb) - { - Tangent = PackingSNorm::tPackF2Bv(othert); - Bitangent = PackingSNorm::tPackF2Bv(otherb); - } - - explicit SMeshTangents(const Vec3& othert, const Vec3& otherb, const Vec3& othern) - { - // TODO: can be optimized to use only integer arithmetic - int16 othersign = 1; - if (othert.Cross(otherb).Dot(othern) < 0) - { - othersign = -1; - } - - Tangent = Vec4sf(PackingSNorm::tPackF2B(othert.x), PackingSNorm::tPackF2B(othert.y), PackingSNorm::tPackF2B(othert.z), PackingSNorm::tPackS2B(othersign)); - Bitangent = Vec4sf(PackingSNorm::tPackF2B(otherb.x), PackingSNorm::tPackF2B(otherb.y), PackingSNorm::tPackF2B(otherb.z), PackingSNorm::tPackS2B(othersign)); - } - - explicit SMeshTangents(const Vec3& othert, const Vec3& otherb, const int16& othersign) - { - Tangent = Vec4sf(PackingSNorm::tPackF2B(othert.x), PackingSNorm::tPackF2B(othert.y), PackingSNorm::tPackF2B(othert.z), PackingSNorm::tPackS2B(othersign)); - Bitangent = Vec4sf(PackingSNorm::tPackF2B(otherb.x), PackingSNorm::tPackF2B(otherb.y), PackingSNorm::tPackF2B(otherb.z), PackingSNorm::tPackS2B(othersign)); - } - - void ExportTo(Vec4sf& othert, Vec4sf& otherb) const - { - othert = Tangent; - otherb = Bitangent; - } - - void ExportTo(SPipTangents& other) const - { - other.Tangent = Tangent; - other.Bitangent = Bitangent; - } - - bool operator ==(const SMeshTangents& other) const - { - return - Tangent[0] == other.Tangent[0] || - Tangent[1] == other.Tangent[1] || - Tangent[2] == other.Tangent[2] || - Tangent[3] == other.Tangent[3] || - Bitangent[0] == other.Bitangent[0] || - Bitangent[1] == other.Bitangent[1] || - Bitangent[2] == other.Bitangent[2] || - Bitangent[3] == other.Bitangent[3]; - } - - bool operator !=(const SMeshTangents& other) const - { - return !(*this == other); - } - - bool IsEquivalent(const Vec3& othert, const Vec3& otherb, const int16& othersign, float epsilon = 0.01f) const - { - // TODO: can be optimized to use only integer arithmetic - Vec4 tng, btg; - GetTB(tng, btg); - - Vec3 tng3(tng.x, tng.y, tng.z); - Vec3 btg3(btg.x, btg.y, btg.z); - - return - (tng.w == othersign) && - (btg.w == othersign) && - (tng3.Dot(othert) >= (1.0f - epsilon)) && - (btg3.Dot(otherb) >= (1.0f - epsilon)); - } - - void GetTB(Vec4sf& othert, Vec4sf& otherb) const - { - othert = Tangent; - otherb = Bitangent; - } - - void GetTB(Vec4& othert, Vec4& otherb) const - { - othert = PackingSNorm::tPackB2F(Tangent); - otherb = PackingSNorm::tPackB2F(Bitangent); - } - - void GetTB(Vec3& othert, Vec3& otherb) const - { - const Vec4 t = PackingSNorm::tPackB2F(Tangent); - const Vec4 b = PackingSNorm::tPackB2F(Bitangent); - - othert = Vec3(t.x, t.y, t.z); - otherb = Vec3(b.x, b.y, b.z); - } - - ILINE Vec3 GetN() const - { - Vec4 tng, btg; - GetTB(tng, btg); - - Vec3 tng3(tng.x, tng.y, tng.z); - Vec3 btg3(btg.x, btg.y, btg.z); - - // assumes w 1 or -1 - return tng3.Cross(btg3) * tng.w; - } - - void GetN(Vec3& othern) const - { - othern = GetN(); - } - - void GetTBN(Vec3& othert, Vec3& otherb, Vec3& othern) const - { - Vec4 tng, btg; - GetTB(tng, btg); - - Vec3 tng3(tng.x, tng.y, tng.z); - Vec3 btg3(btg.x, btg.y, btg.z); - - // assumes w 1 or -1 - othert = tng3; - otherb = btg3; - othern = tng3.Cross(btg3) * tng.w; - } - - ILINE int16 GetR() const - { - return PackingSNorm::tPackB2S(Tangent.w); - } - - void GetR(int16& sign) const - { - sign = GetR(); - } - - void RotateBy(const Matrix33& rot) - { - Vec4 tng, btg; - GetTB(tng, btg); - - Vec3 tng3(tng.x, tng.y, tng.z); - Vec3 btg3(btg.x, btg.y, btg.z); - - tng3 = rot * tng3; - btg3 = rot * btg3; - - *this = SMeshTangents(tng3, btg3, PackingSNorm::tPackB2S(Tangent.w)); - } - - void RotateSafelyBy(const Matrix33& rot) - { - Vec4 tng, btg; - GetTB(tng, btg); - - Vec3 tng3(tng.x, tng.y, tng.z); - Vec3 btg3(btg.x, btg.y, btg.z); - - tng3 = rot * tng3; - btg3 = rot * btg3; - - // normalize in case "rot" wasn't length-preserving - tng3.Normalize(); - btg3.Normalize(); - - *this = SMeshTangents(tng3, btg3, PackingSNorm::tPackB2S(Tangent.w)); - } - - void RotateBy(const Matrix34& trn) - { - Vec4 tng, btg; - GetTB(tng, btg); - - Vec3 tng3(tng.x, tng.y, tng.z); - Vec3 btg3(btg.x, btg.y, btg.z); - - tng3 = trn.TransformVector(tng3); - btg3 = trn.TransformVector(btg3); - - *this = SMeshTangents(tng3, btg3, PackingSNorm::tPackB2S(Tangent.w)); - } - - void RotateSafelyBy(const Matrix34& trn) - { - Vec4 tng, btg; - GetTB(tng, btg); - - Vec3 tng3(tng.x, tng.y, tng.z); - Vec3 btg3(btg.x, btg.y, btg.z); - - tng3 = trn.TransformVector(tng3); - btg3 = trn.TransformVector(btg3); - - // normalize in case "rot" wasn't length-preserving - tng3.Normalize(); - btg3.Normalize(); - - *this = SMeshTangents(tng3, btg3, PackingSNorm::tPackB2S(Tangent.w)); - } - - void SlerpTowards(const SMeshTangents& other, const SMeshNormal& normal, float pos) - { - Vec3 tngA, btgA; - Vec3 tngB, btgB; - this->GetTB(tngA, btgA); - other.GetTB(tngB, btgB); - - // Q: necessary? - tngA.Normalize(); - tngB.Normalize(); - btgA.Normalize(); - btgB.Normalize(); - - tngA.SetSlerp(tngA, tngB, pos); - btgA.SetSlerp(btgA, btgB, pos); - - *this = SMeshTangents(tngA, btgA, normal.GetN()); - } - - AUTO_STRUCT_INFO -}; - -struct SMeshQTangents -{ - SMeshQTangents() {} - -private: - Vec4sf TangentBitangent; - -public: - explicit SMeshQTangents(const SPipQTangents& other) - { - TangentBitangent = other.QTangent; - } - - explicit SMeshQTangents(const Quat& other) - { - TangentBitangent.x = PackingSNorm::tPackF2B(other.v.x); - TangentBitangent.y = PackingSNorm::tPackF2B(other.v.y); - TangentBitangent.z = PackingSNorm::tPackF2B(other.v.z); - TangentBitangent.w = PackingSNorm::tPackF2B(other.w); - } - - void ExportTo(SPipQTangents& other) - { - other.QTangent = TangentBitangent; - } - - ILINE Quat GetQ() const - { - Quat q; - - q.v.x = PackingSNorm::tPackB2F(TangentBitangent.x); - q.v.y = PackingSNorm::tPackB2F(TangentBitangent.y); - q.v.z = PackingSNorm::tPackB2F(TangentBitangent.z); - q.w = PackingSNorm::tPackB2F(TangentBitangent.w); - - return q; - } - - AUTO_STRUCT_INFO -}; - -// Description: -// for skinning every vertex has 4 bones and 4 weights. -struct SMeshBoneMapping_uint16 -{ - typedef uint16 BoneId; - typedef uint8 Weight; - - BoneId boneIds[4]; - Weight weights[4]; - - AUTO_STRUCT_INFO -}; - -struct SMeshBoneMapping_uint8 -{ - typedef uint8 BoneId; - typedef uint8 Weight; - - BoneId boneIds[4]; - Weight weights[4]; - - AUTO_STRUCT_INFO -}; - -//START: Add LOD support for touch bending vegetation -struct SMeshBoneMappingInfo_uint8 -{ - SMeshBoneMappingInfo_uint8(int vertexCount) - { - //Will be deleted by ~SFoliageInfoCGF() - pBoneMapping = new SMeshBoneMapping_uint8[vertexCount]; - nVertexCount = vertexCount; - } - - int nVertexCount; - struct SMeshBoneMapping_uint8* pBoneMapping; - - AUTO_STRUCT_INFO -}; -//END: Add LOD support for touch bending vegetation - -// Subset of mesh is a continuous range of vertices and indices that share same material. -struct SMeshSubset -{ - Vec3 vCenter; - float fRadius; - float fTexelDensity; - - int nFirstIndexId; - int nNumIndices; - - int nFirstVertId; - int nNumVerts; - - int nMatID; // Material Sub-object id. - int nMatFlags; // Special Material flags. - int nPhysicalizeType; // Type of physicalization for this subset. - - AZ::Vertex::Format vertexFormat; - - SMeshSubset() - : vCenter(0, 0, 0) - , fRadius(0) - , fTexelDensity(0) - , nFirstIndexId(0) - , nNumIndices(0) - , nFirstVertId(0) - , nNumVerts(0) - , nMatID(0) - , nMatFlags(0) - , nPhysicalizeType(PHYS_GEOM_TYPE_DEFAULT) - , vertexFormat(eVF_P3S_C4B_T2S) - { - } - - void GetMemoryUsage([[maybe_unused]] class ICrySizer* pSizer) const - { - } - - // fix numVerts - void FixRanges(vtx_idx* pIndices) - { - int startVertexToMerge = nFirstVertId; - int startIndexToMerge = nFirstIndexId; - int numIndiciesToMerge = nNumIndices; - // find good min and max AGAIN - int maxVertexInUse = 0; - for (int n = 0; n < numIndiciesToMerge; n++) - { - int i = (int)pIndices[n + startIndexToMerge]; - startVertexToMerge = (i < startVertexToMerge ? i : startVertexToMerge);// min - maxVertexInUse = (i > maxVertexInUse ? i : maxVertexInUse);// max - } - nNumVerts = maxVertexInUse - startVertexToMerge + 1; - } -}; - -class CMeshHelpers -{ -public: - template <class TPosition, class TTexCoordinates, class TIndex> - static bool ComputeTexMappingAreas( - size_t indexCount, const TIndex* pIndices, - size_t vertexCount, - const TPosition* pPositions, size_t stridePositions, - const TTexCoordinates* pTexCoords, size_t strideTexCoords, - float& computedPosArea, float& computedTexArea, const char*& errorText) - { - static const float minPosArea = 10e-6f; - static const float minTexArea = 10e-8f; - - computedPosArea = 0; - computedTexArea = 0; - errorText = "?"; - - if (indexCount <= 0) - { - errorText = "index count is 0"; - return false; - } - - if (vertexCount <= 0) - { - errorText = "vertex count is 0"; - return false; - } - - if ((pIndices == NULL) || (pPositions == NULL)) - { - errorText = "indices and/or positions are NULL"; - return false; - } - - if (pTexCoords == NULL) - { - errorText = "texture coordinates are NULL"; - return false; - } - - if (indexCount % 3 != 0) - { - assert(0); - errorText = "bad number of indices"; - return false; - } - - // Compute average geometry area of face - - int count = 0; - float posAreaSum = 0; - float texAreaSum = 0; - for (size_t i = 0; i < indexCount; i += 3) - { - const size_t index0 = pIndices[i]; - const size_t index1 = pIndices[i + 1]; - const size_t index2 = pIndices[i + 2]; - - if ((index0 >= vertexCount) || (index1 >= vertexCount) || (index2 >= vertexCount)) - { - errorText = "bad vertex index detected"; - return false; - } - - const Vec3 pos0 = ToVec3(*(const TPosition*) (((const char*)pPositions) + index0 * stridePositions)); - const Vec3 pos1 = ToVec3(*(const TPosition*) (((const char*)pPositions) + index1 * stridePositions)); - const Vec3 pos2 = ToVec3(*(const TPosition*) (((const char*)pPositions) + index2 * stridePositions)); - - const Vec2 tex0 = ToVec2(*(const TTexCoordinates*) (((const char*)pTexCoords) + index0 * strideTexCoords)); - const Vec2 tex1 = ToVec2(*(const TTexCoordinates*) (((const char*)pTexCoords) + index1 * strideTexCoords)); - const Vec2 tex2 = ToVec2(*(const TTexCoordinates*) (((const char*)pTexCoords) + index2 * strideTexCoords)); - - const float posArea = ((pos1 - pos0).Cross(pos2 - pos0)).GetLength() * 0.5f; - const float texArea = fabsf((tex1 - tex0).Cross(tex2 - tex0)) * 0.5f; - - if ((posArea >= minPosArea) && (texArea >= minTexArea)) - { - posAreaSum += posArea; - texAreaSum += texArea; - ++count; - } - } - - if (count == 0 || (posAreaSum < minPosArea) || (texAreaSum < minTexArea)) - { - errorText = "faces are too small or have stretched mapping"; - return false; - } - - computedPosArea = posAreaSum; - computedTexArea = texAreaSum; - return true; - } - - template <class TPosition> - static bool CollectFaceAreas(size_t indexCount, const vtx_idx* pIndices, size_t vertexCount, - const TPosition* pPositions, size_t stridePositions, std::vector<float>& areas) - { - static const float minFaceArea = 10e-6f; - - if (indexCount % 3 != 0) - { - return false; - } - - areas.reserve(areas.size() + indexCount / 3); - - for (size_t i = 0; i < indexCount; i += 3) - { - const uint index0 = pIndices[i]; - const uint index1 = pIndices[i + 1]; - const uint index2 = pIndices[i + 2]; - - if ((index0 >= vertexCount) || (index1 >= vertexCount) || (index2 >= vertexCount)) - { - return false; - } - - const Vec3 pos0 = ToVec3(*(const TPosition*) (((const char*)pPositions) + index0 * stridePositions)); - const Vec3 pos1 = ToVec3(*(const TPosition*) (((const char*)pPositions) + index1 * stridePositions)); - const Vec3 pos2 = ToVec3(*(const TPosition*) (((const char*)pPositions) + index2 * stridePositions)); - - const float faceArea = ((pos1 - pos0).Cross(pos2 - pos0)).GetLength() * 0.5f; - - if (faceArea >= minFaceArea) - { - areas.push_back(faceArea); - } - } - - return true; - } - -private: - template <class T> - inline static Vec3 ToVec3(const T& v) - { - return v.ToVec3(); - } - - template <class T> - inline static Vec2 ToVec2(const T& v) - { - Vec2 uv; - v.GetUV(uv); - - return uv; - } -}; - -template <> -inline Vec3 CMeshHelpers::ToVec3<Vec3>(const Vec3& v) -{ - return v; -} - -template <> -inline Vec2 CMeshHelpers::ToVec2<Vec2>(const Vec2& v) -{ - return v; -} - -template <> -inline Vec2 CMeshHelpers::ToVec2<Vec2f16>(const Vec2f16& v) -{ - return v.ToVec2(); -} - -template <> -inline Vec2 CMeshHelpers::ToVec2<SMeshTexCoord>(const SMeshTexCoord& v) -{ - return v.GetUV(); -} - - -////////////////////////////////////////////////////////////////////////// -// Description: -// General purpose mesh class. -////////////////////////////////////////////////////////////////////////// -class CMesh -{ -public: - // e.g. no more than 8 positions, 8 colors, 8 uv sets, etc. - const static uint maxStreamsPerType = 8; - enum EStream - { - POSITIONS = 0, - POSITIONSF16, - NORMALS, - FACES, - TOPOLOGY_IDS, - TEXCOORDS, - COLORS, - INDICES, - TANGENTS, - BONEMAPPING, - VERT_MATS, - QTANGENTS, - P3S_C4B_T2S, - - EXTRABONEMAPPING, // Extra stream. Does not have a stream ID in the CGF. Its data is saved at the end of the BONEMAPPING stream. - - LAST_STREAM, - }; - - SMeshFace* m_pFaces; // faces are used in mesh processing/compilation - int32* m_pTopologyIds; - - // geometry data - vtx_idx* m_pIndices; // indices are used for the final render-mesh - Vec3* m_pPositions; - Vec3f16* m_pPositionsF16; - - SMeshNormal* m_pNorms; - SMeshTangents* m_pTangents; - SMeshQTangents* m_pQTangents; - SMeshTexCoord* m_pTexCoord; - SMeshColor* m_pColor0; - SMeshColor* m_pColor1; - - int* m_pVertMats; - SVF_P3S_C4B_T2S* m_pP3S_C4B_T2S; - - SMeshBoneMapping_uint16* m_pBoneMapping; //bone-mapping for the final render-mesh - SMeshBoneMapping_uint16* m_pExtraBoneMapping; //bone indices and weights for bones 5 to 8. - - int m_nCoorCount; //number of texture coordinates in m_pTexCoord array - int m_streamSize[LAST_STREAM][maxStreamsPerType]; - - // Bounding box. - AABB m_bbox; - - // Array of mesh subsets. - DynArray<SMeshSubset> m_subsets; - - // Mask that indicate if this stream is using not allocated in Mesh pointer; - // ex. if (m_sharedStreamMasks[0] & (1<<NORMALS) -> the 1st normals stream is shared - // if (m_sharedStreamMasks[1] & (1<<TEXCOORDS) -> the 2nd uv set stream is shared - uint32 m_sharedStreamMasks[maxStreamsPerType]; - - // Texture space area divided by geometry area. Zero if cannot compute. - float m_texMappingDensity; - - // Geometric mean value calculated from the areas of this mesh faces. - float m_geometricMeanFaceArea; - - ////////////////////////////////////////////////////////////////////////// - void GetMemoryUsage(class ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - pSizer->AddObject(m_subsets); - - for (int streamType = 0; streamType < LAST_STREAM; streamType++) - { - for (int streamIndex = 0; streamIndex < GetNumberOfStreamsByType(streamType); ++streamIndex) - { - void* pStream; - int nElementSize = 0; - GetStreamInfo(streamType, streamIndex, pStream, nElementSize); - pSizer->AddObject(pStream, m_streamSize[streamType][streamIndex] * nElementSize); - } - } - } - - ////////////////////////////////////////////////////////////////////////// - CMesh() - { - m_pFaces = NULL; - m_pTopologyIds = NULL; - m_pIndices = NULL; - m_pPositions = NULL; - m_pPositionsF16 = NULL; - m_pNorms = NULL; - m_pTangents = NULL; - m_pQTangents = NULL; - m_pTexCoord = NULL; - m_pColor0 = NULL; - m_pColor1 = NULL; - m_pVertMats = NULL; - m_pP3S_C4B_T2S = NULL; - m_pBoneMapping = NULL; - m_pExtraBoneMapping = NULL; - - m_nCoorCount = 0; - - memset(m_texCoords, 0, sizeof(m_texCoords)); - memset(m_streamSize, 0, sizeof(m_streamSize)); - - m_bbox.Reset(); - - memset(m_sharedStreamMasks, 0, sizeof(m_sharedStreamMasks)); - - m_texMappingDensity = 0.0f; - m_geometricMeanFaceArea = 0.0f; - } - - virtual ~CMesh() - { - FreeStreams(); - } - - void FreeStreams() - { - for (int streamType = 0; streamType < LAST_STREAM; ++streamType) - { - for (int streamIndex = 0; streamIndex < GetNumberOfStreamsByType(streamType); ++streamIndex) - { - ReallocStream(streamType, streamIndex, 0); - } - } - } - - int GetFaceCount() const - { - return m_streamSize[FACES][0]; - } - int GetVertexCount() const - { - return max(max(m_streamSize[POSITIONS][0], m_streamSize[POSITIONSF16][0]), m_streamSize[P3S_C4B_T2S][0]); - } - int GetTexCoordCount() const - { - return m_nCoorCount; - } - int GetTangentCount() const - { - return m_streamSize[TANGENTS][0]; - } - int GetSubSetCount() const - { - return m_subsets.size(); - } - int GetIndexCount() const - { - return m_streamSize[INDICES][0]; - } - - void SetFaceCount(int nNewCount) - { - ReallocStream(FACES, 0, nNewCount); - } - - void SetVertexCount(int nNewCount) - { - if (GetVertexCount() != nNewCount || GetVertexCount() == 0) - { - ReallocStream(POSITIONS, 0, nNewCount); - ReallocStream(POSITIONSF16, 0, 0); - ReallocStream(NORMALS, 0, nNewCount); - - if (m_pColor0) - { - ReallocStream(COLORS, 0, nNewCount); - } - - if (m_pColor1) - { - ReallocStream(COLORS, 1, nNewCount); - } - - if (m_pVertMats) - { - ReallocStream(VERT_MATS, 0, nNewCount); - } - } - } - - void SetTexCoordsCount(int nNewCount) - { - if (m_nCoorCount != nNewCount || m_nCoorCount == 0) - { - ReallocStream(TEXCOORDS, 0, nNewCount); - m_nCoorCount = nNewCount; - } - } - - void SetTexCoordsAndTangentsCount(int nNewCount) - { - if (m_nCoorCount != nNewCount || m_nCoorCount == 0) - { - ReallocStream(TEXCOORDS, 0, nNewCount); - ReallocStream(TANGENTS, 0, nNewCount); - m_nCoorCount = nNewCount; - } - } - - void SetIndexCount(int nNewCount) - { - ReallocStream(INDICES, 0, nNewCount); - } - // Once m_pTexCoords, m_pColors, etc. are wrapped in vectors, return the size of the vector - // or if we go with fixed size arrays, with a bunch of nullptrs, maybe just return the fixed size or the number of non-null ptrs - int GetNumberOfStreamsByType(int streamType) const - { - if (streamType == COLORS || streamType == TEXCOORDS) - { - return 2; - } - return 1; - } - - bool Has32BitPositions(void) const - { - return m_pPositions != nullptr; - } - - bool Has16BitPositions(void) const - { - return m_pPositionsF16 != nullptr; - } - - bool IsUVSetEmptyForSubmesh(uint submeshIndex, uint uvSet) - { - // Get a pointer to the uv set - SMeshTexCoord* texCoords = nullptr; - if (uvSet == 0) - { - texCoords = m_pTexCoord; - } - else - { - texCoords = m_texCoords[uvSet]; - } - - if (texCoords) - { - // Iterate through the vertices for the submesh - Vec2 emptyTexCoord = Vec2(0.0f, 0.0f); - for (int i = m_subsets[submeshIndex].nFirstVertId; i < m_subsets[submeshIndex].nFirstVertId + m_subsets[submeshIndex].nNumVerts; ++i) - { - // If any of the texture coordinates for the given uv set are non-zero, return false. - if (texCoords[i].GetUV() != emptyTexCoord) - { - return false; - } - } - } - // If no valid texture coordinates are found for submesh for the given uv set, return true. - return true; - } - - void SetSubmeshVertexFormats(void) - { - EVertexFormat desiredFormat = eVF_Unknown; - for (int submeshIndex = 0; submeshIndex < m_subsets.size(); ++submeshIndex) - { - // Choose float or short based on the precision of the positions - if (this->Has32BitPositions()) - { - // Choose one or two uv sets - if (IsUVSetEmptyForSubmesh(submeshIndex, 1)) - { - desiredFormat = eVF_P3F_C4B_T2F; - } - else - { - desiredFormat = eVF_P3F_C4B_T2F_T2F; - } - } - else if (this->Has16BitPositions()) - { - // Choose one or two uv sets - if (IsUVSetEmptyForSubmesh(submeshIndex, 1)) - { - desiredFormat = eVF_P3S_C4B_T2S; - } - else - { - desiredFormat = eVF_P3S_C4B_T2S_T2S; - } - } - else - { - AZ_Assert(false, "Submesh does not contain positions"); - } - - // Set the vertex format for the submesh - m_subsets[submeshIndex].vertexFormat = AZ::Vertex::Format(desiredFormat); - } - } - - AZ::Vertex::Format GetVertexFormatForSubmesh(int submeshIndex) const - { - assert(submeshIndex < m_subsets.size()); - - return m_subsets[submeshIndex].vertexFormat; - } - - AZ::Vertex::Format GetMeshGroupVertexFormat() const - { - AZ::Vertex::Format meshGroupFormat; - for (int submeshIndex = 0; submeshIndex < m_subsets.size(); ++submeshIndex) - { - if (m_subsets[submeshIndex].vertexFormat > meshGroupFormat) - { - meshGroupFormat = m_subsets[submeshIndex].vertexFormat; - } - } - - return meshGroupFormat; - } - - // Set specific stream type as shared. If there are multiple streams for a given type (such as multiple uv sets), then all streams of that type will be marked as shared - void SetSharedStream(int streamType, int streamIndex, void* pStream, int nElementCount) - { - AZ_Assert(streamType >= 0 && streamType < LAST_STREAM && streamIndex < maxStreamsPerType, "Stream type %d outside of allowable range (%d to %d) of CMesh::EStream, or stream index %d exceeds the maximum number of vertex streams (%d) per type.", streamType, 0, CMesh::LAST_STREAM, streamIndex, maxStreamsPerType); - if ((m_sharedStreamMasks[streamIndex] & (1 << streamType)) == 0) - { - ReallocStream(streamType, streamIndex, 0); - m_sharedStreamMasks[streamIndex] |= (1 << streamType); - } - SetStreamData(streamType, streamIndex, pStream, nElementCount); - } - - template <class T> - T* GetStreamPtrAndElementCount(int streamType, int streamIndex, int* pElementCount = 0) const - { - void* pStream = 0; - int nElementSize = 0; - GetStreamInfo(streamType, streamIndex, pStream, nElementSize); - - if (nElementSize != sizeof(T)) - { - AZ_Assert(false, "The element size %d returned by GetStreamInfo does not match the size %d of type T", nElementSize, sizeof(T)); - pStream = 0; - } - - const int nElementCount = (pStream ? this->m_streamSize[streamType][streamIndex] : 0); - - if (pElementCount) - { - *pElementCount = nElementCount; - } - return (T*)pStream; - } - - template <class T> - T* GetStreamPtr(int streamType, int streamIndex = 0) const - { - void* pStream = 0; - int nElementSize = 0; - GetStreamInfo(streamType, streamIndex, pStream, nElementSize); - - if (nElementSize != sizeof(T)) - { - AZ_Assert(false, "The element size %d returned by GetStreamInfo does not match the size %d of type T", nElementSize, sizeof(T)); - pStream = 0; - } - - return (T*)pStream; - } - - void GetStreamInfo(int streamType, int streamIndex, void*& pStream, int& nElementSize) const - { - pStream = 0; - nElementSize = 0; - AZ_Assert(streamType >= 0 && streamType < LAST_STREAM && streamIndex < maxStreamsPerType, "Stream type %d outside of allowable range (%d to %d) of CMesh::EStream, or stream index %d exceeds the maximum number of vertex streams (%d) per type.", streamType, 0, CMesh::LAST_STREAM, streamIndex, maxStreamsPerType); - - switch (streamType) - { - case POSITIONS: - pStream = m_pPositions; - nElementSize = sizeof(Vec3); - break; - case POSITIONSF16: - pStream = m_pPositionsF16; - nElementSize = sizeof(Vec3f16); - break; - case NORMALS: - pStream = m_pNorms; - nElementSize = sizeof(Vec3); - break; - case VERT_MATS: - pStream = m_pVertMats; - nElementSize = sizeof(int); - break; - case FACES: - pStream = m_pFaces; - nElementSize = sizeof(SMeshFace); - break; - case TOPOLOGY_IDS: - pStream = m_pTopologyIds; - nElementSize = sizeof(int32); - break; - case TEXCOORDS: - if (streamIndex == 0) - { - pStream = m_pTexCoord; - } - else - { - pStream = m_texCoords[streamIndex]; - } - nElementSize = sizeof(SMeshTexCoord); - break; - case COLORS: - if (streamIndex == 0) - { - pStream = m_pColor0; - } - else - { - pStream = m_pColor1; - } - nElementSize = sizeof(SMeshColor); - break; - case INDICES: - pStream = m_pIndices; - nElementSize = sizeof(vtx_idx); - break; - case TANGENTS: - pStream = m_pTangents; - nElementSize = sizeof(SMeshTangents); - break; - case QTANGENTS: - pStream = m_pQTangents; - nElementSize = sizeof(SMeshQTangents); - break; - case BONEMAPPING: - pStream = m_pBoneMapping; - nElementSize = sizeof(SMeshBoneMapping_uint16); - break; - case EXTRABONEMAPPING: - pStream = m_pExtraBoneMapping; - nElementSize = sizeof(SMeshBoneMapping_uint16); - break; - case P3S_C4B_T2S: - pStream = m_pP3S_C4B_T2S; - nElementSize = sizeof(SVF_P3S_C4B_T2S); - break; - default: - AZ_Assert(false, "Unknown stream"); - break; - } - } - - - virtual void ReallocStream(int streamType, int streamIndex, int nNewCount) - { - if (streamType < 0 || streamType >= LAST_STREAM || streamIndex >= maxStreamsPerType) - { - AZ_Assert(false, "Stream type %d outside of allowable range (%d to %d) of CMesh::EStream, or stream index %d exceeds the maximum number of vertex streams (%d) per type.", streamType, 0, CMesh::LAST_STREAM, streamIndex, maxStreamsPerType); - return; - } - - if (m_sharedStreamMasks[streamIndex] & (1 << streamType)) - { - m_sharedStreamMasks[streamIndex] &= ~(1 << streamType); - - if (nNewCount <= 0) - { - SetStreamData(streamType, 0, nullptr, 0); - } - else - { - const int nOldCount = m_streamSize[streamType][streamIndex]; - void* pOldElements = 0; - int nElementSize = 0; - GetStreamInfo(streamType, streamIndex, pOldElements, nElementSize); - - void* const pNewElements = realloc(0, nNewCount * nElementSize); - if (!pNewElements) - { - AZ_Assert(false, "Allocation failed"); - SetStreamData(streamType, streamIndex, nullptr, 0); - return; - } - - if (nOldCount > 0) - { - memcpy(pNewElements, pOldElements, min(nOldCount, nNewCount) * nElementSize); - } - if (nNewCount > nOldCount) - { - memset((char*)pNewElements + nOldCount * nElementSize, 0, (nNewCount - nOldCount) * nElementSize); - } - - SetStreamData(streamType, streamIndex, pNewElements, nNewCount); - } - } - else - { - const int nOldCount = m_streamSize[streamType][streamIndex]; - if (nOldCount == nNewCount) - { - // stream already has required size - return; - } - - void* pOldElements = 0; - int nElementSize = 0; - GetStreamInfo(streamType, streamIndex, pOldElements, nElementSize); - - if (nNewCount <= 0) - { - free(pOldElements); - SetStreamData(streamType, streamIndex, nullptr, 0); - } - else - { - void* const pNewElements = realloc(pOldElements, nNewCount * nElementSize); - if (!pNewElements) - { - AZ_Assert(false, "Allocation failed"); - free(pOldElements); - SetStreamData(streamType, streamIndex, nullptr, 0); - return; - } - - if (nNewCount > nOldCount) - { - memset((char*)pNewElements + nOldCount * nElementSize, 0, (nNewCount - nOldCount) * nElementSize); - } - - SetStreamData(streamType, streamIndex, pNewElements, nNewCount); - } - } - } - - // Copy mesh from source mesh. - void Copy(const CMesh& mesh) - { - for (int streamType = 0; streamType < LAST_STREAM; streamType++) - { - for (int streamIndex = 0; streamIndex < GetNumberOfStreamsByType(streamType); ++streamIndex) - { - ReallocStream(streamType, streamIndex, mesh.m_streamSize[streamType][streamIndex]); - if (mesh.m_streamSize[streamType][streamIndex] > 0) - { - void* pSrcStream = 0; - void* pTrgStream = 0; - int nElementSize = 0; - mesh.GetStreamInfo(streamType, streamIndex, pSrcStream, nElementSize); - GetStreamInfo(streamType, streamIndex, pTrgStream, nElementSize); - if (pSrcStream && pTrgStream) - { - memcpy(pTrgStream, pSrcStream, m_streamSize[streamType][streamIndex] * nElementSize); - } - } - } - } - m_bbox = mesh.m_bbox; - m_subsets = mesh.m_subsets; - m_texMappingDensity = mesh.m_texMappingDensity; - m_geometricMeanFaceArea = mesh.m_geometricMeanFaceArea; - } - - bool CompareStreams(const CMesh& mesh) const - { - for (int streamType = 0; streamType < LAST_STREAM; streamType++) - { - for (int streamIndex = 0; streamIndex < GetNumberOfStreamsByType(streamType); ++streamIndex) - { - if (m_streamSize[streamType][streamIndex] != mesh.m_streamSize[streamType][streamIndex]) - { - return false; - } - - if (m_streamSize[streamType][streamIndex]) - { - void* pStream1 = 0; - void* pStream2 = 0; - int nElementSize1 = 0; - int nElementSize2 = 0; - GetStreamInfo(streamType, streamIndex, pStream1, nElementSize1); - mesh.GetStreamInfo(streamType, streamIndex, pStream2, nElementSize2); - - assert(nElementSize1 == nElementSize2); - - if ((pStream1 && !pStream2) || (!pStream1 && pStream2)) - { - return false; - } - - if (pStream1 && pStream2) - { - if (memcmp(pStream1, pStream2, m_streamSize[streamType][streamIndex] * nElementSize1) != 0) - { - return false; - } - } - } - } - } - return true; - } - - // Add streams from source mesh to the end of existing streams. - const char* Append(const CMesh& mesh) - { - return Append(mesh, 0, -1, 0, -1); - } - - // Add streams from source mesh to the end of existing streams. - const char* Append(const CMesh& mesh, int fromVertex, int vertexCount, int fromFace, int faceCount) - { - if (GetIndexCount() > 0 || mesh.GetIndexCount() > 0) - { - assert(0); - return "Cmesh::Append() cannot handle meshes with indices, it can handle faces only"; - } - - // Non-ranged requests should start from 0th element and element count should be <0. - if ((vertexCount < 0 && fromVertex != 0) || (faceCount < 0 && fromFace != 0)) - { - assert(0); - return "Cmesh::Append(): Bad CMesh parameters"; - } - if (vertexCount < 0) - { - vertexCount = mesh.GetVertexCount(); - } - if (faceCount < 0) - { - faceCount = mesh.GetFaceCount(); - } - - const int oldVertexCount = GetVertexCount(); - const int oldFaceCount = GetFaceCount(); - const int nOldCoorCount = GetTexCoordCount(); - - if (GetTexCoordCount() != 0 && GetTexCoordCount() != oldVertexCount) - { - assert(0); - return "Cmesh::Append(): Mismatch in target CMesh vert/tcoord counts"; - } - - if (mesh.GetTexCoordCount() != 0 && mesh.GetTexCoordCount() != mesh.GetVertexCount()) - { - assert(0); - return "Cmesh::Append(): Mismatch in source CMesh vert/tcoord counts"; - } - - for (int streamType = 0; streamType < LAST_STREAM; ++streamType) - { - for (int streamIndex = 0; streamIndex < GetNumberOfStreamsByType(streamType); ++streamIndex) - { - const int oldCount = (streamType == FACES) ? oldFaceCount : oldVertexCount; - - const int from = (streamType == FACES) ? fromFace : fromVertex; - const int count = (streamType == FACES) ? faceCount : vertexCount; - - const int oldStreamSize = m_streamSize[streamType][streamIndex]; - const int streamSize = mesh.m_streamSize[streamType][streamIndex]; - - if (oldStreamSize <= 0 && (count <= 0 || streamSize <= 0)) - { - continue; - } - - ReallocStream(streamType, streamIndex, oldCount + count); - - if (count > 0) - { - void* pSrcStream = 0; - void* pTrgStream = 0; - int srcElementSize = 0; - int trgElementSize = 0; - mesh.GetStreamInfo(streamType, streamIndex, pSrcStream, srcElementSize); - GetStreamInfo(streamType, streamIndex, pTrgStream, trgElementSize); - - assert(srcElementSize == trgElementSize); - - if (pSrcStream && pTrgStream) - { - memcpy( - (char*)pTrgStream + oldCount * trgElementSize, - (char*)pSrcStream + from * srcElementSize, - count * srcElementSize); - } - } - } - } - - { - const int nOffset = oldVertexCount - fromVertex; - const int newFaceCount = GetFaceCount(); - - for (int i = oldFaceCount; i < newFaceCount; ++i) - { - m_pFaces[i].v[0] += nOffset; - m_pFaces[i].v[1] += nOffset; - m_pFaces[i].v[2] += nOffset; - } - } - - m_bbox.Add(mesh.m_bbox.min); - m_bbox.Add(mesh.m_bbox.max); - - return 0; - } - - void RemoveRangeFromStream(int streamType, int streamIndex, int nFirst, int nCount) - { - if (streamType < 0 || streamType >= LAST_STREAM || streamIndex >= maxStreamsPerType) - { - AZ_Assert(false, "Stream type %d outside of allowable range (%d to %d) of CMesh::EStream, or stream index %d exceeds the maximum number of vertex streams (%d) per type.", streamType, 0, CMesh::LAST_STREAM, streamIndex, maxStreamsPerType); - return; - } - - if (m_sharedStreamMasks[streamIndex] & (1 << streamType)) - { - // Make shared stream non-shared - ReallocStream(streamType, streamIndex, m_streamSize[streamType][streamIndex]); - } - - const int nTotalCount = m_streamSize[streamType][streamIndex]; - - int nElementSize; - void* pStream = 0; - GetStreamInfo(streamType, streamIndex, pStream, nElementSize); - - if (nFirst >= nTotalCount || nTotalCount <= 0 || pStream == 0) - { - return; - } - if (nFirst + nCount > nTotalCount) - { - nCount = nTotalCount - nFirst; - } - if (nCount <= 0) - { - return; - } - - const int nTailCount = nTotalCount - (nFirst + nCount); - if (nTailCount > 0) - { - char* const pRangeStart = (char*)pStream + nFirst * nElementSize; - char* const pRangeEnd = (char*)pStream + (nFirst + nCount) * nElementSize; - memmove(pRangeStart, pRangeEnd, nTailCount * nElementSize); - } - - ReallocStream(streamType, streamIndex, nTotalCount - nCount); - } - - bool Validate(const char** const ppErrorDescription) const - { - const int vertexCount = GetVertexCount(); - const int faceCount = GetFaceCount(); - const int indexCount = GetIndexCount(); - - if ((faceCount <= 0) && (indexCount <= 0)) - { - if (vertexCount > 0) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "no any indices, but vertices exist"; - } - return false; - } - } - - if ((uint)vertexCount > (sizeof(vtx_idx) == 2 ? 0xffff : 0x7fffffff)) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = - (sizeof(vtx_idx) == 2) - ? "vertex count is greater or equal than 64K" - : "vertex count is greater or equal than 2G"; - } - return false; - } - - if (faceCount > 0) - { - if (vertexCount <= 0) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "no any vertices, but faces exist"; - } - return false; - } - } - - if (indexCount > 0) - { - if (vertexCount <= 0) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "no any vertices, but indices exist"; - } - return false; - } - } - - for (int i = 0; i < faceCount; ++i) - { - const SMeshFace& face = m_pFaces[i]; - for (int j = 0; j < 3; ++j) - { - const int v = face.v[j]; - if ((v < 0) || (v >= vertexCount)) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "a face refers vertex outside of vertex array"; - } - return false; - } - } - } - - for (int i = 0; i < indexCount; i++) - { - if ((uint)m_pIndices[i] >= (uint)vertexCount) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "an index refers vertex outside of vertex array"; - } - return false; - } - } - - if (GetTexCoordCount() != 0 && GetTexCoordCount() != vertexCount) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "number of texture coordinates is different from number of vertices"; - } - return false; - } - - if (!_finite(m_bbox.min.x) || !_finite(m_bbox.min.y) || !_finite(m_bbox.min.z) || - !_finite(m_bbox.max.x) || !_finite(m_bbox.max.y) || !_finite(m_bbox.max.z)) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "bounding box contains damaged data"; - } - return false; - } - - if (m_bbox.IsReset()) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "bounding box is not set"; - } - return false; - } - - if (m_bbox.max.x < m_bbox.min.x || - m_bbox.max.y < m_bbox.min.y || - m_bbox.max.z < m_bbox.min.z) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "bounding box min is greater than max"; - } - return false; - } - - if (m_bbox.min.GetDistance(m_bbox.max) < 0.001f) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "bounding box is less than 1 mm in size"; - } - return false; - } - - for (int s = 0, subsetCount = m_subsets.size(); s < subsetCount; ++s) - { - const SMeshSubset& subset = m_subsets[s]; - - if (subset.nNumIndices <= 0) - { - if (subset.nNumVerts > 0) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "a mesh subset without indices contains vertices"; - } - return false; - } - continue; - } - else if (subset.nNumVerts <= 0) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "a mesh subset has indices but vertices are missing"; - } - return false; - } - - if (subset.nFirstIndexId < 0) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "a mesh subset has negative start position in index array"; - } - return false; - } - if (subset.nFirstIndexId + subset.nNumIndices > indexCount) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "a mesh subset refers indices outside of index array"; - } - return false; - } - if (subset.nFirstVertId < 0) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "a mesh subset has negative start position in vertex array"; - } - return false; - } - if (subset.nFirstVertId + subset.nNumVerts > vertexCount) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "a mesh subset refers vertices outside of vertex array"; - } - return false; - } - - for (int ii = subset.nFirstIndexId; ii < subset.nFirstIndexId + subset.nNumIndices; ++ii) - { - const uint index = m_pIndices[ii]; - if (index < (uint)subset.nFirstVertId) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "a mesh subset refers a vertex lying before subset vertices"; - } - return false; - } - if (index >= (uint)(subset.nFirstVertId + subset.nNumVerts)) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "a mesh subset refers a vertex lying after subset vertices"; - } - return false; - } - - Vec3 p(ZERO); - const Vec3* pp = &p; - if (m_pPositions) - { - pp = &m_pPositions[index]; - } - else if (m_pPositionsF16) - { - p = m_pPositionsF16[index].ToVec3(); - } - else if (m_pP3S_C4B_T2S) - { - p = m_pP3S_C4B_T2S[index].xyz.ToVec3(); - } - if (!_finite(pp->x)) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "a mesh subset contains a vertex with damaged x component"; - } - return false; - } - if (!_finite(pp->y)) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "a mesh subset contains a vertex with damaged y component"; - } - return false; - } - if (!_finite(pp->z)) - { - if (ppErrorDescription) - { - ppErrorDescription[0] = "a mesh subset contains a vertex with damaged z component"; - } - return false; - } - } - } - - return true; - } - - bool ComputeSubsetTexMappingAreas( - size_t subsetIndex, - float& computedPosArea, float& computedTexArea, const char*& errorText) - { - computedPosArea = 0.0f; - computedTexArea = 0.0f; - errorText = ""; - - if (subsetIndex >= (size_t)m_subsets.size()) - { - errorText = "subset index is bad"; - return false; - } - - if (GetIndexCount() <= 0) - { - errorText = "missing indices"; - return false; - } - - if ((GetVertexCount() <= 0) || ((m_pPositions == NULL) && (m_pPositionsF16 == NULL))) - { - errorText = "missing vertices"; - return false; - } - - if ((m_pTexCoord == NULL) || (GetTexCoordCount() <= 0)) - { - errorText = "missing texture coordinates"; - return false; - } - - const SMeshSubset& subset = m_subsets[subsetIndex]; - - if ((subset.nNumIndices <= 0) || (subset.nFirstIndexId < 0)) - { - errorText = "missing or bad indices in subset"; - return false; - } - - bool ok; - if (m_pPositions) - { - ok = CMeshHelpers::ComputeTexMappingAreas( - subset.nNumIndices, &m_pIndices[subset.nFirstIndexId], - GetVertexCount(), - &m_pPositions[0], sizeof(m_pPositions[0]), - &m_pTexCoord[0], sizeof(m_pTexCoord[0]), - computedPosArea, computedTexArea, errorText); - } - else - { - ok = CMeshHelpers::ComputeTexMappingAreas( - subset.nNumIndices, &m_pIndices[subset.nFirstIndexId], - GetVertexCount(), - &m_pPositionsF16[0], sizeof(m_pPositionsF16[0]), - &m_pTexCoord[0], sizeof(m_pTexCoord[0]), - computedPosArea, computedTexArea, errorText); - } - - return ok; - } - - // note: this function doesn't work for "old" uncompressed meshes (with faces instead of indices) - bool RecomputeTexMappingDensity() - { - m_texMappingDensity = 0; - - if (GetFaceCount() > 0) - { - // uncompressed mesh - not supported - return false; - } - - if ((GetIndexCount() <= 0) || (GetVertexCount() <= 0) || ((m_pPositions == NULL) && (m_pPositionsF16 == NULL))) - { - return false; - } - - if ((m_pTexCoord == NULL) || (GetTexCoordCount() <= 0)) - { - return false; - } - - float totalPosArea = 0; - float totalTexArea = 0; - - for (size_t i = 0, count = m_subsets.size(); i < count; ++i) - { - - float posArea; - float texArea; - const char* errorText = ""; - - const bool ok = ComputeSubsetTexMappingAreas(i, posArea, texArea, errorText); - - if (ok) - { - totalPosArea += posArea; - totalTexArea += texArea; - } - } - - if (totalPosArea <= 0) - { - return false; - } - - m_texMappingDensity = totalTexArea / totalPosArea; - return true; - } - - bool RecomputeGeometricMeanFaceArea() - { - m_geometricMeanFaceArea = 0.0f; - - if (GetFaceCount() > 0) - { - // uncompressed mesh - not supported - return false; - } - - if ((GetIndexCount() <= 0) || (GetVertexCount() <= 0) || ((m_pPositions == NULL) && (m_pPositionsF16 == NULL))) - { - return false; - } - - std::vector<float> areas; - const size_t subsetCount = m_subsets.size(); - - for (size_t i = 0; i < subsetCount; ++i) - { - CollectSubsetFaceAreas(m_subsets[i], areas); - } - - const size_t areasCount = areas.size(); - if (areasCount == 0) - { - return false; - } - - float fGeometricTotal = 0.0f; - for (size_t i = 0; i < areasCount; ++i) - { - fGeometricTotal += logf(areas[i]); - } - - m_geometricMeanFaceArea = expf(fGeometricTotal / areasCount); - - assert(m_geometricMeanFaceArea > 0.0f); - - return true; - } - - bool CollectSubsetFaceAreas(const SMeshSubset& subset, std::vector<float>& areas) - { - if ((subset.nNumIndices <= 0) || (subset.nFirstIndexId < 0)) - { - return false; - } - - bool ok = false; - if (m_pPositions != NULL) - { - ok = CMeshHelpers::CollectFaceAreas(subset.nNumIndices, &m_pIndices[subset.nFirstIndexId], - GetVertexCount(), &m_pPositions[0], sizeof(m_pPositions[0]), areas); - } - else if (m_pPositionsF16 != NULL) - { - ok = CMeshHelpers::CollectFaceAreas(subset.nNumIndices, &m_pIndices[subset.nFirstIndexId], - GetVertexCount(), &m_pPositionsF16[0], sizeof(m_pPositionsF16[0]), areas); - } - - return ok; - } - - ////////////////////////////////////////////////////////////////////////// - // Estimates the size of the render mesh. - uint32 EstimateRenderMeshMemoryUsage() const - { - const size_t cSizeStream[VSF_NUM] = { - 0U, - sizeof(SPipTangents), // VSF_TANGENTS - sizeof(SPipQTangents), // VSF_QTANGENTS - sizeof(SVF_W4B_I4S), // VSF_HWSKIN_INFO - sizeof(SVF_P3F), // VSF_VERTEX_VELOCITY -#if ENABLE_NORMALSTREAM_SUPPORT - sizeof(SPipNormal), // VSF_NORMALS -#endif - }; - - uint32 nMeshSize = 0; - uint32 activeStreams = (GetVertexCount()) ? 1U << VSF_GENERAL : 0U; - activeStreams |= - (m_pQTangents) ? (1U << VSF_QTANGENTS) : - (m_pTangents) ? (1U << VSF_TANGENTS) : 0U; - if (m_pBoneMapping) - { - activeStreams |= 1U << VSF_HWSKIN_INFO; - } - for (uint32 i = 0; i < VSF_NUM; i++) - { - if (activeStreams & (1U << i)) - { - nMeshSize += ((i == VSF_GENERAL) ? sizeof(SVF_P3S_C4B_T2S) : cSizeStream[i]) * GetVertexCount(); - nMeshSize += TARGET_DEFAULT_ALIGN - (nMeshSize & (TARGET_DEFAULT_ALIGN - 1)); - } - } - if (GetIndexCount()) - { - nMeshSize += GetIndexCount() * sizeof(vtx_idx); - nMeshSize += TARGET_DEFAULT_ALIGN - (nMeshSize & (TARGET_DEFAULT_ALIGN - 1)); - } - - return nMeshSize; - } - ////////////////////////////////////////////////////////////////////////// - - // This function used when we do not have an actual mesh, but only vertex/index count of it. - static uint32 ApproximateRenderMeshMemoryUsage(int nVertexCount, int nIndexCount) - { - uint32 nMeshSize = 0; - nMeshSize += nVertexCount * sizeof(SVF_P3S_C4B_T2S); - nMeshSize += nVertexCount * sizeof(SPipTangents); - - nMeshSize += nIndexCount * sizeof(vtx_idx); - return nMeshSize; - } - -private: - // Set stream size. - void SetStreamData(int streamType, int streamIndex, void* pStream, int nNewCount) - { - if (streamType < 0 || streamType >= LAST_STREAM || streamIndex >= maxStreamsPerType) - { - AZ_Assert(false, "Stream type %d outside of allowable range (%d to %d) of CMesh::EStream, or stream index %d exceeds the maximum number of vertex streams (%d) per type.", streamType, 0, CMesh::LAST_STREAM, streamIndex, maxStreamsPerType); - return; - } - m_streamSize[streamType][streamIndex] = nNewCount; - switch (streamType) - { - case POSITIONS: - m_pPositions = (Vec3*)pStream; - break; - case POSITIONSF16: - m_pPositionsF16 = (Vec3f16*)pStream; - break; - case NORMALS: - m_pNorms = (SMeshNormal*)pStream; - break; - case VERT_MATS: - m_pVertMats = (int*)pStream; - break; - case FACES: - m_pFaces = (SMeshFace*)pStream; - break; - case TOPOLOGY_IDS: - m_pTopologyIds = (int32*)pStream; - break; - case TEXCOORDS: - if (streamIndex == 0) - { - m_pTexCoord = (SMeshTexCoord*)pStream; - } - else - { - m_texCoords[streamIndex] = (SMeshTexCoord*)pStream; - } - m_nCoorCount = nNewCount; - break; - case COLORS: - if (streamIndex == 0) - { - m_pColor0 = (SMeshColor*)pStream; - } - else - { - m_pColor1 = (SMeshColor*)pStream; - } - break; - case INDICES: - m_pIndices = (vtx_idx*)pStream; - break; - case TANGENTS: - m_pTangents = (SMeshTangents*)pStream; - break; - case QTANGENTS: - m_pQTangents = (SMeshQTangents*)pStream; - break; - case BONEMAPPING: - m_pBoneMapping = (SMeshBoneMapping_uint16*)pStream; - break; - case EXTRABONEMAPPING: - m_pExtraBoneMapping = (SMeshBoneMapping_uint16*)pStream; - break; - case P3S_C4B_T2S: - m_pP3S_C4B_T2S = (SVF_P3S_C4B_T2S*)pStream; - m_nCoorCount = nNewCount; - break; - default: - AZ_Assert(false, "Unknown stream"); - break; - } - } - - SMeshTexCoord* m_texCoords[maxStreamsPerType]; -}; - -// Description: -// Editable mesh interface. -// IndexedMesh can be created directly or loaded from CGF file, before rendering it is converted into IRenderMesh. -// IStatObj is used to host IIndexedMesh, and corresponding IRenderMesh. -struct IIndexedMesh -{ - /*! Structure used for read-only access to mesh data. Used by GetMesh() function */ - struct SMeshDescription - { - const SMeshFace* m_pFaces; // pointer to array of faces - const Vec3* m_pVerts; // pointer to array of vertices in f32 format - const Vec3f16* m_pVertsF16; // pointer to array of vertices in f16 format - const SMeshNormal* m_pNorms; // pointer to array of normals - const SMeshColor* m_pColor; // pointer to array of vertex colors - const SMeshTexCoord* m_pTexCoord; // pointer to array of texture coordinates - const vtx_idx* m_pIndices; // pointer to array of indices - int m_nFaceCount; // number of elements m_pFaces array - int m_nVertCount; // number of elements in m_pVerts, m_pNorms and m_pColor arrays - int m_nCoorCount; // number of elements in m_pTexCoord array - int m_nIndexCount; // number of elements in m_pIndices array - }; - - // <interfuscator:shuffle> - virtual ~IIndexedMesh() {} - - // Release indexed mesh. - virtual void Release() = 0; - - //! Gives read-only access to mesh data - virtual void GetMeshDescription(SMeshDescription& meshDesc) const = 0; - - virtual CMesh* GetMesh() = 0; - - virtual void SetMesh(CMesh& mesh) = 0; - - /*! Frees vertex and face streams. Calling this function invalidates SMeshDescription pointers */ - virtual void FreeStreams() = 0; - - //! Return number of allocated faces - virtual int GetFaceCount() const = 0; - - /*! Reallocates faces. Calling this function invalidates SMeshDescription pointers */ - virtual void SetFaceCount(int nNewCount) = 0; - - //! Return number of allocated vertices, normals and colors - virtual int GetVertexCount() const = 0; - - /*! Reallocates vertices, normals and colors. Calling this function invalidates SMeshDescription pointers */ - virtual void SetVertexCount(int nNewCount) = 0; - - /*! Reallocates colors. Calling this function invalidates SMeshDescription pointers */ - virtual void SetColorCount(int nNewCount) = 0; - - //! Return number of allocated texture coordinates - virtual int GetTexCoordCount() const = 0; - - /*! Reallocates texture coordinates. Calling this function invalidates SMeshDescription pointers */ - virtual void SetTexCoordCount(int nNewCount, int numStreams = 1) = 0; - - //! Return number of allocated tangents. - virtual int GetTangentCount() const = 0; - - /*! Reallocates tangents. Calling this function invalidates SMeshDescription pointers */ - virtual void SetTangentCount(int nNewCount) = 0; - - // Get number of indices in the mesh. - virtual int GetIndexCount() const = 0; - - // Set number of indices in the mesh. - virtual void SetIndexCount(int nNewCount) = 0; - - // Allocates m_pBoneMapping in CMesh - virtual void AllocateBoneMapping() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Subset access. - ////////////////////////////////////////////////////////////////////////// - virtual int GetSubSetCount() const = 0; - virtual void SetSubSetCount(int nSubsets) = 0; - virtual const SMeshSubset& GetSubSet(int nIndex) const = 0; - virtual void SetSubsetBounds(int nIndex, const Vec3& vCenter, float fRadius) = 0; - virtual void SetSubsetIndexVertexRanges(int nIndex, int nFirstIndexId, int nNumIndices, int nFirstVertId, int nNumVerts) = 0; - virtual void SetSubsetMaterialId(int nIndex, int nMatID) = 0; - virtual void SetSubsetMaterialProperties(int nIndex, int nMatFlags, int nPhysicalizeType, const AZ::Vertex::Format& vertexFormat) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Mesh bounding box. - ////////////////////////////////////////////////////////////////////////// - virtual void SetBBox(const AABB& box) = 0; - virtual AABB GetBBox() const = 0; - virtual void CalcBBox() = 0; - - virtual void RestoreFacesFromIndices() = 0; - // </interfuscator:shuffle> - - // Optimizes mesh - virtual void Optimize(const char* szComment = NULL) = 0; -}; - - -#endif // CRYINCLUDE_CRYCOMMON_IINDEXEDMESH_H diff --git a/Code/CryEngine/CryCommon/IIndexedMesh_info.cpp b/Code/CryEngine/CryCommon/IIndexedMesh_info.cpp deleted file mode 100644 index 11303ed16e..0000000000 --- a/Code/CryEngine/CryCommon/IIndexedMesh_info.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "TypeInfo_impl.h" -#include <IIndexedMesh.h> // <> required for Interfuscator - -STRUCT_INFO_BEGIN(SMeshTexCoord) -STRUCT_VAR_INFO(s, TYPE_INFO(float)) -STRUCT_VAR_INFO(t, TYPE_INFO(float)) -STRUCT_INFO_END(SMeshTexCoord) - -STRUCT_INFO_BEGIN(SMeshNormal) -STRUCT_VAR_INFO(Normal, TYPE_INFO(Vec3)) -STRUCT_INFO_END(SMeshNormal) - -STRUCT_INFO_BEGIN(SMeshColor) -STRUCT_VAR_INFO(r, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(g, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(b, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(a, TYPE_INFO(uint8)) -STRUCT_INFO_END(SMeshColor) - -STRUCT_INFO_BEGIN(SMeshTangents) -STRUCT_VAR_INFO(Tangent, TYPE_INFO(Vec4sf)) -STRUCT_VAR_INFO(Bitangent, TYPE_INFO(Vec4sf)) -STRUCT_INFO_END(SMeshTangents) - -STRUCT_INFO_BEGIN(SMeshQTangents) -STRUCT_VAR_INFO(TangentBitangent, TYPE_INFO(Vec4sf)) -STRUCT_INFO_END(SMeshQTangents) - -STRUCT_INFO_BEGIN(SMeshBoneMapping_uint16) -STRUCT_VAR_INFO(boneIds, TYPE_ARRAY(4, TYPE_INFO(SMeshBoneMapping_uint16::BoneId))) -STRUCT_VAR_INFO(weights, TYPE_ARRAY(4, TYPE_INFO(SMeshBoneMapping_uint16::Weight))) -STRUCT_INFO_END(SMeshBoneMapping_uint16) - -STRUCT_INFO_BEGIN(SMeshBoneMapping_uint8) -STRUCT_VAR_INFO(boneIds, TYPE_ARRAY(4, TYPE_INFO(SMeshBoneMapping_uint8::BoneId))) -STRUCT_VAR_INFO(weights, TYPE_ARRAY(4, TYPE_INFO(SMeshBoneMapping_uint8::Weight))) -STRUCT_INFO_END(SMeshBoneMapping_uint8) diff --git a/Code/CryEngine/CryCommon/ILevelSystem.h b/Code/CryEngine/CryCommon/ILevelSystem.h deleted file mode 100644 index 949cf84c89..0000000000 --- a/Code/CryEngine/CryCommon/ILevelSystem.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Gathers level information. Loads a level. - - -#ifndef CRYINCLUDE_CRYACTION_ILEVELSYSTEM_H -#define CRYINCLUDE_CRYACTION_ILEVELSYSTEM_H -#pragma once - -#include <CrySizer.h> -#include <IXml.h> -#include <AzCore/Asset/AssetCommon.h> - -struct IConsoleCmdArgs; - -namespace AZ::IO -{ - struct IArchive; -} - -// [LYN-2376] Remove once legacy slice support is removed -struct ILevelInfo -{ - virtual ~ILevelInfo() = default; - - virtual const char* GetName() const = 0; - virtual const char* GetPath() const = 0; - virtual const char* GetAssetName() const = 0; -}; - - -/*! - * Extend this class and call ILevelSystem::AddListener() to receive level system related events. - */ -struct ILevelSystemListener -{ - virtual ~ILevelSystemListener() = default; - //! Called when loading a level fails due to it not being found. - virtual void OnLevelNotFound([[maybe_unused]] const char* levelName) {} - //! Called after ILevelSystem::PrepareNextLevel() completes. - virtual void OnPrepareNextLevel([[maybe_unused]] const char* levelName) {} - //! Called after ILevelSystem::OnLoadingStart() completes, before the level actually starts loading. - virtual void OnLoadingStart([[maybe_unused]] const char* levelName) {} - //! Called after the level finished - virtual void OnLoadingComplete([[maybe_unused]] const char* levelName) {} - //! Called when there's an error loading a level, with the level info and a description of the error. - virtual void OnLoadingError([[maybe_unused]] const char* levelName, [[maybe_unused]] const char* error) {} - //! Called whenever the loading status of a level changes. progressAmount goes from 0->100. - virtual void OnLoadingProgress([[maybe_unused]] const char* levelName, [[maybe_unused]] int progressAmount) {} - //! Called after a level is unloaded, before the data is freed. - virtual void OnUnloadComplete([[maybe_unused]] const char* levelName) {} - - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { } -}; - -struct ILevelSystem -{ - virtual ~ILevelSystem() = default; - - virtual void Release() = 0; - - virtual void AddListener(ILevelSystemListener* pListener) = 0; - virtual void RemoveListener(ILevelSystemListener* pListener) = 0; - - virtual bool LoadLevel(const char* levelName) = 0; - virtual void UnloadLevel() = 0; - virtual bool IsLevelLoaded() = 0; - virtual const char* GetCurrentLevelName() const = 0; - - // If the level load failed then we need to have a different shutdown procedure vs when a level is naturally unloaded - virtual void SetLevelLoadFailed(bool loadFailed) = 0; - virtual bool GetLevelLoadFailed() = 0; - - virtual AZ::Data::AssetType GetLevelAssetType() const = 0; - - static const char* GetLevelsDirectoryName() - { - return LevelsDirectoryName; - } - - // [LYN-2376] Deprecated methods, to be removed once slices are removed: - virtual void Rescan(const char* levelsFolder) = 0; - virtual int GetLevelCount() = 0; - virtual ILevelInfo* GetLevelInfo(int level) = 0; - virtual ILevelInfo* GetLevelInfo(const char* levelName) = 0; - -protected: - - static constexpr const char* LevelsDirectoryName = "levels"; -}; - -#endif // CRYINCLUDE_CRYACTION_ILEVELSYSTEM_H diff --git a/Code/CryEngine/CryCommon/ILocalizationManager.h b/Code/CryEngine/CryCommon/ILocalizationManager.h deleted file mode 100644 index 207baeee7d..0000000000 --- a/Code/CryEngine/CryCommon/ILocalizationManager.h +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_ILOCALIZATIONMANAGER_H -#define CRYINCLUDE_CRYCOMMON_ILOCALIZATIONMANAGER_H -#pragma once - -#include "LocalizationManagerBus.h" -//#include <platform.h> // Needed for LARGE_INTEGER (for consoles). - -//////////////////////////////////////////////////////////////////////////////////////////////// -// Forward declarations -//////////////////////////////////////////////////////////////////////////////////////////////// - -class XmlNodeRef; - -////////////////////////////////////////////////////////////////////////// -// Localized strings manager interface. -////////////////////////////////////////////////////////////////////////// - -// Localization Info structure -struct SLocalizedInfoGame -{ - SLocalizedInfoGame () - : szCharacterName(NULL) - , bUseSubtitle(false) - { - } - - const char* szCharacterName; - string sUtf8TranslatedText; - - bool bUseSubtitle; -}; - -struct SLocalizedAdvancesSoundEntry -{ - string sName; - float fValue; - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(sName); - } -}; - -// Localization Sound Info structure, containing sound related parameters. -struct SLocalizedSoundInfoGame - : public SLocalizedInfoGame -{ - SLocalizedSoundInfoGame() - : sSoundEvent(NULL) - , fVolume(0.f) - , fRadioRatio (0.f) - , bIsDirectRadio(false) - , bIsIntercepted(false) - , nNumSoundMoods(0) - , pSoundMoods (NULL) - , nNumEventParameters(0) - , pEventParameters(NULL) - { - } - - const char* sSoundEvent; - float fVolume; - float fRadioRatio; - bool bIsDirectRadio; - bool bIsIntercepted; - - // SoundMoods. - int nNumSoundMoods; - SLocalizedAdvancesSoundEntry* pSoundMoods; - - // EventParameters. - int nNumEventParameters; - SLocalizedAdvancesSoundEntry* pEventParameters; -}; - -// Localization Sound Info structure, containing sound related parameters. -struct SLocalizedInfoEditor - : public SLocalizedInfoGame -{ - SLocalizedInfoEditor() - : sKey(NULL) - , sOriginalCharacterName(NULL) - , sOriginalActorLine(NULL) - , sUtf8TranslatedActorLine(NULL) - , nRow(0) - { - } - - const char* sKey; - const char* sOriginalCharacterName; - const char* sOriginalActorLine; - const char* sUtf8TranslatedActorLine; - unsigned int nRow; -}; - -// Summary: -// Interface to the Localization Manager. -struct ILocalizationManager - : public LocalizationManagerRequestBus::Handler -{ - //Platform independent language IDs. These are used to map the platform specific language codes to localization pakfiles - //Please ensure that each entry in this enum has a corresponding entry in the PLATFORM_INDEPENDENT_LANGUAGE_NAMES array which is defined in LocalizedStringManager.cpp currently. - enum EPlatformIndependentLanguageID - { - ePILID_English_US, - ePILID_English_GB, - ePILID_German_DE, - ePILID_Russian_RU, - ePILID_Polish_PL, - ePILID_Turkish_TR, - ePILID_Spanish_ES, - ePILID_Spanish_MX, - ePILID_French_FR, - ePILID_French_CA, - ePILID_Italian_IT, - ePILID_Portugese_PT, - ePILID_Portugese_BR, - ePILID_Japanese_JP, - ePILID_Korean_KR, - ePILID_Chinese_T, - ePILID_Chinese_S, - ePILID_Dutch_NL, - ePILID_Finnish_FI, - ePILID_Swedish_SE, - ePILID_Czech_CZ, - ePILID_Norwegian_NO, - ePILID_Arabic_SA, - ePILID_Danish_DK, - ePILID_MAX_OR_INVALID, //Not a language, denotes the maximum number of languages or an unknown language - }; - - typedef uint32 TLocalizationBitfield; - - // <interfuscator:shuffle> - virtual ~ILocalizationManager(){} - virtual const char* LangNameFromPILID(const ILocalizationManager::EPlatformIndependentLanguageID id) = 0; - virtual ILocalizationManager::EPlatformIndependentLanguageID PILIDFromLangName(AZStd::string langName) = 0; - virtual ILocalizationManager::EPlatformIndependentLanguageID GetSystemLanguage() { return ILocalizationManager::EPlatformIndependentLanguageID::ePILID_English_US; } - virtual ILocalizationManager::TLocalizationBitfield MaskSystemLanguagesFromSupportedLocalizations(const ILocalizationManager::TLocalizationBitfield systemLanguages) = 0; - virtual ILocalizationManager::TLocalizationBitfield IsLanguageSupported(const ILocalizationManager::EPlatformIndependentLanguageID id) = 0; - virtual bool SetLanguage([[maybe_unused]] const char* sLanguage) override { return false; } - virtual const char* GetLanguage() override { return nullptr; } - - virtual int GetLocalizationFormat() const { return -1; } - virtual AZStd::string GetLocalizedSubtitleFilePath([[maybe_unused]] const AZStd::string& localVideoPath, [[maybe_unused]] const AZStd::string& subtitleFileExtension) const { return ""; } - virtual AZStd::string GetLocalizedLocXMLFilePath([[maybe_unused]] const AZStd::string& localXmlPath) const { return ""; } - // load the descriptor file with tag information - virtual bool InitLocalizationData(const char* sFileName, bool bReload = false) = 0; - // request to load loca data by tag. Actual loading will happen during next level load begin event. - virtual bool RequestLoadLocalizationDataByTag(const char* sTag) = 0; - // direct load of loca data by tag - virtual bool LoadLocalizationDataByTag(const char* sTag, bool bReload = false) = 0; - virtual bool ReleaseLocalizationDataByTag(const char* sTag) = 0; - - virtual bool LoadAllLocalizationData(bool bReload = false) = 0; - virtual bool LoadExcelXmlSpreadsheet([[maybe_unused]] const char* sFileName, [[maybe_unused]] bool bReload = false) override { return false; } - virtual void ReloadData() override {}; - - // Summary: - // Free localization data. - virtual void FreeData() = 0; - - // Summary: - // Translate a string into the currently selected language. - // Description: - // Processes the input string and translates all labels contained into the currently selected language. - // Parameters: - // sString - String to be translated. - // outLocalizedString - Translated version of the string. - // bEnglish - if true, translates the string into the always present English language. - // Returns: - // true if localization was successful, false otherwise - virtual bool LocalizeString_ch([[maybe_unused]] const char* sString, [[maybe_unused]] string& outLocalizedString, [[maybe_unused]] bool bEnglish = false) override { return false; } - - // Summary: - // Same as LocalizeString( const char* sString, string& outLocalizedString, bool bEnglish=false ) - // but at the moment this is faster. - virtual bool LocalizeString_s([[maybe_unused]] const string& sString, [[maybe_unused]] string& outLocalizedString, [[maybe_unused]] bool bEnglish = false) override { return false; } - - // Summary: - virtual void LocalizeAndSubstituteInternal([[maybe_unused]] AZStd::string& locString, [[maybe_unused]] const AZStd::vector<AZStd::string>& keys, [[maybe_unused]] const AZStd::vector<AZStd::string>& values) override {} - // Return the localized version corresponding to a label. - // Description: - // A label has to start with '@' sign. - // Parameters: - // sLabel - Label to be translated, must start with '@' sign. - // outLocalizedString - Localized version of the label. - // bEnglish - if true, returns the always present English version of the label. - // Returns: - // True if localization was successful, false otherwise. - virtual bool LocalizeLabel([[maybe_unused]] const char* sLabel, [[maybe_unused]] string& outLocalizedString, [[maybe_unused]] bool bEnglish = false) override { return false; } - virtual bool IsLocalizedInfoFound([[maybe_unused]] const char* sKey) { return false; } - - // Summary: - // Get localization info structure corresponding to a key (key=label without the '@' sign). - // Parameters: - // sKey - Key to be looked up. Key = Label without '@' sign. - // outGameInfo - Reference to localization info structure to be filled in. - // Returns: - // True if info for key was found, false otherwise. - virtual bool GetLocalizedInfoByKey(const char* sKey, SLocalizedInfoGame& outGameInfo) = 0; - - // Summary: - // Get the sound localization info structure corresponding to a key. - // Parameters: - // sKey - Key to be looked up. Key = Label without '@' sign. - // outSoundInfo - reference to sound info structure to be filled in - // pSoundMoods requires nNumSoundMoods-times allocated memory - // on return nNumSoundMoods will hold how many SoundsMood entries are needed - // pEventParameters requires nNumEventParameters-times allocated memory - // on return nNumEventParameters will hold how many EventParameter entries are needed - // Passing 0 in the Num fields will make the query ignore checking for allocated memory - // Returns: - // True if successful, false otherwise (key not found, or not enough memory provided to write additional info). - virtual bool GetLocalizedInfoByKey(const char* sKey, SLocalizedSoundInfoGame* pOutSoundInfo) = 0; - - // Summary: - // Return number of localization entries. - virtual int GetLocalizedStringCount() override { return -1; } - - // Summary: - // Get the localization info structure at index nIndex. - // Parameters: - // nIndex - Index. - // outEditorInfo - Reference to localization info structure to be filled in. - // Returns: - // True if successful, false otherwise (out of bounds). - virtual bool GetLocalizedInfoByIndex(int nIndex, SLocalizedInfoEditor& outEditorInfo) = 0; - - // Summary: - // Get the localization info structure at index nIndex. - // Parameters: - // nIndex - Index. - // outGameInfo - Reference to localization info structure to be filled in. - // Returns: - // True if successful, false otherwise (out of bounds). - virtual bool GetLocalizedInfoByIndex(int nIndex, SLocalizedInfoGame& outGameInfo) = 0; - - // Summary: - // Get the english localization info structure corresponding to a key. - // Parameters: - // sKey - Key to be looked up. Key = Label without '@' sign. - // sLocalizedString - Corresponding english language string. - // Returns: - // True if successful, false otherwise (key not found). - virtual bool GetEnglishString([[maybe_unused]] const char* sKey, [[maybe_unused]] string& sLocalizedString) override { return false; } - - // Summary: - // Get Subtitle for Key or Label . - // Parameters: - // sKeyOrLabel - Key or Label to be used for subtitle lookup. Key = Label without '@' sign. - // outSubtitle - Subtitle (untouched if Key/Label not found). - // bForceSubtitle - If true, get subtitle (sLocalized or sEnglish) even if not specified in Data file. - // Returns: - // True if subtitle found (and outSubtitle filled in), false otherwise. - virtual bool GetSubtitle([[maybe_unused]] const char* sKeyOrLabel, [[maybe_unused]] string& outSubtitle, [[maybe_unused]] bool bForceSubtitle = false) override { return false; } - - // Description: - // These methods format outString depending on sString with ordered arguments - // FormatStringMessage(outString, "This is %2 and this is %1", "second", "first"); - // Arguments: - // outString - This is first and this is second. - virtual void FormatStringMessage_List([[maybe_unused]] string& outString, [[maybe_unused]] const string& sString, [[maybe_unused]] const char** sParams, [[maybe_unused]] int nParams) override {} - virtual void FormatStringMessage([[maybe_unused]] string& outString, [[maybe_unused]] const string& sString, [[maybe_unused]] const char* param1, [[maybe_unused]] const char* param2 = 0, [[maybe_unused]] const char* param3 = 0, [[maybe_unused]] const char* param4 = 0) override {} - - virtual void LocalizeTime([[maybe_unused]] time_t t, [[maybe_unused]] bool bMakeLocalTime, [[maybe_unused]] bool bShowSeconds, [[maybe_unused]] string& outTimeString) override {} - virtual void LocalizeDate([[maybe_unused]] time_t t, [[maybe_unused]] bool bMakeLocalTime, [[maybe_unused]] bool bShort, [[maybe_unused]] bool bIncludeWeekday, [[maybe_unused]] string& outDateString) override {} - virtual void LocalizeDuration([[maybe_unused]] int seconds, [[maybe_unused]] string& outDurationString) override {} - virtual void LocalizeNumber([[maybe_unused]] int number, [[maybe_unused]] string& outNumberString) override {} - virtual void LocalizeNumber_Decimal([[maybe_unused]] float number, [[maybe_unused]] int decimals, [[maybe_unused]] string& outNumberString) override {} - - // Summary: - // Returns true if the project has localization configured for use, false otherwise. - virtual bool ProjectUsesLocalization() const override { return false; } - // </interfuscator:shuffle> - - static ILINE TLocalizationBitfield LocalizationBitfieldFromPILID(EPlatformIndependentLanguageID pilid) - { - assert(pilid >= 0 && pilid < ePILID_MAX_OR_INVALID); - return (1 << pilid); - } -}; - -// Summary: -// Simple bus that notifies listeners that the language (g_language) has changed. - - - - -#endif // CRYINCLUDE_CRYCOMMON_ILOCALIZATIONMANAGER_H diff --git a/Code/CryEngine/CryCommon/ILog.h b/Code/CryEngine/CryCommon/ILog.h deleted file mode 100644 index ad1c84f3de..0000000000 --- a/Code/CryEngine/CryCommon/ILog.h +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// In Mac, including ILog without including platform.h first fails because platform.h -// includes CryThread.h which includes CryThread_pthreads.h which uses ILog. -// So plaform.h needs the contents of ILog.h. -// By including platform.h outside of the guard, we give platform.h the right include order -#include <platform.h> - -#ifndef CRYINCLUDE_CRYCOMMON_ILOG_H -#define CRYINCLUDE_CRYCOMMON_ILOG_H -#pragma once - -#include <IMiniLog.h> // <> required for Interfuscator - -// enable this define to support log scopes to provide more context information for log lines -// this code is disable by default due it's runtime cost -//#define SUPPORT_LOG_IDENTER - -// forward declarations -class ICrySizer; - -// Summary: -// Callback interface to the ILog. -struct ILogCallback -{ - // <interfuscator:shuffle> - virtual ~ILogCallback() {} - //OnWrite will always be called even if verbosity settings cause OnWriteToConsole and OnWriteToFile to not be called. - virtual void OnWrite(const char* sText, IMiniLog::ELogType type) = 0; - virtual void OnWriteToConsole(const char* sText, bool bNewLine) = 0; - virtual void OnWriteToFile(const char* sText, bool bNewLine) = 0; - // </interfuscator:shuffle> -}; - -// Summary: -// Interface for logging operations based on IMiniLog. -// Notes: -// Logging in CryEngine should be done using the following global functions: -// CryLog (eMessage) -// CryLogAlways (eAlways) -// CryError (eError) -// CryWarning (eWarning) -// CryComment (eComment) -// ILog gives you more control on logging operations. -// See also: -// IMiniLog, CryLog, CryLogAlways, CryError, CryWarning -struct ILog - : public IMiniLog -{ - // <interfuscator:shuffle> - virtual void Release() = 0; - - // Summary: - // Sets the file used to log to disk. - // if you don't specify the full path it will be assumed relative to the 'log folder' - // dobackups controls whether or not it will backup old logs when creating new ones. - virtual bool SetFileName(const char* fileNameOrFullPath, bool doBackups) = 0; - - // Summary: - // Gets the filename used to log to disk. - virtual const char* GetFileName() = 0; - - // Summary: - // Gets the filename where the current log backup was copied to on disk - virtual const char* GetBackupFileName() = 0; - - //all the following functions will be removed are here just to be able to compile the project --------------------------- - - // Summary: - // Logs the text both to file and console. - virtual void Log(const char* szCommand, ...) PRINTF_PARAMS(2, 3) = 0; - - virtual void LogAlways(const char* szCommand, ...) PRINTF_PARAMS(2, 3) = 0; - - virtual void LogWarning(const char* szCommand, ...) PRINTF_PARAMS(2, 3) = 0; - - virtual void LogError(const char* szCommand, ...) PRINTF_PARAMS(2, 3) = 0; - - // Summary: - // Logs the text both to the end of file and console. - virtual void LogPlus(const char* command, ...) PRINTF_PARAMS(2, 3) = 0; - - // Summary: - // Logs to the file specified in SetFileName. - // See also: - // SetFileName - virtual void LogToFile(const char* command, ...) PRINTF_PARAMS(2, 3) = 0; - - // - virtual void LogToFilePlus(const char* command, ...) PRINTF_PARAMS(2, 3) = 0; - - // Summary: - // Logs to console only. - virtual void LogToConsole(const char* command, ...) PRINTF_PARAMS(2, 3) = 0; - - // - virtual void LogToConsolePlus(const char* command, ...) PRINTF_PARAMS(2, 3) = 0; - - // - virtual void UpdateLoadingScreen(const char* command, ...) PRINTF_PARAMS(2, 3) = 0; - - // - virtual void RegisterConsoleVariables() {} - - // - virtual void UnregisterConsoleVariables() {} - - // Notes: - // Full logging (to console and file) can be enabled with verbosity 4. - // In the console 'log_Verbosity 4' command can be used. - virtual void SetVerbosity(int verbosity) = 0; - - virtual int GetVerbosityLevel() = 0; - - virtual void AddCallback(ILogCallback* pCallback) = 0; - virtual void RemoveCallback(ILogCallback* pCallback) = 0; - - // Notes: - // The function called every frame by system. - virtual void Update() = 0; - - virtual const char* GetModuleFilter() = 0; - - // Notes: - // Collect memory statistics in CrySizer - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - - // Asset scope strings help to figure out asset dependencies in case of asset loading errors. - // Should not be used directly, only by using define CRY_DEFINE_ASSET_SCOPE - // @see CRY_DEFINE_ASSET_SCOPE - virtual void PushAssetScopeName([[maybe_unused]] const char* sAssetType, [[maybe_unused]] const char* sName) {}; - virtual void PopAssetScopeName() {}; - virtual const char* GetAssetScopeString() { return ""; }; - // </interfuscator:shuffle> - -#if defined(SUPPORT_LOG_IDENTER) - virtual void Indent(class CLogIndenter* indenter) = 0; - virtual void Unindent(class CLogIndenter* indenter) = 0; -#endif - -#if !defined(RESOURCE_COMPILER) - virtual void FlushAndClose() = 0; -#endif -}; - -#if !defined(SUPPORT_LOG_IDENTER) -#define INDENT_LOG_DURING_SCOPE(...) (void)(0) -#define CRY_DEFINE_ASSET_SCOPE(sAssetType, sAssetName) (void)(0) -#else -class CLogIndenter -{ -public: - CLogIndenter(ILog* log) - : m_log(log) - , m_enabled(false) - , m_nextIndenter(NULL) - , m_needToPrintSectionText(false) - { - } - - void Enable(bool enable = true, const char* sectionTextFormat = NULL, ...) - { - va_list args; - va_start (args, sectionTextFormat); - - enable &= (m_log != NULL); - - if (enable != m_enabled) - { - if (sectionTextFormat && enable) - { - char buffer[1024]; - - vsnprintf(buffer, sizeof(buffer), sectionTextFormat, args); - buffer[sizeof(buffer) - 1] = '\0'; - - m_sectionText = buffer; - m_needToPrintSectionText = true; - } - else - { - m_sectionText = ""; - m_needToPrintSectionText = m_nextIndenter ? m_nextIndenter->m_needToPrintSectionText : false; - } - - assert(m_log); - - if (enable) - { - m_log->Indent(this); - } - else - { - m_log->Unindent(this); - } - m_enabled = enable; - } - - va_end (args); - } - - CLogIndenter* GetNextIndenter() - { - return m_nextIndenter; - } - - void SetNextIndenter(CLogIndenter* indenter) - { - m_nextIndenter = indenter; - } - - void DisplaySectionText() - { - if (m_needToPrintSectionText) - { - m_needToPrintSectionText = false; - string sectionText = m_sectionText; - Enable(false); - - if (m_nextIndenter) - { - m_nextIndenter->DisplaySectionText(); - } - - if (!sectionText.empty()) - { - assert (m_log); - m_log->Log ("%s", sectionText.c_str()); - } - Enable(true); - } - } - - ~CLogIndenter() - { - Enable(false); - } - -private: - bool m_enabled; - bool m_needToPrintSectionText; - ILog* m_log; - CLogIndenter* m_nextIndenter; - string m_sectionText; -}; - -class CLogAssetScopeName -{ - ILog* m_pLog; -public: - CLogAssetScopeName(ILog* pLog, const char* sAssetType, const char* sAssetName) - : m_pLog(pLog) { pLog->PushAssetScopeName(sAssetType, sAssetName); } - ~CLogAssetScopeName() { m_pLog->PopAssetScopeName(); } -}; - -#define ILOG_CONCAT_IMPL(x, y) x##y -#define ILOG_CONCAT_MACRO(x, y) ILOG_CONCAT_IMPL(x, y) -#define INDENT_LOG_DURING_SCOPE(...) CLogIndenter ILOG_CONCAT_MACRO(indentMe, __LINE__) ((CryGetCurrentThreadId() == gEnv->mMainThreadId) ? gEnv->pLog : NULL); ILOG_CONCAT_MACRO(indentMe, __LINE__).Enable(__VA_ARGS__) - -#define CRY_DEFINE_ASSET_SCOPE(sAssetType, sAssetName) CLogAssetScopeName __asset_scope_name(gEnv->pLog, sAssetType, sAssetName); -#endif - - -#endif // CRYINCLUDE_CRYCOMMON_ILOG_H - - - diff --git a/Code/CryEngine/CryCommon/IMNM.h b/Code/CryEngine/CryCommon/IMNM.h deleted file mode 100644 index 6aace5024c..0000000000 --- a/Code/CryEngine/CryCommon/IMNM.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef __IMNM_H__ -#define __IMNM_H__ - -#pragma once - -namespace MNM -{ - namespace Constants - { - enum Edges - { - InvalidEdgeIndex = ~0u - }; - - enum TileIdConstants - { - InvalidTileID = 0, - }; - enum TriangleIDConstants - { - InvalidTriangleID = 0, - }; - - enum EStaticIsland - { - eStaticIsland_InvalidIslandID = 0, - eStaticIsland_FirstValidIslandID = 1, - }; - enum EGlobalIsland - { - eGlobalIsland_InvalidIslandID = 0, - }; - - enum EOffMeshLink - { - eOffMeshLinks_InvalidOffMeshLinkID = 0, - }; - } - - // ------------------------------------------------------------------------------------------ - // Basic types used in the MNM namespace - - typedef uint32 TileID; - typedef uint32 TriangleID; - typedef uint32 OffMeshLinkID; - - // StaticIslandIDs identify triangles that are statically connected inside a mesh - // and that are reachable without the use of any off mesh links. - typedef uint32 StaticIslandID; - - // GlobalIslandIDs define IDs able to code and connect islands between meshes. - struct GlobalIslandID - { - GlobalIslandID(const uint64 defaultValue = MNM::Constants::eGlobalIsland_InvalidIslandID) - : id(defaultValue) - { - STATIC_ASSERT(sizeof(StaticIslandID) <= 4, "The maximum supported size for StaticIslandIDs is 4 bytes."); - } - - GlobalIslandID(const uint32 navigationMeshID, const MNM::StaticIslandID islandID) - { - id = ((uint64)navigationMeshID << 32) | islandID; - } - - GlobalIslandID operator=(const GlobalIslandID other) - { - id = other.id; - return *this; - } - - inline bool operator==(const GlobalIslandID& rhs) const - { - return id == rhs.id; - } - - inline bool operator<(const GlobalIslandID& rhs) const - { - return id < rhs.id; - } - - MNM::StaticIslandID GetStaticIslandID() const - { - return (MNM::StaticIslandID) (id & ((uint64)1 << 32) - 1); - } - - uint32 GetNavigationMeshIDAsUint32() const - { - return static_cast<uint32>(id >> 32); - } - - uint64 id; - }; -} - -#endif // __IMNM_H__ diff --git a/Code/CryEngine/CryCommon/IMaterial.h b/Code/CryEngine/CryCommon/IMaterial.h deleted file mode 100644 index 02153cd031..0000000000 --- a/Code/CryEngine/CryCommon/IMaterial.h +++ /dev/null @@ -1,579 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : IMaterial interface declaration. - - -#ifndef CRYINCLUDE_CRYCOMMON_IMATERIAL_H -#define CRYINCLUDE_CRYCOMMON_IMATERIAL_H -#pragma once - -struct ISurfaceType; -struct ISurfaceTypeManager; -class ICrySizer; - -enum EEfResTextures : int; // Need to specify a fixed size for the forward declare to work on clang -struct IRenderShaderResources; -struct SEfTexModificator; -struct SInputShaderResources; - -struct SShaderItem; -struct SShaderParam; -struct IShader; -struct IShaderPublicParams; -struct IMaterial; -struct IMaterialManager; -struct CMaterialCGF; -struct CRenderChunk; -struct IRenderMesh; - -#include <Tarray.h> -#include <IXml.h> -#include <smartptr.h> -#include <AzCore/EBus/EBus.h> - -#ifdef MAX_SUB_MATERIALS -// This checks that the values are in sync in the different files. -COMPILE_TIME_ASSERT(MAX_SUB_MATERIALS == 128); -#else -#define MAX_SUB_MATERIALS 128 -#endif - -// Special names for materials. -#define MTL_SPECIAL_NAME_COLLISION_PROXY "collision_proxy" -#define MTL_SPECIAL_NAME_COLLISION_PROXY_VEHICLE "nomaterial_vehicle" -#define MTL_SPECIAL_NAME_RAYCAST_PROXY "raycast_proxy" - -namespace AZ -{ - class MaterialNotificationEvents : public AZ::EBusTraits - { - public: - virtual ~MaterialNotificationEvents() {} - - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - static const bool EnableEventQueue = true; - using EventQueueMutexType = AZStd::mutex; - - - virtual void OnShaderLoaded([[maybe_unused]] IShader* shader) {} - }; - using MaterialNotificationEventBus = AZ::EBus<MaterialNotificationEvents>; -} - -enum -{ - MAX_STREAM_PREDICTION_ZONES = 2 -}; - -////////////////////////////////////////////////////////////////////////// -// Description: -// IMaterial is an interface to the material object, SShaderItem host which is a combination of IShader and SShaderInputResources. -// Material bind together rendering algorithm (Shader) and resources needed to render this shader, textures, colors, etc... -// All materials except for pure sub material childs have a unique name which directly represent .mtl file on disk. -// Ex: "Materials/Fire/Burn" -// Materials can be created by Sandbox MaterialEditor. -////////////////////////////////////////////////////////////////////////// -enum EMaterialFlags -{ - MTL_FLAG_WIRE = 0x0001, // Use wire frame rendering for this material. - MTL_FLAG_2SIDED = 0x0002, // Use 2 Sided rendering for this material. - MTL_FLAG_ADDITIVE = 0x0004, // Use Additive blending for this material. - //MTL_FLAG_DETAIL_DECAL = 0x0008, // UNUSED RESERVED FOR LEGACY REASONS - MTL_FLAG_LIGHTING = 0x0010, // Should lighting be applied on this material. - MTL_FLAG_NOSHADOW = 0x0020, // Material do not cast shadows. - MTL_FLAG_ALWAYS_USED = 0x0040, // When set forces material to be export even if not explicitly used. - MTL_FLAG_PURE_CHILD = 0x0080, // Not shared sub material, sub material unique to his parent multi material. - MTL_FLAG_MULTI_SUBMTL = 0x0100, // This material is a multi sub material. - MTL_FLAG_NOPHYSICALIZE = 0x0200, // Should not physicalize this material. - MTL_FLAG_NODRAW = 0x0400, // Do not render this material. - MTL_FLAG_NOPREVIEW = 0x0800, // Cannot preview the material. - MTL_FLAG_NOTINSTANCED = 0x1000, // Do not instantiate this material. - MTL_FLAG_COLLISION_PROXY = 0x2000, // This material is the collision proxy. - MTL_FLAG_SCATTER = 0x4000, // Use scattering for this material - MTL_FLAG_REQUIRE_FORWARD_RENDERING = 0x8000, // This material has to be rendered in forward rendering passes (alpha/additive blended) - MTL_FLAG_NON_REMOVABLE = 0x10000, // Material with this flag once created are never removed from material manager (Used for decal materials, this flag should not be saved). - MTL_FLAG_HIDEONBREAK = 0x20000, // Non-physicalized subsets with such materials will be removed after the object breaks - MTL_FLAG_UIMATERIAL = 0x40000, // Used for UI in Editor. Don't need show it DB. - MTL_64BIT_SHADERGENMASK = 0x80000, // ShaderGen mask is remapped - MTL_FLAG_RAYCAST_PROXY = 0x100000, - MTL_FLAG_REQUIRE_NEAREST_CUBEMAP = 0x200000, // materials with alpha blending requires special processing for shadows - MTL_FLAG_CONSOLE_MAT = 0x400000, - MTL_FLAG_DELETE_PENDING = 0x800000, // Internal use only - MTL_FLAG_BLEND_TERRAIN = 0x1000000, - MTL_FLAG_IS_TERRAIN = 0x2000000,// indication to the loader - Terrain type - MTL_FLAG_IS_SKY = 0x4000000,// indication to the loader - Sky type - MTL_FLAG_FOG_VOLUME_SHADING_QUALITY_HIGH= 0x8000000 // high vertex shading quality behaves more accurately with fog volumes. -}; - -#define MTL_FLAGS_SAVE_MASK (MTL_FLAG_WIRE | MTL_FLAG_2SIDED | MTL_FLAG_ADDITIVE | MTL_FLAG_LIGHTING | \ - MTL_FLAG_NOSHADOW | MTL_FLAG_MULTI_SUBMTL | MTL_FLAG_SCATTER | MTL_FLAG_REQUIRE_FORWARD_RENDERING | MTL_FLAG_FOG_VOLUME_SHADING_QUALITY_HIGH | MTL_FLAG_HIDEONBREAK | MTL_FLAG_UIMATERIAL | MTL_64BIT_SHADERGENMASK | MTL_FLAG_REQUIRE_NEAREST_CUBEMAP | MTL_FLAG_CONSOLE_MAT | MTL_FLAG_BLEND_TERRAIN) - -// Post effects flags -enum EPostEffectFlags -{ - POST_EFFECT_GHOST = 0x1, - POST_EFFECT_HOLOGRAM = 0x2, - - POST_EFFECT_MASK = POST_EFFECT_GHOST | POST_EFFECT_HOLOGRAM -}; - -// Bit offsets for shader layer flags -enum EMaterialLayerFlags -{ - // Active layers flags - MTL_LAYER_FROZEN = 0x0001, - MTL_LAYER_WET = 0x0002, - MTL_LAYER_DYNAMICFROZEN = 0x0008, - - // Usage flags - MTL_LAYER_USAGE_NODRAW = 0x0001, // Layer is disabled - MTL_LAYER_USAGE_REPLACEBASE = 0x0002, // Replace base pass rendering with layer - optimization - MTL_LAYER_USAGE_FADEOUT = 0x0004, // Layer doesn't render but still causes parent to fade out - - // Blend offsets - MTL_LAYER_BLEND_FROZEN = 0xff000000, - MTL_LAYER_BLEND_WET = 0x00fe0000, - MTL_LAYER_BLEND_DYNAMICFROZEN = 0x000000ff, - - MTL_LAYER_FROZEN_MASK = 0xff, - MTL_LAYER_WET_MASK = 0xfe, // bit stolen - MTL_LAYER_DYNAMICFROZEN_MASK = 0xff, - - MTL_LAYER_BLEND_MASK = (MTL_LAYER_BLEND_FROZEN | MTL_LAYER_BLEND_WET | MTL_LAYER_BLEND_DYNAMICFROZEN), - - // Slot count - MTL_LAYER_MAX_SLOTS = 3 -}; - -// copy flags -enum EMaterialCopyFlags -{ - // copy flags - MTL_COPY_DEFAULT = 0, - MTL_COPY_NAME = BIT(0), - MTL_COPY_TEXTURES = BIT(1), -}; - -struct IMaterialHelpers -{ - virtual ~IMaterialHelpers() {} - - ////////////////////////////////////////////////////////////////////////// - virtual EEfResTextures FindTexSlot(const char* texName) const = 0; - virtual const char* FindTexName(EEfResTextures texSlot) const = 0; - virtual const char* LookupTexName(EEfResTextures texSlot) const = 0; - virtual const char* LookupTexDesc(EEfResTextures texSlot) const = 0; - virtual const char* LookupTexEnum(EEfResTextures texSlot) const = 0; - virtual const char* LookupTexSuffix(EEfResTextures texSlot) const = 0; - virtual bool IsAdjustableTexSlot(EEfResTextures texSlot) const = 0; - - ////////////////////////////////////////////////////////////////////////// - virtual bool SetGetMaterialParamFloat(IRenderShaderResources& pShaderResources, const char* sParamName, float& v, bool bGet) const = 0; - virtual bool SetGetMaterialParamVec3(IRenderShaderResources& pShaderResources, const char* sParamName, Vec3& v, bool bGet) const = 0; - - ////////////////////////////////////////////////////////////////////////// - virtual void SetTexModFromXml(SEfTexModificator& pShaderResources, const XmlNodeRef& node) const = 0; - virtual void SetXmlFromTexMod(const SEfTexModificator& pShaderResources, XmlNodeRef& node) const = 0; - - ////////////////////////////////////////////////////////////////////////// - virtual void SetTexturesFromXml(SInputShaderResources& pShaderResources, const XmlNodeRef& node) const = 0; - virtual void SetXmlFromTextures( SInputShaderResources& pShaderResources, XmlNodeRef& node) const = 0; - - ////////////////////////////////////////////////////////////////////////// - virtual void SetVertexDeformFromXml(SInputShaderResources& pShaderResources, const XmlNodeRef& node) const = 0; - virtual void SetXmlFromVertexDeform(const SInputShaderResources& pShaderResources, XmlNodeRef& node) const = 0; - - ////////////////////////////////////////////////////////////////////////// - virtual void SetLightingFromXml(SInputShaderResources& pShaderResources, const XmlNodeRef& node) const = 0; - virtual void SetXmlFromLighting(const SInputShaderResources& pShaderResources, XmlNodeRef& node) const = 0; - - ////////////////////////////////////////////////////////////////////////// - virtual void SetShaderParamsFromXml(SInputShaderResources& pShaderResources, const XmlNodeRef& node) const = 0; - virtual void SetXmlFromShaderParams(const SInputShaderResources& pShaderResources, XmlNodeRef& node) const = 0; - - ////////////////////////////////////////////////////////////////////////// - virtual void MigrateXmlLegacyData(SInputShaderResources& pShaderResources, const XmlNodeRef& node) const = 0; -}; - -////////////////////////////////////////////////////////////////////////////////////// -// Description: -// IMaterialLayer is group of material layer properties. -// Each layer is composed of shader item, specific layer textures, lod info, etc -struct IMaterialLayer -{ - // <interfuscator:shuffle> - virtual ~IMaterialLayer(){} - // Reference counting - virtual void AddRef() = 0; - virtual void Release() = 0; - - // Description: - // - Enable/disable layer usage - virtual void Enable(bool bEnable = true) = 0; - // Description: - // - Check if layer enabled - virtual bool IsEnabled() const = 0; - // Description: - // - Enable/disable fade out - virtual void FadeOut(bool bFadeOut = true) = 0; - // Description: - // - Check if layer fades out - virtual bool DoesFadeOut() const = 0; - // Description: - // - Set shader item - virtual void SetShaderItem(const _smart_ptr<IMaterial> pParentMtl, const SShaderItem& pShaderItem) = 0; - // Description: - // - Return shader item - virtual const SShaderItem& GetShaderItem() const = 0; - virtual SShaderItem& GetShaderItem() = 0; - // Description: - // - Set layer usage flags - virtual void SetFlags(uint8 nFlags) = 0; - // Description: - // - Get layer usage flags - virtual uint8 GetFlags() const = 0; - - // todo: layer specific textures support - // - // </interfuscator:shuffle> -}; - -struct IMaterial -{ - // TODO: Remove it! - //! default texture mapping - uint8 m_ucDefautMappingAxis; - float m_fDefautMappingScale; - - // <interfuscator:shuffle> - virtual ~IMaterial() {}; - - ////////////////////////////////////////////////////////////////////////// - // Reference counting. - ////////////////////////////////////////////////////////////////////////// - virtual void AddRef() = 0; - virtual void Release() = 0; - virtual int GetNumRefs() = 0; - - virtual IMaterialHelpers& GetMaterialHelpers() = 0; - virtual IMaterialManager* GetMaterialManager() = 0; - - ////////////////////////////////////////////////////////////////////////// - // material name - ////////////////////////////////////////////////////////////////////////// - //! Set material name, (Do not use this directly - virtual void SetName(const char* pName) = 0; - //! Returns material name. - virtual const char* GetName() const = 0; - - //! Set/get shader name. The shader name may include technique name so it could be deferent than GetShaderItem()->m_pShader->GetName(). - virtual void SetShaderName(const char* pName) = 0; - virtual const char* GetShaderName() const = 0; - - //! Material flags. - //! @see EMaterialFlags - virtual void SetFlags(int flags) = 0; - virtual int GetFlags() const = 0; - virtual void UpdateFlags() = 0; - - // Returns true if this is the default material. - virtual bool IsDefault() = 0; - - virtual int GetSurfaceTypeId() = 0; - - // Assign a different surface type to this material. - virtual void SetSurfaceType(const char* sSurfaceTypeName) = 0; - - virtual ISurfaceType* GetSurfaceType() = 0; - - // shader item - virtual void ReleaseCurrentShaderItem() = 0; - virtual void SetShaderItem(const SShaderItem& _ShaderItem) = 0; - // [Alexey] EF_LoadShaderItem return value with RefCount = 1, so if you'll use SetShaderItem after EF_LoadShaderItem use Assign function - virtual void AssignShaderItem(const SShaderItem& _ShaderItem) = 0; - virtual SShaderItem& GetShaderItem() = 0; - virtual const SShaderItem& GetShaderItem() const = 0; - - // Returns shader item for correct sub material or for single material. - // Even if this is not sub material or nSubMtlSlot is invalid it will return valid renderable shader item. - virtual SShaderItem& GetShaderItem(int nSubMtlSlot) = 0; - virtual const SShaderItem& GetShaderItem(int nSubMtlSlot) const = 0; - - // Returns true if streamed in - virtual bool IsStreamedIn(const int nMinPrecacheRoundIds[MAX_STREAM_PREDICTION_ZONES], IRenderMesh* pRenderMesh) const = 0; - - ////////////////////////////////////////////////////////////////////////// - // Sub materials access. - ////////////////////////////////////////////////////////////////////////// - //! Returns number of child sub materials holded by this material. - virtual void SetSubMtlCount(int numSubMtl) = 0; - //! Returns number of child sub materials holded by this material. - virtual int GetSubMtlCount() = 0; - //! Return sub material at specified index. - virtual _smart_ptr<IMaterial> GetSubMtl(int nSlot) = 0; - // Assign material to the sub mtl slot. - // Must first allocate slots using SetSubMtlCount. - virtual void SetSubMtl(int nSlot, _smart_ptr<IMaterial> pMtl) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Layers access. - ////////////////////////////////////////////////////////////////////////// - //! Returns number of layers in this material. - virtual void SetLayerCount(uint32 nCount) = 0; - //! Returns number of layers in this material. - virtual uint32 GetLayerCount() const = 0; - //! Set layer at slot id (### MUST ALOCATE SLOTS FIRST ### USING SetLayerCount) - virtual void SetLayer(uint32 nSlot, IMaterialLayer* pLayer) = 0; - //! Return active layer - virtual const IMaterialLayer* GetLayer(uint8 nLayersMask, uint8 nLayersUsageMask) const = 0; - //! Return layer at slot id - virtual const IMaterialLayer* GetLayer(uint32 nSlot) const = 0; - //! Create a new layer - virtual IMaterialLayer* CreateLayer() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Always get a valid material. - // If not multi material return this material. - // If Multi material return Default material if wrong id. - virtual _smart_ptr<IMaterial> GetSafeSubMtl(int nSlot) = 0; - - // Description: - // Fill an array of integeres representing surface ids of the sub materials or the material itself. - // Arguments: - // pSurfaceIdsTable is a pointer to the array of int with size enough to hold MAX_SUB_MATERIALS surface type ids. - // Return: - // number of filled items. - virtual int FillSurfaceTypeIds(int pSurfaceIdsTable[]) = 0; - - ////////////////////////////////////////////////////////////////////////// - // UserData used to link with the Editor. - ////////////////////////////////////////////////////////////////////////// - virtual void SetUserData(void* pUserData) = 0; - virtual void* GetUserData() const = 0; - - ////////////////////////////////////////////////////////////////////////// - //! Set or get a material parameter value. - //! \param sParamName - Name of the parameter - //! \param v - Input or output value depending on bGet - //! \param bGet - If true, v is an output; if false, v is an input - //! \param allowShaderParam - If true, and sParamName is not a built-in parameter of the Material, then custom shader parameters will be searched as well. Defaults to false to preserve legacy behavior. - //! \param materialIndex - Index of the sub-material if this is a material group - //! return - True if sParamName was found - virtual bool SetGetMaterialParamFloat(const char* sParamName, float& v, bool bGet, bool allowShaderParam = false, int materialIndex = 0) = 0; - //! Set or get a material parameter value. - //! \param sParamName - Name of the parameter - //! \param v - Input or output value depending on bGet - //! \param bGet - If true, v is an output; if false, v is an input - //! \param allowShaderParam - If true, and sParamName is not a built-in parameter of the Material, then custom shader parameters will be searched as well. Defaults to false to preserve legacy behavior. - //! \param materialIndex - Index of the sub-material if this is a material group - //! return - True if sParamName was found - virtual bool SetGetMaterialParamVec3(const char* sParamName, Vec3& v, bool bGet, bool allowShaderParam = false, int materialIndex = 0) = 0; - //! Set or get a material parameter value. - //! \param sParamName - Name of the parameter - //! \param v - Input or output value depending on bGet - //! \param bGet - If true, v is an output; if false, v is an input - //! \param allowShaderParam - If true, and sParamName is not a built-in parameter of the Material, then custom shader parameters will be searched as well. Defaults to false to preserve legacy behavior. - //! \param materialIndex - Index of the sub-material if this is a material group - //! return - True if sParamName was found - virtual bool SetGetMaterialParamVec4(const char* sParamName, Vec4& v, bool bGet, bool allowShaderParam = false, int materialIndex = 0) = 0; - - virtual void SetDirty(bool dirty = true) = 0; - virtual bool IsDirty() const = 0; - - //! Returns true if the material is the parent of a group of materials - virtual bool IsMaterialGroup() const = 0; - - //! Returns true if the material is a single material belongs to a material group - virtual bool IsSubMaterial() const = 0; - - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - - virtual size_t GetResourceMemoryUsage(ICrySizer* pSizer) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Makes this specific material enter sketch mode. - // Current supported sketch modes: - // - 0, no sketch. - // - 1, normal sketch mode. - // - 2, fast sketch mode. - virtual void SetSketchMode(int mode) = 0; - - // Sets FT_DONT_STREAM flag for all textures used by the material - // If a stream is already in process, this will stop the stream and flush the device texture - virtual void DisableTextureStreaming() = 0; - ////////////////////////////////////////////////////////////////////////// - // Tells to texture streamer to start loading textures asynchronously - ////////////////////////////////////////////////////////////////////////// - virtual void RequestTexturesLoading(const float fMipFactor) = 0; - - virtual void PrecacheMaterial(const float fEntDistance, struct IRenderMesh* pRenderMesh, bool bFullUpdate, bool bDrawNear = false) = 0; - - // Estimates texture memory usage for this material - // When nMatID is not negative only caluclate for one sub-material - virtual int GetTextureMemoryUsage(ICrySizer* pSizer, int nMatID = -1) = 0; - - // Set & retrieve a material link name - // This value by itself is not used by the material system per-se and hence - // has no real effect, however it is used on a higher level to tie related materials - // together, for example by procedural breakable glass to determine which material to - // switch to. - virtual void SetMaterialLinkName(const char* name) = 0; - virtual const char* GetMaterialLinkName() const = 0; - virtual void SetKeepLowResSysCopyForDiffTex() = 0; - - virtual uint32 GetDccMaterialHash() const = 0; - virtual void SetDccMaterialHash(uint32 hash) = 0; - - virtual CryCriticalSection& GetSubMaterialResizeLock() = 0; - - virtual void UpdateShaderItems() = 0; - - // </interfuscator:shuffle> -}; - - - -////////////////////////////////////////////////////////////////////////// -// Description: -// IMaterialManagerListener is a callback interface to listenen -// for special events of material manager, (used by Editor). -struct IMaterialManagerListener -{ - // <interfuscator:shuffle> - virtual ~IMaterialManagerListener(){} - // Called when material manager tries to load a material. - // nLoadingFlags - Zero or a bitwise combination of the flagas defined in ELoadingFlags. - virtual void OnCreateMaterial(_smart_ptr<IMaterial> pMaterial) = 0; - virtual void OnDeleteMaterial(_smart_ptr<IMaterial> pMaterial) = 0; - virtual bool IsCurrentMaterial(_smart_ptr<IMaterial> pMaterial) const = 0; - // </interfuscator:shuffle> -}; - -using IMaterialRef = _smart_ptr<IMaterial>; -////////////////////////////////////////////////////////////////////////// -// Description: -// IMaterialManager interface provide access to the material manager -// implemented in 3d engine. -struct IMaterialManager -{ - //! Loading flags - enum ELoadingFlags - { - ELoadingFlagsPreviewMode = BIT(0), - }; - - // <interfuscator:shuffle> - virtual ~IMaterialManager(){} - - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - - // Summary: - // Creates a new material object and register it with the material manager - // Return Value: - // A newly created object derived from IMaterial. - virtual _smart_ptr<IMaterial> CreateMaterial(const char* sMtlName, int nMtlFlags = 0) = 0; - - // Summary: - // Renames a material object - // Note: - // Do not use IMaterial::SetName directly. - // Arguments: - // pMtl - Pointer to a material object - // sNewName - New name to assign to the material - virtual void RenameMaterial(_smart_ptr<IMaterial> pMtl, const char* sNewName) = 0; - - // Description: - // Finds named material. - virtual _smart_ptr<IMaterial> FindMaterial(const char* sMtlName) const = 0; - - // Description: - // Loads material. - // nLoadingFlags - Zero or a bitwise combination of the values defined in ELoadingFlags. - virtual _smart_ptr<IMaterial> LoadMaterial(const char* sMtlName, bool bMakeIfNotFound = true, bool bNonremovable = false, unsigned long nLoadingFlags = 0) = 0; - - // Description: - // Loads material from xml. - virtual _smart_ptr<IMaterial> LoadMaterialFromXml(const char* sMtlName, XmlNodeRef mtlNode) = 0; - - // Description: - // Reloads the material from disk. - virtual void ReloadMaterial(_smart_ptr<IMaterial> pMtl) = 0; - - // Description: - // Saves material. - virtual bool SaveMaterial(XmlNodeRef mtlNode, _smart_ptr<IMaterial> pMtl) = 0; - - // Description: - // Clone single material or multi sub material. - // Arguments: - // nSubMtl - when negative all sub materials of MultiSubMtl are cloned, if positive only specified slot is cloned. - virtual _smart_ptr<IMaterial> CloneMaterial(_smart_ptr<IMaterial> pMtl, int nSubMtl = -1) = 0; - - // Description: - // Copy single material. - virtual void CopyMaterial(_smart_ptr<IMaterial> pMtlSrc, _smart_ptr<IMaterial> pMtlDest, EMaterialCopyFlags flags) = 0; - - // Description: - // Clone MultiSubMtl material. - // Arguments: - // sSubMtlName - name of the sub-material to clone, if NULL all submaterial are cloned. - virtual _smart_ptr<IMaterial> CloneMultiMaterial(_smart_ptr<IMaterial> pMtl, const char* sSubMtlName = 0) = 0; - - // Description: - // Associate a special listener callback with material manager inside 3d engine. - // This listener callback is used primerly by the editor. - virtual void SetListener(IMaterialManagerListener* pListener) = 0; - - // Description: - // Retrieve a default engine material. - virtual _smart_ptr<IMaterial> GetDefaultMaterial() = 0; - - // Description: - // Retrieve a default engine material for terrain layer - virtual _smart_ptr<IMaterial> GetDefaultTerrainLayerMaterial() = 0; - - // Description: - // Retrieve a default engine material with material layers presets. - virtual _smart_ptr<IMaterial> GetDefaultLayersMaterial() = 0; - - // Description: - // Retrieve a default engine material for drawing helpers. - virtual _smart_ptr<IMaterial> GetDefaultHelperMaterial() = 0; - - // Description: - // Retrieve surface type by name. - virtual ISurfaceType* GetSurfaceTypeByName(const char* sSurfaceTypeName, const char* sWhy = NULL) = 0; - virtual int GetSurfaceTypeIdByName(const char* sSurfaceTypeName, const char* sWhy = NULL) = 0; - // Description: - // Retrieve surface type by unique surface type id. - virtual ISurfaceType* GetSurfaceType(int nSurfaceTypeId, const char* sWhy = NULL) = 0; - // Description: - // Retrieve interface to surface type manager. - virtual ISurfaceTypeManager* GetSurfaceTypeManager() = 0; - - // Get IMaterial pointer from the CGF material structure. - // nLoadingFlags - Zero, or a bitwise combination of the enum items from ELoadingFlags. - virtual _smart_ptr<IMaterial> LoadCGFMaterial(CMaterialCGF* pMaterialCGF, const char* sCgfFilename, unsigned long nLoadingFlags = 0) = 0; - - // for statistics - call once to get the count (pData==0), again to get the data(pData!=0) - virtual void GetLoadedMaterials(AZStd::vector<_smart_ptr<IMaterial>>* pData, uint32& nObjCount) const = 0; - - // Updates material data in the renderer - virtual void RefreshMaterialRuntime() = 0; - - //// Forcing to create ISurfaceTypeManager - //virtual void CreateSurfaceTypeManager() = 0; - //// Forcing to destroy ISurfaceTypeManager - //virtual void ReleaseSurfaceTypeManager() = 0; - - // </interfuscator:shuffle> -}; - -#endif // CRYINCLUDE_CRYCOMMON_IMATERIAL_H diff --git a/Code/CryEngine/CryCommon/IMiniLog.h b/Code/CryEngine/CryCommon/IMiniLog.h deleted file mode 100644 index 2c1069b11d..0000000000 --- a/Code/CryEngine/CryCommon/IMiniLog.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : This is the smallest possible interface to the Log - -// it s independent and small so that it can be easily moved -// across the engine and test applications to test engine -// parts that need logging (e.g. Streaming Engine) separately - - -#ifndef CRYINCLUDE_CRYCOMMON_IMINILOG_H -#define CRYINCLUDE_CRYCOMMON_IMINILOG_H -#pragma once - - -struct IMiniLog -{ - enum ELogType - { - eMessage, - eWarning, - eError, - eAlways, - eWarningAlways, - eErrorAlways, - eInput, // e.g. "e_CaptureFolder ?" or all printouts from history or auto completion - eInputResponse, // e.g. "Set output folder for video capturing" in response to "e_CaptureFolder ?" - eComment - }; - - // <interfuscator:shuffle> - // Notes: - // You only have to implement this function. - virtual void LogV(ELogType nType, const char* szFormat, va_list args) PRINTF_PARAMS(3, 0) = 0; - - virtual void LogV(ELogType nType, int flags, const char* szFormat, va_list args) PRINTF_PARAMS(4, 0) = 0; - - // Summary: - // Logs using type. - inline void LogWithType(ELogType nType, const char* szFormat, ...) PRINTF_PARAMS(3, 4); - - inline void LogWithType(ELogType nType, int flags, const char* szFormat, ...) PRINTF_PARAMS(4, 5); - - // -------------------------------------------------------------------------- - - // Summary: - // Destructor. - virtual ~IMiniLog() {} - - // Description: - // This is the simplest log function for messages - // with the default implementation. - virtual inline void Log(const char* szFormat, ...) PRINTF_PARAMS(2, 3); - - // Description: - // This is the simplest log function for warnings - // with the default implementation. - virtual inline void LogWarning(const char* szFormat, ...) PRINTF_PARAMS(2, 3); - - // Description: - // This is the simplest log function for errors - // with the default implementation. - virtual inline void LogError(const char* szFormat, ...) PRINTF_PARAMS(2, 3); - // </interfuscator:shuffle> -}; - -inline void IMiniLog::LogWithType(ELogType nType, int flags, const char* szFormat, ...) -{ - va_list args; - va_start(args, szFormat); - LogV(nType, flags, szFormat, args); - va_end(args); -} - -inline void IMiniLog::LogWithType(ELogType nType, const char* szFormat, ...) -{ - va_list args; - va_start(args, szFormat); - LogV(nType, szFormat, args); - va_end(args); -} - -inline void IMiniLog::Log(const char* szFormat, ...) -{ - va_list args; - va_start(args, szFormat); - LogV (eMessage, szFormat, args); - va_end(args); -} - -inline void IMiniLog::LogWarning(const char* szFormat, ...) -{ - va_list args; - va_start(args, szFormat); - LogV (eWarning, szFormat, args); - va_end(args); -} - -inline void IMiniLog::LogError(const char* szFormat, ...) -{ - va_list args; - va_start(args, szFormat); - LogV (eError, szFormat, args); - va_end(args); -} - -// Notes: -// By default, to make it possible not to implement the log at the beginning at all, -// empty implementations of the two functions are given. -struct CNullMiniLog - : public IMiniLog -{ - // Notes: - // The default implementation just won't do anything - //##@{ - void LogV([[maybe_unused]] const char* szFormat, [[maybe_unused]] va_list args) {} - void LogV([[maybe_unused]] ELogType nType, [[maybe_unused]] const char* szFormat, [[maybe_unused]] va_list args) {} - void LogV ([[maybe_unused]] ELogType nType, [[maybe_unused]] int flags, [[maybe_unused]] const char* szFormat, [[maybe_unused]] va_list args) {} - //##@} -}; - - -#endif // CRYINCLUDE_CRYCOMMON_IMINILOG_H diff --git a/Code/CryEngine/CryCommon/IMovieSystem.h b/Code/CryEngine/CryCommon/IMovieSystem.h deleted file mode 100644 index fd30671296..0000000000 --- a/Code/CryEngine/CryCommon/IMovieSystem.h +++ /dev/null @@ -1,1467 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_IMOVIESYSTEM_H -#define CRYINCLUDE_CRYCOMMON_IMOVIESYSTEM_H -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Component/EntityId.h> -#include <AzCore/Math/Crc.h> -#include <AzCore/Math/Quaternion.h> -#include <AzCore/Serialization/SerializeContext.h> - -#include <Range.h> -#include <AnimKey.h> -#include <ISplines.h> -#include <IRenderer.h> -#include <IRenderAuxGeom.h> -#include <VectorSet.h> -#include <CryName.h> - -// forward declaration. -struct IAnimTrack; -struct IAnimNode; -struct IAnimSequence; -struct IMovieSystem; -struct IKey; -class XmlNodeRef; -struct ISplineInterpolator; -struct ILightAnimWrapper; - -namespace AZ -{ - namespace Data - { - class AssetData; - } -} - -namespace Maestro -{ - template<typename AssetType> - struct AssetBlends; -} - -typedef IMovieSystem* (* PFNCREATEMOVIESYSTEM)(struct ISystem*); - -#define LIGHT_ANIMATION_SET_NAME "_LightAnimationSet" -#define MAX_ANIM_NAME_LENGTH 64 -//! Very high priority for cut scene sounds. -#define MOVIE_SOUND_PRIORITY 230 - -#if !defined(CONSOLE) -#define MOVIESYSTEM_SUPPORT_EDITING -#endif - -typedef std::vector<IAnimSequence*> AnimSequences; -typedef AZStd::vector<AZStd::string> TrackEvents; - -// Forward declare, including will cause much pain with the precompiled headers -enum class SequenceType; -enum class AnimNodeType; -enum class AnimValueType; -enum class AnimParamType; - -// TODO: Refactor headers that are using these values so they are not need in header files - -// AnimValueType::Float is the default value -#define kAnimValueDefault static_cast<AnimValueType>(0) -// AnimValueType::Unknown -#define kAnimValueUnknown static_cast<AnimValueType>(0xFFFFFFFF) -// SequenceType::SequenceComponent is the default value -#define kSequenceTypeDefault static_cast<SequenceType>(1) -// AnimParamType::Invalid -#define kAnimParamTypeInvalid static_cast<AnimParamType>(0xFFFFFFFF) -// AnimParamType::ByString -#define kAnimParamTypeByString static_cast<AnimParamType>(8) - -//! Flags that can be set on animation node. -enum EAnimNodeFlags -{ - eAnimNodeFlags_Expanded = BIT(0), //!< Deprecated, handled by sandbox now - eAnimNodeFlags_EntitySelected = BIT(1), //!< Set if the referenced entity is selected in the editor - eAnimNodeFlags_CanChangeName = BIT(2), //!< Set if this node allow changing of its name. - eAnimNodeFlags_Disabled = BIT(3), //!< Disable this node. - eAnimNodeFlags_DisabledForComponent = BIT(4), //!< Disable this node for a disabled or pending entity component. -}; - -enum ENodeExportType -{ - eNodeExportType_Global = 0, - eNodeExportType_Local = 1, -}; - -// Common parameters of animation node. -class CAnimParamType -{ - friend class CMovieSystem; - friend class AnimSerializer; - -public: - AZ_TYPE_INFO(CAnimParamType, "{E2F34955-3B07-4241-8D34-EA3BEF3B33D2}") - - static const uint kParamTypeVersion = 9; - - CAnimParamType() - : m_type(kAnimParamTypeInvalid) {} - - CAnimParamType(const string& name) - { - *this = name; - } - - CAnimParamType(AnimParamType type) - { - *this = type; - } - - // Convert from old enum or int - void operator =(AnimParamType type) - { - m_type = type; - } - - void operator =(const string& name) - { - m_type = kAnimParamTypeByString; - m_name = name; - } - - void operator =(const AZStd::string& name) - { - m_type = kAnimParamTypeByString; - m_name = name; - } - // Convert to enum. This needs to be explicit, - // otherwise operator== will be ambiguous - AnimParamType GetType() const { return m_type; } - - // Get name - const char* GetName() const { return m_name.c_str(); } - - bool operator ==(const CAnimParamType& animParamType) const - { - if (m_type == kAnimParamTypeByString && animParamType.m_type == kAnimParamTypeByString) - { - return m_name == animParamType.m_name; - } - - return m_type == animParamType.m_type; - } - - bool operator !=(const CAnimParamType& animParamType) const - { - return !(*this == animParamType); - } - - bool operator <(const CAnimParamType& animParamType) const - { - if (m_type == kAnimParamTypeByString && animParamType.m_type == kAnimParamTypeByString) - { - return m_name < animParamType.m_name; - } - else if (m_type == kAnimParamTypeByString) - { - return false; // Always sort named params last - } - else if (animParamType.m_type == kAnimParamTypeByString) - { - return true; // Always sort named params last - } - if (m_type < animParamType.m_type) - { - return true; - } - - return false; - } - - - void SaveToXml(XmlNodeRef& xmlNode) const; - void LoadFromXml(const XmlNodeRef& xmlNode, const uint version = kParamTypeVersion); - - // Serialization. Defined in Movie.cpp - inline void Serialize(XmlNodeRef& xmlNode, bool bLoading, const uint version = kParamTypeVersion); - -private: - AnimParamType m_type; - AZStd::string m_name; -}; - -namespace AZStd -{ - // define hasher to allow for AZStd maps and sets of CAnimParamType - template <> - struct hash < CAnimParamType > - { - inline size_t operator()(const CAnimParamType& paramType) const - { - AZStd::hash<AnimParamType> paramTypeHasher; - size_t retVal = paramTypeHasher(paramType.GetType()); - AZStd::hash_combine(retVal, AZ::Crc32(paramType.GetName())); - return retVal; - } - }; -} // namespace AZStd - -//! Types of animation track. -// Do not change values! they are serialized -// -// Attention: This should only be expanded if you add a completely new way how tracks store data! -// If you just want to control a new parameter of an entity etc. extend EParamType -// -// Note: TCB splines are only for backward compatibility, Bezier is the default -// -enum EAnimCurveType -{ - eAnimCurveType_TCBFloat = 1, - eAnimCurveType_TCBVector = 2, - eAnimCurveType_TCBQuat = 3, - eAnimCurveType_BezierFloat = 4, - - eAnimCurveType_Unknown = 0xFFFFFFFF -}; - -enum ETrackMask -{ - eTrackMask_MaskSound = 1 << 11, // Old: 1 << ATRACK_SOUND -}; - -//! Structure passed to Animate function. -struct SAnimContext -{ - SAnimContext() - { - singleFrame = false; - forcePlay = false; - resetting = false; - time = 0; - dt = 0; - fps = 0; - sequence = nullptr; - trackMask = 0; - startTime = 0; - } - - float time; //!< Current time in seconds. - float dt; //!< Delta of time from previous animation frame in seconds. - float fps; //!< Last calculated frames per second value. - bool singleFrame; //!< This is not a playing animation, more a single-frame update. - bool forcePlay; //!< Set when force playing animation. - bool resetting; //!< Set when animation sequence is resetting. - - IAnimSequence* sequence; //!< Sequence in which animation performed. - - // TODO: Replace trackMask with something more type safe - // TODO: Mask should be stored with dynamic length - uint32 trackMask; //!< To update certain types of tracks only - float startTime; //!< The start time of this playing sequence - - void Serialize(XmlNodeRef& xmlNode, bool loading); -}; - -/** Parameters for cut-scene cameras -*/ -struct SCameraParams -{ - SCameraParams() - { - fov = 0.0f; - nearZ = DEFAULT_NEAR; - justActivated = false; - } - AZ::EntityId cameraEntityId; - float fov; - float nearZ; - bool justActivated; -}; - -//! Interface for movie-system implemented by user for advanced function-support -struct IMovieUser -{ - // <interfuscator:shuffle> - virtual ~IMovieUser(){} - //! Called when movie system requests a camera-change. - virtual void SetActiveCamera(const SCameraParams& Params) = 0; - //! Called when movie system enters into cut-scene mode. - virtual void BeginCutScene(IAnimSequence* pSeq, unsigned long dwFlags, bool bResetFX) = 0; - //! Called when movie system exits from cut-scene mode. - virtual void EndCutScene(IAnimSequence* pSeq, unsigned long dwFlags) = 0; - //! Called when movie system wants to send a global event. - virtual void SendGlobalEvent(const char* pszEvent) = 0; - // </interfuscator:shuffle> -}; - -//! Callback-class -struct IMovieCallback -{ - //! Callback-reasons - enum ECallbackReason - { - CBR_CHANGENODE, // Node is changing. - CBR_CHANGETRACK // Track of the node is changing. - }; - - // <interfuscator:shuffle> - virtual ~IMovieCallback(){} - // Called by movie system. - virtual void OnMovieCallback(ECallbackReason reason, IAnimNode* pNode) = 0; - virtual void OnSetCamera(const SCameraParams& Params) = 0; - virtual bool IsSequenceCamUsed() const = 0; - // </interfuscator:shuffle> -}; - -/** Interface of Animation Track. -*/ -struct IAnimTrack -{ - AZ_RTTI(IAnimTrack, "{AA0D5170-FB28-426F-BA13-7EFF6BB3AC67}"); - AZ_CLASS_ALLOCATOR(IAnimTrack, AZ::SystemAllocator, 0); - - static void Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context)) - { - serializeContext->Class<IAnimTrack>(); - } - } - - //! Flags that can be set on animation track. - enum EAnimTrackFlags - { - eAnimTrackFlags_Linear = BIT(1), //!< Use only linear interpolation between keys. - eAnimTrackFlags_Loop = BIT(2), //!< Play this track in a loop. - eAnimTrackFlags_Cycle = BIT(3), //!< Cycle track. - eAnimTrackFlags_Disabled = BIT(4), //!< Disable this track. - - ////////////////////////////////////////////////////////////////////////// - // Used by editor. - ////////////////////////////////////////////////////////////////////////// - eAnimTrackFlags_Hidden = BIT(5), //!< Set when track is hidden in track view. - eAnimTrackFlags_Muted = BIT(8), //!< Mute this sound track or music track. This only affects the playback in editor on these types of tracks. - }; - - // <interfuscator:shuffle> - virtual ~IAnimTrack() {}; - - // for intrusive_ptr support - virtual void add_ref() = 0; - virtual void release() = 0; - - ////////////////////////////////////////////////////////////////////////// - virtual EAnimCurveType GetCurveType() = 0; - virtual AnimValueType GetValueType() = 0; - -#ifdef MOVIESYSTEM_SUPPORT_EDITING - // This color is used for the editor. - virtual ColorB GetCustomColor() const = 0; - virtual void SetCustomColor(ColorB color) = 0; - virtual bool HasCustomColor() const = 0; - virtual void ClearCustomColor() = 0; -#endif - - // Return what parameter of the node, this track is attached to. - virtual const CAnimParamType& GetParameterType() const = 0; - - // Assign node parameter ID for this track. - virtual void SetParameterType(CAnimParamType type) = 0; - - virtual void SetNode(IAnimNode* node) = 0; - // Return Animation Sequence that owns this node. - virtual IAnimNode* GetNode() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Animation track can contain sub-tracks (Position XYZ anim track have sub-tracks for x,y,z) - // Get count of sub tracks. - virtual int GetSubTrackCount() const = 0; - // Retrieve pointer the specfied sub track. - virtual IAnimTrack* GetSubTrack(int nIndex) const = 0; - virtual const char* GetSubTrackName(int nIndex) const = 0; - virtual void SetSubTrackName(int nIndex, const char* name) = 0; - ////////////////////////////////////////////////////////////////////////// - - virtual void GetKeyValueRange(float& fMin, float& fMax) const = 0; - virtual void SetKeyValueRange(float fMin, float fMax) = 0; - - //! Return number of keys in track. - virtual int GetNumKeys() const = 0; - - //! Return true if keys exists in this track - virtual bool HasKeys() const = 0; - - //! Set number of keys in track. - //! If needed adds empty keys at end or remove keys from end. - virtual void SetNumKeys(int numKeys) = 0; - - //! Remove specified key. - virtual void RemoveKey(int num) = 0; - - //! Get key at specified location. - //! @param key Must be valid pointer to compatible key structure, to be filled with specified key location. - virtual void GetKey(int index, IKey* key) const = 0; - - //! Get time of specified key. - //! @return key time. - virtual float GetKeyTime(int index) const = 0; - - //! Find key at given time. - //! @return Index of found key, or -1 if key with this time not found. - virtual int FindKey(float time) = 0; - - //! Get flags of specified key. - //! @return key time. - virtual int GetKeyFlags(int index) = 0; - - //! Set key at specified location. - //! @param key Must be valid pointer to compatible key structure. - virtual void SetKey(int index, IKey* key) = 0; - - //! Set time of specified key. - virtual void SetKeyTime(int index, float time) = 0; - - //! Set flags of specified key. - virtual void SetKeyFlags(int index, int flags) = 0; - - //! Sort keys in track (after time of keys was modified). - virtual void SortKeys() = 0; - - //! Get track flags. - virtual int GetFlags() = 0; - - //! Check if track is masked by mask - // TODO: Mask should be stored with dynamic length - virtual bool IsMasked(const uint32 mask) const = 0; - - //! Set track flags. - virtual void SetFlags(int flags) = 0; - - //! Create key at given time, and return its index. - //! @return Index of new key. - virtual int CreateKey(float time) = 0; - - //! Clone key at specified index. - //! @retun Index of new key. - virtual int CloneKey(int key) = 0; - - //! Clone key at specified index from another track of SAME TYPE. - //! @retun Index of new key. - virtual int CopyKey(IAnimTrack* pFromTrack, int nFromKey) = 0; - - //! Get info about specified key. - //! @param Short human readable text description of this key. - //! @param duration of this key in seconds. - virtual void GetKeyInfo(int key, const char*& description, float& duration) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Get track value at specified time. - // Interpolates keys if needed. - // Applies a scale multiplier set in SetMultiplier(), if requested - ////////////////////////////////////////////////////////////////////////// - virtual void GetValue(float time, float& value, bool applyMultiplier=false) = 0; - virtual void GetValue(float time, Vec3& value, bool applyMultiplier = false) = 0; - virtual void GetValue(float time, Vec4& value, bool applyMultiplier = false) = 0; - virtual void GetValue(float time, Quat& value) = 0; - virtual void GetValue(float time, bool& value) = 0; - virtual void GetValue(float time, Maestro::AssetBlends<AZ::Data::AssetData>& value) = 0; - - // support for AZ:: vector types - re-route to legacy types - void GetValue(float time, AZ::Vector3& value, bool applyMultiplier = false) - { - Vec3 vec3; - GetValue(time, vec3, applyMultiplier); - value.Set(vec3.x, vec3.y, vec3.z); - } - void GetValue(float time, AZ::Quaternion& value) - { - Quat quat; - GetValue(time, quat); - value.Set(quat.v.x, quat.v.y, quat.v.z, quat.w); - } - - ////////////////////////////////////////////////////////////////////////// - // Set track value at specified time. - // Adds new keys if required. - ////////////////////////////////////////////////////////////////////////// - virtual void SetValue(float time, const float& value, bool bDefault = false, bool applyMultiplier = false) = 0; - virtual void SetValue(float time, const Vec3& value, bool bDefault = false, bool applyMultiplier = false) = 0; - virtual void SetValue(float time, const Vec4& value, bool bDefault = false, bool applyMultiplier = false) = 0; - virtual void SetValue(float time, const Quat& value, bool bDefault = false) = 0; - virtual void SetValue(float time, const bool& value, bool bDefault = false) = 0; - virtual void SetValue(float time, const Maestro::AssetBlends<AZ::Data::AssetData>& value, bool bDefault = false) = 0; - - // support for AZ:: vector types - re-route to legacy types - void SetValue(float time, AZ::Vector3& value, bool bDefault = false, bool applyMultiplier = false) - { - Vec3 vec3(value.GetX(), value.GetY(), value.GetZ()); - SetValue(time, vec3, bDefault, applyMultiplier); - } - void SetValue(float time, AZ::Quaternion& value, [[maybe_unused]] bool bDefault = false) - { - Quat quat(value.GetW(), value.GetX(), value.GetY(), value.GetZ()); - SetValue(time, quat); - } - - // Only for position tracks, offset all track keys by this amount. - virtual void OffsetKeyPosition(const Vec3& value) = 0; - - // Used to update the data in tracks after the parent entity has been changed. - virtual void UpdateKeyDataAfterParentChanged(const AZ::Transform& oldParentWorldTM, const AZ::Transform& newParentWorldTM) = 0; - - // Assign active time range for this track. - virtual void SetTimeRange(const Range& timeRange) = 0; - - //! @deprecated - IAnimTracks use AZ::Serialization now. Legacy - Serialize this animation track to XML. - virtual bool Serialize(XmlNodeRef& xmlNode, bool bLoading, bool bLoadEmptyTracks = true) = 0; - virtual bool SerializeSelection(XmlNodeRef& xmlNode, bool bLoading, bool bCopySelected = false, float fTimeOffset = 0) = 0; - - virtual void InitPostLoad(IAnimSequence* /*sequence*/) {}; - - //! For custom track animate parameters. - virtual void Animate([[maybe_unused]] SAnimContext& ec) {}; - - // Get access to the internal spline of the track. - virtual ISplineInterpolator* GetSpline() const { return 0; }; - - virtual bool IsKeySelected([[maybe_unused]] int key) const { return false; } - - virtual void SelectKey([[maybe_unused]] int key, [[maybe_unused]] bool select) {} - - virtual void SetSortMarkerKey([[maybe_unused]] unsigned int keyIndex, [[maybe_unused]] bool enabled) {} - virtual bool IsSortMarkerKey([[maybe_unused]] unsigned int keyIndex) const { return false; } - - //! Return the index of the key which lies right after the given key in time. - //! @param key Index of of key. - //! @return Index of the next key in time. If the last key given, this returns -1. - // In case of keys sorted, it's just 'key+1', but if not sorted, it can be another value. - virtual int NextKeyByTime(int key) const - { - if (key + 1 < GetNumKeys()) - { - return key + 1; - } - else - { - return -1; - } - } - - //! Get the animation layer index assigned. (only for character/look-at tracks ATM) - virtual int GetAnimationLayerIndex() const { return -1; } - //! Set the animation layer index. (only for character/look-at tracks ATM) - virtual void SetAnimationLayerIndex([[maybe_unused]] int index) { } - - //! Returns whether the track responds to muting (false by default), which only affects the Edtior. - //! Tracks that use mute should override this, such as CSoundTrack - //! @return Boolean of whether the track respnnds to muting or not - virtual bool UsesMute() const { return false; } - - //! Set a multiplier which will be multiplied to track values in SetValue and divided out in GetValue if requested - virtual void SetMultiplier(float trackValueMultiplier) = 0; - - // Expanded state interface - virtual void SetExpanded(bool expanded) = 0; - virtual bool GetExpanded() const = 0; - - virtual unsigned int GetId() const = 0; - virtual void SetId(unsigned int id) = 0; - - // </interfuscator:shuffle> -}; - - -/** Callback called by animation node when its animated. -*/ -struct IAnimNodeOwner -{ - // <interfuscator:shuffle> - virtual ~IAnimNodeOwner(){} - virtual void OnNodeAnimated([[maybe_unused]] IAnimNode* pNode) {} - virtual void OnNodeVisibilityChanged(IAnimNode* pNode, const bool bHidden) = 0; - virtual void OnNodeReset([[maybe_unused]] IAnimNode* pNode) {} - - // mark the node's sequence object layer as modified - virtual void MarkAsModified() = 0; - // </interfuscator:shuffle> -}; - -/** Base class for all Animation nodes, - can host multiple animation tracks, and execute them other time. - Animation node is reference counted. -*/ -struct IAnimNode -{ -public: - AZ_RTTI(IAnimNode, "{0A096354-7F26-4B18-B8C0-8F10A3E0440A}"); - AZ_CLASS_ALLOCATOR(IAnimNode, AZ::SystemAllocator, 0); - - static void Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context)) - { - serializeContext->Class<IAnimNode>(); - } - } - - ////////////////////////////////////////////////////////////////////////// - // Supported params. - ////////////////////////////////////////////////////////////////////////// - enum ESupportedParamFlags - { - eSupportedParamFlags_MultipleTracks = 0x01, // Set if parameter can be assigned multiple tracks. - eSupportedParamFlags_Hidden = 0x02, // Hidden from the Track View UI. - }; - - struct SParamInfo - { - SParamInfo() - : name("") - , valueType(kAnimValueDefault) - , flags(ESupportedParamFlags(0)) {}; - SParamInfo(const char* _name, CAnimParamType _paramType, AnimValueType _valueType, ESupportedParamFlags _flags) - : name(_name) - , paramType(_paramType) - , valueType(_valueType) - , flags(_flags) {}; - - const char* name; // parameter name. - CAnimParamType paramType; // parameter id. - AnimValueType valueType; // value type, defines type of track to use for animating this parameter. - ESupportedParamFlags flags; // combination of flags from ESupportedParamFlags. - }; - - using AnimParamInfos = AZStd::vector<SParamInfo>; - - // <interfuscator:shuffle> - virtual ~IAnimNode() {}; - - // for intrusive_ptr support - virtual void add_ref() = 0; - virtual void release() = 0; - - //! Set node name. - virtual void SetName(const char* name) = 0; - - //! Get node name. - virtual const char* GetName() = 0; - - // Get Type of this node. - virtual AnimNodeType GetType() const = 0; - - // Return Animation Sequence that owns this node. - virtual IAnimSequence* GetSequence() const = 0; - - // Set the Animation Sequence that owns this node. - virtual void SetSequence(IAnimSequence* sequence) = 0; - - // Called when sequence is activated / deactivated - virtual void Activate(bool bActivate) = 0; - - // Set AnimNode flags. - // @param flags One or more flags from EAnimNodeFlags. - // @see EAnimNodeFlags - virtual void SetFlags(int flags) = 0; - - // Get AnimNode flags. - // @return flags set on node. - // @see EAnimNodeFlags - virtual int GetFlags() const = 0; - - // return true if flagsToCheck is set on the node or any of the node's parents - virtual bool AreFlagsSetOnNodeOrAnyParent(EAnimNodeFlags flagsToCheck) const = 0; - - // AZ::Entity is bound/handled via their Id over EBuses, as opposed to directly with pointers. - virtual void SetAzEntityId(const AZ::EntityId& id) = 0; - virtual AZ::EntityId GetAzEntityId() const = 0; - - // Return movie system that created this node. - virtual IMovieSystem* GetMovieSystem() const = 0; - - ////////////////////////////////////////////////////////////////////////// - // Space position/orientation scale. - ////////////////////////////////////////////////////////////////////////// - //! Translate entity node. - virtual void SetPos(float time, const Vec3& pos) = 0; - //! Rotate entity node. - virtual void SetRotate(float time, const Quat& quat) = 0; - //! Scale entity node. - virtual void SetScale(float time, const Vec3& scale) = 0; - - //! Compute and return the offset which brings the current position to the given position - virtual Vec3 GetOffsetPosition(const Vec3& position) { return position - GetPos(); } - - //! Get current entity position. - virtual Vec3 GetPos() = 0; - //! Get current entity rotation. - virtual Quat GetRotate() = 0; - //! Get entity rotation at specified time. - virtual Quat GetRotate(float time) = 0; - //! Get current entity scale. - virtual Vec3 GetScale() = 0; - - // General Set param. - // Set float/vec3/vec4 parameter at given time. - // @return true if parameter set, false if this parameter not exist in node. - virtual bool SetParamValue(float time, CAnimParamType param, float value) = 0; - virtual bool SetParamValue(float time, CAnimParamType param, const Vec3& value) = 0; - virtual bool SetParamValue(float time, CAnimParamType param, const Vec4& value) = 0; - // Get float/vec3/vec4 parameter at given time. - // @return true if parameter exist, false if this parameter not exist in node. - virtual bool GetParamValue(float time, CAnimParamType param, float& value) = 0; - virtual bool GetParamValue(float time, CAnimParamType param, Vec3& value) = 0; - virtual bool GetParamValue(float time, CAnimParamType param, Vec4& value) = 0; - - //! Evaluate animation node while not playing animation. - virtual void StillUpdate() = 0; - - //! Evaluate animation to the given time. - virtual void Animate(SAnimContext& ec) = 0; - - // Description: - // Returns number of supported parameters by this animation node (position,rotation,scale,etc..). - // Returns: - // Number of supported parameters. - virtual unsigned int GetParamCount() const = 0; - - // Description: - // Returns the type of a param by index - // Arguments: - // nIndex - parameter index in range 0 <= nIndex < GetSupportedParamCount() - virtual CAnimParamType GetParamType(unsigned int nIndex) const = 0; - - // Description: - // Check if parameter is supported by this node. - virtual bool IsParamValid(const CAnimParamType& paramType) const = 0; - - // Description: - // Returns name of supported parameter of this animation node or NULL if not available - // Arguments: - // paramType - parameter id - virtual const char* GetParamName(const CAnimParamType& paramType) const = 0; - - // Description: - // Returns the params value type - virtual AnimValueType GetParamValueType(const CAnimParamType& paramType) const = 0; - - // Description: - // Returns the params value type - virtual ESupportedParamFlags GetParamFlags(const CAnimParamType& paramType) const = 0; - - // Called node data is re-initialized, such as when changing the entity associated with it. - virtual void OnReset() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Working with Tracks. - ////////////////////////////////////////////////////////////////////////// - virtual int GetTrackCount() const = 0; - - // Return track assigned to the specified parameter. - virtual IAnimTrack* GetTrackByIndex(int nIndex) const = 0; - - // Return first track assigned to the specified parameter. - virtual IAnimTrack* GetTrackForParameter(const CAnimParamType& paramType) const = 0; - - // Return the i-th track assigned to the specified parameter in case of multiple tracks. - virtual IAnimTrack* GetTrackForParameter(const CAnimParamType& paramType, uint32 index) const = 0; - - // Get the index of a given track among tracks with the same parameter type in this node. - virtual uint32 GetTrackParamIndex(const IAnimTrack* pTrack) const = 0; - - // Creates a new track for given parameter. - virtual IAnimTrack* CreateTrack(const CAnimParamType& paramType) = 0; - - // Initializes track default values after de-serialization / user creation. Only called in editor. - virtual void InitializeTrackDefaultValue(IAnimTrack* pTrack, const CAnimParamType& paramType) = 0; - - // Assign animation track to parameter. - // if track parameter is NULL track with parameter id param will be removed. - virtual void SetTrack(const CAnimParamType& paramType, IAnimTrack* track) = 0; - - // Set time range for all tracks in this sequence. - virtual void SetTimeRange(Range timeRange) = 0; - - // Remove track from anim node. - virtual void AddTrack(IAnimTrack* pTrack) = 0; - - // Remove track from anim node. - virtual bool RemoveTrack(IAnimTrack* pTrack) = 0; - - // Description: - // Creates default set of tracks supported by this node. - virtual void CreateDefaultTracks() = 0; - - // returns the tangent type to use for created keys. Override this if you have an animNode that you wish - // to have tangents other than UNIFIED created for new keys. - virtual int GetDefaultKeyTangentFlags() const { return SPLINE_KEY_TANGENT_UNIFIED; } - - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // Callback for animation node used by editor. - // Register notification callback with animation node. - virtual void SetNodeOwner(IAnimNodeOwner* pOwner) = 0; - virtual IAnimNodeOwner* GetNodeOwner() = 0; - - // Serialize this animation node to XML. - virtual void Serialize(XmlNodeRef& xmlNode, bool bLoading, bool bLoadEmptyTracks) = 0; - - // Serialize only the tracks in this animation node to/from XML - virtual void SerializeAnims(XmlNodeRef& xmlNode, bool bLoading, bool bLoadEmptyTracks) = 0; - - // Sets up internal pointers post load from Sequence Component - virtual void InitPostLoad(IAnimSequence* sequence) = 0; - - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - // Groups interface - ////////////////////////////////////////////////////////////////////////// - virtual void SetParent(IAnimNode* pParent) = 0; - virtual IAnimNode* GetParent() const = 0; - virtual IAnimNode* HasDirectorAsParent() const = 0; - ////////////////////////////////////////////////////////////////////////// - - virtual void Render() = 0; - - virtual bool NeedToRender() const = 0; - - // Called from editor if dynamic params need updating - virtual void UpdateDynamicParams() = 0; - // </interfuscator:shuffle> - - // Used by AnimCameraNode - virtual bool GetShakeRotation([[maybe_unused]] const float& time, [[maybe_unused]] Quat& rot){return false; } - - virtual void SetCameraShakeSeed([[maybe_unused]] const uint shakeSeed){}; - - // override this method to handle explicit setting of time - virtual void TimeChanged([[maybe_unused]] float newTime) {}; - - // Compares all of the node's track values at the given time with the associated property value and - // sets a key at that time if they are different to match the latter - // Returns the number of keys set - virtual int SetKeysForChangedTrackValues([[maybe_unused]] float time) { return 0; }; - - // Callbacks used when Game/Simulation mode is started and stopped in the Editor. Override if you want to handle these events - virtual void OnStartPlayInEditor() {}; - virtual void OnStopPlayInEditor() {}; - - //////////////////////////////////////////////////////////////////////////////// - // interface for Components - implemented by CAnimComponentNode - - // Override if the derived node has an associated component type (e.g. CAnimComponentNode) - virtual void SetComponent([[maybe_unused]] AZ::ComponentId comopnentId, [[maybe_unused]] const AZ::Uuid& componentTypeId) {} - - // returns the componentId of the component the node is associate with, if applicable, or a AZ::InvalidComponentId otherwise - virtual AZ::ComponentId GetComponentId() const { return AZ::InvalidComponentId; } - // ~interface for Components - //////////////////////////////////////////////////////////////////////////////// - - // Used to disable any animation that is overridden by a SceneNode during camera interpolation, such as - // FoV, transform, nearZ - virtual void SetSkipInterpolatedCameraNode([[maybe_unused]] const bool skipNodeCameraAnimation) {}; - - // Expanded state interface - virtual void SetExpanded(bool expanded) = 0; - virtual bool GetExpanded() const = 0; - - // Return the node id. This id is unique within a given sequence. - virtual int GetId() const = 0; -}; - -//! Track event listener -struct ITrackEventListener -{ - //! Reasons - enum ETrackEventReason - { - eTrackEventReason_Added, - eTrackEventReason_Removed, - eTrackEventReason_Renamed, - eTrackEventReason_Triggered, - eTrackEventReason_MovedUp, - eTrackEventReason_MovedDown, - }; - - // <interfuscator:shuffle> - virtual ~ITrackEventListener(){} - // Description: - // Called when track event is updated - // Arguments: - // pSeq - Animation sequence - // reason - Reason for update (see EReason) - // event - Track event added - // pUserData - Data to accompany reason - virtual void OnTrackEvent(IAnimSequence* sequence, int reason, const char* event, void* pUserData) = 0; - virtual void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const{}; - // </interfuscator:shuffle> -}; - -struct IAnimLegacySequenceObject -{ - // <interfuscator:shuffle> - virtual ~IAnimLegacySequenceObject() {} - virtual void OnNameChanged() = 0; - virtual void OnModified() = 0; - // </interfuscator:shuffle> -}; - -struct IAnimStringTable -{ - AZ_RTTI(IAnimStringTable, "{35690309-9D22-41FF-80B7-8AF7C8419945}") - virtual ~IAnimStringTable() {} - - // for intrusive_ptr support - virtual void add_ref() = 0; - virtual void release() = 0; - - virtual const char* Add(const char* p) = 0; -}; - -/** Animation sequence, operates on animation nodes contained in it. - */ -struct IAnimSequence -{ - AZ_RTTI(IAnimSequence, "{A60F95F5-5A4A-47DB-B3BB-525BBC0BC8DB}"); - AZ_CLASS_ALLOCATOR(IAnimSequence, AZ::SystemAllocator, 0); - - static const int kSequenceVersion = 5; - - static void Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context)) - { - serializeContext->Class<IAnimSequence>(); - } - } - - //! Flags used for SetFlags(),GetFlags(),SetParentFlags(),GetParentFlags() methods. - enum EAnimSequenceFlags - { - eSeqFlags_PlayOnReset = BIT(0), //!< Start playing this sequence immediately after reset of movie system(Level load). - eSeqFlags_OutOfRangeConstant = BIT(1), //!< Constant Out-Of-Range,time continues normally past sequence time range. - eSeqFlags_OutOfRangeLoop = BIT(2), //!< Loop Out-Of-Range,time wraps back to the start of range when reaching end of range. - eSeqFlags_CutScene = BIT(3), //!< Cut scene sequence. - eSeqFlags_NoHUD = BIT(4), //!< @deprecated - Don`t display HUD - eSeqFlags_NoPlayer = BIT(5), //!< Disable input and drawing of player - eSeqFlags_NoGameSounds = BIT(9), //!< Suppress all game sounds. - eSeqFlags_NoSeek = BIT(10), //!< Cannot seek in sequence. - eSeqFlags_NoAbort = BIT(11), //!< Cutscene can not be aborted - eSeqFlags_NoSpeed = BIT(13), //!< Cannot modify sequence speed - TODO: add interface control if required - // eSeqFlags_CanWarpInFixedTime = BIT(14), //!< @deprecated - Timewarp by scaling a fixed time step - removed July 2017, unused - eSeqFlags_EarlyMovieUpdate = BIT(15), //!< Turn the 'sys_earlyMovieUpdate' on during the sequence. - eSeqFlags_LightAnimationSet = BIT(16), //!< A special unique sequence for light animations - eSeqFlags_NoMPSyncingNeeded = BIT(17), //!< this sequence doesn't require MP net syncing - }; - - virtual ~IAnimSequence() {}; - - // for intrusive_ptr support - virtual void add_ref() = 0; - virtual void release() = 0; - - //! Set the name of this sequence. (ex. "Intro" in the same case as above) - virtual void SetName(const char* name) = 0; - //! Get the name of this sequence. (ex. "Intro" in the same case as above) - virtual const char* GetName() const = 0; - //! Get the ID (unique in a level and consistent across renaming) of this sequence. - virtual uint32 GetId () const = 0; - //! Resets the ID to the next available ID - used on sequence loads into levels to resolve ID collisions - virtual void ResetId() = 0; - - // Legacy sequence objects are connected by pointers. SequenceComponents are connected by AZ::EntityId - virtual void SetLegacySequenceObject(IAnimLegacySequenceObject* legacySequenceObject) = 0; - virtual IAnimLegacySequenceObject* GetLegacySequenceObject() const = 0; - virtual void SetSequenceEntityId(const AZ::EntityId& entityOwnerId) = 0; - virtual const AZ::EntityId& GetSequenceEntityId() const = 0; - - //! Set the currently active director node. - virtual void SetActiveDirector(IAnimNode* pDirectorNode) = 0; - //! Get the currently active director node, if any. - virtual IAnimNode* GetActiveDirector() const = 0; - - //! Set animation sequence flags - virtual void SetFlags(int flags) = 0; - //! Get animation sequence flags - virtual int GetFlags() const = 0; - //! Get cutscene related animation sequence flags - virtual int GetCutSceneFlags(const bool localFlags = false) const = 0; - //! Set parent animation sequence - virtual void SetParentSequence(IAnimSequence* pParentSequence) = 0; - //! Get parent animation sequence - virtual const IAnimSequence* GetParentSequence() const = 0; - //! Check whether this sequence has the given sequence as a descendant through one of its sequence tracks. - virtual bool IsAncestorOf(const IAnimSequence* sequence) const = 0; - - //! Return number of animation nodes in sequence. - virtual int GetNodeCount() const = 0; - //! Get animation node at specified index. - virtual IAnimNode* GetNode(int index) const = 0; - - //! Add animation node to sequence. - //! @return True if node added, same node will not be added 2 times. - virtual bool AddNode(IAnimNode* node) = 0; - - // Reorders the array of nodes, so the specified node is placed after or before the given pivot node depending on the parameter 'next'. - virtual void ReorderNode(IAnimNode* node, IAnimNode* pPivotNode, bool next) = 0; - - // Description: - // Creates a new animation node with specified type. - // Arguments: - // nodeType - Type of node, one of AnimNodeType enums. - virtual IAnimNode* CreateNode(AnimNodeType nodeType) = 0; - - // Description: - // Creates a new animation node from serialized node XML. - // Arguments: - // node - Serialized form of node - virtual IAnimNode* CreateNode(XmlNodeRef node) = 0; - - //! Remove animation node from sequence. - virtual void RemoveNode(IAnimNode* node, bool removeChildRelationships /*=true*/) = 0; - - // Finds node by name, can be slow. - // If the node belongs to a director, the director node also should be given - // since there can be multiple instances of the same node(i.e. the same name) - // across multiple director nodes. - virtual IAnimNode* FindNodeByName(const char* sNodeName, const IAnimNode* pParentDirector) = 0; - - //! Remove all nodes from sequence. - virtual void RemoveAll() = 0; - - // Activate sequence by binding sequence animations to nodes. - // must be called prior animating sequence. - virtual void Activate() = 0; - - /** Check if sequence is activated - */ - virtual bool IsActivated() const = 0; - - // Deactivates sequence by unbinding sequence animations from nodes. - virtual void Deactivate() = 0; - - // Pre-caches data associated with this anim sequence. - virtual void PrecacheData(float startTime = 0.0f) = 0; - - // Update sequence while not playing animation. - virtual void StillUpdate() = 0; - - // Render function call for some special node. - virtual void Render() = 0; - - // Evaluate animations of all nodes in sequence. - // Sequence must be activated before animating. - virtual void Animate(const SAnimContext& ec) = 0; - - //! Set time range of this sequence. - virtual void SetTimeRange(Range timeRange) = 0; - - //! Get time range of this sequence. - virtual Range GetTimeRange() = 0; - - //! Resets the sequence - virtual void Reset(bool bSeekToStart) = 0; - - //! This can have more time-consuming tasks performed additional to tasks of the usual 'Reset()' method. - virtual void ResetHard() = 0; - - // Called to pause sequence. - virtual void Pause() = 0; - - // Called to resume sequence. - virtual void Resume() = 0; - - /** Called to check if sequence is paused. - */ - virtual bool IsPaused() const = 0; - - /** Called when a sequence is looped. - */ - virtual void OnLoop() = 0; - - /** Move/Scale all keys in tracks from previous time range to new time range. - */ - virtual void AdjustKeysToTimeRange(const Range& timeRange) = 0; - - /** Called when time was explicitly jumped to/set. - */ - virtual void TimeChanged(float newTime) = 0; - - // fix up internal pointers after load from Sequence Component - virtual void InitPostLoad() = 0; - - // Copy some nodes of this sequence to XML. - virtual void CopyNodes(XmlNodeRef& xmlNode, IAnimNode** pSelectedNodes, uint32 count) = 0; - - // Paste nodes given by the XML to this sequence. - virtual void PasteNodes(const XmlNodeRef& xmlNode, IAnimNode* pParent) = 0; - - // Summary: - // Adds/removes track events in sequence. - virtual bool AddTrackEvent(const char* szEvent) = 0; - virtual bool RemoveTrackEvent(const char* szEvent) = 0; - virtual bool RenameTrackEvent(const char* szEvent, const char* szNewEvent) = 0; - virtual bool MoveUpTrackEvent(const char* szEvent) = 0; - virtual bool MoveDownTrackEvent(const char* szEvent) = 0; - virtual void ClearTrackEvents() = 0; - - // Summary: - // Gets the track events in the sequence. - virtual int GetTrackEventsCount() const = 0; - // Summary: - // Gets the specified track event in the sequence. - virtual char const* GetTrackEvent(int iIndex) const = 0; - - virtual IAnimStringTable* GetTrackEventStringTable() = 0; - - // Summary: - // Called to trigger a track event. - virtual void TriggerTrackEvent(const char* event, const char* param = NULL) = 0; - - //! Track event listener - virtual void AddTrackEventListener(ITrackEventListener* pListener) = 0; - virtual void RemoveTrackEventListener(ITrackEventListener* pListener) = 0; - - // return the sequence type - legacy or new component entity - virtual SequenceType GetSequenceType() const = 0; - - // Expanded state interface - virtual void SetExpanded(bool expanded) = 0; - virtual bool GetExpanded() const = 0; - - virtual unsigned int GetUniqueTrackIdAndGenerateNext() = 0; - - // </interfuscator:shuffle> -}; - -/** Movie Listener interface. - Register at movie system to get notified about movie events -*/ -struct IMovieListener -{ - enum EMovieEvent - { - eMovieEvent_Started = 0, // fired when sequence is started - eMovieEvent_Stopped, // fired when sequence ended normally - eMovieEvent_Aborted, // fired when sequence was aborted before normal end (STOP and ABORTED event are mutually exclusive!) - eMovieEvent_Updated, // fired after sequence time or playback speed was updated - eMovieEvent_RecordModeStarted, // fired when Record Mode is started - eMovieEvent_RecordModeStopped, // fired when Record Mode is stopped - }; - - // <interfuscator:shuffle> - virtual ~IMovieListener(){} - //! callback on movie events - virtual void OnMovieEvent(EMovieEvent movieEvent, IAnimSequence* pAnimSequence) = 0; - // </interfuscator:shuffle> - - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const{} -}; - -/** Movie System interface. - Main entrance point to engine movie capability. - Enumerate available movies, update all movies, create animation nodes and tracks. - */ -struct IMovieSystem -{ - AZ_RTTI(IMovieSystem, "{D8E6D6E9-830D-40DC-87F3-E9A069FBEB69}") - - enum ESequenceStopBehavior - { - eSSB_LeaveTime = 0, // When sequence is stopped it remains in last played time. - eSSB_GotoEndTime = 1, // Default behavior in game, sequence is animated at end time before stop. - eSSB_GotoStartTime = 2, // Default behavior in editor, sequence is animated at start time before stop. - }; - - // <interfuscator:shuffle> - virtual ~IMovieSystem(){} - - //! Release movie system. - virtual void Release() = 0; - //! Set the user. - virtual void SetUser(IMovieUser* pUser) = 0; - //! Get the user. - virtual IMovieUser* GetUser() = 0; - - virtual IAnimSequence* CreateSequence(const char* sequence, bool bLoad = false, uint32 id = 0, SequenceType = kSequenceTypeDefault, AZ::EntityId entityId = AZ::EntityId()) = 0; - virtual void AddSequence(IAnimSequence* sequence) = 0; - virtual void RemoveSequence(IAnimSequence* sequence) = 0; - virtual IAnimSequence* FindLegacySequenceByName(const char* sequence) const = 0; - virtual IAnimSequence* FindSequence(const AZ::EntityId& componentEntitySequenceId) const = 0; - virtual IAnimSequence* FindSequenceById(uint32 id) const = 0; - virtual IAnimSequence* GetSequence(int i) const = 0; - virtual int GetNumSequences() const = 0; - virtual IAnimSequence* GetPlayingSequence(int i) const = 0; - virtual int GetNumPlayingSequences() const = 0; - virtual bool IsCutScenePlaying() const = 0; - - virtual uint32 GrabNextSequenceId() = 0; - // called whenever a new sequence Id is set - to update nextSequenceId - virtual void OnSetSequenceId(uint32 sequenceId) = 0; - ////////////////////////////////////////////////////////////////////////// - // - // If the name of a sequence changes, the keys that refer it in the - // sequence track of the director node should be properly updated also. - // - // @param before The old name of the sequence. - // @param after The new name of the sequence. - // @return Number of modified sequence keys. - // - ////////////////////////////////////////////////////////////////////////// - virtual int OnSequenceRenamed(const char* before, const char* after) = 0; - ////////////////////////////////////////////////////////////////////////// - // - // If the name of a camera changes, the keys that refer it in the - // camera track of the director node should be properly updated also. - // This updates the name of the corresponding camera node also, if any. - // - // @param before The old name of the camera. - // @param after The new name of the camera. - // @return Number of modified camera keys. - // - ////////////////////////////////////////////////////////////////////////// - virtual int OnCameraRenamed(const char* before, const char* after) = 0; - - // Adds a listener to a sequence - // @param sequence Pointer to sequence - // @param pListener Pointer to an IMovieListener - // @return true on successful add, false otherwise - virtual bool AddMovieListener(IAnimSequence* sequence, IMovieListener* pListener) = 0; - - // Removes a listener from a sequence - // @param sequence Pointer to sequence - // @param pListener Pointer to an IMovieListener - // @return true on successful removal, false otherwise - virtual bool RemoveMovieListener(IAnimSequence* sequence, IMovieListener* pListener) = 0; - - virtual ISystem* GetSystem() = 0; - - // Remove all sequences from movie system. - virtual void RemoveAllSequences() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Sequence playback. - ////////////////////////////////////////////////////////////////////////// - // Start playing sequence. - // Call ignored if sequence is already playing. - // @param sequence Name of sequence to play. - virtual void PlaySequence(const char* pSequenceName, IAnimSequence* pParentSeq, bool bResetFX, bool bTrackedSequence, float startTime = -FLT_MAX, float endTime = -FLT_MAX) = 0; - - // Start playing sequence. - // Call ignored if sequence is already playing. - // @param sequence Pointer to Valid sequence to play. - virtual void PlaySequence(IAnimSequence* sequence, IAnimSequence* pParentSeq, bool bResetFX, bool bTrackedSequence, float startTime = -FLT_MAX, float endTime = -FLT_MAX) = 0; - - // Stops currently playing sequence. - // Ignored if sequence is not playing. - // Returns true if sequence has been stopped. false otherwise - // @param sequence Name of playing sequence to stop. - virtual bool StopSequence(const char* pSequenceName) = 0; - - // Stop's currently playing sequence. - // Ignored if sequence is not playing. - // Returns true if sequence has been stopped. false otherwise - // @param sequence Pointer to Valid sequence to stop. - virtual bool StopSequence(IAnimSequence* sequence) = 0; - - /** Aborts a currently playing sequence. - Ignored if sequence is not playing. - Calls IMovieListener with MOVIE_EVENT_ABORTED event (MOVIE_EVENT_DONE is NOT called) - Returns true if sequence has been aborted. false otherwise - @param sequence Pointer to Valid sequence to stop. - @param bLeaveTime If false, uses default stop behavior, otherwise leaves the sequence at time - */ - virtual bool AbortSequence(IAnimSequence* sequence, bool bLeaveTime = false) = 0; - - // Stops all currently playing sequences. - virtual void StopAllSequences() = 0; - - // Stops all playing cut-scene sequences. - // This will not stop all sequences, but only those with CUT_SCENE flag set. - virtual void StopAllCutScenes() = 0; - - // Checks if specified sequence is playing. - virtual bool IsPlaying(IAnimSequence* seq) const = 0; - - /** Resets playback state of movie system, - usually called after loading of level, - */ - virtual void Reset(bool bPlayOnReset, bool bSeekToStart) = 0; - - // Sequences with PLAY_ONRESET flag will start playing after this call. - virtual void PlayOnLoadSequences() = 0; - - // Update movie system while not playing animation. - virtual void StillUpdate() = 0; - - // Updates movie system every frame before the entity system to animate all playing sequences. - virtual void PreUpdate(const float dt) = 0; - - // Updates movie system every frame after the entity system to animate all playing sequences. - virtual void PostUpdate(const float dt) = 0; - - // Render function call of some special node. - virtual void Render() = 0; - - // Set and enable Fixed Step cvars - virtual void EnableFixedStepForCapture(float step) = 0; - - // Disable Fixed Step cvars and return to previous settings - virtual void DisableFixedStepForCapture() = 0; - - // Signal the capturing start. - virtual void StartCapture(const ICaptureKey& key, int frame) = 0; - - // Signal the capturing end. - virtual void EndCapture() = 0; - - // Actually turn on/off the capturing. - // This is needed for the timing issue of turning on/off the capturing. - virtual void ControlCapture() = 0; - - // Returns true if a Render Output capture is currently active. - virtual bool IsCapturing() const = 0; - - // Set movie system into recording mode, - // While in recording mode any changes made to node will be added as keys to tracks. - virtual void SetRecording(bool recording) = 0; - virtual bool IsRecording() const = 0; - - virtual void EnableCameraShake(bool bEnabled) = 0; - virtual bool IsCameraShakeEnabled() const = 0; - - // Pause any playing sequences. - virtual void Pause() = 0; - - // Resume playing sequences. - virtual void Resume() = 0; - - // Pause cut scenes in editor. - virtual void PauseCutScenes() = 0; - - // Resume cut scenes in editor. - virtual void ResumeCutScenes() = 0; - - // Callback when animation-data changes - virtual void SetCallback(IMovieCallback* pCallback) = 0; - - virtual IMovieCallback* GetCallback() = 0; - - virtual const SCameraParams& GetCameraParams() const = 0; - virtual void SetCameraParams(const SCameraParams& Params) = 0; - virtual void SendGlobalEvent(const char* pszEvent) = 0; - - // Gets the float time value for a sequence that is already playing - virtual float GetPlayingTime(IAnimSequence* pSeq) = 0; - virtual float GetPlayingSpeed(IAnimSequence* pSeq) = 0; - // Sets the time progression of an already playing cutscene. - // If IAnimSequence:NO_SEEK flag is set on pSeq, this call is ignored. - virtual bool SetPlayingTime(IAnimSequence* pSeq, float fTime) = 0; - virtual bool SetPlayingSpeed(IAnimSequence* pSeq, float fSpeed) = 0; - // Set behavior pattern for stopping sequences. - virtual void SetSequenceStopBehavior(ESequenceStopBehavior behavior) = 0; - - // Set the start and end time of an already playing cutscene. - virtual bool GetStartEndTime(IAnimSequence* pSeq, float& fStartTime, float& fEndTime) = 0; - virtual bool SetStartEndTime(IAnimSequence* pSeq, const float fStartTime, const float fEndTime) = 0; - - // Make the specified sequence go to a given frame time. - // @param seqName A sequence name. - // @param targetFrame A target frame to go to in time. - virtual void GoToFrame(const char* seqName, float targetFrame) = 0; - - // Get the name of camera used for sequences instead of cameras specified in the director node. - virtual const char* GetOverrideCamName() const = 0; - - // Get behavior pattern for stopping sequences. - virtual IMovieSystem::ESequenceStopBehavior GetSequenceStopBehavior() = 0; - - // These are used to disable 'Ragdollize' events in the editor when the 'AI/Physics' is off. - virtual bool IsPhysicsEventsEnabled() const = 0; - virtual void EnablePhysicsEvents(bool enable) = 0; - - virtual void EnableBatchRenderMode(bool bOn) = 0; - virtual bool IsInBatchRenderMode() const = 0; - - virtual ILightAnimWrapper* CreateLightAnimWrapper(const char* name) const = 0; - - virtual void LoadParamTypeFromXml(CAnimParamType& animParamType, const XmlNodeRef& xmlNode, const uint version) = 0; - virtual void SaveParamTypeToXml(const CAnimParamType& animParamType, XmlNodeRef& xmlNode) = 0; - - // Should only be called from CAnimParamType - virtual void SerializeParamType(CAnimParamType& animParamType, XmlNodeRef& xmlNode, bool bLoading, const uint version) = 0; - - // For buffering and presenting user notification messages in the Editor. Will also print as an AZ_Warning() - virtual void LogUserNotificationMsg(const AZStd::string& msg) = 0; - virtual void ClearUserNotificationMsgs() = 0; - virtual const AZStd::string& GetUserNotificationMsgs() const = 0; - - // Call this from OnActivate() when a new sequence component entity is activated. - virtual void OnSequenceActivated(IAnimSequence* sequence) = 0; - -#ifdef MOVIESYSTEM_SUPPORT_EDITING - virtual AnimNodeType GetNodeTypeFromString(const char* pString) const = 0; - virtual CAnimParamType GetParamTypeFromString(const char* pString) const = 0; -#endif - - // fill in the animNodeType from the xmlNode description (or vice versa) - virtual void SerializeNodeType(AnimNodeType& animNodeType, XmlNodeRef& xmlNode, bool bLoading, const uint version, int flags) = 0; - - // </interfuscator:shuffle> -}; - -inline void SAnimContext::Serialize(XmlNodeRef& xmlNode, bool bLoading) -{ - if (bLoading) - { - XmlString name; - if (xmlNode->getAttr("sequence", name)) - { - sequence = gEnv->pMovieSystem->FindLegacySequenceByName(name.c_str()); - } - xmlNode->getAttr("dt", dt); - xmlNode->getAttr("fps", fps); - xmlNode->getAttr("time", time); - xmlNode->getAttr("bSingleFrame", singleFrame); - xmlNode->getAttr("bResetting", resetting); - xmlNode->getAttr("trackMask", trackMask); - xmlNode->getAttr("startTime", startTime); - } - else - { - if (sequence) - { - string fullname = sequence->GetName(); - xmlNode->setAttr("sequence", fullname.c_str()); - } - xmlNode->setAttr("dt", dt); - xmlNode->setAttr("fps", fps); - xmlNode->setAttr("time", time); - xmlNode->setAttr("bSingleFrame", singleFrame); - xmlNode->setAttr("bResetting", resetting); - xmlNode->setAttr("trackMask", trackMask); - xmlNode->setAttr("startTime", startTime); - } -} - -inline void CAnimParamType::SaveToXml(XmlNodeRef& xmlNode) const -{ - gEnv->pMovieSystem->SaveParamTypeToXml(*this, xmlNode); -} - -inline void CAnimParamType::LoadFromXml(const XmlNodeRef& xmlNode, const uint version) -{ - gEnv->pMovieSystem->LoadParamTypeFromXml(*this, xmlNode, version); -} - -inline void CAnimParamType::Serialize(XmlNodeRef& xmlNode, bool bLoading, const uint version) -{ - gEnv->pMovieSystem->SerializeParamType(*this, xmlNode, bLoading, version); -} - -#endif // CRYINCLUDE_CRYCOMMON_IMOVIESYSTEM_H diff --git a/Code/CryEngine/CryCommon/INavigationSystem.h b/Code/CryEngine/CryCommon/INavigationSystem.h deleted file mode 100644 index 9d04a87132..0000000000 --- a/Code/CryEngine/CryCommon/INavigationSystem.h +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_INAVIGATIONSYSTEM_H -#define CRYINCLUDE_CRYCOMMON_INAVIGATIONSYSTEM_H -#pragma once - -#include <AzCore/std/functional.h> - -#include <IMNM.h> -#include <physinterface.h> - -struct IOffMeshNavigationManager; - -enum ENavigationIDTag -{ - MeshIDTag = 0, - AgentTypeIDTag, - VolumeIDTag, -}; - -template <ENavigationIDTag T> -struct TNavigationID -{ - explicit TNavigationID(uint32 _id = 0) - : id(_id) {} - - TNavigationID& operator=(const TNavigationID& other) { id = other.id; return *this; } - - ILINE operator uint32() const { return id; } - ILINE bool operator==(const TNavigationID& other) const { return id == other.id; } - ILINE bool operator!=(const TNavigationID& other) const { return id != other.id; } - ILINE bool operator<(const TNavigationID& other) const { return id < other.id; } - -private: - uint32 id; -}; - - -typedef TNavigationID<MeshIDTag> NavigationMeshID; -typedef TNavigationID<AgentTypeIDTag> NavigationAgentTypeID; -typedef TNavigationID<VolumeIDTag> NavigationVolumeID; -typedef AZStd::function<void(NavigationAgentTypeID, NavigationMeshID, uint32)> NavigationMeshChangeCallback; -typedef AZStd::function<bool(IPhysicalEntity&, uint32&)> NavigationMeshEntityCallback; - -struct INavigationSystemUser -{ - virtual ~INavigationSystemUser() {} - - virtual void Reset() = 0; - virtual void UpdateForSynchronousOrAsynchronousReadingOperation() = 0; - virtual void UpdateForSynchronousWritingOperations() = 0; - virtual void CompleteRunningTasks() = 0; -}; - -struct INavigationSystem -{ - enum ENavigationEvent - { - MeshReloaded = 0, - MeshReloadedAfterExporting, - NavigationCleared, - }; - - enum EAccessbilityDir - { - AccessibilityToward, - AccessibilityAway, - }; - - struct INavigationSystemListener - { - // <interfuscator:shuffle> - virtual ~INavigationSystemListener(){} - virtual void OnNavigationEvent(const ENavigationEvent event) = 0; - // </interfuscator:shuffle> - }; - - enum WorkingState - { - Idle = 0, - Working, - }; - - - struct CreateAgentTypeParams - { - CreateAgentTypeParams(const Vec3& _voxelSize = Vec3(0.1f), uint16 _radiusVoxelCount = 4, - uint16 _climbableVoxelCount = 4, uint16 _heightVoxelCount = 18, - [[maybe_unused]] uint16 _maxWaterDepthVoxelCount = 6) - : voxelSize(_voxelSize) - , climbableInclineGradient(1.0f) - , climbableStepRatio(0.75f) - , radiusVoxelCount(_radiusVoxelCount) - , climbableVoxelCount(_climbableVoxelCount) - , heightVoxelCount(_heightVoxelCount) - , maxWaterDepthVoxelCount() - { - } - - Vec3 voxelSize; - - float climbableInclineGradient; - float climbableStepRatio; - - uint16 radiusVoxelCount; - uint16 climbableVoxelCount; - uint16 heightVoxelCount; - uint16 maxWaterDepthVoxelCount; - }; - - struct CreateMeshParams - { - CreateMeshParams(const Vec3& _origin = Vec3(ZERO), const Vec3i& _tileSize = Vec3i(8), const uint32 _tileCount = 1024) - : origin(_origin) - , tileSize(_tileSize) - , tileCount(_tileCount) - { - } - - Vec3 origin; - Vec3i tileSize; - uint32 tileCount; - }; - - // <interfuscator:shuffle> - virtual ~INavigationSystem() {} - virtual NavigationAgentTypeID CreateAgentType(const char* name, const CreateAgentTypeParams& params) = 0; - virtual NavigationAgentTypeID GetAgentTypeID(const char* name) const = 0; - virtual NavigationAgentTypeID GetAgentTypeID(size_t index) const = 0; - virtual const char* GetAgentTypeName(NavigationAgentTypeID agentTypeID) const = 0; - virtual size_t GetAgentTypeCount() const = 0; - - virtual NavigationMeshID CreateMesh(const char* name, NavigationAgentTypeID agentTypeID, const CreateMeshParams& params) = 0; - virtual NavigationMeshID CreateMesh(const char* name, NavigationAgentTypeID agentTypeID, const CreateMeshParams& params, NavigationMeshID requestedID) = 0; - virtual void DestroyMesh(NavigationMeshID meshID) = 0; - - virtual void SetMeshEntityCallback(NavigationAgentTypeID agentTypeID, const NavigationMeshEntityCallback& callback) = 0; - virtual void AddMeshChangeCallback(NavigationAgentTypeID agentTypeID, const NavigationMeshChangeCallback& callback) = 0; - virtual void RemoveMeshChangeCallback(NavigationAgentTypeID agentTypeID, const NavigationMeshChangeCallback& callback) = 0; - - virtual void SetMeshBoundaryVolume(NavigationMeshID meshID, NavigationVolumeID volumeID) = 0; - virtual NavigationVolumeID CreateVolume(Vec3* vertices, size_t vertexCount, float height) = 0; - virtual NavigationVolumeID CreateVolume(Vec3* vertices, size_t vertexCount, float height, NavigationVolumeID requestedID) = 0; - virtual void DestroyVolume(NavigationVolumeID volumeID) = 0; - virtual void SetVolume(NavigationVolumeID volumeID, Vec3* vertices, size_t vertexCount, float height) = 0; - virtual bool ValidateVolume(NavigationVolumeID volumeID) = 0; - virtual NavigationVolumeID GetVolumeID(NavigationMeshID meshID) = 0; - - virtual void SetExclusionVolume(const NavigationAgentTypeID* agentTypeIDs, size_t agentTypeIDCount, NavigationVolumeID volumeID) = 0; - - virtual NavigationMeshID GetMeshID(const char* name, NavigationAgentTypeID agentTypeID) const = 0; - virtual const char* GetMeshName(NavigationMeshID meshID) const = 0; - virtual void SetMeshName(NavigationMeshID meshID, const char* name) = 0; - - virtual WorkingState GetState() const = 0; - virtual WorkingState Update(bool blocking = false) = 0; - virtual void PauseNavigationUpdate() = 0; - virtual void RestartNavigationUpdate() = 0; - - virtual size_t QueueMeshUpdate(NavigationMeshID meshID, const AABB& aabb) = 0; - virtual void ProcessQueuedMeshUpdates() = 0; - - virtual void Clear() = 0; - // ClearAndNotify it's used when the listeners need to be notified about - // the performed clear operation. - virtual void ClearAndNotify() = 0; - virtual bool ReloadConfig() = 0; - virtual void DebugDraw() = 0; - virtual void Reset() = 0; - - virtual void WorldChanged(const AABB& aabb) = 0; - - virtual void SetDebugDisplayAgentType(NavigationAgentTypeID agentTypeID) = 0; - virtual NavigationAgentTypeID GetDebugDisplayAgentType() const = 0; - - //Returns impact mesh ID and point if segment intersects - virtual std::tuple<bool, NavigationMeshID, Vec3> RaycastWorld(const Vec3& segP0, const Vec3& segP1) const = 0; - - virtual bool GetClosestPointInNavigationMesh(const NavigationAgentTypeID agentID, const Vec3& location, float vrange, float hrange, Vec3* meshLocation, float minIslandArea = 0.f) const = 0; - - //Returns nav mesh ID at the specified location based on the passed in agent type - virtual NavigationMeshID GetEnclosingMeshID(NavigationAgentTypeID agentTypeID, const Vec3& location) const = 0; - - virtual bool IsLocationValidInNavigationMesh(const NavigationAgentTypeID agentID, const Vec3& location) const = 0; - - //Test to see if the specified location is within the navmesh. The point has to be weithin downRange and upRange offset from location - virtual bool IsLocationContainedWithinTriangleInNavigationMesh(const NavigationAgentTypeID agentID, const Vec3& location, float downRange, float upRange) const = 0; - - //Returns a list of triangle centers within the specified AABB and navmesh - virtual size_t GetTriangleCenterLocationsInMesh(const NavigationMeshID meshID, const Vec3& location, const AABB& searchAABB, Vec3* centerLocations, size_t maxCenterLocationCount, float minIslandArea = 0.f) const = 0; - - // Returns all borders (unconnected edges) in the specified AABB. There are 3 Vec3's - // per border edge, vert 0, vert 1, and a normal pointing out from the edge. You can - // pass null for pBorders to return the total number of borders (multiply this by 3 to - // get the total number of Vec3's you need to pass in). - virtual size_t GetTriangleBorders(const NavigationMeshID meshID, const AABB& aabb, Vec3* pBorders, size_t maxBorderCount, float minIslandArea = 0.f) const = 0; - - //For Hunt - gets triangle centers, and island ids - this is used to compute spawn points for an area - virtual size_t GetTriangleInfo(const NavigationMeshID meshID, const AABB& aabb, Vec3* centerLocations, uint32* islandids, size_t max_count, float minIslandArea = 0.f) const = 0; - - //returns island id of the triangle at the current position - virtual MNM::GlobalIslandID GetGlobalIslandIdAtPosition(const NavigationAgentTypeID agentID, const Vec3& location) = 0; - - virtual bool ReadFromFile(const char* fileName, bool bAfterExporting) = 0; - virtual bool SaveToFile(const char* fileName) const = 0; - - virtual void RegisterListener(INavigationSystemListener* pListener, const char* name = NULL) = 0; - virtual void UnRegisterListener(INavigationSystemListener* pListener) = 0; - - virtual void RegisterUser(INavigationSystemUser* pExtension, const char* name = NULL) = 0; - virtual void UnRegisterUser(INavigationSystemUser* pExtension) = 0; - - virtual void RegisterArea(const char* shapeName) = 0; - virtual void UnRegisterArea(const char* shapeName) = 0; - virtual bool IsAreaPresent(const char* shapeName) = 0; - virtual NavigationVolumeID GetAreaId(const char* shapeName) const = 0; - virtual void SetAreaId(const char* shapeName, NavigationVolumeID id) = 0; - virtual void UpdateAreaNameForId(const NavigationVolumeID id, const char* newShapeName) = 0; - - virtual void StartWorldMonitoring() = 0; - virtual void StopWorldMonitoring() = 0; - - virtual bool IsInUse() const = 0; - - virtual void CalculateAccessibility() = 0; - - virtual uint32 GetTileIdWhereLocationIsAtForMesh(NavigationMeshID meshID, const Vec3& location) = 0; - virtual void GetTileBoundsForMesh(NavigationMeshID meshID, uint32 tileID, AABB& bounds) const = 0; - - virtual MNM::TriangleID GetTriangleIDWhereLocationIsAtForMesh(const NavigationAgentTypeID agentID, const Vec3& location) = 0; - - virtual const IOffMeshNavigationManager& GetIOffMeshNavigationManager() const = 0; - virtual IOffMeshNavigationManager& GetIOffMeshNavigationManager() = 0; - virtual void ComputeAccessibility(const Vec3& seedPos, NavigationAgentTypeID agentTypeId = NavigationAgentTypeID(0), float range = 0.f, EAccessbilityDir dir = AccessibilityAway) = 0; - virtual bool TryGetAgentRadiusData(const char* agentType, Vec3& voxelSize, uint16& radiusInVoxels) const = 0; - // </interfuscator:shuffle> -}; - - - -#endif // CRYINCLUDE_CRYCOMMON_INAVIGATIONSYSTEM_H diff --git a/Code/CryEngine/CryCommon/IPathfinder.h b/Code/CryEngine/CryCommon/IPathfinder.h deleted file mode 100644 index 6678470be2..0000000000 --- a/Code/CryEngine/CryCommon/IPathfinder.h +++ /dev/null @@ -1,753 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Pathfinder Interface. - -#pragma once - -struct IAIPathAgent; - -#include <INavigationSystem.h> -#include <IMNM.h> -#include <ISerialize.h> -#include <SerializeFwd.h> -#include <Cry_Geo.h> - -#include <AzCore/std/functional.h> -#include <AzCore/std/smart_ptr/shared_ptr.h> -#include <limits> - -// Hacks to deal with windows header inclusion. -#ifdef GetObject -#undef GetObject -#endif -#ifdef GetUserName -#undef GetUserName -#endif -#ifdef DrawText -#undef DrawText -#endif -#ifdef LoadLibrary -#undef LoadLibrary -#endif -#ifdef max -#undef max -#endif - -/* WARNING: These interfaces and structures are soon to be deprecated. - Use at your own risk of having to change your code later! -*/ - - -// Passing through navigational SO methods. -enum ENavSOMethod -{ - nSOmNone, // not passing or not passable - nSOmAction, // execute an AI action - nSOmPriorityAction, // execute a higher priority AI action - nSOmStraight, // just pass straight - nSOmSignalAnimation, // play signal animation - nSOmActionAnimation, // play action animation - nSOmLast -}; - -// Indication of (a) what a graph node represents and (b) what kind of graph node an AI entity -// can navigate. In the latter case it can be used as a bit mask. -// Copied from CryCommon/IAISystem.h which has been deleted. -enum ENavigationType -{ - NAV_UNSET = 1 << 0, - NAV_TRIANGULAR = 1 << 1, - NAV_WAYPOINT_HUMAN = 1 << 2, - NAV_WAYPOINT_3DSURFACE = 1 << 3, - NAV_FLIGHT = 1 << 4, - NAV_VOLUME = 1 << 5, - NAV_ROAD = 1 << 6, - NAV_SMARTOBJECT = 1 << 7, - NAV_FREE_2D = 1 << 8, - NAV_CUSTOM_NAVIGATION = 1 << 9, - NAV_MAX_VALUE = NAV_CUSTOM_NAVIGATION -}; - -//==================================================================== -// NavigationBlocker -// Represents an object that might be blocking a link. Each blocker is -// assumed to be spherical, with the position centred around the floor -// so that links can intersect it. -//==================================================================== -struct NavigationBlocker -{ - /// pos and radius define the sphere. - /// costAddMod is a fixed cost (in m) associated with the blocker obscuring a link - a value of 0 has - /// no effect - a value of 10 would make the link effectively 10m longer than it is. - /// costMultMod is the cost modification factor - a value of 0 has no effect - a value of 10 would make the link - /// 10x more costly. -ve disables the link - /// radialDecay indicates if the cost modifiers should decay linearly to 0 over the radius of the sphere - /// directional indicates if the cost should be unaffected for motion in a radial direction - NavigationBlocker(const Vec3& pos, float radius, float _costAddMod, float _costMultMod, bool _radialDecay, bool _directional) - : sphere(pos, radius) - , costAddMod(_costAddMod) - , costMultMod(_costMultMod) - , restrictedLocation(false) - , radialDecay(_radialDecay) - , directional(_directional) {} - - /// Just to allow std::vector::resize(0) - NavigationBlocker() - : sphere(Vec3(0, 0, 0), 0.0f) - , costAddMod(0) - , costMultMod(0) - , radialDecay(false) {AZ_Assert(false, "Should never get called"); } - - ::Sphere sphere; - bool radialDecay; - bool directional; - - /// absolute cost added to any link going through this blocker (useful for small blockers) - float costAddMod; - /// multiplier for link costs going through this blocker (0 means no extra cost, 1 means to double etc) - float costMultMod; - - // info to speed up the intersection checks - /// If this is true then the blocker is small enough that it only affects the - /// nav type it resides in. If false then it affects everything. - bool restrictedLocation; - ENavigationType navType; - union Location - { - struct // similar for other nav types when there's info to go in them - { - // no node because the node "areas" can overlap so it's not useful - int nBuildingID; - } waypoint; - }; - /// Only gets used if restrictedLocation = true - Location location; -}; - -typedef DynArray<NavigationBlocker> NavigationBlockers; - - -//==================================================================== -// PathPointDescriptor -//==================================================================== -struct PathPointDescriptor -{ - struct SmartObjectNavData - : public _i_reference_target_t - { - unsigned fromIndex; - unsigned toIndex; - }; - typedef _smart_ptr< SmartObjectNavData > SmartObjectNavDataPtr; - - struct OffMeshLinkData - { - OffMeshLinkData() - : meshID(0) - , offMeshLinkID(0) - {} - - uint32 meshID; - MNM::OffMeshLinkID offMeshLinkID; - }; - - PathPointDescriptor(ENavigationType _navType = NAV_UNSET, const Vec3& _vPos = ZERO) - : vPos(_vPos) - , navType(_navType) - , navTypeCustomId(0) - , iTriId(0) - , pSONavData(0) - , navSOMethod(nSOmNone) - {} - - PathPointDescriptor(const Vec3& _vPos) - : vPos(_vPos) - , navType(NAV_UNSET) - , navTypeCustomId(0) - , iTriId(0) - , pSONavData(0) - , navSOMethod(nSOmNone) - {} - - bool IsEquivalent(const PathPointDescriptor& other) const - { - return (navType == other.navType) && vPos.IsEquivalent(other.vPos, 0.01f); - } - - static bool ArePointsEquivalent(const PathPointDescriptor& point1, const PathPointDescriptor& point2) - { - return point1.IsEquivalent(point2); - } - - Vec3 vPos; - ENavigationType navType; - uint16 navTypeCustomId; - - uint32 iTriId; - OffMeshLinkData offMeshLinkData; - - SmartObjectNavDataPtr pSONavData; - - ENavSOMethod navSOMethod; -}; - -struct PathfindingExtraConstraint -{ - enum EExtraConstraintType - { - ECT_MAXCOST, - ECT_MINDISTFROMPOINT, - ECT_AVOIDSPHERE, - ECT_AVOIDCAPSULE - }; - - EExtraConstraintType type; - - union UConstraint - { - struct SConstraintMaxCost - { - float maxCost; - }; - struct SConstraintMinDistFromPoint - { - float px, py, pz; // Can't use Vec3 as it has a constructor. - float minDistSq; - }; - struct SConstraintAvoidSphere - { - float px, py, pz; // Can't use Vec3 as it has a constructor. - float minDistSq; - }; - struct SConstraintAvoidCapsule - { - float px, py, pz; - float qx, qy, qz; - float minDistSq; - }; - SConstraintMaxCost maxCost; - SConstraintMinDistFromPoint minDistFromPoint; - SConstraintAvoidSphere avoidSphere; - SConstraintAvoidCapsule avoidCapsule; - }; - UConstraint constraint; -}; - -typedef DynArray<PathfindingExtraConstraint> PathfindingExtraConstraints; - - -struct PathfindRequest -{ - enum ERequestType - { - TYPE_ACTOR, - TYPE_RAW, - }; - ERequestType type; - - unsigned startIndex; - unsigned endIndex; - Vec3 startPos; - Vec3 startDir; - Vec3 endPos; - /// endDir magnitude indicates the tendency to line up at the end of the path - - /// magnitude should be between 0 and 1 - Vec3 endDir; - bool bSuccess; - IAIPathAgent* pRequester; - int nForceTargetBuildingId; - bool allowDangerousDestination; - float endTol; - float endDistance; - // as a result of RequestPathInDirection or RequestPathTo - bool isDirectional; - - /// This gets set to false if the path end position doesn't match the requested end position - /// (e.g. in the event of a partial path, or if the destination is in forbidden) - bool bPathEndIsAsRequested; - - int id; - float passRadius; - - PathfindingExtraConstraints extraConstraints; - - PathfindRequest(ERequestType _type) - : type(_type) - , startIndex(0) - , endIndex(0) - , pRequester(0) - , bPathEndIsAsRequested(false) - , allowDangerousDestination(false) - , endTol(std::numeric_limits<float>::max()) - , endDistance(0) - , nForceTargetBuildingId(-1) - , isDirectional(false) - , id(-1) - , passRadius(0.0f) - { - } -}; - -struct PathFollowerParams -{ - PathFollowerParams() - : normalSpeed(0.0f) - , pathRadius(0.0f) - , pathLookAheadDist(1.0f) - , maxAccel(0.0f) - , maxDecel(1.0f) - , minSpeed(0.0f) - , maxSpeed(10.0f) - , endAccuracy(0.2f) - , endDistance(0.0f) - , stopAtEnd(true) - , use2D(true) - , isVehicle(false) - , isAllowedToShortcut(true) - , passRadius(0.5f) - {} - - // OLD: Remove this when possible, Animation to take over majority of logic - float normalSpeed; ///< normal entity speed - float pathRadius; ///< max deviation allowed from the path - float pathLookAheadDist; ///< how far we look ahead along the path - normally the same as pathRadius - float maxAccel; ///< maximum acceleration of the entity - float maxDecel; ///< maximum deceleration of the entity - float minSpeed; ///< minimum output speed (unless it's zero on path end etc) - float maxSpeed; ///< maximum output speed - - // KEEP: Additions and useful state for new impl. - float endAccuracy; ///< How close to the end point the agent must be to finish pathing - float endDistance; ///< stop this much before the end - bool stopAtEnd; ///< aim to finish the path by reaching the end position (stationary), or simply overshoot - bool use2D; ///< follow in 2 or 3D - bool isVehicle; - bool isAllowedToShortcut; - - /// The minimum radius of the agent for navigating - float passRadius; -}; - - -struct PathFollowResult -{ - struct SPredictedState - { - SPredictedState() {} - SPredictedState(const Vec3& p, const Vec3& v) - : pos(p) - , vel(v) {} - Vec3 pos; - Vec3 vel; - }; - typedef AZStd::vector<SPredictedState, AZ::StdLegacyAllocator> TPredictedStates; - - // OLD: Obsolete & to be replaced by new impl. - - /// maximum time to predict out to - actual prediction may not go this far - float desiredPredictionTime; - /// the first element in predictedStates will be now + predictionDeltaTime, etc - float predictionDeltaTime; - /// if this is non-zero then on output the prediction will be placed into it - TPredictedStates* predictedStates; - - PathFollowResult() - : predictionDeltaTime(0.1f) - , predictedStates(0) - , desiredPredictionTime(0) - , distanceToEnd(0.f) - , reachedEnd(false) - , followTargetPos(0) - , inflectionPoint(0) {} - - - float distanceToEnd; - bool reachedEnd; - Vec3 velocityOut; - - // NEW: Replaces data above - - // NOTE: If the turningPoint and inflectionPoint are equal, they represent the end of the path. - /// The furthest point on the path we can move directly towards without colliding with anything - Vec3 followTargetPos; - /// The next point on the path beyond the follow target that deviates substantially from a straight-line path - Vec3 inflectionPoint; - - /// The maximum distance the agent can safely move in a straight line beyond the turning point - // float maxOverrunDistance; -}; - - - -// Intermediary and minimal interface to use the pathfinder without requiring an AI object -// TODO: Fix the long function names. At the moment they collide with IAIObject base. -// The alternative would be to make IAIObject derive from IAIPathAgent. -struct IAIPathAgent -{ - virtual ~IAIPathAgent(){} - virtual const char* GetPathAgentName() const = 0; - virtual unsigned short GetPathAgentType() const = 0; - - virtual float GetPathAgentPassRadius() const = 0; - virtual Vec3 GetPathAgentPos() const = 0; - virtual Vec3 GetPathAgentVelocity() const = 0; - - // This cannot easily be const, but has no side-effects - virtual void GetPathAgentNavigationBlockers(NavigationBlockers& blockers, const PathfindRequest* pRequest) = 0; - - virtual void SetPathToFollow(const char* pathName) = 0; - virtual void SetPathAttributeToFollow(bool bSpline) = 0; - - //Path finding avoids blocker type by radius. - virtual void SetPFBlockerRadius(int blockerType, float radius) = 0; - - virtual bool GetValidPositionNearby(const Vec3& proposedPosition, Vec3& adjustedPosition) const = 0; - virtual bool GetTeleportPosition(Vec3& teleportPos) const = 0; - - virtual class IPathFollower* GetPathFollower() const = 0; - - virtual bool IsPointValidForAgent(const Vec3& pos, uint32 flags) const = 0; -}; - -typedef std::list<PathPointDescriptor> TPathPoints; - -struct SNavPathParams -{ - SNavPathParams(const Vec3& _start = Vec3_Zero, const Vec3& _end = Vec3_Zero, - const Vec3& _startDir = Vec3_Zero, const Vec3& _endDir = Vec3_Zero, - int _nForceBuildingID = -1, bool _allowDangerousDestination = false, float _endDistance = 0.0f, - bool _continueMovingAtEnd = false, bool _isDirectional = false) - : start(_start) - , end(_end) - , startDir(_startDir) - , endDir(_endDir) - , nForceBuildingID(_nForceBuildingID) - , allowDangerousDestination(_allowDangerousDestination) - , precalculatedPath(false) - , inhibitPathRegeneration(false) - , continueMovingAtEnd(_continueMovingAtEnd) - , endDistance(_endDistance) - , isDirectional(_isDirectional) - {} - - Vec3 start; - Vec3 end; - Vec3 startDir; - Vec3 endDir; - int nForceBuildingID; - bool allowDangerousDestination; - /// if path is precalculated it should not be regenerated, and also some things like steering - /// will be disabled - bool precalculatedPath; - /// sometimes it is necessary to disable a normal path from getting regenerated - bool inhibitPathRegeneration; - bool continueMovingAtEnd; - bool isDirectional; - float endDistance; // The requested cut distance of the path, positive value means distance from path end, negative value means distance from path start. - NavigationMeshID meshID; - - void Clear() - { - start = Vec3_Zero; - end = Vec3_Zero; - startDir = Vec3_Zero; - endDir = Vec3_Zero; - allowDangerousDestination = false; - precalculatedPath = false; - inhibitPathRegeneration = false; - continueMovingAtEnd = false; - isDirectional = false; - endDistance = 0.0f; - meshID = NavigationMeshID(0); - } - - void Serialize(TSerialize ser) - { - ser.Value("start", start); - ser.Value("end", end); - ser.Value("startDir", startDir); - ser.Value("endDir", endDir); - ser.Value("nForceBuildingID", nForceBuildingID); - ser.Value("allowDangerousDestination", allowDangerousDestination); - ser.Value("precalculatedPath", precalculatedPath); - ser.Value("inhibitPathRegeneration", inhibitPathRegeneration); - ser.Value("continueMovingAtEnd", continueMovingAtEnd); - ser.Value("isDirectional", isDirectional); - ser.Value("endDistance", endDistance); - - if (ser.IsReading()) - { - uint32 meshIdAsUint32; - ser.Value("meshID", meshIdAsUint32); - meshID = NavigationMeshID(meshIdAsUint32); - } - else - { - uint32 meshIdAsUint32 = (uint32) meshID; - ser.Value("meshID", meshIdAsUint32); - } - } -}; - -class INavPath -{ -public: - virtual ~INavPath(){} - virtual void Release() = 0; - virtual void CopyTo(INavPath* pRecipient) const = 0; - virtual AZStd::shared_ptr<INavPath> Clone() const = 0; - - virtual NavigationMeshID GetMeshID() const = 0; - - virtual int GetVersion() const = 0; - virtual void SetVersion(int version) = 0; - - virtual void SetParams(const SNavPathParams& params) = 0; - virtual const SNavPathParams& GetParams() const = 0; - virtual SNavPathParams& GetParams() = 0; - virtual const TPathPoints& GetPath() const = 0; - virtual void SetPathPoints(const TPathPoints& points) = 0; - - virtual float GetPathLength(bool twoD) const = 0; - virtual void PushFront(const PathPointDescriptor& newPathPoint, bool force = false) = 0; - virtual void PushBack(const PathPointDescriptor& newPathPoint, bool force = false) = 0; - virtual void Clear(const char* contextName) = 0; - virtual bool Advance(PathPointDescriptor& nextPathPoint) = 0; - - virtual bool GetPathEndIsAsRequested() const = 0; - virtual void SetPathEndIsAsRequested(bool value) = 0; - - virtual bool Empty() const = 0; - - virtual const PathPointDescriptor* GetLastPathPoint() const = 0; - virtual const PathPointDescriptor* GetPrevPathPoint() const = 0; - virtual const PathPointDescriptor* GetNextPathPoint() const = 0; - virtual const PathPointDescriptor* GetNextNextPathPoint() const = 0; - - virtual const Vec3& GetNextPathPos(const Vec3& defaultPos = Vec3_Zero) const = 0; - virtual const Vec3& GetLastPathPos(const Vec3& defaultPos = Vec3_Zero) const = 0; - - virtual bool GetPosAlongPath(Vec3& posOut, float dist, bool twoD, bool extrapolateBeyondEnd, ENavigationType* nextPointType = NULL) const = 0; - virtual float GetDistToPath(Vec3& pathPosOut, float& distAlongPathOut, const Vec3& pos, float dist, bool twoD) const = 0; - virtual float GetDistToSmartObject(bool twoD) const = 0; - virtual PathPointDescriptor::SmartObjectNavDataPtr GetLastPathPointAnimNavSOData() const = 0; - virtual void SetPreviousPoint(const PathPointDescriptor& previousPoint) = 0; - - virtual AABB GetAABB(float dist) const = 0; - - virtual bool GetPathPropertiesAhead(float distAhead, bool twoD, Vec3& posOut, Vec3& dirOut, float* invROut, float& lowestPathDotOut, bool scaleOutputWithDist) const = 0; - - virtual void SetEndDir(const Vec3& endDir) = 0; - virtual const Vec3& GetEndDir() const = 0; - - virtual bool UpdateAndSteerAlongPath(Vec3& dirOut, float& distToEndOut, float& distToPathOut, bool& isResolvingSticking, Vec3& pathDirOut, Vec3& pathAheadDirOut, Vec3& pathAheadPosOut, Vec3 currentPos, const Vec3& currentVel, float lookAhead, float pathRadius, float dt, bool resolveSticking, bool twoD) = 0; - - virtual void TrimPath(float length, bool twoD) = 0; - virtual float GetDiscardedPathLength() const = 0; - virtual float UpdatePathPosition(Vec3 agentPos, float pathLookahead, bool twoD, bool allowPathToFinish) = 0; - virtual Vec3 CalculateTargetPos(Vec3 agentPos, float lookAhead, float minLookAheadAlongPath, float pathRadius, bool twoD) const = 0; - - virtual void Draw(const Vec3& drawOffset = ZERO) const = 0; - virtual void Dump(const char* name) const = 0; - - bool ArePathsEqual(const INavPath& otherNavPath) - { - const TPathPoints& path1 = this->GetPath(); - const TPathPoints& path2 = otherNavPath.GetPath(); - const TPathPoints::size_type path1Size = path1.size(); - const TPathPoints::size_type path2Size = path2.size(); - if (path1Size != path2Size) - { - return false; - } - - TPathPoints::const_iterator path1It = path1.begin(); - TPathPoints::const_iterator path1End = path1.end(); - TPathPoints::const_iterator path2It = path2.begin(); - - typedef std::pair<TPathPoints::const_iterator, TPathPoints::const_iterator> TMismatchResult; - - TMismatchResult result = std::mismatch(path1It, path1End, path2It, PathPointDescriptor::ArePointsEquivalent); - return result.first == path1.end(); - } -}; -using INavPathPtr = AZStd::shared_ptr<INavPath>; - -enum EMNMPathResult -{ - eMNMPR_NoPathFound = 0, - eMNMPR_Success, -}; - -struct MNMPathRequestResult -{ - MNMPathRequestResult() - : cost(0.f) - , id(0) - , result(eMNMPR_NoPathFound) - {} - - ILINE bool HasPathBeenFound() const - { - return result == eMNMPR_Success; - } - - INavPathPtr pPath; - float cost; - uint32 id; - EMNMPathResult result; -}; - -struct IPathObstacles -{ - virtual ~IPathObstacles() {} - - virtual bool IsPathIntersectingObstacles(const NavigationMeshID meshID, const Vec3& start, const Vec3& end, float radius) const = 0; - virtual bool IsPointInsideObstacles(const Vec3& position) const = 0; - virtual bool IsLineSegmentIntersectingObstaclesOrCloseToThem(const Lineseg& linesegToTest, float maxDistanceToConsiderClose) const = 0; -}; - -class IPathFollower -{ -public: - virtual ~IPathFollower(){} - - virtual void Release() = 0; - - virtual void Reset() = 0; - - /// This attaches us to a particular path (pass 0 to detach) - virtual void AttachToPath(INavPath* navPath) = 0; - - virtual void SetParams(const PathFollowerParams& params) = 0; - - /// Just view the params - virtual const PathFollowerParams& GetParams() const = 0; - virtual PathFollowerParams& GetParams() = 0; - - // Advances the follow target along the path as far as possible while ensuring the follow - // target remains reachable. Returns true if the follow target is reachable, false otherwise. - virtual bool Update(PathFollowResult& result, const Vec3& curPos, const Vec3& curVel, float dt) = 0; - - /// Advances the current state in terms of position - effectively pretending that the follower - /// has gone further than it has. - virtual void Advance(float distance) = 0; - - /// Returns the distance from the lookahead to the end, plus the distance from the position passed in - /// to the LA if pCurPos != 0 - virtual float GetDistToEnd(const Vec3* pCurPos) const = 0; - - /// Returns the distance along the path from the current look-ahead position to the - /// first smart object path segment. If there's no path, or no smart objects on the - /// path, then std::numeric_limits<float>::max() will be returned - virtual float GetDistToSmartObject() const = 0; - virtual float GetDistToNavType(ENavigationType navType) const = 0; - - /// Returns a point on the path some distance ahead. actualDist is set according to - /// how far we looked - may be less than dist if we'd reach the end - virtual Vec3 GetPathPointAhead(float dist, float& actualDist) const = 0; - - virtual void Draw(const Vec3& drawOffset = ZERO) const = 0; - - virtual void Serialize(TSerialize ser) = 0; - - // Checks ability to walk along a piecewise linear path starting from the current position - // (useful for example when animation would like to deviate from the path) - virtual bool CheckWalkability(const Vec2* path, const size_t length) const = 0; - - // Can the pathfollower cut corners if there is space to do so? (default: true) - virtual bool GetAllowCuttingCorners() const = 0; - - // Sets whether or not the pathfollower is allowed to cut corners if there is space to do so. (default: true) - virtual void SetAllowCuttingCorners(const bool allowCuttingCorners) = 0; -}; - -namespace MNM -{ - typedef unsigned int QueuedPathID; - - namespace Constants - { - enum EQueuedPathID - { - eQueuedPathID_InvalidID = 0, - }; - } -} - -struct MNMPathRequest -{ - using Callback = AZStd::function<void(const MNM::QueuedPathID&, MNMPathRequestResult&)>; - - MNMPathRequest() - : resultCallback(0) - , startLocation(ZERO) - , endLocation(ZERO) - , endDirection(Vec3(0, 1, 0)) - , agentTypeID(NavigationAgentTypeID()) - , forceTargetBuildingId(0) - , endTolerance(0.0f) - , endDistance(0.0f) - , allowDangerousDestination(false) - , beautify(true) - { - } - - MNMPathRequest(const Vec3& start, const Vec3& end, const Vec3& _endDirection, int _forceTargetBuildingId, - float _endTolerance, float _endDistance, [[maybe_unused]] bool _allowDangerousDestination, const Callback& callback, - const NavigationAgentTypeID& _agentTypeID) - : resultCallback(callback) - , startLocation(start) - , endLocation(end) - , endDirection(_endDirection) - , agentTypeID(_agentTypeID) - , forceTargetBuildingId(_forceTargetBuildingId) - , endTolerance(_endTolerance) - , endDistance(_endDistance) - , allowDangerousDestination(false) - , beautify(true) - { - } - - Callback resultCallback; - - Vec3 startLocation; - Vec3 endLocation; - Vec3 endDirection; - - NavigationAgentTypeID agentTypeID; - - //Set beautify to false if you don't want to "beautify" the path (make it little less jagged, and more curvy) - bool beautify; - - int forceTargetBuildingId; - float endTolerance; - float endDistance; - bool allowDangerousDestination; -}; - -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// - -struct IMNMPathfinder -{ - virtual ~IMNMPathfinder() {}; - - //Request a path (look at MNMPathRequest for relevant request info). This request is queued and processed in a seperate - //thread. The path result is sent to the callback function specified in the request. Returns an ID so you can cancel - //the request. - virtual MNM::QueuedPathID RequestPathTo(const IAIPathAgent* pRequester, const MNMPathRequest& request) = 0; - // Returns a four-tuple: triangle ID and three vertices - virtual const std::tuple<uint32, Vec3, Vec3, Vec3> GetCurrentNavTriangle(const IAIPathAgent* pRequester, NavigationAgentTypeID agentTypeID) const = 0; - - //Cancel a requested path by ID - virtual void CancelPathRequest(MNM::QueuedPathID requestId) = 0; - - virtual bool CheckIfPointsAreOnStraightWalkableLine(const NavigationMeshID& meshID, const Vec3& source, const Vec3& destination, float heightOffset = 0.2f) const = 0; -}; diff --git a/Code/CryEngine/CryCommon/IPhysics.h b/Code/CryEngine/CryCommon/IPhysics.h deleted file mode 100644 index 9abbe5431a..0000000000 --- a/Code/CryEngine/CryCommon/IPhysics.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_IPHYSICS_H -#define CRYINCLUDE_CRYCOMMON_IPHYSICS_H -#pragma once - - -// -#ifdef PHYSICS_EXPORTS - #define CRYPHYSICS_API DLL_EXPORT -#else - #define CRYPHYSICS_API DLL_IMPORT -#endif - -#define vector_class Vec3_tpl - - -#include <CrySizer.h> - -////////////////////////////////////////////////////////////////////////// -// IDs that can be used for foreign id. -////////////////////////////////////////////////////////////////////////// -enum EPhysicsForeignIds -{ - PHYS_FOREIGN_ID_TERRAIN = 0, - PHYS_FOREIGN_ID_STATIC = 1, - PHYS_FOREIGN_ID_ENTITY = 2, - PHYS_FOREIGN_ID_FOLIAGE = 3, - PHYS_FOREIGN_ID_ROPE = 4, - PHYS_FOREIGN_ID_SOUND_OBSTRUCTION = 5, - PHYS_FOREIGN_ID_SOUND_PROXY_OBSTRUCTION = 6, - PHYS_FOREIGN_ID_SOUND_REVERB_OBSTRUCTION = 7, - PHYS_FOREIGN_ID_WATERVOLUME = 8, - PHYS_FOREIGN_ID_BREAKABLE_GLASS = 9, - PHYS_FOREIGN_ID_BREAKABLE_GLASS_FRAGMENT = 10, - PHYS_FOREIGN_ID_RIGID_PARTICLE = 11, - PHYS_FOREIGN_ID_RESERVED1 = 12, - PHYS_FOREIGN_ID_RAGDOLL = 13, - PHYS_FOREIGN_ID_COMPONENT_ENTITY = 14, - - PHYS_FOREIGN_ID_USER = 100, // All user defined foreign ids should start from this enum. -}; - - -//#include "utils.h" -#include "Cry_Math.h" -#include "primitives.h" -#include <physinterface.h> // <> required for Interfuscator - - -#endif // CRYINCLUDE_CRYCOMMON_IPHYSICS_H diff --git a/Code/CryEngine/CryCommon/IPostEffectGroup.h b/Code/CryEngine/CryCommon/IPostEffectGroup.h deleted file mode 100644 index 4e45fcff21..0000000000 --- a/Code/CryEngine/CryCommon/IPostEffectGroup.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/std/containers/variant.h> - -typedef AZStd::variant<float, Vec4, AZStd::string> PostEffectGroupParam; - -// A prioritized group of postprocessing effect parameters. -// These are defined in XML files and can be enabled or disabled using flow graph or Lua scripts. -// Effect groups can also optionally specify blend curves to smoothly transition between effects, whether to stay enabled until explicitly disabled, -// and whether to make effect strength based on distance from the camera. -class IPostEffectGroup -{ -public: - virtual ~IPostEffectGroup(){} - - virtual const char* GetName() const = 0; - virtual void SetEnable(bool enable) = 0; - virtual bool GetEnable() const = 0; - virtual unsigned int GetPriority() const = 0; - virtual bool GetHold() const = 0; - virtual float GetFadeDistance() const = 0; - virtual void SetParam(const char* name, const PostEffectGroupParam& value) = 0; - virtual PostEffectGroupParam* GetParam(const char* name) = 0; - virtual void ClearParams() = 0; - // Increases the strength of the effects based on distance from the camera each time it's called. The effect strength is cleared each frame. - // Only applies to effect groups with the fadeDistance attribute set. - virtual void ApplyAtPosition(const Vec3& position) = 0; -}; - -typedef AZStd::list<IPostEffectGroup*> PostEffectGroupList; - -class IPostEffectGroupManager -{ -public: - virtual ~IPostEffectGroupManager(){} - - virtual IPostEffectGroup* GetGroup(const char* name) = 0; - virtual IPostEffectGroup* GetGroup(const unsigned int index) = 0; - virtual const unsigned int GetGroupCount() = 0; - // Returns a list of IPostEffectGroups who had their Enabled state toggled this frame - virtual const PostEffectGroupList& GetGroupsToggledThisFrame() = 0; -}; diff --git a/Code/CryEngine/CryCommon/IProcess.h b/Code/CryEngine/CryCommon/IProcess.h deleted file mode 100644 index c99bf2fbdc..0000000000 --- a/Code/CryEngine/CryCommon/IProcess.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Process common interface - - -#ifndef CRYINCLUDE_CRYCOMMON_IPROCESS_H -#define CRYINCLUDE_CRYCOMMON_IPROCESS_H -#pragma once - - -// forward declaration -struct SRenderingPassInfo; -//////////////////////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////////////////////// -struct IProcess -{ - // <interfuscator:shuffle> - virtual ~IProcess(){} - virtual bool Init() = 0; - virtual void Update() = 0; - virtual void RenderWorld(int nRenderFlags, const SRenderingPassInfo& passInfo, const char* szDebugName) = 0; - virtual void ShutDown() = 0; - virtual void SetFlags(int flags) = 0; - virtual int GetFlags(void) = 0; - // </interfuscator:shuffle> -}; - -#endif // CRYINCLUDE_CRYCOMMON_IPROCESS_H diff --git a/Code/CryEngine/CryCommon/IReadWriteXMLSink.h b/Code/CryEngine/CryCommon/IReadWriteXMLSink.h deleted file mode 100644 index a36b9e5492..0000000000 --- a/Code/CryEngine/CryCommon/IReadWriteXMLSink.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Moved Craig's ReadWriteXMLSink from CryAction to CrySystem - - -#ifndef CRYINCLUDE_CRYCOMMON_IREADWRITEXMLSINK_H -#define CRYINCLUDE_CRYCOMMON_IREADWRITEXMLSINK_H -#pragma once - -#include <IXml.h> -#include <AzCore/std/containers/variant.h> - -struct IReadXMLSink; -struct IWriteXMLSource; - -struct IReadWriteXMLSink -{ - // <interfuscator:shuffle> - virtual ~IReadWriteXMLSink(){} - virtual bool ReadXML(const char* definitionFile, const char* dataFile, IReadXMLSink* pSink) = 0; - virtual bool ReadXML(const char* definitionFile, XmlNodeRef node, IReadXMLSink* pSink) = 0; - virtual bool ReadXML(XmlNodeRef definition, const char* dataFile, IReadXMLSink* pSink) = 0; - virtual bool ReadXML(XmlNodeRef definition, XmlNodeRef node, IReadXMLSink* pSink) = 0; - - virtual XmlNodeRef CreateXMLFromSource(const char* definitionFile, IWriteXMLSource* pSource) = 0; - virtual bool WriteXML(const char* definitionFile, const char* dataFile, IWriteXMLSource* pSource) = 0; - // </interfuscator:shuffle> -}; - - -struct SReadWriteXMLCommon -{ - typedef AZStd::variant<Vec3, int, float, const char*, bool> TValue; -}; - - -TYPEDEF_AUTOPTR(IReadXMLSink); -typedef IReadXMLSink_AutoPtr IReadXMLSinkPtr; - -// this interface allows customization of the data read routines -struct IReadXMLSink - : public SReadWriteXMLCommon -{ - // <interfuscator:shuffle> - virtual ~IReadXMLSink(){} - // reference counting - virtual void AddRef() = 0; - virtual void Release() = 0; - - virtual IReadXMLSinkPtr BeginTable(const char* name, const XmlNodeRef& definition) = 0; - virtual IReadXMLSinkPtr BeginTableAt(int elem, const XmlNodeRef& definition) = 0; - virtual bool SetValue(const char* name, const TValue& value, const XmlNodeRef& definition) = 0; - virtual bool EndTableAt(int elem) = 0; - virtual bool EndTable(const char* name) = 0; - - virtual IReadXMLSinkPtr BeginArray(const char* name, const XmlNodeRef& definition) = 0; - virtual bool SetAt(int elem, const TValue& value, const XmlNodeRef& definition) = 0; - virtual bool EndArray(const char* name) = 0; - - virtual bool Complete() = 0; - - virtual bool IsCreationMode() = 0; - virtual XmlNodeRef GetCreationNode() = 0; - virtual void SetCreationNode(XmlNodeRef definition) = 0; - // </interfuscator:shuffle> -}; - - -TYPEDEF_AUTOPTR(IWriteXMLSource); -typedef IWriteXMLSource_AutoPtr IWriteXMLSourcePtr; - -// this interface allows customization of the data write routines -struct IWriteXMLSource - : public SReadWriteXMLCommon -{ - // <interfuscator:shuffle> - virtual ~IWriteXMLSource(){} - // reference counting - virtual void AddRef() = 0; - virtual void Release() = 0; - - virtual IWriteXMLSourcePtr BeginTable(const char* name) = 0; - virtual IWriteXMLSourcePtr BeginTableAt(int elem) = 0; - virtual bool HaveValue(const char* name) = 0; - virtual bool GetValue(const char* name, TValue& value, const XmlNodeRef& definition) = 0; - virtual bool EndTableAt(int elem) = 0; - virtual bool EndTable(const char* name) = 0; - - virtual IWriteXMLSourcePtr BeginArray(const char* name, size_t* numElems, const XmlNodeRef& definition) = 0; - virtual bool HaveElemAt(int elem) = 0; - virtual bool GetAt(int elem, TValue& value, const XmlNodeRef& definition) = 0; - virtual bool EndArray(const char* name) = 0; - - virtual bool Complete() = 0; - // </interfuscator:shuffle> -}; - -#endif // CRYINCLUDE_CRYCOMMON_IREADWRITEXMLSINK_H diff --git a/Code/CryEngine/CryCommon/IRenderAuxGeom.h b/Code/CryEngine/CryCommon/IRenderAuxGeom.h deleted file mode 100644 index 8bce5bc477..0000000000 --- a/Code/CryEngine/CryCommon/IRenderAuxGeom.h +++ /dev/null @@ -1,837 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_IRENDERAUXGEOM_H -#define CRYINCLUDE_CRYCOMMON_IRENDERAUXGEOM_H -#pragma once - - -struct SAuxGeomRenderFlags; - -#include "IRenderer.h" - - -enum EBoundingBoxDrawStyle -{ - eBBD_Faceted, - eBBD_Extremes_Color_Encoded -}; - -// Summary: -// Auxiliary geometry render interface. -// Description: -// Used mostly for debugging, editor purposes, the Auxiliary geometry render -// interface provide functions to render 2d geometry and also text. -struct IRenderAuxGeom -{ - // <interfuscator:shuffle> - virtual ~IRenderAuxGeom(){} - // Summary: - // Sets render flags. - virtual void SetRenderFlags(const SAuxGeomRenderFlags& renderFlags) = 0; - // Summary: - // Gets render flags. - virtual SAuxGeomRenderFlags GetRenderFlags() = 0; - - // 2D/3D rendering function - - // Summary: - // Draws a point. - // Arguments: - // v - Vector storing the position of the point. - // col - Color used to draw the point. - // size - Size of the point drawn. - virtual void DrawPoint(const Vec3& v, const ColorB& col, uint8 size = 1) = 0; - // Summary: - // Draws n points. - // Arguments: - // v - Pointer to a list of vector storing the position of the points. - // numPoints - Number of point we will find starting from the area memory defined by v. - // col - Color used to draw the points. - // size - Size of the points drawn. - //##@{ - virtual void DrawPoints(const Vec3* v, uint32 numPoints, const ColorB& col, uint8 size = 1) = 0; - virtual void DrawPoints(const Vec3* v, uint32 numPoints, const ColorB* col, uint8 size = 1) = 0; - //##@} - - // Summary: - // Draws a line. - // Arguments: - // v0 - Starting vertex of the line. - // colV0 - Color of the first vertex. - // v1 - Ending vertex of the line. - // colV1 - Color of the second vertex. - // thickness - Thickness of the line. - virtual void DrawLine(const Vec3& v0, const ColorB& colV0, const Vec3& v1, const ColorB& colV1, float thickness = 1.0f) = 0; - // Summary: - // Draws n lines. - // Arguments: - // v - List of vertexes belonging to the lines we want to draw. - // numPoints - Number of the points we will find starting from the area memory defined by v. - // col - Color of the vertexes. - // thickness - Thickness of the line. - //##@{ - virtual void DrawLines(const Vec3* v, uint32 numPoints, const ColorB& col, float thickness = 1.0f) = 0; - virtual void DrawLines(const Vec3* v, uint32 numPoints, const ColorB* col, float thickness = 1.0f) = 0; - //##@} - - // Summary: - // Draws n lines. - // Arguments: - // v - List of vertexes belonging to the lines we want to draw. - // numPoints - Number of the points we will find starting from the area memory defined by v. - // ind - - // numIndices - - // col - Color of the vertexes. - // thickness - Thickness of the line. - //##@{ - virtual void DrawLines(const Vec3* v, uint32 numPoints, const vtx_idx* ind, uint32 numIndices, const ColorB& col, float thickness = 1.0f) = 0; - virtual void DrawLines(const Vec3* v, uint32 numPoints, const vtx_idx* ind, uint32 numIndices, const ColorB* col, float thickness = 1.0f) = 0; - //##@} - - // Summary: - // Draws a polyline. - // Arguments: - // v - List of vertexes belonging to the polyline we want to draw. - // numPoints - Number of the points we will find starting from the area memory defined by v. - // closed - If true a line between the last vertex and the first one is drawn. - // col - Color of the vertexes. - // thickness - Thickness of the line. - //##@{ - virtual void DrawPolyline(const Vec3* v, uint32 numPoints, bool closed, const ColorB& col, float thickness = 1.0f) = 0; - virtual void DrawPolyline(const Vec3* v, uint32 numPoints, bool closed, const ColorB* col, float thickness = 1.0f) = 0; - //##@} - - // Summary: - // Draws a triangle. - // Arguments: - // v0 - First vertex of the triangle. - // colV0 - Color of the first vertex of the triangle. - // v1 - Second vertex of the triangle. - // colV1 - Color of the second vertex of the triangle. - // v2 - Third vertex of the triangle. - // colV2 - Color of the third vertex of the triangle. - virtual void DrawTriangle(const Vec3& v0, const ColorB& colV0, const Vec3& v1, const ColorB& colV1, const Vec3& v2, const ColorB& colV2) = 0; - // Summary: - // Draws n triangles. - // Arguments: - // v - List of vertexes belonging to the sequence of triangles we have to draw. - // numPoints - Number of the points we will find starting from the area memory defined by v. - // col - Color of the vertexes. - //##@{ - virtual void DrawTriangles(const Vec3* v, uint32 numPoints, const ColorB& col) = 0; - virtual void DrawTriangles(const Vec3* v, uint32 numPoints, const ColorB* col) = 0; - //##@} - // Summary: - // Draws n triangles. - // Arguments: - // v - List of vertexes belonging to the sequence of triangles we have to draw. - // numPoints - Number of the points we will find starting from the area memory defined by v. - // ind - - // numIndices - - // col - Color of the vertexes. - //##@{ - virtual void DrawTriangles(const Vec3* v, uint32 numPoints, const vtx_idx* ind, uint32 numIndices, const ColorB& col) = 0; - virtual void DrawTriangles(const Vec3* v, uint32 numPoints, const vtx_idx* ind, uint32 numIndices, const ColorB* col) = 0; - //##@} - - // Summary: - // Draws a quad on the xz plane. - // Arguments: - // pos - Center position of the quad - // width - Width of the quad. - // height - Height of the quad. - // matWorld - World matrix to transform the quad. - // col - Color of the quad. - // drawShaded - True if you want to draw the quad shaded, false otherwise. - virtual void DrawQuad(float width, float height, const Matrix34& matWorld, const ColorB& col, bool drawShaded = true) = 0; - - // Summary: - // Draws a Axis-aligned Bounding Boxes (AABB). - //##@{ - virtual void DrawAABB(const AABB& aabb, bool bSolid, const ColorB& col, const EBoundingBoxDrawStyle& bbDrawStyle) = 0; - virtual void DrawAABBs(const AABB* aabbs, uint32 aabbCount, bool bSolid, const ColorB& col, const EBoundingBoxDrawStyle& bbDrawStyle) = 0; - virtual void DrawAABB(const AABB& aabb, const Matrix34& matWorld, bool bSolid, const ColorB& col, const EBoundingBoxDrawStyle& bbDrawStyle) = 0; - //##@} - - // Summary: - // Draws a Oriented Bounding Boxes (AABB). - //##@{ - virtual void DrawOBB(const OBB& obb, const Vec3& pos, bool bSolid, const ColorB& col, const EBoundingBoxDrawStyle& bbDrawStyle) = 0; - virtual void DrawOBB(const OBB& obb, const Matrix34& matWorld, bool bSolid, const ColorB& col, const EBoundingBoxDrawStyle& bbDrawStyle) = 0; - //##@} - - // Summary: - // Draws a sphere. - // Arguments: - // pos - Center of the sphere. - // radius - Radius of the sphere. - // col - Color of the sphere. - // drawShaded - True if you want to draw the sphere shaded, false otherwise. - virtual void DrawSphere(const Vec3& pos, float radius, const ColorB& col, bool drawShaded = true) = 0; - - // Summary: - // Draws a disk. - // Arguments: - // pos - Center of the disk. - // radius - Radius of the disk. - // col - Color of the disk. - // drawShaded - True if you want to draw the disk shaded, false otherwise. - virtual void DrawDisk(const Vec3& pos, const Vec3& dir, float radius, const ColorB& col, bool drawShaded = true) = 0; - - // Summary: - // Draws a cone. - // Arguments: - // pos - Center of the base of the cone. - // dir - Direction of the cone. - // radius - Radius of the base of the cone. - // height - Height of the cone. - // col - Color of the cone. - // drawShaded - True if you want to draw the cone shaded, false otherwise. - virtual void DrawCone(const Vec3& pos, const Vec3& dir, float radius, float height, const ColorB& col, bool drawShaded = true) = 0; - // Summary: - // Draws a cylinder. - // Arguments: - // pos - Center of the base of the cylinder. - // dir - Direction of the cylinder. - // radius - Radius of the base of the cylinder. - // height - Height of the cylinder. - // col - Color of the cylinder. - // drawShaded - True if you want to draw the cylinder shaded, false otherwise. - virtual void DrawCylinder(const Vec3& pos, const Vec3& dir, float radius, float height, const ColorB& col, bool drawShaded = true) = 0; - - // Summary: - // Draws bones. - //##@{ - virtual void DrawBone(const Vec3& rParent, const Vec3& rBone, ColorB col) = 0; - //##@} - - // Summary: - // Draws Text. - //##@{ - virtual void RenderText(Vec3 pos, SDrawTextInfo& ti, const char* format, va_list args) = 0; - - // Summary: - // Draws 3d Label. - //##@{ - void Draw3dLabel(Vec3 pos, float font_size, const ColorF& color, const char* label_text, ...) PRINTF_PARAMS(5, 6) - { - va_list args; - va_start(args, label_text); - - SDrawTextInfo ti; - ti.xscale = ti.yscale = font_size; - ti.color[0] = color[0]; - ti.color[1] = color[1]; - ti.color[2] = color[2]; - ti.color[3] = color[3]; - ti.flags = eDrawText_2D | eDrawText_FixedSize | eDrawText_Monospace; - - RenderText(pos, ti, label_text, args); - - va_end(args); - } - - void Draw2dLabelInternal(float x, float y, float font_size, const float* pfColor, int flags, const char* format, va_list args) - { - SDrawTextInfo ti; - ti.xscale = ti.yscale = font_size; - ti.flags = (eDrawText_2D | eDrawText_800x600 | eDrawText_FixedSize | flags); - if (pfColor) - { - ti.color[0] = pfColor[0]; - ti.color[1] = pfColor[1]; - ti.color[2] = pfColor[2]; - ti.color[3] = pfColor[3]; - } - - RenderText(Vec3(x, y, 0.5f), ti, format, args); - } - - void Draw2dLabel(float x, float y, float font_size, const float* pfColor, bool bCenter, const char* label_text, ...) PRINTF_PARAMS(7, 8) - { - va_list args; - va_start(args, label_text); - Draw2dLabelInternal(x, y, font_size, pfColor, (bCenter ? eDrawText_Center : eDrawText_Left), label_text, args); - va_end(args); - } - - void Draw2dLabel(float x, float y, float font_size, const ColorF& fColor, bool bCenter, const char* label_text, ...) PRINTF_PARAMS(7, 8) - { - const AZStd::array<float, 4> color = fColor.GetAsArray(); - va_list args; - va_start(args, label_text); - Draw2dLabelInternal(x, y, font_size, color.data(), (bCenter ? eDrawText_Center : eDrawText_Left), label_text, args); - va_end(args); - } - - void Draw2dLabelCustom(float x, float y, float font_size, const float* pfColor, int flags, const char* label_text, ...) PRINTF_PARAMS(7, 8) - { - va_list args; - va_start(args, label_text); - Draw2dLabelInternal(x, y, font_size, pfColor, flags, label_text, args); - va_end(args); - } - - void Draw2dLabelCustom(float x, float y, float font_size, const ColorF& fColor, int flags, const char* label_text, ...) PRINTF_PARAMS(7, 8) - { - const AZStd::array<float, 4> color = fColor.GetAsArray(); - va_list args; - va_start(args, label_text); - Draw2dLabelInternal(x, y, font_size, color.data(), flags, label_text, args); - va_end(args); - } - //##@} - - // Summary: - // If possible flushes all elements stored on the buffer to rendering system. - // Note 1: rendering system may start processing flushed commands immediately or postpone it till Commit() call - // Note 2: worker threads's commands are always postponed till Commit() call - // - virtual void Flush() = 0; - // </interfuscator:shuffle> - - // Summary: - // Flushes yet unprocessed elements and notifies rendering system that issuing rendering commands for current frame is done and frame is ready to be drawn - // Thus Commit() guarantees that all previously issued commands will appear on the screen - // Each thread rendering AUX geometry MUST call Commit() at the end of drawing cycle/frame - // "frames" indicate how many frames current commands butch must be presented on screen unless there till next butch is ready. - // for render and main thread this parameter has no effect - virtual void Commit(uint frames = 0) = 0; - // </interfuscator:shuffle> - - /** - * Processes and resets the underlying vertex buffer - */ - virtual void Process() = 0; -}; - -// Notes: -// Don't change the xxxShift values blindly as they affect the rendering output -// that is two primitives have to be rendered after 3d primitives, alpha blended -// geometry have to be rendered after opaque ones, etc. -// This also applies to the individual flags in EAuxGeomPublicRenderflags_*! -// Remarks: -// Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) -// Check RenderAuxGeom.h in ../RenderDll/Common -enum EAuxGeomPublicRenderflagBitMasks -{ - e_Mode2D3DShift = 31, - e_Mode2D3DMask = 0x1 << e_Mode2D3DShift, - - e_AlphaBlendingShift = 29, - e_AlphaBlendingMask = 0x3 << e_AlphaBlendingShift, - - e_DrawInFrontShift = 28, - e_DrawInFrontMask = 0x1 << e_DrawInFrontShift, - - e_FillModeShift = 26, - e_FillModeMask = 0x3 << e_FillModeShift, - - e_CullModeShift = 24, - e_CullModeMask = 0x3 << e_CullModeShift, - - e_DepthWriteShift = 23, - e_DepthWriteMask = 0x1 << e_DepthWriteShift, - - e_DepthTestShift = 22, - e_DepthTestMask = 0x1 << e_DepthTestShift, - - e_PublicParamsMask = e_Mode2D3DMask | e_AlphaBlendingMask | e_DrawInFrontMask | e_FillModeMask | - e_CullModeMask | e_DepthWriteMask | e_DepthTestMask -}; - -// Notes: -// e_Mode2D renders in normalized [0.. 1] screen space. -// Don't change the xxxShift values blindly as they affect the rendering output -// that is two primitives have to be rendered after 3d primitives, alpha blended -// geometry have to be rendered after opaque ones, etc. -// This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! -// Remarks: -// Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) -// Check RenderAuxGeom.h in ../RenderDll/Common -// See also: -// EAuxGeomPublicRenderflagBitMasks -enum EAuxGeomPublicRenderflags_Mode2D3D -{ - e_Mode3D = 0x0 << e_Mode2D3DShift, - e_Mode2D = 0x1 << e_Mode2D3DShift, -}; - -// Notes: -// Don't change the xxxShift values blindly as they affect the rendering output -// that is two primitives have to be rendered after 3d primitives, alpha blended -// geometry have to be rendered after opaque ones, etc. -// This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! -// Remarks: -// Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) -// Check RenderAuxGeom.h in ../RenderDll/Common -// See also: -// EAuxGeomPublicRenderflagBitMasks -enum EAuxGeomPublicRenderflags_AlphaBlendMode -{ - e_AlphaNone = 0x0 << e_AlphaBlendingShift, - e_AlphaAdditive = 0x1 << e_AlphaBlendingShift, - e_AlphaBlended = 0x2 << e_AlphaBlendingShift, -}; - -// Notes: -// Don't change the xxxShift values blindly as they affect the rendering output -// that is two primitives have to be rendered after 3d primitives, alpha blended -// geometry have to be rendered after opaque ones, etc. -// This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! -// Remarks: -// Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) -// Check RenderAuxGeom.h in ../RenderDll/Common -// See also: -// EAuxGeomPublicRenderflagBitMasks -enum EAuxGeomPublicRenderflags_DrawInFrontMode -{ - e_DrawInFrontOff = 0x0 << e_DrawInFrontShift, - e_DrawInFrontOn = 0x1 << e_DrawInFrontShift, -}; - -// Notes: -// Don't change the xxxShift values blindly as they affect the rendering output -// that is two primitives have to be rendered after 3d primitives, alpha blended -// geometry have to be rendered after opaque ones, etc. -// This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! -// Remarks: -// Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) -// Check RenderAuxGeom.h in ../RenderDll/Common -// See also: -// EAuxGeomPublicRenderflagBitMasks -enum EAuxGeomPublicRenderflags_FillMode -{ - e_FillModeSolid = 0x0 << e_FillModeShift, - e_FillModeWireframe = 0x1 << e_FillModeShift, - e_FillModePoint = 0x2 << e_FillModeShift, -}; - -// Notes: -// Don't change the xxxShift values blindly as they affect the rendering output -// that is two primitives have to be rendered after 3d primitives, alpha blended -// geometry have to be rendered after opaque ones, etc. -// This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! -// Remarks: -// Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) -// Check RenderAuxGeom.h in ../RenderDll/Common -// See also: -// EAuxGeomPublicRenderflagBitMasks -enum EAuxGeomPublicRenderflags_CullMode -{ - e_CullModeNone = 0x0 << e_CullModeShift, - e_CullModeFront = 0x1 << e_CullModeShift, - e_CullModeBack = 0x2 << e_CullModeShift, -}; - -// Notes: -// Don't change the xxxShift values blindly as they affect the rendering output -// that is two primitives have to be rendered after 3d primitives, alpha blended -// geometry have to be rendered after opaque ones, etc. -// This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! -// Remarks: -// Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) -// Check RenderAuxGeom.h in ../RenderDll/Common -// See also: -// EAuxGeomPublicRenderflagBitMasks -enum EAuxGeomPublicRenderflags_DepthWrite -{ - e_DepthWriteOn = 0x0 << e_DepthWriteShift, - e_DepthWriteOff = 0x1 << e_DepthWriteShift, -}; - -// Notes: -// Don't change the xxxShift values blindly as they affect the rendering output -// that is two primitives have to be rendered after 3d primitives, alpha blended -// geometry have to be rendered after opaque ones, etc. -// This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! -// Remarks: -// Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) -// Check RenderAuxGeom.h in ../RenderDll/Common -// See also: -// EAuxGeomPublicRenderflagBitMasks -enum EAuxGeomPublicRenderflags_DepthTest -{ - e_DepthTestOn = 0x0 << e_DepthTestShift, - e_DepthTestOff = 0x1 << e_DepthTestShift, -}; - - -enum EAuxGeomPublicRenderflags_Defaults -{ - // Default render flags for 3d primitives. - e_Def3DPublicRenderflags = e_Mode3D | e_AlphaNone | e_DrawInFrontOff | e_FillModeSolid | - e_CullModeBack | e_DepthWriteOn | e_DepthTestOn, - - // Default render flags for 2d primitives. - e_Def2DPublicRenderflags = e_Mode2D | e_AlphaNone | e_DrawInFrontOff | e_FillModeSolid | - e_CullModeBack | e_DepthWriteOn | e_DepthTestOn -}; - - -struct SAuxGeomRenderFlags -{ - uint32 m_renderFlags; - - SAuxGeomRenderFlags(); - SAuxGeomRenderFlags(const SAuxGeomRenderFlags& rhs); - SAuxGeomRenderFlags(uint32 renderFlags); - SAuxGeomRenderFlags& operator =(const SAuxGeomRenderFlags& rhs); - SAuxGeomRenderFlags& operator =(uint32 rhs); - - bool operator ==(const SAuxGeomRenderFlags& rhs) const; - bool operator ==(uint32 rhs) const; - bool operator !=(const SAuxGeomRenderFlags& rhs) const; - bool operator !=(uint32 rhs) const; - - // Summary: - // Gets the flags for 2D/3D rendering mode. - EAuxGeomPublicRenderflags_Mode2D3D GetMode2D3DFlag() const; - // Summary: - // Sets the flags for 2D/3D rendering mode. - void SetMode2D3DFlag(const EAuxGeomPublicRenderflags_Mode2D3D& state); - - // Summary: - // Gets the flags for alpha blend mode. - EAuxGeomPublicRenderflags_AlphaBlendMode GetAlphaBlendMode() const; - // Summary: - // Sets the flags for the alpha blend mode. - void SetAlphaBlendMode(const EAuxGeomPublicRenderflags_AlphaBlendMode& state); - - - EAuxGeomPublicRenderflags_DrawInFrontMode GetDrawInFrontMode() const; - void SetDrawInFrontMode(const EAuxGeomPublicRenderflags_DrawInFrontMode& state); - - // Summary: - // Gets the flags for the filling mode. - EAuxGeomPublicRenderflags_FillMode GetFillMode() const; - // Summary: - // Sets the flags for the filling mode. - void SetFillMode(const EAuxGeomPublicRenderflags_FillMode& state); - - // Summary: - // Gets the flags for the culling mode. - EAuxGeomPublicRenderflags_CullMode GetCullMode() const; - // Summary: - // Sets the flags for the culling mode. - void SetCullMode(const EAuxGeomPublicRenderflags_CullMode& state); - - - EAuxGeomPublicRenderflags_DepthWrite GetDepthWriteFlag() const; - void SetDepthWriteFlag(const EAuxGeomPublicRenderflags_DepthWrite& state); - - // Summary: - // Gets the flags for the depth test. - EAuxGeomPublicRenderflags_DepthTest GetDepthTestFlag() const; - // Summary: - // Sets the flags for the depth test. - void SetDepthTestFlag(const EAuxGeomPublicRenderflags_DepthTest& state); -}; - - -inline -SAuxGeomRenderFlags::SAuxGeomRenderFlags() - : m_renderFlags(e_Def3DPublicRenderflags) -{ -} - -inline -SAuxGeomRenderFlags::SAuxGeomRenderFlags(const SAuxGeomRenderFlags& rhs) - : m_renderFlags(rhs.m_renderFlags) -{ -} - - -inline -SAuxGeomRenderFlags::SAuxGeomRenderFlags(uint32 renderFlags) - : m_renderFlags(renderFlags) -{ -} - - -inline SAuxGeomRenderFlags& -SAuxGeomRenderFlags::operator =(const SAuxGeomRenderFlags& rhs) -{ - m_renderFlags = rhs.m_renderFlags; - return(*this); -} - - -inline SAuxGeomRenderFlags& -SAuxGeomRenderFlags::operator =(uint32 rhs) -{ - m_renderFlags = rhs; - return(*this); -} - - -inline bool -SAuxGeomRenderFlags::operator ==(const SAuxGeomRenderFlags& rhs) const -{ - return(m_renderFlags == rhs.m_renderFlags); -} - - -inline bool -SAuxGeomRenderFlags::operator ==(uint32 rhs) const -{ - return(m_renderFlags == rhs); -} - - -inline bool -SAuxGeomRenderFlags::operator !=(const SAuxGeomRenderFlags& rhs) const -{ - return(m_renderFlags != rhs.m_renderFlags); -} - - -inline bool -SAuxGeomRenderFlags::operator !=(uint32 rhs) const -{ - return(m_renderFlags != rhs); -} - - -inline EAuxGeomPublicRenderflags_Mode2D3D -SAuxGeomRenderFlags::GetMode2D3DFlag() const -{ - int mode2D3D((int)(m_renderFlags & (uint32)e_Mode2D3DMask)); - switch (mode2D3D) - { - case e_Mode2D: - { - return(e_Mode2D); - } - case e_Mode3D: - default: - { - assert(e_Mode3D == mode2D3D); - return(e_Mode3D); - } - } -} - - -inline void -SAuxGeomRenderFlags::SetMode2D3DFlag(const EAuxGeomPublicRenderflags_Mode2D3D& state) -{ - m_renderFlags &= ~e_Mode2D3DMask; - m_renderFlags |= state; -} - - -inline EAuxGeomPublicRenderflags_AlphaBlendMode -SAuxGeomRenderFlags::GetAlphaBlendMode() const -{ - uint32 alphaBlendMode(m_renderFlags & e_AlphaBlendingMask); - switch (alphaBlendMode) - { - case e_AlphaAdditive: - { - return(e_AlphaAdditive); - } - case e_AlphaBlended: - { - return(e_AlphaBlended); - } - case e_AlphaNone: - default: - { - assert(e_AlphaNone == alphaBlendMode); - return(e_AlphaNone); - } - } -} - - -inline void -SAuxGeomRenderFlags::SetAlphaBlendMode(const EAuxGeomPublicRenderflags_AlphaBlendMode& state) -{ - m_renderFlags &= ~e_AlphaBlendingMask; - m_renderFlags |= state; -} - - -inline EAuxGeomPublicRenderflags_DrawInFrontMode -SAuxGeomRenderFlags::GetDrawInFrontMode() const -{ - uint32 drawInFrontMode(m_renderFlags & e_DrawInFrontMask); - switch (drawInFrontMode) - { - case e_DrawInFrontOff: - { - return(e_DrawInFrontOff); - } - case e_DrawInFrontOn: - default: - { - assert(e_DrawInFrontOn == drawInFrontMode); - return(e_DrawInFrontOn); - } - } -} - - -inline void -SAuxGeomRenderFlags::SetDrawInFrontMode(const EAuxGeomPublicRenderflags_DrawInFrontMode& state) -{ - m_renderFlags &= ~e_DrawInFrontMask; - m_renderFlags |= state; -} - - -inline EAuxGeomPublicRenderflags_FillMode -SAuxGeomRenderFlags::GetFillMode() const -{ - uint32 fillMode(m_renderFlags & e_FillModeMask); - switch (fillMode) - { - case e_FillModePoint: - { - return(e_FillModePoint); - } - case e_FillModeWireframe: - { - return(e_FillModeWireframe); - } - case e_FillModeSolid: - default: - { - assert(e_FillModeSolid == fillMode); - return(e_FillModeSolid); - } - } -} - - -inline void -SAuxGeomRenderFlags::SetFillMode(const EAuxGeomPublicRenderflags_FillMode& state) -{ - m_renderFlags &= ~e_FillModeMask; - m_renderFlags |= state; -} - - -inline EAuxGeomPublicRenderflags_CullMode -SAuxGeomRenderFlags::GetCullMode() const -{ - uint32 cullMode(m_renderFlags & e_CullModeMask); - switch (cullMode) - { - case e_CullModeNone: - { - return(e_CullModeNone); - } - case e_CullModeFront: - { - return(e_CullModeFront); - } - case e_CullModeBack: - default: - { - assert(e_CullModeBack == cullMode); - return(e_CullModeBack); - } - } -} - - -inline void -SAuxGeomRenderFlags::SetCullMode(const EAuxGeomPublicRenderflags_CullMode& state) -{ - m_renderFlags &= ~e_CullModeMask; - m_renderFlags |= state; -} - - -inline EAuxGeomPublicRenderflags_DepthWrite -SAuxGeomRenderFlags::GetDepthWriteFlag() const -{ - uint32 depthWriteFlag(m_renderFlags & e_DepthWriteMask); - switch (depthWriteFlag) - { - case e_DepthWriteOff: - { - return(e_DepthWriteOff); - } - case e_DepthWriteOn: - default: - { - assert(e_DepthWriteOn == depthWriteFlag); - return(e_DepthWriteOn); - } - } -} - - -inline void -SAuxGeomRenderFlags::SetDepthWriteFlag(const EAuxGeomPublicRenderflags_DepthWrite& state) -{ - m_renderFlags &= ~e_DepthWriteMask; - m_renderFlags |= state; -} - - -inline EAuxGeomPublicRenderflags_DepthTest -SAuxGeomRenderFlags::GetDepthTestFlag() const -{ - uint32 depthTestFlag(m_renderFlags & e_DepthTestMask); - switch (depthTestFlag) - { - case e_DepthTestOff: - { - return(e_DepthTestOff); - } - case e_DepthTestOn: - default: - { - assert(e_DepthTestOn == depthTestFlag); - return(e_DepthTestOn); - } - } -} - - -inline void -SAuxGeomRenderFlags::SetDepthTestFlag(const EAuxGeomPublicRenderflags_DepthTest& state) -{ - m_renderFlags &= ~e_DepthTestMask; - m_renderFlags |= state; -} - - -class CRenderAuxGeomRenderFlagsRestore -{ -public: - explicit CRenderAuxGeomRenderFlagsRestore(IRenderAuxGeom* pRender); - ~CRenderAuxGeomRenderFlagsRestore(); - -private: - IRenderAuxGeom* m_pRender; - SAuxGeomRenderFlags m_backuppedRenderFlags; - - // copy-construction not supported - CRenderAuxGeomRenderFlagsRestore(const CRenderAuxGeomRenderFlagsRestore&); - CRenderAuxGeomRenderFlagsRestore& operator=(const CRenderAuxGeomRenderFlagsRestore&); -}; - -inline CRenderAuxGeomRenderFlagsRestore::CRenderAuxGeomRenderFlagsRestore(IRenderAuxGeom* pRender) -{ - m_pRender = pRender; - m_backuppedRenderFlags = m_pRender->GetRenderFlags(); -} - -inline CRenderAuxGeomRenderFlagsRestore::~CRenderAuxGeomRenderFlagsRestore() -{ - m_pRender->SetRenderFlags(m_backuppedRenderFlags); -} - - -#endif // CRYINCLUDE_CRYCOMMON_IRENDERAUXGEOM_H diff --git a/Code/CryEngine/CryCommon/IRenderMesh.h b/Code/CryEngine/CryCommon/IRenderMesh.h deleted file mode 100644 index 85797d45ea..0000000000 --- a/Code/CryEngine/CryCommon/IRenderMesh.h +++ /dev/null @@ -1,308 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_IRENDERMESH_H -#define CRYINCLUDE_CRYCOMMON_IRENDERMESH_H -#pragma once - -#include "VertexFormats.h" -#include <IMaterial.h> -#include <IShader.h> -#include <IRenderer.h> // PublicRenderPrimitiveType -#include <Cry_Geo.h> -#include <CryArray.h> -#include <ITimer.h> - -class CMesh; -struct CRenderChunk; -class CRenderObject; -struct SSkinningData; -struct IMaterial; -struct IShader; -struct IIndexedMesh; -struct SMRendTexVert; -struct UCol; -struct GeomInfo; - -struct TFace; -struct SMeshSubset; -struct SRenderingPassInfo; -struct SRendItemSorter; -struct SRenderObjectModifier; - -namespace AZ -{ - namespace Vertex - { - class Format; - } -} - -enum eRenderPrimitiveType : int8; - -// Keep this in sync with BUFFER_USAGE hints DevBuffer.h -enum ERenderMeshType -{ - eRMT_Immmutable = 0, - eRMT_Static = 1, - eRMT_Dynamic = 2, - eRMT_Transient = 3, -}; - - -#define FSM_VERTEX_VELOCITY 1 -#define FSM_NO_TANGENTS 2 -#define FSM_CREATE_DEVICE_MESH 4 -#define FSM_SETMESH_ASYNC 8 -#define FSM_ENABLE_NORMALSTREAM 16 -#define FSM_IGNORE_TEXELDENSITY 32 - -// Invalidate video buffer flags -#define FMINV_STREAM 1 -#define FMINV_STREAM_MASK ((1 << VSF_NUM) - 1) -#define FMINV_INDICES 0x100 -#define FMINV_ALL -1 - -// Stream lock flags -#define FSL_READ 0x01 -#define FSL_WRITE 0x02 -#define FSL_DYNAMIC 0x04 -#define FSL_DISCARD 0x08 -#define FSL_VIDEO 0x10 -#define FSL_SYSTEM 0x20 -#define FSL_INSTANCED 0x40 -#define FSL_NONSTALL_MAP 0x80 // Map must not stall for VB/IB locking -#define FSL_VBIBPUSHDOWN 0x100 // Push down from vram on demand if target architecture supports it, used internally -#define FSL_DIRECT 0x200 // Access VRAM directly if target architecture supports it, used internally -#define FSL_LOCKED 0x400 // Internal use -#define FSL_SYSTEM_CREATE (FSL_WRITE | FSL_DISCARD | FSL_SYSTEM) -#define FSL_SYSTEM_UPDATE (FSL_WRITE | FSL_SYSTEM) -#define FSL_VIDEO_CREATE (FSL_WRITE | FSL_DISCARD | FSL_VIDEO) -#define FSL_VIDEO_UPDATE (FSL_WRITE | FSL_VIDEO) - -#define FSL_ASYNC_DEFER_COPY (1u << 1) -#define FSL_FREE_AFTER_ASYNC (2u << 1) - -struct IRenderMesh -{ - enum EMemoryUsageArgument - { - MEM_USAGE_COMBINED, - MEM_USAGE_ONLY_SYSTEM, - MEM_USAGE_ONLY_VIDEO, - MEM_USAGE_ONLY_STREAMS, - }; - - // Render mesh initialization parameters, that can be used to create RenderMesh from raw pointers. - struct SInitParamerers - { - AZ::Vertex::Format vertexFormat; - ERenderMeshType eType; - - void* pVertBuffer; - int nVertexCount; - SPipTangents* pTangents; - SPipNormal* pNormals; - vtx_idx* pIndices; - int nIndexCount; - PublicRenderPrimitiveType nPrimetiveType; - int nRenderChunkCount; - int nClientTextureBindID; - bool bOnlyVideoBuffer; - bool bPrecache; - bool bLockForThreadAccess; - - SInitParamerers() - : vertexFormat(eVF_P3F_C4B_T2F) - , eType(eRMT_Static) - , pVertBuffer(0) - , nVertexCount(0) - , pTangents(0) - , pNormals(0) - , pIndices(0) - , nIndexCount(0) - , nPrimetiveType(prtTriangleList) - , nRenderChunkCount(0) - , nClientTextureBindID(0) - , bOnlyVideoBuffer(false) - , bPrecache(true) - , bLockForThreadAccess(false) {} - }; - - struct ThreadAccessLock - { - ThreadAccessLock(IRenderMesh* pRM) - : m_pRM(pRM) - { - m_pRM->LockForThreadAccess(); - } - - ~ThreadAccessLock() - { - m_pRM->UnLockForThreadAccess(); - } - - private: - ThreadAccessLock(const ThreadAccessLock&); - ThreadAccessLock& operator = (const ThreadAccessLock&); - - private: - IRenderMesh* m_pRM; - }; - - // <interfuscator:shuffle> - virtual ~IRenderMesh(){} - - ////////////////////////////////////////////////////////////////////////// - // Reference Counting. - virtual void AddRef() = 0; - virtual int Release() = 0; - ////////////////////////////////////////////////////////////////////////// - - // Prevent rendering if video memory could not been allocated for it - virtual bool CanRender() = 0; - - // Returns type name given to the render mesh on creation time. - virtual const char* GetTypeName() = 0; - // Returns the name of the source given to the render mesh on creation time. - virtual const char* GetSourceName() const = 0; - - virtual int GetIndicesCount() = 0; - virtual int GetVerticesCount() = 0; - virtual AZ::Vertex::Format GetVertexFormat() = 0; - virtual ERenderMeshType GetMeshType() = 0; - virtual float GetGeometricMeanFaceArea() const = 0; - - virtual bool CheckUpdate(uint32 nStreamMask) = 0; - virtual int GetStreamStride(int nStream) const = 0; - - virtual const uintptr_t GetVBStream(int nStream) const = 0; - virtual const uintptr_t GetIBStream() const = 0; - virtual int GetNumVerts() const = 0; - virtual int GetNumInds() const = 0; - virtual const eRenderPrimitiveType GetPrimitiveType() const = 0; - - virtual void SetSkinned(bool bSkinned = true) = 0; - virtual uint GetSkinningWeightCount() const = 0; - - // Create render buffers from render mesh. Returns the final size of the render mesh or ~0U on failure - virtual size_t SetMesh(CMesh& mesh, int nSecColorsSetOffset, uint32 flags, bool requiresLock) = 0; - virtual void CopyTo(IRenderMesh* pDst, int nAppendVtx = 0, bool bDynamic = false, bool fullCopy = true) = 0; - virtual void SetSkinningDataVegetation(struct SMeshBoneMapping_uint8* pBoneMapping) = 0; - virtual void SetSkinningDataCharacter(CMesh& mesh, struct SMeshBoneMapping_uint16* pBoneMapping, struct SMeshBoneMapping_uint16* pExtraBoneMapping) = 0; - // Creates an indexed mesh from this render mesh (accepts an optional pointer to an IIndexedMesh object that should be used) - virtual IIndexedMesh* GetIndexedMesh(IIndexedMesh* pIdxMesh = 0) = 0; - virtual int GetRenderChunksCount(_smart_ptr<IMaterial> pMat, int& nRenderTrisCount) = 0; - - virtual IRenderMesh* GenerateMorphWeights() = 0; - virtual IRenderMesh* GetMorphBuddy() = 0; - virtual void SetMorphBuddy(IRenderMesh* pMorph) = 0; - - virtual bool UpdateVertices(const void* pVertBuffer, int nVertCount, int nOffset, int nStream, uint32 copyFlags, bool requiresLock = true) = 0; - virtual bool UpdateIndices(const vtx_idx* pNewInds, int nInds, int nOffsInd, uint32 copyFlags, bool requiresLock = true) = 0; - virtual void SetCustomTexID(int nCustomTID) = 0; - virtual void SetChunk(int nIndex, CRenderChunk& chunk) = 0; - virtual void SetChunk(_smart_ptr<IMaterial> pNewMat, int nFirstVertId, int nVertCount, int nFirstIndexId, int nIndexCount, float texelAreaDensity, const AZ::Vertex::Format& vertexFormat, int nMatID = 0) = 0; - - // Assign array of render chunks. - // Initializes render element for each render chunk. - virtual void SetRenderChunks(CRenderChunk* pChunksArray, int nCount, bool bSubObjectChunks) = 0; - - virtual void GenerateQTangents() = 0; - virtual void CreateChunksSkinned() = 0; - virtual void NextDrawSkinned() = 0; - virtual IRenderMesh* GetVertexContainer() = 0; - virtual void SetVertexContainer(IRenderMesh* pBuf) = 0; - virtual TRenderChunkArray& GetChunks() = 0; - virtual TRenderChunkArray& GetChunksSkinned() = 0; - virtual TRenderChunkArray& GetChunksSubObjects() = 0; - virtual void SetBBox(const Vec3& vBoxMin, const Vec3& vBoxMax) = 0; - virtual void GetBBox(Vec3& vBoxMin, Vec3& vBoxMax) = 0; - virtual void UpdateBBoxFromMesh() = 0; - virtual uint32* GetPhysVertexMap() = 0; - virtual bool IsEmpty() = 0; - - virtual byte* GetPosPtrNoCache(int32& nStride, uint32 nFlags) = 0; - virtual byte* GetPosPtr(int32& nStride, uint32 nFlags) = 0; - virtual byte* GetColorPtr(int32& nStride, uint32 nFlags) = 0; - virtual byte* GetNormPtr(int32& nStride, uint32 nFlags) = 0; - //! Returns a pointer to the first uv coordinate in the interleaved vertex stream - virtual byte* GetUVPtrNoCache(int32& nStride, uint32 nFlags, uint32 uvSetIndex = 0) = 0; - /*! Get a pointer to the mesh's uv coordinates and the stride from the beginning of one uv coordinate to the next - \param[out] nStride The stride in between successive uv coordinates. - \param nFlags Stream lock flags (FSL_READ, FSL_WRITE, etc) - \param uvSetIndex Which uv set to retrieve (defaults to 0) - \return A pointer to cached uvs which contains all of the uv coordinates contiguous in memory, or as a fallback a pointer to the first uv coordinate in the interleaved vertex stream - Either way, nStride is set such that the caller can use it to iterate over the data in the same way regardless of which pointer was returned - Returns nullptr if there is no uv coordinate stream at the given index - */ - virtual byte* GetUVPtr(int32& nStride, uint32 nFlags, uint32 uvSetIndex = 0) = 0; - - virtual byte* GetTangentPtr(int32& nStride, uint32 nFlags) = 0; - virtual byte* GetQTangentPtr(int32& nStride, uint32 nFlags) = 0; - - virtual byte* GetHWSkinPtr(int32& nStride, uint32 nFlags, bool remapped = false) = 0; - virtual byte* GetVelocityPtr(int32& nStride, uint32 nFlags) = 0; - - virtual void UnlockStream(int nStream) = 0; - virtual void UnlockIndexStream() = 0; - - virtual vtx_idx* GetIndexPtr(uint32 nFlags, int32 nOffset = 0) = 0; - virtual const PodArray<std::pair<int, int> >* GetTrisForPosition(const Vec3& vPos, _smart_ptr<IMaterial> pMaterial) = 0; - - virtual float GetExtent(EGeomForm eForm) = 0; - virtual void GetRandomPos(PosNorm& ran, EGeomForm eForm, SSkinningData const* pSkinning = NULL) = 0; - - virtual void Render(const struct SRendParams& rParams, CRenderObject* pObj, _smart_ptr<IMaterial> pMaterial, const SRenderingPassInfo& passInfo, bool bSkinned = false) = 0; - virtual void Render(CRenderObject* pObj, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter) = 0; - virtual void AddRenderElements(_smart_ptr<IMaterial> pIMatInfo, CRenderObject* pObj, const SRenderingPassInfo& passInfo, int nSortId = EFSLIST_GENERAL, int nAW = 1) = 0; - virtual void AddRE(_smart_ptr<IMaterial> pMaterial, CRenderObject* pObj, IShader* pEf, const SRenderingPassInfo& passInfo, int nList, int nAW, const SRendItemSorter& rendItemSorter) = 0; - virtual void SetREUserData(float* pfCustomData, float fFogScale = 0, float fAlpha = 1) = 0; - - // Debug draw this render mesh. - virtual void DebugDraw(const struct SGeometryDebugDrawInfo& info, uint32 nVisibleChunksMask = ~0, float fExtrdueScale = 0.01f) = 0; - - // Returns mesh memory usage and add it to the CrySizer (if not NULL). - // Arguments: - // pSizer - Sizer interface, can be NULL if caller only want to calculate size - // nType - see EMemoryUsageArgument - virtual size_t GetMemoryUsage(ICrySizer* pSizer, EMemoryUsageArgument nType) const = 0; - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - - // Get allocated only in video memory or only in system memory. - virtual int GetAllocatedBytes(bool bVideoMem) const = 0; - virtual float GetAverageTrisNumPerChunk(_smart_ptr<IMaterial> pMat) = 0; - virtual int GetTextureMemoryUsage(const _smart_ptr<IMaterial> pMaterial, ICrySizer* pSizer = NULL, bool bStreamedIn = true) const = 0; - virtual void KeepSysMesh(bool keep) = 0; // HACK: temp workaround for GDC-888 - virtual void UnKeepSysMesh() = 0; - virtual void SetMeshLod(int nLod) = 0; - - virtual void LockForThreadAccess() = 0; - virtual void UnLockForThreadAccess() = 0; - - // Sets the async update state - will sync before rendering to this - virtual volatile int* SetAsyncUpdateState(void) = 0; - virtual void CreateRemappedBoneIndicesPair(const DynArray<JointIdType>& arrRemapTable, const uint pairGuid) = 0; - virtual void ReleaseRemappedBoneIndicesPair(const uint pairGuid) = 0; - - virtual void OffsetPosition(const Vec3& delta) = 0; - // </interfuscator:shuffle> -}; - -struct SBufferStream -{ - void* m_pLocalData; // pointer to buffer data - uintptr_t m_BufferHdl; - SBufferStream() - { - m_pLocalData = NULL; - m_BufferHdl = ~0u; - } -}; - -#endif // CRYINCLUDE_CRYCOMMON_IRENDERMESH_H diff --git a/Code/CryEngine/CryCommon/IRenderer.h b/Code/CryEngine/CryCommon/IRenderer.h deleted file mode 100644 index a72149f9c7..0000000000 --- a/Code/CryEngine/CryCommon/IRenderer.h +++ /dev/null @@ -1,2606 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include "Cry_Geo.h" -#include "Cry_Camera.h" -#include "ITexture.h" -#include "Cry_Vector2.h" -#include "Cry_Vector3.h" -#include "Cry_Matrix33.h" -#include "Cry_Color.h" -#include "smartptr.h" -#include "StringUtils.h" -#include <IXml.h> // <> required for Interfuscator -#include "smartptr.h" -#include <AzCore/Casting/numeric_cast.h> -#include <AzCore/std/containers/intrusive_slist.h> - -// forward declarations -struct SRenderingPassInfo; -struct SRTStack; -struct SFogVolumeData; -// Callback used for DXTCompress -typedef void (* MIPDXTcallback)(const void* buffer, size_t count, void* userData); - -typedef void (* GpuCallbackFunc)(DWORD context); - -// Callback for shadercache miss -typedef void (* ShaderCacheMissCallback)(const char* acShaderRequest); - -struct ICaptureFrameListener -{ - virtual ~ICaptureFrameListener (){} - virtual bool OnNeedFrameData(unsigned char*& pConvertedTextureBuf) = 0; - virtual void OnFrameCaptured(void) = 0; - virtual int OnGetFrameWidth(void) = 0; - virtual int OnGetFrameHeight(void) = 0; - virtual int OnCaptureFrameBegin(int* pTexHandle) = 0; - - enum ECaptureFrameFlags - { - eCFF_NoCaptureThisFrame = (0 << 1), - eCFF_CaptureThisFrame = (1 << 1), - }; -}; - -// Forward declarations. -////////////////////////////////////////////////////////////////////// -typedef void* WIN_HWND; -typedef void* WIN_HINSTANCE; -typedef void* WIN_HDC; -typedef void* WIN_HGLRC; - -class CREMesh; -class CMesh; -//class CImage; -struct CStatObj; -class CVegetation; -struct ShadowMapFrustum; -struct IStatObj; -class CObjManager; -struct SPrimitiveGroup; -class CRendElementBase; -class CRenderObject; -class CTexMan; -//class ColorF; -class CShadowVolEdge; -class CCamera; -class CDLight; -struct SDeferredLightVolume; -struct ILog; -struct IConsole; -struct ICVar; -struct ITimer; -struct ISystem; -class IGPUParticleEngine; -class ICrySizer; -struct IRenderAuxGeom; -struct SREPointSpriteCreateParams; -struct SPointSpriteVertex; -struct RenderLMData; -struct SShaderParam; -struct SSkyLightRenderParams; -struct SParticleRenderInfo; -struct SParticleAddJobCompare; -struct IColorGradingController; -class IStereoRenderer; -struct IFFont; -struct IFFont_RenderProxy; -struct STextDrawContext; -struct IRenderMesh; -struct ShadowFrustumMGPUCache; -struct IAsyncTextureCompileListener; -struct IClipVolume; -struct SClipVolumeBlendInfo; -class CRenderView; -struct SDynTexture2; -class CTexture; -enum ETexPool : int; - -////////////////////////////////////////////////////////////////////// -typedef unsigned char bvec4[4]; -typedef float vec4_t[4]; -typedef unsigned char byte; -typedef float vec2_t[2]; - -//DOC-IGNORE-BEGIN -#include "Cry_Color.h" -#include "Tarray.h" - -#include <IFont.h> -//DOC-IGNORE-END - -#define MAX_NUM_VIEWPORTS 7 - -// Query types for CryInd editor (used in EF_Query() function). -enum ERenderQueryTypes -{ - EFQ_DeleteMemoryArrayPtr = 1, - EFQ_DeleteMemoryPtr, - EFQ_GetShaderCombinations, - EFQ_SetShaderCombinations, - EFQ_CloseShaderCombinations, - - EFQ_MainThreadList, - EFQ_RenderThreadList, - EFQ_RenderMultithreaded, - - EFQ_RecurseLevel, - EFQ_IncrementFrameID, - EFQ_DeviceLost, - EFQ_LightSource, - - EFQ_Alloc_APITextures, - EFQ_Alloc_APIMesh, - - // Memory allocated by meshes in system memory. - EFQ_Alloc_Mesh_SysMem, - EFQ_Mesh_Count, - - EFQ_HDRModeEnabled, - EFQ_ParticlesTessellation, - EFQ_WaterTessellation, - EFQ_MeshTessellation, - EFQ_GetShadowPoolFrustumsNum, - EFQ_GetShadowPoolAllocThisFrameNum, - EFQ_GetShadowMaskChannelsNum, - EFQ_GetTiledShadingSkippedLightsNum, - - // Description: - // Query will return all textures in the renderer, - // pass pointer to an SRendererQueryGetAllTexturesParam instance - EFQ_GetAllTextures, - - // Description: - // Release resources allocated by GetAllTextures query - // pass pointer to an SRendererQueryGetAllTexturesParam instance, populated by EFQ_GetAllTextures - EFQ_GetAllTexturesRelease, - - // Description: - // Query will return all IRenderMesh objects in the renderer, - // Pass an array pointer to be allocated and filled with the IRendermesh pointers. The calling function is responsible for freeing this memory. - // This was originally a two pass process, but proved to be non-thread-safe, leading to buffer overruns and underruns. - EFQ_GetAllMeshes, - - // Summary: - // Multigpu (crossfire/sli) is enabled. - EFQ_MultiGPUEnabled, - EFQ_SetDrawNearFov, - EFQ_GetDrawNearFov, - EFQ_TextureStreamingEnabled, - EFQ_MSAAEnabled, - EFQ_AAMode, - - EFQ_Fullscreen, - EFQ_GetTexStreamingInfo, - EFQ_GetMeshPoolInfo, - - // Description: - // True when shading is done in linear space, de-gamma on texture lookup, gamma on frame buffer writing (sRGB), false otherwise. - EFQ_sLinearSpaceShadingEnabled, - - // The percentages of overscan borders for left/right and top/bottom to adjust the title safe area. - EFQ_OverscanBorders, - - // Get num active post effects - EFQ_NumActivePostEffects, - - // Get size of textures memory pool - EFQ_TexturesPoolSize, - EFQ_RenderTargetPoolSize, - - EFQ_GetShaderCacheInfo, - - EFQ_GetFogCullDistance, - EFQ_GetMaxRenderObjectsNum, - - EFQ_IsRenderLoadingThreadActive, - - EFQ_GetSkinningDataPoolSize, - - EFQ_GetViewportDownscaleFactor, - EFQ_ReverseDepthEnabled, - - EFQ_GetLastD3DDebugMessage -}; - -struct ID3DDebugMessage -{ -public: - virtual void Release() = 0; - virtual const char* GetMessage() const = 0; - -protected: - ID3DDebugMessage() {} - virtual ~ID3DDebugMessage() {} -}; - -enum EScreenAspectRatio -{ - eAspect_Unknown, - eAspect_4_3, - eAspect_16_9, - eAspect_16_10, -}; - -class SBoundingVolume -{ -public: - SBoundingVolume() - : m_vCenter(0, 0, 0) - , m_fRadius(0) {} - ~SBoundingVolume() {} - - void SetCenter(const Vec3& center) { m_vCenter = center; } - void SetRadius(float radius) { m_fRadius = radius; } - const Vec3& GetCenter() const { return m_vCenter; } - float GetRadius() const { return m_fRadius; } - -protected: - Vec3 m_vCenter; - float m_fRadius; -}; - -class SMinMaxBox - : public SBoundingVolume -{ -public: - SMinMaxBox() - { - Clear(); - } - SMinMaxBox(const Vec3& min, const Vec3& max) : - m_min(min), - m_max(max) - { - UpdateSphere(); - } - - // Summary: - // Destructor - virtual ~SMinMaxBox() {} - - void AddPoint(const Vec3& pt) - { - if (pt.x > m_max.x) - { - m_max.x = pt.x; - } - if (pt.x < m_min.x) - { - m_min.x = pt.x; - } - - if (pt.y > m_max.y) - { - m_max.y = pt.y; - } - if (pt.y < m_min.y) - { - m_min.y = pt.y; - } - - if (pt.z > m_max.z) - { - m_max.z = pt.z; - } - if (pt.z < m_min.z) - { - m_min.z = pt.z; - } - - // Summary: - // Updates the center and radius. - UpdateSphere(); - } - void AddPoint(float x, float y, float z) - { - AddPoint(Vec3(x, y, z)); - } - - void Union(const SMinMaxBox& box) { AddPoint(box.GetMin()); AddPoint(box.GetMax()); } - - const Vec3& GetMin() const { return m_min; } - const Vec3& GetMax() const { return m_max; } - - void SetMin(const Vec3& min) { m_min = min; UpdateSphere(); } - void SetMax(const Vec3& max) { m_max = max; UpdateSphere(); } - - float GetWidthInX() const { return m_max.x - m_min.x; } - float GetWidthInY() const { return m_max.y - m_min.y; } - float GetWidthInZ() const { return m_max.z - m_min.z; } - - bool PointInBBox(const Vec3& pt) const; - - bool ViewFrustumCull(const CameraViewParameters& viewParameters, const Matrix44& mat); - - void Transform(const Matrix34& mat) - { - Vec3 verts[8]; - CalcVerts(verts); - Clear(); - for (int i = 0; i < 8; i++) - { - AddPoint(mat.TransformPoint(verts[i])); - } - } - - // Summary: - // Resets the bounding box. - void Clear() - { - m_min = Vec3(999999.0f, 999999.0f, 999999.0f); - m_max = Vec3(-999999.0f, -999999.0f, -999999.0f); - } - -protected: - void UpdateSphere() - { - m_vCenter = m_min; - m_vCenter += m_max; - m_vCenter *= 0.5f; - - Vec3 rad = m_max; - rad -= m_vCenter; - m_fRadius = rad.len(); - } - void CalcVerts(Vec3 pVerts[8]) const - { - pVerts[0].Set(m_max.x, m_max.y, m_max.z); - pVerts[4].Set(m_max.x, m_max.y, m_min.z); - pVerts[1].Set(m_min.x, m_max.y, m_max.z); - pVerts[5].Set(m_min.x, m_max.y, m_min.z); - pVerts[2].Set(m_min.x, m_min.y, m_max.z); - pVerts[6].Set(m_min.x, m_min.y, m_min.z); - pVerts[3].Set(m_max.x, m_min.y, m_max.z); - pVerts[7].Set(m_max.x, m_min.y, m_min.z); - } - -private: - Vec3 m_min; // Original object space BV. - Vec3 m_max; -}; - - - -////////////////////////////////////////////////////////////////////// -// All possible primitive types - -enum PublicRenderPrimitiveType -{ - prtTriangleList, - prtTriangleStrip, - prtLineList, - prtLineStrip -}; - -////////////////////////////////////////////////////////////////////// -#define R_CULL_DISABLE 0 -#define R_CULL_NONE 0 -#define R_CULL_FRONT 1 -#define R_CULL_BACK 2 - -////////////////////////////////////////////////////////////////////// -#define R_DEFAULT_LODBIAS 0 - -////////////////////////////////////////////////////////////////////// -#define R_SOLID_MODE 0 -#define R_WIREFRAME_MODE 1 - -#define R_DX9_RENDERER 2 -#define R_DX11_RENDERER 3 -#define R_NULL_RENDERER 4 -#define R_CUBAGL_RENDERER 5 -#define R_GL_RENDERER 6 -#define R_METAL_RENDERER 7 -#define R_DX12_RENDERER 8 - -////////////////////////////////////////////////////////////////////// -// Render features - -#define RFT_FREE_0x1 0x1 -#define RFT_ALLOW_RECTTEX 0x2 -#define RFT_OCCLUSIONQUERY 0x4 -#define RFT_FREE_0x8 0x8 -#define RFT_HWGAMMA 0x10 -#define RFT_FREE_0x20 0x20 -#define RFT_COMPRESSTEXTURE 0x40 -#define RFT_FREE_0x80 0x80 -#define RFT_ALLOWANISOTROPIC 0x100 // Allows anisotropic texture filtering. -#define RFT_SUPPORTZBIAS 0x200 -#define RFT_FREE_0x400 0x400 -#define RFT_FREE_0x800 0x800 -#define RFT_FREE_0x1000 0x1000 -#define RFT_FREE_0x2000 0x2000 -#define RFT_OCCLUSIONTEST 0x8000 // Support hardware occlusion test. - -#define RFT_HW_ARM_MALI 0x04000 // Unclassified ARM (MALI) hardware. -#define RFT_HW_INTEL 0x10000 // Unclassified intel hardware. -#define RFT_HW_QUALCOMM 0x10000 // Unclassified Qualcomm hardware -#define RFT_HW_ATI 0x20000 // Unclassified ATI hardware. -#define RFT_HW_NVIDIA 0x40000 // Unclassified NVidia hardware. -#define RFT_HW_MASK 0x74000 // Graphics chip mask. - -#define RFT_HW_HDR 0x80000 // Hardware supports high dynamic range rendering. - -#define RFT_HW_SM20 0x100000 // Shader model 2.0 -#define RFT_HW_SM2X 0x200000 // Shader model 2.X -#define RFT_HW_SM30 0x400000 // Shader model 3.0 -#define RFT_HW_SM40 0x800000 // Shader model 4.0 -#define RFT_HW_SM50 0x1000000 // Shader model 5.0 - -#define RFT_FREE_0x2000000 0x2000000 -#define RFT_FREE_0x4000000 0x4000000 -#define RFT_FREE_0x8000000 0x8000000 - -#define RFT_HW_VERTEX_STRUCTUREDBUF 0x10000000 // Supports Structured Buffers in the Vertex Shader. -#define RFT_RGBA 0x20000000 // RGBA order (otherwise BGRA). -#define RFT_COMPUTE_SHADERS 0x40000000 // Compute Shaders support -#define RFT_HW_VERTEXTEXTURES 0x80000000 // Vertex texture fetching supported. - -//==================================================================== -// PrecacheResources flags - -#define FPR_NEEDLIGHT 1 -#define FPR_2D 2 -#define FPR_HIGHPRIORITY 4 -#define FPR_SYNCRONOUS 8 -#define FPR_STARTLOADING 16 -#define FPR_SINGLE_FRAME_PRIORITY_UPDATE 32 - -//===================================================================== -// SetRenderTarget flags -#define SRF_SCREENTARGET 1 -#define SRF_USE_ORIG_DEPTHBUF 2 -#define SRF_USE_ORIG_DEPTHBUF_MSAA 4 - -//==================================================================== -// Draw shaders flags (EF_EndEf3d) - -#define SHDF_ALLOWHDR BIT(0) -#define SHDF_CUBEMAPGEN BIT(1) -#define SHDF_ZPASS BIT(2) -#define SHDF_ZPASS_ONLY BIT(3) -#define SHDF_DO_NOT_CLEAR_Z_BUFFER BIT(4) -#define SHDF_ALLOWPOSTPROCESS BIT(5) -#define SHDF_ALLOW_AO BIT(8) -#define SHDF_ALLOW_WATER BIT(9) -#define SHDF_NOASYNC BIT(10) -#define SHDF_NO_DRAWNEAR BIT(11) -#define SHDF_STREAM_SYNC BIT(13) -#define SHDF_NO_SHADOWGEN BIT(15) - -////////////////////////////////////////////////////////////////////// -// Virtual screen size -const float VIRTUAL_SCREEN_WIDTH = 800.0f; -const float VIRTUAL_SCREEN_HEIGHT = 600.0f; - -////////////////////////////////////////////////////////////////////// -// Object states -#define OS_ALPHA_BLEND 0x1 -#define OS_ADD_BLEND 0x2 -#define OS_MULTIPLY_BLEND 0x4 -#define OS_TRANSPARENT (OS_ALPHA_BLEND | OS_ADD_BLEND | OS_MULTIPLY_BLEND) -#define OS_NODEPTH_TEST 0x8 -#define OS_NODEPTH_WRITE 0x10 -#define OS_ANIM_BLEND 0x20 -#define OS_ENVIRONMENT_CUBEMAP 0x40 - -// Render State flags -#define GS_BLSRC_MASK 0xf -#define GS_BLSRC_ZERO 0x1 -#define GS_BLSRC_ONE 0x2 -#define GS_BLSRC_DSTCOL 0x3 -#define GS_BLSRC_ONEMINUSDSTCOL 0x4 -#define GS_BLSRC_SRCALPHA 0x5 -#define GS_BLSRC_ONEMINUSSRCALPHA 0x6 -#define GS_BLSRC_DSTALPHA 0x7 -#define GS_BLSRC_ONEMINUSDSTALPHA 0x8 -#define GS_BLSRC_ALPHASATURATE 0x9 -#define GS_BLSRC_SRCALPHA_A_ZERO 0xa // separate alpha blend state -#define GS_BLSRC_SRC1ALPHA 0xb // dual source blending - - -#define GS_BLDST_MASK 0xf0 -#define GS_BLDST_ZERO 0x10 -#define GS_BLDST_ONE 0x20 -#define GS_BLDST_SRCCOL 0x30 -#define GS_BLDST_ONEMINUSSRCCOL 0x40 -#define GS_BLDST_SRCALPHA 0x50 -#define GS_BLDST_ONEMINUSSRCALPHA 0x60 -#define GS_BLDST_DSTALPHA 0x70 -#define GS_BLDST_ONEMINUSDSTALPHA 0x80 -#define GS_BLDST_ONE_A_ZERO 0x90 // separate alpha blend state -#define GS_BLDST_ONEMINUSSRC1ALPHA 0xa0 // dual source blending - - -#define GS_DEPTHWRITE 0x00000100 - -#define GS_COLMASK_RT1 0x00000200 -#define GS_COLMASK_RT2 0x00000400 -#define GS_COLMASK_RT3 0x00000800 - -#define GS_NOCOLMASK_R 0x00001000 -#define GS_NOCOLMASK_G 0x00002000 -#define GS_NOCOLMASK_B 0x00004000 -#define GS_NOCOLMASK_A 0x00008000 -#define GS_COLMASK_RGB (GS_NOCOLMASK_A) -#define GS_COLMASK_A (GS_NOCOLMASK_R | GS_NOCOLMASK_G | GS_NOCOLMASK_B) -#define GS_COLMASK_NONE (GS_NOCOLMASK_R | GS_NOCOLMASK_G | GS_NOCOLMASK_B | GS_NOCOLMASK_A) -#define GS_COLMASK_MASK GS_COLMASK_NONE -#define GS_COLMASK_SHIFT 12 - -#define GS_WIREFRAME 0x00010000 -#define GS_NODEPTHTEST 0x00040000 - -#define GS_BLEND_MASK 0x0f0000ff - -#define GS_DEPTHFUNC_LEQUAL 0x00000000 -#define GS_DEPTHFUNC_EQUAL 0x00100000 -#define GS_DEPTHFUNC_GREAT 0x00200000 -#define GS_DEPTHFUNC_LESS 0x00300000 -#define GS_DEPTHFUNC_GEQUAL 0x00400000 -#define GS_DEPTHFUNC_NOTEQUAL 0x00500000 -#define GS_DEPTHFUNC_HIZEQUAL 0x00600000 // keep hi-z test, always pass fine depth. Useful for debug display -#define GS_DEPTHFUNC_ALWAYS 0x00700000 -#define GS_DEPTHFUNC_MASK 0x00700000 - -#define GS_STENCIL 0x00800000 - -#define GS_BLEND_OP_MASK 0x03000000 -#define GS_BLOP_MAX 0x01000000 -#define GS_BLOP_MIN 0x02000000 - -// Separate alpha blend mode -#define GS_BLALPHA_MASK 0x0c000000 -#define GS_BLALPHA_MIN 0x04000000 -#define GS_BLALPHA_MAX 0x08000000 - -#define GS_ALPHATEST_MASK 0xf0000000 -#define GS_ALPHATEST_GREATER 0x10000000 -#define GS_ALPHATEST_LESS 0x20000000 -#define GS_ALPHATEST_GEQUAL 0x40000000 -#define GS_ALPHATEST_LEQUAL 0x80000000 - -#define FORMAT_8_BIT 8 -#define FORMAT_24_BIT 24 -#define FORMAT_32_BIT 32 - -//================================================================== -// StencilStates - -//Note: If these are altered, g_StencilFuncLookup and g_StencilOpLookup arrays -// need to be updated in turn - -#define FSS_STENCFUNC_ALWAYS 0x0 -#define FSS_STENCFUNC_NEVER 0x1 -#define FSS_STENCFUNC_LESS 0x2 -#define FSS_STENCFUNC_LEQUAL 0x3 -#define FSS_STENCFUNC_GREATER 0x4 -#define FSS_STENCFUNC_GEQUAL 0x5 -#define FSS_STENCFUNC_EQUAL 0x6 -#define FSS_STENCFUNC_NOTEQUAL 0x7 -#define FSS_STENCFUNC_MASK 0x7 - -#define FSS_STENCIL_TWOSIDED 0x8 - -#define FSS_CCW_SHIFT 16 - -#define FSS_STENCOP_KEEP 0x0 -#define FSS_STENCOP_REPLACE 0x1 -#define FSS_STENCOP_INCR 0x2 -#define FSS_STENCOP_DECR 0x3 -#define FSS_STENCOP_ZERO 0x4 -#define FSS_STENCOP_INCR_WRAP 0x5 -#define FSS_STENCOP_DECR_WRAP 0x6 -#define FSS_STENCOP_INVERT 0x7 - -#define FSS_STENCFAIL_SHIFT 4 -#define FSS_STENCFAIL_MASK (0x7 << FSS_STENCFAIL_SHIFT) - -#define FSS_STENCZFAIL_SHIFT 8 -#define FSS_STENCZFAIL_MASK (0x7 << FSS_STENCZFAIL_SHIFT) - -#define FSS_STENCPASS_SHIFT 12 -#define FSS_STENCPASS_MASK (0x7 << FSS_STENCPASS_SHIFT) - -#define STENC_FUNC(op) (op) -#define STENC_CCW_FUNC(op) (op << FSS_CCW_SHIFT) -#define STENCOP_FAIL(op) (op << FSS_STENCFAIL_SHIFT) -#define STENCOP_ZFAIL(op) (op << FSS_STENCZFAIL_SHIFT) -#define STENCOP_PASS(op) (op << FSS_STENCPASS_SHIFT) -#define STENCOP_CCW_FAIL(op) (op << (FSS_STENCFAIL_SHIFT + FSS_CCW_SHIFT)) -#define STENCOP_CCW_ZFAIL(op) (op << (FSS_STENCZFAIL_SHIFT + FSS_CCW_SHIFT)) -#define STENCOP_CCW_PASS(op) (op << (FSS_STENCPASS_SHIFT + FSS_CCW_SHIFT)) - -//Stencil masks -#define BIT_STENCIL_RESERVED 0x80 -#define BIT_STENCIL_INSIDE_CLIPVOLUME 0x40 -#define STENC_VALID_BITS_NUM 7 -#define STENC_MAX_REF ((1 << STENC_VALID_BITS_NUM) - 1) - -// Read FrameBuffer type -enum ERB_Type -{ - eRB_BackBuffer, - eRB_FrontBuffer, - eRB_ShadowBuffer -}; - -enum EVertexCostTypes -{ - EVCT_STATIC = 0, - EVCT_VEGETATION, - EVCT_SKINNED, - EVCT_NUM -}; - -////////////////////////////////////////////////////////////////////// - -struct SDispFormat -{ - int m_Width; - int m_Height; - int m_BPP; -}; - -struct SAAFormat -{ - char szDescr[64]; - int nSamples; - int nQuality; -}; - -// Summary: -// Info about Terrain sector texturing. -struct SSectorTextureSet -{ - SSectorTextureSet(unsigned short nT0) - { - nTex0 = nT0; - fTexOffsetX = fTexOffsetY = 0; - fTexScale = 1.f; - } - - unsigned short nTex0; - float fTexOffsetX, fTexOffsetY, fTexScale; -}; - -struct IRenderNode; -struct SShaderItem; - -#ifdef SUPPORT_HW_MOUSE_CURSOR -class IHWMouseCursor -{ -public: - virtual ~IHWMouseCursor() {} - virtual void SetPosition(int x, int y) = 0; - virtual void Show() = 0; - virtual void Hide() = 0; -}; -#endif - -////////////////////////////////////////////////////////////////////// -//DOC-IGNORE-BEGIN -#include <IShader.h> // <> required for Interfuscator -//DOC-IGNORE-END -#include <IRenderMesh.h> - -// Flags passed in function FreeResources. -#define FRR_SHADERS 1 -#define FRR_SHADERTEXTURES 2 -#define FRR_TEXTURES 4 -#define FRR_SYSTEM 8 -#define FRR_RESTORE 0x10 -#define FRR_REINITHW 0x20 -#define FRR_DELETED_MESHES 0x40 -#define FRR_FLUSH_TEXTURESTREAMING 0x80 -#define FRR_OBJECTS 0x100 -#define FRR_RENDERELEMENTS 0x200 -#define FRR_RP_BUFFERS 0x400 -#define FRR_SYSTEM_RESOURCES 0x800 -#define FRR_POST_EFFECTS 0x1000 -#define FRR_ALL -1 - -// Refresh render resources flags. -// Flags passed in function RefreshResources. -#define FRO_SHADERS 1 -#define FRO_SHADERTEXTURES 2 -#define FRO_TEXTURES 4 -#define FRO_GEOMETRY 8 -#define FRO_FORCERELOAD 0x10 - -//============================================================================= -// Shaders render target stuff. - -#define FRT_CLEAR_DEPTH 0x1 -#define FRT_CLEAR_STENCIL 0x2 -#define FRT_CLEAR_COLOR 0x4 -#define FRT_CLEAR (FRT_CLEAR_COLOR | FRT_CLEAR_DEPTH | FRT_CLEAR_STENCIL) -#define FRT_CLEAR_FOGCOLOR 0x8 -#define FRT_CLEAR_IMMEDIATE 0x10 -#define FRT_CLEAR_COLORMASK 0x20 -#define FRT_CLEAR_RESET_VIEWPORT 0x40 - -#define FRT_CAMERA_REFLECTED_WATERPLANE 0x40 -#define FRT_CAMERA_REFLECTED_PLANE 0x80 -#define FRT_CAMERA_CURRENT 0x100 - -#define FRT_USE_FRONTCLIPPLANE 0x200 -#define FRT_USE_BACKCLIPPLANE 0x400 - -#define FRT_GENERATE_MIPS 0x800 - -#define FRT_RENDTYPE_CUROBJECT 0x1000 -#define FRT_RENDTYPE_CURSCENE 0x2000 -#define FRT_RENDTYPE_RECURSIVECURSCENE 0x4000 -#define FRT_RENDTYPE_COPYSCENE 0x8000 - -// Summary: -// Flags used in DrawText function. -// See also: -// SDrawTextInfo -// Remarks: -// Text must be fixed pixel size. -enum EDrawTextFlags -{ - eDrawText_Left = 0, // default left alignment if neither Center or Right are specified - eDrawText_Center = BIT(0), // centered alignment, otherwise right or left - eDrawText_Right = BIT(1), // right alignment, otherwise center or left - eDrawText_CenterV = BIT(2), // center vertically, otherwise top - eDrawText_Bottom = BIT(3), // bottom alignment - - eDrawText_2D = BIT(4), // 3 component vector is used for xy screen position, otherwise it's 3d world space position - - eDrawText_FixedSize = BIT(5), // font size is defined in the actual pixel resolution, otherwise it's in the virtual 800x600 - eDrawText_800x600 = BIT(6), // position are specified in the virtual 800x600 resolution, otherwise coordinates are in pixels - - eDrawText_Monospace = BIT(7), // non proportional font rendering (Font width is same for all characters) - - eDrawText_Framed = BIT(8), // draw a transparent, rectangular frame behind the text to ease readability independent from the background - - eDrawText_DepthTest = BIT(9), // text should be occluded by world geometry using the depth buffer - eDrawText_IgnoreOverscan = BIT(10), // ignore the overscan borders, text should be drawn at the location specified - eDrawText_UseTransform = BIT(11), // use a transform for the text -}; - -// Debug stats/views for Partial resolves -// if REFRACTION_PARTIAL_RESOLVE_DEBUG_VIEWS is enabled, make sure REFRACTION_PARTIAL_RESOLVE_STATS is too -#if defined(PERFORMANCE_BUILD) - #define REFRACTION_PARTIAL_RESOLVE_STATS 1 - #define REFRACTION_PARTIAL_RESOLVE_DEBUG_VIEWS 0 -#elif defined(_RELEASE) // note: _RELEASE is defined in PERFORMANCE_BUILD, so this check must come second - #define REFRACTION_PARTIAL_RESOLVE_STATS 0 - #define REFRACTION_PARTIAL_RESOLVE_DEBUG_VIEWS 0 -#else - #define REFRACTION_PARTIAL_RESOLVE_STATS 1 - #define REFRACTION_PARTIAL_RESOLVE_DEBUG_VIEWS 1 -#endif - -#if REFRACTION_PARTIAL_RESOLVE_DEBUG_VIEWS -enum ERefractionPartialResolvesDebugViews -{ - eRPR_DEBUG_VIEW_2D_AREA = 1, - eRPR_DEBUG_VIEW_3D_BOUNDS, - eRPR_DEBUG_VIEW_2D_AREA_OVERLAY -}; -#endif - -////////////////////////////////////////////////////////////////////////// -// Description: -// This structure used in DrawText method of renderer. -// It provide all necessary information of how to render text on screen. -// See also: -// IRenderer::Draw2dText -struct SDrawTextInfo -{ - // Summary: - // One of EDrawTextFlags flags. - // See also: - // EDrawTextFlags - int flags; - // Summary: - // Text color, (r,g,b,a) all members must be specified. - float color[4]; - float xscale; - float yscale; - - SDrawTextInfo() - { - flags = 0; - color[0] = color[1] = color[2] = color[3] = 1; - xscale = 1.0f; - yscale = 1.0f; - } -}; - -#define UIDRAW_TEXTSIZEFACTOR (12.0f) -#define MIN_RESOLUTION_SCALE (0.25f) -#define MAX_RESOLUTION_SCALE (4.0f) - -#if defined(AZ_RESTRICTED_PLATFORM) - #include AZ_RESTRICTED_FILE(IRenderer_h) -#else -//SLI/CROSSFIRE GPU maximum count - #define MAX_GPU_NUM 4 -#endif - -#define MAX_FRAME_ID_STEP_PER_FRAME 20 -const int MAX_GSM_LODS_NUM = 16; - -const f32 DRAW_NEAREST_MIN = 0.03f; -const f32 DRAW_NEAREST_MAX = 40.0f; - -//=================================================================== - -////////////////////////////////////////////////////////////////////// -struct IRenderDebugListener -{ - virtual ~IRenderDebugListener() {} - - virtual void OnDebugDraw() = 0; -}; - -////////////////////////////////////////////////////////////////////// -struct ILoadtimeCallback -{ - virtual void LoadtimeUpdate(float fDeltaTime) = 0; - virtual void LoadtimeRender() = 0; - virtual ~ILoadtimeCallback(){} -}; - -////////////////////////////////////////////////////////////////////// -struct ISyncMainWithRenderListener -{ - virtual void SyncMainWithRender() = 0; - virtual ~ISyncMainWithRenderListener(){} -}; - -////////////////////////////////////////////////////////////////////// -enum ERenderType -{ - eRT_Undefined, - eRT_Null, - eRT_DX11, - eRT_DX12, - eRT_Provo, - eRT_OpenGL, - eRT_Metal, - eRT_Jasper, -}; - -////////////////////////////////////////////////////////////////////// -// Enum for types of deferred lights -enum eDeferredLightType -{ - eDLT_DeferredLight = 0, - - eDLT_NumShadowCastingLights = eDLT_DeferredLight + 1, - // these lights cannot cast shadows - eDLT_DeferredCubemap = eDLT_NumShadowCastingLights, - eDLT_DeferredAmbientLight, - eDLT_NumLightTypes, -}; - -const float RENDERER_LIGHT_UNIT_SCALE = 10000.0f; // Scale factor between photometric and internal light units - -////////////////////////////////////////////////////////////////////// -struct SCustomRenderInitArgs -{ - bool appStartedFromMediaCenter; -}; - -#if defined(ANDROID) -enum -{ - CULL_SIZEX = 128 -}; -enum -{ - CULL_SIZEY = 64 -}; -#else -enum -{ - CULL_SIZEX = 256 -}; -enum -{ - CULL_SIZEY = 128 -}; -#endif - -////////////////////////////////////////////////////////////////////// -// Description: -// Z-buffer as occlusion buffer definitions: used, shared and initialized in engine and renderer. -struct SHWOccZBuffer -{ - uint32* pHardwareZBuffer; - uint32* pZBufferVMem; - uint32 ZBufferSizeX; - uint32 ZBufferSizeY; - uint32 HardwareZBufferRSXOff; - uint32 ZBufferVMemRSXOff; - uint32 pad[2]; // Keep 32 byte aligned - SHWOccZBuffer() - : pHardwareZBuffer(NULL) - , pZBufferVMem(NULL) - , ZBufferSizeX(CULL_SIZEX) - , ZBufferSizeY(CULL_SIZEY) - , ZBufferVMemRSXOff(0) - , HardwareZBufferRSXOff(0){} -}; - -class ITextureStreamListener -{ -public: - virtual void OnCreatedStreamedTexture(void* pHandle, const char* name, int nMips, int nMinMipAvailable) = 0; - virtual void OnDestroyedStreamedTexture(void* pHandle) = 0; - virtual void OnTextureWantsMip(void* pHandle, int nMinMip) = 0; - virtual void OnTextureHasMip(void* pHandle, int nMinMip) = 0; - virtual void OnBegunUsingTextures(void** pHandles, size_t numHandles) = 0; - virtual void OnEndedUsingTextures(void** pHandle, size_t numHandles) = 0; - -protected: - virtual ~ITextureStreamListener() {} -}; - -enum eDolbyVisionMode -{ - eDVM_Disabled, - eDVM_RGBPQ, - eDVM_Vision, -}; - -enum ERenderPipelineProfilerStats -{ - eRPPSTATS_OverallFrame = 0, - eRPPSTATS_Recursion, - - // Scene - eRPPSTATS_SceneOverall, - eRPPSTATS_SceneDecals, - eRPPSTATS_SceneForward, - eRPPSTATS_SceneWater, - - // Shadows - eRPPSTATS_ShadowsOverall, - eRPPSTATS_ShadowsSun, - eRPPSTATS_ShadowsSunCustom, - eRPPSTATS_ShadowsLocal, - - // Lighting - eRPPSTATS_LightingOverall, - eRPPSTATS_LightingGI, - - // VFX - eRPPSTATS_VfxOverall, - eRPPSTATS_VfxTransparent, - eRPPSTATS_VfxFog, - eRPPSTATS_VfxFlares, - - // Individual Total Illumination stats - eRPPSTATS_TI_INJECT_CLEAR, - eRPPSTATS_TI_VOXELIZE, - eRPPSTATS_TI_INJECT_AIR, - eRPPSTATS_TI_INJECT_LIGHT, - eRPPSTATS_TI_INJECT_REFL0, - eRPPSTATS_TI_INJECT_REFL1, - eRPPSTATS_TI_INJECT_DYNL, - eRPPSTATS_TI_NID_DIFF, - eRPPSTATS_TI_GEN_DIFF, - eRPPSTATS_TI_GEN_SPEC, - eRPPSTATS_TI_GEN_AIR, - eRPPSTATS_TI_DEMOSAIC_DIFF, - eRPPSTATS_TI_DEMOSAIC_SPEC, - eRPPSTATS_TI_UPSCALE_DIFF, - eRPPSTATS_TI_UPSCALE_SPEC, - - RPPSTATS_NUM -}; - -struct RPProfilerStats -{ - float gpuTime; - float gpuTimeSmoothed; - float gpuTimeMax; - float cpuTime; - uint32 numDIPs; - uint32 numPolys; - - // Internal - float _gpuTimeMaxNew; -}; - -struct TransformationMatrices -{ - Matrix44A m_viewMatrix; - Matrix44A m_projectMatrix; -}; - -struct ISvoRenderer -{ - virtual bool IsShaderItemUsedForVoxelization([[maybe_unused]] SShaderItem& rShaderItem, [[maybe_unused]] IRenderNode* pRN){ return false; } - virtual void Release(){} -}; - -////////////////////////////////////////////////////////////////////// -struct SRenderPipeline; -struct SRenderThread; -struct SShaderTechnique; -struct SShaderPass; -struct SDepthTexture; -struct SRenderTileInfo; - -class CShaderMan; -class CDeviceBufferManager; -class CShaderResources; -class PerInstanceConstantBufferPool; - -namespace AZ { - class Plane; - namespace Vertex { - class Format; - } -} -enum eRenderPrimitiveType : int8; -enum RenderIndexType : int; - -struct IRenderAPI -{ -}; - -struct IRenderer - : public IRenderAPI -{ - virtual ~IRenderer(){} - - virtual void AddRenderDebugListener(IRenderDebugListener* pRenderDebugListener) = 0; - virtual void RemoveRenderDebugListener(IRenderDebugListener* pRenderDebugListener) = 0; - - virtual ERenderType GetRenderType() const = 0; - - virtual const char* GetRenderDescription() const - { - return "CryRenderer"; - } - - // Summary: - // Initializes the renderer, params are self-explanatory. - virtual WIN_HWND Init(int x, int y, int width, int height, unsigned int cbpp, int zbpp, int sbits, bool fullscreen, bool isEditor, WIN_HINSTANCE hinst, WIN_HWND Glhwnd = 0, bool bReInit = false, const SCustomRenderInitArgs* pCustomArgs = 0, bool bShaderCacheGen = false) = 0; - virtual void PostInit() = 0; - - virtual bool IsPost3DRendererEnabled() const { return false; } - - virtual int GetFeatures() = 0; - virtual const void SetApiVersion(const AZStd::string& apiVersion) = 0; - virtual const void SetAdapterDescription(const AZStd::string& adapterDescription) = 0; - virtual const AZStd::string& GetApiVersion() const = 0; - virtual const AZStd::string& GetAdapterDescription() const = 0; - virtual void GetVideoMemoryUsageStats(size_t& vidMemUsedThisFrame, size_t& vidMemUsedRecently, bool bGetPoolsSizes = false) = 0; - virtual int GetNumGeomInstances() const = 0; - virtual int GetNumGeomInstanceDrawCalls() const = 0; - virtual int GetCurrentNumberOfDrawCalls() const = 0; - virtual void GetCurrentNumberOfDrawCalls(int& nGeneral, int& nShadowGen) const = 0; - //Sums DIP counts for the EFSLIST_* passes that match the submitted mask. - //Compose the mask with bitwise arithmetic, use (1 << EFSLIST_*) per list. - //e.g. to sum general and transparent, pass in ( (1 << EFSLIST_GENERAL) | (1 << EFSLIST_TRANSP) ) - virtual int GetCurrentNumberOfDrawCalls(uint32 EFSListMask) const = 0; - virtual float GetCurrentDrawCallRTTimes(uint32 EFSListMask) const = 0; - - virtual void SetDebugRenderNode(IRenderNode* pRenderNode) = 0; - virtual bool IsDebugRenderNode(IRenderNode* pRenderNode) const = 0; - - ///////////////////////////////////////////////////////////////////////////////// - // Render-context management - ///////////////////////////////////////////////////////////////////////////////// - virtual bool DeleteContext(WIN_HWND hWnd) = 0; - virtual bool CreateContext(WIN_HWND hWnd, bool bAllowMSAA = false, int SSX = 1, int SSY = 1) = 0; - virtual bool SetCurrentContext(WIN_HWND hWnd) = 0; - virtual void MakeMainContextActive() = 0; - virtual WIN_HWND GetCurrentContextHWND() = 0; - virtual bool IsCurrentContextMainVP() = 0; - - // Summary: - // Gets height of the current viewport. - virtual int GetCurrentContextViewportHeight() const = 0; - - // Summary: - // Gets width of the current viewport. - virtual int GetCurrentContextViewportWidth() const = 0; - ///////////////////////////////////////////////////////////////////////////////// - - // Summary: - // Shuts down the renderer. - virtual void ShutDown(bool bReInit = false) = 0; - virtual void ShutDownFast() = 0; - - // Description: - // Creates array of all supported video formats (except low resolution formats). - // Return value: - // Number of formats in memory. - virtual int EnumDisplayFormats(SDispFormat* Formats) = 0; - - // Summary: - // Returns all supported by video card video AA formats. - virtual int EnumAAFormats(SAAFormat* Formats) = 0; - - // Summary: - // Changes resolution of the window/device (doesn't require to reload the level. - virtual bool ChangeResolution(int nNewWidth, int nNewHeight, int nNewColDepth, int nNewRefreshHZ, bool bFullScreen, bool bForceReset) = 0; - - // Note: - // Should be called at the beginning of every frame. - virtual void BeginFrame() = 0; - - // Summary: - // Creates default system shaders and textures. - virtual void InitSystemResources(int nFlags) = 0; - virtual void InitTexturesSemantics() = 0; - - // Summary: - // Frees the allocated resources. - virtual void FreeResources(int nFlags) = 0; - - // Summary: - // Shuts down the renderer. - virtual void Release() = 0; - - // See also: - // r_ShowDynTextures - virtual void RenderDebug(bool bRenderStats = true) = 0; - - // Note: - // Should be called at the end of every frame. - virtual void EndFrame() = 0; - - // Force a swap on the backbuffer - virtual void ForceSwapBuffers() = 0; - - // Summary: - // Try to flush the render thread commands to keep the render thread active during - // level loading, but simpy return if the render thread is still busy - virtual void TryFlush() = 0; - - virtual void GetViewport(int* x, int* y, int* width, int* height) const = 0; - virtual void SetViewport(int x, int y, int width, int height, int id = 0) = 0; - virtual void SetRenderTile(f32 nTilesPosX = 0.f, f32 nTilesPosY = 0.f, f32 nTilesGridSizeX = 1.f, f32 nTilesGridSizeY = 1.f) = 0; - virtual void SetScissor(int x = 0, int y = 0, int width = 0, int height = 0) = 0; - virtual Matrix44A& GetViewProjectionMatrix() = 0; - virtual void SetTranspOrigCameraProjMatrix(Matrix44A& matrix) = 0; - - virtual EScreenAspectRatio GetScreenAspect(int nWidth, int nHeight) = 0; - - virtual Vec2 SetViewportDownscale(float xscale, float yscale) = 0; - virtual void SetViewParameters(const CameraViewParameters& viewParameters) = 0; // Direct setter - virtual void ApplyViewParameters(const CameraViewParameters& viewParameters) = 0; // Uses CameraViewParameters to create matrices. - - // Summary: - // Draws user primitives. - virtual void DrawDynVB(SVF_P3F_C4B_T2F* pBuf, uint16* pInds, int nVerts, int nInds, PublicRenderPrimitiveType nPrimType) = 0; - - struct DynUiPrimitive : public AZStd::intrusive_slist_node<DynUiPrimitive> - { - SVF_P2F_C4B_T2F_F4B* m_vertices = nullptr; - uint16* m_indices = nullptr; - int m_numVertices = 0; - int m_numIndices = 0; - }; - - using DynUiPrimitiveList = AZStd::intrusive_slist<DynUiPrimitive, AZStd::slist_base_hook<DynUiPrimitive>>; - - // Summary: - // Draws a list of UI primitives as one draw call (if using separate render thread) - virtual void DrawDynUiPrimitiveList(DynUiPrimitiveList& primitives, int totalNumVertices, int totalNumIndices) = 0; - - // Summary: - // Sets the renderer camera. - virtual void SetCamera(const CCamera& cam) = 0; - - // Summary: - // Gets the renderer camera. - virtual const CCamera& GetCamera() = 0; - - virtual CRenderView* GetRenderViewForThread(int nThreadID) = 0; - // Summary: - // Gets the renderer previous camera. - //virtual const CCamera& GetCameraPrev() = 0; - - // Summary: - // Sets delta gamma. - virtual bool SetGammaDelta(float fGamma) = 0; - - // Summary: - // Restores gamma - // Note: - // Reset gamma setting if not in fullscreen mode. - virtual void RestoreGamma(void) = 0; - - // Summary: - // Changes display size. - virtual bool ChangeDisplay(unsigned int width, unsigned int height, unsigned int cbpp) = 0; - - // Summary: - // Changes viewport size. - virtual void ChangeViewport(unsigned int x, unsigned int y, unsigned int width, unsigned int height, bool bMainViewport = false, float scaleWidth = 1.0f, float scaleHeight = 1.0f) = 0; - - // Summary: - // Saves source data to a Tga file. - // Note: - // Should not be here. - virtual bool SaveTga(unsigned char* sourcedata, int sourceformat, int w, int h, const char* filename, bool flip) const = 0; - - // Summary: - // Sets the current binded texture. - virtual void SetTexture(int tnum) = 0; - - // Summary: - // Sets the current bound texture for the given texture unit - virtual void SetTexture(int tnum, int nUnit) = 0; - - // Summary: - // Sets the white texture. - virtual void SetWhiteTexture() = 0; - - // Summary: - // Gets the white texture Id. - virtual int GetWhiteTextureId() const = 0; - - // Summary: - // Gets the white texture Id. - virtual int GetBlackTextureId() const = 0; - - // Summary: - // Draws a 2d image on the screen. - // Example: - // Hud etc. - virtual void Draw2dImage(float xpos, float ypos, float w, float h, int texture_id, float s0 = 0, float t0 = 0, float s1 = 1, float t1 = 1, float angle = 0, float r = 1, float g = 1, float b = 1, float a = 1, float z = 1) = 0; - - virtual void Draw2dImageStretchMode(bool stretch) = 0; - - // Summary: - // Adds a 2d image that should be drawn on the screen to an internal render list. The list can be drawn with Draw2dImageList. - // If several images will be drawn, using this function is more efficient than calling Draw2dImage as it allows better batching. - // The function supports placing images in stereo 3d space. - // Arguments: - // stereoDepth - Places image in stereo 3d space. The depth is specified in camera space, the stereo params are the same that - // are used for the scene. A value of 0 is handled as a special case and always places the image on the screen plane. - virtual void Push2dImage(float xpos, float ypos, float w, float h, int texture_id, float s0 = 0, float t0 = 0, float s1 = 1, float t1 = 1, float angle = 0, float r = 1, float g = 1, float b = 1, float a = 1, float z = 1, float stereoDepth = 0) = 0; - - // Summary: - // Draws all images to the screen that were collected with Push2dImage. - virtual void Draw2dImageList() = 0; - - // Summary: - // Draws a image using the current matrix. - virtual void DrawImage(float xpos, float ypos, float w, float h, int texture_id, float s0, float t0, float s1, float t1, float r, float g, float b, float a, bool filtered = true) = 0; - - // Description: - // Draws a image using the current matrix, more flexible than DrawImage - // order for s and t: 0=left_top, 1=right_top, 2=right_bottom, 3=left_bottom. - virtual void DrawImageWithUV(float xpos, float ypos, float z, float width, float height, int texture_id, float* s, float* t, float r = 1, float g = 1, float b = 1, float a = 1, bool filtered = true) = 0; - - // Summary: - // Sets the polygon mode with Push, Pop restores the last used one - // Example: - // Wireframe, solid. - virtual void PushWireframeMode(int mode) = 0; - virtual void PopWireframeMode() = 0; - - // Summary: - // Gets height of the main rendering resolution. - virtual int GetHeight() const = 0; - - // Summary: - // Gets width of the main rendering resolution. - virtual int GetWidth() const = 0; - - // Summary: - // Gets Pixel Aspect Ratio. - virtual float GetPixelAspectRatio() const = 0; - - // Summary: - // Gets the height of the overlay viewport where UI and debug output are rendered. - virtual int GetOverlayHeight() const = 0; - - // Summary: - // Gets the width of the overlay viewport where UI and debug output are rendered. - virtual int GetOverlayWidth() const = 0; - - // Summary: - // Gets the maximum dimension for a square custom render resolution. - virtual int GetMaxSquareRasterDimension() const = 0; - - // Summary: - // Switches subsequent rendering from the internal backbuffer to the native resolution backbuffer if available. - virtual void SwitchToNativeResolutionBackbuffer() = 0; - - // Summary: - // Gets memory status information - virtual void GetMemoryUsage(ICrySizer* Sizer) = 0; - - // Summary: - // Gets textures streaming bandwidth information - virtual void GetBandwidthStats(float* fBandwidthRequested) = 0; - - // Summary: - // Sets an event listener for texture streaming updates - virtual void SetTextureStreamListener(ITextureStreamListener* pListener) = 0; - - // Summary: - // Populates a CPU-side occlusion buffer with the contents from the previous frame's downsampled depth buffer. - // This will be called from a job thread within the occlusion system. - virtual int GetOcclusionBuffer(uint16* pOutOcclBuffer, Matrix44* pmCamBuffer) = 0; - - // Summary: - // Gets a screenshot and save to a file - // Returns: - // true=success - virtual bool ScreenShot(const char* filename = NULL, int width = 0) = 0; - - // Summary: - // Gets current bpp. - virtual int GetColorBpp() = 0; - - // Summary: - // Gets current z-buffer depth. - virtual int GetDepthBpp() = 0; - - // Summary: - // Gets current stencil bits. - virtual int GetStencilBpp() = 0; - - // Summary: - // Returns true if stereo rendering is enabled. - virtual bool IsStereoEnabled() const = 0; - - // Summary: - // Returns values of nearest rendering z-range max - virtual float GetNearestRangeMax() const = 0; - - // Summary: - // Returns the PerInstanceConstantBufferPool - virtual PerInstanceConstantBufferPool* GetPerInstanceConstantBufferPoolPointer() = 0; - - // Summary: - // Projects to screen. - // Returns true if successful. - virtual bool ProjectToScreen( - float ptx, float pty, float ptz, - float* sx, float* sy, float* sz) = 0; - - // Summary: - // Unprojects to screen. - virtual int UnProject( - float sx, float sy, float sz, - float* px, float* py, float* pz, - const float modelMatrix[16], - const float projMatrix[16], - const int viewport[4]) = 0; - - // Summary: - // Unprojects from screen. - virtual int UnProjectFromScreen( - float sx, float sy, float sz, - float* px, float* py, float* pz) = 0; - - // Remarks: - // For editor. - virtual void GetModelViewMatrix(float* mat) = 0; - - // Remarks: - // For editor. - virtual void GetProjectionMatrix(float* mat) = 0; - - virtual bool WriteDDS(const byte* dat, int wdt, int hgt, int Size, const char* name, ETEX_Format eF, int NumMips) = 0; - virtual bool WriteTGA(const byte* dat, int wdt, int hgt, const char* name, int src_bits_per_pixel, int dest_bits_per_pixel) = 0; - virtual bool WriteJPG(const byte* dat, int wdt, int hgt, char* name, int src_bits_per_pixel, int nQuality = 100) = 0; - - ///////////////////////////////////////////////////////////////////////////////// - //Replacement functions for Font - - static const bool FontCreateTextureGenMipsDefaultValue = false; - virtual int FontCreateTexture(int Width, int Height, byte* pData, ETEX_Format eTF = eTF_R8G8B8A8, bool genMips = FontCreateTextureGenMipsDefaultValue, const char* textureName = nullptr) = 0; - virtual bool FontUpdateTexture(int nTexId, int X, int Y, int USize, int VSize, byte* pData) = 0; - virtual void FontSetTexture(int nTexId, int nFilterMode) = 0; - virtual void FontSetRenderingState(bool overrideViewProjMatrices, TransformationMatrices& backupMatrices) = 0; - virtual void FontSetBlending(int src, int dst, int baseState) = 0; - virtual void FontRestoreRenderingState(bool overrideViewProjMatrices, const TransformationMatrices& restoringMatrices) = 0; - - virtual bool FlushRTCommands(bool bWait, bool bImmediatelly, bool bForce) = 0; - virtual void DrawStringU(IFFont_RenderProxy* pFont, float x, float y, float z, const char* pStr, bool asciiMultiLine, const STextDrawContext& ctx) const = 0; - - virtual int RT_CurThreadList() = 0; - - ///////////////////////////////////////////////////////////////////////////////// - // External interface for shaders - ///////////////////////////////////////////////////////////////////////////////// - virtual bool EF_PrecacheResource(SShaderItem* pSI, float fMipFactor, float fTimeToReady, int Flags, int nUpdateId, int nCounter = 1) = 0; - virtual bool EF_PrecacheResource(IShader* pSH, float fMipFactor, float fTimeToReady, int Flags) = 0; - virtual bool EF_PrecacheResource(ITexture* pTP, float fMipFactor, float fTimeToReady, int Flags, int nUpdateId, int nCounter = 1) = 0; - virtual bool EF_PrecacheResource(IRenderMesh* pPB, _smart_ptr<IMaterial> pMaterial, float fMipFactor, float fTimeToReady, int Flags, int nUpdateId) = 0; - virtual bool EF_PrecacheResource(CDLight* pLS, float fMipFactor, float fTimeToReady, int Flags, int nUpdateId) = 0; - - virtual ITexture* EF_CreateCompositeTexture(int type, const char* szName, int nWidth, int nHeight, int nDepth, int nMips, int nFlags, ETEX_Format eTF, const STexComposition* pCompositions, size_t nCompositions, int8 nPriority = -1) = 0; - - virtual void PostLevelLoading() = 0; - virtual void PostLevelUnload() = 0; - - virtual CRenderObject* EF_AddPolygonToScene(SShaderItem& si, int numPts, const SVF_P3F_C4B_T2F* verts, const SPipTangents* tangs, CRenderObject* obj, const SRenderingPassInfo& passInfo, uint16* inds, int ninds, int nAW, const SRendItemSorter& rendItemSorter) = 0; - virtual CRenderObject* EF_AddPolygonToScene(SShaderItem& si, CRenderObject* obj, const SRenderingPassInfo& passInfo, int numPts, int ninds, SVF_P3F_C4B_T2F*& verts, SPipTangents*& tangs, uint16*& inds, int nAW, const SRendItemSorter& rendItemSorter) = 0; - - // This is a workaround for when an editor viewport needs to do immediate rendering - // in the editor. Specifically, global constants are updated in a deferred fashion, so - // if a viewport (like the lens flare view) starts doing main-thread rendering, those - // parameters are not bound. - virtual void ForceUpdateGlobalShaderParameters() {} - - ///////////////////////////////////////////////////////////////////////////////// - // Shaders/Shaders management ///////////////////////////////////////////////////////////////////////////////// - - virtual const char* EF_GetShaderMissLogPath() = 0; - - ///////////////////////////////////////////////////////////////////////////////// - virtual string* EF_GetShaderNames(int& nNumShaders) = 0; - // Summary: - // Reloads file - virtual bool EF_ReloadFile (const char* szFileName) = 0; - // Summary: - // Reloads file at any time the renderer feels to do so (no guarantees, but likely on next frame update) - // Is threadsafe - virtual bool EF_ReloadFile_Request (const char* szFileName) = 0; - - // Summary: - // Remaps shader gen mask to common global mask. - virtual uint64 EF_GetRemapedShaderMaskGen(const char* name, uint64 nMaskGen = 0, bool bFixup = 0) = 0; - - virtual uint64 EF_GetShaderGlobalMaskGenFromString(const char* szShaderName, const char* szShaderGen, uint64 nMaskGen = 0) = 0; - virtual AZStd::string EF_GetStringFromShaderGlobalMaskGen(const char* szShaderName, uint64 nMaskGen = 0) = 0; - - virtual const SShaderProfile& GetShaderProfile(EShaderType eST) const = 0; - virtual void EF_SetShaderQuality(EShaderType eST, EShaderQuality eSQ) = 0; - - // Summary: - // Gets renderer quality. - virtual ERenderQuality EF_GetRenderQuality() const = 0; - // Summary: - // Gets shader type quality. - virtual EShaderQuality EF_GetShaderQuality(EShaderType eST) = 0; - // Summary: - // Loads shader item for name (name). - virtual SShaderItem EF_LoadShaderItem (const char* szName, bool bShare, int flags = 0, SInputShaderResources* Res = NULL, uint64 nMaskGen = 0) = 0; - // Summary: - // Loads shader for name (name). - virtual IShader* EF_LoadShader (const char* name, int flags = 0, uint64 nMaskGen = 0) = 0; - // Summary: - // Reinitializes all shader files (build hash tables). - virtual void EF_ReloadShaderFiles (int nCategory) = 0; - // Summary: - // Reloads all texture files. - virtual void EF_ReloadTextures () = 0; - // Summary: - // Gets texture object by ID. - virtual ITexture* EF_GetTextureByID(int Id) = 0; - // Summary: - // Gets texture object by Name. - virtual ITexture* EF_GetTextureByName(const char* name, uint32 flags = 0) = 0; - // Summary: - // Loads the texture for name(nameTex). - virtual ITexture* EF_LoadTexture(const char* nameTex, uint32 flags = 0) = 0; - virtual ITexture* EF_LoadCubemapTexture(const char* nameTex, uint32 flags = 0) = 0; - // Summary: - // Loads default texture whose life cycle is managed by Texture Manager, do not try to release them by yourself! - virtual ITexture* EF_LoadDefaultTexture(const char* nameTex) = 0; - - // Summary: - // Loads lightmap for name. - virtual int EF_LoadLightmap (const char* name) = 0; - - // Summary: - // Starts using of the shaders (return first index for allow recursions). - virtual void EF_StartEf (const SRenderingPassInfo& passInfo) = 0; - - virtual SRenderObjData* EF_GetObjData(CRenderObject* pObj, bool bCreate, int nThreadID) = 0; - - // Summary: - // Gets CRenderObject for RE transformation. - //Get temporary RenderObject - virtual CRenderObject* EF_GetObject_Temp (int nThreadID) = 0; - - //Get permanent RenderObject - virtual CRenderObject* EF_DuplicateRO(CRenderObject* pObj, const SRenderingPassInfo& passInfo) = 0; - - // Summary: - // Adds shader to the list. - virtual void EF_AddEf (IRenderElement* pRE, SShaderItem& pSH, CRenderObject* pObj, const SRenderingPassInfo& passInfo, int nList, int nAW, const SRendItemSorter& rendItemSorter) = 0; - - //! Draw all shaded REs in the list - virtual void EF_EndEf3D (int nFlags, int nPrecacheUpdateId, int nNearPrecacheUpdateId, const SRenderingPassInfo& passInfo) = 0; - - virtual void EF_InvokeShadowMapRenderJobs(int nFlags) = 0; - - // Dynamic lights - void EF_ClearLightsList() {}; // For FC Compatibility. - virtual bool EF_IsFakeDLight (const CDLight* Source) = 0; - virtual void EF_ADDDlight(CDLight* Source, const SRenderingPassInfo& passInfo) = 0; - virtual bool EF_UpdateDLight(SRenderLight* pDL) = 0; - virtual bool EF_AddDeferredDecal([[maybe_unused]] const SDeferredDecal& rDecal){return true; } - - // Deferred lights/vis areas - - virtual int EF_AddDeferredLight(const CDLight& pLight, float fMult, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter) = 0; - virtual uint32 EF_GetDeferredLightsNum(eDeferredLightType eLightType = eDLT_DeferredLight) = 0; - virtual void EF_ClearDeferredLightsList() = 0; - - virtual uint8 EF_AddDeferredClipVolume(const IClipVolume* pClipVolume) = 0; - virtual bool EF_SetDeferredClipVolumeBlendData(const IClipVolume* pClipVolume, const SClipVolumeBlendInfo& blendInfo) = 0; - virtual void EF_ClearDeferredClipVolumesList() = 0; - - // called in between levels to free up memory - virtual void EF_ReleaseDeferredData() = 0; - - // called in between levels to free up memory - virtual void EF_ReleaseInputShaderResource(SInputShaderResources* pRes) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Post processing effects interfaces - - virtual void EF_SetPostEffectParam(const char* pParam, float fValue, bool bForceValue = false) = 0; - virtual void EF_SetPostEffectParamVec4(const char* pParam, const Vec4& pValue, bool bForceValue = false) = 0; - virtual void EF_SetPostEffectParamString(const char* pParam, const char* pszArg) = 0; - - virtual void EF_GetPostEffectParam(const char* pParam, float& fValue) = 0; - virtual void EF_GetPostEffectParamVec4(const char* pParam, Vec4& pValue) = 0; - virtual void EF_GetPostEffectParamString(const char* pParam, const char*& pszArg) = 0; - - virtual int32 EF_GetPostEffectID(const char* pPostEffectName) = 0; - - virtual void EF_ResetPostEffects(bool bOnSpecChange = false) = 0; - - virtual void SyncPostEffects() = 0; - - virtual void EF_DisableTemporalEffects() = 0; - - ////////////////////////////////////////////////////////////////////////// - - virtual void EF_AddWaterSimHit(const Vec3& vPos, float scale, float strength) = 0; - virtual void EF_DrawWaterSimHits() = 0; - - ///////////////////////////////////////////////////////////////////////////////// - // 2d interface for the shaders - ///////////////////////////////////////////////////////////////////////////////// - virtual void EF_EndEf2D(bool bSort) = 0; - - // Summary: - // Returns various Renderer Settings, see ERenderQueryTypes. - // Arguments: - // Query - e.g. EFQ_GetShaderCombinations. - // rInOut - Input/Output Parameter, depends on the query if written to/read from, or both - void EF_Query(ERenderQueryTypes eQuery) - { - EF_QueryImpl(eQuery, NULL, 0, NULL, 0); - } - template<typename T> - void EF_Query(ERenderQueryTypes eQuery, T& rInOut) - { - EF_QueryImpl(eQuery, static_cast<void*>(&rInOut), sizeof(T), NULL, 0); - } - template<typename T0, typename T1> - void EF_Query(ERenderQueryTypes eQuery, T0& rInOut0, T1& rInOut1) - { - EF_QueryImpl(eQuery, static_cast<void*>(&rInOut0), sizeof(T0), static_cast<void*>(&rInOut1), sizeof(T1)); - } - - // Summary: - // Toggles render mesh garbage collection - // Arguments: - // Param - - virtual void ForceGC() = 0; - - // Remarks: - // For stats. - virtual int GetPolyCount() const = 0; - virtual void GetPolyCount(int& nPolygons, int& nShadowVolPolys) const = 0; - - // Note: - // 3d engine set this color to fog color. - virtual void SetClearColor(const Vec3& vColor) = 0; - - virtual void SetClearBackground(bool bClearBackground) = 0; - - // Summary: - // Creates/deletes RenderMesh object. - virtual _smart_ptr<IRenderMesh> CreateRenderMesh( - const char* szType - , const char* szSourceName - , IRenderMesh::SInitParamerers* pInitParams = NULL - , ERenderMeshType eBufType = eRMT_Static - ) = 0; - - virtual _smart_ptr<IRenderMesh> CreateRenderMeshInitialized( - const void* pVertBuffer, int nVertCount, const AZ::Vertex::Format& vertexFormat, - const vtx_idx* pIndices, int nIndices, - const PublicRenderPrimitiveType nPrimetiveType, const char* szType, const char* szSourceName, ERenderMeshType eBufType = eRMT_Static, - int nMatInfoCount = 1, int nClientTextureBindID = 0, - bool (* PrepareBufferCallback)(IRenderMesh*, bool) = NULL, - void* CustomData = NULL, - bool bOnlyVideoBuffer = false, - bool bPrecache = true, - const SPipTangents* pTangents = NULL, bool bLockForThreadAcc = false, Vec3* pNormals = NULL) = 0; - - //Pass false to get a frameID that increments by one each frame. For this case the increment happens in the game thread at the beginning of the frame. - virtual int GetFrameID(bool bIncludeRecursiveCalls = true) = 0; - - virtual void MakeMatrix(const Vec3& pos, const Vec3& angles, const Vec3& scale, Matrix34* mat) = 0; - - // Description: - // Draws text queued. - // Note: - // Position can be in 3d or in 2d depending on the flags. - virtual void DrawTextQueued(Vec3 pos, SDrawTextInfo& ti, const char* format, va_list args) = 0; - - // Description: - // Draws text queued. - // Note: - // Position can be in 3d or in 2d depending on the flags. - virtual void DrawTextQueued(Vec3 pos, SDrawTextInfo& ti, const char* text) = 0; - - ////////////////////////////////////////////////////////////////////// - - virtual float ScaleCoordX(float value) const = 0; - virtual float ScaleCoordY(float value) const = 0; - virtual void ScaleCoord(float& x, float& y) const = 0; - - virtual void SetState(int State, int AlphaRef = -1) = 0; - virtual void SetCullMode (int mode = R_CULL_BACK) = 0; - virtual void SetStencilState(int st, uint32 nStencRef, uint32 nStencMask, uint32 nStencWriteMask, bool bForceFullReadMask = false) = 0; - - virtual void PushProfileMarker(const char* label) = 0; - virtual void PopProfileMarker(const char* label) = 0; - - virtual bool EnableFog(bool enable) = 0; - virtual void SetFogColor(const ColorF& color) = 0; - - virtual void SetColorOp(byte eCo, byte eAo, byte eCa, byte eAa) = 0; - virtual void SetSrgbWrite(bool srgbWrite) = 0; - - // for one frame allows to disable limit of texture streaming requests - virtual void RequestFlushAllPendingTextureStreamingJobs([[maybe_unused]] int nFrames) { } - - // allows to dynamically adjust texture streaming load depending on game conditions - virtual void SetTexturesStreamingGlobalMipFactor([[maybe_unused]] float fFactor) { } - - ////////////////////////////////////////////////////////////////////// - // Summary: - // Interface for auxiliary geometry (for debugging, editor purposes, etc.) - virtual IRenderAuxGeom* GetIRenderAuxGeom(void* jobID = 0) = 0; - ////////////////////////////////////////////////////////////////////// - - // Interface for renderer side SVO - virtual ISvoRenderer* GetISvoRenderer() { return 0; } - - virtual IColorGradingController* GetIColorGradingController() = 0; - virtual IStereoRenderer* GetIStereoRenderer() = 0; - - virtual ITexture* Create2DTexture(const char* name, int width, int height, int numMips, int flags, unsigned char* data, ETEX_Format format) = 0; - virtual void TextToScreen(float x, float y, const char* format, ...) PRINTF_PARAMS(4, 5) = 0; - virtual void TextToScreenColor(int x, int y, float r, float g, float b, float a, const char* format, ...) PRINTF_PARAMS(8, 9) = 0; - virtual void ResetToDefault() = 0; - virtual void SetMaterialColor(float r, float g, float b, float a) = 0; - - // Sets default Blend, DepthStencil and Raster states. - virtual void SetDefaultRenderStates() = 0; - - virtual void Graph(byte* g, int x, int y, int wdt, int hgt, int nC, int type, const char* text, ColorF& color, float fScale) = 0; - virtual void EF_RenderTextMessages() = 0; - - virtual void ClearTargetsImmediately(uint32 nFlags) = 0; - virtual void ClearTargetsImmediately(uint32 nFlags, const ColorF& Colors, float fDepth) = 0; - virtual void ClearTargetsImmediately(uint32 nFlags, const ColorF& Colors) = 0; - virtual void ClearTargetsImmediately(uint32 nFlags, float fDepth) = 0; - - virtual void ClearTargetsLater(uint32 nFlags) = 0; - virtual void ClearTargetsLater(uint32 nFlags, const ColorF& Colors, float fDepth) = 0; - virtual void ClearTargetsLater(uint32 nFlags, const ColorF& Colors) = 0; - virtual void ClearTargetsLater(uint32 nFlags, float fDepth) = 0; - - virtual void ReadFrameBuffer(unsigned char* pRGB, int nImageX, int nSizeX, int nSizeY, ERB_Type eRBType, bool bRGBA, int nScaledX = -1, int nScaledY = -1) = 0; - virtual void ReadFrameBufferFast(uint32* pDstARGBA8, int dstWidth, int dstHeight, bool BGRA = true) = 0; - - // Note: - // The following functions will be removed. - virtual void EnableVSync(bool enable) = 0; - - virtual void CreateResourceAsync(SResourceAsync* Resource) = 0; - virtual void ReleaseResourceAsync(SResourceAsync* Resource) = 0; - virtual void ReleaseResourceAsync(AZStd::unique_ptr<SResourceAsync> pResource) = 0; - virtual unsigned int DownLoadToVideoMemory(const byte* data, int w, int h, ETEX_Format eTFSrc, ETEX_Format eTFDst, int nummipmap, bool repeat = true, int filter = FILTER_BILINEAR, int Id = 0, const char* szCacheName = NULL, int flags = 0, EEndian eEndian = eLittleEndian, RectI* pRegion = NULL, bool bAsynDevTexCreation = false) = 0; - virtual unsigned int DownLoadToVideoMemory3D(const byte* data, int w, int h, int d, ETEX_Format eTFSrc, ETEX_Format eTFDst, int nummipmap, bool repeat = true, int filter = FILTER_BILINEAR, int Id = 0, const char* szCacheName = NULL, int flags = 0, EEndian eEndian = eLittleEndian, RectI* pRegion = NULL, bool bAsynDevTexCreation = false) = 0; - virtual unsigned int DownLoadToVideoMemoryCube(const byte* data, int w, int h, ETEX_Format eTFSrc, ETEX_Format eTFDst, int nummipmap, bool repeat = true, int filter = FILTER_BILINEAR, int Id = 0, const char* szCacheName = NULL, int flags = 0, EEndian eEndian = eLittleEndian, RectI* pRegion = NULL, bool bAsynDevTexCreation = false) = 0; - virtual void UpdateTextureInVideoMemory(uint32 tnum, const byte* newdata, int posx, int posy, int w, int h, ETEX_Format eTFSrc = eTF_B8G8R8, int posz = 0, int sizez = 1) = 0; - - virtual bool DXTCompress(const byte* raw_data, int nWidth, int nHeight, ETEX_Format eTF, bool bUseHW, bool bGenMips, int nSrcBytesPerPix, MIPDXTcallback callback) = 0; - virtual bool DXTDecompress(const byte* srcData, size_t srcFileSize, byte* dstData, int nWidth, int nHeight, int nMips, ETEX_Format eSrcTF, bool bUseHW, int nDstBytesPerPix) = 0; - virtual void RemoveTexture(unsigned int TextureId) = 0; - virtual void DeleteFont(IFFont* font) = 0; - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // This routines uses 2 destination surfaces. It triggers a backbuffer copy to one of its surfaces, - // and then copies the other surface to system memory. This hopefully will remove any - // CPU stalls due to the rect lock call since the buffer will already be in system - // memory when it is called - // Inputs : - // pDstARGBA8 : Pointer to a buffer that will hold the captured frame (should be at least 4*dstWidth*dstHieght for RGBA surface) - // destinationWidth : Width of the frame to copy - // destinationHeight : Height of the frame to copy - // - // Note : If dstWidth or dstHeight is larger than the current surface dimensions, the dimensions - // of the surface are used for the copy - // - virtual bool CaptureFrameBufferFast(unsigned char* pDstRGBA8, int destinationWidth, int destinationHeight) = 0; - - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // Copy a captured surface to a buffer - // - // Inputs : - // pDstARGBA8 : Pointer to a buffer that will hold the captured frame (should be at least 4*dstWidth*dstHieght for RGBA surface) - // destinationWidth : Width of the frame to copy - // destinationHeight : Height of the frame to copy - // - // Note : If dstWidth or dstHeight is larger than the current surface dimensions, the dimensions - // of the surface are used for the copy - // - virtual bool CopyFrameBufferFast(unsigned char* pDstRGBA8, int destinationWidth, int destinationHeight) = 0; - - - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // This routine registers a callback address that is called when a new frame is available - // Inputs : - // pCapture : Address of the ICaptureFrameListener object - // - // Outputs : returns true if successful, otherwise false - // - virtual bool RegisterCaptureFrame(ICaptureFrameListener* pCapture) = 0; - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // This routine unregisters a callback address that was previously registered - // Inputs : - // pCapture : Address of the ICaptureFrameListener object to unregister - // - // Outputs : returns true if successful, otherwise false - // - virtual bool UnRegisterCaptureFrame(ICaptureFrameListener* pCapture) = 0; - - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // This routine initializes 2 destination surfaces for use by the CaptureFrameBufferFast routine - // It also, captures the current backbuffer into one of the created surfaces - // - // Inputs : - // bufferWidth : Width of capture buffer, on consoles the scaling is done on the GPU. Pass in 0 (the default) to use backbuffer dimensions - // bufferHeight : Height of capture buffer. - // - // Outputs : returns true if surfaces were created otherwise returns false - // - virtual bool InitCaptureFrameBufferFast(uint32 bufferWidth = 0, uint32 bufferHeight = 0) = 0; - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // This routine releases the 2 surfaces used for frame capture by the CaptureFrameBufferFast routine - // - // Inputs : None - // - // Returns : None - // - virtual void CloseCaptureFrameBufferFast(void) = 0; - - - ///////////////////////////////////////////////////////////////////////////////////////////////////// - // This routine checks for any frame buffer callbacks that are needed and calls them - // - // Inputs : None - // - // Outputs : None - // - virtual void CaptureFrameBufferCallBack(void) = 0; - - virtual void RegisterSyncWithMainListener(ISyncMainWithRenderListener* pListener) = 0; - virtual void RemoveSyncWithMainListener(const ISyncMainWithRenderListener* pListener) = 0; - - virtual void Set2DMode(uint32 orthoX, uint32 orthoY, TransformationMatrices& backupMatrices, float znear = -1e10f, float zfar = 1e10f) = 0; - virtual void Unset2DMode(const TransformationMatrices& restoringMatrices) = 0; - virtual void Set2DModeNonZeroTopLeft(float orthoLeft, float orthoTop, float orthoWidth, float orthoHeight, TransformationMatrices& backupMatrices, float znear = -1e10f, float zfar = 1e10f) = 0; - - virtual int ScreenToTexture(int nTexID) = 0; - virtual void EnableSwapBuffers(bool bEnable) = 0; - virtual WIN_HWND GetHWND() = 0; - - // Set the window icon to be displayed on the output window. - // The parameter is the path to a DDS texture file to be used as the icon. - // For best results, pass a square power-of-two sized texture, with a mip-chain. - virtual bool SetWindowIcon(const char* path) = 0; - - virtual void OnEntityDeleted(struct IRenderNode* pRenderNode) = 0; - - virtual int CreateRenderTarget(const char* name, int nWidth, int nHeight, const ColorF& clearColor, ETEX_Format eTF) = 0; - virtual bool DestroyRenderTarget (int nHandle) = 0; - virtual bool ResizeRenderTarget(int nHandle, int nWidth, int nHeight) = 0; - virtual bool SetRenderTarget(int nHandle, SDepthTexture* pDepthSurf = nullptr) = 0; - virtual SDepthTexture* CreateDepthSurface(int nWidth, int nHeight, bool shaderResourceView = false) = 0; - virtual void DestroyDepthSurface(SDepthTexture* pDepthSurf) = 0; - - // Note: - // Used for pausing timer related stuff. - // Example: - // For texture animations, and shader 'time' parameter. - virtual void PauseTimer(bool bPause) = 0; - - // Description: - // Creates an Interface to the public params container. - // Return: - // Created IShaderPublicParams interface. - virtual IShaderPublicParams* CreateShaderPublicParams() = 0; - - virtual void GetThreadIDs(threadID& mainThreadID, threadID& renderThreadID) const = 0; - - struct SArtProfileData - { - enum EArtProfileUnit - { - eArtProfileUnit_GPU = 0, - eArtProfileUnit_CPU, - eArtProfile_NumUnits - }; - - enum EArtProfileSections - { - eArtProfile_Shadows = 0, - eArtProfile_ZPass, - eArtProfile_Decals, - eArtProfile_Lighting, - eArtProfile_Opaque, - eArtProfile_Transparent, - eArtProfile_Max, - }; - - float times[eArtProfile_Max]; - float budgets[eArtProfile_Max]; - float total, budgetTotal; - - // detailed values for anything that is grouped together and can be timed - enum EBreakdownDetailValues - { - // Lighting - eArtProfileDetail_LightsAmbient, - eArtProfileDetail_LightsCubemaps, - eArtProfileDetail_LightsDeferred, - eArtProfileDetail_LightsShadowMaps, // just the cost of the shadow maps - - // Transparent - eArtProfileDetail_Reflections, - eArtProfileDetail_Caustics, - eArtProfileDetail_RefractionOverhead, // partial resolves - eArtProfileDetail_Rain, - eArtProfileDetail_LensOptics, - - eArtProfileDetail_Max, - }; - - float breakdowns[eArtProfileDetail_Max]; - - int batches, drawcalls, processedLights; - -#if defined(ENABLE_ART_RT_TIME_ESTIMATE) - int numStandardBatches; - int numStandardDrawCalls; - int numLightDrawCalls; - float actualRenderTimeMinusPost; - float actualRenderTimePost; - float actualMiscRTTime; - float actualTotalRTTime; -#endif - }; - - virtual void EnableGPUTimers2(bool bEnabled) = 0; - virtual void AllowGPUTimers2(bool bAllow) = 0; - virtual const RPProfilerStats* GetRPPStats(ERenderPipelineProfilerStats eStat, bool bCalledFromMainThread = true) const = 0; - virtual const RPProfilerStats* GetRPPStatsArray(bool bCalledFromMainThread = true) const = 0; - - virtual int GetPolygonCountByType(uint32 EFSList, EVertexCostTypes vct, uint32 z, bool bCalledFromMainThread = true) = 0; - - virtual void SetCloudShadowsParams(int nTexID, const Vec3& speed, float tiling, bool invert, float brightness) = 0; - virtual uint16 PushFogVolumeContribution(const SFogVolumeData& fogVolData, const SRenderingPassInfo& passInfo) = 0; - virtual void PushFogVolume(class CREFogVolume* pFogVolume, const SRenderingPassInfo& passInfo) = 0; - - virtual int GetMaxTextureSize() = 0; - - virtual const char* GetTextureFormatName(ETEX_Format eTF) = 0; - virtual int GetTextureFormatDataSize(int nWidth, int nHeight, int nDepth, int nMips, ETEX_Format eTF) = 0; - - virtual void SetDefaultMaterials(_smart_ptr<IMaterial> pDefMat, _smart_ptr<IMaterial> pTerrainDefMat) = 0; - - virtual IGPUParticleEngine* GetGPUParticleEngine() const { return 0; } - - virtual uint32 GetActiveGPUCount() const = 0; - virtual ShadowFrustumMGPUCache* GetShadowFrustumMGPUCache() = 0; - virtual const StaticArray<int, MAX_GSM_LODS_NUM>& GetCachedShadowsResolution() const = 0; - virtual void SetCachedShadowsResolution(const StaticArray<int, MAX_GSM_LODS_NUM>& arrResolutions) = 0; - virtual void UpdateCachedShadowsLodCount(int nGsmLods) const = 0; - - virtual void SetTexturePrecaching(bool stat) = 0; - - //platform specific - virtual void RT_InsertGpuCallback(uint32 context, GpuCallbackFunc callback) = 0; - virtual void EnablePipelineProfiler(bool bEnable) = 0; - - struct SRenderTimes - { - float fWaitForMain; - float fWaitForRender; - float fWaitForGPU; - float fTimeProcessedRT; - float fTimeProcessedRTScene; //The part of the render thread between the "SCENE" profiler labels - float fTimeProcessedGPU; - float fTimeGPUIdlePercent; - }; - virtual void GetRenderTimes(SRenderTimes& outTimes) = 0; - virtual float GetGPUFrameTime() = 0; - - // Enable the batch mode if the meshpools are used to enable quick and dirty flushes. - virtual void EnableBatchMode(bool enable) = 0; - // Flag level unloading in progress to disable f.i. rendermesh creation requests - virtual void EnableLevelUnloading(bool enable) = 0; - // Function to handle cleanup required if a level load fails - virtual void OnLevelLoadFailed() = 0; - - struct SDrawCallCountInfo - { - static const uint32 MESH_NAME_LENGTH = 32; - static const uint32 TYPE_NAME_LENGTH = 16; - - SDrawCallCountInfo() - : pPos(0, 0, 0) - , nZpass(0) - , nShadows(0) - , nGeneral(0) - , nTransparent(0) - , nMisc(0) - { - meshName[0] = '\0'; - typeName[0] = '\0'; - } - - void Update(CRenderObject* pObj, IRenderMesh* pRM); - - Vec3 pPos; - uint8 nZpass, nShadows, nGeneral, nTransparent, nMisc; - char meshName[MESH_NAME_LENGTH]; - char typeName[TYPE_NAME_LENGTH]; - }; - - //Debug draw call info (per node) - typedef AZStd::unordered_map< IRenderNode*, IRenderer::SDrawCallCountInfo, AZStd::hash<IRenderNode*>, AZStd::equal_to<IRenderNode*>, AZ::StdLegacyAllocator > RNDrawcallsMapNode; - typedef RNDrawcallsMapNode::iterator RNDrawcallsMapNodeItor; - - //Debug draw call info (per mesh) - typedef AZStd::unordered_map< IRenderMesh*, IRenderer::SDrawCallCountInfo, AZStd::hash<IRenderMesh*>, AZStd::equal_to<IRenderMesh*>, AZ::StdLegacyAllocator > RNDrawcallsMapMesh; - typedef RNDrawcallsMapMesh::iterator RNDrawcallsMapMeshItor; - -#if !defined(_RELEASE) - //Get draw call info for frame - virtual RNDrawcallsMapMesh& GetDrawCallsInfoPerMesh(bool mainThread = true) = 0; - virtual RNDrawcallsMapMesh& GetDrawCallsInfoPerMeshPreviousFrame(bool mainThread = true) = 0; - virtual RNDrawcallsMapNode& GetDrawCallsInfoPerNodePreviousFrame(bool mainThread = true) = 0; - virtual int GetDrawCallsPerNode(IRenderNode* pRenderNode) = 0; - virtual void ForceRemoveNodeFromDrawCallsMap(IRenderNode* pNode) = 0; -#endif - - virtual void CollectDrawCallsInfo(bool status) = 0; - virtual void CollectDrawCallsInfoPerNode(bool status) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Summary: - // Helper functions to draw text. - ////////////////////////////////////////////////////////////////////////// - void DrawLabel(Vec3 pos, float font_size, const char* label_text, ...) PRINTF_PARAMS(4, 5) - { - va_list args; - va_start(args, label_text); - SDrawTextInfo ti; - ti.xscale = ti.yscale = font_size; - ti.flags = eDrawText_FixedSize | eDrawText_800x600; - DrawTextQueued(pos, ti, label_text, args); - va_end(args); - } - - void DrawLabelEx(Vec3 pos, float font_size, const float* pfColor, bool bFixedSize, bool bCenter, const char* label_text, ...) PRINTF_PARAMS(7, 8) - { - va_list args; - va_start(args, label_text); - SDrawTextInfo ti; - ti.xscale = ti.yscale = font_size; - ti.flags = ((bFixedSize) ? eDrawText_FixedSize : 0) | ((bCenter) ? eDrawText_Center : 0) | eDrawText_800x600; - if (pfColor) - { - ti.color[0] = pfColor[0]; - ti.color[1] = pfColor[1]; - ti.color[2] = pfColor[2]; - ti.color[3] = pfColor[3]; - } - DrawTextQueued(pos, ti, label_text, args); - va_end(args); - } - - void Draw2dLabelEx(float x, float y, float font_size, const ColorF& fColor, EDrawTextFlags flags, const char* label_text, ...) PRINTF_PARAMS(7, 8) - { - va_list args; - va_start(args, label_text); - SDrawTextInfo ti; - ti.xscale = ti.yscale = font_size; - ti.flags = flags; - { - ti.color[0] = fColor[0]; - ti.color[1] = fColor[1]; - ti.color[2] = fColor[2]; - ti.color[3] = fColor[3]; - } - DrawTextQueued(Vec3(x, y, 0.5f), ti, label_text, args); - va_end(args); - } - - void Draw2dLabel(float x, float y, float font_size, const float* pfColor, bool bCenter, const char* label_text, ...) PRINTF_PARAMS(7, 8) - { - va_list args; - va_start(args, label_text); - SDrawTextInfo ti; - ti.xscale = ti.yscale = font_size; - ti.flags = eDrawText_2D | eDrawText_800x600 | eDrawText_FixedSize | ((bCenter) ? eDrawText_Center : 0); - if (pfColor) - { - ti.color[0] = pfColor[0]; - ti.color[1] = pfColor[1]; - ti.color[2] = pfColor[2]; - ti.color[3] = pfColor[3]; - } - DrawTextQueued(Vec3(x, y, 0.5f), ti, label_text, args); - va_end(args); - } - - void Draw2dLabel(float x, float y, float font_size, const ColorF& fColor, bool bCenter, const char* label_text, ...) PRINTF_PARAMS(7, 8) - { - va_list args; - va_start(args, label_text); - SDrawTextInfo ti; - ti.xscale = ti.yscale = font_size; - ti.flags = eDrawText_2D | eDrawText_800x600 | eDrawText_FixedSize | ((bCenter) ? eDrawText_Center : 0); - { - ti.color[0] = fColor[0]; - ti.color[1] = fColor[1]; - ti.color[2] = fColor[2]; - ti.color[3] = fColor[3]; - } - DrawTextQueued(Vec3(x, y, 0.5f), ti, label_text, args); - va_end(args); - } - - // BLM - Added override that takes flags manually, so we can draw monospaced, etc. - void Draw2dLabelWithFlags(float x, float y, float font_size, const ColorF& fColor, uint32 flags, const char* label_text, ...) PRINTF_PARAMS(7, 8) - { - va_list args; - va_start(args, label_text); - SDrawTextInfo ti; - ti.xscale = ti.yscale = font_size; - ti.flags = flags; - { - ti.color[0] = fColor[0]; - ti.color[1] = fColor[1]; - ti.color[2] = fColor[2]; - ti.color[3] = fColor[3]; - } - DrawTextQueued(Vec3(x, y, 0.5f), ti, label_text, args); - va_end(args); - } - - /** - * Used to determine if the renderer has loaded default system - * textures yet. - * - * Some textures like s_ptexWhite aren't available until this is true. - * - * @return True if the renderer has loaded default resources - */ - virtual bool HasLoadedDefaultResources() { return false; } - - // Summary: - virtual SSkinningData* EF_CreateSkinningData(uint32 nNumBones, bool bNeedJobSyncVar, bool bUseMatrixSkinning = false) = 0; - virtual SSkinningData* EF_CreateRemappedSkinningData(uint32 nNumBones, SSkinningData* pSourceSkinningData, uint32 nCustomDataSize, uint32 pairGuid) = 0; - virtual void EF_ClearSkinningDataPool() = 0; - virtual int EF_GetSkinningPoolID() = 0; - - virtual void ClearShaderItem(SShaderItem* pShaderItem) = 0; - virtual void UpdateShaderItem(SShaderItem* pShaderItem, _smart_ptr<IMaterial> pMaterial) = 0; - virtual void ForceUpdateShaderItem(SShaderItem* pShaderItem, _smart_ptr<IMaterial> pMaterial) = 0; - virtual void RefreshShaderResourceConstants(SShaderItem* pShaderItem, IMaterial* pMaterial) = 0; - - // Summary: - // Determine if a switch to stereo mode will occur at the start of the next frame - virtual bool IsStereoModeChangePending() = 0; - - // Summary: - // Lock/Unlock the video memory buffer used by particles when using the jobsystem - virtual void LockParticleVideoMemory(uint32 nId) = 0; - virtual void UnLockParticleVideoMemory(uint32 nId) = 0; - - // Summary: - // tell the renderer that we will begin/stop spawning jobs which generate SRendItems - virtual void BeginSpawningGeneratingRendItemJobs(int nThreadID) = 0; - virtual void BeginSpawningShadowGeneratingRendItemJobs(int nThreadID) = 0; - virtual void EndSpawningGeneratingRendItemJobs() = 0; - - virtual void StartLoadtimePlayback(ILoadtimeCallback* pCallback) = 0; - virtual void StopLoadtimePlayback() = 0; - - // Summary: - // get the shared job state for SRendItem Generating jobs - virtual AZ::LegacyJobExecutor* GetGenerateRendItemJobExecutor() = 0; - virtual AZ::LegacyJobExecutor* GetGenerateShadowRendItemJobExecutor() = 0; - virtual AZ::LegacyJobExecutor* GetGenerateRendItemJobExecutorPreProcess() = 0; - virtual AZ::LegacyJobExecutor* GetFinalizeRendItemJobExecutor(int nThreadID) = 0; - virtual AZ::LegacyJobExecutor* GetFinalizeShadowRendItemJobExecutor(int nThreadID) = 0; - - virtual void FlushPendingTextureTasks() = 0; - - virtual void SetShadowJittering(float fShadowJittering) = 0; - virtual float GetShadowJittering() const = 0; - - virtual bool LoadShaderStartupCache() = 0; - virtual void UnloadShaderStartupCache() = 0; - - virtual bool LoadShaderLevelCache() = 0; - virtual void UnloadShaderLevelCache() = 0; - - virtual void StartScreenShot([[maybe_unused]] int e_ScreenShot) {}; - virtual void EndScreenShot([[maybe_unused]] int e_ScreenShot) {}; - - // Sets a renderer tracked cvar - virtual void SetRendererCVar(ICVar* pCVar, const char* pArgText, bool bSilentMode = false) = 0; - - // Get the render piepline - virtual SRenderPipeline* GetRenderPipeline() = 0; - - // Get the sahder manager - virtual CShaderMan* GetShaderManager() = 0; - - // Get render thread - virtual SRenderThread* GetRenderThread() = 0; - - // Get premade white texture - virtual ITexture* GetWhiteTexture() = 0; - - // Get the texture for the name and format given - virtual ITexture* GetTextureForName(const char* name, uint32 nFlags, ETEX_Format eFormat) = 0; - - // Get the camera view parameters - virtual const CameraViewParameters& GetViewParameters() = 0; - - // Get frame reset number - virtual uint32 GetFrameReset() = 0; - - // Get original depth buffer - virtual SDepthTexture* GetDepthBufferOrig() = 0; - - // Get width of backbuffer - virtual uint32 GetBackBufferWidth() = 0; - - // Get height of backbuffer - virtual uint32 GetBackBufferHeight() = 0; - - // Get the device buffer manager - virtual CDeviceBufferManager* GetDeviceBufferManager() = 0; - - // Get render tile info - virtual const SRenderTileInfo* GetRenderTileInfo() const = 0; - - // Returns precomputed identity matrix - virtual Matrix44A GetIdentityMatrix() = 0; - - // Get current GPU group Id. Used for tracking which GPU is being used - virtual int32 RT_GetCurrGpuID() const = 0; - - // Generate the next texture id - virtual int GenerateTextureId() = 0; - - // Set culling mode - virtual void SetCull(ECull eCull, bool bSkipMirrorCull = false) = 0; - - // Draw a 2D quad - virtual void DrawQuad(float x0, float y0, float x1, float y1, const ColorF& color, float z = 1.0f, float s0 = 0.0f, float t0 = 0.0f, float s1 = 1.0f, float t1 = 1.0f) = 0; - - // Draw a quad - virtual void DrawQuad3D(const Vec3& v0, const Vec3& v1, const Vec3& v2, const Vec3& v3, const ColorF& color, float ftx0, float fty0, float ftx1, float fty1) = 0; - - // Resets render pipeline state - virtual void FX_ResetPipe() = 0; - - // Gets an (existing) depth surface of the dimensions given - virtual SDepthTexture* FX_GetDepthSurface(int nWidth, int nHeight, bool bAA, bool shaderResourceView = false) = 0; - - // Check to see if buffers are full and if so flush - virtual void FX_CheckOverflow(int nVerts, int nInds, IRenderElement* re, int* nNewVerts = nullptr, int* nNewInds = nullptr) = 0; - - // Perform pre render work - virtual void FX_PreRender(int Stage) = 0; - - // Perform post render work - virtual void FX_PostRender() = 0; - - // Set render states - virtual void FX_SetState(int st, int AlphaRef = -1, int RestoreState = 0) = 0; - - // Commit render states - virtual void FX_CommitStates(const SShaderTechnique* pTech, const SShaderPass* pPass, bool bUseMaterialState) = 0; - - // Commit changes made thus dar - virtual void FX_Commit(bool bAllowDIP = false) = 0; - - // Sets vertex declaration - virtual long FX_SetVertexDeclaration(int StreamMask, const AZ::Vertex::Format& vertexFormat) = 0; - - // Draw indexed prim - virtual void FX_DrawIndexedPrimitive(eRenderPrimitiveType eType, int nVBOffset, int nMinVertexIndex, int nVerticesCount, int nStartIndex, int nNumIndices, bool bInstanced = false) = 0; - - // Set Index stream - virtual long FX_SetIStream(const void* pB, uint32 nOffs, RenderIndexType idxType) = 0; - - // Set vertex stream - virtual long FX_SetVStream(int nID, const void* pB, uint32 nOffs, uint32 nStride, uint32 nFreq = 1) = 0; - - // Draw primitives - virtual void FX_DrawPrimitive(eRenderPrimitiveType eType, int nStartVertex, int nVerticesCount, int nInstanceVertices = 0) = 0; - - // Clear texture - virtual void FX_ClearTarget(ITexture* pTex) = 0; - - // Clear depth - virtual void FX_ClearTarget(SDepthTexture* pTex) = 0; - - // Set render target - virtual bool FX_SetRenderTarget(int nTarget, void* pTargetSurf, SDepthTexture* pDepthTarget, uint32 nTileCount = 1) = 0; - - // Pushes render target - virtual bool FX_PushRenderTarget(int nTarget, void* pTargetSurf, SDepthTexture* pDepthTarget, uint32 nTileCount = 1) = 0; - - // Sets up the render target - virtual bool FX_SetRenderTarget(int nTarget, CTexture* pTarget, SDepthTexture* pDepthTarget, bool bPush = false, int nCMSide = -1, bool bScreenVP = false, uint32 nTileCount = 1) = 0; - - // Push render target - virtual bool FX_PushRenderTarget(int nTarget, CTexture* pTarget, SDepthTexture* pDepthTarget, int nCMSide = -1, bool bScreenVP = false, uint32 nTileCount = 1) = 0; - - // Restore render target - virtual bool FX_RestoreRenderTarget(int nTarget) = 0; - - // Pop render target - virtual bool FX_PopRenderTarget(int nTarget) = 0; - - // Set active render targets - virtual void FX_SetActiveRenderTargets(bool bAllowDIP = false) = 0; - - // Start an effect / shader / etc.. - virtual void FX_Start(CShader* ef, int nTech, CShaderResources* Res, IRenderElement* re) = 0; - - // Pop render target on render thread - virtual void RT_PopRenderTarget(int nTarget) = 0; - - // Sets viewport dimensions on render thread - virtual void RT_SetViewport(int x, int y, int width, int height, int id = -1) = 0; - - // Push render target on render thread - virtual void RT_PushRenderTarget(int nTarget, CTexture* pTex, SDepthTexture* pDS, int nS) = 0; - - // Setup scissors rect - virtual void EF_Scissor(bool bEnable, int sX, int sY, int sWdt, int sHgt) = 0; - -#ifdef SUPPORT_HW_MOUSE_CURSOR - virtual IHWMouseCursor* GetIHWMouseCursor() = 0; -#endif - - virtual int GetRecursionLevel() = 0; - - virtual int GetIntegerConfigurationValue(const char* varName, int defaultValue) = 0; - virtual float GetFloatConfigurationValue(const char* varName, float defaultValue) = 0; - virtual bool GetBooleanConfigurationValue(const char* varName, bool defaultValue) = 0; - - // Methods exposed to external libraries - virtual void ApplyDepthTextureState(int unit, int nFilter, bool clamp) = 0; - virtual ITexture* GetZTargetTexture() = 0; - virtual int GetTextureState(const STexState& TS) = 0; - virtual uint32 TextureDataSize(uint32 nWidth, uint32 nHeight, uint32 nDepth, uint32 nMips, uint32 nSlices, ETEX_Format eTF, ETEX_TileMode eTM = eTM_None) = 0; - virtual void ApplyForID(int nID, int nTUnit, int nTState, int nTexMaterialSlot, int nSUnit, bool useWhiteDefault) = 0; - virtual ITexture* Create3DTexture(const char* szName, int nWidth, int nHeight, int nDepth, int nMips, int nFlags, const byte* pData, ETEX_Format eTFSrc, ETEX_Format eTFDst) = 0; - virtual bool IsTextureExist(const ITexture* pTex) = 0; - virtual const char* NameForTextureFormat(ETEX_Format eTF) = 0; - virtual const char* NameForTextureType(ETEX_Type eTT) = 0; - virtual bool IsVideoThreadModeEnabled() = 0; - virtual IDynTexture* CreateDynTexture2(uint32 nWidth, uint32 nHeight, uint32 nTexFlags, const char* szSource, ETexPool eTexPool) = 0; - virtual uint32 GetCurrentTextureAtlasSize() = 0; - - virtual void BeginProfilerSection(const char* name, uint32 eProfileLabelFlags = 0) = 0; - virtual void EndProfilerSection(const char* name) = 0; - virtual void AddProfilerLabel(const char* name) = 0; - -private: - // use private for EF_Query to prevent client code to submit arbitrary combinations of output data/size - virtual void EF_QueryImpl(ERenderQueryTypes eQuery, void* pInOut0, uint32 nInOutSize0, void* pInOut1, uint32 nInOutSize1) = 0; -}; - -struct SShaderCacheStatistics -{ - size_t m_nTotalLevelShaderCacheMisses; - size_t m_nGlobalShaderCacheMisses; - size_t m_nNumShaderAsyncCompiles; - bool m_bShaderCompileActive; - - SShaderCacheStatistics() - : m_nTotalLevelShaderCacheMisses(0) - , m_nGlobalShaderCacheMisses(0) - , m_nNumShaderAsyncCompiles(0) - , m_bShaderCompileActive(false) - {} -}; - -// The statistics about the pool for render mesh data -// Note: -struct SMeshPoolStatistics -{ - // The size of the mesh data size in bytes - size_t nPoolSize; - - // The amount of memory currently in use in the pool - size_t nPoolInUse; - - // The highest amount of memory allocated within the mesh data pool - size_t nPoolInUsePeak; - - // The size of the mesh data size in bytes - size_t nInstancePoolSize; - - // The amount of memory currently in use in the pool - size_t nInstancePoolInUse; - - // The highest amount of memory allocated within the mesh data pool - size_t nInstancePoolInUsePeak; - - size_t nFallbacks; - size_t nInstanceFallbacks; - size_t nFlushes; - - SMeshPoolStatistics() - : nPoolSize() - , nPoolInUse() - , nInstancePoolSize() - , nInstancePoolInUse() - , nInstancePoolInUsePeak() - , nFallbacks() - , nInstanceFallbacks() - , nFlushes() - {} -}; - -struct SRendererQueryGetAllTexturesParam -{ - SRendererQueryGetAllTexturesParam() - : pTextures(NULL) - , numTextures(0) - { - } - - _smart_ptr<ITexture>* pTextures; - uint32 numTextures; -}; - - -////////////////////////////////////////////////////////////////////// - -#define STRIPTYPE_NONE 0 -#define STRIPTYPE_ONLYLISTS 1 -#define STRIPTYPE_SINGLESTRIP 2 -#define STRIPTYPE_MULTIPLESTRIPS 3 -#define STRIPTYPE_DEFAULT 4 - -///////////////////////////////////////////////////////////////////// - -struct IRenderMesh; - -//DOC-IGNORE-BEGIN -#include "VertexFormats.h" -//DOC-IGNORE-END - -struct SRestLightingInfo -{ - SRestLightingInfo() - { - averDir.zero(); - averCol = Col_Black; - refPoint.zero(); - } - Vec3 averDir; - ColorF averCol; - Vec3 refPoint; -}; - -class CLodValue -{ -public: - CLodValue() - { - m_nLodA = -1; - m_nLodB = -1; - m_nDissolveRef = 0; - } - - CLodValue(int nLodA) - { - m_nLodA = aznumeric_caster(nLodA); - m_nLodB = -1; - m_nDissolveRef = 0; - } - - CLodValue(int nLodA, uint8 nDissolveRef, int nLodB) - { - m_nLodA = aznumeric_caster(nLodA); - m_nLodB = aznumeric_caster(nLodB); - m_nDissolveRef = nDissolveRef; - } - - int LodA() const { return m_nLodA; } - int LodB() const { return m_nLodB; } - - uint8 DissolveRefA() const { return m_nDissolveRef; } - uint8 DissolveRefB() const { return 255 - m_nDissolveRef; } - -private: - int16 m_nLodA; - int16 m_nLodB; - uint8 m_nDissolveRef; -}; - -// Description: -// Structure used to pass render parameters to Render() functions of IStatObj and ICharInstance. -struct SRendParams -{ - SRendParams() - { - memset(this, 0, sizeof(SRendParams)); - fAlpha = 1.f; - fRenderQuality = 1.f; - nRenderList = EFSLIST_GENERAL; - nAfterWater = 1; - mRenderFirstContainer = false; - NoDecalReceiver = false; - } - - // Summary: - // object transformations. - Matrix34* pMatrix; - struct SInstancingInfo* pInstInfo; - // Summary: - // object previous transformations - motion blur specific. - Matrix34* pPrevMatrix; - // Summary: - // VisArea that contains this object, used for RAM-ambient cube query - IVisArea* m_pVisArea; - // Summary: - // Override material. - _smart_ptr<IMaterial> pMaterial; - // Summary: - // Weights stream for deform morphs. - IRenderMesh* pWeights; - // Summary: - // Object Id for objects identification in renderer. - struct IRenderNode* pRenderNode; - // Summary: - // Unique object Id for objects identification in renderer. - void* pInstance; - // Summary: - // TerrainTexInfo for grass. - struct SSectorTextureSet* pTerrainTexInfo; - // Summary: - // storage for LOD transition states. - struct CRNTmpData** ppRNTmpData; - // Summary: - // dynamic render data object which can be set by the game - AZStd::vector<SShaderParam>* pShaderParams; - // Summary: - // Ambient color for the object. - ColorF AmbientColor; - // Summary: - // Custom sorting offset. - float fCustomSortOffset; - // Summary: - // Object alpha. - float fAlpha; - // Summary: - // Distance from camera. - float fDistance; - // Summary: - // Quality of shaders rendering. - float fRenderQuality; - // Summary: - // Light mask to specify which light to use on the object. - uint32 nDLightMask; - // Summary: - // Approximate information about the lights not included into nDLightMask. - // SRestLightingInfo restLightInfo; - // Summary: - // CRenderObject flags. - int32 dwFObjFlags; - // Summary: - // Material layers blending amount - uint32 nMaterialLayersBlend; - // Summary: - // Vision modes params - uint32 nVisionParams; - // Summary: - // Vision modes params - uint32 nHUDSilhouettesParams; - // Summary: - // Defines what pieces of pre-broken geometry has to be rendered - uint64 nSubObjHideMask; - - // Defines per object float custom data - float fCustomData[4]; - - // Custom TextureID - int16 nTextureID; - - // Defines per object custom flags - uint16 nCustomFlags; - - // The LOD value compute for rendering - CLodValue lodValue; - - // Defines per object custom data - uint8 nCustomData; - - // Summary: - // Defines per object DissolveRef value if used by shader. - uint8 nDissolveRef; - // Summary: - // per-instance vis area stencil ref id - uint8 nClipVolumeStencilRef; - // Summary: - // Custom offset for sorting by distance. - uint8 nAfterWater; - - // Summary: - // Material layers bitmask -> which material layers are active. - uint8 nMaterialLayers; - - // Summary: - // Force a sort value for render elements. - uint8 nRenderList; - // Summary: - // Special sorter to ensure correct ordering even if parts of the 3DEngine are run in parallel - uint32 rendItemSorter; - // Summary: - // Render the first particle container only, instead of all the containers - bool mRenderFirstContainer; - - // Summary: - // Check if the preview would Show Wireframe - Vera,Confetti - bool bIsShowWireframe; - - //Summary: - // Force drawing static instead of deformable meshes - bool bForceDrawStatic; - - bool NoDecalReceiver; -}; diff --git a/Code/CryEngine/CryCommon/ISerialize.h b/Code/CryEngine/CryCommon/ISerialize.h deleted file mode 100644 index 6b2eaa271a..0000000000 --- a/Code/CryEngine/CryCommon/ISerialize.h +++ /dev/null @@ -1,1016 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : main header file - - -#ifndef CRYINCLUDE_CRYCOMMON_ISERIALIZE_H -#define CRYINCLUDE_CRYCOMMON_ISERIALIZE_H -#pragma once - -#include <Cry_Math.h> -#include <IXml.h> -#include "MiniQueue.h" -#include <VectorSet.h> -#include <VectorMap.h> -#include <StlUtils.h> -#include <AzCore/Math/Vector3.h> -#include <list> - -class CTimeValue; -// Forward template declaration -template<class T, class U> -class InterpolatedValue_tpl; - -// Unfortunately this needs to be here - should be in CryNetwork somewhere. -struct SNetObjectID -{ - static const uint16 InvalidId = ~uint16(0); - - SNetObjectID() - : id(InvalidId) - , salt(0) {} - SNetObjectID(uint16 i, uint16 s) - : id(i) - , salt(s) {} - - uint16 id; - uint16 salt; - - ILINE bool operator!() const - { - return id == InvalidId; - } - typedef uint16 (SNetObjectID::* unknown_bool_type); - ILINE operator unknown_bool_type() const - { - return !!(*this) ? &SNetObjectID::id : NULL; - } - ILINE bool operator!=(const SNetObjectID& rhs) const - { - return !(*this == rhs); - } - ILINE bool operator==(const SNetObjectID& rhs) const - { - return id == rhs.id && salt == rhs.salt; - } - ILINE bool operator<(const SNetObjectID& rhs) const - { - return id < rhs.id || (id == rhs.id && salt < rhs.salt); - } - ILINE bool operator>(const SNetObjectID& rhs) const - { - return id > rhs.id || (id == rhs.id && salt > rhs.salt); - } - - bool IsLegal() const - { - return salt != 0; - } - - const char* GetText(char* tmpBuf = nullptr, size_t bufferSize = 0) const - { - static char singlebuf[64]; - if (!tmpBuf) - { - tmpBuf = singlebuf; - bufferSize = sizeof(singlebuf); - } - - if (id == InvalidId) - { - sprintf_s(tmpBuf, bufferSize, "<nil>"); - } - else if (!salt) - { - sprintf_s(tmpBuf, bufferSize, "illegal:%d:%d", id, salt); - } - else - { - sprintf_s(tmpBuf, bufferSize, "%d:%d", id, salt); - } - - return tmpBuf; - } - - uint32 GetAsUint32() const - { - return (uint32(salt) << 16) | id; - } - - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { /*nothing*/} - - AUTO_STRUCT_INFO -}; - -// this enumeration details what "kind" of serialization we are -// performing, so that classes that want to, for instance, tailor -// the data they present depending on where data is being written -// to can do so -enum ESerializationTarget -{ - eST_SaveGame, - eST_Network, - eST_Script -}; - -// this inner class defines an interface so that OnUpdate -// functions can be passed abstractly through to concrete -// serialization classes -struct ISerializeUpdateFunction -{ - // <interfuscator:shuffle> - virtual ~ISerializeUpdateFunction(){} - virtual void Execute() = 0; - // </interfuscator:shuffle> -}; - -// concrete implementation of IUpdateFunction for a general functor class -template <class F_Update> -class CSerializeUpdateFunction - : public ISerializeUpdateFunction -{ -public: - CSerializeUpdateFunction(F_Update& update) - : m_rUpdate(update) {} - - virtual void Execute() - { - m_rUpdate(); - } - -private: - F_Update m_rUpdate; -}; - -////////////////////////////////////////////////////////////////////////// -// Temporary class for string serialization. -////////////////////////////////////////////////////////////////////////// -struct SSerializeString -{ - AUTO_STRUCT_INFO - - SSerializeString() {}; - SSerializeString(const SSerializeString& src) { m_str.assign(src.c_str()); }; - explicit SSerializeString(const char* sbegin, const char* send) - : m_str(sbegin, send) {}; - ~SSerializeString() {} - - // Casting to const char* - SSerializeString(const char* s) - : m_str(s) { }; - //operator const char* () const { return m_str; } - - SSerializeString& operator =(const SSerializeString& src) { m_str.assign(src.c_str()); return *this; } - SSerializeString& operator =(const char* src) { m_str.assign(src); return *this; } - - bool operator != (const SSerializeString& src) { return m_str != src.m_str; } - - size_t size() const { return m_str.size(); } - size_t length() const { return m_str.length(); } - const char* c_str() const { return m_str.c_str(); }; - bool empty() const { return m_str.empty(); } - void resize(int sz) { m_str.resize(sz); } - void reserve(int sz) { m_str.reserve(sz); } - - void set_string(const string& s) - { - m_str.assign(s.begin(), s.size()); - } -#if !defined(RESOURCE_COMPILER) - void set_string(const CryStringLocal& s) - { - m_str.assign(s.begin(), s.size()); - } -#endif - template<size_t S> - void set_string(const CryFixedStringT<S>& s) - { - m_str.assign(s.begin(), s.size()); - } - - operator const string () const { - return m_str; - } - -private: - string m_str; -}; - -// the ISerialize is intended to be implemented by objects that need -// to read and write from various data sources, in such a way that -// different tradeoffs can be balanced by the object that is being -// serialized, and so that objects being serialized need only write -// a single function in order to be read from and written to -struct ISerialize -{ - static const int ENUM_POLICY_TAG = 0xe0000000; - - ILINE ISerialize() {} - - // <interfuscator:shuffle> - virtual ~ISerialize(){} - - // this is for string values -- they need special support - virtual void ReadStringValue(const char* name, SSerializeString& curValue, uint32 policy = 0) = 0; - virtual void WriteStringValue(const char* name, SSerializeString& buffer, uint32 policy = 0) = 0; - // this function should be implemented to call the passed in interface - // if we are reading, and to not call it if we are writing - virtual void Update(ISerializeUpdateFunction* pUpdate) = 0; - - // for network updates: notify the network engine that this value was only partially read and we - // should re-request an update from the server soon - virtual void FlagPartialRead() = 0; - - ////////////////////////////////////////////////////////////////////////// - // these functions should be implemented to deal with groups - ////////////////////////////////////////////////////////////////////////// - - // Begins a serialization group - must be matched by an EndGroup - // szName is preferably as short as possible for performance reasons - // Spaces in szName cause undefined behaviour, use alpha characters,underscore and numbers only for a name. - virtual void BeginGroup(const char* szName) = 0; - virtual bool BeginOptionalGroup(const char* szName, bool condition) = 0; - virtual void EndGroup() = 0; - ////////////////////////////////////////////////////////////////////////// - - virtual bool IsReading() const = 0; - virtual bool ShouldCommitValues() const = 0; - virtual ESerializationTarget GetSerializationTarget() const = 0; - virtual bool Ok() const = 0; - // </interfuscator:shuffle> - - // declare all primitive Value() implementations -#define SERIALIZATION_TYPE(T) \ - virtual void Value(const char* name, T & x, uint32 policy) = 0; -#include "SerializationTypes.h" -#undef SERIALIZATION_TYPE - - // declare all primitive Value() implementations -#define SERIALIZATION_TYPE(T) \ - virtual void ValueWithDefault(const char* name, T & x, const T&defaultValue) = 0; -#include "SerializationTypes.h" - SERIALIZATION_TYPE(SSerializeString) -#undef SERIALIZATION_TYPE - void Value([[maybe_unused]] const char* name, [[maybe_unused]] AZ::Vector3& x) - { - } - template <class B> - void Value(const char* name, B& x) - { - Value(name, x, 0); - } - - template <class B> - void Value(const char* name, B& x, uint32 policy); - - template <class B> - void ValueWithDefault(const char* name, B& x, const B& defaultValue); -}; - -// this class provides a wrapper so that ISerialize can be used much more -// easily; it is a template so that if we need to wrap a more specific -// ISerialize implementation we can do so easily -template <class TISerialize> -class CSerializeWrapper -{ -public: - CSerializeWrapper(TISerialize* pSerialize) - : m_pSerialize(pSerialize) - { - } - - // we provide a wrapper around the abstract implementation - // ISerialize to allow easy changing of our - // interface, and easy implementation of our details. - // some of the wrappers are trivial, however for consistency, they - // have been made to follow the trend. - - // the value function allows us to declare that a value needs - // to be serialized/deserialized; we can pass a serialization policy - // in order to compress the value, and an update function to allow - // us to be informed of when this value is changed - template <typename T_Value> - ILINE void Value(const char* szName, T_Value& value, int policy) - { - m_pSerialize->Value(szName, value, policy); - } - - template <typename T_Value> - ILINE void Value(const char* szName, T_Value& value) - { - m_pSerialize->Value(szName, value); - } - - void Value(const char* szName, string& value, int policy) - { - if (IsWriting()) - { - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->WriteStringValue(szName, serializeString, policy); - } - else - { - if (GetSerializationTarget() != eST_Script) - { - value = ""; - } - - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->ReadStringValue(szName, serializeString, policy); - value = serializeString.c_str(); - } - } - ILINE void Value(const char* szName, string& value) - { - Value(szName, value, 0); - } - void Value(const char* szName, const string& value, int policy) - { - if (IsWriting()) - { - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->WriteStringValue(szName, serializeString, policy); - } - else - { - assert(0 && "This function can only be used for Writing"); - } - } - ILINE void Value(const char* szName, const string& value) - { - Value(szName, value, 0); - } - template <typename T> - void Value(const char* szName, CryStringLocalT<T>& value, int policy) - { - if (IsWriting()) - { - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->WriteStringValue(szName, serializeString, policy); - } - else - { - if (GetSerializationTarget() != eST_Script) - { - value = ""; - } - - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->ReadStringValue(szName, serializeString, policy); - value = serializeString.c_str(); - } - } - template <typename T> - ILINE void Value(const char* szName, CryStringLocalT<T>& value) - { - Value(szName, value, 0); - } - template <typename T> - void Value(const char* szName, const CryStringLocalT<T>& value, int policy) - { - if (IsWriting()) - { - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->WriteStringValue(szName, serializeString, policy); - } - else - { - assert(0 && "This function can only be used for Writing"); - } - } - template <typename T> - ILINE void Value(const char* szName, const CryStringLocalT<T>& value) - { - Value(szName, value, 0); - } - template<size_t S> - void Value(const char* szName, CryFixedStringT<S>& value, int policy) - { - if (IsWriting()) - { - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->WriteStringValue(szName, serializeString, policy); - } - else - { - if (GetSerializationTarget() != eST_Script) - { - value = ""; - } - - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->ReadStringValue(szName, serializeString, policy); - assert(serializeString.length() <= S); - value = serializeString.c_str(); - } - } - template<size_t S> - ILINE void Value(const char* szName, CryFixedStringT<S>& value) - { - Value(szName, value, 0); - } - template <class T_Class, typename T_Value> - void Value(const char* szName, T_Class* pInst, T_Value (T_Class::* get)() const, void (T_Class::* set)(T_Value)) - { - if (IsWriting()) - { - T_Value temp = (pInst->*get)(); - Value(szName, temp); - } - else - { - T_Value temp; - Value(szName, temp); - (pInst->*set)(temp); - } - } - - template<class T, class TT> - void Value(const char* name, InterpolatedValue_tpl<T, TT>& val) - { - if (IsWriting()) - { - T a = val.Get(); - Value(name, a); - } - - if (IsReading()) - { - T a; - Value(name, a); - val.SetGoal(a); - } - } - - template<class T, class TT> - void Value(const char* name, InterpolatedValue_tpl<T, TT>& val, int policy) - { - if (IsWriting()) - { - T a = val.Get(); - Value(name, a, policy); - } - - if (IsReading()) - { - T a; - Value(name, a, policy); - val.SetGoal(a); - } - } - - bool ValueChar(const char* name, char* buffer, int len) - { - string temp; - if (IsReading()) - { - Value(name, temp); - if ((int)temp.length() > len - 1) - { - return false; // truncated read - } - memcpy(buffer, temp.data(), temp.length() + 1); - buffer[len - 1] = 0; - } - else - { - temp = string(buffer, buffer + len); - Value(name, temp); - } - return true; - } - - template <typename T> - void ValueWithDefault(const char* name, T& x, const T& defaultValue) - { - m_pSerialize->ValueWithDefault(name, x, defaultValue); - } - - void ValueWithDefault(const char* szName, string& value, const string& defaultValue) - { - static SSerializeString defaultSerializeString; - - { - defaultSerializeString.set_string(defaultValue); - } - - SSerializeString& serializeString = SetSharedSerializeString(value); - m_pSerialize->ValueWithDefault(szName, serializeString, defaultSerializeString); - if (IsReading()) - { - value = serializeString.c_str(); - } - } - - template <class T_Class, typename T_Value, class T_SerializationPolicy> - void Value(const char* szName, T_Class* pInst, T_Value (T_Class::* get)() const, void (T_Class::* set)(T_Value), - const T_SerializationPolicy& policy) - { - if (IsWriting()) - { - T_Value temp = (pInst->*get)(); - Value(szName, temp, policy); - } - else - { - T_Value temp = static_cast<T_Value>(0); - Value(szName, temp, policy); - (pInst->*set)(temp); - } - } - - // a value that is written by referring to a map of key/value pairs - we receive the key, and write the value - template <class T_Key, class T_Map> - void MappedValue(const char* szName, T_Key& value, const T_Map& mapper) - { - typedef typename T_Map::ValueType T_Value; - - if (IsWriting()) - { - T_Value write = mapper.KeyToValue(value); - Value(szName, write); - } - else - { - T_Value read; - Value(szName, read); - value = mapper.ValueToKey(read); - } - } - -#define CONTAINER_VALUE(container_type, insert_function) \ - template <typename T_Value, class Allocator> \ - void Value(const char* name, container_type<T_Value, Allocator>&cont) \ - { \ - if (!BeginOptionalGroup(name, true)) {return; } \ - if (IsWriting()) \ - { \ - uint32 count = cont.size(); \ - Value("Size", count); \ - for (typename container_type<T_Value, Allocator>::iterator iter = cont.begin(); iter != cont.end(); ++iter) \ - { \ - BeginGroup("i"); \ - T_Value value = *iter; \ - Value("v", value); \ - EndGroup(); \ - } \ - } \ - else \ - { \ - cont.clear(); \ - uint32 count = 0; \ - Value("Size", count); \ - while (count--) \ - { \ - BeginGroup("i"); \ - T_Value temp; \ - Value("v", temp); \ - cont.insert_function(temp); \ - EndGroup(); \ - } \ - } \ - EndGroup(); \ - } \ - template <typename T_Value, class T_Map> \ - void MappedValue(const char* name, container_type<T_Value>&cont, const T_Map&mapper) \ - { \ - if (!BeginOptionalGroup(name, true)) {return; } \ - if (IsWriting()) \ - { \ - uint32 count = cont.size(); \ - Value("Size", count); \ - for (typename container_type<T_Value>::iterator iter = cont.begin(); iter != cont.end(); ++iter) \ - { \ - BeginGroup("i"); \ - MappedValue("v", *iter, mapper); \ - EndGroup(); \ - } \ - } \ - else \ - { \ - cont.clear(); \ - uint32 count = 0; \ - Value("Size", count); \ - while (count--) \ - { \ - BeginGroup("i"); \ - T_Value temp; \ - MappedValue("v", temp, mapper); \ - cont.insert_function(temp); \ - EndGroup(); \ - } \ - } \ - EndGroup(); \ - } - -#define PAIR_CONTAINER_VALUE(container_type, insert_function) \ - template <typename T_Value1, typename T_Value2, class Allocator> \ - void Value(const char* name, container_type<std::pair<T_Value1, T_Value2>, Allocator>&cont) \ - { \ - if (!BeginOptionalGroup(name, true)) {return; } \ - if (IsWriting()) \ - { \ - uint32 count = cont.size(); \ - Value("Size", count); \ - for (typename container_type<std::pair<T_Value1, T_Value2>, Allocator>::iterator iter = cont.begin(); iter != cont.end(); ++iter) \ - { \ - BeginGroup("i"); \ - T_Value1 value1 = iter->first; \ - T_Value2 value2 = iter->second; \ - Value("v1", value1); \ - Value("v2", value2); \ - EndGroup(); \ - } \ - } \ - else \ - { \ - cont.clear(); \ - uint32 count = 0; \ - Value("Size", count); \ - while (count--) \ - { \ - BeginGroup("i"); \ - T_Value1 temp1; \ - T_Value2 temp2; \ - Value("v1", temp1); \ - Value("v2", temp2); \ - cont.insert_function(std::pair<T_Value1, T_Value2>(temp1, temp2)); \ - EndGroup(); \ - } \ - } \ - EndGroup(); \ - } \ - - CONTAINER_VALUE(std::vector, push_back); - CONTAINER_VALUE(std::list, push_back); - CONTAINER_VALUE(std::set, insert); - CONTAINER_VALUE(std::deque, push_back); - CONTAINER_VALUE(VectorSet, insert); - CONTAINER_VALUE(DynArray, insert); - - PAIR_CONTAINER_VALUE(std::list, push_back); - PAIR_CONTAINER_VALUE(std::vector, push_back); - - template <typename T_Value> - void DummyValues(uint32 numDummyValues) - { - T_Value dummyValue; - for (uint32 i = 0; i < numDummyValues; ++i) - { - Value("Value", dummyValue); - } - } - - template <typename T_Value, uint8 N> - void Value(const char* name, MiniQueue<T_Value, N>& cont) - { - if (!BeginOptionalGroup(name, true)) - { - return; - } - if (IsWriting()) - { - uint32 count = cont.Size(); - Value("Size", count); - for (typename MiniQueue<T_Value, N>::SIterator iter = cont.Begin(); iter != cont.End(); ++iter) - { - T_Value value = *iter; - Value("Value", value); - } - } - else - { - cont.Clear(); - uint32 count = 0; - Value("Size", count); - while (count--) - { - T_Value temp; - Value("Value", temp); - cont.Push(temp); - } - } - DummyValues<T_Value>(cont.Capacity() - cont.Size()); - EndGroup(); - } - template <typename T_Value, uint8 N, class T_Map> - void MappedValue(const char* name, MiniQueue<T_Value, N>& cont, const T_Map& mapper) - { - if (!BeginOptionalGroup(name, true)) - { - return; - } - if (IsWriting()) - { - uint8 count = cont.Size(); - Value("Size", count); - for (typename MiniQueue<T_Value, N>::SIterator iter = cont.Begin(); iter != cont.End(); ++iter) - { - BeginGroup("i"); - MappedValue("Value", *iter, mapper); - EndGroup(); - } - } - else - { - cont.Clear(); - uint8 count = 0; - Value("Size", count); - while (count--) - { - BeginGroup("i"); - T_Value temp; - MappedValue("Value", temp, mapper); - cont.Push(temp); - EndGroup(); - } - } - EndGroup(); - } - -#define MAP_CONTAINER_VALUE(container_type) \ - template <typename T_Key, typename T_Value> \ - void Value(const char* name, container_type<T_Key, T_Value>&cont) \ - { \ - if (!BeginOptionalGroup(name, true)) {return; } \ - if (IsWriting()) \ - { \ - uint32 count = (uint32)cont.size(); \ - Value("Size", count); \ - for (typename container_type<T_Key, T_Value>::iterator iter = cont.begin(); iter != cont.end(); ++iter) \ - { \ - T_Key tempKey = iter->first; \ - BeginGroup("pair"); \ - Value("k", tempKey); \ - Value("v", iter->second); \ - EndGroup(); \ - } \ - } \ - else \ - { \ - cont.clear(); \ - uint32 count; \ - Value("Size", count); \ - while (count--) \ - { \ - std::pair<T_Key, T_Value> temp; \ - BeginGroup("pair"); \ - Value("k", temp.first); \ - Value("v", temp.second); \ - EndGroup(); \ - cont.insert(temp); \ - } \ - } \ - EndGroup(); \ - } - -#define HASH_CONTAINER_VALUE(container_type) \ - template <typename T_Key, typename T_Value, typename T_Hash> \ - void Value(const char* name, container_type<T_Key, T_Value, T_Hash>&cont) \ - { \ - if (!BeginOptionalGroup(name, true)) {return; } \ - if (IsWriting()) \ - { \ - uint32 count = (uint32)cont.size(); \ - Value("Size", count); \ - for (typename container_type<T_Key, T_Value, T_Hash>::iterator iter = cont.begin(); iter != cont.end(); ++iter) \ - { \ - T_Key tempKey = iter->first; \ - BeginGroup("pair"); \ - Value("k", tempKey); \ - Value("v", iter->second); \ - EndGroup(); \ - } \ - } \ - else \ - { \ - cont.clear(); \ - uint32 count; \ - Value("Size", count); \ - while (count--) \ - { \ - AZStd::pair<T_Key, T_Value> temp; \ - BeginGroup("pair"); \ - Value("k", temp.first); \ - Value("v", temp.second); \ - EndGroup(); \ - cont.insert(temp); \ - } \ - } \ - EndGroup(); \ - } - MAP_CONTAINER_VALUE(std::map); - MAP_CONTAINER_VALUE(std::multimap); - MAP_CONTAINER_VALUE(VectorMap); - - HASH_CONTAINER_VALUE(AZStd::unordered_map); - - template <typename T_Value> - ILINE void EnumValue(const char* szName, T_Value& value, - T_Value first, T_Value last) - { - int32 nValue = int32(value) - first; - Value(szName, nValue, ISerialize::ENUM_POLICY_TAG | (last - first)); - value = T_Value(nValue + first); - } - template <typename T_Value, class T_Class> - ILINE void EnumValue(const char* szName, - T_Class* pClass, T_Value (T_Class::* GetValue)() const, void (T_Class::* SetValue)(T_Value), - T_Value first, T_Value last) - { - bool w = IsWriting(); - int nValue; - if (w) - { - nValue = int32((pClass->*GetValue)()) - first; - } - Value(szName, nValue, ISerialize::ENUM_POLICY_TAG | (last - first)); - if (!w) - { - (pClass->*SetValue)(T_Value(nValue + first)); - } - } - /* - // we can request that a functor be called whenever our values - // are being updated by calling this function - template <class F_Update> - ILINE void OnUpdate( F_Update& update ) - { - CUpdateFunction<F_Update> func(update); - m_pSerialize->Update( &func ); - } - template <class T> - ILINE void OnUpdate( T * pCls, void (T::*func)() ) - { - class CFunc : public IUpdateFunction - { - public: - CFunc( T * pCls, void (T::*func)() ) : m_pCls(pCls), m_func(func) {} - virtual void Execute() - { - (m_pCls->*m_func)(); - } - private: - T * m_pCls; - void (T::*m_func)(); - }; - CFunc ifunc( pCls, func ); - m_pSerialize->Update( &ifunc ); - } - */ - // groups help us find common data - ILINE void BeginGroup(const char* szName) - { - m_pSerialize->BeginGroup(szName); - } - ILINE bool BeginOptionalGroup(const char* szName, bool condition) - { - return m_pSerialize->BeginOptionalGroup(szName, condition); - } - ILINE void EndGroup() - { - m_pSerialize->EndGroup(); - } - - // fetch the serialization target - ILINE ESerializationTarget GetSerializationTarget() const - { - return m_pSerialize->GetSerializationTarget(); - } - - ILINE bool IsWriting() const - { - return !m_pSerialize->IsReading(); - } - ILINE bool IsReading() const - { - return m_pSerialize->IsReading(); - } - ILINE bool ShouldCommitValues() const - { - assert(m_pSerialize->IsReading()); - return m_pSerialize->ShouldCommitValues(); - } - - ILINE bool Ok() const - { - return m_pSerialize->Ok(); - } - - friend ILINE TISerialize* GetImpl(CSerializeWrapper<TISerialize> ser) - { - return ser.m_pSerialize; - } - - ILINE void FlagPartialRead() - { - m_pSerialize->FlagPartialRead(); - } - - operator CSerializeWrapper<ISerialize>() - { - return CSerializeWrapper<ISerialize>(m_pSerialize); - } - - SSerializeString& SetSharedSerializeString(const string& str) - { - static SSerializeString serializeString; - serializeString.set_string(str); - return serializeString; - } - -#if !defined(RESOURCE_COMPILER) - SSerializeString& SetSharedSerializeString(const CryStringLocal& str) - { - - - static SSerializeString serializeString; - serializeString.set_string(str); - return serializeString; - } -#endif - - template<size_t S> - SSerializeString& SetSharedSerializeString(const CryFixedStringT<S>& str) - { - - - static SSerializeString serializeString; - serializeString.set_string(str); - return serializeString; - } - -private: - TISerialize* m_pSerialize; -}; - -// default serialize class to use!! -typedef CSerializeWrapper<ISerialize> TSerialize; - -// simple struct to declare something serializable... useful for -// exposition -struct ISerializable -{ - virtual ~ISerializable(){} - virtual void SerializeWith(TSerialize) = 0; -}; - -template <class B> -void ISerialize::Value(const char* name, B& x, uint32 policy) -{ - if (!BeginOptionalGroup(name, true)) - { - return; - } - TSerialize ser(this); - x.Serialize(ser); - EndGroup(); -} -// -//template <> -//void ISerialize::Value(const char * name, AZ::Vector3& x, uint32 policy) -//{ -// -//} - -// Based off ValueWithDefault in SimpleSerialize.h -template <class B> -void ISerialize::ValueWithDefault(const char* name, B& x, const B& defaultValue) -{ - if (BeginOptionalGroup(name, x != defaultValue)) - { - TSerialize ser(this); - x.Serialize(ser); - EndGroup(); - } - else if (IsReading()) - { - x = defaultValue; - } -} - -////////////////////////////////////////////////////////////////////////// -// Used to automatically Begin/End group in serialization stream -////////////////////////////////////////////////////////////////////////// -struct SSerializeScopedBeginGroup -{ - SSerializeScopedBeginGroup(TSerialize& ser, const char* sGroupName) - { - m_pSer = &ser; - m_pSer->BeginGroup(sGroupName); - } - ~SSerializeScopedBeginGroup() - { - m_pSer->EndGroup(); - } -private: - TSerialize* m_pSer; -}; - -#endif // CRYINCLUDE_CRYCOMMON_ISERIALIZE_H diff --git a/Code/CryEngine/CryCommon/IShader.h b/Code/CryEngine/CryCommon/IShader.h deleted file mode 100644 index c14a7a8af4..0000000000 --- a/Code/CryEngine/CryCommon/IShader.h +++ /dev/null @@ -1,3309 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Shaders common interface. - - -#ifndef CRYINCLUDE_CRYCOMMON_ISHADER_H -#define CRYINCLUDE_CRYCOMMON_ISHADER_H -#pragma once - - -#if defined(LINUX) || defined(APPLE) - #include <platform.h> -#endif - -#include "smartptr.h" -#include "Cry_Vector2.h" -#include "Cry_Vector3.h" -#include "Cry_Matrix33.h" -#include "Cry_Color.h" -#include "smartptr.h" -#include "StringUtils.h" -#include <IXml.h> // <> required for Interfuscator -#include "smartptr.h" -#include "VertexFormats.h" -#include <Vertex.h> -#include <AzCore/Casting/numeric_cast.h> -#include <AzCore/std/containers/map.h> - -#include "Cry_XOptimise.h" -#include <CrySizer.h> -#include <IMaterial.h> - -struct IMaterial; -class CRendElementBase; -class CRenderObject; -class CREMesh; -struct IRenderMesh; -struct IShader; -struct IVisArea; -class CShader; -class CRendElement; -class CRendElementBase; -class ITexAnim; -struct SShaderPass; -struct SShaderItem; -class ITexture; -struct IMaterial; -struct SParam; -struct SShaderSerializeContext; -struct IAnimNode; -struct SSkinningData; -struct SSTexSamplerFX; -struct SShaderTextureSlot; -struct IRenderElement; - -namespace AZ -{ - class LegacyJobExecutor; - - namespace Vertex - { - class Format; - } -} - -//================================================================ -// Summary: -// Geometry Culling type. -enum ECull -{ - eCULL_Back = 0, // Back culling flag. - eCULL_Front, // Front culling flag. - eCULL_None // No culling flag. -}; - -enum ERenderResource -{ - eRR_Unknown, - eRR_Mesh, - eRR_Texture, - eRR_Shader, - eRR_ShaderResource, -}; - -enum EEfResTextures : int // This needs a fixed size so the enum can be forward declared (needed by IMaterial.h) -{ - EFTT_DIFFUSE = 0, - EFTT_NORMALS, - EFTT_SPECULAR, - EFTT_ENV, - EFTT_DETAIL_OVERLAY, - EFTT_SECOND_SMOOTHNESS, - EFTT_HEIGHT, - EFTT_DECAL_OVERLAY, - EFTT_SUBSURFACE, - EFTT_CUSTOM, - EFTT_CUSTOM_SECONDARY, - EFTT_OPACITY, - EFTT_SMOOTHNESS, - EFTT_EMITTANCE, - EFTT_OCCLUSION, - EFTT_SPECULAR_2, - - EFTT_MAX, - EFTT_UNKNOWN = EFTT_MAX -}; - -enum EEfResSamplers -{ - EFSS_ANISO_HIGH = 0, - EFSS_ANISO_LOW, - EFSS_TRILINEAR, - EFSS_BILINEAR, - EFSS_TRILINEAR_CLAMP, - EFSS_BILINEAR_CLAMP, - EFSS_ANISO_HIGH_BORDER, - EFSS_TRILINEAR_BORDER, - - EFSS_MAX, -}; - -//========================================================================= - -// Summary: -// Array Pointers for Shaders. - -enum ESrcPointer -{ - eSrcPointer_Unknown, - eSrcPointer_Vert, - eSrcPointer_Color, - eSrcPointer_Tex, - eSrcPointer_TexLM, - eSrcPointer_Normal, - eSrcPointer_Tangent, - eSrcPointer_Max, -}; - -struct SWaveForm; -struct SWaveForm2; - -#define FRF_REFRACTIVE 1 -// FREE 2 -#define FRF_HEAT 4 -#define MAX_HEATSCALE 4 - -#if !defined(MAX_JOINT_AMOUNT) -#error MAX_JOINT_AMOUNT is not defined -#endif - -#if (MAX_JOINT_AMOUNT <= 256) -typedef uint8 JointIdType; -#else -typedef uint16 JointIdType; -#endif - -// The soft maximum cap for the sliders for emissive intensity. Also used to clamp legacy glow calculations in MaterialHelpers::MigrateXmlLegacyData. -// Note this is a "soft max" because the Emissive Intensity slider is capped at 200, but values higher than 200 may be entered in the text field. -#define EMISSIVE_INTENSITY_SOFT_MAX 200.0f - -//========================================================================= - -enum EParamType -{ - eType_UNKNOWN, - eType_BYTE, - eType_BOOL, - eType_SHORT, - eType_INT, - eType_HALF, - eType_FLOAT, - eType_STRING, - eType_FCOLOR, - eType_VECTOR, - eType_TEXTURE_HANDLE, - eType_CAMERA, - eType_FCOLORA, // with alpha channel -}; - -enum ESamplerType -{ - eSType_UNKNOWN, - eSType_Sampler, - eSType_SamplerComp, -}; - -union UParamVal -{ - byte m_Byte; - bool m_Bool; - short m_Short; - int m_Int; - float m_Float; - char* m_String; - float m_Color[4]; - float m_Vector[3]; - CCamera* m_pCamera; -}; - -// Note: -// In order to facilitate the memory allocation tracking, we're using here this class; -// if you don't like it, please write a substitute for all string within the project and use them everywhere. -struct SShaderParam -{ - AZStd::string m_Name; - AZStd::string m_Script; - UParamVal m_Value; - EParamType m_Type; - uint8 m_eSemantic; - uint8 m_Pad[3] = { 0 }; - - inline void Construct() - { - memset(&m_Value, 0, sizeof(m_Value)); - m_Type = eType_UNKNOWN; - m_eSemantic = 0; - m_Name.clear(); - m_Script.clear(); - } - inline SShaderParam() - { - Construct(); - } - size_t Size() - { - size_t nSize = sizeof(*this); - if (m_Type == eType_STRING) - { - nSize += strlen (m_Value.m_String) + 1; - } - - return nSize; - } - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(m_Script); - if (m_Type == eType_STRING) - { - pSizer->AddObject(m_Value.m_String, strlen (m_Value.m_String) + 1); - } - } - - inline void Destroy() - { - if (m_Type == eType_STRING) - { - delete [] m_Value.m_String; - } - } - inline ~SShaderParam() - { - Destroy(); - } - inline SShaderParam (const SShaderParam& src) - { - m_Name = src.m_Name; - m_Script = src.m_Script; - m_Type = src.m_Type; - m_eSemantic = src.m_eSemantic; - if (m_Type == eType_STRING) - { - const size_t len = strlen(src.m_Value.m_String) + 1; - m_Value.m_String = new char[len]; - azstrcpy(m_Value.m_String, len, src.m_Value.m_String); - } - else - { - m_Value = src.m_Value; - } - } - inline SShaderParam& operator = (const SShaderParam& src) - { - this->~SShaderParam(); - new(this)SShaderParam(src); - return *this; - } - - static bool SetParam(const char* name, AZStd::vector<SShaderParam>* Params, const UParamVal& pr) - { - uint32 i; - for (i = 0; i < (uint32)Params->size(); i++) - { - SShaderParam* sp = &(*Params)[i]; - if (!sp || &sp->m_Value == &pr) - { - continue; - } - if (azstricmp(sp->m_Name.c_str(), name) == 0) - { - if (sp->m_Type == eType_STRING) - { - delete[] sp->m_Value.m_String; - } - - - switch (sp->m_Type) - { - case eType_FLOAT: - sp->m_Value.m_Float = pr.m_Float; - break; - case eType_SHORT: - sp->m_Value.m_Short = pr.m_Short; - break; - case eType_INT: - case eType_TEXTURE_HANDLE: - sp->m_Value.m_Int = pr.m_Int; - break; - - case eType_VECTOR: - sp->m_Value.m_Vector[0] = pr.m_Vector[0]; - sp->m_Value.m_Vector[1] = pr.m_Vector[1]; - sp->m_Value.m_Vector[2] = pr.m_Vector[2]; - break; - - case eType_FCOLOR: - case eType_FCOLORA: - sp->m_Value.m_Color[0] = pr.m_Color[0]; - sp->m_Value.m_Color[1] = pr.m_Color[1]; - sp->m_Value.m_Color[2] = pr.m_Color[2]; - sp->m_Value.m_Color[3] = pr.m_Color[3]; - break; - - case eType_STRING: - { - char* str = pr.m_String; - const size_t len = strlen(str) + 1; - sp->m_Value.m_String = new char [len]; - azstrcpy(sp->m_Value.m_String, len, str); - } - break; - } - break; - } - } - if (i == Params->size()) - { - return false; - } - return true; - } - static bool GetValue(const char* szName, AZStd::vector<SShaderParam>* Params, float* v, int nID); - - static bool GetValue(uint8 eSemantic, AZStd::vector<SShaderParam>* Params, float* v, int nID); - - inline void CopyValue(const SShaderParam& src) - { - if (m_Type == eType_STRING && this != &src) - { - delete[] m_Value.m_String; - - if (src.m_Type == eType_STRING) - { - size_t size = strlen(src.m_Value.m_String) + 1; - m_Value.m_String = new char[size]; - azstrcpy(m_Value.m_String, size, src.m_Value.m_String); - return; - } - } - - m_Value = src.m_Value; - } - - inline void CopyValueNoString(const SShaderParam& src) - { - assert(m_Type != eType_STRING && src.m_Type != eType_STRING); - - m_Value = src.m_Value; - } - - inline void CopyType(const SShaderParam& src) - { - m_Type = src.m_Type; - } -}; - - -// Description: -// IShaderPublicParams can be used to hold a collection of the shader public params. -// Manipulate this collection, and use them during rendering by submit to the SRendParams. -struct IShaderPublicParams -{ - // <interfuscator:shuffle> - virtual ~IShaderPublicParams(){} - virtual void AddRef() = 0; - virtual void Release() = 0; - - // Description: - // Changes number of parameters in collection. - virtual void SetParamCount(int nParam) = 0; - - // Description: - // Retrieves number of parameters in collection. - virtual int GetParamCount() const = 0; - - // Description: - // Retrieves shader public parameter at specified index of the collection. - virtual SShaderParam& GetParam(int nIndex) = 0; - virtual const SShaderParam& GetParam(int nIndex) const = 0; - - // Description: - // Retrieves shader public parameter at specified index of the collection. - virtual SShaderParam* GetParamByName(const char* pszName) = 0; - virtual const SShaderParam* GetParamByName(const char* pszName) const = 0; - - virtual SShaderParam* GetParamBySemantic(uint8 eParamSemantic) = 0; - virtual const SShaderParam* GetParamBySemantic(uint8 eParamSemantic) const = 0; - - // Description: - // Sets a shader parameter (and if doesn't exists, add it to the parameters list). - virtual void SetParam(const char* pszName, UParamVal& pParam, EParamType nType = eType_FLOAT, uint8 eSemantic = 0) = 0; - - // Description: - // Assigns shader public parameter at specified index of the collection. - virtual void SetParam(int nIndex, const SShaderParam& param) = 0; - - // Description: - // Assigns existing shader parameters list. - virtual void SetShaderParams(const AZStd::vector<SShaderParam>& pParams) = 0; - - // Description: - // Adds a new shader public parameter at the end of the collection. - virtual void AddParam(const SShaderParam& param) = 0; - - // Description: - // Removes a shader public parameter - virtual void RemoveParamByName(const char* pszName) = 0; - virtual void RemoveParamBySemantic(uint8 eParamSemantic) = 0; - - // Description: - // Assigns collection of shader public parameters to the specified render params structure. - virtual void AssignToRenderParams(struct SRendParams& rParams) = 0; - - virtual uint8 GetSemanticByName(const char* pszName) = 0; - - // Description: - // Gets shader parameters. - virtual AZStd::vector<SShaderParam>* GetShaderParams() = 0; - virtual const AZStd::vector<SShaderParam>* GetShaderParams() const = 0; - // </interfuscator:shuffle> -}; - -//================================================================================= - -class CInputLightMaterial -{ -public: - CInputLightMaterial() - : m_Diffuse(0, 0, 0, 0) - , m_Specular(0, 0, 0, 0) - , m_Emittance(1, 1, 1, 0) - , m_Opacity(0) - , m_Smoothness(0) - { - // memset() - for (int i = 0; i < EFTT_MAX; i++) - { - m_Channels[i][0] = 0.0f, - m_Channels[i][1] = 1.0f; - } - } - - // scale & bias - ColorF m_Channels[EFTT_MAX][2]; - - // TODO: these will go away - ColorF m_Diffuse; - ColorF m_Specular; - ColorF m_Emittance; // RGB: Color, Alpha: Intensity (kcd/m2 or kilonits) - float m_Opacity; - float m_Smoothness; - - inline friend bool operator == (const CInputLightMaterial& m1, const CInputLightMaterial& m2) - { - return !memcmp(&m1, &m2, CInputLightMaterial::Size()); - } - - inline static int Size() - { - int nSize = sizeof(CInputLightMaterial); - return nSize; - } -}; - -class CTexture; -class CTexAnim; -#include <ITexture.h> - -// Summary: -// Vertex modificators definitions (must be 16 bit flag). - -#define MDV_BENDING 0x100 -#define MDV_DET_BENDING 0x200 -#define MDV_DET_BENDING_GRASS 0x400 -#define MDV_WIND 0x800 -#define MDV_DEPTH_OFFSET 0x2000 - -// Does the vertex shader require position-invariant compilation? -// This would be true of shaders rendering multiple times with different vertex shaders - for example during zprepass and the gbuffer pass -// Note this is different than the technique flag FHF_POSITION_INVARIANT as that does custom behavior for terrain -#define MDV_POSITION_INVARIANT 0x4000 - -// Summary: -// Deformations/Morphing types. -enum EDeformType -{ - eDT_Unknown = 0, - eDT_SinWave = 1, - eDT_SinWaveUsingVtxColor = 2, - eDT_Bulge = 3, - eDT_Squeeze = 4, - eDT_Perlin2D = 5, - eDT_Perlin3D = 6, - eDT_FromCenter = 7, - eDT_Bending = 8, - eDT_ProcFlare = 9, - eDT_AutoSprite = 10, - eDT_Beam = 11, - eDT_FixedOffset = 12, -}; - -// Summary: -// Wave form evaluator flags. -enum EWaveForm -{ - eWF_None, - eWF_Sin, - eWF_HalfSin, - eWF_InvHalfSin, - eWF_Square, - eWF_Triangle, - eWF_SawTooth, - eWF_InvSawTooth, - eWF_Hill, - eWF_InvHill, -}; - -#define WFF_CLAMP 1 -#define WFF_LERP 2 - -// Summary: -// Wave form definition. -struct SWaveForm -{ - EWaveForm m_eWFType; - byte m_Flags; - - float m_Level; - float m_Level1; - float m_Amp; - float m_Amp1; - float m_Phase; - float m_Phase1; - float m_Freq; - float m_Freq1; - - SWaveForm(EWaveForm eWFType, float fLevel, float fAmp, float fPhase, float fFreq) - { - m_eWFType = eWFType; - m_Level = m_Level1 = fLevel; - m_Amp = m_Amp1 = fAmp; - m_Phase = m_Phase1 = fPhase; - m_Freq = m_Freq1 = fFreq; - } - - int Size() - { - int nSize = sizeof(SWaveForm); - return nSize; - } - SWaveForm() - { - memset(this, 0, sizeof(SWaveForm)); - } - bool operator == (const SWaveForm& wf) const - { - if (m_eWFType == wf.m_eWFType && m_Level == wf.m_Level && m_Amp == wf.m_Amp && m_Phase == wf.m_Phase && m_Freq == wf.m_Freq && m_Level1 == wf.m_Level1 && m_Amp1 == wf.m_Amp1 && m_Phase1 == wf.m_Phase1 && m_Freq1 == wf.m_Freq1 && m_Flags == wf.m_Flags) - { - return true; - } - return false; - } - - SWaveForm& operator += (const SWaveForm& wf) - { - m_Level += wf.m_Level; - m_Level1 += wf.m_Level1; - m_Amp += wf.m_Amp; - m_Amp1 += wf.m_Amp1; - m_Phase += wf.m_Phase; - m_Phase1 += wf.m_Phase1; - m_Freq += wf.m_Freq; - m_Freq1 += wf.m_Freq1; - return *this; - } -}; - -struct SWaveForm2 -{ - EWaveForm m_eWFType; - - float m_Level; - float m_Amp; - float m_Phase; - float m_Freq; - - SWaveForm2() - { - memset(this, 0, sizeof(SWaveForm2)); - } - bool operator == (const SWaveForm2& wf) const - { - if (m_eWFType == wf.m_eWFType && m_Level == wf.m_Level && m_Amp == wf.m_Amp && m_Phase == wf.m_Phase && m_Freq == wf.m_Freq) - { - return true; - } - return false; - } - - SWaveForm2& operator += (const SWaveForm2& wf) - { - m_Level += wf.m_Level; - m_Amp += wf.m_Amp; - m_Phase += wf.m_Phase; - m_Freq += wf.m_Freq; - return *this; - } -}; - -struct SDeformInfo -{ - EDeformType m_eType; - SWaveForm2 m_WaveX; - float m_fDividerX; - Vec3 m_vNoiseScale; - - SDeformInfo() - { - m_eType = eDT_Unknown; - m_fDividerX = 0.01f; - m_vNoiseScale = Vec3(1, 1, 1); - } - - inline bool operator == (const SDeformInfo& m) - { - if (m_eType == m.m_eType && - m_WaveX == m.m_WaveX && - m_vNoiseScale == m.m_vNoiseScale && - m_fDividerX == m.m_fDividerX) - { - return true; - } - - return false; - } - - int Size() - { - return sizeof(SDeformInfo); - } - - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->Add(*this); - } -}; - -//============================================================================== -// CRenderObject - -////////////////////////////////////////////////////////////////////// -// CRenderObject::m_ObjFlags: Flags used by shader pipeline - -enum ERenderObjectFlags -{ - FOB_VERTEX_VELOCITY = BIT(0), - FOB_RENDER_TRANS_AFTER_DOF = BIT(1), //transparencies rendered after depth of field - //Unused = BIT(2), - FOB_RENDER_AFTER_POSTPROCESSING = BIT(3), - FOB_OWNER_GEOMETRY = BIT(4), - FOB_MESH_SUBSET_INDICES = BIT(5), - FOB_SELECTED = BIT(6), - FOB_RENDERER_IDENDITY_OBJECT = BIT(7), - FOB_GLOBAL_ILLUMINATION = BIT(8), - FOB_NO_FOG = BIT(9), - FOB_DECAL = BIT(10), - FOB_OCTAGONAL = BIT(11), - FOB_POINT_SPRITE = BIT(13), - FOB_SOFT_PARTICLE = BIT(14), - FOB_REQUIRES_RESOLVE = BIT(15), - FOB_UPDATED_RTMASK = BIT(16), - FOB_AFTER_WATER = BIT(17), - FOB_BENDED = BIT(18), - FOB_ZPREPASS = BIT(19), - FOB_PARTICLE_SHADOWS = BIT(20), - FOB_DISSOLVE = BIT(21), - FOB_MOTION_BLUR = BIT(22), - FOB_NEAREST = BIT(23), // [Rendered in Camera Space] - FOB_SKINNED = BIT(24), - FOB_DISSOLVE_OUT = BIT(25), - FOB_DYNAMIC_OBJECT = BIT(26), - FOB_ALLOW_TESSELLATION = BIT(27), - FOB_DECAL_TEXGEN_2D = BIT(28), - FOB_IN_DOORS = BIT(29), - FOB_HAS_PREVMATRIX = BIT(30), - FOB_LIGHTVOLUME = BIT(31), - - FOB_DECAL_MASK = (FOB_DECAL | FOB_DECAL_TEXGEN_2D), - FOB_PARTICLE_MASK = (FOB_SOFT_PARTICLE | FOB_NO_FOG | FOB_GLOBAL_ILLUMINATION | FOB_PARTICLE_SHADOWS | FOB_NEAREST | FOB_MOTION_BLUR | FOB_LIGHTVOLUME | FOB_ALLOW_TESSELLATION | FOB_IN_DOORS | FOB_AFTER_WATER), - - // WARNING: FOB_MASK_AFFECTS_MERGING must start from 0x10000/bit 16 (important for instancing). - FOB_MASK_AFFECTS_MERGING_GEOM = (FOB_ZPREPASS | FOB_SKINNED | FOB_BENDED | FOB_DYNAMIC_OBJECT | FOB_ALLOW_TESSELLATION | FOB_NEAREST), - FOB_MASK_AFFECTS_MERGING = (FOB_ZPREPASS | FOB_MOTION_BLUR | FOB_HAS_PREVMATRIX | FOB_SKINNED | FOB_BENDED | FOB_PARTICLE_SHADOWS | FOB_AFTER_WATER | FOB_DISSOLVE | FOB_DISSOLVE_OUT | FOB_NEAREST | FOB_DYNAMIC_OBJECT | FOB_ALLOW_TESSELLATION) -}; - -struct SSkyInfo -{ - ITexture* m_SkyBox[3]; - float m_fSkyLayerHeight; - - int Size() - { - int nSize = sizeof(SSkyInfo); - return nSize; - } - SSkyInfo() - { - memset(this, 0, sizeof(SSkyInfo)); - } -}; - -struct SBending -{ - Vec2 m_vBending; - float m_fMainBendingScale; - SWaveForm2 m_Waves[2]; - - SBending() - { - m_vBending.zero(); - m_fMainBendingScale = 1.f; - } - - Vec4 GetShaderConstants(float realTime) const; - void GetShaderConstantsStatic(float realTime, Vec4* vBendInfo) const; -}; - -// Description: -// Interface for the skinnable objects (renderer calls its functions to get the skinning data). -// should only created by EF_CreateSkinningData -_MS_ALIGN(16) struct SSkinningData -{ - uint32 nNumBones; - uint32 nHWSkinningFlags; - DualQuat* pBoneQuatsS; - Matrix34* pBoneMatrices; - JointIdType* pRemapTable; - AZ::LegacyJobExecutor* pAsyncJobExecutor; - AZ::LegacyJobExecutor* pAsyncDataJobExecutor; - SSkinningData* pPreviousSkinningRenderData; // used for motion blur - uint32 remapGUID; - void* pCharInstCB; // used if per char instance cbs are available in renderdll (d3d11+); - // members below are for Software Skinning - void* pCustomData; // client specific data, used for example for sw-skinning on animation side - SSkinningData* pNextSkinningData; // List to the next element which needs SW-Skinning -} _ALIGN(16); - -struct SRenderObjData -{ - uintptr_t m_uniqueObjectId; - - SSkinningData* m_pSkinningData; - - float m_fTempVars[10]; // Different useful vars (ObjVal component in shaders) - - // using a pointer, the client code has to ensure that the data stays valid - const AZStd::vector<SShaderParam>* m_pShaderParams; - - uint32 m_nHUDSilhouetteParams; - - uint64 m_nSubObjHideMask; - - union - { - SBending* m_pBending; - }; - - SBending* m_BendingPrev; - - uint16 m_FogVolumeContribIdx[2]; - - uint16 m_nLightID; - uint16 m_LightVolumeId; - - uint8 m_screenBounds[4]; - - uint16 m_nCustomFlags; - uint8 m_nCustomData; - - SRenderObjData() - { - Init(); - } - - void Init() - { - m_nSubObjHideMask = 0; - m_uniqueObjectId = 0; - m_nLightID = 0; - m_LightVolumeId = 0; - m_pSkinningData = NULL; - m_screenBounds[0] = m_screenBounds[1] = m_screenBounds[2] = m_screenBounds[3] = 0; - m_nCustomData = 0; - m_nCustomFlags = 0; - m_nHUDSilhouetteParams = 0; - m_pBending = nullptr; - m_BendingPrev = nullptr; - m_pShaderParams = nullptr; - m_FogVolumeContribIdx[0] = m_FogVolumeContribIdx[1] = static_cast<uint16>(-1); - - // The following should be changed to be something like 0xac to indicate invalid data so that by default - // data that was not set will break render features and will be traced (otherwise, default 0 just might pass) - memset(m_fTempVars, 0, 10 * sizeof(float)); - } - - void SetShaderParams(const AZStd::vector<SShaderParam>* pShaderParams) - { - m_pShaderParams = pShaderParams; - } - - void GetMemoryUsage(ICrySizer* pSizer) const - { - AZ_UNUSED(pSizer); - } -} _ALIGN(16); - -////////////////////////////////////////////////////////////////////// -// Objects using in shader pipeline - - -// Summary: -// Same as in the 3dEngine. -#define MAX_LIGHTS_NUM 32 - -struct ShadowMapFrustum; - -////////////////////////////////////////////////////////////////////// -/// -/// Objects using in shader pipeline -/// Single rendering item, that can be created from 3DEngine and persist across multiple frames -/// It can be compiled into the platform specific efficient rendering compiled object. -/// -////////////////////////////////////////////////////////////////////// -_MS_ALIGN(16) class CRenderObject -{ -public: - AZ_CLASS_ALLOCATOR(CRenderObject, AZ::LegacyAllocator, 0); - - struct SInstanceInfo - { - Matrix34 m_Matrix; - ColorF m_AmbColor; - }; - - struct SInstanceData - { - Matrix34 m_MatInst; - Vec4 m_vBendInfo; - Vec4 m_vDissolveInfo; - }; - - struct PerInstanceConstantBufferKey - { - PerInstanceConstantBufferKey() - : m_Id{0xFFFF} - , m_IndirectId{0xFF} - {} - - inline bool IsValid() const - { - return m_Id != 0xFFFF; - } - - AZ::u16 m_Id; - AZ::u8 m_IndirectId; - }; - - ////////////////////////////////////////////////////////////////////////// - SInstanceInfo m_II; //!< Per instance data - - uint64 m_ObjFlags; //!< Combination of FOB_ flags. - uint32 m_Id; - - float m_fAlpha; //!< Object alpha. - float m_fDistance; //!< Distance to the object. - - union - { - float m_fSort; //!< Custom sort value. - uint16 m_nSort; - }; - - uint64 m_nRTMask; //!< Shader runtime modification flags - uint16 m_nMDV; //!< Vertex modifier flags for Shader. - uint16 m_nRenderQuality; //!< 65535 - full quality, 0 - lowest quality, used by CStatObj - int16 m_nTextureID; //!< Custom texture id. - - union - { - uint8 m_breakableGlassSubFragIndex; - uint8 m_ParticleObjFlags; - }; - uint8 m_nClipVolumeStencilRef; //!< Per instance vis area stencil reference ID - uint8 m_DissolveRef; //!< Dissolve value - uint8 m_RState; //!< Render state used for object - - bool m_NoDecalReceiver; - - uint32 m_nMaterialLayers; //!< Which mtl layers active and how much to blend them - - IRenderNode* m_pRenderNode; //!< Will define instance id. - _smart_ptr<IMaterial> m_pCurrMaterial; //!< Parent material used for render object. - IRenderElement* m_pRE; //!< RenderElement used by this CRenderObject - - PerInstanceConstantBufferKey m_PerInstanceConstantBufferKey; - - //! Embedded SRenderObjData, optional data carried by CRenderObject - SRenderObjData m_data; - -public: - - ////////////////////////////////////////////////////////////////////////// - // Methods - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - /// Constructor - ////////////////////////////////////////////////////////////////////////// - CRenderObject() - : m_Id(~0u) - { - Init(); - } - ~CRenderObject() {}; - - //========================================================================================================= - - inline Vec3 GetTranslation() const { return m_II.m_Matrix.GetTranslation(); } - inline float GetScaleX() const { return sqrt_tpl(m_II.m_Matrix(0, 0) * m_II.m_Matrix(0, 0) + m_II.m_Matrix(0, 1) * m_II.m_Matrix(0, 1) + m_II.m_Matrix(0, 2) * m_II.m_Matrix(0, 2)); } - inline float GetScaleZ() const { return sqrt_tpl(m_II.m_Matrix(2, 0) * m_II.m_Matrix(2, 0) + m_II.m_Matrix(2, 1) * m_II.m_Matrix(2, 1) + m_II.m_Matrix(2, 2) * m_II.m_Matrix(2, 2)); } - - inline void Init() - { - m_ObjFlags = 0; - m_nRenderQuality = 65535; - - m_RState = 0; - m_fDistance = 0.0f; - - m_nClipVolumeStencilRef = 0; - m_nMaterialLayers = 0; - m_DissolveRef = 0; - - m_nMDV = 0; - m_fSort = 0; - - m_II.m_AmbColor = Col_White; - m_fAlpha = 1.0f; - m_nTextureID = -1; - m_pCurrMaterial = nullptr; - m_pRE = nullptr; - m_PerInstanceConstantBufferKey = {}; - - m_nRTMask = 0; - m_pRenderNode = NULL; - - m_NoDecalReceiver = false; - m_data.Init(); - } - void AssignId(uint32 id) { m_Id = id; } - - ILINE Matrix34A& GetMatrix() { return m_II.m_Matrix; } - - ILINE SRenderObjData* GetObjData() - { - return &m_data; - } - - IRenderElement* GetRE() { return m_pRE; } - void SetRE(IRenderElement* re) { m_pRE = re; } - -protected: - - // Disallow copy (potential bugs with PERMANENT objects) - // alwasy use IRendeer::EF_DuplicateRO if you want a copy - // of a CRenderObject - CRenderObject& operator= (CRenderObject& other) = default; - - void CloneObject(CRenderObject* srcObj) - { - *this = *srcObj; - } - - friend class CRenderer; -} _ALIGN(16); - -enum EResClassName -{ - eRCN_Texture, - eRCN_Shader, -}; - -// className: CTexture, CHWShader_VS, CHWShader_PS, CShader -struct SResourceAsync -{ - AZ_CLASS_ALLOCATOR(SResourceAsync, AZ::SystemAllocator, 0); - int nReady; // 0: Not ready; 1: Ready; -1: Error - byte* pData; - EResClassName eClassName; // Resource class name - char* Name; // Resource name - union - { - // CTexture parameters - struct - { - int nWidth, nHeight, nMips, nTexFlags, nFormat, nTexId; - }; - // CShader parameters - struct - { - int nShaderFlags; - }; - }; - void* pResource; // Pointer to created resource - - SResourceAsync() - { - memset(this, 0, sizeof(SResourceAsync)); - } - - ~SResourceAsync() - { - delete Name; - } -}; - -#include "IRenderer.h" - -//============================================================================== - -// Summary: -// Color operations flags. -enum EColorOp -{ - eCO_NOSET = 0, - eCO_DISABLE = 1, - eCO_REPLACE = 2, - eCO_DECAL = 3, - eCO_ARG2 = 4, - eCO_MODULATE = 5, - eCO_MODULATE2X = 6, - eCO_MODULATE4X = 7, - eCO_BLENDDIFFUSEALPHA = 8, - eCO_BLENDTEXTUREALPHA = 9, - eCO_DETAIL = 10, - eCO_ADD = 11, - eCO_ADDSIGNED = 12, - eCO_ADDSIGNED2X = 13, - eCO_MULTIPLYADD = 14, - eCO_BUMPENVMAP = 15, - eCO_BLEND = 16, - eCO_MODULATEALPHA_ADDCOLOR = 17, - eCO_MODULATECOLOR_ADDALPHA = 18, - eCO_MODULATEINVALPHA_ADDCOLOR = 19, - eCO_MODULATEINVCOLOR_ADDALPHA = 20, - eCO_DOTPRODUCT3 = 21, - eCO_LERP = 22, - eCO_SUBTRACT = 23, - eCO_MODULATE_METAL_FONT_SPECIAL_MODE = 24, -}; - -enum EColorArg -{ - eCA_Unknown, - eCA_Specular, - eCA_Texture, - eCA_Texture1, - eCA_Normal, - eCA_Diffuse, - eCA_Previous, - eCA_Constant, -}; - -#define DEF_TEXARG0 (eCA_Texture | (eCA_Diffuse << 3)) -#define DEF_TEXARG1 (eCA_Texture | (eCA_Previous << 3)) - -enum ETexModRotateType -{ - ETMR_NoChange, - ETMR_Fixed, - ETMR_Constant, - ETMR_Oscillated, - ETMR_Max -}; - -enum ETexModMoveType -{ - ETMM_NoChange, - ETMM_Fixed, - ETMM_Constant, - ETMM_Jitter, - ETMM_Pan, - ETMM_Stretch, - ETMM_StretchRepeat, - ETMM_Max -}; - -enum ETexGenType -{ - ETG_Stream, - ETG_World, - ETG_Camera, - ETG_Max -}; - -#define CASE_TEXMOD(var_name) \ - if (!_stricmp(#var_name, szParamName)) \ - { \ - var_name = fValue; \ - return true; \ - } \ - -#define CASE_TEXMODANGLE(var_name) \ - if (!_stricmp(#var_name, szParamName)) \ - { \ - var_name = Degr2Word(fValue); \ - return true; \ - } \ - -#define CASE_TEXMODBYTE(var_name) \ - if (!_stricmp(#var_name, szParamName)) \ - { \ - var_name = (byte)fValue; \ - return true; \ - } \ - -#define CASE_TEXMODBOOL(var_name) \ - if (!_stricmp(#var_name, szParamName)) \ - { \ - var_name = (fValue == 1.f); \ - return true; \ - } \ - -struct SEfTexModificator -{ - AZ_CLASS_ALLOCATOR(SEfTexModificator, AZ::SystemAllocator, 0); - bool SetMember(const char* szParamName, float fValue) - { - CASE_TEXMODBYTE(m_eTGType); - CASE_TEXMODBYTE(m_eRotType); - CASE_TEXMODBYTE(m_eMoveType[0]); - CASE_TEXMODBYTE(m_eMoveType[1]); - CASE_TEXMODBOOL(m_bTexGenProjected); - - CASE_TEXMOD(m_Tiling[0]); - CASE_TEXMOD(m_Tiling[1]); - CASE_TEXMOD(m_Tiling[2]); - CASE_TEXMOD(m_Offs[0]); - CASE_TEXMOD(m_Offs[1]); - CASE_TEXMOD(m_Offs[2]); - - CASE_TEXMODANGLE(m_Rot[0]); - CASE_TEXMODANGLE(m_Rot[1]); - CASE_TEXMODANGLE(m_Rot[2]); - CASE_TEXMODANGLE(m_RotOscRate[0]); - CASE_TEXMODANGLE(m_RotOscRate[1]); - CASE_TEXMODANGLE(m_RotOscRate[2]); - CASE_TEXMODANGLE(m_RotOscAmplitude[0]); - CASE_TEXMODANGLE(m_RotOscAmplitude[1]); - CASE_TEXMODANGLE(m_RotOscAmplitude[2]); - CASE_TEXMODANGLE(m_RotOscPhase[0]); - CASE_TEXMODANGLE(m_RotOscPhase[1]); - CASE_TEXMODANGLE(m_RotOscPhase[2]); - CASE_TEXMOD(m_RotOscCenter[0]); - CASE_TEXMOD(m_RotOscCenter[1]); - CASE_TEXMOD(m_RotOscCenter[2]); - - CASE_TEXMOD(m_OscRate[0]); - CASE_TEXMOD(m_OscRate[1]); - CASE_TEXMOD(m_OscAmplitude[0]); - CASE_TEXMOD(m_OscAmplitude[1]); - CASE_TEXMOD(m_OscPhase[0]); - CASE_TEXMOD(m_OscPhase[1]); - - return false; - } - - _MS_ALIGN(16) Matrix44 m_TexGenMatrix _ALIGN(16); - _MS_ALIGN(16) Matrix44 m_TexMatrix _ALIGN(16); - - float m_Tiling[3]; - float m_Offs[3]; - - float m_RotOscCenter[3]; - - float m_OscRate[2]; - float m_OscAmplitude[2]; - float m_OscPhase[2]; - - // This members are used only during updating of the matrices - float m_LastTime[2]; - float m_CurrentJitter[2]; - - uint16 m_RotOscPhase[3]; - uint16 m_Rot[3]; - uint16 m_RotOscRate[3]; - uint16 m_RotOscAmplitude[3]; - - uint8 m_eTGType; - uint8 m_eRotType; - uint8 m_eMoveType[2]; - bool m_bTexGenProjected; - - void Reset() - { - memset(this, 0, sizeof(*this)); - m_Tiling[0] = m_Tiling[1] = 1.0f; - } - inline SEfTexModificator() - { - Reset(); - } - inline SEfTexModificator(const SEfTexModificator& m) - { - if (&m != this) - { - memcpy(this, &m, sizeof(*this)); - } - } - SEfTexModificator& operator = (const SEfTexModificator& src) - { - if (&src != this) - { - this->~SEfTexModificator(); - new(this)SEfTexModificator(src); - } - return *this; - } - int Size() - { - return sizeof(*this); - } - - inline bool operator != (const SEfTexModificator& m) - { - return memcmp(this, &m, sizeof(*this)) != 0; - } - - inline bool isModified() - { - return ( m_eMoveType[0] != ETMM_NoChange || - m_eMoveType[1] != ETMM_NoChange || - m_eRotType != ETMR_NoChange || - m_Offs[0] != 0.0f || - m_Offs[1] != 0.0f || - m_Tiling[0] != 1.0f || - m_Tiling[1] != 1.0f || - m_Rot[0] != 0.0f || - m_Rot[1] != 0.0f || - m_Rot[2] != 0.0f ); - } -}; - -inline bool IsTextureModifierSupportedForTextureMap(EEfResTextures texture) -{ - // Custom uv modifiers are currently only supported for diffuse, detail, decal, 2nd diffuse, and emittance texture maps - if (texture == EFTT_DIFFUSE || texture == EFTT_DETAIL_OVERLAY || texture == EFTT_DECAL_OVERLAY || texture == EFTT_CUSTOM || texture == EFTT_EMITTANCE) - { - return true; - } - - return false; -} - -////////////////////////////////////////////////////////////////////// -#define FILTER_NONE -1 -#define FILTER_POINT 0 -#define FILTER_LINEAR 1 -#define FILTER_BILINEAR 2 -#define FILTER_TRILINEAR 3 -#define FILTER_ANISO2X 4 -#define FILTER_ANISO4X 5 -#define FILTER_ANISO8X 6 -#define FILTER_ANISO16X 7 - -////////////////////////////////////////////////////////////////////// -#define TADDR_WRAP 0 -#define TADDR_CLAMP 1 -#define TADDR_MIRROR 2 -#define TADDR_BORDER 3 - -//============================================================================== -//------------------------------------------------------------------------------ -struct STexState -{ - struct - { - signed char m_nMinFilter : 8; - signed char m_nMagFilter : 8; - signed char m_nMipFilter : 8; - signed char m_nAddressU : 8; - signed char m_nAddressV : 8; - signed char m_nAddressW : 8; - signed char m_nAnisotropy : 8; - signed char padding : 8; - }; - DWORD m_dwBorderColor; - float m_MipBias; - void* m_pDeviceState; - bool m_bActive; - bool m_bComparison; - bool m_bSRGBLookup; - byte m_bPAD; - // NOTE: There are 4 more pad bytes that exist here because m_pDeviceState is a 64-bit pointer. - uint32 m_PadBytes; - - STexState () - { - // Make sure we clear everything, including "invisible" pad bytes. - memset(this, 0, sizeof(*this)); - } - STexState(int nFilter, bool bClamp) - { - memset(this, 0, sizeof(*this)); - int nAddress = bClamp ? TADDR_CLAMP : TADDR_WRAP; - SetFilterMode(nFilter); - SetClampMode(nAddress, nAddress, nAddress); - SetBorderColor(0); - } - STexState(int nFilter, int nAddressU, int nAddressV, int nAddressW, unsigned int borderColor) - { - memset(this, 0, sizeof(*this)); - SetFilterMode(nFilter); - SetClampMode(nAddressU, nAddressV, nAddressW); - SetBorderColor(borderColor); - } - - void Destroy(); - void Init(const STexState& src); - - ~STexState() { Destroy(); } - STexState(const STexState& src) { Init(src); } - STexState& operator = (const STexState& src) - { - this->~STexState(); - new(this)STexState(src); - return *this; - } - _inline friend bool operator == (const STexState& m1, const STexState& m2) - { - return (*(uint64*)&m1 == *(uint64*)&m2 && m1.m_dwBorderColor == m2.m_dwBorderColor && - m1.m_bActive == m2.m_bActive && m1.m_bComparison == m2.m_bComparison && m1.m_bSRGBLookup == m2.m_bSRGBLookup && - m1.m_MipBias == m2.m_MipBias); - } - void Release() - { - delete this; - } - - bool SetFilterMode(int nFilter); - bool SetClampMode(int nAddressU, int nAddressV, int nAddressW); - void SetBorderColor(DWORD dwColor); - void SetComparisonFilter(bool bEnable); - void PostCreate(); -}; - - -struct IRenderTarget -{ - virtual ~IRenderTarget(){} - virtual void Release() = 0; - virtual void AddRef() = 0; -}; - -//============================================================================== -// FX shader texture sampler (description) -//------------------------------------------------------------------------------ -struct STexSamplerFX -{ -#if SHADER_REFLECT_TEXTURE_SLOTS - string m_szUIName; - string m_szUIDescription; -#endif - - string m_szName; - string m_szTexture; - - union - { - struct SHRenderTarget* m_pTarget; - IRenderTarget* m_pITarget; - }; - - int16 m_nTexState; - byte m_eTexType; // ETEX_Type e.g. eTT_2D or eTT_Cube - byte m_nSlotId; // EFTT_ index if it references one of the material texture slots, EFTT_MAX otherwise - uint32 m_nTexFlags; - - STexSamplerFX() - { - m_nTexState = -1; - m_eTexType = eTT_2D; - m_nSlotId = EFTT_MAX; - m_nTexFlags = 0; - m_pTarget = NULL; - } - - ~STexSamplerFX() - { - SAFE_RELEASE(m_pITarget); - } - - int Size() - { - int nSize = sizeof(*this); - nSize += m_szName.capacity(); - nSize += m_szTexture.capacity(); -#if SHADER_REFLECT_TEXTURE_SLOTS - nSize += m_szUIName.capacity(); - nSize += m_szUIDescription.capacity(); -#endif - return nSize; - } - - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const - { - } - - uint32 GetTexFlags() { return m_nTexFlags; } - void Update(); - void PostLoad(); - NO_INLINE STexSamplerFX (const STexSamplerFX& src) - { - m_pITarget = src.m_pITarget; - if (m_pITarget) - { - m_pITarget->AddRef(); - } - m_szName = src.m_szName; - m_szTexture = src.m_szTexture; - m_nSlotId = src.m_nSlotId; - m_eTexType = src.m_eTexType; - m_nTexFlags = src.m_nTexFlags; - m_nTexState = src.m_nTexState; - -#if SHADER_REFLECT_TEXTURE_SLOTS - m_szUIName = src.m_szUIName; - m_szUIDescription = src.m_szUIDescription; -#endif - } - NO_INLINE STexSamplerFX& operator = (const STexSamplerFX& src) - { - this->~STexSamplerFX(); - new(this)STexSamplerFX(src); - return *this; - } - _inline friend bool operator != (const STexSamplerFX& m1, const STexSamplerFX& m2) - { - if (m1.m_szTexture != m2.m_szTexture || m1.m_eTexType != m2.m_eTexType || m1.m_nTexFlags != m2.m_nTexFlags) - { - return true; - } - return false; - } - _inline bool operator == (const STexSamplerFX& m1) - { - return !(*this != m1); - } - - bool Export(SShaderSerializeContext& SC); - bool Import(SShaderSerializeContext& SC, SSTexSamplerFX* pTS); -}; - - -//============================================================================== -// Resource texture sampler (runtime) -//------------------------------------------------------------------------------ -struct STexSamplerRT -{ - union - { - CTexture* m_pTex; - ITexture* m_pITex; - }; - - union - { - struct SHRenderTarget* m_pTarget; - IRenderTarget* m_pITarget; - }; - - union - { - CTexAnim* m_pAnimInfo; - ITexAnim* m_pIAnimInfo; - }; - - uint32 m_nTexFlags; - int16 m_nTexState; - - uint8 m_eTexType; // ETEX_Type e.g. eTT_2D or eTT_Cube - int8 m_nSamplerSlot; - int8 m_nTextureSlot; - - bool m_bGlobal; - - STexSamplerRT() - { - m_nTexState = -1; - m_pTex = NULL; - m_eTexType = eTT_2D; - m_nTexFlags = 0; - m_pTarget = NULL; - m_pAnimInfo = NULL; - m_nSamplerSlot = -1; - m_nTextureSlot = -1; - m_bGlobal = false; - } - ~STexSamplerRT() - { - Cleanup(); - } - - void Cleanup() - { - SAFE_RELEASE(m_pITex); - // TODO: ref counted deleting of m_pAnimInfo & m_pTarget! - CW - SAFE_RELEASE(m_pITarget); - SAFE_RELEASE(m_pIAnimInfo); - } - int Size() const - { - int nSize = sizeof(*this); - return nSize; - } - - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const - { - } - - uint32 GetTexFlags() const { return m_nTexFlags; } - void Update(); - void PostLoad(); - - NO_INLINE STexSamplerRT (const STexSamplerRT& src) - { - m_pITex = src.m_pITex; - if (m_pITex) - { - m_pITex->AddRef(); - } - m_pITarget = src.m_pITarget; - if (m_pITarget) - { - m_pITarget->AddRef(); - } - m_pIAnimInfo = src.m_pIAnimInfo; - if (m_pIAnimInfo) - { - m_pIAnimInfo->AddRef(); - } - m_eTexType = src.m_eTexType; - m_nTexFlags = src.m_nTexFlags; - m_nTexState = src.m_nTexState; - m_nSamplerSlot = src.m_nSamplerSlot; - m_nTextureSlot = src.m_nTextureSlot; - m_bGlobal = src.m_bGlobal; - } - NO_INLINE STexSamplerRT& operator = (const STexSamplerRT& src) - { - this->~STexSamplerRT(); - new(this)STexSamplerRT(src); - return *this; - } - STexSamplerRT (const STexSamplerFX& src) - { - m_pITex = NULL; - m_pAnimInfo = NULL; - m_pITarget = src.m_pITarget; - if (m_pITarget) - { - m_pITarget->AddRef(); - } - m_eTexType = src.m_eTexType; - m_nTexFlags = src.m_nTexFlags; - m_nTexState = src.m_nTexState; - m_nSamplerSlot = -1; - m_nTextureSlot = -1; - m_bGlobal = (src.m_nTexFlags & FT_FROMIMAGE) != 0; - } - inline bool operator != (const STexSamplerRT& m) const - { - if (m_pTex != m.m_pTex || m_eTexType != m.m_eTexType || m_nTexFlags != m.m_nTexFlags || m_nTexState != m.m_nTexState) - { - return true; - } - return false; - } -}; - -//============================================================================== -//------------------------------------------------------------------------------ -struct SEfResTextureExt -{ - int32 m_nFrameUpdated; - int32 m_nUpdateFlags; - int32 m_nLastRecursionLevel; - SEfTexModificator* m_pTexModifier; - - SEfResTextureExt () - { - m_nFrameUpdated = -1; - m_nUpdateFlags = 0; - m_nLastRecursionLevel = 0; - m_pTexModifier = nullptr; - } - ~SEfResTextureExt () - { - Cleanup(); - } - void Cleanup() - { - SAFE_DELETE(m_pTexModifier); - } - inline bool operator != (const SEfResTextureExt& m) const - { - if (m_pTexModifier && m.m_pTexModifier) - { - return *m_pTexModifier != *m.m_pTexModifier; - } - if (!m_pTexModifier && !m.m_pTexModifier) - { - return false; - } - return true; - } - SEfResTextureExt(const SEfResTextureExt& src) - { - if (&src != this) - { - Cleanup(); - if (src.m_pTexModifier) - { - m_pTexModifier = new SEfTexModificator; - * m_pTexModifier = *src.m_pTexModifier; - } - m_nFrameUpdated = -1; - m_nUpdateFlags = src.m_nUpdateFlags; - m_nLastRecursionLevel = -1; - } - } - SEfResTextureExt& operator = (const SEfResTextureExt& src) - { - if (&src != this) - { - Cleanup(); - new(this)SEfResTextureExt(src); - } - return *this; - } - - void CopyTo(SEfResTextureExt* pTo) const - { - if (pTo && pTo != this) - { - pTo->Cleanup(); - pTo->m_nFrameUpdated = -1; - pTo->m_nUpdateFlags = m_nUpdateFlags; - pTo->m_nLastRecursionLevel = -1; - pTo->m_pTexModifier = nullptr; - if (m_pTexModifier) - { - pTo->m_pTexModifier = new SEfTexModificator; - *(pTo->m_pTexModifier) = *m_pTexModifier; - } - } - } - inline int Size() const - { - int nSize = sizeof(SEfResTextureExt); - if (m_pTexModifier) - { - nSize += m_pTexModifier->Size(); - } - return nSize; - } -}; - -//============================================================================== -// SEfResTexture - holds the actual data representing a texture and its associated -// sampler and modulator properties. -//------------------------------------------------------------------------------ -struct SEfResTexture -{ - string m_Name; - bool m_bUTile; - bool m_bVTile; - signed char m_Filter; - - STexSamplerRT m_Sampler; - SEfResTextureExt m_Ext; - - void UpdateForCreate(int nTSlot); - void Update(int nTSlot); - void UpdateWithModifier(int nTSlot); - - inline bool operator != (const SEfResTexture& m) const - { - if (_stricmp(m_Name.c_str(), m.m_Name.c_str()) != 0 || - m_bUTile != m.m_bUTile || - m_bVTile != m.m_bVTile || - m_Filter != m.m_Filter || - m_Ext != m.m_Ext || - m_Sampler != m.m_Sampler) - { - return true; - } - return false; - } - - inline bool IsHasModificators() const - { - return (m_Ext.m_pTexModifier != NULL); - } - - //! Find out if the texture has modulator and if it requires per frame computation change - bool IsNeedTexTransform() const - { - if (!m_Ext.m_pTexModifier) - { - return false; - } - if (m_Ext.m_pTexModifier->m_eRotType != ETMR_NoChange || m_Ext.m_pTexModifier->m_eMoveType[0] != ETMM_NoChange || m_Ext.m_pTexModifier->m_eMoveType[1] != ETMM_NoChange) - { - return true; - } - return false; - } - - bool IsNeedTexGen() const - { - if (!m_Ext.m_pTexModifier) - { - return false; - } - if (m_Ext.m_pTexModifier->m_eTGType != ETG_Stream) - { - return true; - } - return false; - } - - inline float GetTiling(int n) const - { - if (!m_Ext.m_pTexModifier) - { - return 1.0f; - } - return m_Ext.m_pTexModifier->m_Tiling[n]; - } - - inline float GetOffset(int n) const - { - if (!m_Ext.m_pTexModifier) - { - return 0; - } - return m_Ext.m_pTexModifier->m_Offs[n]; - } - - inline SEfTexModificator* AddModificator() - { - if (!m_Ext.m_pTexModifier) - { - m_Ext.m_pTexModifier = new SEfTexModificator; - } - return m_Ext.m_pTexModifier; - } - - inline SEfTexModificator* GetModificator() const - { - if (!m_Ext.m_pTexModifier) - { - static SEfTexModificator dummy; - dummy.Reset(); - return &dummy; - } - - return m_Ext.m_pTexModifier; - } - - int Size() const - { - int nSize = sizeof(SEfResTexture) - sizeof(STexSamplerRT) - sizeof(SEfResTextureExt); - nSize += m_Name.size(); - nSize += m_Sampler.Size(); - nSize += m_Ext.Size(); - - return nSize; - } - - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->Add(*this); - pSizer->AddObject(m_Name); - pSizer->AddObject(m_Sampler); - } - - void Cleanup() - { - m_Sampler.Cleanup(); - m_Ext.Cleanup(); - } - - ~SEfResTexture() - { - Cleanup(); - } - - void Reset() - { - m_bUTile = true; - m_bVTile = true; - m_Filter = FILTER_NONE; - SAFE_DELETE(m_Ext.m_pTexModifier); - m_Ext.m_nFrameUpdated = -1; - } - - SEfResTexture (const SEfResTexture& src) - { - if (&src != this) - { - Cleanup(); - m_Sampler = src.m_Sampler; - m_Ext = src.m_Ext; - m_Name = src.m_Name; - m_bUTile = src.m_bUTile; - m_bVTile = src.m_bVTile; - m_Filter = src.m_Filter; - } - } - - SEfResTexture& operator = (const SEfResTexture& src) - { - if (&src != this) - { - Cleanup(); - new(this)SEfResTexture(src); - } - return *this; - } - void CopyTo(SEfResTexture* pTo) const - { - if (pTo && (pTo != this)) - { - pTo->Cleanup(); - pTo->m_Sampler = m_Sampler; - m_Ext.CopyTo(&pTo->m_Ext); - pTo->m_Name = m_Name; - pTo->m_bUTile = m_bUTile; - pTo->m_bVTile = m_bVTile; - pTo->m_Filter = m_Filter; - } - } - - SEfResTexture() - { - Reset(); - } -}; - -//============================================================================== -//------------------------------------------------------------------------------ -struct SBaseShaderResources -{ - AZStd::vector<SShaderParam> m_ShaderParams; - string m_TexturePath; - const char* m_szMaterialName; - - float m_AlphaRef; - uint32 m_ResFlags; - - uint16 m_SortPrio; - - uint8 m_VoxelCoverage; - - int Size() const - { - int nSize = sizeof(SBaseShaderResources) + m_ShaderParams.size() * sizeof(SShaderParam); - return nSize; - } - - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(m_ShaderParams); - } - - SBaseShaderResources& operator=(const SBaseShaderResources& src) - { - if (&src != this) - { - ReleaseParams(); - m_szMaterialName = src.m_szMaterialName; - m_ResFlags = src.m_ResFlags; - m_AlphaRef = src.m_AlphaRef; - m_VoxelCoverage = src.m_VoxelCoverage; - m_SortPrio = src.m_SortPrio; - m_ShaderParams = src.m_ShaderParams; - } - return *this; - } - - SBaseShaderResources() - { - m_ResFlags = 0; - m_AlphaRef = 0; - m_VoxelCoverage = 255; - m_SortPrio = 0; - m_szMaterialName = NULL; - } - - void ReleaseParams() - { - m_ShaderParams.clear(); - } - - virtual ~SBaseShaderResources() - { - ReleaseParams(); - } -}; - -//------------------------------------------------------------------------------ -typedef uint16 ResourceSlotIndex; -typedef AZStd::unordered_map<ResourceSlotIndex, SEfResTexture> TexturesResourcesMap; -typedef AZStd::unordered_map<ResourceSlotIndex, SShaderTextureSlot*> TexturesSlotsUsageMap; -//------------------------------------------------------------------------------ - -struct IRenderShaderResources -{ - // <interfuscator:shuffle> - virtual void AddRef() = 0; - virtual void UpdateConstants(IShader* pSH) = 0; - virtual void CloneConstants(const IRenderShaderResources* pSrc) = 0; - virtual bool HasLMConstants() const = 0; - - // properties - virtual void ToInputLM(CInputLightMaterial& lm) = 0; - virtual void SetInputLM(const CInputLightMaterial& lm) = 0; - - virtual ColorF GetColorValue(EEfResTextures slot) const = 0; - virtual void SetColorValue(EEfResTextures slot, const ColorF& color) = 0; - - virtual float GetStrengthValue(EEfResTextures slot) const = 0; - virtual void SetStrengthValue(EEfResTextures slot, float value) = 0; - - // configs - virtual const float& GetAlphaRef() const = 0; - virtual void SetAlphaRef(float v) = 0; - - virtual int GetResFlags() = 0; - virtual void SetMtlLayerNoDrawFlags(uint8 nFlags) = 0; - virtual uint8 GetMtlLayerNoDrawFlags() const = 0; - virtual SSkyInfo* GetSkyInfo() = 0; - virtual void SetMaterialName(const char* szName) = 0; - - virtual bool TextureSlotExists(ResourceSlotIndex slotId) const = 0; - virtual SEfResTexture* GetTextureResource(ResourceSlotIndex slotId) = 0; - virtual TexturesResourcesMap* GetTexturesResourceMap() = 0; - virtual AZStd::vector<SShaderParam>& GetParameters() = 0; - - virtual ColorF GetFinalEmittance() = 0; - virtual float GetVoxelCoverage() = 0; - - virtual ~IRenderShaderResources() {} - virtual void Release() = 0; - virtual void ConvertToInputResource(struct SInputShaderResources* pDst) = 0; - virtual IRenderShaderResources* Clone() const = 0; - virtual void SetShaderParams(struct SInputShaderResources* pDst, IShader* pSH) = 0; - - virtual size_t GetResourceMemoryUsage(ICrySizer* pSizer) = 0; - - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - // </interfuscator:shuffle> - - inline bool IsEmissive() const - { - // worst: *reinterpret_cast<int32*>(&) > 0x00000000 - // causes value to pass from FPU to CPU registers - return GetStrengthValue(EFTT_EMITTANCE) > 0.0f; - } - inline bool IsTransparent() const - { - // worst: *reinterpret_cast<int32*>(&) < 0x3f800000 - // causes value to pass from FPU to CPU registers - return GetStrengthValue(EFTT_OPACITY) < 1.0f; - } - inline bool IsAlphaTested() const - { - return GetAlphaRef() > 0.0f; - } - inline bool IsInvisible() const - { - const float o = GetStrengthValue(EFTT_OPACITY); - const float a = GetAlphaRef(); - - return o == 0.0f || a == 1.0f || o <= a; - } -}; - - -struct SInputShaderResources - : public SBaseShaderResources -{ - CInputLightMaterial m_LMaterial; - TexturesResourcesMap m_TexturesResourcesMap; // a map of all textures resources used by the shader by name - SDeformInfo m_DeformInfo; - - int Size() const - { - int nSize = SBaseShaderResources::Size();// -sizeof(SEfResTexture) * m_TexturesResourcesMap.size(); - nSize += m_TexturePath.size(); - nSize += sizeof(SDeformInfo); - - for (auto& iter : m_TexturesResourcesMap) - { - nSize += iter.second.Size(); - } - return nSize; - } - - SInputShaderResources& operator=(const SInputShaderResources& src) - { - if (&src != this) - { - Cleanup(); // this will also remove all texture slots - SBaseShaderResources::operator = (src); - m_TexturePath = src.m_TexturePath; - m_DeformInfo = src.m_DeformInfo; - m_TexturesResourcesMap = src.m_TexturesResourcesMap; - m_LMaterial = src.m_LMaterial; - } - return *this; - } - - SInputShaderResources() {} - SInputShaderResources(struct IRenderShaderResources* pSrc) - { - pSrc->ConvertToInputResource(this); - m_ShaderParams = pSrc->GetParameters(); - } - - void Cleanup() - { - m_TexturesResourcesMap.clear(); - } - - virtual ~SInputShaderResources() - { - Cleanup(); - } - - bool IsEmpty(ResourceSlotIndex nTSlot) const - { - auto iter = m_TexturesResourcesMap.find(nTSlot); - return (iter != m_TexturesResourcesMap.end()) ? iter->second.m_Name.empty() : true; - } - - SEfResTexture* GetTextureResource(ResourceSlotIndex slotId) - { - auto iter = m_TexturesResourcesMap.find(slotId); - return (iter != m_TexturesResourcesMap.end()) ? &iter->second : nullptr; - } - - inline TexturesResourcesMap* GetTexturesResourceMap() - { - return &m_TexturesResourcesMap; - } -}; - -//=================================================================================== -// Shader gen structure (used for automatic shader script generating). - -// -#define SHGF_HIDDEN 1 -#define SHGF_PRECACHE 2 -#define SHGF_AUTO_PRECACHE 4 -#define SHGF_LOWSPEC_AUTO_PRECACHE 8 -#define SHGF_RUNTIME 0x10 - -#define SHGD_LM_DIFFUSE 0x1 -#define SHGD_TEX_DETAIL 0x2 -#define SHGD_TEX_NORMALS 0x4 -#define SHGD_TEX_ENVCM 0x8 -#define SHGD_TEX_SPECULAR 0x10 -#define SHGD_TEX_SECOND_SMOOTHNESS 0x20 -#define SHGD_TEX_HEIGHT 0x40 -#define SHGD_TEX_SUBSURFACE 0x80 -#define SHGD_HW_BILINEARFP16 0x100 -#define SHGD_HW_SEPARATEFP16 0x200 -#define SHGD_HW_ORBIS 0x800 -#define SHGD_TEX_CUSTOM 0x1000 -#define SHGD_TEX_CUSTOM_SECONDARY 0x2000 -#define SHGD_TEX_DECAL 0x4000 -#define SHGD_TEX_OCC 0x8000 -#define SHGD_TEX_SPECULAR_2 0x10000 -#define SHGD_HW_GLES3 0x20000 -#define SHGD_USER_ENABLED 0x40000 -#define SHGD_HW_SAA 0x80000 -#define SHGD_TEX_EMITTANCE 0x100000 -#define SHGD_HW_DX10 0x200000 -#define SHGD_HW_DX11 0x400000 -#define SHGD_HW_GL4 0x800000 -#define SHGD_HW_WATER_TESSELLATION 0x1000000 -#define SHGD_HW_SILHOUETTE_POM 0x2000000 -// Confetti Nicholas Baldwin: adding metal shader language support -#define SHGD_HW_METAL 0x4000000 -#define SHGD_TEX_MASK ( SHGD_TEX_DETAIL | SHGD_TEX_NORMALS | SHGD_TEX_ENVCM | SHGD_TEX_SPECULAR | SHGD_TEX_SECOND_SMOOTHNESS | \ - SHGD_TEX_HEIGHT | SHGD_TEX_SUBSURFACE | SHGD_TEX_CUSTOM | SHGD_TEX_CUSTOM_SECONDARY | SHGD_TEX_DECAL | \ - SHGD_TEX_OCC | SHGD_TEX_SPECULAR_2 | SHGD_TEX_EMITTANCE) - - -//------------------------------------------------------------------------------ -// Texture slot descriptor for shader -//------------------------------------------------------------------------------ -struct SShaderTextureSlot -{ - SShaderTextureSlot() - { - m_TexType = eTT_MaxTexType; - } - - string m_Name; - string m_Description; - byte m_TexType; // 2D, 3D, Cube etc.. - - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(m_Name); - pSizer->AddObject(m_Description); - pSizer->AddObject(m_TexType); - } -}; - -//------------------------------------------------------------------------------ -// Shader's used texture slots -//------------------------------------------------------------------------------ -/* [Shader System] - To Do: bring that back to life after testing -struct SShaderTexSlots -{ - uint32 m_nRefCount; - TexturesSlotsUsageMap m_UsedTextureSlots; - - SShaderTexSlots() - { - m_nRefCount = 1; - } - - ~SShaderTexSlots() - { - for (auto& iter : m_UsedTextureSlots ) - { - SAFE_DELETE( iter.second ); - } - m_UsedTextureSlots.clear(); - } - void Release() - { - m_nRefCount--; - if (!m_nRefCount) - { - delete this; - } - } - - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(m_UsedTextureSlots); - } - - SShaderTextureSlot* GetUsedTextureSlot(uint16 slotId) - { - auto iter = m_UsedTextureSlots.find(slotId); - return (iter != m_UsedTextureSlots.end()) ? iter->second : nullptr; - } -}; -*/ - -// [Shader System] - To Do: replace this with the code above after testing -struct SShaderTexSlots -{ - uint32 m_nRefCount; - SShaderTextureSlot* m_UsedTextureSlots[EFTT_MAX]; - SShaderTexSlots() - { - m_nRefCount = 1; - memset(m_UsedTextureSlots, 0, sizeof(m_UsedTextureSlots)); - } - ~SShaderTexSlots() - { - uint32 i; - for (i = 0; i < EFTT_MAX; i++) - { - SShaderTextureSlot* pSlot = m_UsedTextureSlots[i]; - SAFE_DELETE(pSlot); - } - } - void Release() - { - m_nRefCount--; - if (!m_nRefCount) - { - delete this; - } - } - - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(m_UsedTextureSlots); - } -}; - -//=================================================================================== - -enum EShaderType -{ - eST_All = -1, // To set all with one call. - - eST_General = 0, - eST_Metal, - eST_Glass, - eST_Ice, - eST_Shadow, - eST_Water, - eST_FX, - eST_PostProcess, - eST_HDR, - eST_Sky, - eST_Compute, - eST_Max // To define array size. -}; - -enum EShaderDrawType -{ - eSHDT_General, - eSHDT_Light, - eSHDT_Shadow, - eSHDT_Terrain, - eSHDT_Overlay, - eSHDT_OceanShore, - eSHDT_Fur, - eSHDT_NoDraw, - eSHDT_CustomDraw, - eSHDT_Sky, - eSHDT_Volume -}; - -enum EShaderQuality -{ - eSQ_Low = 0, - eSQ_Medium = 1, - eSQ_High = 2, - eSQ_VeryHigh = 3, - eSQ_Max = 4 -}; - -enum ERenderQuality -{ - eRQ_Low = 0, - eRQ_Medium = 1, - eRQ_High = 2, - eRQ_VeryHigh = 3, - eRQ_Max = 4 -}; - -// Summary: -// Shader profile flags . -#define SPF_LOADNORMALALPHA 0x1 - -struct SShaderProfile -{ - SShaderProfile() - : m_iShaderProfileQuality(eSQ_High) - , m_nShaderProfileFlags(SPF_LOADNORMALALPHA) - { - } - - EShaderQuality GetShaderQuality() const - { - return (EShaderQuality)CLAMP(m_iShaderProfileQuality, 0, eSQ_VeryHigh); - } - - void SetShaderQuality(const EShaderQuality& rValue) - { - m_iShaderProfileQuality = (int)rValue; - } - - // ---------------------------------------------------------------- - - int m_iShaderProfileQuality; // EShaderQuality e.g. eSQ_Medium, use Get/Set functions if possible - uint32 m_nShaderProfileFlags; // SPF_... -}; - -//==================================================================================== -// Phys. material flags - -#define MATF_NOCLIP 1 - -//==================================================================================== -// Registered shader techniques ID's - -enum EShaderTechniqueID -{ - TTYPE_GENERAL = -1, - TTYPE_Z = 0, - TTYPE_SHADOWGEN, - TTYPE_GLOWPASS, - TTYPE_MOTIONBLURPASS, - TTYPE_CUSTOMRENDERPASS, - TTYPE_EFFECTLAYER, - TTYPE_SOFTALPHATESTPASS, - TTYPE_WATERREFLPASS, - TTYPE_WATERCAUSTICPASS, - TTYPE_ZPREPASS, - TTYPE_PARTICLESTHICKNESSPASS, - - // PC specific techniques must go after this point, to support shader serializing - // TTYPE_CONSOLE_MAX must equal TTYPE_MAX for console - TTYPE_CONSOLE_MAX, - TTYPE_DEBUG = TTYPE_CONSOLE_MAX, - - TTYPE_MAX -}; - -//==================================================================================== - -// EFSLIST_ lists -// Note - declaration order/index value has no explicit meaning. - -enum ERenderListID -{ - EFSLIST_INVALID = 0, // Don't use, internally used. - EFSLIST_PREPROCESS, // Pre-process items. - EFSLIST_GENERAL, // Opaque ambient_light+shadow passes. - EFSLIST_SHADOW_GEN, // Shadow map generation. - EFSLIST_DECAL, // Opaque or transparent decals. - EFSLIST_WATER_VOLUMES, // After decals. - EFSLIST_TRANSP, // Sorted by distance under-water render items. - EFSLIST_WATER, // Water-ocean render items. - EFSLIST_HDRPOSTPROCESS, // Hdr post-processing screen effects. - EFSLIST_AFTER_HDRPOSTPROCESS, // After hdr post-processing screen effects. - EFSLIST_POSTPROCESS, // Post-processing screen effects. - EFSLIST_AFTER_POSTPROCESS, // After post-processing screen effects. - EFSLIST_SHADOW_PASS, // Shadow mask generation (usually from from shadow maps). - EFSLIST_DEFERRED_PREPROCESS, // Pre-process before deferred passes. - EFSLIST_SKIN, // Skin rendering pre-process - EFSLIST_HALFRES_PARTICLES, // Half resolution particles - EFSLIST_PARTICLES_THICKNESS, // Particles thickness passes - EFSLIST_LENSOPTICS, // Lens-optics processing - EFSLIST_VOXELIZE, // Mesh voxelization - EFSLIST_EYE_OVERLAY, // Eye overlay layer requires special processing - EFSLIST_FOG_VOLUME, // Fog density injection passes. - EFSLIST_GPU_PARTICLE_CUBEMAP_COLLISION, // Cubemaps for GPU particle cubemap depth collision - EFSLIST_REFRACTIVE_SURFACE, // After decals, used for instance for the water surface that comes with water volumes. - - EFSLIST_NUM -}; - -//================================================================ -// Different preprocess flags for shaders that require preprocessing (like recursive render to texture, screen effects, visibility check, ...) -// SShader->m_nPreprocess flags in priority order - -#define SPRID_FIRST 25 -#define SPRID_SCANTEXWATER 26 -#define FSPR_SCANTEXWATER (1 << SPRID_SCANTEXWATER) -#define SPRID_SCANTEX 27 -#define FSPR_SCANTEX (1 << SPRID_SCANTEX) -#define SPRID_SCANLCM 28 -#define FSPR_SCANLCM (1 << SPRID_SCANLCM) -#define SPRID_GENSPRITES_DEPRECATED 29 -#define FSPR_GENSPRITES_DEPRECATED (1 << SPRID_GENSPRITES_DEPRECATED) -#define SPRID_CUSTOMTEXTURE 30 -#define FSPR_CUSTOMTEXTURE (1 << SPRID_CUSTOMTEXTURE) -#define SPRID_GENCLOUDS 31 -#define FSPR_GENCLOUDS (1 << SPRID_GENCLOUDS) - -#define FSPR_MASK 0xfff00000 -#define FSPR_MAX (1 << 31) - -#define FEF_DONTSETTEXTURES 1 // Set: explicit setting of samplers (e.g. tex->Apply(1,nTexStatePoint)), not set: set sampler by sematics (e.g. $ZTarget). -#define FEF_DONTSETSTATES 2 - -// SShader::m_Flags -// Different useful flags -#define EF_RELOAD 1 // Shader needs tangent vectors array. -#define EF_FORCE_RELOAD 2 -#define EF_RELOADED 4 -#define EF_NODRAW 8 -#define EF_HASCULL 0x10 -#define EF_SUPPORTSDEFERREDSHADING_MIXED 0x20 -#define EF_SUPPORTSDEFERREDSHADING_FULL 0x40 -#define EF_SUPPORTSDEFERREDSHADING (EF_SUPPORTSDEFERREDSHADING_MIXED | EF_SUPPORTSDEFERREDSHADING_FULL) -#define EF_DECAL 0x80 -#define EF_LOADED 0x100 -#define EF_LOCALCONSTANTS 0x200 -#define EF_BUILD_TREE 0x400 -#define EF_LIGHTSTYLE 0x800 -#define EF_NOCHUNKMERGING 0x1000 -#define EF_SUNFLARES 0x2000 -#define EF_NEEDNORMALS 0x4000 // Need normals operations. -#define EF_OFFSETBUMP 0x8000 -#define EF_NOTFOUND 0x10000 -#define EF_DEFAULT 0x20000 -#define EF_SKY 0x40000 -#define EF_USELIGHTS 0x80000 -#define EF_ALLOW3DC 0x100000 -#define EF_FOGSHADER 0x200000 -#define EF_FAILED_IMPORT 0x400000 // Currently just for debug, can be removed if necessary -#define EF_PRECACHESHADER 0x800000 -#define EF_FORCEREFRACTIONUPDATE 0x1000000 -#define EF_SUPPORTSINSTANCING_CONST 0x2000000 -#define EF_SUPPORTSINSTANCING_ATTR 0x4000000 -#define EF_SUPPORTSINSTANCING (EF_SUPPORTSINSTANCING_CONST | EF_SUPPORTSINSTANCING_ATTR) -#define EF_WATERPARTICLE 0x8000000 -#define EF_CLIENTEFFECT 0x10000000 -#define EF_SYSTEM 0x20000000 -#define EF_REFRACTIVE 0x40000000 -#define EF_NOPREVIEW 0x80000000 - -#define EF_PARSE_MASK (EF_SUPPORTSINSTANCING | EF_SKY | EF_HASCULL | EF_USELIGHTS | EF_REFRACTIVE) - - -// SShader::Flags2 -// Additional Different useful flags - -#define EF2_PREPR_GENSPRITES_DEPRECATED 0x1 -#define EF2_PREPR_GENCLOUDS 0x2 -#define EF2_PREPR_SCANWATER 0x4 -#define EF2_NOCASTSHADOWS 0x8 -#define EF2_NODRAW 0x10 -#define EF2_HASOPAQUE 0x40 -#define EF2_AFTERHDRPOSTPROCESS 0x80 -#define EF2_DONTSORTBYDIST 0x100 -#define EF2_FORCE_WATERPASS 0x200 -#define EF2_FORCE_GENERALPASS 0x400 -#define EF2_AFTERPOSTPROCESS 0x800 -#define EF2_IGNORERESOURCESTATES 0x1000 -#define EF2_EYE_OVERLAY 0x2000 -#define EF2_FORCE_TRANSPASS 0x4000 -#define EF2_DEFAULTVERTEXFORMAT 0x8000 -#define EF2_FORCE_ZPASS 0x10000 -#define EF2_FORCE_DRAWLAST 0x20000 -#define EF2_FORCE_DRAWAFTERWATER 0x40000 -// free 0x80000 -#define EF2_DEPTH_FIXUP 0x100000 -#define EF2_SINGLELIGHTPASS 0x200000 -#define EF2_FORCE_DRAWFIRST 0x400000 -#define EF2_HAIR 0x800000 -#define EF2_DETAILBUMPMAPPING 0x1000000 -#define EF2_HASALPHATEST 0x2000000 -#define EF2_HASALPHABLEND 0x4000000 -#define EF2_ZPREPASS 0x8000000 -#define EF2_VERTEXCOLORS 0x10000000 -#define EF2_SKINPASS 0x20000000 -#define EF2_HW_TESSELLATION 0x40000000 -#define EF2_ALPHABLENDSHADOWS 0x80000000 - -class CCryNameR; -class CCryNameTSCRC; -struct IShader -{ -public: - // <interfuscator:shuffle> - virtual ~IShader(){} - virtual int GetID() = 0; - virtual int AddRef() = 0; - virtual int Release() = 0; - virtual int ReleaseForce() = 0; - - virtual const char* GetName() = 0; - virtual const char* GetName() const = 0; - virtual int GetFlags() const = 0; - virtual int GetFlags2() const = 0; - virtual void SetFlags2(int Flags) = 0; - virtual void ClearFlags2(int Flags) = 0; - virtual bool Reload(int nFlags, const char* szShaderName) = 0; - virtual AZStd::vector<SShaderParam>& GetPublicParams() = 0; - virtual int GetTexId () = 0; - virtual ITexture* GetBaseTexture(int* nPass, int* nTU) = 0; - virtual unsigned int GetUsedTextureTypes(void) = 0; - virtual SShaderTexSlots* GetUsedTextureSlots(int nTechnique) = 0; - virtual ECull GetCull(void) = 0; - virtual int Size(int Flags) = 0; - virtual uint64 GetGenerationMask() = 0; - virtual size_t GetNumberOfUVSets() = 0; - virtual int GetTechniqueID(int nTechnique, int nRegisteredTechnique) = 0; - virtual AZ::Vertex::Format GetVertexFormat(void) = 0; - - // D3D Effects interface - virtual bool FXSetTechnique(const CCryNameTSCRC& Name) = 0; - virtual bool FXSetPSFloat(const CCryNameR& NameParam, const Vec4 fParams[], int nParams) = 0; - virtual bool FXSetCSFloat(const CCryNameR& NameParam, const Vec4 fParams[], int nParams) = 0; - virtual bool FXSetVSFloat(const CCryNameR& NameParam, const Vec4 fParams[], int nParams) = 0; - virtual bool FXSetGSFloat(const CCryNameR& NameParam, const Vec4 fParams[], int nParams) = 0; - - virtual bool FXSetPSFloat(const char* NameParam, const Vec4 fParams[], int nParams) = 0; - virtual bool FXSetCSFloat(const char* NameParam, const Vec4 fParams[], int nParams) = 0; - virtual bool FXSetVSFloat(const char* NameParam, const Vec4 fParams[], int nParams) = 0; - virtual bool FXSetGSFloat(const char* NameParam, const Vec4 fParams[], int nParams) = 0; - - virtual bool FXBegin(uint32* uiPassCount, uint32 nFlags) = 0; - virtual bool FXBeginPass(uint32 uiPass) = 0; - virtual bool FXCommit(const uint32 nFlags) = 0; - virtual bool FXEndPass() = 0; - virtual bool FXEnd() = 0; - - virtual EShaderType GetShaderType() = 0; - virtual EShaderDrawType GetShaderDrawType() const = 0; - virtual uint32 GetVertexModificator() = 0; - - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - // </interfuscator:shuffle> - - static uint32 GetTextureSlot(EEfResTextures textureType) { return (uint32)textureType; } -}; - -struct SShaderItem -{ - IShader* m_pShader; - IRenderShaderResources* m_pShaderResources; - int32 m_nTechnique; - uint32 m_nPreprocessFlags; - - SShaderItem() - { - m_pShader = NULL; - m_pShaderResources = NULL; - m_nTechnique = -1; - m_nPreprocessFlags = 1; - } - SShaderItem(IShader* pSH) - { - m_pShader = pSH; - m_pShaderResources = NULL; - m_nTechnique = -1; - m_nPreprocessFlags = 1; - } - SShaderItem(IShader* pSH, IRenderShaderResources* pRS) - { - m_pShader = pSH; - m_pShaderResources = pRS; - m_nTechnique = -1; - m_nPreprocessFlags = 1; - } - SShaderItem(IShader* pSH, IRenderShaderResources* pRS, int nTechnique) - { - m_pShader = pSH; - m_pShaderResources = pRS; - m_nTechnique = nTechnique; - m_nPreprocessFlags = 1; - } - - uint32 PostLoad(); - bool Update(); - bool RefreshResourceConstants(); - // Note: - // If you change this function please check bTransparent variable in CRenderMesh::Render(). - // See also: - // CRenderMesh::Render() - inline bool IsZWrite() const - { - IShader* pSH = m_pShader; - if (pSH->GetFlags() & (EF_NODRAW | EF_DECAL)) - { - return false; - } - if (pSH->GetFlags2() & EF2_FORCE_ZPASS) - { - return true; - } - if (m_pShaderResources && m_pShaderResources->IsTransparent()) - { - return false; - } - return true; - } - inline struct SShaderTechnique* GetTechnique() const; - bool IsMergable(SShaderItem& PrevSI); - - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(m_pShader); - pSizer->AddObject(m_pShaderResources); - } -}; - - -////////////////////////////////////////////////////////////////////// -// define before including <IRenderMesh.h> - -struct CRenderChunk -{ - bool m_bUsesBones; - CREMesh* pRE; // Pointer to the mesh. - - float m_texelAreaDensity; - - uint32 nFirstIndexId; - uint32 nNumIndices; - - uint32 nFirstVertId; - uint32 nNumVerts; - - uint16 m_nMatFlags; // Material flags from originally assigned material @see EMaterialFlags. - uint16 m_nMatID; // Material Sub-object id. - - // Index of sub-object that this chunk originates from, used by sub-object hide mask. - // @see IStatObj::GetSubObject - uint32 nSubObjectIndex; - - AZ::Vertex::Format m_vertexFormat; - - ////////////////////////////////////////////////////////////////////////// - CRenderChunk() - : m_bUsesBones(false) - , pRE(0) - , m_texelAreaDensity(1.0f) - , nFirstIndexId(0) - , nNumIndices(0) - , nFirstVertId(0) - , nNumVerts(0) - , m_nMatFlags(0) - , m_nMatID(0) - , nSubObjectIndex(0) - , m_vertexFormat(eVF_P3F_C4B_T2F) - { - } - - int Size() const; - - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const - { - } -}; - -typedef DynArray<CRenderChunk> TRenderChunkArray; - -////////////////////////////////////////////////////////////////////// -// DLights - -enum eDynamicLightFlags -{ - DLF_AREA_SPEC_TEX = BIT(0), - DLF_DIRECTIONAL = BIT(1), - DLF_BOX_PROJECTED_CM = BIT(2), - // BIT(3) DEPRECATED, Available for use - DLF_POST_3D_RENDERER = BIT(4), - DLF_CASTSHADOW_MAPS = BIT(5), - DLF_POINT = BIT(6), - DLF_PROJECT = BIT(7), - DLF_LIGHT_BEAM = BIT(8), - DLF_IGNORES_VISAREAS = BIT(10), - DLF_DEFERRED_CUBEMAPS = BIT(11), - DLF_HAS_CLIP_VOLUME = BIT(12), - DLF_DISABLED = BIT(13), - DLF_AREA_LIGHT = BIT(14), - DLF_USE_FOR_SVOGI = BIT(15), - // UNUSED = BIT(16), - DLF_FAKE = BIT(17), // No lighting, used for Flares, beams and such. - DLF_SUN = BIT(18), - DLF_LM = BIT(19), - DLF_THIS_AREA_ONLY = BIT(20), // Affects only current area/sector. - DLF_AMBIENT = BIT(21), // Ambient light (has name indicates, used for replacing ambient) - DLF_INDOOR_ONLY = BIT(22), // Do not affect height map. - DLF_VOLUMETRIC_FOG = BIT(23), // Affects volumetric fog. - DLF_ATTACH_TO_SUN = BIT(24), // Add only to Light Propagation Volume if it's possible. - DLF_TRACKVIEW_TIMESCRUBBING = BIT(25), // Add only to Light Propagation Volume if it's possible. - DLF_VOLUMETRIC_FOG_ONLY = BIT(26), // Affects only volumetric fog. - DLF_DEFERRED_LIGHT = BIT(27), // DEPRECATED. Remove once deferred shading by default - DLF_SPECULAROCCLUSION = BIT(28), // DEPRECATED. Remove all dependencies editor side, etc - DLF_DIFFUSEOCCLUSION = BIT(29), - DLF_CAST_TERRAIN_SHADOWS = BIT(30), // Include terrain in shadow casters - - DLF_LIGHTTYPE_MASK = (DLF_DIRECTIONAL | DLF_POINT | DLF_PROJECT | DLF_AREA_LIGHT) -}; - - -//Area light types -#define DLAT_SPHERE 0x1 -#define DLAT_RECTANGLE 0x2 -#define DLAT_POINT 0x4 - -#define DL_SHADOW_UPDATE_SHIFT 8 - -#include <IRenderMesh.h> // <> required for Interfuscator - -struct IAnimNode; - -struct ILightAnimWrapper - : public _i_reference_target_t -{ -public: - virtual bool Resolve() = 0; - IAnimNode* GetNode() const { return m_pNode; } - -protected: - ILightAnimWrapper(const char* name) - : m_name(name) - , m_pNode(0) {} - virtual ~ILightAnimWrapper() {} - -protected: - string m_name; - IAnimNode* m_pNode; -}; - -struct SOpticsInstanceParameters -{ - SOpticsInstanceParameters(float brightness = 0.0f, float size = 0.0f, const ColorF& color = ColorF(), bool valid = false) : - m_brightness(brightness), - m_size(size), m_color(color), - m_isValid(valid) {} - - float m_brightness; - float m_size; - ColorF m_color; - bool m_isValid; -}; - -#define MAX_RECURSION_LEVELS 2 - -struct SRenderLight -{ - SRenderLight() - { - memset(this, 0, sizeof(SRenderLight)); - m_fLightFrustumAngle = 45.0f; - m_fRadius = 4.0f; - m_fBaseRadius = 4.0f; - m_SpecMult = m_BaseSpecMult = 1.0f; - m_ProjMatrix.SetIdentity(); - m_ObjMatrix.SetIdentity(); - m_BaseObjMatrix.SetIdentity(); - m_sName = ""; - m_pLightAnim = NULL; - m_fAreaWidth = 1; - m_fAreaHeight = 1; - m_fBoxWidth = 1.0f; - m_fBoxHeight = 1.0f; - m_fBoxLength = 1.0f; - m_fTimeScrubbed = 0.0f; - - m_fShadowBias = 1.0f; - m_fShadowSlopeBias = 1.0f; - m_fShadowResolutionScale = 1.0f; - m_nShadowMinResolution = 0; - m_fShadowUpdateMinRadius = m_fRadius; - m_nShadowUpdateRatio = 1 << DL_SHADOW_UPDATE_SHIFT; - m_nEntityId = (uint32) - 1; - m_LensOpticsFrustumAngle = 255; - m_nAttenFalloffMax = 255; - m_fAttenuationBulbSize = 0.1f; - m_fProbeAttenuation = 1.0f; - m_lightId = -1; - } - - const Vec3& GetPosition() const - { - return m_Origin; - } - void SetPosition(const Vec3& vPos) - { - m_BaseOrigin = vPos; - m_Origin = vPos; - } - - // Summary: - // Use this instead of m_Color. - void SetLightColor(const ColorF& cColor) - { - m_Color = cColor; - m_BaseColor = cColor; - } - - ITexture* GetDiffuseCubemap() const - { - return m_pDiffuseCubemap; - } - - ITexture* GetSpecularCubemap() const - { - return m_pSpecularCubemap; - } - - ITexture* GetLightTexture() const - { - return m_pLightImage ? m_pLightImage : NULL; - } - - void SetOpticsParams(const SOpticsInstanceParameters& params) - { - m_opticsParams = params; - } - - const SOpticsInstanceParameters& GetOpticsParams() const - { - return m_opticsParams; - } - - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { /*LATER*/} - - void AcquireResources() - { - if (m_Shader.m_pShader) - { - m_Shader.m_pShader->AddRef(); - } - if (m_pLightImage) - { - m_pLightImage->AddRef(); - } - if (m_pDiffuseCubemap) - { - m_pDiffuseCubemap->AddRef(); - } - if (m_pSpecularCubemap) - { - m_pSpecularCubemap->AddRef(); - } - if (m_pLightAnim) - { - m_pLightAnim->AddRef(); - } - if (m_pLightAttenMap) - { - m_pLightAttenMap->AddRef(); - } - } - - void DropResources() - { - SAFE_RELEASE(m_Shader.m_pShader); - SAFE_RELEASE(m_pLightImage); - SAFE_RELEASE(m_pDiffuseCubemap); - SAFE_RELEASE(m_pSpecularCubemap); - SAFE_RELEASE(m_pLightAnim); - SAFE_RELEASE(m_pLightAttenMap); - } - - void SetAnimSpeed(float fAnimSpeed) - { - m_nAnimSpeed = aznumeric_caster(int_round(min(fAnimSpeed * 255.0f / 4.0f, 255.0f))); // Assuming speed multiplier in range [0, 4] - } - - float GetAnimSpeed() const - { - return ((float) m_nAnimSpeed) * (4.0f / 255.0f); - } - - void SetFalloffMax(float fMax) - { - m_nAttenFalloffMax = aznumeric_caster(int_round(fMax * 255.0f)); - } - - float GetFalloffMax() const - { - return ((float) m_nAttenFalloffMax) / 255.0f; - } - - // Calculate the scissor rectangle in screenspace that encompasses this light. These values are used to set - // the hardware scissor rect in order to clip the min/max 2d extents for the light. - // These values must be calculated and read on the render thread due to the VR tracking updates performed on the render thread. - void CalculateScissorRect(); - - //========================================================================================================================= - - // Commonly used on most code paths (64 bytes) - int16 m_Id; // Shader id - uint8 m_nStencilRef[2]; - uint32 m_n3DEngineUpdateFrameID; - uint32 m_nEntityId; // Unique entity id - uint32 m_Flags; // light flags (DLF_etc). - Vec3 m_Origin; // World space position - float m_fRadius; // xyz= Origin, w=Radius. (Do not change order) - ColorF m_Color; // w component unused - todo pack spec mul into alpha (post c3 - touches quite some code) - float m_SpecMult; // Specular multiplier - float m_fHDRDynamic; // <DEPRECATED> 0 to get the same results in HDR, <0 to get darker, >0 to get brighter. - int16 m_sX; // Scissor parameters (2d extent). - int16 m_sY; - int16 m_sWidth; - int16 m_sHeight; - int m_lightId; - - // Env. probes - ITexture* m_pDiffuseCubemap; // Very small cubemap texture to make a lookup for diffuse. - ITexture* m_pSpecularCubemap; // Cubemap texture to make a lookup for local specular. - Vec3 m_ProbeExtents; - float m_fBoxWidth; - float m_fBoxHeight; - float m_fBoxLength; - float m_fProbeAttenuation; // Can be used fade out distant probes, or to manually blend between multiple co-located probes - uint8 m_nAttenFalloffMax; - uint8 m_nSortPriority; - - // Shadow map fields - struct ILightSource* m_pOwner; - ShadowMapFrustum** m_pShadowMapFrustums; - float m_fShadowBias; - float m_fShadowSlopeBias; - float m_fShadowResolutionScale; - float m_fShadowUpdateMinRadius; - uint16 m_nShadowMinResolution; - uint16 m_nShadowUpdateRatio; - uint8 m_ShadowChanMask : 4; - uint8 m_ShadowMaskIndex : 4; - - // Projector - ITexture* m_pLightAttenMap; // User can specify custom light attenuation gradient - ITexture* m_pLightImage; - Matrix44 m_ProjMatrix; - Matrix34 m_ObjMatrix; - float m_fLightFrustumAngle; - float m_fProjectorNearPlane; - - // Misc fields. todo: put in cold data struct (post c3 - touches quite some code) - 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. - ILightAnimWrapper* m_pLightAnim; - - Matrix34 m_BaseObjMatrix; - float m_fTimeScrubbed; - Vec3 m_BaseOrigin; // World space position. - float m_fBaseRadius; // Base radius - ColorF m_BaseColor; // w component unused.. - float m_BaseSpecMult; - - float m_fAttenuationBulbSize; - - float m_fAreaWidth; - float m_fAreaHeight; - - float m_fFogRadialLobe; // The blend ratio of two radial lobe for volumetric fog. - - AZ::u8 m_nAnimSpeed; - AZ::u8 m_nLightStyle; - AZ::u8 m_nLightPhase; - AZ::u8 m_LensOpticsFrustumAngle; // from 0 to 255, The range will be adjusted from 0 to 360 when used. - - IClipVolume* m_pClipVolumes[2]; - - SOpticsInstanceParameters m_opticsParams; // Per instance optics parameters -}; - -////////////////////////////////////////////////////////////////////// -class CDLight - : public SRenderLight -{ -public: - CDLight() - : SRenderLight() - { - } - - ~CDLight() - { - DropResources(); - } - - // Summary: - // Good for debugging. - bool IsOk() const - { - for (int i = 0; i < 3; ++i) - { - if (m_Color[i] < 0 || m_Color[i] > 100.0f || _isnan(m_Color[i])) - { - return false; - } - if (m_BaseColor[i] < 0 || m_BaseColor[i] > 100.0f || _isnan(m_BaseColor[i])) - { - return false; - } - } - return true; - } - - CDLight(const CDLight& other) - { - operator=(other); - } - - CDLight& operator=(const CDLight& dl) - { - if (this == &dl) - { - return *this; - } - - DropResources(); - - m_pOwner = dl.m_pOwner; - memcpy(m_pObject, dl.m_pObject, sizeof(m_pObject)); - m_Shader = dl.m_Shader; - m_pShadowMapFrustums = dl.m_pShadowMapFrustums; - m_pDiffuseCubemap = dl.m_pDiffuseCubemap; - m_pSpecularCubemap = dl.m_pSpecularCubemap; - m_pLightImage = dl.m_pLightImage; - m_pLightAttenMap = dl.m_pLightAttenMap; - m_sName = dl.m_sName; - m_ProjMatrix = dl.m_ProjMatrix; - m_ObjMatrix = dl.m_ObjMatrix; - m_BaseObjMatrix = dl.m_BaseObjMatrix; - m_Color = dl.m_Color; - m_BaseColor = dl.m_BaseColor; - m_Origin = dl.m_Origin; - m_BaseOrigin = dl.m_BaseOrigin; - m_fRadius = dl.m_fRadius; - m_fBaseRadius = dl.m_fBaseRadius; - m_ProbeExtents = dl.m_ProbeExtents; - m_SpecMult = dl.m_SpecMult; - m_BaseSpecMult = dl.m_BaseSpecMult; - m_fShadowBias = dl.m_fShadowBias; - m_fShadowSlopeBias = dl.m_fShadowSlopeBias; - m_fShadowResolutionScale = dl.m_fShadowResolutionScale; - m_fHDRDynamic = dl.m_fHDRDynamic; - m_LensOpticsFrustumAngle = dl.m_LensOpticsFrustumAngle; - m_fLightFrustumAngle = dl.m_fLightFrustumAngle; - m_fProjectorNearPlane = dl.m_fProjectorNearPlane; - m_Flags = dl.m_Flags; - m_Id = dl.m_Id; - m_n3DEngineUpdateFrameID = dl.m_n3DEngineUpdateFrameID; - m_sX = dl.m_sX; - m_sY = dl.m_sY; - m_sWidth = dl.m_sWidth; - m_sHeight = dl.m_sHeight; - m_nLightStyle = dl.m_nLightStyle; - m_nLightPhase = dl.m_nLightPhase; - m_ShadowChanMask = dl.m_ShadowChanMask; - m_pLightAnim = dl.m_pLightAnim; - m_fAreaWidth = dl.m_fAreaWidth; - m_fAreaHeight = dl.m_fAreaHeight; - m_fBoxWidth = dl.m_fBoxWidth; - m_fBoxHeight = dl.m_fBoxHeight; - m_fBoxLength = dl.m_fBoxLength; - m_fTimeScrubbed = dl.m_fTimeScrubbed; - m_nShadowMinResolution = dl.m_nShadowMinResolution; - m_fShadowUpdateMinRadius = dl.m_fShadowUpdateMinRadius; - m_nShadowUpdateRatio = dl.m_nShadowUpdateRatio; - m_nAnimSpeed = dl.m_nAnimSpeed; - m_nSortPriority = dl.m_nSortPriority; - m_nAttenFalloffMax = dl.m_nAttenFalloffMax; - m_fProbeAttenuation = dl.m_fProbeAttenuation; - m_fAttenuationBulbSize = dl.m_fAttenuationBulbSize; - m_fFogRadialLobe = dl.m_fFogRadialLobe; - m_nEntityId = dl.m_nEntityId; - memcpy(m_nStencilRef, dl.m_nStencilRef, sizeof(m_nStencilRef)); - memcpy(m_pClipVolumes, dl.m_pClipVolumes, sizeof(m_pClipVolumes)); - m_opticsParams = dl.m_opticsParams; - AcquireResources(); - - return *this; - } - - // Summary: - // Use this instead of m_Color. - const ColorF& GetFinalColor([[maybe_unused]] const ColorF& cColor) const - { - return m_Color; - } - - // Summary: - // Use this instead of m_Color. - void SetSpecularMult(float fSpecMult) - { - m_SpecMult = fSpecMult; - m_BaseSpecMult = fSpecMult; - } - - void SetShadowBiasParams(float fShadowBias, float fShadowSlopeBias) - { - m_fShadowBias = fShadowBias; - m_fShadowSlopeBias = fShadowSlopeBias; - } - - // Summary: - // Use this instead of m_Color. - const float& GetSpecularMult() const - { - return m_SpecMult; - } - void SetMatrix(const Matrix34& Matrix, bool reset = true) - { - // Scale the cubemap to adjust the default 45 degree 1/2 angle fustrum to - // the desired angle (0 to 90 degrees). - float scaleFactor = tan_tpl((90.0f - m_fLightFrustumAngle) * gf_PI / 180.0f); - m_ProjMatrix = Matrix33(Matrix) * Matrix33::CreateScale(Vec3(1, scaleFactor, scaleFactor)); - Matrix44 transMat; - transMat.SetIdentity(); - transMat(3, 0) = -Matrix(0, 3); - transMat(3, 1) = -Matrix(1, 3); - transMat(3, 2) = -Matrix(2, 3); - m_ProjMatrix = transMat * m_ProjMatrix; - m_ObjMatrix = Matrix; - - // Remove any scale - m_ObjMatrix.GetColumn0().NormalizeSafe(Vec3_OneX); - m_ObjMatrix.GetColumn1().NormalizeSafe(Vec3_OneY); - m_ObjMatrix.GetColumn2().NormalizeSafe(Vec3_OneZ); - - if (reset) - { - m_BaseObjMatrix = m_ObjMatrix; - } - } - - void SetSpecularCubemap(ITexture* texture) - { - m_pSpecularCubemap = texture; - } - - void SetDiffuseCubemap(ITexture* texture) - { - m_pDiffuseCubemap = texture; - } - - void ReleaseCubemaps() - { - SAFE_RELEASE(m_pSpecularCubemap); - SAFE_RELEASE(m_pDiffuseCubemap); - } -}; - -#define DECAL_HAS_NORMAL_MAP (1 << 0) -#define DECAL_STATIC (1 << 1) -#define DECAL_HAS_SPECULAR_MAP (1 << 2) - -struct SDeferredDecal -{ - SDeferredDecal() - { - ZeroStruct(*this); - rectTexture.w = rectTexture.h = 1.f; - angleAttenuation = 1.0f; - } - - Matrix34 projMatrix; // defines where projection should be applied in the world - _smart_ptr<IMaterial> pMaterial; // decal material - float fAlpha; // transparency of decal, used mostly for distance fading - float fGrowAlphaRef; - float angleAttenuation; - RectF rectTexture; // subset of texture to render - uint32 nFlags; - uint8 nSortOrder; // user defined sort order -}; - -// Summary: -// Runtime shader flags for HW skinning. -enum EHWSkinningRuntimeFlags -{ - eHWS_MotionBlured = 0x04, - eHWS_Skinning_DQ_Linear = 0x08, // Convert dual-quaternions to matrices on the GPU - eHWS_Skinning_Matrix = 0x10, // Pass float3x4 skinning matrices directly to the GPU -}; - -// Enum of data types that can be used as bones on GPU for skinning -enum EBoneTypes -{ - eBoneType_DualQuat = 0, - eBoneType_Matrix, - eBoneType_Count, -}; - -// Summary: -// Shader graph support. -enum EGrBlockType -{ - eGrBlock_Unknown, - eGrBlock_VertexInput, - eGrBlock_VertexOutput, - eGrBlock_PixelInput, - eGrBlock_PixelOutput, - eGrBlock_Texture, - eGrBlock_Sampler, - eGrBlock_Function, - eGrBlock_Constant, -}; - -enum EGrBlockSamplerType -{ - eGrBlockSampler_Unknown, - eGrBlockSampler_2D, - eGrBlockSampler_3D, - eGrBlockSampler_Cube, - eGrBlockSampler_Bias2D, - eGrBlockSampler_BiasCube, -}; - -enum EGrNodeType -{ - eGrNode_Unknown, - eGrNode_Input, - eGrNode_Output, -}; - -enum EGrNodeFormat -{ - eGrNodeFormat_Unknown, - eGrNodeFormat_Float, - eGrNodeFormat_Vector, - eGrNodeFormat_Matrix, - eGrNodeFormat_Int, - eGrNodeFormat_Bool, - eGrNodeFormat_Texture2D, - eGrNodeFormat_Texture3D, - eGrNodeFormat_TextureCUBE, -}; - -enum EGrNodeIOSemantic -{ - eGrNodeIOSemantic_Unknown, - eGrNodeIOSemantic_Custom, - eGrNodeIOSemantic_VPos, - eGrNodeIOSemantic_Color0, - eGrNodeIOSemantic_Color1, - eGrNodeIOSemantic_Color2, - eGrNodeIOSemantic_Color3, - eGrNodeIOSemantic_Normal, - eGrNodeIOSemantic_TexCoord0, - eGrNodeIOSemantic_TexCoord1, - eGrNodeIOSemantic_TexCoord2, - eGrNodeIOSemantic_TexCoord3, - eGrNodeIOSemantic_TexCoord4, - eGrNodeIOSemantic_TexCoord5, - eGrNodeIOSemantic_TexCoord6, - eGrNodeIOSemantic_TexCoord7, - eGrNodeIOSemantic_Tangent, - eGrNodeIOSemantic_Binormal, -}; - -struct SShaderGraphFunction -{ - string m_Data; - string m_Name; - std::vector<string> inParams; - std::vector<string> outParams; - std::vector<string> szInTypes; - std::vector<string> szOutTypes; -}; - -struct SShaderGraphNode -{ - EGrNodeType m_eType; - EGrNodeFormat m_eFormat; - EGrNodeIOSemantic m_eSemantic; - string m_CustomSemantics; - string m_Name; - bool m_bEditable; - bool m_bWasAdded; - SShaderGraphFunction* m_pFunction; - AZStd::vector<SShaderParam> m_Properties; - - SShaderGraphNode() - { - m_eType = eGrNode_Unknown; - m_eFormat = eGrNodeFormat_Unknown; - m_eSemantic = eGrNodeIOSemantic_Unknown; - m_bEditable = false; - m_bWasAdded = false; - m_pFunction = NULL; - } - ~SShaderGraphNode(); -}; - - -typedef std::vector<SShaderGraphNode*> FXShaderGraphNodes; -typedef FXShaderGraphNodes::iterator FXShaderGraphNodeItor; - -struct SShaderGraphBlock -{ - EGrBlockType m_eType; - EGrBlockSamplerType m_eSamplerType; - string m_ClassName; - FXShaderGraphNodes m_Nodes; - - ~SShaderGraphBlock(); -}; - -typedef std::vector<SShaderGraphBlock*> FXShaderGraphBlocks; -typedef FXShaderGraphBlocks::iterator FXShaderGraphBlocksItor; - -#include <CryCommon/StaticInstance.h> - -#endif // CRYINCLUDE_CRYCOMMON_ISHADER_H diff --git a/Code/CryEngine/CryCommon/ISplines.h b/Code/CryEngine/CryCommon/ISplines.h deleted file mode 100644 index 5f05786f19..0000000000 --- a/Code/CryEngine/CryCommon/ISplines.h +++ /dev/null @@ -1,1258 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_ISPLINES_H -#define CRYINCLUDE_CRYCOMMON_ISPLINES_H -#pragma once - -#include <CrySizer.h> -#include <IXml.h> - -////////////////////////////////////////////////////////////////////////// - -// These flags are mostly applicable for hermit based splines. -enum ESplineKeyTangentType -{ - SPLINE_KEY_TANGENT_NONE = 0, - SPLINE_KEY_TANGENT_CUSTOM = 1, - SPLINE_KEY_TANGENT_ZERO = 2, - SPLINE_KEY_TANGENT_STEP = 3, - SPLINE_KEY_TANGENT_LINEAR = 4, - SPLINE_KEY_TANGENT_BEZIER = 5 -}; - -#define SPLINE_KEY_TANGENT_IN_SHIFT (0) -#define SPLINE_KEY_TANGENT_IN_MASK (0x07) // 0000111 -#define SPLINE_KEY_TANGENT_OUT_SHIFT (3) -#define SPLINE_KEY_TANGENT_OUT_MASK (0x07 << (SPLINE_KEY_TANGENT_OUT_SHIFT)) // 0111000 -#define SPLINE_KEY_TANGENT_UNIFY_SHIFT (6) -#define SPLINE_KEY_TANGENT_UNIFY_MASK (0x01 << (SPLINE_KEY_TANGENT_UNIFY_SHIFT)) // 1000000 - -#define SPLINE_KEY_TANGENT_ALL_MASK (SPLINE_KEY_TANGENT_IN_MASK | SPLINE_KEY_TANGENT_OUT_MASK | SPLINE_KEY_TANGENT_UNIFY_MASK) -#define SPLINE_KEY_TANGENT_UNIFIED ((SPLINE_KEY_TANGENT_CUSTOM << SPLINE_KEY_TANGENT_IN_SHIFT) \ - | (SPLINE_KEY_TANGENT_CUSTOM << SPLINE_KEY_TANGENT_OUT_SHIFT) \ - | (0x01 << SPLINE_KEY_TANGENT_UNIFY_SHIFT)) -#define SPLINE_KEY_TANGENT_BROKEN ((SPLINE_KEY_TANGENT_CUSTOM << SPLINE_KEY_TANGENT_IN_SHIFT) \ - | (SPLINE_KEY_TANGENT_CUSTOM << SPLINE_KEY_TANGENT_OUT_SHIFT) \ - | (0x00 << SPLINE_KEY_TANGENT_UNIFY_SHIFT)) - -enum ESplineKeyFlags -{ - ESPLINE_KEY_UI_SELECTED_SHIFT = 16, - ESPLINE_KEY_UI_SELECTED_MAX_DIMENSION_COUNT = 4, // should be power of 2 (see ESPLINE_KEY_UI_SELECTED_MASK) - ESPLINE_KEY_UI_SELECTED_MASK = ((1 << ESPLINE_KEY_UI_SELECTED_MAX_DIMENSION_COUNT) - 1) << ESPLINE_KEY_UI_SELECTED_SHIFT -}; - - -// Return value closest to 0 if same sign, or 0 if opposite. -template<class T> -inline T minmag(T const& a, T const& b) -{ - if (a * b <= T(0.f)) - { - return T(0.f); - } - else if (a < T(0.f)) - { - return max(a, b); - } - else - { - return min(a, b); - } -} - -template<class T> -inline Vec3_tpl<T> minmag(Vec3_tpl<T> const& a, Vec3_tpl<T> const& b) -{ - return Vec3_tpl<T>(minmag(a.x, b.x), minmag(a.y, b.y), minmag(a.z, b.z)); -} - -template<class T> -T abs(Vec3_tpl<T> v) -{ - return v.GetLength(); -} - -////////////////////////////////////////////////////////////////////////// -// Interface returned by backup methods of ISplineInterpolator. -////////////////////////////////////////////////////////////////////////// -struct ISplineBackup -{ - // <interfuscator:shuffle> - virtual ~ISplineBackup(){} - virtual void AddRef() = 0; - virtual void Release() = 0; - // </interfuscator:shuffle> -}; - -////////////////////////////////////////////////////////////////////////// -// General Interpolation interface. -////////////////////////////////////////////////////////////////////////// -struct ISplineInterpolator -{ - typedef float ElemType; - typedef ElemType ValueType[4]; - - // <interfuscator:shuffle> - virtual ~ISplineInterpolator(){} - - // Dimension of the spline from 0 to 3, number of parameters used in ValueType. - virtual int GetNumDimensions() = 0; - - // Insert`s a new key, returns index of the key. - virtual int InsertKey(float time, ValueType value) = 0; - virtual void RemoveKey(int key) = 0; - - virtual void FindKeysInRange(float startTime, float endTime, int& firstFoundKey, int& numFoundKeys) = 0; - virtual void RemoveKeysInRange(float startTime, float endTime) = 0; - - virtual int GetKeyCount() = 0; - virtual void SetKeyTime(int key, float time) = 0; - virtual float GetKeyTime(int key) = 0; - virtual void SetKeyValue(int key, ValueType value) = 0; - virtual bool GetKeyValue(int key, ValueType& value) = 0; - - virtual void SetKeyInTangent(int key, ValueType tin) = 0; - virtual void SetKeyOutTangent(int key, ValueType tout) = 0; - virtual void SetKeyTangents(int key, ValueType tin, ValueType tout) = 0; - virtual bool GetKeyTangents(int key, ValueType& tin, ValueType& tout) = 0; - - // Changes key flags, @see ESplineKeyFlags - virtual void SetKeyFlags(int key, int flags) = 0; - // Retrieve key flags, @see ESplineKeyFlags - virtual int GetKeyFlags(int key) = 0; - - virtual void Interpolate(float time, ValueType& value) = 0; - virtual void EvalInTangent([[maybe_unused]] float time, [[maybe_unused]] ValueType& value) {}; - virtual void EvalOutTangent([[maybe_unused]] float time, [[maybe_unused]] ValueType& value) {}; - - virtual void SerializeSpline(XmlNodeRef& node, bool bLoading) = 0; - - virtual ISplineBackup* Backup() = 0; - virtual void Restore(ISplineBackup* pBackup) = 0; - - void ClearAllKeys() - { - while (GetKeyCount() > 0) - { - RemoveKey(0); - } - Update(); - } - - // </interfuscator:shuffle> - - ////////////////////////////////////////////////////////////////////////// - // Helper functions. - ////////////////////////////////////////////////////////////////////////// - inline bool IsKeySelectedAtAnyDimension(const int key) - { - const int flags = GetKeyFlags(key); - const int dimensionCount = GetNumDimensions(); - const int mask = ((1 << dimensionCount) - 1) << ESPLINE_KEY_UI_SELECTED_SHIFT; - return (flags & mask) != 0; - } - - inline bool IsKeySelectedAtDimension(const int key, const int dimension) - { - const int flags = GetKeyFlags(key); - const int mask = 1 << (ESPLINE_KEY_UI_SELECTED_SHIFT + dimension); - return (flags & mask) != 0; - } - - void SelectKeyAllDimensions(int key, bool select) - { - const int flags = GetKeyFlags(key); - if (select) - { - const int dimensionCount = GetNumDimensions(); - const int mask = ((1 << dimensionCount) - 1) << ESPLINE_KEY_UI_SELECTED_SHIFT; - SetKeyFlags(key, (flags & (~ESPLINE_KEY_UI_SELECTED_MASK)) | mask); - } - else - { - SetKeyFlags(key, flags & (~ESPLINE_KEY_UI_SELECTED_MASK)); - } - } - - void SelectKeyAtDimension(int key, int dimension, bool select) - { - const int flags = GetKeyFlags(key); - const int mask = 1 << (ESPLINE_KEY_UI_SELECTED_SHIFT + dimension); - SetKeyFlags(key, (select ? (flags | mask) : (flags & (~mask)))); - } - - inline int InsertKeyFloat(float time, float val) { ValueType v = {val, 0, 0, 0}; return InsertKey(time, v); } - inline int InsertKeyFloat3(float time, float* vals) { ValueType v = {vals[0], vals[1], vals[2], 0}; return InsertKey(time, v); } - inline bool GetKeyValueFloat(int key, float& value) { ValueType v = {value}; bool b = GetKeyValue(key, v); value = v[0]; return b; } - inline void SetKeyValueFloat(int key, float value) { ValueType v = {value, 0, 0, 0}; SetKeyValue(key, v); } - inline void SetKeyValueFloat3(int key, float* vals) { ValueType v = {vals[0], vals[1], vals[2], 0}; SetKeyValue(key, v); } - inline void InterpolateFloat(float time, float& val) { ValueType v = {val}; Interpolate(time, v); val = v[0]; } - inline void InterpolateFloat3(float time, float* vals) { ValueType v = {vals[0], vals[1], vals[2]}; Interpolate(time, v); vals[0] = v[0]; vals[1] = v[1]; vals[2] = v[2]; } - - inline void EvalInTangentFloat(float time, float& val) { ValueType v = { val }; EvalInTangent(time, v); val = v[0]; } - inline void EvalOutTangentFloat(float time, float& val) { ValueType v = { val }; EvalOutTangent(time, v); val = v[0]; } - - - // Return Key closest to the specified time. - inline int FindKey(float fTime, float fEpsilon = 0.01f) - { - int nKey = -1; - // Find key. - for (int k = 0; k < GetKeyCount(); k++) - { - if (fabs(GetKeyTime(k) - fTime) < fEpsilon) - { - nKey = k; - break; - } - } - return nKey; - } - - // Force update. - void Update() { ValueType val; Interpolate(0.f, val); } - static void ZeroValue(ValueType& value) { value[0] = 0; value[1] = 0; value[2] = 0; value[3] = 0; } -}; - -////////////////////////////////////////////////////////////////////////// -// -////////////////////////////////////////////////////////////////////////// -namespace spline -{ - template <int N> - class BasisFunction - { - public: - const float& operator[](int i) const { return m_f[i]; }; - protected: - float m_f[N]; - }; - - // Special functions that makes parameter zero. - template <class T> - inline void Zero(T& val) - { - memset(&val, 0, sizeof(val)); - } - // Specialized Zero functions - template <> - inline void Zero(float& val) { val = 0.0f; } - template <> - inline void Zero(Vec2& val) { val = Vec2(0.0f, 0.0f); } - template <> - inline void Zero(Vec3& val) { val = Vec3(0.0f, 0.0f, 0.0f); } - template <> - inline void Zero(Quat& val) { val.SetIdentity(); } - - inline float Concatenate(float left, float right) { return left + right; } - inline Vec3 Concatenate(const Vec3& left, const Vec3& right) { return left + right; } - inline Quat Concatenate(const Quat& left, const Quat& right) { return left * right; } - inline float Subtract (float left, float right) { return left - right; } - inline Vec3 Subtract (const Vec3& left, const Vec3& right) { return left - right; } - inline Quat Subtract(const Quat& left, const Quat& right) { return left / right; } - - /////////////////////////////////////////////////////////////////////////////// - // HermitBasis. - class HermitBasis - : public BasisFunction<4> - { - public: - HermitBasis(float t) - { - float t2, t3, t2_3, t3_2, t3_t2; - - t2 = t * t; // t2 = t^2; - t3 = t2 * t; // t3 = t^3; - - t3_2 = t3 + t3; - t2_3 = 3 * t2; - t3_t2 = t3 - t2; - m_f[0] = t3_2 - t2_3 + 1; - m_f[1] = -t3_2 + t2_3; - m_f[2] = t3_t2 - t2 + t; - m_f[3] = t3_t2; - } - }; - - /////////////////////////////////////////////////////////////////////////////// - // BezierBasis. - class BezierBasis - : public BasisFunction<4> - { - public: - BezierBasis(const float t) - { - const float t2 = t * t; - const float t3 = t2 * t; - m_f[0] = -t3 + 3 * t2 - 3 * t + 1; - m_f[1] = 3 * t3 - 6 * t2 + 3 * t; - m_f[2] = -3 * t3 + 3 * t2; - m_f[3] = t3; - } - }; - - template<class T> - struct TCoeffBasis - { - // Coefficients for a cubic polynomial. - T m_c[4]; - - inline T eval(float t) const - { - return m_c[0] + t * (m_c[1] + t * (m_c[2] + t * m_c[3])); - } - // Compute coeffs based on 2 endpoints & slopes. - void set(float t0, T v0, T s0, float t1, T v1, T s1) - { - /* - Solve cubic equation: - v(u) = d t^3 + c t^2 + b t + a - for - v(0) = v0, v'(0) = s0, v(t1) = v1, v'(t1) = s1 - - Solution: - a = v0 - b = s0 - c = -3v0 +3v1 -2s0 -s1 - d = +2v0 -2v1 +s0 +s1 - */ - - /* - Polynomial will be evaluated on adjusted parameter u == t-t0. u0 = 0, u1 = t1-t0. - The range is normalised to start at 0 to avoid extra terms in the coefficient - computation that can compromise precision. However, the range is not normalised - to length 1, because that would require a division at runtime. Instead, we perform - the division on the coefficients. - */ - m_c[0] = v0; - - if (t1 <= t0) - { - m_c[1] = m_c[2] = m_c[3] = T(0.f); - } - else - { - float idt = 1.f / (t1 - t0); - - m_c[1] = T(s0 * idt); - m_c[2] = T((-3.0f * v0 + 3.0f * v1 - 2.0f * s0 - s1) * idt * idt); - m_c[3] = T((2.0f * v0 - 2.0f * v1 + s0 + s1) * idt * idt * idt); - } - } - - void GetMemoryUsage(ICrySizer* pSizer) const {} - }; - - inline float fast_fmod(float x, float y) - { - return fmod_tpl(x, y); - //int ival = ftoi(x/y); - //return x - ival*y; - } - - /**************************************************************************** - ** Key classes ** - ****************************************************************************/ - template <class T> - struct SplineKey - { - typedef T value_type; - - float time; //!< Key time. - int flags; //!< Key flags. - value_type value; //!< Key value. - value_type ds; //!< Incoming tangent. - value_type dd; //!< Outgoing tangent. - SplineKey() - { - memset(this, 0, sizeof(SplineKey)); - } - - SplineKey& operator=(const SplineKey& src) { memcpy(this, &src, sizeof(*this)); return *this; } - - static void Reflect(AZ::SerializeContext* serializeContext) {} - }; - - template <class T> - bool operator ==(const SplineKey<T>& k1, const SplineKey<T>& k2) { return k1.time == k2.time; }; - template <class T> - bool operator !=(const SplineKey<T>& k1, const SplineKey<T>& k2) { return k1.time != k2.time; }; - template <class T> - bool operator < (const SplineKey<T>& k1, const SplineKey<T>& k2) { return k1.time < k2.time; }; - template <class T> - bool operator > (const SplineKey<T>& k1, const SplineKey<T>& k2) { return k1.time > k2.time; }; - - ////////////////////////////////////////////////////////////////////////// - // TCBSplineKey class - ////////////////////////////////////////////////////////////////////////// - - template <class T> - struct TCBSplineKey - : public SplineKey<T> - { - // Key controls. - float tens; //!< Key tension value. - float cont; //!< Key continuity value. - float bias; //!< Key bias value. - float easeto; //!< Key ease to value. - float easefrom; //!< Key ease from value. - - TCBSplineKey() { tens = 0, cont = 0, bias = 0, easeto = 0, easefrom = 0; }; - }; - - //! TCB spline key used in quaternion spline with angle axis as input. - struct TCBAngAxisKey - : public TCBSplineKey<CryQuat> - { - float angle; - Vec3 axis; - - TCBAngAxisKey() - : axis(0, 0, 0) - , angle(0) {}; - }; - - ////////////////////////////////////////////////////////////////////////// - // General Spline class - ////////////////////////////////////////////////////////////////////////// - template <class KeyType, class BasisType> - class TSpline - { - public: - typedef KeyType key_type; - typedef typename KeyType::value_type value_type; - typedef BasisType basis_type; - - // Out of range types. - enum - { - ORT_CONSTANT = 0x0001, // Constant track. - ORT_CYCLE = 0x0002, // Cycle track - ORT_LOOP = 0x0003, // Loop track. - ORT_OSCILLATE = 0x0004, // Oscillate track. - ORT_LINEAR = 0x0005, // Linear track. - ORT_RELATIVE_REPEAT = 0x0007 // Relative repeat track. - }; - // Spline flags. - enum - { - MODIFIED = 0x0001, // Track modified. - MUST_SORT = 0x0002, // Track modified and must be sorted. - }; - - ///////////////////////////////////////////////////////////////////////////// - // Methods. - inline TSpline() - { - m_flags = MODIFIED; - m_ORT = 0; - m_curr = 0; - m_rangeStart = 0; - m_rangeEnd = 0; - m_refCount = 0; - } - - virtual ~TSpline() {}; - - ILINE void flag_set(int flag) { m_flags |= flag; }; - ILINE void flag_clr(int flag) { m_flags &= ~flag; }; - ILINE int flag(int flag) { return m_flags & flag; }; - - ILINE void ORT(int ort) { m_ORT = ort; }; - ILINE int ORT() const { return m_ORT; }; - ILINE int isORT(int o) const { return (m_ORT == o); }; - - ILINE void SetRange(float start, float end) { m_rangeStart = start; m_rangeEnd = end; }; - ILINE float GetRangeStart() const { return m_rangeStart; }; - ILINE float GetRangeEnd() const { return m_rangeEnd; }; - - // Keys access methods. - ILINE void reserve_keys(int n) { m_keys.reserve(n); }; // Reserve memory for more keys. - ILINE void clear() { m_keys.clear(); }; - ILINE void resize(int num) { m_keys.resize(num); SetModified(true); }; // Set new key count. - ILINE bool empty() const { return m_keys.empty(); }; // Check if curve empty (no keys). - ILINE int num_keys() const { return (int)m_keys.size(); }; // Return number of keys in curve. - - ILINE key_type& key(int n) { return m_keys[n]; }; // Return n key. - ILINE float& time(int n) { return m_keys[n].time; }; // Shortcut to key n time. - ILINE value_type& value(int n) { return m_keys[n].value; }; // Shortcut to key n value. - ILINE value_type& ds(int n) { return m_keys[n].ds; }; // Shortcut to key n incoming tangent. - ILINE value_type& dd(int n) { return m_keys[n].dd; }; // Shortcut to key n outgoing tangent. - ILINE int& flags(int n) { return m_keys[n].flags; }; // Shortcut to key n flags. - - ILINE key_type const& key(int n) const { return m_keys[n]; }; // Return n key. - ILINE float time(int n) const { return m_keys[n].time; }; // Shortcut to key n time. - ILINE value_type const& value(int n) const { return m_keys[n].value; }; // Shortcut to key n value. - ILINE value_type const& ds(int n) const { return m_keys[n].ds; }; // Shortcut to key n incoming tangent. - ILINE value_type const& dd(int n) const { return m_keys[n].dd; }; // Shortcut to key n outgoing tangent. - ILINE int flags(int n) const { return m_keys[n].flags; }; // Shortcut to key n flags. - - ILINE int GetInTangentType(int nkey) const { return (flags(nkey) & SPLINE_KEY_TANGENT_IN_MASK) >> SPLINE_KEY_TANGENT_IN_SHIFT; } - ILINE int GetOutTangentType(int nkey) const { return (flags(nkey) & SPLINE_KEY_TANGENT_OUT_MASK) >> SPLINE_KEY_TANGENT_OUT_SHIFT; } - - ILINE void erase(int key) { m_keys.erase(m_keys.begin() + key); SetModified(true); }; - ILINE bool closed() { return (ORT() == ORT_LOOP); } // return True if curve closed. - - ILINE void SetModified(bool bOn, bool bSort = false) - { - if (bOn) - { - m_flags |= MODIFIED; - } - else - { - m_flags &= ~(MODIFIED); - } - if (bSort) - { - m_flags |= MUST_SORT; - } - m_curr = 0; - } - - ILINE void sort_keys() - { - std::stable_sort(m_keys.begin(), m_keys.end()); - m_flags &= ~MUST_SORT; - } - - ILINE void push_back(const key_type& k) - { - m_keys.push_back(k); - SetModified(true); - }; - ILINE int insert_key(const key_type& k) - { - int num = num_keys(); - for (int i = 0; i < num; i++) - { - if (m_keys[i].time > k.time) - { - m_keys.insert(m_keys.begin() + i, k); - SetModified(true); - return i; - } - } - m_keys.push_back(k); - SetModified(true); - return num_keys() - 1; - }; - - ILINE int insert_key(float t, value_type const& val) - { - key_type key; - key.time = t; - key.value = val; - key.flags = 0; - Zero(key.ds); - Zero(key.dd); - return insert_key(key); - } - - inline void update() - { - if (m_flags & MODIFIED) - { - sort_keys(); - if (m_flags & MODIFIED) - { - comp_deriv(); - } - } - } - - inline bool is_updated() const - { - return (m_flags & MODIFIED) == 0; - } - - // Interpolate the value along the spline. - inline bool interpolate(float t, value_type& val) - { - update(); - - if (empty()) - { - return false; - } - - if (t < time(0)) - { - val = value(0); - return true; - } - - adjust_time(t); - - int curr = seek_key(t); - if (curr < num_keys() - 1) - { - assert(t >= time(curr)); - float u = (t - time(curr)) / (time(curr + 1) - time(curr)); - interp_keys(curr, curr + 1, u, val); - } - else - { - val = value(num_keys() - 1); - } - return true; - } - - size_t mem_size() const - { - return this->m_keys.capacity() * sizeof(this->m_keys[0]); - } - - size_t sizeofThis() const - { - return sizeof(*this) + mem_size(); - } - - void swap(TSpline<KeyType, BasisType>& b) - { - using std::swap; - - m_keys.swap(b.m_keys); - swap(m_flags, b.m_flags); - swap(m_ORT, b.m_ORT); - swap(m_curr, b.m_curr); - swap(m_rangeStart, b.m_rangeStart); - swap(m_rangeEnd, b.m_rangeEnd); - } - - ////////////////////////////////////////////////////////////////////////// - // This two functions must be overridden in derived spline classes. - ////////////////////////////////////////////////////////////////////////// - // Pre-compute spline tangents. - virtual void comp_deriv() = 0; - // Interpolate value between two keys. - virtual void interp_keys(int key1, int key2, float u, value_type& val) = 0; - ////////////////////////////////////////////////////////////////////////// - - static void Reflect(AZ::SerializeContext* serializeContext) {} - - inline void add_ref() - { - ++m_refCount; - }; - - inline void release() - { - AZ_Assert(m_refCount > 0, "Reference count logic error, trying to decrement reference when refCount is 0"); - if (--m_refCount == 0) - { - delete this; - } - } - - private: - int m_refCount; - - protected: - AZStd::vector<key_type> m_keys; // List of keys. - uint8 m_flags; - uint8 m_ORT; // Out-Of-Range type. - int16 m_curr; // Current key in track. - - float m_rangeStart; - float m_rangeEnd; - - // Return key before or equal to this time. - inline int seek_key(float t) - { - assert(num_keys() < (1 << 15)); - if ((m_curr >= num_keys()) || (time(m_curr) > t)) - { - // Search from begining. - m_curr = 0; - } - while ((m_curr < num_keys() - 1) && (time(m_curr + 1) <= t)) - { - ++m_curr; - } - return m_curr; - } - - inline void adjust_time(float& t) - { - if (isORT(ORT_CYCLE) || isORT(ORT_LOOP)) - { - if (num_keys() > 0) - { - float endtime = time(num_keys() - 1); - if (t > endtime) - { - // Warp time. - t = fast_fmod(t, endtime); - } - } - } - } - }; - - ////////////////////////////////////////////////////////////////////////// - // TSplineSlopes is default implementation of slope computation - ////////////////////////////////////////////////////////////////////////// - template < class T, class Key = SplineKey<T>, bool bCLAMP = false > - class TSplineSlopes - : public TSpline< Key, TCoeffBasis<T> > - { - public: - typedef TSpline< Key, TCoeffBasis<T> > super_type; - using_type(super_type, key_type); - using_type(super_type, value_type); - static const bool clamp_range = bCLAMP; - - void comp_deriv() - { - this->SetModified(false); - - int last = this->num_keys() - 1; - if (last <= 0) - { - return; - } - - if (bCLAMP) - { - // Change discontinuous slopes. - for (int i = 0; i <= last; ++i) - { - // Out slopes. - if (i < last && this->GetOutTangentType(i) == SPLINE_KEY_TANGENT_LINEAR) - { - // Set linear between points. - this->dd(i) = this->value(i + 1) - this->value(i); - if (this->GetInTangentType(i + 1) == SPLINE_KEY_TANGENT_NONE) - { - // Match continuous slope on right. - this->dd(i) = 2.0f * this->dd(i) - this->ds(i + 1); - } - } - else if (i < last && this->GetOutTangentType(i) == SPLINE_KEY_TANGENT_NONE) - { - this->dd(i) = value_type(0.f); - } - - // In slopes. - if (i > 0 && this->GetInTangentType(i) == SPLINE_KEY_TANGENT_LINEAR) - { - // Set linear between points. - this->ds(i) = this->value(i) - this->value(i - 1); - if (this->GetOutTangentType(i - 1) == SPLINE_KEY_TANGENT_NONE) - { - // Match continuous slope on left. - this->ds(i) = 2.0f * this->ds(i) - this->dd(i - 1); - } - } - else if (i < last && this->GetInTangentType(i) == SPLINE_KEY_TANGENT_NONE) - { - this->ds(i) = value_type(0.f); - } - } - } - else - { - key_type& k0 = this->key(0); - key_type& k1 = this->key(last); - - Zero(k0.ds); - k0.dd = (0.5f) * (this->value(1) - this->value(0)); - k1.ds = (0.5f) * (this->value(last) - this->value(last - 1)); - Zero(k1.dd); - - for (int i = 1; i < (this->num_keys() - 1); ++i) - { - key_type& key = this->key(i); - key.ds = 0.5f * (this->value(i + 1) - this->value(i - 1)); - key.dd = key.ds; - } - } - } - - virtual void interp_keys(int key1, int key2, float u, value_type& val) - { - // Compute coeffs dynamically. - TCoeffBasis<T> coeff; - coeff.set(0.f, this->value(key1), this->dd(key1), 1.f, this->value(key2), this->ds(key2)); - val = coeff.eval(u); - } - }; - - ////////////////////////////////////////////////////////////////////////// - // CatmullRomSpline class implementation - ////////////////////////////////////////////////////////////////////////// - template <class T, class Key = SplineKey<T>, bool bRangeLimit = false > - class CatmullRomSpline - : public TSplineSlopes< T, Key, bRangeLimit > - { - protected: - - typedef TSplineSlopes< T, Key, bRangeLimit > super_type; - - std::vector< TCoeffBasis<T> > m_coeffs; - - virtual void comp_deriv() - { - super_type::comp_deriv(); - - // Store coeffs for each segment. - m_coeffs.resize(this->num_keys()); - - if (this->num_keys() > 0) - { - unsigned i; - for (i = 0; i < m_coeffs.size() - 1; i++) - { - m_coeffs[i].set(this->time(i), this->value(i), this->dd(i), this->time(i + 1), this->value(i + 1), this->ds(i + 1)); - } - - // Last segment is just constant value. - m_coeffs[i].set(this->time(i), this->value(i), T(0.f), this->time(i) + 1.f, this->value(i), T(0.f)); - } - } - - virtual void interp_keys(int key1, int key2, float u, typename TSpline<Key, HermitBasis>::value_type& val) - { - u *= this->time(key2) - this->time(key1); - val = m_coeffs[key1].eval(u); - } - - public: - - size_t mem_size() const - { - return super_type::mem_size() + this->m_coeffs.capacity() * sizeof(this->m_coeffs[0]); - } - size_t sizeofThis() const - { - return sizeof(*this) + mem_size(); - } - }; - - ////////////////////////////////////////////////////////////////////////// - // Extended version of Hermit Spline. - // Provides more control on key tangents. - ////////////////////////////////////////////////////////////////////////// - template <class T, class Key = SplineKey<T> > - class HermitSplineEx - : public TSpline< Key, HermitBasis > - { - public: - typedef TSpline< Key, HermitBasis > super_type; - using_type(super_type, key_type); - using_type(super_type, value_type); - - virtual void comp_deriv() - { - this->SetModified(false); - if (this->num_keys() > 1) - { - int last = this->num_keys() - 1; - key_type& k0 = this->key(0); - key_type& k1 = this->key(last); - Zero(k0.ds); - Zero(k0.dd); - Zero(k1.ds); - Zero(k1.dd); - - Zero(k0.ds); - k0.dd = (0.5f) * (this->value(1) - this->value(0)); - k1.ds = (0.5f) * (this->value(last) - this->value(last - 1)); - Zero(k1.dd); - - for (int i = 1; i < (this->num_keys() - 1); ++i) - { - key_type& key = this->key(i); - key.ds = 0.5f * (this->value(i + 1) - this->value(i - 1)); - key.dd = key.ds; - switch (this->GetInTangentType(i)) - { - case SPLINE_KEY_TANGENT_STEP: - key.ds = value_type(); - break; - case SPLINE_KEY_TANGENT_ZERO: - key.ds = value_type(); - break; - case SPLINE_KEY_TANGENT_LINEAR: - key.ds = this->value(i) - this->value(i - 1); - break; - } - switch (this->GetOutTangentType(i)) - { - case SPLINE_KEY_TANGENT_STEP: - key.dd = value_type(); - break; - case SPLINE_KEY_TANGENT_ZERO: - key.dd = value_type(); - break; - case SPLINE_KEY_TANGENT_LINEAR: - key.dd = this->value(i + 1) - this->value(i); - break; - } - } - } - } - - protected: - virtual void interp_keys(int from, int to, float u, T& val) - { - if (this->GetInTangentType(to) == SPLINE_KEY_TANGENT_STEP || this->GetOutTangentType(from) == SPLINE_KEY_TANGENT_STEP) - { - val = this->value(from); - return; - } - typename TSpline<Key, HermitBasis >::basis_type basis(u); - val = (basis[0] * this->value(from)) + (basis[1] * this->value(to)) + (basis[2] * this->dd(from)) + (basis[3] * this->ds(to)); - } - }; - - - ////////////////////////////////////////////////////////////////////////// - // Bezier Spline. - ////////////////////////////////////////////////////////////////////////// - template <class T, class Key = SplineKey<T> > - class BezierSpline - : public TSpline< Key, BezierBasis > - { - public: - typedef TSpline< Key, BezierBasis > super_type; - using_type(super_type, key_type); - using_type(super_type, value_type); - - virtual void comp_deriv() - { - this->SetModified(false); - - if (this->num_keys() > 1) - { - const float oneThird = 1 / 3.0f; - - const int last = this->num_keys() - 1; - - { - if (this->GetInTangentType(0) != SPLINE_KEY_TANGENT_CUSTOM) - { - Zero(this->key(0).ds); - } - if (this->GetOutTangentType(0) != SPLINE_KEY_TANGENT_CUSTOM) - { - this->key(0).dd = oneThird * (this->value(1) - this->value(0)); - } - - if (this->GetInTangentType(last) != SPLINE_KEY_TANGENT_CUSTOM) - { - this->key(last).ds = oneThird * (this->value(last) - this->value(last - 1)); - } - if (this->GetOutTangentType(last) != SPLINE_KEY_TANGENT_CUSTOM) - { - Zero(this->key(last).dd); - } - } - - for (int i = 1; i < last; ++i) - { - key_type& key = this->key(i); - T ds0 = key.ds; - T dd0 = key.dd; - - const float deltaTime = this->time(i + 1) - this->time(i - 1); - if (deltaTime <= 0) - { - Zero(key.ds); - Zero(key.dd); - } - else - { - const float k = (this->time(i) - this->time(i - 1)) / deltaTime; - const value_type deltaValue = this->value(i + 1) - this->value(i - 1); - key.ds = oneThird * deltaValue * k; - key.dd = oneThird * deltaValue * (1 - k); - } - - switch (this->GetInTangentType(i)) - { - case SPLINE_KEY_TANGENT_STEP: - Zero(key.ds); - break; - case SPLINE_KEY_TANGENT_ZERO: - Zero(key.ds); - break; - case SPLINE_KEY_TANGENT_LINEAR: - key.ds = oneThird * (this->value(i) - this->value(i - 1)); - break; - case SPLINE_KEY_TANGENT_CUSTOM: - key.ds = ds0; - break; - } - - switch (this->GetOutTangentType(i)) - { - case SPLINE_KEY_TANGENT_STEP: - Zero(key.dd); - break; - case SPLINE_KEY_TANGENT_ZERO: - Zero(key.dd); - break; - case SPLINE_KEY_TANGENT_LINEAR: - key.dd = oneThird * (this->value(i + 1) - this->value(i)); - break; - case SPLINE_KEY_TANGENT_CUSTOM: - key.dd = dd0; - break; - } - } - } - } - - static void Reflect(AZ::SerializeContext* serializeContext) {} - - protected: - virtual void interp_keys(int from, int to, float u, T& val) - { - if (this->GetOutTangentType(from) == SPLINE_KEY_TANGENT_STEP) - { - val = this->value(to); - } - else if (this->GetInTangentType(to) == SPLINE_KEY_TANGENT_STEP) - { - val = this->value(from); - } - else - { - typename TSpline<Key, BezierBasis >::basis_type basis(u); - - const T p0 = this->value(from); - const T p3 = this->value(to); - const T p1 = p0 + this->dd(from); - const T p2 = p3 - this->ds(to); - - val = (basis[0] * p0) + (basis[1] * p1) + (basis[2] * p2) + (basis[3] * p3); - } - } - }; - - - ////////////////////////////////////////////////////////////////////////// - // Base class for spline interpolators. - ////////////////////////////////////////////////////////////////////////// - - template <typename spline_type> - struct SSplineBackup - : public ISplineBackup - , public spline_type - { - int refCount; - - SSplineBackup(spline_type const& s) - : spline_type(s) - , refCount(0) {} - virtual void AddRef() {++refCount; } - virtual void Release() - { - if (--refCount <= 0) - { - delete this; - } - } - }; - - template <class value_type, class spline_type> - class CBaseSplineInterpolator - : public ISplineInterpolator - , public spline_type - { - public: - static const int DIM = sizeof(value_type) / sizeof(ElemType); - - ////////////////////////////////////////////////////////////////////////// - inline void ToValueType(const value_type& t, ValueType& v) { *(value_type*)v = t; } - inline void FromValueType(ValueType v, value_type& t) { t = *(value_type*)v; } - ////////////////////////////////////////////////////////////////////////// - - virtual void SetModified(bool b, bool bSort = false) - { - spline_type::SetModified(b, bSort); - } - virtual int GetNumDimensions() - { - assert(sizeof(value_type) % sizeof(ElemType) == 0); - return DIM; - } - - virtual int InsertKey(float t, ValueType val) - { - value_type value; - FromValueType(val, value); - return spline_type::insert_key(t, value); - } - virtual void RemoveKey(int key) - { - if (key >= 0 && key < this->num_keys()) - { - this->erase(key); - } - } - virtual void FindKeysInRange(float startTime, float endTime, int& firstFoundKey, int& numFoundKeys) - { - int count = this->num_keys(); - int start = 0; - int end = count; - for (int i = 0; i < count; ++i) - { - float keyTime = this->key(i).time; - if (keyTime < startTime) - { - start = i + 1; - } - if (keyTime > endTime && end > i) - { - end = i; - } - } - if (start < end) - { - firstFoundKey = start; - numFoundKeys = end - start; - } - else - { - firstFoundKey = -1; - numFoundKeys = 0; - } - } - virtual void RemoveKeysInRange(float startTime, float endTime) - { - int firstFoundKey, numFoundKeys; - FindKeysInRange(startTime, endTime, firstFoundKey, numFoundKeys); - while (numFoundKeys-- > 0) - { - this->erase(firstFoundKey++); - } - } - virtual int GetKeyCount() - { - return this->num_keys(); - }; - virtual float GetKeyTime(int key) - { - if (key >= 0 && key < this->num_keys()) - { - return this->key(key).time; - } - return 0; - } - virtual bool GetKeyValue(int key, ValueType& val) - { - if (key >= 0 && key < this->num_keys()) - { - ToValueType(this->key(key).value, val); - return true; - } - return false; - } - virtual void SetKeyValue(int k, ValueType val) - { - if (k >= 0 && k < this->num_keys()) - { - FromValueType(val, this->key(k).value); - this->SetModified(true); - } - } - virtual void SetKeyTime(int k, float fTime) - { - if (k >= 0 && k < this->num_keys()) - { - this->key(k).time = fTime; - this->SetModified(true, true); - } - } - virtual void SetKeyInTangent(int k, ValueType tin) - { - if (k >= 0 && k < this->num_keys()) - { - FromValueType(tin, this->key(k).ds); - this->SetModified(true); - } - } - virtual void SetKeyOutTangent(int k, ValueType tout) - { - if (k >= 0 && k < this->num_keys()) - { - FromValueType(tout, this->key(k).dd); - this->SetModified(true); - } - } - virtual void SetKeyTangents(int k, ValueType tin, ValueType tout) - { - if (k >= 0 && k < this->num_keys()) - { - FromValueType(tin, this->key(k).ds); - FromValueType(tout, this->key(k).dd); - this->SetModified(true); - } - } - virtual bool GetKeyTangents(int k, ValueType& tin, ValueType& tout) - { - if (k >= 0 && k < this->num_keys()) - { - ToValueType(this->key(k).ds, tin); - ToValueType(this->key(k).dd, tout); - return true; - } - else - { - return false; - } - } - virtual void SetKeyFlags(int k, int flags) - { - if (k >= 0 && k < this->num_keys()) - { - this->key(k).flags = flags; - this->SetModified(true); - } - } - virtual int GetKeyFlags(int k) - { - if (k >= 0 && k < this->num_keys()) - { - return this->key(k).flags; - } - return 0; - } - - virtual void Interpolate(float time, ValueType& value) - { - value_type v; - if (spline_type::interpolate(time, v)) - { - ToValueType(v, value); - } - } - - virtual ISplineBackup* Backup() - { - return new SSplineBackup<spline_type>(*this); - } - - virtual void Restore(ISplineBackup* p) - { - SSplineBackup<spline_type>* pBackup = static_cast<SSplineBackup<spline_type>*>(p); - static_cast<spline_type&>(*this) = *pBackup; - } - }; -} - -namespace AZ -{ - AZ_TYPE_INFO_SPECIALIZE(spline::SplineKey<Vec2>, "{24A4D7E5-C36D-427D-AB49-CD86573B7288}"); -} -#endif // CRYINCLUDE_CRYCOMMON_ISPLINES_H diff --git a/Code/CryEngine/CryCommon/IStatObj.h b/Code/CryEngine/CryCommon/IStatObj.h deleted file mode 100644 index 2ba9d0cd16..0000000000 --- a/Code/CryEngine/CryCommon/IStatObj.h +++ /dev/null @@ -1,798 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include "smartptr.h" // TYPEDEF_AUTOPTR -#include "IMaterial.h" - -// forward declarations -////////////////////////////////////////////////////////////////////// -struct ShadowMapFrustum; -struct SRenderingPassInfo; -struct SRendItemSorter; -struct IShader; -struct SPhysGeomArray; -struct CStatObj; - -class CRenderObject; -class CDLight; -class IReadStream; -class CRenderObject; -class CLodValue; - - -TYPEDEF_AUTOPTR(IReadStream); - -//! Interface to non animated object -struct phys_geometry; -struct IChunkFile; - -// General forward declaration. -class CRenderObject; -struct SMeshLodInfo; - -#include "CryHeaders.h" -#include "Cry_Math.h" -#include "Cry_Geo.h" -#include "IPhysics.h" - -#define MAX_STATOBJ_LODS_NUM 6 - -////////////////////////////////////////////////////////////////////////// -// Type of static sub object. -////////////////////////////////////////////////////////////////////////// -enum EStaticSubObjectType -{ - STATIC_SUB_OBJECT_MESH, // This simple geometry part of the multi-sub object geometry. - STATIC_SUB_OBJECT_HELPER_MESH, // Special helper mesh, not rendered usually, used for broken pieces. - STATIC_SUB_OBJECT_POINT, - STATIC_SUB_OBJECT_DUMMY, - STATIC_SUB_OBJECT_XREF, - STATIC_SUB_OBJECT_CAMERA, - STATIC_SUB_OBJECT_LIGHT, -}; - -////////////////////////////////////////////////////////////////////////// -// Flags that can be set on static object. -////////////////////////////////////////////////////////////////////////// -enum EStaticObjectFlags -{ - STATIC_OBJECT_HIDDEN = BIT(0), // When set static object will not be displayed. - STATIC_OBJECT_CLONE = BIT(1), // specifies whether this object was cloned for modification - STATIC_OBJECT_GENERATED = BIT(2), // tells that the object was generated procedurally (breakable obj., f.i.) - STATIC_OBJECT_CANT_BREAK = BIT(3), // StatObj has geometry unsuitable for procedural breaking - STATIC_OBJECT_DEFORMABLE = BIT(4), // StatObj can be procedurally smeared (using SmearStatObj) - STATIC_OBJECT_COMPOUND = BIT(5), // StatObj has subobject meshes - STATIC_OBJECT_MULTIPLE_PARENTS = BIT(6), // Child StatObj referenced by several parents - - // Collisions - STATIC_OBJECT_NO_PLAYER_COLLIDE = BIT(10), - - // Special flags. - STATIC_OBJECT_SPAWN_ENTITY = BIT(20), // StatObj spawns entity when broken. - STATIC_OBJECT_NO_AUTO_HIDEPOINTS = BIT(22), // Do not generate AI auto hide points around object if it's dynamic - STATIC_OBJECT_DYNAMIC = BIT(23), // mesh data should be kept in system memory (and yes, the name *is* an oxymoron) -}; - -#define HIT_NO_HIT (-1) -#define HIT_UNKNOWN (-2) - -#define HIT_OBJ_TYPE_BRUSH 0 -#define HIT_OBJ_TYPE_TERRAIN 1 -#define HIT_OBJ_TYPE_VISAREA 2 - -// used for on-CPU voxelization -struct SRayHitTriangle -{ - SRayHitTriangle() { ZeroStruct(*this); } - Vec3 v[3]; - Vec2 t[3]; - ColorB c[3]; - Vec3 n; - _smart_ptr<IMaterial> pMat; - uint8 nTriArea; - uint8 nOpacity; - uint8 nHitObjType; -}; - -struct SRayHitInfo -{ - SRayHitInfo() - { - memset(this, 0, sizeof(*this)); - nHitTriID = HIT_UNKNOWN; - } - ////////////////////////////////////////////////////////////////////////// - // Input parameters. - Vec3 inReferencePoint; - Ray inRay; - bool bInFirstHit; - bool inRetTriangle; - bool bUseCache; - bool bOnlyZWrite; - bool bGetVertColorAndTC; - float fMaxHitDistance; // When not 0, only hits with closer distance will be registered. - Vec3 vTri0; - Vec3 vTri1; - Vec3 vTri2; - float fMinHitOpacity; - - ////////////////////////////////////////////////////////////////////////// - // Output parameters. - float fDistance; // Distance from reference point. - Vec3 vHitPos; - Vec3 vHitNormal; - int nHitMatID; // Material Id that was hit. - int nHitTriID; // Triangle Id that was hit. - int nHitSurfaceID; // Material Id that was hit. - struct IRenderMesh* pRenderMesh; - struct IStatObj* pStatObj; - Vec2 vHitTC; - Vec4 vHitColor; - Vec4 vHitTangent; - Vec4 vHitBitangent; - PodArray<SRayHitTriangle>* pHitTris; -}; - -enum EFileStreamingStatus -{ - ecss_NotLoaded, - ecss_InProgress, - ecss_Ready -}; - -// Interface for streaming of objects like CStatObj. -struct IStreamable -{ - struct SInstancePriorityInfo - { - int nRoundId; - float fMaxImportance; - }; - - IStreamable() - { - ZeroStruct(m_arrUpdateStreamingPrioriryRoundInfo); - m_eStreamingStatus = ecss_NotLoaded; - fCurImportance = 0; - m_nSelectedFrameId = 0; - m_nStatsInUse = 0; - } - - bool UpdateStreamingPrioriryLowLevel(float fImportance, int nRoundId, bool bFullUpdate) - { - bool bRegister = false; - - if (m_arrUpdateStreamingPrioriryRoundInfo[0].nRoundId != nRoundId) - { - if (!m_arrUpdateStreamingPrioriryRoundInfo[0].nRoundId) - { - bRegister = true; - } - - m_arrUpdateStreamingPrioriryRoundInfo[1] = m_arrUpdateStreamingPrioriryRoundInfo[0]; - - m_arrUpdateStreamingPrioriryRoundInfo[0].nRoundId = nRoundId; - m_arrUpdateStreamingPrioriryRoundInfo[0].fMaxImportance = fImportance; - } - else - { - m_arrUpdateStreamingPrioriryRoundInfo[0].fMaxImportance = max(m_arrUpdateStreamingPrioriryRoundInfo[0].fMaxImportance, fImportance); - } - - if (bFullUpdate) - { - m_arrUpdateStreamingPrioriryRoundInfo[1] = m_arrUpdateStreamingPrioriryRoundInfo[0]; - m_arrUpdateStreamingPrioriryRoundInfo[1].nRoundId--; - } - - return bRegister; - } - - // <interfuscator:shuffle> - virtual ~IStreamable(){} - virtual void StartStreaming(bool bFinishNow, IReadStream_AutoPtr* ppStream) = 0; - virtual int GetStreamableContentMemoryUsage(bool bJustForDebug = false) = 0; - virtual void ReleaseStreamableContent() = 0; - virtual void GetStreamableName(string& sName) = 0; - virtual uint32 GetLastDrawMainFrameId() = 0; - virtual bool IsUnloadable() const = 0; - - SInstancePriorityInfo m_arrUpdateStreamingPrioriryRoundInfo[2]; - float fCurImportance; - EFileStreamingStatus m_eStreamingStatus; - uint32 m_nSelectedFrameId : 31; - uint32 m_nStatsInUse : 1; -}; - -struct SMeshBoneMapping_uint8; -struct SSpine; -struct SMeshColor; - -// Summary: -// Interface to hold static object data -struct IStatObj - : public IStreamable -{ - //! Loading flags - enum ELoadingFlags - { - ELoadingFlagsPreviewMode = BIT(0), - ELoadingFlagsForceBreakable = BIT(1), - ELoadingFlagsIgnoreLoDs = BIT(2), - ELoadingFlagsTessellate = BIT(3), // if e_StatObjTessellation enabled - ELoadingFlagsJustGeometry = BIT(4), // for streaming, to avoid parsing all chunks - }; - - ////////////////////////////////////////////////////////////////////////// - // SubObject - ////////////////////////////////////////////////////////////////////////// - struct SSubObject - { - SSubObject() { bShadowProxy = 0; } - - EStaticSubObjectType nType; - string name; - string properties; - int nParent; // Index of the parent sub object, if there`s hierarchy between them. - Matrix34 tm; // Transformation matrix. - Matrix34 localTM; // Local transformation matrix, relative to parent. - IStatObj* pStatObj; // Static object for sub part of CGF. - Vec3 helperSize; // Size of the helper (if helper). - struct IRenderMesh* pWeights; // render mesh with a single deformation weights stream - unsigned int bIdentityMatrix : 1; // True if sub object matrix is identity. - unsigned int bHidden : 1; // True if sub object is hidden - unsigned int bShadowProxy : 1; // Child StatObj has 'shadowproxy' in name - unsigned int nBreakerJoints : 8; // number of joints that can switch this part to a broken state - - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(name); - pSizer->AddObject(properties); - } - }; - ////////////////////////////////////////////////////////////////////////// - - // Statistics information about this object. - struct SStatistics - { - int nVertices; - int nVerticesPerLod[MAX_STATOBJ_LODS_NUM]; - int nIndices; - int nIndicesPerLod[MAX_STATOBJ_LODS_NUM]; - int nMeshSize; - int nMeshSizeLoaded; - int nPhysProxySize; - int nPhysProxySizeMax; - int nPhysPrimitives; - int nDrawCalls; - int nLods; - int nSubMeshCount; - int nNumRefs; - bool bSplitLods; // Lods split between files. - - // Optional texture sizer. - ICrySizer* pTextureSizer; - ICrySizer* pTextureSizer2; - - SStatistics() { Reset(); } - - void Reset() - { - pTextureSizer = NULL; - pTextureSizer2 = NULL; - nVertices = 0; - nIndices = 0; - nMeshSize = 0; - nMeshSizeLoaded = 0; - nNumRefs = 0; - nPhysProxySize = 0; - nPhysPrimitives = 0; - nDrawCalls = 0; - nLods = 0; - nSubMeshCount = 0; - bSplitLods = false; - ZeroStruct(nVerticesPerLod); - ZeroStruct(nIndicesPerLod); - } - }; - - // <interfuscator:shuffle> - // Description: - // Increase the reference count of the object. - // Summary: - // Notifies that the object is being used - virtual int AddRef() = 0; - - // Description: - // Decrease the reference count of the object. If the reference count - // reaches zero, the object will be deleted from memory. - // Summary: - // Notifies that the object is no longer needed - virtual int Release() = 0; - - // Description: - // Set static object flags. - // Arguments: - // nFlags - flags to set, a combination of EStaticObjectFlags values. - virtual void SetFlags(int nFlags) = 0; - - // Description: - // Retrieve flags set on the static object. - virtual int GetFlags() const = 0; - - // Sets the default object indicator - virtual void SetDefaultObject(bool state) = 0; - - // Description: - // Retrieves the internal flag m_nVehicleOnlyPhysics. - virtual unsigned int GetVehicleOnlyPhysics() = 0; - - // Description: - // Retrieves the internal flag m_nIdMaterialBreakable. - virtual int GetIDMatBreakable() = 0; - - // Description: - // Retrieves the internal flag m_bBreakableByGame. - virtual unsigned int GetBreakableByGame() = 0; - - // Description: - // Provide access to the faces, vertices, texture coordinates, normals and - // colors of the object used later for CRenderMesh construction. - // Return Value: - // - // Summary: - // Get the object source geometry - virtual struct IIndexedMesh* GetIndexedMesh(bool bCreateIfNone = false) = 0; - - // Description: - // Create an empty indexed mesh ready to be filled with data - // If an indexed mesh already exists it is returned - // Return Value: - // An empty indexed mesh or the existing indexed mesh - virtual struct IIndexedMesh* CreateIndexedMesh() = 0; - - //! Access to rendering geometry for indoor engine ( optimized vert arrays, lists of shader pointers ) - virtual struct IRenderMesh* GetRenderMesh() = 0; - - // Description: - // Returns the physical representation of the object. - // Arguments: - // nType - one of PHYS_GEOM_TYPE_'s, or an explicit slot index - // Return Value: - // A pointer to a phys_geometry structure. - // Summary: - // Get the physic representation - virtual phys_geometry* GetPhysGeom(int nType = PHYS_GEOM_TYPE_DEFAULT) = 0; - - // Description: - // Updates rendermesh's vertices, normals, and tangents with the data provided - // Summary: - // Updates vertices in the range [iVtx0..iVtx0+nVtx-1], vertices are in their original order - // (as they are physicalized). Clones the object if necessary to make the modifications - // Return Value: - // modified IStatObj (a clone or this one, if it's already a clone) - virtual IStatObj* UpdateVertices(strided_pointer<Vec3> pVtx, strided_pointer<Vec3> pNormals, int iVtx0, int nVtx, int* pVtxMap = 0, float rscale = 1.f) = 0; - - // Description: - // Skins rendermesh's vertices based on skeleton vertices - // Summary: - // Skins vertices based on mtxSkelToMesh[pSkelVtx[i]] - // Clones the object if necessary to make the modifications - // Return Value: - // modified IStatObj (a clone or this one, if it's already a clone) - virtual IStatObj* SkinVertices(strided_pointer<Vec3> pSkelVtx, const Matrix34& mtxSkelToMesh) = 0; - - // Description: - // Sets and replaces the physical representation of the object. - // Arguments: - // pPhysGeom - A pointer to a phys_geometry class. - // nType - Pass 0 to set the physic geometry or pass 1 to set the obstruct geometry - // Summary: - // Set the physic representation - virtual void SetPhysGeom(phys_geometry* pPhysGeom, int nType = 0) = 0; - - // Description: - // Returns a tetrahedral lattice, if any (used for breakable objects) - virtual ITetrLattice* GetTetrLattice() = 0; - - virtual float GetAIVegetationRadius() const = 0; - virtual void SetAIVegetationRadius(float radius) = 0; - - // Description: - // Set default material for the geometry. - // Arguments: - // pMaterial - A valid pointer to the material. - virtual void SetMaterial(_smart_ptr<IMaterial> pMaterial) = 0; - - // Description: - // Returns default material of the geometry. - // Arguments: - // nType - Pass 0 to get the physic geometry or pass 1 to get the obstruct geometry - // Return Value: - // A pointer to a phys_geometry class. - virtual _smart_ptr<IMaterial> GetMaterial() = 0; - virtual const _smart_ptr<IMaterial> GetMaterial() const = 0; - - // Return Value: - // A Vec3 object containing the bounding box. - // Summary: - // Get the minimal bounding box component - virtual Vec3 GetBoxMin() = 0; - - // Return Value: - // A Vec3 object containing the bounding box. - // Summary: - // Get the minimal bounding box component - virtual Vec3 GetBoxMax() = 0; - - // Return Value: - // A Vec3 object containing the bounding box center. - // Summary: - // Get the center of bounding box - virtual const Vec3 GetVegCenter() = 0; - - // Arguments: - // Minimum bounding box component - // Summary: - // Set the minimum bounding box component - virtual void SetBBoxMin(const Vec3& vBBoxMin) = 0; - - // Arguments: - // Minimum bounding box component - // Summary: - // Set the minimum bounding box component - virtual void SetBBoxMax(const Vec3& vBBoxMax) = 0; - - // Summary: - // Get the object radius - // Return Value: - // A float containing the radius - virtual float GetRadius() = 0; - - // Description: - // Reloads one or more component of the object. The possible flags - // are FRO_SHADERS, FRO_TEXTURES and FRO_GEOMETRY. - // Arguments: - // nFlags - One or more flag which indicate which element of the object - // to reload - // Summary: - // Reloads the object - virtual void Refresh(int nFlags) = 0; - - // Description: - // Registers the object elements into the renderer. - // Arguments: - // rParams - Render parameters - // nLogLevel - Level of the LOD - // Summary: - // Renders the object - virtual void Render(const struct SRendParams& rParams, const SRenderingPassInfo& passInfo) = 0; - - // Summary: - // Get the bounding box - // Arguments: - // Mins - Position of the bottom left close corner of the bounding box - // Maxs - Position of the top right far corner of the bounding box - virtual AABB GetAABB() = 0; - - // Summary: - // Generate a random point in object. - // Arguments: - // eForm - Object aspect to generate on (surface, volume, etc) - virtual float GetExtent(EGeomForm eForm) = 0; - virtual void GetRandomPos(PosNorm& ran, EGeomForm eForm) const = 0; - - // Description: - // Returns the LOD object, if present. - // Arguments: - // nLodLevel - Level of the LOD - // bReturnNearest - if true will return nearest available LOD to nLodLevel. - // Return Value: - // A static object with the desired LOD. The value NULL will be return if there isn't any LOD object for the level requested. - // Summary: - // Get the LOD object - virtual IStatObj* GetLodObject(int nLodLevel, bool bReturnNearest = false) = 0; - virtual IStatObj* GetLowestLod() = 0; - virtual int FindNearesLoadedLOD(int nLodIn, bool bSearchUp = false) = 0; - virtual int FindHighestLOD(int nBias) = 0; - - virtual bool LoadCGF(const char* filename, bool bLod, unsigned long nLoadingFlags, const void* pData, const int nDataSize) = 0; - virtual void DisableStreaming() = 0; - virtual void TryMergeSubObjects(bool bFromStreaming) = 0; - virtual bool IsUnloadable() const = 0; - virtual void SetCanUnload(bool value) = 0; - - virtual string& GetFileName() = 0; - virtual const string& GetFileName() const = 0; - - virtual const string& GetCGFNodeName() const = 0; - - // Summary: - // Returns the filename of the object - // Return Value: - // A null terminated string which contain the filename of the object. - virtual const char* GetFilePath() const = 0; - - // Summary: - // Set the filename of the object - // Arguments: - // szFileName - New filename of the object - // Return Value: - // None - virtual void SetFilePath(const char* szFileName) = 0; - - // Summary: - // Returns the name of the geometry - // Return Value: - // A null terminated string which contains the name of the geometry - virtual const char* GetGeoName() = 0; - - // Summary: - // Sets the name of the geometry - virtual void SetGeoName(const char* szGeoName) = 0; - - // Summary: - // Compares if another object is the same - // Arguments: - // szFileName - Filename of the object to compare - // szGeomName - Geometry name of the object to compare (optional) - // Return Value: - // A boolean which equals to true in case both object are the same, or false in the opposite case. - virtual bool IsSameObject(const char* szFileName, const char* szGeomName) = 0; - - // Description: - // Will return the position of the helper named in the argument. The - // helper should have been specified during the exporting process of - // the cgf file. - // Arguments: - // szHelperName - A null terminated string holding the name of the helper - // Return Value: - // A Vec3 object which contains the position. - // Summary: - // Gets the position of a specified helper - virtual Vec3 GetHelperPos(const char* szHelperName) = 0; - - // Summary: - // Gets the transformation matrix of a specified helper, see GetHelperPos - virtual const Matrix34& GetHelperTM(const char* szHelperName) = 0; - - //! Tell us if the object is not found - virtual bool IsDefaultObject() = 0; - - // Summary: - // Free the geometry data - virtual void FreeIndexedMesh() = 0; - - // Pushes the underlying tree of objects into the given Sizer object for statistics gathering - virtual void GetMemoryUsage(class ICrySizer* pSizer) const = 0; - - //DOC-IGNORE-BEGIN - //! used for sprites - virtual float& GetRadiusVert() = 0; - - //! used for sprites - virtual float& GetRadiusHors() = 0; - //DOC-IGNORE-END - - // Summary: - // Determines if the object has physics capabilities - virtual bool IsPhysicsExist() = 0; - - // Summary: - // Returns a pointer to the object - // Return Value: - // A pointer to the current object, which is simply done like this "return this;" - virtual struct IStatObj* GetIStatObj() { return this; } - - // Summary: - // Invalidates geometry inside IStatObj, will mark hosted IIndexedMesh as invalid. - // Arguments: - // bPhysics - if true will also recreate physics for indexed mesh. - virtual void Invalidate(bool bPhysics = false, float tolerance = 0.05f) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Interface to the Sub Objects. - ////////////////////////////////////////////////////////////////////////// - // Summary: - // Retrieve number of sub-objects. - virtual int GetSubObjectCount() const = 0; - // Summary: - // Sets number of sub-objects. - virtual void SetSubObjectCount(int nCount) = 0; - // Summary: - // Retrieve sub object by index, where 0 <= nIndex < GetSubObjectCount() - virtual IStatObj::SSubObject* GetSubObject(int nIndex) = 0; - // Summary: - // Check if this object is sub object of another IStatObj. - virtual bool IsSubObject() const = 0; - // Summary: - // Retrieve parent static object, only relevant when this IStatObj is Sub-object. - virtual IStatObj* GetParentObject() const = 0; - // Summary: - // Retrieve the static object, from which this one was cloned (if that is the case) - virtual IStatObj* GetCloneSourceObject() const = 0; - // Summary: - // Find sub-pbject by name. - virtual IStatObj::SSubObject* FindSubObject(const char* sNodeName) = 0; - // Find sub-object by name (including spaces, comma and semi-colon. - virtual IStatObj::SSubObject* FindSubObject_CGA(const char* sNodeName) = 0; - - // Summary: - // Find object by full name (use all the characters) - virtual IStatObj::SSubObject* FindSubObject_StrStr(const char* sNodeName) = 0; - // Remove Sub-Object. - virtual bool RemoveSubObject(int nIndex) = 0; - // Copy Sub-Object. - virtual bool CopySubObject(int nToIndex, IStatObj* pFromObj, int nFromIndex) = 0; - // adds a new sub object - virtual IStatObj::SSubObject& AddSubObject(IStatObj* pStatObj) = 0; - - // Summary: - // Adds subobjects to pent, meshes as parts, joint helpers as breakable joints - virtual int PhysicalizeSubobjects(IPhysicalEntity* pent, const Matrix34* pMtx, float mass, float density = 0.0f, int id0 = 0, strided_pointer<int> pJointsIdMap = 0, const char* szPropsOverride = 0) = 0; - // Summary: - // Adds all phys geometries to pent, assigns ids starting from id; takes mass and density from the StatObj properties if not set in pgp - // for compound objects calls PhysicalizeSubobjects - // returns the physical id of the last physicalized part - virtual int Physicalize(IPhysicalEntity* pent, pe_geomparams* pgp, int id = 0, const char* szPropsOverride = 0) = 0; - - virtual bool IsDeformable() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Save contents of static object to the CGF file. - ////////////////////////////////////////////////////////////////////////// - // Save object to the CGF file. - // Arguments: - // sFilename - // Filename of the CGF file. - // Note that the function fails if pOutChunkFile is NULL and the path - // to the file does not exist on the drive. You can call - // CFileUtil::CreatePath() before SaveToCGF() call to create all - // folders that do not exist yet. - // pOutChunkFile - // Optional output parameter. If it is specified then the file will not be written to - // the drive but instead the function returns a pointer to the IChunkFile interface with - // filled CGF chunks. Caller of the function is responsible to call Release method - // of IChunkFile to release it later. - virtual bool SaveToCGF(const char* sFilename, IChunkFile** pOutChunkFile = NULL, bool bHavePhysicalProxy = false) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Summary: - // Clones static geometry, Makes an exact copy of the Static object and the contained geometry. - //virtual IStatObj* Clone(bool bCloneChildren=true, bool nDynamic=false) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Summary: - // Clones static geometry, Makes an exact copy of the Static object and the contained geometry. - virtual IStatObj* Clone(bool bCloneGeometry, bool bCloneChildren, bool bMeshesOnly) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Summary: - // makes sure that both objects have one-to-one vertex correspondance - // sets MorphBuddy for this object's render mesh - // returns 0 if failed (due to objects having no vertex maps most likely) - virtual int SetDeformationMorphTarget(IStatObj* pDeformed) = 0; - - // chages the weights of the deformation morphing according to point, radius, and strength - // (radius==0 updates all weights of all vertices) - // if the object is a compound object, updates the weights of its subobjects that have deformation morphs; clones the object if necessary - // otherwise, updates the weights passed as a pWeights param - virtual IStatObj* DeformMorph(const Vec3& pt, float r, float strength, IRenderMesh* pWeights = 0) = 0; - - // hides all non-physicalized geometry, clones the object if necessary - virtual IStatObj* HideFoliage() = 0; - - // serializes the StatObj's mesh into a stream - virtual int Serialize(TSerialize ser) = 0; - - // Get object properties as loaded from CGF. - virtual const char* GetProperties() = 0; - - // Get physical properties specified for object. - virtual bool GetPhysicalProperties(float& mass, float& density) = 0; - - // Returns the last B operand for this object as A, along with its relative scale - virtual IStatObj* GetLastBooleanOp(float& scale) = 0; - - // Intersect ray with static object. - // Ray must be in object local space. - virtual bool RayIntersection(SRayHitInfo& hitInfo, _smart_ptr<IMaterial> pCustomMtl = 0) = 0; - - // Intersect lineseg with static object. Works on dedi server as well. - // Lineseg must be in object local space. Returns the hit position and the surface type id of the point hit. - virtual bool LineSegIntersection(const Lineseg& lineSeg, Vec3& hitPos, int& surfaceTypeId) = 0; - - // Debug Draw this static object. - virtual void DebugDraw(const struct SGeometryDebugDrawInfo& info, float fExtrdueScale = 0.01f) = 0; - - // Fill statistics about the level. - virtual void GetStatistics(SStatistics& stats) = 0; - - // Returns initial hide mask - virtual uint64 GetInitialHideMask() = 0; - - // Updates hide mask as new mask = (mask & maskAND) | maskOR - virtual uint64 UpdateInitialHideMask(uint64 maskAND = 0ul - 1ul, uint64 maskOR = 0) = 0; - - // Set the filename of the mesh of the next state (for example damaged version) - virtual void SetStreamingDependencyFilePath(const char* szFileName) = 0; - - virtual void ComputeGeometricMean(SMeshLodInfo& lodInfo) = 0; - - // Returns the distance for the first LOD switch. Used for brushes and vegetation. - virtual float GetLodDistance() const = 0; - - // Returns true if the mesh has been stripped - virtual bool IsMeshStrippedCGF() const = 0; - - virtual void LoadLowLODs(bool bUseStreaming, unsigned long nLoadingFlags) = 0; - - // Indicates if lods have been loaded - virtual bool AreLodsLoaded() const = 0; - - // Indicates if a garbage check should be done - virtual bool CheckGarbage() const = 0; - - // Sets state of check garbage flags - virtual void SetCheckGarbage(bool val) = 0; - - // Returns the number of child references - virtual int CountChildReferences() const = 0; - - // Returns the user count - virtual int GetUserCount() const = 0; - - // Shutdown - virtual void ShutDown() = 0; - - virtual int GetMaxUsableLod() const = 0; - virtual int GetMinUsableLod() const = 0; - - virtual SMeshBoneMapping_uint8* GetBoneMapping() const = 0; - - virtual int GetSpineCount() const = 0; - virtual SSpine* GetSpines() const = 0; - - virtual IStatObj* GetLodLevel0() = 0; - virtual void SetLodLevel0(IStatObj* lod) = 0; - virtual _smart_ptr<CStatObj>* GetLods() = 0; - virtual int GetLoadedLodsNum() = 0; - - virtual bool UpdateStreamableComponents(float fImportance, const Matrix34A& objMatrix, bool bFullUpdate, int nNewLod) = 0; - - virtual void RenderInternal(CRenderObject* pRenderObject, uint64 nSubObjectHideMask, const CLodValue& lodValue, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter, bool forceStaticDraw) = 0; - virtual void RenderObjectInternal(CRenderObject* pRenderObject, int nLod, uint8 uLodDissolveRef, bool dissolveOut, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter, bool forceStaticDraw) = 0; - virtual void RenderSubObject(CRenderObject* pRenderObject, int nLod, int nSubObjId, const Matrix34A& renderTM, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter, bool forceStaticDraw) = 0; - virtual void RenderSubObjectInternal(CRenderObject* pRenderObject, int nLod, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter, bool forceStaticDraw) = 0; - virtual void RenderRenderMesh(CRenderObject* pObj, struct SInstancingInfo* pInstInfo, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter) = 0; - - virtual SPhysGeomArray& GetArrPhysGeomInfo() = 0; - virtual bool IsLodsAreLoadedFromSeparateFile() = 0; - - virtual void StartStreaming(bool bFinishNow, IReadStream_AutoPtr* ppStream) = 0; - virtual void UpdateStreamingPrioriryInternal(const Matrix34A& objMatrix, float fDistance, bool bFullUpdate) = 0; - - virtual void SetMerged(bool state) = 0; - - virtual int GetRenderMeshMemoryUsage() const = 0; - virtual void SetLodObject(int nLod, IStatObj* pLod) = 0; - virtual int GetLoadedTrisCount() const = 0; - virtual int GetRenderTrisCount() const = 0; - virtual int GetRenderMatIds() const = 0; - - virtual bool IsUnmergable() const = 0; - virtual void SetUnmergable(bool state) = 0; - - virtual int GetSubObjectMeshCount() const = 0; - virtual void SetSubObjectMeshCount(int count) = 0; - virtual void CleanUnusedLods() = 0; - - virtual AZStd::vector<SMeshColor>& GetClothData() = 0; -}; diff --git a/Code/CryEngine/CryCommon/IStereoRenderer.h b/Code/CryEngine/CryCommon/IStereoRenderer.h deleted file mode 100644 index b75269264c..0000000000 --- a/Code/CryEngine/CryCommon/IStereoRenderer.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef __ISTEREORENDERER_H__ -#define __ISTEREORENDERER_H__ - -#pragma once - -#include "StereoRendererBus.h" - -enum EStereoEye -{ - STEREO_EYE_LEFT = 0, - STEREO_EYE_RIGHT = 1, - STEREO_EYE_COUNT -}; - -enum EStereoDevice -{ - STEREO_DEVICE_NONE = 0, - STEREO_DEVICE_FRAMECOMP = 1, - STEREO_DEVICE_HDMI = 2, - STEREO_DEVICE_DRIVER = 3, //!< Nvidia and AMD drivers. - STEREO_DEVICE_DUALHEAD = 4, - STEREO_DEVICE_COUNT, - - STEREO_DEVICE_DEFAULT = 100 //!< Auto-detect device. -}; - -enum EStereoMode -{ - STEREO_MODE_NO_STEREO = 0, //!< Stereo disabled. - STEREO_MODE_DUAL_RENDERING = 1, - STEREO_MODE_COUNT, -}; - -enum EStereoOutput -{ - STEREO_OUTPUT_STANDARD = 0, - STEREO_OUTPUT_IZ3D = 1, - STEREO_OUTPUT_CHECKERBOARD = 2, - STEREO_OUTPUT_ABOVE_AND_BELOW = 3, - STEREO_OUTPUT_SIDE_BY_SIDE = 4, - STEREO_OUTPUT_LINE_BY_LINE = 5, - STEREO_OUTPUT_ANAGLYPH = 6, - STEREO_OUTPUT_HMD = 7, - STEREO_OUTPUT_COUNT, -}; - -enum EStereoDeviceState -{ - STEREO_DEVSTATE_OK = 0, - STEREO_DEVSTATE_UNSUPPORTED_DEVICE, - STEREO_DEVSTATE_REQ_1080P, - STEREO_DEVSTATE_REQ_FRAMEPACKED, - STEREO_DEVSTATE_BAD_DRIVER, - STEREO_DEVSTATE_REQ_FULLSCREEN -}; - -class IStereoRenderer - : public AZ::StereoRendererRequestBus::Handler -{ -public: - enum EHmdRender - { - eHR_Eyes = 0, - eHR_Latency - }; - - // <interfuscator:shuffle> - virtual ~IStereoRenderer(){} - - virtual EStereoDevice GetDevice() = 0; - virtual EStereoDeviceState GetDeviceState() = 0; - virtual void GetInfo(EStereoDevice* device, EStereoMode* mode, EStereoOutput* output, EStereoDeviceState* state) const = 0; - - virtual bool GetStereoEnabled() = 0; - virtual float GetStereoStrength() = 0; - virtual float GetMaxSeparationScene(bool half = true) = 0; - virtual float GetZeroParallaxPlaneDist() = 0; - - virtual void OnHmdDeviceChanged() = 0; - - virtual void OnResolutionChanged() {} - - virtual void GetNVControlValues(bool& stereoEnabled, float& stereoStrength) = 0; - // </interfuscator:shuffle> - - enum class Status - { - kRenderingFirstEye, - kRenderingSecondEye, - kIdle ///< Not currently rendering to either eye. - }; - - virtual Status GetStatus() const = 0; -}; - -#endif diff --git a/Code/CryEngine/CryCommon/ISurfaceType.h b/Code/CryEngine/CryCommon/ISurfaceType.h deleted file mode 100644 index b9fcad4633..0000000000 --- a/Code/CryEngine/CryCommon/ISurfaceType.h +++ /dev/null @@ -1,243 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Defines interfaces to access Surface Types. - - -#ifndef CRYINCLUDE_CRYCOMMON_ISURFACETYPE_H -#define CRYINCLUDE_CRYCOMMON_ISURFACETYPE_H -#pragma once - -////////////////////////////////////////////////////////////////////////// -// Flags that ISurfaceType::GetFlags() can return. -////////////////////////////////////////////////////////////////////////// -enum ESurfaceTypeFlags -{ - SURFACE_TYPE_NO_PHYSICALIZE = BIT(1), // This surface should not be physicalized. - SURFACE_TYPE_NO_COLLIDE = BIT(2), // Should only be set for vegetation canopy mats - SURFACE_TYPE_VEHICLE_ONLY_COLLISION = BIT(3), - SURFACE_TYPE_CAN_SHATTER = BIT(4), // This surface type can shatter - SURFACE_TYPE_BULLET_PIERCEABLE = BIT(5), // This surface is pierceable by bullets (used by MFX system to spawn front/back FX) -}; - -// Parameter structure passed to ISurfaceType::Execute -struct SSurfaceTypeExecuteParams -{ - Vec3 hitPoint; - Vec3 hitNormal; - int hitType; -}; - -#define SURFACE_BREAKAGE_TYPE(x) x - -////////////////////////////////////////////////////////////////////////// -// Surface definition. -////////////////////////////////////////////////////////////////////////// -struct ISurfaceType -{ - ////////////////////////////////////////////////////////////////////////// - struct SSurfaceTypeAIParams - { - float fImpactRadius; - float fImpactSoundRadius; - float fFootStepRadius; - float proneMult; - float crouchMult; - float movingMult; - - SSurfaceTypeAIParams() - { - fImpactRadius = 2.5f; - fImpactSoundRadius = 20.0f; - fFootStepRadius = 20.0f; - proneMult = 0.2f; - crouchMult = 0.5f; - movingMult = 2.5f; - } - }; - struct SPhysicalParams - { - int breakable_id; - int break_energy; - float hole_size; - float hole_size_explosion; - float hit_radius; - float hit_points; - float hit_points_secondary; - float hit_maxdmg; - float hit_lifetime; - int pierceability; - float damage_reduction; - float ric_angle; - float ric_dam_reduction; - float ric_vel_reduction; - float friction; - float bouncyness; - int iBreakability; - int collType; - float sound_obstruction; - }; - struct SBreakable2DParams - { - string particle_effect; - float blast_radius; - float blast_radius_first; - float vert_size_spread; - int rigid_body; - float life_time; - float cell_size; - int max_patch_tris; - float filter_angle; - float shard_density; - int use_edge_alpha; - float crack_decal_scale; - string crack_decal_mtl; - float max_fracture; - string full_fracture_fx; - string fracture_fx; - int no_procedural_full_fracture; - string broken_mtl; - float destroy_timeout; - float destroy_timeout_spread; - - SBreakable2DParams() - : blast_radius(0) - , rigid_body(0) - , life_time(0) - , cell_size(0) - , max_patch_tris(0) - , shard_density(0) - , crack_decal_scale(0) - , max_fracture(1.0f) - , vert_size_spread(0) - , filter_angle(0) - , use_edge_alpha(0) - , blast_radius_first(0) - , no_procedural_full_fracture(0) - , destroy_timeout(0) - , destroy_timeout_spread(0) {} - }; - struct SBreakageParticles - { - string type; - string particle_effect; - int count_per_unit; - float count_scale; - float scale; - SBreakageParticles() - : count_per_unit(1) - , count_scale(1) - , scale(1) {} - }; - - // <interfuscator:shuffle> - virtual ~ISurfaceType(){} - - // Releases surface type. - virtual void Release() = 0; - - // Return unique Id of this surface type. - // Maximum of 65535 simultanious surface types can exist. - virtual uint16 GetId() const = 0; - - // Unique name of the surface type. - virtual const char* GetName() const = 0; - - // Typename of this surface type. - virtual const char* GetType() const = 0; - - // Flags of the surface type. - // Return: - // A combination of ESurfaceTypeFlags flags. - virtual int GetFlags() const = 0; - - // Execute material. - virtual void Execute(SSurfaceTypeExecuteParams& params) = 0; - - // returns a some cached properties for faster access - virtual int GetBreakability() const = 0; - virtual float GetBreakEnergy() const = 0; - virtual int GetHitpoints() const = 0; - - ////////////////////////////////////////////////////////////////////////// - virtual const SPhysicalParams& GetPhyscalParams() = 0; - - // Optional AI Params. - virtual const SSurfaceTypeAIParams* GetAIParams() = 0; - - // Optional params for 2D breakable plane. - virtual SBreakable2DParams* GetBreakable2DParams() = 0; - virtual SBreakageParticles* GetBreakageParticles(const char* sType, bool bLookInDefault = true) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Called by Surface manager. - ////////////////////////////////////////////////////////////////////////// - // Loads surface, (do not use directly). - virtual bool Load(int nId) = 0; - // </interfuscator:shuffle> -}; - -////////////////////////////////////////////////////////////////////////// -// Description: -// This interface is used to enumerate all items registered to the surface type manager. -////////////////////////////////////////////////////////////////////////// -struct ISurfaceTypeEnumerator -{ - // <interfuscator:shuffle> - virtual ~ISurfaceTypeEnumerator(){} - virtual void Release() = 0; - virtual ISurfaceType* GetFirst() = 0; - virtual ISurfaceType* GetNext() = 0; - // </interfuscator:shuffle> -}; - -// Description: -// Manages loading and mapping of physical surface materials to Ids and materials scripts. -// Behaviour: -// At start will enumerate all material names. -// When the surface is first time requested by name it will be loaded and cached -// and new unique id will be generated for it. -struct ISurfaceTypeManager -{ - // <interfuscator:shuffle> - virtual ~ISurfaceTypeManager(){} - - - // Description: - // Load Surface types - virtual void LoadSurfaceTypes() = 0; - - // Description: - // Return surface type by name. - // If surface is not yet loaded it will be loaded and and cached. - // Arguments: - // sName - Name of the surface type ("mat_metal","mat_wood", etc..) - // warn - print warning message if surface not found - virtual ISurfaceType* GetSurfaceTypeByName(const char* sName, const char* sWhy = NULL, bool warn = true) = 0; - - // Description: - // Return surface type by id. - // If surface is not yet loaded it will be loaded and and cached. - // Arguments: - // sName - Name of the surface type ("mat_metal","mat_wood", etc..) - virtual ISurfaceType* GetSurfaceType(int nSurfaceId, const char* sWhy = NULL) = 0; - - // Description: - // Retrieve an interface to the enumerator class that allow to iterate over all surface types. - virtual ISurfaceTypeEnumerator* GetEnumerator() = 0; - - // Register a new surface type. - virtual bool RegisterSurfaceType(ISurfaceType* pSurfaceType, bool bDefault = false) = 0; - virtual void UnregisterSurfaceType(ISurfaceType* pSurfaceType) = 0; - - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - // </interfuscator:shuffle> -}; - -#endif // CRYINCLUDE_CRYCOMMON_ISURFACETYPE_H - diff --git a/Code/CryEngine/CryCommon/ISystem.h b/Code/CryEngine/CryCommon/ISystem.h deleted file mode 100644 index 1a2ffc5a7c..0000000000 --- a/Code/CryEngine/CryCommon/ISystem.h +++ /dev/null @@ -1,1690 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// In Mac, including ISystem without including platform.h first fails because platform.h -// includes CryThread.h which includes CryThread_pthreads.h which uses ISystem (gEnv). -// So plaform.h needs the contents of ISystem.h. -// By including platform.h outside of the guard, we give platform.h the right include order -#include <platform.h> // Needed for LARGE_INTEGER (for consoles). - -#ifndef CRYINCLUDE_CRYCOMMON_ISYSTEM_H -#define CRYINCLUDE_CRYCOMMON_ISYSTEM_H -#pragma once - -#ifdef CRYSYSTEM_EXPORTS -#define CRYSYSTEM_API DLL_EXPORT -#else -#define CRYSYSTEM_API DLL_IMPORT -#endif - -#include "CryAssert.h" -#include "CompileTimeAssert.h" - -#include <AzCore/IO/SystemFile.h> - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define ISYSTEM_H_SECTION_1 1 -#define ISYSTEM_H_SECTION_2 2 -#define ISYSTEM_H_SECTION_3 3 -#define ISYSTEM_H_SECTION_4 4 -#define ISYSTEM_H_SECTION_5 5 -#endif - -//////////////////////////////////////////////////////////////////////////////////////////////// -// Forward declarations -//////////////////////////////////////////////////////////////////////////////////////////////// -#include <IXml.h> // <> required for Interfuscator -#include "IValidator.h" // <> required for Interfuscator -#include <ILog.h> // <> required for Interfuscator -#include "CryVersion.h" -#include "smartptr.h" -#include <memory> // shared_ptr -#include <CrySystemBus.h> - -struct ISystem; -struct ILog; -namespace AZ::IO -{ - struct IArchive; -} -struct IConsole; -struct IRemoteConsole; -struct IRenderer; -struct IProcess; -struct ITimer; -struct ICryFont; -struct IMovieSystem; -namespace Audio -{ - struct IAudioSystem; -} // namespace Audio -struct SFileVersion; -struct INameTable; -struct ILevelSystem; -struct IViewSystem; -class ICrySizer; -class IXMLBinarySerializer; -struct IReadWriteXMLSink; -struct IAVI_Reader; -class CPNoise3; -struct ILocalizationManager; -struct IOutputPrintSink; -struct IWindowMessageHandler; - -namespace AZ -{ - namespace IO - { - class FileIOBase; - } -} - -typedef void* WIN_HWND; - -class CCamera; -struct CLoadingTimeProfiler; - -class ICmdLine; - -class ILyShine; - -enum ESystemUpdateFlags -{ - // Summary: - // Special update mode for editor. - ESYSUPDATE_EDITOR = 0x0004 -}; - -// Description: -// Configuration specification, depends on user selected machine specification. -enum ESystemConfigSpec -{ - CONFIG_AUTO_SPEC = 0, - CONFIG_LOW_SPEC = 1, - CONFIG_MEDIUM_SPEC = 2, - CONFIG_HIGH_SPEC = 3, - CONFIG_VERYHIGH_SPEC = 4, - - END_CONFIG_SPEC_ENUM, // MUST BE LAST VALUE. USED FOR ERROR CHECKING. -}; - -// Description: -// Configuration platform. Autodetected at start, can be modified through the editor. -enum ESystemConfigPlatform -{ - CONFIG_INVALID_PLATFORM = 0, - CONFIG_PC = 1, - CONFIG_MAC = 2, - CONFIG_OSX_METAL = 3, - CONFIG_ANDROID = 4, - CONFIG_IOS = 5, - CONFIG_PROVO = 7, - CONFIG_SALEM = 8, - CONFIG_JASPER = 9, - - END_CONFIG_PLATFORM_ENUM, // MUST BE LAST VALUE. USED FOR ERROR CHECKING. -}; - -enum ESystemGlobalState -{ - ESYSTEM_GLOBAL_STATE_UNKNOWN, - ESYSTEM_GLOBAL_STATE_INIT, - ESYSTEM_GLOBAL_STATE_RUNNING, - ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_PREPARE, - ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START, - ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_MATERIALS, - ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_OBJECTS, - ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_STATIC_WORLD, - ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_PRECACHE, - ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_TEXTURES, - ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_END, - ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_COMPLETE -}; - -// Summary: -// System wide events. -enum ESystemEvent -{ - // Description: - // Seeds all random number generators to the same seed number, WParam will hold seed value. - //##@{ - ESYSTEM_EVENT_RANDOM_SEED = 1, - ESYSTEM_EVENT_RANDOM_ENABLE, - ESYSTEM_EVENT_RANDOM_DISABLE, - //##@} - - // Description: - // Changes to main window focus. - // wparam is not 0 is focused, 0 if not focused - ESYSTEM_EVENT_CHANGE_FOCUS = 10, - - // Description: - // Moves of the main window. - // wparam=x, lparam=y - ESYSTEM_EVENT_MOVE = 11, - - // Description: - // Resizes of the main window. - // wparam=width, lparam=height - ESYSTEM_EVENT_RESIZE = 12, - - // Description: - // Activation of the main window. - // wparam=1/0, 1=active 0=inactive - ESYSTEM_EVENT_ACTIVATE = 13, - - // Description: - // Main window position changed. - ESYSTEM_EVENT_POS_CHANGED = 14, - - // Description: - // Main window style changed. - ESYSTEM_EVENT_STYLE_CHANGED = 15, - - // Description: - // Sent before the loading movie is begun - ESYSTEM_EVENT_LEVEL_LOAD_START_PRELOADINGSCREEN, - - // Description: - // Sent before the loading last save - ESYSTEM_EVENT_LEVEL_LOAD_RESUME_GAME, - - // Description: - // Sent before starting level, before game rules initialization and before ESYSTEM_EVENT_LEVEL_LOAD_START event - // Used mostly for level loading profiling - ESYSTEM_EVENT_LEVEL_LOAD_PREPARE, - - // Description: - // Sent to start the active loading screen rendering. - ESYSTEM_EVENT_LEVEL_LOAD_START_LOADINGSCREEN, - - // Description: - // Sent when loading screen is active - ESYSTEM_EVENT_LEVEL_LOAD_LOADINGSCREEN_ACTIVE, - - // Description: - // Sent before starting loading a new level. - // Used for a more efficient resource management. - ESYSTEM_EVENT_LEVEL_LOAD_START, - - // Description: - // Sent after loading a level finished. - // Used for a more efficient resource management. - ESYSTEM_EVENT_LEVEL_LOAD_END, - - // Description: - // Sent after trying to load a level failed. - // Used for resetting the front end. - ESYSTEM_EVENT_LEVEL_LOAD_ERROR, - - // Description: - // Sent in case the level was requested to load, but it's not ready - // Used in streaming install scenario for notifying the front end. - ESYSTEM_EVENT_LEVEL_NOT_READY, - - // Description: - // Sent after precaching of the streaming system has been done - ESYSTEM_EVENT_LEVEL_PRECACHE_START, - - // Description: - // Sent before object/texture precache stream requests are submitted - ESYSTEM_EVENT_LEVEL_PRECACHE_FIRST_FRAME, - - // Description: - // Sent when level loading is completely finished with no more onscreen - // movie or info rendering, and when actual gameplay can start - ESYSTEM_EVENT_LEVEL_GAMEPLAY_START, - - // Level is unloading. - ESYSTEM_EVENT_LEVEL_UNLOAD, - - // Summary: - // Sent after level have been unloaded. For cleanup code. - ESYSTEM_EVENT_LEVEL_POST_UNLOAD, - - // Summary: - // Called when the game framework has been initialized. - ESYSTEM_EVENT_GAME_POST_INIT, - - // Summary: - // Called when the game framework has been initialized, not loading should happen in this event. - ESYSTEM_EVENT_GAME_POST_INIT_DONE, - - // Summary: - // Sent when the system is doing a full shutdown. - ESYSTEM_EVENT_FULL_SHUTDOWN, - - // Summary: - // Sent when the system is doing a fast shutdown. - ESYSTEM_EVENT_FAST_SHUTDOWN, - - // Summary: - // When keyboard layout changed. - ESYSTEM_EVENT_LANGUAGE_CHANGE, - - // Description: - // Toggled fullscreen. - // wparam is 1 means we switched to fullscreen, 0 if for windowed - ESYSTEM_EVENT_TOGGLE_FULLSCREEN, - ESYSTEM_EVENT_SHARE_SHADER_COMBINATIONS, - - // Summary: - // Start 3D post rendering - ESYSTEM_EVENT_3D_POST_RENDERING_START, - - // Summary: - // End 3D post rendering - ESYSTEM_EVENT_3D_POST_RENDERING_END, - - // Summary: - // Called before switching to level memory heap - ESYSTEM_EVENT_SWITCHING_TO_LEVEL_HEAP_DEPRECATED, - - // Summary: - // Called after switching to level memory heap - ESYSTEM_EVENT_SWITCHED_TO_LEVEL_HEAP_DEPRECATED, - - // Summary: - // Called before switching to global memory heap - ESYSTEM_EVENT_SWITCHING_TO_GLOBAL_HEAP_DEPRECATED, - - // Summary: - // Called after switching to global memory heap - ESYSTEM_EVENT_SWITCHED_TO_GLOBAL_HEAP_DEPRECATED, - - // Description: - // Sent after precaching of the streaming system has been done - ESYSTEM_EVENT_LEVEL_PRECACHE_END, - - // Description: - // Sent when game mode switch begins - ESYSTEM_EVENT_GAME_MODE_SWITCH_START, - - // Description: - // Sent when game mode switch ends - ESYSTEM_EVENT_GAME_MODE_SWITCH_END, - - // Description: - // Video notifications - // wparam=[0/1/2/3] : [stop/play/pause/resume] - ESYSTEM_EVENT_VIDEO, - - // Description: - // Sent if the game is paused - ESYSTEM_EVENT_GAME_PAUSED, - - // Description: - // Sent if the game is resumed - ESYSTEM_EVENT_GAME_RESUMED, - - // Description: - // Sent when time of day is set - ESYSTEM_EVENT_TIME_OF_DAY_SET, - - // Description: - // Sent once the Editor finished initialization. - ESYSTEM_EVENT_EDITOR_ON_INIT, - - // Description: - // Sent when frontend is initialised - ESYSTEM_EVENT_FRONTEND_INITIALISED, - - // Description: - // Sent once the Editor switches between in-game and editing mode. - ESYSTEM_EVENT_EDITOR_GAME_MODE_CHANGED, - - // Description: - // Sent once the Editor switches simulation mode (AI/Physics). - ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_CHANGED, - - // Description: - // Sent when frontend is reloaded - ESYSTEM_EVENT_FRONTEND_RELOADED, - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION ISYSTEM_H_SECTION_1 - #include AZ_RESTRICTED_FILE(ISystem_h) -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION ISYSTEM_H_SECTION_2 - #include AZ_RESTRICTED_FILE(ISystem_h) -#endif - ESYSTEM_EVENT_STREAMING_INSTALL_ERROR, - - // Description: - // Sent when the online services are initialized. - ESYSTEM_EVENT_ONLINE_SERVICES_INITIALISED, - - // Description: - // Sent when a new audio implementation is loaded - ESYSTEM_EVENT_AUDIO_IMPLEMENTATION_LOADED, - - // Description: - // Sent when simulation mode switch begins - ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_SWITCH_START, - - // Description: - // Sent when simluation mode switch ends - ESYSTEM_EVENT_EDITOR_SIMULATION_MODE_SWITCH_END, - - ESYSTEM_EVENT_USER = 0x1000, - - ESYSTEM_BEAM_PLAYER_TO_CAMERA_POS -}; - -// Description: -// User defined callback, which can be passed to ISystem. -struct ISystemUserCallback -{ - // <interfuscator:shuffle> - virtual ~ISystemUserCallback() {} - // Description: - // This method is called at the earliest point the ISystem pointer can be used - // the log might not be yet there. - virtual void OnSystemConnect([[maybe_unused]] ISystem* pSystem) {} - - // Summary: - // Signals to User that engine error occurred. - // Return Value: - // True to Halt execution or false to ignore this error - virtual bool OnError(const char* szErrorString) = 0; - - // Notes: - // If working in Editor environment notify user that engine want to Save current document. - // This happens if critical error have occurred and engine gives a user way to save data and not lose it - // due to crash. - virtual bool OnSaveDocument() = 0; - - // Notes: - // If working in Editor environment and a critical error occurs notify the user to backup - // the current document to prevent data loss due to crash. - virtual bool OnBackupDocument() = 0; - - // Description: - // Notifies user that system wants to switch out of current process. - // Example: - // Called when pressing ESC in game mode to go to Menu. - virtual void OnProcessSwitch() = 0; - - // Description: - // Notifies user, usually editor, about initialization progress in system. - virtual void OnInitProgress(const char* sProgressMsg) = 0; - - // Description: - // Initialization callback. This is called early in CSystem::Init(), before - // any of the other callback methods is called. - // See also: - // CSystem::Init() - virtual void OnInit(ISystem*) { } - - // Summary: - // Shutdown callback. - virtual void OnShutdown() { } - - // Summary: - // Quit callback. - // See also: - // CSystem::Quit() - virtual void OnQuit() { } - - // Description: - // Notify user of an update iteration. Called in the update loop. - virtual void OnUpdate() { } - - // Description: - // Show message by provider. - virtual int ShowMessage(const char* text, const char* caption, unsigned int uType) { return CryMessageBox(text, caption, uType); } - - // Description: - // Collects the memory information in the user program/application. - virtual void GetMemoryUsage(ICrySizer* pSizer) = 0; - // </interfuscator:shuffle> - - // Post console load, for cvar setting - virtual void OnConsoleCreated([[maybe_unused]] ::IConsole* pConsole) {} -}; - -// Description: -// Interface used for getting notified when a system event occurs. -struct ISystemEventListener -{ - // <interfuscator:shuffle> - virtual ~ISystemEventListener() {} - virtual void OnSystemEventAnyThread([[maybe_unused]] ESystemEvent event, [[maybe_unused]] UINT_PTR wparam, [[maybe_unused]] UINT_PTR lparam) {} - virtual void OnSystemEvent([[maybe_unused]] ESystemEvent event, [[maybe_unused]] UINT_PTR wparam, [[maybe_unused]] UINT_PTR lparam) { } - // </interfuscator:shuffle> -}; - -// Description: -// Structure used for getting notified when a system event occurs. -struct ISystemEventDispatcher -{ - // <interfuscator:shuffle> - virtual ~ISystemEventDispatcher() {} - virtual bool RegisterListener(ISystemEventListener* pListener) = 0; - virtual bool RemoveListener(ISystemEventListener* pListener) = 0; - - virtual void OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam) = 0; - virtual void Update() = 0; - - //virtual void OnLocaleChange() = 0; - // </interfuscator:shuffle> -}; - -struct IErrorObserver -{ - // <interfuscator:shuffle> - virtual ~IErrorObserver() {} - virtual void OnAssert(const char* condition, const char* message, const char* fileName, unsigned int fileLineNumber) = 0; - virtual void OnFatalError(const char* message) = 0; - // </interfuscator:shuffle> -}; - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION ISYSTEM_H_SECTION_3 - #include AZ_RESTRICTED_FILE(ISystem_h) -#endif - -namespace AZ -{ - namespace Internal - { - class EnvironmentInterface; - } // namespace Internal -} // namespace AZ - -typedef AZ::Internal::EnvironmentInterface SharedEnvironmentInstance; - -// Description: -// Structure passed to Init method of ISystem interface. -struct SSystemInitParams -{ - void* hInstance; // - void* hWnd; // - - 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). - ISystemUserCallback* pUserCallback; - const char* sLogFileName; // File name to use for log. - bool autoBackupLogs; // if true, logs will be automatically backed up each startup - IOutputPrintSink* pPrintSync; // Print Sync which can be used to catch all output from engine - char szSystemCmdLine[2048]; // Command line. - - bool bEditor; // When running in Editor mode. - 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 bSkipConsole; // Don't create console - 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 bToolMode; // System is running inside a tool. Will not create USER directory or anything else that the game needs to do - - ISystem* pSystem; // Pointer to existing ISystem interface, it will be reused if not NULL. - - SharedEnvironmentInstance* pSharedEnvironment; - - // Summary: - // Initialization defaults. - SSystemInitParams() - { - hInstance = NULL; - hWnd = NULL; - - pLog = NULL; - pLogCallback = NULL; - pUserCallback = NULL; - sLogFileName = NULL; - autoBackupLogs = true; - pPrintSync = NULL; - memset(szSystemCmdLine, 0, sizeof(szSystemCmdLine)); - - bEditor = false; - bPreview = false; - bTestMode = false; - bDedicatedServer = false; - bSkipConsole = false; - bUnattendedMode = false; - bSkipMovie = false; - bToolMode = false; - - pSystem = NULL; - - pSharedEnvironment = nullptr; - } -}; - -// Notes: -// Can be used for LoadConfiguration(). -// See also: -// LoadConfiguration() -struct ILoadConfigurationEntrySink -{ - // <interfuscator:shuffle> - virtual ~ILoadConfigurationEntrySink() {} - virtual void OnLoadConfigurationEntry(const char* szKey, const char* szValue, const char* szGroup) = 0; - virtual void OnLoadConfigurationEntry_End() {} - // </interfuscator:shuffle> -}; - -struct SPlatformInfo -{ - unsigned int numCoresAvailableToProcess; - unsigned int numLogicalProcessors; - -#if defined(WIN32) || defined(WIN64) - enum EWinVersion - { - WinUndetected, - Win2000, - WinXP, - WinSrv2003, - WinVista, - Win7, - Win8, - Win81, - Win10 - }; - - EWinVersion winVer; - bool win64Bit; - bool vistaKB940105Required; -#endif -}; - -// Description: -// Holds info about system update stats over perior of time (cvar-tweakable) - -struct SSystemUpdateStats -{ - SSystemUpdateStats() - : avgUpdateTime(0.0f) - , minUpdateTime(0.0f) - , maxUpdateTime(0.0f) {} - float avgUpdateTime; - float minUpdateTime; - float maxUpdateTime; -}; - -// Description: -// Global environment. -// Contains pointers to all global often needed interfaces. -// This is a faster way to get interface pointer then calling ISystem interface to retrieve one. -// Notes: -// Some pointers can be NULL, use with care. -// See also: -// ISystem -struct SSystemGlobalEnvironment -{ - AZ::IO::IArchive* pCryPak; - AZ::IO::FileIOBase* pFileIO; - ITimer* pTimer; - ICryFont* pCryFont; - ::IConsole* pConsole; - ISystem* pSystem = nullptr; - ILog* pLog; - IMovieSystem* pMovieSystem; - INameTable* pNameTable; - IRenderer* pRenderer; - ILyShine* pLyShine; - SharedEnvironmentInstance* pSharedEnvironment; - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION ISYSTEM_H_SECTION_4 - #include AZ_RESTRICTED_FILE(ISystem_h) -#endif - - threadID mMainThreadId; //The main thread ID is used in multiple systems so should be stored globally - - ////////////////////////////////////////////////////////////////////////// - // Used by CRY_ASSERT - bool bIgnoreAllAsserts; - bool bNoAssertDialog; - ////////////////////////////////////////////////////////////////////////// - - bool bToolMode; - - int retCode = 0; - - ILINE const bool IsDedicated() const - { -#if defined(CONSOLE) - return false; -#else - return bDedicated; -#endif - } - -#if !defined(CONSOLE) - ILINE void SetIsEditor(bool isEditor) - { - bEditor = isEditor; - } - - ILINE void SetIsEditorGameMode(bool isEditorGameMode) - { - bEditorGameMode = isEditorGameMode; - } - - ILINE void SetIsEditorSimulationMode(bool isEditorSimulationMode) - { - bEditorSimulationMode = isEditorSimulationMode; - } - - ILINE void SetIsDedicated(bool isDedicated) - { - bDedicated = isDedicated; - } -#endif - - //this way the compiler can strip out code for consoles - ILINE const bool IsEditor() const - { -#if defined(CONSOLE) - return false; -#else - return bEditor; -#endif - } - - ILINE const bool IsEditorGameMode() const - { -#if defined(CONSOLE) - return false; -#else - return bEditorGameMode; -#endif - } - - ILINE const bool IsEditorSimulationMode() const - { -#if defined(CONSOLE) - return false; -#else - return bEditorSimulationMode; -#endif - } - - ILINE const bool IsEditing() const - { -#if defined(CONSOLE) - return false; -#else - return bEditor && !bEditorGameMode; -#endif - } - - ILINE bool IsInToolMode() const - { - return bToolMode; - } - - ILINE void SetToolMode(bool bNewToolMode) - { - bToolMode = bNewToolMode; - } - -#if !defined(CONSOLE) -private: - 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 - -public: - SSystemGlobalEnvironment() - : bToolMode(false) - { - }; -}; - -// NOTE Nov 25, 2008: <pvl> the ISystem interface that follows has a member function -// called 'GetUserName'. If we don't #undef'ine the same-named Win32 symbol here -// ISystem wouldn't even compile. -// TODO Nov 25, 2008: <pvl> there might be a better place for this? -#ifdef GetUserName -#undef GetUserName -#endif - - -struct IProfilingSystem -{ - // <interfuscator:shuffle> - virtual ~IProfilingSystem() {} - ////////////////////////////////////////////////////////////////////////// - // VTune Profiling interface. - - // Summary: - // Resumes vtune data collection. - virtual void VTuneResume() = 0; - // Summary: - // Pauses vtune data collection. - virtual void VTunePause() = 0; - ////////////////////////////////////////////////////////////////////////// - // </interfuscator:shuffle> -}; - -//////////////////////////////////////////////////////////////////////////////////////////////// - -// Description: -// Main Engine Interface. -// Initialize and dispatch all engine's subsystems. -struct ISystem -{ - // <interfuscator:shuffle> - virtual ~ISystem() {} - // Summary: - // Releases ISystem. - virtual void Release() = 0; - - // Summary: - // Returns pointer to the global environment structure. - virtual SSystemGlobalEnvironment* GetGlobalEnvironment() = 0; - - // Summary: - // Updates all subsystems (including the ScriptSink() ) - // Arguments: - // flags - One or more flags from ESystemUpdateFlags structure. - // nPauseMode - 0=normal(no pause), 1=menu/pause, 2=cutscene - virtual bool UpdatePreTickBus(int updateFlags = 0, int nPauseMode = 0) = 0; - - // Summary: - // Updates all subsystems (including the ScriptSink() ) - // Arguments: - // flags - One or more flags from ESystemUpdateFlags structure. - // nPauseMode - 0=normal(no pause), 1=menu/pause, 2=cutscene - virtual bool UpdatePostTickBus(int updateFlags = 0, int nPauseMode = 0) = 0; - - // Summary: - // Updates only require components during loading - virtual bool UpdateLoadtime() = 0; - - // Summary: - // Optimisation: do part of the update while waiting for occlusion queries to complete - virtual void DoWorkDuringOcclusionChecks() = 0; - virtual bool NeedDoWorkDuringOcclusionChecks() = 0; - - // Summary: - // Retrieve the name of the user currently logged in to the computer. - virtual const char* GetUserName() = 0; - - // Summary: - // Quits the application. - virtual void Quit() = 0; - // Summary: - // Tells the system if it is relaunching or not. - virtual void Relaunch(bool bRelaunch) = 0; - // Summary: - // Returns true if the application is in the shutdown phase. - virtual bool IsQuitting() const = 0; - // Summary: - // Tells the system in which way we are using the serialization system. - virtual void SerializingFile(int mode) = 0; - virtual int IsSerializingFile() const = 0; - - virtual bool IsRelaunch() const = 0; - - // Description: - // Displays error message. - // Logs it to console and file and error message box then terminates execution. - virtual void FatalError(const char* sFormat, ...) PRINTF_PARAMS(2, 3) = 0; - - // Description: - // Reports a bug using the crash handler. - // Logs an error to the console and launches the crash handler, then continues execution. - virtual void ReportBug(const char* sFormat, ...) PRINTF_PARAMS(2, 3) = 0; - - // Description: - // Report warning to current Validator object. - // Doesn't terminate the execution. - //##@{ - virtual void WarningV(EValidatorModule module, EValidatorSeverity severity, int flags, const char* file, const char* format, va_list args) = 0; - virtual void Warning(EValidatorModule module, EValidatorSeverity severity, int flags, const char* file, const char* format, ...) = 0; - //##@} - - // Description: - // Report message by provider or by using CryMessageBox. - // Doesn't terminate the execution. - virtual int ShowMessage(const char* text, const char* caption, unsigned int uType) = 0; - - // Summary: - // Compare specified verbosity level to the one currently set. - virtual bool CheckLogVerbosity(int verbosity) = 0; - - // return the related subsystem interface - - // - virtual IViewSystem* GetIViewSystem() = 0; - virtual ILevelSystem* GetILevelSystem() = 0; - virtual INameTable* GetINameTable() = 0; - virtual ICmdLine* GetICmdLine() = 0; - virtual ILog* GetILog() = 0; - virtual AZ::IO::IArchive* GetIPak() = 0; - virtual ICryFont* GetICryFont() = 0; - virtual IMovieSystem* GetIMovieSystem() = 0; - virtual ::IConsole* GetIConsole() = 0; - virtual IRemoteConsole* GetIRemoteConsole() = 0; - virtual IProfilingSystem* GetIProfilingSystem() = 0; - virtual ISystemEventDispatcher* GetISystemEventDispatcher() = 0; - - virtual ITimer* GetITimer() = 0; - - // Arguments: - // bValue - Set to true when running on a cheat protected server or a client that is connected to it (not used in singleplayer). - virtual void SetForceNonDevMode(bool bValue) = 0; - // Return Value: - // True when running on a cheat protected server or a client that is connected to it (not used in singleplayer). - virtual bool GetForceNonDevMode() const = 0; - virtual bool WasInDevMode() const = 0; - virtual bool IsDevMode() const = 0; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // IXmlNode interface. - ////////////////////////////////////////////////////////////////////////// - - // Summary: - // Creates new xml node. - virtual XmlNodeRef CreateXmlNode(const char* sNodeName = "", bool bReuseStrings = false, bool bIsProcessingInstruction = false) = 0; - // Summary: - // Loads xml from memory buffer, returns 0 if load failed. - virtual XmlNodeRef LoadXmlFromBuffer(const char* buffer, size_t size, bool bReuseStrings = false, bool bSuppressWarnings = false) = 0; - // Summary: - // Loads xml file, returns 0 if load failed. - virtual XmlNodeRef LoadXmlFromFile(const char* sFilename, bool bReuseStrings = false) = 0; - // Summary: - // Retrieves access to XML utilities interface. - virtual IXmlUtils* GetXmlUtils() = 0; - - virtual void SetViewCamera(CCamera& Camera) = 0; - virtual CCamera& GetViewCamera() = 0; - - // Description: - // When ignore update sets to true, system will ignore and updates and render calls. - virtual void IgnoreUpdates(bool bIgnore) = 0; - - // Summary: - // Sets the active process - // Arguments: - // process - A pointer to a class that implement the IProcess interface. - virtual void SetIProcess(IProcess* process) = 0; - - // Summary: - // Gets the active process. - // Return Value: - // A pointer to the current active process. - virtual IProcess* GetIProcess() = 0; - - // Return Value: - // True if system running in Test mode. - virtual bool IsTestMode() const = 0; - - ////////////////////////////////////////////////////////////////////////// - // File version. - ////////////////////////////////////////////////////////////////////////// - - // Summary: - // Gets file version. - virtual const SFileVersion& GetFileVersion() = 0; - // Summary: - // Gets product version. - virtual const SFileVersion& GetProductVersion() = 0; - // Summary: - // Gets build version. - virtual const SFileVersion& GetBuildVersion() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Configuration. - ////////////////////////////////////////////////////////////////////////// - - // Summary: - // Loads configurations from CVarGroup directory recursively - // If m_GraphicsSettingsMap is defined (in Graphics Settings Dialog box), fills in mapping based on sys_spec_Full - // Arguments: - // sPath - e.g. "Game/Config/CVarGroups" - virtual void AddCVarGroupDirectory(const string& sPath) = 0; - - // Summary: - // Saves system configuration. - virtual void SaveConfiguration() = 0; - - // Summary: - // Loads system configuration - // Arguments: - // pCallback - 0 means normal LoadConfigVar behaviour is used - virtual void LoadConfiguration(const char* sFilename, ILoadConfigurationEntrySink* pSink = 0, bool warnIfMissing = true) = 0; - - virtual ESystemConfigSpec GetMaxConfigSpec() const = 0; - - ////////////////////////////////////////////////////////////////////////// - - // Summary: - // Retrieves current configuration platform - virtual ESystemConfigPlatform GetConfigPlatform() const = 0; - - // Summary: - // Changes current configuration platform. - virtual void SetConfigPlatform(ESystemConfigPlatform platform) = 0; - ////////////////////////////////////////////////////////////////////////// - - // Summary: - // Query if system is now paused. - // Pause flag is set when calling system update with pause mode. - virtual bool IsPaused() const = 0; - - // Summary: - // Retrieves localized strings manager interface. - virtual ILocalizationManager* GetLocalizationManager() = 0; - - // Summary: - // Retrieves the perlin noise singleton instance. - virtual CPNoise3* GetNoiseGen() = 0; - - // Summary: - // Retrieves system update counter. - virtual uint64 GetUpdateCounter() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Error callback handling - - // Summary: - // Registers listeners to CryAssert and error messages. (may not be called if asserts are disabled) - // Each pointer can be registered only once. (stl::push_back_unique) - // It will return false if the pointer is already registered. Returns true, otherwise. - virtual bool RegisterErrorObserver(IErrorObserver* errorObserver) = 0; - - // Summary: - // Unregisters listeners to CryAssert and error messages. - // It will return false if the pointer is not registered. Otherwise, returns true. - virtual bool UnregisterErrorObserver(IErrorObserver* errorObserver) = 0; - - // Summary: - // Called after the processing of the assert message box on some platforms. - // It will be called even when asserts are disabled by the console variables. - virtual void OnAssert(const char* condition, const char* message, const char* fileName, unsigned int fileLineNumber) = 0; - - // Summary: - // Returns if the assert window from CryAssert is visible. - // OBS1: needed by the editor, as in some cases it can freeze if during an assert engine it will handle - // some events such as mouse movement in a CryPhysics assert. - // OBS2: it will always return false, if asserts are disabled or ignored. - virtual bool IsAssertDialogVisible() const = 0; - - // Summary: - // Sets the AssertVisisble internal variable. - // Typically it should only be called by CryAssert. - virtual void SetAssertVisible(bool bAssertVisble) = 0; - ////////////////////////////////////////////////////////////////////////// - - // Summary: - // Enable/Disable drawing the console - virtual void SetConsoleDrawEnabled(bool enabled) = 0; - - // Enable/Disable drawing the UI - virtual void SetUIDrawEnabled(bool enabled) = 0; - - // Summary: - // Get the index of the currently running Crytek application. (0 = first instance, 1 = second instance, etc) - virtual int GetApplicationInstance() = 0; - - // Summary: - // 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: - // Clear all currently logged and drawn on screen error messages - virtual void ClearErrorMessages() = 0; - ////////////////////////////////////////////////////////////////////////// - // For debugging use only!, query current C++ call stack. - ////////////////////////////////////////////////////////////////////////// - - // Notes: - // Pass nCount to indicate maximum number of functions to get. - // For debugging use only, query current C++ call stack. - // Description: - // Fills array of function pointers, nCount return number of functions. - virtual void debug_GetCallStack(const char** pFunctions, int& nCount) = 0; - // Summary: - // Logs current callstack. - // Notes: - // For debugging use only!, query current C++ call stack. - virtual void debug_LogCallStack(int nMaxFuncs = 32, int nFlags = 0) = 0; - - // Description: - // Execute command line arguments. - // Should be after init game. - // Example: - // +g_gametype ASSAULT +map "testy" - virtual void ExecuteCommandLine(bool deferred=true) = 0; - - // Description: - // GetSystemUpdate stats (all systems update without except console) - // very useful on dedicated server as we throttle it to fixed frequency - // returns zeroes if no updates happened yet - virtual void GetUpdateStats(SSystemUpdateStats& stats) = 0; - - virtual ESystemGlobalState GetSystemGlobalState(void) = 0; - virtual void SetSystemGlobalState(ESystemGlobalState systemGlobalState) = 0; - -#if !defined(_RELEASE) - virtual bool IsSavingResourceList() const = 0; -#endif - - // Summary: - // Gets the root window message handler function - // The returned pointer is platform-specific: - // For Windows OS, the pointer is of type WNDPROC - virtual void* GetRootWindowMessageHandler() = 0; - - // Summary: - // Register a IWindowMessageHandler that will be informed about window messages - // The delivered messages are platform-specific - virtual void RegisterWindowMessageHandler(IWindowMessageHandler* pHandler) = 0; - - // Summary: - // Unregister an IWindowMessageHandler that was previously registered using RegisterWindowMessageHandler - virtual void UnregisterWindowMessageHandler(IWindowMessageHandler* pHandler) = 0; - - // Create an instance of a Local File IO object (which reads directly off the local filesystem, instead of, - // for example, reading from the network or a pack or USB or such. - virtual std::shared_ptr<AZ::IO::FileIOBase> CreateLocalFileIO() = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////// - // EBus interface used to listen for cry system notifications - class CrySystemNotifications : public AZ::EBusTraits - { - public: - virtual ~CrySystemNotifications() = default; - - // Override to be notified right before the call to ISystem::Render - virtual void OnPreRender() {} - - // Override to be notified right after the call to ISystem::Render (but before RenderEnd) - virtual void OnPostRender() {} - }; - using CrySystemNotificationBus = AZ::EBus<CrySystemNotifications>; -}; - -#if defined(USE_DISK_PROFILER) - -struct DiskOperationInfo -{ - DiskOperationInfo() - : m_nSeeksCount(0) - , m_nFileOpenCount(0) - , m_nFileReadCount(0) - , m_dOperationSize(0.) - , m_dOperationTime(0.) {} - int m_nSeeksCount; - int m_nFileOpenCount; - int m_nFileReadCount; - double m_dOperationTime; - double m_dOperationSize; - - DiskOperationInfo& operator -= (const DiskOperationInfo& rv) - { - m_nSeeksCount -= rv.m_nSeeksCount; - m_nFileOpenCount -= rv.m_nFileOpenCount; - m_nFileReadCount -= rv.m_nFileReadCount; - m_dOperationSize -= rv.m_dOperationSize; - m_dOperationTime -= rv.m_dOperationTime; - return *this; - } - - DiskOperationInfo& operator += (const DiskOperationInfo& rv) - { - m_nSeeksCount += rv.m_nSeeksCount; - m_nFileOpenCount += rv.m_nFileOpenCount; - m_nFileReadCount += rv.m_nFileReadCount; - m_dOperationSize += rv.m_dOperationSize; - m_dOperationTime += rv.m_dOperationTime; - return *this; - } - - DiskOperationInfo operator - (const DiskOperationInfo& rv) - { - DiskOperationInfo res(*this); - return res -= rv; - } - - DiskOperationInfo operator + (const DiskOperationInfo& rv) - { - DiskOperationInfo res(*this); - return res += rv; - } -}; - -#endif - -#if defined(ENABLE_LOADING_PROFILER) && AZ_PROFILE_TELEMETRY - -#define LOADING_TIME_PROFILE_SECTION AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzCore) -#define LOADING_TIME_PROFILE_SECTION_ARGS(...) AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, __VA_ARGS__) -#define LOADING_TIME_PROFILE_SECTION_NAMED(sectionName) AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::AzCore, sectionName) -#define LOADING_TIME_PROFILE_SECTION_NAMED_ARGS(sectionName, ...) AZ_PROFILE_SCOPE_DYNAMIC(AZ::Debug::ProfileCategory::AzCore, sectionName, __VA_ARGS__) - -#else - -#define LOADING_TIME_PROFILE_SECTION -#define LOADING_TIME_PROFILE_SECTION_ARGS(...) -#define LOADING_TIME_PROFILE_SECTION_NAMED(sectionName) -#define LOADING_TIME_PROFILE_SECTION_NAMED_ARGS(sectionName, ...) - -#endif - -////////////////////////////////////////////////////////////////////////// -// CrySystem DLL Exports. -////////////////////////////////////////////////////////////////////////// -typedef ISystem* (*PFNCREATESYSTEMINTERFACE)(SSystemInitParams& initParams); - - -////////////////////////////////////////////////////////////////////////// -// Global environment variable. -////////////////////////////////////////////////////////////////////////// -extern SSystemGlobalEnvironment* gEnv; - - -// Summary: -// Gets the system interface. -inline ISystem* GetISystem() -{ - // Some unit tests temporarily install and then uninstall ISystem* mocks. - // It is generally okay for runtime and tool systems which call this function to cache the returned pointer, - // because their lifetime is usually shorter than the lifetime of the ISystem* implementation. - // It is NOT safe for this function to cache it as a static itself, though, as the static it would cache - // it inside may outlive the the actual instance implementing ISystem* when unit tests are torn down and then restarted. - ISystem* systemInterface = gEnv ? gEnv->pSystem : nullptr; - if (!systemInterface) - { - CrySystemRequestBus::BroadcastResult(systemInterface, &CrySystemRequests::GetCrySystem); - } - return systemInterface; -}; -////////////////////////////////////////////////////////////////////////// - -// Description: -// This function must be called once by each module at the beginning, to setup global pointers. -extern "C" AZ_DLL_EXPORT void ModuleInitISystem(ISystem* pSystem, const char* moduleName); -extern "C" AZ_DLL_EXPORT void ModuleShutdownISystem(ISystem* pSystem); -extern "C" AZ_DLL_EXPORT void InjectEnvironment(void* env); -extern "C" AZ_DLL_EXPORT void DetachEnvironment(); - -void* GetModuleInitISystemSymbol(); -void* GetModuleShutdownISystemSymbol(); -void* GetInjectEnvironmentSymbol(); -void* GetDetachEnvironmentSymbol(); - -#define PREVENT_MODULE_AND_ENVIRONMENT_SYMBOL_STRIPPING \ - AZ_UNUSED(GetModuleInitISystemSymbol()); \ - AZ_UNUSED(GetModuleShutdownISystemSymbol()); \ - AZ_UNUSED(GetInjectEnvironmentSymbol()); \ - AZ_UNUSED(GetDetachEnvironmentSymbol()); - - -extern bool g_bProfilerEnabled; - -// Summary: -// Interface of the DLL. -extern "C" -{ - CRYSYSTEM_API ISystem* CreateSystemInterface(const SSystemInitParams& initParams); -} - -// Description: -// Displays error message. -// Logs it to console and file and error message box. -// Then terminates execution. -void CryFatalError(const char*, ...) PRINTF_PARAMS(1, 2); -inline void CryFatalError(const char* format, ...) -{ - if (!gEnv || !gEnv->pSystem) - { - return; - } - - va_list ArgList; - char szBuffer[MAX_WARNING_LENGTH]; - va_start(ArgList, format); - int count = azvsnprintf(szBuffer, sizeof(szBuffer), format, ArgList); - if (count == -1 || count >= sizeof(szBuffer)) - { - szBuffer[sizeof(szBuffer) - 1] = '\0'; - } - va_end(ArgList); - - gEnv->pSystem->FatalError("%s", szBuffer); -} - -////////////////////////////////////////////////////////////////////////// - -// Description: -// Displays warning message. -// Logs it to console and file and display a warning message box. -// Doesn't terminate execution. -void CryWarning(EValidatorModule, EValidatorSeverity, const char*, ...) PRINTF_PARAMS(3, 4); -inline void CryWarning(EValidatorModule module, EValidatorSeverity severity, const char* format, ...) -{ - if (!gEnv || !gEnv->pSystem || !format) - { - return; - } - - va_list args; - va_start(args, format); - GetISystem()->WarningV(module, severity, 0, 0, format, args); - va_end(args); -} - -#ifdef EXCLUDE_CVARHELP -#define CVARHELP(_comment) 0 -#else -#define CVARHELP(_comment) _comment -#endif - -//Provide macros for fixing cvars for release mode on consoles to enums to allow for code stripping -//Do not enable for PC, apply VF_CHEAT there if required -#if defined(CONSOLE) -#define CONST_CVAR_FLAGS (VF_CHEAT) -#else -#define CONST_CVAR_FLAGS (VF_NULL) -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION ISYSTEM_H_SECTION_5 - #include AZ_RESTRICTED_FILE(ISystem_h) -#endif -#if defined(_RELEASE) && defined(IS_CONSOLE_PLATFORM) -#ifndef LOG_CONST_CVAR_ACCESS -#error LOG_CONST_CVAR_ACCESS should be defined in ProjectDefines.h -#endif - -#include "IConsole.h" -namespace Detail -{ - template<typename T> - struct SQueryTypeEnum; - template<> - struct SQueryTypeEnum<int> - { - static const int type = CVAR_INT; - static int ParseString(const char* s) { return atoi(s); } - }; - template<> - struct SQueryTypeEnum<float> - { - static const int type = CVAR_FLOAT; - static float ParseString(const char* s) { return (float)atof(s); } - }; - - template<typename T> - struct SDummyCVar - : ICVar - { - const T value; -#if LOG_CONST_CVAR_ACCESS - mutable bool bWasRead; - mutable bool bWasChanged; - SDummyCVar(T val) - : value(val) - , bWasChanged(false) - , bWasRead(false) {} -#else - SDummyCVar(T val) - : value(val) {} -#endif - - void WarnUse() const - { -#if LOG_CONST_CVAR_ACCESS - if (!bWasRead) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "[CVAR] Read from const CVar '%s' via name look-up, this is non-optimal", GetName()); - bWasRead = true; - } -#endif - } - - void InvalidAccess() const - { -#if LOG_CONST_CVAR_ACCESS - if (!bWasChanged) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "[CVAR] Write to const CVar '%s' with wrong value '%f' was ignored. This indicates a bug in code or a config file", GetName(), GetFVal()); - bWasChanged = true; - } -#endif - } - - void Release() {} - int GetIVal() const { WarnUse(); return static_cast<int>(value); } - int64 GetI64Val() const { WarnUse(); return static_cast<int64>(value); } - float GetFVal() const { WarnUse(); return static_cast<float>(value); } - const char* GetString() const { return ""; } - const char* GetDataProbeString() const { return ""; } - void Set(const char* s) - { - if (SQueryTypeEnum<T>::ParseString(s) != value) - { - InvalidAccess(); - } - } - void ForceSet(const char* s) { Set(s); } - void Set(const float f) - { - if (static_cast<T>(f) != value) - { - InvalidAccess(); - } - } - void Set(const int i) - { - if (static_cast<T>(i) != value) - { - InvalidAccess(); - } - } - void ClearFlags([[maybe_unused]] int flags) {} - int GetFlags() const { return VF_CONST_CVAR | VF_READONLY; } - int SetFlags([[maybe_unused]] int flags) { return 0; } - int GetType() { return SQueryTypeEnum<T>::type; } - const char* GetHelp() { return NULL; } - bool IsConstCVar() const { return true; } - void SetOnChangeCallback(ConsoleVarFunc pChangeFunc) { (void)pChangeFunc; } - uint64 AddOnChangeFunctor(const SFunctor& pChangeFunctor) { (void)pChangeFunctor; return 0; } - uint64 GetNumberOfOnChangeFunctors() const { return 0; } - const SFunctor& GetOnChangeFunctor([[maybe_unused]] uint64 nFunctorIndex) const { InvalidAccess(); SFunctor* pNull = nullptr; return *pNull; } - bool RemoveOnChangeFunctor([[maybe_unused]] const uint64 nElement) { return true; } - ConsoleVarFunc GetOnChangeCallback() const { InvalidAccess(); return NULL; } - void GetMemoryUsage([[maybe_unused]] class ICrySizer* pSizer) const {} - int GetRealIVal() const { return GetIVal(); } - void SetLimits([[maybe_unused]] float min, [[maybe_unused]] float max) { return; } - void GetLimits([[maybe_unused]] float& min, [[maybe_unused]] float& max) { return; } - bool HasCustomLimits() { return false; } - void SetDataProbeString([[maybe_unused]] const char* pDataProbeString) { InvalidAccess(); } - }; -} - -#define REGISTER_DUMMY_CVAR(type, name, value) \ - do { \ - static struct DummyCVar \ - : Detail::SDummyCVar<type> \ - { \ - DummyCVar() \ - : Detail::SDummyCVar<type>(value) {} \ - const char* GetName() const { return name; } \ - } DummyStaticInstance; \ - if (!(gEnv->pConsole != 0 ? gEnv->pConsole->Register(&DummyStaticInstance) : 0)) \ - { \ - DEBUG_BREAK; \ - CryFatalError("Can not register dummy CVar"); \ - } \ - } while (0) - -# define CONSOLE_CONST_CVAR_MODE -# define DeclareConstIntCVar(name, defaultValue) enum : int { name = (defaultValue) } -# define DeclareStaticConstIntCVar(name, defaultValue) enum : int { name = (defaultValue) } - -# define DefineConstIntCVarName(strname, name, defaultValue, flags, help) { COMPILE_TIME_ASSERT((int)(defaultValue) == (int)(name)); REGISTER_DUMMY_CVAR(int, strname, defaultValue); } -# define DefineConstIntCVar(name, defaultValue, flags, help) { COMPILE_TIME_ASSERT((int)(defaultValue) == (int)(name)); REGISTER_DUMMY_CVAR(int, (#name), defaultValue); } -// DefineConstIntCVar2 is deprecated, any such instance can be converted to the 3 variant by removing the quotes around the first parameter -# define DefineConstIntCVar3(name, _var_, defaultValue, flags, help) { COMPILE_TIME_ASSERT((int)(defaultValue) == (int)(_var_)); REGISTER_DUMMY_CVAR(int, name, defaultValue); } -# define AllocateConstIntCVar(scope, name) - -# define DefineConstFloatCVar(name, flags, help) { REGISTER_DUMMY_CVAR(float, (#name), name ## Default); } -# define DeclareConstFloatCVar(name) -# define DeclareStaticConstFloatCVar(name) -# define AllocateConstFloatCVar(scope, name) - -# define IsCVarConstAccess(expr) expr - -#else - -# define DeclareConstIntCVar(name, defaultValue) int name { defaultValue } -# define DeclareStaticConstIntCVar(name, defaultValue) static int name -# define DefineConstIntCVarName(strname, name, defaultValue, flags, help) \ - (gEnv->pConsole == 0 ? 0 : gEnv->pConsole->Register(strname, &name, defaultValue, flags | CONST_CVAR_FLAGS, CVARHELP(help))) -# define DefineConstIntCVar(name, defaultValue, flags, help) \ - (gEnv->pConsole == 0 ? 0 : gEnv->pConsole->Register((#name), &name, defaultValue, flags | CONST_CVAR_FLAGS, CVARHELP(help), 0, false)) -// DefineConstIntCVar2 is deprecated, any such instance can be converted to the 3 variant by removing the quotes around the first parameter -# define DefineConstIntCVar3(_name, _var, _def_val, _flags, help) \ - (gEnv->pConsole == 0 ? 0 : gEnv->pConsole->Register(_name, &(_var), (_def_val), (_flags) | CONST_CVAR_FLAGS, CVARHELP(help), 0, false)) -# define AllocateConstIntCVar(scope, name) int scope:: name - -# define DefineConstFloatCVar(name, flags, help) \ - (gEnv->pConsole == 0 ? 0 : gEnv->pConsole->Register((#name), &name, name ## Default, flags | CONST_CVAR_FLAGS, CVARHELP(help), 0, false)) -# define DeclareConstFloatCVar(name) float name -# define DeclareStaticConstFloatCVar(name) static float name -# define AllocateConstFloatCVar(scope, name) float scope:: name - -# define IsCVarConstAccess(expr) - -#endif - -#if defined(USE_CRY_ASSERT) -static void AssertConsoleExists(void) -{ - CRY_ASSERT(gEnv->pConsole != NULL); -} -#define ASSERT_CONSOLE_EXISTS AssertConsoleExists() -#else -#define ASSERT_CONSOLE_EXISTS 0 -#endif // defined(USE_CRY_ASSERT) - -// the following macros allow the help text to be easily stripped out - -// Summary: -// Preferred way to register a CVar -#define REGISTER_CVAR(_var, _def_val, _flags, _comment) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? 0 : gEnv->pConsole->Register((#_var), &(_var), (_def_val), (_flags), CVARHELP(_comment))) -// Summary: -// Preferred way to register a CVar with a callback -#define REGISTER_CVAR_CB(_var, _def_val, _flags, _comment, _onchangefunction) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? 0 : gEnv->pConsole->Register((#_var), &(_var), (_def_val), (_flags), CVARHELP(_comment), _onchangefunction)) -// Summary: -// Preferred way to register a string CVar -#define REGISTER_STRING(_name, _def_val, _flags, _comment) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? 0 : gEnv->pConsole->RegisterString(_name, (_def_val), (_flags), CVARHELP(_comment))) -// Summary: -// Preferred way to register a string CVar with a callback -#define REGISTER_STRING_CB(_name, _def_val, _flags, _comment, _onchangefunction) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? 0 : gEnv->pConsole->RegisterString(_name, (_def_val), (_flags), CVARHELP(_comment), _onchangefunction)) -// Summary: -// Preferred way to register an int CVar -#define REGISTER_INT(_name, _def_val, _flags, _comment) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? 0 : gEnv->pConsole->RegisterInt(_name, (_def_val), (_flags), CVARHELP(_comment))) -// Summary: -// Preferred way to register an int CVar with a callback -#define REGISTER_INT_CB(_name, _def_val, _flags, _comment, _onchangefunction) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? 0 : gEnv->pConsole->RegisterInt(_name, (_def_val), (_flags), CVARHELP(_comment), _onchangefunction)) -// Summary: -// Preferred way to register an int64 CVar -#define REGISTER_INT64(_name, _def_val, _flags, _comment) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? 0 : gEnv->pConsole->RegisterInt64(_name, (_def_val), (_flags), CVARHELP(_comment))) -// Summary: -// Preferred way to register an int64 CVar with a callback -#define REGISTER_INT64_CB(_name, _def_val, _flags, _comment, _onchangefunction) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? 0 : gEnv->pConsole->RegisterInt64(_name, (_def_val), (_flags), CVARHELP(_comment), _onchangefunction)) -// Summary: -// Preferred way to register a float CVar -#define REGISTER_FLOAT(_name, _def_val, _flags, _comment) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? 0 : gEnv->pConsole->RegisterFloat(_name, (_def_val), (_flags), CVARHELP(_comment))) -// Summary: -// Preferred way to register a float CVar with a callback -#define REGISTER_FLOAT_CB(_name, _def_val, _flags, _comment, _onchangefunction) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? 0 : gEnv->pConsole->RegisterFloat(_name, (_def_val), (_flags), CVARHELP(_comment), _onchangefunction)) -// Summary: -// Offers more flexibility but more code is required -#define REGISTER_CVAR2(_name, _var, _def_val, _flags, _comment) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? 0 : gEnv->pConsole->Register(_name, _var, (_def_val), (_flags), CVARHELP(_comment))) -// Summary: -// Offers more flexibility but more code is required -#define REGISTER_CVAR2_CB(_name, _var, _def_val, _flags, _comment, _onchangefunction) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? 0 : gEnv->pConsole->Register(_name, _var, (_def_val), (_flags), CVARHELP(_comment), _onchangefunction)) -// Summary: -// Offers more flexibility but more code is required, explicit address taking of destination variable -#define REGISTER_CVAR3(_name, _var, _def_val, _flags, _comment) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? 0 : gEnv->pConsole->Register(_name, &(_var), (_def_val), (_flags), CVARHELP(_comment))) -// Summary: -// Offers more flexibility but more code is required, explicit address taking of destination variable -#define REGISTER_CVAR3_CB(_name, _var, _def_val, _flags, _comment, _onchangefunction) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? 0 : gEnv->pConsole->Register(_name, &(_var), (_def_val), (_flags), CVARHELP(_comment), _onchangefunction)) -// Summary: -// Preferred way to register a console command -#define REGISTER_COMMAND(_name, _func, _flags, _comment) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? false : gEnv->pConsole->AddCommand(_name, _func, (_flags), CVARHELP(_comment))) -// Summary: -// Preferred way to unregister a CVar -#define UNREGISTER_CVAR(_name) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? (void)0 : gEnv->pConsole->UnregisterVariable(_name)) -// Preferred way to unregister a console command -#define UNREGISTER_COMMAND(_name) (ASSERT_CONSOLE_EXISTS, gEnv->pConsole == 0 ? (void)0 : gEnv->pConsole->RemoveCommand(_name)) - -//////////////////////////////////////////////////////////////////////////////// -// -// Development only cvars -// -// N.B: -// (1) Registered as real cvars *in non release builds only*. -// (2) Can still be manipulated in release by the mapped variable, so not the same as const cvars. -// (3) Any 'OnChanged' callback will need guarding against in release builds since the cvar won't exist -// (4) Any code that tries to get ICVar* will need guarding against in release builds since the cvar won't exist -// -// ILLEGAL_DEV_FLAGS is a mask of all those flags which make no sense in a _DEV_ONLY or _DEDI_ONLY cvar since the -// cvar potentially won't exist in a release build. -// -#define ILLEGAL_DEV_FLAGS (VF_NET_SYNCED | VF_CHEAT | VF_CHEAT_ALWAYS_CHECK | VF_CHEAT_NOCHECK | VF_READONLY | VF_CONST_CVAR) - -#if defined(_RELEASE) -#define REGISTER_CVAR_DEV_ONLY(_var, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val -#define REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val /* _onchangefunction consumed; callback not available */ -#define REGISTER_STRING_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_STRING_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_INT_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_INT_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_INT64_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_FLOAT_DEV_ONLY(_name, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) /* consumed; pure cvar not available */ -#define REGISTER_CVAR2_DEV_ONLY(_name, _var, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); *(_var) = _def_val -#define REGISTER_CVAR2_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); *(_var) = _def_val -#define REGISTER_CVAR3_DEV_ONLY(_name, _var, _def_val, _flags, _comment) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val -#define REGISTER_CVAR3_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) NULL; COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0); _var = _def_val -#define REGISTER_COMMAND_DEV_ONLY(_name, _func, _flags, _comment) /* consumed; command not available */ -#else -#define REGISTER_CVAR_DEV_ONLY(_var, _def_val, _flags, _comment) REGISTER_CVAR(_var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR_CB(_var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_STRING_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_STRING(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_STRING_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_STRING_CB(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT_CB_DEV_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_INT_CB(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT64_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT64(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_FLOAT_DEV_ONLY(_name, _def_val, _flags, _comment) REGISTER_FLOAT(_name, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR2_DEV_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR2(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR2_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR2_CB(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR3_DEV_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR3(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR3_CB_DEV_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR3_CB(_name, _var, _def_val, ((_flags) | VF_DEV_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_COMMAND_DEV_ONLY(_name, _func, _flags, _comment) REGISTER_COMMAND(_name, _func, ((_flags) | VF_DEV_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#endif // defined(_RELEASE) -// -//////////////////////////////////////////////////////////////////////////////// - -//////////////////////////////////////////////////////////////////////////////// -// -// Dedicated server only cvars -// -// N.B: -// (1) Registered as real cvars in all non release builds -// (2) Registered as real cvars in release on dedi servers only, otherwise treated as DEV_ONLY type cvars (see above) -// - -// TODO Registering all cvars for Dedicated server as well. Currently CrySystems have no concept of Dedicated server with cmake. -// If we introduce server specific targets for CrySystems, we can add DEDICATED_SERVER flags to those and add the flag back in here. -#if defined(_RELEASE) -#define REGISTER_CVAR_DEDI_ONLY(_var, _def_val, _flags, _comment) REGISTER_CVAR(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR_CB_DEDI_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR_CB(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_STRING_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_STRING(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_STRING_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_STRING_CB(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_INT_CB(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_INT64_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT64(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_FLOAT_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_FLOAT(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR2_DEDI_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR2(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR2_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR2_CB(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR3_DEDI_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR3(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_CVAR3_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR3_CB(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#define REGISTER_COMMAND_DEDI_ONLY(_name, _func, _flags, _comment) REGISTER_COMMAND(_name, _func, ((_flags) | VF_DEDI_ONLY), _comment); COMPILE_TIME_ASSERT(((_flags) & ILLEGAL_DEV_FLAGS) == 0) -#else -#define REGISTER_CVAR_DEDI_ONLY(_var, _def_val, _flags, _comment) REGISTER_CVAR_DEV_ONLY(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment) -#define REGISTER_CVAR_CB_DEDI_ONLY(_var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR_CB_DEV_ONLY(_var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction) -#define REGISTER_STRING_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_STRING_DEV_ONLY(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment) -#define REGISTER_STRING_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_STRING_CB_DEV_ONLY(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction) -#define REGISTER_INT_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT_DEV_ONLY(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment) -#define REGISTER_INT_CB_DEDI_ONLY(_name, _def_val, _flags, _comment, _onchangefunction) REGISTER_INT_CB_DEV_ONLY(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction) -#define REGISTER_INT64_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_INT64_DEV_ONLY(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment) -#define REGISTER_FLOAT_DEDI_ONLY(_name, _def_val, _flags, _comment) REGISTER_FLOAT_DEV_ONLY(_name, _def_val, ((_flags) | VF_DEDI_ONLY), _comment) -#define REGISTER_CVAR2_DEDI_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR2_DEV_ONLY(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment) -#define REGISTER_CVAR2_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR2_CB_DEV_ONLY(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction) -#define REGISTER_CVAR3_DEDI_ONLY(_name, _var, _def_val, _flags, _comment) REGISTER_CVAR3_DEV_ONLY(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment) -#define REGISTER_CVAR3_CB_DEDI_ONLY(_name, _var, _def_val, _flags, _comment, _onchangefunction) REGISTER_CVAR3_CB_DEV_ONLY(_name, _var, _def_val, ((_flags) | VF_DEDI_ONLY), _comment, _onchangefunction) -#define REGISTER_COMMAND_DEDI_ONLY(_name, _func, _flags, _comment) REGISTER_COMMAND_DEV_ONLY(_name, _func, ((_flags) | VF_DEDI_ONLY), _comment) -#endif // defined(_RELEASE) -// -//////////////////////////////////////////////////////////////////////////////// - -#ifdef EXCLUDE_NORMAL_LOG // setting this removes a lot of logging to reduced code size (useful for consoles) - -#define CryLog(...) ((void)0) -#define CryComment(...) ((void)0) -#define CryLogAlways(...) ((void)0) - -#else // EXCLUDE_NORMAL_LOG - -// Summary: -// Simple logs of data with low verbosity. -void CryLog(const char*, ...) PRINTF_PARAMS(1, 2); -inline void CryLog(const char* format, ...) -{ - // Fran: we need these guards for the testing framework to work - if (gEnv && gEnv->pSystem && gEnv->pLog) - { - va_list args; - va_start(args, format); - gEnv->pLog->LogV(ILog::eMessage, format, args); - va_end(args); - } -} -// Notes: -// Very rarely used log comment. -void CryComment(const char*, ...) PRINTF_PARAMS(1, 2); -inline void CryComment(const char* format, ...) -{ - // Fran: we need these guards for the testing framework to work - if (gEnv && gEnv->pSystem && gEnv->pLog) - { - va_list args; - va_start(args, format); - gEnv->pLog->LogV(ILog::eComment, format, args); - va_end(args); - } -} -// Summary: -// Logs important data that must be printed regardless verbosity. -void CryLogAlways(const char*, ...) PRINTF_PARAMS(1, 2); -inline void CryLogAlways(const char* format, ...) -{ - // log should not be used before system is ready - // error before system init should be handled explicitly - - // Fran: we need these guards for the testing framework to work - - if (gEnv && gEnv->pSystem && gEnv->pLog) - { - // assert(gEnv); - // assert(gEnv->pSystem); - - va_list args; - va_start(args, format); - gEnv->pLog->LogV(ILog::eAlways, format, args); - va_end(args); - } -} - -#endif // EXCLUDE_NORMAL_LOG - -////////////////////////////////////////////////////////////////////////// -// Additional headers. -////////////////////////////////////////////////////////////////////////// -#include <FrameProfiler.h> - -#endif // CRYINCLUDE_CRYCOMMON_ISYSTEM_H - diff --git a/Code/CryEngine/CryCommon/ITexture.h b/Code/CryEngine/CryCommon/ITexture.h deleted file mode 100644 index c2244b6840..0000000000 --- a/Code/CryEngine/CryCommon/ITexture.h +++ /dev/null @@ -1,422 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_ITEXTURE_H -#define CRYINCLUDE_CRYCOMMON_ITEXTURE_H -#pragma once - -#include <AzCore/PlatformDef.h> - -#include "Cry_Math.h" -#include "Cry_Color.h" -#include "Tarray.h" -#include <smartptr.h> -class CTexture; - -#ifndef COMPILER_SUPPORTS_ENUM_SPECIFICATION -# if defined(_MSC_VER) -# define COMPILER_SUPPORTS_ENUM_SPECIFICATION 1 -# else -# define COMPILER_SUPPORTS_ENUM_SPECIFICATION 0 -# endif -#endif - -#if COMPILER_SUPPORTS_ENUM_SPECIFICATION -enum ETEX_Type : uint8 -#else -typedef uint8 ETEX_Type; -enum eTEX_Type -#endif -{ - eTT_1D = 0, - eTT_2D, - eTT_3D, - eTT_Cube, - eTT_CubeArray, - eTT_Dyn2D, - eTT_User, - eTT_NearestCube, - - eTT_2DArray, - eTT_2DMS, - - eTT_Auto2D, - - eTT_MaxTexType, // not used -}; - - -// Texture formats -#if COMPILER_SUPPORTS_ENUM_SPECIFICATION -enum ETEX_Format : uint8 -#else -typedef uint8 ETEX_Format; -enum eTEX_Format -#endif -{ - eTF_Unknown = 0, - eTF_R8G8B8A8S, - eTF_R8G8B8A8 = 2, // may be saved into file - - eTF_A8 = 4, - eTF_R8, - eTF_R8S, - eTF_R16, - eTF_R16F, - eTF_R32F, - eTF_R8G8, - eTF_R8G8S, - eTF_R16G16, - eTF_R16G16S, - eTF_R16G16F, - eTF_R11G11B10F, - eTF_R10G10B10A2, - eTF_R16G16B16A16, - eTF_R16G16B16A16S, - eTF_R16G16B16A16F, - eTF_R32G32B32A32F, - - eTF_CTX1, - eTF_BC1 = 22, // may be saved into file - eTF_BC2 = 23, // may be saved into file - eTF_BC3 = 24, // may be saved into file - eTF_BC4U, // 3Dc+ - eTF_BC4S, - eTF_BC5U, // 3Dc - eTF_BC5S, - eTF_BC6UH, - eTF_BC6SH, - eTF_BC7, - eTF_R9G9B9E5, - - // hardware depth buffers - eTF_D16, - eTF_D24S8, - eTF_D32F, - eTF_D32FS8, - - // only available as hardware format under DX11.1 with DXGI 1.2 - eTF_B5G6R5, - eTF_B5G5R5, - eTF_B4G4R4A4, - - // only available as hardware format under OpenGL - eTF_EAC_R11, - eTF_EAC_RG11, - eTF_ETC2, - eTF_ETC2A, - - // only available as hardware format under DX9 - eTF_A8L8, - eTF_L8, - eTF_L8V8U8, - eTF_B8G8R8, - eTF_L8V8U8X8, - eTF_B8G8R8X8, - eTF_B8G8R8A8, - - eTF_PVRTC2, - eTF_PVRTC4, - - eTF_ASTC_4x4, - eTF_ASTC_5x4, - eTF_ASTC_5x5, - eTF_ASTC_6x5, - eTF_ASTC_6x6, - eTF_ASTC_8x5, - eTF_ASTC_8x6, - eTF_ASTC_8x8, - eTF_ASTC_10x5, - eTF_ASTC_10x6, - eTF_ASTC_10x8, - eTF_ASTC_10x10, - eTF_ASTC_12x10, - eTF_ASTC_12x12, - - // add R16 unsigned int format for hardware that do not support float point rendering - eTF_R16U, - eTF_R16G16U, - eTF_R10G10B10A2UI, - - eTF_MaxFormat // unused, must be always the last in the list -}; - -#if COMPILER_SUPPORTS_ENUM_SPECIFICATION -enum ETEX_TileMode : uint8 -#else -typedef uint8 ETEX_TileMode; -enum eTEX_TileMode -#endif -{ - eTM_None = 0, - eTM_LinearPadded, - eTM_Optimal, -}; - - -enum ETextureFlags -{ - FT_NOMIPS = 0x00000001, - FT_TEX_NORMAL_MAP = 0x00000002, - FT_TEX_WAS_NOT_PRE_TILED = 0x00000004, - FT_USAGE_DEPTHSTENCIL = 0x00000008, - FT_USAGE_ALLOWREADSRGB = 0x00000010, - FT_FILESINGLE = 0x00000020, // suppress loading of additional files like _DDNDIF (faster, RC can tag the file for that) - FT_TEX_FONT = 0x00000040, - FT_HAS_ATTACHED_ALPHA = 0x00000080, - FT_USAGE_UNORDERED_ACCESS = 0x00000100, - FT_USAGE_READBACK = 0x00000200, - FT_USAGE_MSAA = 0x00000400, - FT_FORCE_MIPS = 0x00000800, - FT_USAGE_RENDERTARGET = 0x00001000, - FT_USAGE_DYNAMIC = 0x00002000, - FT_STAGE_READBACK = 0x00004000, - FT_STAGE_UPLOAD = 0x00008000, - FT_DONT_RELEASE = 0x00010000, - FT_ASYNC_PREPARE = 0x00020000, - FT_DONT_STREAM = 0x00040000, -#if defined(AZ_RESTRICTED_PLATFORM) - #include AZ_RESTRICTED_FILE(ITexture_h) -#endif - -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) - #undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -#if defined(AZ_PLATFORM_IOS) - FT_USAGE_MEMORYLESS = 0x00080000, //reusing an unused bit for ios -#else - FT_USAGE_PREDICATED_TILING = 0x00080000, //unused -#endif -#endif - FT_FAILED = 0x00100000, - FT_FROMIMAGE = 0x00200000, - FT_STATE_CLAMP = 0x00400000, - FT_USAGE_ATLAS = 0x00800000, - FT_ALPHA = 0x01000000, - FT_REPLICATE_TO_ALL_SIDES = 0x02000000, - FT_KEEP_LOWRES_SYSCOPY = 0x04000000, // keep low res copy in system memory for voxelization on CPU - FT_SPLITTED = 0x08000000, // for split dds files - FT_USE_HTILE = 0x10000000, - FT_IGNORE_PRECACHE = 0x20000000, - FT_COMPOSITE = 0x40000000, - FT_USAGE_UAV_RWTEXTURE = 0x80000000, -}; - -struct SDepthTexture; - -struct STextureStreamingStats -{ - STextureStreamingStats(bool bComputeTexturesPerFrame) - : bComputeReuquiredTexturesPerFrame(bComputeTexturesPerFrame) - { - nMaxPoolSize = 0; - nCurrentPoolSize = 0; - nStreamedTexturesSize = 0; - nStaticTexturesSize = 0; - nThroughput = 0; - nNumTexturesPerFrame = 0; - nRequiredStreamedTexturesSize = 0; - nRequiredStreamedTexturesCount = 0; - bPoolOverflow = false; - bPoolOverflowTotally = false; - fPoolFragmentation = 0.0f; - } - size_t nMaxPoolSize; - size_t nCurrentPoolSize; - size_t nStreamedTexturesSize; - size_t nStaticTexturesSize; - uint32 nNumTexturesPerFrame; - size_t nThroughput; - size_t nRequiredStreamedTexturesSize; - uint32 nRequiredStreamedTexturesCount; - float fPoolFragmentation; - uint32 bPoolOverflow : 1; - uint32 bPoolOverflowTotally : 1; - const bool bComputeReuquiredTexturesPerFrame; -}; - - -////////////////////////////////////////////////////////////////////// -// Texture object interface -class CDeviceTexture; -class ITexture -{ -protected: - virtual ~ITexture() {} -public: - - // <interfuscator:shuffle> - virtual int AddRef() = 0; - virtual int Release() = 0; - virtual int ReleaseForce() = 0; - - virtual const ColorF& GetClearColor() const = 0; - virtual const ETEX_Format GetDstFormat() const = 0; - virtual const ETEX_Format GetSrcFormat() const = 0; - virtual const ETEX_Type GetTexType() const = 0; - virtual void ApplyTexture(int nTUnit, int nState = -1) = 0; - virtual const char* GetName() const = 0; - virtual const int GetWidth() const = 0; - virtual const int GetHeight() const = 0; - virtual const int GetDepth() const = 0; - virtual const int GetTextureID() const = 0; - virtual const uint32 GetFlags() const = 0; - virtual const int GetNumMips() const = 0; - virtual const int GetRequiredMip() const = 0; - virtual const int GetDeviceDataSize() const = 0; - virtual const int GetDataSize() const = 0; - virtual const ETEX_Type GetTextureType() const = 0; - // Sets the texture type of the texture to be used before the texture is loaded. - // Once the texture is loaded the type from the file will overwrite whatever - // value was set here. - virtual void SetTextureType(ETEX_Type type) = 0; - virtual const bool IsTextureLoaded() const = 0; - virtual void PrecacheAsynchronously(float fMipFactor, int nFlags, int nUpdateId, int nCounter = 1) = 0; - virtual uint8* GetData32(int nSide = 0, int nLevel = 0, uint8* pDst = NULL, ETEX_Format eDstFormat = eTF_R8G8B8A8) = 0; - virtual bool SetFilter(int nFilter) = 0; // FILTER_ flags - virtual void SetClamp(bool bEnable) = 0; // Texture addressing set - virtual float GetAvgBrightness() const = 0; - - virtual int StreamCalculateMipsSigned(float fMipFactor) const = 0; - virtual int GetStreamableMipNumber() const = 0; - virtual int GetStreamableMemoryUsage(int nStartMip) const = 0; - virtual int GetMinLoadedMip() const = 0; - - using StagingHook = AZStd::function<bool(void*, uint32, uint32)>; - virtual void Readback(AZ::u32 subresourceIndex, StagingHook callback) = 0; - - virtual bool Reload() = 0; - // Used for debugging/profiling. - virtual const char* GetFormatName() const = 0; - virtual const char* GetTypeName() const = 0; - virtual const bool IsStreamedVirtual() const = 0; - virtual const bool IsShared() const = 0; - virtual const bool IsStreamable() const = 0; - virtual bool IsStreamedIn(const int nMinPrecacheRoundIds[2]) const = 0; - virtual const int GetAccessFrameId() const = 0; - - virtual const ETEX_Format GetTextureDstFormat() const = 0; - virtual const ETEX_Format GetTextureSrcFormat() const = 0; - - virtual bool IsPostponed() const = 0; - virtual const bool IsParticularMipStreamed(float fMipFactor) const = 0; - - // get low res system memory (used for CPU voxelization) - virtual const ColorB* GetLowResSystemCopy([[maybe_unused]] uint16& nWidth, [[maybe_unused]] uint16& nHeight, [[maybe_unused]] int** ppLowResSystemCopyAtlasId) { return 0; } - - // </interfuscator:shuffle> - - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const - { - COMPILE_TIME_ASSERT(eTT_MaxTexType <= 255); - COMPILE_TIME_ASSERT(eTF_MaxFormat <= 255); - /*LATER*/ - } - - virtual void SetKeepSystemCopy(bool bKeepSystemCopy) = 0; - virtual void UpdateTextureRegion(const uint8_t* data, int nX, int nY, int nZ, int USize, int VSize, int ZSize, ETEX_Format eTFSrc) = 0; - virtual CDeviceTexture* GetDevTexture() const = 0; - -}; - -struct STextureLoadData -{ - void* m_pData; - size_t m_DataSize; - int m_Width; - int m_Height; - ETEX_Format m_Format; - int m_NumMips; - int m_nFlags; - ITexture* m_pTexture; - STextureLoadData() - : m_pData(nullptr) - , m_Width(0) - , m_Height(0) - , m_Format(eTF_Unknown) - , m_NumMips(0) - , m_nFlags(0) - , m_pTexture(nullptr) - { - } - ~STextureLoadData() - { - if (m_pData) - { - CryModuleFree(m_pData); - } - } - - static void* AllocateData(size_t dataSize) - { - return CryModuleMalloc(dataSize); - } -}; -struct ITextureLoadHandler -{ - virtual ~ITextureLoadHandler() {} - virtual bool LoadTextureData(const char* path, STextureLoadData& loadData) = 0; - virtual bool SupportsExtension(const char* ext) const = 0; - virtual void Update() = 0; -}; - -//========================================================================================= - -class IDynTexture -{ -public: - enum - { - fNeedRegenerate = 1ul << 0, - }; - // <interfuscator:shuffle> - virtual ~IDynTexture(){} - virtual void Release() = 0; - virtual void GetSubImageRect(uint32& nX, uint32& nY, uint32& nWidth, uint32& nHeight) = 0; - virtual void GetImageRect(uint32& nX, uint32& nY, uint32& nWidth, uint32& nHeight) = 0; - virtual int GetTextureID() = 0; - virtual void Lock() = 0; - virtual void UnLock() = 0; - virtual int GetWidth() = 0; - virtual int GetHeight() = 0; - virtual bool IsValid() = 0; - virtual uint8 GetFlags() const = 0; - virtual void SetFlags([[maybe_unused]] uint8 flags) {} - virtual bool Update(int nNewWidth, int nNewHeight) = 0; - virtual void Apply(int nTUnit, int nTS = -1) = 0; - virtual bool ClearRT() = 0; - virtual bool SetRT(int nRT, bool bPush, struct SDepthTexture* pDepthSurf, bool bScreenVP = false) = 0; - virtual bool SetRectStates() = 0; - virtual bool RestoreRT(int nRT, bool bPop) = 0; - virtual ITexture* GetTexture() = 0; - virtual void SetUpdateMask() = 0; - virtual void ResetUpdateMask() = 0; - virtual bool IsSecondFrame() = 0; - virtual bool GetImageData32([[maybe_unused]] uint8* pData, [[maybe_unused]] int nDataSize) { return 0; } - // </interfuscator:shuffle> -}; - -// Animating Texture sequence definition -class ITexAnim -{ -public: - virtual ~ITexAnim() {}; - virtual void Release() = 0; - virtual void AddRef() = 0; -}; - -struct AZ_DEPRECATED(STexAnim, "STexAnim has been deprecated and replaced by the abstract interface ITexAnim above and CTexAnim in RenderDLL/Common/Textures/Texture.h. This was done to keep proper ref counting between CryRenderDLL and EditorLib.") {}; - -struct STexComposition -{ - _smart_ptr<ITexture> pTexture; - uint16 nSrcSlice; - uint16 nDstSlice; -}; - -#endif // CRYINCLUDE_CRYCOMMON_ITEXTURE_H diff --git a/Code/CryEngine/CryCommon/ITimer.h b/Code/CryEngine/CryCommon/ITimer.h deleted file mode 100644 index dccdafae17..0000000000 --- a/Code/CryEngine/CryCommon/ITimer.h +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_ITIMER_H -#define CRYINCLUDE_CRYCOMMON_ITIMER_H -#pragma once - - -#include "TimeValue.h" // CTimeValue -#include "SerializeFwd.h" - -struct tm; - -// Summary: -// Interface to the Timer System. -struct ITimer -{ - enum ETimer - { - ETIMER_GAME = 0, // Pausable, serialized, frametime is smoothed/scaled/clamped. - ETIMER_UI, // Non-pausable, non-serialized, frametime unprocessed. - ETIMER_LAST - }; - - enum ETimeScaleChannels - { - eTSC_Trackview = 0, - eTSC_GameStart - }; - - // <interfuscator:shuffle> - virtual ~ITimer() {}; - - // Summary: - // Resets the timer - // Notes: - // Only needed because float precision wasn't last that long - can be removed if 64bit is used everywhere. - virtual void ResetTimer() = 0; - - // Summary: - // Updates the timer every frame, needs to be called by the system. - virtual void UpdateOnFrameStart() = 0; - - // Summary: - // Returns the absolute time at the last UpdateOnFrameStart() call. - // Todo: - // Remove, use GetFrameStartTime() instead. - // See also: - // UpdateOnFrameStart(),GetFrameStartTime() - virtual float GetCurrTime(ETimer which = ETIMER_GAME) const = 0; - - // Summary: - // Returns the absolute time at the last UpdateOnFrameStart() call. - // See also: - // UpdateOnFrameStart() - //virtual const CTimeValue& GetFrameStartTime(ETimer which = ETIMER_GAME) const = 0; - virtual const CTimeValue& GetFrameStartTime(ETimer which = ETIMER_GAME) const = 0; - - // Summary: - // Returns the absolute current time. - // Notes: - // The value continuously changes, slower than GetFrameStartTime(). - // See also: - // GetFrameStartTime() - virtual CTimeValue GetAsyncTime() const = 0; - - // Summary: - // Returns the absolute current time at the moment of the call. - virtual float GetAsyncCurTime() = 0; - - // Summary: - // Returns the relative time passed from the last UpdateOnFrameStart() in seconds. - // See also: - // UpdateOnFrameStart() - virtual float GetFrameTime(ETimer which = ETIMER_GAME) const = 0; - - // Description: - // Returns the relative time passed from the last UpdateOnFrameStart() in seconds without any dilation, smoothing, clamping, etc... - // See also: - // UpdateOnFrameStart() - virtual float GetRealFrameTime() const = 0; - - // Summary: - // Returns the time scale applied to time values. - virtual float GetTimeScale() const = 0; - - // Summary: - // Returns the time scale factor for the given channel - virtual float GetTimeScale(uint32 channel) const = 0; - - // Summary: - // Clears all current time scale requests - virtual void ClearTimeScales() = 0; - - // Summary: - // Sets the time scale applied to time values. - virtual void SetTimeScale(float s, uint32 channel = 0) = 0; - - // Summary: - // Enables/disables timer. - virtual void EnableTimer(bool bEnable) = 0; - - // Return Value: - // True if timer is enabled - virtual bool IsTimerEnabled() const = 0; - - // Summary: - // Returns the current framerate in frames/second. - virtual float GetFrameRate() = 0; - - // Summary: - // Returns the fraction to blend current frame in profiling stats. - virtual float GetProfileFrameBlending(float* pfBlendTime = 0, int* piBlendMode = 0) = 0; - - // Summary: - // Serialization. - virtual void Serialize(TSerialize ser) = 0; - - // Summary: - // Tries to pause/unpause a timer. - // Return Value: - // True if successfully paused/unpaused, false otherwise. - virtual bool PauseTimer(ETimer which, bool bPause) = 0; - - // Summary: - // Determines if a timer is paused. - // Returns: - // True if paused, false otherwise. - virtual bool IsTimerPaused(ETimer which) = 0; - - // Summary: - // Tries to set a timer. - // Returns: - // True if successful, false otherwise. - virtual bool SetTimer(ETimer which, float timeInSeconds) = 0; - - // Summary: - // Makes a tm struct from a time_t in UTC - // Example: - // Like gmtime. - virtual void SecondsToDateUTC(time_t time, struct tm& outDateUTC) = 0; - - // Summary: - // Makes a UTC time from a tm. - // Example: - // Like timegm, but not available on all platforms. - virtual time_t DateToSecondsUTC(struct tm& timePtr) = 0; - - - // Summary - // Convert from ticks (CryGetTicks()) to seconds - // - virtual float TicksToSeconds(int64 ticks) = 0; - - // Summary - // Get number of ticks per second - // - virtual int64 GetTicksPerSecond() = 0; - - // Summary - // Create a new timer of the same type - // - virtual ITimer* CreateNewTimer() = 0; - - /*! - This is similar to the cvar t_FixedStep. However it is stronger, and will cause even GetRealFrameTime to follow the fixed time stamp. - GetRealFrameTime will always return the same value as GetFrameTime. This mode is mostly intended for Feature tests that have strict requirements - for determinism. It will cause even fps counters to return a fixed value that does not match the actual fps. I could see this also being useful - if rendering a video. - */ - virtual void EnableFixedTimeMode(bool enable, float timeStep) = 0; - // </interfuscator:shuffle> -}; - -// Description: -// This class is used for automatic profiling of a section of the code. -// Creates an instance of this class, and upon exiting from the code section. -template <typename time> -class CITimerAutoProfiler -{ -public: - CITimerAutoProfiler (ITimer* pTimer, time& rTime) - : m_pTimer (pTimer) - , m_rTime (rTime) - { - rTime -= pTimer->GetAsyncCurTime(); - } - - ~CITimerAutoProfiler () - { - m_rTime += m_pTimer->GetAsyncCurTime(); - } - -protected: - ITimer* m_pTimer; - time& m_rTime; -}; - -// Description: -// Include this string AUTO_PROFILE_SECTION(pITimer, g_fTimer) for the section of code where the profiler timer must be turned on and off. -// The profiler timer is just some global or static float or double value that accumulates the time (in seconds) spent in the given block of code. -// pITimer is a pointer to the ITimer interface, g_fTimer is the global accumulator. -#define AUTO_PROFILE_SECTION(pITimer, g_fTimer) CITimerAutoProfiler<double> __section_auto_profiler(pITimer, g_fTimer) - -#endif // CRYINCLUDE_CRYCOMMON_ITIMER_H diff --git a/Code/CryEngine/CryCommon/IValidator.h b/Code/CryEngine/CryCommon/IValidator.h deleted file mode 100644 index 610b8f8748..0000000000 --- a/Code/CryEngine/CryCommon/IValidator.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : IValidator interface used to check objects for warnings and errors -// Report missing resources or invalid files. - - -#ifndef CRYINCLUDE_CRYCOMMON_IVALIDATOR_H -#define CRYINCLUDE_CRYCOMMON_IVALIDATOR_H -#pragma once - -# define MAX_WARNING_LENGTH 4096 - -#if MAX_WARNING_LENGTH < 33 -#error "MAX_WARNING_LENGTH should be bigger than 32" -#endif - -#define ERROR_CANT_FIND_CENTRAL_DIRECTORY "Cannot find Central Directory Record in pak. This is either not a pak file, or a pak file without Central Directory. It does not mean that the data is permanently lost, but it may be severely damaged. Please repair the file with external tools, there may be enough information left to recover the file completely." - -enum EValidatorSeverity -{ - VALIDATOR_ERROR, - VALIDATOR_ERROR_DBGBRK, // will __debugbreak() if sys_error_debugbreak is 1 - VALIDATOR_WARNING, - VALIDATOR_COMMENT -}; - -enum EValidatorModule -{ - VALIDATOR_MODULE_UNKNOWN, - VALIDATOR_MODULE_RENDERER, - VALIDATOR_MODULE_3DENGINE, - VALIDATOR_MODULE_ASSETS, - VALIDATOR_MODULE_SYSTEM, - VALIDATOR_MODULE_AUDIO, - VALIDATOR_MODULE_MOVIE, - VALIDATOR_MODULE_EDITOR, - VALIDATOR_MODULE_NETWORK, - VALIDATOR_MODULE_PHYSICS, - VALIDATOR_MODULE_RESERVED, // formerly VALIDATOR_MODULE_FLOWGRAPH - VALIDATOR_MODULE_FEATURETESTS, - VALIDATOR_MODULE_ONLINE, - VALIDATOR_MODULE_SHINE, - VALIDATOR_MODULE_DRS, -}; - -enum EValidatorFlags -{ - VALIDATOR_FLAG_FILE = 0x0001, // Indicate that required file was not found or file was invalid. - VALIDATOR_FLAG_TEXTURE = 0x0002, // Problem with texture. - VALIDATOR_FLAG_SCRIPT = 0x0004, // Problem with script. - VALIDATOR_FLAG_AUDIO = 0x0008, // Problem with audio. - VALIDATOR_FLAG_AI = 0x0010, // Problem with AI. - VALIDATOR_FLAG_LOG_ASSET_SCOPE = 0x0020, // Log asset scope with the warning. - VALIDATOR_FLAG_IGNORE_IN_EDITOR = 0x0040, // Do not log this with the editor - VALIDATOR_FLAG_SKIP_VALIDATOR = 0x0080, // Do not call validator's Report() -}; - -struct SValidatorRecord -{ - //! Severity of this error. - EValidatorSeverity severity; - //! In which module error occured. - EValidatorModule module; - //! Error Text. - const char* text; - //! File which is missing or causing problem. - const char* file; - //! Additional description for this error. - const char* description; - //! Asset scope sring - const char* assetScope; - //! Flags that suggest kind of error. - int flags; - - ////////////////////////////////////////////////////////////////////////// - SValidatorRecord() - { - module = VALIDATOR_MODULE_UNKNOWN; - text = NULL; - file = NULL; - assetScope = NULL; - description = NULL; - severity = VALIDATOR_WARNING; - flags = 0; - } -}; - -/*! This interface will be given to Validate methods of engine, for resources and objects validation. - */ -struct IValidator -{ - // <interfuscator:shuffle> - virtual ~IValidator(){} - virtual void Report(SValidatorRecord& record) = 0; - // </interfuscator:shuffle> -}; - -#endif // CRYINCLUDE_CRYCOMMON_IVALIDATOR_H diff --git a/Code/CryEngine/CryCommon/IViewSystem.h b/Code/CryEngine/CryCommon/IViewSystem.h deleted file mode 100644 index 646e963653..0000000000 --- a/Code/CryEngine/CryCommon/IViewSystem.h +++ /dev/null @@ -1,305 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : View System interfaces. - - -#ifndef CRYINCLUDE_CRYACTION_IVIEWSYSTEM_H -#define CRYINCLUDE_CRYACTION_IVIEWSYSTEM_H -#pragma once - -#include <ISerialize.h> -#include <Cry_Camera.h> -#include <AzCore/Component/EntityId.h> - -// -#define VIEWID_NORMAL 0 -#define VIEWID_FOLLOWHEAD 1 -#define VIEWID_VEHICLE 2 -#define VIEWID_RAGDOLL 3 - -//Forward declaration of AZ::Entity -namespace AZ { - class Entity; -} - -enum EMotionBlurType -{ - eMBT_None = 0, - eMBT_Accumulation = 1, - eMBT_Velocity = 2 -}; - -struct SViewParams -{ - SViewParams() - : position(ZERO) - , rotation(IDENTITY) - , localRotationLast(IDENTITY) - , nearplane(0.0f) - , farplane(0.0f) - , fov(0.0f) - , viewID(0) - , groundOnly(false) - , shakingRatio(0.0f) - , currentShakeQuat(IDENTITY) - , currentShakeShift(ZERO) - , targetPos(ZERO) - , frameTime(0.0f) - , angleVel(0.0f) - , vel(0.0f) - , dist(0.0f) - , blend(true) - , blendPosSpeed(5.0f) - , blendRotSpeed(10.0f) - , blendFOVSpeed(5.0f) - , blendPosOffset(ZERO) - , blendRotOffset(IDENTITY) - , blendFOVOffset(0) - , justActivated(false) - , viewIDLast(0) - , positionLast(ZERO) - , rotationLast(IDENTITY) - , FOVLast(0) - { - } - - void SetViewID(uint8 id, bool shouldBlend = true) - { - viewID = id; - if (!shouldBlend) - { - viewIDLast = id; - } - } - - void UpdateBlending(float curFrameTime) - { - //if necessary blend the view - if (blend) - { - if (viewIDLast != viewID) - { - blendPosOffset = positionLast - position; - blendRotOffset = (rotationLast / rotation).GetNormalized(); - blendFOVOffset = FOVLast - fov; - } - else - { - blendPosOffset -= blendPosOffset * min(1.0f, blendPosSpeed * curFrameTime); - blendRotOffset = Quat::CreateSlerp(blendRotOffset, IDENTITY, min(1.0f, curFrameTime * blendRotSpeed)); - blendFOVOffset -= blendFOVOffset * min(1.0f, blendFOVSpeed * curFrameTime); - } - - position += blendPosOffset; - rotation *= blendRotOffset; - fov += blendFOVOffset; - } - else - { - blendPosOffset.zero(); - blendRotOffset.SetIdentity(); - blendFOVOffset = 0.0f; - } - - viewIDLast = viewID; - } - - void BlendFrom(const SViewParams& params) - { - positionLast = params.position; - rotationLast = params.rotation; - FOVLast = params.fov; - localRotationLast = params.localRotationLast; - blend = true; - viewIDLast = 0xff; - } - - void SaveLast() - { - if (viewIDLast != 0xff) - { - positionLast = position; - rotationLast = rotation; - FOVLast = fov; - } - else - { - viewIDLast = 0xfe; - } - } - - void ResetBlending() - { - blendPosOffset.zero(); - blendRotOffset.SetIdentity(); - } - - const Vec3& GetPositionLast() { return positionLast; } - const Quat& GetRotationLast() { return rotationLast; } - - // - Vec3 position;//view position - Quat rotation;//view orientation - Quat localRotationLast; - - float nearplane;//custom near clipping plane, 0 means use engine defaults - float farplane;//custom far clipping plane, 0 means use engine defaults - float fov; - - uint8 viewID; - - //view shake status - bool groundOnly; - float shakingRatio;//whats the ammount of shake, from 0.0 to 1.0 - Quat currentShakeQuat;//what the current angular shake - Vec3 currentShakeShift;//what is the current translational shake - - // For damping camera movement. - Vec3 targetPos; // Where the target was. - float frameTime; // current dt. - float angleVel; // previous rate of change of angle. - float vel; // previous rate of change of dist between target and camera. - float dist; // previous dist of cam from target - - //blending - bool blend; - float blendPosSpeed; - float blendRotSpeed; - float blendFOVSpeed; - Vec3 blendPosOffset; - Quat blendRotOffset; - float blendFOVOffset; - bool justActivated; - -private: - uint8 viewIDLast; - Vec3 positionLast;//last view position - Quat rotationLast;//last view orientation - float FOVLast; -}; - -struct IAnimSequence; -struct SCameraParams; - -struct IView -{ - virtual ~IView() {} - struct SShakeParams - { - Ang3 shakeAngle; - Vec3 shakeShift; - float sustainDuration; - float fadeInDuration; - float fadeOutDuration; - float frequency; - float randomness; - int shakeID; - bool bFlipVec; - bool bUpdateOnly; - bool bGroundOnly; - bool bPermanent; // if true, sustainDuration is ignored - bool isSmooth; - - SShakeParams() - : shakeAngle(0, 0, 0) - , shakeShift(0, 0, 0) - , sustainDuration(0) - , fadeInDuration(0) - , fadeOutDuration(2.f) - , frequency(0) - , randomness(0) - , shakeID(0) - , bFlipVec(true) - , bUpdateOnly(false) - , bGroundOnly(false) - , bPermanent(false) - , isSmooth(false) - { - } - }; - - virtual void Release() = 0; - virtual void Update(float frameTime, bool isActive) = 0; - virtual void LinkTo(AZ::Entity* follow) = 0; - virtual void Unlink() = 0; - virtual AZ::EntityId GetLinkedId() = 0; - virtual CCamera& GetCamera() = 0; - virtual const CCamera& GetCamera() const = 0; - - virtual void Serialize(TSerialize ser) = 0; - virtual void PostSerialize() = 0; - virtual void SetCurrentParams(SViewParams& params) = 0; - virtual const SViewParams* GetCurrentParams() = 0; - virtual void SetViewShake(Ang3 shakeAngle, Vec3 shakeShift, float duration, float frequency, float randomness, int shakeID, bool bFlipVec = true, bool bUpdateOnly = false, bool bGroundOnly = false) = 0; - virtual void SetViewShakeEx(const SShakeParams& params) = 0; - virtual void StopShake(int shakeID) = 0; - virtual void ResetShaking() = 0; - virtual void ResetBlending() = 0; - virtual void SetFrameAdditiveCameraAngles(const Ang3& addFrameAngles) = 0; - virtual void SetScale(const float scale) = 0; - virtual void SetZoomedScale(const float scale) = 0; - virtual void SetActive(const bool bActive) = 0; - virtual void UpdateAudioListener(const Matrix34& rMatrix) = 0; -}; - -struct IViewSystemListener -{ - virtual ~IViewSystemListener() {} - virtual bool OnBeginCutScene(IAnimSequence* pSeq, bool bResetFX) = 0; - virtual bool OnEndCutScene(IAnimSequence* pSeq) = 0; - virtual bool OnCameraChange(const SCameraParams& cameraParams) = 0; -}; - -struct IViewSystem -{ - virtual ~IViewSystem() {} - virtual void Release() = 0; - virtual void Update(float frameTime) = 0; - virtual IView* CreateView() = 0; - virtual unsigned int AddView(IView* pView) = 0; - virtual void RemoveView(IView* pView) = 0; - virtual void RemoveView(unsigned int viewId) = 0; - - virtual void SetActiveView(IView* pView) = 0; - virtual void SetActiveView(unsigned int viewId) = 0; - - //utility functions - virtual IView* GetView(unsigned int viewId) = 0; - virtual IView* GetActiveView() = 0; - - virtual unsigned int GetViewId(IView* pView) = 0; - virtual unsigned int GetActiveViewId() = 0; - - virtual IView* GetViewByEntityId(const AZ::EntityId& id, bool forceCreate = false) = 0; - - virtual bool AddListener(IViewSystemListener* pListener) = 0; - virtual bool RemoveListener(IViewSystemListener* pListener) = 0; - - virtual void Serialize(TSerialize ser) = 0; - virtual void PostSerialize() = 0; - - // Get default distance to near clipping plane. - virtual float GetDefaultZNear() = 0; - - virtual void SetBlendParams(float fBlendPosSpeed, float fBlendRotSpeed, bool performBlendOut) = 0; - - // Used by time demo playback. - virtual void SetOverrideCameraRotation(bool bOverride, Quat rotation) = 0; - - virtual bool IsPlayingCutScene() const = 0; - - virtual void UpdateSoundListeners() = 0; - - virtual void SetDeferredViewSystemUpdate(bool const bDeferred) = 0; - virtual bool UseDeferredViewSystemUpdate() const = 0; - virtual void SetControlAudioListeners(bool const bActive) = 0; - virtual void ForceUpdate(float elapsed) = 0; -}; - -#endif // CRYINCLUDE_CRYACTION_IVIEWSYSTEM_H diff --git a/Code/CryEngine/CryCommon/IWindowMessageHandler.h b/Code/CryEngine/CryCommon/IWindowMessageHandler.h deleted file mode 100644 index 855fc585d8..0000000000 --- a/Code/CryEngine/CryCommon/IWindowMessageHandler.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef _CRY_WINDOW_MESSAGE_HANDLER_H_ -#define _CRY_WINDOW_MESSAGE_HANDLER_H_ -#include "platform.h" -#if defined(WIN32) -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif -#include <windows.h> - -// Summary: -// Window message handler for Windows OS -struct IWindowMessageHandler -{ - // Summary: - // The low-level pre-process message handler for Windows - // This is called before TranslateMessage/DispatchMessage (which will eventually end up in the HandleMessage handler) - // Typically, do not implement this function. - virtual void PreprocessMessage([[maybe_unused]] HWND hWnd, [[maybe_unused]] UINT uMsg, [[maybe_unused]] WPARAM wParam, [[maybe_unused]] LPARAM lParam) {} - - // Summary: - // The low-level window message handler for Windows - // The return value specifies if the implementation wants to modify the message handling result - // When returning true, the desired result value should be written through the pResult pointer - // When returning false, the value stored through pResult (if any) is ignored - // If more than one implementation write different results, the behavior is undefined - // If none of the implementations write any result, the default OS result will be used instead - // In general, return false if the handler doesn't care about the message, or only uses it for informational purposes - virtual bool HandleMessage([[maybe_unused]] HWND hWnd, [[maybe_unused]] UINT uMsg, [[maybe_unused]] WPARAM wParam, [[maybe_unused]] LPARAM lParam, [[maybe_unused]] LRESULT* pResult) { return false; } -}; -#else -// Summary: -// Dummy window message handler -// This is used for platforms that don't use window message handlers -struct IWindowMessageHandler -{ -}; -#endif -#endif diff --git a/Code/CryEngine/CryCommon/IXml.h b/Code/CryEngine/CryCommon/IXml.h deleted file mode 100644 index 19bc010a39..0000000000 --- a/Code/CryEngine/CryCommon/IXml.h +++ /dev/null @@ -1,950 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_IXML_H -#define CRYINCLUDE_CRYCOMMON_IXML_H -#pragma once - -#include <platform.h> -#include <Cry_Math.h> -#include <AzCore/IO/FileIO.h> - -class ICrySizer; - -template <class T> -struct Color_tpl; -typedef Color_tpl<uint8> ColorB; - -template <typename F> -struct Vec2_tpl; -typedef Vec2_tpl<f32> Vec2; -typedef Vec2_tpl<f64> Vec2d; - -template <typename F> -struct Vec3_tpl; -typedef Vec3_tpl<f32> Vec3; -typedef Vec3_tpl<f64> Vec3d; - -template <typename F> -struct Vec4_tpl; -typedef Vec4_tpl<f32> Vec4; -typedef Vec4_tpl<f64> Vec4d; - -template <typename F> -struct Quat_tpl; -typedef Quat_tpl<f32> Quat; - -template <typename F> -struct Ang3_tpl; -typedef Ang3_tpl<f32> Ang3; - - -#if defined(QT_VERSION) -#include <QColor> -#include <QString> -#elif defined(_AFX) -#include "Util/GuidUtil.h" -#endif - -#include <AzCore/Math/Guid.h> -#include <AzCore/Math/Uuid.h> - -class QColor; -class QString; - -class IXMLBinarySerializer; -struct IReadWriteXMLSink; -struct ISerialize; - -/* -This is wrapper around expat library to provide DOM type of access for xml. -Do not use IXmlNode class directly instead always use XmlNodeRef wrapper that -takes care of memory management issues. - -Usage Example: -------------------------------------------------------- -void testXml(bool bReuseStrings) -{ - XmlParser xml(bReuseStrings); - XmlNodeRef root = xml.ParseFile("test.xml", true); - - if (root) - { - for (int i = 0; i < root->getChildCount(); ++i) - { - XmlNodeRef child = root->getChild(i); - if (child->isTag("world")) - { - if (child->getAttr("name") == "blah") - { - .... - } - } - } - } -} -*/ - -// Summary: -// Special string wrapper for xml nodes. -class XmlString - : public string -{ -public: - XmlString() {}; - XmlString(const char* str) - : string(str) {}; - - operator const char*() const { - return c_str(); - } -}; - -// Summary: -// XML string data. -struct IXmlStringData -{ - // <interfuscator:shuffle> - virtual ~IXmlStringData(){} - virtual void AddRef() = 0; - virtual void Release() = 0; - virtual const char* GetString() = 0; - virtual size_t GetStringLength() = 0; - // </interfuscator:shuffle> -}; - -class IXmlNode; - -// Summary: -// XmlNodeRef, wrapper class implementing reference counting for IXmlNode. -// See also: -// IXmlNode -class XmlNodeRef -{ -private: - IXmlNode* p; -public: - XmlNodeRef() - : p(NULL) {} - XmlNodeRef(IXmlNode* p_); - XmlNodeRef(const XmlNodeRef& p_); - - ~XmlNodeRef(); - - operator IXmlNode*() const { - return p; - } - - IXmlNode& operator*() const { return *p; } - IXmlNode* operator->(void) const { return p; } - - XmlNodeRef& operator=(IXmlNode* newp); - XmlNodeRef& operator=(const XmlNodeRef& newp); - -#if !defined(RESOURCE_COMPILER) - template<typename Sizer > - void GetMemoryUsage(Sizer* pSizer) const - { - pSizer->AddObject(p); - } -#endif - - //Support for range based for, and stl algorithms. - class XmlNodeRefIterator begin(); - class XmlNodeRefIterator end(); -}; - -// Summary: -// IXmlNode class -// Notes: -// Never use IXmlNode directly instead use reference counted XmlNodeRef. -// See also: -// XmlNodeRef -class IXmlNode -{ -protected: - int m_nRefCount; - -protected: - // <interfuscator:shuffle> - virtual void DeleteThis() = 0; - virtual ~IXmlNode() {}; - // </interfuscator:shuffle> - -public: - - // <interfuscator:shuffle> - // Summary: - // Creates new XML node. - virtual XmlNodeRef createNode(const char* tag) = 0; - - // Notes: - // AddRef/Release need to be virtual to permit overloading from CXMLNodePool - - // Summary: - // Reference counting. - virtual void AddRef() { m_nRefCount++; }; - // Notes: - // When ref count reach zero XML node dies. - virtual void Release() - { - if (--m_nRefCount <= 0) - { - DeleteThis(); - } - }; - virtual int GetRefCount() const { return m_nRefCount; }; - - // Summary: - // Gets XML node tag. - virtual const char* getTag() const = 0; - // Summary: - // Sets XML node tag. - virtual void setTag(const char* tag) = 0; - - // Summary: - // Returns true if a given tag equal to node tag. - virtual bool isTag(const char* tag) const = 0; - - // Summary: - // Gets XML Node attributes. - virtual int getNumAttributes() const = 0; - // Summary: - // Returns attribute key and value by attribute index. - virtual bool getAttributeByIndex(int index, const char** key, const char** value) = 0; - - // Summary: - // Copies attributes to this node from a given node. - virtual void copyAttributes(XmlNodeRef fromNode) = 0; - - // Summary: - // Gets XML Node attribute for specified key. - // Return Value: - // The value of the attribute if it exists, otherwise an empty string. - virtual const char* getAttr(const char* key) const = 0; - - // Summary: - // Gets XML Node attribute for specified key. - // Return Value: - // True if the attribute exists, false otherwise. - virtual bool getAttr(const char* key, const char** value) const = 0; - - // Summary: - // Checks if attributes with specified key exist. - virtual bool haveAttr(const char* key) const = 0; - - // Summary: - // Adds new child node. - virtual void addChild(const XmlNodeRef& node) = 0; - - // Summary: - // Creates new xml node and add it to childs list. - virtual XmlNodeRef newChild(const char* tagName) = 0; - - // Summary: - // Removes child node. - virtual void removeChild(const XmlNodeRef& node) = 0; - - // Summary: - // Inserts child node. - virtual void insertChild(int nIndex, const XmlNodeRef& node) = 0; - - // Summary: - // Replaces a specified child with the passed one - // Not supported by all node implementations - virtual void replaceChild(int nIndex, const XmlNodeRef& fromNode) = 0; - - // Summary: - // Removes all child nodes. - virtual void removeAllChilds() = 0; - - // Summary: - // Gets number of child XML nodes. - virtual int getChildCount() const = 0; - - // Summary: - // Gets XML Node child nodes. - virtual XmlNodeRef getChild(int i) const = 0; - - // Summary: - // Finds node with specified tag. - virtual XmlNodeRef findChild(const char* tag) const = 0; - - // Summary: - // Gets parent XML node. - virtual XmlNodeRef getParent() const = 0; - - // Summary: - // Sets parent XML node. - virtual void setParent(const XmlNodeRef& inRef) = 0; - - // Summary: - // Returns content of this node. - virtual const char* getContent() const = 0; - // Summary: - // Sets content of this node. - virtual void setContent(const char* str) = 0; - - // Summary: - // Deep clone of this and all child xml nodes. - virtual XmlNodeRef clone() = 0; - - // Summary: - // Returns line number for XML tag. - virtual int getLine() const = 0; - // Summary: - // Set line number in xml. - virtual void setLine(int line) = 0; - - // Summary: - // Returns XML of this node and sub nodes. - // Notes: - // IXmlStringData pointer must be release when string is not needed anymore. - // See also: - // IXmlStringData - virtual IXmlStringData* getXMLData(int nReserveMem = 0) const = 0; - // Summary: - // Returns XML of this node and sub nodes. - virtual XmlString getXML(int level = 0) const = 0; - virtual bool saveToFile(const char* fileName) = 0; - - // Summary: - // Sets new XML Node attribute (or override attribute with same key). - //##@{ - virtual void setAttr(const char* key, const char* value) = 0; - virtual void setAttr(const char* key, int value) = 0; - virtual void setAttr(const char* key, unsigned int value) = 0; - virtual void setAttr(const char* key, int64 value) = 0; - virtual void setAttr(const char* key, uint64 value, bool useHexFormat = true) = 0; - virtual void setAttr(const char* key, float value) = 0; - virtual void setAttr(const char* key, double value) = 0; - virtual void setAttr(const char* key, const Vec2& value) = 0; - virtual void setAttr(const char* key, const Vec2d& value) = 0; - virtual void setAttr(const char* key, const Ang3& value) = 0; - virtual void setAttr(const char* key, const Vec3& value) = 0; - virtual void setAttr(const char* key, const Vec4& value) = 0; - virtual void setAttr(const char* key, const Vec3d& value) = 0; - virtual void setAttr(const char* key, const Quat& value) = 0; -#if defined(LINUX64) || defined(APPLE) - // Compatibility functions, on Linux and Mac long int is the default int64_t - ILINE void setAttr(const char* key, unsigned long int value, bool useHexFormat = true) - { - setAttr(key, (uint64)value, useHexFormat); - } - - ILINE void setAttr(const char* key, long int value) - { - setAttr(key, (int64)value); - } -#endif - - virtual void setAttr([[maybe_unused]] const char* key, [[maybe_unused]] const QColor& color) - { -#if defined(QT_VERSION) - setAttr(key, static_cast<unsigned long>(color.red() | (color.green() << 8) | (color.blue() << 16))); -#endif - } - //##@} - - // Summary: - // Inline Helpers. - //##@{ - //##@} - - // Summary: - // Deletes attribute. - virtual void delAttr(const char* key) = 0; - // Summary: - // Removes all node attributes. - virtual void removeAllAttributes() = 0; - - // Summary: - // Gets attribute value of node. - //##@{ - virtual bool getAttr(const char* key, int& value) const = 0; - virtual bool getAttr(const char* key, unsigned int& value) const = 0; - virtual bool getAttr(const char* key, int64& value) const = 0; - virtual bool getAttr(const char* key, uint64& value, bool useHexFormat = true) const = 0; - virtual bool getAttr(const char* key, float& value) const = 0; - virtual bool getAttr(const char* key, double& value) const = 0; - virtual bool getAttr(const char* key, Vec2& value) const = 0; - virtual bool getAttr(const char* key, Vec2d& value) const = 0; - virtual bool getAttr(const char* key, Ang3& value) const = 0; - virtual bool getAttr(const char* key, Vec3& value) const = 0; - virtual bool getAttr(const char* key, Vec4& value) const = 0; - virtual bool getAttr(const char* key, Vec3d& value) const = 0; - virtual bool getAttr(const char* key, Quat& value) const = 0; - virtual bool getAttr(const char* key, bool& value) const = 0; - virtual bool getAttr(const char* key, XmlString& value) const = 0; - virtual bool getAttr(const char* key, ColorB& value) const = 0; - -#if defined(LINUX64) || defined(APPLE) - // Compatibility functions, on Linux and Mac long int is the default int64_t - ILINE bool getAttr(const char* key, unsigned long int& value, bool useHexFormat = true) const - { - return getAttr(key, (uint64&)value, useHexFormat); - } - - ILINE bool getAttr(const char* key, long int& value) const - { - return getAttr(key, (int64&)value); - } -#endif - - // </interfuscator:shuffle> - -#if !defined(RESOURCE_COMPILER) - // <interfuscator:shuffle> - // Summary: - // Collect all allocated memory - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - - // Summary: - // Copies children to this node from a given node. - // Children are reference copied (shallow copy) and the children's parent is NOT set to this - // node, but left with its original parent (which is still the parent) - virtual void shareChildren(const XmlNodeRef& fromNode) = 0; - - // Summary: - // Removes child node at known position. - virtual void deleteChildAt(int nIndex) = 0; - - // Summary: - // Returns XML of this node and sub nodes into tmpBuffer without XML checks (much faster) - virtual XmlString getXMLUnsafe(int level, [[maybe_unused]] char* tmpBuffer, [[maybe_unused]] uint32 sizeOfTmpBuffer) const { return getXML(level); } - - // Notes: - // Save in small memory chunks. - virtual bool saveToFile(const char* fileName, size_t chunkSizeBytes, AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle) = 0; - // </interfuscator:shuffle> -#endif - - //##@} - - // Summary: - // Inline Helpers. - //##@{ -#if !defined(LINUX64) && !defined(APPLE) - bool getAttr(const char* key, long& value) const - { - int v; - if (getAttr(key, v)) - { - value = static_cast<long>(v); - return true; - } - else - { - return false; - } - } - bool getAttr(const char* key, unsigned long& value) const - { - int v; - if (getAttr(key, v)) - { - value = static_cast<unsigned long>(v); - return true; - } - else - { - return false; - } - } - void setAttr(const char* key, unsigned long value) { setAttr(key, (unsigned int)value); }; - void setAttr(const char* key, long value) { setAttr(key, (int)value); }; -#endif - bool getAttr(const char* key, unsigned short& value) const - { - int v; - if (getAttr(key, v)) - { - value = static_cast<unsigned short>(v); - return true; - } - else - { - return false; - } - } - bool getAttr(const char* key, unsigned char& value) const - { - int v; - if (getAttr(key, v)) - { - value = static_cast<unsigned char>(v); - return true; - } - else - { - return false; - } - } - bool getAttr(const char* key, short& value) const - { - int v; - if (getAttr(key, v)) - { - value = static_cast<short>(v); - return true; - } - else - { - return false; - } - } - bool getAttr(const char* key, char& value) const - { - int v; - if (getAttr(key, v)) - { - value = static_cast<char>(v); - return true; - } - else - { - return false; - } - } - //##@} - - // Summary: - // Gets QString attribute. - bool getAttr([[maybe_unused]] const char* key, [[maybe_unused]] QString& value) const - { -#if defined(QT_VERSION) - if (!haveAttr(key)) - { - return false; - } - value = getAttr(key); - return true; -#else - return false; -#endif - } - - bool getAttr([[maybe_unused]] const char* key, [[maybe_unused]] QColor& color) const - { -#if defined(QT_VERSION) - if (!haveAttr(key)) - { - return false; - } - int v; - getAttr(key, v); - color = QColor(v & 0xff, (v >> 8) & 0xff, (v >> 16) & 0xff); - return true; -#else - return false; -#endif - } - -#if defined(QT_VERSION) - // Summary: - // Sets GUID attribute. - void setAttr(const char* key, const GUID& value) - { - AZ::Uuid uuid; - uuid = value; - setAttr(key, uuid.ToString<AZStd::string>().c_str()); - }; - - // Summary: - // Gets GUID from attribute. - bool getAttr(const char* key, GUID& value) const - { - if (!haveAttr(key)) - { - return false; - } - const char* guidStr = getAttr(key); - value = AZ::Uuid(guidStr); - if (value.Data1 == 0) - { - memset(&value, 0, sizeof(value)); - // If bad GUID, use old guid system. - value.Data1 = atoi(guidStr); - } - return true; - } -#elif defined(_AFX) - // Summary: - // Sets GUID attribute. - void setAttr(const char* key, REFGUID value) - { - const char* str = GuidUtil::ToString(value); - setAttr(key, str); - }; - - // Summary: - // Gets GUID from attribute. - bool getAttr(const char* key, GUID& value) const - { - if (!haveAttr(key)) - { - return false; - } - const char* guidStr = getAttr(key); - value = GuidUtil::FromString(guidStr); - if (value.Data1 == 0) - { - memset(&value, 0, sizeof(value)); - // If bad GUID, use old guid system. - value.Data1 = atoi(guidStr); - } - return true; - } -#endif - - // Summary: - // Lets be friendly to him. - friend class XmlNodeRef; -}; - -/* -// Summary: -// Inline Implementation of XmlNodeRef -inline XmlNodeRef::XmlNodeRef(const char *tag, IXmlNode *node) -{ - if (node) - { - p = node->createNode(tag); - } - else - { - p = new XmlNode(tag); - } - p->AddRef(); -} -*/ - -////////////////////////////////////////////////////////////////////////// -inline XmlNodeRef::XmlNodeRef(IXmlNode* p_) - : p(p_) -{ - if (p) - { - p->AddRef(); - } -} - -inline XmlNodeRef::XmlNodeRef(const XmlNodeRef& p_) - : p(p_.p) -{ - if (p) - { - p->AddRef(); - } -} - -inline XmlNodeRef::~XmlNodeRef() -{ - if (p) - { - p->Release(); - } -} - -inline XmlNodeRef& XmlNodeRef::operator=(IXmlNode* newp) -{ - if (newp) - { - newp->AddRef(); - } - if (p) - { - p->Release(); - } - p = newp; - return *this; -} - -inline XmlNodeRef& XmlNodeRef::operator=(const XmlNodeRef& newp) -{ - if (newp.p) - { - newp.p->AddRef(); - } - if (p) - { - p->Release(); - } - p = newp.p; - return *this; -} - - -//XmlNodeRef can be treated as a container. Iterating through it, iterates through its children -class XmlNodeRefIterator -{ -public: - XmlNodeRefIterator() - : m_index(0) - { - } - XmlNodeRefIterator(XmlNodeRef& parentNode, std::size_t index) - : m_parentNode(parentNode) - , m_index(index) - { - Update(); - } - - XmlNodeRefIterator& operator=(const XmlNodeRefIterator& other) = default; - - XmlNodeRefIterator& operator++() - { - ++m_index; - Update(); - return *this; - } - XmlNodeRefIterator operator++(int) - { - XmlNodeRefIterator ret = *this; - ++m_index; - Update(); - return ret; - } - - IXmlNode* operator*() const - { - return m_currentChildNode; - } - - XmlNodeRefIterator& operator--() - { - --m_index; - Update(); - return *this; - } - - XmlNodeRefIterator operator--(int) - { - XmlNodeRefIterator ret = *this; - --m_index; - Update(); - return ret; - } - - bool operator!=(const XmlNodeRefIterator& rhs) { - return m_index != rhs.m_index; - } - -private: - friend void swap(XmlNodeRefIterator& lhs, XmlNodeRefIterator& rhs); - friend bool operator==(const XmlNodeRefIterator& lhs, const XmlNodeRefIterator& rhs); - friend bool operator!=(const XmlNodeRefIterator& lhs, const XmlNodeRefIterator& rhs); - - void Update() - { - if (m_index >= 0 && m_index < m_parentNode->getChildCount()) - { - m_currentChildNode = m_parentNode->getChild(static_cast<int>(m_index)); - } - } - - XmlNodeRef m_parentNode; - XmlNodeRef m_currentChildNode; - std::size_t m_index; //default to first child, if no children then this will equal size which is what we use for the end iterator -}; - -inline void swap(XmlNodeRefIterator& lhs, XmlNodeRefIterator& rhs) -{ - AZStd::swap(lhs.m_parentNode, rhs.m_parentNode); - AZStd::swap(lhs.m_currentChildNode, rhs.m_currentChildNode); - AZStd::swap(lhs.m_index, rhs.m_index); -} - -inline bool operator==(const XmlNodeRefIterator& lhs, const XmlNodeRefIterator& rhs) -{ - return lhs.m_index == rhs.m_index; -} - -inline bool operator!=(const XmlNodeRefIterator& lhs, const XmlNodeRefIterator& rhs) -{ - return lhs.m_index != rhs.m_index; -} - -inline XmlNodeRefIterator XmlNodeRef::begin() -{ - return XmlNodeRefIterator(*this, 0); -} - -inline XmlNodeRefIterator XmlNodeRef::end() -{ - return XmlNodeRefIterator(*this, (*this)->getChildCount()); -} - -////////////////////////////////////////////////////////////////////////// -struct IXmlSerializer -{ - // <interfuscator:shuffle> - virtual ~IXmlSerializer(){} - virtual void AddRef() = 0; - virtual void Release() = 0; - - virtual ISerialize* GetWriter(XmlNodeRef& node) = 0; - virtual ISerialize* GetReader(XmlNodeRef& node) = 0; - // </interfuscator:shuffle> -#if !defined(RESOURCE_COMPILER) - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; -#endif -}; - -#if !defined(RESOURCE_COMPILER) -////////////////////////////////////////////////////////////////////////// -// Summary: -// XML Parser interface. -struct IXmlParser -{ - // <interfuscator:shuffle> - virtual ~IXmlParser(){} - virtual void AddRef() = 0; - virtual void Release() = 0; - - // Summary: - // Parses xml file. - virtual XmlNodeRef ParseFile(const char* filename, bool bCleanPools) = 0; - - // Summary: - // Parses xml from memory buffer. - virtual XmlNodeRef ParseBuffer(const char* buffer, int nBufLen, bool bCleanPools, bool bSuppressWarnings = false) = 0; - - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - // </interfuscator:shuffle> -}; - -////////////////////////////////////////////////////////////////////////// -// Summary: -// XML Table Reader interface. -// -// Can be used to read tables exported from Excel in .xml format. Supports -// reading CryEngine's version of those Excel .xml tables (produced by RC). -// -// Usage: -// p->Begin(rootNode); -// while (p->ReadRow(...)) -// { -// while (p->ReadCell(...)) -// { -// ... -// } -// } -struct IXmlTableReader -{ - // <interfuscator:shuffle> - virtual ~IXmlTableReader(){} - - virtual void Release() = 0; - - // Returns false if XML tree is not in supported table format. - virtual bool Begin(XmlNodeRef rootNode) = 0; - - // Returns estimated number of rows (estimated number of ReadRow() calls returning true). - // Returned number is equal *or greater* than real number, because it's impossible to - // know real number in advance in case of Excel XML. - virtual int GetEstimatedRowCount() = 0; - - // Prepares next row for reading by ReadCell(). - // Returns true and sets rowIndex if the row was prepared successfully. - // Note: empty rows are skipped sometimes, so use returned rowIndex if you need - // to know absolute row index. - // Returns false if no rows left. - virtual bool ReadRow(int& rowIndex) = 0; - - // Reads next cell in the current row. - // Returns true and sets columnIndex, pContent, contenSize if the cell was read successfully. - // Note: empty cells are skipped sometimes, so use returned cellIndex if you need - // to know absolute cell index (i.e. column). - // Returns false if no cells left in the row. - virtual bool ReadCell(int& columnIndex, const char*& pContent, size_t& contentSize) = 0; - virtual float GetCurrentRowHeight() = 0; - // </interfuscator:shuffle> -}; -#endif - -////////////////////////////////////////////////////////////////////////// -// Summary: -// IXmlUtils structure. -struct IXmlUtils -{ - // <interfuscator:shuffle> - virtual ~IXmlUtils(){} - - // Summary: - // Loads xml file, returns 0 if load failed. - virtual XmlNodeRef LoadXmlFromFile(const char* sFilename, bool bReuseStrings = false, bool bEnablePatching = true) = 0; - // Summary: - // Loads xml from memory buffer, returns 0 if load failed. - virtual XmlNodeRef LoadXmlFromBuffer(const char* buffer, size_t size, bool bReuseStrings = false, bool bSuppressWarnings = false) = 0; - - // Summary: - // Creates an MD5 hash of an XML file - virtual const char* HashXml(XmlNodeRef node) = 0; - - // Summary: - // Gets an object that can read a xml into a IReadXMLSink - // and writes a xml from a IWriteXMLSource - virtual IReadWriteXMLSink* GetIReadWriteXMLSink() = 0; - - // Summary: - // Creates XML Writer for ISerialize interface. - // See also: - // IXmlSerializer - virtual IXmlSerializer* CreateXmlSerializer() = 0; - // </interfuscator:shuffle> - -#if !defined(RESOURCE_COMPILER) - // <interfuscator:shuffle> - // Summary: - // Creates XML Parser. - // Notes: - // WARNING!!! - // IXmlParser does not normally support recursive XML loading, all nodes loaded by this parser are invalidated on loading new file. - // This is a specialized interface for fast loading of many XMLs, - // After use it must be released with call to Release method. - virtual IXmlParser* CreateXmlParser() = 0; - - // Summary: - // Creates XML to file in the binary form. - virtual bool SaveBinaryXmlFile(const char* sFilename, XmlNodeRef root) = 0; - // Summary: - // Reads XML data from file in the binary form. - virtual XmlNodeRef LoadBinaryXmlFile(const char* sFilename, bool bEnablePatching = true) = 0; - - // Summary: - // Enables or disables checking for binary xml files. - // Return Value: - // The previous status. - virtual bool EnableBinaryXmlLoading(bool bEnable) = 0; - - // Summary: - // Creates XML Table reader. - // Notes: - // After use it must be released with call to Release method. - virtual IXmlTableReader* CreateXmlTableReader() = 0; - - // Init xml stats nodes pool - virtual void InitStatsXmlNodePool(uint32 nPoolSize) = 0; - - // Creates new xml node for statistics. - virtual XmlNodeRef CreateStatsXmlNode(const char* sNodeName) = 0; - // Set owner thread - virtual void SetStatsOwnerThread(threadID threadId) = 0; - - // Free memory held on to by xml pool if empty - virtual void FlushStatsXmlNodePool() = 0; - - // Sets the patch which is used to transform loaded XML files. the patch itself is encoded into XML - // Set to NULL to clear an existing transform and disable further patching - virtual void SetXMLPatcher(XmlNodeRef* pPatcher) = 0; - // </interfuscator:shuffle> -#endif -}; - -#endif // CRYINCLUDE_CRYCOMMON_IXML_H diff --git a/Code/CryEngine/CryCommon/LCGRandom.h b/Code/CryEngine/CryCommon/LCGRandom.h deleted file mode 100644 index 169f1b1be0..0000000000 --- a/Code/CryEngine/CryCommon/LCGRandom.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_LCGRANDOM_H -#define CRYINCLUDE_CRYCOMMON_LCGRANDOM_H -#pragma once - -#include "BaseTypes.h" // uint32, uint64 -#include "CryRandomInternal.h" // CryRandom_Internal::BoundedRandom - - -// A simple Linear Congruential Generator (LCG) of pseudo-randomized numbers. -// NOTE: It should *not* be used for any encryption methods. -// -// We use Microsoft Visual/Quick C/C++ generator's settings (mul 214013, add 2531011) -// (see http://en.wikipedia.org/wiki/Linear_congruential_generator), but our generator -// returns results that are different from Microsoft's: -// Microsoft's version returns 15-bit values (bits 30..16 of the 32-bit state), -// our version returns 32-bit values (bits 47..16 of the 64-bit state). - -class CRndGen -{ -public: - CRndGen() - { - Seed(5489UL); - } - - CRndGen(uint32 seed) - { - Seed(seed); - } - - // Initializes the generator using an unsigned 32-bit number. - void Seed(uint32 seed) - { - m_state = (uint64)seed; - } - - // Generates a random number in the closed interval [0; max uint32]. - uint32 GenerateUint32() - { - m_state = ((uint64)214013) * m_state + ((uint64)2531011); - return (uint32)(m_state >> 16); - } - - // Generates a random number in the closed interval [0; max uint64]. - uint64 GenerateUint64() - { - const uint32 a = GenerateUint32(); - const uint32 b = GenerateUint32(); - return ((uint64)b << 32) | (uint64)a; - } - - // Generates a random number in the closed interval [0.0f; 1.0f]. - float GenerateFloat() - { - return (float)GenerateUint32() * (1.0f / 4294967295.0f); - } - - // Ranged function returns random value within the *inclusive* range - // between minValue and maxValue. - // Any orderings work correctly: minValue <= maxValue and - // minValue >= minValue. - template <class T> - T GetRandom(const T minValue, const T maxValue) - { - return CryRandom_Internal::BoundedRandom<CRndGen, T>::Get(*this, minValue, maxValue); - } - - // Vector (Vec2, Vec3, Vec4) ranged function returns vector with - // every component within the *inclusive* ranges between minValue.component - // and maxValue.component. - // All orderings work correctly: minValue.component <= maxValue.component and - // minValue.component >= maxValue.component. - template <class T> - T GetRandomComponentwise(const T& minValue, const T& maxValue) - { - return CryRandom_Internal::BoundedRandomComponentwise<CRndGen, T>::Get(*this, minValue, maxValue); - } - - // The function returns a random unit vector (Vec2, Vec3, Vec4). - template <class T> - T GetRandomUnitVector() - { - return CryRandom_Internal::GetRandomUnitVector<CRndGen, T>(*this); - } - -private: - uint64 m_state; -}; - -#endif // CRYINCLUDE_CRYCOMMON_LCGRANDOM_H diff --git a/Code/CryEngine/CryCommon/LegacyAllocator.h b/Code/CryEngine/CryCommon/LegacyAllocator.h deleted file mode 100644 index 0b79e99f7a..0000000000 --- a/Code/CryEngine/CryCommon/LegacyAllocator.h +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include <AzCore/Memory/AllocatorBase.h> -#include <AzCore/Memory/HphaSchema.h> - -#define AZCORE_SYS_ALLOCATOR_HPPA -//#define AZCORE_SYS_ALLOCATOR_MALLOC - -#ifdef AZCORE_SYS_ALLOCATOR_HPPA -# include <AzCore/Memory/HphaSchema.h> -#elif defined(AZCORE_SYS_ALLOCATOR_MALLOC) -# include <AzCore/Memory/MallocSchema.h> -#else -# include <AzCore/Memory/HeapSchema.h> -#endif - -namespace AZ -{ - -#ifdef AZCORE_SYS_ALLOCATOR_HPPA - typedef AZ::HphaSchema LegacyAllocatorSchema; -#elif defined(AZCORE_SYS_ALLOCATOR_MALLOC) - typedef AZ::MallocSchema LegacyAllocatorSchema; -#else - typedef AZ::HeapSchema LegacyAllocatorSchema; -#endif - - struct LegacyAllocatorDescriptor - : public LegacyAllocatorSchema::Descriptor - { - LegacyAllocatorDescriptor() - { - // pull 32MB from the OS at a time -#ifdef AZCORE_SYS_ALLOCATOR_HPPA - m_systemChunkSize = 32 * 1024 * 1024; -#endif - } - }; - - class LegacyAllocator - : public SimpleSchemaAllocator<AZ::HphaSchema, LegacyAllocatorDescriptor> - { - public: - AZ_TYPE_INFO(LegacyAllocator, "{17FC25A4-92D9-48C5-BB85-7F860FCA2C6F}"); - - using Descriptor = LegacyAllocatorDescriptor; - using Base = SimpleSchemaAllocator<AZ::HphaSchema, LegacyAllocatorDescriptor>; - - LegacyAllocator() - : Base("LegacyAllocator", "Allocator for Legacy CryEngine systems") - { - } - - pointer_type Allocate(size_type byteSize, size_type alignment, int flags = 0, const char* name = 0, const char* fileName = 0, int lineNum = 0, unsigned int suppressStackRecord = 0) override - { - if (alignment == 0) - { - // Some STL containers, like std::vector, are assuming a specific minimum alignment. seems to have a requirement - // Take a look at _Allocate_manually_vector_aligned in xmemory0 - alignment = sizeof(void*) * 2; - } - - pointer_type ptr = m_schema->Allocate(byteSize, alignment, flags, name, fileName, lineNum, suppressStackRecord); - AZ_PROFILE_MEMORY_ALLOC_EX(AZ::Debug::ProfileCategory::MemoryReserved, fileName, lineNum, ptr, byteSize, name ? name : GetName()); - AZ_MEMORY_PROFILE(ProfileAllocation(ptr, byteSize, alignment, name, fileName, lineNum, suppressStackRecord)); - AZ_Assert(ptr || byteSize == 0, "OOM - Failed to allocate %zu bytes from LegacyAllocator", byteSize); - return ptr; - } - - // DeAllocate with file/line, to track when allocs were freed from Cry - void DeAllocate(pointer_type ptr, [[maybe_unused]] const char* file, [[maybe_unused]] const int line, size_type byteSize = 0, size_type alignment = 0) - { - AZ_PROFILE_MEMORY_FREE_EX(AZ::Debug::ProfileCategory::MemoryReserved, file, line, ptr); - AZ_MEMORY_PROFILE(ProfileDeallocation(ptr, byteSize, alignment, nullptr)); - m_schema->DeAllocate(ptr, byteSize, alignment); - } - - // Realloc with file/line, because Cry uses realloc(nullptr) and realloc(ptr, 0) to mimic malloc/free - pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment, [[maybe_unused]] const char* file, [[maybe_unused]] const int line) - { - if (newAlignment == 0) - { - // Some STL containers, like std::vector, are assuming a specific minimum alignment. seems to have a requirement - // Take a look at _Allocate_manually_vector_aligned in xmemory0 - newAlignment = sizeof(void*) * 2; - } - - AZ_MEMORY_PROFILE(ProfileReallocationBegin(ptr, newSize)); - AZ_PROFILE_MEMORY_FREE_EX(AZ::Debug::ProfileCategory::MemoryReserved, file, line, ptr); - pointer_type newPtr = m_schema->ReAllocate(ptr, newSize, newAlignment); - AZ_PROFILE_MEMORY_ALLOC_EX(AZ::Debug::ProfileCategory::MemoryReserved, file, line, newPtr, newSize, "LegacyAllocator Realloc"); - AZ_MEMORY_PROFILE(ProfileReallocationEnd(ptr, newPtr, newSize, newAlignment)); - AZ_Assert(newPtr || newSize == 0, "OOM - Failed to reallocate %zu bytes from LegacyAllocator", newSize); - return newPtr; - } - - void DeAllocate(pointer_type ptr, size_type byteSize = 0, size_type alignment = 0) override - { - AZ_MEMORY_PROFILE(ProfileDeallocation(ptr, 0, 0, nullptr)); - Base::DeAllocate(ptr, byteSize, alignment); - } - - pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment) override - { - if (newAlignment == 0) - { - // Some STL containers, like std::vector, are assuming a specific minimum alignment. seems to have a requirement - // Take a look at _Allocate_manually_vector_aligned in xmemory0 - newAlignment = sizeof(void*) * 2; - } - - AZ_MEMORY_PROFILE(ProfileReallocationBegin(ptr, newSize)); - pointer_type newPtr = Base::ReAllocate(ptr, newSize, newAlignment); - AZ_MEMORY_PROFILE(ProfileReallocationEnd(ptr, newPtr, newSize, newAlignment)); - AZ_Assert(newPtr || newSize == 0, "OOM - Failed to reallocate %zu bytes from LegacyAllocator", newSize); - return newPtr; - } - }; - - using StdLegacyAllocator = AZStdAlloc<LegacyAllocator>; - - // Specialize for the LegacyAllocator to provide one per module that does not use the - // environment for its storage - template <> - class AllocatorInstance<LegacyAllocator> : public Internal::AllocatorInstanceBase<LegacyAllocator> - { - }; - -#if defined(AZ_PLATFORM_PROVO) || defined(AZ_PLATFORM_JASPER) - struct GlobalAllocatorDescriptor - : public AZ::HphaSchema::Descriptor - { - GlobalAllocatorDescriptor() - { - // pull 1MB from the OS at a time - m_systemChunkSize = 1024 * 1024; - } - }; - - class GlobalAllocator - : public SimpleSchemaAllocator<AZ::HphaSchema, GlobalAllocatorDescriptor> - { - public: - AZ_TYPE_INFO(GlobalAllocator, "{BC7861DA-AF7F-4FFD-A2F5-BAD89BDD77FD}"); - - using Descriptor = GlobalAllocatorDescriptor; - using Base = SimpleSchemaAllocator<AZ::HphaSchema, GlobalAllocatorDescriptor>; - - GlobalAllocator() - : Base("GlobalAllocator", "Allocator for untracked new/delete/malloc/free") - { - } - - //--------------------------------------------------------------------- - // IAllocatorAllocate - //--------------------------------------------------------------------- - pointer_type Allocate(size_type byteSize, size_type alignment, int flags = 0, const char* name = 0, const char* fileName = 0, int lineNum = 0, unsigned int suppressStackRecord = 0) override - { - // Note: We cannot put the asserts in the AllocateBase class because various allocators depend on allocations failing from some heap classes. - pointer_type ptr = Base::Allocate(byteSize, alignment, flags, name, fileName, lineNum, suppressStackRecord); - AZ_Assert(ptr, "OOM - Failed to allocate %zu bytes from GlobalAllocator", byteSize); - return ptr; - } - - pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment) override - { - pointer_type newPtr = Base::ReAllocate(ptr, newSize, newAlignment); - AZ_Assert(newPtr, "OOM - Failed to reallocate %zu bytes from GlobalAllocator", newSize); - return newPtr; - } - - }; - - // Specialize for the GlobalAllocator to provide one per module that does not use the - // environment for its storage - template <> - class AllocatorInstance<GlobalAllocator> : public Internal::AllocatorInstanceBase<GlobalAllocator, AllocatorStorage::ModuleStoragePolicy<GlobalAllocator, false>> - { - }; -#endif -} diff --git a/Code/CryEngine/CryCommon/Linux32Specific.h b/Code/CryEngine/CryCommon/Linux32Specific.h deleted file mode 100644 index 19f7a5bba0..0000000000 --- a/Code/CryEngine/CryCommon/Linux32Specific.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Specific to Linux declarations, inline functions etc. - - -#ifndef CRYINCLUDE_CRYCOMMON_LINUX32SPECIFIC_H -#define CRYINCLUDE_CRYCOMMON_LINUX32SPECIFIC_H -#pragma once - - -#define _CPU_X86 -//#define _CPU_SSE - -#define DEBUG_BREAK raise(SIGTRAP) -#define RC_EXECUTABLE "rc" -#define USE_CRT 1 -#define SIZEOF_PTR 4 - -////////////////////////////////////////////////////////////////////////// -// Standard includes. -////////////////////////////////////////////////////////////////////////// -#include <malloc.h> -//#include <winbase.h> -#include <stdint.h> -#include <sys/dir.h> -#include <sys/io.h> -#include <fcntl.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <time.h> -#include <ctype.h> -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// Define platform independent types. -////////////////////////////////////////////////////////////////////////// -#include "BaseTypes.h" - -typedef signed long long INT64; - -typedef double real; - -typedef unsigned long DWORD; -typedef unsigned long* LPDWORD; -typedef DWORD DWORD_PTR; -typedef int INT_PTR, * PINT_PTR; -typedef unsigned int UINT_PTR, * PUINT_PTR; -typedef char* LPSTR, * PSTR; - -typedef long LONG_PTR, * PLONG_PTR, * PLONG; -typedef unsigned long ULONG_PTR, * PULONG_PTR; - -typedef unsigned char BYTE; -typedef unsigned short WORD; -typedef void* HWND; -typedef UINT_PTR WPARAM; -typedef LONG_PTR LPARAM; -typedef LONG_PTR LRESULT; -#define PLARGE_INTEGER LARGE_INTEGER * -typedef const char* LPCSTR, * PCSTR; -typedef long long LONGLONG; -typedef ULONG_PTR SIZE_T; -typedef unsigned char byte; - -#define __int64 long long - -#define ILINE __forceinline - -#define _A_RDONLY (0x01) -#define _A_SUBDIR (0x10) - -////////////////////////////////////////////////////////////////////////// -// Win32 FileAttributes. -////////////////////////////////////////////////////////////////////////// -#define FILE_ATTRIBUTE_READONLY 0x00000001 -#define FILE_ATTRIBUTE_HIDDEN 0x00000002 -#define FILE_ATTRIBUTE_SYSTEM 0x00000004 -#define FILE_ATTRIBUTE_DIRECTORY 0x00000010 -#define FILE_ATTRIBUTE_ARCHIVE 0x00000020 -#define FILE_ATTRIBUTE_DEVICE 0x00000040 -#define FILE_ATTRIBUTE_NORMAL 0x00000080 -#define FILE_ATTRIBUTE_TEMPORARY 0x00000100 -#define FILE_ATTRIBUTE_SPARSE_FILE 0x00000200 -#define FILE_ATTRIBUTE_REPARSE_POINT 0x00000400 -#define FILE_ATTRIBUTE_COMPRESSED 0x00000800 -#define FILE_ATTRIBUTE_OFFLINE 0x00001000 -#define FILE_ATTRIBUTE_NOT_CONTENT_INDEXED 0x00002000 -#define FILE_ATTRIBUTE_ENCRYPTED 0x00004000 - -#define INVALID_FILE_ATTRIBUTES (-1) - -#define DEFINE_ALIGNED_DATA(type, name, alignment) \ - type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \ - static type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \ - const type __attribute__ ((aligned(alignment))) name; - -#include "LinuxSpecific.h" - -#define TARGET_DEFAULT_ALIGN (0x4U) - -#endif // CRYINCLUDE_CRYCOMMON_LINUX32SPECIFIC_H diff --git a/Code/CryEngine/CryCommon/Linux64Specific.h b/Code/CryEngine/CryCommon/Linux64Specific.h deleted file mode 100644 index f1a72ec236..0000000000 --- a/Code/CryEngine/CryCommon/Linux64Specific.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Specific to Linux declarations, inline functions etc. - - -#ifndef CRYINCLUDE_CRYCOMMON_LINUX64SPECIFIC_H -#define CRYINCLUDE_CRYCOMMON_LINUX64SPECIFIC_H -#pragma once - - - -//#define _CPU_X86 -#define _CPU_AMD64 -#define _CPU_SSE - -#define DEBUG_BREAK ::raise(SIGTRAP) -#define RC_EXECUTABLE "rc" -#define USE_CRT 1 -#define SIZEOF_PTR 8 - -////////////////////////////////////////////////////////////////////////// -// Standard includes. -////////////////////////////////////////////////////////////////////////// -#include <malloc.h> -#include <stdint.h> -#include <sys/dir.h> -#include <sys/io.h> -#include <fcntl.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <time.h> -#include <ctype.h> - -#if defined(_CPU_SSE) -#include <xmmintrin.h> -#endif -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// Define platform independent types. -////////////////////////////////////////////////////////////////////////// -#include "BaseTypes.h" - -typedef double real; - -typedef uint32 DWORD; -typedef DWORD* LPDWORD; -typedef uint64 DWORD_PTR; -typedef intptr_t INT_PTR, * PINT_PTR; -typedef uintptr_t UINT_PTR, * PUINT_PTR; -typedef char* LPSTR, * PSTR; -typedef uint64 __uint64; -#if !defined(__clang__) -typedef int64 __int64; -#endif -typedef int64 INT64; -typedef uint64 UINT64; - -typedef long LONG_PTR, * PLONG_PTR, * PLONG; -typedef unsigned long ULONG_PTR, * PULONG_PTR; - -typedef uint8 BYTE; -typedef uint16 WORD; -typedef void* HWND; -typedef UINT_PTR WPARAM; -typedef LONG_PTR LPARAM; -typedef LONG_PTR LRESULT; -#define PLARGE_INTEGER LARGE_INTEGER * -typedef const char* LPCSTR, * PCSTR; -typedef long long LONGLONG; -typedef ULONG_PTR SIZE_T; -typedef uint8 byte; -#define ILINE __forceinline -#define _A_RDONLY (0x01) -#define _A_SUBDIR (0x10) -#define _A_HIDDEN (0x02) - -////////////////////////////////////////////////////////////////////////// -// Win32 FileAttributes. -////////////////////////////////////////////////////////////////////////// -#define FILE_ATTRIBUTE_READONLY 0x00000001 -#define FILE_ATTRIBUTE_HIDDEN 0x00000002 -#define FILE_ATTRIBUTE_SYSTEM 0x00000004 -#define FILE_ATTRIBUTE_DIRECTORY 0x00000010 -#define FILE_ATTRIBUTE_ARCHIVE 0x00000020 -#define FILE_ATTRIBUTE_DEVICE 0x00000040 -#define FILE_ATTRIBUTE_NORMAL 0x00000080 -#define FILE_ATTRIBUTE_TEMPORARY 0x00000100 -#define FILE_ATTRIBUTE_SPARSE_FILE 0x00000200 -#define FILE_ATTRIBUTE_REPARSE_POINT 0x00000400 -#define FILE_ATTRIBUTE_COMPRESSED 0x00000800 -#define FILE_ATTRIBUTE_OFFLINE 0x00001000 -#define FILE_ATTRIBUTE_NOT_CONTENT_INDEXED 0x00002000 -#define FILE_ATTRIBUTE_ENCRYPTED 0x00004000 - -#define INVALID_FILE_ATTRIBUTES (-1) - -#define DEFINE_ALIGNED_DATA(type, name, alignment) \ - type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) \ - static type __attribute__ ((aligned(alignment))) name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) \ - const type __attribute__ ((aligned(alignment))) name; - -#include "LinuxSpecific.h" - -#define TARGET_DEFAULT_ALIGN (0x8U) - -#define PLATFORM_64BIT - -#ifdef _RELEASE - #define __debugbreak() -#else - #define __debugbreak() "_asm int 3" -#endif - -#define __assume(x) - -#define _msize(p) malloc_usable_size(p) - -#endif // CRYINCLUDE_CRYCOMMON_LINUX64SPECIFIC_H diff --git a/Code/CryEngine/CryCommon/LinuxSpecific.h b/Code/CryEngine/CryCommon/LinuxSpecific.h deleted file mode 100644 index 8ecee9bfff..0000000000 --- a/Code/CryEngine/CryCommon/LinuxSpecific.h +++ /dev/null @@ -1,593 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Specific to Linux declarations, inline functions etc. - - -#ifndef CRYINCLUDE_CRYCOMMON_LINUXSPECIFIC_H -#define CRYINCLUDE_CRYCOMMON_LINUXSPECIFIC_H -#pragma once - - -#include <stdlib.h> -#include <time.h> -#include <pthread.h> -#include <math.h> -#include <string.h> -#include <errno.h> -#include <ctype.h> -#include <algorithm> -#include <signal.h> -#ifndef __COUNTER__ -#define __COUNTER__ __LINE__ -#endif -#include <sys/types.h> -#include <unistd.h> -#include <fcntl.h> -#include <stdio.h> -#if defined(APPLE) -#include <dirent.h> -#endif //defined(APPLE) -#if !defined(SKIP_INET_INCLUDES) -#include <arpa/inet.h> -#include <netinet/in.h> -#include <arpa/inet.h> -#endif // defined(SKIP_INET_INCLUDES) -#include <vector> -#include <string> - -#ifdef __FUNC__ -#undef __FUNC__ -#endif -#if defined(__GNUC__) || defined(__clang__) -#define __FUNC__ __func__ -#else -#define __FUNC__ \ - ({ \ - static char __f[sizeof(__PRETTY_FUNCTION__) + 1]; \ - strcpy(__f, __PRETTY_FUNCTION__); \ - char* __p = (char*)strchr(__f, '('); \ - *__p = 0; \ - while (*(__p) != ' ' && __p != (__f - 1)) {--__p; } \ - (__p + 1); \ - }) -#endif - -typedef void* LPVOID; -#define VOID void -#define PVOID void* - -typedef unsigned int UINT; -typedef char CHAR; -typedef float FLOAT; - -#define PHYSICS_EXPORTS -// MSVC compiler-specific keywords -#define __forceinline inline -#define _inline inline -#define __cdecl -#define _cdecl -#define __stdcall -#define _stdcall -#define __fastcall -#define _fastcall -#define IN -#define OUT - -#ifdef AZ_MONOLITHIC_BUILD -#if !defined(USE_STATIC_NAME_TABLE) -#define USE_STATIC_NAME_TABLE 1 -#endif -#endif // AZ_MONOLITHIC_BUILD - -#if !defined(_STLP_HASH_MAP) && !defined(USING_STLPORT) -#define _STLP_HASH_MAP 1 -#endif - -// Enable memory address tracing code. -#if !defined(MM_TRACE_ADDRS) // && !defined(NDEBUG) -#define MM_TRACE_ADDRS 1 -#endif - -#ifndef STDMETHODCALLTYPE_DEFINED -#define STDMETHODCALLTYPE_DEFINED -#define STDMETHODCALLTYPE -#endif - -#define _ALIGN(num) \ - __attribute__ ((aligned(num))) \ - AZ_POP_DISABLE_WARNING - -#define _PACK __attribute__ ((packed)) - -// Safe memory freeing -#ifndef SAFE_DELETE -#define SAFE_DELETE(p) { if (p) { delete (p); (p) = NULL; } \ -} -#endif - -#ifndef SAFE_DELETE_ARRAY -#define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p); (p) = NULL; } \ -} -#endif - -#ifndef SAFE_RELEASE -#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p) = NULL; } \ -} -#endif - - -#ifndef SAFE_RELEASE_FORCE -#define SAFE_RELEASE_FORCE(p) { if (p) { (p)->ReleaseForce(); (p) = NULL; } \ -} -#endif - -#define MAKEWORD(a, b) ((WORD)(((BYTE)((DWORD_PTR)(a) & 0xff)) | ((WORD)((BYTE)((DWORD_PTR)(b) & 0xff))) << 8)) -#define MAKELONG(a, b) ((LONG)(((WORD)((DWORD_PTR)(a) & 0xffff)) | ((DWORD)((WORD)((DWORD_PTR)(b) & 0xffff))) << 16)) -#define LOWORD(l) ((WORD)((DWORD_PTR)(l) & 0xffff)) -#define HIWORD(l) ((WORD)((DWORD_PTR)(l) >> 16)) -#define LOBYTE(w) ((BYTE)((DWORD_PTR)(w) & 0xff)) -#define HIBYTE(w) ((BYTE)((DWORD_PTR)(w) >> 8)) - -#define CALLBACK -#define WINAPI - -#ifndef __cplusplus -#ifndef _WCHAR_T_DEFINED -typedef unsigned short wchar_t; -#define TCHAR wchar_t; -#define _WCHAR_T_DEFINED -#endif -#endif -typedef wchar_t WCHAR; // wc, 16-bit UNICODE character -typedef WCHAR* PWCHAR; -typedef WCHAR* LPWCH, * PWCH; -typedef const WCHAR* LPCWCH, * PCWCH; -typedef WCHAR* NWPSTR; -typedef WCHAR* LPWSTR, * PWSTR; -typedef WCHAR* LPUWSTR, * PUWSTR; - -typedef const WCHAR* LPCWSTR, * PCWSTR; -typedef const WCHAR* LPCUWSTR, * PCUWSTR; - -#ifdef UNICODE -typedef LPCWSTR LPCTSTR; -typedef LPWSTR LPTSTR; -#else -typedef LPCSTR LPCTSTR; -typedef LPSTR LPTSTR; -#endif -typedef char TCHAR; - -typedef DWORD COLORREF; -#define RGB(r,g,b) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16))) - -#define GetRValue(rgb) (LOBYTE(rgb)) -#define GetGValue(rgb) (LOBYTE(((WORD)(rgb)) >> 8)) -#define GetBValue(rgb) (LOBYTE((rgb)>>16)) - -#define MAKEFOURCC(ch0, ch1, ch2, ch3) \ - ((DWORD)(BYTE)(ch0) | ((DWORD)(BYTE)(ch1) << 8) | \ - ((DWORD)(BYTE)(ch2) << 16) | ((DWORD)(BYTE)(ch3) << 24)) -#define FILE_ATTRIBUTE_NORMAL 0x00000080 - -typedef int BOOL; -typedef int32_t LONG; -typedef uint32_t ULONG; -typedef int HRESULT; - -#define BST_UNCHECKED 0x0000 - -#ifndef MAXUINT -#define MAXUINT ((uint) ~((uint)0)) -#endif - -#ifndef MAXINT -#define MAXINT ((int)(MAXUINT >> 1)) -#endif - -#if !defined(__clang__) -typedef int32 __int32; -typedef uint32 __uint32; -typedef int64 __int64; -typedef uint64 __uint64; -#endif - -#define THREADID_NULL -1 -typedef unsigned long int threadID; - -#define TRUE 1 -#define FALSE 0 - -#ifndef MAX_PATH - #define MAX_PATH 256 -#endif -#ifndef _MAX_PATH -#define _MAX_PATH MAX_PATH -#endif - -#define _PTRDIFF_T_DEFINED 1 - -//#define __TIMESTAMP__ __DATE__" "__TIME__ - -// function renaming -#define _finite __finite -#define _snprintf snprintf -#define _isnan isnan -#define stricmp strcasecmp -#define _stricmp strcasecmp -#define strnicmp strncasecmp -#define _strnicmp strncasecmp -#define wcsicmp wcscasecmp -#define wcsnicmp wcsncasecmp - - -#define _wtof(str) wcstod(str, 0) - -/*static unsigned char toupper(unsigned char c) -{ - return c & ~0x40; -} -*/ -typedef union _LARGE_INTEGER -{ - struct - { - DWORD LowPart; - LONG HighPart; - }; - struct - { - DWORD LowPart; - LONG HighPart; - } u; - long long QuadPart; -} LARGE_INTEGER; - - -// stdlib.h stuff -#define _MAX_DRIVE 3 // max. length of drive component -#define _MAX_DIR 256 // max. length of path component -#define _MAX_FNAME 256 // max. length of file name component -#define _MAX_EXT 256 // max. length of extension component - -// fcntl.h -#define _O_RDONLY 0x0000 /* open for reading only */ -#define _O_WRONLY 0x0001 /* open for writing only */ -#define _O_RDWR 0x0002 /* open for reading and writing */ -#define _O_APPEND 0x0008 /* writes done at eof */ -#define _O_CREAT 0x0100 /* create and open file */ -#define _O_TRUNC 0x0200 /* open and truncate */ -#define _O_EXCL 0x0400 /* open only if file doesn't already exist */ -#define _O_TEXT 0x4000 /* file mode is text (translated) */ -#define _O_BINARY 0x8000 /* file mode is binary (untranslated) */ -#define _O_RAW _O_BINARY -#define _O_NOINHERIT 0x0080 /* child process doesn't inherit file */ -#define _O_TEMPORARY 0x0040 /* temporary file bit */ -#define _O_SHORT_LIVED 0x1000 /* temporary storage file, try not to flush */ -#define _O_SEQUENTIAL 0x0020 /* file access is primarily sequential */ -#define _O_RANDOM 0x0010 /* file access is primarily random */ - -// curses.h stubs for PDcurses keys -#define PADENTER KEY_MAX + 1 -#define CTL_HOME KEY_MAX + 2 -#define CTL_END KEY_MAX + 3 -#define CTL_PGDN KEY_MAX + 4 -#define CTL_PGUP KEY_MAX + 5 - -// stubs for virtual keys, isn't used on Linux -#define VK_UP 0 -#define VK_DOWN 0 -#define VK_RIGHT 0 -#define VK_LEFT 0 -#define VK_CONTROL 0 -#define VK_SCROLL 0 - -enum -{ - IDOK = 1, - IDCANCEL = 2, - IDABORT = 3, - IDRETRY = 4, - IDIGNORE = 5, - IDYES = 6, - IDNO = 7, - IDTRYAGAIN = 10, - IDCONTINUE = 11 -}; - -#define ES_MULTILINE 0x0004L -#define ES_AUTOVSCROLL 0x0040L -#define ES_AUTOHSCROLL 0x0080L -#define ES_WANTRETURN 0x1000L - -#define LB_ERR (-1) - -#define LB_ADDSTRING 0x0180 -#define LB_GETCOUNT 0x018B -#define LB_SETTOPINDEX 0x0197 - -#define MB_OK 0x00000000L -#define MB_OKCANCEL 0x00000001L -#define MB_ABORTRETRYIGNORE 0x00000002L -#define MB_YESNOCANCEL 0x00000003L -#define MB_YESNO 0x00000004L -#define MB_RETRYCANCEL 0x00000005L -#define MB_CANCELTRYCONTINUE 0x00000006L - -#define MB_ICONQUESTION 0x00000020L -#define MB_ICONEXCLAMATION 0x00000030L - -#define MB_ICONERROR 0x00000010L -#define MB_ICONWARNING 0x00000030L -#define MB_ICONINFORMATION 0x00000040L - -#define MB_SETFOREGROUND 0x00010000L - -#define MB_APPLMODAL 0x00000000L - -#define MF_STRING 0x00000000L - -#define MK_LBUTTON 0x0001 -#define MK_RBUTTON 0x0002 -#define MK_SHIFT 0x0004 -#define MK_CONTROL 0x0008 -#define MK_MBUTTON 0x0010 - -#define MK_ALT ( 0x20 ) - -#define SM_MOUSEPRESENT 0x00000000L - -#define SM_CMOUSEBUTTONS 43 - -#define USER_TIMER_MINIMUM 0x0000000A - -#define VK_TAB 0x09 -#define VK_SHIFT 0x10 -#define VK_MENU 0x12 -#define VK_ESCAPE 0x1B -#define VK_SPACE 0x20 -#define VK_DELETE 0x2E - -#define VK_NUMPAD1 0x61 -#define VK_NUMPAD2 0x62 -#define VK_NUMPAD3 0x63 -#define VK_NUMPAD4 0x64 - -#define VK_OEM_COMMA 0xBC // ',' any country -#define VK_OEM_PERIOD 0xBE // '.' any country -#define VK_OEM_3 0xC0 // '`~' for US -#define VK_OEM_4 0xDB // '[{' for US -#define VK_OEM_6 0xDD // ']}' for US - -#define WAIT_TIMEOUT 258L // dderror - -#define WM_MOVE 0x0003 -#define WM_USER 0x0400 - -#define WHEEL_DELTA 120 - -#define WS_CHILD 0x40000000L -#define WS_VISIBLE 0x10000000L - -#define CB_ERR (-1) - -// io.h stuff -typedef unsigned int _fsize_t; - -#define _flushall() - -struct _OVERLAPPED; - -typedef void (* LPOVERLAPPED_COMPLETION_ROUTINE)(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, struct _OVERLAPPED* lpOverlapped); - -typedef struct _OVERLAPPED -{ - void* pCaller;//this is orginally reserved for internal purpose, we store the Caller pointer here - LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine; ////this is orginally ULONG_PTR InternalHigh and reserved for internal purpose - union - { - struct - { - DWORD Offset; - DWORD OffsetHigh; - }; - PVOID Pointer; - }; - DWORD dwNumberOfBytesTransfered; //additional member temporary speciying the number of bytes to be read - /*HANDLE*/ void* hEvent; -} OVERLAPPED, * LPOVERLAPPED; - -typedef struct _SECURITY_ATTRIBUTES -{ - DWORD nLength; - LPVOID lpSecurityDescriptor; - BOOL bInheritHandle; -} SECURITY_ATTRIBUTES, * PSECURITY_ATTRIBUTES, * LPSECURITY_ATTRIBUTES; - -#ifdef __cplusplus -extern bool QueryPerformanceCounter(LARGE_INTEGER*); -extern bool QueryPerformanceFrequency(LARGE_INTEGER* frequency); - -static pthread_mutex_t mutex_t; -template<typename T> -const volatile T InterlockedIncrement(volatile T* pT) -{ - pthread_mutex_lock(&mutex_t); - ++(*pT); - pthread_mutex_unlock(&mutex_t); - return *pT; -} - -template<typename T> -const volatile T InterlockedDecrement(volatile T* pT) -{ - pthread_mutex_lock(&mutex_t); - --(*pT); - pthread_mutex_unlock(&mutex_t); - return *pT; -} - -#if 0 -template<typename S, typename T> -inline const S& min(const S& rS, const T& rT) -{ - return (rS <= rT) ? rS : rT; -} - -template<typename S, typename T> -inline const S& max(const S& rS, const T& rT) -{ - return (rS >= rT) ? rS : rT; -} -#endif - -template<typename S, typename T> -inline S __min(const S& rS, const T& rT) -{ - return std::min(rS, rT); -} - -template<typename S, typename T> -inline S __max(const S& rS, const T& rT) -{ - return std::max(rS, rT); -} - - -typedef enum -{ - INVALID_HANDLE_VALUE = -1l -}INVALID_HANDLE_VALUE_ENUM; -//for compatibility reason we got to create a class which actually contains an int rather than a void* and make sure it does not get mistreated -template <class T, T U> -//U is default type for invalid handle value, T the encapsulated handle type to be used instead of void* (as under windows and never linux) -class CHandle -{ -public: - typedef T HandleType; - typedef void* PointerType; //for compatibility reason to encapsulate a void* as an int - - static const HandleType sciInvalidHandleValue = U; - - CHandle(const CHandle<T, U>& cHandle) - : m_Value(cHandle.m_Value){} - CHandle(const HandleType cHandle = U) - : m_Value(cHandle){} - CHandle(const PointerType cpHandle) - : m_Value(reinterpret_cast<HandleType>(cpHandle)){} - CHandle(INVALID_HANDLE_VALUE_ENUM) - : m_Value(U){} //to be able to use a common value for all InvalidHandle - types -#if defined(LINUX64) && !defined(__clang__) - //treat __null tyope also as invalid handle type - CHandle(__typeof__(__null)) - : m_Value(U){} //to be able to use a common value for all InvalidHandle - types -#endif - operator HandleType(){ - return m_Value; - } - bool operator!() const{return m_Value == sciInvalidHandleValue; } - const CHandle& operator =(const CHandle& crHandle){m_Value = crHandle.m_Value; return *this; } - const CHandle& operator =(const PointerType cpHandle){m_Value = (HandleType) reinterpret_cast<UINT_PTR>(cpHandle); return *this; } - const bool operator ==(const CHandle& crHandle) const{return m_Value == crHandle.m_Value; } - const bool operator ==(const HandleType cHandle) const{return m_Value == cHandle; } - const bool operator ==(const PointerType cpHandle) const{return m_Value == (HandleType) reinterpret_cast<UINT_PTR>(cpHandle); } - const bool operator !=(const HandleType cHandle) const{return m_Value != cHandle; } - const bool operator !=(const CHandle& crHandle) const{return m_Value != crHandle.m_Value; } - const bool operator !=(const PointerType cpHandle) const{return m_Value != (HandleType) reinterpret_cast<UINT_PTR>(cpHandle); } - const bool operator < (const CHandle& crHandle) const{return m_Value < crHandle.m_Value; } - HandleType Handle() const{return m_Value; } - -private: - HandleType m_Value; //the actual value, remember that file descriptors are ints under linux - - typedef void ReferenceType; //for compatibility reason to encapsulate a void* as an int - //forbid these function which would actually not work on an int - PointerType operator->(); - PointerType operator->() const; - ReferenceType operator*(); - ReferenceType operator*() const; - operator PointerType(); -}; - -typedef CHandle<int, (int) - 1l> HANDLE; - -typedef HANDLE EVENT_HANDLE; -typedef pid_t THREAD_HANDLE; - -typedef HANDLE HKEY; -// typedef HANDLE HDC; - -typedef HANDLE HBITMAP; - -typedef HANDLE HMENU; - -inline int64 CryGetTicks() -{ - LARGE_INTEGER counter; - QueryPerformanceCounter(&counter); - return counter.QuadPart; -} - -inline int64 CryGetTicksPerSec() -{ - LARGE_INTEGER li; - QueryPerformanceFrequency(&li); - return li.QuadPart; -} - -#endif //__cplusplus - -inline int _CrtCheckMemory() { return 1; }; - -inline char* _fullpath(char* absPath, const char* relPath, size_t maxLength) -{ - char path[PATH_MAX]; - - if (realpath(relPath, path) == NULL) - { - return NULL; - } - const size_t len = std::min(strlen(path), maxLength - 1); - memcpy(absPath, path, len); - absPath[len] = 0; - return absPath; -} - -typedef void* HGLRC; -typedef void* HDC; -typedef void* PROC; -typedef void* PIXELFORMATDESCRIPTOR; - -#define SCOPED_ENABLE_FLOAT_EXCEPTIONS - -// Linux_Win32Wrapper.h now included directly by platform.h -//#include "Linux_Win32Wrapper.h" - -#define closesocket close -inline int WSAGetLastError() -{ - return errno; -} - -template <typename T, size_t N> -char (*RtlpNumberOf( T (&)[N] ))[N]; - -#define RTL_NUMBER_OF_V2(A) (sizeof(*RtlpNumberOf(A))) - -#define ARRAYSIZE(A) RTL_NUMBER_OF_V2(A) - -#undef SUCCEEDED -#define SUCCEEDED(x) ((x) >= 0) -#undef FAILED -#define FAILED(x) (!(SUCCEEDED(x))) - -#endif // CRYINCLUDE_CRYCOMMON_LINUXSPECIFIC_H - -// vim:ts=2:sw=2:tw=78 - diff --git a/Code/CryEngine/CryCommon/Linux_Win32Wrapper.h b/Code/CryEngine/CryCommon/Linux_Win32Wrapper.h deleted file mode 100644 index 8b905ff025..0000000000 --- a/Code/CryEngine/CryCommon/Linux_Win32Wrapper.h +++ /dev/null @@ -1,716 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_LINUX_WIN32WRAPPER_H -#define CRYINCLUDE_CRYCOMMON_LINUX_WIN32WRAPPER_H -#pragma once - -#include <CryAssert.h> -#include <dirent.h> -#include <vector> -/* Memory block identification */ -#define _FREE_BLOCK 0 -#define _NORMAL_BLOCK 1 -#define _CRT_BLOCK 2 -#define _IGNORE_BLOCK 3 -#define _CLIENT_BLOCK 4 -#define _MAX_BLOCKS 5 - -typedef void* HMODULE; - -typedef struct _MEMORYSTATUS -{ - DWORD dwLength; - DWORD dwMemoryLoad; - SIZE_T dwTotalPhys; - SIZE_T dwAvailPhys; - SIZE_T dwTotalPageFile; - SIZE_T dwAvailPageFile; - SIZE_T dwTotalVirtual; - SIZE_T dwAvailVirtual; -} MEMORYSTATUS, * LPMEMORYSTATUS; - -extern void GlobalMemoryStatus(LPMEMORYSTATUS lpmem); - -#if defined(PLATFORM_64BIT) -# define MEMORY_ALLOCATION_ALIGNMENT 16 -#else -# define MEMORY_ALLOCATION_ALIGNMENT 8 -#endif - -#define S_OK 0 -#define THREAD_PRIORITY_NORMAL 0 -#define THREAD_PRIORITY_IDLE 0 -#define THREAD_PRIORITY_LOWEST 0 -#define THREAD_PRIORITY_BELOW_NORMAL 0 -#define THREAD_PRIORITY_ABOVE_NORMAL 0 -#define THREAD_PRIORITY_HIGHEST 0 -#define THREAD_PRIORITY_TIME_CRITICAL 0 -#define MAX_COMPUTERNAME_LENGTH 15 // required by CryOnline module - -#if 0 -//for compatibility reason we got to create a class which actually contains an int rather than a void* and make sure it does not get mistreated -template <class T, T U> -//U is default type for invalid handle value, T the encapsulated handle type to be used instead of void* (as under windows and never linux) -class CHandle -{ -public: - typedef T HandleType; - typedef void* PointerType; //for compatibility reason to encapsulate a void* as an int - - static const HandleType sciInvalidHandleValue = U; - - CHandle(const CHandle<T, U>& cHandle) - : m_Value(cHandle.m_Value){} - CHandle(const HandleType cHandle = U) - : m_Value(cHandle){} - //CHandle(const PointerType cpHandle) : m_Value(reinterpret_cast<HandleType>(cpHandle)){} - //CHandle(INVALID_HANDLE_VALUE_ENUM) : m_Value(U){}//to be able to use a common value for all InvalidHandle - types - - operator HandleType(){ - return m_Value; - } - bool operator!() const{return m_Value == sciInvalidHandleValue; } - const CHandle& operator =(const CHandle& crHandle){m_Value = crHandle.m_Value; return *this; } - const CHandle& operator =(const PointerType cpHandle){m_Value = reinterpret_cast<HandleType>(cpHandle); return *this; } - const bool operator ==(const CHandle& crHandle) const{return m_Value == crHandle.m_Value; } - const bool operator ==(const HandleType cHandle) const{return m_Value == cHandle; } - //const bool operator ==(const PointerType cpHandle)const{return m_Value == reinterpret_cast<HandleType>(cpHandle);} - const bool operator !=(const HandleType cHandle) const{return m_Value != cHandle; } - const bool operator !=(const CHandle& crHandle) const{return m_Value != crHandle.m_Value; } - //const bool operator !=(const PointerType cpHandle)const{return m_Value != reinterpret_cast<HandleType>(cpHandle);} - const bool operator < (const CHandle& crHandle) const{return m_Value < crHandle.m_Value; } - HandleType Handle() const{return m_Value; } - -private: - HandleType m_Value; //the actual value, remember that file descriptors are ints under linux - - typedef void ReferenceType;//for compatibility reason to encapsulate a void* as an int - //forbid these function which would actually not work on an int - PointerType operator->(); - PointerType operator->() const; - ReferenceType operator*(); - ReferenceType operator*() const; - operator PointerType(); -}; - -typedef CHandle<INT_PTR, (INT_PTR) 0> HANDLE; - -typedef HANDLE EVENT_HANDLE; -typedef HANDLE THREAD_HANDLE; - -#define INVALID_HANDLE_VALUE ((HANDLE)(LONG_PTR)-1) -#endif - -//#define __TIMESTAMP__ __DATE__" "__TIME__ - -// stdlib.h stuff -#define _MAX_DRIVE 3 // max. length of drive component -#define _MAX_DIR 256 // max. length of path component -#define _MAX_FNAME 256 // max. length of file name component -#define _MAX_EXT 256 // max. length of extension component - -// fcntl.h -#define _O_RDONLY 0x0000 /* open for reading only */ -#define _O_WRONLY 0x0001 /* open for writing only */ -#define _O_RDWR 0x0002 /* open for reading and writing */ -#define _O_APPEND 0x0008 /* writes done at eof */ -#define _O_CREAT 0x0100 /* create and open file */ -#define _O_TRUNC 0x0200 /* open and truncate */ -#define _O_EXCL 0x0400 /* open only if file doesn't already exist */ -#define _O_TEXT 0x4000 /* file mode is text (translated) */ -#define _O_BINARY 0x8000 /* file mode is binary (untranslated) */ -#define _O_RAW _O_BINARY -#define _O_NOINHERIT 0x0080 /* child process doesn't inherit file */ -#define _O_TEMPORARY 0x0040 /* temporary file bit */ -#define _O_SHORT_LIVED 0x1000 /* temporary storage file, try not to flush */ -#define _O_SEQUENTIAL 0x0020 /* file access is primarily sequential */ -#define _O_RANDOM 0x0010 /* file access is primarily random */ - -inline void MemoryBarrier() { - __sync_synchronize(); -} -// Memory barrier implementation taken from https://code.google.com/p/gperftools/ -//inline void MemoryBarrier() { -// __asm__ __volatile__("mfence" : : : "memory"); -//} - -#if !defined(_CPU_SSE) -typedef int64 __m128; -#endif - -#if defined(LINUX64) || defined(APPLE) -unsigned char _InterlockedCompareExchange128(int64 volatile* dst, int64 exchangehigh, int64 exchangelow, int64* comperand); -#endif -////////////////////////////////////////////////////////////////////////// -// io.h stuff -#if !defined(ANDROID) -extern int errno; -#endif -typedef unsigned int _fsize_t; - -struct _OVERLAPPED; -typedef _OVERLAPPED* LPOVERLAPPED; - -typedef void (* LPOVERLAPPED_COMPLETION_ROUTINE)(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, struct _OVERLAPPED* lpOverlapped); - -typedef struct tagRECT -{ - LONG left; - LONG top; - LONG right; - LONG bottom; -} RECT, * PRECT; - -typedef struct tagPOINT -{ - LONG x; - LONG y; -} POINT, * PPOINT; - -#ifndef _FILETIME_ -#define _FILETIME_ -typedef struct _FILETIME -{ - DWORD dwLowDateTime; - DWORD dwHighDateTime; -} FILETIME, * PFILETIME, * LPFILETIME; -#endif - -typedef union _ULARGE_INTEGER -{ - struct - { - DWORD LowPart; - DWORD HighPart; - }; - unsigned long long QuadPart; -} ULARGE_INTEGER; - -typedef ULARGE_INTEGER* PULARGE_INTEGER; - -#ifdef __cplusplus -inline LONG CompareFileTime(const FILETIME* lpFileTime1, const FILETIME* lpFileTime2) -#else -static LONG CompareFileTime(const FILETIME* lpFileTime1, const FILETIME* lpFileTime2) -#endif -{ - ULARGE_INTEGER u1, u2; - memcpy(&u1, lpFileTime1, sizeof u1); - memcpy(&u2, lpFileTime2, sizeof u2); - if (u1.QuadPart < u2.QuadPart) - { - return -1; - } - else - if (u1.QuadPart > u2.QuadPart) - { - return 1; - } - return 0; -} - -typedef struct _SYSTEMTIME -{ - WORD wYear; - WORD wMonth; - WORD wDayOfWeek; - WORD wDay; - WORD wHour; - WORD wMinute; - WORD wSecond; - WORD wMilliseconds; -} SYSTEMTIME, * PSYSTEMTIME, * LPSYSTEMTIME; - -typedef struct _TIME_FIELDS -{ - short Year; - short Month; - short Day; - short Hour; - short Minute; - short Second; - short Milliseconds; - short Weekday; -} TIME_FIELDS, * PTIME_FIELDS; - -#define DAYSPERNORMALYEAR 365 -#define DAYSPERLEAPYEAR 366 -#define MONSPERYEAR 12 - -inline void ZeroMemory(void* pPtr, int nSize) -{ - memset(pPtr, 0, nSize); -} - -inline BOOL InflateRect(RECT* pRect, int dx, int dy) -{ - pRect->left -= dx; - pRect->right += dx; - pRect->top -= dy; - pRect->bottom += dy; - return TRUE; -} - -////////////////////////////////////////////////////////////////////////// -extern BOOL SystemTimeToFileTime(const SYSTEMTIME* syst, LPFILETIME ft); -//Win32API function declarations actually used -extern bool IsBadReadPtr(void* ptr, unsigned int size); - -// Defined in the launcher. -DLL_IMPORT void OutputDebugString(const char*); -DLL_IMPORT void DebugBreak(); - -/* -//critical section stuff -#define pthread_attr_default NULL - -typedef pthread_mutex_t CRITICAL_SECTION; -#ifdef __cplusplus -inline void InitializeCriticalSection(CRITICAL_SECTION *lpCriticalSection) -{ -pthread_mutexattr_t pthread_mutexattr_def; -pthread_mutexattr_settype(&pthread_mutexattr_def, PTHREAD_MUTEX_RECURSIVE_NP); -pthread_mutex_init(lpCriticalSection, &pthread_mutexattr_def); -} -inline void EnterCriticalSection(CRITICAL_SECTION *lpCriticalSection){pthread_mutex_lock(lpCriticalSection);} -inline void LeaveCriticalSection(CRITICAL_SECTION *lpCriticalSection){pthread_mutex_unlock(lpCriticalSection);} -inline void DeleteCriticalSection(CRITICAL_SECTION *lpCriticalSection){} -#else -static void InitializeCriticalSection(CRITICAL_SECTION *lpCriticalSection) -{ -pthread_mutexattr_t pthread_mutexattr_def; -pthread_mutexattr_settype(&pthread_mutexattr_def, PTHREAD_MUTEX_RECURSIVE_NP); -pthread_mutex_init(lpCriticalSection, &pthread_mutexattr_def); -} -static void EnterCriticalSection(CRITICAL_SECTION *lpCriticalSection){pthread_mutex_lock(lpCriticalSection);} -static void LeaveCriticalSection(CRITICAL_SECTION *lpCriticalSection){pthread_mutex_unlock(lpCriticalSection);} -static void DeleteCriticalSection(CRITICAL_SECTION *lpCriticalSection){} -#endif -*/ - -extern bool QueryPerformanceCounter(LARGE_INTEGER* counter); -extern bool QueryPerformanceFrequency(LARGE_INTEGER* frequency); -#ifdef __cplusplus - -inline uint32 GetTickCount() -{ - LARGE_INTEGER count, freq; - QueryPerformanceCounter(&count); - QueryPerformanceFrequency(&freq); - return uint32(count.QuadPart * 1000 / freq.QuadPart); -} - -#define IGNORE 0 // Ignore signal -#define INFINITE 0xFFFFFFFF // Infinite timeout -#endif -//begin--------------------------------findfirst/-next declaration/implementation---------------------------------------------------- - - -////////////////////////////////////////////////////////////////////////// -// function renaming -#define _TRUNCATE (size_t(-1)) -#define _chmod chmod -#define _snprintf snprintf -#define stricmp strcasecmp -#define _stricmp strcasecmp -#define strnicmp strncasecmp -#define _strnicmp strncasecmp - -#define _strlwr strlwr -#define _strlwr_s(BUF, SIZE) strlwr(BUF) -#define _strups strupr - -#define _wtof(str) wcstod(str, 0) - -// Need to include this before using it's used in finddata, but after the strnicmp definition -#include "CryString.h" - -typedef struct __finddata64_t -{ - //!< atributes set by find request - unsigned int attrib; //!< attributes, only directory and readonly flag actually set - int64 time_create; //!< creation time, cannot parse under linux, last modification time is used instead (game does nowhere makes decision based on this values) - int64 time_access; //!< last access time - int64 time_write; //!< last modification time - int64 size; //!< file size (for a directory it will be the block size) - char name[256]; //!< file/directory name - -private: - int m_LastIndex; //!< last index for findnext - char m_DirectoryName[260]; //!< directory name, needed when getting file attributes on the fly - char m_ToMatch[260]; //!< pattern to match with - DIR* m_Dir; //!< directory handle - std::vector<string> m_Entries; //!< all file entries in the current directories -public: - - inline __finddata64_t() - : attrib(0) - , time_create(0) - , time_access(0) - , time_write(0) - , size(0) - , m_LastIndex(-1) - , m_Dir(NULL) - { - memset(name, '0', 256); - } - ~__finddata64_t(); - - //!< copies and retrieves the data for an actual match (to not waste any effort retrioeving data for unused files) - void CopyFoundData(const char* rMatchedFileName); - -public: - //!< global _findfirst64 function using struct above, can't be a member function due to required semantic match - friend intptr_t _findfirst64(const char* pFileName, __finddata64_t* pFindData); - //!< global _findnext64 function using struct above, can't be a member function due to required semantic match - friend int _findnext64(intptr_t last, __finddata64_t* pFindData); -}__finddata64_t; - -typedef struct _finddata_t - : public __finddata64_t -{}_finddata_t;//!< need inheritance since in many places it get used as struct _finddata_t -extern int _findnext64(intptr_t last, __finddata64_t* pFindData); -extern intptr_t _findfirst64(const char* pFileName, __finddata64_t* pFindData); - -extern DWORD GetFileAttributes(LPCSTR lpFileName); - -extern const bool GetFilenameNoCase(const char* file, char*, const bool cCreateNew = false); - -extern BOOL GetUserName(LPSTR lpBuffer, LPDWORD nSize); - -//error code stuff -//not thread specific, just a coarse implementation for the main thread -inline DWORD GetLastError() { return errno; } -inline void SetLastError(DWORD dwErrCode) { errno = dwErrCode; } - -////////////////////////////////////////////////////////////////////////// -#define GENERIC_READ (0x80000000L) -#define GENERIC_WRITE (0x40000000L) -#define GENERIC_EXECUTE (0x20000000L) -#define GENERIC_ALL (0x10000000L) - -#define CREATE_NEW 1 -#define CREATE_ALWAYS 2 -#define OPEN_EXISTING 3 -#define OPEN_ALWAYS 4 -#define TRUNCATE_EXISTING 5 - -#define FILE_SHARE_READ 0x00000001 -#define FILE_SHARE_WRITE 0x00000002 -#define OPEN_EXISTING 3 -#define FILE_FLAG_OVERLAPPED 0x40000000 -#define INVALID_FILE_SIZE ((DWORD)0xFFFFFFFFl) -#define FILE_BEGIN 0 -#define FILE_CURRENT 1 -#define FILE_END 2 -#define ERROR_NO_SYSTEM_RESOURCES 1450L -#define ERROR_INVALID_USER_BUFFER 1784L -#define ERROR_NOT_ENOUGH_MEMORY 8L -#define ERROR_PATH_NOT_FOUND 3L -#define FILE_FLAG_SEQUENTIAL_SCAN 0x08000000 - -////////////////////////////////////////////////////////////////////////// -extern threadID GetCurrentThreadId(); - -////////////////////////////////////////////////////////////////////////// -extern HANDLE CreateEvent( - LPSECURITY_ATTRIBUTES lpEventAttributes, - BOOL bManualReset, - BOOL bInitialState, - LPCSTR lpName - ); - -////////////////////////////////////////////////////////////////////////// -extern DWORD Sleep(DWORD dwMilliseconds); - -////////////////////////////////////////////////////////////////////////// -extern DWORD SleepEx(DWORD dwMilliseconds, BOOL bAlertable); - -////////////////////////////////////////////////////////////////////////// -extern DWORD WaitForSingleObjectEx( - HANDLE hHandle, - DWORD dwMilliseconds, - BOOL bAlertable); - -////////////////////////////////////////////////////////////////////////// -extern DWORD WaitForMultipleObjectsEx( - DWORD nCount, - const HANDLE* lpHandles, - BOOL bWaitAll, - DWORD dwMilliseconds, - BOOL bAlertable); - -////////////////////////////////////////////////////////////////////////// -extern DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds); - -////////////////////////////////////////////////////////////////////////// -extern BOOL SetEvent(HANDLE hEvent); - -////////////////////////////////////////////////////////////////////////// -extern BOOL ResetEvent(HANDLE hEvent); - -////////////////////////////////////////////////////////////////////////// -extern HANDLE CreateMutex( - LPSECURITY_ATTRIBUTES lpMutexAttributes, - BOOL bInitialOwner, - LPCSTR lpName - ); - -////////////////////////////////////////////////////////////////////////// -extern BOOL ReleaseMutex(HANDLE hMutex); - -////////////////////////////////////////////////////////////////////////// -typedef DWORD (* PTHREAD_START_ROUTINE)(LPVOID lpThreadParameter); -typedef PTHREAD_START_ROUTINE LPTHREAD_START_ROUTINE; - -////////////////////////////////////////////////////////////////////////// -extern HANDLE CreateThread( - LPSECURITY_ATTRIBUTES lpThreadAttributes, - SIZE_T dwStackSize, - LPTHREAD_START_ROUTINE lpStartAddress, - LPVOID lpParameter, - DWORD dwCreationFlags, - LPDWORD lpThreadId - ); - -extern BOOL GetComputerName(LPSTR lpBuffer, LPDWORD lpnSize); //required for CryOnline -extern DWORD GetCurrentProcessId(void); - -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -#ifdef __cplusplus - -//helper function -extern void adaptFilenameToLinux(char* rAdjustedFilename); -extern const int comparePathNames(const char* cpFirst, const char* cpSecond, unsigned int len);//returns 0 if identical -extern void replaceDoublePathFilename(char* szFileName);//removes "\.\" to "\" and "/./" to "/" - -////////////////////////////////////////////////////////////////////////// -extern char* _fullpath(char* absPath, const char* relPath, size_t maxLength); -////////////////////////////////////////////////////////////////////////// -extern void _makepath(char* path, const char* drive, const char* dir, const char* filename, const char* ext); - -template <size_t size> -void _makepath_s(char(&path)[size], const char *drive, const char *dir, const char *fname, const char *ext) -{ - _makepath(path, drive, dir, fname, ext); -} - -extern void _splitpath(const char* inpath, char* drv, char* dir, char* fname, char* ext); - -template <size_t drivesize, size_t dirsize, size_t fnamesize, size_t extsize> -void _splitpath_s(const char *path, char(&drive)[drivesize], char(&dir)[dirsize], char(&fname)[fnamesize], char(&ext)[extsize]) -{ - _splitpath(path, drive, dir, fname, ext); -} - - -////////////////////////////////////////////////////////////////////////// -extern int memicmp(LPCSTR s1, LPCSTR s2, DWORD len); - -extern "C" char* strlwr (char* str); -extern "C" char* strupr(char* str); - -extern char* _ui64toa(unsigned long long value, char* str, int radix); -extern long long _atoi64(const char* str); - -extern int* _errno(); - -template <size_t SIZE> -int vsprintf_s(char (&dst)[SIZE], const char* format, va_list argptr) -{ - vsnprintf(dst, SIZE, format, argptr); - dst[SIZE - 1] = 0; - return 0; -} - -inline int vsprintf_s(char* dst, size_t size, const char* format, va_list argptr) -{ - vsnprintf(dst, size, format, argptr); - dst[size - 1] = 0; - return 0; -} - -//note that behaviour is different from strncpy. -//this will not pad string with zeroes if length of src is less than 'size' - -inline int strncpy_s(char* dst, size_t buf_size, const char* src, size_t size) -{ - size_t to_copy = std::min(size, strlen(src)); - size_t term = std::min(buf_size - 1, to_copy);//length of result - strncpy(dst, src, term); - dst[term] = 0; - return 0; -} - -template <size_t SIZE> -inline int strncpy_s(char(&dst)[SIZE], const char* src, size_t size) -{ - size_t to_copy = std::min(size, strlen(src)); - size_t term = std::min(SIZE - 1, to_copy);//length of result - strncpy(dst, src, term); - dst[term] = 0; - return 0; -} - -inline int strcat_s(char* dst, size_t size, const char* src) -{ - if (!dst || !src) - { - return EINVAL; - } - size_t len_dst = strlen(dst); - size_t len_src = strlen(src); - if (size == 0 || len_dst + len_src + 1 >= size) - { - return ERANGE; - } - memcpy(dst + len_dst, src, len_src); - dst[len_dst + len_src] = 0; - return 0; -} - -template <size_t SIZE> -int strcat_s(char(&dst)[SIZE], const char* src) -{ - return strcat_s(dst, SIZE, src); -} - - -template <size_t SIZE> -int strcpy_s(char(&dst)[SIZE], const char* src) -{ - strncpy(dst, src, SIZE); - dst[SIZE - 1] = 0; - return 0; -} - -inline int strcpy_s(char* dst, size_t size, const char* src) -{ - strncpy(dst, src, size); - dst[size - 1] = 0; - return 0; -} - -inline int sprintf_s(char* buffer, size_t sizeOfBuffer, const char* format, ...) -{ - va_list args; - va_start(args, format); - int err = vsnprintf(buffer, sizeOfBuffer, format, args); - va_end(args); - return err; -} - -template <size_t size> -int sprintf_s(char (&buffer)[size], const char* format, ...) -{ - va_list args; - va_start(args, format); - int err = vsnprintf(buffer, size, format, args); - va_end(args); - return err; -} - -#ifdef _isnan -#undef _isnan -template <typename T> -bool _isnan(T value) -{ - return value != value; -} -#endif - - -#define vsnprintf_s(BUF, SIZE, COUNT, FORMAT, ARGVLIST) vsnprintf(BUF, SIZE, FORMAT, ARGVLIST) -#define _vsnwprintf_s(BUF, SIZE, COUNT, FORMAT, ARGVLIST) vswprintf(BUF, SIZE, FORMAT, ARGVLIST) -#define fprintf_s fprintf -#define sscanf_s sscanf -#define fread_s(BUF, SIZE, NMEMB, MAX, HANDLE) fread(BUF, SIZE, NMEMB, HANDLE) - -////////////////////////////////////////////////////////////////////////// - -#ifndef __TRLTOA__ -#define __TRLTOA__ -extern char* ltoa (long i, char* a, int radix); -#endif -#define itoa ltoa - -////////////////////////////////////////////////////////////////////////// -#if 0 -inline long int abs(long int x) -{ - return labs(x); -} - -inline float abs(float x) -{ - return fabsf(x); -} - -inline double abs(double x) -{ - return fabs(x); -} - -inline float sqrt(float x) -{ - return sqrtf(x); -} -#else -#include <cmath> -using std::abs; -using std::sqrt; -using std::fabs; -#endif - -extern char* _strtime(char* date); -extern char* _strdate(char* date); - -#if !defined(_CPU_SSE) -#define _MM_HINT_T0 (1) -#define _MM_HINT_T1 (2) -#define _MM_HINT_T2 (3) -#define _MM_HINT_NTA (0) -inline void _mm_prefetch(const char*, int) { } -#endif // !_CPU_SSE - -#endif //__cplusplus -////////////////////////////////////////////////////////////////////////// -// Byte Swapping functions - -inline unsigned short _byteswap_ushort(unsigned short input) -{ - return ((input & 0xff) << 8) | ((input & 0xff00) >> 8); -} - -inline LONG _byteswap_ulong(LONG input) -{ - return (input & 0x000000ff) << 24 | - (input & 0x0000ff00) << 8 | - (input & 0x00ff0000) >> 8 | - (input & 0xff000000) >> 24; -} - -inline unsigned long long _byteswap_uint64(unsigned long long input) -{ - return (((input & 0xff00000000000000ull) >> 56) | - ((input & 0x00ff000000000000ull) >> 40) | - ((input & 0x0000ff0000000000ull) >> 24) | - ((input & 0x000000ff00000000ull) >> 8) | - ((input & 0x00000000ff000000ull) << 8) | - ((input & 0x0000000000ff0000ull) << 24) | - ((input & 0x000000000000ff00ull) << 40) | - ((input & 0x00000000000000ffull) << 56)); -} - -#endif // CRYINCLUDE_CRYCOMMON_LINUX_WIN32WRAPPER_H - -// vim:ts=2 - diff --git a/Code/CryEngine/CryCommon/LoadScreenBus.h b/Code/CryEngine/CryCommon/LoadScreenBus.h deleted file mode 100644 index 65c87ade88..0000000000 --- a/Code/CryEngine/CryCommon/LoadScreenBus.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#define AZ_LOADSCREENCOMPONENT_ENABLED (1) - -#if AZ_LOADSCREENCOMPONENT_ENABLED - -#include <AzCore/Component/ComponentBus.h> - -class LoadScreenInterface - : public AZ::ComponentBus -{ -public: - using MutexType = AZStd::recursive_mutex; - - //! Invoked when the load screen should be updated and rendered. Single threaded loading only. - virtual void UpdateAndRender() = 0; - - //! Invoked when the game load screen should become visible. - virtual void GameStart() = 0; - - //! Invoked when the level load screen should become visible. - virtual void LevelStart() = 0; - - //! Invoked when the load screen should be paused. - virtual void Pause() = 0; - - //! Invoked when the load screen should be resumed. - virtual void Resume() = 0; - - //! Invoked when the load screen should be stopped. - virtual void Stop() = 0; - - //! Invoked to find out if loading screen is playing. - virtual bool IsPlaying() = 0; -}; -using LoadScreenBus = AZ::EBus<LoadScreenInterface>; - -//! Interface for notifying load screen providers that specific load events are happening. -//! This is meant to notify systems to connect/disconnect to the LoadScreenUpdateNotificationBus if necessary. -struct LoadScreenNotifications - : public AZ::EBusTraits -{ - //! Invoked when the game/engine loading starts. Returns true if any provider handles this. - virtual bool NotifyGameLoadStart(bool usingLoadingThread) = 0; - - //! Invoked when level loading starts. Returns true if any provider handles this. - virtual bool NotifyLevelLoadStart(bool usingLoadingThread) = 0; - - //! Invoked when loading finishes. - virtual void NotifyLoadEnd() = 0; -}; -using LoadScreenNotificationBus = AZ::EBus<LoadScreenNotifications>; - -//! Interface for triggering load screen updates and renders. Has different methods for single threaded vs multi threaded. -//! This is a separate bus from the LoadScreenNotificationBus to avoid threading issues and to allow implementers to conditionally attach -//! from inside LoadScreenNotificationBus::NotifyGameLoadStart/NotifyLevelLoadStart -struct LoadScreenUpdateNotifications - : public AZ::EBusTraits -{ - //! Invoked when the load screen should be updated and rendered. Single threaded loading only. - virtual void UpdateAndRender(float deltaTimeInSeconds) = 0; - - //! Invoked when the load screen should be updated. Multi-threaded loading only. - virtual void LoadThreadUpdate(float deltaTimeInSeconds) = 0; - - //! Invoked when the load screen should be updated. Multi-threaded loading only. - virtual void LoadThreadRender() = 0; -}; -using LoadScreenUpdateNotificationBus = AZ::EBus<LoadScreenUpdateNotifications>; - -#endif // if AZ_LOADSCREENCOMPONENT_ENABLED diff --git a/Code/CryEngine/CryCommon/LocalizationManagerBus.h b/Code/CryEngine/CryCommon/LocalizationManagerBus.h deleted file mode 100644 index e21c19dc5a..0000000000 --- a/Code/CryEngine/CryCommon/LocalizationManagerBus.h +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include <CrySizer.h> -#include <AzCore/EBus/EBus.h> -#include <AzCore/std/containers/vector.h> -#include <AzCore/std/string/string.h> -#include <AzCore/std/string/conversions.h> - -//////////////////////////////////////////////////////////////////////////////////////////////// -// Forward declarations -//////////////////////////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// Localization Utility classes/functions. -////////////////////////////////////////////////////////////////////////// - -template<typename... Args> -AZStd::vector<AZStd::string> MakeLocKeyList(Args... args) -{ - return {args...}; -} - -// Helper functions for Localization and data-string substitution -struct LocalizationHelpers -{ - // Returns the string version of any type convertible by std::to_string() - // otherwise throws a compile error. - template <typename T> - static AZStd::string DataToString(T t); - - // Need a function to specifically handle std::string, since std::to_string() doesn't handle it. - static inline AZStd::string DataToString(AZStd::string str); - - // Need a function to specifically handle const char*, since std::to_string() doesn't handle it. - static inline AZStd::string DataToString(const char* str); - - // Base case of the recursive function to convert a data list to strings - template<typename T> - static void ConvertValuesToStrings(AZStd::vector<AZStd::string>& values, T t); - - // Recursive function to convert a data list to strings - template<typename T, typename... Args> - static void ConvertValuesToStrings(AZStd::vector<AZStd::string>& values, T t, Args... args); - - // Check if a key string is in a list of substitution strings - static inline bool IsKeyInList(const AZStd::vector<AZStd::string>& keys, const AZStd::string& target, int& index); -}; - -////////////////////////////////////////////////////////////////////////// -// Localization manager bus interface. -////////////////////////////////////////////////////////////////////////// - -// Summary: -// Interface to the Localization Manager. -class LocalizationManagerRequests - : public AZ::EBusTraits -{ -public: - virtual bool SetLanguage(const char* sLanguage) = 0; - virtual const char* GetLanguage() = 0; - - virtual int GetLocalizationFormat() const = 0; - - // Get Localized subtitle file for current language - // Summary: - // Provides the asset path of a video subtitle file based on the input video path name. Input localVideoPath - // should contain the game-specific path after the current language folder. - // ex: - // input: localVideoPath = "/VideoSubtitleSrt/100/101/101VT_01.bnk" - // output: return "Localization/en-US/VideoSubtitleSrt/100/101/101VT_01.srt" - // - // NOTE: System expects that video file has the same name as the subtitle file (other than the file extension). - virtual AZStd::string GetLocalizedSubtitleFilePath(const AZStd::string& localVideoPath, const AZStd::string& subtitleFileExtension) const = 0; - - // Get the given xml for the current language - // Summary: - // Provides the asset path of a localization xml file given the local path (e.g. the path starting from - // your language folder). - virtual AZStd::string GetLocalizedLocXMLFilePath(const AZStd::string& localXmlPath) const = 0; - - virtual bool LoadExcelXmlSpreadsheet(const char* sFileName, bool bReload = false) = 0; - virtual void ReloadData() = 0; - - // Summary: - // Translate a string into the currently selected language. - // Description: - // Processes the input string and translates all labels contained into the currently selected language. - // Parameters: - // sString - String to be translated. - // outLocalizedString - Translated version of the string. - // bEnglish - if true, translates the string into the always present English language. - // Returns: - // true if localization was successful, false otherwise - virtual bool LocalizeString_ch(const char* sString, string& outLocalizedString, bool bEnglish = false) = 0; - - // Summary: - // Same as LocalizeString( const char* sString, string& outLocalizedString, bool bEnglish=false ) - // but at the moment this is faster. - virtual bool LocalizeString_s(const string& sString, string& outLocalizedString, bool bEnglish = false) = 0; - - // Set up system for passing in placeholder data for localized strings - // Summary: - // Parse localized string and substitute data in for each key that is surrounded by curly braces - // ie. {player_name} - virtual void LocalizeAndSubstituteInternal(AZStd::string& locString, const AZStd::vector<AZStd::string>& keys, const AZStd::vector<AZStd::string>& values) = 0; - - // Summary: - // Parse localized string and substitute data in for each key that is surrounded by curly braces. Number of arguments - // after 'const AZStd::vector<AZStd::string>& keys' should be equal to the number of strings in 'keys'. - // ex: - // float distance = GetWinDistance(); - // AZStd::string winState = IsPlayerFirstPlace() ? "won" : "lost"; - // LocalizationManagerRequests::Broadcast(&LocalizationManagerRequests::Events::LocalizeAndSubstitute<float, AZStd::string> - // , "@QUICKRESULTS_DISTANCEDIFFERENCE, outLocalizedString - // , MakeLocKeyString("race_result", "distance_ahead") - // , winState, distance); - // - // where "@QUICKRESULTS_DISTANCEDIFFERENCE" would be localized to "You {race_result} by {distance_ahead} meters!" and then - // "{race_result}" would be replaced by 'winState" and "{distance_ahead}" would be replaced by the 'distance' argument as a string. - template<typename T, typename... Args> - void LocalizeAndSubstitute(const AZStd::string& locString, AZStd::string& outLocalizedString, const AZStd::vector<AZStd::string>& keys, T t, Args... args); - - // Summary: - // Return the localized version corresponding to a label. - // Description: - // A label has to start with '@' sign. - // Parameters: - // sLabel - Label to be translated, must start with '@' sign. - // outLocalizedString - Localized version of the label. - // bEnglish - if true, returns the always present English version of the label. - // Returns: - // True if localization was successful, false otherwise. - virtual bool LocalizeLabel(const char* sLabel, string& outLocalizedString, bool bEnglish = false) = 0; - - // Summary: - // Return number of localization entries. - virtual int GetLocalizedStringCount() = 0; - - // Summary: - // Get the english localization info structure corresponding to a key. - // Parameters: - // sKey - Key to be looked up. Key = Label without '@' sign. - // sLocalizedString - Corresponding english language string. - // Returns: - // True if successful, false otherwise (key not found). - virtual bool GetEnglishString(const char* sKey, string& sLocalizedString) = 0; - - // Summary: - // Get Subtitle for Key or Label . - // Parameters: - // sKeyOrLabel - Key or Label to be used for subtitle lookup. Key = Label without '@' sign. - // outSubtitle - Subtitle (untouched if Key/Label not found). - // bForceSubtitle - If true, get subtitle (sLocalized or sEnglish) even if not specified in Data file. - // Returns: - // True if subtitle found (and outSubtitle filled in), false otherwise. - virtual bool GetSubtitle(const char* sKeyOrLabel, string& outSubtitle, bool bForceSubtitle = false) = 0; - - // Description: - // These methods format outString depending on sString with ordered arguments - // FormatStringMessage(outString, "This is %2 and this is %1", "second", "first"); - // Arguments: - // outString - This is first and this is second. - virtual void FormatStringMessage_List(string& outString, const string& sString, const char** sParams, int nParams) = 0; - virtual void FormatStringMessage(string& outString, const string& sString, const char* param1, const char* param2 = 0, const char* param3 = 0, const char* param4 = 0) = 0; - - virtual void LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, string& outTimeString) = 0; - virtual void LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, string& outDateString) = 0; - virtual void LocalizeDuration(int seconds, string& outDurationString) = 0; - virtual void LocalizeNumber(int number, string& outNumberString) = 0; - virtual void LocalizeNumber_Decimal(float number, int decimals, string& outNumberString) = 0; - - // Summary: - // Returns true if the project has localization configured for use, false otherwise. - virtual bool ProjectUsesLocalization() const = 0; - // </interfuscator:shuffle> - -}; -using LocalizationManagerRequestBus = AZ::EBus<LocalizationManagerRequests>; - -// Summary: -// Simple bus that notifies listeners that the language (g_language) has changed. -class LanguageChangeNotification - : public AZ::EBusTraits -{ -public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - - virtual ~LanguageChangeNotification() = default; - - virtual void LanguageChanged() = 0; -}; - -using LanguageChangeNotificationBus = AZ::EBus<LanguageChangeNotification>; - -// Set up system for passing in placeholder data for localized strings -#include "LocalizationManagerBus.inl" - diff --git a/Code/CryEngine/CryCommon/LocalizationManagerBus.inl b/Code/CryEngine/CryCommon/LocalizationManagerBus.inl deleted file mode 100644 index 617219a74c..0000000000 --- a/Code/CryEngine/CryCommon/LocalizationManagerBus.inl +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - - -// Returns the string version of any type convertible by AZStd::to_string() -// otherwise throws a compile error. -template <typename T> -AZStd::string LocalizationHelpers::DataToString(T t) -{ - return AZStd::to_string(t); -} - -// Need a function to specifically handle AZStd::string, since AZStd::to_string() doesn't handle it. -AZStd::string LocalizationHelpers::DataToString(AZStd::string str) -{ - return str; -} - -// Need a function to specifically handle const char*, since AZStd::to_string() doesn't handle it. -AZStd::string LocalizationHelpers::DataToString(const char* str) -{ - return str; -} - -// Base case of the recursive function to convert a data list to strings -template<typename T> -void LocalizationHelpers::ConvertValuesToStrings(AZStd::vector<AZStd::string>& values, T t) -{ - values.push_back(DataToString(t)); -} - -// Recursive function to convert a data list to strings -template<typename T, typename... Args> -void LocalizationHelpers::ConvertValuesToStrings(AZStd::vector<AZStd::string>& values, T t, Args... args) -{ - values.push_back(DataToString(t)); - ConvertValuesToStrings(values, args...); -} - -// Check if a key string is in a list of substitution strings -bool LocalizationHelpers::IsKeyInList(const AZStd::vector<AZStd::string>& keys, const AZStd::string& target, int& index) -{ - for (index = 0; index < keys.size(); ++index) - { - if (keys[index] == target) - { - return true; - } - } - - index = -1; - return false; -} - -// Summary: -// Parse localized string and substitute data in for each key that is surrounded by curly braces. Number of arguments -// after 'const AZStd::vector<AZStd::string>& keys' should be equal to the number of strings in 'keys'. -// ex: -// float distance = GetWinDistance(); -// AZStd::string winState = IsPlayerFirstPlace() ? "won" : "lost"; -// LocalizationManagerRequests::Broadcast(&LocalizationManagerRequests::Events::LocalizeAndSubstitute<float, AZStd::string> -// , "@QUICKRESULTS_DISTANCEDIFFERENCE, outLocalizedString -// , MakeLocKeyString("race_result", "distance_ahead") -// , winState, distance); -// -// where "@QUICKRESULTS_DISTANCEDIFFERENCE" would be localized to "You {race_result} by {distance_ahead} meters!" and then -// "{race_result}" would be replaced by 'winState" and "{distance_ahead}" would be replaced by the 'distance' argument as a string. -template<typename T, typename... Args> -void LocalizationManagerRequests::LocalizeAndSubstitute(const AZStd::string& locString, AZStd::string& outLocalizedString, const AZStd::vector<AZStd::string>& keys, T t, Args... args) -{ - AZStd::vector<AZStd::string> values; - LocalizationHelpers::ConvertValuesToStrings(values, t, args...); - - outLocalizedString = locString; - LocalizationManagerRequestBus::Broadcast(&LocalizationManagerRequestBus::Events::LocalizeAndSubstituteInternal, outLocalizedString, keys, values); -} diff --git a/Code/CryEngine/CryCommon/LyShine/Animation/IUiAnimation.h b/Code/CryEngine/CryCommon/LyShine/Animation/IUiAnimation.h deleted file mode 100644 index 893147d7e6..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Animation/IUiAnimation.h +++ /dev/null @@ -1,1324 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <Range.h> -#include <AnimKey.h> -#include <ITimer.h> -#include <IPhysics.h> -#include <VectorSet.h> -#include <CryName.h> -#include <LyShine/ILyShine.h> -#include <AzCore/Math/Vector2.h> -#include <AzCore/Math/Vector3.h> -#include <AzCore/Math/Vector4.h> -#include <AzCore/Math/Color.h> - -// forward declaration. -struct IUiAnimTrack; -struct IUiAnimNode; -struct IUiAnimSequence; -struct IUiAnimationSystem; -struct IKey; -class XmlNodeRef; -struct ISplineInterpolator; - -namespace AZ -{ - class Component; - class Entity; - class SerializeContext; -} - -#define MAX_ANIM_NAME_LENGTH 64 - -#if !defined(CONSOLE) -#define UI_ANIMATION_SYSTEM_SUPPORT_EDITING -#endif - -typedef AZStd::vector<IUiAnimSequence*> UiAnimSequences; -typedef AZStd::vector<AZStd::string> UiTrackEvents; - -////////////////////////////////////////////////////////////////////////// -//! Node-Types -// -// You need to register new types in UiAnimationSystem.cpp/RegisterNodeTypes for serialization. -// Note: Enums are serialized by string now, there is no need for specific IDs -// anymore for new parameters. Values are for backward compatibility. -enum EUiAnimNodeType -{ - eUiAnimNodeType_Invalid = 0x00, - eUiAnimNodeType_Entity = 0x01, - eUiAnimNodeType_Director = 0x02, - eUiAnimNodeType_Camera = 0x03, - eUiAnimNodeType_CVar = 0x04, - eUiAnimNodeType_ScriptVar = 0x05, - eUiAnimNodeType_Material = 0x06, - eUiAnimNodeType_Event = 0x07, - eUiAnimNodeType_Group = 0x08, - eUiAnimNodeType_Layer = 0x09, - eUiAnimNodeType_Comment = 0x10, - eUiAnimNodeType_RadialBlur = 0x11, - eUiAnimNodeType_ColorCorrection = 0x12, - eUiAnimNodeType_DepthOfField = 0x13, - eUiAnimNodeType_ScreenFader = 0x14, - eUiAnimNodeType_Light = 0x15, - eUiAnimNodeType_HDRSetup = 0x16, - eUiAnimNodeType_ShadowSetup = 0x17, - eUiAnimNodeType_Alembic = 0x18, // Used in cinebox, added so nobody uses that number - eUiAnimNodeType_GeomCache = 0x19, - eUiAnimNodeType_Environment, - eUiAnimNodeType_ScreenDropsSetup, - eUiAnimNodeType_AzEntity, - eUiAnimNodeType_Num -}; - -//! Flags that can be set on animation node. -enum EUiAnimNodeFlags -{ - eUiAnimNodeFlags_Expanded = BIT(0), //!< Deprecated, handled by sandbox now - eUiAnimNodeFlags_EntitySelected = BIT(1), //!< Set if the referenced entity is selected in the editor - eUiAnimNodeFlags_CanChangeName = BIT(2), //!< Set if this node allow changing of its name. - eUiAnimNodeFlags_Disabled = BIT(3), //!< Disable this node. -}; - -// Static common parameters IDs of animation node. -// -// You need to register new params in UiAnimationSystem.cpp/RegisterParamTypes for serialization. -// Note: Enums are serialized by string now, there is no need for specific IDs -// anymore for new parameters. Values are for backward compatibility. -// -// If you want to expand UI Animation system to control new stuff this is probably the enum you want to change. -// For named params see eUiAnimParamType_ByString & CUiAnimParamType -enum EUiAnimParamType : int -{ - eUiAnimParamType_AzComponentField, - eUiAnimParamType_Event, - eUiAnimParamType_TrackEvent, - eUiAnimParamType_Float, - eUiAnimParamType_ByString, - eUiAnimParamType_User = 100000, //!< User node params. - - eUiAnimParamType_Invalid = -1 -}; - -// Common parameters of animation node. -class CUiAnimParamType -{ - friend class UiAnimationSystem; - -public: - AZ_TYPE_INFO(CUiAnimParamType, "{3D4ADD98-DFDD-4984-AC59-E59C5D718CFC}") - - static const uint kParamTypeVersion = 8; - - CUiAnimParamType() - : m_type(eUiAnimParamType_Invalid) {} - - CUiAnimParamType(const string& name) - { - *this = name; - } - - CUiAnimParamType(const EUiAnimParamType type) - { - *this = type; - } - - // Convert from old enum or int - void operator =(const int type) - { - m_type = (EUiAnimParamType)type; - } - - void operator =(const string& name) - { - m_type = eUiAnimParamType_ByString; - m_name = name; - } - - void operator =(const AZStd::string& name) - { - m_type = eUiAnimParamType_ByString; - m_name = name.c_str(); - } - // Convert to enum. This needs to be explicit, - // otherwise operator== will be ambiguous - EUiAnimParamType GetType() const { return m_type; } - - // Get name - const char* GetName() const { return m_name.c_str(); } - - bool operator ==(const CUiAnimParamType& animParamType) const - { - if (m_type == eUiAnimParamType_ByString && animParamType.m_type == eUiAnimParamType_ByString) - { - return m_name == animParamType.m_name; - } - - return m_type == animParamType.m_type; - } - - bool operator !=(const CUiAnimParamType& animParamType) const - { - return !(*this == animParamType); - } - - bool operator <(const CUiAnimParamType& animParamType) const - { - if (m_type == eUiAnimParamType_ByString && animParamType.m_type == eUiAnimParamType_ByString) - { - return m_name < animParamType.m_name; - } - else if (m_type == eUiAnimParamType_ByString) - { - return false; // Always sort named params last - } - else if (animParamType.m_type == eUiAnimParamType_ByString) - { - return true; // Always sort named params last - } - if (m_type < animParamType.m_type) - { - return true; - } - - return false; - } - - // Serialization. Defined in UiAnimationSystem.cpp - inline void Serialize(IUiAnimationSystem* animationSystem, XmlNodeRef& xmlNode, bool bLoading, const uint version = kParamTypeVersion); - -private: - EUiAnimParamType m_type; - CCryName m_name; -}; - -// The data required to identify a specific parameter/property on an AZ component on an AZ entity -class UiAnimParamData -{ - friend class UiAnimationSystem; - -public: - - AZ_TYPE_INFO(UiAnimParamData, "{B2E9F22C-8DB5-40FA-9DF1-276E91BA8B95}") - - UiAnimParamData() - : m_componentId(AZ::InvalidComponentId) - , m_typeId(0) - , m_offset(0) - {} - - UiAnimParamData(AZ::ComponentId componentId, const char* name, AZ::Uuid typeId, size_t offset) - : m_componentId(componentId) - , m_typeId(typeId) - , m_name(name) - , m_offset(offset) - {} - - AZ::ComponentId GetComponentId() const - { - return m_componentId; - } - - AZ::Uuid GetTypeId() const - { - return m_typeId; - } - - const char* GetName() const - { - return m_name.c_str(); - } - - size_t GetOffset() const - { - return m_offset; - } - - AZ::Component* GetComponent(AZ::Entity* entity) const - { - return entity->FindComponent(m_componentId); - } - - bool operator ==(const UiAnimParamData& animParamData) const - { - return m_componentId == animParamData.m_componentId && - m_typeId == animParamData.m_typeId && - m_offset == animParamData.m_offset; - } - - bool operator !=(const UiAnimParamData& animParamData) const - { - return !(*this == animParamData); - } - - bool operator <(const UiAnimParamData& animParamData) const - { - if (m_componentId != animParamData.m_componentId) - { - return m_componentId < animParamData.m_componentId; - } - else if (m_name != animParamData.m_name) - { - return m_name < animParamData.m_name; - } - else if (m_typeId != animParamData.m_typeId) - { - return m_typeId < animParamData.m_typeId; - } - else - { - return m_offset < animParamData.m_offset; - } - } - - - // Serialization. Defined in UiAnimationSystem.cpp - inline void Serialize(IUiAnimationSystem* animationSystem, XmlNodeRef& xmlNode, bool bLoading); - -private: - AZ::ComponentId m_componentId; // unique within the owning entity - AZ::Uuid m_typeId; - AZStd::string m_name; // the name of the element in serialization data - size_t m_offset; -}; - -//! Types of animation track. -// Do not change values! they are serialized -// -// Attention: This should only be expanded if you add a completely new way how tracks store data! -// If you just want to control a new parameter of an entity etc. extend EParamType -// -// Note: TCB splines are only for backward compatibility, Bezier is the default -// -enum EUiAnimCurveType -{ - eUiAnimCurveType_TCBFloat = 1, - eUiAnimCurveType_TCBVector = 2, - eUiAnimCurveType_TCBQuat = 3, - eUiAnimCurveType_BezierFloat = 4, - - eUiAnimCurveType_Unknown = 0xFFFFFFFF -}; - -//! Values that animation track can hold. -// Do not change values! they are serialized -// -// Attention: This should only be expanded if you add a completely new value type that tracks can control! -// If you just want to control a new parameter of an entity etc. extend EParamType -// -// Note: If the param type of a track is known and valid these can be derived from the node. -// These are serialized in case the parameter got invalid (for example for material nodes) -// -enum EUiAnimValue -{ - eUiAnimValue_Float = 0, - eUiAnimValue_Vector = 1, - eUiAnimValue_Quat = 2, - eUiAnimValue_Bool = 3, - eUiAnimValue_Select = 5, - eUiAnimValue_Vector2 = 13, - eUiAnimValue_Vector3 = 14, - eUiAnimValue_Vector4 = 15, - eUiAnimValue_DiscreteFloat = 16, - eUiAnimValue_RGB = 20, - eUiAnimValue_CharacterAnim = 21, - - eUiAnimValue_Unknown = 0xFFFFFFFF -}; - -enum EUiTrackMask -{ - eUiTrackMask_MaskSound = 1 << 11, // Old: 1 << ATRACK_SOUND - eUiTrackMask_MaskMusic = 1 << 14, // Old: 1 << ATRACK_MUSIC -}; - -//! Structure passed to Animate function. -struct SUiAnimContext -{ - SUiAnimContext() - { - bSingleFrame = false; - bForcePlay = false; - bResetting = false; - time = 0; - dt = 0; - fps = 0; - pSequence = NULL; - trackMask = 0; - startTime = 0; - } - - float time; //!< Current time in seconds. - float dt; //!< Delta of time from previous animation frame in seconds. - float fps; //!< Last calculated frames per second value. - bool bSingleFrame; //!< This is not a playing animation, more a single-frame update - bool bForcePlay; //!< Set when force playing animation - bool bResetting; //!< Set when animation sequence is resetted. - - IUiAnimSequence* pSequence; //!< Sequence in which animation performed. - - // TODO: Replace trackMask with something more type safe - // TODO: Mask should be stored with dynamic length - uint32 trackMask; //!< To update certain types of tracks only - float startTime; //!< The start time of this playing sequence - - void Serialize(IUiAnimationSystem* animationSystem, XmlNodeRef& xmlNode, bool bLoading); -}; - -/** Parameters for cut-scene cameras -*/ -//! Callback-class -struct IUiAnimationCallback -{ - //! Callback-reasons - enum ECallbackReason - { - CBR_CHANGENODE, // Node is changing. - CBR_CHANGETRACK // Track of the node is changing. - }; - - // <interfuscator:shuffle> - virtual ~IUiAnimationCallback(){} - // Called by UI animation system. - virtual void OnUiAnimationCallback(ECallbackReason reason, IUiAnimNode* pNode) = 0; - // </interfuscator:shuffle> -}; - -/** Interface of Animation Track. -*/ -struct IUiAnimTrack -{ - AZ_RTTI(IUiAnimTrack, "{11C16CEC-4C03-4342-B4A7-62790E48CBD5}") - - //! Flags that can be set on animation track. - enum EUiAnimTrackFlags - { - eUiAnimTrackFlags_Linear = BIT(1), //!< Use only linear interpolation between keys. - eUiAnimTrackFlags_Loop = BIT(2), //!< Play this track in a loop. - eUiAnimTrackFlags_Cycle = BIT(3), //!< Cycle track. - eUiAnimTrackFlags_Disabled = BIT(4), //!< Disable this track. - - ////////////////////////////////////////////////////////////////////////// - // Used by editor. - ////////////////////////////////////////////////////////////////////////// - eUiAnimTrackFlags_Hidden = BIT(5), //!< Set when track is hidden in UI Animation editor. - eUiAnimTrackFlags_Muted = BIT(8), //!< Mute this sound track. This only affects the playback in editor. - }; - - // <interfuscator:shuffle> - virtual ~IUiAnimTrack() {}; - - // for intrusive_ptr support - virtual void add_ref() = 0; - virtual void release() = 0; - - ////////////////////////////////////////////////////////////////////////// - virtual EUiAnimCurveType GetCurveType() = 0; - virtual EUiAnimValue GetValueType() = 0; - -#ifdef UI_ANIMATION_SYSTEM_SUPPORT_EDITING - // This color is used for the editor. - virtual ColorB GetCustomColor() const = 0; - virtual void SetCustomColor(ColorB color) = 0; - virtual bool HasCustomColor() const = 0; - virtual void ClearCustomColor() = 0; -#endif - - // Return what parameter of the node, this track is attached to. - virtual const CUiAnimParamType& GetParameterType() const = 0; - - // Assign node parameter ID for this track. - virtual void SetParameterType(CUiAnimParamType type) = 0; - - virtual const UiAnimParamData& GetParamData() const = 0; - - virtual void SetParamData(const UiAnimParamData& param) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Animation track can contain sub-tracks (Position XYZ anim track have sub-tracks for x,y,z) - // Get count of sub tracks. - virtual int GetSubTrackCount() const = 0; - // Retrieve pointer the specfied sub track. - virtual IUiAnimTrack* GetSubTrack(int nIndex) const = 0; - virtual const char* GetSubTrackName(int nIndex) const = 0; - virtual void SetSubTrackName(int nIndex, const char* name) = 0; - ////////////////////////////////////////////////////////////////////////// - - virtual void GetKeyValueRange(float& fMin, float& fMax) const = 0; - virtual void SetKeyValueRange(float fMin, float fMax) = 0; - - //! Return number of keys in track. - virtual int GetNumKeys() const = 0; - - //! Return true if keys exists in this track - virtual bool HasKeys() const = 0; - - //! Set number of keys in track. - //! If needed adds empty keys at end or remove keys from end. - virtual void SetNumKeys(int numKeys) = 0; - - //! Remove specified key. - virtual void RemoveKey(int num) = 0; - - //! Get key at specified location. - //! @param key Must be valid pointer to compatible key structure, to be filled with specified key location. - virtual void GetKey(int index, IKey* key) const = 0; - - //! Get time of specified key. - //! @return key time. - virtual float GetKeyTime(int index) const = 0; - - //! Find key at given time. - //! @return Index of found key, or -1 if key with this time not found. - virtual int FindKey(float time) = 0; - - //! Get flags of specified key. - //! @return key time. - virtual int GetKeyFlags(int index) = 0; - - //! Set key at specified location. - //! @param key Must be valid pointer to compatible key structure. - virtual void SetKey(int index, IKey* key) = 0; - - //! Set time of specified key. - virtual void SetKeyTime(int index, float time) = 0; - - //! Set flags of specified key. - virtual void SetKeyFlags(int index, int flags) = 0; - - //! Sort keys in track (after time of keys was modified). - virtual void SortKeys() = 0; - - //! Get track flags. - virtual int GetFlags() = 0; - - //! Check if track is masked by mask - // TODO: Mask should be stored with dynamic length - virtual bool IsMasked(const uint32 mask) const = 0; - - //! Set track flags. - virtual void SetFlags(int flags) = 0; - - //! Create key at given time, and return its index. - //! @return Index of new key. - virtual int CreateKey(float time) = 0; - - //! Clone key at specified index. - //! @retun Index of new key. - virtual int CloneKey(int key) = 0; - - //! Clone key at specified index from another track of SAME TYPE. - //! @retun Index of new key. - virtual int CopyKey(IUiAnimTrack* pFromTrack, int nFromKey) = 0; - - //! Get info about specified key. - //! @param Short human readable text description of this key. - //! @param duration of this key in seconds. - virtual void GetKeyInfo(int key, const char*& description, float& duration) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Get track value at specified time. - // Interpolates keys if needed. - ////////////////////////////////////////////////////////////////////////// - virtual void GetValue(float time, float& value) = 0; - virtual void GetValue(float time, Vec3& value) = 0; - virtual void GetValue(float time, Vec4& value) = 0; - virtual void GetValue(float time, Quat& value) = 0; - virtual void GetValue(float time, bool& value) = 0; - virtual void GetValue(float time, AZ::Vector2& value) = 0; - virtual void GetValue(float time, AZ::Vector3& value) = 0; - virtual void GetValue(float time, AZ::Vector4& value) = 0; - virtual void GetValue(float time, AZ::Color& value) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Set track value at specified time. - // Adds new keys if required. - ////////////////////////////////////////////////////////////////////////// - virtual void SetValue(float time, const float& value, bool bDefault = false) = 0; - virtual void SetValue(float time, const Vec3& value, bool bDefault = false) = 0; - virtual void SetValue(float time, const Vec4& value, bool bDefault = false) = 0; - virtual void SetValue(float time, const Quat& value, bool bDefault = false) = 0; - virtual void SetValue(float time, const bool& value, bool bDefault = false) = 0; - virtual void SetValue(float time, const AZ::Vector2& value, bool bDefault = false) = 0; - virtual void SetValue(float time, const AZ::Vector3& value, bool bDefault = false) = 0; - virtual void SetValue(float time, const AZ::Vector4& value, bool bDefault = false) = 0; - virtual void SetValue(float time, const AZ::Color& value, bool bDefault = false) = 0; - - // Only for position tracks, offset all track keys by this amount. - virtual void OffsetKeyPosition(const Vec3& value) = 0; - - // Assign active time range for this track. - virtual void SetTimeRange(const Range& timeRange) = 0; - - // Serialize this animation track to XML. - virtual bool Serialize(IUiAnimationSystem* uiAnimationSystem, XmlNodeRef& xmlNode, bool bLoading, bool bLoadEmptyTracks = true) = 0; - virtual bool SerializeSelection(XmlNodeRef& xmlNode, bool bLoading, bool bCopySelected = false, float fTimeOffset = 0) = 0; - - virtual void InitPostLoad(IUiAnimSequence* /*sequence*/) {}; - - //! For custom track animate parameters. - virtual void Animate([[maybe_unused]] SUiAnimContext& ec) {}; - - // Get access to the internal spline of the track. - virtual ISplineInterpolator* GetSpline() const { return 0; }; - - virtual bool IsKeySelected([[maybe_unused]] int key) const { return false; } - - virtual void SelectKey([[maybe_unused]] int key, [[maybe_unused]] bool select) {} - - //! Return the index of the key which lies right after the given key in time. - //! @param key Index of of key. - //! @return Index of the next key in time. If the last key given, this returns -1. - // In case of keys sorted, it's just 'key+1', but if not sorted, it can be another value. - virtual int NextKeyByTime(int key) const - { - if (key + 1 < GetNumKeys()) - { - return key + 1; - } - else - { - return -1; - } - } - - //! Get the animation layer index assigned. (only for character/look-at tracks ATM) - virtual int GetAnimationLayerIndex() const { return -1; } - //! Set the animation layer index. (only for character/look-at tracks ATM) - virtual void SetAnimationLayerIndex([[maybe_unused]] int index) { } - - // </interfuscator:shuffle> -}; - - -/** Callback called by animation node when its animated. -*/ -struct IUiAnimNodeOwner -{ - // <interfuscator:shuffle> - virtual ~IUiAnimNodeOwner(){} - virtual void OnNodeUiAnimated(IUiAnimNode* pNode) = 0; - virtual void OnNodeVisibilityChanged(IUiAnimNode* pNode, const bool bHidden) = 0; - virtual void OnNodeReset([[maybe_unused]] IUiAnimNode* pNode) {} - - // </interfuscator:shuffle> -}; - -/** Base class for all Animation nodes, - can host multiple animation tracks, and execute them other time. - Animation node is reference counted. -*/ -struct IUiAnimNode -{ -public: - AZ_RTTI(IUiAnimNode, "{298180CC-B577-440C-8466-A01ABC8CC00A}") - - ////////////////////////////////////////////////////////////////////////// - // Supported params. - ////////////////////////////////////////////////////////////////////////// - enum ESupportedParamFlags - { - eSupportedParamFlags_MultipleTracks = 0x01, // Set if parameter can be assigned multiple tracks. - }; - - // <interfuscator:shuffle> - virtual ~IUiAnimNode() {}; - - // for intrusive_ptr support - virtual void add_ref() = 0; - virtual void release() = 0; - - //! Set node name. - virtual void SetName(const char* name) = 0; - - //! Get node name. - virtual const char* GetName() = 0; - - // Get Type of this node. - virtual EUiAnimNodeType GetType() const = 0; - - // Return Animation Sequence that owns this node. - virtual IUiAnimSequence* GetSequence() const = 0; - - // Set the Animation Sequence that owns this node. - virtual void SetSequence(IUiAnimSequence* sequence) = 0; - - // Called when sequence is activated / deactivated - virtual void Activate(bool bActivate) = 0; - - // Set AnimNode flags. - // @param flags One or more flags from EUiAnimNodeFlags. - // @see EUiAnimNodeFlags - virtual void SetFlags(int flags) = 0; - - // Get AnimNode flags. - // @return flags set on node. - // @see EUiAnimNodeFlags - virtual int GetFlags() const = 0; - - // Return animation system that created this node. - virtual IUiAnimationSystem* GetUiAnimationSystem() const = 0; - - // General Set param. - // Set float/vec3/vec4 parameter at given time. - // @return true if parameter set, false if this parameter not exist in node. - virtual bool SetParamValue(float time, CUiAnimParamType param, float value) = 0; - virtual bool SetParamValue(float time, CUiAnimParamType param, const Vec3& value) = 0; - virtual bool SetParamValue(float time, CUiAnimParamType param, const Vec4& value) = 0; - // Get float/vec3/vec4 parameter at given time. - // @return true if parameter exist, false if this parameter not exist in node. - virtual bool GetParamValue(float time, CUiAnimParamType param, float& value) = 0; - virtual bool GetParamValue(float time, CUiAnimParamType param, Vec3& value) = 0; - virtual bool GetParamValue(float time, CUiAnimParamType param, Vec4& value) = 0; - - virtual bool SetParamValueAz([[maybe_unused]] float time, [[maybe_unused]] const UiAnimParamData& param, [[maybe_unused]] float value) { return false; } - virtual bool SetParamValueAz([[maybe_unused]] float time, [[maybe_unused]] const UiAnimParamData& param, [[maybe_unused]] bool value) { return false; } - virtual bool SetParamValueAz([[maybe_unused]] float time, [[maybe_unused]] const UiAnimParamData& param, [[maybe_unused]] int value) { return false; } - virtual bool SetParamValueAz([[maybe_unused]] float time, [[maybe_unused]] const UiAnimParamData& param, [[maybe_unused]] unsigned int value) { return false; } - virtual bool SetParamValueAz([[maybe_unused]] float time, [[maybe_unused]] const UiAnimParamData& param, [[maybe_unused]] const AZ::Vector2& value) { return false; } - virtual bool SetParamValueAz([[maybe_unused]] float time, [[maybe_unused]] const UiAnimParamData& param, [[maybe_unused]] const AZ::Vector3& value) { return false; } - virtual bool SetParamValueAz([[maybe_unused]] float time, [[maybe_unused]] const UiAnimParamData& param, [[maybe_unused]] const AZ::Vector4& value) { return false; } - virtual bool SetParamValueAz([[maybe_unused]] float time, [[maybe_unused]] const UiAnimParamData& param, [[maybe_unused]] const AZ::Color& value) { return false; } - - virtual bool GetParamValueAz([[maybe_unused]] float time, [[maybe_unused]] const UiAnimParamData& param, [[maybe_unused]] float& value) { return false; } - - //! Evaluate animation node while not playing animation. - virtual void StillUpdate() = 0; - - //! Evaluate animation to the given time. - virtual void Animate(SUiAnimContext& ec) = 0; - - // Description: - // Returns number of supported parameters by this animation node (position,rotation,scale,etc..). - // Returns: - // Number of supported parameters. - virtual unsigned int GetParamCount() const = 0; - - // Description: - // Returns the type of a param by index - // Arguments: - // nIndex - parameter index in range 0 <= nIndex < GetSupportedParamCount() - virtual CUiAnimParamType GetParamType(unsigned int nIndex) const = 0; - - // Description: - // Check if parameter is supported by this node. - virtual bool IsParamValid(const CUiAnimParamType& paramType) const = 0; - - // Description: - // Returns name of supported parameter of this animation node or NULL if not available - // Arguments: - // paramType - parameter id - virtual const char* GetParamName(const CUiAnimParamType& paramType) const = 0; - - // Description: - // Returns name of supported parameter of this animation node or NULL if not available - // Arguments: - // paramType - parameter id - virtual const char* GetParamNameForTrack(const CUiAnimParamType& paramType, [[maybe_unused]] const IUiAnimTrack* track) const { return GetParamName(paramType); } - - // Description: - // Returns the params value type - virtual EUiAnimValue GetParamValueType(const CUiAnimParamType& paramType) const = 0; - - // Description: - // Returns the params value type - virtual ESupportedParamFlags GetParamFlags(const CUiAnimParamType& paramType) const = 0; - - // Called node data is re-initialized, such as when changing the entity associated with it. - virtual void OnReset() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Working with Tracks. - ////////////////////////////////////////////////////////////////////////// - virtual int GetTrackCount() const = 0; - - // Return track assigned to the specified parameter. - virtual IUiAnimTrack* GetTrackByIndex(int nIndex) const = 0; - - // Return first track assigned to the specified parameter. - virtual IUiAnimTrack* GetTrackForParameter(const CUiAnimParamType& paramType) const = 0; - - // Return the i-th track assigned to the specified parameter in case of multiple tracks. - virtual IUiAnimTrack* GetTrackForParameter(const CUiAnimParamType& paramType, uint32 index) const = 0; - - // Get the index of a given track among tracks with the same parameter type in this node. - virtual uint32 GetTrackParamIndex(const IUiAnimTrack* pTrack) const = 0; - - // Creates a new track for given parameter. - virtual IUiAnimTrack* CreateTrack(const CUiAnimParamType& paramType) = 0; - - // Return track assigned to the specified class element. - // Maybe we should pass nameCrc rather than a void* - virtual IUiAnimTrack* GetTrackForAzField(const UiAnimParamData& param) const = 0; - - // Creates a new track for given parameter. - // Maybe we should pass nameCrc rather than a void* - virtual IUiAnimTrack* CreateTrackForAzField(const UiAnimParamData& param) = 0; - - // Assign animation track to parameter. - // if track parameter is NULL track with parameter id param will be removed. - virtual void SetTrack(const CUiAnimParamType& paramType, IUiAnimTrack* track) = 0; - - // Set time range for all tracks in this sequence. - virtual void SetTimeRange(Range timeRange) = 0; - - // Remove track from anim node. - virtual void AddTrack(IUiAnimTrack* pTrack) = 0; - - // Remove track from anim node. - virtual bool RemoveTrack(IUiAnimTrack* pTrack) = 0; - - // Description: - // Creates default set of tracks supported by this node. - virtual void CreateDefaultTracks() = 0; - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // Callback for animation node used by editor. - // Register notification callback with animation node. - virtual void SetNodeOwner(IUiAnimNodeOwner* pOwner) = 0; - virtual IUiAnimNodeOwner* GetNodeOwner() = 0; - - // Serialize this animation node to XML. - virtual void SerializeUiAnims(XmlNodeRef& xmlNode, bool bLoading, bool bLoadEmptyTracks) = 0; - virtual void Serialize(XmlNodeRef& xmlNode, bool bLoading, bool bLoadEmptyTracks) = 0; - - // Sets up internal pointers post load from Sequence Component - virtual void InitPostLoad(IUiAnimSequence* pSequence, bool remapIds, LyShine::EntityIdMap* entityIdMap) = 0; - - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - // Groups interface - ////////////////////////////////////////////////////////////////////////// - virtual void SetParent(IUiAnimNode* pParent) = 0; - virtual IUiAnimNode* GetParent() const = 0; - virtual IUiAnimNode* HasDirectorAsParent() const = 0; - ////////////////////////////////////////////////////////////////////////// - - virtual void Render() = 0; - - virtual bool NeedToRender() const = 0; - - // Called from editor if dynamic params need updating - virtual void UpdateDynamicParams() = 0; - // </interfuscator:shuffle> -}; - -//! Track event listener -struct IUiTrackEventListener -{ - //! Reasons - enum ETrackEventReason - { - eTrackEventReason_Added, - eTrackEventReason_Removed, - eTrackEventReason_Renamed, - eTrackEventReason_Triggered, - eTrackEventReason_MovedUp, - eTrackEventReason_MovedDown, - }; - - // <interfuscator:shuffle> - virtual ~IUiTrackEventListener(){} - // Description: - // Called when track event is updated - // Arguments: - // pSeq - Animation sequence - // reason - Reason for update (see EReason) - // event - Track event added - // pUserData - Data to accompany reason - virtual void OnTrackEvent(IUiAnimSequence* pSequence, int reason, const char* event, void* pUserData) = 0; - // </interfuscator:shuffle> -}; - -struct IUiAnimSequenceOwner -{ - // <interfuscator:shuffle> - virtual ~IUiAnimSequenceOwner() {} - virtual void OnModified() = 0; - // </interfuscator:shuffle> -}; - -struct IUiAnimStringTable -{ - AZ_RTTI(IUiAnimStringTable, "{5B60054D-0D67-4DB5-B867-9869DAB95B83}") - virtual ~IUiAnimStringTable() {} - - // for intrusive_ptr support - virtual void add_ref() = 0; - virtual void release() = 0; - - virtual const char* Add(const char* p) = 0; -}; - -/** Animation sequence, operates on animation nodes contained in it. - */ -struct IUiAnimSequence -{ - AZ_RTTI(IUiAnimSequence, "{74EFA085-7758-4275-98A1-4D40DC6F55B8}") - - static const int kSequenceVersion = 3; - - //! Flags used for SetFlags(),GetFlags(),SetParentFlags(),GetParentFlags() methods. - enum EUiAnimSequenceFlags - { - eSeqFlags_PlayOnReset = BIT(0), //!< Start playing this sequence immediately after reset of UI animation system(Level load). - eSeqFlags_OutOfRangeConstant = BIT(1), //!< Constant Out-Of-Range,time continues normally past sequence time range. - eSeqFlags_OutOfRangeLoop = BIT(2), //!< Loop Out-Of-Range,time wraps back to the start of range when reaching end of range. - eSeqFlags_CutScene = BIT(3), //!< Cut scene sequence. - eSeqFlags_NoHUD = BIT(4), //!< @deprecated - Don`t display HUD - eSeqFlags_NoPlayer = BIT(5), //!< Disable input and drawing of player - eSeqFlags_16To9 = BIT(8), //!< 16:9 bars in sequence - eSeqFlags_NoGameSounds = BIT(9), //!< Suppress all game sounds. - eSeqFlags_NoSeek = BIT(10), //!< Cannot seek in sequence. - eSeqFlags_NoAbort = BIT(11), //!< Cutscene can not be aborted - eSeqFlags_NoSpeed = BIT(13), //!< Cannot modify sequence speed - TODO: add interface control if required - // eSeqFlags_CanWarpInFixedTime = BIT(14), //!< @deprecated - Timewarp by scaling a fixed time step - removed July 2017 - eSeqFlags_EarlyAnimationUpdate = BIT(15), //!< Turn the 'sys_earlyUiAnimationUpdate' on during the sequence. - eSeqFlags_LightAnimationSet = BIT(16), //!< A special unique sequence for light animations - eSeqFlags_NoMPSyncingNeeded = BIT(17), //!< this sequence doesn't require MP net syncing - }; - - virtual ~IUiAnimSequence() {}; - - // for intrusive_ptr support - virtual void add_ref() = 0; - virtual void release() = 0; - - //! Set the animation system for the canvas containing this sequence - virtual IUiAnimationSystem* GetUiAnimationSystem() const = 0; - - //! Set the name of this sequence. (ex. "Intro" in the same case as above) - virtual void SetName(const char* name) = 0; - //! Get the name of this sequence. (ex. "Intro" in the same case as above) - virtual const char* GetName() const = 0; - //! Get the ID (unique in a level and consistent across renaming) of this sequence. - virtual uint32 GetId () const = 0; - - virtual void SetOwner(IUiAnimSequenceOwner* pOwner) = 0; - virtual IUiAnimSequenceOwner* GetOwner() const = 0; - - //! Set the currently active director node. - virtual void SetActiveDirector(IUiAnimNode* pDirectorNode) = 0; - //! Get the currently active director node, if any. - virtual IUiAnimNode* GetActiveDirector() const = 0; - - //! Set animation sequence flags - virtual void SetFlags(int flags) = 0; - //! Get animation sequence flags - virtual int GetFlags() const = 0; - //! Get cutscene related animation sequence flags - virtual int GetCutSceneFlags(const bool localFlags = false) const = 0; - //! Set parent animation sequence - virtual void SetParentSequence(IUiAnimSequence* pParentSequence) = 0; - //! Get parent animation sequence - virtual const IUiAnimSequence* GetParentSequence() const = 0; - //! Check whether this sequence has the given sequence as a descendant through one of its sequence tracks. - virtual bool IsAncestorOf(const IUiAnimSequence* sequence) const = 0; - - //! Return number of animation nodes in sequence. - virtual int GetNodeCount() const = 0; - //! Get animation node at specified index. - virtual IUiAnimNode* GetNode(int index) const = 0; - - //! Add animation node to sequence. - //! @return True if node added, same node will not be added 2 times. - virtual bool AddNode(IUiAnimNode* node) = 0; - - // Reorders the array of nodes, so the specified node is placed after or before the given pivot node depending on the parameter 'next'. - virtual void ReorderNode(IUiAnimNode* node, IUiAnimNode* pPivotNode, bool next) = 0; - - // Description: - // Creates a new animation node with specified type. - // Arguments: - // nodeType - Type of node, one of EUiAnimNodeType enums. - virtual IUiAnimNode* CreateNode(EUiAnimNodeType nodeType) = 0; - - // Description: - // Creates a new animation node from serialized node XML. - // Arguments: - // node - Serialized form of node - virtual IUiAnimNode* CreateNode(XmlNodeRef node) = 0; - - //! Remove animation node from sequence. - virtual void RemoveNode(IUiAnimNode* node) = 0; - - // Finds node by name, can be slow. - // If the node belongs to a director, the director node also should be given - // since there can be multiple instances of the same node(i.e. the same name) - // across multiple director nodes. - virtual IUiAnimNode* FindNodeByName(const char* sNodeName, const IUiAnimNode* pParentDirector) = 0; - - //! Remove all nodes from sequence. - virtual void RemoveAll() = 0; - - // Activate sequence by binding sequence animations to nodes. - // must be called prior animating sequence. - virtual void Activate() = 0; - - /** Check if sequence is activated - */ - virtual bool IsActivated() const = 0; - - // Deactivates sequence by unbinding sequence animations from nodes. - virtual void Deactivate() = 0; - - // Pre-caches data associated with this anim sequence. - virtual void PrecacheData(float startTime = 0.0f) = 0; - - // Update sequence while not playing animation. - virtual void StillUpdate() = 0; - - // Render function call for some special node. - virtual void Render() = 0; - - // Evaluate animations of all nodes in sequence. - // Sequence must be activated before animating. - virtual void Animate(const SUiAnimContext& ec) = 0; - - //! Set time range of this sequence. - virtual void SetTimeRange(Range timeRange) = 0; - - //! Get time range of this sequence. - virtual Range GetTimeRange() = 0; - - //! Resets the sequence - virtual void Reset(bool bSeekToStart) = 0; - - //! This can have more time-consuming tasks performed additional to tasks of the usual 'Reset()' method. - virtual void ResetHard() = 0; - - // Called to pause sequence. - virtual void Pause() = 0; - - // Called to resume sequence. - virtual void Resume() = 0; - - /** Called to check if sequence is paused. - */ - virtual bool IsPaused() const = 0; - - /** Called when a sequence is looped. - */ - virtual void OnLoop() = 0; - - /** Move/Scale all keys in tracks from previous time range to new time range. - */ - virtual void AdjustKeysToTimeRange(const Range& timeRange) = 0; - - // Serialize this sequence to XML. - virtual void Serialize(XmlNodeRef& xmlNode, bool bLoading, bool bLoadEmptyTracks = true, uint32 overrideId = 0, bool bUndo = false) = 0; - virtual void InitPostLoad(IUiAnimationSystem* pUiAnimationSystem, bool remapIds, LyShine::EntityIdMap* entityIdMap) = 0; - - // Copy some nodes of this sequence to XML. - virtual void CopyNodes(XmlNodeRef& xmlNode, IUiAnimNode** pSelectedNodes, uint32 count) = 0; - - // Paste nodes given by the XML to this sequence. - virtual void PasteNodes(const XmlNodeRef& xmlNode, IUiAnimNode* pParent) = 0; - - // Summary: - // Adds/removes track events in sequence. - virtual bool AddTrackEvent(const char* szEvent) = 0; - virtual bool RemoveTrackEvent(const char* szEvent) = 0; - virtual bool RenameTrackEvent(const char* szEvent, const char* szNewEvent) = 0; - virtual bool MoveUpTrackEvent(const char* szEvent) = 0; - virtual bool MoveDownTrackEvent(const char* szEvent) = 0; - virtual void ClearTrackEvents() = 0; - - // Summary: - // Gets the track events in the sequence. - virtual int GetTrackEventsCount() const = 0; - // Summary: - // Gets the specified track event in the sequence. - virtual char const* GetTrackEvent(int iIndex) const = 0; - - virtual IUiAnimStringTable* GetTrackEventStringTable() = 0; - - // Summary: - // Called to trigger a track event. - virtual void TriggerTrackEvent(const char* event, const char* param = NULL) = 0; - - //! Track event listener - virtual void AddTrackEventListener(IUiTrackEventListener* pListener) = 0; - virtual void RemoveTrackEventListener(IUiTrackEventListener* pListener) = 0; - - // </interfuscator:shuffle> -}; - -/** UI animation Listener interface. - Register at UI animation system to get notified about UI animation events -*/ -struct IUiAnimationListener -{ - enum EUiAnimationEvent - { - eUiAnimationEvent_Started = 0, // fired when sequence is started - eUiAnimationEvent_Stopped, // fired when sequence ended normally - eUiAnimationEvent_Aborted, // fired when sequence was aborted before normal end (STOP and ABORTED event are mutually exclusive!) - eUiAnimationEvent_Updated, // fired after sequence time or playback speed was updated - }; - - // <interfuscator:shuffle> - virtual ~IUiAnimationListener(){} - //! callback on UI animation events - virtual void OnUiAnimationEvent(EUiAnimationEvent uiAnimationEvent, IUiAnimSequence* pAnimSequence) = 0; - virtual void OnUiTrackEvent(AZStd::string eventName, AZStd::string valueName, [[maybe_unused]] IUiAnimSequence* pAnimSequence) {} - // </interfuscator:shuffle> -}; - -/** UI Animation System interface. - Main entrance point to UI Animation capability. - Enumerate available UI Animation sequences, update all UI Animation sequences, create animation nodes and tracks. - */ -struct IUiAnimationSystem -{ - AZ_RTTI(IUiAnimationSystem, "{26D795DD-6732-4A2F-81A5-B17B53A3ADAA}") - - enum ESequenceStopBehavior - { - eSSB_LeaveTime = 0, // When sequence is stopped it remains in last played time. - eSSB_GotoEndTime = 1, // Default behavior in game, sequence is animated at end time before stop. - eSSB_GotoStartTime = 2, // Default behavior in editor, sequence is animated at start time before stop. - }; - - // <interfuscator:shuffle> - virtual ~IUiAnimationSystem(){} - - //! Release UI animation system. - virtual void Release() = 0; - //! Loads all nodes and sequences from a specific file (should be called when the level is loaded). - virtual bool Load(const char* pszFile, const char* pszMission) = 0; - - // Description: - // Creates a new animation track with specified type. - // Arguments: - // type - Type of track, one of EUiAnimTrackType enums. - virtual IUiAnimTrack* CreateTrack(EUiAnimCurveType type) = 0; - - virtual IUiAnimSequence* CreateSequence(const char* sequence, bool bLoad = false, uint32 id = 0) = 0; - virtual IUiAnimSequence* LoadSequence(XmlNodeRef& xmlNode, bool bLoadEmpty = true) = 0; - virtual void AddSequence(IUiAnimSequence* pSequence) = 0; - virtual void RemoveSequence(IUiAnimSequence* pSequence) = 0; - virtual IUiAnimSequence* FindSequence(const char* sequence) const = 0; - virtual IUiAnimSequence* FindSequenceById(uint32 id) const = 0; - virtual IUiAnimSequence* GetSequence(int i) const = 0; - virtual int GetNumSequences() const = 0; - virtual IUiAnimSequence* GetPlayingSequence(int i) const = 0; - virtual int GetNumPlayingSequences() const = 0; - virtual bool IsCutScenePlaying() const = 0; - - virtual uint32 GrabNextSequenceId() = 0; - ////////////////////////////////////////////////////////////////////////// - // - // If the name of a sequence changes, the keys that refer it in the - // sequence track of the director node should be properly updated also. - // - // @param before The old name of the sequence. - // @param after The new name of the sequence. - // @return Number of modified sequence keys. - // - ////////////////////////////////////////////////////////////////////////// - virtual int OnSequenceRenamed(const char* before, const char* after) = 0; - ////////////////////////////////////////////////////////////////////////// - // - // If the name of a camera changes, the keys that refer it in the - // camera track of the director node should be properly updated also. - // This updates the name of the corresponding camera node also, if any. - // - // @param before The old name of the camera. - // @param after The new name of the camera. - // @return Number of modified camera keys. - // - ////////////////////////////////////////////////////////////////////////// - virtual int OnCameraRenamed(const char* before, const char* after) = 0; - - // Adds a listener to a sequence - // @param pSequence Pointer to sequence - // @param pListener Pointer to an IUiAnimationListener - // @return true on successful add, false otherwise - virtual bool AddUiAnimationListener(IUiAnimSequence* pSequence, IUiAnimationListener* pListener) = 0; - - // Removes a listener from a sequence - // @param pSequence Pointer to sequence - // @param pListener Pointer to an IUiAnimationListener - // @return true on successful removal, false otherwise - virtual bool RemoveUiAnimationListener(IUiAnimSequence* pSequence, IUiAnimationListener* pListener) = 0; - - virtual ISystem* GetSystem() = 0; - - // Remove all sequences from UI animation system. - virtual void RemoveAllSequences() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Sequence playback. - ////////////////////////////////////////////////////////////////////////// - // Start playing sequence. - // Call ignored if sequence is already playing. - // @param sequence Name of sequence to play. - virtual void PlaySequence(const char* pSequenceName, IUiAnimSequence* pParentSeq, bool bResetFX, bool bTrackedSequence, float startTime = -FLT_MAX, float endTime = -FLT_MAX) = 0; - - // Start playing sequence. - // Call ignored if sequence is already playing. - // @param sequence Pointer to Valid sequence to play. - virtual void PlaySequence(IUiAnimSequence* pSequence, IUiAnimSequence* pParentSeq, bool bResetFX, bool bTrackedSequence, float startTime = -FLT_MAX, float endTime = -FLT_MAX) = 0; - - // Stops currently playing sequence. - // Ignored if sequence is not playing. - // Returns true if sequence has been stopped. false otherwise - // @param sequence Name of playing sequence to stop. - virtual bool StopSequence(const char* pSequenceName) = 0; - - // Stop's currently playing sequence. - // Ignored if sequence is not playing. - // Returns true if sequence has been stopped. false otherwise - // @param sequence Pointer to Valid sequence to stop. - virtual bool StopSequence(IUiAnimSequence* pSequence) = 0; - - /** Aborts a currently playing sequence. - Ignored if sequence is not playing. - Calls IUiAnimationListener with aborted event (done event is NOT called) - Returns true if sequence has been aborted. false otherwise - @param sequence Pointer to Valid sequence to stop. - @param bLeaveTime If false, uses default stop behavior, otherwise leaves the sequence at time - */ - virtual bool AbortSequence(IUiAnimSequence* pSequence, bool bLeaveTime = false) = 0; - - // Stops all currently playing sequences. - virtual void StopAllSequences() = 0; - - // Stops all playing cut-scene sequences. - // This will not stop all sequences, but only those with CUT_SCENE flag set. - virtual void StopAllCutScenes() = 0; - - // Checks if specified sequence is playing. - virtual bool IsPlaying(IUiAnimSequence* seq) const = 0; - - /** Resets playback state of UI animation system, - usually called after loading of level, - */ - virtual void Reset(bool bPlayOnReset, bool bSeekToStart) = 0; - - // Sequences with PLAY_ONRESET flag will start playing after this call. - virtual void PlayOnLoadSequences() = 0; - - // Update UI animation system while not playing animation. - virtual void StillUpdate() = 0; - - // Updates UI animation system every frame before the entity system to animate all playing sequences. - virtual void PreUpdate(const float dt) = 0; - - // Updates UI animation system every frame after the entity system to animate all playing sequences. - virtual void PostUpdate(const float dt) = 0; - - // Render function call of some special node. - virtual void Render() = 0; - - // Set UI animation system into recording mode, - // While in recording mode any changes made to node will be added as keys to tracks. - virtual void SetRecording(bool recording) = 0; - virtual bool IsRecording() const = 0; - - // Pause any playing sequences. - virtual void Pause() = 0; - - // Resume playing sequences. - virtual void Resume() = 0; - - // Callback when animation-data changes - virtual void SetCallback(IUiAnimationCallback* pCallback) = 0; - - virtual IUiAnimationCallback* GetCallback() = 0; - - // Serialize to XML. - virtual void Serialize(XmlNodeRef& xmlNode, bool bLoading, bool bRemoveOldNodes = false, bool bLoadEmpty = true) = 0; - virtual void InitPostLoad(bool remapIds, LyShine::EntityIdMap* entityIdMap) = 0; - - // Gets the float time value for a sequence that is already playing - virtual float GetPlayingTime(IUiAnimSequence* pSeq) = 0; - virtual float GetPlayingSpeed(IUiAnimSequence* pSeq) = 0; - // Sets the time progression of an already playing cutscene. - // If IUiAnimSequence:NO_SEEK flag is set on pSeq, this call is ignored. - virtual bool SetPlayingTime(IUiAnimSequence* pSeq, float fTime) = 0; - virtual bool SetPlayingSpeed(IUiAnimSequence* pSeq, float fSpeed) = 0; - // Set behavior pattern for stopping sequences. - virtual void SetSequenceStopBehavior(ESequenceStopBehavior behavior) = 0; - - // Set the start and end time of an already playing cutscene. - virtual bool GetStartEndTime(IUiAnimSequence* pSeq, float& fStartTime, float& fEndTime) = 0; - virtual bool SetStartEndTime(IUiAnimSequence* pSeq, const float fStartTime, const float fEndTime) = 0; - - // Make the specified sequence go to a given frame time. - // @param seqName A sequence name. - // @param targetFrame A target frame to go to in time. - virtual void GoToFrame(const char* seqName, float targetFrame) = 0; - - // Get behavior pattern for stopping sequences. - virtual IUiAnimationSystem::ESequenceStopBehavior GetSequenceStopBehavior() = 0; - - // Should only be called from CUiAnimParamType - virtual void SerializeParamType(CUiAnimParamType& animParamType, XmlNodeRef& xmlNode, bool bLoading, const uint version) = 0; - - // Should only be called from UiAnimParamData - virtual void SerializeParamData(UiAnimParamData& animParamData, XmlNodeRef& xmlNode, bool bLoading) = 0; - - // Called by a sequence whenever a track event is triggered - virtual void NotifyTrackEventListeners(const char* eventName, const char* valueName, IUiAnimSequence* pSequence) = 0; - -#ifdef UI_ANIMATION_SYSTEM_SUPPORT_EDITING - virtual EUiAnimNodeType GetNodeTypeFromString(const char* pString) const = 0; - virtual CUiAnimParamType GetParamTypeFromString(const char* pString) const = 0; -#endif - - // </interfuscator:shuffle> -}; - -inline void SUiAnimContext::Serialize(IUiAnimationSystem* animationSystem, XmlNodeRef& xmlNode, bool bLoading) -{ - if (bLoading) - { - XmlString name; - if (xmlNode->getAttr("sequence", name)) - { - pSequence = animationSystem->FindSequence(name.c_str()); - } - xmlNode->getAttr("dt", dt); - xmlNode->getAttr("fps", fps); - xmlNode->getAttr("time", time); - xmlNode->getAttr("bSingleFrame", bSingleFrame); - xmlNode->getAttr("bResetting", bResetting); - xmlNode->getAttr("trackMask", trackMask); - xmlNode->getAttr("startTime", startTime); - } - else - { - if (pSequence) - { - string fullname = pSequence->GetName(); - xmlNode->setAttr("sequence", fullname.c_str()); - } - xmlNode->setAttr("dt", dt); - xmlNode->setAttr("fps", fps); - xmlNode->setAttr("time", time); - xmlNode->setAttr("bSingleFrame", bSingleFrame); - xmlNode->setAttr("bResetting", bResetting); - xmlNode->setAttr("trackMask", trackMask); - xmlNode->setAttr("startTime", startTime); - } -} - -void CUiAnimParamType::Serialize(IUiAnimationSystem* animationSystem, XmlNodeRef& xmlNode, bool bLoading, const uint version) -{ - animationSystem->SerializeParamType(*this, xmlNode, bLoading, version); -} - -void UiAnimParamData::Serialize(IUiAnimationSystem* animationSystem, XmlNodeRef& xmlNode, bool bLoading) -{ - animationSystem->SerializeParamData(*this, xmlNode, bLoading); -} diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/Sprite/UiSpriteBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/Sprite/UiSpriteBus.h deleted file mode 100644 index 672eed2894..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/Sprite/UiSpriteBus.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/EBus/EBus.h> - -// Forward declarations -class ISprite; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that listeners need to implement to be notified of changes to the sprite settings -class UiSpriteSettingsChangeNotification - : public AZ::EBusTraits -{ -public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - /** - * Overrides the default AZ::EBusTraits address policy so that the bus - * has multiple addresses at which to receive messages. This bus is - * identified by Sprite pointer. Messages addressed to an ID are received by - * handlers connected to that ID. - */ - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - /** - * Overrides the default AZ::EBusTraits ID type so that Sprite pointers are - * used to access the addresses of the bus. - */ - typedef ISprite* BusIdType; - ////////////////////////////////////////////////////////////////////////// - - virtual ~UiSpriteSettingsChangeNotification() {} - - //! Called when the sprite settings such as number of cells etc change - virtual void OnSpriteSettingsChanged() = 0; -}; - -typedef AZ::EBus<UiSpriteSettingsChangeNotification> UiSpriteSettingsChangeNotificationBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Notify listeners when sprite image sources change. -class UiSpriteSourceNotificationInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiSpriteSourceNotificationInterface() {} - - //! A sprite image (or sequence of images) has changed file sources. - virtual void OnSpriteSourceChanged() = 0; -}; - -typedef AZ::EBus<UiSpriteSourceNotificationInterface> UiSpriteSourceNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/Tools/UiSystemToolsBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/Tools/UiSystemToolsBus.h deleted file mode 100644 index 69ecea5bbf..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/Tools/UiSystemToolsBus.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/EBus/EBus.h> -#include <AzCore/Component/Component.h> -#include <AzCore/Slice/SliceComponent.h> -#include <AzCore/Serialization/ObjectStream.h> - -namespace AZ -{ - namespace IO - { - class FileIOStream; - } -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Bus interface for tools to talk to the LyShine system -//! It is valid to use this bus from resource compilers or the UI Editor -class UiSystemToolsInterface - : public AZ::EBusTraits -{ -public: // types - - class CanvasAssetHandle - { - public: - virtual ~CanvasAssetHandle() {}; - }; - -public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - using MutexType = AZStd::recursive_mutex; - - // Public functions - - //! Load a canvas but do not init or activate the entities - //! The CanvasAssetHandle is an opaque pointer only valid to be passed to the - //! methods below. - virtual CanvasAssetHandle* LoadCanvasFromStream(AZ::IO::GenericStream& stream, const AZ::ObjectStream::FilterDescriptor& filterDesc) = 0; - - //! Save a canvas to a stream - virtual void SaveCanvasToStream(CanvasAssetHandle* canvas, AZ::IO::FileIOStream& stream) = 0; - - //! Get the slice component for a loaded canvas - virtual AZ::SliceComponent* GetRootSliceSliceComponent(CanvasAssetHandle* canvas) = 0; - - //! Get the slice entity for a loaded canvas - virtual AZ::Entity* GetRootSliceEntity(CanvasAssetHandle* canvas) = 0; - - //! Get the canvas entity for a loaded canvas - virtual AZ::Entity* GetCanvasEntity(CanvasAssetHandle* canvas) = 0; - - //! Replace the slice component with a new one. The old slice component is not deleted. - //! The client is responsible for that. - virtual void ReplaceRootSliceSliceComponent(CanvasAssetHandle* canvas, AZ::SliceComponent* newSliceComponent) = 0; - - //! Replace the canvas entity with a new one. The old canvas entity is not deleted. - //! The client is responsible for that. - virtual void ReplaceCanvasEntity(CanvasAssetHandle* canvas, AZ::Entity* newCanvasEntity) = 0; - - //! Delete the canvas file object and its canvas entity and slice entity. - virtual void DestroyCanvas(CanvasAssetHandle* canvas) = 0; -}; - -using UiSystemToolsBus = AZ::EBus<UiSystemToolsInterface>; - diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiAnimateEntityBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiAnimateEntityBus.h deleted file mode 100644 index 8465165056..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiAnimateEntityBus.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -// Forward declarations -class ISprite; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiAnimateEntityInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiAnimateEntityInterface() {} - - //! Called when the animation system has updated the data members of an entity's components - virtual void PropertyValuesChanged() = 0; - -public: // static member data - - //! More than one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; -}; - -typedef AZ::EBus<UiAnimateEntityInterface> UiAnimateEntityBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiAnimationBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiAnimationBus.h deleted file mode 100644 index 63d0e4d84a..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiAnimationBus.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/EBus/EBus.h> - -#include <LyShine/Animation/IUiAnimation.h> - -struct IUiAnimNode; - -namespace AZ -{ - class Entity; -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiAnimNodeInterface - : public AZ::EBusTraits -{ -public: - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - typedef IUiAnimNode* BusIdType; - //! Only one implementation for an IAnimNode* can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - -public: // member functions - - virtual ~UiAnimNodeInterface() {} - - virtual AZ::EntityId GetAzEntityId() = 0; - virtual void SetAzEntity(AZ::Entity* entity) = 0; -}; - -typedef AZ::EBus<UiAnimNodeInterface> UiAnimNodeBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiAnimationInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiAnimationInterface() {} - - //! Start a sequence - virtual void StartSequence(const AZStd::string& sequenceName) = 0; - - //! Play a sequence from startTime to endTime - virtual void PlaySequenceRange(const AZStd::string& sequenceName, float startTime, float endTime) = 0; - - //! Stop a sequence - virtual void StopSequence(const AZStd::string& sequenceName) = 0; - - //! Abort a sequence - virtual void AbortSequence(const AZStd::string& sequenceName) = 0; - - //! Pause a sequence - virtual void PauseSequence(const AZStd::string& sequenceName) = 0; - - //! Resume a sequence - virtual void ResumeSequence(const AZStd::string& sequenceName) = 0; - - //! Reset a sequence - virtual void ResetSequence(const AZStd::string& sequenceName) = 0; - - //! Get the speed of a sequence - virtual float GetSequencePlayingSpeed(const AZStd::string& sequenceName) = 0; - - //! Set the speed of a sequence - virtual void SetSequencePlayingSpeed(const AZStd::string& sequenceName, float speed) = 0; - - //! Get the current time of a sequence - virtual float GetSequencePlayingTime(const AZStd::string& sequenceName) = 0; - - //! Get whether a sequence is currently playing - virtual bool IsSequencePlaying(const AZStd::string& sequenceName) = 0; - - //! Get the length of a sequence in seconds - virtual float GetSequenceLength(const AZStd::string& sequenceName) = 0; - - //! Set the behavior a sequence will exhibit when it stops playing - virtual void SetSequenceStopBehavior(IUiAnimationSystem::ESequenceStopBehavior stopBehavior) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiAnimationInterface> UiAnimationBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiAnimationNotifications - : public AZ::ComponentBus -{ -public: - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const bool EnableEventQueue = true; - ////////////////////////////////////////////////////////////////////////// - -public: // member functions - - virtual ~UiAnimationNotifications(){} - - //! Called on an animation event - virtual void OnUiAnimationEvent(IUiAnimationListener::EUiAnimationEvent uiAnimationEvent, AZStd::string animSequenceName) = 0; - - //! Called on animation track event triggered - virtual void OnUiTrackEvent(AZStd::string eventName, AZStd::string valueName, AZStd::string animSequenceName) {} -}; - -typedef AZ::EBus<UiAnimationNotifications> UiAnimationNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiButtonBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiButtonBus.h deleted file mode 100644 index 11e3dd3724..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiButtonBus.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> -#include <LyShine/UiBase.h> - -class ISprite; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiButtonInterface - : public AZ::ComponentBus -{ -public: // types - - typedef AZStd::function<void(AZ::EntityId, AZ::Vector2)> OnClickCallback; - -public: // member functions - - virtual ~UiButtonInterface() {} - - //! Get the on-click callback - virtual OnClickCallback GetOnClickCallback() = 0; - - //! Set the on-click callback - virtual void SetOnClickCallback(OnClickCallback onClick) = 0; - - //! Get the action name - virtual const LyShine::ActionName& GetOnClickActionName() = 0; - - //! Set the action name - virtual void SetOnClickActionName(const LyShine::ActionName& actionName) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiButtonInterface> UiButtonBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiButtonNotifications - : public AZ::ComponentBus -{ -public: - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const bool EnableEventQueue = true; - ////////////////////////////////////////////////////////////////////////// - -public: // member functions - - virtual ~UiButtonNotifications() {} - - //! Notify listeners that the button was clicked - virtual void OnButtonClick() {} -}; - -typedef AZ::EBus<UiButtonNotifications> UiButtonNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiCanvasBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiCanvasBus.h deleted file mode 100644 index 0c278ea87a..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiCanvasBus.h +++ /dev/null @@ -1,507 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> -#include <AzCore/Math/Matrix4x4.h> -#include <AzFramework/Input/Channels/InputChannelDigitalWithSharedModifierKeyStates.h> -#include <AzFramework/Input/User/LocalUserId.h> -#include <LyShine/UiBase.h> - -// Forward declarations -struct IUiAnimationSystem; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiCanvasInterface - : public AZ::ComponentBus -{ -public: // types - - enum class ErrorCode - { - NoError, - PrefabContainsExternalEntityRefs - }; - -public: // member functions - - //! Deleting a canvas will delete all its child elements recursively and all of their components - virtual ~UiCanvasInterface() {} - - //! Get the asset ID path name of this canvas. If not loaded or saved yet this will be "" - virtual const AZStd::string& GetPathname() = 0; - - //! Get the ID of this canvas. This will remain the same while this canvas is loaded. - virtual LyShine::CanvasId GetCanvasId() = 0; - - //! Get the unique ID of this canvas - virtual AZ::u64 GetUniqueCanvasId() = 0; - - //! Get the draw order of this canvas. Rendering is back-to-front, so higher numbers render in front of lower numbers. - virtual int GetDrawOrder() = 0; - - //! Set the draw order of this canvas. Rendering is back-to-front, so higher numbers render in front of lower numbers. - virtual void SetDrawOrder(int drawOrder) = 0; - - //! Get the flag indicating if this canvas will stay loaded through a level unload. - virtual bool GetKeepLoadedOnLevelUnload() = 0; - - //! Set the flag indicating if this canvas will stay loaded through a level unload. - virtual void SetKeepLoadedOnLevelUnload(bool keepLoaded) = 0; - - //! Force a layout recompute. Layouts marked for a recompute are handled on the canvas update, - //! so this can be used if an immediate recompute is desired - virtual void RecomputeChangedLayouts() = 0; - - //! Get the number child elements of this canvas - virtual int GetNumChildElements() = 0; - - //! Get the specified child element, index must be less than GetNumChildElements() - virtual AZ::Entity* GetChildElement(int index) = 0; - - //! Get the specified child entity Id, index must be less than GetNumChildElements() - virtual AZ::EntityId GetChildElementEntityId(int index) = 0; - - //! Get the child elements of this canvas - virtual LyShine::EntityArray GetChildElements() = 0; - - //! Get the child entity Ids of this canvas - virtual AZStd::vector<AZ::EntityId> GetChildElementEntityIds() = 0; - - //! Create a new element that is a child of the canvas, the canvas has ownership of the child - virtual AZ::Entity* CreateChildElement(const LyShine::NameType& name) = 0; - - //! Return the element on this canvas with the given id or nullptr if no match - virtual AZ::Entity* FindElementById(LyShine::ElementId id) = 0; - - //! Return the first element on this canvas with the given name or nullptr if no match - virtual AZ::Entity* FindElementByName(const LyShine::NameType& name) = 0; - - //! Return the first element on this canvas with the given name or nullptr if no match - virtual AZ::EntityId FindElementEntityIdByName(const LyShine::NameType& name) = 0; - - //! Find all elements on this canvas with the given name - virtual void FindElementsByName(const LyShine::NameType& name, LyShine::EntityArray& result) = 0; - - //! Return the element with the given hierarchical name or nullptr if no match - //! \param name, a hierarchical name relative to the root with '/' as the separator - virtual AZ::Entity* FindElementByHierarchicalName(const LyShine::NameType& name) = 0; - - //! Find all elements on this canvas matching the predicate - virtual void FindElements(AZStd::function<bool(const AZ::Entity*)> predicate, LyShine::EntityArray& result) = 0; - - //! Get the front-most element whose bounds include the given point in canvas space - //! \return nullptr if no match - virtual AZ::Entity* PickElement(AZ::Vector2 point) = 0; - - //! Get all element whose bounds intersect with the given box in canvas space - //! \return empty EntityArray if no match - virtual LyShine::EntityArray PickElements(const AZ::Vector2& bound0, const AZ::Vector2& bound1) = 0; - - //! Look for an entity with interactable component to handle an event at given point - virtual AZ::EntityId FindInteractableToHandleEvent(AZ::Vector2 point) = 0; - - //! Save this canvas to the given path in XML - //! \return true if no error - virtual bool SaveToXml(const string& assetIdPathname, const string& sourceAssetPathname) = 0; - - //! Save the given UI element entity to the given path as a prefab - //! \param pathname the path to save the prefab to - //! \param entity pointer to the entity to save as a prefab - //! \return true if no error - virtual bool SaveAsPrefab(const string& pathname, AZ::Entity* entity) = 0; - - //! Check if it is OK to save the given UI element entity to the given path as a prefab - //! \param entity pointer to the entity to save as a prefab - //! \return errorCode which is NoError if OK to save - virtual ErrorCode CheckElementValidToSaveAsPrefab(AZ::Entity* entity) = 0; - - //! Load a prefab element from the given file and optionally insert as child of given entity - //! \return the top level entity created - virtual AZ::Entity* LoadFromPrefab(const string& pathname, - bool makeUniqueName, - AZ::Entity* optionalInsertionPoint) = 0; - - //! Initialize a set of entities that have been added to the canvas - //! Used when instantiating a slice or for undo/redo, copy/paste - //! \param topLevelEntities - The elements that were created - //! \param makeUniqueNamesAndIds If false the entity names and ElementIds in the string are kept, else unique ones are generated - //! \param insertionPoint The parent element for the created elements, if nullptr the root element is the parent - virtual void FixupCreatedEntities(LyShine::EntityArray topLevelEntities, bool makeUniqueNamesAndIds, AZ::Entity* optionalInsertionPoint) = 0; - - //! Add an existing entity to the canvas (only for internal use from editor) - //! \param element The newly created element to add to the canvas - //! \param parent The parent element for the created element, if nullptr the root element is the parent - //! \param insertBefore The sibling element to place this element before, if nullptr then add as last child - virtual void AddElement(AZ::Entity* element, AZ::Entity* parent, AZ::Entity* insertBefore) = 0; - - //! Go through all elements in the canvas and reinitialize them - //! This is done whenever a slice asset changes and the entity context is rebuilt from the root slice asset - virtual void ReinitializeElements() = 0; - - //! Save this canvas to an XML string - //! \return the resulting string - virtual AZStd::string SaveToXmlString() = 0; - - //! Get an element name that is unique to the children of the specified parent and to an optional array of elements - //! \param parentEntityId The entityId of the parent who's children's names must not match the returned name - //! \param baseName The name to append a unique identifier to - //! \param includedChildren An array of any other elements who's names must not match the returned name - //! \return Unique name that does not match the specified parent's children or the optional array of children - virtual AZStd::string GetUniqueChildName(AZ::EntityId parentEntityId, AZStd::string baseName, const LyShine::EntityArray* includeChildren) = 0; - - //! Clone an element and add it to this canvas as a child of the given parent element - //! The entity and all its components/children are cloned and new IDs are generated - //! NOTE: Only state that is persistent/reflected is cloned - //! \param sourceEntity The entity to clone - //! \param parentEntity The parent element for the created elements, if nullptr the root element is the parent - //! \return The new entity - virtual AZ::Entity* CloneElement(AZ::Entity* sourceEntity, AZ::Entity* parentEntity) = 0; - - //! Clone an element and add it to this canvas as a child of the given parent element - //! The entity and all its components/children are cloned and new IDs are generated - //! NOTE: Only state that is persistent/reflected is cloned - //! \param sourceEntity The entity to clone (may be from a different canvas) - //! \param parentEntity The parent element for the created elements, if invalid the root element is the parent - //! \param insertBefore The child of the parent element that the new element should be inserted before, if invalid the new element is the last child element - //! \return The new entity - virtual AZ::EntityId CloneElementEntityId(AZ::EntityId sourceEntity, AZ::EntityId parentEntity, AZ::EntityId insertBefore) = 0; - - //! Create a clone of this canvas entity - //! \param canvasSize The resolution to display the canvas at - virtual AZ::Entity* CloneCanvas(const AZ::Vector2& canvasSize) = 0; - - //! Set the transformation from canvas space to viewport space - virtual void SetCanvasToViewportMatrix(const AZ::Matrix4x4& matrix) = 0; - - //! Get the transformation from canvas space to viewport space - virtual const AZ::Matrix4x4& GetCanvasToViewportMatrix() = 0; - - //! Get the transformation from viewport space to canvas space - virtual void GetViewportToCanvasMatrix(AZ::Matrix4x4& matrix) = 0; - - //! Returns the "target" size of the canvas (in pixels) - // - //! The target canvas size changes depending on whether you're running in - //! the UI Editor or in-game. While in-game, we assume that the canvas size - //! fills the screen, so the target canvas size is the size of the viewport. - // - //! When using the editor, however, the target size is the "authored" size of - //! the canvas. The canvas is authored in one resolution, but it may be - //! displayed by the game at whatever the game resolution is set to. - virtual AZ::Vector2 GetCanvasSize() = 0; - - //! Set the authored size of the canvas (in pixels) - virtual void SetCanvasSize(const AZ::Vector2& canvasSize) = 0; - - //! Set the target size of the canvas (in pixels) - //! - //! This should be called before the UpdateCanvas and RenderCanvas methods. - //! When running in game in full screen mode the target canvas size should be set to the viewport size - virtual void SetTargetCanvasSize(bool isInGame, const AZ::Vector2& targetCanvasSize) = 0; - - //! Get scale to adjust for the difference between canvas size (authored size) - //! and the viewport size (target canvas size) when running on current device - virtual AZ::Vector2 GetDeviceScale() = 0; - - //! Get flag that indicates whether visual element's vertices should snap to the nearest pixel - virtual bool GetIsPixelAligned() = 0; - - //! Set flag that indicates whether visual element's vertices should snap to the nearest pixel - virtual void SetIsPixelAligned(bool isPixelAligned) = 0; - - //! Get flag that indicates whether text should snap to the nearest pixel - virtual bool GetIsTextPixelAligned() = 0; - - //! Set flag that indicates whether text should snap to the nearest pixel - virtual void SetIsTextPixelAligned(bool isTextPixelAligned) = 0; - - //! Get the animation system for this canvas - virtual IUiAnimationSystem* GetAnimationSystem() = 0; - - //! Get flag that governs whether the canvas is enabled - // - //! A canvas that's enabled will be updated and rendered each frame. - virtual bool GetEnabled() = 0; - - //! Set flag that governs whether the canvas is enabled - // - //! A canvas that's enabled will be updated and rendered each frame. - virtual void SetEnabled(bool enabled) = 0; - - //! Get flag that controls whether the canvas is rendering to a texture - virtual bool GetIsRenderToTexture() = 0; - - //! Set flag that controls whether the canvas is rendering to a texture - virtual void SetIsRenderToTexture(bool isRenderToTexture) = 0; - - //! Get the render target name that this canvas will render to - virtual AZStd::string GetRenderTargetName() = 0; - - //! Set the render target name that this canvas will render to - virtual void SetRenderTargetName(const AZStd::string& name) = 0; - - //! Get flag that controls whether this canvas automatically handles positional input (mouse/touch) - virtual bool GetIsPositionalInputSupported() = 0; - - //! Set flag that controls whether this canvas automatically handles positional input (mouse/touch) - virtual void SetIsPositionalInputSupported(bool isSupported) = 0; - - //! Get flag that controls whether this canvas consumes all input events while it is enabled - virtual bool GetIsConsumingAllInputEvents() = 0; - - //! Set flag that controls whether this canvas consumes all input events while it is enabled - virtual void SetIsConsumingAllInputEvents(bool isConsuming) = 0; - - //! Get flag that controls whether this canvas automatically handles multi-touch input - virtual bool GetIsMultiTouchSupported() = 0; - - //! Set flag that controls whether this canvas automatically handles multi-touch input - virtual void SetIsMultiTouchSupported(bool isSupported) = 0; - - //! Get flag that controls whether this canvas automatically handles navigation input (via keyboard/gamepad) - virtual bool GetIsNavigationSupported() = 0; - - //! Set flag that controls whether this canvas automatically handles navigation input (via keyboard/gamepad) - virtual void SetIsNavigationSupported(bool isSupported) = 0; - - //! Get the analog (eg. thumb-stick) input value that must be exceeded before a navigation command will be processed - virtual float GetNavigationThreshold() = 0; - - //! Set the analog (eg. thumb-stick) input value that must be exceeded before a navigation command will be processed - virtual void SetNavigationThreshold(float navigationThreshold) = 0; - - //! Get the delay (milliseconds) before a held navigation command will begin repeating - virtual AZ::u64 GetNavigationRepeatDelay() = 0; - - //! Set the delay (milliseconds) before a held navigation command will begin repeating - virtual void SetNavigationRepeatDelay(AZ::u64 navigationRepeatDelay) = 0; - - //! Get the delay (milliseconds) before a held navigation command will continue repeating - virtual AZ::u64 GetNavigationRepeatPeriod() = 0; - - //! Set the delay (milliseconds) before a held navigation command will continue repeating - virtual void SetNavigationRepeatPeriod(AZ::u64 navigationRepeatPeriod) = 0; - - //! Get the local user id that is being used to filter incoming input events - virtual AzFramework::LocalUserId GetLocalUserIdInputFilter() = 0; - - //! Set the local user id that will be used to filter incoming input events - virtual void SetLocalUserIdInputFilter(AzFramework::LocalUserId localUserId) = 0; - - //! Handle an input event for the canvas - virtual bool HandleInputEvent(const AzFramework::InputChannel::Snapshot& inputSnapshot, - const AZ::Vector2* viewportPos = nullptr, - AzFramework::ModifierKeyMask activeModifierKeys = AzFramework::ModifierKeyMask::None) = 0; - - //! Handle a unicode text event for the canvas - virtual bool HandleTextEvent(const AZStd::string& textUTF8) = 0; - - //! Handle a positional input event for the canvas, this could come from - //! a ray cast intersection for example - virtual bool HandleInputPositionalEvent(const AzFramework::InputChannel::Snapshot& inputSnapshot, AZ::Vector2 viewportPos) = 0; - - //! Get the mouse position of the last input event - virtual AZ::Vector2 GetMousePosition() = 0; - - //! Get the element to be displayed when hovering over an interactable - virtual AZ::EntityId GetTooltipDisplayElement() = 0; - - //! Set the element to be displayed when hovering over an interactable - virtual void SetTooltipDisplayElement(AZ::EntityId entityId) = 0; - - //! Force the active interactable for the canvas to be the given one, - //! also force AutoActivation of interactable, - //! intended for internal use by UI components - virtual void ForceFocusInteractable(AZ::EntityId interactableId) = 0; - - //! Force the active interactable for the canvas to be the given one, - //! also set last mouse pos to point, - //! intended for internal use by UI components - virtual void ForceActiveInteractable(AZ::EntityId interactableId, bool shouldStayActive, AZ::Vector2 point) = 0; - - //! Get the hover interactable - virtual AZ::EntityId GetHoverInteractable() = 0; - - //! Force the hover interactable for the canvas to be the given one, this can be useful when using - //! keyboard/gamepad navigation and the current hover interactable is deleted by a script and the script - //! wants to specify the new hover interactable - virtual void ForceHoverInteractable(AZ::EntityId interactableId) = 0; - - //! Clear all active interactables, and all hover interactables if last input was positional (mouse/touch). - //! This is intended for internal use by UI components - virtual void ClearAllInteractables() = 0; - - //! Generate Enter pressed/released input events on an interactable. - //! Useful for automated testing to simulate button clicks - virtual void ForceEnterInputEventOnInteractable(AZ::EntityId interactableId) = 0; - -public: // static member data - - //! Only one component on an entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiCanvasInterface> UiCanvasBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! The canvas component implements this bus and it is provided for C++ implementations of -//! UI components to use to talk to the canvas -class UiCanvasComponentImplementationInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiCanvasComponentImplementationInterface() {} - - //! Mark the render graph for the canvas as dirty. This will cause the render graph to get - //! cleared and rebuilt on the next render. - virtual void MarkRenderGraphDirty() = 0; - -public: // static member data - - //! Only one component on an entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiCanvasComponentImplementationInterface> UiCanvasComponentImplementationBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that listeners need to implement to be notified of canvas actions -class UiCanvasActionNotification - : public AZ::ComponentBus -{ -public: - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const bool EnableEventQueue = true; - ////////////////////////////////////////////////////////////////////////// - -public: // member functions - - virtual ~UiCanvasActionNotification(){} - - //! Called when the canvas sends an action to the listener - virtual void OnAction(AZ::EntityId entityId, const LyShine::ActionName& actionName) = 0; -}; - -typedef AZ::EBus<UiCanvasActionNotification> UiCanvasNotificationBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that listeners need to implement to be notified when the draw order of any -//! canvas changes -class UiCanvasOrderNotification - : public AZ::EBusTraits -{ -public: // member functions - - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - virtual ~UiCanvasOrderNotification(){} - - //! Called when the draw order setting for a canvas changes - //! Note this is used to update the order in the UiCanvasManager so that - //! order has not been updated when this fires. - virtual void OnCanvasDrawOrderChanged(AZ::EntityId canvasEntityId) = 0; -}; - -typedef AZ::EBus<UiCanvasOrderNotification> UiCanvasOrderNotificationBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that listeners need to implement to be notified when any canvas has been -//! enabled or disabled -class UiCanvasEnabledStateNotification - : public AZ::EBusTraits -{ -public: // member functions - - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - virtual ~UiCanvasEnabledStateNotification() {} - - //! Called when the canvas was enabled or disabled - virtual void OnCanvasEnabledStateChanged(AZ::EntityId canvasEntityId, bool enabled) = 0; -}; - -typedef AZ::EBus<UiCanvasEnabledStateNotification> UiCanvasEnabledStateNotificationBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that listeners need to implement to be notified of canvas size or scale changes -class UiCanvasSizeNotification - : public AZ::EBusTraits -{ -public: - virtual ~UiCanvasSizeNotification() {} - - //! Called when the target canvas size or uniform device scale changes. - virtual void OnCanvasSizeOrScaleChange(AZ::EntityId canvasEntityId) = 0; -}; - -typedef AZ::EBus<UiCanvasSizeNotification> UiCanvasSizeNotificationBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that listeners need to implement to be notified of changes to the canvas -//! pixel alignment settings -class UiCanvasPixelAlignmentNotification - : public AZ::ComponentBus -{ -public: - virtual ~UiCanvasPixelAlignmentNotification() {} - - //! Called when the pixel alignment setting for the canvas changes - virtual void OnCanvasPixelAlignmentChange() {} - - //! Called when the text pixel alignment setting for the canvas changes - virtual void OnCanvasTextPixelAlignmentChange() {} -}; - -typedef AZ::EBus<UiCanvasPixelAlignmentNotification> UiCanvasPixelAlignmentNotificationBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that listeners need to implement to be notified of canvas input. -//! Note that interactables already get methods called on them when they themselves are interacted -//! with. This notification bus is intended for other entities or Lua to know when some other -//! entities are interacted with. -class UiCanvasInputNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiCanvasInputNotifications() {} - - //! Called when an element is pressed. Will return an invalid entity id if no interactable was - //! pressed. - virtual void OnCanvasPrimaryPressed([[maybe_unused]] AZ::EntityId entityId) {}; - - //! Called when an element is released. The released entity that is sent is the entity that was - //! active (if any). - virtual void OnCanvasPrimaryReleased([[maybe_unused]] AZ::EntityId entityId) {}; - - //! Called when an element is pressed. Will be an invalid entity id if no interactable was - //! pressed. - virtual void OnCanvasMultiTouchPressed([[maybe_unused]] AZ::EntityId entityId, [[maybe_unused]] int multiTouchIndex) {}; - - //! Called when an element is released. The released entity that is sent is the entity that was - //! active (if any). - virtual void OnCanvasMultiTouchReleased([[maybe_unused]] AZ::EntityId entityId, [[maybe_unused]] int multiTouchIndex) {}; - - //! Called when an element starts being hovered - virtual void OnCanvasHoverStart([[maybe_unused]] AZ::EntityId entityId) {}; - - //! Called when an element ends being hovered - virtual void OnCanvasHoverEnd([[maybe_unused]] AZ::EntityId entityId) {}; - - //! Called when the enter key is pressed - virtual void OnCanvasEnterPressed([[maybe_unused]] AZ::EntityId entityId) {}; - - //! Called when the enter key is released - virtual void OnCanvasEnterReleased([[maybe_unused]] AZ::EntityId entityId) {}; -}; - -typedef AZ::EBus<UiCanvasInputNotifications> UiCanvasInputNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiCanvasManagerBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiCanvasManagerBus.h deleted file mode 100644 index c964518c61..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiCanvasManagerBus.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzFramework/Input/User/LocalUserId.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiCanvasManagerInterface - : public AZ::EBusTraits -{ -public: // types - - typedef std::vector<AZ::EntityId> CanvasEntityList; - -public: - //! Create a canvas - virtual AZ::EntityId CreateCanvas() = 0; - - //! Load a canvas - virtual AZ::EntityId LoadCanvas(const AZStd::string& canvasPathname) = 0; - - //! Unload a canvas - virtual void UnloadCanvas(AZ::EntityId canvasEntityId) = 0; - - //! Find a canvas by path, optionally load the canvas if it was not found - virtual AZ::EntityId FindLoadedCanvasByPathName(const AZStd::string& canvasPathname, bool loadIfNotFound = false) = 0; - - //! Get a list of canvases that are loaded in game, this is sorted by draw order - virtual CanvasEntityList GetLoadedCanvases() = 0; - - //! Set the local user id that will be used to filter incoming input events for all canvases. - //! Can be overriden for an individual canvas using UiCanvasInterface::SetLocalUserIdInputFilter. - virtual void SetLocalUserIdInputFilterForAllCanvases(AzFramework::LocalUserId localUserId) = 0; -}; -typedef AZ::EBus<UiCanvasManagerInterface> UiCanvasManagerBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that listeners need to implement to be notified of canvas manager changes -class UiCanvasManagerNotification - : public AZ::EBusTraits -{ -public: - ////////////////////////////////////////////////////////////////////////// - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - ////////////////////////////////////////////////////////////////////////// - - virtual ~UiCanvasManagerNotification() {} - - //! Called when a canvas has been loaded - virtual void OnCanvasLoaded([[maybe_unused]] AZ::EntityId canvasEntityId) {} - - //! Called when a canvas has been unloaded/destroyed - virtual void OnCanvasUnloaded([[maybe_unused]] AZ::EntityId canvasEntityId) {} - - //! Called when a canvas has been reloaded (due to hot-loading) - //! For a hot-load, the OnCanvasLoaded/OnCanvasUnloaded notifications are not sent - only this one is - virtual void OnCanvasReloaded([[maybe_unused]] AZ::EntityId canvasEntityId) {} -}; - -typedef AZ::EBus<UiCanvasManagerNotification> UiCanvasManagerNotificationBus; - diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiCanvasUpdateNotificationBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiCanvasUpdateNotificationBus.h deleted file mode 100644 index ce4eb37f4a..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiCanvasUpdateNotificationBus.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Elements that require update notifications should connect to this bus using the entity id of their -//! containing canvas. -class UiCanvasUpdateNotification - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiCanvasUpdateNotification() {} - - //! Update the component. This is called when the game is running. - //! It is different from the TickBus in that it is called only when the canvas is updated. - //! So it is not called if the canvas is disabled. - virtual void Update(float deltaTime) = 0; - - //! Update the component while in the editor. - //! This is called every frame when in the editor and the game is NOT running. - virtual void UpdateInEditor(float /*deltaTime*/) {} - -public: // static member data - - //! Multiple components on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; -}; - -typedef AZ::EBus<UiCanvasUpdateNotification> UiCanvasUpdateNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiCheckboxBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiCheckboxBus.h deleted file mode 100644 index c9fddd2be9..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiCheckboxBus.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiCheckboxInterface - : public AZ::ComponentBus -{ -public: // types - - //! params: sending entity id, new state - typedef AZStd::function<void(AZ::EntityId, AZ::Vector2, bool)> StateChangeCallback; - -public: // member functions - - virtual ~UiCheckboxInterface() {} - - //! Query the state of the checkbox - //! \return The current state for the checkbox. - virtual bool GetState() = 0; - - //! Manually override the state of the checkbox - //! \param isOn The new desired state of the checkbox. - virtual void SetState(bool checked) = 0; - - //! Toggle the state of the checkbox - //! \return The new state of the checkbox. - virtual bool ToggleState() = 0; - - //! Get the state change callback - virtual StateChangeCallback GetStateChangeCallback() = 0; - - //! Set the state change callback - virtual void SetStateChangeCallback(StateChangeCallback onChange) = 0; - - //! Set the optional checked (ON) entity - virtual void SetCheckedEntity(AZ::EntityId entityId) = 0; - - //! Get the optional checked (ON) entity - virtual AZ::EntityId GetCheckedEntity() = 0; - - //! Set the optional unchecked (OFF) entity - virtual void SetUncheckedEntity(AZ::EntityId entityId) = 0; - - //! Get the optional unchecked (OFF) entity - virtual AZ::EntityId GetUncheckedEntity() = 0; - - //! Get the action triggered when turned on - virtual const LyShine::ActionName& GetTurnOnActionName() = 0; - - //! Set the action triggered when turned on - virtual void SetTurnOnActionName(const LyShine::ActionName& actionName) = 0; - - //! Get the action triggered when turned off - virtual const LyShine::ActionName& GetTurnOffActionName() = 0; - - //! Set the action triggered when turned off - virtual void SetTurnOffActionName(const LyShine::ActionName& actionName) = 0; - - //! Get the action triggered when changed - virtual const LyShine::ActionName& GetChangedActionName() = 0; - - //! Set the action triggered when changed - virtual void SetChangedActionName(const LyShine::ActionName& actionName) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiCheckboxInterface> UiCheckboxBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiCheckboxNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiCheckboxNotifications() {} - - //! Notify listeners that the checkbox state has changed - virtual void OnCheckboxStateChange([[maybe_unused]] bool checked) {} -}; - -typedef AZ::EBus<UiCheckboxNotifications> UiCheckboxNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiCursorBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiCursorBus.h deleted file mode 100644 index 09c3155f23..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiCursorBus.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/EBus/EBus.h> - -#include <AzCore/Math/Vector2.h> - -class UiCursorInterface - : public AZ::EBusTraits -{ -public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - // Public functions - - //! Increment the UI Cursor visible counter. - //! Should be paired with a call to DecrementVisibleCounter. - virtual void IncrementVisibleCounter() = 0; - - //! Decrement the UI Cursor visible counter. - //! Should be paired with a call to IncrementVisibleCounter. - virtual void DecrementVisibleCounter() = 0; - - //! Query whether the UI Cursor is currently visible - virtual bool IsUiCursorVisible() = 0; - - //! Set the UI cursor image. - virtual void SetUiCursor(const char* cursorImagePath) = 0; - - //! Get the UI cursor position (in pixels) relative - //! to the top-left corner of the UI overlay viewport - virtual AZ::Vector2 GetUiCursorPosition() = 0; -}; - -using UiCursorBus = AZ::EBus<UiCursorInterface>; - diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiDraggableBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiDraggableBus.h deleted file mode 100644 index 4696e4c103..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiDraggableBus.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiDraggableInterface - : public AZ::ComponentBus -{ -public: // types - - //! States that the component can be in during a drag. Lua scripts can switch the state to alert the user - enum class DragState - { - Normal, - Valid, - Invalid - }; - -public: // member functions - - virtual ~UiDraggableInterface() {} - - //! Get the state of the drag - virtual DragState GetDragState() = 0; - - //! Set the state of the drag. This is only relevant during a drag. - //! The state affects the visual state of the draggable and can be used to indicate when it is - //! over a valid drop target. - virtual void SetDragState(DragState dragState) = 0; - - //! Redo the drag, this is not usually needed but if a UiDraggableNotificationBus handler causes - //! drop targets to move, and keyboard or console navigation is being used, it can be needed. - //! In that case the handler should call this method after moving drop targets. - virtual void RedoDrag(AZ::Vector2 point) = 0; - - //! Set this draggable element to be a proxy for another draggable element and start a drag on - //! this draggable element at the specified point - virtual void SetAsProxy(AZ::EntityId originalDraggableId, AZ::Vector2 point) = 0; - - //! Conclude the drag of a proxy. This should be called from the OnDragEnd callback of the proxy and - //! will result in calling OnDragEnd on the draggable element that this is a proxy for - virtual void ProxyDragEnd(AZ::Vector2 point) = 0; - - //! Check if this draggable element is a proxy - virtual bool IsProxy() = 0; - - //! Get the original draggable element that this element is a proxy for - //! Returns an invalid entity id if this is not a proxy - virtual AZ::EntityId GetOriginalFromProxy() = 0; - - //! Get the flag that indicates if this draggable can be dropped on any canvas - virtual bool GetCanDropOnAnyCanvas() = 0; - - //! Set the flag that indicates if this draggable can be dropped on any canvas - virtual void SetCanDropOnAnyCanvas(bool anyCanvas) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiDraggableInterface> UiDraggableBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiDraggableNotifications - : public AZ::ComponentBus -{ -public: - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const bool EnableEventQueue = true; - ////////////////////////////////////////////////////////////////////////// - -public: // member functions - - virtual ~UiDraggableNotifications() {} - - //! Called on drag start - virtual void OnDragStart(AZ::Vector2 position) = 0; - - //! Called on position change during drag - virtual void OnDrag(AZ::Vector2 position) = 0; - - //! Called on drag end - virtual void OnDragEnd(AZ::Vector2 position) = 0; -}; - -typedef AZ::EBus<UiDraggableNotifications> UiDraggableNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiDropTargetBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiDropTargetBus.h deleted file mode 100644 index 42bdb14bcc..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiDropTargetBus.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiDropTargetInterface - : public AZ::ComponentBus -{ -public: // types - - using DropState = int; - enum - { - DropStateNormal = 0, - DropStateValid, - DropStateInvalid, - - NumDropStates - }; - -public: // member functions - - virtual ~UiDropTargetInterface() {} - - //! Get the OnDrop action name - virtual const LyShine::ActionName& GetOnDropActionName() = 0; - - //! Set the OnDrop action name - virtual void SetOnDropActionName(const LyShine::ActionName& actionName) = 0; - - //! Called when mouse/touch enters the bounds of this drop target while dragging a UiDraggableComponent - virtual void HandleDropHoverStart(AZ::EntityId draggable) = 0; - - //! Called on the currently drop hovered drop target component when mouse/touch moves outside of bounds - virtual void HandleDropHoverEnd(AZ::EntityId draggable) = 0; - - //! Called when a draggable is dropped on this drop target - virtual void HandleDrop(AZ::EntityId draggable) = 0; - - //! Get the state of the drop - virtual DropState GetDropState() = 0; - - //! Set the state of the drop target. - //! The state affects the visual state of the drop target and can be used to indicate when it has - //! a valid draggable hovering over it. - virtual void SetDropState(DropState dropState) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiDropTargetInterface> UiDropTargetBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiDropTargetNotifications - : public AZ::ComponentBus -{ -public: - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const bool EnableEventQueue = true; - ////////////////////////////////////////////////////////////////////////// - -public: // member functions - - virtual ~UiDropTargetNotifications() {} - - //! Called on starting hovering over a drop target - virtual void OnDropHoverStart(AZ::EntityId draggable) = 0; - - //! Called on ending hovering over a drop target - virtual void OnDropHoverEnd(AZ::EntityId draggable) = 0; - - //! Called on drop - virtual void OnDrop(AZ::EntityId draggable) = 0; -}; - -typedef AZ::EBus<UiDropTargetNotifications> UiDropTargetNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiDropdownBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiDropdownBus.h deleted file mode 100644 index 18994b67d6..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiDropdownBus.h +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! The UI Dropdown Component is an interactable component which displays a list of options when clicked. -//! In its default state, the dropdown display a simple button, next to an arrow indicating the dropdown -//! functionality. When the arrow / option is clicked, the dropdown list appears, displaying the options available. -//! If the list is too long to be displayed, a scrollbar can be added to scroll up and down the list of options. -class UiDropdownInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiDropdownInterface() {} - - //! Get the currently selected option - virtual AZ::EntityId GetValue() = 0; - - //! Set the currently selected option manually - virtual void SetValue(AZ::EntityId value) = 0; - - //! Get the content element this dropdown will expand - virtual AZ::EntityId GetContent() = 0; - - //! Set the content element this dropdown will expand - virtual void SetContent(AZ::EntityId content) = 0; - - //! Get whether this dropdown should expand automatically on hover - virtual bool GetExpandOnHover() = 0; - - //! Set whether this dropdown should expand automatically on hover - virtual void SetExpandOnHover(bool expandOnHover) = 0; - - //! Get how long to wait before expanding upon hover / collapsing upon exit - virtual float GetWaitTime() = 0; - - //! Set how long to wait before expanding upon hover / collapsing upon exit - virtual void SetWaitTime(float waitTime) = 0; - - //! Get whether this dropdown should collapse when the user clicks outside - virtual bool GetCollapseOnOutsideClick() = 0; - - //! Set whether this dropdown should collapse when the user clicks outside - virtual void SetCollapseOnOutsideClick(bool collapseOnOutsideClick) = 0; - - //! Get the element the dropdown content will parent to when expanded (the canvas by default) - virtual AZ::EntityId GetExpandedParentId() = 0; - - //! Set the element the dropdown content will parent to when expanded - virtual void SetExpandedParentId(AZ::EntityId expandedParentId) = 0; - - //! Get the text element to display to show the currently selected option - virtual AZ::EntityId GetTextElement() = 0; - - //! Set the text element to display to show the currently selected option - virtual void SetTextElement(AZ::EntityId textElement) = 0; - - //! Get the icon element to display to show the currently selected option - virtual AZ::EntityId GetIconElement() = 0; - - //! Set the icon element to display to show the currently selected option - virtual void SetIconElement(AZ::EntityId iconElement) = 0; - - //! Expand the dropdown - virtual void Expand() = 0; - - //! Collapse the dropdown - virtual void Collapse() = 0; - - //! Get the name of the action that is sent when the dropdown is expanded - virtual const LyShine::ActionName& GetExpandedActionName() = 0; - - //! Set the name of the action that is sent when the dropdown is expanded - virtual void SetExpandedActionName(const LyShine::ActionName& actionName) = 0; - - //! Get the name of the action that is sent when the dropdown is collapsed - virtual const LyShine::ActionName& GetCollapsedActionName() = 0; - - //! Set the name of the action that is sent when the dropdown is collapsed - virtual void SetCollapsedActionName(const LyShine::ActionName& actionName) = 0; - - //! Get the name of the action that is sent when the dropdown value is changed - virtual const LyShine::ActionName& GetOptionSelectedActionName() = 0; - - //! Set the name of the action that is sent when the dropdown value is changed - virtual void SetOptionSelectedActionName(const LyShine::ActionName& actionName) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiDropdownInterface> UiDropdownBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiDropdownNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiDropdownNotifications() {} - - //! Notify listeners that the dropdown was expanded - virtual void OnDropdownExpanded() {} - - //! Notify listeners that the dropdown was collapsed - virtual void OnDropdownCollapsed() {} - - //! Notify listeners that an option was selected - virtual void OnDropdownValueChanged([[maybe_unused]] AZ::EntityId option) {} -}; - -typedef AZ::EBus<UiDropdownNotifications> UiDropdownNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiDropdownOptionBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiDropdownOptionBus.h deleted file mode 100644 index c46a52e207..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiDropdownOptionBus.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! The UiDropdownOptionComponent is a component that is designed to work in conjunction with the -//! UiDropdownComponent. It represents any option of that dropdown that the user should be able to -//! select to update the value of the dropdown. -class UiDropdownOptionInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiDropdownOptionInterface() {} - - //! Get the owning dropdown of this option - virtual AZ::EntityId GetOwningDropdown() = 0; - - //! Set the owning dropdown of this option - virtual void SetOwningDropdown(AZ::EntityId owningDropdown) = 0; - - //! Get the text element of this option - virtual AZ::EntityId GetTextElement() = 0; - - //! Set the text element of this option - virtual void SetTextElement(AZ::EntityId textElement) = 0; - - //! Get the icon element of this option - virtual AZ::EntityId GetIconElement() = 0; - - //! Set the icon element of this option - virtual void SetIconElement(AZ::EntityId iconElement) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiDropdownOptionInterface> UiDropdownOptionBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiDropdownOptionNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiDropdownOptionNotifications() {} - - //! Notify listeners that the dropdown option was selected - virtual void OnDropdownOptionSelected() {} -}; - -typedef AZ::EBus<UiDropdownOptionNotifications> UiDropdownOptionNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiDynamicLayoutBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiDynamicLayoutBus.h deleted file mode 100644 index 2ff0e81263..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiDynamicLayoutBus.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that a dynamic layout component needs to implement. A dynamic layout component -//! clones a prototype element to achieve the desired number of children. The parent is resized -//! accordingly -class UiDynamicLayoutInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiDynamicLayoutInterface() {} - - //! Clone a prototype element or remove cloned elements to end up with the specified number of children - virtual void SetNumChildElements(int numChildren) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiDynamicLayoutInterface> UiDynamicLayoutBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiDynamicScrollBoxBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiDynamicScrollBoxBus.h deleted file mode 100644 index d09c1ce81a..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiDynamicScrollBoxBus.h +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that a dynamic scrollbox component needs to implement. A dynamic scrollbox -//! component sets up scrollbox content as a horizontal or vertical list of elements that are -//! cloned from prototype entities. Only the minimum number of entities are created for efficient -//! scrolling -class UiDynamicScrollBoxInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiDynamicScrollBoxInterface() {} - - //! Refresh the content. Should be called when list size or element content has changed. - //! This will reset any cached information such as element sizes, so it is recommended - //! to use AddElementsToEnd and RemoveElementsFromFront if possible when elements vary - //! in size. AddElementsToEnd and RemoveElementsFromFront will also ensure that the - //! scroll offset is adjusted to keep the visible elements in place - virtual void RefreshContent() = 0; - - //! Add elements to the end of the list. - //! Used with lists that are not divided into sections - virtual void AddElementsToEnd(int numElementsToAdd, bool scrollToEndIfWasAtEnd) = 0; - - //! Remove elements from the front of the list. - //! Used with lists that are not divided into sections - virtual void RemoveElementsFromFront(int numElementsToRemove) = 0; - - //! Scroll to the end of the list - virtual void ScrollToEnd() = 0; - - //! Get the element index of the specified child element. Returns -1 if not found. - //! If the list is divided into sections, the index is local to the section - virtual int GetElementIndexOfChild(AZ::EntityId childElement) = 0; - - //! Get the section index of the specified child element. Returns -1 if not found. - //! Used with lists that are divided into sections - virtual int GetSectionIndexOfChild(AZ::EntityId childElement) = 0; - - //! Get the child element at the specified element index. - //! Used with lists that are not divided into sections - virtual AZ::EntityId GetChildAtElementIndex(int index) = 0; - - //! Get the child element at the specified section index and element index. - //! Used with lists that are divided into sections - virtual AZ::EntityId GetChildAtSectionAndElementIndex(int sectionIndex, int index) = 0; - - //! Get whether the list should automatically prepare and refresh its content post activation - virtual bool GetAutoRefreshOnPostActivate() = 0; - - //! Set whether the list should automatically prepare and refresh its content post activation - virtual void SetAutoRefreshOnPostActivate(bool autoRefresh) = 0; - - //! Get the prototype entity used for the elements - virtual AZ::EntityId GetPrototypeElement() = 0; - - //! Set the prototype entity used for the elements - virtual void SetPrototypeElement(AZ::EntityId prototypeElement) = 0; - - //! Get whether the elements vary in size - virtual bool GetElementsVaryInSize() = 0; - - //! Set whether the elements vary in size - virtual void SetElementsVaryInSize(bool varyInSize) = 0; - - //! Get whether to auto calculate the elements when they vary in size - virtual bool GetAutoCalculateVariableElementSize() = 0; - - //! Set whether to auto calculate the elements when they vary in size - virtual void SetAutoCalculateVariableElementSize(bool autoCalculateSize) = 0; - - //! Get the estimated size for the variable elements. If set to 0, then element sizes - //! are calculated up front rather than when becoming visible - virtual float GetEstimatedVariableElementSize() = 0; - - //! Set the estimated size for the variable elements. If set to 0, then element sizes - //! are calculated up front rather than when becoming visible - virtual void SetEstimatedVariableElementSize(float estimatedSize) = 0; - - //! Get whether the list is divided into sections with headers - virtual bool GetSectionsEnabled() = 0; - - //! Set whether the list is divided into sections with headers - virtual void SetSectionsEnabled(bool enabled) = 0; - - //! Get the prototype entity used for the headers - virtual AZ::EntityId GetPrototypeHeader() = 0; - - //! Set the prototype entity used for the headers - virtual void SetPrototypeHeader(AZ::EntityId prototypeHeader) = 0; - - //! Get whether headers stick to the beginning of the visible list area - virtual bool GetHeadersSticky() = 0; - - //! Set whether headers stick to the beginning of the visible list area - virtual void SetHeadersSticky(bool stickyHeaders) = 0; - - //! Get whether the headers vary in size - virtual bool GetHeadersVaryInSize() = 0; - - //! Set whether the headers vary in size - virtual void SetHeadersVaryInSize(bool varyInSize) = 0; - - //! Get whether to auto calculate the headers when they vary in size - virtual bool GetAutoCalculateVariableHeaderSize() = 0; - - //! Set whether to auto calculate the headers when they vary in size - virtual void SetAutoCalculateVariableHeaderSize(bool autoCalculateSize) = 0; - - //! Get the estimated size for the variable headers. If set to 0, then header sizes - //! are calculated up front rather than when becoming visible - virtual float GetEstimatedVariableHeaderSize() = 0; - - //! Set the estimated size for the variable headers. If set to 0, then header sizes - //! are calculated up front rather than when becoming visible - virtual void SetEstimatedVariableHeaderSize(float estimatedSize) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiDynamicScrollBoxInterface> UiDynamicScrollBoxBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that provides data needed to display a list of elements -class UiDynamicScrollBoxDataInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiDynamicScrollBoxDataInterface() {} - - //! Returns the number of elements in the list. - //! Called when the list is being constructed (in the component's InGamePostActivate or when RefreshContent is being called explicitely). - //! Used with lists that are not divided into sections - virtual int GetNumElements() { return 0; } - - //! Returns the width of an element at the specified index. - //! Called when a horizontal list contains elements of varying size, and the element's "auto calculate size" option is disabled. - //! Used with lists that are not divided into sections - virtual float GetElementWidth([[maybe_unused]] int index) { return 0.0f; } - - //! Returns the height of an element at the specified index. - //! Called when a vertical list contains elements of varying size, and the element's "auto calculate size" option is disabled. - //! Used with lists that are not divided into sections - virtual float GetElementHeight([[maybe_unused]] int index) { return 0.0f; } - - //! Returns the number of sections in the list. - //! Called when the list is being constructed (in the component's InGamePostActivate or when RefreshContent is being called explicitely). - //! Used with lists that are divided into sections - virtual int GetNumSections() { return 0; } - - //! Returns the number of elements in the specified section. - //! Called when the list is being constructed (in the component's InGamePostActivate or when RefreshContent is being called explicitely). - //! Used with lists that are divided into sections - virtual int GetNumElementsInSection([[maybe_unused]] int sectionIndex) { return 0; } - - //! Returns the width of an element at the specified section. - //! Called when a horizontal list contains elements of varying size, and the element's "auto calculate size" option is disabled. - //! Used with lists that are divided into sections - virtual float GetElementInSectionWidth([[maybe_unused]] int sectionIndex, [[maybe_unused]] int elementindex) { return 0.0f; } - - //! Returns the height of an element at the specified section. - //! Called when a vertical list contains elements of varying size, and the element's "auto calculate size" option is disabled. - //! Used with lists that are divided into sections - virtual float GetElementInSectionHeight([[maybe_unused]] int sectionIndex, [[maybe_unused]] int elementindex) { return 0.0f; } - - //! Returns the width of a header at the specified section. - //! Called when a horizontal list contains headers of varying size, and the header's "auto calculate size" option is disabled. - //! Used with lists that are divided into sections - virtual float GetSectionHeaderWidth([[maybe_unused]] int sectionIndex) { return 0.0f; } - - //! Returns the height of a header at the specified section. - //! Called when a vertical list contains elements of varying size, and the header's "auto calculate size" option is disabled. - //! Used with lists that are divided into sections - virtual float GetSectionHeaderHeight([[maybe_unused]] int sectionIndex) { return 0.0f; } - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiDynamicScrollBoxDataInterface> UiDynamicScrollBoxDataBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that listeners need to implement to receive notifications of element state -//! changes, such as when an element is about to scroll into view -class UiDynamicScrollBoxElementNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiDynamicScrollBoxElementNotifications(){} - - //! Called when an element is about to become visible. Used to populate the element with data for display. - //! Used with lists that are not divided into sections - virtual void OnElementBecomingVisible([[maybe_unused]] AZ::EntityId entityId, [[maybe_unused]] int index) {} - - //! Called when elements have variable sizes and are set to auto calculate. - //! Used with lists that are not divided into sections - virtual void OnPrepareElementForSizeCalculation([[maybe_unused]] AZ::EntityId entityId, [[maybe_unused]] int index) {} - - //! Called when an element in a section is about to become visible. Used to populate the element with data for display - //! Used with lists that are divided into sections - virtual void OnElementInSectionBecomingVisible([[maybe_unused]] AZ::EntityId entityId, [[maybe_unused]] int sectionIndex, [[maybe_unused]] int index) {} - - //! Called when elements in sections have variable sizes and are set to auto calculate - //! Used with lists that are divided into sections - virtual void OnPrepareElementInSectionForSizeCalculation([[maybe_unused]] AZ::EntityId entityId, [[maybe_unused]] int sectionIndex, [[maybe_unused]] int index) {} - - //! Called when a header is about to become visible. Used to populate the header with data for display. - //! Used with lists that are divided into sections - virtual void OnSectionHeaderBecomingVisible([[maybe_unused]] AZ::EntityId entityId, [[maybe_unused]] int sectionIndex) {} - - //! Called when headers have variable sizes and are set to auto calculate. - //! Used with lists that are divided into sections - virtual void OnPrepareSectionHeaderForSizeCalculation([[maybe_unused]] AZ::EntityId entityId, [[maybe_unused]] int sectionIndex) {} -}; - -typedef AZ::EBus<UiDynamicScrollBoxElementNotifications> UiDynamicScrollBoxElementNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiEditorBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiEditorBus.h deleted file mode 100644 index ebac70479f..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiEditorBus.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiEditorInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiEditorInterface() {} - - //! Test if this entity should be visible in the Ui Canvas Editor - virtual bool GetIsVisible() = 0; - - //! Set whether this entity should be visible in the Ui Canvas Editor - virtual void SetIsVisible(bool isVisible) = 0; - - //! Test if this entity is selectable in the UI Canvas Editor - virtual bool GetIsSelectable() = 0; - - //! Set whether this entity is selectable in the UI Canvas Editor - virtual void SetIsSelectable(bool isSelectable) = 0; - - //! Test if this entity is currently selected in the UI Canvas Editor - virtual bool GetIsSelected() = 0; - - //! Set whether this entity is currently selected in the UI Canvas Editor - virtual void SetIsSelected(bool isSelected) = 0; - - //! Test if this entity is currently expanded in the UI Canvas Editor - virtual bool GetIsExpanded() = 0; - - //! Set whether this entity is currently expanded in the UI Canvas Editor - virtual void SetIsExpanded(bool isExpanded) = 0; - - //! Test if all the parents of this UI element are visible in the editor - virtual bool AreAllAncestorsVisible() = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiEditorInterface> UiEditorBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiEditorCanvasBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiEditorCanvasBus.h deleted file mode 100644 index a2e7dd0c2b..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiEditorCanvasBus.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiEditorCanvasInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiEditorCanvasInterface() {} - - //! Get the snap state. - virtual bool GetIsSnapEnabled() = 0; - - //! Set the snap state. - virtual void SetIsSnapEnabled(bool enabled) = 0; - - //! Get the translation distance to snap to - virtual float GetSnapDistance() = 0; - - //! Set the translation distance to snap to - virtual void SetSnapDistance(float distance) = 0; - - //! Get the degrees of rotation to snap to - virtual float GetSnapRotationDegrees() = 0; - - //! Set the degrees of rotation to snap to - virtual void SetSnapRotationDegrees(float degrees) = 0; - - //! Get the positions of the horizontal guide lines (along y-axis in canvas pixels) - virtual AZStd::vector<float> GetHorizontalGuidePositions() = 0; - - //! Add a horizontal guide line - virtual void AddHorizontalGuide(float position) = 0; - - //! Remove the horizontal guide line at the given index - virtual void RemoveHorizontalGuide(int index) = 0; - - //! Set the position of the horizontal guide line at the given index - virtual void SetHorizontalGuidePosition(int index, float position) = 0; - - //! Get the positions of the vertical guide lines (along x-axis in canvas pixels) - virtual AZStd::vector<float> GetVerticalGuidePositions() = 0; - - //! Add a vertical guide line - virtual void AddVerticalGuide(float position) = 0; - - //! Remove the vertical guide line at the given index - virtual void RemoveVerticalGuide(int index) = 0; - - //! Set the position of the vertical guide line at the given index - virtual void SetVerticalGuidePosition(int index, float position) = 0; - - //! Remove all of the guides - virtual void RemoveAllGuides() = 0; - - //! Get the color to draw the guide lines on this canvas - virtual AZ::Color GetGuideColor() = 0; - - //! Set the color to draw the guide lines on this canvas - virtual void SetGuideColor(const AZ::Color& color) = 0; - - //! Get whether the guides on this canvas are locked - virtual bool GetGuidesAreLocked() = 0; - - //! Set whether the guides on this canvas are locked - virtual void SetGuidesAreLocked(bool areLocked) = 0; - - //! Check the canvas for any orphaned elements. These are elements not referenced as a child by the canvas or any of its descendant elements. - virtual bool CheckForOrphanedElements() = 0; - - //! Recover any orphaned elements in the canvas by placing them under a special top-level element. - virtual void RecoverOrphanedElements() = 0; - - //! Remove any orphaned elements in the canvas. - virtual void RemoveOrphanedElements() = 0; - - //! Update the canvas from the UI Editor - //! \param deltaTime the amount of time in seconds since the last call to this function - //! \param isInGame, true if canvas being updated in preview mode, false if being updated in edit mode - virtual void UpdateCanvasInEditorViewport(float deltaTime, bool isInGame) = 0; - - //! Render the canvas in the UI Editor - //! \param isInGame, true if canvas being rendered in preview mode, false if being rendered in edit mode - //! \param viewportSize, this is the size of the viewport that the canvas is being rendered to - virtual void RenderCanvasInEditorViewport(bool isInGame, AZ::Vector2 viewportSize) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiEditorCanvasInterface> UiEditorCanvasBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiEditorChangeNotificationBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiEditorChangeNotificationBus.h deleted file mode 100644 index 35b97fc359..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiEditorChangeNotificationBus.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/EBus/EBus.h> -#include <AzCore/Component/EntityId.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiEditorChangeNotificationInterface - : public AZ::EBusTraits -{ -public: // member functions - - virtual ~UiEditorChangeNotificationInterface() {} - - //! Called when the transform properties in the UI editor need to be refreshed - virtual void OnEditorTransformPropertiesNeedRefresh() = 0; - - //! Forces a refresh of the entire properties tree in the UI Editor. - virtual void OnEditorPropertiesRefreshEntireTree() = 0; -}; - -typedef AZ::EBus<UiEditorChangeNotificationInterface> UiEditorChangeNotificationBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Notify components who store directories as properties when directory contents change. -class UiEditorRefreshDirectoryNotificationInterface - : public AZ::EBusTraits -{ -public: // member functions - - virtual ~UiEditorRefreshDirectoryNotificationInterface() {} - - //! Notify directory properties that they should refresh their contents - virtual void OnRefreshDirectory() = 0; -}; - -typedef AZ::EBus<UiEditorRefreshDirectoryNotificationInterface> UiEditorRefreshDirectoryNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiElementBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiElementBus.h deleted file mode 100644 index e1eac703aa..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiElementBus.h +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> -#include <LyShine/UiBase.h> - -namespace LyShine -{ - class IRenderGraph; -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiElementInterface - : public AZ::ComponentBus -{ -public: // member functions - - //! Deleting an element will remove it from its parent and delete its child elements and components - virtual ~UiElementInterface() {} - - //! Render the element and its child elements and components, this is done by adding primitives to the render graph - //! \param renderGraph, the render graph being added to - //! \param isInGame, true if element being rendered in game (or preview), false if being render in edit mode - virtual void RenderElement(LyShine::IRenderGraph* renderGraph, bool isInGame) = 0; - - //! Retrieves the identifier of this element. - virtual LyShine::ElementId GetElementId() = 0; - - //! Get the name of this element - virtual LyShine::NameType GetName() = 0; - - //! Get the canvas that contains this element (returns AZ::InvalidEntityId if element has no canvas) - virtual AZ::EntityId GetCanvasEntityId() = 0; - - //! Get the parent element of this element (returns nullptr if element has no parent) - virtual AZ::Entity* GetParent() = 0; - - //! Get the parent entity Id of this element (returns invalid Id if element has no parent) - virtual AZ::EntityId GetParentEntityId() = 0; - - //! Get the number child elements of this element - virtual int GetNumChildElements() = 0; - - //! Get the specified child element, index must be less than GetNumChildElements() - virtual AZ::Entity* GetChildElement(int index) = 0; - - //! Get the specified child entity Id, index must be less than GetNumChildElements() - virtual AZ::EntityId GetChildEntityId(int index) = 0; - - //! Get the specified child's UiElementInterface, index must be less than GetNumChildElements() - //! and the element must be fully initialized - virtual UiElementInterface* GetChildElementInterface(int index) = 0; - - //! Get the index of the specified child element - virtual int GetIndexOfChild(const AZ::Entity* child) = 0; - - //! Get the index of the specified child element - virtual int GetIndexOfChildByEntityId(AZ::EntityId childId) = 0; - - //! Get the child elements of this element - virtual LyShine::EntityArray GetChildElements() = 0; - - //! Get the child entity Ids of this element - virtual AZStd::vector<AZ::EntityId> GetChildEntityIds() = 0; - - //! Create a new element that is a child of this element, this element (the parent) has ownership of the child - //! The new entity will have a UiElementComponent added but will not yet be initialized or activated - virtual AZ::Entity* CreateChildElement(const LyShine::NameType& name) = 0; - - //! Destroy this element - virtual void DestroyElement() = 0; - - //! Queue up element for destruction at end of frame - virtual void DestroyElementOnFrameEnd() = 0; - - //! Re-parent this element to move it in the hierarchy - //! \param newParent New parent element. If null then the canvas is the parent - //! \param nextElement Element to insert this element before. If null element is put at end of child list - virtual void Reparent(AZ::Entity* newParent, AZ::Entity* insertBefore = nullptr) = 0; - - //! Re-parent this element to move it in the hierarchy - //! \param newParent New parent element. If InvalidEntityId then the canvas is the parent - //! \param nextElement Element to insert this element before. If InvalidEntityId then element is put at end of child list - virtual void ReparentByEntityId(AZ::EntityId newParent, AZ::EntityId insertBefore) = 0; - - //! Add this element as a child of the specified parent - //! \param newParent New parent element. If null then the canvas is the parent - //! \param index Child index where element is inserted. If -1 element is put at end of child list - virtual void AddToParentAtIndex(AZ::Entity* newParent, int index = -1) = 0; - - //! Remove this element from its parent - virtual void RemoveFromParent() = 0; - - //! Get the front-most child element whose bounds include the given point in canvas space - //! \return nullptr if no match - virtual AZ::Entity* FindFrontmostChildContainingPoint(AZ::Vector2 point, bool isInGame) = 0; - - //! Get all the children whose bounds intersect with the given rect in canvas space - //! \return Empty EntityArray if no match - virtual LyShine::EntityArray FindAllChildrenIntersectingRect(const AZ::Vector2& bound0, const AZ::Vector2& bound1, bool isInGame) = 0; - - //! Look for an entity with interactable component to handle an event at given point - virtual AZ::EntityId FindInteractableToHandleEvent(AZ::Vector2 point) = 0; - - //! Look for a parent (ancestor) entity with interactable component to handle dragging starting at given point - virtual AZ::EntityId FindParentInteractableSupportingDrag(AZ::Vector2 point) = 0; - - //! Return the first immediate child element with the given name or nullptr if no match - virtual AZ::Entity* FindChildByName(const LyShine::NameType& name) = 0; - - //! Return the first descendant element with the given name or nullptr if no match - virtual AZ::Entity* FindDescendantByName(const LyShine::NameType& name) = 0; - - //! Return the first immediate child entity Id with the given name or invalid Id if no match - virtual AZ::EntityId FindChildEntityIdByName(const LyShine::NameType& name) = 0; - - //! Return the first descendant entity Id with the given name or invalid Id if no match - virtual AZ::EntityId FindDescendantEntityIdByName(const LyShine::NameType& name) = 0; - - //! Return the first immediate child element with the given id or nullptr if no match - virtual AZ::Entity* FindChildByEntityId(AZ::EntityId id) = 0; - - //! Return the descendant element with the given id or nullptr if no match - virtual AZ::Entity* FindDescendantById(LyShine::ElementId id) = 0; - - //! recursively find descendant elements matching a predicate - //! \param result, any matching elements will be added to this array - virtual void FindDescendantElements(AZStd::function<bool(const AZ::Entity*)> predicate, LyShine::EntityArray& result) = 0; - - //! recursively visit descendant elements and call the given function on them - //! The function is called first on the element and then on its children - virtual void CallOnDescendantElements(AZStd::function<void(const AZ::EntityId)> callFunction) = 0; - - //! Return whether a given element is an ancestor of this element - virtual bool IsAncestor(AZ::EntityId id) = 0; - - //! Enabled/disabled - virtual bool IsEnabled() = 0; - virtual void SetIsEnabled(bool isEnabled) = 0; - virtual bool GetAreElementAndAncestorsEnabled() = 0; - - //! This can be used to disable the render without disabling the update/interaction. - //! This is used internally by components that temporarily disable rendering of other elements (though they preserve the existing value). - virtual bool IsRenderEnabled() = 0; - virtual void SetIsRenderEnabled(bool isRenderEnabled) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiElementInterface> UiElementBus; - -// UI_ANIMATION_REVISIT This may be a temporary location - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiElementChangeNotification - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiElementChangeNotification() {} - - //! Notify listeners that a property has change on this entity - virtual void UiElementPropertyChanged() {} -}; - -typedef AZ::EBus<UiElementChangeNotification> UiElementChangeNotificationBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiElementNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiElementNotifications() {} - - //! Notify listeners that the element is being destroyed - virtual void OnUiElementBeingDestroyed() {} - - //! Notify listeners that the element has been fixed up (canvas and parent for the element have been set) - virtual void OnUiElementFixup(AZ::EntityId /*canvasEntityId*/, AZ::EntityId /*parentEntityId*/) {} - - //! Notify listeners that the element has been enabled or disabled (the flag on this element was changed) - virtual void OnUiElementEnabledChanged(bool /*isEnabled*/) {} - - //! Notify listeners that the element has been enabled or disabled either directly or to a change to an ancestors enabled flag - virtual void OnUiElementAndAncestorsEnabledChanged(bool /*areElementAndAncestorsEnabled*/) {} -}; - -typedef AZ::EBus<UiElementNotifications> UiElementNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiEntityContextBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiEntityContextBus.h deleted file mode 100644 index 91dc64ed3e..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiEntityContextBus.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/EBus/EBus.h> -#include <AzCore/Math/Uuid.h> -#include <AzCore/Asset/AssetCommon.h> -#include <AzCore/Serialization/ObjectStream.h> -#include <AzCore/Slice/SliceComponent.h> -#include <AzCore/Math/Vector3.h> -#include <AzFramework/Entity/EntityContextBus.h> -#include <AzFramework/Entity/EntityContext.h> - -// Forward declarations -namespace AZ -{ - class Entity; -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Bus for making requests to the UI entity context. -//! There is one UiEntityContext per UI canvas. -class UiEntityContextRequests - : public AZ::EBusTraits -{ -public: - - virtual ~UiEntityContextRequests() {} - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides. Accessed by EntityContextId - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - typedef AzFramework::EntityContextId BusIdType; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - - //! Creates an entity in a UI context. - //! \return a new entity - virtual AZ::Entity* CreateUiEntity(const char* name) = 0; - - //! Registers an existing entity with a UI context. - virtual void AddUiEntity(AZ::Entity* entity) = 0; - - //! Registers an existing set of entities with a UI context. - virtual void AddUiEntities(const AzFramework::EntityList& entities) = 0; - - //! Destroys an entity in a UI context. - //! \return whether or not the entity was destroyed. A false return value signifies the entity did not belong to the UI context. - virtual bool DestroyUiEntity(AZ::EntityId entityId) = 0; - - //! Clones a set of entities. - //! \param sourceEntities - the source set of entities to clone - //! \param resultEntities - the set of entities cloned from the source - virtual bool CloneUiEntities(const AZStd::vector<AZ::EntityId>& sourceEntities, AzFramework::EntityList& resultEntities) = 0; - -}; - -using UiEntityContextRequestBus = AZ::EBus<UiEntityContextRequests>; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Bus for receiving events/notifications from the UI entity context -class UiEntityContextNotification - : public AZ::EBusTraits -{ -public: - - virtual ~UiEntityContextNotification() {}; - - //! Fired when the context is being reset. - virtual void OnContextReset() {} - - //! Fired when a slice has been successfully instantiated. - virtual void OnSliceInstantiated(const AZ::Data::AssetId& /*sliceAssetId*/, const AZ::SliceComponent::SliceInstanceAddress& /*sliceAddress*/, const AzFramework::SliceInstantiationTicket& /*ticket*/) {} - - //! Fired when a slice has failed to instantiate. - virtual void OnSliceInstantiationFailed(const AZ::Data::AssetId& /*sliceAssetId*/, const AzFramework::SliceInstantiationTicket& /*ticket*/) {} - - //! Fired when the entity stream has been successfully loaded. - virtual void OnEntityStreamLoadSuccess() {} - - //! Fired when the entity stream load has failed - virtual void OnEntityStreamLoadFailed() {} -}; - -using UiEntityContextNotificationBus = AZ::EBus<UiEntityContextNotification>; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiFaderBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiFaderBus.h deleted file mode 100644 index 6c03254571..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiFaderBus.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Color.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiFaderInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiFaderInterface() {} - - //! Get the fade value. This is a float between 0 and 1. 1 means no fade. 0 means complete fade to invisible. - virtual float GetFadeValue() = 0; - - //! Set the fade value - virtual void SetFadeValue(float fade) = 0; - - //! Trigger a fade animation. - //! \param targetValue The value to end the fade at [0,1] - //! \param speed Speed measured in full fade amount per second; 0 means instant - //! \param listener The listener to notify when the fade is completed or interrupted - virtual void Fade(float targetValue, float speed) = 0; - - //! Get whether a fade animation is taking place - virtual bool IsFading() = 0; - - //! Get the flag that indicates whether the fader should use render to texture - virtual bool GetUseRenderToTexture() = 0; - - //! Set the flag that indicates whether the fader should use render to texture - virtual void SetUseRenderToTexture(bool useRenderToTexture) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiFaderInterface> UiFaderBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that listeners need to implement -class UiFaderNotifications - : public AZ::ComponentBus -{ -public: - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const bool EnableEventQueue = true; - ////////////////////////////////////////////////////////////////////////// - -public: // member functions - - virtual ~UiFaderNotifications(){} - - //! Called when the animation triggered by UiFaderInterface::Fade() is done. - //! The listener is automatically removed from the fader component after this is called. - virtual void OnFadeComplete() = 0; - - //! Called when the animation triggered by UiFaderInterface::Fade() is interrupted. - //! The listener is automatically removed from the fader component after this is called. - virtual void OnFadeInterrupted() = 0; - - //! Called when the fader component is destroyed - virtual void OnFaderDestroyed() = 0; -}; - -typedef AZ::EBus<UiFaderNotifications> UiFaderNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiFlipbookAnimationBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiFlipbookAnimationBus.h deleted file mode 100644 index 54602dc3f2..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiFlipbookAnimationBus.h +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> -#include <AzFramework/Entity/EntityContextBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Bus that defines the interface for flipbook animations. -//! -//! A flipbook animation component exists on an entity that has an image component -//! and interacts with the image bus to achieve its functionality (such as by -//! manipulating sprite-sheet indices). -class UiFlipbookAnimationInterface - : public AZ::ComponentBus -{ -public: // Types - - //! Defines the looping behavior when playing back a flipbook animation. - enum class LoopType - { - None, //!< No looping behavior - - Linear, //!< When end frame is reached, next frame will be the loop start frame - - PingPong //!< When end frame is reached, next frame will be the previous frame, - //!< continuing in reverse until the start frame is reached. - }; - - //! Units of speed for framerate - enum class FramerateUnits - { - FPS, //!< Framerate of animation - - SecondsPerFrame, //!< Number of seconds to wait before playing next frame - }; - -public: - virtual ~UiFlipbookAnimationInterface() {} - - //! Start the animation sequence, beginning at the start frame. - //! - //! If a LoopType other than None has been set, the animation won't stop - //! unless explicitly done so (or the image is unloaded/destroyed). - virtual void Start() = 0; - - //! Stops animation playback. - virtual void Stop() = 0; - - //! \return True if the flipbook animation is currently playing, false otherwise. - virtual bool IsPlaying() = 0; - - //! \return The starting frame of the animation. - virtual AZ::u32 GetStartFrame() = 0; - - //! Sets the starting frame of the animation. - virtual void SetStartFrame(AZ::u32 startFrame) = 0; - - //! \return End frame of the animation. - virtual AZ::u32 GetEndFrame() = 0; - - //! Sets the ending frame of the animation. - virtual void SetEndFrame(AZ::u32 endFrame) = 0; - - //! \return The current frame of the animation that's being rendered. - virtual AZ::u32 GetCurrentFrame() = 0; - - //! Sets the current frame of the animation to render. - //! - //! If the animation is currently playing, this will effectively "skip" - //! to the given frame. - virtual void SetCurrentFrame(AZ::u32 currentFrame) = 0; - - //! This frame is distinct from the start frame and allows a "lead in" - //! seqence of frames to play leading up to the looping animation. The - //! frames that occur prior to the loop start frame will only play once. - //! - //! \return The frame to start the loop from. - virtual AZ::u32 GetLoopStartFrame() = 0; - - //! Sets the starting frame for looping sequences. - virtual void SetLoopStartFrame(AZ::u32 loopStartFrame) = 0; - - //! \return The LoopType of the flipbook animation. - virtual LoopType GetLoopType() = 0; - - //! Sets the LoopType of the flipbook animation. - virtual void SetLoopType(LoopType loopType) = 0; - - //! Gets the speed used to determine when to transition to the next frame. - //! - //! Framerate is defined relative to unit of time, specified by FramerateUnits. - //! - //! See GetFramerateUnit, SetFramerateUnit. - virtual float GetFramerate() = 0; - - //! Sets the speed used to determine when to transition to the next frame. - //! - //! Framerate is defined relative to unit of time, specified by FramerateUnits. - //! - //! See GetFramerateUnit, SetFramerateUnit. - virtual void SetFramerate(float framerate) = 0; - - //! Gets the framerate unit. - virtual FramerateUnits GetFramerateUnit() = 0; - - //! Sets the framerate unit. - virtual void SetFramerateUnit(FramerateUnits framerateUnit) = 0; - - //! Gets the delay (in seconds) before playing the flipbook (applied only once during playback). - virtual float GetStartDelay() = 0; - - //! Sets the delay (in seconds) before playing the flipbook (applied only once during playback). - virtual void SetStartDelay(float startDelay) = 0; - - //! Gets the delay (in seconds) before playing the loop sequence. - virtual float GetLoopDelay() = 0; - - //! Sets the delay (in seconds) before playing the loop sequence. - virtual void SetLoopDelay(float loopDelay) = 0; - - //! Gets the delay (in seconds) before playing the reverse loop sequence (PingPong loop types only). - virtual float GetReverseDelay() = 0; - - //! Sets the delay (in seconds) before playing the reverse loop sequence (PingPong loop types only). - virtual void SetReverseDelay(float reverseDelay) = 0; - - //! Returns true if the animation will begin playing when the component activates, false otherwise. - virtual bool GetIsAutoPlay() = 0; - - //! Sets whether the animation will automatically begin playing. - //! - //! This flag is ignored after the component has activated. - virtual void SetIsAutoPlay(bool isAutoPlay) = 0; -}; - -using UiFlipbookAnimationBus = AZ::EBus<UiFlipbookAnimationInterface>; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Allows listeners to be aware of events, like loop completion, occurring. -class UiFlipbookAnimationNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiFlipbookAnimationNotifications() {} - - //! Notify listeners when the animation starts - virtual void OnAnimationStarted() {} - - //! Notify listeners when the animation stops - virtual void OnAnimationStopped() {} - - //! Notify listeners when the current loop sequence has completed - //! - //! This will only trigger for LoopType sequences other than None. - //! - //! For Linear LoopType, this will trigger on the last frame of the last - //! frame of the loop. - //! - //! For PingPong LoopType, this will trigger on the last frame of the - //! loop sequence before reversing the loop direction. - virtual void OnLoopSequenceCompleted() {} -}; - -typedef AZ::EBus<UiFlipbookAnimationNotifications> UiFlipbookAnimationNotificationsBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiGameEntityContextBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiGameEntityContextBus.h deleted file mode 100644 index d2118361ae..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiGameEntityContextBus.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/EBus/EBus.h> -#include <AzCore/Math/Uuid.h> -#include <AzCore/Asset/AssetCommon.h> -#include <AzCore/Serialization/ObjectStream.h> -#include <AzCore/Serialization/IdUtils.h> -#include <AzCore/Slice/SliceComponent.h> -#include <AzCore/Math/Vector2.h> -#include <AzFramework/Entity/EntityContextBus.h> -#include <AzFramework/Entity/EntityContext.h> - -// Forward declarations -namespace AZ -{ - class Entity; -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Bus for making requests to the UI game entity context. -class UiGameEntityContextRequests - : public AZ::EBusTraits -{ -public: - - virtual ~UiGameEntityContextRequests() {} - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides. Accessed by EntityContextId - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - typedef AzFramework::EntityContextId BusIdType; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - - //! Instantiates a dynamic slice asynchronously. - //! \return a ticket identifying the spawn request. - //! Callers can immediately subscribe to the SliceInstantiationResultBus for this ticket - //! to receive result for this specific request. - virtual AzFramework::SliceInstantiationTicket InstantiateDynamicSlice( - const AZ::Data::Asset<AZ::Data::AssetData>& /*sliceAsset*/, - const AZ::Vector2& /*position*/, - bool /*isViewportPosition*/, - AZ::Entity* /*parent*/, - const AZ::IdUtils::Remapper<AZ::EntityId>::IdMapper& /*customIdMapper*/) - { return AzFramework::SliceInstantiationTicket(); } -}; - -using UiGameEntityContextBus = AZ::EBus<UiGameEntityContextRequests>; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Bus for receiving notifications from the UI game entity context component. -class UiGameEntityContextNotifications - : public AZ::EBusTraits -{ -public: - - virtual ~UiGameEntityContextNotifications() = default; - - /// Fired when a slice has been successfully instantiated. - virtual void OnSliceInstantiated(const AZ::Data::AssetId& /*sliceAssetId*/, - const AZ::SliceComponent::SliceInstanceAddress& /*instance*/, - const AzFramework::SliceInstantiationTicket& /*ticket*/) {} - - /// Fired when a slice asset could not be instantiated. - virtual void OnSliceInstantiationFailed(const AZ::Data::AssetId& /*sliceAssetId*/, - const AzFramework::SliceInstantiationTicket& /*ticket*/) {} -}; - -using UiGameEntityContextNotificationBus = AZ::EBus<UiGameEntityContextNotifications>; - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Bus for receiving notifications from the UI game entity context component. This bus is used -//! by the UiSpawnerComponent that depends on the UiGameEntityContext fixing entities up before -//! it sends out notifications to listeners on the UiSpawnerNotificationBus -class UiGameEntityContextSliceInstantiationResults - : public AZ::EBusTraits -{ -public: - - virtual ~UiGameEntityContextSliceInstantiationResults() = default; - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides. Addressed by SliceInstantiationTicket - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - typedef AzFramework::SliceInstantiationTicket BusIdType; - ////////////////////////////////////////////////////////////////////////// - - //! Signals that a slice was successfully instantiated prior to entity registration. - virtual void OnEntityContextSlicePreInstantiate(const AZ::Data::AssetId& /*sliceAssetId*/, const AZ::SliceComponent::SliceInstanceAddress& /*sliceAddress*/) {} - - //! Signals that a slice was successfully instantiated after entity registration. - virtual void OnEntityContextSliceInstantiated(const AZ::Data::AssetId& /*sliceAssetId*/, const AZ::SliceComponent::SliceInstanceAddress& /*sliceAddress*/) {} - - //! Signals that a slice could not be instantiated. - virtual void OnEntityContextSliceInstantiationFailed(const AZ::Data::AssetId& /*sliceAssetId*/) {} -}; - -using UiGameEntityContextSliceInstantiationResultsBus = AZ::EBus<UiGameEntityContextSliceInstantiationResults>; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiImageBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiImageBus.h deleted file mode 100644 index 5167978509..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiImageBus.h +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Color.h> - -class ISprite; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiImageInterface - : public AZ::ComponentBus -{ -public: // types - - enum class ImageType : int32_t - { - Stretched, //!< the texture is stretched to fit the rect without maintaining aspect ratio - Sliced, //!< the texture is sliced such that center stretches and the edges do not - Fixed, //!< the texture is not stretched at all - Tiled, //!< the texture is tiled (repeated) - StretchedToFit, //!< the texture is scaled to fit the rect while maintaining aspect ratio - StretchedToFill //!< the texture is scaled to fill the rect while maintaining aspect ratio - }; - - enum class SpriteType : int32_t - { - SpriteAsset, - RenderTarget, - }; - - enum class FillType : int32_t - { - None, //!< the image is displayed fully filled - Linear, //!< the image is filled linearly from one edge to the opposing edge - Radial, //!< the image is filled radially around the center - RadialCorner, //!< the image is filled radially around a corner - RadialEdge, //!< the image is filled radially around the midpoint of an edge - }; - - enum class FillCornerOrigin : int32_t - { - TopLeft, - TopRight, - BottomRight, - BottomLeft, - }; - - enum class FillEdgeOrigin : int32_t - { - Left, - Top, - Right, - Bottom, - }; - -public: // member functions - - virtual ~UiImageInterface() {} - - //! Gets the image color tint - virtual AZ::Color GetColor() = 0; - - //! Sets the image color tint - virtual void SetColor(const AZ::Color& color) = 0; - - //! Gets the image color alpha - virtual float GetAlpha() = 0; - - //! Sets the image color alpha - virtual void SetAlpha(float color) = 0; - - //! Gets the sprite for this element - virtual ISprite* GetSprite() = 0; - - //! Sets the sprite for this element - virtual void SetSprite(ISprite* sprite) = 0; - - //! Gets the source location of the image to be displayed by the element - virtual AZStd::string GetSpritePathname() = 0; - - //! Sets the source location of the image to be displayed by the element - virtual void SetSpritePathname(AZStd::string spritePath) = 0; - - //! Sets the source location of the image to be displayed by the element only - //! if the sprite asset exists. Otherwise, the current sprite remains unchanged. - //! Returns whether the sprite changed - virtual bool SetSpritePathnameIfExists(AZStd::string spritePath) = 0; - - //! Gets the name of the render target - virtual AZStd::string GetRenderTargetName() = 0; - - //! Sets the name of the render target - virtual void SetRenderTargetName(AZStd::string renderTargetName) = 0; - - //! Gets whether the render target is in sRGB color space - virtual bool GetIsRenderTargetSRGB() = 0; - - //! Sets whether the render target is in sRGB color space - virtual void SetIsRenderTargetSRGB(bool isSRGB) = 0; - - //! Gets the type of the sprite - virtual SpriteType GetSpriteType() = 0; - - //! Sets the type of the sprite - virtual void SetSpriteType(SpriteType spriteType) = 0; - - //! Gets the type of the image - virtual ImageType GetImageType() = 0; - - //! Sets the type of the image - virtual void SetImageType(ImageType imageType) = 0; - - //! Gets the fill type for the image - virtual FillType GetFillType() = 0; - - //! Sets the fill type for the image - virtual void SetFillType(FillType fillType) = 0; - - //! Gets the fill amount for the image in the range [0,1] - virtual float GetFillAmount() = 0; - - //! Sets the fill amount for the image in the range [0,1] - virtual void SetFillAmount(float fillAmount) = 0; - - //! Gets the start angle for radial fill, measured clockwise in degrees from straight up - virtual float GetRadialFillStartAngle() = 0; - - //! Sets the start angle for radial fill, measured clockwise in degrees from straight up - virtual void SetRadialFillStartAngle(float radialFillStartAngle) = 0; - - //! Gets the corner fill origin - virtual FillCornerOrigin GetCornerFillOrigin() = 0; - - //! Sets the corner fill origin - virtual void SetCornerFillOrigin(FillCornerOrigin cornerOrigin) = 0; - - //! Gets the edge fill origin - virtual FillEdgeOrigin GetEdgeFillOrigin() = 0; - - //! Sets the edge fill origin - virtual void SetEdgeFillOrigin(FillEdgeOrigin edgeOrigin) = 0; - - //! Gets whether the image is filled clockwise - virtual bool GetFillClockwise() = 0; - - //! Sets whether the image is filled clockwise - virtual void SetFillClockwise(bool fillClockwise) = 0; - - //! Gets whether the center of a sliced image is filled - virtual bool GetFillCenter() = 0; - - //! Sets whether the center of a sliced image is filled - virtual void SetFillCenter(bool fillCenter) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiImageInterface> UiImageBus; - diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiImageSequenceBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiImageSequenceBus.h deleted file mode 100644 index 76c7a81495..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiImageSequenceBus.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiImageSequenceInterface - : public AZ::ComponentBus -{ -public: // types - - enum class ImageType : int32_t - { - Stretched, //!< the texture is stretched to fit the rect without maintaining aspect ratio - Fixed, //!< the texture is not stretched at all - StretchedToFit, //!< the texture is scaled to fit the rect while maintaining aspect ratio - StretchedToFill //!< the texture is scaled to fill the rect while maintaining aspect ratio - }; - -public: // member functions - - virtual ~UiImageSequenceInterface() {} - - //! Gets the type of the image - virtual ImageType GetImageType() = 0; - - //! Sets the type of the image - virtual void SetImageType(ImageType imageType) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiImageSequenceInterface> UiImageSequenceBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiIndexableImageBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiIndexableImageBus.h deleted file mode 100644 index c9b67aaab4..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiIndexableImageBus.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Defines an interface for working with indexable image types, such as sprite-sheets or image sequences. -class UiIndexableImageInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiIndexableImageInterface() {} - - //! Sets the index of the image to display - virtual void SetImageIndex(AZ::u32 index) = 0; - - //! Gets the index of the image to display - virtual const AZ::u32 GetImageIndex() = 0; - - //! Gets the number of indices for this image. - virtual const AZ::u32 GetImageIndexCount() = 0; - - //! Given an index, return its alias (if defined) - virtual AZStd::string GetImageIndexAlias(AZ::u32 index) = 0; - - //! Given an index, set an alias for it - virtual void SetImageIndexAlias(AZ::u32 index, const AZStd::string& alias) = 0; - - //! Given an alias, return the index that corresponds to it - virtual AZ::u32 GetImageIndexFromAlias(const AZStd::string& alias) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiIndexableImageInterface> UiIndexableImageBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiInitializationBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiInitializationBus.h deleted file mode 100644 index f0d6d95cc1..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiInitializationBus.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiInitializationInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiInitializationInterface() {} - - //! Initialize the component after it has been created as part of a set of entities. - //! I.e. After a group of entities has been created and activated from a load or clone operation - //! in the game (not in the UI Editor) this is called on each created element. - //! This allows the component to perform operations that rely on related entities being - //! activated. - virtual void InGamePostActivate() = 0; - -public: // static member functions - - static const char* GetUniqueName() { return "UiInitializationInterface"; } - -public: // static member data - - //! Multiple components on an entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; -}; - -typedef AZ::EBus<UiInitializationInterface> UiInitializationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiInteractableActionsBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiInteractableActionsBus.h deleted file mode 100644 index a67a6b74b9..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiInteractableActionsBus.h +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -// This bus allows the get/set of properties for a group of actions that many interactable components -// implement. -// It is separate from UiInteractableBus because UiInteractableBus is part of a core system for how -// the UI canvas communincates with any UI element that wants user input. Sometimes UI components -// want input because they are part of a 2D puzzle for example but they do not always want to have -// to support the standard action changes. -class UiInteractableActionsInterface - : public AZ::ComponentBus -{ -public: // types - - typedef AZStd::function<void(AZ::EntityId)> OnActionCallback; - -public: // member functions - - virtual ~UiInteractableActionsInterface() {} - - //! Get the hover start action name - virtual const LyShine::ActionName& GetHoverStartActionName() = 0; - - //! Set the hover start action name - virtual void SetHoverStartActionName(const LyShine::ActionName& actionName) = 0; - - //! Get the hover end action name - virtual const LyShine::ActionName& GetHoverEndActionName() = 0; - - //! Set the hover end action name - virtual void SetHoverEndActionName(const LyShine::ActionName& actionName) = 0; - - //! Get the pressed action name - virtual const LyShine::ActionName& GetPressedActionName() = 0; - - //! Set the pressed action name - virtual void SetPressedActionName(const LyShine::ActionName& actionName) = 0; - - //! Get the released action name - virtual const LyShine::ActionName& GetReleasedActionName() = 0; - - //! Set the released action name - virtual void SetReleasedActionName(const LyShine::ActionName& actionName) = 0; - - //! Get the hover start callback - virtual OnActionCallback GetHoverStartActionCallback() = 0; - - //! Set the hover start callback - virtual void SetHoverStartActionCallback(OnActionCallback onActionCallback) = 0; - - //! Get the hover end callback - virtual OnActionCallback GetHoverEndActionCallback() = 0; - - //! Set the hover end callback - virtual void SetHoverEndActionCallback(OnActionCallback onActionCallback) = 0; - - //! Get the pressed callback - virtual OnActionCallback GetPressedActionCallback() = 0; - - //! Set the pressed callback - virtual void SetPressedActionCallback(OnActionCallback onActionCallback) = 0; - - //! Get the release callback - virtual OnActionCallback GetReleasedActionCallback() = 0; - - //! Set the release callback - virtual void SetReleasedActionCallback(OnActionCallback onActionCallback) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiInteractableActionsInterface> UiInteractableActionsBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiInteractableBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiInteractableBus.h deleted file mode 100644 index 4ad4551657..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiInteractableBus.h +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> -#include <AzFramework/Input/Channels/InputChannelDigitalWithSharedModifierKeyStates.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiInteractableInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiInteractableInterface() {} - - //! Check whether this component can handle the event at the given location - virtual bool CanHandleEvent(AZ::Vector2 point) = 0; - - //! Called on an interactable component when a pressed event is received over it - //! \param point, the point at which the event occurred (viewport space) - //! \param shouldStayActive, output - true if the interactable wants to become the active element for the canvas - //! \return true if the interactable handled the event - virtual bool HandlePressed(AZ::Vector2 point, bool& shouldStayActive) = 0; - - //! Called on the currently pressed interactable component when a release event is received - //! \param point, the point at which the event occurred (viewport space) - //! \return true if the interactable handled the event - virtual bool HandleReleased(AZ::Vector2 point) = 0; - - //! Called on an interactable component when a multi-touch pressed event is received over it - //! \param point, the point at which the event occurred (viewport space) - //! \param multiTouchIndex, the index of the multi-touch (the 'primary' touch with index 0 is sent to HandlePressed) - //! \return true if the interactable handled the event - virtual bool HandleMultiTouchPressed(AZ::Vector2 point, int multiTouchIndex) = 0; - - //! Called on the currently pressed interactable component when a multi-touch release event is received - //! \param point, the point at which the event occurred (viewport space) - //! \param multiTouchIndex, the index of the multi-touch (the 'primary' touch with index 0 is sent to HandlePressed) - //! \return true if the interactable handled the event - virtual bool HandleMultiTouchReleased(AZ::Vector2 point, int multiTouchIndex) = 0; - - //! Called on an interactable component when an enter pressed event is received - //! \param shouldStayActive, output - true if the interactable wants to become the active element for the canvas - //! \return true if the interactable handled the event - virtual bool HandleEnterPressed([[maybe_unused]] bool& shouldStayActive) { return false; } - - //! Called on the currently pressed interactable component when an enter released event is received - //! \return true if the interactable handled the event - virtual bool HandleEnterReleased() { return false; } - - //! Called when the interactable was navigated to via gamepad/keyboard, and auto activation is enabled on the interactable - //! \return true if the interactable handled the event - virtual bool HandleAutoActivation() { return false; } - - //! Called on the currently active interactable component when text input is received - //! \return true if the interactable handled the event - virtual bool HandleTextInput([[maybe_unused]] const AZStd::string& textUTF8) { return false; }; - - //! Called on the currently active interactable component when input is received - //! \return true if the interactable handled the event - virtual bool HandleKeyInputBegan([[maybe_unused]] const AzFramework::InputChannel::Snapshot& inputSnapshot, [[maybe_unused]] AzFramework::ModifierKeyMask activeModifierKeys) { return false; } - - //! Called on the currently active interactable component when a mouse/touch position event is received - //! \param point, the current mouse/touch position (viewport space) - virtual void InputPositionUpdate([[maybe_unused]] AZ::Vector2 point) {}; - - //! Called on the currently pressed interactable component when a multi-touch position event is received - //! \param point, the current mouse/touch position (viewport space) - //! \param multiTouchIndex, the index of the multi-touch (the 'primary' touch with index 0 is sent to HandlePressed) - virtual void MultiTouchPositionUpdate([[maybe_unused]] AZ::Vector2 point, [[maybe_unused]] int multiTouchIndex) {}; - - //! Returns true if this interactable supports taking active status when a drag is started on a child - //! interactble AND the given drag startPoint would be a valid drag start point - //! \param point, the start point of the drag (which would be on a child interactable) (viewport space) - virtual bool DoesSupportDragHandOff([[maybe_unused]] AZ::Vector2 startPoint) { return false; } - - //! Called on a parent of the currently active interactable element to allow interactables that - //! contain other interactables to support drags that start on the child. - //! If this return true the hand-off occured and the caller will no longer be considered the - //! active interactable by the canvas. - //! \param currentActiveInteractable, the child element that is the currently active interactable - //! \param startPoint, the start point of the potential drag (viewport space) - //! \param currentPoint, the current points of the potential drag (viewport space) - virtual bool OfferDragHandOff([[maybe_unused]] AZ::EntityId currentActiveInteractable, [[maybe_unused]] AZ::Vector2 startPoint, [[maybe_unused]] AZ::Vector2 currentPoint, [[maybe_unused]] float dragThreshold) { return false; }; - - //! Called on the currently active interactable component when the active interactable changes - virtual void LostActiveStatus() {}; - - //! Called when mouse/touch enters the bounds of this interactable - virtual void HandleHoverStart() = 0; - - //! Called on the currently hovered interactable component when mouse/touch moves outside of bounds - virtual void HandleHoverEnd() = 0; - - //! Called when a descendant of the interactable becomes the hover interactable by being navigated to - virtual void HandleDescendantReceivedHoverByNavigation([[maybe_unused]] AZ::EntityId descendantEntityId) {}; - - //! Called when the interactable becomes the hover interactable by being navigated to from one of its descendants - virtual void HandleReceivedHoverByNavigatingFromDescendant([[maybe_unused]] AZ::EntityId descendantEntityId) {}; - - //! Query whether the interactable is currently pressed - virtual bool IsPressed() { return false; } - - //! Enable/disable event handling - virtual bool IsHandlingEvents() { return true; } - virtual void SetIsHandlingEvents([[maybe_unused]] bool isHandlingEvents) {} - - //! Enable/disable multi-touch event handling - virtual bool IsHandlingMultiTouchEvents() { return true; } - virtual void SetIsHandlingMultiTouchEvents([[maybe_unused]] bool isHandlingMultiTouchEvents) {} - - //! Get/set whether the interactable automatically becomes active when navigated to via gamepad/keyboard - virtual bool GetIsAutoActivationEnabled() = 0; - virtual void SetIsAutoActivationEnabled(bool isEnabled) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiInteractableInterface> UiInteractableBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiInteractableActiveNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiInteractableActiveNotifications() {} - - //! Notify listener that this interactable is no longer active - virtual void ActiveCancelled() {} - - //! Notify listener that this interactable has given up active status to a new interactable - virtual void ActiveChanged([[maybe_unused]] AZ::EntityId m_newActiveInteractable, [[maybe_unused]] bool shouldStayActive) {} -}; - -typedef AZ::EBus<UiInteractableActiveNotifications> UiInteractableActiveNotificationBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that listeners need to implement in order to get notifications when actions are -//! triggered -class UiInteractableNotifications - : public AZ::ComponentBus -{ -public: - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const bool EnableEventQueue = true; - ////////////////////////////////////////////////////////////////////////// - -public: // member functions - - virtual ~UiInteractableNotifications(){} - - //! Called on hover start - virtual void OnHoverStart() {}; - - //! Called on hover end - virtual void OnHoverEnd() {}; - - //! Called on pressed - virtual void OnPressed() {}; - - //! Called on released - virtual void OnReleased() {}; - - //! Called on receiving hover by being navigated to from a descendant - virtual void OnReceivedHoverByNavigatingFromDescendant([[maybe_unused]] AZ::EntityId descendantEntityId) {}; -}; - -typedef AZ::EBus<UiInteractableNotifications> UiInteractableNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiInteractableStatesBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiInteractableStatesBus.h deleted file mode 100644 index e961d315ee..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiInteractableStatesBus.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/UiBase.h> -#include <AzCore/Math/Color.h> - -class ISprite; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -// This bus allows the get/set of properties for a group of states that many interactable components -// implement. -// It is separate from UiInteractableBus because UiInteractableBus is part of a core system for how -// the UI canvas communincates with any UI element that wants user input. Sometimes UI components -// want input because they are part of a 2D puzzle for example but they do not always want to have -// to support the standard state changes. -class UiInteractableStatesInterface - : public AZ::ComponentBus -{ -public: // types - - //! The different visual states that an interactable can be in. An enum class is avoided so that - //! derived components of UiInteractableComponent can extend with additional states. - using State = int; - enum - { - StateNormal = 0, - StateHover, - StatePressed, - StateDisabled, - NumStates - }; - -public: // member functions - - virtual ~UiInteractableStatesInterface() {} - - //! Set the color to be used for the given target when the interactable is in the given state - //! If the interactable already has a color action for this state/target combination then replaces it - virtual void SetStateColor(State state, AZ::EntityId target, const AZ::Color& color) = 0; - - //! Get the color to be used for the given target when the interactable is in the given state - //! \return the color to be used for the given target when the interactable is in the given state - virtual AZ::Color GetStateColor(State state, AZ::EntityId target) = 0; - - //! Get whether the interactable has a color action for this state/target combination - //! \return true if the interactable has a color action for this state/target combination - virtual bool HasStateColor(State state, AZ::EntityId target) = 0; - - //! Set the alpha to be used for the given target when the interactable is in the given state - //! If the interactable already has an alpha action for this state/target combination then replaces it - virtual void SetStateAlpha(State state, AZ::EntityId target, float alpha) = 0; - - //! Get the alpha to be used for the given target when the interactable is in the given state - //! \return the alpha to be used for the given target when the interactable is in the given state - virtual float GetStateAlpha(State state, AZ::EntityId target) = 0; - - //! Get whether the interactable has an alpha action for this state/target combination - //! \return true if the interactable has an alpha action for this state/target combination - virtual bool HasStateAlpha(State state, AZ::EntityId target) = 0; - - //! Set the sprite to be used for the given target when the interactable is in the given state - //! If the interactable already has a sprite action for this state/target combination then replaces it - virtual void SetStateSprite(State state, AZ::EntityId target, ISprite* sprite) = 0; - - //! Get the sprite to be used for the given target when the interactable is in the given state - //! \return the sprite to be used for the given target when the interactable is in the given state - virtual ISprite* GetStateSprite(State state, AZ::EntityId target) = 0; - - //! Set the sprite path to be used for the given target when the interactable is in the given state - //! If the interactable already has a sprite action for this state/target combination then replaces it - virtual void SetStateSpritePathname(State state, AZ::EntityId target, const AZStd::string& spritePath) = 0; - - //! Get the sprite path to be used for the given target when the interactable is in the given state - //! \return the sprite path to be used for the given target when the interactable is in the given state - virtual AZStd::string GetStateSpritePathname(State state, AZ::EntityId target) = 0; - - //! Get whether the interactable has a sprite action for this state/target combination - //! \return true if the interactable has a sprite action for this state/target combination - virtual bool HasStateSprite(State state, AZ::EntityId target) = 0; - - //! Set the font to be used for the given target when the interactable is in the given state - //! If the interactable already has a font action for this state/target combination then replaces it - virtual void SetStateFont(State state, AZ::EntityId target, const AZStd::string& fontPathname, unsigned int fontEffectIndex) = 0; - - //! Get the font path to be used for the given target when the interactable is in the given state - //! \return the font path to be used for the given target when the interactable is in the given state - virtual AZStd::string GetStateFontPathname(State state, AZ::EntityId target) = 0; - - //! Get the font effect to be used for the given target when the interactable is in the given state - //! \return the font effect to be used for the given target when the interactable is in the given state - virtual unsigned int GetStateFontEffectIndex(State state, AZ::EntityId target) = 0; - - //! Get whether the interactable has a font action for this state/target combination - //! \return true if the interactable has a font action for this state/target combination - virtual bool HasStateFont(State state, AZ::EntityId target) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiInteractableStatesInterface> UiInteractableStatesBus; - diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiInteractionMaskBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiInteractionMaskBus.h deleted file mode 100644 index 71c54527c6..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiInteractionMaskBus.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiInteractionMaskInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiInteractionMaskInterface() {} - - //! Check whether this element is masking the given point - virtual bool IsPointMasked(AZ::Vector2 point) = 0; - -public: // static member functions - - static const char* GetUniqueName() { return "UIInteractionMaskInterface"; } - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiInteractionMaskInterface> UiInteractionMaskBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutBus.h deleted file mode 100644 index 429d44bc24..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutBus.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> -#include <LyShine/Bus/UiTransformBus.h> -#include <LyShine/IDraw2d.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiLayoutInterface - : public AZ::ComponentBus -{ -public: // types - - //! Horizontal order used by layout components - enum class HorizontalOrder - { - LeftToRight, - RightToLeft - }; - - //! Vertical order used by layout components - enum class VerticalOrder - { - TopToBottom, - BottomToTop - }; - - //! Padding (in pixels) inside the edges of an element - struct Padding - { - AZ_TYPE_INFO(Padding, "{DE5C18B0-4214-4A37-B590-8D45CC450A96}") - - Padding() - : m_left(0) - , m_top(0) - , m_right(0) - , m_bottom(0) {} - - int m_left; - int m_right; - int m_top; - int m_bottom; - }; - -public: // member functions - - virtual ~UiLayoutInterface() {} - - //! Get whether this layout component uses layout cells to calculate its layout - virtual bool IsUsingLayoutCellsToCalculateLayout() = 0; - - //! Get whether this layout component should bypass the default layout cell values calculated by its children - virtual bool GetIgnoreDefaultLayoutCells() = 0; - - //! Set whether this layout component should bypass the default layout cell values calculated by its children - virtual void SetIgnoreDefaultLayoutCells(bool ignoreDefaultLayoutCells) = 0; - - //! Get the horizontal child alignment - virtual IDraw2d::HAlign GetHorizontalChildAlignment() = 0; - - //! Set the horizontal child alignment - virtual void SetHorizontalChildAlignment(IDraw2d::HAlign alignment) = 0; - - //! Get the vertical child alignment - virtual IDraw2d::VAlign GetVerticalChildAlignment() = 0; - - //! Set the vertical child alignment - virtual void SetVerticalChildAlignment(IDraw2d::VAlign alignment) = 0; - - //! Find out whether this layout component is currently overriding the transform of the specified element. - virtual bool IsControllingChild(AZ::EntityId childId) = 0; - - //! Get the size the element needs to be to fit a specified number of child elements of a certain size - virtual AZ::Vector2 GetSizeToFitChildElements(const AZ::Vector2& childElementSize, int numChildElements) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiLayoutInterface> UiLayoutBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutCellBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutCellBus.h deleted file mode 100644 index 2cf19d09c2..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutCellBus.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/UiLayoutCellBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiLayoutCellInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiLayoutCellInterface() {} - - //! Get the overridden min width. LyShine::UiLayoutCellUnspecifiedSize means it has not been overridden - virtual float GetMinWidth() = 0; - - //! Set the overridden min width. LyShine::UiLayoutCellUnspecifiedSize means don't override - virtual void SetMinWidth(float width) = 0; - - //! Get the overridden min height. LyShine::UiLayoutCellUnspecifiedSize means it has not been overridden - virtual float GetMinHeight() = 0; - - //! Set the overridden min height. LyShine::UiLayoutCellUnspecifiedSize means don't override - virtual void SetMinHeight(float height) = 0; - - //! Get the overridden target width. LyShine::UiLayoutCellUnspecifiedSize means it has not been overridden - virtual float GetTargetWidth() = 0; - - //! Set the overridden target width. LyShine::UiLayoutCellUnspecifiedSize means don't override - virtual void SetTargetWidth(float width) = 0; - - //! Get the overridden target height. LyShine::UiLayoutCellUnspecifiedSize means it has not been overridden - virtual float GetTargetHeight() = 0; - - //! Set the overridden target height. LyShine::UiLayoutCellUnspecifiedSize means don't override - virtual void SetTargetHeight(float height) = 0; - - //! Get the overridden max width. LyShine::UiLayoutCellUnspecifiedSize means it has not been overridden - virtual float GetMaxWidth() = 0; - - //! Set the overridden max width. LyShine::UiLayoutCellUnspecifiedSize means don't override - virtual void SetMaxWidth(float width) = 0; - - //! Get the overridden max height. LyShine::UiLayoutCellUnspecifiedSize means it has not been overridden - virtual float GetMaxHeight() = 0; - - //! Set the overridden max height. LyShine::UiLayoutCellUnspecifiedSize means don't override - virtual void SetMaxHeight(float height) = 0; - - //! Get the overridden extra width ratio. LyShine::UiLayoutCellUnspecifiedSize means it has not been overridden - virtual float GetExtraWidthRatio() = 0; - - //! Set the overridden extra width ratio. LyShine::UiLayoutCellUnspecifiedSize means don't override - virtual void SetExtraWidthRatio(float width) = 0; - - //! Get the overridden extra height ratio. LyShine::UiLayoutCellUnspecifiedSize means it has not been overridden - virtual float GetExtraHeightRatio() = 0; - - //! Set the overridden extra height ratio. LyShine::UiLayoutCellUnspecifiedSize means don't override - virtual void SetExtraHeightRatio(float height) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiLayoutCellInterface> UiLayoutCellBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutCellDefaultBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutCellDefaultBus.h deleted file mode 100644 index 9b0640b6e2..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutCellDefaultBus.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/UiLayoutCellBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiLayoutCellDefaultInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiLayoutCellDefaultInterface() {} - - //! Get the minimum width - virtual float GetMinWidth() = 0; - - //! Get the minimum height - virtual float GetMinHeight() = 0; - - //! Get the target width - //! \param maxWidth A width that the element will not surpass. LyShine::UiLayoutCellUnspecifiedSize means no max - virtual float GetTargetWidth(float maxWidth) = 0; - - //! Get the target height - //! \param maxHeight A height that the element will not surpass. LyShine::UiLayoutCellUnspecifiedSize means no max - virtual float GetTargetHeight(float maxHeight) = 0; - - //! Get the extra width ratio - virtual float GetExtraWidthRatio() = 0; - - //! Get the extra height ratio - virtual float GetExtraHeightRatio() = 0; - -public: // static member data - - //! Multiple components on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; -}; - -typedef AZ::EBus<UiLayoutCellDefaultInterface> UiLayoutCellDefaultBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutColumnBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutColumnBus.h deleted file mode 100644 index 0327cbbe04..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutColumnBus.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/Bus/UiLayoutBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiLayoutColumnInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiLayoutColumnInterface() {} - - //! Get the padding (in pixels) inside the edges of the element - virtual UiLayoutInterface::Padding GetPadding() = 0; - - //! Set the padding (in pixels) inside the edges of the element - virtual void SetPadding(UiLayoutInterface::Padding padding) = 0; - - //! Get the spacing (in pixels) between child elements - virtual float GetSpacing() = 0; - - //! Set the spacing (in pixels) between child elements - virtual void SetSpacing(float spacing) = 0; - - //! Get the vertical order for this layout - virtual UiLayoutInterface::VerticalOrder GetOrder() = 0; - - //! Set the vertical order for this layout - virtual void SetOrder(UiLayoutInterface::VerticalOrder order) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiLayoutColumnInterface> UiLayoutColumnBus; - diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutControllerBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutControllerBus.h deleted file mode 100644 index 02fa66d847..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutControllerBus.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! This interface can to be implemented by any component that wants to modify transform properties -//! of elements are runtime using the Layout system. The methods in this interface will be called -//! by the LayoutManager whenever the element is told to recompute its layout. Because an element -//! might have multiple components that implement this interface, the handlers will be sorted by -//! priority (lower priority number gets called earlier). -class UiLayoutControllerInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiLayoutControllerInterface() {} - - //! Set elements' width transform properties - virtual void ApplyLayoutWidth() = 0; - - //! Set elements' height transform properties - virtual void ApplyLayoutHeight() = 0; - -public: // static member data - - //! Events are ordered, each handler may set its priority - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::MultipleAndOrdered; - - //! Priority will be used for ordering, lower priority number means it gets called earlier - struct BusHandlerOrderCompare - { - AZ_FORCE_INLINE bool operator()(const UiLayoutControllerInterface* left, const UiLayoutControllerInterface* right) const { return left->GetPriority() < right->GetPriority(); } - }; - -protected: // member data - - static const unsigned int k_defaultPriority = 100; // Default is 100, make it lower to get called earlier, higher to get called later - virtual unsigned int GetPriority() const { return k_defaultPriority; } -}; - -typedef AZ::EBus<UiLayoutControllerInterface> UiLayoutControllerBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutFitterBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutFitterBus.h deleted file mode 100644 index a1eda7c30b..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutFitterBus.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! This component resizes its element to fit its content. It uses cell sizing information given to -//! it by other Layout components, Text component, or Image component (fixed type). -class UiLayoutFitterInterface - : public AZ::ComponentBus -{ -public: // types - - //! Fit type indicating enabled fits - enum class FitType - { - None, - HorizontalOnly, - VerticalOnly, - HorizontalAndVertical - }; - -public: // member functions - - virtual ~UiLayoutFitterInterface() {} - - //! Get whether to resize the element horizontally - virtual bool GetHorizontalFit() = 0; - - //! Set whether to resize the element horizontally - virtual void SetHorizontalFit(bool horizontalFit) = 0; - - //! Get whether to resize the element vertically - virtual bool GetVerticalFit() = 0; - - //! Set whether to resize the element vertically - virtual void SetVerticalFit(bool verticalFit) = 0; - - //! Get the fit type - virtual FitType GetFitType() = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiLayoutFitterInterface> UiLayoutFitterBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutGridBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutGridBus.h deleted file mode 100644 index 69d1ba7bd1..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutGridBus.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> -#include <LyShine/Bus/UiLayoutBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiLayoutGridInterface - : public AZ::ComponentBus -{ -public: // types - - //! Used to determine which direction to start the layout with - enum class StartingDirection - { - HorizontalOrder, - VerticalOrder - }; - -public: // member functions - - virtual ~UiLayoutGridInterface() {} - - //! Get the padding (in pixels) inside the edges of the element - virtual UiLayoutInterface::Padding GetPadding() = 0; - - //! Set the padding (in pixels) inside the edges of the element - virtual void SetPadding(UiLayoutInterface::Padding padding) = 0; - - //! Get the spacing (in pixels) between child elements - virtual AZ::Vector2 GetSpacing() = 0; - - //! Set the spacing (in pixels) between child elements - virtual void SetSpacing(AZ::Vector2 spacing) = 0; - - //! Get the size (in pixels) of a child element in this layout - virtual AZ::Vector2 GetCellSize() = 0; - - //! Set the size (in pixels) of a child element in this layout - virtual void SetCellSize(AZ::Vector2 size) = 0; - - //! Get the horizontal order for this layout - virtual UiLayoutInterface::HorizontalOrder GetHorizontalOrder() = 0; - - //! Set the horizontal order for this layout - virtual void SetHorizontalOrder(UiLayoutInterface::HorizontalOrder order) = 0; - - //! Get the vertical order for this layout - virtual UiLayoutInterface::VerticalOrder GetVerticalOrder() = 0; - - //! Set the vertical order for this layout - virtual void SetVerticalOrder(UiLayoutInterface::VerticalOrder order) = 0; - - //! Get the starting direction for this layout - virtual StartingDirection GetStartingDirection() = 0; - - //! Set the starting direction for this layout - virtual void SetStartingDirection(StartingDirection direction) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiLayoutGridInterface> UiLayoutGridBus; - diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutManagerBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutManagerBus.h deleted file mode 100644 index 836ae0d756..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutManagerBus.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiLayoutManagerInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiLayoutManagerInterface() {} - -public: // static member data - - //! Mark an element to recompute its layout. This is called when something that affects the layout - //! has been modified. (ex. layout element size changed, layout element property changed, layout - //! element child count changed.) - virtual void MarkToRecomputeLayout(AZ::EntityId entityId) = 0; - - //! Mark the specified element's parent to recompute its layout. The parent uses its child's layout - //! cell values to calculate its layout, so this is called when something that affects the - //! child's layout cell values has been modified. (ex. child's layout cell property changed.) - //! Since a child's layout cell values may affect its parent's layout cell values, the top level parent - //! is marked - virtual void MarkToRecomputeLayoutsAffectedByLayoutCellChange(AZ::EntityId entityId, bool isDefaultLayoutCell) = 0; - - //! Unmark all elements from needing to recompute their layouts - virtual void UnmarkAllLayouts() = 0; - - //! Recompute layouts of marked elements and clear the marked layout list - virtual void RecomputeMarkedLayouts() = 0; - - //! Compute the layout for the specified element and its descendants - virtual void ComputeLayoutForElementAndDescendants(AZ::EntityId entityId) = 0; - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiLayoutManagerInterface> UiLayoutManagerBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutRowBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutRowBus.h deleted file mode 100644 index 23db162b62..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiLayoutRowBus.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/Bus/UiLayoutBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiLayoutRowInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiLayoutRowInterface() {} - - //! Get the padding (in pixels) inside the edges of the element - virtual UiLayoutInterface::Padding GetPadding() = 0; - - //! Set the padding (in pixels) inside the edges of the element - virtual void SetPadding(UiLayoutInterface::Padding padding) = 0; - - //! Get the spacing (in pixels) between child elements - virtual float GetSpacing() = 0; - - //! Set the spacing (in pixels) between child elements - virtual void SetSpacing(float spacing) = 0; - - //! Get the horizontal order for this layout - virtual UiLayoutInterface::HorizontalOrder GetOrder() = 0; - - //! Set the horizontal order for this layout - virtual void SetOrder(UiLayoutInterface::HorizontalOrder order) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiLayoutRowInterface> UiLayoutRowBus; - diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiMarkupButtonBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiMarkupButtonBus.h deleted file mode 100644 index 919c66780a..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiMarkupButtonBus.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Color.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! A markup button allows for button-like behavior on markup text. -//! -//! The markup itself is contained within a text component. The markup button -//! handles interaction with the text, and can also apply styling (such as -//! coloring for button/clickable text). -//! -//! Markup button behavior is only intended for mouse interactions. -class UiMarkupButtonInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiMarkupButtonInterface() {} - - //! Get the link color - virtual AZ::Color GetLinkColor() = 0; - - //! Set the link color - virtual void SetLinkColor(const AZ::Color& linkColor) = 0; - - //! Get the link hover color - virtual AZ::Color GetLinkHoverColor() = 0; - - //! Set the link hover color - virtual void SetLinkHoverColor(const AZ::Color& linkHoverColor) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiMarkupButtonInterface> UiMarkupButtonBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiMarkupButtonNotifications - : public AZ::ComponentBus -{ -public: - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const bool EnableEventQueue = true; - ////////////////////////////////////////////////////////////////////////// - -public: // member functions - - virtual ~UiMarkupButtonNotifications() {} - - virtual void OnHoverStart(int id, const AZStd::string& action, const AZStd::string& data) = 0; - virtual void OnHoverEnd(int id, const AZStd::string& action, const AZStd::string& data) = 0; - virtual void OnPressed(int id, const AZStd::string& action, const AZStd::string& data) = 0; - virtual void OnReleased(int id, const AZStd::string& action, const AZStd::string& data) = 0; - virtual void OnClick(int id, const AZStd::string& action, const AZStd::string& data) = 0; -}; - -typedef AZ::EBus<UiMarkupButtonNotifications> UiMarkupButtonNotificationsBus; - diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiMaskBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiMaskBus.h deleted file mode 100644 index fc3fd897ac..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiMaskBus.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiMaskInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiMaskInterface() {} - - //! Get whether masking is enabled - virtual bool GetIsMaskingEnabled() = 0; - - //! Set whether masking is enabled - virtual void SetIsMaskingEnabled(bool enableMasking) = 0; - - //! Get whether interaction masking is enabled - virtual bool GetIsInteractionMaskingEnabled() = 0; - - //! Set whether interaction masking is enabled - virtual void SetIsInteractionMaskingEnabled(bool enableInteractionMasking) = 0; - - //! Get whether mask visual is drawn to color buffer behind child elements - virtual bool GetDrawBehind() = 0; - - //! Set whether mask visual is drawn to color buffer behind child elements - virtual void SetDrawBehind(bool drawMaskVisualBehindChildren) = 0; - - //! Get whether mask visual is drawn to color buffer in front of child elements - virtual bool GetDrawInFront() = 0; - - //! Set whether mask visual is drawn to color buffer in front of child elements - virtual void SetDrawInFront(bool drawMaskVisualInFrontOfChildren) = 0; - - //! Get whether to use alpha test when drawing mask visual to stencil - virtual bool GetUseAlphaTest() = 0; - - //! Set whether to use alpha test when drawing mask visual to stencil - virtual void SetUseAlphaTest(bool useAlphaTest) = 0; - - //! Get the flag that indicates whether the mask should use render to texture - virtual bool GetUseRenderToTexture() = 0; - - //! Set the flag that indicates whether the mask should use render to texture - virtual void SetUseRenderToTexture(bool useRenderToTexture) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiMaskInterface> UiMaskBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiNavigationBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiNavigationBus.h deleted file mode 100644 index 3b3bf9fbf7..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiNavigationBus.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiNavigationInterface - : public AZ::ComponentBus -{ -public: // types - - enum class NavigationMode - { - Automatic, - Custom, - None - }; - -public: // member functions - - virtual ~UiNavigationInterface() {} - - //! Get the navigation mode - virtual NavigationMode GetNavigationMode() = 0; - - //! Set the navigation mode - virtual void SetNavigationMode(NavigationMode navigationMode) = 0; - - //! Get the entity to receive focus when up is pressed - virtual AZ::EntityId GetOnUpEntity() = 0; - - //! Set the entity to receive focus when up is pressed - virtual void SetOnUpEntity(AZ::EntityId entityId) = 0; - - //! Get the entity to receive focus when down is pressed - virtual AZ::EntityId GetOnDownEntity() = 0; - - //! Set the entity to receive focus when down is pressed - virtual void SetOnDownEntity(AZ::EntityId entityId) = 0; - - //! Get the entity to receive focus when left is pressed - virtual AZ::EntityId GetOnLeftEntity() = 0; - - //! Set the entity to receive focus when left is pressed - virtual void SetOnLeftEntity(AZ::EntityId entityId) = 0; - - //! Get the entity to receive focus when right is pressed - virtual AZ::EntityId GetOnRightEntity() = 0; - - //! Set the entity to receive focus when right is pressed - virtual void SetOnRightEntity(AZ::EntityId entityId) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiNavigationInterface> UiNavigationBus; - - - diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiParticleEmitterBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiParticleEmitterBus.h deleted file mode 100644 index 88d8da4551..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiParticleEmitterBus.h +++ /dev/null @@ -1,392 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Color.h> -#include <AzFramework/Entity/EntityContextBus.h> - -class ISprite; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Bus for making requests to the UiParticleEmitterComponent -class UiParticleEmitterInterface - : public AZ::ComponentBus -{ -public: // types - - enum class EmitShape - { - Point, //!< particles are emitted from the emitter position along the given angle - Circle, //!< particles are emitted from a circle whose radius is the minimum of the element width and height - Quad //!< particles are emitted from the quad with the same size as the element width and height - }; - - enum class ParticleCoordinateType - { - Cartesian, //!< particles move using X,Y co-ordinates - Polar //!< particles move using X: radial speed, Y: angular speed - }; - - enum class ParticleInitialDirectionType - { - RelativeToEmitAngle, //!< particle initial direction is based on the emit angle - RelativeToEmitterCenter //!< particle initial direction is directed away from the emitter shape center - }; - - enum class ParticleKeyframeTangentType - { - EaseIn, //!< A zero/flat tangent, a keyframe with ease in + ease out would act like an x^3 curve at the origin - EaseOut, //!< A zero/flat tangent, a keyframe with ease in + ease out would act like an x^3 curve at the origin - Linear, //!< The curve moves linearly from this keyframe towards the next/previous keyframe - Step //!< The curve jumps from the current keyframe value to the next/previous keyframe value - }; - - struct ParticleFloatKeyframe - { - AZ_TYPE_INFO(ParticleFloatKeyframe, "{85DF04FE-F614-47C1-B88A-A9F7D4826F6F}"); - - float time = 0.0f; - float multiplier = 1.0f; - ParticleKeyframeTangentType inTangent = ParticleKeyframeTangentType::EaseIn; - ParticleKeyframeTangentType outTangent = ParticleKeyframeTangentType::EaseOut; - }; - - struct ParticleColorKeyframe - { - AZ_TYPE_INFO(ParticleColorKeyframe, "{22B0CBC0-21A5-44E3-90C5-9BFEF6E4E3C5}"); - - float time = 0.0f; - AZ::Color color = AZ::Color(1.0f, 1.0f, 1.0f, 1.0f); - ParticleKeyframeTangentType inTangent = ParticleKeyframeTangentType::EaseIn; - ParticleKeyframeTangentType outTangent = ParticleKeyframeTangentType::EaseOut; - }; - -public: // member functions - - virtual ~UiParticleEmitterInterface() {} - - //! Gets whether the emitter is emitting particles - virtual bool GetIsEmitting() = 0; - - //! Sets whether the emitter is emitting particles - virtual void SetIsEmitting(bool emitParticles) = 0; - - //! Gets whether the emitter uses a fixed random seed - virtual bool GetIsRandomSeedFixed() = 0; - - //! Sets whether the emitter uses a fixed random seed - virtual void SetIsRandomSeedFixed(bool randomSeedFixed) = 0; - - //! Gets the emitter random seed - virtual int GetRandomSeed() = 0; - - //! Sets the emitter random seed - virtual void SetRandomSeed(int randomSeed) = 0; - - //! Gets whether the particles move relative to the emitter position - virtual bool GetIsParticlePositionRelativeToEmitter() = 0; - - //! Sets whether the particles move relative to the emitter position - virtual void SetIsParticlePositionRelativeToEmitter(bool relativeToEmitter) = 0; - - //! Gets the amount of particles emitted per second - virtual float GetParticleEmitRate() = 0; - - //! Sets the amount of particles emitted per second - virtual void SetParticleEmitRate(float particleEmitRate) = 0; - - //! Gets whether the emitter starts emitting on activate - virtual bool GetIsEmitOnActivate() = 0; - - //! Sets whether the emitter starts emitting on activate - virtual void SetIsEmitOnActivate(bool emitOnActivate) = 0; - - //! Gets whether the average particle count is reached as soon as the emitter starts emitting - virtual bool GetIsHitParticleCountOnActivate() = 0; - - //! Sets whether the average particle count is reached as soon as the emitter starts emitting - virtual void SetIsHitParticleCountOnActivate(bool hitParticleCountOnActivate) = 0; - - //! Gets whether the emitter lifetime is infinite - virtual bool GetIsEmitterLifetimeInfinite() = 0; - - //! Sets whether the emitter lifetime is infinite - virtual void SetIsEmitterLifetimeInfinite(bool emitterLifetimeInfinite) = 0; - - //! Gets the lifetime of the emitter (in seconds) - virtual float GetEmitterLifetime() = 0; - - //! Sets the lifetime of the emitter (in seconds) - virtual void SetEmitterLifetime(float emitterLifetime) = 0; - - //! Gets whether there is a cap on the amount of active particles - virtual bool GetIsParticleCountLimited() = 0; - - //! Sets whether there is a cap on the amount of active particles - virtual void SetIsParticleCountLimited(bool particleCountLimited) = 0; - - //! Gets the maximum amount of active particles - virtual AZ::u32 GetMaxParticles() = 0; - - //! Sets the maximum amount of active particles - virtual void SetMaxParticles(AZ::u32 maxParticles) = 0; - - //! Gets the shape of the emitter - virtual EmitShape GetEmitterShape() = 0; - - //! Sets the shape of the emitter - virtual void SetEmitterShape(EmitShape emitterShape) = 0; - - //! Gets whether the particles are emitted on the edge of the emitter shape - virtual bool GetIsEmitOnEdge() = 0; - - //! Sets whether the particles are emitted on the edge of the emitter shape - virtual void SetIsEmitOnEdge(bool emitOnEdge) = 0; - - //! Gets the inside distance from the emitter shape edge that particles should emit from - virtual float GetInsideEmitDistance() = 0; - - //! Sets the inside distance from the emitter shape edge that particles should emit from - virtual void SetInsideEmitDistance(float insideEmitDistance) = 0; - - //! Gets the outside distance from the emitter shape edge that particles should emit from - virtual float GetOutsideEmitDistance() = 0; - - //! Sets the outside distance from the emitter shape edge that particles should emit from - virtual void SetOutsideEmitDistance(float outsideEmitDistance) = 0; - - //! Gets how the initial direction is calculated for Cartesian movement. - virtual ParticleInitialDirectionType GetParticleInitialDirectionType() = 0; - - //! Sets how the initial direction is calculated for Cartesian movement. - virtual void SetParticleInitialDirectionType(ParticleInitialDirectionType initialDirectionType) = 0; - - //! Gets the angle that particles are emitted from (in degrees clockwise measured from straight up) - virtual float GetEmitAngle() = 0; - - //! Sets the angle that particles are emitted from (in degrees clockwise measured from straight up) - virtual void SetEmitAngle(float emitAngle) = 0; - - //! Gets the variation in the angle that particles are emitted from (in degrees, with 10 degrees variation being +/- 10 degrees about the emit angle) - virtual float GetEmitAngleVariation() = 0; - - //! Sets the variation in the angle that particles are emitted from (in degrees, with 10 degrees variation being +/- 10 degrees about the emit angle) - virtual void SetEmitAngleVariation(float emitAngleVariation) = 0; - - //! Gets whether the particle lifetime is infinite - virtual bool GetIsParticleLifetimeInfinite() = 0; - - //! Sets whether the particle lifetime is infinite - virtual void SetIsParticleLifetimeInfinite(bool infiniteLifetime) = 0; - - //! Gets the particle life time (in seconds) - virtual float GetParticleLifetime() = 0; - - //! Sets the particle life time (in seconds) - virtual void SetParticleLifetime(float lifetime) = 0; - - //! Gets the particle life time variation (in seconds, 1 second variation being up to +/- 1 second about the lifetime) - virtual float GetParticleLifetimeVariation() = 0; - - //! Sets the particle life time variation (in seconds, 1 second variation being up to +/- 1 second about the lifetime) - virtual void SetParticleLifetimeVariation(float lifetimeVariation) = 0; - - //! Gets the sprite to be used by the particles - virtual ISprite* GetSprite() = 0; - - //! Sets the sprite to be used by the particles - virtual void SetSprite(ISprite* sprite) = 0; - - //! Gets the source location of the image to be displayed by the particles - virtual AZStd::string GetSpritePathname() = 0; - - //! Sets the source location of the image to be displayed by the particles - virtual void SetSpritePathname(AZStd::string spritePath) = 0; - - //! Gets whether the sprite-sheet cell index changes over time - virtual bool GetIsSpriteSheetAnimated() = 0; - - //! Sets whether the sprite-sheet cell index changes over time - virtual void SetIsSpriteSheetAnimated(bool isSpriteSheetAnimated) = 0; - - //! Gets whether the sprite-sheet cell animation is looped - virtual bool GetIsSpriteSheetAnimationLooped() = 0; - - //! Sets whether the sprite-sheet cell animation is looped - virtual void SetIsSpriteSheetAnimationLooped(bool isSpriteSheetAnimationLooped) = 0; - - //! Gets whether the sprite-sheet cell (starting) index is random - virtual bool GetIsSpriteSheetIndexRandom() = 0; - - //! Sets whether the sprite-sheet cell (starting) index is random - virtual void SetIsSpriteSheetIndexRandom(bool isSpriteSheetIndexRandom) = 0; - - //! Gets the sprite-sheet cell (starting) index - virtual int GetSpriteSheetCellIndex() = 0; - - //! Sets the sprite-sheet cell (starting) index - virtual void SetSpriteSheetCellIndex(int spriteSheetIndex) = 0; - - //! Gets the sprite-sheet cell end index - virtual int GetSpriteSheetCellEndIndex() = 0; - - //! Sets the sprite-sheet cell end index - virtual void SetSpriteSheetCellEndIndex(int spriteSheetEndIndex) = 0; - - //! Gets the sprite-sheet cell frame delay (in seconds) - virtual float GetSpriteSheetFrameDelay() = 0; - - //! Sets the sprite-sheet cell frame delay (in seconds) - virtual void SetSpriteSheetFrameDelay(float spriteSheetFrameDelay) = 0; - - //! Gets whether the aspect ratio of the particles is locked - virtual bool GetIsParticleAspectRatioLocked() = 0; - - //! Sets whether the aspect ratio of the particles is locked - virtual void SetIsParticleAspectRatioLocked(bool aspectRatioLocked) = 0; - - //! Gets the particle pivot (where 0,0 is the top left of the particle and 1,1 is the bottom right of the particle) - virtual AZ::Vector2 GetParticlePivot() = 0; - - //! Sets the particle pivot (where 0,0 is the top left of the particle and 1,1 is the bottom right of the particle) - virtual void SetParticlePivot(AZ::Vector2 particlePivot) = 0; - - //! Gets the particle size - virtual AZ::Vector2 GetParticleSize() = 0; - - //! Sets the particle size - virtual void SetParticleSize(AZ::Vector2 particleSize) = 0; - - //! Gets the particle width - virtual float GetParticleWidth() = 0; - - //! Sets the particle width - virtual void SetParticleWidth(float width) = 0; - - //! Gets the particle width variation (a variation of 1 being up to 1 either side of the given width) - virtual float GetParticleWidthVariation() = 0; - - //! Sets the particle width variation (a variation of 1 being up to 1 either side of the given width) - virtual void SetParticleWidthVariation(float widthVariation) = 0; - - //! Gets the particle height - virtual float GetParticleHeight() = 0; - - //! Sets the particle height - virtual void SetParticleHeight(float height) = 0; - - //! Gets the particle height variation (a variation of 5 being up to 5 either side of the given height) - virtual float GetParticleHeightVariation() = 0; - - //! Sets the particle height variation (a variation of 5 being up to 5 either side of the given height) - virtual void SetParticleHeightVariation(float heightVariation) = 0; - - //! Gets the particle movement co-ordinate type - virtual ParticleCoordinateType GetParticleMovementCoordinateType() = 0; - - //! Sets the particle movement co-ordinate type - virtual void SetParticleMovementCoordinateType(ParticleCoordinateType particleMovementCoordinateType) = 0; - - //! Gets the particle acceleration co-ordinate type - virtual ParticleCoordinateType GetParticleAccelerationCoordinateType() = 0; - - //! Sets the particle acceleration co-ordinate type - virtual void SetParticleAccelerationCoordinateType(ParticleCoordinateType particleAccelerationCoordinateType) = 0; - - //! Gets the particle initial velocity for Polar movement - virtual AZ::Vector2 GetParticleInitialVelocity() = 0; - - //! Sets the particle initial velocity for Polar movement - virtual void SetParticleInitialVelocity(AZ::Vector2 initialVelocity) = 0; - - //! Gets the particle initial velocity variation for Polar movement (a variation of (1,2) being up to (1,2) either side of the initial velocity) - virtual AZ::Vector2 GetParticleInitialVelocityVariation() = 0; - - //! Sets the particle initial velocity variation for Polar movement (a variation of (1,2) being up to (1,2) either side of the initial velocity) - virtual void SetParticleInitialVelocityVariation(AZ::Vector2 initialVelocityVariation) = 0; - - //! Gets the particle speed for particles with a random initial direction for Cartesian movement - virtual float GetParticleSpeed() = 0; - - //! Sets the particle speed for particles with a random initial direction for Cartesian movement - virtual void SetParticleSpeed(float speed) = 0; - - //! Gets the particle speed variation for particles with a random initial direction for Cartesian movement (a variation of 1 being up to 1 either side of the given speed) - virtual float GetParticleSpeedVariation() = 0; - - //! Sets the particle speed variation for particles with a random initial direction for Cartesian movement (a variation of 1 being up to 1 either side of the given speed) - virtual void SetParticleSpeedVariation(float speedVariation) = 0; - - //! Gets the particle acceleration - virtual AZ::Vector2 GetParticleAcceleration() = 0; - - //! Sets the particle acceleration - virtual void SetParticleAcceleration(AZ::Vector2 acceleration) = 0; - - //! Gets whether the particle rotation is based on the current velocity - virtual bool GetIsParticleRotationFromVelocity() = 0; - - //! Sets whether the particle rotation is based on the current velocity - virtual void SetIsParticleRotationFromVelocity(bool rotationFromVelocity) = 0; - - //! Gets whether the particle initial rotation is based on the initial velocity - virtual bool GetIsParticleInitialRotationFromInitialVelocity() = 0; - - //! Sets whether the particle initial rotation is based on the initial velocity - virtual void SetIsParticleInitialRotationFromInitialVelocity(bool rotationFromVelocity) = 0; - - //! Gets the particle initial rotation (in degrees) - virtual float GetParticleInitialRotation() = 0; - - //! Sets the particle initial rotation (in degrees) - virtual void SetParticleInitialRotation(float initialRotation) = 0; - - //! Gets the particle initial rotation variation (in degrees, a variation of 10 being up to 10 degrees either side of the initial rotation) - virtual float GetParticleInitialRotationVariation() = 0; - - //! Sets the particle initial rotation variation (in degrees, a variation of 10 being up to 10 degrees either side of the initial rotation) - virtual void SetParticleInitialRotationVariation(float initialRotationVariation) = 0; - - //! Gets the particle rotation speed (in degrees per second) - virtual float GetParticleRotationSpeed() = 0; - - //! Sets the particle rotation speed (in degrees per second) - virtual void SetParticleRotationSpeed(float rotationSpeed) = 0; - - //! Gets the particle rotation speed variation (in degrees, a variation of 5 being up to 5 either side of the rotation speed) - virtual float GetParticleRotationSpeedVariation() = 0; - - //! Sets the particle rotation speed variation (in degrees, a variation of 5 being up to 5 either side of the rotation speed) - virtual void SetParticleRotationSpeedVariation(float rotationSpeedVariation) = 0; - - //! Gets the particle color tint - virtual AZ::Color GetParticleColor() = 0; - - //! Sets the particle color tint - virtual void SetParticleColor(AZ::Color color) = 0; - - //! Gets the particle color brightness variation (from 0-1, 0 being no variation, 1 being random variation from the original color down to black) - virtual float GetParticleColorBrightnessVariation() = 0; - - //! Sets the particle color brightness variation (from 0-1, 0 being no variation, 1 being random variation from the original color down to black) - virtual void SetParticleColorBrightnessVariation(float brightnessVariation) = 0; - - //! Gets the particle color tint variation - virtual float GetParticleColorTintVariation() = 0; - - //! Sets the particle color tint variation - virtual void SetParticleColorTintVariation(float tintVariation) = 0; - - //! Gets the particle alpha - virtual float GetParticleAlpha() = 0; - - //! Sets the particle alpha - virtual void SetParticleAlpha(float alpha) = 0; -}; - -using UiParticleEmitterBus = AZ::EBus<UiParticleEmitterInterface>; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiRadioButtonBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiRadioButtonBus.h deleted file mode 100644 index 5e39655e82..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiRadioButtonBus.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that a radio button component needs to implement. A radio button component -//! provides functionality for a button that can be turned on or off and is dependent on the other -//! radio buttons in the same radio button group. This interface is designed to be used in -//! conjunction with the UiRadioButtonGroupInterface, which describes the group for radio buttons. -class UiRadioButtonInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiRadioButtonInterface() {} - - //! Query the state of the radio button - //! \return The current state for the radio button. - virtual bool GetState() = 0; - - //! Get the radio button group - virtual AZ::EntityId GetGroup() = 0; - - //! Get the optional checked (ON) entity - virtual AZ::EntityId GetCheckedEntity() = 0; - - //! Set the optional checked (ON) entity - virtual void SetCheckedEntity(AZ::EntityId entityId) = 0; - - //! Get the optional unchecked (OFF) entity - virtual AZ::EntityId GetUncheckedEntity() = 0; - - //! Set the optional unchecked (OFF) entity - virtual void SetUncheckedEntity(AZ::EntityId entityId) = 0; - - //! Get the action triggered when turned on - virtual const LyShine::ActionName& GetTurnOnActionName() = 0; - - //! Set the action triggered when turned on - virtual void SetTurnOnActionName(const LyShine::ActionName& actionName) = 0; - - //! Get the action triggered when turned off - virtual const LyShine::ActionName& GetTurnOffActionName() = 0; - - //! Set the action triggered when turned off - virtual void SetTurnOffActionName(const LyShine::ActionName& actionName) = 0; - - //! Get the action triggered when changed - virtual const LyShine::ActionName& GetChangedActionName() = 0; - - //! Set the action triggered when changed - virtual void SetChangedActionName(const LyShine::ActionName& actionName) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiRadioButtonInterface> UiRadioButtonBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiRadioButtonNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiRadioButtonNotifications() {} - - //! Notify listeners that the radio button state has changed - virtual void OnRadioButtonStateChange([[maybe_unused]] bool checked) {} -}; - -typedef AZ::EBus<UiRadioButtonNotifications> UiRadioButtonNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiRadioButtonCommunicationBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiRadioButtonCommunicationBus.h deleted file mode 100644 index 64b9a44427..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiRadioButtonCommunicationBus.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that a radio button component needs to implement. This interface allows the -//! radio button group to communicate with the radio button itself -class UiRadioButtonCommunicationInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiRadioButtonCommunicationInterface() {} - - //! Used by the group to set the state of the radio button - //! \param The new desired state of the radio button. - //! \param Whether the button should inform listeners that it was changed. - virtual void SetState(bool isOn, bool sendNotifications) = 0; - - //! Set the radio button group - virtual void SetGroup(AZ::EntityId group) = 0; - -public: // static member data - - //! Only one component on an entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiRadioButtonCommunicationInterface> UiRadioButtonCommunicationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiRadioButtonGroupBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiRadioButtonGroupBus.h deleted file mode 100644 index 0dafcd68ae..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiRadioButtonGroupBus.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that a radio button group component needs to implement. A radio button group -//! component provides functionality to manage a group of radio buttons. A group of radio buttons -//! allows users to choose one of a predefined set of mutually exclusive options. No more than one -//! item may be selected. -class UiRadioButtonGroupInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiRadioButtonGroupInterface() {} - - //! Query the state of the radio button group - //! \return The currently checked radio button. - virtual AZ::EntityId GetCheckedRadioButton() = 0; - - //! Set a radio button to a desired state - virtual void SetState(AZ::EntityId radioButton, bool isOn) = 0; - - //! Get the allow uncheck flag - virtual bool GetAllowUncheck() = 0; - - //! Set the allow uncheck flag - virtual void SetAllowUncheck(bool allowUncheck) = 0; - - //! Add a new radio button to the group - virtual void AddRadioButton(AZ::EntityId radioButton) = 0; - - //! Remove a radio button from the group - virtual void RemoveRadioButton(AZ::EntityId radioButton) = 0; - - //! Query whether a radio button is in the group or not - virtual bool ContainsRadioButton(AZ::EntityId radioButton) = 0; - - //! Get the action triggered when changed - virtual const LyShine::ActionName& GetChangedActionName() = 0; - - //! Set the action triggered when changed - virtual void SetChangedActionName(const LyShine::ActionName& actionName) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiRadioButtonGroupInterface> UiRadioButtonGroupBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiRadioButtonGroupNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiRadioButtonGroupNotifications() {} - - //! Notify listeners that the radio button group state has changed - virtual void OnRadioButtonGroupStateChange([[maybe_unused]] AZ::EntityId checkedRadioButton) {} -}; - -typedef AZ::EBus<UiRadioButtonGroupNotifications> UiRadioButtonGroupNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiRadioButtonGroupCommunicationBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiRadioButtonGroupCommunicationBus.h deleted file mode 100644 index a28435a2cd..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiRadioButtonGroupCommunicationBus.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that a radio button group component needs to implement. This interface allows -//! a radio button to communicate with the radio button group itself -class UiRadioButtonGroupCommunicationInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiRadioButtonGroupCommunicationInterface() {} - - //! Registers a radio button within a group - //! \param The radio button to add - //! \return Whether the radio button was successfully added to the group or not - virtual bool RegisterRadioButton(AZ::EntityId radioButton) = 0; - - //! Unregisters a radio button within a group - //! \param The radio button to remove - virtual void UnregisterRadioButton(AZ::EntityId radioButton) = 0; - - //! Called when a radio button wants to change state due to user action (i.e. by clicking it) - //! \param The radio button to change the state of - //! \param The new radio button state - virtual void RequestRadioButtonStateChange(AZ::EntityId radioButton, bool newState) = 0; - -public: // static member data - - //! Only one component on an entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiRadioButtonGroupCommunicationInterface> UiRadioButtonGroupCommunicationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiRenderBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiRenderBus.h deleted file mode 100644 index b5eebb716b..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiRenderBus.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -namespace LyShine -{ - class IRenderGraph; -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiRenderInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiRenderInterface() {} - - //! Render the component into the render graph - virtual void Render(LyShine::IRenderGraph* renderGraph) = 0; - -public: // static member data - - //! Multiple components on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; -}; - -typedef AZ::EBus<UiRenderInterface> UiRenderBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiRenderControlBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiRenderControlBus.h deleted file mode 100644 index 10835a4e3e..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiRenderControlBus.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -namespace LyShine -{ - class IRenderGraph; -} - -class UiElementInterface; -class UiRenderInterface; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! The UiRenderControlBus is used for controlling the rendering of elements that affect the rendering -//! of their children. -//! An example use is a mask component that needs to setup stencil write before rendering its -//! components to increment the stencil buffer, switch to stencil test before rendering the child -//! elements and then do a second pass to decrement the stencil buffer. -//! The interface is designed to be flexible and could also be used for setting up scissoring or -//! rendering to a texture. -class UiRenderControlInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiRenderControlInterface() {} - - //! This renders this element plus its children. It allows the RenderControl element to control - //! the order in which the element's component and children are rendered and to change state - //! at any point while rendering them. - //! \param renderGraph, the render graph being added to - //! \param elementInterface, pointer to the element interface for this element (for performance) - //! \param renderInterface, pointer to the render interface for this element (for performance) - //! \param numChildren, the number of child elements of this element - //! \param isInGame, true if element being rendered in game (or preview), false if being render in edit mode - virtual void Render( - LyShine::IRenderGraph* renderGraph, - UiElementInterface* elementInterface, - UiRenderInterface* renderInterface, - int numChildren, - bool isInGame) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiRenderControlInterface> UiRenderControlBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiScrollBarBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiScrollBarBus.h deleted file mode 100644 index d124577cf9..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiScrollBarBus.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiScrollBarInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiScrollBarInterface() {} - - //! Get the size of the handle relative to the scrollbar (0 - 1) - virtual float GetHandleSize() = 0; - - //! Set the size of the handle relative to the scrollbar (0 - 1) - virtual void SetHandleSize(float size) = 0; - - //! Get the minimum size of the handle in pixels - virtual float GetMinHandlePixelSize() = 0; - - //! Set the minimum size of the handle in pixels - virtual void SetMinHandlePixelSize(float size) = 0; - - //! Get the handle entity - virtual AZ::EntityId GetHandleEntity() = 0; - - //! Set the handle entity - virtual void SetHandleEntity(AZ::EntityId entityId) = 0; - - //! Get auto fade - virtual bool IsAutoFadeEnabled() = 0; - - //! Set auto fade - virtual void SetAutoFadeEnabled(bool isAutoFadeEnabled) = 0; - - //! Get the delay in seconds before the scrollbar will fade if unused - virtual float GetAutoFadeDelay() = 0; - - //! Set the fade delay in seconds - virtual void SetAutoFadeDelay(float delay) = 0; - - //! Get the speed in seconds that it will take for the scrollbar to fade to transparent - virtual float GetAutoFadeSpeed() = 0; - - //! Set the fade speed in seconds - virtual void SetAutoFadeSpeed(float speed) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiScrollBarInterface> UiScrollBarBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiScrollBoxBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiScrollBoxBus.h deleted file mode 100644 index 9d49c6c0b0..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiScrollBoxBus.h +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> -#include <LyShine/UiBase.h> -#include <functional> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiScrollBoxInterface - : public AZ::ComponentBus -{ -public: // types - - //! Callback for when box is scrolled - typedef AZStd::function<void(AZ::EntityId sendingEntityId, AZ::Vector2 newScrollOffset)> ScrollOffsetChangeCallback; - - enum class SnapMode - { - None, - Children, - Grid - }; - - enum class ScrollBarVisibility - { - AlwaysShow, - AutoHide, - AutoHideAndResizeViewport - }; - -public: // member functions - - virtual ~UiScrollBoxInterface() {} - - //! Query the current scroll offset of the scroll box - //! \return The current scroll offset for the scroll box. - //! - //! The scroll offset is the offset from the content element's anchor point to - //! the content element's pivot. - //! If the content element's anchor points are split it is the offset from - //! their center to the pivot. - //! So if the mouse is dragged left, the content moves to the left, so the offset - //! X has the X drag amount subtracted from it. - //! Using the offset from the anchor to the pivot allows the offset to be center - //! to center or top-left to top-left, or any combination of the possible - //! anchor and pivot positions - virtual AZ::Vector2 GetScrollOffset() = 0; - - //! Set the scroll offset of the scroll box - //! \param isOn The new desired scroll offset of the scroll box. - virtual void SetScrollOffset(AZ::Vector2 scrollOffset) = 0; - - //! Get the scroll value from 0 - 1 - virtual AZ::Vector2 GetNormalizedScrollValue() = 0; - - //! Change content size and scroll offset, and handle the changes - virtual void ChangeContentSizeAndScrollOffset(AZ::Vector2 contentSize, AZ::Vector2 scrollOffset) = 0; - - //! Get whether there is content to scroll horizontally - virtual bool HasHorizontalContentToScroll() = 0; - - //! Get whether there is content to scroll vertically - virtual bool HasVerticalContentToScroll() = 0; - - //! Get whether horizontal scrolling interaction is enabled - virtual bool GetIsHorizontalScrollingEnabled() = 0; - - //! Set whether horizontal scrolling interaction is enabled - virtual void SetIsHorizontalScrollingEnabled(bool isEnabled) = 0; - - //! Get whether vertical scrolling interaction is enabled - virtual bool GetIsVerticalScrollingEnabled() = 0; - - //! Set whether vertical scrolling interaction is enabled - virtual void SetIsVerticalScrollingEnabled(bool isEnabled) = 0; - - //! Get whether scrolling interaction is constrained to the content area - virtual bool GetIsScrollingConstrained() = 0; - - //! Set whether vertical scrolling interaction is constrained to the content area - virtual void SetIsScrollingConstrained(bool isConstrained) = 0; - - //! Get snap mode - virtual SnapMode GetSnapMode() = 0; - - //! Set snap mode - virtual void SetSnapMode(SnapMode snapMode) = 0; - - //! Get snap grid - virtual AZ::Vector2 GetSnapGrid() = 0; - - //! Set snap grid - virtual void SetSnapGrid(AZ::Vector2 snapGrid) = 0; - - //! Get horizontal scrollbar visibility behavior - virtual ScrollBarVisibility GetHorizontalScrollBarVisibility() = 0; - - //! Set horizontal scrollbar visibility behavior - virtual void SetHorizontalScrollBarVisibility(ScrollBarVisibility visibility) = 0; - - //! Get vertical scrollbar visibility behavior - virtual ScrollBarVisibility GetVerticalScrollBarVisibility() = 0; - - //! Set vertical scrollbar visibility behavior - virtual void SetVerticalScrollBarVisibility(ScrollBarVisibility visibility) = 0; - - //! Get the callback invoked while the scroll offset is changing - virtual ScrollOffsetChangeCallback GetScrollOffsetChangingCallback() = 0; - - //! Set the callback invoked while the scroll offset is changing - virtual void SetScrollOffsetChangingCallback(ScrollOffsetChangeCallback onChange) = 0; - - //! Get the action triggered while the scroll offset is changing - virtual const LyShine::ActionName& GetScrollOffsetChangingActionName() = 0; - - //! Set the action triggered while the scroll offset is changing - virtual void SetScrollOffsetChangingActionName(const LyShine::ActionName& actionName) = 0; - - //! Get the callback invoked when the scroll offset is done changing - virtual ScrollOffsetChangeCallback GetScrollOffsetChangedCallback() = 0; - - //! Set the callback invoked when the scroll offset is done changing - virtual void SetScrollOffsetChangedCallback(ScrollOffsetChangeCallback onChange) = 0; - - //! Get the action triggered when the scroll offset is done changing - virtual const LyShine::ActionName& GetScrollOffsetChangedActionName() = 0; - - //! Set the action triggered when the scroll offset is done changing - virtual void SetScrollOffsetChangedActionName(const LyShine::ActionName& actionName) = 0; - - //! Set the optional content entity, if none is specified then nothing gets scrolled - virtual void SetContentEntity(AZ::EntityId entityId) = 0; - - //! Get the optional content entity - virtual AZ::EntityId GetContentEntity() = 0; - - //! Set the optional horizontal scrollbar entity - virtual void SetHorizontalScrollBarEntity(AZ::EntityId entityId) = 0; - - //! Get the optional horizontal scrollbar entity - virtual AZ::EntityId GetHorizontalScrollBarEntity() = 0; - - //! Set the optional vertical scrollbar entity - virtual void SetVerticalScrollBarEntity(AZ::EntityId entityId) = 0; - - //! Get the optional vertical scrollbar entity - virtual AZ::EntityId GetVerticalScrollBarEntity() = 0; - - //! Find the child of the content element that is closest to the content anchors - //! at the current scroll offset. i.e. what is the currently "selected" child - virtual AZ::EntityId FindClosestContentChildElement() = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiScrollBoxInterface> UiScrollBoxBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that listeners need to implement to receive scroll box change notifications -class UiScrollBoxNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiScrollBoxNotifications(){} - - //! Called when the scroll offset is changing - virtual void OnScrollOffsetChanging(AZ::Vector2 newScrollOffset) = 0; - - //! Called when the scroll offset is done changing - virtual void OnScrollOffsetChanged(AZ::Vector2 newScrollOffset) = 0; -}; - -typedef AZ::EBus<UiScrollBoxNotifications> UiScrollBoxNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiScrollableBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiScrollableBus.h deleted file mode 100644 index a1272a07bf..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiScrollableBus.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that a scrollable component needs to implement. A scrollable component is one -//! that provides functionality to scroll its content -//! (e.g. UiScrollBoxComponent) -class UiScrollableInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiScrollableInterface() {} - - //! Get the ratio between the scrollable content size and the size of its parent - virtual bool GetScrollableParentToContentRatio(AZ::Vector2& ratioOut) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiScrollableInterface> UiScrollableBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that listeners need to implement in order to get notifications when values of the -//! scrollable change -class UiScrollableNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiScrollableNotifications(){} - - //! Called when the scroll value (0 - 1) is changing - virtual void OnScrollableValueChanging(AZ::Vector2 value) = 0; - - //! Called when the scroll value (0 - 1) has been changed - virtual void OnScrollableValueChanged(AZ::Vector2 value) = 0; -}; - -typedef AZ::EBus<UiScrollableNotifications> UiScrollableNotificationBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that scrollers need to implement in order to get notifications of changes -//! created by the scrollable -class UiScrollableToScrollerNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiScrollableToScrollerNotifications(){} - - //! Called when the scrollable is changing the scroll value (0 - 1) - virtual void OnValueChangingByScrollable(AZ::Vector2 value) = 0; - - //! Called when the scrollable is done changing the scroll value (0 - 1) - virtual void OnValueChangedByScrollable(AZ::Vector2 value) = 0; - - //! Called when the content size or content parent size has been changed - virtual void OnScrollableParentToContentRatioChanged(AZ::Vector2 parentToContentRatio) = 0; -}; - -typedef AZ::EBus<UiScrollableToScrollerNotifications> UiScrollableToScrollerNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiScrollerBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiScrollerBus.h deleted file mode 100644 index 36975e3e80..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiScrollerBus.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that a scroller component needs to implement. A scroller component provides -//! functionality to control the scrolling of scrollable content -//! (e.g. UiScrollBarComponent) -class UiScrollerInterface - : public AZ::ComponentBus -{ -public: // types - - //! params: sending entity id, newValue, newPosition - typedef AZStd::function<void(AZ::EntityId, float)> ValueChangeCallback; - - //! Scroller orientation - enum class Orientation - { - Horizontal, - Vertical - }; - -public: // member functions - - virtual ~UiScrollerInterface() {} - - //! Get the current value for the scrollbar (0 - 1) - virtual float GetValue() = 0; - - //! Set the value of the scrollbar (0 - 1) - virtual void SetValue(float value) = 0; - - //! Get the orientation of the scroller - virtual Orientation GetOrientation() = 0; - - //! Set the orientation of the scroller - virtual void SetOrientation(Orientation orientation) = 0; - - //! Get the scrollable entity - virtual AZ::EntityId GetScrollableEntity() = 0; - - //! Set the scrollable entity - virtual void SetScrollableEntity(AZ::EntityId entityId) = 0; - - //! Get the callback invoked while the value is changing - virtual ValueChangeCallback GetValueChangingCallback() = 0; - - //! Set the callback invoked while the value is changing - virtual void SetValueChangingCallback(ValueChangeCallback onChange) = 0; - - //! Get the callback invoked when the value is done changing - virtual ValueChangeCallback GetValueChangedCallback() = 0; - - //! Set the callback invoked when the value is done changing - virtual void SetValueChangedCallback(ValueChangeCallback onChange) = 0; - - //! Get the action triggered while the value is changing - virtual const LyShine::ActionName& GetValueChangingActionName() = 0; - - //! Set the action triggered while the value is changing - virtual void SetValueChangingActionName(const LyShine::ActionName& actionName) = 0; - - //! Get the action triggered when the value is done changing - virtual const LyShine::ActionName& GetValueChangedActionName() = 0; - - //! Set the action triggered when the value is done changing - virtual void SetValueChangedActionName(const LyShine::ActionName& actionName) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiScrollerInterface> UiScrollerBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that listeners need to implement in order to get notifications when values of the -//! scroller change -class UiScrollerNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiScrollerNotifications(){} - - //! Called when the scroller value (0 - 1) is changing - virtual void OnScrollerValueChanging(float value) = 0; - - //! Called when the scroller value (0 - 1) has been changed - virtual void OnScrollerValueChanged(float value) = 0; -}; - -typedef AZ::EBus<UiScrollerNotifications> UiScrollerNotificationBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that scrollables need to implement in order to get notifications when the scroller -//! changes the value -class UiScrollerToScrollableNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiScrollerToScrollableNotifications(){} - - //! Called when the scroller is changing the scroll value (0 - 1) - virtual void OnValueChangingByScroller(float value) = 0; - - //! Called when the scroller is done changing the scroll value (0 - 1) - virtual void OnValueChangedByScroller(float value) = 0; -}; - -typedef AZ::EBus<UiScrollerToScrollableNotifications> UiScrollerToScrollableNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiSliderBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiSliderBus.h deleted file mode 100644 index c6ffb68b3e..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiSliderBus.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiSliderInterface - : public AZ::ComponentBus -{ -public: // types - - //! params: sending entity id, newValue, newPosition - typedef AZStd::function<void(AZ::EntityId, float)> ValueChangeCallback; - -public: // member functions - - virtual ~UiSliderInterface() {} - - //! Query the value of the slider - //! \return The current value for the slider. - virtual float GetValue() = 0; - - //! Manually override the value of the slider - //! \param isOn The new desired value of the slider. - virtual void SetValue(float value) = 0; - - virtual float GetMinValue() = 0; - virtual void SetMinValue(float value) = 0; - virtual float GetMaxValue() = 0; - virtual void SetMaxValue(float value) = 0; - virtual float GetStepValue() = 0; - virtual void SetStepValue(float step) = 0; - - //! Get the callback invoked while the value is changing - virtual ValueChangeCallback GetValueChangingCallback() = 0; - - //! Set the callback invoked while the value is changing - virtual void SetValueChangingCallback(ValueChangeCallback onChange) = 0; - - //! Get the action triggered while the value is changing - virtual const LyShine::ActionName& GetValueChangingActionName() = 0; - - //! Set the action triggered while the value is changing - virtual void SetValueChangingActionName(const LyShine::ActionName& actionName) = 0; - - //! Get the callback invoked when the value is done changing - virtual ValueChangeCallback GetValueChangedCallback() = 0; - - //! Set the callback invoked when the value is done changing - virtual void SetValueChangedCallback(ValueChangeCallback onChange) = 0; - - //! Get the action triggered when the value is done changing - virtual const LyShine::ActionName& GetValueChangedActionName() = 0; - - //! Set the action triggered when the value is done changing - virtual void SetValueChangedActionName(const LyShine::ActionName& actionName) = 0; - - //! Set the optional track entity - virtual void SetTrackEntity(AZ::EntityId entityId) = 0; - - //! Get the optional track entity - virtual AZ::EntityId GetTrackEntity() = 0; - - //! Set the optional fill entity - virtual void SetFillEntity(AZ::EntityId entityId) = 0; - - //! Get the optional fill entity - virtual AZ::EntityId GetFillEntity() = 0; - - //! Set the optional manipulator entity - virtual void SetManipulatorEntity(AZ::EntityId entityId) = 0; - - //! Get the optional manipulator entity - virtual AZ::EntityId GetManipulatorEntity() = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiSliderInterface> UiSliderBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiSliderNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiSliderNotifications() {} - - //! Notify listeners that the slider value is changing - virtual void OnSliderValueChanging([[maybe_unused]] float value) {} - - //! Notify listeners that the slider value is done changing - virtual void OnSliderValueChanged([[maybe_unused]] float value) {} -}; - -typedef AZ::EBus<UiSliderNotifications> UiSliderNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiSpawnerBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiSpawnerBus.h deleted file mode 100644 index b0674d1c78..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiSpawnerBus.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> -#include <AzFramework/Entity/EntityContextBus.h> -#include <AzFramework/Slice/SliceInstantiationTicket.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Bus for making requests to the UiSpawnerComponent -class UiSpawnerInterface - : public AZ::ComponentBus -{ -public: - virtual ~UiSpawnerInterface() {} - - //! Spawn the selected slice at the entity's location - virtual AzFramework::SliceInstantiationTicket Spawn() = 0; - - //! Spawn the selected slice at the entity's location with the provided relative offset - virtual AzFramework::SliceInstantiationTicket SpawnRelative(const AZ::Vector2& relative) = 0; - - //! Spawn the selected slice at the specified viewport position - virtual AzFramework::SliceInstantiationTicket SpawnViewport(const AZ::Vector2& pos) { (void)pos; return AzFramework::SliceInstantiationTicket(); }; - - //! Spawn the provided slice at the entity's location - virtual AzFramework::SliceInstantiationTicket SpawnSlice(const AZ::Data::Asset<AZ::Data::AssetData>& slice) { (void)slice; return AzFramework::SliceInstantiationTicket(); }; - - //! Spawn the provided slice at the entity's location with the provided relative offset - virtual AzFramework::SliceInstantiationTicket SpawnSliceRelative(const AZ::Data::Asset<AZ::Data::AssetData>& slice, const AZ::Vector2& relative) { (void)slice; (void)relative; return AzFramework::SliceInstantiationTicket(); }; - - //! Spawn the provided slice at the specified viewport position - virtual AzFramework::SliceInstantiationTicket SpawnSliceViewport(const AZ::Data::Asset<AZ::Data::AssetData>& slice, const AZ::Vector2& pos) { (void)slice; (void)pos; return AzFramework::SliceInstantiationTicket(); }; -}; - -using UiSpawnerBus = AZ::EBus<UiSpawnerInterface>; - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Bus for notifications dispatched by the UiSpawnerComponent -//! Whenever one of the "Spawn" calls in UiSpawnerInterface is called then a listener connected -//! on this bus with the spawner entity ID will either get: -//! 1. This sequence of notifications: -//! OnSpawnBegin -//! N x OnEntitySpawned -//! OnEntitiesSpawned -//! OnTopLevelEntitiesSpawned -//! OnSpawnEnd -//! 2. In the case of a spawn error just this notification: -//! OnSpawnFailed -class UiSpawnerNotifications - : public AZ::ComponentBus -{ -public: - virtual ~UiSpawnerNotifications() {} - - //! Notify that slice has been spawned, but entities have not yet been activated. - //! OnEntitySpawned events are about to be dispatched. - virtual void OnSpawnBegin(const AzFramework::SliceInstantiationTicket& /*ticket*/) {} - - //! Notify that an entity has spawned, will be called once for each entity spawned in a slice. - virtual void OnEntitySpawned(const AzFramework::SliceInstantiationTicket& /*ticket*/, const AZ::EntityId& /*spawnedEntity*/) {} - - //! Single event notification for an entire slice spawn, providing a list of all resulting entity Ids. - virtual void OnEntitiesSpawned(const AzFramework::SliceInstantiationTicket& /*ticket*/, const AZStd::vector<AZ::EntityId>& /*spawnedEntities*/) {} - - //! Single event notification for an entire slice spawn, providing a list of all resulting top-level entity Ids. - //! Top-level entities are ones that are not the child of any other entity in the slice - virtual void OnTopLevelEntitiesSpawned(const AzFramework::SliceInstantiationTicket& /*ticket*/, const AZStd::vector<AZ::EntityId>& /*spawnedEntities*/) {} - - //! Notify that a spawn has been completed. All spawn notifications for this ticket have been dispatched. - virtual void OnSpawnEnd(const AzFramework::SliceInstantiationTicket& /*ticket*/) {} - - //! Notify that slice has failed to be spawned. - virtual void OnSpawnFailed(const AzFramework::SliceInstantiationTicket& /*ticket*/) {} -}; - -using UiSpawnerNotificationBus = AZ::EBus<UiSpawnerNotifications>; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiSystemBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiSystemBus.h deleted file mode 100644 index 8b17ca591c..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiSystemBus.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/EBus/EBus.h> -#include <AzCore/Component/Component.h> - -class UiSystemInterface - : public AZ::EBusTraits -{ -public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - // Public functions - - //! Register a component type with the UI system. - //! The order in which component types are registered is the order that they show up in - //! the add component and in the properties pane. - //! This will go away once there is a system that orders things the way we want based - //! on the existing component registration. - virtual void RegisterComponentTypeForMenuOrdering([[maybe_unused]] const AZ::Uuid& typeUuid) {} - - //! Get the UI component types registered with the UI system - //! This is a short-term solution until there is a way to get the registered components - //! from the framework in an order that we want for the menus and the properties pane - virtual const AZStd::vector<AZ::Uuid>* GetComponentTypesForMenuOrdering() = 0; - - //! We use this for metrics to find out which components are part of the LyShine Gem - virtual const AZStd::list<AZ::ComponentDescriptor*>* GetLyShineComponentDescriptors() = 0; -}; - -using UiSystemBus = AZ::EBus<UiSystemInterface>; - diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiTextBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiTextBus.h deleted file mode 100644 index 63eab929e3..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiTextBus.h +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> -#include <AzCore/Math/Color.h> -#include <LyShine/UiBase.h> -#include <LyShine/Bus/UiTransformBus.h> -#include <LyShine/IDraw2d.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiTextInterface - : public AZ::ComponentBus -{ -public: // types - - //! Callback type for retrieving displayed text. - typedef AZStd::function<AZStd::string(const AZStd::string&)> DisplayedTextFunction; - - //! Determines how text overflow should behave - enum class OverflowMode - { - OverflowText, //!< text contents aren't impacted by element size (and vice versa) - ClipText, //!< clips text contents to fit width of element - Ellipsis //!< truncates displayed text to fit element and appends ellipsis to the text - }; - - //! Provides values for determining whether text is wrapped or not - enum class WrapTextSetting - { - NoWrap, - Wrap - }; - - //! Controls whether text should shrink (scale down) to prevent overflowing. - //! - //! The amount of scale applied to text can be limited by minimum shrink scale. - enum class ShrinkToFit - { - None, //!< No shrinking is applied to text - Uniform, //!< Shrink text uniformly along X/Y dimension (maintains aspect ratio) - WidthOnly //!< Only scales text along X axis (width) - }; - - //! Determines what processing should be performed on text before returning - enum GetTextFlags - { - GetAsIs = 0, - GetLocalized = 1 << 0 - }; - - //! Determines how text should be assigned - enum SetTextFlags - { - SetAsIs = 0, - SetEscapeMarkup = 1 << 0, - SetLocalized = 1 << 1 - }; - -public: // member functions - - virtual ~UiTextInterface() {} - - //! Returns the unaltered contents of the string contained within the text component. - //! \return Unaltered string contents of this text component - virtual AZStd::string GetText() = 0; - virtual void SetText(const AZStd::string& text) = 0; - - virtual AZStd::string GetTextWithFlags(GetTextFlags flags = GetAsIs) = 0; - virtual void SetTextWithFlags(const AZStd::string& text, SetTextFlags flags = SetAsIs) = 0; - - virtual AZ::Color GetColor() = 0; - virtual void SetColor(const AZ::Color& color) = 0; - - //! Returns font object used by the displayed text. - virtual LyShine::PathnameType GetFont() = 0; - virtual void SetFont(const LyShine::PathnameType& fontPath) = 0; - - virtual int GetFontEffect() = 0; - virtual void SetFontEffect(int effectIndex) = 0; - - virtual AZStd::string GetFontEffectName(int effectIndex) = 0; - virtual void SetFontEffectByName(const AZStd::string& effectName) = 0; - - virtual float GetFontSize() = 0; - virtual void SetFontSize(float size) = 0; - - virtual void GetTextAlignment(IDraw2d::HAlign& horizontalAlignment, - IDraw2d::VAlign& verticalAlignment) = 0; - virtual void SetTextAlignment(IDraw2d::HAlign horizontalAlignment, - IDraw2d::VAlign verticalAlignment) = 0; - - virtual IDraw2d::HAlign GetHorizontalTextAlignment() = 0; - virtual void SetHorizontalTextAlignment(IDraw2d::HAlign alignment) = 0; - virtual IDraw2d::VAlign GetVerticalTextAlignment() = 0; - virtual void SetVerticalTextAlignment(IDraw2d::VAlign alignment) = 0; - - virtual float GetCharacterSpacing() = 0; - virtual void SetCharacterSpacing(float characterSpacing) = 0; - virtual float GetLineSpacing() = 0; - virtual void SetLineSpacing(float lineSpacing) = 0; - - //! Given a point in viewport space, return the character index in the string - //! \param point a point in viewport space - //! \param mustBeInBoundingBox if true the given point be be contained in the bounding box of - //! actual text characters (not the element). If false it can be anywhere (even outside the element) - //! and is projected onto a text position (for drag select for example). - //! \return -1 if second param is true and point is outside box - //! 0 if to left of first char, 1 if between first and second char, - //! length of string if to right of last char - virtual int GetCharIndexFromPoint(AZ::Vector2 point, bool mustBeInBoundingBox) = 0; - - //! Given a point in untransformed canvas space, return the character index in the string - //! \param point a point in untransformed canvas space - //! \param mustBeInBoundingBox if true the given point be be contained in the bounding box of - //! actual text characters (not the element). If false it can be anywhere (even outside the element) - //! and is projected onto a text position (for drag select for example). - //! \return -1 if second param is true and point is outside box - //! 0 if to left of first char, 1 if between first and second char, - //! length of string if to right of last char - virtual int GetCharIndexFromCanvasSpacePoint(AZ::Vector2 point, bool mustBeInBoundingBox) = 0; - - //! Returns the XY coord of the rendered character position at a given index. - //! Imagining a rect encompassing the character width and line height, - //! the returned coordinate is the upper-left corner of the rect. - //! \param index Index into displayed string. - virtual AZ::Vector2 GetPointFromCharIndex(int index) = 0; - - virtual AZ::Color GetSelectionColor() = 0; - virtual void GetSelectionRange(int& startIndex, int& endIndex) = 0; - - //! Set a range of the text string to be shown as selected - //! - //! If startIndex and endIndex are the same then a one pixel wide vertical bar is highlighted. - //! - //! The provided start and end indices are "character" indices into a UTF8 string. For - //! example, an index of 1 could actually be mapped at buffer index 2 if the first character - //! in the UTF8 string is a multi-byte character of size 2. - //! - //! \param startIndex 0 means starting at the left edge first character - //! \param endIndex if equal to UTF8 text string length that means up to the right edge of the last char - //! \param selectionColor the selection color (for box drawn behind text) - virtual void SetSelectionRange(int startIndex, int endIndex, const AZ::Color& selectionColor) = 0; - - //! Clear any text selection range that has been applied to this text - virtual void ClearSelectionRange() = 0; - - //! Get the width and height of the text - virtual AZ::Vector2 GetTextSize() = 0; - - //! Get the width of the text - virtual float GetTextWidth() = 0; - - //! Get the height of the text - virtual float GetTextHeight() = 0; - - //! Get the bounding box (in viewport space, so it can be rotated) of the given text range - //! If startIndex and endIndex are the same then a rect is still returned that is one pixel wide - //! \param startIndex 0 means starting at the first character - //! \param endIndex if equal to text string length that means including the last char - //! \param rectPoints Output parameter that gets populated with up to three RectPoints for multi-line text selection geometry. - virtual void GetTextBoundingBox(int startIndex, int endIndex, UiTransformInterface::RectPointsArray& rectPoints) = 0; - - //! Returns the function object used to manipulate a given string to condition it for rendering. - //! The default displayed text function for a UiTextComponent is pass-through (the passed string - //! is returned as-is). - virtual DisplayedTextFunction GetDisplayedTextFunction() const = 0; - - //! Allows setting a DisplayedTextFunction object to be called prior to rendering. - //! The string contents of a UiTextComponent can be modified for rendering without - //! changing the actual contents of the text component (GetText()). This functionality - //! is useful in some situations, like password hiding, where the displayed text should - //! be different from the stored text. - virtual void SetDisplayedTextFunction(const DisplayedTextFunction& displayedTextFunction) = 0; - - //! Gets the overflow behavior of this component - virtual OverflowMode GetOverflowMode() = 0; - - //! Sets the overflow setting of this component. - virtual void SetOverflowMode(OverflowMode overflowMode) = 0; - - //! Gets the text wrapping setting of this component - virtual WrapTextSetting GetWrapText() = 0; - - //! Sets the text wrapping setting of this component - virtual void SetWrapText(WrapTextSetting wrapSetting) = 0; - - //! Gets the "shrink-to-fit" value of this component - virtual ShrinkToFit GetShrinkToFit() = 0; - - //! Sets the "shrink-to-fit" value of this component - virtual void SetShrinkToFit(ShrinkToFit shrinkToFit) = 0; - - //! Typically triggered when input mechanism (keyboard vs. mouse) changes/alternates. - virtual void ResetCursorLineHint() = 0; - - //! Get whether markup is enabled. If true then the text string is parsed for XML markup. - virtual bool GetIsMarkupEnabled() = 0; - - //! Set whether markup is enabled. If true then the text string is parsed for XML markup. - virtual void SetIsMarkupEnabled(bool isEnabled) = 0; - - //! Gets the minimum shrink scale when using ShrinkToFit. - virtual float GetMinimumShrinkScale() = 0; - - //! Sets the minimum shrink scale when using ShrinkToFit. - virtual void SetMinimumShrinkScale(float minShrinkScale) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiTextInterface> UiTextBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface that describes "clickable" areas of text for a text component. -//! -//! Text components can contain anchor tags that allow user interaction with text. -//! These anchor tags define clickable areas that can be stylized (via color) and -//! provide information to listeners regarding the text. -class UiClickableTextInterface - : public AZ::ComponentBus -{ -public: // types - - //! Defines an area of interaction for clickable text, along with metadata. - struct ClickableTextRect - { - UiTransformInterface::Rect rect; //!< "Click area" for text. - - AZStd::string action; //!< "action" string from markup. - - AZStd::string data; //!< "data" string from markup. - - int id; //!< Identifier that uniquely identifies clickable text from - //!< a single anchor tag. The clickable text from markup can - //!< be word-wrapped to subsequent lines, in which case the - //!< identifier will identify all clickable text coming from - //!< a single anchor tag. This allows word-wrapped clickable - //!< text to be treated as a single clickable link, - //!< especially useful for hover/color styling. - }; - - using ClickableTextRects = AZStd::vector<ClickableTextRect>; - -public: // member functions - - virtual ~UiClickableTextInterface() {} - - //! Populates given clickable text rects for a text component. - virtual void GetClickableTextRects(UiClickableTextInterface::ClickableTextRects& clickableTextRects) = 0; - - //! Sets the drawbatch color for clickable text, given by the ID. - virtual void SetClickableTextColor(int id, const AZ::Color& color) = 0; - -public: // static member data - - //! Only one component on an entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiClickableTextInterface> UiClickableTextBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiClickableTextNotifications - : public AZ::ComponentBus -{ -public: - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const bool EnableEventQueue = true; - ////////////////////////////////////////////////////////////////////////// - -public: // member functions - - virtual ~UiClickableTextNotifications() {} - - //! Notify listeners that the text has been prepared for render. - virtual void OnClickableTextChanged() {} -}; - -typedef AZ::EBus<UiClickableTextNotifications> UiClickableTextNotificationsBus; - diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiTextInputBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiTextInputBus.h deleted file mode 100644 index 838c74bf13..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiTextInputBus.h +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Color.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiTextInputInterface - : public AZ::ComponentBus -{ -public: // types - - typedef AZStd::function<void(AZ::EntityId, const AZStd::string&)> TextInputCallback; - -public: // member functions - - virtual ~UiTextInputInterface() {} - - //! Get the color to be used for the text background when it is selected - virtual AZ::Color GetTextSelectionColor() = 0; - - //! Set the color to be used for the text background when it is selected - virtual void SetTextSelectionColor(const AZ::Color& color) = 0; - - //! Get the color to be used for the text cursor - virtual AZ::Color GetTextCursorColor() = 0; - - //! Set the color to be used for the text cursor - virtual void SetTextCursorColor(const AZ::Color& color) = 0; - - //! Get the cursor blink interval - virtual float GetCursorBlinkInterval() = 0; - - //! Set the cursor blink interval, 0 means no blink - virtual void SetCursorBlinkInterval(float interval) = 0; - - //! Get the maximum number of character allowed in the edited string - virtual int GetMaxStringLength() = 0; - - //! Set the maximum number of character allowed in the edited string - //! \param maxCharacters, a value of 0 means none allowed, -1 means no limit - virtual void SetMaxStringLength(int maxCharacters) = 0; - - //! Get the on-change callback (called when a character added/removed/changed) - virtual TextInputCallback GetOnChangeCallback() = 0; - - //! Set the on-change callback (called when a character added/removed/changed) - virtual void SetOnChangeCallback(TextInputCallback callbackFunction) = 0; - - //! Get the on-end-edit callback (called when edit of text is completed) - virtual TextInputCallback GetOnEndEditCallback() = 0; - - //! Set the on-end-edit callback (called when edit of text is completed) - virtual void SetOnEndEditCallback(TextInputCallback callbackFunction) = 0; - - //! Get the on-enter callback (called when Enter is pressed on keyboard) - virtual TextInputCallback GetOnEnterCallback() = 0; - - //! Set the on-enter callback (called when Enter is pressed on keyboard) - virtual void SetOnEnterCallback(TextInputCallback callbackFunction) = 0; - - //! Get the "change" action name, the action is sent to canvas listeners when text is changed - virtual const LyShine::ActionName& GetChangeAction() = 0; - - //! Set the "change" action name - virtual void SetChangeAction(const LyShine::ActionName& actionName) = 0; - - //! Get the "end edit" action name, the action is sent to canvas listeners when the - //! editing of the text is finished - i.e. when the text input component is no longer active - virtual const LyShine::ActionName& GetEndEditAction() = 0; - - //! Set the "end edit" action name - virtual void SetEndEditAction(const LyShine::ActionName& actionName) = 0; - - //! Get the "enter" action name, the action is sent to canvas listeners when enter is pressed - virtual const LyShine::ActionName& GetEnterAction() = 0; - - //! Set the "enter" action name - virtual void SetEnterAction(const LyShine::ActionName& actionName) = 0; - - //! Get the entity id for the text element being edited by this component - virtual AZ::EntityId GetTextEntity() = 0; - - //! Set the entity id for the text element being edited by this component - //! This must be a child of this entity - virtual void SetTextEntity(AZ::EntityId textEntity) = 0; - - //! Get the text string being edited by this component (from the text element) - virtual AZStd::string GetText() = 0; - - virtual void SetText(const AZStd::string& text) = 0; - - //! Get the entity id for the placeholder text element for this component - virtual AZ::EntityId GetPlaceHolderTextEntity() = 0; - - //! Set the entity id for the placeholder text element for this component - //! This must be a child of this entity - virtual void SetPlaceHolderTextEntity(AZ::EntityId textEntity) = 0; - - //! True if this text input is configured as a password field, false otherwise - //! - //! Password fields will render the displayed text with all of the characters - //! of the input string replaced with a character. - virtual bool GetIsPasswordField() = 0; - - //! Allows this text input to be configured as a password field. - virtual void SetIsPasswordField(bool passwordField) = 0; - - //! Returns the UTF8 character to be used to display password fields - // - //! Note that having a replacement character configured doesn't determine - //! whether this input is configured as a password field (see GetIsPasswordField). - virtual uint32_t GetReplacementCharacter() = 0; - - //! Sets the UTF8 character that should be used for displaying text in password fields. - // - //! Note that setting a replacement character doesn't determine whether this - //! text input will be used as a password field (see GetIsPasswordField). - virtual void SetReplacementCharacter(uint32_t replacementChar) = 0; - - //! True if copy/cut/paste should be supported, false otherwise - virtual bool GetIsClipboardEnabled() = 0; - - //! Allows copy/cut/paste support for this text input - virtual void SetIsClipboardEnabled(bool enableClipboard) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiTextInputInterface> UiTextInputBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiTextInputNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiTextInputNotifications() {} - - //! Called when a character added/removed/change - virtual void OnTextInputChange([[maybe_unused]] const AZStd::string& textString) {} - - //! Called when edit of text is completed - virtual void OnTextInputEndEdit([[maybe_unused]] const AZStd::string& textString) {} - - //! Called when Enter is pressed on keyboard - virtual void OnTextInputEnter([[maybe_unused]] const AZStd::string& textString) {} -}; - -typedef AZ::EBus<UiTextInputNotifications> UiTextInputNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiTooltipBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiTooltipBus.h deleted file mode 100644 index 7446e93ce8..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiTooltipBus.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that a tooltip component needs to implement. A tooltip component provides -//! data that is assigned to a tooltip display element -class UiTooltipInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiTooltipInterface() {} - - //! Get the tooltip text - virtual AZStd::string GetText() = 0; - - //! Set the tooltip text - virtual void SetText(const AZStd::string& text) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiTooltipInterface> UiTooltipBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiTooltipDataPopulatorBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiTooltipDataPopulatorBus.h deleted file mode 100644 index ce0c96b417..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiTooltipDataPopulatorBus.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that a tooltip component needs to implement. A tooltip component populates -//! a tooltip display element with data -class UiTooltipDataPopulatorInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiTooltipDataPopulatorInterface() {} - - //! Assign data to the specified tooltip display element - virtual void PushDataToDisplayElement(AZ::EntityId displayEntityId) = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiTooltipDataPopulatorInterface> UiTooltipDataPopulatorBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiTooltipDisplayBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiTooltipDisplayBus.h deleted file mode 100644 index c717f37a0e..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiTooltipDisplayBus.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that a tooltip display component needs to implement. A tooltip display -//! component is responsible for displaying an element as a tooltip given sizing and positioning -//! properties -class UiTooltipDisplayInterface - : public AZ::ComponentBus -{ -public: // types - - enum class AutoPositionMode - { - OffsetFromMouse, - OffsetFromElement - }; - - enum class TriggerMode - { - OnHover, - OnPress, - OnClick - }; - -public: // member functions - - virtual ~UiTooltipDisplayInterface() {} - - //! Get the way the tooltip is triggered to display - virtual TriggerMode GetTriggerMode() = 0; - - //! Set the way the tooltip is triggered to display - virtual void SetTriggerMode(TriggerMode triggerMode) = 0; - - //! Get whether the tooltip display element will be auto positioned - virtual bool GetAutoPosition() = 0; - - //! Set whether the tooltip display element will be auto positioned - virtual void SetAutoPosition(bool autoPosition) = 0; - - //! Get auto position mode - virtual AutoPositionMode GetAutoPositionMode() = 0; - - //! Set auto position mode - virtual void SetAutoPositionMode(AutoPositionMode autoPositionMode) = 0; - - //! Get the offset from the tooltip display element's pivot to the mouse position - virtual const AZ::Vector2& GetOffset() = 0; - - //! Set the offset from the tooltip display element's pivot to the mouse position - virtual void SetOffset(const AZ::Vector2& offset) = 0; - - //! Get whether the tooltip display element should be resized so that the text element - //! size matches the size of the string - virtual bool GetAutoSize() = 0; - - //! Set whether the tooltip display element should be resized so that the text element - //! size matches the size of the string - virtual void SetAutoSize(bool autoSize) = 0; - - //! Get the entity id of the text element that is used for resizing - virtual AZ::EntityId GetTextEntity() = 0; - - //! Set the entity id of the text element that is used for resizing - //! This must be a child of this entity - virtual void SetTextEntity(AZ::EntityId textEntity) = 0; - - //! Get the amount of time to wait before showing the tooltip display element after hover start - virtual float GetDelayTime() = 0; - - //! Set the amount of time to wait before showing the tooltip display element after hover start - virtual void SetDelayTime(float delayTime) = 0; - - //! Get the amount of time the tooltip display element is to remain visible - virtual float GetDisplayTime() = 0; - - //! Set the amount of time the tooltip display element is to remain visible - virtual void SetDisplayTime(float displayTime) = 0; - - //! Show the tooltip display element - virtual void PrepareToShow(AZ::EntityId tooltipElement) = 0; - - //! Hide the tooltip display element - virtual void Hide() = 0; - - //! Update the tooltip display element - virtual void Update() = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiTooltipDisplayInterface> UiTooltipDisplayBus; - -//! Interface class that listeners need to implement to be notified of tooltip display events -class UiTooltipDisplayNotifications - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiTooltipDisplayNotifications() {} - - //! Called on tooltip display state changes - virtual void OnShowing() {}; - virtual void OnShown() {}; - virtual void OnHiding() {}; - virtual void OnHidden() {}; -}; - -typedef AZ::EBus<UiTooltipDisplayNotifications> UiTooltipDisplayNotificationBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiTransform2dBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiTransform2dBus.h deleted file mode 100644 index bdaa384ff0..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiTransform2dBus.h +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/Vector2.h> -#include <LyShine/Bus/UiTransformBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiTransform2dInterface - : public AZ::ComponentBus -{ -public: // types - - // Anchors members are always in range 0-1, they are normalized positions within the parent elements bounds - struct Anchors - { - AZ_TYPE_INFO(Anchors, "{65D4346C-FB16-4CB0-9BDC-1185B122C4A9}") - - Anchors() - : m_left(0.5f) - , m_top(0.5f) - , m_right(0.5f) - , m_bottom(0.5f) {} - - Anchors(float left, float top, float right, float bottom) - : m_left(left) - , m_top(top) - , m_right(right) - , m_bottom(bottom) {} - - float m_left; - float m_top; - float m_right; - float m_bottom; - - void UnitClamp() - { - m_left = FClamp(m_left, 0.0f, 1.0f); - m_top = FClamp(m_top, 0.0f, 1.0f); - m_right = FClamp(m_right, 0.0f, 1.0f); - m_bottom = FClamp(m_bottom, 0.0f, 1.0f); - } - - bool operator==(const Anchors& rhs) const - { - return (m_left == rhs.m_left && - m_right == rhs.m_right && - m_top == rhs.m_top && - m_bottom == rhs.m_bottom); - } - - bool operator!=(const Anchors& rhs) const - { - return !(*this == rhs); - } - }; - - // Offsets are in pixels or physical units and are offsets from the anchors - // The left offset is the offset from the left anchor to the left edge of this UiElement - struct Offsets - { - AZ_TYPE_INFO(Offsets, "{F681BA9D-245C-4630-B20E-05DD752FAD57}") - - Offsets() - : m_left(-50) - , m_top(-50) - , m_right(50) - , m_bottom(50) {} - - Offsets(float left, float top, float right, float bottom) - : m_left(left) - , m_top(top) - , m_right(right) - , m_bottom(bottom) {} - - float m_left; - float m_top; - float m_right; - float m_bottom; - - Offsets& operator+=(const UiTransformInterface::RectPoints& rhs) - { - m_left += rhs.TopLeft().GetX(); - m_right += rhs.BottomRight().GetX(); - m_top += rhs.TopLeft().GetY(); - m_bottom += rhs.BottomRight().GetY(); - - return *this; - } - - Offsets operator+(const UiTransformInterface::RectPoints& rhs) const - { - Offsets result(*this); - - result.m_left += rhs.TopLeft().GetX(); - result.m_right += rhs.BottomRight().GetX(); - result.m_top += rhs.TopLeft().GetY(); - result.m_bottom += rhs.BottomRight().GetY(); - - return result; - } - - Offsets& operator+=(const AZ::Vector2& rhs) - { - m_left += rhs.GetX(); - m_right += rhs.GetX(); - m_top += rhs.GetY(); - m_bottom += rhs.GetY(); - - return *this; - } - - Offsets operator+(const AZ::Vector2& rhs) const - { - Offsets result(*this); - - result.m_left += rhs.GetX(); - result.m_right += rhs.GetX(); - result.m_top += rhs.GetY(); - result.m_bottom += rhs.GetY(); - - return result; - } - - bool operator==(const Offsets& rhs) const - { - return (m_left == rhs.m_left && - m_right == rhs.m_right && - m_top == rhs.m_top && - m_bottom == rhs.m_bottom); - } - - bool operator!=(const Offsets& rhs) const - { - return !(*this == rhs); - } - }; - -public: // member functions - - virtual ~UiTransform2dInterface() {} - - //! Get the anchors for the element - virtual Anchors GetAnchors() = 0; - - //! Set the anchors for the element - //! \param adjustOffsets If true the offsets are adjusted to keep the rect in the same position - //! \param allowPush Only has effect if the anchors are invalid. If true changing an anchor - // to overlap its opposite anchor, will move the opposite anchor - virtual void SetAnchors(Anchors anchors, bool adjustOffsets, bool allowPush) = 0; - - //! Get the offsets for the element - virtual Offsets GetOffsets() = 0; - - //! Set the offsets for the element - virtual void SetOffsets(Offsets offsets) = 0; - - //! Set the pivot and adjust the offsets to stay in same place - virtual void SetPivotAndAdjustOffsets(AZ::Vector2 pivot) = 0; - - //! Modify left and right offsets relative the element's anchors - virtual void SetLocalWidth(float width) = 0; - - //! Get the height of the element based off it's offsets - virtual float GetLocalWidth() = 0; - - //! Modify top and bottom offsets relative the element's anchors - virtual void SetLocalHeight(float height) = 0; - - //! Get the height of the element based off it's offsets - virtual float GetLocalHeight() = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiTransform2dInterface> UiTransform2dBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiTransformBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiTransformBus.h deleted file mode 100644 index 0f316c334c..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiTransformBus.h +++ /dev/null @@ -1,549 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/Math/MathUtils.h> -#include <AzCore/Math/Vector2.h> -#include <AzCore/Math/Vector3.h> -#include <AzCore/Math/Matrix4x4.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -// The UiTransformInterface provides an abstract bus interface for UI components that define the -// position and size of a UI element. -class UiTransformInterface - : public AZ::ComponentBus -{ -public: // types - - //! Struct that stores the 4 points of a (transformed) rectangle and provides access either as an array or via access functions - struct RectPoints - { - enum Corner // can be used as an index into RectPoints pt array but access via member functions preferred - { - Corner_TopLeft, - Corner_TopRight, - Corner_BottomRight, - Corner_BottomLeft, - - Corner_Count - }; - - AZ::Vector2 pt[Corner_Count]; // in clockwise order: top left, top right, bottom right, bottom left - - RectPoints(); - RectPoints(float left, float right, float top, float bottom); - - AZ::Vector2& TopLeft(); - const AZ::Vector2& TopLeft() const; - - AZ::Vector2& TopRight(); - const AZ::Vector2& TopRight() const; - - AZ::Vector2& BottomRight(); - const AZ::Vector2& BottomRight() const; - - AZ::Vector2& BottomLeft(); - const AZ::Vector2& BottomLeft() const; - - AZ::Vector2 GetCenter() const; - - AZ::Vector2 GetAxisAlignedSize() const; - AZ::Vector2 GetAxisAlignedTopLeft() const; - AZ::Vector2 GetAxisAlignedTopRight() const; - AZ::Vector2 GetAxisAlignedBottomRight() const; - AZ::Vector2 GetAxisAlignedBottomLeft() const; - void SetAxisAligned(float left, float right, float top, float bottom); - - RectPoints Transform(AZ::Matrix4x4& transform) const; - RectPoints operator-(const RectPoints& rhs) const; - }; - - using RectPointsArray = AZStd::vector < UiTransformInterface::RectPoints >; - - //! Struct that stores the bounds of an axis-aligned rectangle - struct Rect - { - float left; - float right; - float top; - float bottom; - - void Set(float l, float r, float t, float b); - - float GetWidth() const; - float GetHeight() const; - - float GetCenterX(); - float GetCenterY(); - - AZ::Vector2 GetSize() const; - AZ::Vector2 GetCenter(); - - void MoveBy(AZ::Vector2 offset); - - RectPoints GetPoints(); - - bool operator==(const Rect& rhs) const; - - bool operator!=(const Rect& rhs) const; - }; - - //! Enum used as a parameter to SetRecomputeFlags - enum class Recompute - { - RectOnly, //!< Only the rect (offsets or anchors for example) changed (this may affect transform if local scale or rotation) - TransformOnly, //!< Only the transform changed (canvas and viewport transforms must be recomputed) - ViewportTransformOnly, //!< Only the viewport transform changed (viewport transform must be recomputed) - RectAndTransform //!< Both rect and transform changed (all cached data must be recomputed) - }; - - //! Enum used as a parameter to SetScaleToDeviceMode - //! The value determines how an element is scaled when the canvas reference size and actual size are different - //! The comments below reference the canvas's "deviceScale". The deviceScale is target (actual) canvas size divided the reference canvas size - enum class ScaleToDeviceMode - { - None, //!< Default, this element is not affected by device resolution changes - UniformScaleToFit, //!< Apply a uniform scale which is the minimum of deviceScale.x and deviceScale.y - UniformScaleToFill, //!< Apply a uniform scale which is the maximum of deviceScale.x and deviceScale.y - UniformScaleToFitX, //!< Apply a uniform scale of deviceScale.x - UniformScaleToFitY, //!< Apply a uniform scale of deviceScale.y - NonUniformScale, //!< Apply a non-uniform scale which is simply deviceScale - ScaleXOnly, //!< Scale the element only in the X dimension by deviceScale.x - ScaleYOnly //!< Scale the element only in the Y dimension by deviceScale.y - }; - -public: // member functions - - virtual ~UiTransformInterface() {} - - //////////////////////////////////////////////////////////////////////////////////////////////////// - // Methods to get and set the properties of the transform component - //////////////////////////////////////////////////////////////////////////////////////////////////// - - //! Get the rotation about the Z axis - virtual float GetZRotation() = 0; - - //! Set the rotation about the Z axis - virtual void SetZRotation(float rotation) = 0; - - //! Get the scale - virtual AZ::Vector2 GetScale() = 0; - - //! Set the scale - virtual void SetScale(AZ::Vector2 scale) = 0; - - //! Get the scale X - virtual float GetScaleX() = 0; - - //! Set the scale X - virtual void SetScaleX(float scale) = 0; - - //! Get the scale Y - virtual float GetScaleY() = 0; - - //! Set the scale Y - virtual void SetScaleY(float scale) = 0; - - //! Get the pivot point for the element - virtual AZ::Vector2 GetPivot() = 0; - - //! Set the pivot point for the element - virtual void SetPivot(AZ::Vector2 pivot) = 0; - - //! Get the pivot point for the element - virtual float GetPivotX() = 0; - - //! Set the pivot point for the element - virtual void SetPivotX(float pivot) = 0; - - //! Get the pivot point for the element - virtual float GetPivotY() = 0; - - //! Set the pivot point for the element - virtual void SetPivotY(float pivot) = 0; - - //! Get how the element and all its children will be scaled to allow for the difference - //! between the authored canvas size and the actual viewport size. - virtual ScaleToDeviceMode GetScaleToDeviceMode() = 0; - - //! Set how the element and all its children will be scaled to allow for the difference - //! between the authored canvas size and the actual viewport size. - virtual void SetScaleToDeviceMode(ScaleToDeviceMode scaleToDeviceMode) = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////// - // Methods to get data in viewport space - // - // Viewport space is a 1-1 mapping to whatever viewport the UI canvas is being rendered to. - // A position in viewport space is an offset in pixels from the top left of the viewport. - //////////////////////////////////////////////////////////////////////////////////////////////////// - - //! Get the four points defining the rectangle of this element, in viewport space pixel coords - virtual void GetViewportSpacePoints(RectPoints& points) = 0; - - //! Get the pivot for this element in viewport space - virtual AZ::Vector2 GetViewportSpacePivot() = 0; - - //! Get the transform matrix to transform from canvas (noScaleRotate) space to viewport space - virtual void GetTransformToViewport(AZ::Matrix4x4& mat) = 0; - - //! Get the transform matrix to transform from viewport space to canvas (noScaleRotate) space - virtual void GetTransformFromViewport(AZ::Matrix4x4& mat) = 0; - - //! Apply the "to viewport" transform to the given points - virtual void RotateAndScalePoints(RectPoints& points) = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////// - // Methods to get data in canvas space - // - // Often canvas space and viewport space are the same thing. For example if a canvas is being - // displayed full screen. - // However, in other cases they are different. For example in the UI editor when Zoom and Pan allow - // the canvas to be moved around in the viewport. In that case an offset of 1 does not mean 1 pixel - // in the viewport. Canvas space is defined by the canvas size stored in the canvas. - //////////////////////////////////////////////////////////////////////////////////////////////////// - - //! Get the four points defining the rectangle of this element, in canvas space coords - virtual void GetCanvasSpacePoints(RectPoints& points) = 0; - - //! Get the pivot for this element in canvas space - virtual AZ::Vector2 GetCanvasSpacePivot() = 0; - - //! Get the transform matrix to transform from canvasNoScaleRotate space to canvas space - virtual void GetTransformToCanvasSpace(AZ::Matrix4x4& mat) = 0; - - //! Get the transform matrix to transform from canvas space to canvasNoScaleRotate space - virtual void GetTransformFromCanvasSpace(AZ::Matrix4x4& mat) = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////// - // Methods to get data in unrotated and unscaled canvas space (CanvasNoScaleRotate space) - // - // CanvasNoScaleRotate space is like canvas space but without any of the rotation or scaling in - // any of the elments applied. So if none of the elements in the canvas have scale or rotation - // the two are the same. - // - // CanvasNoScaleRotate space is like local space for an element but it does include all of the - // parent's anchor and offset calculations so it is not really local space. - // - // This is a useful space to do calculations in because all elements are axis aligned and their - // rectangle can be represented by a Rect struct rather requiring a RectPoints struct. - //////////////////////////////////////////////////////////////////////////////////////////////////// - - //! Get the axis-aligned rect for the element without accounting for rotation or scale - virtual void GetCanvasSpaceRectNoScaleRotate(Rect& rect) = 0; - - //! Get the rect points for the element without accounting for rotation or scale - virtual void GetCanvasSpacePointsNoScaleRotate(RectPoints& points) = 0; - - //! Get the size for the element without accounting for rotation or scale - virtual AZ::Vector2 GetCanvasSpaceSizeNoScaleRotate() = 0; - - //! Get the pivot for the element without accounting for rotation or scale - virtual AZ::Vector2 GetCanvasSpacePivotNoScaleRotate() = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////// - // Methods to get data in/about local space - //////////////////////////////////////////////////////////////////////////////////////////////////// - - //! Get the transform matrix to apply this element's rotation and scale about pivot - virtual void GetLocalTransform(AZ::Matrix4x4& mat) = 0; - - //! Get the transform matrix to apply the inverse of this element's rotation and scale about pivot - virtual void GetLocalInverseTransform(AZ::Matrix4x4& mat) = 0; - - //! Test whether this transform component has any scale or rotation - virtual bool HasScaleOrRotation() = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////// - // Methods to get/set the element's position - //////////////////////////////////////////////////////////////////////////////////////////////////// - - //! Get the position for this element in viewport space (same as GetViewportSpacePivot) - virtual AZ::Vector2 GetViewportPosition() = 0; - - //! Set the position for this element in viewport space - virtual void SetViewportPosition(const AZ::Vector2& position) = 0; - - //! Get the position for this element in canvas space (same as GetCanvasSpacePivot) - virtual AZ::Vector2 GetCanvasPosition() = 0; - - //! Set the position for this element in canvas space - virtual void SetCanvasPosition(const AZ::Vector2& position) = 0; - - //! Get the position for this element relative to the center of the element's anchors - virtual AZ::Vector2 GetLocalPosition() = 0; - - //! Set the position for this element relative to the center of the element's anchors - virtual void SetLocalPosition(const AZ::Vector2& position) = 0; - - //! Get the X position for this element relative to the center of the element's anchors - virtual float GetLocalPositionX() = 0; - - //! Set the X position for this element relative to the center of the element's anchors - virtual void SetLocalPositionX(float position) = 0; - - //! Get the Y position for this element relative to the center of the element's anchors - virtual float GetLocalPositionY() = 0; - - //! Set the Y position for this element relative to the center of the element's anchors - virtual void SetLocalPositionY(float position) = 0; - - //! Move this element in viewport space - virtual void MoveViewportPositionBy(const AZ::Vector2& offset) = 0; - - //! Move this element in canvas space - virtual void MoveCanvasPositionBy(const AZ::Vector2& offset) = 0; - - //! Move this element relative to the center of the element's anchors - virtual void MoveLocalPositionBy(const AZ::Vector2& offset) = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////// - // Query functions - //////////////////////////////////////////////////////////////////////////////////////////////////// - - //! Test if the given point (in viewport space) is in the rectangle of this element - virtual bool IsPointInRect(AZ::Vector2 point) = 0; - - //! Test if the given rect (in viewport space) is in the rectangle of this element - virtual bool BoundsAreOverlappingRect(const AZ::Vector2& bound0, const AZ::Vector2& bound1) = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////// - // Optimization and caching - //////////////////////////////////////////////////////////////////////////////////////////////////// - - //! Set the required dirty flags for the cached transforms and rect on this element and all its children - virtual void SetRecomputeFlags(Recompute recompute) = 0; - - //////////////////////////////////////////////////////////////////////////////////////////////////// - // Canvas space rect change - //////////////////////////////////////////////////////////////////////////////////////////////////// - - //! Get whether the canvas space rect has changed since the last call to NotifyAndResetCanvasSpaceRectChange. - //! May trigger a recompute of the rect if the recompute flag is dirty - virtual bool HasCanvasSpaceRectChanged() = 0; - - //! Get whether the canvas space size has changed since the last call to NotifyAndResetCanvasSpaceRectChange. - //! May trigger a recompute of the rect if the recompute flag is dirty - virtual bool HasCanvasSpaceSizeChanged() = 0; - - //! Get whether the canvas space rect was changed due to initialization - virtual bool HasCanvasSpaceRectChangedByInitialization() = 0; - - //! Send notification of canvas space rect change and reset to unchanged - virtual void NotifyAndResetCanvasSpaceRectChange() = 0; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiTransformInterface> UiTransformBus; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Interface class that listeners need to implement -class UiTransformChangeNotification - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiTransformChangeNotification(){} - - //! Called when an entity's transform (canvas space) has been modified - virtual void OnCanvasSpaceRectChanged(AZ::EntityId entityId, const UiTransformInterface::Rect& oldRect, const UiTransformInterface::Rect& newRect) = 0; - - //! Called when an entity's transform (viewport space) has been modified - virtual void OnTransformToViewportChanged() {} -}; - -typedef AZ::EBus<UiTransformChangeNotification> UiTransformChangeNotificationBus; - - -//////////////////////////////////////////////////////////////////////////////////////////////////// -// RectPoints inline methods -//////////////////////////////////////////////////////////////////////////////////////////////////// - -inline UiTransformInterface::RectPoints::RectPoints() -{ -} - -inline UiTransformInterface::RectPoints::RectPoints(float left, float right, float top, float bottom) -{ - SetAxisAligned(left, right, top, bottom); -} - -inline AZ::Vector2& UiTransformInterface::RectPoints::TopLeft() -{ - return pt[Corner_TopLeft]; -} - -inline const AZ::Vector2& UiTransformInterface::RectPoints::TopLeft() const -{ - return pt[Corner_TopLeft]; -} - -inline AZ::Vector2& UiTransformInterface::RectPoints::TopRight() -{ - return pt[Corner_TopRight]; -} - -inline const AZ::Vector2& UiTransformInterface::RectPoints::TopRight() const -{ - return pt[Corner_TopRight]; -} - -inline AZ::Vector2& UiTransformInterface::RectPoints::BottomRight() -{ - return pt[Corner_BottomRight]; -} - -inline const AZ::Vector2& UiTransformInterface::RectPoints::BottomRight() const -{ - return pt[Corner_BottomRight]; -} - -inline AZ::Vector2& UiTransformInterface::RectPoints::BottomLeft() -{ - return pt[Corner_BottomLeft]; -} - -inline const AZ::Vector2& UiTransformInterface::RectPoints::BottomLeft() const -{ - return pt[Corner_BottomLeft]; -} - -inline AZ::Vector2 UiTransformInterface::RectPoints::GetCenter() const -{ - return ((GetAxisAlignedTopLeft() + GetAxisAlignedBottomRight()) * 0.5f); -} - -inline AZ::Vector2 UiTransformInterface::RectPoints::GetAxisAlignedSize() const -{ - return AZ::Vector2(BottomRight().GetX() - TopLeft().GetX(), BottomRight().GetY() - TopLeft().GetY()); -} - -inline AZ::Vector2 UiTransformInterface::RectPoints::GetAxisAlignedTopLeft() const -{ - return AZ::Vector2(min(min(min(TopLeft().GetX(), TopRight().GetX()), BottomRight().GetX()), BottomLeft().GetX()), - min(min(min(TopLeft().GetY(), TopRight().GetY()), BottomRight().GetY()), BottomLeft().GetY())); -} - -inline AZ::Vector2 UiTransformInterface::RectPoints::GetAxisAlignedTopRight() const -{ - return AZ::Vector2(max(max(max(TopLeft().GetX(), TopRight().GetX()), BottomRight().GetX()), BottomLeft().GetX()), - min(min(min(TopLeft().GetY(), TopRight().GetY()), BottomRight().GetY()), BottomLeft().GetY())); -} - -inline AZ::Vector2 UiTransformInterface::RectPoints::GetAxisAlignedBottomRight() const -{ - return AZ::Vector2(max(max(max(TopLeft().GetX(), TopRight().GetX()), BottomRight().GetX()), BottomLeft().GetX()), - max(max(max(TopLeft().GetY(), TopRight().GetY()), BottomRight().GetY()), BottomLeft().GetY())); -} - -inline AZ::Vector2 UiTransformInterface::RectPoints::GetAxisAlignedBottomLeft() const -{ - return AZ::Vector2(min(min(min(TopLeft().GetX(), TopRight().GetX()), BottomRight().GetX()), BottomLeft().GetX()), - max(max(max(TopLeft().GetY(), TopRight().GetY()), BottomRight().GetY()), BottomLeft().GetY())); -} - -inline void UiTransformInterface::RectPoints::SetAxisAligned(float left, float right, float top, float bottom) -{ - pt[Corner_TopLeft] = AZ::Vector2(left, top); - pt[Corner_TopRight] = AZ::Vector2(right, top); - pt[Corner_BottomRight] = AZ::Vector2(right, bottom); - pt[Corner_BottomLeft] = AZ::Vector2(left, bottom); -} - -inline UiTransformInterface::RectPoints UiTransformInterface::RectPoints::Transform(AZ::Matrix4x4& transform) const -{ - RectPoints result; - for (int i = 0; i < Corner_Count; ++i) - { - AZ::Vector3 point3(pt[i].GetX(), pt[i].GetY(), 0.0f); - point3 = transform * point3; - result.pt[i] = AZ::Vector2(point3.GetX(), point3.GetY()); - } - return result; -} - -inline UiTransformInterface::RectPoints UiTransformInterface::RectPoints::operator-(const RectPoints& rhs) const -{ - RectPoints result(*this); - for (int i = 0; i < Corner_Count; ++i) - { - result.pt[i] -= rhs.pt[i]; - } - return result; -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// -// Rect inline methods -//////////////////////////////////////////////////////////////////////////////////////////////////// - -inline void UiTransformInterface::Rect::Set(float l, float r, float t, float b) -{ - left = l; - right = r; - top = t; - bottom = b; -} - -inline float UiTransformInterface::Rect::GetWidth() const -{ - return right - left; -} - -inline float UiTransformInterface::Rect::GetHeight() const -{ - return bottom - top; -} - -inline float UiTransformInterface::Rect::GetCenterX() -{ - return (left + right) * 0.5f; -} - -inline float UiTransformInterface::Rect::GetCenterY() -{ - return (top + bottom) * 0.5f; -} - -inline AZ::Vector2 UiTransformInterface::Rect::GetSize() const -{ - return AZ::Vector2(GetWidth(), GetHeight()); -} - -inline AZ::Vector2 UiTransformInterface::Rect::GetCenter() -{ - return AZ::Vector2(GetCenterX(), GetCenterY()); -} - -inline void UiTransformInterface::Rect::MoveBy(AZ::Vector2 offset) -{ - left += offset.GetX(); - right += offset.GetX(); - top += offset.GetY(); - bottom += offset.GetY(); -} - -inline UiTransformInterface::RectPoints UiTransformInterface::Rect::GetPoints() -{ - return UiTransformInterface::RectPoints(left, right, top, bottom); -} - -inline bool UiTransformInterface::Rect::operator==(const Rect& rhs) const -{ - return left == rhs.left - && right == rhs.right - && top == rhs.top - && bottom == rhs.bottom; -} - -inline bool UiTransformInterface::Rect::operator!=(const Rect& rhs) const -{ - return !(*this == rhs); -} diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/UiVisualBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/UiVisualBus.h deleted file mode 100644 index a8a9987044..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/UiVisualBus.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <LyShine/Bus/UiImageBus.h> -#include <AzCore/Math/Color.h> -#include <IFont.h> - -// Forward declarations -class ISprite; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -class UiVisualInterface - : public AZ::ComponentBus -{ -public: // member functions - - virtual ~UiVisualInterface() {} - - //! Reset the overrides, used when setting interactable states - virtual void ResetOverrides() = 0; - - //! Set the override color, used for interactable states - virtual void SetOverrideColor(const AZ::Color& color) = 0; - - //! Set the override alpha, used for interactable states - virtual void SetOverrideAlpha(float alpha) = 0; - - //! Set the override sprite, if this visual component uses a sprite this will override it - //! \param sprite If null the sprite on the visual component will not be overridden - //! \param cellIndex This value will be ignored if the given sprite isn't a sprite-sheet spritetype. - virtual void SetOverrideSprite([[maybe_unused]] ISprite* sprite, [[maybe_unused]] AZ::u32 cellIndex) {}; - - //! Set the override font, if this visual component uses a font this will override it - //! \param font If null the font on the visual component will not be overridden - virtual void SetOverrideFont(FontFamilyPtr fontFamily) {}; - - //! Set the override font effect, if this visual component uses a font this will override it - virtual void SetOverrideFontEffect([[maybe_unused]] unsigned int fontEffectIndex) {}; - -public: // static member data - - //! Only one component on a entity can implement the events - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; -}; - -typedef AZ::EBus<UiVisualInterface> UiVisualBus; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/World/UiCanvasOnMeshBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/World/UiCanvasOnMeshBus.h deleted file mode 100644 index 5928562ccb..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/World/UiCanvasOnMeshBus.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzFramework/Input/Channels/InputChannel.h> -#include <Cry_Math.h> - -struct ray_hit; - -namespace AzFramework -{ - namespace RenderGeometry - { - struct RayResult; - } -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// -// UiCanvasOnMeshBus -class UiCanvasOnMeshInterface - : public AZ::ComponentBus -{ -public: - virtual ~UiCanvasOnMeshInterface() {} - - - //! Convert the input ray collision into a canvas space position and pass the event and that position - //! to the UI canvas to handle as a positional input event - //! \return true if the event was handled - virtual bool ProcessHitInputEvent(const AzFramework::InputChannel::Snapshot& inputSnapshot, const AzFramework::RenderGeometry::RayResult& rayResult) = 0; -}; - -using UiCanvasOnMeshBus = AZ::EBus<UiCanvasOnMeshInterface>; diff --git a/Code/CryEngine/CryCommon/LyShine/Bus/World/UiCanvasRefBus.h b/Code/CryEngine/CryCommon/LyShine/Bus/World/UiCanvasRefBus.h deleted file mode 100644 index 2ad0ca218f..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/Bus/World/UiCanvasRefBus.h +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! UiCanvasRefBus -//! Allows a reference to a UI Canvas entity (which is loaded from a .uicanvas asset file) to -//! associated with a component entity in the level. -//! This is used for convenience by flow graph nodes and also for supprting rendering UI -//! canvases in the 3D world on a component entity. -class UiCanvasRefInterface - : public AZ::ComponentBus -{ -public: - virtual ~UiCanvasRefInterface() {} - - //! Get the UI canvas associated with this entity - virtual AZ::EntityId GetCanvas() = 0; -}; - -using UiCanvasRefBus = AZ::EBus<UiCanvasRefInterface>; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! UiCanvasRefNotificationBus -//! Clients can connect to this bus to receive notifications of when the canvas reference -//! in a UiCanvasRef changes to a different canvas -class UiCanvasRefNotifications - : public AZ::ComponentBus -{ -public: - virtual ~UiCanvasRefNotifications() {} - - //! Called when the canvas referenced by a canvas ref component changes - //! This can happen through a load, unload or set - virtual void OnCanvasRefChanged([[maybe_unused]] AZ::EntityId uiCanvasRefEntity, [[maybe_unused]] AZ::EntityId uiCanvasEntity) {} -}; - -using UiCanvasRefNotificationBus = AZ::EBus<UiCanvasRefNotifications>; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! UiCanvasAssetRefBus -//! Allows loading and unloading of a UI canvas asset using a pathname stored in a component on -//! an entity in the level. -class UiCanvasAssetRefInterface - : public AZ::ComponentBus -{ -public: - virtual ~UiCanvasAssetRefInterface() {} - - //! Get the canvas pathname. This is the pathname of the canvas that this component - //! will load (either on activate or when told to load by the LoadCanvas method) - //! The Canvas pathname can be empty and the associated canvas can be set via SetCanvas - virtual AZStd::string GetCanvasPathname() = 0; - - //! Set the canvas pathname - virtual void SetCanvasPathname(const AZStd::string& pathname) = 0; - - //! Get the flag indicating whether this component will automatically load the canvas - virtual bool GetIsAutoLoad() = 0; - - //! Set the flag indicating whether this component will automatically load the canvas - virtual void SetIsAutoLoad(bool isAutoLoad) = 0; - - //! Get the flag indicating whether the canvas should be loaded in a disabled state - virtual bool GetShouldLoadDisabled() = 0; - - //! Set the flag indicating whether the canvas should be loaded in a disabled state - virtual void SetShouldLoadDisabled(bool shouldLoadDisabled) = 0; - - //! Load the UI canvas using the stored asset ref - virtual AZ::EntityId LoadCanvas() = 0; - - //! Unload the UI canvas using the stored asset ref (if it is owned by this component) - virtual void UnloadCanvas() = 0; -}; - -using UiCanvasAssetRefBus = AZ::EBus<UiCanvasAssetRefInterface>; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! UiCanvasAssetRefNotificationBus -//! Clients can connect to this bus to receive notifications of when a canvas is loaded into -//! a canvas ref component on an entity -class UiCanvasAssetRefNotifications - : public AZ::ComponentBus -{ -public: - virtual ~UiCanvasAssetRefNotifications() {} - - //! Called when the canvas ref loads a UI canvas - virtual void OnCanvasLoadedIntoEntity([[maybe_unused]] AZ::EntityId uiCanvasEntity) {} -}; - -using UiCanvasAssetRefNotificationBus = AZ::EBus<UiCanvasAssetRefNotifications>; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! UiCanvasProxyRefBus -//! Allows an entity in a level to share a reference to a UI canvas that was loaded into another -//! UiCanvasRef. -//! This bus is only needed to allow two entities in the world to use the same instance of a -//! UI canvas asset. -class UiCanvasProxyRefInterface - : public AZ::ComponentBus -{ -public: - virtual ~UiCanvasProxyRefInterface() {} - - //! Set the entity that is managing the UI canvas for this proxy - //! This will cause the OnCanvasRefChanged event to be sent to any UiCanvasRefNotifications - virtual void SetCanvasRefEntity(AZ::EntityId canvasAssetRefEntity) = 0; -}; - -using UiCanvasProxyRefBus = AZ::EBus<UiCanvasProxyRefInterface>; - diff --git a/Code/CryEngine/CryCommon/LyShine/IDraw2d.h b/Code/CryEngine/CryCommon/LyShine/IDraw2d.h deleted file mode 100644 index 68eee0ce34..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/IDraw2d.h +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Math/Vector2.h> -#include <AzCore/Math/Vector3.h> -#include <AzCore/Math/Color.h> - -// Forward declarations -struct IFFont; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Class for 2D drawing in screen space -// -//! The IDraw2d interface allows drawing images and text in 2D. -//! Positions and sizes are specified in pixels in the current 2D viewport. -//! The BeginDraw2d method should be called before calling the Draw methods to enter 2D mode -//! and the EndDraw2d method should be called after calling the Draw methods to exit 2D mode. -//! There is a helper class Draw2dHelper that encapsulates this in its constructor and destructor. -class IDraw2d -{ -public: // types - - //! Horizontal alignment can be used for both text and image drawing - enum class HAlign - { - Left, - Center, - Right, - }; - - //! Vertical alignment can be used for both text and image drawing - enum class VAlign - { - Top, - Center, - Bottom, - }; - - //! Used for specifying how to round positions to an exact pixel position for pixel-perfect rendering - enum class Rounding - { - None, - Nearest, - Down, - Up - }; - - enum - { - //! Limit imposed by FFont. This is the max number of characters including the null terminator. - MAX_TEXT_STRING_LENGTH = 1024, - }; - - enum : int - { - //! Constant that indicates the built-in default value should be used - UseDefault = -1 - }; - - //! Struct used to pass additional image options. - // - //! If this is not passed then the defaults below are used - struct ImageOptions - { - int blendMode; //!< default is GS_BLSRC_SRCALPHA|GS_BLDST_ONEMINUSSRCALPHA - AZ::Vector3 color; //!< default is (1,1,1) - Rounding pixelRounding; //!< default is Rounding::Nearest - int baseState; //!< Additional flags for SetState. Default is GS_NODEPTHTEST - }; - - //! Struct used to pass additional text options - mostly ones that do not change from call to call. - // - //! If this is not passed then the defaults below are used - struct TextOptions - { - AZStd::string fontName; //!< default is "default" - unsigned int effectIndex; //!< default is 0 - AZ::Vector3 color; //!< default is (1,1,1) - HAlign horizontalAlignment; //!< default is HAlign::Left - VAlign verticalAlignment; //!< default is VAlign::Top - AZ::Vector2 dropShadowOffset; //!< default is (0,0), zero offset means no drop shadow is drawn - AZ::Color dropShadowColor; //!< default is (0,0,0,0), zero alpha means no drop shadow is drawn - float rotation; //!< default is 0 - int baseState; //!< Additional flags for SetState. Default is GS_NODEPTHTEST - }; - - //! Used to pass in arrays of vertices (e.g. to DrawQuad) - struct VertexPosColUV - { - VertexPosColUV(){} - VertexPosColUV(const AZ::Vector2& inPos, const AZ::Color& inColor, const AZ::Vector2& inUV) - { - position = inPos; - color = inColor; - uv = inUV; - } - - AZ::Vector2 position; //!< 2D position of vertex - AZ::Color color; //!< Float color - AZ::Vector2 uv; //!< Texture coordinate - }; - -public: // member functions - - //! Implement virtual destructor just for safety. - virtual ~IDraw2d() {} -}; diff --git a/Code/CryEngine/CryCommon/LyShine/ILyShine.h b/Code/CryEngine/CryCommon/LyShine/ILyShine.h deleted file mode 100644 index 6746053596..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/ILyShine.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Math/Vector2.h> -#include <LyShine/UiBase.h> - -class IDraw2d; -class ISprite; -struct IUiAnimationSystem; -class UiEntityContext; - -// The following ifdef block is the standard way of creating macros which make exporting -// from a DLL simpler. All files within this DLL are compiled with the LYSHINE_EXPORTS -// symbol defined in the StdAfx.h. this symbol should not be defined on any project -// that uses this DLL. This way any other project whose source files include this file see -// LYSHINE_API functions as being imported from a DLL, whereas this DLL sees symbols -// defined with this macro as being exported. -#ifdef LYSHINE_EXPORTS - #define LYSHINE_API DLL_EXPORT -#else - #define LYSHINE_API DLL_IMPORT -#endif - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! The ILyShine interface provides access to the other interfaces provided by the UI module -class ILyShine -{ -public: - virtual ~ILyShine(){} - - //! Delete this object - virtual void Release() = 0; - - //! Gets the IDraw2d interface - virtual IDraw2d* GetDraw2d() = 0; - - //! Create an empty UI Canvas (in game) - // - //! The system keeps track of all the loaded canvases and unloads them on game exit. - virtual AZ::EntityId CreateCanvas() = 0; - - //! Load a UI Canvas from in-game - virtual AZ::EntityId LoadCanvas(const string& assetIdPathname) = 0; - - //! Create an empty UI Canvas (for the UI editor) - // - //! The editor keeps track of the canvases it has open. - virtual AZ::EntityId CreateCanvasInEditor(UiEntityContext* entityContext) = 0; - - //! Load a UI Canvas from the UI editor - virtual AZ::EntityId LoadCanvasInEditor(const string& assetIdPathname, const string& sourceAssetPathname, UiEntityContext* entityContext) = 0; - - //! Reload a UI Canvas from xml. For use in the editor for the undo system only - virtual AZ::EntityId ReloadCanvasFromXml(const AZStd::string& xmlString, UiEntityContext* entityContext) = 0; - - //! Get a loaded canvas by CanvasId - //! NOTE: this only searches canvases loaded in the game (not the editor) - virtual AZ::EntityId FindCanvasById(LyShine::CanvasId id) = 0; - - //! Get a loaded canvas by path name - //! NOTE: this only searches canvases loaded in the game (not the editor) - virtual AZ::EntityId FindLoadedCanvasByPathName(const string& assetIdPathname) = 0; - - //! Release a canvas from use either in-game or in editor, destroy UI Canvas if no longer used in either - virtual void ReleaseCanvas(AZ::EntityId canvas, bool forEditor = false) = 0; - - //! Queue a canvas for release on the next tick (used in game mode) - virtual void ReleaseCanvasDeferred(AZ::EntityId canvas) = 0; - - //! Load a sprite object. - virtual ISprite* LoadSprite(const string& pathname) = 0; - - //! Create a sprite that references the specified render target - virtual ISprite* CreateSprite(const string& renderTargetName) = 0; - - //! Check if a sprite's texture asset exists. The .sprite sidecar file is optional and is not checked - virtual bool DoesSpriteTextureAssetExist(const AZStd::string& pathname) = 0; - - //! Perform post-initialization (script system will be available) - virtual void PostInit() = 0; - - //! Set the current viewport size, this should be called before Update and Render are called - virtual void SetViewportSize(AZ::Vector2 viewportSize) = 0; - - //! Update UI elements - //! \param deltaTimeInSeconds the amount of time in seconds since the last call to this function - virtual void Update(float deltaTimeInSeconds) = 0; - - //! Render 2D and UI elements that should be rendered at end of frame - virtual void Render() = 0; - - //! Execute events that were queued during a canvas update or input event handler - virtual void ExecuteQueuedEvents() = 0; - - //! Reset the system (this happens at end of running game in Editor for example) - virtual void Reset() = 0; - - //! Unload canvases that should be unloaded when a level is unloaded - virtual void OnLevelUnload() = 0; - - //! Called when a load screen is finished displaying (when a level load is complete). - //! Used to mark all render graphs dirty in case the loaded canvases were already rendered before their textures - //! were done loading. This happens when a load screen is being rendered during a level load. When other canvases - //! associated with the level are loaded, they also get rendered by the UiLoadScreenComponent, but their texture - //! loading is delayed until further down the level load process. Once a canvas is rendered, its render graph's - //! dirty flag is cleared, so the render graph needs to be marked dirty again after the textures are loaded - virtual void OnLoadScreenUnloaded() = 0; -}; - -#ifdef __cplusplus -extern "C" { -#endif - -LYSHINE_API ILyShine* CreateLyShineInterface(ISystem* system); - -#ifdef __cplusplus -}; -#endif - diff --git a/Code/CryEngine/CryCommon/LyShine/IRenderGraph.h b/Code/CryEngine/CryCommon/LyShine/IRenderGraph.h deleted file mode 100644 index 402a8f3b25..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/IRenderGraph.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <IRenderer.h> -#include <LyShine/UiBase.h> - -namespace AZ -{ - class Color; - class Vector2; -} - -namespace LyShine -{ - //////////////////////////////////////////////////////////////////////////////////////////////////// - // UI visual components use this interface to add primitives to the render graph, which is how the - // UI gets rendered. - // There is one render graph per UI canvas. The render graph (like a display list) is rebuilt when - // any visual change occurs on the canvas. - class IRenderGraph - { - public: - - //! Virtual destructor - virtual ~IRenderGraph() {} - - //---- Functions for creating and adding primitives to the render graph ---- - - //! Begin the setup of a mask render node, primitives added between this call and StartChildrenForMask define the mask - virtual void BeginMask(bool isMaskingEnabled, bool useAlphaTest, bool drawBehind, bool drawInFront) = 0; - - //! Start defining the children (masked primitives) of a mask - virtual void StartChildrenForMask() = 0; - - //! End the setup of a mask render node, this marks the end of adding child primitives - virtual void EndMask() = 0; - - //! Begin rendering to a texture - virtual void BeginRenderToTexture(int renderTargetHandle, SDepthTexture* renderTargetDepthSurface, - const AZ::Vector2& viewportTopLeft, const AZ::Vector2& viewportSize, const AZ::Color& clearColor) = 0; - - //! End rendering to a texture - virtual void EndRenderToTexture() = 0; - - //! Add an indexed triangle list primitive to the render graph with given render state - virtual void AddPrimitive(IRenderer::DynUiPrimitive* primitive, ITexture* texture, - bool isClampTextureMode, bool isTextureSRGB, bool isTexturePremultipliedAlpha, BlendMode blendMode) = 0; - - //! Add an indexed triangle list primitive to the render graph which will use maskTexture as an alpha (gradient) mask - virtual void AddAlphaMaskPrimitive(IRenderer::DynUiPrimitive* primitive, - ITexture* texture, ITexture* maskTexture, - bool isClampTextureMode, bool isTextureSRGB, bool isTexturePremultipliedAlpha, BlendMode blendMode) = 0; - - //! Get a dynamic quad primitive that can be added as an image primitive to the render graph - //! The graph handles the allocation of this DynUiPrimitive and deletes it when the graph is reset - //! This can be used if the UI component doesn't want to own the storage of the primitive. Used infrequently, - //! e.g. for the selection rect on a text component. - virtual IRenderer::DynUiPrimitive* GetDynamicQuadPrimitive(const AZ::Vector2* positions, uint32 packedColor) = 0; - - //---- Functions for supporting masking (used during creation of the graph, not rendering ) ---- - - //! Get flag that indicates we are rendering into a mask. Used to avoid masks on child mask elements. - virtual bool IsRenderingToMask() const = 0; - - //! Set flag that we are rendering into a mask. Used to avoid masks on child mask elements. - virtual void SetIsRenderingToMask(bool isRenderingToMask) = 0; - - //---- Functions for supporting fading (used during creation of the graph, not rendering ) ---- - - //! Push an alpha fade, this is multiplied with any existing alpha fade from parents - virtual void PushAlphaFade(float alphaFadeValue) = 0; - - //! Push a new alpha fade value, this replaces any existing alpha fade - virtual void PushOverrideAlphaFade(float alphaFadeValue) = 0; - - //! Pop an alpha fade off the stack - virtual void PopAlphaFade() = 0; - - //! Get the current alpha fade value - virtual float GetAlphaFade() const = 0; - }; -} diff --git a/Code/CryEngine/CryCommon/LyShine/ISprite.h b/Code/CryEngine/CryCommon/LyShine/ISprite.h deleted file mode 100644 index 8789fc5d71..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/ISprite.h +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <SerializeFwd.h> -#include <smartptr.h> -#include <LyShine/Bus/UiTransformBus.h> -#include <AzCore/Math/Vector2.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! A sprite is a texture with extra information about how it behaves for 2D drawing -//! Currently a sprite exists on disk as a side car file next to the texture file. -class ISprite - : public _i_reference_target<int> -{ -public: // types - - // The borders define the areas of the sprite that stretch - // Border's members are always in range 0-1, they are normalized positions within the texture bounds - struct Borders - { - Borders() - : m_left(0.0f) - , m_right(1.0f) - , m_top(0.0f) - , m_bottom(1.0f) {} - - Borders(float left, float right, float top, float bottom) - : m_left(left) - , m_right(right) - , m_top(top) - , m_bottom(bottom) {} - - float m_left; - float m_right; - float m_top; - float m_bottom; - }; - - //! \brief Defines the UV-extents of a particular "cell" in a sprite-sheet. - //! 9-slice information for the cell is also stored. - struct SpriteSheetCell - { - AZStd::string alias; - UiTransformInterface::RectPoints uvCellCoords; - Borders borders; - }; - - using SpriteSheetCellContainer = AZStd::vector<SpriteSheetCell>; - -public: // member functions - - //! Deleting a sprite will release its texture - virtual ~ISprite() {} - - //! Get the pathname of this sprite - virtual const string& GetPathname() const = 0; - - //! Get the pathname of the texture of this sprite - virtual const string& GetTexturePathname() const = 0; - - //! Get the borders of this sprite - virtual Borders GetBorders() const = 0; - - //! Set the borders of this sprite - virtual void SetBorders(Borders borders) = 0; - - //! Set the borders of a given cell within the sprite-sheet. - virtual void SetCellBorders(int cellIndex, Borders borders) = 0; - - //! Serialize this object for save/load - virtual void Serialize(TSerialize ser) = 0; - - //! Save this sprite data to disk - virtual bool SaveToXml(const string& pathname) = 0; - - //! Test if this sprite has any borders - virtual bool AreBordersZeroWidth() const = 0; - - //! Tests if the sprite-sheet cell has borders - virtual bool AreCellBordersZeroWidth(int cellIndex) const = 0; - - //! Get the dimensions of the sprite - virtual AZ::Vector2 GetSize() = 0; - - //! Gets the dimensions of a specific cell texture within a sprite-sheet - virtual AZ::Vector2 GetCellSize(int cellIndex) = 0; - - //! Gets cell info for each of the cells within the sprite-sheet. - virtual const SpriteSheetCellContainer& GetSpriteSheetCells() const = 0; - - //! Sets the sprite's sprite-sheet cells. - virtual void SetSpriteSheetCells(const SpriteSheetCellContainer& cells) = 0; - - //! Removes all sprite-sheet cell info for this sprite. - virtual void ClearSpriteSheetCells() = 0; - - //! Defines a new SpriteSheetCell for this sprite. - virtual void AddSpriteSheetCell(const SpriteSheetCell& spriteSheetCell) = 0; - - //! Gets the dimensions of a specific cell (in a sprite-sheet) in UV coords (UV range). - virtual AZ::Vector2 GetCellUvSize(int cellIndex) const = 0; - - //! Gets the UV coords associated for a given cell in a sprite-sheet. - virtual UiTransformInterface::RectPoints GetCellUvCoords(int cellIndex) const = 0; - - //! Gets the UV coords associated for a given cell in a sprite-sheet in a way that ignores texture atlases - virtual UiTransformInterface::RectPoints GetSourceCellUvCoords(int cellIndex) const = 0; - - //! Gets the sliced border info for a given cell within a sprite-sheet. - //! - //! The returned UV borders are in "cell space" relative to the given indexed spell. For example, - //! a top-left border of (0.5, 0.5) would be the center of the given cell. - virtual Borders GetCellUvBorders(int cellIndex) const = 0; - - //! Gets the sliced border UV coordinates in texture space for a given cell within a sprite-sheet. - //! - //! The returned UV border coordinates are in texture space. For example, a top-left border of (0.5, 0.5) - //! would be the center of the sprite-sheet. - virtual Borders GetTextureSpaceCellUvBorders(int cellIndex) const = 0; - - //! Gets the string alias associated with the given cell in a sprite-sheet. - virtual const AZStd::string& GetCellAlias(int cellIndex) const = 0; - - //! Sets the string alias associated with the given cell in a sprite-sheet. - virtual void SetCellAlias(int cellIndex, const AZStd::string& cellAlias) = 0; - - //! Returns the sprite-sheet cell index that corresponds to the given string alias. - virtual int GetCellIndexFromAlias(const AZStd::string& cellAlias) const = 0; - - //! Returns true if this sprite is configured as a sprite-sheet, false otherwise - virtual bool IsSpriteSheet() const = 0; -}; - diff --git a/Code/CryEngine/CryCommon/LyShine/UiAssetTypes.h b/Code/CryEngine/CryCommon/LyShine/UiAssetTypes.h deleted file mode 100644 index 169ec6e143..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/UiAssetTypes.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/RTTI/TypeInfo.h> -#include <AzFramework/Asset/SimpleAsset.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// -namespace LyShine -{ - class FontAsset - { - public: - AZ_TYPE_INFO(FontAsset, "{57767D37-0EBE-43BE-8F60-AB36D2056EF8}") - static const char* GetFileFilter() - { - return "*.xml;*.font;*.fontfamily"; - } - }; - - class CanvasAsset - { - public: - AZ_TYPE_INFO(CanvasAsset, "{E48DDAC8-1F1E-4183-AAAB-37424BCC254B}") - static const char* GetFileFilter() - { - return "*.uicanvas"; - } - }; -} diff --git a/Code/CryEngine/CryCommon/LyShine/UiBase.h b/Code/CryEngine/CryCommon/LyShine/UiBase.h deleted file mode 100644 index f5aabc9141..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/UiBase.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <platform.h> -#include <algorithm> -#include <Cry_Math.h> -#include <Cry_Color.h> -#include <ISystem.h> - -#include <AzCore/std/string/string.h> -#include <AzCore/Component/Entity.h> -#include <AzCore/std/containers/unordered_map.h> - -// This is a workaround for AZCore including WinUser.h which defines DrawText to be DrawTextA -#ifdef DrawText - #undef DrawText -#endif - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Common types used across the LyShine UI system -namespace LyShine -{ - //! used for UI element names and canvas names, should be the same as the AZ::Entity name type - typedef AZStd::string NameType; - - //! Used for pathnames for UI canvas and prefab files - typedef AZStd::string PathnameType; - - //! USed for our 32-bit id's for canvases and elements. Only used so FlowGraph can reference these things - //! These should go away once FlowGraph can used AZ::EntityIds - typedef unsigned int CanvasId; - typedef unsigned int ElementId; - - //! Used for UI action names - typedef AZStd::string ActionName; - - //! Used for test strings in UI text elements - typedef AZStd::string StringType; // not yet decided if we should use wchar_t or UTF8 - - //! Used for passing lists of entities - typedef DynArray<AZ::Entity*> EntityArray; - - enum class BlendMode - { - Normal, //!< interpolate from dest color to source color according to source alpha - Add, //!< source color * source alpha is added to dest color (Linear Dodge) - Screen, //!< as close as we can get to Photoshop Screen - Darken, //!< like Photoshop darken - Lighten, //!< like Photoshop lighten - }; - - // used to map old EntityId's to new EntityId's when generating new ids for a paste or prefab - typedef AZStd::unordered_map<AZ::EntityId, AZ::EntityId> EntityIdMap; -}; - - -namespace AZ -{ - AZ_TYPE_INFO_SPECIALIZE(ColorF, "{63782551-A309-463B-A301-3A360800DF1E}"); - AZ_TYPE_INFO_SPECIALIZE(ColorB, "{6F0CC2C0-0CC6-4DBF-9297-B043F270E6A4}"); - AZ_TYPE_INFO_SPECIALIZE(Vec4, "{CAC9510C-8C00-41D4-BC4D-2C6A8136EB30}"); - AZ_TYPE_INFO_SPECIALIZE(CryStringT<char>, "{835199FB-292B-4DB3-BC7C-366E356300FA}"); -} // namespace AZ - diff --git a/Code/CryEngine/CryCommon/LyShine/UiComponentTypes.h b/Code/CryEngine/CryCommon/LyShine/UiComponentTypes.h deleted file mode 100644 index 1870ffd9ce..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/UiComponentTypes.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Common types used across the LyShine UI system -namespace LyShine -{ - // Uuid strings for all component types define by LyShine. - // This can be used to create components at runtime. E.g.: - // entity->CreateComponent(LyShine::UiTransform2dComponentUuid); - const char* const UiButtonComponentUuid = "{7329DFE8-0F3C-4629-B395-78B2CF646B96}"; - const char* const UiCanvasComponentUuid = "{50B8CF6C-B19A-4D86-AFE9-96EFB820D422}"; - const char* const UiCheckboxComponentUuid = "{68D62281-B360-4426-AACA-E8BDE8BFEB3A}"; - const char* const UiDraggableComponentUuid = "{C96B1EEF-033A-479B-829B-ED3555D0F33A}"; - const char* const UiDropTargetComponentUuid = "{E4B8ACE0-FCE7-42D8-9836-942F910168B4}"; - const char* const UiDropdownComponentUuid = "{BFC4D5A3-2F7C-4079-B19C-C2A06E93F343}"; - const char* const UiDropdownOptionComponentUuid = "{554E16E4-CBA1-4E57-B326-9731AA963BAA}"; - const char* const UiDynamicLayoutComponentUuid = "{690BEC14-3642-4247-BD96-FE414CCB7DE7}"; - const char* const UiDynamicScrollBoxComponentUuid = "{6982C200-4D32-43CC-A7F6-F54FA50FCFF5}"; - const char* const UiElementComponentUuid = "{4A97D63E-CE7A-45B6-AAE4-102DB4334688}"; - const char* const UiFaderComponentUuid = "{CD01FF77-2249-4ED8-BFFB-33A66A47E17C}"; - const char* const UiFlipbookAnimationComponentUuid ="{AACCFFA1-B694-4F8B-A289-391A56404E0C}"; - const char* const UiImageComponentUuid = "{BDBEFD23-DBB4-4726-A32D-4FEAC24E51F6}"; - const char* const UiImageSequenceComponentUuid = "{BFAC7909-3A56-4980-AF7C-261A99D6371B}"; - const char* const UiLayoutColumnComponentUuid = "{4BC2E786-360B-4426-8D9C-9B254C5EA21F}"; - const char* const UiLayoutCellComponentUuid = "{A0568E58-4382-47F8-8B88-77C64B99AC80}"; - const char* const UiLayoutFitterComponentUuid = "{96C55390-9D03-4C47-BB0D-17D3BD5219E3}"; - const char* const UiLayoutGridComponentUuid = "{ADDA3AE5-B9AB-44B7-A462-8B89B398A837}"; - const char* const UiLayoutRowComponentUuid = "{7B2820C4-7FC7-4F02-B777-6727EB4BAC13}"; - const char* const UiMarkupButtonComponentUuid = "{D7EB1706-75E8-4C94-A266-61913F42431B}"; - const char* const UiMaskComponentUuid = "{2279AA38-271D-4D4F-A472-E42B984088AC}"; - const char* const UiParticleEmitterComponentUuid = "{E8B1288C-CB49-4CAD-B366-AF1B40C47E74}"; - const char* const UiRadioButtonComponentUuid = "{773A0F4B-F9F9-4B82-9951-BBD73A737DE4}"; - const char* const UiRadioButtonGroupComponentUuid = "{F89D5EF2-37C4-4CA7-9AA2-23DC3867EC9D}"; - const char* const UiScrollBarComponentUuid = "{6B283F90-3519-47DA-A1DD-65A79CE119CF}"; - const char* const UiScrollBoxComponentUuid = "{2F539588-AEAB-4341-A6A6-AF645D129693}"; - const char* const UiSliderComponentUuid = "{2913D76B-36A0-45E0-A104-33C668EB612D}"; - const char* const UiTextComponentUuid = "{5B3FB2A7-5DC4-4033-A970-001CEC85B6C4}"; - const char* const UiTextInputComponentUuid = "{2CB3872B-D2B4-4DDB-B39A-97492310AE11}"; - const char* const UiTooltipComponentUuid = "{493EBF89-C299-4722-829D-4DFAB926795B}"; - const char* const UiTooltipDisplayComponentUuid = "{18CEE6A7-3CBC-4638-9F4D-87E8D53DDF1A}"; - const char* const UiTransform2dComponentUuid = "{2751A5A5-3291-4A4D-9FC0-9CB0EB8D1DE6}"; - - // The Uuid of the LyShine system component. Can be used from tools to activate this component. - const char* const lyShineSystemComponentUuid = "{B0C78B8D-1E5B-47D7-95D0-EC69C0513804}"; -}; diff --git a/Code/CryEngine/CryCommon/LyShine/UiEntityContext.h b/Code/CryEngine/CryCommon/LyShine/UiEntityContext.h deleted file mode 100644 index 1c68646b7a..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/UiEntityContext.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Math/Uuid.h> -#include <AzCore/Component/Component.h> -#include <AzCore/Component/ComponentApplicationBus.h> -#include <AzCore/Asset/AssetCommon.h> -#include <AzCore/Slice/SliceComponent.h> - -#include <AzFramework/Entity/EntityContext.h> -#include <AzFramework/Asset/AssetCatalogBus.h> - -#include <LyShine/Bus/UiEntityContextBus.h> - -namespace AZ -{ - class SerializeContext; -} - -namespace AzFramework -{ - class EntityContext; -} - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! The UI Entity Context stores the prefab asset for the root slice of a UI canvas -//! So all of the UI element entities in a canvas are owned indirectly by the context and managed -//! by the entity context. -class UiEntityContext - : public AzFramework::EntityContext - , public UiEntityContextRequestBus::Handler -{ -public: // member functions - - //! Initialize the entity context and instantiate the root slice - virtual void InitUiContext() = 0; - - //! Destroy the Entity Context - virtual void DestroyUiContext() = 0; - - //! Saves the context's slice root to the specified buffer. If necessary - //! entities undergo conversion for game: editor -> game components. - //! \return true if successfully saved. Failure is only possible if serialization data is corrupt. - virtual bool SaveToStreamForGame(AZ::IO::GenericStream& stream, AZ::DataStream::StreamType streamType) = 0; - - //! Saves the given canvas entity to the specified buffer. If necessary - //! the entity undergoes conversion for game: editor -> game components. - //! \return true if successfully saved. Failure is only possible if serialization data is corrupt. - //! This is needed because the canvas entity is not part of the root slice. It is here in the entity - //! context because that allows us to get to the ToolsFramework functionality. - virtual bool SaveCanvasEntityToStreamForGame(AZ::Entity* canvasEntity, AZ::IO::GenericStream& stream, AZ::DataStream::StreamType streamType) = 0; -}; diff --git a/Code/CryEngine/CryCommon/LyShine/UiLayoutCellBase.h b/Code/CryEngine/CryCommon/LyShine/UiLayoutCellBase.h deleted file mode 100644 index fe20273393..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/UiLayoutCellBase.h +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -//////////////////////////////////////////////////////////////////////////////////////////////////// -//! Common types used across the LyShine UI layout cell system -namespace LyShine -{ - const float UiLayoutCellUnspecifiedSize = -1.0f; - - inline bool IsUiLayoutCellSizeSpecified(float size) - { - return size >= 0.0f; - } -}; diff --git a/Code/CryEngine/CryCommon/LyShine/UiSerializeHelpers.h b/Code/CryEngine/CryCommon/LyShine/UiSerializeHelpers.h deleted file mode 100644 index 090b622d9f..0000000000 --- a/Code/CryEngine/CryCommon/LyShine/UiSerializeHelpers.h +++ /dev/null @@ -1,670 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Math/Crc.h> -#include <AzCore/Math/Vector2.h> -#include <AzCore/Math/Vector3.h> -#include <AzCore/Math/Color.h> -#include <AzCore/Serialization/SerializeContext.h> -#include <AzCore/Math/Sfmt.h> -#include <AzCore/Component/Entity.h> - -#include <LyShine/UiAssetTypes.h> -#include <LyShine/UiBase.h> - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -namespace LyShine -{ - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to convert a CryString field to an AZStd::String - // Inline to avoid DLL linkage issues - inline bool ConvertSubElementFromCryStringToAzString( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* subElementName) - { - int index = classElement.FindElement(AZ_CRC(subElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - - CryStringT<char> oldData; - - if (!elementNode.GetData(oldData)) - { - // Error, old subElement was not a string or not valid - AZ_Error("Serialization", false, "Cannot get string data for element %s.", subElementName); - return false; - } - - // Remove old version. - classElement.RemoveElement(index); - - // Add a new element for the new data. - int newElementIndex = classElement.AddElement<AZStd::string>(context, subElementName); - if (newElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element %s", subElementName); - return false; - } - - AZStd::string newData(oldData.c_str()); - classElement.GetSubElement(newElementIndex).SetData(context, newData); - } - - // if the field did not exist then we do not report an error - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to convert a CryString field to a char - // Inline to avoid DLL linkage issues - inline bool ConvertSubElementFromCryStringToChar( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* subElementName, - char defaultValue) - { - int index = classElement.FindElement(AZ_CRC(subElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - - CryStringT<char> oldData; - - if (!elementNode.GetData(oldData)) - { - // Error, old subElement was not a CryString - AZ_Error("Serialization", false, "Element %s is not a CryString.", subElementName); - return false; - } - - // Remove old version. - classElement.RemoveElement(index); - - // Add a new element for the new data. - int newElementIndex = classElement.AddElement<char>(context, subElementName); - if (newElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element %s", subElementName); - return false; - } - - char newData = (oldData.empty()) ? defaultValue : oldData[0]; - classElement.GetSubElement(newElementIndex).SetData(context, newData); - } - - // if the field did not exist then we do not report an error - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to convert a CryString field to a simple asset reference - // Inline to avoid DLL linkage issues - template<typename T> - inline bool ConvertSubElementFromCryStringToAssetRef( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* subElementName) - { - int index = classElement.FindElement(AZ_CRC(subElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - - CryStringT<char> oldData; - - if (!elementNode.GetData(oldData)) - { - // Error, old subElement was not a CryString - AZ_Error("Serialization", false, "Element %s is not a CryString.", subElementName); - return false; - } - - // Remove old version. - classElement.RemoveElement(index); - - // Add a new element for the new data. - int simpleAssetRefIndex = classElement.AddElement<AzFramework::SimpleAssetReference<T> >(context, subElementName); - if (simpleAssetRefIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for simpleAssetRefIndex %s", subElementName); - return false; - } - - // add a sub element for the SimpleAssetReferenceBase within the SimpleAssetReference - AZ::SerializeContext::DataElementNode& simpleAssetRefNode = classElement.GetSubElement(simpleAssetRefIndex); - int simpleAssetRefBaseIndex = simpleAssetRefNode.AddElement<AzFramework::SimpleAssetReferenceBase>(context, "BaseClass1"); - if (simpleAssetRefBaseIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element BaseClass1"); - return false; - } - - // add a sub element for the AssetPath within the SimpleAssetReference - AZ::SerializeContext::DataElementNode& simpleAssetRefBaseNode = simpleAssetRefNode.GetSubElement(simpleAssetRefBaseIndex); - int assetPathElementIndex = simpleAssetRefBaseNode.AddElement<AZStd::string>(context, "AssetPath"); - if (assetPathElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element AssetPath"); - return false; - } - - AZStd::string newData(oldData.c_str()); - simpleAssetRefBaseNode.GetSubElement(assetPathElementIndex).SetData(context, newData); - } - - // if the field did not exist then we do not report an error - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to convert an AZStd::string field to a simple asset reference - // Inline to avoid DLL linkage issues - template<typename T> - inline bool ConvertSubElementFromAzStringToAssetRef( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* subElementName) - { - int index = classElement.FindElement(AZ_CRC(subElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - - AZStd::string oldData; - - if (!elementNode.GetData(oldData)) - { - // Error, old subElement was not a string or not valid - AZ_Error("Serialization", false, "Cannot get string data for element %s.", subElementName); - return false; - } - - // Remove old version. - classElement.RemoveElement(index); - - // Add a new element for the new data. - int simpleAssetRefIndex = classElement.AddElement<AzFramework::SimpleAssetReference<T> >(context, subElementName); - if (simpleAssetRefIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for simpleAssetRefIndex %s", subElementName); - return false; - } - - // add a sub element for the SimpleAssetReferenceBase within the SimpleAssetReference - AZ::SerializeContext::DataElementNode& simpleAssetRefNode = classElement.GetSubElement(simpleAssetRefIndex); - int simpleAssetRefBaseIndex = simpleAssetRefNode.AddElement<AzFramework::SimpleAssetReferenceBase>(context, "BaseClass1"); - if (simpleAssetRefBaseIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element BaseClass1"); - return false; - } - - // add a sub element for the AssetPath within the SimpleAssetReference - AZ::SerializeContext::DataElementNode& simpleAssetRefBaseNode = simpleAssetRefNode.GetSubElement(simpleAssetRefBaseIndex); - int assetPathElementIndex = simpleAssetRefBaseNode.AddElement<AZStd::string>(context, "AssetPath"); - if (assetPathElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element AssetPath"); - return false; - } - - AZStd::string newData(oldData.c_str()); - simpleAssetRefBaseNode.GetSubElement(assetPathElementIndex).SetData(context, newData); - } - - // if the field did not exist then we do not report an error - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to convert a char to a uint32_t - // Inline to avoid DLL linkage issues - inline bool ConvertSubElementFromCharToUInt32( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* subElementName) - { - int index = classElement.FindElement(AZ_CRC(subElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - - char oldData; - - if (!elementNode.GetData(oldData)) - { - // Error, old subElement was not a CryString - AZ_Error("Serialization", false, "Element %s is not a char.", subElementName); - return false; - } - - // Remove old version. - classElement.RemoveElement(index); - - // Add a new element for the new data. - int newElementIndex = classElement.AddElement<uint32_t>(context, subElementName); - if (newElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element %s", subElementName); - return false; - } - - uint32_t newData = oldData; - classElement.GetSubElement(newElementIndex).SetData(context, newData); - } - - // if the field did not exist then we do not report an error - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to get the value for a named sub element - template<typename T> - inline bool GetSubElementValue( - AZ::SerializeContext::DataElementNode& classElement, - const char* elementName, T& value) - { - int index = classElement.FindElement(AZ_CRC(elementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - if (!elementNode.GetData(value)) - { - return false; - } - } - else - { - return false; - } - - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to make a ColorF out of an RGB color and an alpha - inline ColorF MakeColorF(AZ::Vector3 color, float alpha) - { - return ColorF(color.GetX(), color.GetY(), color.GetZ(), alpha); - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to make an AZ::Vector3 from the rgb elements of a ColorF - inline AZ::Vector3 MakeColorVector3(ColorF color) - { - return AZ::Vector3(color.r, color.g, color.b); - } - - // Helper function to make an AZ::Color from a ColorF - inline AZ::Color MakeColorAZColor(ColorF color) - { - return AZ::Color(color.r, color.g, color.b, color.a); - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to convert a ColorF field to a Vector3 color and a float - // alpha. - // Inline to avoid DLL linkage issues - inline bool ConvertSubElementFromColorToColorPlusAlpha( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* colorElementName, - const char* alphaElementName) - { - int index = classElement.FindElement(AZ_CRC(colorElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - - ColorF oldData; - - if (!(GetSubElementValue(elementNode, "r", oldData.r) && - GetSubElementValue(elementNode, "g", oldData.g) && - GetSubElementValue(elementNode, "b", oldData.b) && - GetSubElementValue(elementNode, "a", oldData.a))) - { - // Error, old subElement was not a ColorF - AZ_Error("Serialization", false, "Element %s is not a ColorF.", colorElementName); - return false; - } - - // Remove old version. - classElement.RemoveElement(index); - - // Add new elements for the new data. - - int newColorElementIndex = classElement.AddElement<AZ::Vector3>(context, colorElementName); - if (newColorElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element %s", colorElementName); - return false; - } - - int newAlphaElementIndex = classElement.AddElement<float>(context, alphaElementName); - if (newAlphaElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element %s", alphaElementName); - return false; - } - - AZ::Vector3 newColorData(oldData.r, oldData.g, oldData.b); - classElement.GetSubElement(newColorElementIndex).SetData(context, newColorData); - - float newAlphaData(oldData.a); - classElement.GetSubElement(newAlphaElementIndex).SetData(context, newAlphaData); - } - - // if the field did not exist then we do not report an error - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to convert a AZ::Vector3 field to a AZ::Color - // Inline to avoid DLL linkage issues - inline bool ConvertSubElementFromVector3ToAzColor( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* colorElementName) - { - int index = classElement.FindElement(AZ_CRC(colorElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - - AZ::Vector3 oldData; - - if (!elementNode.GetData(oldData)) - { - // Error, old subElement was not a Vector3 or not valid - AZ_Error("Serialization", false, "Cannot get Vector3 data for element %s.", colorElementName); - return false; - } - - // Remove old version. - classElement.RemoveElement(index); - - // Add new elements for the new data. - - int newColorElementIndex = classElement.AddElement<AZ::Color>(context, colorElementName); - if (newColorElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element %s", colorElementName); - return false; - } - - AZ::Color newColorData = AZ::Color::CreateFromVector3(oldData); - classElement.GetSubElement(newColorElementIndex).SetData(context, newColorData); - } - - // if the field did not exist then we do not report an error - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to convert a ColorF field to a AZ::Color - // Inline to avoid DLL linkage issues - inline bool ConvertSubElementFromColorFToAzColor( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* colorElementName) - { - int index = classElement.FindElement(AZ_CRC(colorElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - - ColorF oldData; - - if (!(GetSubElementValue(elementNode, "r", oldData.r) && - GetSubElementValue(elementNode, "g", oldData.g) && - GetSubElementValue(elementNode, "b", oldData.b) && - GetSubElementValue(elementNode, "a", oldData.a))) - { - // Error, old subElement was not a ColorF - AZ_Error("Serialization", false, "Element %s is not a ColorF.", colorElementName); - return false; - } - - // Remove old version. - classElement.RemoveElement(index); - - // Add new elements for the new data. - - int newColorElementIndex = classElement.AddElement<AZ::Color>(context, colorElementName); - if (newColorElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element %s", colorElementName); - return false; - } - - classElement.GetSubElement(newColorElementIndex).SetData(context, MakeColorAZColor(oldData)); - } - - // if the field did not exist then we do not report an error - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to convert a Vec2 field to a AZ::Vector2. - // Inline to avoid DLL linkage issues - inline bool ConvertSubElementFromVec2ToVector2( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* vec2ElementName) - { - int index = classElement.FindElement(AZ_CRC(vec2ElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& elementNode = classElement.GetSubElement(index); - - Vec2 oldData; - - if (!(GetSubElementValue(elementNode, "x", oldData.x) && - GetSubElementValue(elementNode, "y", oldData.y))) - { - // Error, old subElement was not a Vec2 - AZ_Error("Serialization", false, "Element %s is not a Vec2.", vec2ElementName); - return false; - } - - // Remove old version. - classElement.RemoveElement(index); - - // Add new elements for the new data. - - int newVector2ElementIndex = classElement.AddElement<AZ::Vector2>(context, vec2ElementName); - if (newVector2ElementIndex == -1) - { - // Error adding the new sub element - AZ_Error("Serialization", false, "AddElement failed for converted element %s", vec2ElementName); - return false; - } - - AZ::Vector2 newVector2Data(oldData.x, oldData.y); - classElement.GetSubElement(newVector2ElementIndex).SetData(context, newVector2Data); - } - - // if the field did not exist then we do not report an error - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to move a sub-element from one DataElementNode to another - // DataElementNode and rename it - inline bool MoveElement( - [[maybe_unused]] AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& srcElement, - AZ::SerializeContext::DataElementNode& dstElement, - const char* srcSubElementName, - const char* dstSubElementName) - { - // find the sub-element (the field we will move) - int srcSubElementIndex = srcElement.FindElement(AZ_CRC(srcSubElementName)); - if (srcSubElementIndex != -1) - { - // add a copy of the sub-element into the base class - AZ::SerializeContext::DataElementNode subElementNode = srcElement.GetSubElement(srcSubElementIndex); - subElementNode.SetName(dstSubElementName); - dstElement.AddElement(subElementNode); - - // remove the sub-element from its original location - srcElement.RemoveElement(srcSubElementIndex); - } - - // if the field did not exist then we do not report an error - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to VersionConverter to remove leading forward slashes from asset path - inline bool RemoveLeadingForwardSlashesFromAssetPath( - AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement, - const char* simpleAssetRefSubElementName) - { - int index = classElement.FindElement(AZ_CRC(simpleAssetRefSubElementName)); - if (index != -1) - { - AZ::SerializeContext::DataElementNode& simpleAssetRefNode = classElement.GetSubElement(index); - index = simpleAssetRefNode.FindElement(AZ_CRC("BaseClass1", 0xd4925735)); - - if (index != -1) - { - AZ::SerializeContext::DataElementNode& baseClassNode = simpleAssetRefNode.GetSubElement(index); - index = baseClassNode.FindElement(AZ_CRC("AssetPath", 0x2c355179)); - - if (index != -1) - { - AZ::SerializeContext::DataElementNode& assetPathNode = baseClassNode.GetSubElement(index); - AZStd::string assetPath; - - if (!assetPathNode.GetData(assetPath)) - { - AZ_Error("Serialization", false, "Element AssetPath is not a AZStd::string."); - return false; - } - - // Count leading forward slashes - int i = 0; - while ((i < assetPath.length()) && (assetPath[i] == '/')) - { - i++; - } - if (i > 0) - { - // Remove leading forward slashes - assetPath.erase(0, i); - - if (!assetPathNode.SetData(context, assetPath)) - { - AZ_Error("Serialization", false, "Unable to set AssetPath data."); - return false; - } - } - } - } - } - - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to find a component with the given UUID in an entity - inline AZ::SerializeContext::DataElementNode* FindComponentNode(AZ::SerializeContext::DataElementNode& entityNode, const AZ::Uuid& uuid) - { - // get the component vector node - int componentsIndex = entityNode.FindElement(AZ_CRC("Components", 0xee48f5fd)); - if (componentsIndex == -1) - { - return nullptr; - } - AZ::SerializeContext::DataElementNode& componentsNode = entityNode.GetSubElement(componentsIndex); - - // search the components vector for the first component with the given ID - int numComponents = componentsNode.GetNumSubElements(); - for (int compIndex = 0; compIndex < numComponents; ++compIndex) - { - AZ::SerializeContext::DataElementNode& componentNode = componentsNode.GetSubElement(compIndex); - - if (componentNode.GetId() == uuid) - { - return &componentNode; - } - } - - return nullptr; - } - - //////////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to create an EntityId node for a newly created entity node - inline bool CreateEntityIdNode(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& entityNode) - { - // Generate a new EntityId and extract the raw u64 - AZ::EntityId newEntityId = AZ::Entity::MakeId(); - AZ::u64 rawId = static_cast<AZ::u64>(newEntityId); - - // Create the EntityId node within this entity - int entityIdIndex = entityNode.AddElement<AZ::EntityId>(context, "Id"); - if (entityIdIndex == -1) - { - return false; - } - AZ::SerializeContext::DataElementNode& elementIdNode = entityNode.GetSubElement(entityIdIndex); - - // Create the sub node of the EntityID that actually stores the u64 - int u64Index = elementIdNode.AddElementWithData(context, "id", rawId); - if (u64Index == -1) - { - return false; - } - - return true; - } - - //////////////////////////////////////////////////////////////////////////////////////////////////// - // Helper function to create the AZ::Component base class for a newly created component - inline bool CreateComponentBaseClassNode(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& componentNode) - { - // Generate a new component ID (using same technique that the AZ::Component uses) - AZ::ComponentId compId = AZ::Sfmt::GetInstance().Rand64(); - - // Create the base class node within this component node - int baseClassIndex = componentNode.AddElement<AZ::Component>(context, "BaseClass1"); - if (baseClassIndex == -1) - { - return false; - } - AZ::SerializeContext::DataElementNode& baseClassNode = componentNode.GetSubElement(baseClassIndex); - - // Create the sub node of the component base class that stores the u64 component id - int u64Index = baseClassNode.AddElementWithData(context, "Id", compId); - if (u64Index == -1) - { - return false; - } - - return true; - } - -} diff --git a/Code/CryEngine/CryCommon/MacSpecific.h b/Code/CryEngine/CryCommon/MacSpecific.h deleted file mode 100644 index 9d1eb38cb3..0000000000 --- a/Code/CryEngine/CryCommon/MacSpecific.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Mac declarations - - -#ifndef CRYINCLUDE_CRYCOMMON_MACSPECIFIC_H -#define CRYINCLUDE_CRYCOMMON_MACSPECIFIC_H -#pragma once - - -#include "AppleSpecific.h" -#include <cstddef> -#include <cfloat> -#include <xmmintrin.h> -//#define _CPU_X86 -#define _CPU_AMD64 -#define _CPU_SSE -#define PLATFORM_64BIT - -#define USE_CRT 1 -#define SIZEOF_PTR 8 - -typedef uint64_t threadID; - - -// curses.h stubs for PDcurses keys -#define PADENTER KEY_MAX + 1 -#define CTL_HOME KEY_MAX + 2 -#define CTL_END KEY_MAX + 3 -#define CTL_PGDN KEY_MAX + 4 -#define CTL_PGUP KEY_MAX + 5 - -// stubs for virtual keys, isn't used on Mac -#define VK_UP 0 -#define VK_DOWN 0 -#define VK_RIGHT 0 -#define VK_LEFT 0 -#define VK_CONTROL 0 -#define VK_SCROLL 0 - -#define MAC_NOT_IMPLEMENTED assert(false); - - -typedef enum -{ - eDAContinue, - eDAIgnore, - eDAIgnoreAll, - eDABreak, - eDAStop, - eDAReportAsBug -} EDialogAction; - -extern EDialogAction MacOSXHandleAssert(const char* condition, const char* file, int line, const char* reason, bool); - -#endif // CRYINCLUDE_CRYCOMMON_MACSPECIFIC_H diff --git a/Code/CryEngine/CryCommon/Maestro/Bus/EditorSequenceAgentComponentBus.h b/Code/CryEngine/CryCommon/Maestro/Bus/EditorSequenceAgentComponentBus.h deleted file mode 100644 index 7c50486567..0000000000 --- a/Code/CryEngine/CryCommon/Maestro/Bus/EditorSequenceAgentComponentBus.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/EBus/EBus.h> -#include <AzCore/std/string/string.h> -#include <Maestro/Bus/SequenceComponentBus.h> -#include <Maestro/Bus/SequenceAgentComponentBus.h> -#include <IMovieSystem.h> - -#include "SequenceAgentComponentBus.h" - -namespace Maestro -{ - /*! - * EditorSequenceAgentComponentRequests EBus Interface - * Messages serviced by EditorSequenceAgentComponents. - * - * The EBus is Id'ed on a pair of SequenceEntityId, SequenceAgentEntityId - */ - - class EditorSequenceAgentComponentBus - : public AZ::EBusTraits - { - public: - virtual ~EditorSequenceAgentComponentBus() = default; - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - using BusIdType = SequenceAgentEventBusId; - ////////////////////////////////////////////////////////////////////////// - }; - - class EditorSequenceAgentComponentRequests - : public EditorSequenceAgentComponentBus - { - public: - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - application is a singleton - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; // Only one component on a entity can implement the events - ////////////////////////////////////////////////////////////////////////// - - //! Returns a list of all animatable properties for a given componentId on the entity which holds the SequenceAgent Component - virtual void GetAllAnimatableProperties(IAnimNode::AnimParamInfos& propertyNames, AZ::ComponentId componentId) = 0; - - //! Append all animatable components on the entity which holds the SequenceAgent Component - virtual void GetAnimatableComponents(AZStd::vector<AZ::ComponentId>& animatableComponentIds) = 0; - }; - - using EditorSequenceAgentComponentRequestBus = AZ::EBus<EditorSequenceAgentComponentRequests>; - - /** - * Notifications from the Editor Sequence Agent Component - */ - class EditorSequenceAgentComponentNotification - : public AZ::EBusTraits - { - public: - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - using BusIdType = AZ::EntityId; - ////////////////////////////////////////////////////////////////////////// - - virtual ~EditorSequenceAgentComponentNotification() {} - - /** - * Called when a Sequence Agent has been connected to a Sequence. - */ - virtual void OnSequenceAgentConnected() {} - }; - - using EditorSequenceAgentComponentNotificationBus = AZ::EBus<EditorSequenceAgentComponentNotification>; - -} // namespace Maestro diff --git a/Code/CryEngine/CryCommon/Maestro/Bus/EditorSequenceBus.h b/Code/CryEngine/CryCommon/Maestro/Bus/EditorSequenceBus.h deleted file mode 100644 index 8432372f2d..0000000000 --- a/Code/CryEngine/CryCommon/Maestro/Bus/EditorSequenceBus.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/EBus/EBus.h> - -namespace Maestro -{ - /** - * Global Notifications from the Editor Sequences - */ - class EditorSequenceNotification - : public AZ::EBusTraits - { - public: - - /** - * Called when a Sequence has been selected in Track View. - */ - virtual void OnSequenceSelected([[maybe_unused]] const AZ::EntityId& sequenceEntityId) {} - }; - - using EditorSequenceNotificationBus = AZ::EBus<EditorSequenceNotification>; - -} // namespace Maestro diff --git a/Code/CryEngine/CryCommon/Maestro/Bus/EditorSequenceComponentBus.h b/Code/CryEngine/CryCommon/Maestro/Bus/EditorSequenceComponentBus.h deleted file mode 100644 index 7515b24735..0000000000 --- a/Code/CryEngine/CryCommon/Maestro/Bus/EditorSequenceComponentBus.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/std/string/string.h> -#include <IMovieSystem.h> - -#include "SequenceComponentBus.h" -enum class AnimValueType; - -namespace Maestro -{ - /*! - * EditorSequenceComponentRequests EBus Interface - * Messages serviced by DirectorComponents. - */ - class EditorSequenceComponentRequests - : public AZ::ComponentBus - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - application is a singleton - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; // Only one component on a entity can implement the events - ////////////////////////////////////////////////////////////////////////// - - //! Adds an entity to be animated - virtual void AddEntityToAnimate(AZ::EntityId entityToAnimate) = 0; - - //! Remove EntityToAnimate - virtual void RemoveEntityToAnimate(AZ::EntityId removedEntityId) = 0; - - //! Marks the entity as dirty in the Editor. Returns true if the entity was marked as dirty, false otherwise. - virtual bool MarkEntityAsDirty() const = 0; - - //! Fills in a list of all animatable properites for a given component on a given entity. - virtual void GetAllAnimatablePropertiesForComponent(IAnimNode::AnimParamInfos& addressList, AZ::EntityId id, AZ::ComponentId componentId) = 0; - - //! Fills in a list of all animatable component ids for the given entity. - virtual void GetAnimatableComponents(AZStd::vector<AZ::ComponentId>& componentIds, AZ::EntityId id) = 0; - - //! Return the AnimValueType type for the given address - virtual AnimValueType GetValueType(const AZStd::string& animatableAddress) = 0; - }; - - using EditorSequenceComponentRequestBus = AZ::EBus<EditorSequenceComponentRequests>; - -// defined in the bus header so we can refer to it in the Editor code -#define EditorSequenceComponentTypeId "{C02DC0E2-D0F3-488B-B9EE-98E28077EC56}" - -} // namespace Maestro diff --git a/Code/CryEngine/CryCommon/Maestro/Bus/SequenceAgentComponentBus.h b/Code/CryEngine/CryCommon/Maestro/Bus/SequenceAgentComponentBus.h deleted file mode 100644 index 6ff8e541fe..0000000000 --- a/Code/CryEngine/CryCommon/Maestro/Bus/SequenceAgentComponentBus.h +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/EBus/EBus.h> -#include <AzCore/std/string/string.h> -#include <Maestro/Bus/SequenceComponentBus.h> - -namespace Maestro -{ - /*! - * SequenceAgentComponentRequests EBus Interface - * Messages serviced by SequenceAgentComponents. - * - * The EBus is Id'ed on a pair of SequenceEntityId, SequenceAgentEntityId - */ - - // - // SequenceComponents broadcast to SequenceAgentComponents via a pair of Ids: - // sequenceEntityId, sequenceAgentEntityId - using SequenceAgentEventBusId = AZStd::pair<AZ::EntityId, AZ::EntityId>; // SequenceComponenet Entity Id, SequenceAgent EntityId - - class SequenceAgentComponentBus - : public AZ::EBusTraits - { - public: - virtual ~SequenceAgentComponentBus() = default; - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - typedef SequenceAgentEventBusId BusIdType; - ////////////////////////////////////////////////////////////////////////// - }; - - class SequenceAgentComponentRequests - : public SequenceAgentComponentBus - { - public: - using AnimatablePropertyAddress = Maestro::SequenceComponentRequests::AnimatablePropertyAddress; - using AnimatedValue = Maestro::SequenceComponentRequests::AnimatedValue; - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - application is a singleton - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; // Only one component on a entity can implement the events - ////////////////////////////////////////////////////////////////////////// - - //! Called when a SequenceComponent is connected - virtual void ConnectSequence(const AZ::EntityId& sequenceEntityId) = 0; - - //! Called when a SequenceComponent is disconnected - virtual void DisconnectSequence() = 0; - - //! Get the value for an animated float property at the given address on the same entity as the agent. - //! @param returnValue holds the value to get - this must be instance of one of the concrete subclasses of AnimatedValue, corresponding to the type of the property referenced by the animatedAdresss - //! @param animatedAddress identifies the component and property to be set - virtual void GetAnimatedPropertyValue(AnimatedValue& returnValue, const AnimatablePropertyAddress& animatableAddress) = 0; - - //! Set the value for an animated property at the given address on the same entity as the agent - //! @param animatedAddress identifies the component and property to be set - //! @param value the value to set - this must be instance of one of the concrete subclasses of AnimatedValue, corresponding to the type of the property referenced by the animatedAdresss - //! @return true if the value was changed. - virtual bool SetAnimatedPropertyValue(const AnimatablePropertyAddress& animatableAddress, const AnimatedValue& value) = 0; - - //! Returns the Uuid of the type that the 'getter' returns for this animatableAddress - virtual AZ::Uuid GetAnimatedAddressTypeId(const Maestro::SequenceComponentRequests::AnimatablePropertyAddress& animatableAddress) = 0; - - //! Track View will expect some components (those using AZ::Data::AssetBlends as a virtual property) to supply a GetAssetDuration event - //! so Track View can query the duration of an asset (like a motion) without having any knowledge of that that asset is. - virtual void GetAssetDuration(AnimatedValue& returnValue, AZ::ComponentId componentId, const AZ::Data::AssetId& assetId) = 0; - }; - - using SequenceAgentComponentRequestBus = AZ::EBus<SequenceAgentComponentRequests>; - -} // namespace Maestro - -namespace AZStd -{ - template <> - struct hash < Maestro::SequenceAgentEventBusId > - { - inline size_t operator()(const Maestro::SequenceAgentEventBusId& eventBusId) const - { - AZStd::hash<AZ::EntityId> entityIdHasher; - size_t retVal = entityIdHasher(eventBusId.first); - AZStd::hash_combine(retVal, eventBusId.second); - return retVal; - } - }; -} diff --git a/Code/CryEngine/CryCommon/Maestro/Bus/SequenceComponentBus.h b/Code/CryEngine/CryCommon/Maestro/Bus/SequenceComponentBus.h deleted file mode 100644 index 7aa9089991..0000000000 --- a/Code/CryEngine/CryCommon/Maestro/Bus/SequenceComponentBus.h +++ /dev/null @@ -1,842 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Math/Quaternion.h> -#include <AzCore/Math/Vector3.h> -#include <AzCore/Serialization/SerializeContext.h> -#include <AzCore/Serialization/EditContext.h> -#include <AzCore/Component/ComponentApplicationBus.h> -#include <AzCore/Component/Entity.h> -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/std/string/string.h> - -namespace Maestro -{ - /*! - * SequenceComponentRequests EBus Interface - * Messages serviced by SequenceComponents. - */ - class SequenceComponentRequests - : public AZ::ComponentBus - { - public: - /** - * helper class to define an animatable property address - */ - class AnimatablePropertyAddress - { - public: - AZ_TYPE_INFO(AnimatablePropertyAddress, "{CEE14802-F1E8-4C0A-9750-64C59C39ECE9}"); - - AnimatablePropertyAddress(AZ::ComponentId componentId, const AZStd::string& virtualPropertyName) - : m_componentId(componentId) - , m_virtualPropertyName(virtualPropertyName) {} - - AnimatablePropertyAddress() - : m_componentId(AZ::InvalidComponentId) {} - - const AZStd::string& GetVirtualPropertyName() const { return m_virtualPropertyName; } - AZ::ComponentId GetComponentId() const { return m_componentId; } - - bool operator== (const AnimatablePropertyAddress& rhs) const - { - return (m_componentId == rhs.m_componentId && m_virtualPropertyName == rhs.m_virtualPropertyName); - } - - private: - AZ::ComponentId m_componentId; // componentId of the component being animated on the sequenceAgent's entity - AZStd::string m_virtualPropertyName; // EBus virtual property name being animated on the component - }; - - /** - * Interface for an animated value to abstract the type (i.e. float/Vector3/Bool) of the value. - * - * Inherited concrete subclasses determines the actual type of the animatedValue and fills in get/set methods - * for casting to other types - */ - // forward declarations - class AnimatedFloatValue; - class AnimatedVector3Value; - class AnimatedBoolValue; - class AnimatedQuaternionValue; - class AnimatedAssetIdValue; - - class AnimatedValue - { - public: - AZ_TYPE_INFO(AnimatedValue, "{5C4BBDD6-8F80-4510-B5B8-8FA0FBD101A6}"); - - virtual ~AnimatedValue() {}; - - // Query the type of the value - virtual const AZ::Uuid& GetTypeId() const = 0; - - void GetValue(AZ::Vector3& vector3Value) const - { - vector3Value = GetVector3Value(); - } - void GetValue(AZ::Quaternion& quaternionValue) const - { - quaternionValue = GetQuaternionValue(); - } - void GetValue(float& floatValue) const - { - floatValue = GetFloatValue(); - } - void GetValue(bool& boolValue) const - { - boolValue = GetBoolValue(); - } - void GetValue(AZ::s32& s32Value) const - { - s32Value = GetS32Value(); - } - void GetValue(AZ::u32& u32Value) const - { - u32Value = GetU32Value(); - } - void GetValue(AZ::Data::AssetId& assetIdValue) const - { - assetIdValue = GetAssetIdValue(); - } - - // same as above but returning the value - virtual AZ::Quaternion GetQuaternionValue() const = 0; - virtual AZ::Vector3 GetVector3Value() const = 0; - virtual float GetFloatValue() const = 0; - virtual bool GetBoolValue() const = 0; - virtual AZ::s32 GetS32Value() const = 0; - virtual AZ::u32 GetU32Value() const = 0; - virtual const AZ::Data::AssetId& GetAssetIdValue() const = 0; - - // Set the value to the given arg. Returns true if the arg is the 'native' type of the concrete animated value - virtual bool SetValue(const AZ::Vector3& vector3Value) = 0; - virtual bool SetValue(const AZ::Quaternion& quaternionValue) = 0; - virtual bool SetValue(float floatValue) = 0; - virtual bool SetValue(bool boolValue) = 0; - virtual bool SetValue(AZ::s32 s32Value) = 0; - virtual bool SetValue(AZ::u32 u32Value) = 0; - virtual bool SetValue(const AZ::Data::AssetId& assetIdValue) = 0; - - virtual bool IsClose(const AnimatedFloatValue& rhs, float tolerance = AZ::Constants::Tolerance) const = 0; - virtual bool IsClose(const AnimatedVector3Value& rhs, float tolerance = AZ::Constants::Tolerance) const = 0; - virtual bool IsClose(const AnimatedQuaternionValue& rhs, float tolerance = AZ::Constants::Tolerance) const = 0; - virtual bool IsClose(const AnimatedBoolValue& rhs, float tolerance = AZ::Constants::Tolerance) const = 0; - virtual bool IsClose(const AnimatedAssetIdValue& rhs, float tolerance = AZ::Constants::Tolerance) const = 0; - - protected: - AnimatedValue() {} // protected constructor as the interface should never be constructed directly - it's an abstract class - }; - - class AnimatedFloatValue - : public AnimatedValue - { - public: - AZ_TYPE_INFO(AnimatedFloatValue, "{2C90BCBB-1DF2-47C8-8193-18EFE1C70E20}"); - - AnimatedFloatValue(float value = .0f) { m_value = value; } - ~AnimatedFloatValue() {} - - const AZ::Uuid& GetTypeId() const override - { - return AZ::AzTypeInfo<float>::Uuid(); - } - - AZ::Vector3 GetVector3Value() const override - { - return AZ::Vector3(m_value); - } - AZ::Quaternion GetQuaternionValue() const override - { - return AZ::Quaternion(m_value); - } - float GetFloatValue() const override - { - return m_value; - } - bool GetBoolValue() const override - { - return (!AZ::IsClose(m_value, .0f, FLT_EPSILON)); - } - AZ::s32 GetS32Value() const override - { - return static_cast<AZ::s32>(m_value); - } - AZ::u32 GetU32Value() const override - { - return static_cast<AZ::u32>(m_value); - } - const AZ::Data::AssetId& GetAssetIdValue() const override - { - AZ_Assert(0, "Not expected to be used."); - static AZ::Data::AssetId assetId; - return assetId; - } - - bool SetValue(const AZ::Vector3& vector3Value) override - { - m_value = vector3Value.GetX(); - return false; - } - bool SetValue(const AZ::Quaternion& quaternionValue) override - { - m_value = quaternionValue.GetLength(); - return false; - } - bool SetValue(float floatValue) override - { - m_value = floatValue; - return true; - } - bool SetValue(bool boolValue) override - { - m_value = boolValue ? 1.0f : .0f; - return false; - } - bool SetValue(AZ::s32 s32Value) override - { - m_value = static_cast<float>(s32Value); - return false; - } - bool SetValue(AZ::u32 u32Value) override - { - m_value = static_cast<float>(u32Value); - return false; - } - bool SetValue(const AZ::Data::AssetId& assetIdValue) override - { - AZ_UNUSED(assetIdValue); - return true; - } - - bool IsClose(const AnimatedFloatValue& rhs, float tolerance = AZ::Constants::FloatEpsilon) const override - { - return AZ::IsClose(m_value, rhs.GetFloatValue(), tolerance); - } - bool IsClose(const AnimatedVector3Value& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - return AZ::IsClose(m_value, rhs.GetFloatValue(), tolerance); - } - bool IsClose(const AnimatedQuaternionValue& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - return AZ::IsClose(m_value, rhs.GetFloatValue(), tolerance); - } - bool IsClose(const AnimatedBoolValue& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - return rhs.GetBoolValue() == (!AZ::IsClose(m_value, .0f, tolerance)); - } - bool IsClose(const AnimatedAssetIdValue& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - AZ_Assert(0, "Shouldnt be used."); - AZ_UNUSED(rhs); - AZ_UNUSED(tolerance); - return false; - } - - private: - float m_value; - }; - - class AnimatedVector3Value - : public AnimatedValue - { - public: - AZ_TYPE_INFO(AnimatedVector3Value, "{B8CDD566-9D55-47B2-BF91-162E428B237E}"); - - AnimatedVector3Value(const AZ::Vector3& value) { m_value = value; } - ~AnimatedVector3Value() {} - - const AZ::Uuid& GetTypeId() const override - { - return AZ::Vector3::TYPEINFO_Uuid(); - } - - AZ::Vector3 GetVector3Value() const override - { - return m_value; - } - AZ::Quaternion GetQuaternionValue() const override - { - // treat m_value as Euler Angles in degrees - return AZ::ConvertEulerDegreesToQuaternion(m_value); - } - float GetFloatValue() const override - { - return m_value.GetX(); // return the first component - } - bool GetBoolValue() const override - { - return !m_value.IsClose(AZ::Vector3::CreateZero()); - } - AZ::s32 GetS32Value() const override - { - return static_cast<AZ::s32>(m_value.GetX()); - } - AZ::u32 GetU32Value() const override - { - return static_cast<AZ::u32>(m_value.GetX()); - } - const AZ::Data::AssetId& GetAssetIdValue() const override - { - AZ_Assert(0, "Not expected to be used."); - static AZ::Data::AssetId assetId; - return assetId; - } - - bool SetValue(const AZ::Vector3& vector3Value) override - { - m_value = vector3Value; - return true; - } - bool SetValue(const AZ::Quaternion& quaternionValue) override - { - m_value = AZ::ConvertQuaternionToEulerDegrees(quaternionValue); - return true; - } - bool SetValue(float floatValue) override - { - m_value.Set(floatValue); // sets vector components to floatValue - return false; - } - bool SetValue(bool boolValue) override - { - m_value = boolValue ? AZ::Vector3::CreateOne() : AZ::Vector3::CreateZero(); - return false; - } - bool SetValue(AZ::s32 s32Value) override - { - m_value.Set(static_cast<float>(s32Value)); - return false; - } - bool SetValue(AZ::u32 u32Value) override - { - m_value.Set(static_cast<float>(u32Value)); - return false; - } - bool SetValue(const AZ::Data::AssetId& assetIdValue) override - { - AZ_UNUSED(assetIdValue); - return true; - } - - bool IsClose(const AnimatedFloatValue& rhs, float tolerance = AZ::Constants::FloatEpsilon) const override - { - return m_value.IsClose(rhs.GetVector3Value(), tolerance); - } - bool IsClose(const AnimatedVector3Value& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - return m_value.IsClose(rhs.GetVector3Value(), tolerance); - } - bool IsClose(const AnimatedQuaternionValue& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - return m_value.IsClose(rhs.GetVector3Value(), tolerance); - } - bool IsClose(const AnimatedBoolValue& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - return rhs.GetBoolValue() == (!m_value.IsClose(AZ::Vector3::CreateZero(), tolerance)); - } - bool IsClose(const AnimatedAssetIdValue& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - AZ_Assert(0, "Shouldn't be used."); - AZ_UNUSED(rhs); - AZ_UNUSED(tolerance); - return false; - } - - private: - AZ::Vector3 m_value; - }; - - class AnimatedQuaternionValue - : public AnimatedValue - { - public: - AZ_TYPE_INFO(AnimatedQuaternionValue, "{572E640B-9375-4E16-8F3A-5DCA1734B820}"); - - AnimatedQuaternionValue(const AZ::Quaternion value) { m_value = value; } - ~AnimatedQuaternionValue() {} - - const AZ::Uuid& GetTypeId() const override - { - return AZ::Quaternion::TYPEINFO_Uuid(); - } - - AZ::Vector3 GetVector3Value() const override - { - // convert Quaternion to Euler angles - return AZ::ConvertQuaternionToEulerDegrees(m_value); - } - AZ::Quaternion GetQuaternionValue() const override - { - return m_value; - } - float GetFloatValue() const override - { - // return the length of the quat - return m_value.GetLength(); - } - bool GetBoolValue() const override - { - return !m_value.IsZero(); - } - AZ::s32 GetS32Value() const override - { - return static_cast<AZ::s32>(m_value.GetLength()); - } - AZ::u32 GetU32Value() const override - { - return static_cast<AZ::u32>(m_value.GetLength()); - } - const AZ::Data::AssetId& GetAssetIdValue() const override - { - AZ_Assert(0, "Not expected to be used."); - static AZ::Data::AssetId assetId; - return assetId; - } - - bool SetValue(const AZ::Vector3& vector3Value) override - { - // convert from Euler angles - m_value = AZ::ConvertEulerRadiansToQuaternion(vector3Value); - return false; - } - bool SetValue(const AZ::Quaternion& quaternionValue) override - { - m_value = quaternionValue; - return true; - } - bool SetValue(float floatValue) override - { - m_value.Set(floatValue); // sets quat with all components set to floatValue - return false; - } - bool SetValue(bool boolValue) override - { - m_value = boolValue ? AZ::Quaternion::CreateIdentity() : AZ::Quaternion::CreateZero(); - return false; - } - bool SetValue(AZ::s32 s32Value) override - { - m_value.Set(static_cast<float>(s32Value)); - return false; - } - bool SetValue(AZ::u32 u32Value) override - { - m_value.Set(static_cast<float>(u32Value)); - return false; - } - bool SetValue(const AZ::Data::AssetId& assetIdValue) override - { - AZ_UNUSED(assetIdValue); - return true; - } - - bool IsClose(const AnimatedFloatValue& rhs, float tolerance = AZ::Constants::FloatEpsilon) const override - { - return m_value.IsClose(rhs.GetQuaternionValue(), tolerance); - } - bool IsClose(const AnimatedVector3Value& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - return m_value.IsClose(rhs.GetQuaternionValue(), tolerance); - } - bool IsClose(const AnimatedQuaternionValue& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - return m_value.IsClose(rhs.m_value, tolerance); - } - bool IsClose(const AnimatedBoolValue& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - return rhs.GetBoolValue() == (!m_value.IsZero(tolerance)); - } - bool IsClose(const AnimatedAssetIdValue& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - AZ_Assert(0, "Shouldn't be used."); - AZ_UNUSED(rhs); - AZ_UNUSED(tolerance); - return false; - } - - private: - AZ::Quaternion m_value; - }; - - class AnimatedBoolValue - : public AnimatedValue - { - public: - AZ_TYPE_INFO(AnimatedBoolValue, "{5FF422AD-20E7-4109-A2EA-4AACE8213860}"); - - AnimatedBoolValue(bool value) { m_value = value; } - ~AnimatedBoolValue() {} - - const AZ::Uuid& GetTypeId() const override - { - return AZ::AzTypeInfo<bool>::Uuid(); - } - - AZ::Vector3 GetVector3Value() const override - { - return m_value ? AZ::Vector3::CreateOne() : AZ::Vector3::CreateZero();; - } - AZ::Quaternion GetQuaternionValue() const override - { - return m_value ? AZ::Quaternion::CreateIdentity() : AZ::Quaternion::CreateZero();; - } - float GetFloatValue() const override - { - return m_value ? 1.0f : .0f; - } - bool GetBoolValue() const override - { - return m_value; - } - AZ::s32 GetS32Value() const override - { - return m_value ? 1 : 0; - } - AZ::u32 GetU32Value() const override - { - return m_value ? 1 : 0; - } - const AZ::Data::AssetId& GetAssetIdValue() const override - { - AZ_Assert(0, "Not expected to be used."); - static AZ::Data::AssetId assetId; - return assetId; - } - - bool SetValue(const AZ::Vector3& vector3Value) override - { - m_value = !vector3Value.IsClose(AZ::Vector3::CreateZero()); - return false; - } - bool SetValue(const AZ::Quaternion& quaternionValue) override - { - m_value = !quaternionValue.IsZero(); - return false; - } - bool SetValue(float floatValue) override - { - m_value = !AZ::IsClose(floatValue, .0f, FLT_EPSILON); - return false; - } - bool SetValue(bool boolValue) override - { - m_value = boolValue; - return true; - } - bool SetValue(AZ::s32 s32Value) override - { - m_value = s32Value != 0; - return false; - } - bool SetValue(AZ::u32 u32Value) override - { - m_value = u32Value != 0; - return false; - } - bool SetValue(const AZ::Data::AssetId& assetIdValue) override - { - AZ_UNUSED(assetIdValue); - return true; - } - - bool IsClose(const AnimatedFloatValue& rhs, float tolerance = AZ::Constants::FloatEpsilon) const override - { - return m_value == (!AZ::IsClose(rhs.GetFloatValue(), .0f, tolerance)); - } - bool IsClose(const AnimatedVector3Value& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - return m_value == (!rhs.GetVector3Value().IsClose(AZ::Vector3::CreateZero(), tolerance)); - } - bool IsClose(const AnimatedQuaternionValue& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - return m_value == (!rhs.GetQuaternionValue().IsZero(tolerance)); - } - bool IsClose(const AnimatedBoolValue& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - (void)tolerance; // avoid compiler warning for unused variable - return m_value == rhs.m_value; - } - bool IsClose(const AnimatedAssetIdValue& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - AZ_Assert(0, "Shouldn't be used."); - AZ_UNUSED(rhs); - AZ_UNUSED(tolerance); - return false; - } - - private: - bool m_value; - }; - - class AnimatedAssetIdValue - : public AnimatedValue - { - public: - AZ_TYPE_INFO(AnimatedAssetIdValue, "{BA8AFA84-44C7-4358-AB35-775AF2B8A109}"); - - AnimatedAssetIdValue() { m_value.SetInvalid(); } - AnimatedAssetIdValue(const AZ::Data::AssetId& value) { m_value = value; } - - const AZ::Uuid& GetTypeId() const override - { - return AZ::AzTypeInfo<AZ::Data::AssetId>::Uuid(); - } - - AZ::Vector3 GetVector3Value() const override - { - return AZ::Vector3::CreateZero();; - } - AZ::Quaternion GetQuaternionValue() const override - { - return AZ::Quaternion::CreateZero();; - } - float GetFloatValue() const override - { - return 0.0f; - } - bool GetBoolValue() const override - { - return false; - } - AZ::s32 GetS32Value() const override - { - return 0; - } - AZ::u32 GetU32Value() const override - { - return 0; - } - const AZ::Data::AssetId& GetAssetIdValue() const override - { - return m_value; - } - - bool SetValue(const AZ::Vector3& vector3Value) override - { - AZ_UNUSED(vector3Value); - return false; - } - bool SetValue(const AZ::Quaternion& quaternionValue) override - { - AZ_UNUSED(quaternionValue); - return false; - } - bool SetValue(float floatValue) override - { - AZ_UNUSED(floatValue); - return false; - } - bool SetValue(bool boolValue) override - { - AZ_UNUSED(boolValue); - return true; - } - bool SetValue(AZ::s32 s32Value) override - { - AZ_UNUSED(s32Value); - return false; - } - bool SetValue(AZ::u32 u32Value) override - { - AZ_UNUSED(u32Value); - return false; - } - bool SetValue(const AZ::Data::AssetId& assetIdValue) override - { - m_value = assetIdValue; - return true; - } - - bool IsClose([[maybe_unused]] const AnimatedFloatValue& rhs, float tolerance = AZ::Constants::FloatEpsilon) const override - { - AZ_UNUSED(tolerance); - return false; - } - bool IsClose([[maybe_unused]] const AnimatedVector3Value& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - AZ_UNUSED(tolerance); - return false; - } - bool IsClose([[maybe_unused]] const AnimatedQuaternionValue& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - AZ_UNUSED(tolerance); - return false; - } - bool IsClose([[maybe_unused]] const AnimatedBoolValue& rhs, float tolerance = AZ::Constants::Tolerance) const override - { - AZ_UNUSED(tolerance); - return false; - } - bool IsClose(const AnimatedAssetIdValue& rhs, [[maybe_unused]] float tolerance = AZ::Constants::Tolerance) const override - { - return m_value == rhs.m_value; - } - - private: - AZ::Data::AssetId m_value; - }; - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - application is a singleton - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; // Only one component on a entity can implement the events - ////////////////////////////////////////////////////////////////////////// - - /** - * Set a value for an animated property at the given address on the given entity. - * @param animatedEntityId the entity Id of the entity containing the animatedAddress - * @param animatedAddress identifies the component and property to be set - * @param value the value to set - this must be instance of one of the concrete subclasses of AnimatedValue, corresponding to the type of the property referenced by the animatedAdresss - * @return true if the value was changed. - */ - virtual bool SetAnimatedPropertyValue(const AZ::EntityId& animatedEntityId, const AnimatablePropertyAddress& animatableAddress, const AnimatedValue& value) = 0; - - /** - * Get the current value for a property - * @param returnValue holds the value to get - this must be instance of one of the concrete subclasses of AnimatedValue, corresponding to the type of the property referenced by the animatedAdresss - * @param animatedEntityId the entity Id of the entity containing the animatedAddress - * @param animatedAddress identifies the component and property to be set - */ - virtual void GetAnimatedPropertyValue(AnimatedValue& returnValue, const AZ::EntityId& animatedEntityId, const AnimatablePropertyAddress& animatableAddress) = 0; - - /** Returns the Uuid of the type for the property at the animatableAddress on the given entityId - */ - virtual AZ::Uuid GetAnimatedAddressTypeId(const AZ::EntityId& enityId, const Maestro::SequenceComponentRequests::AnimatablePropertyAddress& animatableAddress) = 0; - - /** - * Track View will expect some components to supply a GetAssetDuration event so Track View can query the duration of an asset (like a motion) - * without having any knowledge of that that asset is. - */ - virtual void GetAssetDuration(AnimatedValue& returnValue, const AZ::EntityId& animatedEntityId, AZ::ComponentId componentId, const AZ::Data::AssetId& assetId) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Behaviors - /** - * Play sequence from the start to end times set the sequence - */ - virtual void Play() {} - /** - * Play sequence between the start to end times, outside of which the sequence behaves according to its 'Out of Range' time setting - * @param startTime Sequence start time in seconds - * @param endTime Sequence end time in seconds - */ - virtual void PlayBetweenTimes(float startTime, float endTime) {(void)startTime; (void)endTime;} - /** - * Stop the sequence. Stopping the sequence jumps the play time to the end of the sequence. - */ - virtual void Stop() {} - /** - * Pause the sequence. Sequence must be playing for pause to have an effect. Pausing leaves the play time at its current position. - */ - virtual void Pause() {} - /** - * Resume the sequence. Resume essentially 'unpauses' a sequence. It must have been playing before the pause for playback to start again. - */ - virtual void Resume() {} - /** - * Set the play speed - * @param newSpeed speed multiplier (1.0 is normal speed, less is slower, more is faster). - */ - virtual void SetPlaySpeed(float newSpeed) {(void)newSpeed;} - /** - * Move the Playhead to the given time - * @param time time to move the play head to, in seconds, clamped to be between the start and end times of the sequence - */ - virtual void JumpToTime(float newTime) {(void)newTime;} - /** - * Move the Playhead to the end of the sequence - */ - virtual void JumpToEnd() {} - /** - * Move the Playhead to the beginning of the sequence - */ - virtual void JumpToBeginning() {} - /** - * Returns the current play time in seconds - */ - virtual float GetCurrentPlayTime() { return .0f; } - /** - * Returns the current play back speed as a multiplier (1.0 is normal speed, less is slower, more is faster). - */ - virtual float GetPlaySpeed() { return 1.0f; } - ////////////////////////////////////////////////////////////////////////// - }; - using SequenceComponentRequestBus = AZ::EBus<SequenceComponentRequests>; - - /** - * Notifications from the Sequence Component - */ - class SequenceComponentNotification - : public AZ::ComponentBus - { - public: - //////////////////////////////////////////////////////////////////////// - // EBusTraits - // multiple handlers (addressed by AZ::EntityId inherited from AZ::ComponentBus) - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - //////////////////////////////////////////////////////////////////////// - - virtual ~SequenceComponentNotification() {} - - /** - * Called when Sequence starts - * @param startTime Time when sequence starts, in seconds - */ - virtual void OnStart(float startTime) { (void)startTime; } - /** - * Called when Sequence stops - * @param stopTime Time when the sequence stops, in seconds - */ - virtual void OnStop(float stopTime) { (void)stopTime; } - /** - * Called when Sequence pauses - */ - virtual void OnPause() {} - /** - * Called when Sequence resumes - */ - virtual void OnResume() {} - /** - * Called when Sequence is aborted - * @param abortTime Time when the sequence aborts, in seconds - */ - virtual void OnAbort(float abortTime) { (void)abortTime; } - /** - * Called when Sequence is updated. That is, when the current play time changes, or the playback speed changes. - * @param updateTime Time when the sequence updates, in seconds - */ - virtual void OnUpdate(float updateTime) { (void)updateTime; } - /** - * Called when a Sequence Event is triggered. - * @param paramValue The Event Key's Value parameter as a string - */ - virtual void OnTrackEventTriggered(const char* eventName, const char* eventValue) { (void)eventName; (void)eventValue; } - /** - * Called when a Sequence changes camera during playback in Track View. - * @param cameraEntityId entityId of the new camera. - */ - virtual void OnCameraChanged([[maybe_unused]] const AZ::EntityId& oldCameraEntityId, [[maybe_unused]] const AZ::EntityId& newCameraEntityId) {} - }; - - using SequenceComponentNotificationBus = AZ::EBus<SequenceComponentNotification>; -} // namespace Maestro - -namespace AZStd -{ - template <> - struct hash < Maestro::SequenceComponentRequests::AnimatablePropertyAddress > - { - inline size_t operator()(const Maestro::SequenceComponentRequests::AnimatablePropertyAddress& animatablePropertyAddress) const - { - AZStd::hash<AZ::ComponentId> componentIdHasher; - size_t retVal = componentIdHasher(animatablePropertyAddress.GetComponentId()); - AZStd::hash_combine(retVal, animatablePropertyAddress.GetVirtualPropertyName()); - return retVal; - } - }; -} // namespace AZStd diff --git a/Code/CryEngine/CryCommon/Maestro/Types/AnimNodeType.h b/Code/CryEngine/CryCommon/Maestro/Types/AnimNodeType.h deleted file mode 100644 index 67eea7b21d..0000000000 --- a/Code/CryEngine/CryCommon/Maestro/Types/AnimNodeType.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_ANIMNODETYPE_H -#define CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_ANIMNODETYPE_H -#pragma once - -// **NOTE**: Do not include into the precompiled header hierarchy! - -////////////////////////////////////////////////////////////////////////// -//! Node-Types -// -// You need to register new types in Movie.cpp/RegisterNodeTypes for serialization. -// Note: Enums are serialized by string now, there is no need for specific IDs -// anymore for new parameters. Values are for backward compatibility. -enum class AnimNodeType -{ - Invalid = 0x00, - Entity = 0x01, // Legacy Cry Entities (CE is AzEntity) - Director = 0x02, - Camera = 0x03, // Legacy Cry Camera Object - CVar = 0x04, - ScriptVar = 0x05, - Material = 0x06, - Event = 0x07, - Group = 0x08, - Layer = 0x09, - Comment = 0x10, - RadialBlur = 0x11, - ColorCorrection = 0x12, - DepthOfField = 0x13, - ScreenFader = 0x14, - Light = 0x15, // Legacy Cry Light - // HDRSetup = 0x16, // deprecated Jan 2016 - ShadowSetup = 0x17, - Alembic = 0x18, // Used in cinebox, added so nobody uses that number - GeomCache = 0x19, - Environment, - ScreenDropsSetup, // deprecated Jan 2016 - AzEntity, - Component, - Num -}; - -#endif // CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_ANIMNODETYPE_H diff --git a/Code/CryEngine/CryCommon/Maestro/Types/AnimParamType.h b/Code/CryEngine/CryCommon/Maestro/Types/AnimParamType.h deleted file mode 100644 index 3218769cc1..0000000000 --- a/Code/CryEngine/CryCommon/Maestro/Types/AnimParamType.h +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_ANIMPARAMTYPE_H -#define CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_ANIMPARAMTYPE_H -#pragma once - -// **NOTES**: Do not include into the precompiled header hierarchy! -// There are a couple legacy defines in IMovieSystem.h that -// correspond to these values. ByString and Invalid. - -// Static common parameters IDs of animation node. -// -// You need to register new params in Movie.cpp/RegisterParamTypes for serialization. -// Note: Enums are serialized by string now, there is no need for specific IDs -// anymore for new parameters. Values are for backward compatibility. -// -// If you want to expand CryMovie to control new stuff this is probably the enum you want to change. -// For named params see AnimParamType::ByString & CAnimParamType -enum class AnimParamType -{ - // Parameter is specified by string. See CAnimParamType - ByString = 8, - - FOV = 0, - Position = 1, - Rotation = 2, - Scale = 3, - Event = 4, - Visibility = 5, - Camera = 6, - Animation = 7, - Sound = 10, - Sequence = 13, - // Expression = 14, ///@deprecated Jan 2016 - Console = 17, - Music = 18, ///@deprecated in 1.11, July 2017 - left in for legacy serialization - Float = 19, - // FaceSequence = 20, ///@deprecated Jan 2016 - LookAt = 21, - TrackEvent = 22, - - ShakeAmplitudeA = 23, - ShakeAmplitudeB = 24, - ShakeFrequencyA = 25, - ShakeFrequencyB = 26, - ShakeMultiplier = 27, - ShakeNoise = 28, - ShakeWorking = 29, - ShakeAmpAMult = 61, - ShakeAmpBMult = 62, - ShakeFreqAMult = 63, - ShakeFreqBMult = 64, - - DepthOfField = 30, - FocusDistance = 31, - FocusRange = 32, - BlurAmount = 33, - - Capture = 34, - TransformNoise = 35, - TimeWarp = 36, - FixedTimeStep = 37, - NearZ = 38, - Goto = 39, - - PositionX = 51, - PositionY = 52, - PositionZ = 53, - - RotationX = 54, - RotationY = 55, - RotationZ = 56, - - ScaleX = 57, - ScaleY = 58, - ScaleZ = 59, - - ColorR = 82, - ColorG = 83, - ColorB = 84, - - CommentText = 70, - ScreenFader = 71, - - LightDiffuse = 81, - LightRadius = 85, - LightDiffuseMult = 86, - LightHDRDynamic = 87, - LightSpecularMult = 88, - LightSpecPercentage = 89, - - MaterialDiffuse = 90, - MaterialSpecular = 91, - MaterialEmissive = 92, - // MaterialEmissiveIntensity = 99, // declared below to keep enumerations in order - MaterialOpacity = 93, - MaterialSmoothness = 94, - - TimeRanges = 95, //!< Generic track with keys that have time ranges - - Physics = 96, //! Not used anymore, see Physicalize & PhysicsDriven - - ProceduralEyes = 97, - - Unused = 98, //!< Mannequin parameter that was removed. - - MaterialEmissiveIntensity = 99, - - // Add new param types without explicit ID here: - // NOTE: don't forget to register in Movie.cpp - - GSMCache, - - ShutterSpeed, - - Physicalize, - PhysicsDriven, - - SunLongitude, - SunLatitude, - MoonLongitude, - MoonLatitude, - - User = 100000, //!< User node params. - - Invalid = static_cast<int>(0xFFFFFFFF) -}; - -static const int OLD_APARAM_USER = 100; - -#endif // CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_ANIMPARAMTYPE_H diff --git a/Code/CryEngine/CryCommon/Maestro/Types/AnimValue.h b/Code/CryEngine/CryCommon/Maestro/Types/AnimValue.h deleted file mode 100644 index 73a3388678..0000000000 --- a/Code/CryEngine/CryCommon/Maestro/Types/AnimValue.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_ANIMVALUE_H -#define CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_ANIMVALUE_H -#pragma once - -// **NOTE**: Do not include into the precompiled header hierarchy! - -//! Values that animation track can hold. -// Do not change values! they are serialized -// -// Attention: This should only be expanded if you add a completely new value type that tracks can control! -// If you just want to control a new parameter of an entity etc. extend EParamType -// -// Note: If the param type of a track is known and valid these can be derived from the node. -// These are serialized in case the parameter got invalid (for example for material nodes) -// -enum class AnimValue -{ - Float = 0, - Vector = 1, - Quat = 2, - Bool = 3, - Select = 5, - Vector4 = 15, - DiscreteFloat = 16, - RGB = 20, - CharacterAnim = 21, - - Unknown = static_cast<int>(0xFFFFFFFF) -}; - - -#endif CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_ANIMVALUE_H diff --git a/Code/CryEngine/CryCommon/Maestro/Types/AnimValueType.h b/Code/CryEngine/CryCommon/Maestro/Types/AnimValueType.h deleted file mode 100644 index bf3f7c245d..0000000000 --- a/Code/CryEngine/CryCommon/Maestro/Types/AnimValueType.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_ANIMVALUETYPE_H -#define CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_ANIMVALUETYPE_H -#pragma once - -// **NOTES**: Do not include into the precompiled header hierarchy! -// There are a couple legacy defines in IMovieSystem.h that -// correspond to these values. Unknown and Float. - -//! Values that animation track can hold. -// Do not change values! they are serialized -// -// Attention: This should only be expanded if you add a completely new value type that tracks can control! -// If you just want to control a new parameter of an entity etc. extend EParamType -// -// Note: If the param type of a track is known and valid these can be derived from the node. -// These are serialized in case the parameter got invalid (for example for material nodes) -// -enum class AnimValueType -{ - Float = 0, - Vector = 1, - Quat = 2, - Bool = 3, - Select = 5, - Vector4 = 15, - DiscreteFloat = 16, - RGB = 20, - CharacterAnim = 21, - AssetBlend = 22, - - Unknown = static_cast<int>(0xFFFFFFFF) -}; - - -#endif // CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_ANIMVALUETYPE_H diff --git a/Code/CryEngine/CryCommon/Maestro/Types/AssetBlendKey.h b/Code/CryEngine/CryCommon/Maestro/Types/AssetBlendKey.h deleted file mode 100644 index 0d82272543..0000000000 --- a/Code/CryEngine/CryCommon/Maestro/Types/AssetBlendKey.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Asset/AssetCommon.h> - -namespace AZ -{ - -/** IAssetBlendKey used in AssetBlend animation track. -*/ -struct IAssetBlendKey - : public ITimeRangeKey -{ - AZ::Data::AssetId m_assetId; //!< Asset Id - AZStd::string m_description; //!< Description (filename part of path) - float m_blendInTime; //!< Blend in time in seconds; - float m_blendOutTime; //!< Blend in time in seconds; - - IAssetBlendKey() - : ITimeRangeKey() - , m_blendInTime(0.0f) - , m_blendOutTime(0.0f) - { - } -}; - - AZ_TYPE_INFO_SPECIALIZE(IAssetBlendKey, "{15B82C3A-6DB8-466F-AF7F-18298FCD25FD}"); -} diff --git a/Code/CryEngine/CryCommon/Maestro/Types/AssetBlends.h b/Code/CryEngine/CryCommon/Maestro/Types/AssetBlends.h deleted file mode 100644 index b3f6bcfd5b..0000000000 --- a/Code/CryEngine/CryCommon/Maestro/Types/AssetBlends.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include <AzCore/Serialization/SerializeContext.h> -#include <AzCore/Asset/AssetCommon.h> - -namespace Maestro -{ - /** - * AssetBlend type - */ - struct AssetBlend - { - AZ_TYPE_INFO(AssetBlend, "{90EB921C-456C-4CD8-A487-414219CF123B}"); - - AssetBlend() - : m_time(0.0f) - , m_blendInTime(0.0f) - , m_blendOutTime(0.0f) - { - m_assetId.SetInvalid(); - } - - AssetBlend(const AZ::Data::AssetId& assetId, float time, float blendInTime, float blendOutTime) - : m_assetId(assetId) - , m_time(time) - , m_blendInTime(blendInTime) - , m_blendOutTime(blendOutTime) - { - } - - bool IsClose(const AssetBlend& rhs, float tolerance) const - { - return m_assetId == rhs.m_assetId - && (fabsf(m_time - rhs.m_time) <= tolerance) - && (fabsf(m_blendInTime - rhs.m_blendInTime) <= tolerance) - && (fabsf(m_blendOutTime - rhs.m_blendOutTime) <= tolerance); - } - - AZ::Data::AssetId m_assetId; - float m_time; - float m_blendInTime; - float m_blendOutTime; - }; - - /** - * AssetBlends type - */ - template<typename AssetType> - struct AssetBlends - { - AZ_TYPE_INFO(AssetBlends<AssetType>, "{636A51DA-48E8-4AF9-8310-541E735F2703}"); - AZStd::vector<AssetBlend> m_assetBlends; - - bool IsClose(const AssetBlends& rhs, float tolerance) const - { - bool result = m_assetBlends.size() == rhs.m_assetBlends.size(); - - for (int x = 0; result && (x < m_assetBlends.size()); x++) - { - result = m_assetBlends[x].IsClose(rhs.m_assetBlends[x], tolerance); - } - - return result; - } - }; - -} // namespace Maestro diff --git a/Code/CryEngine/CryCommon/Maestro/Types/SequenceType.h b/Code/CryEngine/CryCommon/Maestro/Types/SequenceType.h deleted file mode 100644 index 6eaa8df451..0000000000 --- a/Code/CryEngine/CryCommon/Maestro/Types/SequenceType.h +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_SEQUENCETYPE_H -#define CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_SEQUENCETYPE_H -#pragma once - -// **NOTES**: Do not include into the precompiled header hierarchy! -// There is a legacy define in IMovieSystem.h that -// correspond to a value, Legacy. - -enum class SequenceType -{ - Legacy = 0, // legacy CryEntity Sequence Object - SequenceComponent = 1 // Sequence Component on an AZ::Entity -}; - -#endif // CRYINCLUDE_CRYCOMMON_MAESTRO_TYPES_SEQUENCETYPE_H diff --git a/Code/CryEngine/CryCommon/MainThreadRenderRequestBus.h b/Code/CryEngine/CryCommon/MainThreadRenderRequestBus.h deleted file mode 100644 index db20c9cf88..0000000000 --- a/Code/CryEngine/CryCommon/MainThreadRenderRequestBus.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <AzCore/Component/ComponentBus.h> -#include <AzCore/std/parallel/mutex.h> - -namespace AZ -{ - /** - * Used to queue render commands to be safely executed on the main thread - */ - class MainThreadRenderQueueEvents - : public AZ::EBusTraits - { - public: - - virtual ~MainThreadRenderQueueEvents() {} - - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = EBusHandlerPolicy::Single; - static const bool EnableEventQueue = true; - typedef AZStd::mutex EventQueueMutexType; - }; - - using MainThreadRenderRequestBus = AZ::EBus<MainThreadRenderQueueEvents>; -} diff --git a/Code/CryEngine/CryCommon/MathConversion.h b/Code/CryEngine/CryCommon/MathConversion.h deleted file mode 100644 index 39426031e3..0000000000 --- a/Code/CryEngine/CryCommon/MathConversion.h +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include <AzCore/Math/Aabb.h> -#include <AzCore/Math/Obb.h> -#include <AzCore/Math/Vector2.h> -#include <AzCore/Math/Vector3.h> -#include <AzCore/Math/Vector4.h> -#include <AzCore/Math/Color.h> -#include <AzCore/Math/Transform.h> -#include <AzCore/Math/Matrix3x3.h> -#include <AzCore/Math/Matrix3x4.h> -#include <AzCore/Math/Quaternion.h> -#include <AzCore/Component/EntityId.h> -#include <AzCore/Math/Plane.h> -#include <Cry_Math.h> -#include <Cry_Geo.h> -#include <Cry_Color.h> - -inline AZ::Vector2 LYVec2ToAZVec2(const Vec2& source) -{ - return AZ::Vector2(source.x, source.y); -} - -inline Vec2 AZVec2ToLYVec2(const AZ::Vector2& source) -{ - return Vec2(source.GetX(), source.GetY()); -} - -inline AZ::Vector3 LYVec3ToAZVec3(const Vec3& source) -{ - return AZ::Vector3(source.x, source.y, source.z); -} - -inline Vec3 AZVec3ToLYVec3(const AZ::Vector3& source) -{ - return Vec3(source.GetX(), source.GetY(), source.GetZ()); -} - -inline AZ::Vector4 LYVec4ToAZVec4(const Vec4& source) -{ - return AZ::Vector4(source.x, source.y, source.z, source.w); -} - -inline Vec4 AZVec4ToLYVec4(const AZ::Vector4& source) -{ - return Vec4(source.GetX(), source.GetY(), source.GetZ(), source.GetW()); -} - -inline AZ::Color LYVec3ToAZColor(const Vec3& source) -{ - return AZ::Color(source.x, source.y, source.z, 1.0f); -} - -inline Vec3 AZColorToLYVec3(const AZ::Color& source) -{ - return Vec3(source.GetR(), source.GetG(), source.GetB()); -} - -inline Vec4 AZColorToLYVec4(const AZ::Color& source) -{ - return Vec4(source.GetR(), source.GetG(), source.GetB(), source.GetA()); -} - -inline ColorF AZColorToLYColorF(const AZ::Color& source) -{ - return ColorF(source.ToU32()); -} - -inline AZ::Color LYColorFToAZColor(const ColorF& source) -{ - return AZ::Color(source.r, source.g, source.b, source.a); -} - -inline ColorB AZColorToLYColorB(const AZ::Color& source) -{ - return ColorB(source.ToU32()); -} - -inline AZ::Color LYColorBToAZColor(const ColorB& source) -{ - return AZ::Color(source.r, source.g, source.b, source.a); -} - - -inline AZ::Quaternion LYQuaternionToAZQuaternion(const Quat& source) -{ - const float f4[4] = { source.v.x, source.v.y, source.v.z, source.w }; - return AZ::Quaternion::CreateFromFloat4(f4); -} - -inline Quat AZQuaternionToLYQuaternion(const AZ::Quaternion& source) -{ - float f4[4]; - source.StoreToFloat4(f4); - return Quat(f4[3], f4[0], f4[1], f4[2]); -} - -inline Matrix34 AZTransformToLYTransform(const AZ::Transform& source) -{ - return Matrix34::CreateFromVectors( - AZVec3ToLYVec3(source.GetBasisX()), - AZVec3ToLYVec3(source.GetBasisY()), - AZVec3ToLYVec3(source.GetBasisZ()), - AZVec3ToLYVec3(source.GetTranslation())); -} - -inline Matrix33 AZMatrix3x3ToLYMatrix3x3(const AZ::Matrix3x3& source) -{ - return Matrix33::CreateFromVectors( - AZVec3ToLYVec3(source.GetColumn(0)), - AZVec3ToLYVec3(source.GetColumn(1)), - AZVec3ToLYVec3(source.GetColumn(2))); -} - -inline AZ::Matrix3x3 LyMatrix3x3ToAzMatrix3x3(const Matrix33& source) -{ - return AZ::Matrix3x3::CreateFromColumns( - LYVec3ToAZVec3(source.GetColumn(0)), - LYVec3ToAZVec3(source.GetColumn(1)), - LYVec3ToAZVec3(source.GetColumn(2))); -} - -inline Matrix34 AZMatrix3x4ToLYMatrix3x4(const AZ::Matrix3x4& source) -{ - AZ::Vector3 col0; - AZ::Vector3 col1; - AZ::Vector3 col2; - AZ::Vector3 col3; - source.GetBasisAndTranslation(&col0, &col1, &col2, &col3); - - return Matrix34( - col0.GetX(), col1.GetX(), col2.GetX(), col3.GetX(), - col0.GetY(), col1.GetY(), col2.GetY(), col3.GetY(), - col0.GetZ(), col1.GetZ(), col2.GetZ(), col3.GetZ()); -} - -inline AZ::Transform LYTransformToAZTransform(const Matrix34& source) -{ - const AZ::Matrix3x4 matrix3x4 = AZ::Matrix3x4::CreateFromRowMajorFloat12(source.GetData()); - return AZ::Transform::CreateFromMatrix3x4(matrix3x4); -} - -inline AZ::Matrix3x4 LYTransformToAZMatrix3x4(const Matrix34& source) -{ - return AZ::Matrix3x4::CreateFromRowMajorFloat12(source.GetData()); -} - -inline AZ::Transform LYQuatTToAZTransform(const QuatT& source) -{ - return AZ::Transform::CreateFromQuaternionAndTranslation( - LYQuaternionToAZQuaternion(source.q), - LYVec3ToAZVec3(source.t)); -} - -inline QuatT AZTransformToLYQuatT(const AZ::Transform& source) -{ - return QuatT( - AZQuaternionToLYQuaternion(source.GetRotation()), - AZVec3ToLYVec3(source.GetTranslation())); -} - -inline QuatT AZMatrix3x4ToLYQuatT(const AZ::Matrix3x4& source) -{ - AZ::Matrix3x4 sourceNoScale(source); - sourceNoScale.ExtractScale(); - - return QuatT( - AZQuaternionToLYQuaternion(AZ::Quaternion::CreateFromMatrix3x4(sourceNoScale)), - AZVec3ToLYVec3(source.GetTranslation())); -} - -inline DualQuat AZMatrix3x4ToLYDualQuat(const AZ::Matrix3x4& matrix3x4) -{ - return DualQuat(AZMatrix3x4ToLYMatrix3x4(matrix3x4)); -} - -inline AABB AZAabbToLyAABB(const AZ::Aabb& source) -{ - return AABB(AZVec3ToLYVec3(source.GetMin()), AZVec3ToLYVec3(source.GetMax())); -} - -inline AZ::Aabb LyAABBToAZAabb(const AABB& source) -{ - return AZ::Aabb::CreateFromMinMax(LYVec3ToAZVec3(source.min), LYVec3ToAZVec3(source.max)); -} - -inline AZ::Obb LyOBBtoAZObb(const OBB& source) -{ - const AZ::Vector3 position = LYVec3ToAZVec3(source.c); - const AZ::Quaternion rotation = AZ::Quaternion::CreateFromMatrix3x3(LyMatrix3x3ToAzMatrix3x3(source.m33)); - const AZ::Vector3 halfLengths(source.h.x, source.h.y, source.h.z); - return AZ::Obb::CreateFromPositionRotationAndHalfLengths(position, rotation, halfLengths); -} - -inline OBB AZObbToLyOBB(const AZ::Obb& source) -{ - return OBB::CreateOBB( - Matrix33::CreateFromVectors( - AZVec3ToLYVec3(source.GetAxisX()), - AZVec3ToLYVec3(source.GetAxisY()), - AZVec3ToLYVec3(source.GetAxisZ())), - Vec3(source.GetHalfLengthX(), source.GetHalfLengthY(), source.GetHalfLengthZ()), - AZVec3ToLYVec3(source.GetPosition())); -} - -inline AZ::Plane LyPlaneToAZPlane(const ::Plane& source) -{ - return AZ::Plane::CreateFromNormalAndDistance(LYVec3ToAZVec3(source.n), source.d); -} - -inline ::Plane AZPlaneToLyPlane(const AZ::Plane& source) -{ - ::Plane resultPlane; - resultPlane.Set(AZVec3ToLYVec3(source.GetNormal()), source.GetDistance()); - - return resultPlane; -} diff --git a/Code/CryEngine/CryCommon/MemoryAccess.h b/Code/CryEngine/CryCommon/MemoryAccess.h deleted file mode 100644 index 085c45339c..0000000000 --- a/Code/CryEngine/CryCommon/MemoryAccess.h +++ /dev/null @@ -1,566 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Misc mathematical functions - -#pragma once - - -#include <platform.h> - -// Section dictionary -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define MEMORYACCESS_H_SECTION_TRAITS 1 -#define MEMORYACCESS_H_SECTION_CRYPREFETCH 2 -#endif - -// Traits -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MEMORYACCESS_H_SECTION_TRAITS - #include AZ_RESTRICTED_FILE(MemoryAccess_h) -#else -#define MEMORYACCESS_H_TRAIT_USE_LEGACY_PREFETCHLINE 1 -#endif - -#if MEMORYACCESS_H_TRAIT_USE_LEGACY_PREFETCHLINE -#define PrefetchLine(ptr, off) cryPrefetchT0SSE((void*)((UINT_PTR)ptr + off)) -#else -#define PrefetchLine(ptr, off) (void)(0) -#endif -#define ResetLine128(ptr, off) (void)(0) -#define FlushLine128(ptr, off) (void)(0) - - - -//======================================================================================== - -// cryMemcpy flags -#define MC_CPU_TO_GPU 0x10 -#define MC_GPU_TO_CPU 0x20 -#define MC_CPU_TO_CPU 0x40 - -extern int g_CpuFlags; - -// -#define CPUF_SSE 0x01 -#define CPUF_SSE2 0x02 -#define CPUF_3DNOW 0x04 -#define CPUF_MMX 0x08 -#define CPUF_SSE3 0x10 -#define CPUF_F16C 0x20 -#define CPUF_SSE41 0x40 - -#ifdef _CPU_SSE - -#ifdef _CPU_X86 -#include <xmmintrin.h> -#endif - -#define _MM_PREFETCH(MemPtr, Hint) _mm_prefetch((MemPtr), (Hint)); -#define _MM_PREFETCH_LOOP(nCount, MemPtr, Hint) { for (int p = 0; p < nCount; p += 64) { _mm_prefetch((const char*)(MemPtr) + p, Hint); } \ -} -#else //_CPU_SSE -#define _MM_PREFETCH(MemPtr, Hint) -#define _MM_PREFETCH_LOOP(nCount, MemPtr, Hint) -#endif //_CPU_SSE - -void cryMemcpy(void* Dst, const void* Src, int Count); -#if defined(LINUX) || defined(APPLE) -// Define this for Mac and Linux since it is used with the pthread sources - #define mymemcpy16 memcpy -#endif - - -//========================================================================================== -// 3DNow! optimizations - -#if defined _CPU_X86 && !defined(LINUX) && !defined(APPLE) -// *************************************************************************** -inline void cryPrecacheSSE(const void* src, int nbytes) -{ - _asm - { - mov esi, src - mov ecx, nbytes - // 64 bytes per pass - shr ecx, 6 - jz endLabel - -loopMemToL1: - prefetchnta 64[ESI] // Prefetch next loop, non-temporal - prefetchnta 96[ESI] - - movq mm1, 0[ESI]// Read in source data - movq mm2, 8[ESI] - movq mm3, 16[ESI] - movq mm4, 24[ESI] - movq mm5, 32[ESI] - movq mm6, 40[ESI] - movq mm7, 48[ESI] - movq mm0, 56[ESI] - - add esi, 64 - dec ecx - jnz loopMemToL1 - - emms - -endLabel: - } -} - - -#endif - - - -ILINE void cryPrefetchT0SSE(const void* src) -{ -#if defined(WIN32) && !defined(WIN64) - _asm - { - mov esi, src - prefetchT0 [ESI] // Prefetch - } -#else - _MM_PREFETCH((char*)src, _MM_HINT_T0); -#endif -} - -//================================================================================= - -// Very optimized memcpy() routine for AMD Athlon and Duron family. -// This code uses any of FOUR different basic copy methods, depending -// on the transfer size. -// NOTE: Since this code uses MOVNTQ (also known as "Non-Temporal MOV" or -// "Streaming Store"), and also uses the software prefetch instructions, -// be sure you're running on Athlon/Duron or other recent CPU before calling! - -#define TINY_BLOCK_COPY 64 // Upper limit for movsd type copy. -// The smallest copy uses the X86 "movsd" instruction, in an optimized -// form which is an "unrolled loop". - -#define IN_CACHE_COPY 64 * 1024 // Upper limit for movq/movq copy w/SW prefetch. -// Next is a copy that uses the MMX registers to copy 8 bytes at a time, -// also using the "unrolled loop" optimization. This code uses -// the software prefetch instruction to get the data into the cache. - -#define UNCACHED_COPY 197 * 1024 // Upper limit for movq/movntq w/SW prefetch. -// For larger blocks, which will spill beyond the cache, it's faster to -// use the Streaming Store instruction MOVNTQ. This write instruction -// bypasses the cache and writes straight to main memory. This code also -// uses the software prefetch instruction to pre-read the data. -// USE 64 * 1024 FOR THIS VALUE IF YOU'RE ALWAYS FILLING A "CLEAN CACHE". - -#define BLOCK_PREFETCH_COPY infinity // No limit for movq/movntq w/block prefetch. -#define CACHEBLOCK 80h // Number of 64-byte blocks (cache lines) for block prefetch. -// For the largest size blocks, a special technique called Block Prefetch -// can be used to accelerate the read operations. Block Prefetch reads -// one address per cache line, for a series of cache lines, in a short loop. -// This is faster than using software prefetch. The technique is great for -// getting maximum read bandwidth, especially in DDR memory systems. - - -#if defined _CPU_X86 && !defined(LINUX) && !defined(APPLE) -// Inline assembly syntax for use with Visual C++ -inline void cryMemcpy(void* Dst, const void* Src, int Count) -{ - if (g_CpuFlags & CPUF_SSE) - { - __asm - { - mov ecx, [Count]; - number of bytes to copy - mov edi, [Dst]; - destination - mov esi, [Src]; - source - mov ebx, ecx; - keep a copy of count - - cld - cmp ecx, TINY_BLOCK_COPY - jb $memcpy_ic_3; - tiny ? skip mmx copy - - cmp ecx, 32 * 1024; - dont align between 32k - 64k because - jbe $memcpy_do_align; - it appears to be slower - cmp ecx, 64*1024 - jbe $memcpy_align_done - $memcpy_do_align : - mov ecx, 8; - a trick thats faster than rep movsb ... - sub ecx, edi; - align destination to qword - and ecx, 111b; - get the low bits - sub ebx, ecx; - update copy count - neg ecx; - set up to jump into the array - add ecx, offset $memcpy_align_done - jmp ecx; - jump to array of movsbs - - align 4 - movsb - movsb - movsb - movsb - movsb - movsb - movsb - movsb - -$memcpy_align_done:; - destination is dword aligned - mov ecx, ebx; - number of bytes left to copy - shr ecx, 6; - get 64 - byte block count - jz $memcpy_ic_2; - finish the last few bytes - - cmp ecx, IN_CACHE_COPY / 64; - too big 4 cache ? use uncached copy - jae $memcpy_uc_test - - // This is small block copy that uses the MMX registers to copy 8 bytes - // at a time. It uses the "unrolled loop" optimization, and also uses - // the software prefetch instruction to get the data into the cache. - align 16 - $memcpy_ic_1 :; - 64 - byte block copies, in - cache copy - - prefetchnta [esi + (200 * 64 / 34 + 192)]; - start reading ahead - - movq mm0, [esi + 0]; - read 64 bits - movq mm1, [esi + 8] - movq [edi + 0], mm0; - write 64 bits - movq [edi + 8], mm1; -note: the normal movq writes the - movq mm2, [esi + 16]; - data to cache; - a cache line will be - movq mm3, [esi + 24]; - allocated as needed, to store the data - movq [edi + 16], mm2 - movq [edi + 24], mm3 - movq mm0, [esi + 32] - movq mm1, [esi + 40] - movq [edi + 32], mm0 - movq [edi + 40], mm1 - movq mm2, [esi + 48] - movq mm3, [esi + 56] - movq [edi + 48], mm2 - movq [edi + 56], mm3 - - add esi, 64; - update source pointer - add edi, 64; - update destination pointer - dec ecx; - count down - jnz $memcpy_ic_1; - last 64 - byte block ? - - $memcpy_ic_2 : - mov ecx, ebx; - has valid low 6 bits of the byte count -$memcpy_ic_3: - shr ecx, 2; - dword count - and ecx, 1111b; - only look at the "remainder" bits - neg ecx; - set up to jump into the array - add ecx, offset $memcpy_last_few - jmp ecx; - jump to array of movsds - -$memcpy_uc_test: - cmp ecx, UNCACHED_COPY / 64; - big enough ? use block prefetch copy - jae $memcpy_bp_1 - - $memcpy_64_test : - or ecx, ecx; - tail end of block prefetch will jump here - jz $memcpy_ic_2; - no more 64 - byte blocks left - - // For larger blocks, which will spill beyond the cache, it's faster to - // use the Streaming Store instruction MOVNTQ. This write instruction - // bypasses the cache and writes straight to main memory. This code also - // uses the software prefetch instruction to pre-read the data. - align 16 -$memcpy_uc_1:; - 64 - byte blocks, uncached copy - - prefetchnta [esi + (200 * 64 / 34 + 192)]; - start reading ahead - - movq mm0, [esi + 0]; - read 64 bits - add edi, 64; - update destination pointer - movq mm1, [esi + 8] - add esi, 64; - update source pointer - movq mm2, [esi - 48] - movntq [edi - 64], mm0; - write 64 bits, bypassing the cache - movq mm0, [esi - 40]; -note: movntq also prevents the CPU - movntq [edi - 56], mm1; - from READING the destination address - movq mm1, [esi - 32]; - into the cache, only to be over - written - movntq [edi - 48], mm2; - so that also helps performance - movq mm2, [esi - 24] - movntq [edi - 40], mm0 - movq mm0, [esi - 16] - movntq [edi - 32], mm1 - movq mm1, [esi - 8] - movntq [edi - 24], mm2 - movntq [edi - 16], mm0 - dec ecx - movntq [edi - 8], mm1 - jnz $memcpy_uc_1; - last 64 - byte block ? - - jmp $memcpy_ic_2; - almost done - - // For the largest size blocks, a special technique called Block Prefetch - // can be used to accelerate the read operations. Block Prefetch reads - // one address per cache line, for a series of cache lines, in a short loop. - // This is faster than using software prefetch. The technique is great for - // getting maximum read bandwidth, especially in DDR memory systems. - $memcpy_bp_1 :; - large blocks, block prefetch copy - - cmp ecx, CACHEBLOCK; - big enough to run another prefetch loop ? - jl $memcpy_64_test; - no, back to regular uncached copy - - mov eax, CACHEBLOCK / 2; - block prefetch loop, unrolled 2X - add esi, CACHEBLOCK* 64; - move to the top of the block - align 16 - $memcpy_bp_2 : - mov edx, [esi - 64]; - grab one address per cache line - mov edx, [esi - 128]; - grab one address per cache line - sub esi, 128; - go reverse order to suppress HW prefetcher - dec eax; - count down the cache lines - jnz $memcpy_bp_2; - keep grabbing more lines into cache - - mov eax, CACHEBLOCK; - now that its in cache, do - { - the copy - align 16 -$memcpy_bp_3: - movq mm0, [esi ]; - } read 64 bits - movq mm1, [esi + 8] - movq mm2, [esi + 16] - movq mm3, [esi + 24] - movq mm4, [esi + 32] - movq mm5, [esi + 40] - movq mm6, [esi + 48] - movq mm7, [esi + 56] - add esi, 64; - update source pointer - movntq [edi ], mm0; - write 64 bits, bypassing cache - movntq [edi + 8], mm1; -note: movntq also prevents the CPU - movntq [edi + 16], mm2; - from READING the destination address - movntq [edi + 24], mm3; - into the cache, only to be over - written, - movntq [edi + 32], mm4; - so that also helps performance - movntq [edi + 40], mm5 - movntq [edi + 48], mm6 - movntq [edi + 56], mm7 - add edi, 64; - update dest pointer - - dec eax; - count down - - jnz $memcpy_bp_3; - keep copying - sub ecx, CACHEBLOCK; - update the 64 - byte block count - jmp $memcpy_bp_1; - keep processing chunks - - // The smallest copy uses the X86 "movsd" instruction, in an optimized - // form which is an "unrolled loop". Then it handles the last few bytes. - align 4 - movsd - movsd; - perform last 1 - 15 dword copies - movsd - movsd - movsd - movsd - movsd - movsd - movsd - movsd; - perform last 1 - 7 dword copies - movsd - movsd - movsd - movsd - movsd - movsd - -$memcpy_last_few:; - dword aligned from before movsds - mov ecx, ebx; - has valid low 2 bits of the byte count - and ecx, 11b; - the last few cows must come home - jz $memcpy_final; - no more, lets leave - rep movsb; - the last 1, 2, or 3 bytes - -$memcpy_final: - emms; - clean up the MMX state - sfence; - flush the write buffer - // mov eax, [dest] ; ret value = destination pointer - } - } - else - { - memcpy(Dst, Src, Count); - } -} - -inline void cryPrefetch(const void* Src, int nCount) -{ - nCount >>= 6; - if (nCount > 0) - { - _asm - { - mov esi, Src; - mov ecx, nCount; -mPr0: - align 16 - dec ecx; - mov eax, [esi]; - mov eax, 0; - lea esi, [esi + 40h]; - jne mPr0; - } - } - else - { - _asm - { - mov esi, Src; - mov ecx, nCount; -mPr1: - align 16 - inc ecx; - mov eax, [esi]; - mov eax, 0; - lea esi, [esi - 40h]; - jne mPr1; - } - } -} - -inline void cryMemcpy (void* inDst, const void* inSrc, int nCount, int nFlags) -{ - cryMemcpy(inDst, inSrc, nCount); -} - -//========================================================================================== -// SSE optimizations - - -#else - -const int PREFNTA_BLOCK = 0x4000; - -ILINE void cryMemcpy(void* Dst, const void* Src, int n) -{ - char* dst = (char*)Dst; - char* src = (char*)Src; - while (n > PREFNTA_BLOCK) - { - _MM_PREFETCH_LOOP(PREFNTA_BLOCK, src, _MM_HINT_NTA); - - memcpy(dst, src, PREFNTA_BLOCK); - src += PREFNTA_BLOCK; - dst += PREFNTA_BLOCK; - n -= PREFNTA_BLOCK; - } - _MM_PREFETCH_LOOP(n, src, _MM_HINT_NTA); - memcpy(dst, src, n); -} - -ILINE void cryMemcpy(void* Dst, const void* Src, int n, [[maybe_unused]] int nFlags) -{ - char* dst = (char*)Dst; - char* src = (char*)Src; - while (n > PREFNTA_BLOCK) - { - _MM_PREFETCH_LOOP(PREFNTA_BLOCK, src, _MM_HINT_NTA); - memcpy(dst, src, PREFNTA_BLOCK); - src += PREFNTA_BLOCK; - dst += PREFNTA_BLOCK; - n -= PREFNTA_BLOCK; - } - _MM_PREFETCH_LOOP(n, src, _MM_HINT_NTA); - memcpy(dst, src, n); -} - - -#endif - - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MEMORYACCESS_H_SECTION_CRYPREFETCH - #include AZ_RESTRICTED_FILE(MemoryAccess_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -//implement something usual to bring one memory location into L1 data cache -ILINE void CryPrefetch(const void* const cpSrc) -{ - cryPrefetchT0SSE(cpSrc); -} -#endif - -#define CryPrefetchInl CryPrefetch diff --git a/Code/CryEngine/CryCommon/MetaUtils.h b/Code/CryEngine/CryCommon/MetaUtils.h deleted file mode 100644 index 7ed2925672..0000000000 --- a/Code/CryEngine/CryCommon/MetaUtils.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_METAUTILS_H -#define CRYINCLUDE_CRYCOMMON_METAUTILS_H -#pragma once - - - -namespace metautils -{ - // select - - template<bool Condition, typename Ty1, typename Ty2> - struct select; - - template<typename Ty1, typename Ty2> - struct select<true, Ty1, Ty2> - { - typedef Ty1 type; - }; - - template<typename Ty1, typename Ty2> - struct select<false, Ty1, Ty2> - { - typedef Ty2 type; - }; - - // is_same - // Identifies whether types Ty1 and Ty2 are the same including const & volatile. - - template<typename Ty1, typename Ty2> - struct is_same; - - template<typename Ty1> - struct is_same<Ty1, Ty1> - { - enum - { - value = true, - }; - }; - - template<typename Ty1, typename Ty2> - struct is_same - { - enum - { - value = false, - }; - }; - - // remove_const - // Removes top level const qualifier. - - template<class Ty> - struct remove_const - { - typedef Ty type; - }; - - template<class Ty> - struct remove_const<const Ty> - { - typedef Ty type; - }; - - template<class Ty> - struct remove_const<const Ty[]> - { - typedef Ty type[]; - }; - - template<class Ty, unsigned int N> - struct remove_const<const Ty[N]> - { - typedef Ty type[N]; - }; - - // is_const - // Determines whether type Ty is const qualified. - - template <typename Ty> - struct is_const - { - enum - { - value = false - }; - }; - - template <typename Ty> - struct is_const<const Ty> - { - enum - { - value = true - }; - }; - - template<class Ty, unsigned int N> - struct is_const<Ty[N]> - { - enum - { - value = false - }; - }; - - template<class Ty, unsigned int N> - struct is_const<const Ty[N]> - { - enum - { - value = true - }; - }; - - template<class Ty> - struct is_const<Ty&> - { - enum - { - value = false - }; - }; -}; - -#endif // CRYINCLUDE_CRYCOMMON_METAUTILS_H diff --git a/Code/CryEngine/CryCommon/MicrophoneBus.h b/Code/CryEngine/CryCommon/MicrophoneBus.h deleted file mode 100644 index 43ea57f839..0000000000 --- a/Code/CryEngine/CryCommon/MicrophoneBus.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include <AzCore/EBus/EBus.h> -#include <IAudioInterfacesCommonData.h> - -namespace Audio -{ - /** - * Interface for connecting with a hardware Microphone device. - * The pattern that should be used is as follows: - * - * InitializeDevice - * StartSession - * (Capturing Mic Data...) - * EndSession - * ... - * (optional: additional StartSession/EndSession pairs) - * ... - * ShutdownDevice - */ - class MicrophoneRequests - : public AZ::EBusTraits - { - public: - /** - * EBus Traits - */ - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - using MutexType = AZStd::recursive_mutex; - - /** - * Initialize a hardware Microphone input device with the OS. - * @return True if the Microphone was initialized without errors, false otherwise. - */ - virtual bool InitializeDevice() = 0; - - /** - * Shutdown the connection to the Microphone device. - */ - virtual void ShutdownDevice() = 0; - - /** - * Start capturing Microphone data. - * @return True if the Microphone capturing session was started without errors, false otherwise. - */ - virtual bool StartSession() = 0; - - /** - * Stop capturing Microphone data. - */ - virtual void EndSession() = 0; - - /** - * Check if the Microphone is actively capturing data. - * @return True if a capturing session has started and is running, false otherwise. - */ - virtual bool IsCapturing() = 0; - - /** - * Obtain the format set up for the mic capture session. - * @return Configuration of the Microphone. - */ - virtual SAudioInputConfig GetFormatConfig() const = 0; - - /** - * Consume a number of sample frames from the captured data. - * @param outputData Where the data will be copied to. - * @param numFrames The number of sample frames requested. - * @param targetConfig The configuration of the data sink (sample rate, channels, sample type, etc). - * @param shouldDeinterleave Ask for a deinterleaved copy when in stereo: [LRLRLRLR] --> [LLLL, RRRR] - * @return The number of sample frames obtained. - */ - virtual AZStd::size_t GetData(void** outputData, AZStd::size_t numFrames, const SAudioInputConfig& targetConfig, bool shouldDeinterleave) = 0; - }; - - using MicrophoneRequestBus = AZ::EBus<MicrophoneRequests>; - -} // namespace Audio diff --git a/Code/CryEngine/CryCommon/MiniQueue.h b/Code/CryEngine/CryCommon/MiniQueue.h deleted file mode 100644 index 986d5b2505..0000000000 --- a/Code/CryEngine/CryCommon/MiniQueue.h +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : a small memory overhead, fixed size, efficient, iterable -// queue class used for CContextView SObjectClone - - -#ifndef CRYINCLUDE_CRYCOMMON_MINIQUEUE_H -#define CRYINCLUDE_CRYCOMMON_MINIQUEUE_H -#pragma once - - -// this class implements a very small queue of plain-old-data -template <typename T, uint8 N> -struct MiniQueue -{ -public: - MiniQueue() - : m_nValues(0) - , m_nOffset(0) {} - - MiniQueue(const MiniQueue& mq) - { - m_nValues = mq.m_nValues; - m_nOffset = 0; - for (int i = 0; i < m_nValues; i++) - { - m_vValues[i] = mq[i]; - } - } - - bool Empty() const - { - return m_nValues == 0; - } - bool Full() const - { - return m_nValues == N; - } - uint8 Size() const - { - return m_nValues; - } - uint8 Capacity() const - { - return N; - } - ILINE void Push(T nValue) - { - assert(!Full()); - m_vValues[(m_nOffset + m_nValues) % N] = nValue; - m_nValues++; - } - // push, but if the queue is full, then pop first - void CyclePush(T nValue) - { - if (Full()) - { - Pop(); - } - Push(nValue); - } - void PushFront(T nValue) - { - assert(!Full()); - m_nOffset = (m_nOffset + (N - 1)) % N; - m_vValues[m_nOffset] = nValue; - m_nValues++; - } - T Front() const - { - assert(!Empty()); - return m_vValues[m_nOffset]; - } - T& Front() - { - assert(!Empty()); - return m_vValues[m_nOffset]; - } - T& operator[](int i) - { - return m_vValues[(m_nOffset + i) % N]; - } - T operator[](int i) const - { - return m_vValues[(m_nOffset + i) % N]; - } - T Back() const - { - assert(!Empty()); - return m_vValues[(m_nOffset + m_nValues - 1) % N]; - } - T& Back() - { - assert(!Empty()); - return m_vValues[(m_nOffset + m_nValues - 1) % N]; - } - void Pop() - { - assert(!Empty()); - m_nOffset = (m_nOffset + 1) % N; - m_nValues--; - } - void PopBack() - { - assert(!Empty()); - m_nValues--; - } - void Clear() - { - m_nOffset = m_nValues = 0; - } - - struct SIterator - { - public: - SIterator() {} - SIterator(T* pValues, uint8 nOffset) - : m_pValues(pValues) - , m_nOffset(nOffset) {} - T& operator*() - { - return m_pValues[m_nOffset % N]; - } - T* operator->() - { - return &m_pValues[m_nOffset % N]; - } - SIterator& operator++() - { - m_nOffset++; - return *this; - } - SIterator operator++(int) - { - SIterator itor = *this; - ++m_nOffset; - return itor; - } - SIterator& operator--() - { - m_nOffset--; - return *this; - } - SIterator& operator+=(uint8 delta) - { - m_nOffset += delta; - return *this; - } - SIterator& operator-=(uint8 delta) - { - m_nOffset -= delta; - return *this; - } - - friend bool operator!=(const SIterator& a, const SIterator& b) - { - assert(a.m_pValues == b.m_pValues); - return a.m_nOffset != b.m_nOffset; - } - friend bool operator==(const SIterator& a, const SIterator& b) - { - assert(a.m_pValues == b.m_pValues); - return a.m_nOffset == b.m_nOffset; - } - - friend int operator-(const SIterator& a, const SIterator& b) - { - assert(a.m_pValues == b.m_pValues); - int diff = int(a.m_nOffset) - int(b.m_nOffset); - return diff; - } - - uint8 Offset() { return m_nOffset; } - - private: - T* m_pValues; - uint8 m_nOffset; - }; - - SIterator Begin() { return SIterator(m_vValues, m_nOffset); } - SIterator End() { return SIterator(m_vValues, m_nOffset + m_nValues); } - - SIterator RBegin() { return SIterator(m_vValues, m_nOffset + m_nValues - 1); } - SIterator REnd() { return SIterator(m_vValues, m_nOffset - 1); } - - struct SConstIterator - { - public: - SConstIterator() {} - SConstIterator(const T* pValues, uint8 nOffset) - : m_pValues(pValues) - , m_nOffset(nOffset) {} - const T& operator*() - { - return m_pValues[m_nOffset % N]; - } - const T* operator->() - { - return &m_pValues[m_nOffset % N]; - } - SConstIterator& operator++() - { - m_nOffset++; - return *this; - } - SConstIterator& operator--() - { - m_nOffset--; - return *this; - } - SConstIterator& operator+=(uint8 delta) - { - m_nOffset += delta; - return *this; - } - SConstIterator& operator-=(uint8 delta) - { - m_nOffset -= delta; - return *this; - } - friend bool operator!=(const SConstIterator& a, const SConstIterator& b) - { - assert(a.m_pValues == b.m_pValues); - return a.m_nOffset != b.m_nOffset; - } - friend bool operator==(const SConstIterator& a, const SConstIterator& b) - { - assert(a.m_pValues == b.m_pValues); - return a.m_nOffset == b.m_nOffset; - } - - friend int operator-(const SConstIterator& a, const SConstIterator& b) - { - assert(a.m_pValues == b.m_pValues); - int diff = int(a.m_nOffset) - int(b.m_nOffset); - return diff; - } - - uint8 Offset() { return m_nOffset; } - - private: - const T* m_pValues; - uint8 m_nOffset; - }; - - SConstIterator Begin() const { return SConstIterator(m_vValues, m_nOffset); } - SConstIterator End() const { return SConstIterator(m_vValues, m_nOffset + m_nValues); } - - SConstIterator RBegin() const { return SConstIterator(m_vValues, m_nOffset + m_nValues - 1); } - SConstIterator REnd() const { return SConstIterator(m_vValues, m_nOffset - 1); } - - void Erase(SIterator where) - { - assert(where.Offset() >= m_nOffset); - assert(where.Offset() < m_nOffset + m_nValues); - for (size_t offset = where.Offset(); offset < (size_t)(m_nOffset + m_nValues - 1); offset++) - { - m_vValues[offset % N] = m_vValues[(offset + 1) % N]; - } - m_nValues--; - } - - void Erase(SIterator first, SIterator last) - { - int num = last - first; - if (num == 0) - { - return; - } - assert(num > 0); - assert(num <= Size()); - assert(first.Offset() >= m_nOffset); - assert(first.Offset() < m_nOffset + m_nValues); - assert(last.Offset() >= m_nOffset); - assert(last.Offset() <= m_nOffset + m_nValues); - for (int offset = (int)first.Offset(); offset < m_nOffset + m_nValues - 1; offset++) - { - m_vValues[offset % N] = m_vValues[(offset + num) % N]; - } - m_nValues -= num; - } - -private: - uint8 m_nValues; - uint8 m_nOffset; - T m_vValues[N]; -}; - -#endif // CRYINCLUDE_CRYCOMMON_MINIQUEUE_H diff --git a/Code/CryEngine/CryCommon/Mocks/IAudioSystemMock.h b/Code/CryEngine/CryCommon/Mocks/IAudioSystemMock.h deleted file mode 100644 index 75dc792d41..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/IAudioSystemMock.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include <IAudioSystem.h> - -namespace Audio -{ - struct AudioProxyMock - : public IAudioProxy - { - MOCK_METHOD2(Initialize, void(const char* const sObjectName, bool bInitAsync /* = true */)); - MOCK_METHOD0(Release, void()); - MOCK_METHOD0(Reset, void()); - MOCK_METHOD1(StopTrigger, void(TAudioControlID nTriggerID)); - MOCK_METHOD2(SetSwitchState, void(TAudioControlID nSwitchID, TAudioSwitchStateID nStateID)); - MOCK_METHOD2(SetRtpcValue, void(TAudioControlID nRtpcID, float fValue)); - MOCK_METHOD1(SetObstructionCalcType, void(EAudioObjectObstructionCalcType eObstructionType)); - MOCK_METHOD1(SetPosition, void(const SATLWorldPosition& rPosition)); - MOCK_METHOD1(SetPosition, void(const AZ::Vector3& rPosition)); - MOCK_METHOD2(SetEnvironmentAmount, void(TAudioEnvironmentID nEnvironmentID, float fAmount)); - MOCK_METHOD0(SetCurrentEnvironments, void()); - MOCK_CONST_METHOD0(GetAudioObjectID, TAudioObjectID()); - }; - - struct AudioSystemMock - : public IAudioSystem - { - MOCK_METHOD0(Initialize, bool()); - MOCK_METHOD0(Release, void()); - MOCK_METHOD1(PushRequest, void(const SAudioRequest& rAudioRequestData)); - MOCK_METHOD4(AddRequestListener, void(AudioRequestCallbackType func, void* pObjectToListenTo, EAudioRequestType requestType /* = eART_AUDIO_ALL_REQUESTS */, TATLEnumFlagsType specificRequestMask /* = ALL_AUDIO_REQUEST_SPECIFIC_TYPE_FLAGS */)); - MOCK_METHOD2(RemoveRequestListener, void(AudioRequestCallbackType func, void* pObjectToListenTo)); - MOCK_METHOD0(ExternalUpdate, void()); - MOCK_CONST_METHOD1(GetAudioTriggerID, TAudioControlID(const char* sAudioTriggerName)); - MOCK_CONST_METHOD1(GetAudioRtpcID, TAudioControlID(const char* sAudioRtpcName)); - MOCK_CONST_METHOD1(GetAudioSwitchID, TAudioControlID(const char* sAudioSwitchName)); - MOCK_CONST_METHOD2(GetAudioSwitchStateID, TAudioSwitchStateID(const TAudioControlID nSwitchID, const char* sAudioStateName)); - MOCK_CONST_METHOD1(GetAudioPreloadRequestID, TAudioPreloadRequestID(const char* sAudioPreloadRequestName)); - MOCK_CONST_METHOD1(GetAudioEnvironmentID, TAudioEnvironmentID(const char* sAudioEnvironmentName)); - MOCK_METHOD1(ReserveAudioListenerID, bool(TAudioObjectID& rAudioListenerID)); - MOCK_METHOD1(ReleaseAudioListenerID, bool(TAudioObjectID nAudioObjectID)); - MOCK_METHOD1(OnCVarChanged, void(ICVar* const pCVar)); - MOCK_METHOD1(GetInfo, void(SAudioSystemInfo& rAudioSystemInfo)); - MOCK_CONST_METHOD0(GetControlsPath, const char*()); - MOCK_METHOD0(UpdateControlsPath, void()); - MOCK_METHOD0(GetFreeAudioProxy, IAudioProxy*()); - MOCK_METHOD1(FreeAudioProxy, void(IAudioProxy* pIAudioProxy)); - MOCK_CONST_METHOD2(GetAudioControlName, const char*(EAudioControlType eAudioEntityType, TATLIDType nAudioEntityID)); - MOCK_CONST_METHOD2(GetAudioSwitchStateName, const char*(TAudioControlID switchID, TAudioSwitchStateID stateID)); - }; - -} // namespace Audio diff --git a/Code/CryEngine/CryCommon/Mocks/ICVarMock.h b/Code/CryEngine/CryCommon/Mocks/ICVarMock.h deleted file mode 100644 index 96301e7733..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/ICVarMock.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include <IConsole.h> -#include <AzTest/AzTest.h> - -#include <SFunctor.h> - -class CVarMock - : public ICVar -{ -public: - MOCK_METHOD0(Release, void()); - MOCK_CONST_METHOD0(GetIVal, int()); - MOCK_CONST_METHOD0(GetI64Val, int64()); - MOCK_CONST_METHOD0(GetFVal, float()); - MOCK_CONST_METHOD0(GetString, const char*()); - MOCK_CONST_METHOD0(GetDataProbeString, const char*()); - MOCK_METHOD1(Set, void(const char*)); - MOCK_METHOD1(ForceSet, void(const char*)); - MOCK_METHOD1(Set, void(float)); - MOCK_METHOD1(Set, void(int)); - MOCK_METHOD1(ClearFlags, void(const int)); - MOCK_CONST_METHOD0(GetFlags, int()); - MOCK_METHOD1(SetFlags, int(const int)); - MOCK_METHOD0(GetType, int()); - MOCK_CONST_METHOD0(GetName, const char*()); - MOCK_METHOD0(GetHelp, const char*()); - MOCK_CONST_METHOD0(IsConstCVar, bool()); - MOCK_METHOD1(SetOnChangeCallback, void(ConsoleVarFunc)); - MOCK_METHOD1(AddOnChangeFunctor, uint64(const SFunctor& pChangeFunctor)); - MOCK_CONST_METHOD0(GetNumberOfOnChangeFunctors, uint64()); - MOCK_CONST_METHOD1(GetOnChangeFunctor, const SFunctor&(uint64)); - MOCK_METHOD1(RemoveOnChangeFunctor, bool(uint64)); - MOCK_CONST_METHOD0(GetOnChangeCallback, ConsoleVarFunc()); - MOCK_CONST_METHOD1(GetMemoryUsage, void(class ICrySizer* pSizer)); - MOCK_CONST_METHOD0(GetRealIVal, int()); - MOCK_METHOD2(SetLimits, void(float, float)); - MOCK_METHOD2(GetLimits, void(float&, float&)); - MOCK_METHOD0(HasCustomLimits, bool()); - MOCK_METHOD1(SetDataProbeString, void(const char*)); -}; diff --git a/Code/CryEngine/CryCommon/Mocks/IConsoleMock.h b/Code/CryEngine/CryCommon/Mocks/IConsoleMock.h deleted file mode 100644 index abeec34a3e..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/IConsoleMock.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#ifndef CRYINCLUDE_CRYCOMMON_ICONSOLEMOCK_H -#define CRYINCLUDE_CRYCOMMON_ICONSOLEMOCK_H -#pragma once - -#include <IConsole.h> -#include <AzTest/AzTest.h> - -// Implements the Console interface -class ConsoleMock - : public ::IConsole -{ -public: - MOCK_METHOD0(Release, void()); - MOCK_METHOD1(Init, void(ISystem * pSystem)); - MOCK_METHOD5(RegisterString, ICVar * (const char* sName, const char* sValue, int nFlags, const char* help, ConsoleVarFunc pChangeFunc)); - MOCK_METHOD5(RegisterInt, ICVar * (const char* sName, int iValue, int nFlags, const char* help, ConsoleVarFunc pChangeFunc)); - MOCK_METHOD5(RegisterInt64, ICVar * (const char* sName, int64 iValue, int nFlags, const char* help, ConsoleVarFunc pChangeFunc)); - MOCK_METHOD5(RegisterFloat, ICVar * (const char* sName, float fValue, int nFlags, const char* help, ConsoleVarFunc pChangeFunc)); - MOCK_METHOD7(Register, ICVar * (const char* name, float* src, float defaultvalue, int nFlags, const char* help, ConsoleVarFunc pChangeFunc, bool allowModify)); - MOCK_METHOD7(Register, ICVar * (const char* name, int* src, int defaultvalue, int nFlags, const char* help, ConsoleVarFunc pChangeFunc, bool allowModify)); - MOCK_METHOD7(Register, ICVar * (const char* name, const char** src, const char* defaultvalue, int nFlags, const char* help, ConsoleVarFunc pChangeFunc, bool allowModify)); - MOCK_METHOD1(Register, ICVar * (ICVar * pVar)); - MOCK_METHOD2(UnregisterVariable, void(const char* sVarName, bool bDelete )); - MOCK_METHOD1(SetScrollMax, void(int value)); - MOCK_METHOD1(AddOutputPrintSink, void(IOutputPrintSink * inpSink)); - MOCK_METHOD1(RemoveOutputPrintSink, void(IOutputPrintSink * inpSink)); - MOCK_METHOD2(ShowConsole, void(bool show, int iRequestScrollMax)); - MOCK_METHOD2(DumpCVars, void(ICVarDumpSink * pCallback, unsigned int nFlagsFilter)); - MOCK_METHOD2(CreateKeyBind, void(const char* sCmd, const char* sRes)); - MOCK_METHOD2(SetImage, void (ITexture * pImage, bool bDeleteCurrent)); - MOCK_METHOD0(GetImage, ITexture * ()); - MOCK_METHOD1(StaticBackground, void (bool bStatic)); - MOCK_METHOD1(SetLoadingImage, void(const char* szFilename)); - MOCK_CONST_METHOD3(GetLineNo, bool(int indwLineNo, char* outszBuffer, int indwBufferSize)); - MOCK_CONST_METHOD0(GetLineCount, int ()); - MOCK_METHOD1(GetCVar, ICVar * (const char* name)); - MOCK_METHOD3(GetVariable, char*(const char* szVarName, const char* szFileName, const char* def_val)); - MOCK_METHOD3(GetVariable, float (const char* szVarName, const char* szFileName, float def_val)); - MOCK_METHOD1(PrintLine, void (const char* s)); - MOCK_METHOD1(PrintLinePlus, void (const char* s)); - MOCK_METHOD0(GetStatus, bool()); - MOCK_METHOD0(Clear, void()); - MOCK_METHOD0(Update, void()); - MOCK_METHOD0(Draw, void()); - MOCK_METHOD4(AddCommand, bool (const char* sCommand, ConsoleCommandFunc func, int nFlags, const char* sHelp)); - MOCK_METHOD4(AddCommand, bool (const char* sName, const char* sScriptFunc, int nFlags, const char* sHelp)); - MOCK_METHOD1(RemoveCommand, void (const char* sName)); - MOCK_METHOD3(ExecuteString, void (const char* command, bool bSilentMode, bool bDeferExecution )); - MOCK_METHOD0(IsOpened, bool ()); - MOCK_METHOD0(GetNumVars, int()); - MOCK_METHOD0(GetNumVisibleVars, int()); - MOCK_METHOD3(GetSortedVars, size_t (const char** pszArray, size_t numItems, const char* szPrefix)); - MOCK_METHOD1(AutoComplete, const char*(const char* substr)); - MOCK_METHOD1(AutoCompletePrev, const char*(const char* substr)); - MOCK_METHOD1(ProcessCompletion, const char*(const char* szInputBuffer)); - MOCK_METHOD2(RegisterAutoComplete, void (const char* sVarOrCommand, IConsoleArgumentAutoComplete * pArgAutoComplete)); - MOCK_METHOD1(UnRegisterAutoComplete, void (const char* sVarOrCommand)); - MOCK_METHOD0(ResetAutoCompletion, void ()); - MOCK_CONST_METHOD1(GetMemoryUsage, void (ICrySizer * pSizer)); - MOCK_METHOD1(ResetProgressBar, void (int nProgressRange)); - MOCK_METHOD0(TickProgressBar, void ()); - MOCK_METHOD1(SetInputLine, void (const char* szLine)); - MOCK_METHOD1(DumpKeyBinds, void (IKeyBindDumpSink * pCallback)); - MOCK_CONST_METHOD1(FindKeyBind, const char*(const char* sCmd)); - MOCK_METHOD0(GetNumCheatVars, int ()); - MOCK_METHOD2(SetCheatVarHashRange, void (size_t firstVar, size_t lastVar)); - MOCK_METHOD0(CalcCheatVarHash, void ()); - MOCK_METHOD0(IsHashCalculated, bool ()); - MOCK_METHOD0(GetCheatVarHash, uint64 ()); - MOCK_METHOD1(PrintCheatVars, void (bool bUseLastHashRange)); - MOCK_METHOD1(GetCheatVarAt, char* (uint32 nOffset)); - MOCK_METHOD1(AddConsoleVarSink, void (IConsoleVarSink * pSink)); - MOCK_METHOD1(RemoveConsoleVarSink, void (IConsoleVarSink * pSink)); - MOCK_METHOD1(GetHistoryElement, const char*(bool bUpOrDown)); - MOCK_METHOD1(AddCommandToHistory, void (const char* szCommand)); - MOCK_METHOD2(LoadConfigVar, void (const char* sVariable, const char* sValue)); - MOCK_METHOD1(EnableActivationKey, void (bool bEnable)); - MOCK_METHOD2(SetClientDataProbeString, void (const char* pName, const char* pValue)); - - // can't mock variadic methods, so just override here. - void Exit([[maybe_unused]] const char* command, ...) override {}; -}; - -#endif // CRYINCLUDE_CRYCOMMON_ICONSOLEMOCK_H diff --git a/Code/CryEngine/CryCommon/Mocks/ICryPakMock.h b/Code/CryEngine/CryCommon/Mocks/ICryPakMock.h deleted file mode 100644 index 7e2cf9e6c5..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/ICryPakMock.h +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include <AzTest/AzTest.h> -#include <AzCore/IO/FileIO.h> -#include <AzFramework/Archive/INestedArchive.h> -#include <AzFramework/Archive/IArchive.h> - - -struct CryPakMock - : AZ::IO::IArchive -{ - MOCK_METHOD5(AdjustFileName, const char*(AZStd::string_view src, char* dst, size_t dstSize, uint32_t nFlags, bool skipMods)); - MOCK_METHOD1(Init, bool(AZStd::string_view szBasePath)); - MOCK_METHOD0(Release, void()); - MOCK_CONST_METHOD1(IsInstalledToHDD, bool(AZStd::string_view acFilePath)); - - MOCK_METHOD5(OpenPack, bool(AZStd::string_view, uint32_t, AZStd::intrusive_ptr<AZ::IO::MemoryBlock>, AZStd::fixed_string<AZ::IO::IArchive::MaxPath>*, bool)); - MOCK_METHOD6(OpenPack, bool(AZStd::string_view, AZStd::string_view, uint32_t, AZStd::intrusive_ptr<AZ::IO::MemoryBlock>, AZStd::fixed_string<AZ::IO::IArchive::MaxPath>*, bool)); - MOCK_METHOD3(OpenPacks, bool(AZStd::string_view pWildcard, uint32_t nFlags, AZStd::vector<AZStd::fixed_string<AZ::IO::IArchive::MaxPath>>* pFullPaths)); - MOCK_METHOD4(OpenPacks, bool(AZStd::string_view pBindingRoot, AZStd::string_view pWildcard, uint32_t nFlags, AZStd::vector<AZStd::fixed_string<AZ::IO::IArchive::MaxPath>>* pFullPaths)); - MOCK_METHOD2(ClosePack, bool(AZStd::string_view pName, uint32_t nFlags)); - MOCK_METHOD2(ClosePacks, bool(AZStd::string_view pWildcard, uint32_t nFlags)); - MOCK_METHOD1(FindPacks, bool(AZStd::string_view pWildcardIn)); - MOCK_METHOD3(SetPacksAccessible, bool(bool bAccessible, AZStd::string_view pWildcard, uint32_t nFlags)); - MOCK_METHOD3(SetPackAccessible, bool(bool bAccessible, AZStd::string_view pName, uint32_t nFlags)); - MOCK_METHOD3(LoadPakToMemory, bool(AZStd::string_view pName, EInMemoryArchiveLocation eLoadToMemory, AZStd::intrusive_ptr<AZ::IO::MemoryBlock> pMemoryBlock)); - MOCK_METHOD2(LoadPaksToMemory, void(int nMaxPakSize, bool bLoadToMemory)); - MOCK_METHOD1(GetMod, const char*(int index)); - MOCK_METHOD1(ParseAliases, void(AZStd::string_view szCommandLine)); - MOCK_METHOD3(SetAlias, void(AZStd::string_view szName, AZStd::string_view szAlias, bool bAdd)); - MOCK_METHOD2(GetAlias, const char*(AZStd::string_view szName, bool bReturnSame)); - MOCK_METHOD0(Lock, void()); - MOCK_METHOD0(Unlock, void()); - MOCK_METHOD1(SetLocalizationFolder, void(AZStd::string_view sLocalizationFolder)); - MOCK_CONST_METHOD0(GetLocalizationFolder, const char*()); - MOCK_CONST_METHOD0(GetLocalizationRoot, const char*()); - MOCK_METHOD3(FOpen, AZ::IO::HandleType(AZStd::string_view pName, const char* mode, uint32_t nFlags)); - MOCK_METHOD4(FReadRaw, size_t(void* data, size_t length, size_t elems, AZ::IO::HandleType handle)); - MOCK_METHOD3(FReadRawAll, size_t(void* data, size_t nFileSize, AZ::IO::HandleType handle)); - MOCK_METHOD2(FGetCachedFileData, void*(AZ::IO::HandleType handle, size_t & nFileSize)); - MOCK_METHOD4(FWrite, size_t(const void* data, size_t length, size_t elems, AZ::IO::HandleType handle)); - MOCK_METHOD3(FGets, char*(char*, int, AZ::IO::HandleType)); - MOCK_METHOD1(Getc, int(AZ::IO::HandleType)); - MOCK_METHOD1(FGetSize, size_t(AZ::IO::HandleType f)); - MOCK_METHOD2(FGetSize, size_t(AZStd::string_view pName, bool bAllowUseFileSystem)); - MOCK_METHOD1(IsInPak, bool(AZ::IO::HandleType handle)); - MOCK_METHOD1(RemoveFile, bool(AZStd::string_view pName)); - MOCK_METHOD1(RemoveDir, bool(AZStd::string_view pName)); - MOCK_METHOD1(IsAbsPath, bool(AZStd::string_view pPath)); - MOCK_METHOD3(FSeek, size_t(AZ::IO::HandleType handle, uint64_t seek, int mode)); - MOCK_METHOD1(FTell, uint64_t(AZ::IO::HandleType handle)); - MOCK_METHOD1(FClose, int(AZ::IO::HandleType handle)); - MOCK_METHOD1(FEof, int(AZ::IO::HandleType handle)); - MOCK_METHOD1(FFlush, int(AZ::IO::HandleType handle)); - MOCK_METHOD1(PoolMalloc, void*(size_t size)); - MOCK_METHOD1(PoolFree, void(void* p)); - MOCK_METHOD3(PoolAllocMemoryBlock, AZStd::intrusive_ptr<AZ::IO::MemoryBlock> (size_t nSize, const char* sUsage, size_t nAlign)); - MOCK_METHOD2(FindFirst, AZ::IO::ArchiveFileIterator(AZStd::string_view pDir, AZ::IO::IArchive::EFileSearchType)); - MOCK_METHOD1(FindNext, AZ::IO::ArchiveFileIterator(AZ::IO::ArchiveFileIterator handle)); - MOCK_METHOD1(FindClose, bool(AZ::IO::ArchiveFileIterator)); - MOCK_METHOD1(GetModificationTime, AZ::IO::IArchive::FileTime(AZ::IO::HandleType f)); - MOCK_METHOD2(IsFileExist, bool(AZStd::string_view sFilename, EFileSearchLocation)); - MOCK_METHOD1(IsFolder, bool(AZStd::string_view sPath)); - MOCK_METHOD1(GetFileSizeOnDisk, AZ::IO::IArchive::SignedFileSize(AZStd::string_view filename)); - MOCK_METHOD2(MakeDir, bool(AZStd::string_view szPath, bool bGamePathMapping)); - MOCK_METHOD4(OpenArchive, AZStd::intrusive_ptr<AZ::IO::INestedArchive> (AZStd::string_view szPath, AZStd::string_view bindRoot, uint32_t nFlags, AZStd::intrusive_ptr<AZ::IO::MemoryBlock> pData)); - MOCK_METHOD1(GetFileArchivePath, const char* (AZ::IO::HandleType f)); - MOCK_METHOD5(RawCompress, int(const void* pUncompressed, size_t* pDestSize, void* pCompressed, size_t nSrcSize, int nLevel)); - MOCK_METHOD4(RawUncompress, int(void* pUncompressed, size_t* pDestSize, const void* pCompressed, size_t nSrcSize)); - MOCK_METHOD1(RecordFileOpen, void(ERecordFileOpenList eList)); - MOCK_METHOD2(RecordFile, void(AZ::IO::HandleType in, AZStd::string_view szFilename)); - MOCK_METHOD1(GetResourceList, AZ::IO::IResourceList * (ERecordFileOpenList eList)); - MOCK_METHOD2(SetResourceList, void(ERecordFileOpenList eList, AZ::IO::IResourceList * pResourceList)); - MOCK_METHOD0(GetRecordFileOpenList, AZ::IO::IArchive::ERecordFileOpenList()); - MOCK_METHOD2(ComputeCRC, uint32_t(AZStd::string_view szPath, uint32_t nFileOpenFlags)); - MOCK_METHOD4(ComputeMD5, bool(AZStd::string_view szPath, uint8_t* md5, uint32_t nFileOpenFlags, bool useDirectAccess)); - MOCK_METHOD1(RegisterFileAccessSink, void(AZ::IO::IArchiveFileAccessSink * pSink)); - MOCK_METHOD1(UnregisterFileAccessSink, void(AZ::IO::IArchiveFileAccessSink * pSink)); - MOCK_METHOD1(DisableRuntimeFileAccess, void(bool status)); - MOCK_METHOD2(DisableRuntimeFileAccess, bool(bool status, AZStd::thread_id threadId)); - MOCK_METHOD2(CheckFileAccessDisabled, bool(AZStd::string_view name, const char* mode)); - MOCK_METHOD1(SetRenderThreadId, void(AZStd::thread_id renderThreadId)); - MOCK_CONST_METHOD0(GetPakPriority, AZ::IO::ArchiveLocationPriority()); - MOCK_CONST_METHOD1(GetFileOffsetOnMedia, uint64_t(AZStd::string_view szName)); - MOCK_CONST_METHOD1(GetFileMediaType, EStreamSourceMediaType(AZStd::string_view szName)); - MOCK_METHOD0(GetLevelPackOpenEvent, auto()->LevelPackOpenEvent*); - MOCK_METHOD0(GetLevelPackCloseEvent, auto()->LevelPackCloseEvent*); - - // Implementations required for variadic functions - virtual int FPrintf([[maybe_unused]] AZ::IO::HandleType handle, [[maybe_unused]] const char* format, ...) PRINTF_PARAMS(3, 4) - { - return 0; - } -}; - diff --git a/Code/CryEngine/CryCommon/Mocks/ILogMock.h b/Code/CryEngine/CryCommon/Mocks/ILogMock.h deleted file mode 100644 index 8cb6dfe1b3..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/ILogMock.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once -#include <ILog.h> - -class LogMock - : public ILog -{ -public: - MOCK_METHOD3(LogV, - void(ELogType nType, const char* szFormat, va_list args)); - MOCK_METHOD4(LogV, - void(ELogType nType, int flags, const char* szFormat, va_list args)); - MOCK_METHOD0(Release, - void()); - MOCK_METHOD2(SetFileName, - bool(const char* fileNameOrFullPath, bool doBackups)); - MOCK_METHOD0(GetFileName, - const char*()); - MOCK_METHOD0(GetBackupFileName, - const char*()); - - virtual void Log([[maybe_unused]] const char* szCommand, ...) override {} - virtual void LogWarning([[maybe_unused]] const char* szCommand, ...) override {} - virtual void LogError([[maybe_unused]] const char* szCommand, ...) override {} - virtual void LogAlways([[maybe_unused]] const char* szCommand, ...) override {} - virtual void LogPlus([[maybe_unused]] const char* command, ...) override {} - virtual void LogToFile([[maybe_unused]] const char* command, ...) override {} - virtual void LogToFilePlus([[maybe_unused]] const char* command, ...) override {} - virtual void LogToConsole([[maybe_unused]] const char* command, ...) override {} - virtual void LogToConsolePlus([[maybe_unused]] const char* command, ...) override {} - virtual void UpdateLoadingScreen([[maybe_unused]] const char* command, ...) override {} - - MOCK_METHOD1(SetVerbosity, - void(int verbosity)); - MOCK_METHOD0(GetVerbosityLevel, - int()); - MOCK_METHOD1(AddCallback, - void(ILogCallback * pCallback)); - MOCK_METHOD1(RemoveCallback, - void(ILogCallback * pCallback)); - MOCK_METHOD0(Update, - void()); - MOCK_METHOD0(GetModuleFilter, - const char*()); - MOCK_CONST_METHOD1(GetMemoryUsage, - void(ICrySizer * pSizer)); - MOCK_METHOD1(Indent, - void(class CLogIndenter * indenter)); - MOCK_METHOD1(Unindent, - void(class CLogIndenter * indenter)); - MOCK_METHOD0(FlushAndClose, - void()); -}; diff --git a/Code/CryEngine/CryCommon/Mocks/IRemoteConsoleMock.h b/Code/CryEngine/CryCommon/Mocks/IRemoteConsoleMock.h deleted file mode 100644 index 4c1d1f460b..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/IRemoteConsoleMock.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include "IConsole.h" - -// Auto-generated by gmock_gen.py - -class IRemoteConsoleMock - : public IRemoteConsole -{ -public: - MOCK_METHOD0(RegisterConsoleVariables, void()); - MOCK_METHOD0(UnregisterConsoleVariables, void()); - MOCK_METHOD0(Start, void()); - MOCK_METHOD0(Stop, void()); - MOCK_CONST_METHOD0(IsStarted, bool()); - MOCK_METHOD1(AddLogMessage, void(const char* log)); - MOCK_METHOD1(AddLogWarning, void(const char* log)); - MOCK_METHOD1(AddLogError, void(const char* log)); - MOCK_METHOD0(Update, void()); - MOCK_METHOD2(RegisterListener, void(IRemoteConsoleListener* pListener, const char* name)); - MOCK_METHOD1(UnregisterListener, void(IRemoteConsoleListener* pListener)); -}; diff --git a/Code/CryEngine/CryCommon/Mocks/IRendererMock.h b/Code/CryEngine/CryCommon/Mocks/IRendererMock.h deleted file mode 100644 index 9acd628056..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/IRendererMock.h +++ /dev/null @@ -1,853 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <IRenderer.h> -#include <gmock/gmock.h> - -struct SRendItemSorter {}; -struct SRenderingPassInfo {}; -struct SClipVolumeBlendInfo {}; -struct SFogVolumeData {}; - -// the following was generated using google's python script to autogenerate mocks. -// however, it needed some hand-editing to make it work, so if you add functions to IRenderer, -// it will probably be better to just manually add them here than try to run the script again -// hand-edits are marked with 'hand-edit'. Everything else was autogenerated. - -class IRendererMock - : public IRenderer -{ -public: - MOCK_METHOD1(AddRenderDebugListener, - void(IRenderDebugListener * pRenderDebugListener)); - MOCK_METHOD1(RemoveRenderDebugListener, - void(IRenderDebugListener * pRenderDebugListener)); - MOCK_CONST_METHOD0(GetRenderType, - ERenderType()); - - // Hand-edit: Googlemock cannot handle 14 param functions. - WIN_HWND Init(int, int, int, int, unsigned int, int, int, bool, bool, WIN_HINSTANCE, WIN_HWND = 0, - bool = false, const SCustomRenderInitArgs* = 0, bool = false) override { return nullptr; } - - MOCK_METHOD0(PostInit, - void()); - MOCK_CONST_METHOD0(IsPost3DRendererEnabled, - bool()); - MOCK_METHOD0(GetFeatures, - int()); - - // Hand-edit: Googlemock doesn't like 'const void' as a return type: - const void SetApiVersion(const AZStd::string&) override {} - const void SetAdapterDescription(const AZStd::string&) override {} - - MOCK_CONST_METHOD0(GetApiVersion, - const AZStd::string& ()); - MOCK_CONST_METHOD0(GetAdapterDescription, - const AZStd::string& ()); - MOCK_METHOD3(GetVideoMemoryUsageStats, - void(size_t&, size_t&, bool)); - MOCK_CONST_METHOD0(GetNumGeomInstances, - int()); - MOCK_CONST_METHOD0(GetNumGeomInstanceDrawCalls, - int()); - MOCK_CONST_METHOD0(GetCurrentNumberOfDrawCalls, - int()); - MOCK_CONST_METHOD2(GetCurrentNumberOfDrawCalls, - void(int& nGeneral, int& nShadowGen)); - MOCK_CONST_METHOD1(GetCurrentNumberOfDrawCalls, - int(uint32 EFSListMask)); - MOCK_CONST_METHOD1(GetCurrentDrawCallRTTimes, - float(uint32 EFSListMask)); - MOCK_METHOD1(SetDebugRenderNode, - void(IRenderNode * pRenderNode)); - MOCK_CONST_METHOD1(IsDebugRenderNode, - bool(IRenderNode * pRenderNode)); - MOCK_METHOD1(DeleteContext, - bool(WIN_HWND hWnd)); - MOCK_METHOD4(CreateContext, - bool(WIN_HWND, bool, int, int)); - MOCK_METHOD1(SetCurrentContext, - bool(WIN_HWND hWnd)); - MOCK_METHOD0(MakeMainContextActive, - void()); - MOCK_METHOD0(GetCurrentContextHWND, - WIN_HWND()); - MOCK_METHOD0(IsCurrentContextMainVP, - bool()); - MOCK_CONST_METHOD0(GetCurrentContextViewportHeight, - int()); - MOCK_CONST_METHOD0(GetCurrentContextViewportWidth, - int()); - MOCK_METHOD1(ShutDown, - void(bool)); - MOCK_METHOD0(ShutDownFast, - void()); - MOCK_METHOD1(EnumDisplayFormats, - int(SDispFormat * Formats)); - MOCK_METHOD1(EnumAAFormats, - int(SAAFormat * Formats)); - MOCK_METHOD6(ChangeResolution, - bool(int nNewWidth, int nNewHeight, int nNewColDepth, int nNewRefreshHZ, bool bFullScreen, bool bForceReset)); - MOCK_METHOD0(BeginFrame, - void()); - MOCK_METHOD1(InitSystemResources, - void(int nFlags)); - MOCK_METHOD0(InitTexturesSemantics, - void()); - MOCK_METHOD1(FreeResources, - void(int nFlags)); - MOCK_METHOD0(Release, - void()); - MOCK_METHOD1(RenderDebug, - void(bool)); - MOCK_METHOD0(EndFrame, - void()); - MOCK_METHOD0(ForceSwapBuffers, - void()); - MOCK_METHOD0(TryFlush, - void()); - MOCK_CONST_METHOD4(GetViewport, - void(int* x, int* y, int* width, int* height)); - MOCK_METHOD5(SetViewport, - void(int, int, int, int, int)); - MOCK_METHOD4(SetRenderTile, - void(f32, f32, f32, f32)); - MOCK_METHOD4(SetScissor, - void(int, int, int, int)); - MOCK_METHOD0(GetViewProjectionMatrix, - Matrix44A & ()); - MOCK_METHOD1(SetTranspOrigCameraProjMatrix, - void(Matrix44A & matrix)); - MOCK_METHOD2(GetScreenAspect, - EScreenAspectRatio(int nWidth, int nHeight)); - MOCK_METHOD2(SetViewportDownscale, - Vec2(float xscale, float yscale)); - MOCK_METHOD1(SetViewParameters, - void(const CameraViewParameters& viewParameters)); - MOCK_METHOD1(ApplyViewParameters, - void(const CameraViewParameters& viewParameters)); - MOCK_METHOD5(DrawDynVB, - void(SVF_P3F_C4B_T2F * pBuf, uint16 * pInds, int nVerts, int nInds, PublicRenderPrimitiveType nPrimType)); - - // Hand-edit: google mock has issues with DynUiPrimitiveList - void DrawDynUiPrimitiveList([[maybe_unused]] DynUiPrimitiveList& primitives, [[maybe_unused]] int totalNumVertices, [[maybe_unused]] int totalNumIndices) override { return; } - - MOCK_METHOD1(SetCamera, - void(const CCamera& cam)); - MOCK_METHOD0(GetCamera, - const CCamera& ()); - MOCK_METHOD1(GetRenderViewForThread, - CRenderView * (int nThreadID)); - MOCK_METHOD1(SetGammaDelta, - bool(float fGamma)); - MOCK_METHOD0(RestoreGamma, - void(void)); - MOCK_METHOD3(ChangeDisplay, - bool(unsigned int width, unsigned int height, unsigned int cbpp)); - MOCK_METHOD7(ChangeViewport, - void(unsigned int, unsigned int, unsigned int, unsigned int, bool, float, float)); - MOCK_CONST_METHOD6(SaveTga, - bool(unsigned char* sourcedata, int sourceformat, int w, int h, const char* filename, bool flip)); - MOCK_METHOD1(SetTexture, - void(int tnum)); - MOCK_METHOD2(SetTexture, - void(int tnum, int nUnit)); - MOCK_METHOD0(SetWhiteTexture, - void()); - MOCK_CONST_METHOD0(GetWhiteTextureId, - int()); - MOCK_CONST_METHOD0(GetBlackTextureId, - int()); - - // Hand-edit: google mock can only do up to 10 parameters - void Draw2dImage(float, float, float, float, int, float, float, float, float, float, float, float, float, float, float) override {}; - MOCK_METHOD1(Draw2dImageStretchMode, - void(bool stretch)); - - // Hand-edit: google mock can only do up to 10 parameters - void Push2dImage(float, float, float, float, int, float, float, float, float, float, float, float, float, float, float, float) override {}; - - MOCK_METHOD0(Draw2dImageList, - void()); - - // Hand-edit: Hand-edit: google mock can only do up to 10 parameters - void DrawImage(float, float, float, float, int, float, float, float, float, float, float, float, float, bool) override {} - - // Hand-edit: google mock can only do up to 10 parameters - void DrawImageWithUV(float, float, float, float, float, int, float*, float*, float, float, float, float, bool) override {} - - MOCK_METHOD1(PushWireframeMode, - void(int mode)); - MOCK_METHOD0(PopWireframeMode, - void()); - MOCK_CONST_METHOD0(GetHeight, - int()); - MOCK_CONST_METHOD0(GetWidth, - int()); - MOCK_CONST_METHOD0(GetPixelAspectRatio, - float()); - MOCK_CONST_METHOD0(GetOverlayHeight, - int()); - MOCK_CONST_METHOD0(GetOverlayWidth, - int()); - MOCK_CONST_METHOD0(GetMaxSquareRasterDimension, - int()); - MOCK_METHOD0(SwitchToNativeResolutionBackbuffer, - void()); - MOCK_METHOD1(GetMemoryUsage, - void(ICrySizer * Sizer)); - MOCK_METHOD1(GetBandwidthStats, - void(float* fBandwidthRequested)); - MOCK_METHOD1(SetTextureStreamListener, - void(ITextureStreamListener * pListener)); - MOCK_METHOD2(GetOcclusionBuffer, - int(uint16 * pOutOcclBuffer, Matrix44 * pmCamBuffer)); - MOCK_METHOD2(ScreenShot, - bool(const char*, int)); - MOCK_METHOD0(GetColorBpp, - int()); - MOCK_METHOD0(GetDepthBpp, - int()); - MOCK_METHOD0(GetStencilBpp, - int()); - MOCK_CONST_METHOD0(IsStereoEnabled, - bool()); - MOCK_CONST_METHOD0(GetNearestRangeMax, - float()); - MOCK_METHOD0(GetPerInstanceConstantBufferPoolPointer, - PerInstanceConstantBufferPool * ()); - MOCK_METHOD6(ProjectToScreen, - bool(float ptx, float pty, float ptz, float* sx, float* sy, float* sz)); - MOCK_METHOD9(UnProject, - int(float sx, float sy, float sz, float* px, float* py, float* pz, const float modelMatrix[16], const float projMatrix[16], const int viewport[4])); - MOCK_METHOD6(UnProjectFromScreen, - int(float sx, float sy, float sz, float* px, float* py, float* pz)); - MOCK_METHOD1(GetModelViewMatrix, - void(float* mat)); - MOCK_METHOD1(GetProjectionMatrix, - void(float* mat)); - MOCK_METHOD7(WriteDDS, - bool(const byte * dat, int wdt, int hgt, int Size, const char* name, ETEX_Format eF, int NumMips)); - MOCK_METHOD6(WriteTGA, - bool(const byte * dat, int wdt, int hgt, const char* name, int src_bits_per_pixel, int dest_bits_per_pixel)); - MOCK_METHOD6(WriteJPG, - bool(const byte*, int, int, char*, int, int)); - MOCK_METHOD6(FontCreateTexture, - int(int, int, byte*, ETEX_Format, bool, const char*)); - MOCK_METHOD6(FontUpdateTexture, - bool(int nTexId, int X, int Y, int USize, int VSize, byte * pData)); - MOCK_METHOD2(FontSetTexture, - void(int nTexId, int nFilterMode)); - MOCK_METHOD2(FontSetRenderingState, - void(bool overrideViewProjMatrices, TransformationMatrices & backupMatrices)); - MOCK_METHOD3(FontSetBlending, - void(int src, int dst, int baseState)); - MOCK_METHOD2(FontRestoreRenderingState, - void(bool overrideViewProjMatrices, const TransformationMatrices& restoringMatrices)); - MOCK_METHOD3(FlushRTCommands, - bool(bool bWait, bool bImmediatelly, bool bForce)); - MOCK_CONST_METHOD7(DrawStringU, - void(IFFont_RenderProxy * pFont, float x, float y, float z, const char* pStr, bool asciiMultiLine, const STextDrawContext& ctx)); - MOCK_METHOD0(RT_CurThreadList, - int()); - MOCK_METHOD6(EF_PrecacheResource, - bool(SShaderItem*, float, float, int, int, int)); - MOCK_METHOD4(EF_PrecacheResource, - bool(IShader * pSH, float fMipFactor, float fTimeToReady, int Flags)); - MOCK_METHOD6(EF_PrecacheResource, - bool(ITexture*, float, float, int, int, int)); - MOCK_METHOD6(EF_PrecacheResource, - bool(IRenderMesh * pPB, _smart_ptr<IMaterial> pMaterial, float fMipFactor, float fTimeToReady, int Flags, int nUpdateId)); - MOCK_METHOD5(EF_PrecacheResource, - bool(CDLight * pLS, float fMipFactor, float fTimeToReady, int Flags, int nUpdateId)); - - // Hand-edit: google mock can only do up to 10 parameters - ITexture* EF_CreateCompositeTexture([[maybe_unused]] int type, [[maybe_unused]] const char* szName, [[maybe_unused]] int nWidth, [[maybe_unused]] int nHeight, [[maybe_unused]] int nDepth, [[maybe_unused]] int nMips, [[maybe_unused]] int nFlags, [[maybe_unused]] ETEX_Format eTF, [[maybe_unused]] const STexComposition* pCompositions, [[maybe_unused]] size_t nCompositions, [[maybe_unused]] int8 nPriority = -1) override { return nullptr; } - - MOCK_METHOD0(PostLevelLoading, - void()); - MOCK_METHOD0(PostLevelUnload, - void()); - MOCK_METHOD10(EF_AddPolygonToScene, - CRenderObject * (SShaderItem & si, int numPts, const SVF_P3F_C4B_T2F * verts, const SPipTangents * tangs, CRenderObject * obj, const SRenderingPassInfo& passInfo, uint16 * inds, int ninds, int nAW, const SRendItemSorter& rendItemSorter)); - MOCK_METHOD10(EF_AddPolygonToScene, - CRenderObject * (SShaderItem & si, CRenderObject * obj, const SRenderingPassInfo& passInfo, int numPts, int ninds, SVF_P3F_C4B_T2F * &verts, SPipTangents * &tangs, uint16 * &inds, int nAW, const SRendItemSorter& rendItemSorter)); - MOCK_METHOD0(ForceUpdateGlobalShaderParameters, - void()); - MOCK_METHOD0(EF_GetShaderMissLogPath, - const char*()); - MOCK_METHOD1(EF_GetShaderNames, - string * (int& nNumShaders)); - MOCK_METHOD1(EF_ReloadFile, - bool(const char* szFileName)); - MOCK_METHOD1(EF_ReloadFile_Request, - bool(const char* szFileName)); - MOCK_METHOD3(EF_GetRemapedShaderMaskGen, - uint64(const char*, uint64, bool)); - MOCK_METHOD3(EF_GetShaderGlobalMaskGenFromString, - uint64(const char*, const char*, uint64)); - MOCK_METHOD2(EF_GetStringFromShaderGlobalMaskGen, - AZStd::string(const char*, uint64)); - MOCK_CONST_METHOD1(GetShaderProfile, - const SShaderProfile& (EShaderType eST)); - MOCK_METHOD2(EF_SetShaderQuality, - void(EShaderType eST, EShaderQuality eSQ)); - MOCK_CONST_METHOD0(EF_GetRenderQuality, - ERenderQuality()); - MOCK_METHOD1(EF_GetShaderQuality, - EShaderQuality(EShaderType eST)); - MOCK_METHOD5(EF_LoadShaderItem, - SShaderItem(const char*, bool, int, SInputShaderResources*, uint64)); - MOCK_METHOD3(EF_LoadShader, - IShader * (const char*, int, uint64)); - MOCK_METHOD1(EF_ReloadShaderFiles, - void(int nCategory)); - MOCK_METHOD0(EF_ReloadTextures, - void()); - MOCK_METHOD1(EF_GetTextureByID, - ITexture * (int Id)); - MOCK_METHOD2(EF_GetTextureByName, - ITexture * (const char*, uint32)); - MOCK_METHOD2(EF_LoadTexture, - ITexture * (const char*, uint32)); - MOCK_METHOD2(EF_LoadCubemapTexture, - ITexture * (const char*, uint32)); - MOCK_METHOD1(EF_LoadDefaultTexture, - ITexture * (const char* nameTex)); - MOCK_METHOD1(EF_LoadLightmap, - int(const char* name)); - MOCK_METHOD1(EF_StartEf, - void(const SRenderingPassInfo& passInfo)); - MOCK_METHOD3(EF_GetObjData, - SRenderObjData * (CRenderObject * pObj, bool bCreate, int nThreadID)); - MOCK_METHOD1(EF_GetObject_Temp, - CRenderObject * (int nThreadID)); - MOCK_METHOD2(EF_DuplicateRO, - CRenderObject * (CRenderObject * pObj, const SRenderingPassInfo& passInfo)); - MOCK_METHOD7(EF_AddEf, - void(IRenderElement * pRE, SShaderItem & pSH, CRenderObject * pObj, const SRenderingPassInfo& passInfo, int nList, int nAW, const SRendItemSorter& rendItemSorter)); - MOCK_METHOD4(EF_EndEf3D, - void(int nFlags, int nPrecacheUpdateId, int nNearPrecacheUpdateId, const SRenderingPassInfo& passInfo)); - MOCK_METHOD1(EF_InvokeShadowMapRenderJobs, - void(int nFlags)); - MOCK_METHOD1(EF_IsFakeDLight, - bool(const CDLight * Source)); - MOCK_METHOD2(EF_ADDDlight, - void(CDLight * Source, const SRenderingPassInfo& passInfo)); - MOCK_METHOD1(EF_UpdateDLight, - bool(SRenderLight * pDL)); - MOCK_METHOD1(EF_AddDeferredDecal, - bool(const SDeferredDecal& rDecal)); - MOCK_METHOD4(EF_AddDeferredLight, - int(const CDLight& pLight, float fMult, const SRenderingPassInfo& passInfo, const SRendItemSorter& rendItemSorter)); - MOCK_METHOD1(EF_GetDeferredLightsNum, - uint32(eDeferredLightType)); - MOCK_METHOD0(EF_ClearDeferredLightsList, - void()); - MOCK_METHOD1(EF_AddDeferredClipVolume, - uint8(const IClipVolume * pClipVolume)); - MOCK_METHOD2(EF_SetDeferredClipVolumeBlendData, - bool(const IClipVolume * pClipVolume, const SClipVolumeBlendInfo& blendInfo)); - MOCK_METHOD0(EF_ClearDeferredClipVolumesList, - void()); - MOCK_METHOD0(EF_ReleaseDeferredData, - void()); - MOCK_METHOD1(EF_ReleaseInputShaderResource, - void(SInputShaderResources * pRes)); - MOCK_METHOD3(EF_SetPostEffectParam, - void(const char*, float, bool)); - MOCK_METHOD3(EF_SetPostEffectParamVec4, - void(const char*, const Vec4&, bool)); - MOCK_METHOD2(EF_SetPostEffectParamString, - void(const char* pParam, const char* pszArg)); - MOCK_METHOD2(EF_GetPostEffectParam, - void(const char* pParam, float& fValue)); - MOCK_METHOD2(EF_GetPostEffectParamVec4, - void(const char* pParam, Vec4 & pValue)); - MOCK_METHOD2(EF_GetPostEffectParamString, - void(const char* pParam, const char* & pszArg)); - MOCK_METHOD1(EF_GetPostEffectID, - int32(const char* pPostEffectName)); - MOCK_METHOD1(EF_ResetPostEffects, - void(bool)); - MOCK_METHOD0(SyncPostEffects, - void()); - MOCK_METHOD0(EF_DisableTemporalEffects, - void()); - MOCK_METHOD3(EF_AddWaterSimHit, - void(const Vec3& vPos, float scale, float strength)); - MOCK_METHOD0(EF_DrawWaterSimHits, - void()); - MOCK_METHOD1(EF_EndEf2D, - void(bool bSort)); - MOCK_METHOD0(ForceGC, - void()); - MOCK_CONST_METHOD0(GetPolyCount, - int()); - MOCK_CONST_METHOD2(GetPolyCount, - void(int& nPolygons, int& nShadowVolPolys)); - MOCK_METHOD1(SetClearColor, - void(const Vec3& vColor)); - MOCK_METHOD1(SetClearBackground, - void(bool bClearBackground)); - MOCK_METHOD4(CreateRenderMesh, - _smart_ptr<IRenderMesh>(const char*, const char*, IRenderMesh::SInitParamerers*, ERenderMeshType)); - - // Hand-edit: google mock can only do up to 10 parameters - virtual _smart_ptr<IRenderMesh> CreateRenderMeshInitialized( - const void*, int, const AZ::Vertex::Format&, const vtx_idx*, int, const PublicRenderPrimitiveType, - const char*, const char*, ERenderMeshType = eRMT_Static, int = 1, int = 0, - [[maybe_unused]] bool (*PrepareBufferCallback)(IRenderMesh*, bool) = nullptr, void* = nullptr, bool = false, bool = true, - const SPipTangents* = nullptr, bool = false, Vec3* = nullptr) - { - return _smart_ptr<IRenderMesh>(); - } - - MOCK_METHOD1(GetFrameID, - int(bool)); - MOCK_CONST_METHOD0(GetCameraFrameID, - int()); - MOCK_CONST_METHOD0(IsRenderToTextureActive, - bool()); - MOCK_METHOD4(MakeMatrix, - void(const Vec3& pos, const Vec3& angles, const Vec3& scale, Matrix34 * mat)); - MOCK_METHOD4(DrawTextQueued, - void(Vec3 pos, SDrawTextInfo & ti, const char* format, va_list args)); - MOCK_METHOD3(DrawTextQueued, - void(Vec3 pos, SDrawTextInfo & ti, const char* text)); - MOCK_CONST_METHOD1(ScaleCoordX, - float(float value)); - MOCK_CONST_METHOD1(ScaleCoordY, - float(float value)); - MOCK_CONST_METHOD2(ScaleCoord, - void(float& x, float& y)); - MOCK_METHOD2(SetState, - void(int, int)); - MOCK_METHOD1(SetCullMode, - void(int)); - MOCK_METHOD5(SetStencilState, - void(int, uint32, uint32, uint32, bool)); - MOCK_METHOD1(PushProfileMarker, - void(const char* label)); - MOCK_METHOD1(PopProfileMarker, - void(const char* label)); - MOCK_METHOD1(EnableFog, - bool(bool enable)); - MOCK_METHOD1(SetFogColor, - void(const ColorF& color)); - MOCK_METHOD4(SetColorOp, - void(byte eCo, byte eAo, byte eCa, byte eAa)); - MOCK_METHOD1(SetSrgbWrite, - void(bool srgbWrite)); - MOCK_METHOD1(RequestFlushAllPendingTextureStreamingJobs, - void(int nFrames)); - MOCK_METHOD1(SetTexturesStreamingGlobalMipFactor, - void(float fFactor)); - MOCK_METHOD1(GetIRenderAuxGeom, - IRenderAuxGeom * (void*)); - MOCK_METHOD0(GetISvoRenderer, - ISvoRenderer * ()); - MOCK_METHOD0(GetIColorGradingController, - IColorGradingController * ()); - MOCK_METHOD0(GetIStereoRenderer, - IStereoRenderer * ()); - MOCK_METHOD7(Create2DTexture, - ITexture * (const char* name, int width, int height, int numMips, int flags, unsigned char* data, ETEX_Format format)); - - void TextToScreen([[maybe_unused]] float x, [[maybe_unused]] float y, [[maybe_unused]] const char* format, ...) override {} - void TextToScreenColor([[maybe_unused]] int x, [[maybe_unused]] int y, [[maybe_unused]] float r, [[maybe_unused]] float g, [[maybe_unused]] float b, [[maybe_unused]] float a, [[maybe_unused]] const char* format, ...) override {} - - MOCK_METHOD0(ResetToDefault, - void()); - MOCK_METHOD4(SetMaterialColor, - void(float r, float g, float b, float a)); - MOCK_METHOD0(SetDefaultRenderStates, - void()); - MOCK_METHOD10(Graph, - void(byte * g, int x, int y, int wdt, int hgt, int nC, int type, const char* text, ColorF & color, float fScale)); - MOCK_METHOD0(EF_RenderTextMessages, - void()); - MOCK_METHOD1(ClearTargetsImmediately, - void(uint32 nFlags)); - MOCK_METHOD3(ClearTargetsImmediately, - void(uint32 nFlags, const ColorF& Colors, float fDepth)); - MOCK_METHOD2(ClearTargetsImmediately, - void(uint32 nFlags, const ColorF& Colors)); - MOCK_METHOD2(ClearTargetsImmediately, - void(uint32 nFlags, float fDepth)); - MOCK_METHOD1(ClearTargetsLater, - void(uint32 nFlags)); - MOCK_METHOD3(ClearTargetsLater, - void(uint32 nFlags, const ColorF& Colors, float fDepth)); - MOCK_METHOD2(ClearTargetsLater, - void(uint32 nFlags, const ColorF& Colors)); - MOCK_METHOD2(ClearTargetsLater, - void(uint32 nFlags, float fDepth)); - MOCK_METHOD8(ReadFrameBuffer, - void(unsigned char*, int, int, int, ERB_Type, bool, int, int)); - MOCK_METHOD4(ReadFrameBufferFast, - void(uint32*, int, int, bool)); - MOCK_METHOD1(EnableVSync, - void(bool enable)); - MOCK_METHOD1(CreateResourceAsync, - void(SResourceAsync * Resource)); - MOCK_METHOD1(ReleaseResourceAsync, - void(SResourceAsync * Resource)); - MOCK_METHOD1(ReleaseResourceAsync, - void(AZStd::unique_ptr<SResourceAsync> Resource)); - - // Hand-edit: google mock can only do up to 10 parameters - unsigned int DownLoadToVideoMemory(const byte*, int, int, ETEX_Format, ETEX_Format, int, bool = true, - int = FILTER_BILINEAR, int = 0, const char* = nullptr, int = 0, EEndian = eLittleEndian, - RectI* = nullptr, bool = false) override { return 0; } - - unsigned int DownLoadToVideoMemory3D(const byte*, int, int, [[maybe_unused]] int d, ETEX_Format, ETEX_Format, int, bool = true, - int = FILTER_BILINEAR, int = 0, const char* = nullptr, int = 0, EEndian = eLittleEndian, - RectI* = nullptr, bool = false) override { return 0; } - - unsigned int DownLoadToVideoMemoryCube(const byte*, int, int, ETEX_Format, ETEX_Format, int, bool = true, - int = FILTER_BILINEAR, int = 0, const char* = nullptr, int = 0, EEndian = eLittleEndian, - RectI* = nullptr, bool = false) override { return 0; } - - MOCK_METHOD9(UpdateTextureInVideoMemory, - void(uint32, const byte*, int, int, int, int, ETEX_Format, int, int)); - MOCK_METHOD8(DXTCompress, - bool(const byte * raw_data, int nWidth, int nHeight, ETEX_Format eTF, bool bUseHW, bool bGenMips, int nSrcBytesPerPix, MIPDXTcallback callback)); - MOCK_METHOD9(DXTDecompress, - bool(const byte * srcData, size_t srcFileSize, byte * dstData, int nWidth, int nHeight, int nMips, ETEX_Format eSrcTF, bool bUseHW, int nDstBytesPerPix)); - MOCK_METHOD1(RemoveTexture, - void(unsigned int TextureId)); - MOCK_METHOD1(DeleteFont, - void(IFFont * font)); - MOCK_METHOD3(CaptureFrameBufferFast, - bool(unsigned char* pDstRGBA8, int destinationWidth, int destinationHeight)); - MOCK_METHOD3(CopyFrameBufferFast, - bool(unsigned char* pDstRGBA8, int destinationWidth, int destinationHeight)); - MOCK_METHOD1(RegisterCaptureFrame, - bool(ICaptureFrameListener * pCapture)); - MOCK_METHOD1(UnRegisterCaptureFrame, - bool(ICaptureFrameListener * pCapture)); - MOCK_METHOD2(InitCaptureFrameBufferFast, - bool(uint32, uint32)); - MOCK_METHOD0(CloseCaptureFrameBufferFast, - void(void)); - MOCK_METHOD0(CaptureFrameBufferCallBack, - void(void)); - MOCK_METHOD1(RegisterSyncWithMainListener, - void(ISyncMainWithRenderListener * pListener)); - MOCK_METHOD1(RemoveSyncWithMainListener, - void(const ISyncMainWithRenderListener * pListener)); - MOCK_METHOD5(Set2DMode, - void(uint32, uint32, TransformationMatrices&, float, float)); - MOCK_METHOD1(Unset2DMode, - void(const TransformationMatrices& restoringMatrices)); - MOCK_METHOD7(Set2DModeNonZeroTopLeft, - void(float, float, float, float, TransformationMatrices&, float, float)); - MOCK_METHOD1(ScreenToTexture, - int(int nTexID)); - MOCK_METHOD1(EnableSwapBuffers, - void(bool bEnable)); - MOCK_METHOD0(GetHWND, - WIN_HWND()); - MOCK_METHOD1(SetWindowIcon, - bool(const char* path)); - MOCK_METHOD1(OnEntityDeleted, - void(struct IRenderNode* pRenderNode)); - MOCK_METHOD5(CreateRenderTarget, - int(const char* name, int nWidth, int nHeight, const ColorF& clearColor, ETEX_Format eTF)); - MOCK_METHOD1(DestroyRenderTarget, - bool(int nHandle)); - MOCK_METHOD3(ResizeRenderTarget, - bool(int nHandle, int nWidth, int nHeight)); - MOCK_METHOD2(SetRenderTarget, - bool(int, SDepthTexture*)); - MOCK_METHOD3(CreateDepthSurface, - SDepthTexture * (int, int, bool)); - MOCK_METHOD1(DestroyDepthSurface, - void(SDepthTexture * pDepthSurf)); - MOCK_METHOD1(PauseTimer, - void(bool bPause)); - MOCK_METHOD0(CreateShaderPublicParams, - IShaderPublicParams * ()); - MOCK_CONST_METHOD2(GetThreadIDs, - void(threadID & mainThreadID, threadID & renderThreadID)); - MOCK_METHOD1(EnableGPUTimers2, - void(bool bEnabled)); - MOCK_METHOD1(AllowGPUTimers2, - void(bool bAllow)); - MOCK_CONST_METHOD2(GetRPPStats, - const RPProfilerStats * (ERenderPipelineProfilerStats, bool)); - MOCK_CONST_METHOD1(GetRPPStatsArray, - const RPProfilerStats * (bool)); - MOCK_METHOD4(GetPolygonCountByType, - int(uint32, EVertexCostTypes, uint32, bool)); - MOCK_METHOD5(SetCloudShadowsParams, - void(int nTexID, const Vec3& speed, float tiling, bool invert, float brightness)); - MOCK_METHOD2(PushFogVolumeContribution, - uint16(const SFogVolumeData& fogVolData, const SRenderingPassInfo& passInfo)); - MOCK_METHOD2(PushFogVolume, - void(class CREFogVolume * pFogVolume, const SRenderingPassInfo& passInfo)); - MOCK_METHOD0(GetMaxTextureSize, - int()); - MOCK_METHOD1(GetTextureFormatName, - const char*(ETEX_Format eTF)); - MOCK_METHOD5(GetTextureFormatDataSize, - int(int nWidth, int nHeight, int nDepth, int nMips, ETEX_Format eTF)); - MOCK_METHOD2(SetDefaultMaterials, - void(_smart_ptr<IMaterial> pDefMat, _smart_ptr<IMaterial> pTerrainDefMat)); - MOCK_CONST_METHOD0(GetGPUParticleEngine, - IGPUParticleEngine * ()); - MOCK_CONST_METHOD0(GetActiveGPUCount, - uint32()); - MOCK_METHOD0(GetShadowFrustumMGPUCache, - ShadowFrustumMGPUCache * ()); - - MOCK_CONST_METHOD0(GetCachedShadowsResolution, - const StaticArray<int, MAX_GSM_LODS_NUM>&()); - - MOCK_METHOD1(SetCachedShadowsResolution, - void(const StaticArray<int, MAX_GSM_LODS_NUM>&arrResolutions)); - MOCK_CONST_METHOD1(UpdateCachedShadowsLodCount, - void(int nGsmLods)); - MOCK_METHOD1(SetTexturePrecaching, - void(bool stat)); - MOCK_METHOD2(RT_InsertGpuCallback, - void(uint32 context, GpuCallbackFunc callback)); - MOCK_METHOD1(EnablePipelineProfiler, - void(bool bEnable)); - MOCK_METHOD1(GetRenderTimes, - void(SRenderTimes & outTimes)); - MOCK_METHOD0(GetGPUFrameTime, - float()); - MOCK_METHOD1(EnableBatchMode, - void(bool enable)); - MOCK_METHOD1(EnableLevelUnloading, - void(bool enable)); - MOCK_METHOD0(OnLevelLoadFailed, - void()); -#if !defined(_RELEASE) - MOCK_METHOD1(GetDrawCallsInfoPerMesh, - RNDrawcallsMapMesh & (bool)); - MOCK_METHOD1(GetDrawCallsInfoPerMeshPreviousFrame, - RNDrawcallsMapMesh & (bool)); - MOCK_METHOD1(GetDrawCallsInfoPerNodePreviousFrame, - RNDrawcallsMapNode & (bool)); - MOCK_METHOD1(GetDrawCallsPerNode, - int(IRenderNode * pRenderNode)); - MOCK_METHOD1(ForceRemoveNodeFromDrawCallsMap, - void(IRenderNode * pNode)); -#endif - MOCK_METHOD1(CollectDrawCallsInfo, - void(bool status)); - MOCK_METHOD1(CollectDrawCallsInfoPerNode, - void(bool status)); - MOCK_METHOD0(HasLoadedDefaultResources, - bool()); - MOCK_METHOD3(EF_CreateSkinningData, - SSkinningData * (uint32, bool, bool)); - MOCK_METHOD4(EF_CreateRemappedSkinningData, - SSkinningData * (uint32 nNumBones, SSkinningData * pSourceSkinningData, uint32 nCustomDataSize, uint32 pairGuid)); - MOCK_METHOD0(EF_ClearSkinningDataPool, - void()); - MOCK_METHOD0(EF_GetSkinningPoolID, - int()); - MOCK_METHOD1(ClearShaderItem, - void(SShaderItem * pShaderItem)); - MOCK_METHOD2(UpdateShaderItem, - void(SShaderItem * pShaderItem, _smart_ptr<IMaterial> pMaterial)); - MOCK_METHOD2(ForceUpdateShaderItem, - void(SShaderItem * pShaderItem, _smart_ptr<IMaterial> pMaterial)); - MOCK_METHOD2(RefreshShaderResourceConstants, - void(SShaderItem * pShaderItem, IMaterial * pMaterial)); - MOCK_METHOD0(IsStereoModeChangePending, - bool()); - MOCK_METHOD1(LockParticleVideoMemory, - void(uint32 nId)); - MOCK_METHOD1(UnLockParticleVideoMemory, - void(uint32 nId)); - MOCK_METHOD1(BeginSpawningGeneratingRendItemJobs, - void(int nThreadID)); - MOCK_METHOD1(BeginSpawningShadowGeneratingRendItemJobs, - void(int nThreadID)); - MOCK_METHOD0(EndSpawningGeneratingRendItemJobs, - void()); - MOCK_METHOD1(StartLoadtimePlayback, - void(ILoadtimeCallback* pCallback)); - MOCK_METHOD0(StopLoadtimePlayback, - void()); - - MOCK_METHOD0(GetGenerateRendItemJobExecutor, - AZ::LegacyJobExecutor*()); - MOCK_METHOD0(GetGenerateShadowRendItemJobExecutor, - AZ::LegacyJobExecutor*()); - MOCK_METHOD0(GetGenerateRendItemJobExecutorPreProcess, - AZ::LegacyJobExecutor*()); - MOCK_METHOD1(GetFinalizeRendItemJobExecutor, - AZ::LegacyJobExecutor*(int nThreadID)); - MOCK_METHOD1(GetFinalizeShadowRendItemJobExecutor, - AZ::LegacyJobExecutor*(int nThreadID)); - MOCK_METHOD0(FlushPendingTextureTasks, - void()); - MOCK_METHOD1(SetShadowJittering, - void(float fShadowJittering)); - MOCK_CONST_METHOD0(GetShadowJittering, - float()); - MOCK_METHOD0(LoadShaderStartupCache, - bool()); - MOCK_METHOD0(UnloadShaderStartupCache, - void()); - MOCK_METHOD0(LoadShaderLevelCache, - bool()); - MOCK_METHOD0(UnloadShaderLevelCache, - void()); - MOCK_METHOD1(StartScreenShot, - void(int e_ScreenShot)); - MOCK_METHOD1(EndScreenShot, - void(int e_ScreenShot)); - MOCK_METHOD3(SetRendererCVar, - void(ICVar*, const char*, bool)); - MOCK_METHOD0(GetRenderPipeline, - SRenderPipeline * ()); - MOCK_METHOD0(GetShaderManager, - CShaderMan * ()); - MOCK_METHOD0(GetRenderThread, - SRenderThread * ()); - MOCK_METHOD0(GetWhiteTexture, - ITexture * ()); - MOCK_METHOD3(GetTextureForName, - ITexture * (const char* name, uint32 nFlags, ETEX_Format eFormat)); - MOCK_METHOD0(GetViewParameters, - const CameraViewParameters& ()); - MOCK_METHOD0(GetFrameReset, - uint32()); - MOCK_METHOD0(GetDepthBufferOrig, - SDepthTexture * ()); - MOCK_METHOD0(GetBackBufferWidth, - uint32()); - MOCK_METHOD0(GetBackBufferHeight, - uint32()); - MOCK_METHOD0(GetDeviceBufferManager, - CDeviceBufferManager * ()); - MOCK_CONST_METHOD0(GetRenderTileInfo, - const SRenderTileInfo * ()); - MOCK_METHOD0(GetIdentityMatrix, - Matrix44A()); - MOCK_CONST_METHOD0(RT_GetCurrGpuID, - int32()); - MOCK_METHOD0(GenerateTextureId, - int()); - MOCK_METHOD2(SetCull, - void(ECull, bool)); - MOCK_METHOD10(DrawQuad, - void(float x0, float y0, float x1, float y1, const ColorF& color, float z, float s0, float t0, float s1, float t1)); - MOCK_METHOD9(DrawQuad3D, - void(const Vec3& v0, const Vec3& v1, const Vec3& v2, const Vec3& v3, const ColorF& color, float ftx0, float fty0, float ftx1, float fty1)); - MOCK_METHOD0(FX_ResetPipe, - void()); - MOCK_METHOD4(FX_GetDepthSurface, - SDepthTexture * (int, int, bool, bool)); - MOCK_METHOD5(FX_CheckOverflow, - void(int, int, IRenderElement*, int*, int*)); - MOCK_METHOD1(FX_PreRender, - void(int Stage)); - MOCK_METHOD0(FX_PostRender, - void()); - MOCK_METHOD3(FX_SetState, - void(int, int, int)); - MOCK_METHOD3(FX_CommitStates, - void(const SShaderTechnique * pTech, const SShaderPass * pPass, bool bUseMaterialState)); - MOCK_METHOD1(FX_Commit, - void(bool)); - MOCK_METHOD2(FX_SetVertexDeclaration, - long(int StreamMask, const AZ::Vertex::Format& vertexFormat)); - MOCK_METHOD7(FX_DrawIndexedPrimitive, - void(eRenderPrimitiveType, int, int, int, int, int, bool)); - MOCK_METHOD3(FX_SetIStream, - long(const void* pB, uint32 nOffs, RenderIndexType idxType)); - MOCK_METHOD5(FX_SetVStream, - long(int, const void*, uint32, uint32, uint32)); - MOCK_METHOD4(FX_DrawPrimitive, - void(eRenderPrimitiveType, int, int, int)); - MOCK_METHOD1(FX_ClearTarget, - void(ITexture * pTex)); - MOCK_METHOD1(FX_ClearTarget, - void(SDepthTexture * pTex)); - MOCK_METHOD4(FX_SetRenderTarget, - bool(int, void*, SDepthTexture*, uint32)); - MOCK_METHOD4(FX_PushRenderTarget, - bool(int, void*, SDepthTexture*, uint32)); - MOCK_METHOD7(FX_SetRenderTarget, - bool(int, CTexture*, SDepthTexture*, bool, int, bool, uint32)); - MOCK_METHOD6(FX_PushRenderTarget, - bool(int, CTexture*, SDepthTexture*, int, bool, uint32)); - MOCK_METHOD1(FX_RestoreRenderTarget, - bool(int nTarget)); - MOCK_METHOD1(FX_PopRenderTarget, - bool(int nTarget)); - MOCK_METHOD1(FX_SetActiveRenderTargets, - void(bool bAllowDIP)); - MOCK_METHOD4(FX_Start, - void(CShader * ef, int nTech, CShaderResources * Res, IRenderElement * re)); - MOCK_METHOD1(RT_PopRenderTarget, - void(int nTarget)); - MOCK_METHOD5(RT_SetViewport, - void(int, int, int, int, int)); - MOCK_METHOD4(RT_PushRenderTarget, - void(int nTarget, CTexture * pTex, SDepthTexture * pDS, int nS)); - MOCK_METHOD5(EF_Scissor, - void(bool bEnable, int sX, int sY, int sWdt, int sHgt)); - -#ifdef SUPPORT_HW_MOUSE_CURSOR - MOCK_METHOD0(GetIHWMouseCursor, - IHWMouseCursor * ()); -#endif - - MOCK_METHOD0(GetRecursionLevel, - int()); - MOCK_METHOD2(GetIntegerConfigurationValue, - int(const char* varName, int defaultValue)); - MOCK_METHOD2(GetFloatConfigurationValue, - float(const char* varName, float defaultValue)); - MOCK_METHOD2(GetBooleanConfigurationValue, - bool(const char* varName, bool defaultValue)); - MOCK_METHOD3(ApplyDepthTextureState, - void(int unit, int nFilter, bool clamp)); - MOCK_METHOD0(GetZTargetTexture, - ITexture * ()); - MOCK_METHOD1(GetTextureState, - int(const STexState& TS)); - MOCK_METHOD7(TextureDataSize, - uint32(uint32, uint32, uint32, uint32, uint32, ETEX_Format, ETEX_TileMode)); - MOCK_METHOD6(ApplyForID, - void(int nID, int nTUnit, int nTState, int nTexMaterialSlot, int nSUnit, bool useWhiteDefault)); - MOCK_METHOD9(Create3DTexture, - ITexture * (const char* szName, int nWidth, int nHeight, int nDepth, int nMips, int nFlags, const byte * pData, ETEX_Format eTFSrc, ETEX_Format eTFDst)); - MOCK_METHOD1(IsTextureExist, - bool(const ITexture * pTex)); - MOCK_METHOD1(NameForTextureFormat, - const char*(ETEX_Format eTF)); - MOCK_METHOD1(NameForTextureType, - const char*(ETEX_Type eTT)); - MOCK_METHOD0(IsVideoThreadModeEnabled, - bool()); - MOCK_METHOD5(CreateDynTexture2, - IDynTexture * (uint32 nWidth, uint32 nHeight, uint32 nTexFlags, const char* szSource, ETexPool eTexPool)); - MOCK_METHOD0(GetCurrentTextureAtlasSize, - uint32()); - MOCK_METHOD2(BeginProfilerSection, - void(const char*, uint32)); - MOCK_METHOD1(EndProfilerSection, - void(const char*)); - MOCK_METHOD1(AddProfilerLabel, - void(const char*)); - - MOCK_METHOD5(EF_QueryImpl, - void(ERenderQueryTypes eQuery, void* pInOut0, uint32 nInOutSize0, void* pInOut1, uint32 nInOutSize1)); -}; - - diff --git a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h deleted file mode 100644 index 9c25748eca..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once -#include <ISystem.h> -#include <Cry_Camera.h> - -#ifdef GetUserName -#undef GetUserName -#endif - -class SystemMock - : public ISystem -{ -public: - MOCK_METHOD0(Release, - void()); - MOCK_METHOD0(GetGlobalEnvironment, - SSystemGlobalEnvironment * ()); - MOCK_METHOD2(UpdatePreTickBus, - bool(int, int)); - MOCK_METHOD2(UpdatePostTickBus, - bool(int, int)); - MOCK_METHOD0(UpdateLoadtime, - bool()); - MOCK_METHOD0(DoWorkDuringOcclusionChecks, - void()); - MOCK_METHOD0(NeedDoWorkDuringOcclusionChecks, - bool()); - MOCK_METHOD0(RenderStatistics, - void()); - MOCK_METHOD0(GetUserName, - const char*()); - MOCK_METHOD0(Quit, - void()); - MOCK_METHOD1(Relaunch, - void(bool bRelaunch)); - MOCK_CONST_METHOD0(IsQuitting, - bool()); - MOCK_METHOD1(SerializingFile, - void(int mode)); - MOCK_CONST_METHOD0(IsSerializingFile, - int()); - MOCK_CONST_METHOD0(IsRelaunch, - bool()); - - void FatalError([[maybe_unused]] const char* sFormat, ...) override {} - void ReportBug([[maybe_unused]] const char* sFormat, ...) override {} - - MOCK_METHOD6(WarningV, - void(EValidatorModule module, EValidatorSeverity severity, int flags, const char* file, const char* format, va_list args)); - - void Warning([[maybe_unused]] EValidatorModule module, [[maybe_unused]] EValidatorSeverity severity, [[maybe_unused]] int flags, [[maybe_unused]] const char* file, [[maybe_unused]] const char* format, ...) override {} - - MOCK_METHOD3(ShowMessage, - int(const char* text, const char* caption, unsigned int uType)); - MOCK_METHOD1(CheckLogVerbosity, - bool(int verbosity)); - MOCK_METHOD0(GetIViewSystem, - IViewSystem * ()); - MOCK_METHOD0(GetILevelSystem, - ILevelSystem * ()); - MOCK_METHOD0(GetINameTable, - INameTable * ()); - MOCK_METHOD0(GetICmdLine, - ICmdLine * ()); - MOCK_METHOD0(GetILog, - ILog * ()); - MOCK_METHOD0(GetIPak, - AZ::IO::IArchive * ()); - MOCK_METHOD0(GetICryFont, - ICryFont * ()); - MOCK_METHOD0(GetIMovieSystem, - IMovieSystem * ()); - MOCK_METHOD0(GetIAudioSystem, - Audio::IAudioSystem * ()); - MOCK_METHOD0(GetIConsole, - ::IConsole * ()); - MOCK_METHOD0(GetIRemoteConsole, - IRemoteConsole * ()); - MOCK_METHOD0(GetIProfilingSystem, - IProfilingSystem * ()); - MOCK_METHOD0(GetISystemEventDispatcher, - ISystemEventDispatcher * ()); - MOCK_METHOD0(GetITimer, - ITimer * ()); - MOCK_METHOD1(SetForceNonDevMode, - void(bool bValue)); - MOCK_CONST_METHOD0(GetForceNonDevMode, - bool()); - MOCK_CONST_METHOD0(WasInDevMode, - bool()); - MOCK_CONST_METHOD0(IsDevMode, - bool()); - MOCK_METHOD3(CreateXmlNode, - XmlNodeRef(const char*, bool, bool)); - MOCK_METHOD4(LoadXmlFromBuffer, - XmlNodeRef(const char*, size_t, bool, bool)); - MOCK_METHOD2(LoadXmlFromFile, - XmlNodeRef(const char*, bool)); - MOCK_METHOD0(GetXmlUtils, - IXmlUtils * ()); - MOCK_METHOD1(SetViewCamera, - void(CCamera & Camera)); - MOCK_METHOD0(GetViewCamera, - CCamera & ()); - MOCK_METHOD1(IgnoreUpdates, - void(bool bIgnore)); - MOCK_METHOD1(SetIProcess, - void(IProcess * process)); - MOCK_METHOD0(GetIProcess, - IProcess * ()); - MOCK_CONST_METHOD0(IsTestMode, - bool()); - MOCK_METHOD3(SetFrameProfiler, - void(bool on, bool display, char* prefix)); - MOCK_METHOD0(GetFileVersion, - const SFileVersion&()); - MOCK_METHOD0(GetProductVersion, - const SFileVersion&()); - MOCK_METHOD0(GetBuildVersion, - const SFileVersion&()); - - MOCK_METHOD1(AddCVarGroupDirectory, - void(const string&)); - MOCK_METHOD0(SaveConfiguration, - void()); - MOCK_METHOD3(LoadConfiguration, - void(const char*, ILoadConfigurationEntrySink*, bool)); - - MOCK_CONST_METHOD0(GetMaxConfigSpec, - ESystemConfigSpec()); - MOCK_CONST_METHOD0(GetConfigPlatform, - ESystemConfigPlatform()); - MOCK_METHOD1(SetConfigPlatform, - void(ESystemConfigPlatform platform)); - MOCK_CONST_METHOD0(IsPaused, - bool()); - MOCK_METHOD0(GetLocalizationManager, - ILocalizationManager * ()); - MOCK_METHOD0(GetNoiseGen, - CPNoise3 * ()); - MOCK_METHOD0(GetUpdateCounter, - uint64()); - MOCK_METHOD1(RegisterErrorObserver, - bool(IErrorObserver * errorObserver)); - MOCK_METHOD1(UnregisterErrorObserver, - bool(IErrorObserver * errorObserver)); - MOCK_METHOD4(OnAssert, - void(const char* condition, const char* message, const char* fileName, unsigned int fileLineNumber)); - MOCK_CONST_METHOD0(IsAssertDialogVisible, - bool()); - MOCK_METHOD1(SetAssertVisible, - void(bool bAssertVisble)); - MOCK_METHOD1(SetConsoleDrawEnabled, - void(bool enabled)); - MOCK_METHOD1(SetUIDrawEnabled, - void(bool enabled)); - MOCK_METHOD0(GetApplicationInstance, - int()); - MOCK_METHOD1(GetApplicationLogInstance, - int(const char* logFilePath)); - MOCK_METHOD0(ClearErrorMessages, - void()); - MOCK_METHOD2(debug_GetCallStack, - void(const char** pFunctions, int& nCount)); - MOCK_METHOD2(debug_LogCallStack, - void(int, int)); - MOCK_METHOD1(ExecuteCommandLine, - void(bool)); - MOCK_METHOD1(GetUpdateStats, - void(SSystemUpdateStats & stats)); - MOCK_METHOD0(GetSystemGlobalState, - ESystemGlobalState(void)); - MOCK_METHOD1(SetSystemGlobalState, - void(ESystemGlobalState systemGlobalState)); - -#if !defined(_RELEASE) - MOCK_CONST_METHOD0(IsSavingResourceList, - bool()); -#endif - - MOCK_METHOD0(GetRootWindowMessageHandler, - void*()); - MOCK_METHOD1(RegisterWindowMessageHandler, - void(IWindowMessageHandler * pHandler)); - MOCK_METHOD1(UnregisterWindowMessageHandler, - void(IWindowMessageHandler * pHandler)); - MOCK_METHOD0(CreateLocalFileIO, - std::shared_ptr<AZ::IO::FileIOBase>()); - - MOCK_METHOD2(ForceMaxFps, void(bool, int)); -}; diff --git a/Code/CryEngine/CryCommon/Mocks/ITextureMock.h b/Code/CryEngine/CryCommon/Mocks/ITextureMock.h deleted file mode 100644 index 691b8808d6..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/ITextureMock.h +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <ITexture.h> -#include <AzTest/AzTest.h> - -class ITextureMock - : public ITexture -{ -public: - MOCK_METHOD0(AddRef, - int()); - MOCK_METHOD0(Release, - int()); - MOCK_METHOD0(ReleaseForce, - int()); - MOCK_CONST_METHOD0(GetClearColor, - const ColorF& ()); - MOCK_CONST_METHOD0(GetDstFormat, - const ETEX_Format()); - MOCK_CONST_METHOD0(GetSrcFormat, - const ETEX_Format()); - MOCK_CONST_METHOD0(GetTexType, - const ETEX_Type()); - MOCK_METHOD2(ApplyTexture, - void(int, int)); - MOCK_CONST_METHOD0(GetName, - const char*()); - MOCK_CONST_METHOD0(GetWidth, - const int()); - MOCK_CONST_METHOD0(GetHeight, - const int()); - MOCK_CONST_METHOD0(GetDepth, - const int()); - MOCK_CONST_METHOD0(GetTextureID, - const int()); - MOCK_CONST_METHOD0(GetFlags, - const uint32()); - MOCK_CONST_METHOD0(GetNumMips, - const int()); - MOCK_CONST_METHOD0(GetRequiredMip, - const int()); - MOCK_CONST_METHOD0(GetDeviceDataSize, - const int()); - MOCK_CONST_METHOD0(GetDataSize, - const int()); - MOCK_CONST_METHOD0(GetTextureType, - const ETEX_Type()); - MOCK_METHOD1(SetTextureType, - void(ETEX_Type type)); - MOCK_CONST_METHOD0(IsTextureLoaded, - const bool()); - MOCK_METHOD4(PrecacheAsynchronously, - void(float, int, int, int)); - MOCK_METHOD4(GetData32, - uint8 * (int nSide, int nLevel, uint8 * pDst, ETEX_Format eDstFormat)); - MOCK_METHOD1(SetFilter, - bool(int nFilter)); - MOCK_METHOD1(SetClamp, - void(bool bEnable)); - MOCK_CONST_METHOD0(GetAvgBrightness, - float()); - MOCK_CONST_METHOD1(StreamCalculateMipsSigned, - int(float fMipFactor)); - MOCK_CONST_METHOD0(GetStreamableMipNumber, - int()); - MOCK_CONST_METHOD1(GetStreamableMemoryUsage, - int(int nStartMip)); - MOCK_CONST_METHOD0(GetMinLoadedMip, - int()); - MOCK_METHOD2(Readback, - void(AZ::u32 subresourceIndex, StagingHook callback)); - MOCK_METHOD0(Reload, - bool()); - MOCK_CONST_METHOD0(GetFormatName, - const char*()); - MOCK_CONST_METHOD0(GetTypeName, - const char*()); - MOCK_CONST_METHOD0(IsStreamedVirtual, - const bool()); - MOCK_CONST_METHOD0(IsShared, - const bool()); - MOCK_CONST_METHOD0(IsStreamable, - const bool()); - MOCK_CONST_METHOD1(IsStreamedIn, - bool(const int nMinPrecacheRoundIds[2])); - MOCK_CONST_METHOD0(GetAccessFrameId, - const int()); - MOCK_CONST_METHOD0(GetTextureDstFormat, - const ETEX_Format()); - MOCK_CONST_METHOD0(GetTextureSrcFormat, - const ETEX_Format()); - MOCK_CONST_METHOD0(IsPostponed, - bool()); - MOCK_CONST_METHOD1(IsParticularMipStreamed, - const bool(float fMipFactor)); - MOCK_METHOD3(GetLowResSystemCopy, - const ColorB * (uint16 & nWidth, uint16 & nHeight, int** ppLowResSystemCopyAtlasId)); - MOCK_METHOD1(SetKeepSystemCopy, - void(bool bKeepSystemCopy)); - MOCK_METHOD8(UpdateTextureRegion, - void(const uint8_t * data, int nX, int nY, int nZ, int USize, int VSize, int ZSize, ETEX_Format eTFSrc)); - MOCK_CONST_METHOD0(GetDevTexture, - CDeviceTexture * ()); -}; - -class ITextureLoadHandlerMock - : public ITextureLoadHandler -{ -public: - MOCK_METHOD2(LoadTextureData, - bool(const char* path, STextureLoadData & loadData)); - MOCK_CONST_METHOD1(SupportsExtension, - bool(const char* ext)); - MOCK_METHOD0(Update, - void()); -}; - -class IDynTextureMock - : public IDynTexture -{ -public: - MOCK_METHOD0(Release, - void()); - MOCK_METHOD4(GetSubImageRect, - void(uint32 & nX, uint32 & nY, uint32 & nWidth, uint32 & nHeight)); - MOCK_METHOD4(GetImageRect, - void(uint32 & nX, uint32 & nY, uint32 & nWidth, uint32 & nHeight)); - MOCK_METHOD0(GetTextureID, - int()); - MOCK_METHOD0(Lock, - void()); - MOCK_METHOD0(UnLock, - void()); - MOCK_METHOD0(GetWidth, - int()); - MOCK_METHOD0(GetHeight, - int()); - MOCK_METHOD0(IsValid, - bool()); - MOCK_CONST_METHOD0(GetFlags, - uint8()); - MOCK_METHOD1(SetFlags, - void(uint8 flags)); - MOCK_METHOD2(Update, - bool(int nNewWidth, int nNewHeight)); - MOCK_METHOD2(Apply, - void(int, int)); - MOCK_METHOD0(ClearRT, - bool()); - MOCK_METHOD4(SetRT, - bool(int nRT, bool bPush, struct SDepthTexture* pDepthSurf, bool bScreenVP)); - MOCK_METHOD0(SetRectStates, - bool()); - MOCK_METHOD2(RestoreRT, - bool(int nRT, bool bPop)); - MOCK_METHOD0(GetTexture, - ITexture * ()); - MOCK_METHOD0(SetUpdateMask, - void()); - MOCK_METHOD0(ResetUpdateMask, - void()); - MOCK_METHOD0(IsSecondFrame, - bool()); - MOCK_METHOD2(GetImageData32, - bool(uint8 * pData, int nDataSize)); -}; diff --git a/Code/CryEngine/CryCommon/Mocks/ITimerMock.h b/Code/CryEngine/CryCommon/Mocks/ITimerMock.h deleted file mode 100644 index 12d3a9e57b..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/ITimerMock.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#ifndef CRYINCLUDE_CRYSYSTEM_ITIMERMOCK_H -#define CRYINCLUDE_CRYSYSTEM_ITIMERMOCK_H -#pragma once - -#include <ISerialize.h> -#include <ITimer.h> -#include <AzTest/AzTest.h> - -// Implements all common timing routines -class TimerMock - : public ITimer -{ -public: - MOCK_METHOD0(ResetTimer, void()); - MOCK_METHOD0(UpdateOnFrameStart, void()); - MOCK_CONST_METHOD1(GetCurrTime, float(ETimer which)); - MOCK_CONST_METHOD0(GetAsyncTime, CTimeValue()); - MOCK_METHOD0(GetAsyncCurTime, float()); - MOCK_CONST_METHOD1(GetFrameTime, float(ETimer which)); - MOCK_CONST_METHOD0(GetRealFrameTime, float()); - MOCK_CONST_METHOD0(GetTimeScale, float()); - MOCK_CONST_METHOD1(GetTimeScale, float(uint32 channel)); - MOCK_METHOD2(SetTimeScale, void(float scale, uint32 channel)); - MOCK_METHOD0(ClearTimeScales, void()); - MOCK_METHOD1(EnableTimer, void(bool bEnable)); - MOCK_METHOD0(GetFrameRate, float()); - MOCK_METHOD2(GetProfileFrameBlending, float(float* pfBlendTime, int* piBlendMode)); - MOCK_METHOD1(Serialize, void(TSerialize ser)); - MOCK_CONST_METHOD0(IsTimerEnabled, bool()); - MOCK_METHOD2(PauseTimer, bool(ETimer which, bool bPause)); - MOCK_METHOD1(IsTimerPaused, bool(ETimer which)); - MOCK_METHOD2(SetTimer, bool(ETimer which, float timeInSeconds)); - MOCK_METHOD2(SecondsToDateUTC, void(time_t time, struct tm& outDateUTC)); - MOCK_METHOD1(DateToSecondsUTC, time_t(struct tm& timePtr)); - MOCK_METHOD1(TicksToSeconds, float(int64 ticks)); - MOCK_METHOD0(GetTicksPerSecond, int64()); - - MOCK_CONST_METHOD1(GetFrameStartTime, const CTimeValue&(ETimer which)); - MOCK_METHOD0(CreateNewTimer, ITimer * ()); - - MOCK_METHOD2(EnableFixedTimeMode, void(bool enable, float timeStep)); -}; - -#endif // CRYINCLUDE_CRYSYSTEM_ITIMERMOCK_H diff --git a/Code/CryEngine/CryCommon/Mocks/StubTimer.h b/Code/CryEngine/CryCommon/Mocks/StubTimer.h deleted file mode 100644 index 1a2aec3e30..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/StubTimer.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include <ITimer.h> - -//! Simple stub timer that exposes a single simple interface for setting the current time. -class StubTimer - : public ITimer -{ -public: - // Stub methods - void SetTime(float seconds) - { - m_frameStartTime.SetSeconds(seconds); - } - //~Stub methods - - StubTimer(float frameTime) - : m_frameTime(frameTime) - , m_frameRate(1.0f / frameTime) - , m_frameStartTime(0.0f) - { - } - virtual ~StubTimer() {}; - - // ITimer - void ResetTimer() override {} - void UpdateOnFrameStart() override {} - float GetCurrTime([[maybe_unused]] ETimer which = ETIMER_GAME) const override - { - // return the same as the frame start time - return m_frameStartTime.GetSeconds(); - } - const CTimeValue& GetFrameStartTime([[maybe_unused]] ETimer which = ETIMER_GAME) const override - { - return m_frameStartTime; - } - CTimeValue GetAsyncTime() const override - { - return m_frameStartTime; - } - float GetAsyncCurTime() override - { - return m_frameStartTime.GetSeconds(); - } - float GetFrameTime([[maybe_unused]] ETimer which = ETIMER_GAME) const override - { - return m_frameTime; - } - float GetRealFrameTime() const override - { - return m_frameTime; - } - float GetTimeScale() const override - { - return 1.0f; - } - float GetTimeScale([[maybe_unused]] uint32 channel) const override - { - return 1.0f; - } - void ClearTimeScales() override {} - void SetTimeScale([[maybe_unused]] float s, [[maybe_unused]] uint32 channel = 0) override {} - void EnableTimer([[maybe_unused]] bool bEnable) override {} - bool IsTimerEnabled() const override - { - return true; - } - float GetFrameRate() override - { - return m_frameRate; - } - float GetProfileFrameBlending([[maybe_unused]] float* pfBlendTime = 0, [[maybe_unused]] int* piBlendMode = 0) override - { - return 0.0f; - } - void Serialize([[maybe_unused]] TSerialize ser) override {} - bool PauseTimer([[maybe_unused]] ETimer which, [[maybe_unused]] bool bPause) override { return false; } - bool IsTimerPaused([[maybe_unused]] ETimer which) override { return false; } - bool SetTimer([[maybe_unused]] ETimer which, [[maybe_unused]] float timeInSeconds) override { return false; } - void SecondsToDateUTC([[maybe_unused]] time_t time, [[maybe_unused]] struct tm& outDateUTC) override {} - time_t DateToSecondsUTC([[maybe_unused]] struct tm& timePtr) override - { - return 0; - } - float TicksToSeconds([[maybe_unused]] int64 ticks) override - { - return 0.0f; - } - int64 GetTicksPerSecond() override - { - return 0; - } - ITimer* CreateNewTimer() override - { - return nullptr; - } - void EnableFixedTimeMode([[maybe_unused]] bool enable, [[maybe_unused]] float timeStep) override {} - // ~ITimer - -private: - CTimeValue m_frameStartTime; - float m_frameTime; - float m_frameRate; -}; diff --git a/Code/CryEngine/CryCommon/MultiThread.h b/Code/CryEngine/CryCommon/MultiThread.h deleted file mode 100644 index 94b311d459..0000000000 --- a/Code/CryEngine/CryCommon/MultiThread.h +++ /dev/null @@ -1,602 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#if defined(APPLE) || defined(LINUX) -#include <sched.h> -#endif - -#include <AzCore/std/parallel/mutex.h> - -#include "CryAssert.h" - -// Section dictionary -#if defined(AZ_RESTRICTED_PLATFORM) -#define MULTITHREAD_H_SECTION_TRAITS 1 -#define MULTITHREAD_H_SECTION_DEFINE_CRYINTERLOCKEXCHANGE 2 -#define MULTITHREAD_H_SECTION_IMPLEMENT_CRYSPINLOCK 3 -#define MULTITHREAD_H_SECTION_IMPLEMENT_CRYINTERLOCKEDADD 4 -#define MULTITHREAD_H_SECTION_IMPLEMENT_CRYINTERLOCKEDADDSIZE 5 -#define MULTITHREAD_H_SECTION_CRYINTERLOCKEDFLUSHSLIST_PT1 6 -#define MULTITHREAD_H_SECTION_CRYINTERLOCKEDFLUSHSLIST_PT2 7 -#define MULTITHREAD_H_SECTION_IMPLEMENT_CRYINTERLOCKEDCOMPAREEXCHANGE64 8 -#endif - -#define THREAD_NAME_LENGTH_MAX 64 - -#define WRITE_LOCK_VAL (1 << 16) - -// Traits -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_TRAITS - #include AZ_RESTRICTED_FILE(MultiThread_h) -#else -#define MULTITHREAD_H_TRAIT_SLOCKFREESINGLELINKEDLISTENTRY_ATTRIBUTE_ALIGN_16 0 -#if defined(WIN64) -#define MULTITHREAD_H_TRAIT_SLOCKFREESINGLELINKEDLISTENTRY_MSALIGN_16 1 -#endif -#if defined(APPLE) || defined(LINUX) -#define MULTITHREAD_H_TRAIT_USE_SALTED_LINKEDLISTHEADER 1 -#endif -#endif - -//as PowerPC operates via cache line reservation, lock variables should reside ion their own cache line -template <class T> -struct SAtomicVar -{ - T val; - - inline operator T() const{return val; } - inline operator T() volatile const{return val; } - inline SAtomicVar& operator =(const T& rV){val = rV; return *this; } - inline void Assign(const T& rV){val = rV; } - inline void Assign(const T& rV) volatile{val = rV; } - inline T* Addr() {return &val; } - inline volatile T* Addr() volatile {return &val; } - - inline bool operator<(const T& v) const{return val < v; } - inline bool operator<(const SAtomicVar<T>& v) const{return val < v.val; } - inline bool operator>(const T& v) const{return val > v; } - inline bool operator>(const SAtomicVar<T>& v) const{return val > v.val; } - inline bool operator<=(const T& v) const{return val <= v; } - inline bool operator<=(const SAtomicVar<T>& v) const{return val <= v.val; } - inline bool operator>=(const T& v) const{return val >= v; } - inline bool operator>=(const SAtomicVar<T>& v) const{return val >= v.val; } - inline bool operator==(const T& v) const{return val == v; } - inline bool operator==(const SAtomicVar<T>& v) const{return val == v.val; } - inline bool operator!=(const T& v) const{return val != v; } - inline bool operator!=(const SAtomicVar<T>& v) const{return val != v.val; } - inline T operator*(const T& v) const{return val * v; } - inline T operator/(const T& v) const{return val / v; } - inline T operator+(const T& v) const{return val + v; } - inline T operator-(const T& v) const{return val - v; } - - inline bool operator<(const T& v) volatile const{return val < v; } - inline bool operator<(const SAtomicVar<T>& v) volatile const{return val < v.val; } - inline bool operator>(const T& v) volatile const{return val > v; } - inline bool operator>(const SAtomicVar<T>& v) volatile const{return val > v.val; } - inline bool operator<=(const T& v) volatile const{return val <= v; } - inline bool operator<=(const SAtomicVar<T>& v) volatile const{return val <= v.val; } - inline bool operator>=(const T& v) volatile const{return val >= v; } - inline bool operator>=(const SAtomicVar<T>& v) volatile const{return val >= v.val; } - inline bool operator==(const T& v) volatile const{return val == v; } - inline bool operator==(const SAtomicVar<T>& v) volatile const{return val == v.val; } - inline bool operator!=(const T& v) volatile const{return val != v; } - inline bool operator!=(const SAtomicVar<T>& v) volatile const{return val != v.val; } - inline T operator*(const T& v) volatile const{return val * v; } - inline T operator/(const T& v) volatile const{return val / v; } - inline T operator+(const T& v) volatile const{return val + v; } - inline T operator-(const T& v) volatile const{return val - v; } -}; - -typedef SAtomicVar<int> TIntAtomic; -typedef SAtomicVar<unsigned int> TUIntAtomic; -typedef SAtomicVar<float> TFloatAtomic; - -#define __add_db16cycl__ NIntrinsics::YieldFor16Cycles(); - -void CrySpinLock(volatile int* pLock, int checkVal, int setVal); -void CryReleaseSpinLock (volatile int*, int); - -LONG CryInterlockedIncrement(int volatile* lpAddend); -LONG CryInterlockedDecrement(int volatile* lpAddend); -LONG CryInterlockedOr(LONG volatile* Destination, LONG Value); -LONG CryInterlockedExchangeAdd(LONG volatile* lpAddend, LONG Value); -LONG CryInterlockedCompareExchange(LONG volatile* dst, LONG exchange, LONG comperand); -void* CryInterlockedCompareExchangePointer(void* volatile* dst, void* exchange, void* comperand); -void* CryInterlockedExchangePointer (void* volatile* dst, void* exchange); - -void* CryCreateCriticalSection(); -void CryCreateCriticalSectionInplace(void*); -void CryDeleteCriticalSection(void* cs); -void CryDeleteCriticalSectionInplace(void* cs); -void CryEnterCriticalSection(void* cs); -bool CryTryCriticalSection(void* cs); -void CryLeaveCriticalSection(void* cs); - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_DEFINE_CRYINTERLOCKEXCHANGE - #include AZ_RESTRICTED_FILE(MultiThread_h) -#endif - -ILINE void CrySpinLock(volatile int* pLock, int checkVal, int setVal) -{ -#ifdef _CPU_X86 -# ifdef __GNUC__ - int val; - __asm__ __volatile__ ( - "0: mov %[checkVal], %%eax\n" - " lock cmpxchg %[setVal], (%[pLock])\n" - " jnz 0b" - : "=m" (*pLock) - : [pLock] "r" (pLock), "m" (*pLock), - [checkVal] "m" (checkVal), - [setVal] "r" (setVal) - : "eax", "cc", "memory" - ); -# else //!__GNUC__ - __asm - { - mov edx, setVal - mov ecx, pLock -Spin: - // Trick from Intel Optimizations guide -#ifdef _CPU_SSE - pause -#endif - mov eax, checkVal - lock cmpxchg [ecx], edx - jnz Spin - } -# endif //!__GNUC__ -#else // !_CPU_X86 -# if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_IMPLEMENT_CRYSPINLOCK - #include AZ_RESTRICTED_FILE(MultiThread_h) -# endif -# if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -# undef AZ_RESTRICTED_SECTION_IMPLEMENTED -# elif defined(APPLE) || defined(LINUX) - // register int val; - // __asm__ __volatile__ ( - // "0: mov %[checkVal], %%eax\n" - // " lock cmpxchg %[setVal], (%[pLock])\n" - // " jnz 0b" - // : "=m" (*pLock) - // : [pLock] "r" (pLock), "m" (*pLock), - // [checkVal] "m" (checkVal), - // [setVal] "r" (setVal) - // : "eax", "cc", "memory" - // ); - //while(CryInterlockedCompareExchange((volatile long*)pLock,setVal,checkVal)!=checkVal) ; - uint loops = 0; - while (__sync_val_compare_and_swap((volatile int32_t*)pLock, (int32_t)checkVal, (int32_t)setVal) != checkVal) - { -# if !defined (ANDROID) && !defined(IOS) - _mm_pause(); -# endif - - if (!(++loops & 0x7F)) - { - usleep(1); // give threads with other prio chance to run - } - else if (!(loops & 0x3F)) - { - sched_yield(); // give threads with same prio chance to run - } - } -# else - // NOTE: The code below will fail on 64bit architectures! - while (_InterlockedCompareExchange((volatile LONG*)pLock, setVal, checkVal) != checkVal) - { - _mm_pause(); - } -# endif -#endif -} - -ILINE void CryReleaseSpinLock(volatile int* pLock, int setVal) -{ - *pLock = setVal; -} - -////////////////////////////////////////////////////////////////////////// -#if defined(APPLE) || defined(LINUX64) -// Fixes undefined reference to CryInterlockedAdd(unsigned long volatile*, long) on -// Mac and linux. -ILINE void CryInterLockedAdd(volatile LONG* pVal, LONG iAdd) -{ - (void) CryInterlockedExchangeAdd(pVal, iAdd); -} - - -/* -ILINE void CryInterLockedAdd(volatile unsigned long *pVal, long iAdd) -{ - long r; - __asm__ __volatile__ ( - #if defined(LINUX64) || defined(MAC) // long is 64 bits on amd64. - "lock ; xaddq %0, (%1) \n\t" - #else - "lock ; xaddl %0, (%1) \n\t" - #endif - : "=r" (r) - : "r" (pVal), "0" (iAdd) - : "memory" - ); - (void) r; -}*/ -/*ILINE void CryInterlockedAdd(volatile size_t *pVal, ptrdiff_t iAdd) { - //(void)CryInterlockedExchangeAdd((volatile long*)pVal,(long)iAdd); - (void) __sync_fetch_and_add(pVal,iAdd); -}*/ - -#endif -ILINE void CryInterlockedAdd(volatile int* pVal, int iAdd) -{ -#ifdef _CPU_X86 -# ifdef __GNUC__ - __asm__ __volatile__ ( - " lock add %[iAdd], (%[pVal])\n" - : "=m" (*pVal) - : [pVal] "r" (pVal), "m" (*pVal), [iAdd] "r" (iAdd) - ); -# else - __asm - { - mov edx, pVal - mov eax, iAdd - lock add [edx], eax - } -# endif -#else - // NOTE: The code below will fail on 64bit architectures! -#if defined(_WIN64) - _InterlockedExchangeAdd((volatile LONG*)pVal, iAdd); -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_IMPLEMENT_CRYINTERLOCKEDADD - #include AZ_RESTRICTED_FILE(MultiThread_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(APPLE) || defined(LINUX) - CryInterlockedExchangeAdd((volatile LONG*)pVal, iAdd); -#elif defined(APPLE) - OSAtomicAdd32(iAdd, (volatile LONG*)pVal); -#else - InterlockedExchangeAdd((volatile LONG*)pVal, iAdd); -#endif - -#endif -} - -ILINE void CryInterlockedAddSize(volatile size_t* pVal, ptrdiff_t iAdd) -{ -#if defined(PLATFORM_64BIT) -#if defined(_WIN64) - _InterlockedExchangeAdd64((volatile __int64*)pVal, iAdd); -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_IMPLEMENT_CRYINTERLOCKEDADDSIZE - #include AZ_RESTRICTED_FILE(MultiThread_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(WIN32) - InterlockedExchangeAdd64((volatile LONG64*)pVal, iAdd); -#elif defined(APPLE) || defined(LINUX) - (void)__sync_fetch_and_add((int64_t*)pVal, (int64_t)iAdd); -#else - int64 x, n; - do - { - x = (int64) * pVal; - n = x + iAdd; - } - while (CryInterlockedCompareExchange64((volatile int64*)pVal, n, x) != x); -#endif -#else - CryInterlockedAdd((volatile int*)pVal, (int)iAdd); -#endif -} - - - -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -// CryInterlocked*SList Function, these are specialized C-A-S -// functions for single-linked lists which prevent the A-B-A problem there -// there are implemented in the platform specific CryThread_*.h files -// TODO clean up the interlocked function the same was the CryThread_* header are - -//TODO somehow get their real size on WIN (without including windows.h...) -//NOTE: The sizes are verifyed at compile-time in the implementation functions, but this is still ugly -#if MULTITHREAD_H_TRAIT_SLOCKFREESINGLELINKEDLISTENTRY_MSALIGN_16 -_MS_ALIGN(16) -#elif defined(WIN32) -_MS_ALIGN(8) -#endif -struct SLockFreeSingleLinkedListEntry -{ - SLockFreeSingleLinkedListEntry* volatile pNext; -} -#if MULTITHREAD_H_TRAIT_SLOCKFREESINGLELINKEDLISTENTRY_ATTRIBUTE_ALIGN_16 -__attribute__ ((aligned(16))) -#elif defined(LINUX32) -_ALIGN(8) -#elif defined(APPLE) || defined(LINUX64) -_ALIGN(16) -#endif -; - -#if MULTITHREAD_H_TRAIT_SLOCKFREESINGLELINKEDLISTENTRY_MSALIGN_16 -_MS_ALIGN(16) -#elif defined(WIN32) -_MS_ALIGN(8) -#endif -struct SLockFreeSingleLinkedListHeader -{ - SLockFreeSingleLinkedListEntry* volatile pNext; -#if defined(INTERLOCKED_COMPARE_EXCHANGE_128_NOT_SUPPORTED) - // arm64 processors do not provide a cmpxchg16b (or equivalent) instruction, - // so _InterlockedCompareExchange128 is not implemented on arm64 platforms, - // and we have to use a mutex to ensure thread safety. - AZStd::mutex mutex; -#elif MULTITHREAD_H_TRAIT_USE_SALTED_LINKEDLISTHEADER - // If pointers 32bit, salt should be as well. Otherwise we get 4 bytes of padding between pNext and salt and CAS operations fail -#if defined(PLATFORM_64BIT) - volatile uint64 salt; -#else - volatile uint32 salt; -#endif -#endif -} -#if MULTITHREAD_H_TRAIT_SLOCKFREESINGLELINKEDLISTENTRY_ATTRIBUTE_ALIGN_16 -__attribute__ ((aligned(16))) -#elif defined(LINUX32) -_ALIGN(8) -#elif defined(APPLE) || defined(LINUX64) -_ALIGN(16) -#endif -; - - -// push a element atomically onto a single linked list -void CryInterlockedPushEntrySList(SLockFreeSingleLinkedListHeader& list, SLockFreeSingleLinkedListEntry& element); - -// push a element atomically from a single linked list -void* CryInterlockedPopEntrySList(SLockFreeSingleLinkedListHeader& list); - -// initialzied the lock-free single linked list -void CryInitializeSListHead(SLockFreeSingleLinkedListHeader& list); - -// flush the whole list -void* CryInterlockedFlushSList(SLockFreeSingleLinkedListHeader& list); - -ILINE void CryReadLock(volatile int* rw, bool yield) -{ - CryInterlockedAdd(rw, 1); -#ifdef NEED_ENDIAN_SWAP - volatile char* pw = (volatile char*)rw + 1; -#else - volatile char* pw = (volatile char*)rw + 2; -#endif - - uint64 loops = 0; - for (; *pw; ) - { - if (yield) - { -# if !defined(ANDROID) && !defined(IOS) && !defined(MULTITHREAD_H_TRAIT_NO_MM_PAUSE) - _mm_pause(); -# endif - - if (!(++loops & 0x7F)) - { - // give other threads with other prio right to run -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_CRYINTERLOCKEDFLUSHSLIST_PT1 - #include AZ_RESTRICTED_FILE(MultiThread_h) -#elif defined (LINUX) - usleep(1); -#endif - } - else if (!(loops & 0x3F)) - { - // give threads with same prio chance to run -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_CRYINTERLOCKEDFLUSHSLIST_PT2 - #include AZ_RESTRICTED_FILE(MultiThread_h) -#elif defined (LINUX) - sched_yield(); -#endif - } - } - } -} - -ILINE void CryReleaseReadLock(volatile int* rw) -{ - CryInterlockedAdd(rw, -1); -} - -ILINE void CryWriteLock(volatile int* rw) -{ - CrySpinLock(rw, 0, WRITE_LOCK_VAL); -} - -ILINE void CryReleaseWriteLock(volatile int* rw) -{ - CryInterlockedAdd(rw, -WRITE_LOCK_VAL); -} - -////////////////////////////////////////////////////////////////////////// -struct ReadLock -{ - ILINE ReadLock(volatile int& rw) - { - CryInterlockedAdd(prw = &rw, 1); -#ifdef NEED_ENDIAN_SWAP - volatile char* pw = (volatile char*)&rw + 1; - for (; * pw; ) - { - ; - } -#else - volatile char* pw = (volatile char*)&rw + 2; - for (; * pw; ) - { - ; - } -#endif - } - ILINE ReadLock(volatile int& rw, bool yield) - { - CryReadLock(prw = &rw, yield); - } - ~ReadLock() - { - CryReleaseReadLock(prw); - } -private: - volatile int* prw; -}; - -struct ReadLockCond -{ - ILINE ReadLockCond(volatile int& rw, int bActive) - { - if (bActive) - { - CryInterlockedAdd(&rw, 1); - bActivated = 1; -#ifdef NEED_ENDIAN_SWAP - volatile char* pw = (volatile char*)&rw + 1; - for (; * pw; ) - { - ; - } -#else - volatile char* pw = (volatile char*)&rw + 2; - for (; * pw; ) - { - ; - } -#endif - } - else - { - bActivated = 0; - } - prw = &rw; - } - void SetActive(int bActive = 1) { bActivated = bActive; } - void Release() { CryInterlockedAdd(prw, -bActivated); } - ~ReadLockCond() - { - CryInterlockedAdd(prw, -bActivated); - } - -private: - volatile int* prw; - int bActivated; -}; - -////////////////////////////////////////////////////////////////////////// -struct WriteLock -{ - ILINE WriteLock(volatile int& rw) { CryWriteLock(&rw); prw = &rw; } - ~WriteLock() { CryReleaseWriteLock(prw); } -private: - volatile int* prw; -}; - -////////////////////////////////////////////////////////////////////////// -struct WriteAfterReadLock -{ - ILINE WriteAfterReadLock(volatile int& rw) { CrySpinLock(&rw, 1, WRITE_LOCK_VAL + 1); prw = &rw; } - ~WriteAfterReadLock() { CryInterlockedAdd(prw, -WRITE_LOCK_VAL); } -private: - volatile int* prw; -}; - -////////////////////////////////////////////////////////////////////////// -struct WriteLockCond -{ - ILINE WriteLockCond(volatile int& rw, int bActive = 1) - { - if (bActive) - { - CrySpinLock(&rw, 0, iActive = WRITE_LOCK_VAL); - } - else - { - iActive = 0; - } - prw = &rw; - } - ILINE WriteLockCond() { prw = &(iActive = 0); } - ~WriteLockCond() - { - CryInterlockedAdd(prw, -iActive); - } - void SetActive(int bActive = 1) { iActive = -bActive & WRITE_LOCK_VAL; } - void Release() { CryInterlockedAdd(prw, -iActive); } - volatile int* prw; - int iActive; -}; - - -#if defined(LINUX) || defined(APPLE) -ILINE int64 CryInterlockedCompareExchange64(volatile int64* addr, int64 exchange, int64 comperand) -{ - return __sync_val_compare_and_swap(addr, comperand, exchange); - // This is OK, because long is signed int64 on Linux x86_64 - //return CryInterlockedCompareExchange((volatile long*)addr, (long)exchange, (long)comperand); -} - -ILINE int64 CryInterlockedExchange64(volatile int64* addr, int64 exchange) -{ - __sync_synchronize(); - return __sync_lock_test_and_set(addr, exchange); -} -#else -ILINE int64 CryInterlockedCompareExchange64(volatile int64* addr, int64 exchange, int64 compare) -{ - // forward to system call -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_IMPLEMENT_CRYINTERLOCKEDCOMPAREEXCHANGE64 - #include AZ_RESTRICTED_FILE(MultiThread_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - return _InterlockedCompareExchange64((volatile int64*)addr, exchange, compare); -#endif -} -#endif - -////////////////////////////////////////////////////////////////////////// -#if defined(EXCLUDE_PHYSICS_THREAD) -ILINE void SpinLock(volatile int* pLock, int checkVal, int setVal) { *(int*)pLock = setVal; } -ILINE void AtomicAdd(volatile int* pVal, int iAdd) { *(int*)pVal += iAdd; } -ILINE void AtomicAdd(volatile unsigned int* pVal, int iAdd) { *(unsigned int*)pVal += iAdd; } - -ILINE void JobSpinLock(volatile int* pLock, int checkVal, int setVal) { CrySpinLock(pLock, checkVal, setVal); } -#else -ILINE void SpinLock(volatile int* pLock, int checkVal, int setVal) { CrySpinLock(pLock, checkVal, setVal); } -ILINE void AtomicAdd(volatile int* pVal, int iAdd) { CryInterlockedAdd(pVal, iAdd); } -ILINE void AtomicAdd(volatile unsigned int* pVal, int iAdd) { CryInterlockedAdd((volatile int*)pVal, iAdd); } - -ILINE void JobSpinLock(volatile int* pLock, int checkVal, int setVal) { SpinLock(pLock, checkVal, setVal); } -#endif - -ILINE void JobAtomicAdd(volatile int* pVal, int iAdd) { CryInterlockedAdd(pVal, iAdd); } -ILINE void JobAtomicAdd(volatile unsigned int* pVal, int iAdd) { CryInterlockedAdd((volatile int*)pVal, iAdd); } diff --git a/Code/CryEngine/CryCommon/MultiThread_Containers.h b/Code/CryEngine/CryCommon/MultiThread_Containers.h deleted file mode 100644 index cc88fc42ef..0000000000 --- a/Code/CryEngine/CryCommon/MultiThread_Containers.h +++ /dev/null @@ -1,423 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_MULTITHREAD_CONTAINERS_H -#define CRYINCLUDE_CRYCOMMON_MULTITHREAD_CONTAINERS_H -#pragma once - -#include "StlUtils.h" -#include "BitFiddling.h" - -#include <queue> -#include <set> -#include <algorithm> - - -namespace CryMT -{ - ////////////////////////////////////////////////////////////////////////// - // Thread Safe wrappers on the standard STL containers. - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // Multi-Thread safe queue container, can be used instead of std::vector. - ////////////////////////////////////////////////////////////////////////// - template <class T, class Alloc = std::allocator<T> > - class queue - { - public: - typedef T value_type; - typedef std::vector<T, Alloc> container_type; - typedef CryAutoCriticalSection AutoLock; - - ////////////////////////////////////////////////////////////////////////// - // std::queue interface - ////////////////////////////////////////////////////////////////////////// - const T& front() const { AutoLock lock(m_cs); return v.front(); }; - const T& back() const { AutoLock lock(m_cs); return v.back(); } - void push(const T& x) { AutoLock lock(m_cs); return v.push_back(x); }; - void reserve(const size_t n) { AutoLock lock(m_cs); v.reserve(n); }; - // classic pop function of queue should not be used for thread safety, use try_pop instead - //void pop() { AutoLock lock(m_cs); return v.erase(v.begin()); }; - - CryCriticalSection& get_lock() const { return m_cs; } - - bool empty() const { AutoLock lock(m_cs); return v.empty(); } - int size() const { AutoLock lock(m_cs); return v.size(); } - void clear() { AutoLock lock(m_cs); v.clear(); } - void free_memory() { AutoLock lock(m_cs); stl::free_container(v); } - - template <class Func> - void sort(const Func& compare_less) { AutoLock lock(m_cs); std::sort(v.begin(), v.end(), compare_less); } - - ////////////////////////////////////////////////////////////////////////// - bool try_pop(T& returnValue) - { - AutoLock lock(m_cs); - if (!v.empty()) - { - returnValue = v.front(); - v.erase(v.begin()); - return true; - } - return false; - }; - - ////////////////////////////////////////////////////////////////////////// - bool try_remove(const T& value) - { - AutoLock lock(m_cs); - if (!v.empty()) - { - typename container_type::iterator it = std::find(v.begin(), v.end(), value); - if (it != v.end()) - { - v.erase(it); - return true; - } - } - return false; - }; - - template<typename Sizer> - void GetMemoryUsage(Sizer* pSizer) const - { - pSizer->AddObject(v); - } - private: - container_type v; - mutable CryCriticalSection m_cs; - }; - - ////////////////////////////////////////////////////////////////////////// - // Multi-Thread safe vector container, can be used instead of std::vector. - ////////////////////////////////////////////////////////////////////////// - template <class T> - class vector - { - public: - typedef T value_type; - typedef CryAutoCriticalSection AutoLock; - - CryCriticalSection& get_lock() const { return m_cs; } - - void free_memory() { AutoLock lock(m_cs); stl::free_container(v); } - - ////////////////////////////////////////////////////////////////////////// - // std::vector interface - ////////////////////////////////////////////////////////////////////////// - bool empty() const { AutoLock lock(m_cs); return v.empty(); } - int size() const { AutoLock lock(m_cs); return v.size(); } - void resize(int sz) { AutoLock lock(m_cs); v.resize(sz); } - void reserve(int sz) { AutoLock lock(m_cs); v.reserve(sz); } - size_t capacity() const { AutoLock lock(m_cs); return v.size(); } - void clear() { AutoLock lock(m_cs); v.clear(); } - T& operator[](size_t pos) { AutoLock lock(m_cs); return v[pos]; } - const T& operator[](size_t pos) const { AutoLock lock(m_cs); return v[pos]; } - const T& front() const { AutoLock lock(m_cs); return v.front(); } - const T& back() const { AutoLock lock(m_cs); return v.back(); } - T& back() { AutoLock lock(m_cs); return v.back(); } - - void push_back(const T& x) { AutoLock lock(m_cs); return v.push_back(x); } - void pop_back() { AutoLock lock(m_cs); return v.pop_back(); } - ////////////////////////////////////////////////////////////////////////// - - template <class Func> - void sort(const Func& compare_less) { AutoLock lock(m_cs); std::sort(v.begin(), v.end(), compare_less); } - - template <class Iter> - void append(const Iter& startRange, const Iter& endRange) { AutoLock lock(m_cs); v.insert(v.end(), startRange, endRange); } - - void swap(std::vector<T>& vec) { AutoLock lock(m_cs); v.swap(vec); } - - ////////////////////////////////////////////////////////////////////////// - bool try_pop_front(T& returnValue) - { - AutoLock lock(m_cs); - if (!v.empty()) - { - returnValue = v.front(); - v.erase(v.begin()); - return true; - } - return false; - }; - bool try_pop_back(T& returnValue) - { - AutoLock lock(m_cs); - if (!v.empty()) - { - returnValue = v.back(); - v.pop_back(); - return true; - } - return false; - }; - - ////////////////////////////////////////////////////////////////////////// - template <typename FindFunction, typename KeyType> - bool find_and_copy(FindFunction findFunc, const KeyType& key, T& foundValue) const - { - AutoLock lock(m_cs); - if (!v.empty()) - { - typename std::vector<T>::const_iterator it; - for (it = v.begin(); it != v.end(); ++it) - { - if (findFunc(key, *it)) - { - foundValue = *it; - return true; - } - } - } - return false; - } - - ////////////////////////////////////////////////////////////////////////// - bool try_remove(const T& value) - { - AutoLock lock(m_cs); - if (!v.empty()) - { - typename std::vector<T>::iterator it = std::find(v.begin(), v.end(), value); - if (it != v.end()) - { - v.erase(it); - return true; - } - } - return false; - }; - - ////////////////////////////////////////////////////////////////////////// - template <typename Predicate> - bool try_remove_and_erase_if(Predicate predicateFunction) - { - AutoLock lock(m_cs); - if (!v.empty()) - { - typename std::vector<T>::iterator it = std::remove_if(v.begin(), v.end(), predicateFunction); - if (it != v.end()) - { - v.erase(it, v.end()); - return true; - } - } - return false; - }; - - - ////////////////////////////////////////////////////////////////////////// - bool try_remove_at(size_t idx) - { - AutoLock lock(m_cs); - if (idx < v.size()) - { - v.erase(v.begin() + idx); - return true; - } - return false; - } - - - ////////////////////////////////////////////////////////////////////////// - //Fast remove - just move last elem over deleted element - order is not preserved - bool try_remove_unordered(const T& value) - { - AutoLock lock(m_cs); - if (!v.empty()) - { - typename std::vector<T>::iterator it = std::find(v.begin(), v.end(), value); - if (it != v.end()) - { - if (v.size() > 1) - { - typename std::vector<T>::iterator it_back = v.end() - 1; - - if (it != it_back) - { - *it = *it_back; - } - - v.erase(it_back); - } - else - { - v.erase(it); - } - return true; - } - } - return false; - }; - - vector() {} - - vector(const vector<T>& rOther) - { - AutoLock lock1(m_cs); - AutoLock lock2(rOther.m_cs); - - v = rOther.v; - } - - vector& operator=(const vector<T>& rOther) - { - if (this == &rOther) - { - return *this; - } - - AutoLock lock1(m_cs); - AutoLock lock2(rOther.m_cs); - - v = rOther.v; - - return *this; - } - private: - std::vector<T> v; - mutable CryCriticalSection m_cs; - }; - - - ////////////////////////////////////////////////////////////////////////// - // Multi-Thread safe set container, can be used instead of std::set. - // It has limited functionality, but most of it is there. - ////////////////////////////////////////////////////////////////////////// - template <class T> - class set - { - public: - typedef T value_type; - typedef T Key; - typedef typename std::set<T>::size_type size_type; - typedef CryAutoCriticalSection AutoLock; - - ////////////////////////////////////////////////////////////////////////// - // Methods - ////////////////////////////////////////////////////////////////////////// - void clear() { AutoLock lock(m_cs); s.clear(); } - size_type count(const Key& _Key) const { AutoLock lock(m_cs); return s.count(_Key); } - bool empty() const { AutoLock lock(m_cs); return s.empty(); } - size_type erase(const Key& _Key) { AutoLock lock(m_cs); return s.erase(_Key); } - - bool find(const Key& _Key) { AutoLock lock(m_cs); return (s.find(_Key) != s.end()); } - - bool pop_front(value_type& rFrontElement) - { - AutoLock lock(m_cs); - if (s.empty()) - { - return false; - } - rFrontElement = *s.begin(); - s.erase(s.begin()); - return true; - } - bool pop_front() - { - AutoLock lock(m_cs); - if (s.empty()) - { - return false; - } - s.erase(s.begin()); - return true; - } - - bool front(value_type& rFrontElement) - { - AutoLock lock(m_cs); - if (s.empty()) - { - return false; - } - rFrontElement = *s.begin(); - return true; - } - - bool insert(const value_type& _Val) { AutoLock lock(m_cs); return s.insert(_Val).second; } - size_type max_size() const { AutoLock lock(m_cs); return s.max_size(); } - size_type size() const { AutoLock lock(m_cs); return s.size(); } - void swap(set& _Right) { AutoLock lock(m_cs); s.swap(_Right); } - - CryCriticalSection& get_lock() { return m_cs; } - - private: - std::set<value_type> s; - mutable CryCriticalSection m_cs; - }; - - - /////////////////////////////////////////////////////////////////////////////// - // - // Multi-thread safe lock-less FIFO queue container for passing pointers between threads. - // The queue only stores pointers to T, it does not copy the contents of T. - // - ////////////////////////////////////////////////////////////////////////// - template <class T, class Alloc = std::allocator<T> > - class CLocklessPointerQueue - { - public: - explicit CLocklessPointerQueue(size_t reserve = 32) { m_lockFreeQueue.reserve(reserve); }; - ~CLocklessPointerQueue() {}; - - // Check's if queue is empty. - bool empty() const; - - // Pushes item to the queue, only pointer is stored, T contents are not copied. - void push(T* ptr); - // pop can return NULL, always check for it before use. - T* pop(); - - private: - queue<T*, typename std::allocator_traits<Alloc>::template rebind_alloc<T*>> m_lockFreeQueue; - }; - - ////////////////////////////////////////////////////////////////////////// - template <class T, class Alloc> - inline bool CLocklessPointerQueue<T, Alloc>::empty() const - { - return m_lockFreeQueue.empty(); - } - - ////////////////////////////////////////////////////////////////////////// - template <class T, class Alloc> - inline void CLocklessPointerQueue<T, Alloc>::push(T* ptr) - { - m_lockFreeQueue.push(ptr); - } - - ////////////////////////////////////////////////////////////////////////// - template <class T, class Alloc> - inline T* CLocklessPointerQueue<T, Alloc>::pop() - { - T* val = NULL; - m_lockFreeQueue.try_pop(val); - return val; - } -}; // namespace CryMT - -namespace stl -{ - template <typename T> - void free_container(CryMT::vector<T>& v) - { - v.free_memory(); - } - template <typename T> - void free_container(CryMT::queue<T>& v) - { - v.free_memory(); - } -} - - -#endif // CRYINCLUDE_CRYCOMMON_MULTITHREAD_CONTAINERS_H diff --git a/Code/CryEngine/CryCommon/NullAudioSystem.h b/Code/CryEngine/CryCommon/NullAudioSystem.h deleted file mode 100644 index b5a893aa50..0000000000 --- a/Code/CryEngine/CryCommon/NullAudioSystem.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include <IAudioSystem.h> - -namespace Audio -{ - /////////////////////////////////////////////////////////////////////////////////////////////////// - class NullAudioProxy - : public IAudioProxy - { - public: - NullAudioProxy() {} - ~NullAudioProxy() override {} - - void Initialize(const char* const, const bool = true) override {} - void Release() override {} - void Reset() override {} - void ExecuteSourceTrigger([[maybe_unused]] TAudioControlID nTriggerID, [[maybe_unused]] const SAudioSourceInfo& rSourceInfo, [[maybe_unused]] const SAudioCallBackInfos & rCallbackInfos = SAudioCallBackInfos::GetEmptyObject()) override {} - void ExecuteTrigger(const TAudioControlID, [[maybe_unused]] const SAudioCallBackInfos& rCallbackInfos = SAudioCallBackInfos::GetEmptyObject()) override {} - void StopAllTriggers() override {} - void StopTrigger(const TAudioControlID) override {} - void SetSwitchState(const TAudioControlID, const TAudioSwitchStateID) override {} - void SetRtpcValue(const TAudioControlID, const float) override {} - void SetObstructionCalcType(const EAudioObjectObstructionCalcType) override {} - void SetPosition(const SATLWorldPosition&) override {} - void SetPosition(const AZ::Vector3&) override {} - void SetMultiplePositions([[maybe_unused]] const MultiPositionParams& positions) override {} - void SetEnvironmentAmount(const TAudioEnvironmentID, const float) override {} - void SetCurrentEnvironments() override {} - void ResetRtpcValues() override {} - TAudioObjectID GetAudioObjectID() const override { return INVALID_AUDIO_OBJECT_ID; } - }; - - /////////////////////////////////////////////////////////////////////////////////////////////////// - class NullAudioSystem - : public IAudioSystem - { - public: - AZ_CLASS_ALLOCATOR(Audio::NullAudioSystem, AZ::SystemAllocator, 0) - - NullAudioSystem() - { - AudioSystemRequestBus::Handler::BusConnect(); - AudioSystemThreadSafeRequestBus::Handler::BusConnect(); - AZ_TracePrintf(AZ::Debug::Trace::GetDefaultSystemWindow(), "<Audio>: Running with Null Audio System!\n"); - } - ~NullAudioSystem() override - { - AudioSystemRequestBus::Handler::BusDisconnect(); - AudioSystemThreadSafeRequestBus::Handler::BusDisconnect(); - } - - bool Initialize() override { return true; } - void Release() override {} - void ExternalUpdate() override {} - - void PushRequest(const SAudioRequest&) override {} - void PushRequestBlocking(const SAudioRequest&) override {} - void PushRequestThreadSafe(const SAudioRequest&) override {} - void AddRequestListener(AudioRequestCallbackType, void* const, const EAudioRequestType, const TATLEnumFlagsType) override {} - void RemoveRequestListener(AudioRequestCallbackType, void* const) override {} - - TAudioControlID GetAudioTriggerID(const char* const) const override { return INVALID_AUDIO_CONTROL_ID; } - TAudioControlID GetAudioRtpcID(const char* const) const override { return INVALID_AUDIO_CONTROL_ID; } - TAudioControlID GetAudioSwitchID(const char* const) const override { return INVALID_AUDIO_CONTROL_ID; } - TAudioSwitchStateID GetAudioSwitchStateID(const TAudioControlID, const char* const) const override { return INVALID_AUDIO_SWITCH_STATE_ID; } - TAudioPreloadRequestID GetAudioPreloadRequestID(const char* const) const override { return INVALID_AUDIO_PRELOAD_REQUEST_ID; } - TAudioEnvironmentID GetAudioEnvironmentID(const char* const) const override { return INVALID_AUDIO_ENVIRONMENT_ID; } - - bool ReserveAudioListenerID(TAudioObjectID& rAudioObjectID) override { rAudioObjectID = INVALID_AUDIO_OBJECT_ID; return true; } - bool ReleaseAudioListenerID(const TAudioObjectID) override { return true; } - bool SetAudioListenerOverrideID(const TAudioObjectID) override { return true; } - - void GetInfo(SAudioSystemInfo&) override {} - const char* GetControlsPath() const override { return ""; } - void UpdateControlsPath() override {} - void RefreshAudioSystem(const char* const) override {} - - IAudioProxy* GetFreeAudioProxy() override { return static_cast<IAudioProxy*>(&m_nullAudioProxy); } - void FreeAudioProxy(IAudioProxy* const) override {} - - TAudioSourceId CreateAudioSource([[maybe_unused]] const SAudioInputConfig& sourceConfig) override { return INVALID_AUDIO_SOURCE_ID; } - void DestroyAudioSource([[maybe_unused]] TAudioSourceId sourceId) override {} - - const char* GetAudioControlName([[maybe_unused]] const EAudioControlType controlType, [[maybe_unused]] const TATLIDType atlID) const override { return nullptr; } - const char* GetAudioSwitchStateName([[maybe_unused]] const TAudioControlID switchID, [[maybe_unused]] const TAudioSwitchStateID stateID) const override { return nullptr; } - - private: - NullAudioProxy m_nullAudioProxy; - }; - -} // namespace Audio diff --git a/Code/CryEngine/CryCommon/Options.h b/Code/CryEngine/CryCommon/Options.h deleted file mode 100644 index 6cec7b61f6..0000000000 --- a/Code/CryEngine/CryCommon/Options.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Facilities for defining and combining general-purpose or specific options, for functions or structs. - - -#ifndef CRYINCLUDE_CRYCOMMON_OPTIONS_H -#define CRYINCLUDE_CRYCOMMON_OPTIONS_H -#pragma once - - -// Facilities for collecting options in a struct, and quickly constructing them. -// Used, for example, as construction argument. Safer and more informative than bool arguments. -// -// Example: -// struct FObjectOpts; -// struct CObject { CObject(FObjectOpts = ZERO); }; -// CObject object_def(); -// CObject object( FObjectOpts().Size(8).AllowGrowth(true) ); - -template<class TOpt, class T, class TContainer, int NInit = 0> -struct TOptVar -{ - typedef T TValue; - - TOptVar() - : _val(T(NInit)) - { - offset(this); - } - TOptVar(T val) - : _val(val) {} - - operator T () const - { - return _val; - } - T operator ()() const - { return _val; } - T operator +() const - { return _val; } - bool operator !() const - { return !_val; } - - TContainer& operator()(T val) - { - _val = val; - return *(TContainer*)((char*)this - offset()); - } - -private: - T _val; - - static size_t offset(void* self = 0) - { - static size_t _offset = TContainer::static_offset(self); - return _offset; - } -}; - -#define OPT_STRUCT(TOpts) \ - typedef TOpts TThis; typedef uint TInt; \ - static size_t static_offset(void* var) { static void* _first = var; return (char*)var - (char*)_first; } \ - TOpts([[maybe_unused]] void* p = 0) {} \ - TOpts operator()() const { return TOpts(*this); } \ - -#define OPT_VAR(Type, Var) \ - enum E##Var {}; TOptVar<E##Var, Type, TThis> Var; \ - -#define OPT_VAR_INIT(Type, Var, init) \ - enum E##Var {}; TOptVar<E##Var, Type, TThis, init> Var; \ - -#define BIT_STRUCT(Struc, Int) \ - typedef Struc TThis; typedef Int TInt; \ - TInt Mask() const { return *(const TInt*)this; } \ - TInt& Mask() { return *(TInt*)this; } \ - Struc(TInt init = 0) { COMPILE_TIME_ASSERT(sizeof(TThis) == sizeof(TInt)); Mask() = init; } \ - -#define BIT_VAR(Var) \ - TInt _##Var : 1; \ - bool Var() const { return _##Var; } \ - TThis& Var(bool val) { _##Var = val; return *this; } \ - -#endif // CRYINCLUDE_CRYCOMMON_OPTIONS_H diff --git a/Code/CryEngine/CryCommon/PoolAllocator.h b/Code/CryEngine/CryCommon/PoolAllocator.h deleted file mode 100644 index 391e09cd31..0000000000 --- a/Code/CryEngine/CryCommon/PoolAllocator.h +++ /dev/null @@ -1,506 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_POOLALLOCATOR_H -#define CRYINCLUDE_CRYCOMMON_POOLALLOCATOR_H -#pragma once - - -//--------------------------------------------------------------------------- -// Memory allocation class. Allocates, frees, and reuses fixed-size blocks of -// memory, a scheme sometimes known as Simple Segregated Memory. -// -// Allocation is amortized constant time. The normal case is very fast - -// basically just a couple of dereferences. If many blocks are allocated, -// the system may occasionally need to allocate a further bucket of blocks -// for itself. Deallocation is strictly fast constant time. -// -// Each PoolAllocator allocates blocks of a single size and alignment, specified -// by template arguments. There is no per-block space overhead, except for -// alignment. The free list mechanism uses the memory of the block itself -// when it is deallocated. -// -// In this implementation memory claimed by the system is never deallocated, -// until the entire allocator is deallocated. This is to ensure fast -// allocation/deallocation - reference counting the bucket quickly would -// require a pointer to the bucket be stored, whereas now no memory is used -// while the block is allocated. -// -// The class can optionally support multi-threading, using the second -// template parameter. By default it is multithread-safe. -// See Synchronization.h. -// -// The class is implemented using a HeapAllocator. -//--------------------------------------------------------------------------- - -#include "HeapAllocator.h" - -namespace stl -{ - ////////////////////////////////////////////////////////////////////////// - // Fixed-size pool allocator, using a shared heap. - template <typename THeap> - class SharedSizePoolAllocator - { - template <typename T> - friend struct PoolCommonAllocator; - protected: - - using_type(THeap, Lock); - - struct ObjectNode - { - ObjectNode* pNext; - }; - - static size_t AllocSize(size_t nSize) - { - return max<size_t>(nSize, sizeof(ObjectNode)); - } - static size_t AllocAlign(size_t nSize, size_t nAlign) - { - return nAlign > 0 ? nAlign : min<size_t>(nSize, alignof(void*)); - } - - public: - - SharedSizePoolAllocator(THeap& heap, size_t nSize, size_t nAlign = 0) - : _pHeap(&heap) - , _nAllocSize(AllocSize(nSize)) - , _nAllocAlign(AllocAlign(nSize, nAlign)) - , _pFreeList(0) - { - } - - ~SharedSizePoolAllocator() - { - // All allocated objects should be freed by now. - Lock lock(*_pHeap); - Validate(lock); - for (ObjectNode* pFree = _pFreeList; pFree; ) - { - ObjectNode* pNext = pFree->pNext; - _pHeap->Deallocate(lock, pFree, _nAllocSize); - pFree = pNext; - } - } - - // Raw allocation. - void* Allocate() - { - Lock lock(*_pHeap); - if (_pFreeList) - { - ObjectNode* pFree = _pFreeList; - _pFreeList = _pFreeList->pNext; - Validate(lock); - _Counts.nUsed++; - return pFree; - } - - // No free pointer, allocate a new one. - void* pNewMemory = _pHeap->Allocate(lock, _nAllocSize, _nAllocAlign); - if (pNewMemory) - { - _Counts.nUsed++; - _Counts.nAlloc++; - Validate(lock); - } - return pNewMemory; - } - - void Deallocate(void* pObject) - { - Deallocate(Lock(*_pHeap), pObject); - } - - SMemoryUsage GetCounts() const - { - Lock lock(*_pHeap); - return _Counts; - } - SMemoryUsage GetTotalMemory(const Lock&) const - { - return SMemoryUsage(_Counts.nAlloc * _nAllocSize, _Counts.nUsed * _nAllocSize); - } - - protected: - - void Deallocate(const Lock& lock, void* pObject) - { - if (pObject) - { - assert(_pHeap->CheckPtr(lock, pObject)); - - ObjectNode* pNode = static_cast<ObjectNode*>(pObject); - - // Add the object to the front of the free list. - pNode->pNext = _pFreeList; - _pFreeList = pNode; - _Counts.nUsed--; - Validate(lock); - } - } - - void Validate(const Lock& lock) const - { - _pHeap->Validate(lock); - _Counts.Validate(); - assert(_Counts.nAlloc * _nAllocSize <= _pHeap->GetTotalMemory(lock).nUsed); - } - - void Reset(const Lock&, [[maybe_unused]] bool bForce = false) - { - assert(bForce || _Counts.nUsed == 0); - _Counts.Clear(); - _pFreeList = 0; - } - - protected: - const size_t _nAllocSize, _nAllocAlign; - SMemoryUsage _Counts; - - THeap* _pHeap; - ObjectNode* _pFreeList; - }; - - ////////////////////////////////////////////////////////////////////////// - struct SPoolMemoryUsage - : SMemoryUsage - { - size_t nPool; - - SPoolMemoryUsage(size_t _nAlloc = 0, size_t _nPool = 0, size_t _nUsed = 0) - : SMemoryUsage(_nAlloc, _nUsed) - , nPool(_nPool) - { - // These values are pulled from 3 atomic variables and not guaranteed to be a perfect "snapshot" - // Of the current state of the pool memory usage (e.g. Used may be > max, etc) - // Patch the values so that they make sense (it won't be wrong, just mildly out of date) - // This is done to prevent sticking expensive mutexes or potentially forever blocking semaphores in the pool - if (nUsed > nPool) - { - nPool = nUsed; - } - - assert(nPool <= nAlloc); - } - - size_t nPoolFree() const - { - return nPool - nUsed; - } - size_t nNonPoolFree() const - { - return nAlloc - nPool; - } - - void Clear() - { - nAlloc = nUsed = nPool = 0; - } - - void operator += (SPoolMemoryUsage const& op) - { - nAlloc += op.nAlloc; - nPool += op.nPool; - nUsed += op.nUsed; - } - }; - - ////////////////////////////////////////////////////////////////////////// - // SizePoolAllocator with owned heap - template <typename THeap> - class SizePoolAllocator - : protected THeap - , public SharedSizePoolAllocator<THeap> - { - typedef SharedSizePoolAllocator<THeap> TPool; - - using_type(THeap, Lock); - using_type(THeap, FreeMemLock); - using TPool::AllocSize; - using TPool::_Counts; - using TPool::_nAllocSize; - - public: - - SizePoolAllocator(size_t nSize, size_t nAlign = 0, FHeap opts = 0) - : THeap(opts.PageSize(opts.PageSize * AllocSize(nSize))) - , TPool(*this, nSize, nAlign) - { - } - - using TPool::Allocate; - using THeap::GetMemoryUsage; - - void Deallocate(void* pObject) - { - FreeMemLock lock(*this); - TPool::Deallocate(lock, pObject); - if (THeap::FreeWhenEmpty && _Counts.nUsed == 0) - { - TPool::Reset(lock); - THeap::Clear(lock); - } - } - - void FreeMemoryIfEmpty() - { - FreeMemLock lock(*this); - if (_Counts.nUsed == 0) - { - TPool::Reset(lock); - THeap::Clear(lock); - } - } - - void ResetMemory() - { - FreeMemLock lock(*this); - TPool::Reset(lock); - THeap::Reset(lock); - } - - void FreeMemory() - { - FreeMemLock lock(*this); - TPool::Reset(lock); - THeap::Clear(lock); - } - - - void FreeMemoryForce() - { - FreeMemLock lock(*this); - TPool::Reset(lock, true); - THeap::Clear(lock); - } - - SPoolMemoryUsage GetTotalMemory() - { - Lock lock(*this); - return SPoolMemoryUsage(THeap::GetTotalMemory(lock).nAlloc, _Counts.nAlloc * _nAllocSize, _Counts.nUsed * _nAllocSize); - } - }; - - ////////////////////////////////////////////////////////////////////////// - // Templated size version of SizePoolAllocator - template <int S, typename L = PSyncMultiThread, int A = 0> - class PoolAllocator - : public SizePoolAllocator< HeapAllocator<L> > - { - public: - PoolAllocator(FHeap opts = 0) - : SizePoolAllocator< HeapAllocator<L> >(S, A, opts) - { - } - }; - - ////////////////////////////////////////////////////////////////////////// - template <int S, int A = 0> - class PoolAllocatorNoMT - : public SizePoolAllocator< HeapAllocator<PSyncNone> > - { - public: - PoolAllocatorNoMT(FHeap opts = 0) - : SizePoolAllocator< HeapAllocator<PSyncNone> >(S, A, opts) - { - } - }; - - ////////////////////////////////////////////////////////////////////////// - template<typename T, typename L = PSyncMultiThread, size_t A = 0> - class TPoolAllocator - : public SizePoolAllocator< HeapAllocator<L> > - { - typedef SizePoolAllocator< HeapAllocator<L> > TSizePool; - - public: - - using TSizePool::Allocate; - using TSizePool::Deallocate; - - TPoolAllocator(FHeap opts = 0) - : TSizePool(sizeof(T), max<size_t>(alignof(T), A), opts) - {} - - T* New() - { - return new(Allocate())T(); - } - - template<class I> - T* New(const I& init) - { - return new(Allocate())T(init); - } - - void Delete(T* ptr) - { - if (ptr) - { - ptr->~T(); - Deallocate(ptr); - } - } - }; - - // Legacy verbose typedefs. - typedef PSyncNone PoolAllocatorSynchronizationSinglethreaded; - typedef PSyncMultiThread PoolAllocatorSynchronizationMultithreaded; - - ////////////////////////////////////////////////////////////////////////// - // Allocator maintaining multiple type-specific pools, sharing a common heap source. - template<typename THeap> - struct PoolCommonAllocator - : protected THeap - { - typedef SharedSizePoolAllocator<THeap> TPool; - - using_type(THeap, Lock); - using_type(THeap, FreeMemLock); - - struct TPoolNode - : SharedSizePoolAllocator<THeap> - { - TPoolNode* pNext; - - TPoolNode(THeap& heap, TPoolNode*& pList, size_t nSize, size_t nAlign) - : SharedSizePoolAllocator<THeap>(heap, nSize, nAlign) - { - pNext = pList; - pList = this; - } - }; - - public: - - PoolCommonAllocator() - : _pPoolList(0) - { - } - ~PoolCommonAllocator() - { - TPoolNode* pPool = _pPoolList; - while (pPool) - { - TPoolNode* pNextPool = pPool->pNext; - delete pPool; - pPool = pNextPool; - } - } - - TPool* CreatePool(size_t nSize, size_t nAlign = 0) - { - return new TPoolNode(*this, _pPoolList, nSize, nAlign); - } - - SPoolMemoryUsage GetTotalMemory() - { - Lock lock(*this); - SMemoryUsage mem; - for (TPoolNode* pPool = _pPoolList; pPool; pPool = pPool->pNext) - { - mem += pPool->GetTotalMemory(lock); - } - return SPoolMemoryUsage(THeap::GetTotalMemory(lock).nAlloc, mem.nAlloc, mem.nUsed); - } - - bool FreeMemory(bool bDeallocate = true) - { - FreeMemLock lock(*this); - for (TPoolNode* pPool = _pPoolList; pPool; pPool = pPool->pNext) - { - if (pPool->GetTotalMemory(lock).nUsed) - { - return false; - } - } - - for (TPoolNode* pPool = _pPoolList; pPool; pPool = pPool->pNext) - { - pPool->Reset(lock); - } - - if (bDeallocate) - { - THeap::Clear(lock); - } - else - { - THeap::Reset(lock); - } - return true; - } - - protected: - TPoolNode* _pPoolList; - }; - - ////////////////////////////////////////////////////////////////////////// - // The additional TInstancer type provides a way of instantiating multiple instances - // of this class, without static variables. - template<typename THeap, typename TInstancer = int> - struct StaticPoolCommonAllocator - { - ILINE static PoolCommonAllocator<THeap>& StaticAllocator() - { - static PoolCommonAllocator<THeap> s_Allocator; - return s_Allocator; - } - - typedef SharedSizePoolAllocator<THeap> TPool; - - template<class T> - ILINE static TPool& TypeAllocator() - { - static TPool* sp_Pool = CreatePoolOnGlobalHeap(sizeof(T), alignof(T)); - return *sp_Pool; - } - - template<class T> - ILINE static void* Allocate(T*& p) - { return p = (T*)TypeAllocator<T>().Allocate(); } - - template<class T> - ILINE static void Deallocate(T* p) - { return TypeAllocator<T>().Deallocate(p); } - - template<class T> - static T* New() - { return new(TypeAllocator<T>().Allocate())T(); } - - template<class T, class I> - static T* New(const I& init) - { return new(TypeAllocator<T>().Allocate())T(init); } - - template<class T> - static void Delete(T* ptr) - { - if (ptr) - { - ptr->~T(); - TypeAllocator<T>().Deallocate(ptr); - } - } - - static SPoolMemoryUsage GetTotalMemory() - { return StaticAllocator().GetTotalMemory(); } - - private: - - ILINE static TPool* CreatePoolOnGlobalHeap(size_t nSize, size_t nAlign = 0) - { - return StaticAllocator().CreatePool(nSize, nAlign); - } - }; -}; - - -#endif // CRYINCLUDE_CRYCOMMON_POOLALLOCATOR_H diff --git a/Code/CryEngine/CryCommon/ProjectDefines.h b/Code/CryEngine/CryCommon/ProjectDefines.h deleted file mode 100644 index 097191c039..0000000000 --- a/Code/CryEngine/CryCommon/ProjectDefines.h +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : to get some defines available in every CryEngine project - - -#pragma once - - -#include "BaseTypes.h" -#include <AzCore/PlatformDef.h> - -#if defined(_RELEASE) && !defined(RELEASE) - #define RELEASE -#endif - -// Section dictionary -#if defined(AZ_RESTRICTED_PLATFORM) -#define PROJECTDEFINES_H_SECTION_STATS_AGENT 1 -#define PROJECTDEFINES_H_SECTION_TRAITS 2 -#define PROJECTDEFINES_H_SECTION_VTX_IDX 3 -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PROJECTDEFINES_H_SECTION_STATS_AGENT - #include AZ_RESTRICTED_FILE(ProjectDefines_h) -#elif defined(WIN32) || defined(WIN64) -#if !defined(_RELEASE) || defined(PERFORMANCE_BUILD) -#define ENABLE_STATS_AGENT -#endif -#endif - -// The following definitions are used by Sandbox and RC to determine which platform support is needed -#define TOOLS_SUPPORT_POWERVR -#define TOOLS_SUPPORT_ETC2COMP - -// Type used for vertex indices -// WARNING: If you change this typedef, you need to update AssetProcessorPlatformConfig.ini to convert cgf and abc files to the proper index format. -#if defined(RESOURCE_COMPILER) -typedef uint32 vtx_idx; -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(MOBILE) -typedef uint16 vtx_idx; -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PROJECTDEFINES_H_SECTION_VTX_IDX - #include AZ_RESTRICTED_FILE(ProjectDefines_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -// Uncomment one of the two following typedefs: -typedef uint32 vtx_idx; -//typedef uint16 vtx_idx; -#endif - - -// see http://wiki/bin/view/CryEngine/TerrainTexCompression for more details on this -// 0=off, 1=on -#define TERRAIN_USE_CIE_COLORSPACE 0 - -// When non-zero, const cvar accesses (by name) are logged in release-mode on consoles. -// This can be used to find non-optimal usage scenario's, where the constant should be used directly instead. -// Since read accesses tend to be used in flow-control logic, constants allow for better optimization by the compiler. -#define LOG_CONST_CVAR_ACCESS 0 - -#if defined(WIN32) || defined(WIN64) || LOG_CONST_CVAR_ACCESS -#define RELEASE_LOGGING -#endif - -#if defined(_RELEASE) && !defined(RELEASE_LOGGING) -#define EXCLUDE_NORMAL_LOG -#endif - -// Add the "REMOTE_ASSET_PROCESSOR" define except in release -// this makes it so that asset processor functions. Without this, all assets must be present and on local media -// with this, the asset processor can be used to remotely process assets. -#if !defined(_RELEASE) -# define REMOTE_ASSET_PROCESSOR -#endif - -#if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD)) - #define USE_HTTP_WEBSOCKETS 0 -#endif - - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PROJECTDEFINES_H_SECTION_TRAITS - #include AZ_RESTRICTED_FILE(ProjectDefines_h) -#else -#define PROJECTDEFINES_H_TRAIT_DISABLE_MONOLITHIC_PROFILING_MARKERS 1 -#if !defined(LINUX) && !defined(APPLE) -#define PROJECTDEFINES_H_TRAIT_ENABLE_SOFTCODE_SYSTEM 1 -#endif -#if defined(WIN32) || defined(WIN64) || defined(LINUX) || defined(APPLE) -#define PROJECTDEFINES_H_TRAIT_USE_GPU_PARTICLES 1 -#endif -#define PROJECTDEFINES_H_TRAIT_USE_MESH_TESSELLATION 1 -#if defined(WIN32) -#define PROJECTDEFINES_H_TRAIT_USE_SVO_GI 1 -#endif -#if defined(APPLE) || defined(LINUX) -#define AZ_LEGACY_CRYCOMMON_TRAIT_USE_PTHREADS 1 -#define AZ_LEGACY_CRYCOMMON_TRAIT_USE_UNIX_PATHS 1 -#endif -#endif - -#define USE_GLOBAL_BUCKET_ALLOCATOR - -#ifdef IS_PROSDK -# define USING_TAGES_SECURITY // Wrapper for TGVM security -# if defined(LINUX) || defined(APPLE) -# error LINUX and Mac does not support evaluation version -# endif -#endif - -#ifdef USING_TAGES_SECURITY -# define TAGES_EXPORT __declspec(dllexport) -#else -# define TAGES_EXPORT -#endif // USING_TAGES_SECURITY -// test ------------------------------------- - -#define _DATAPROBE - - - -//This feature allows automatic crash submission to JIRA, but does not work outside of CryTek -//Note: This #define will be commented out during code export -#define ENABLE_CRASH_HANDLER - -#if !defined(PHYSICS_STACK_SIZE) -# define PHYSICS_STACK_SIZE (128U << 10) -#endif - -#if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD)) && !defined(RESOURCE_COMPILER) -#ifndef ENABLE_PROFILING_CODE - #define ENABLE_PROFILING_CODE -#endif -#if !(defined(SANDBOX_EXPORTS) || defined(PLUGIN_EXPORTS) || (defined(AZ_MONOLITHIC_BUILD) && PROJECTDEFINES_H_TRAIT_DISABLE_MONOLITHIC_PROFILING_MARKERS)) - #define ENABLE_PROFILING_MARKERS -#endif - -//lightweight profilers, disable for submissions, disables displayinfo inside 3dengine as well -#ifndef ENABLE_LW_PROFILERS - #define ENABLE_LW_PROFILERS -#endif -#endif - -#if defined(ENABLE_PROFILING_CODE) -#define ENABLE_ART_RT_TIME_ESTIMATE -#endif - -#if defined(ENABLE_PROFILING_CODE) && !defined(_RELEASE) - #define FMOD_STREAMING_DEBUGGING 1 -#endif - -#if defined(WIN32) || defined(WIN64) || defined(APPLE) || defined(AZ_PLATFORM_LINUX) -#define FLARES_SUPPORT_EDITING -#endif - -// Reflect texture slot information - only used in the editor -#if defined(WIN32) || defined(WIN64) || defined(AZ_PLATFORM_MAC) -#define SHADER_REFLECT_TEXTURE_SLOTS 1 -#else -#define SHADER_REFLECT_TEXTURE_SLOTS 0 -#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 - -#if (!defined(_RELEASE) || defined(PERFORMANCE_BUILD)) && !PROFILE_PERFORMANCE_NET_COMPATIBLE -#define USE_LAGOMETER (1) -#else -#define USE_LAGOMETER (0) -#endif - -// enable this in order to support old style material names in old data ("engine/material.mtl" or "mygame/material.mtl" as opposed to just "material.mtl") -// previously, material names could have the game folder in it, but this is not necessary anymore and would not work with things like gems -// note that if you use any older projects such as GameSDK this should remain enabled -#define SUPPORT_LEGACY_MATERIAL_NAMES - -// Enable additional structures and code for sprite motion blur. Currently non-functional and disabled -// #define PARTICLE_MOTION_BLUR - -// a special ticker thread to run during load and unload of levels -#define USE_NETWORK_STALL_TICKER_THREAD - -#if !defined(MOBILE) -//--------------------------------------------------------------------- -// Enable Tessellation Features -// (displacement mapping, subdivision, water tessellation) -//--------------------------------------------------------------------- -// Modules : 3DEngine, Renderer -// Depends on: DX11 - -// Global tessellation feature flag - #define TESSELLATION - #ifdef TESSELLATION -// Specific features flags - #define WATER_TESSELLATION - #define PARTICLES_TESSELLATION - - #if PROJECTDEFINES_H_TRAIT_USE_MESH_TESSELLATION -// Mesh tessellation (displacement, smoothing, subd) - #define MESH_TESSELLATION -// Mesh tessellation also in motion blur passes - #define MOTIONBLUR_TESSELLATION - #endif - -// Dependencies - #ifdef MESH_TESSELLATION - #define MESH_TESSELLATION_ENGINE - #endif - #ifndef NULL_RENDERER - #ifdef WATER_TESSELLATION - #define WATER_TESSELLATION_RENDERER - #endif - #ifdef PARTICLES_TESSELLATION - #define PARTICLES_TESSELLATION_RENDERER - #endif - #ifdef MESH_TESSELLATION_ENGINE - #define MESH_TESSELLATION_RENDERER - #endif - - #if defined(WATER_TESSELLATION_RENDERER) || defined(PARTICLES_TESSELLATION_RENDERER) || defined(MESH_TESSELLATION_RENDERER) -// Common tessellation flag enabling tessellation stages in renderer - #define TESSELLATION_RENDERER - #endif - #endif // !NULL_RENDERER - #endif // TESSELLATION -#endif // !defined(MOBILE) - -//------------------------------------------------------ -// SVO GI -//------------------------------------------------------ -// Modules : Renderer, Engine -// Platform : DX11 -#if !defined(RENDERNODES_LEAN_AND_MEAN) - #if PROJECTDEFINES_H_TRAIT_USE_SVO_GI - #define FEATURE_SVO_GI - #endif -#endif - -#if defined(ENABLE_PROFILING_CODE) -# define USE_DISK_PROFILER -# define ENABLE_LOADING_PROFILER // requires AZ_PROFILE_TELEMETRY to also be defined -#endif - -#if PROJECTDEFINES_H_TRAIT_USE_GPU_PARTICLES && !defined(NULL_RENDERER) - #define GPU_PARTICLES 1 -#else - #define GPU_PARTICLES 0 -#endif - -// The maximum number of joints in an animation -#define MAX_JOINT_AMOUNT 1024 diff --git a/Code/CryEngine/CryCommon/Random.h b/Code/CryEngine/CryCommon/Random.h deleted file mode 100644 index 4f958bff10..0000000000 --- a/Code/CryEngine/CryCommon/Random.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_RANDOM_H -#define CRYINCLUDE_CRYCOMMON_RANDOM_H -#pragma once - -#include "BaseTypes.h" -#include "LCGRandom.h" - -namespace CryRandom_Internal -{ - // Private access point to the global random number generator. - extern CRndGen g_random_generator; -} - - -// Seed the global random number generator. -inline void cry_random_seed(const uint32 nSeed) -{ - CryRandom_Internal::g_random_generator.Seed(nSeed); -} - -inline uint32 cry_random_uint32() -{ - return CryRandom_Internal::g_random_generator.GenerateUint32(); -} - -inline float cry_frand() -{ - return CryRandom_Internal::g_random_generator.GenerateFloat(); -} - -// Ranged function returns random value within the *inclusive* range -// between minValue and maxValue. -// Any orderings work correctly: minValue <= maxValue and -// minValue >= minValue. -template <class T> -inline T cry_random(const T minValue, const T maxValue) -{ - return CryRandom_Internal::g_random_generator.GetRandom(minValue, maxValue); -} - -// Vector (Vec2, Vec3, Vec4) ranged function returns vector with -// every component within the *inclusive* ranges between minValue.component -// and maxValue.component. -// All orderings work correctly: minValue.component <= maxValue.component and -// minValue.component >= maxValue.component. -template <class T> -inline T cry_random_componentwise(const T& minValue, const T& maxValue) -{ - return CryRandom_Internal::g_random_generator.GetRandomComponentwise(minValue, maxValue); -} - -// The function returns a random unit vector (Vec2, Vec3, Vec4). -template <class T> -inline T cry_random_unit_vector() -{ - return CryRandom_Internal::g_random_generator.GetRandomUnitVector<T>(); -} - -// eof -#endif // CRYINCLUDE_CRYCOMMON_RANDOM_H diff --git a/Code/CryEngine/CryCommon/Range.h b/Code/CryEngine/CryCommon/Range.h deleted file mode 100644 index 1240f8123c..0000000000 --- a/Code/CryEngine/CryCommon/Range.h +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Time TRange class. - - -#ifndef CRYINCLUDE_CRYCOMMON_RANGE_H -#define CRYINCLUDE_CRYCOMMON_RANGE_H - -#pragma once - -#include <AzCore/RTTI/TypeInfo.h> - -#ifndef MIN -#define MIN(a, b) ((a) < (b) ? (a) : (b)) -#endif - -#ifndef MAX -#define MAX(a, b) ((a) > (b) ? (a) : (b)) -#endif - -/*! - Class TRange, can represent anything that is range between two values, mostly used for time ranges. - */ -template <class T> -class TRange -{ -public: - T start; - T end; - - TRange() { start = T(0); end = T(0); }; - TRange(const TRange& r) { start = r.start; end = r.end; }; - TRange(T s, T e) { start = s; end = e; }; - - void Set(T s, T e) { start = s; end = e; }; - void Clear() { start = 0; end = 0; }; - - //! Get length of range. - T Length() const { return end - start; }; - //! Check if range is empty. - bool IsEmpty() const { return (start == 0 && end == 0); } - - //! Check if value is inside range. - bool IsInside(T val) { return val >= start && val <= end; }; - - void ClipValue(T& val) const - { - if (val < start) - { - val = start; - } - if (val > end) - { - val = end; - } - } - - //! Compare two ranges. - bool operator == (const TRange& r) const - { - return start == r.start && end == r.end; - } - - bool operator != (const TRange& r) const - { - return !(*this == r); - } - //! Assign operator. - TRange& operator =(const TRange& r) - { - start = r.start; - end = r.end; - return *this; - } - //! Interect two ranges. - TRange operator & (const TRange& r) const - { - return TRange(MAX(start, r.start), MIN(end, r.end)); - } - TRange& operator &= (const TRange& r) - { - return (*this = (*this & r)); - } - //! Concatent two ranges. - TRange operator | (const TRange& r) const - { - return TRange(MIN(start, r.start), MAX(end, r.end)); - } - TRange& operator |= (const TRange& r) - { - return (*this = (*this | r)); - } - //! Add new value to range. - TRange operator + (T v) const - { - T s = start, e = end; - if (v < start) - { - s = v; - } - if (v > end) - { - e = v; - } - return TRange(s, e); - } - //! Add new value to range. - TRange& operator += (T v) const - { - if (v < start) - { - start = v; - } - if (v > end) - { - end = v; - } - return *this; - } -}; - -//! CRange if just TRange for floats.. -typedef TRange<float> Range; - -namespace AZ -{ - AZ_TYPE_INFO_SPECIALIZE(Range, "{515CF4CF-4992-4139-BDE5-42A887432B45}"); -} - -#endif // CRYINCLUDE_CRYCOMMON_RANGE_H diff --git a/Code/CryEngine/CryCommon/RenderBus.h b/Code/CryEngine/CryCommon/RenderBus.h deleted file mode 100644 index 2cb12fdec9..0000000000 --- a/Code/CryEngine/CryCommon/RenderBus.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include <AzCore/EBus/EBus.h> - -namespace AZ -{ - /** - * This bus serves as a way for non-rendering systems to react to events - * that occur inside the renderer. For now these events will probably be implemented by - * things like CSystem and CryAction. In the future the idea is that these can be implemented - * by a user's GameComponent. - */ - class RenderNotifications - : public AZ::EBusTraits - { - public: - virtual ~RenderNotifications() = default; - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - ////////////////////////////////////////////////////////////////////////// - - /** - * This event gets posted at the beginning of CD3D9Renderer's FreeResources method, before the resources have been freed. - */ - virtual void OnRendererFreeResources([[maybe_unused]] int flags) {}; - }; - - using RenderNotificationsBus = AZ::EBus<RenderNotifications>; - - /** - * This bus is used for renderer notifications that occur directly from the render thread - * while scene rendering is occurring. (In contrast, the RenderNotificationsBus above runs on the - * main thread while the renderer is preparing the scene.) - */ - class RenderThreadEvents - : public AZ::EBusTraits - { - public: - virtual ~RenderThreadEvents() = default; - - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - ////////////////////////////////////////////////////////////////////////// - - /* - * This hook enables per-frame render work at the beginning of the frame. - * - * This event is triggered when RT_RenderScene is called at the beginning of a frame. - * The event will only be triggered on the render thread, if multithreaded rendering - * is enabled. And, it will only be triggered on a non-recursive scene render. - */ - virtual void OnRenderThreadRenderSceneBegin() {} - }; - - using RenderThreadEventsBus = AZ::EBus<RenderThreadEvents>; - - /** - * This bus is used for firing screenshot request to any rendering system. - * The rendering system should implement its own screenshot function. - */ - class RenderScreenshotRequests - : public AZ::EBusTraits - { - public: - static const EBusHandlerPolicy HandlerPolicy = EBusHandlerPolicy::Single; ///< EBusTraits overrides - static const EBusAddressPolicy AddressPolicy = EBusAddressPolicy::Single; ///< EBusTraits overrides - - /** Take a screenshot and save it to a file. - @param filepath the path where a the screenshot is saved. - */ - virtual void WriteScreenshotToFile(const char* filepath) = 0; - - /** Take a screenshot and preserve it within a buffer - */ - virtual void WriteScreenshotToBuffer() = 0; - - /** Fill a provided buffer with the render buffer - @param imageBuffer The provided buffer to be filled - */ - virtual bool CopyScreenshotToBuffer(unsigned char* imageBuffer, unsigned int width, unsigned int height) = 0; - - }; - - using RenderScreenshotRequestBus = AZ::EBus<RenderScreenshotRequests>; - - class RenderScreenshotNotifications - : public AZ::EBusTraits - { - public: - virtual ~RenderScreenshotNotifications() = default; - - static const EBusAddressPolicy AddressPolicy = EBusAddressPolicy::Single; ///< EBusTraits overrides - - /** Notify waiting components that the requested screenshot is ready - */ - virtual void OnScreenshotReady() = 0; - }; - - using RenderScreenshotNotificationBus = AZ::EBus<RenderScreenshotNotifications>; -} diff --git a/Code/CryEngine/CryCommon/SFunctor.h b/Code/CryEngine/CryCommon/SFunctor.h deleted file mode 100644 index 05f08c8290..0000000000 --- a/Code/CryEngine/CryCommon/SFunctor.h +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : User header for multi DLL functors. - - -#ifndef CRYINCLUDE_CRYCOMMON_SFUNCTOR_H -#define CRYINCLUDE_CRYCOMMON_SFUNCTOR_H -#pragma once - - -#include "FunctorBaseFunction.h" -#include "FunctorBaseMember.h" - -// Needed for CryFont to compile. -// Maybe for others too. -#include "smartptr.h" - - -struct SFunctor -{ -public: - // Calls the functor method. - // returns true, if a functor is registered, false otherwise. - bool Call() - { - if (!m_pFunctor) - { - return false; - } - - m_pFunctor->Call(); - - return true; - } - - // Sets a new functor, common function, void return type, no arguments. - // Parameters: the function pointer. - template<typename tCallback> - void Set(tCallback pCallback) - { - typedef TFunctor<tCallback> TType; - m_pFunctor = new TType(pCallback); - } - - // Sets a new functor, common function, void return type, 1 argument. - // Parameters: the function pointer, the argument to be passed to the function. - template<typename tCallback, typename tArgument1> - void Set(tCallback pCallback, const tArgument1& Argument1) - { - typedef TFunctor<tCallback> TType; - m_pFunctor = new TType(pCallback, Argument1); - } - - // Sets a new functor, common function, void return type, 2 arguments. - // Parameters: the function pointer, the 2 arguments to be passed to the function. - template<typename tCallback, typename tArgument1, typename tArgument2> - void Set(tCallback pCallback, const tArgument1& Argument1, const tArgument2& Argument2) - { - typedef TFunctor<tCallback> TType; - m_pFunctor = new TType(pCallback, Argument1, Argument2); - } - - // Sets a new functor, common function, void return type, no arguments. - // Parameters: the function pointer, the 2 arguments to be passed to the function. - template<typename tCallee> - void Set(tCallee* pCallee, void (tCallee::* pCallback)()) - { - typedef TFunctor<void (tCallee::*)()> TType; - m_pFunctor = new TType(pCallee, pCallback); - } - - // Sets a new functor, common function, void return type, 1 argument. - // Parameters: the function pointer, the 2 arguments to be passed to the function, the argument. - template<typename tCallee, typename tArgument1> - void Set(tCallee* pCallee, void (tCallee::* pCallback)(tArgument1), const tArgument1& Argument1) - { - typedef TFunctor<void (tCallee::*)(tArgument1)> TType; - m_pFunctor = new TType(pCallee, pCallback, Argument1); - } - - // Sets a new functor, common function, void return type, 2 arguments. - // Parameters: the function pointer, the 2 arguments to be passed to the function, the 2 arguments. - template<typename tCallee, typename tArgument1, typename tArgument2> - void Set(tCallee* pCallee, void (tCallee::* pCallback)(tArgument1, tArgument2), const tArgument1& Argument1, const tArgument2& Argument2) - { - typedef TFunctor<void (tCallee::*)(tArgument1, tArgument2)> TType; - m_pFunctor = new TType(pCallee, pCallback, Argument1, Argument2); - } - - // Used to compare equality between 2 IFunctors. - bool operator==(const SFunctor& rOther) - { - return m_pFunctor == rOther.m_pFunctor; - } - - // Used order to IFunctors (needed for some containers, like map). - bool operator<(const SFunctor& rOther) - { - return m_pFunctor < rOther.m_pFunctor; - } -protected: - _smart_ptr<IFunctorBase> m_pFunctor; -}; - -#endif // CRYINCLUDE_CRYCOMMON_SFUNCTOR_H diff --git a/Code/CryEngine/CryCommon/ScopedVariableSetter.h b/Code/CryEngine/CryCommon/ScopedVariableSetter.h deleted file mode 100644 index 5b2c36b7b9..0000000000 --- a/Code/CryEngine/CryCommon/ScopedVariableSetter.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_SCOPEDVARIABLESETTER_H -#define CRYINCLUDE_CRYCOMMON_SCOPEDVARIABLESETTER_H -#pragma once - - -// The idea of this class is to set the value of a variable in its constructor, -// and then in the destructor to reset it to its initial value. -template <typename T> -class CScopedVariableSetter -{ -public: - typedef T Value; - - CScopedVariableSetter(Value& variable, const Value& temporaryValue) - : m_oldValue(variable) - , m_variable(variable) - { - m_variable = temporaryValue; - } - - ~CScopedVariableSetter() - { - m_variable = m_oldValue; - } - -private: - Value m_oldValue; - Value& m_variable; -}; - -#endif // CRYINCLUDE_CRYCOMMON_SCOPEDVARIABLESETTER_H diff --git a/Code/CryEngine/CryCommon/SerializationTypes.h b/Code/CryEngine/CryCommon/SerializationTypes.h deleted file mode 100644 index 55b0144815..0000000000 --- a/Code/CryEngine/CryCommon/SerializationTypes.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -// this file is included anywhere that we need a complete list of primitive serializable types - -SERIALIZATION_TYPE(bool) -SERIALIZATION_TYPE(float) -SERIALIZATION_TYPE(double) -SERIALIZATION_TYPE(Vec2) -SERIALIZATION_TYPE(Vec3) -SERIALIZATION_TYPE(Quat) -SERIALIZATION_TYPE(Ang3) -SERIALIZATION_TYPE(int8) -SERIALIZATION_TYPE(int16) -SERIALIZATION_TYPE(int32) -SERIALIZATION_TYPE(int64) -SERIALIZATION_TYPE(uint8) -SERIALIZATION_TYPE(uint16) -SERIALIZATION_TYPE(uint32) -SERIALIZATION_TYPE(uint64) -SERIALIZATION_TYPE(CTimeValue) -SERIALIZATION_TYPE(SNetObjectID) -SERIALIZATION_TYPE(XmlNodeRef) // not for network - only for save games diff --git a/Code/CryEngine/CryCommon/SerializeFwd.h b/Code/CryEngine/CryCommon/SerializeFwd.h deleted file mode 100644 index a7e06ec8b8..0000000000 --- a/Code/CryEngine/CryCommon/SerializeFwd.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : forward declaration of TSerialize - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZEFWD_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZEFWD_H -#pragma once - - - -template <class T> -class CSerializeWrapper; -struct ISerialize; -typedef CSerializeWrapper<ISerialize> TSerialize; - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZEFWD_H diff --git a/Code/CryEngine/CryCommon/SimpleSerialize.h b/Code/CryEngine/CryCommon/SimpleSerialize.h deleted file mode 100644 index 01e5e3d9b4..0000000000 --- a/Code/CryEngine/CryCommon/SimpleSerialize.h +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_SIMPLESERIALIZE_H -#define CRYINCLUDE_CRYCOMMON_SIMPLESERIALIZE_H -#pragma once - - -#include <ISerialize.h> // <> required for Interfuscator -#include "TimeValue.h" - -template <bool READING> -class CSimpleSerializeImpl_Reading; - -template <> -class CSimpleSerializeImpl_Reading<true> -{ -public: - CSimpleSerializeImpl_Reading() - : m_bCommit(true) {} - ILINE bool IsReading() const - { - return true; - } - ILINE bool ShouldCommitValues() const - { - return m_bCommit; - } - ILINE void Update(ISerializeUpdateFunction* pFunc) - { - if (m_bCommit) - { - pFunc->Execute(); - } - } -protected: - bool m_bCommit; -}; - -template <> -class CSimpleSerializeImpl_Reading<false> -{ -public: - ILINE bool IsReading() const - { - return false; - } - ILINE bool ShouldCommitValues() const - { - return true; - } - ILINE void Update(ISerializeUpdateFunction*) - { - } -}; - -template <bool READING, ESerializationTarget TARGET> -class CSimpleSerializeImpl - : public CSimpleSerializeImpl_Reading<READING> -{ -public: - CSimpleSerializeImpl() - : m_failed(false) {} - ILINE void BeginGroup(const char* szName) - { - } - ILINE void EndGroup() - { - } - ILINE ESerializationTarget GetSerializationTarget() const - { - return TARGET; - } - ILINE void FlagPartialRead() {} - - ILINE bool Ok() const - { - return !m_failed; - } - -protected: - ILINE void Failed() - { - m_failed = true; - } - -private: - bool m_failed; -}; - -template <class Impl> -class CSimpleSerialize - : public ISerialize -{ -public: - ILINE CSimpleSerialize(Impl& impl) - : m_impl(impl) - { - } - - void Update(ISerializeUpdateFunction* pFunc) - { - m_impl.Update(pFunc); - } - - void BeginGroup(const char* szName) - { - m_impl.BeginGroup(szName); - } - - bool BeginOptionalGroup(const char* szName, bool condition) - { - return m_impl.BeginOptionalGroup(szName, condition); - } - - void EndGroup() - { - m_impl.EndGroup(); - } - - bool IsReading() const - { - return m_impl.IsReading(); - } - - bool ShouldCommitValues() const - { - return m_impl.ShouldCommitValues(); - } - - ESerializationTarget GetSerializationTarget() const - { - return m_impl.GetSerializationTarget(); - } - - void WriteStringValue(const char* name, SSerializeString& value, uint32 policy) - { - m_impl.Value(name, value, policy); - } - void ReadStringValue(const char* name, SSerializeString& curValue, uint32 policy) - { - m_impl.Value(name, curValue, policy); - } - - bool Ok() const - { - return m_impl.Ok(); - } - - void FlagPartialRead() - { - m_impl.FlagPartialRead(); - } - -#define SERIALIZATION_TYPE(T) \ - virtual void Value(const char* name, T & x, uint32 policy) { m_impl.Value(name, x, policy); } -#include "SerializationTypes.h" -#undef SERIALIZATION_TYPE - -#define SERIALIZATION_TYPE(T) \ - virtual void ValueWithDefault([[maybe_unused]] const char* name, [[maybe_unused]] T & x, [[maybe_unused]] const T&defaultValue) { assert(0); } -#include "SerializationTypes.h" - SERIALIZATION_TYPE(SSerializeString) -#undef SERIALIZATION_TYPE - - Impl * GetInnerImpl() { - return &m_impl; - } - -protected: - Impl& m_impl; -}; - -////////////////////////////////////////////////////////////////////////// -// Support serialization with default values, -// Require Implementation serialization stub to have Value() method returning boolean. -////////////////////////////////////////////////////////////////////////// -template <class Impl> -class CSimpleSerializeWithDefaults - : public CSimpleSerialize<Impl> -{ -public: - ILINE CSimpleSerializeWithDefaults(Impl& impl) - : CSimpleSerialize<Impl>(impl) {} - -#define SERIALIZATION_TYPE(T) \ - virtual void ValueWithDefault(const char* name, T & x, const T&defaultValue) { \ - if (CSimpleSerialize<Impl>::m_impl.IsReading()) { \ - if (!CSimpleSerialize<Impl>::m_impl.Value(name, x, 0)) { \ - x = defaultValue; } \ - } \ - else if (x != defaultValue) { \ - CSimpleSerialize<Impl>::m_impl.Value(name, x, 0); } \ - } -#include "SerializationTypes.h" - SERIALIZATION_TYPE(SSerializeString) -#undef SERIALIZATION_TYPE -}; - -#endif // CRYINCLUDE_CRYCOMMON_SIMPLESERIALIZE_H diff --git a/Code/CryEngine/CryCommon/StatObjBus.h b/Code/CryEngine/CryCommon/StatObjBus.h deleted file mode 100644 index cefdc4b7c7..0000000000 --- a/Code/CryEngine/CryCommon/StatObjBus.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#ifndef CRYINCLUDE_CRYCOMMON_STATOBJBUS_H -#define CRYINCLUDE_CRYCOMMON_STATOBJBUS_H - -#include <AzCore/EBus/EBus.h> -#include <AzCore/std/containers/unordered_set.h> - -struct IStatObj; - -////////////////////////////////////////////////////////////////////////// -// -// Ebus support for handling unique IDs between IStatInstGroup instances. -// -////////////////////////////////////////////////////////////////////////// -using StatInstGroupId = int; - -class StatInstGroupEvents - : public AZ::EBusTraits -{ -public: - const static StatInstGroupId s_InvalidStatInstGroupId = -1; - - virtual ~StatInstGroupEvents() = default; - - // AZ::EBusTraits - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - using MutexType = AZStd::recursive_mutex; - - virtual StatInstGroupId GenerateStatInstGroupId() = 0; - virtual void ReleaseStatInstGroupId(StatInstGroupId statInstGroupId) = 0; - virtual void ReleaseStatInstGroupIdSet(const AZStd::unordered_set<StatInstGroupId>& statInstGroupIdSet) = 0; - virtual void ReserveStatInstGroupIdRange(StatInstGroupId from, StatInstGroupId to) = 0; -}; - -using StatInstGroupEventBus = AZ::EBus<StatInstGroupEvents>; - -////////////////////////////////////////////////////////////////////////// -// -// EBUS support for triggering necessary updates when IStatObj instances -// caches should be updated when 3D Engine events happen during level loads, -// shutting down the application, and so forth -// -////////////////////////////////////////////////////////////////////////// -class InstanceStatObjEvents - : public AZ::EBusTraits -{ -public: - virtual ~InstanceStatObjEvents() = default; - - // AZ::EBusTraits - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - using MutexType = AZStd::recursive_mutex; - - virtual void ReleaseData() - { - } -}; - -using InstanceStatObjEventBus = AZ::EBus<InstanceStatObjEvents>; - -#endif // CRYINCLUDE_CRYCOMMON_STATOBJBUS_H -#pragma once diff --git a/Code/CryEngine/CryCommon/StaticInstance.h b/Code/CryEngine/CryCommon/StaticInstance.h deleted file mode 100644 index 5303c3fd73..0000000000 --- a/Code/CryEngine/CryCommon/StaticInstance.h +++ /dev/null @@ -1,683 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -template <class T> -class StaticInstanceSpecialization -{ -}; - -// Specializations for std::vector and std::map which allows us to modify the -// least amount of legacy code by mirroring the std APIs that are in use -// These are not intended to be complete, just enough to shim existing legacy code -template <typename U, class A> -class StaticInstanceSpecialization<std::vector<U, A>> -{ -public: - using Container = std::vector<U, A>; - using reference = typename Container::reference; - using const_reference = typename Container::const_reference; - using iterator = typename Container::iterator; - using const_iterator = typename Container::const_iterator; - using pointer = typename Container::pointer; - using const_pointer = typename Container::const_pointer; - using size_type = typename Container::size_type; - - template <class Integral> - AZ_FORCE_INLINE - typename AZStd::enable_if<AZStd::is_integral<Integral>::value, reference>::type - operator[](Integral index) - { - return get()[size_type(index)]; - } - - template <class Integral> - AZ_FORCE_INLINE - typename AZStd::enable_if<AZStd::is_integral<Integral>::value, const_reference>::type - operator[](Integral index) const - { - return get()[size_type(index)]; - } - - AZ_FORCE_INLINE iterator begin() - { - return get().begin(); - } - - AZ_FORCE_INLINE const_iterator begin() const - { - return get().begin(); - } - - AZ_FORCE_INLINE iterator end() - { - return get().end(); - } - - AZ_FORCE_INLINE const_iterator end() const - { - return get().end(); - } - - AZ_FORCE_INLINE iterator erase(iterator it) - { - return get().erase(it); - } - - AZ_FORCE_INLINE iterator erase(iterator first, iterator last) - { - return get().erase(first, last); - } - - AZ_FORCE_INLINE void resize(size_t size) - { - get().resize(size); - } - - AZ_FORCE_INLINE void reserve(size_t size) - { - get().reserve(size); - } - - AZ_FORCE_INLINE void clear() - { - get().clear(); - } - - AZ_FORCE_INLINE size_type size() - { - return get().size(); - } - - AZ_FORCE_INLINE void push_back(U&& val) - { - get().push_back(val); - } - - AZ_FORCE_INLINE void push_back(const U& val) - { - get().push_back(val); - } - - AZ_FORCE_INLINE bool empty() const - { - return get().empty(); - } - - AZ_FORCE_INLINE iterator insert(U&& val) - { - return get().insert(val); - } - - AZ_FORCE_INLINE iterator insert(iterator it, U&& val) - { - return get().insert(it, val); - } - - AZ_FORCE_INLINE reference front() - { - return get().front(); - } - - AZ_FORCE_INLINE const_reference front() const - { - return get().front(); - } - - AZ_FORCE_INLINE reference back() - { - return get().back(); - } - - AZ_FORCE_INLINE const_reference back() const - { - return get().back(); - } - - AZ_FORCE_INLINE void pop_back() - { - get().pop_back(); - } - - AZ_FORCE_INLINE pointer data() - { - return get().data(); - } - - AZ_FORCE_INLINE const_pointer data() const - { - return get().data(); - } - - void swap(Container& other) - { - get().swap(other); - } - -private: - Container& get() const; -}; - - -template <typename U, class A> -class StaticInstanceSpecialization<std::list<U, A>> -{ -public: - using Container = std::list<U, A>; - using reference = typename Container::reference; - using const_reference = typename Container::const_reference; - using iterator = typename Container::iterator; - using const_iterator = typename Container::const_iterator; - using pointer = typename Container::pointer; - using const_pointer = typename Container::const_pointer; - using size_type = typename Container::size_type; - - AZ_FORCE_INLINE iterator begin() - { - return get().begin(); - } - - AZ_FORCE_INLINE const_iterator begin() const - { - return get().begin(); - } - - AZ_FORCE_INLINE iterator end() - { - return get().end(); - } - - AZ_FORCE_INLINE const_iterator end() const - { - return get().end(); - } - - AZ_FORCE_INLINE iterator erase(iterator it) - { - return get().erase(it); - } - - AZ_FORCE_INLINE iterator erase(iterator first, iterator last) - { - return get().erase(first, last); - } - - AZ_FORCE_INLINE void resize(size_t size) - { - get().resize(size); - } - - AZ_FORCE_INLINE void reserve(size_t size) - { - get().reserve(size); - } - - AZ_FORCE_INLINE void clear() - { - get().clear(); - } - - AZ_FORCE_INLINE size_type size() - { - return get().size(); - } - - AZ_FORCE_INLINE void push_back(U&& val) - { - get().push_back(val); - } - - AZ_FORCE_INLINE void push_back(const U& val) - { - get().push_back(val); - } - - AZ_FORCE_INLINE void push_front(U&& val) - { - get().push_front(val); - } - - AZ_FORCE_INLINE void push_front(const U& val) - { - get().push_front(val); - } - - AZ_FORCE_INLINE bool empty() const - { - return get().empty(); - } - - AZ_FORCE_INLINE iterator insert(U&& val) - { - return get().insert(val); - } - - AZ_FORCE_INLINE iterator insert(iterator it, U&& val) - { - return get().insert(it, val); - } - - AZ_FORCE_INLINE reference front() - { - return get().front(); - } - - AZ_FORCE_INLINE const_reference front() const - { - return get().front(); - } - - AZ_FORCE_INLINE reference back() - { - return get().back(); - } - - AZ_FORCE_INLINE const_reference back() const - { - return get().back(); - } - - AZ_FORCE_INLINE void pop_back() - { - get().pop_back(); - } - - AZ_FORCE_INLINE pointer data() - { - return get().data(); - } - - AZ_FORCE_INLINE const_pointer data() const - { - return get().data(); - } - - void swap(Container& other) - { - get().swap(other); - } - -private: - Container& get() const; -}; - -template <class K, class V, class Less, class Allocator> -class StaticInstanceSpecialization<std::map<K, V, Less, Allocator>> -{ -public: - using Container = std::map<K, V, Less, Allocator>; - using reference = typename Container::reference; - using const_reference = typename Container::const_reference; - using iterator = typename Container::iterator; - using const_iterator = typename Container::const_iterator; - using key_type = typename Container::key_type; - using mapped_type = typename Container::mapped_type; - using value_type = typename Container::value_type; - using size_type = typename Container::size_type; - - using pair_iter_bool = std::pair<iterator, bool>; - - - AZ_FORCE_INLINE iterator begin() - { - return get().begin(); - } - - AZ_FORCE_INLINE const_iterator begin() const - { - return get().begin(); - } - - AZ_FORCE_INLINE iterator end() - { - return get().end(); - } - - AZ_FORCE_INLINE const_iterator end() const - { - return get().end(); - } - - AZ_FORCE_INLINE iterator erase(iterator it) - { - return get().erase(it); - } - - AZ_FORCE_INLINE size_t erase(const key_type& key) - { - return get().erase(key); - } - - AZ_FORCE_INLINE mapped_type& operator[](const key_type& key) - { - return get()[key]; - } - - template <class K2> - AZ_FORCE_INLINE - typename AZStd::enable_if<AZStd::is_constructible<key_type, K2>::value, mapped_type&>::type - operator[](const K2& keylike) - { - return get()[key_type(keylike)]; - } - - AZ_FORCE_INLINE iterator find(const key_type& key) - { - return get().find(key); - } - - AZ_FORCE_INLINE const_iterator find(const key_type& key) const - { - return get().find(key); - } - - AZ_FORCE_INLINE void clear() - { - get().clear(); - } - - AZ_FORCE_INLINE bool empty() const - { - return get().empty(); - } - - AZ_FORCE_INLINE iterator insert(iterator hint, const value_type& kv) - { - return get().insert(hint, kv); - } - - AZ_FORCE_INLINE pair_iter_bool insert(const value_type& kv) - { - return get().insert(kv); - } - - AZ_FORCE_INLINE size_type size() const - { - return get().size(); - } - - void swap(Container& cont) - { - get().swap(cont); - } - -private: - Container& get() const; -}; - -template <class K, class V, class Less, class Allocator> -class StaticInstanceSpecialization<std::multimap<K, V, Less, Allocator>> -{ -public: - using Container = std::multimap<K, V, Less, Allocator>; - using reference = typename Container::reference; - using const_reference = typename Container::const_reference; - using iterator = typename Container::iterator; - using const_iterator = typename Container::const_iterator; - using key_type = typename Container::key_type; - using mapped_type = typename Container::mapped_type; - using value_type = typename Container::value_type; - using size_type = typename Container::size_type; - - AZ_FORCE_INLINE iterator begin() - { - return get().begin(); - } - - AZ_FORCE_INLINE const_iterator begin() const - { - return get().begin(); - } - - AZ_FORCE_INLINE iterator end() - { - return get().end(); - } - - AZ_FORCE_INLINE const_iterator end() const - { - return get().end(); - } - - AZ_FORCE_INLINE iterator erase(iterator it) - { - return get().erase(it); - } - - AZ_FORCE_INLINE size_t erase(const key_type& key) - { - return get().erase(key); - } - - AZ_FORCE_INLINE iterator find(const key_type& key) - { - return get().find(key); - } - - AZ_FORCE_INLINE const_iterator find(const key_type& key) const - { - return get().find(key); - } - - AZ_FORCE_INLINE void clear() - { - get().clear(); - } - - AZ_FORCE_INLINE bool empty() const - { - return get().empty(); - } - - AZ_FORCE_INLINE iterator insert(value_type&& kv) - { - return get().insert(kv); - } - - AZ_FORCE_INLINE iterator insert(const value_type& kv) - { - return get().insert(kv); - } - - AZ_FORCE_INLINE size_type size() const - { - return get().size(); - } - -private: - Container& get() const; -}; - -template <class T, class Less, class Allocator> -class StaticInstanceSpecialization<std::set<T, Less, Allocator>> -{ -public: - using Container = std::set<T, Less, Allocator>; - using reference = typename Container::reference; - using const_reference = typename Container::const_reference; - using iterator = typename Container::iterator; - using const_iterator = typename Container::const_iterator; - using value_type = typename Container::value_type; - using size_type = typename Container::size_type; - - using pair_iter_bool = std::pair<iterator, bool>; - - AZ_FORCE_INLINE iterator begin() - { - return get().begin(); - } - - AZ_FORCE_INLINE const_iterator begin() const - { - return get().begin(); - } - - AZ_FORCE_INLINE iterator end() - { - return get().end(); - } - - AZ_FORCE_INLINE const_iterator end() const - { - return get().end(); - } - - AZ_FORCE_INLINE iterator erase(iterator it) - { - return get().erase(it); - } - - AZ_FORCE_INLINE size_t erase(const value_type& key) - { - return get().erase(key); - } - - AZ_FORCE_INLINE iterator find(const value_type& key) - { - return get().find(key); - } - - AZ_FORCE_INLINE const_iterator find(const value_type& key) const - { - return get().find(key); - } - - AZ_FORCE_INLINE void clear() - { - get().clear(); - } - - AZ_FORCE_INLINE bool empty() const - { - return get().empty(); - } - - AZ_FORCE_INLINE pair_iter_bool insert(value_type&& kv) - { - return get().insert(kv); - } - - AZ_FORCE_INLINE pair_iter_bool insert(const value_type& kv) - { - return get().insert(kv); - } - - AZ_FORCE_INLINE size_type size() const - { - return get().size(); - } - -private: - Container& get() const; -}; - -// This is a non-thread safe version of AZStd::static_storage, used purely to lazy -// initialize various Cry DLL statics/singletons. They are created on first access. -template <class T, class Destructor=AZStd::default_destruct<T>> -class StaticInstance - : public StaticInstanceSpecialization<T> -{ -public: - template <class ...Args> - StaticInstance(Args&& ...args) - { - // We need to pass args as a copy to avoid taking references to values that dont support it. - // For example, if an enum value is being passed in args, we would lost the value inside the lambda - m_ctor = [=]() - { - return Create(args...); - }; - } - - ~StaticInstance() - { - if (m_instance) - { - Destructor()(m_instance); - } - } - - AZ_FORCE_INLINE T* operator->() const - { - return Get(); - } - - AZ_FORCE_INLINE operator T*() const - { - return Get(); - } - - AZ_FORCE_INLINE operator T&() const - { - return *Get(); - } - - AZ_FORCE_INLINE T* operator&() const - { - return Get(); - } - - AZ_FORCE_INLINE operator bool() const - { - return m_instance != nullptr; - } - -private: - StaticInstance(const StaticInstance&) = delete; - StaticInstance(StaticInstance&&) = delete; - StaticInstance& operator=(const StaticInstance&) = delete; - - template <class ...Args> - T* Create(Args&& ...args) const - { - return new((void*)&m_storage) T(AZStd::forward<Args>(args)...); - } - - T* Get() const - { - if (!m_instance) - { - m_instance = m_ctor(); - } - return m_instance; - } - - mutable T* m_instance = nullptr; - mutable typename AZStd::aligned_storage<sizeof(T), AZStd::alignment_of<T>::value>::type m_storage; - AZStd::function<T*()> m_ctor; -}; - -template <typename U, class A> -std::vector<U, A>& StaticInstanceSpecialization<std::vector<U, A>>::get() const -{ - return *(*static_cast<const StaticInstance<std::vector<U, A>>*>(this)); -} - -template <typename U, class A> -std::list<U, A>& StaticInstanceSpecialization<std::list<U, A>>::get() const -{ - return *(*static_cast<const StaticInstance<std::list<U, A>>*>(this)); -} - -template <class K, class V, class Less, class Allocator> -std::map<K, V, Less, Allocator>& StaticInstanceSpecialization<std::map<K, V, Less, Allocator>>::get() const -{ - return *(*static_cast<const StaticInstance<std::map<K, V, Less, Allocator>>*>(this)); -} - -template <class K, class V, class Less, class Allocator> -std::multimap<K, V, Less, Allocator>& StaticInstanceSpecialization<std::multimap<K, V, Less, Allocator>>::get() const -{ - return *(*static_cast<const StaticInstance<std::multimap<K, V, Less, Allocator>>*>(this)); -} - -template <class T, class Less, class Allocator> -std::set<T, Less, Allocator>& StaticInstanceSpecialization<std::set<T, Less, Allocator>>::get() const -{ - return *(*static_cast<const StaticInstance<std::set<T, Less, Allocator>>*>(this)); -} diff --git a/Code/CryEngine/CryCommon/StereoRendererBus.h b/Code/CryEngine/CryCommon/StereoRendererBus.h deleted file mode 100644 index d89e347f9f..0000000000 --- a/Code/CryEngine/CryCommon/StereoRendererBus.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include <AzCore/EBus/EBus.h> - -namespace AZ -{ - /// - /// The Stereo Renderer bus allows other systems to query various properties on the stereo renderer - /// - class StereoRendererBus - : public EBusTraits - { - public: - - ////////////////////////////////////////////////////////////////////////// - // EBus Traits - static const EBusHandlerPolicy HandlerPolicy = EBusHandlerPolicy::Multiple; - static const EBusAddressPolicy AddressPolicy = EBusAddressPolicy::Single; - using MutexType = AZStd::recursive_mutex; - ////////////////////////////////////////////////////////////////////////// - - virtual ~StereoRendererBus() {} - - /// - /// Return whether the renderer is rendering to the HMD - /// - /// @return True if rendering to the HMD - /// - virtual bool IsRenderingToHMD() { return false; } - - protected: - }; - - using StereoRendererRequestBus = EBus < StereoRendererBus >; -} diff --git a/Code/CryEngine/CryCommon/StlUtils.h b/Code/CryEngine/CryCommon/StlUtils.h deleted file mode 100644 index 0b8db7c76c..0000000000 --- a/Code/CryEngine/CryCommon/StlUtils.h +++ /dev/null @@ -1,1030 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Various convenience utility functions for STL and alike -// Used in Animation subsystem, and in some tools -#ifndef CRYINCLUDE_CRYCOMMON_STLUTILS_H -#define CRYINCLUDE_CRYCOMMON_STLUTILS_H -#pragma once - -#include <unordered_map> -#include <unordered_set> -#include <AzCore/std/containers/unordered_map.h> -#include <AzCore/std/containers/unordered_set.h> - -#if (defined(LINUX) || defined(APPLE)) - #include "platform.h" -#endif - -#define STATIC_ASSERT(condition, errMessage) static_assert(condition, errMessage) - -#include <map> -#include <set> -#include <algorithm> -#include <deque> -#include <vector> - -#undef std__hash_map -#define std__hash_map AZStd::unordered_map -#define std__unordered_set AZStd::unordered_set -#define std__hash_multimap AZStd::unordered_multimap -#define std__hash AZStd::hash -#define std__unordered_map AZStd::unordered_map - -template <class T, class Destructor> -class StaticInstance; - -// auto-cleaner: upon destruction, calls the clear() method -template <class T> -class CAutoClear -{ -public: - CAutoClear (T* p) - : m_p(p) {} - ~CAutoClear () {m_p->clear(); } -protected: - T* m_p; -}; - - -template <class Container> -unsigned sizeofArray (const Container& arr) -{ - return (unsigned)(sizeof(typename Container::value_type) * arr.size()); -} - -template <class Container> -unsigned sizeofVector (const Container& arr) -{ - return (unsigned)(sizeof(typename Container::value_type) * arr.capacity()); -} - -template <class Container> -unsigned sizeofArray (const Container& arr, unsigned nSize) -{ - return arr.empty() ? 0u : (unsigned)(sizeof(typename Container::value_type) * nSize); -} - -template <class Container> -unsigned capacityofArray (const Container& arr) -{ - return (unsigned)(arr.capacity() * sizeof(arr[0])); -} - -template <class T> -unsigned countElements (const std::vector<T>& arrT, const T& x) -{ - unsigned nSum = 0; - for (typename std::vector<T>::const_iterator iter = arrT.begin(); iter != arrT.end(); ++iter) - { - if (x == *iter) - { - ++nSum; - } - } - return nSum; -} - -// [Timur] -/** Contain extensions for STL library. -*/ -namespace stl -{ - ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Compare member of class/struct. - // - // e.g. Sort Vec3s by x component - // - // std::sort(vec3s.begin(), vec3s.end(), stl::member_compare<Vec3, float, &Vec3::x>()); - // - ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - template <typename OWNER_TYPE, typename MEMBER_TYPE, MEMBER_TYPE OWNER_TYPE::* MEMBER_PTR, typename EQUALITY = std::less<MEMBER_TYPE> > - struct member_compare - { - inline bool operator () (const OWNER_TYPE& lhs, const OWNER_TYPE& rhs) const - { - return EQUALITY()(lhs.*MEMBER_PTR, rhs.*MEMBER_PTR); - } - }; - - ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - // Compare member of class/struct against parameter. - // - // e.g. Find Vec3 with x component less than 1.0 - // - // std::find_if(vec3s.begin(), vec3s.end(), stl::member_compare_param<Vec3, float, &Vec3::x>(1.0f)); - // - ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - template <typename OWNER_TYPE, typename MEMBER_TYPE, MEMBER_TYPE OWNER_TYPE::* MEMBER_PTR, typename EQUALITY = std::less<MEMBER_TYPE> > - struct member_compare_param - { - inline member_compare_param(const MEMBER_TYPE& _value) - : value(_value) - { - } - - inline bool operator () (const OWNER_TYPE& rhs) const - { - return EQUALITY()(rhs.*MEMBER_PTR, value); - } - - const MEMBER_TYPE& value; - }; - - ////////////////////////////////////////////////////////////////////////// - //! Searches the given entry in the map by key, and if there is none, returns the default value - ////////////////////////////////////////////////////////////////////////// - template <typename Map> - inline typename Map::mapped_type find_in_map(const Map& mapKeyToValue, const typename Map::key_type& key, typename Map::mapped_type valueDefault) - { - typename Map::const_iterator it = mapKeyToValue.find (key); - if (it == mapKeyToValue.end()) - { - return valueDefault; - } - else - { - return it->second; - } - } - - ////////////////////////////////////////////////////////////////////////// - //! Inserts and returns a reference to the given value in the map, or returns the current one if it's already there. - ////////////////////////////////////////////////////////////////////////// - template <typename Map> - inline typename Map::mapped_type& map_insert_or_get(Map& mapKeyToValue, const typename Map::key_type& key, const typename Map::mapped_type& defValue = typename Map::mapped_type()) - { - auto&& iresult = mapKeyToValue.insert(typename Map::value_type(key, defValue)); - return iresult.first->second; - } - - // searches the given entry in the map by key, and if there is none, returns the default value - // The values are taken/returned in REFERENCEs rather than values - template <typename Key, typename mapped_type, typename Traits, typename Allocator> - inline mapped_type& find_in_map_ref(std::map<Key, mapped_type, Traits, Allocator>& mapKeyToValue, const Key& key, mapped_type& valueDefault) - { - typedef std::map<Key, mapped_type, Traits, Allocator> Map; - typename Map::iterator it = mapKeyToValue.find (key); - if (it == mapKeyToValue.end()) - { - return valueDefault; - } - else - { - return it->second; - } - } - - template <typename Key, typename mapped_type, typename Traits, typename Allocator> - inline const mapped_type& find_in_map_ref(const std::map<Key, mapped_type, Traits, Allocator>& mapKeyToValue, const Key& key, const mapped_type& valueDefault) - { - typedef std::map<Key, mapped_type, Traits, Allocator> Map; - typename Map::const_iterator it = mapKeyToValue.find (key); - if (it == mapKeyToValue.end()) - { - return valueDefault; - } - else - { - return it->second; - } - } - - ////////////////////////////////////////////////////////////////////////// - //! Fills vector with contents of map. - ////////////////////////////////////////////////////////////////////////// - template <class Map, class Vector> - inline void map_to_vector(const Map& theMap, Vector& array) - { - array.resize(0); - array.reserve(theMap.size()); - for (typename Map::const_iterator it = theMap.begin(); it != theMap.end(); ++it) - { - array.push_back(it->second); - } - } - - ////////////////////////////////////////////////////////////////////////// - //! Fills vector with contents of set. - ////////////////////////////////////////////////////////////////////////// - template <class Set, class Vector> - inline void set_to_vector(const Set& theSet, Vector& array) - { - array.resize(0); - array.reserve(theSet.size()); - for (typename Set::const_iterator it = theSet.begin(); it != theSet.end(); ++it) - { - array.push_back(*it); - } - } - - ////////////////////////////////////////////////////////////////////////// - //! Find and erase element from container. - // @return true if item was find and erased, false if item not found. - ////////////////////////////////////////////////////////////////////////// - template <class Container, class Value> - inline bool find_and_erase(Container& container, const Value& value) - { - typename Container::iterator it = AZStd::find(container.begin(), container.end(), value); - if (it != container.end()) - { - container.erase(it); - return true; - } - return false; - } - - template <typename K, typename P, typename A> - inline bool find_and_erase(std::set<K, P, A>& container, const K& value) - { - return container.erase(value) > 0; - } - - ////////////////////////////////////////////////////////////////////////// - //! Find and erase element from container. - // @return true if item was find and erased, false if item not found. - ////////////////////////////////////////////////////////////////////////// - template <class CONTAINER, class PREDICATE> - inline bool find_and_erase_if(CONTAINER& container, const PREDICATE& predicate) - { - typename CONTAINER::iterator end = container.end(), i = std::find_if(container.begin(), end, predicate); - - if (i != end) - { - container.erase(i); - - return true; - } - - return false; - } - - ////////////////////////////////////////////////////////////////////////// - //! Find and erase all elements matching value from container. - // Assume that this will invalidate any exiting iterators. - // Commonly used for removing NULL pointers from collections. - ////////////////////////////////////////////////////////////////////////// - template <class Container> - inline void find_and_erase_all(Container& container, const typename Container::value_type& value) - { - // Shuffles all elements != value to the front and returns the start of the removed elements. - typename Container::iterator endIter(container.end()); - typename Container::iterator newEndIter(std::remove(container.begin(), endIter, value)); - - // Delete the removed range at the back of the container (low-cost for vector). - container.erase(newEndIter, endIter); - } - - ////////////////////////////////////////////////////////////////////////// - //! Find and erase element from map. - // @return true if item was find and erased, false if item not found. - ////////////////////////////////////////////////////////////////////////// - template <class Container, class Key> - inline bool member_find_and_erase(Container& container, const Key& key) - { - typename Container::iterator it = container.find (key); - if (it != container.end()) - { - container.erase(it); - return true; - } - return false; - } - - - ////////////////////////////////////////////////////////////////////////// - //! Push back to container unique element. - // @return true if item added, false overwise. - template <class Container, class Value> - inline bool push_back_unique(Container& container, const Value& value) - { - if (AZStd::find(container.begin(), container.end(), value) == container.end()) - { - container.push_back(value); - return true; - } - return false; - } - - ////////////////////////////////////////////////////////////////////////// - //! Push back to container unique element. - // @return true if item added, false overwise. - template <class CONTAINER, class PREDICATE, typename VALUE> - inline bool push_back_unique_if(CONTAINER& container, const PREDICATE& predicate, const VALUE& value) - { - typename CONTAINER::iterator end = container.end(); - - if (AZStd::find_if(container.begin(), end, predicate) == end) - { - container.push_back(value); - - return true; - } - else - { - return false; - } - } - - ////////////////////////////////////////////////////////////////////////// - //! Push back to container contents of another container - template <class Container, class Iter> - inline void push_back_range(Container& container, Iter begin, Iter end) - { - for (Iter it = begin; it != end; ++it) - { - container.push_back(*it); - } - } - - ////////////////////////////////////////////////////////////////////////// - //! Push back to container contents of another container, if not already present - template <class Container, class Iter> - inline void push_back_range_unique(Container& container, Iter begin, Iter end) - { - for (Iter it = begin; it != end; ++it) - { - push_back_unique(container, *it); - } - } - - ////////////////////////////////////////////////////////////////////////// - //! Find element in container. - // @return true if item found. - template <class Container, class Value> - inline bool find(Container& container, const Value& value) - { - return std::find(container.begin(), container.end(), value) != container.end(); - } - - ////////////////////////////////////////////////////////////////////////// - //! Find element in a sorted container using binary search with logarithmic efficiency. - // - template <class Iterator, class T> - inline Iterator binary_find(Iterator first, Iterator last, const T& value) - { - Iterator it = std::lower_bound(first, last, value); - return (it == last || value != *it) ? last : it; - } - - ////////////////////////////////////////////////////////////////////////// - //! Find element in a sorted container using binary search with logarithmic efficiency. - // @return true if item was inserted. - template <class Container, class Value> - inline bool binary_insert_unique(Container& container, const Value& value) - { - typename Container::iterator it = std::lower_bound(container.begin(), container.end(), value); - if (it != container.end()) - { - if (*it == value) - { - return false; - } - container.insert(it, value); - } - else - { - container.insert(container.end(), value); - } - return true; - } - ////////////////////////////////////////////////////////////////////////// - //! Find element in a sorted container using binary search with logarithmic efficiency. - // and erases if element found. - // @return true if item was erased. - template <class Container, class Value> - inline bool binary_erase(Container& container, const Value& value) - { - typename Container::iterator it = std::lower_bound(container.begin(), container.end(), value); - if (it != container.end() && *it == value) - { - container.erase(it); - return true; - } - return false; - } - - template <typename ItT, typename Func> - ItT remove_from_heap(ItT begin, ItT end, ItT at, Func order) - { - using std::swap; - - --end; - if (at == end) - { - return at; - } - - size_t idx = std::distance(begin, at); - swap(*end, *at); - - size_t length = std::distance(begin, end); - size_t parent, child; - - if (idx > 0 && order(*(begin + idx / 2), *(begin + idx))) - { - do - { - parent = idx / 2; - swap(*(begin + idx), *(begin + parent)); - idx = parent; - - if (idx == 0 || order(*(begin + idx), *(begin + idx / 2))) - { - return end; - } - } - while (true); - } - else - { - do - { - child = idx * 2 + 1; - if (child >= length) - { - return end; - } - - ItT left = begin + child; - ItT right = begin + child + 1; - - if (right < end && order(*left, *right)) - { - ++child; - } - - if (order(*(begin + child), *(begin + idx))) - { - return end; - } - - swap(*(begin + child), *(begin + idx)); - idx = child; - } - while (true); - } - - return end; - } - - struct container_object_deleter - { - template<typename T> - void operator()(const T* ptr) const - { - delete ptr; - } - }; - - ////////////////////////////////////////////////////////////////////////// - //! Convert arbitary class to const char* - ////////////////////////////////////////////////////////////////////////// - template <class Type> - inline const char* constchar_cast(const Type& type) - { - return type; - } - - //! Specialization of string to const char cast. - template <> - inline const char* constchar_cast(const string& type) - { - return type.c_str(); - } - - ////////////////////////////////////////////////////////////////////////// - //! Case sensetive less key for any type convertable to const char*. - ////////////////////////////////////////////////////////////////////////// - template <class Type> - struct less_strcmp - { - bool operator()(const Type& left, const Type& right) const - { - return strcmp(constchar_cast(left), constchar_cast(right)) < 0; - } - }; - - ////////////////////////////////////////////////////////////////////////// - //! Case insensetive less key for any type convertable to const char*. - template <class Type> - struct less_stricmp - { - bool operator()(const Type& left, const Type& right) const - { - return _stricmp(constchar_cast(left), constchar_cast(right)) < 0; - } - }; - - ////////////////////////////////////////////////////////////////////////// - // Hash map usage: - // typedef AZStd::unordered_map<string,int, stl::hash_string_insensitve<string>, stl::equality_string_insensitive<string> > StringToIntHash; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // useful when the key is already the result of an hash function - // key needs to be convertible to size_t - ////////////////////////////////////////////////////////////////////////// - template <class Key> - class hash_simple - { - public: - enum // parameters for hash table - { - bucket_size = 4, // 0 < bucket_size - min_buckets = 8 - };// min_buckets = 2 ^^ N, 0 < N - - size_t operator()(const Key& key) const - { - return size_t(key); - }; - bool operator()(const Key& key1, const Key& key2) const - { - return key1 < key2; - } - }; - - // simple hash class that has the avalanche property (a change in one bit affects all others) - // ... use this if you have uint32 key values! - class hash_uint32 - { - public: - enum // parameters for hash table - { - bucket_size = 4, // 0 < bucket_size - min_buckets = 8 // min_buckets = 2 ^^ N, 0 < N - }; - - ILINE size_t operator()(uint32 a) const - { - a = (a + 0x7ed55d16) + (a << 12); - a = (a ^ 0xc761c23c) ^ (a >> 19); - a = (a + 0x165667b1) + (a << 5); - a = (a + 0xd3a2646c) ^ (a << 9); - a = (a + 0xfd7046c5) + (a << 3); - a = (a ^ 0xb55a4f09) ^ (a >> 16); - return a; - }; - bool operator()(uint32 key1, uint32 key2) const - { - return key1 < key2; - } - }; - - - ////////////////////////////////////////////////////////////////////////// - //! Case sensitive string hash - ////////////////////////////////////////////////////////////////////////// - template <class Key> - class hash_string - { - public: - enum // parameters for hash table - { - bucket_size = 4, // 0 < bucket_size - min_buckets = 8 - };// min_buckets = 2 ^^ N, 0 < N - - size_t operator()(const Key& key) const - { - unsigned int h = 0; - const char* s = constchar_cast(key); - for (; *s; ++s) - { - h = 5 * h + *(unsigned char*)s; - } - return size_t(h); - }; - }; - - ////////////////////////////////////////////////////////////////////////// - //! Case sensitive string equality - ////////////////////////////////////////////////////////////////////////// - template <class Key> - class equality_string - { - public: - bool operator()(const Key& key1, const Key& key2) const - { - return strcmp(constchar_cast(key1), constchar_cast(key2)) == 0; - } - }; - - ////////////////////////////////////////////////////////////////////////// - //! Case insensitive string hasher - ////////////////////////////////////////////////////////////////////////// - template <class Key> - class hash_string_caseless - { - public: - enum // parameters for hash table - { - bucket_size = 4, // 0 < bucket_size - min_buckets = 8 - };// min_buckets = 2 ^^ N, 0 < N - - size_t operator()(const Key& key) const - { - unsigned int h = 0; - const char* s = constchar_cast(key); - for (; *s; ++s) - { - h = 5 * h + tolower(*(unsigned char*)s); - } - return size_t(h); - }; - }; - - ////////////////////////////////////////////////////////////////////////// - //! Case insensitive string comparer - ////////////////////////////////////////////////////////////////////////// - template <class Key> - class equality_string_caseless - { - public: - bool operator()(const Key& key1, const Key& key2) const - { - return _stricmp(constchar_cast(key1), constchar_cast(key2)) == 0; - } - }; - - - // Support for both Microsoft and SGI kind of hash_map. - -#if defined(_STLP_HASH_MAP) || defined(APPLE) || defined(LINUX) - // STL Port - template <class _Key, class _Predicate = std::less<_Key> > - struct hash_compare - { - enum - { // parameters for hash table - bucket_size = 4, // 0 < bucket_size - min_buckets = 8 // min_buckets = 2 ^^ N, 0 < N - }; - - size_t operator()(const _Key& _Keyval) const - { - // return hash value. - uint32 a = _Keyval; - a = (a + 0x7ed55d16) + (a << 12); - a = (a ^ 0xc761c23c) ^ (a >> 19); - a = (a + 0x165667b1) + (a << 5); - a = (a + 0xd3a2646c) ^ (a << 9); - a = (a + 0xfd7046c5) + (a << 3); - a = (a ^ 0xb55a4f09) ^ (a >> 16); - return a; - } - - // Less then function. - bool operator()(const _Key& _Keyval1, const _Key& _Keyval2) const - { // test if _Keyval1 ordered before _Keyval2 - _Predicate comp; - return (comp(_Keyval1, _Keyval2)); - } - }; - - template <class Key, class HashFunc> - struct stlport_hash_equal - { - // Equal function. - bool operator()(const Key& k1, const Key& k2) const - { - HashFunc less; - // !(k1 < k2) && !(k2 < k1) - return !less(k1, k2) && !less(k2, k1); - } - }; - - template <class Key, class Value, class HashFunc = hash_compare<Key>, class Alloc = std::allocator< std::pair<const Key, Value> > > - struct hash_map - : public std__hash_map<Key, Value, HashFunc, stlport_hash_equal<Key, HashFunc>, Alloc> - { - hash_map() - : std__hash_map<Key, Value, HashFunc, stlport_hash_equal<Key, HashFunc>, Alloc>(HashFunc::min_buckets) {} - }; - - template <class Key, class Value, class HashFunc = hash_compare<Key>, class Alloc = std::allocator< std::pair<const Key, Value> > > - struct hash_multimap - : public std__hash_multimap<Key, Value, HashFunc, stlport_hash_equal<Key, HashFunc>, Alloc> - { - hash_multimap() - : std__hash_multimap<Key, Value, HashFunc, stlport_hash_equal<Key, HashFunc>, Alloc>(HashFunc::min_buckets) {} - }; -#endif - - ////////////////////////////////////////////////////////////////////////// - template<class T> - class intrusive_linked_list_node - { - public: - intrusive_linked_list_node() { link_to_intrusive_list(static_cast<T*>(this)); } - // Not virtual by design - ~intrusive_linked_list_node() { unlink_from_intrusive_list(static_cast<T*>(this)); } - - static T* get_intrusive_list_root() { return m_root_intrusive; }; - - static void link_to_intrusive_list(T* pNode) - { - if (m_root_intrusive) - { - // Add to the beginning of the list. - T* head = m_root_intrusive; - pNode->m_prev_intrusive = 0; - pNode->m_next_intrusive = head; - head->m_prev_intrusive = pNode; - m_root_intrusive = pNode; - } - else - { - m_root_intrusive = pNode; - pNode->m_prev_intrusive = 0; - pNode->m_next_intrusive = 0; - } - } - static void unlink_from_intrusive_list(T* pNode) - { - if (pNode == m_root_intrusive) // if head of list. - { - m_root_intrusive = pNode->m_next_intrusive; - if (m_root_intrusive) - { - m_root_intrusive->m_prev_intrusive = 0; - } - } - else - { - if (pNode->m_prev_intrusive) - { - pNode->m_prev_intrusive->m_next_intrusive = pNode->m_next_intrusive; - } - if (pNode->m_next_intrusive) - { - pNode->m_next_intrusive->m_prev_intrusive = pNode->m_prev_intrusive; - } - } - pNode->m_next_intrusive = 0; - pNode->m_prev_intrusive = 0; - } - - public: - static T* m_root_intrusive; - T* m_next_intrusive; - T* m_prev_intrusive; - }; - - template <class T> - inline void reconstruct(T& t) - { - t.~T(); - new(&t)T; - } - - template <class T, class D> - inline void reconstruct(StaticInstance<T, D>& instance) - { - reconstruct(*instance); - } - - template <typename T, typename A1> - inline void reconstruct(T& t, const A1& a1) - { - t.~T(); - new (&t)T(a1); - } - - template <typename T, typename A1, typename A2> - inline void reconstruct(T& t, const A1& a1, const A2& a2) - { - t.~T(); - new (&t)T(a1, a2); - } - - template <typename T, typename A1, typename A2, typename A3> - inline void reconstruct(T& t, const A1& a1, const A2& a2, const A3& a3) - { - t.~T(); - new (&t)T(a1, a2, a3); - } - - template <typename T, typename A1, typename A2, typename A3, typename A4> - inline void reconstruct(T& t, const A1& a1, const A2& a2, const A3& a3, const A4& a4) - { - t.~T(); - new (&t)T(a1, a2, a3, a4); - } - - template <typename T, typename A1, typename A2, typename A3, typename A4, typename A5> - inline void reconstruct(T& t, const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5) - { - t.~T(); - new (&t)T(a1, a2, a3, a4, a5); - } - - template <class T> - inline void free_container(T& t) - { - reconstruct(t); - } - - template <class T, class A> - inline void free_container(std::deque<T, A>& t) - { - reconstruct(t); - } - - template <class K, class D, class H, class A> - inline void free_container(std__hash_map<K, D, H, A>& t) - { - reconstruct(t); - } - - template <class T, class D> - inline void free_container(StaticInstance<T, D>& instance) - { - reconstruct(*instance); - } - - struct container_freer - { - template <typename T> - void operator () (T& container) const - { - stl::free_container(container); - } - }; - - template <typename T> - struct scoped_set - { - scoped_set(T& ref, T val) - : m_ref(&ref) - , m_oldVal(ref) - { - ref = val; - } - - ~scoped_set() - { - (*m_ref) = m_oldVal; - } - - private: - scoped_set(const scoped_set<T>& other); - scoped_set<T>& operator = (const scoped_set<T>& other); - - private: - T* m_ref; - T m_oldVal; - }; - - template <typename T, size_t Length, typename Func> - inline void for_each_array(T (&buffer)[Length], Func func) - { - std::for_each(&buffer[0], &buffer[Length], func); - } - - template <typename T, typename D, size_t Length, typename Func> - inline void for_each_array(StaticInstance<T, D>(&buffer)[Length], Func func) - { - for (size_t idx = 0; idx < Length; ++idx) - { - func(*buffer[idx]); - } - } - - template <typename T> - inline void destruct(T* p) - { - p->~T(); - } -} - -#define DEFINE_INTRUSIVE_LINKED_LIST(Class) \ - template<> \ - Class * stl::intrusive_linked_list_node<Class>::m_root_intrusive = nullptr; - - -// Performs a less-than compare on a serial sequence space, such that earlier values compare less-than later values. -// Unlike a normal integral value, this accounts for overflowing the limit of the underlying type. -// For example, assuming a 2-bit unsigned underlying type (with possible values 0, 1, 2 and 3), the following will hold: 0 < 1 && 1 < 2 && 2 < 3 && 3 < 0 -// Assuming two equal values V1 and V2, V2 can be incremented up to "(2 ^ (bits - 1) - 1)" times and V1 < V2 will continue to hold. -// See also RFC-1982 that documents this http://tools.ietf.org/html/rfc1982 -template<typename T> -struct SSerialCompare -{ - static_assert(std::is_integral<T>::value && std::is_unsigned<T>::value, "T must be an unsigned integral type"); - - static const T limit = (T(1) << (sizeof(T) * 8 - 1)); - - bool operator()(T lhs, T rhs) - { - return ((lhs < rhs) && (rhs - lhs < limit)) || ((lhs > rhs) && (lhs - rhs > limit)); - } -}; - -template <class Container> -unsigned sizeOfVP(Container& arr) -{ - int i; - unsigned size = 0; - for (i = 0; i < (int)arr.size(); i++) - { - typename Container::value_type& T = arr[i]; - size += T->Size(); - } - size += (arr.capacity() - arr.size()) * sizeof(typename Container::value_type); - return size; -} - -template <class Container> -unsigned sizeOfV(Container& arr) -{ - int i; - unsigned size = 0; - for (i = 0; i < (int)arr.size(); i++) - { - typename Container::value_type& T = arr[i]; - size += T.Size(); - } - size += (arr.capacity() - arr.size()) * sizeof(typename Container::value_type); - return size; -} -template <class Container> -unsigned sizeOfA(Container& arr) -{ - int i; - unsigned size = 0; - for (i = 0; i < arr.size(); i++) - { - typename Container::value_type& T = arr[i]; - size += T.Size(); - } - return size; -} -// define the maplikestruct, used to approximate the memory requirements for a map node -namespace stl -{ - struct MapLikeStruct - { - bool color; - void* parent; - void* left; - void* right; - }; -} -template <class Map> -unsigned sizeOfMap(Map& map) -{ - unsigned size = 0; - for (typename Map::iterator it = map.begin(); it != map.end(); it++) - { - typename Map::mapped_type& T = it->second; - size += T.Size(); - } - size += map.size() * sizeof(stl::MapLikeStruct); - return size; -} -template <class Map> -unsigned sizeOfMapStr(Map& map) -{ - unsigned size = 0; - for (typename Map::iterator it = map.begin(); it != map.end(); it++) - { - typename Map::mapped_type& T = it->second; - size += T.capacity(); - } - size += map.size() * sizeof(stl::MapLikeStruct); - return size; -} -template <class Map> -unsigned sizeOfMapP(Map& map) -{ - unsigned size = 0; - for (typename Map::iterator it = map.begin(); it != map.end(); it++) - { - typename Map::mapped_type& T = it->second; - size += T->Size(); - } - size += map.size() * sizeof(stl::MapLikeStruct); - return size; -} -template <class Map> -unsigned sizeOfMapS(Map& map) -{ - unsigned size = 0; - for (typename Map::iterator it = map.begin(); it != map.end(); it++) - { - typename Map::mapped_type& T = it->second; - size += sizeof(T); - } - size += map.size() * sizeof(stl::MapLikeStruct); - return size; -} - -#endif // CRYINCLUDE_CRYCOMMON_STLUTILS_H diff --git a/Code/CryEngine/CryCommon/StringUtils.h b/Code/CryEngine/CryCommon/StringUtils.h deleted file mode 100644 index 6b34953c22..0000000000 --- a/Code/CryEngine/CryCommon/StringUtils.h +++ /dev/null @@ -1,1357 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef _CRY_ENGINE_STRING_UTILS_HDR_ -#define _CRY_ENGINE_STRING_UTILS_HDR_ - -#pragma once - -#include "CryString.h" -#include <ISystem.h> -#include <algorithm> // std::replace, std::min -#include "UnicodeFunctions.h" -#include "UnicodeIterator.h" -#include <set> - -#if !defined(RESOURCE_COMPILER) -# include "CryCrc32.h" -#endif - -#if defined(LINUX) || defined(APPLE) -# include <ctype.h> -#endif - -namespace CryStringUtils -{ - // Convert a single ASCII character to lower case, this is compatible with the standard "C" locale (ie, only A-Z). - inline char toLowerAscii(char c) - { - return (c >= 'A' && c <= 'Z') ? (c - 'A' + 'a') : c; - } - - // Convert a single ASCII character to upper case, this is compatible with the standard "C" locale (ie, only A-Z). - inline char toUpperAscii(char c) - { - return (c >= 'a' && c <= 'z') ? (c - 'a' + 'A') : c; - } -} - -// cry_strXXX() and CryStringUtils_Internal::strXXX(): -// -// The functions copy 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 functions write the terminating zero -// character to the destination buffer and return. -// -// The functions guarantee writing the terminating zero character to the -// destination buffer (if the buffer can fit at least one character). -// -// The functions return 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). - -namespace CryStringUtils_Internal -{ - template <class TChar> - inline bool strcpy_with_clamp(TChar* const dst, size_t const dst_size_in_bytes, const TChar* const src, size_t const src_size_in_bytes) - { - COMPILE_TIME_ASSERT(sizeof(TChar) == sizeof(char) || sizeof(TChar) == sizeof(wchar_t)); - - if (!dst || dst_size_in_bytes < sizeof(TChar)) - { - return false; - } - - if (!src || src_size_in_bytes < sizeof(TChar)) - { - dst[0] = 0; - return src != 0; // we return true for non-null src without characters - } - - const size_t src_n = src_size_in_bytes / sizeof(TChar); - const size_t n = (std::min)(dst_size_in_bytes / sizeof(TChar) - 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 TChar> - inline bool strcat_with_clamp(TChar* const dst, size_t const dst_size_in_bytes, const TChar* const src, size_t const src_size_in_bytes) - { - COMPILE_TIME_ASSERT(sizeof(TChar) == sizeof(char) || sizeof(TChar) == sizeof(wchar_t)); - - if (!dst || dst_size_in_bytes < sizeof(TChar)) - { - return false; - } - - const size_t dst_n = dst_size_in_bytes / sizeof(TChar) - 1; - - size_t dst_len = 0; - while (dst_len < dst_n && dst[dst_len]) - { - ++dst_len; - } - - if (!src || src_size_in_bytes < sizeof(TChar)) - { - dst[dst_len] = 0; - return src != 0; // we return true for non-null src without characters - } - - const size_t src_n = src_size_in_bytes / sizeof(TChar); - const size_t n = (std::min)(dst_n - dst_len, src_n); - TChar* dst_ptr = &dst[dst_len]; - - for (size_t i = 0; i < n; ++i) - { - *dst_ptr++ = src[i]; - if (!src[i]) - { - return true; - } - } - - *dst_ptr = 0; - return n >= src_n || src[n] == 0; - } - - // Compares characters as case-sensitive, locale agnostic. - template<class CharType> - struct SCharComparatorCaseSensitive - { - static bool IsEqual(CharType a, CharType b) - { - return a == b; - } - }; - - // Compares characters as case-insensitive, uses the standard "C" locale. - template<class CharType> - struct SCharComparatorCaseInsensitive - { - static bool IsEqual(CharType a, CharType b) - { - if (a < 0x80 && b < 0x80) - { - a = (CharType)CryStringUtils::toLowerAscii(char(a)); - b = (CharType)CryStringUtils::toLowerAscii(char(b)); - } - return a == b; - } - }; - - // Template for wildcard matching, UCS code-point aware. - // Can be used for ASCII and Unicode (UTF-8/UTF-16/UTF-32), but not for ANSI. - // ? will match exactly one code-point. - // * will match zero or more code-points. - template <template<class> class CharComparator, class CharType> - inline bool MatchesWildcards_Tpl(const CharType* pStr, const CharType* pWild) - { - const CharType* savedStr = 0; - const CharType* savedWild = 0; - - while ((*pStr) && (*pWild != '*')) - { - if (!CharComparator<CharType>::IsEqual(*pWild, *pStr) && (*pWild != '?')) - { - return false; - } - - // We need special handling of '?' for Unicode - if (*pWild == '?' && *pStr > 127) - { - Unicode::CIterator<const CharType*> utf(pStr, pStr + 4); - if (utf.IsAtValidCodepoint()) - { - pStr = (++utf).GetPosition(); - --pStr; - } - } - - ++pWild; - ++pStr; - } - - while (*pStr) - { - if (*pWild == '*') - { - if (!*++pWild) - { - return true; - } - savedWild = pWild; - savedStr = pStr + 1; - } - else if (CharComparator<CharType>::IsEqual(*pWild, *pStr) || (*pWild == '?')) - { - // We need special handling of '?' for Unicode - if (*pWild == '?' && *pStr > 127) - { - Unicode::CIterator<const CharType*> utf(pStr, pStr + 4); - if (utf.IsAtValidCodepoint()) - { - pStr = (++utf).GetPosition(); - --pStr; - } - } - - ++pWild; - ++pStr; - } - else - { - pWild = savedWild; - pStr = savedStr++; - } - } - - while (*pWild == '*') - { - ++pWild; - } - - return *pWild == 0; - } -} // namespace CryStringUtils_Internal - - -inline bool cry_strcpy(char* const dst, size_t const dst_size_in_bytes, const char* const src) -{ - return CryStringUtils_Internal::strcpy_with_clamp<char>(dst, dst_size_in_bytes, src, (size_t)-1); -} - -inline bool cry_strcpy(char* const dst, size_t const dst_size_in_bytes, const char* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcpy_with_clamp<char>(dst, dst_size_in_bytes, src, src_size_in_bytes); -} - -template <size_t SIZE_IN_CHARS> -inline bool cry_strcpy(char(&dst)[SIZE_IN_CHARS], const char* const src) -{ - return CryStringUtils_Internal::strcpy_with_clamp<char>(dst, SIZE_IN_CHARS, src, (size_t)-1); -} - -template <size_t SIZE_IN_CHARS> -inline bool cry_strcpy(char(&dst)[SIZE_IN_CHARS], const char* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcpy_with_clamp<char>(dst, SIZE_IN_CHARS, src, src_size_in_bytes); -} - - -inline bool cry_wstrcpy(wchar_t* const dst, size_t const dst_size_in_bytes, const wchar_t* const src) -{ - return CryStringUtils_Internal::strcpy_with_clamp<wchar_t>(dst, dst_size_in_bytes, src, (size_t)-1); -} - -inline bool cry_wstrcpy(wchar_t* const dst, size_t const dst_size_in_bytes, const wchar_t* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcpy_with_clamp<wchar_t>(dst, dst_size_in_bytes, src, src_size_in_bytes); -} - -template <size_t SIZE_IN_WCHARS> -inline bool cry_wstrcpy(wchar_t(&dst)[SIZE_IN_WCHARS], const wchar_t* const src) -{ - return CryStringUtils_Internal::strcpy_with_clamp<wchar_t>(dst, SIZE_IN_WCHARS * sizeof(wchar_t), src, (size_t)-1); -} - -template <size_t SIZE_IN_WCHARS> -inline bool cry_wstrcpy(wchar_t(&dst)[SIZE_IN_WCHARS], const wchar_t* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcpy_with_clamp<wchar_t>(dst, SIZE_IN_WCHARS * sizeof(wchar_t), src, src_size_in_bytes); -} - - -inline bool cry_strcat(char* const dst, size_t const dst_size_in_bytes, const char* const src) -{ - return CryStringUtils_Internal::strcat_with_clamp<char>(dst, dst_size_in_bytes, src, (size_t)-1); -} - -inline bool cry_strcat(char* const dst, size_t const dst_size_in_bytes, const char* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcat_with_clamp<char>(dst, dst_size_in_bytes, src, src_size_in_bytes); -} - -template <size_t SIZE_IN_CHARS> -inline bool cry_strcat(char(&dst)[SIZE_IN_CHARS], const char* const src) -{ - return CryStringUtils_Internal::strcat_with_clamp<char>(dst, SIZE_IN_CHARS, src, (size_t)-1); -} - -template <size_t SIZE_IN_CHARS> -inline bool cry_strcat(char(&dst)[SIZE_IN_CHARS], const char* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcat_with_clamp<char>(dst, SIZE_IN_CHARS, src, src_size_in_bytes); -} - - -inline bool cry_wstrcat(wchar_t* const dst, size_t const dst_size_in_bytes, const wchar_t* const src) -{ - return CryStringUtils_Internal::strcat_with_clamp<wchar_t>(dst, dst_size_in_bytes, src, (size_t)-1); -} - -inline bool cry_wstrcat(wchar_t* const dst, size_t const dst_size_in_bytes, const wchar_t* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcat_with_clamp<wchar_t>(dst, dst_size_in_bytes, src, src_size_in_bytes); -} - -template <size_t SIZE_IN_WCHARS> -inline bool cry_wstrcat(wchar_t(&dst)[SIZE_IN_WCHARS], const wchar_t* const src) -{ - return CryStringUtils_Internal::strcat_with_clamp<wchar_t>(dst, SIZE_IN_WCHARS * sizeof(wchar_t), src, (size_t)-1); -} - -template <size_t SIZE_IN_WCHARS> -inline bool cry_wstrcat(wchar_t(&dst)[SIZE_IN_WCHARS], const wchar_t* const src, size_t const src_size_in_bytes) -{ - return CryStringUtils_Internal::strcat_with_clamp<wchar_t>(dst, SIZE_IN_WCHARS * sizeof(wchar_t), src, src_size_in_bytes); -} - - -namespace CryStringUtils -{ - enum - { - CRY_DEFAULT_HASH_SEED = 40503, // This is a large 16 bit prime number (perfect for seeding) - CRY_EMPTY_STR_HASH = 3350499166U, // HashString("") - }; - - // removes the extension from the file path - // \param szFilePath the source path - inline char* StripFileExtension(char* szFilePath) - { - for (char* p = szFilePath + (int)strlen(szFilePath) - 1; p >= szFilePath; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - // we've reached a path separator - it means there's no extension in this name - return nullptr; - case '.': - // there's an extension in this file name - *p = '\0'; - return p + 1; - } - } - // it seems the file name is a pure name, without path or extension - return nullptr; - } - - - // returns the parent directory of the given file or directory. - // the returned path is WITHOUT the trailing slash - // if the input path has a trailing slash, it's ignored - // nGeneration - is the number of parents to scan up - // Note: A drive specifier (if any) will always be kept (Windows-specific). - template <class StringCls> - StringCls GetParentDirectory(const StringCls& strFilePath, int nGeneration = 1) - { - for (const char* p = strFilePath.c_str() + strFilePath.length() - 2; // -2 is for the possible trailing slash: there always must be some trailing symbol which is the file/directory name for which we should get the parent - p >= strFilePath.c_str(); - --p) - { - switch (*p) - { - case ':': - return StringCls(strFilePath.c_str(), p); - break; - case '/': - case '\\': - // we've reached a path separator - return everything before it. - if (!--nGeneration) - { - return StringCls(strFilePath.c_str(), p); - } - break; - } - } - ; - // the file name is a pure name, without path or extension - return StringCls(); - } - - /*! - // converts all chars to lower case - */ - inline string ToLower(const string& str) - { - string temp = str; - -#ifndef NOT_USE_CRY_STRING - temp.MakeLower(); -#else - std::transform(temp.begin(), temp.end(), temp.begin(), toLowerAscii); // STL MakeLower -#endif - - return temp; - } - - /// Converts the single character to lower case. - /*! - \param c source character to convert to lower case if possible - \return the lower case character equivalent if possible - */ - inline char ToLower(char c) - { - return ((c <= 'Z') && (c >= 'A')) ? c + ('a' - 'A') : c; - } - - /// Converts the specified character into lowercase. - /*! - \param c the character to convert to lowercase - \return the lowercase character - */ - // Converts all ASCII characters to upper case. - // Note: Any non-ASCII characters are left unchanged. - // This function is ASCII-only and locale agnostic. - inline string toUpper (const string& str) - { - string temp = str; - -#ifndef NOT_USE_CRY_STRING - temp.MakeUpper(); -#else - std::transform(temp.begin(), temp.end(), temp.begin(), toUpperAscii); // STL MakeLower -#endif - - return temp; - } - - // searches and returns the pointer to the extension of the given file - /*! - \param szFileName source filename to search - // This function is Unicode agnostic and locale agnostic. - */ - inline const char* FindExtension(const char* szFileName) - { - const char* szEnd = szFileName + (int)strlen(szFileName); - for (const char* p = szEnd - 1; p >= szFileName; --p) - { - if (*p == '.') - { - return p + 1; - } - } - - return szEnd; - } - - // searches and returns the pointer to the file name in the given file path - /*! - \param szFilePath source path to search - */ - inline const char* FindFileNameInPath(const char* szFilePath) - { - for (const char* p = szFilePath + (int)strlen(szFilePath) - 1; p >= szFilePath; --p) - { - if (*p == '\\' || *p == '/') - { - return p + 1; - } - } - return szFilePath; - } - - // works like strstr, but is case-insensitive - /*! - \param szString the source string - \param szSubstring the sub-string to look for - */ - inline const char* stristr(const char* szString, const char* szSubstring) - { - int nSuperstringLength = (int)strlen(szString); - int nSubstringLength = (int)strlen(szSubstring); - - for (int nSubstringPos = 0; nSubstringPos <= nSuperstringLength - nSubstringLength; ++nSubstringPos) - { - if (_strnicmp(szString + nSubstringPos, szSubstring, nSubstringLength) == 0) - { - return szString + nSubstringPos; - } - } - return nullptr; - } - - -#ifndef NOT_USE_CRY_STRING - - /* - \param strPath the path to "unify" - */ - inline void UnifyFilePath(stack_string& strPath) - { - strPath.replace('\\', '/'); - strPath.MakeLower(); - } - - template<size_t SIZE> - inline void UnifyFilePath(CryStackStringT<char, SIZE>& strPath) - { - strPath.replace('\\', '/'); - strPath.MakeLower(); - } - - /// Replaces backslashes with forward slashes and transforms string to lowercase. - /*! - \param strPath the path to "unify" - */ - inline void UnifyFilePath(string& strPath) - { - strPath.replace('\\', '/'); - strPath.MakeLower(); - } - -#endif - - // converts the number to a string - /* - \param nNumber an unsigned number - \return the unsigned number as a string - */ - inline string ToString(unsigned nNumber) - { - char szNumber[16]; - sprintf_s(szNumber, "%u", nNumber); - return szNumber; - } - - /// Converts the number to a string. - /*! - \param nNumber an signed integer - \return the signed integer as a string - */ - inline string ToString(signed int nNumber) - { - char szNumber[16]; - sprintf_s(szNumber, "%d", nNumber); - return szNumber; - } - - /// Converts the floating point number to a string. - /*! - \param nNumber a floating point number - \return the floating point number as a string - */ - inline string ToString(float nNumber) - { - char szNumber[128]; - sprintf_s(szNumber, "%f", nNumber); - return szNumber; - } - - /// Converts the boolean value to a string ("0" or "1"). - /*! - \param nNumber an unsigned number - \return the bool as a string (either "1" or "0") - */ - inline string ToString(bool nNumber) - { - char szNumber[4]; - sprintf_s(szNumber, "%i", (int)nNumber); - return szNumber; - } - -#ifdef CRYINCLUDE_CRYCOMMON_CRY_MATRIX44_H - /// Converts a Matrix44 to a string. - /*! - \param m A matrix of type Matrix44 - \return the matrix in the format {0,0,0,0}{0,0,0,0}{0,0,0,0}{0,0,0,0} - */ - inline string ToString(const Matrix44& m) - { - char szBuf[0x200]; - sprintf_s(szBuf, "{%g,%g,%g,%g}{%g,%g,%g,%g}{%g,%g,%g,%g}{%g,%g,%g,%g}", - m(0, 0), m(0, 1), m(0, 2), m(0, 3), - m(1, 0), m(1, 1), m(1, 2), m(1, 3), - m(2, 0), m(2, 1), m(2, 2), m(2, 3), - m(3, 0), m(3, 1), m(3, 2), m(3, 3)); - return szBuf; - } -#endif - -#ifdef CRYINCLUDE_CRYCOMMON_CRY_QUAT_H - /// Converts a CryQuat to a string. - /*! - \param m A quaternion of type CryQuat - \return the quaternion in the format {0,{0,0,0,0}} - */ - inline string ToString (const CryQuat& q) - { - char szBuf[0x100]; - sprintf_s(szBuf, "{%g,{%g,%g,%g}}", q.w, q.v.x, q.v.y, q.v.z); - return szBuf; - } -#endif - -#ifdef CRYINCLUDE_CRYCOMMON_CRY_VECTOR3_H - /// Converts a Vec3 to a string. - /*! - \param m A vector of type Vec3 - \return the vector in the format {0,0,0} - */ - inline string ToString (const Vec3& v) - { - char szBuf[0x80]; - sprintf_s(szBuf, "{%g,%g,%g}", v.x, v.y, v.z); - return szBuf; - } -#endif - - /// This function only exists to allow ToString to compile if it is ever used with an unsupported type. - /*! - \param unknownType - \return a string that reads "unknown" - */ - template<class T> - inline string ToString(T& unknownType) - { - char szValue[8]; - sprintf_s(szValue, "%s", "unknown"); - return szValue; - } - - // does the same as strstr, but the szString is allowed to be no more than the specified size - /*! - \param szString the source string - \param szSubstring the sub-string to look for - \param nSuperstringLength the maximum size of szString - */ - inline const char* strnstr(const char* szString, const char* szSubstring, int nSuperstringLength) - { - int nSubstringLength = (int)strlen(szSubstring); - if (!nSubstringLength) - { - return szString; - } - - for (int nSubstringPos = 0; szString[nSubstringPos] && nSubstringPos < nSuperstringLength - nSubstringLength; ++nSubstringPos) - { - if (strncmp(szString + nSubstringPos, szSubstring, nSubstringLength) == 0) - { - return szString + nSubstringPos; - } - } - return nullptr; - } - - - // Finds the string in the array of strings. - // Returns its 0-based index or -1 if not found. - // Comparison is case-sensitive. - // The string array end is demarked by the NULL value. - // This function is Unicode agnostic (but no Unicode collation is performed for equality test) and locale agnostic. - inline int findString(const char* szString, const char* arrStringList[]) - { - for (const char** p = arrStringList; *p; ++p) - { - if (0 == strcmp(*p, szString)) - { - return (int)(p - arrStringList); - } - } - return -1; // string was not found - } - - /// Finds the string in the array of strings. - /*! - \param szString the string to look for - \param arrStringList array of strings - \remark comparison is case-sensitive - \remark The string array end is delimited by the nullptr value - \return its 0-based index or -1 if not found - */ - inline int FindString(const char* szString, const char* arrStringList[]) - { - for (const char** p = arrStringList; *p; ++p) - { - if (0 == strcmp(*p, szString)) - { - return (int)(p - arrStringList); - } - } - return -1; // string was not found - } - - /// Used for printing out sets of objects of string type. - /*! - \remark just forms the comma-delimited string where each string in the set is presented as a formatted substring - \param setStrings set of strings to print - \return a formatted string - */ - inline string ToString(const std::set<string>& setStrings) - { - string strResult; - if (!setStrings.empty()) - { - strResult += "{"; - for (std::set<string>::const_iterator it = setStrings.begin(); it != setStrings.end(); ++it) - { - if (it != setStrings.begin()) - { - strResult += ", "; - } - strResult += "\""; - strResult += *it; - strResult += "\""; - } - strResult += "}"; - } - return strResult; - } - - // Cuts the string and adds leading ... if it's longer than specified maximum length. - // This function is ASCII-only and locale agnostic. - inline string cutString(const string& strPath, unsigned nMaxLength) - { - if (strPath.length() > nMaxLength && nMaxLength > 3) - { - return string("...") + string(strPath.c_str() + strPath.length() - (nMaxLength - 3)); - } - else - { - return strPath; - } - } - - /// Cuts the string and adds leading ... if it's longer than specified maximum length. - /*! - \param str the string to cut - \param nMaxLength the allowed length of the string before its cut. - \return a shortened string starting in ellipses or the source string if it's smaller than nMaxLength - */ - inline string CutString(const string& str, unsigned nMaxLength) - { - if (str.length() > nMaxLength && nMaxLength > 3) - { - return string("...") + string(str.c_str() + str.length() - (nMaxLength - 3)); - } - else - { - return str; - } - } - - /// Converts the given set of NUMBERS into the string. - /*! - \param setMtlms A numeric set to convert into a string - \param szFormat - \param szPostfix - */ - template <typename T> - string ToString(const std::set<T>& setMtls, const char* szFormat, const char* szPostfix = "") - { - string strResult; - char szBuffer[64]; - if (!setMtls.empty()) - { - strResult += strResult.empty() ? "(" : " ("; - for (typename std::set<T>::const_iterator it = setMtls.begin(); it != setMtls.end(); ) - { - if (it != setMtls.begin()) - { - strResult += ", "; - } - sprintf_s(szBuffer, szFormat, *it); - strResult += szBuffer; - T nStart = *it; - - ++it; - - if (it != setMtls.end() && *it == nStart + 1) - { - T nPrev = *it; - // we've got a region - while (++it != setMtls.end() && *it == nPrev + 1) - { - nPrev = *it; - } - if (nPrev == nStart + 1) - { - // special case - range of length 1 - strResult += ","; - } - else - { - strResult += ".."; - } - sprintf_s(szBuffer, szFormat, nPrev); - strResult += szBuffer; - } - } - strResult += ")"; - } - return szPostfix[0] ? strResult + szPostfix : strResult; - } - - - // Attempts to find a matching wildcard in a string. - /*! - \param szString source string - \param szWildcard the wildcard, supports * and ? - // returns true if the string matches the wildcard - // Note: ANSI input is not supported, ASCII is fine since it's a subset of UTF-8. - */ - inline bool MatchWildcard(const char* szString, const char* szWildcard) - { - return CryStringUtils_Internal::MatchesWildcards_Tpl<CryStringUtils_Internal::SCharComparatorCaseSensitive>(szString, szWildcard); - } - - // Returns true if the string matches the wildcard. - // Supports wildcard ? (matches one code-point) and * (matches zero or more code-points). - // This function is Unicode aware and uses the "C" locale for case comparison. - // Note: ANSI input is not supported, ASCII is fine since it's a subset of UTF-8. - inline bool MatchWildcardIgnoreCase(const char* szString, const char* szWildcard) - { - return CryStringUtils_Internal::MatchesWildcards_Tpl<CryStringUtils_Internal::SCharComparatorCaseInsensitive>(szString, szWildcard); - } - -#if !defined(RESOURCE_COMPILER) - - // calculates a hash value for a given string - inline uint32 CalculateHash(const char* str) - { - return CCrc32::Compute(str); - } - - // calculates a hash value for the lower case version of a given string - inline uint32 CalculateHashLowerCase(const char* str) - { - return CCrc32::ComputeLowercase(str); - } - - // This function is Unicode agnostic and locale agnostic. - inline uint32 HashStringSeed(const char* string, const uint32 seed) - { - // A string hash taken from the FRD/Crysis2 (game) code with low probability of clashes - // Recommend you use the CRY_DEFAULT_HASH_SEED (see HashString) - const char* p; - uint32 hash = seed; - for (p = string; *p != '\0'; p++) - { - hash += *p; - hash += (hash << 10); - hash ^= (hash >> 6); - } - hash += (hash << 3); - hash ^= (hash >> 11); - hash += (hash << 15); - return hash; - } - - // This function is ASCII-only and uses the standard "C" locale for case conversion. - inline uint32 HashStringLowerSeed(const char* string, const uint32 seed) - { - // computes the hash of 'string' converted to lower case - // also see the comment in HashStringSeed - const char* p; - uint32 hash = seed; - for (p = string; *p != '\0'; p++) - { - hash += toLowerAscii(*p); - hash += (hash << 10); - hash ^= (hash >> 6); - } - hash += (hash << 3); - hash ^= (hash >> 11); - hash += (hash << 15); - return hash; - } - - // This function is Unicode agnostic and locale agnostic. - inline uint32 HashString(const char* string) - { - return HashStringSeed(string, CRY_DEFAULT_HASH_SEED); - } - - // This function is ASCII-only and uses the standard "C" locale for case conversion. - inline uint32 HashStringLower(const char* string) - { - return HashStringLowerSeed(string, CRY_DEFAULT_HASH_SEED); - } -#endif - - // converts all chars to lower case - avoids memory allocation - /*! - \param str Reference to string to convert into lowercase. - */ - inline void ToLowerInplace(string& str) - { -#ifndef NOT_USE_CRY_STRING - str.MakeLower(); -#else - std::transform(str.begin(), str.end(), str.begin(), toLowerAscii); // STL MakeLower -#endif - } - - /// Converts all chars to lower case - avoids memory allocation - /*! - \param str Reference to string to convert into lowercase. - */ - inline void ToLowerInplace(char* str) - { - if (str == nullptr) - { - return; - } - - for (char* s = str; *s != '\0'; s++) - { - *s = toLowerAscii(*s); - } - } - - -#ifndef NOT_USE_CRY_STRING - - // Converts a wide string (can be UTF-16 or UTF-32 depending on platform) to UTF-8. - // This function is Unicode aware and locale agnostic. - /// Converts a wide string to a UTF8 string. - /*! - \param str The wide string to convert. - \return dstr The wide string converted into the specified UTF8 type. - */ - template <typename T> - inline void WStrToUTF8(const wchar_t* str, T& dstr) - { - string utf8; - Unicode::Convert(utf8, str); - - // Note: This function expects T to have assign(ptr, len) function - dstr.assign(utf8.c_str(), utf8.length()); - } - - // Converts a wide string (can be UTF-16 or UTF-32 depending on platform) to UTF-8. - // This function is Unicode aware and locale agnostic. - /// Converts a wide string to UTF8. - /*! - \param str The wchar_t string to convert. - \return The UTF8 string. - */ - inline string WStrToUTF8(const wchar_t* str) - { - return Unicode::Convert<string>(str); - } - - /// Converts a UTF8 string to a wide string. - /*! - \param str The UTF8 string to convert. - \return dstr The UTF8 string converted into the specified type. - */ - template <typename T> - inline void UTF8ToWStr(const char* str, T& dstr) - { - wstring wide; - Unicode::Convert(wide, str); - - // Note: This function expects T to have assign(ptr, len) function - dstr.assign(wide.c_str(), wide.length()); - } - - // Converts an UTF-8 string to wide string (can be UTF-16 or UTF-32 depending on platform). - // This function is Unicode aware and locale agnostic. - /*! - \param str The UTF8 string to convert. - \return str as converted to wstring. - */ - inline wstring UTF8ToWStr(const char* str) - { - return Unicode::Convert<wstring>(str); - } - - /// Converts a string to a wide character string - /*! - \param str Source string. - \param dstr Destination wstring. - */ - inline void StrToWstr(const char* str, wstring& dstr) - { - CryStackStringT<wchar_t, 64> tmp; - tmp.resize(strlen(str)); - tmp.clear(); - - while (const wchar_t c = (wchar_t)(*str++)) - { - tmp.append(1, c); - } - - dstr.assign(tmp.data(), tmp.length()); - } - -#endif // NOT_USE_CRY_STRING - - /// The type used to parse a yes/no string -#if defined(_DISALLOW_ENUM_CLASS) - enum YesNoType -#else - enum class YesNoType -#endif - { - Yes, - No, - Invalid - }; - - // parse the yes/no string - /*! - \param szString any of the following strings: yes, enable, true, 1, no, disable, false, 0 - \return YesNoType::Yes if szString is yes/enable/true/1, YesNoType::No if szString is no, disable, false, 0 and YesNoType::Invalid if the string is not one of the expected values. - */ - inline YesNoType ToYesNoType(const char* szString) - { - if (!_stricmp(szString, "yes") - || !_stricmp(szString, "enable") - || !_stricmp(szString, "true") - || !_stricmp(szString, "1")) -#if defined(_DISALLOW_ENUM_CLASS) - { - return Yes; - } -#else - { - return YesNoType::Yes; - } -#endif - if (!_stricmp(szString, "no") - || !_stricmp(szString, "disable") - || !_stricmp(szString, "false") - || !_stricmp(szString, "0")) -#if defined(_DISALLOW_ENUM_CLASS) - { - return No; - } -#else - { - return YesNoType::No; - } -#endif - -#if defined(_DISALLOW_ENUM_CLASS) - return Invalid; -#else - return YesNoType::Invalid; -#endif - } - - /// Verifies if the filename provided only contains the accepted characters. - /*! - \param fileName the filename to verify - \return true if the filename only contains alphanumeric values and/or dot, dash and underscores. - */ - inline bool IsValidFileName(const char* fileName) - { - size_t i = 0; - for (;; ) - { - const char c = fileName[i++]; - if (c == 0) - { - return true; - } - if (!((c >= '0' && c <= '9') - || (c >= 'A' && c <= 'Z') - || (c >= 'a' && c <= 'z') - || c == '.' || c == '-' || c == '_')) - { - return false; - } - } - } - - - /************************************************************************** - *void _makepath() - build path name from components - * - *Purpose: - * create a path name from its individual components - * - *Entry: - * char *path - pointer to buffer for constructed path - * char *drive - pointer to drive component, may or may not contain trailing ':' - * char *dir - pointer to subdirectory component, may or may not include leading and/or trailing '/' or '\' characters - * char *fname - pointer to file base name component - * char *ext - pointer to extension component, may or may not contain a leading '.'. - * - *Exit: - * path - pointer to constructed path name - * - *******************************************************************************/ - ILINE void portable_makepath(char path[_MAX_PATH], const char* drive, const char* dir, const char* fname, const char* ext) - { - const char* p; - - /* we assume that the arguments are in the following form (although we - * do not diagnose invalid arguments or illegal filenames (such as - * names longer than 8.3 or with illegal characters in them) - * - * drive: - * A ; or - * A: - * dir: - * \top\next\last\ ; or - * /top/next/last/ ; or - * either of the above forms with either/both the leading - * and trailing / or \ removed. Mixed use of '/' and '\' is - * also tolerated - * fname: - * any valid file name - * ext: - * any valid extension (none if empty or null ) - */ - - /* copy drive */ - - if (drive && *drive) - { - *path++ = *drive; - *path++ = (':'); - } - - /* copy dir */ - - if ((p = dir) && *p) - { - do - { - *path++ = *p++; - } while (*p); - if (*(p - 1) != '/' && *(p - 1) != ('\\')) - { - *path++ = ('\\'); - } - } - - /* copy fname */ - - if (p = fname) - { - while (*p) - { - *path++ = *p++; - } - } - - /* copy ext, including 0-terminator - check to see if a '.' needs - * to be inserted. - */ - - if (p = ext) - { - if (*p && *p != ('.')) - { - *path++ = ('.'); - } - while (*path++ = *p++) - { - ; - } - } - else - { - /* better add the 0-terminator */ - *path = ('\0'); - } - } - - /// Create a path name from its individual components. - /*! - \param char *path pointer to buffer for constructed path - \param char *drive pointer to drive component, may or may not contain trailing ':' - \param char *dir pointer to subdirectory component, may or may not include leading and/or trailing '/' or '\' characters - \param char *fname pointer to file base name component - \param char *ext pointer to extension component, may or may not contain a leading '.'. - \return path pointer to constructed path name - */ - inline void MakePath(char path[_MAX_PATH], const char* drive, const char* dir, const char* fname, const char* ext) - { - const char* p; - - // we assume that the arguments are in the following form (although we - // do not diagnose invalid arguments or illegal filenames (such as - // names longer than 8.3 or with illegal characters in them) - // - // drive: - // A ; or - // A: - // dir: - // \top\next\last\ ; or - // /top/next/last/ ; or - // either of the above forms with either/both the leading - // and trailing / or \ removed. Mixed use of '/' and '\' is - // also tolerated - // fname: - // any valid file name - // ext: - // any valid extension (none if empty or null ) - // - - // copy drive - if (drive && *drive) - { - *path++ = *drive; - *path++ = (':'); - } - - // copy dir - if ((p = dir) && *p) - { - do - { - *path++ = *p++; - } while (*p); - if (*(p - 1) != '/' && *(p - 1) != ('\\')) - { - *path++ = ('\\'); - } - } - - // copy fname - if (p = fname) - { - while (*p) - { - *path++ = *p++; - } - } - - // copy ext, including 0-terminator - check to see if a '.' needs - // to be inserted. - if (p = ext) - { - if (*p && *p != ('.')) - { - *path++ = ('.'); - } - while (*path++ = *p++) - { - ; - } - } - else - { - // better add the 0-terminator - *path = ('\0'); - } - } - - // Copies characters from a string. - /*! - \param destination Pointer to the destination array where the content is to be copied. - \param source C string to be copied. - \param num Maximum number of characters to be copied from source. - \remark Parameter order is the same as strncpy; Copies only up to num characters from source to destination. - \return true if entirety of source was copied into destination. - */ - inline bool strncpy(char* destination, const char* source, size_t num) - { - bool reply = false; - -#if CRY_STRING_ASSERTS && !defined(RESOURCE_COMPILER) - CRY_ASSERT(destination); - CRY_ASSERT(source); -#endif - - if (num) - { - size_t i; - for (i = 0; source[i] && (i + 1) < num; ++i) - { - destination[i] = source[i]; - } - destination[i] = '\0'; - reply = (source[i] == '\0'); - } - -#if CRY_STRING_ASSERTS && !defined(RESOURCE_COMPILER) - CRY_ASSERT_MESSAGE(reply, string().Format("String '%s' is too big to fit into a buffer of length %u", source, (unsigned int)num)); -#endif - return reply; - } - - // Copies wide characters from a wide string. - /*! - \param destination Pointer to the destination wchar_t array where the content is to be copied. - \param source C wide string to be copied. - \param num Maximum number of characters to be copied from source. - \remark Parameter order is the same as strncpy; Copies only up to num characters from source to destination. - \return true if entirety of source was copied into destination. - */ - inline bool wstrncpy(wchar_t* destination, const wchar_t* source, size_t bufferLength) - { - bool reply = false; - -#if CRY_STRING_ASSERTS && !defined(RESOURCE_COMPILER) - CRY_ASSERT(destination); - CRY_ASSERT(source); -#endif - - if (bufferLength) - { - size_t i; - for (i = 0; source[i] && (i + 1) < bufferLength; ++i) - { - destination[i] = source[i]; - } - destination[i] = '\0'; - reply = (source[i] == '\0'); - } - -#if CRY_STRING_ASSERTS && !defined(RESOURCE_COMPILER) - CRY_ASSERT_MESSAGE(reply, string().Format("String '%ls' is too big to fit into a buffer of length %u", source, (unsigned int)bufferLength)); -#endif - return reply; - } - - // Copies a C string into a destination buffer up to a specified delimiter or null terminator. - /*! - \param destination Pointer to a buffer where the resulting C-string is stored. - \param source C string to be copied. - \param num Maximum number of characters to be copied from source. - \param delimiter Delimiter character up to which the string will be copied. - \return Number of bytes written into destination (including null terminator) or 0 if delimiter is not found within the first num bytes of source. - */ - inline size_t CopyStringUntilFindChar(char* destination, const char* source, size_t num, char delimiter) - { - size_t reply = 0; - -#if CRY_STRING_ASSERTS && !defined(RESOURCE_COMPILER) - CRY_ASSERT(destination); - CRY_ASSERT(source); -#endif - - if (num) - { - size_t i; - for (i = 0; source[i] && source[i] != delimiter && (i + 1) < num; ++i) - { - destination[i] = source[i]; - } - destination[i] = '\0'; - reply = (source[i] == delimiter) ? (i + 1) : 0; - } - - return reply; - } -} // namespace CryStringUtils - -#endif // CRYINCLUDE_CRYCOMMON_STRINGUTILS_H diff --git a/Code/CryEngine/CryCommon/Synchronization.h b/Code/CryEngine/CryCommon/Synchronization.h deleted file mode 100644 index 428b0d33df..0000000000 --- a/Code/CryEngine/CryCommon/Synchronization.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_SYNCHRONIZATION_H -#define CRYINCLUDE_CRYCOMMON_SYNCHRONIZATION_H -#pragma once - - -//--------------------------------------------------------------------------- -// Synchronization policies, for classes (e.g. containers, allocators) that may -// or may not be multithread-safe. -// -// Policies should be used as a template argument to such classes, -// and these class implementations should then utilise the policy, as a base-class or member. -// -//--------------------------------------------------------------------------- - -#include "MultiThread.h" -#include "CryThread.h" - -namespace stl -{ - template<class Sync> - struct AutoLock - { - ILINE AutoLock(Sync& sync) - : _sync(sync) - { - sync.Lock(); - } - ILINE ~AutoLock() - { - _sync.Unlock(); - } - - private: - Sync& _sync; - }; - - - struct PSyncNone - { - void Lock() {} - void Unlock() {} - }; - - struct PSyncMultiThread - { - PSyncMultiThread() - : _Semaphore(0) {} - - void Lock() - { - CryWriteLock(&_Semaphore); - } - void Unlock() - { - CryReleaseWriteLock(&_Semaphore); - } - int IsLocked() const volatile - { - return _Semaphore; - } - - private: - volatile int _Semaphore; - }; - -#ifdef _DEBUG - - struct PSyncDebug - : public PSyncMultiThread - { - void Lock() - { - assert(!IsLocked()); - PSyncMultiThread::Lock(); - } - }; - -#else - - typedef PSyncNone PSyncDebug; - -#endif -}; - -#endif // CRYINCLUDE_CRYCOMMON_SYNCHRONIZATION_H diff --git a/Code/CryEngine/CryCommon/Tarray.h b/Code/CryEngine/CryCommon/Tarray.h deleted file mode 100644 index 9dfd410ffd..0000000000 --- a/Code/CryEngine/CryCommon/Tarray.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_TARRAY_H -#define CRYINCLUDE_CRYCOMMON_TARRAY_H -#pragma once - - -#include <ILog.h> -#include <Cry_Math.h> -#include <AzCore/IO/FileIO.h> - -#ifndef CLAMP -#define CLAMP(X, mn, mx) ((X) < (mn) ? (mn) : ((X) < (mx) ? (X) : (mx))) -#endif - -#ifndef SATURATE -#define SATURATE(X) clamp_tpl(X, 0.f, 1.f) -#endif - -#ifndef SATURATEB -#define SATURATEB(X) CLAMP(X, 0, 255) -#endif - -#ifndef LERP -#define LERP(A, B, Alpha) ((A) + (Alpha) * ((B)-(A))) -#endif - -// Safe memory freeing -#ifndef SAFE_DELETE -#define SAFE_DELETE(p) { if (p) { delete (p); (p) = NULL; } \ -} -#endif - -#ifndef SAFE_DELETE_ARRAY -#define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p); (p) = NULL; } \ -} -#endif - -#ifndef SAFE_RELEASE -#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p) = NULL; } \ -} -#endif - -#ifndef SAFE_RELEASE_FORCE -#define SAFE_RELEASE_FORCE(p) { if (p) { (p)->ReleaseForce(); (p) = NULL; } \ -} -#endif - -#endif // CRYINCLUDE_CRYCOMMON_TARRAY_H diff --git a/Code/CryEngine/CryCommon/TimeValue.h b/Code/CryEngine/CryCommon/TimeValue.h deleted file mode 100644 index b5a3135c9a..0000000000 --- a/Code/CryEngine/CryCommon/TimeValue.h +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_TIMEVALUE_H -#define CRYINCLUDE_CRYCOMMON_TIMEVALUE_H - -#pragma once - - -class CTimeValue -{ -public: - static const int64 TIMEVALUE_PRECISION = 100000; // one second - -public: - void GetMemoryUsage(class ICrySizer*) const { /*nothing*/} - - // Default constructor. - ILINE CTimeValue() - { - m_lValue = 0; - } - - // Constructor. - ILINE CTimeValue(const float fSeconds) - { - SetSeconds(fSeconds); - } - - ILINE CTimeValue(const double fSeconds) - { - SetSeconds(fSeconds); - } - - // Constructor. - // Arguments: - // inllValue - positive negative, absolute or relative in 1 second= TIMEVALUE_PRECISION units. - ILINE CTimeValue(const int64 inllValue) - { - m_lValue = inllValue; - } - - // Copy constructor. - ILINE CTimeValue(const CTimeValue& inValue) - { - m_lValue = inValue.m_lValue; - } - - // Destructor. - ILINE ~CTimeValue() {} - - // Description: - // Assignment operator. - // Arguments: - // inRhs - Right side. - ILINE CTimeValue& operator=(const CTimeValue& inRhs) - { - m_lValue = inRhs.m_lValue; - return *this; - }; - - // Use only for relative value, absolute values suffer a lot from precision loss. - ILINE float GetSeconds() const - { - return m_lValue * (1.f / TIMEVALUE_PRECISION); - } - - // Get relative time difference in seconds - call on the endTime object: endTime.GetDifferenceInSeconds( startTime ); - ILINE float GetDifferenceInSeconds(const CTimeValue& startTime) const - { - return (m_lValue - startTime.m_lValue) * (1.f / TIMEVALUE_PRECISION); - } - - // - ILINE void SetSeconds(const float infSec) - { - m_lValue = (int64)(infSec * TIMEVALUE_PRECISION); - } - - // - ILINE void SetSeconds(const double infSec) - { - m_lValue = (int64)(infSec * TIMEVALUE_PRECISION); - } - - // - ILINE void SetSeconds(const int64 indwSec) - { - m_lValue = indwSec * TIMEVALUE_PRECISION; - } - - // - ILINE void SetMilliSeconds(const int64 indwMilliSec) - { - m_lValue = indwMilliSec * (TIMEVALUE_PRECISION / 1000); - } - - // Use only for relative value, absolute values suffer a lot from precision loss. - ILINE float GetMilliSeconds() const - { - return m_lValue * (1000.f / TIMEVALUE_PRECISION); - } - - ILINE int64 GetMilliSecondsAsInt64() const - { - return m_lValue * 1000 / TIMEVALUE_PRECISION; - } - - ILINE int64 GetMicroSecondsAsInt64() const - { - return m_lValue * (1000 * 1000) / TIMEVALUE_PRECISION; - } - - ILINE int64 GetValue() const - { - return m_lValue; - } - - ILINE void SetValue(int64 val) - { - m_lValue = val; - } - - // Description: - // Useful for periodic events (e.g. water wave, blinking). - // Changing TimePeriod can results in heavy changes in the returned value. - // Return Value: - // [0..1[ - float GetPeriodicFraction(const CTimeValue TimePeriod) const - { - // todo: change float implement to int64 for more precision - float fAbs = GetSeconds() / TimePeriod.GetSeconds(); - return fAbs - (int)(fAbs); - } - - // math operations ----------------------- - - // Minus. - ILINE CTimeValue operator-(const CTimeValue& inRhs) const { CTimeValue ret; ret.m_lValue = m_lValue - inRhs.m_lValue; return ret; }; - // Plus. - ILINE CTimeValue operator+(const CTimeValue& inRhs) const { CTimeValue ret; ret.m_lValue = m_lValue + inRhs.m_lValue; return ret; }; - // Unary minus. - ILINE CTimeValue operator-() const { CTimeValue ret; ret.m_lValue = -m_lValue; return ret; }; - - ILINE CTimeValue& operator+=(const CTimeValue& inRhs) { m_lValue += inRhs.m_lValue; return *this; } - ILINE CTimeValue& operator-=(const CTimeValue& inRhs) { m_lValue -= inRhs.m_lValue; return *this; } - - ILINE CTimeValue& operator/=(int inRhs) { m_lValue /= inRhs; return *this; } - - // comparison ----------------------- - - ILINE bool operator<(const CTimeValue& inRhs) const { return m_lValue < inRhs.m_lValue; }; - ILINE bool operator>(const CTimeValue& inRhs) const { return m_lValue > inRhs.m_lValue; }; - ILINE bool operator>=(const CTimeValue& inRhs) const { return m_lValue >= inRhs.m_lValue; }; - ILINE bool operator<=(const CTimeValue& inRhs) const { return m_lValue <= inRhs.m_lValue; }; - ILINE bool operator==(const CTimeValue& inRhs) const { return m_lValue == inRhs.m_lValue; }; - ILINE bool operator!=(const CTimeValue& inRhs) const { return m_lValue != inRhs.m_lValue; }; - - AUTO_STRUCT_INFO - - void GetMemoryStatistics(class ICrySizer*) const { /*nothing*/} - -private: // ---------------------------------------------------------- - - int64 m_lValue; // absolute or relative value in 1/TIMEVALUE_PRECISION, might be negative - - - friend class CTimer; -}; - -#endif // CRYINCLUDE_CRYCOMMON_TIMEVALUE_H diff --git a/Code/CryEngine/CryCommon/TimeValue_info.h b/Code/CryEngine/CryCommon/TimeValue_info.h deleted file mode 100644 index 8d2b23b441..0000000000 --- a/Code/CryEngine/CryCommon/TimeValue_info.h +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_TIMEVALUE_INFO_H -#define CRYINCLUDE_CRYCOMMON_TIMEVALUE_INFO_H -#pragma once - -#include "TimeValue.h" - -STRUCT_INFO_BEGIN(CTimeValue) -STRUCT_VAR_INFO(m_lValue, TYPE_INFO(int64)) -STRUCT_INFO_END(CTimeValue) - - -#endif // CRYINCLUDE_CRYCOMMON_TIMEVALUE_INFO_H diff --git a/Code/CryEngine/CryCommon/Timer.h b/Code/CryEngine/CryCommon/Timer.h deleted file mode 100644 index ffd1d52014..0000000000 --- a/Code/CryEngine/CryCommon/Timer.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once -#ifndef CRYINCLUDE_CRYCOMMON_TIMER_H -#define CRYINCLUDE_CRYCOMMON_TIMER_H - -struct Timer -{ - Timer() - : endTime(-1.0f) - { - } - - void Reset(float duration, float variation = 0.0f) - { - endTime = gEnv->pSystem->GetITimer()->GetFrameStartTime() + CTimeValue(duration) + CTimeValue(cry_random(0.0f, variation)); - } - - bool Elapsed() const - { - return endTime >= 0.0f && gEnv->pSystem->GetITimer()->GetFrameStartTime() >= endTime; - } - - float GetSecondsLeft() const - { - return (endTime - gEnv->pSystem->GetITimer()->GetFrameStartTime()).GetSeconds(); - } - - CTimeValue endTime; -}; -#endif // CRYINCLUDE_CRYCOMMON_TIMER_H diff --git a/Code/CryEngine/CryCommon/TypeInfo_decl.h b/Code/CryEngine/CryCommon/TypeInfo_decl.h deleted file mode 100644 index dbab741bae..0000000000 --- a/Code/CryEngine/CryCommon/TypeInfo_decl.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Macros and other definitions needed for TypeInfo declarations. - - -#ifndef CRYINCLUDE_CRYCOMMON_TYPEINFO_DECL_H -#define CRYINCLUDE_CRYCOMMON_TYPEINFO_DECL_H -#pragma once - -#include <AzCore/Math/Uuid.h> - -////////////////////////////////////////////////////////////////////////// -// Meta-type support. -////////////////////////////////////////////////////////////////////////// - -// Currently enable type info for all platforms. -#if !defined(ENABLE_TYPE_INFO) -#define ENABLE_TYPE_INFO -#endif -#ifdef ENABLE_TYPE_INFO - -struct CTypeInfo; - -// If TypeInfo exists for T, it is accessed via TypeInfo(T*). -// Default TypeInfo() is implemented by a struct member function. -template<class T> -inline const CTypeInfo& TypeInfo(const T* t) -{ - return t->TypeInfo(); -} - -// Declare a class's TypeInfo member -#define STRUCT_INFO \ - const CTypeInfo&TypeInfo() const; - -#define NULL_STRUCT_INFO \ - const CTypeInfo&TypeInfo() const { return *(CTypeInfo*)0; } - -// Declare an override for a type without TypeInfo() member (e.g. basic type) -#define DECLARE_TYPE_INFO(Type) \ - template<> \ - const CTypeInfo&TypeInfo(const Type*); - -// Template version. -#define DECLARE_TYPE_INFO_T(Type) \ - template<class T> \ - const CTypeInfo&TypeInfo(const Type<T>*); - -// Type info declaration, with additional prototypes for string conversions. -#define BASIC_TYPE_INFO(Type) \ - string ToString(Type const & val); \ - bool FromString(Type & val, const char* s); \ - DECLARE_TYPE_INFO(Type) - -#define CUSTOM_STRUCT_INFO(Struct) \ - const CTypeInfo&TypeInfo() const \ - { static Struct Info; return Info; } - -#else // ENABLE_TYPE_INFO - -#define STRUCT_INFO -#define NULL_STRUCT_INFO -#define DECLARE_TYPE_INFO(Type) -#define DECLARE_TYPE_INFO_T(Type) -#define BASIC_TYPE_INFO(T) - -#endif // ENABLE_TYPE_INFO - -// Specify automatic tool generation of TypeInfo bodies. -#define AUTO_STRUCT_INFO STRUCT_INFO -#define AUTO_TYPE_INFO DECLARE_TYPE_INFO -#define AUTO_TYPE_INFO_T DECLARE_TYPE_INFO_T - -// Obsolete "LOCAL" versions (all infos now generated in local files). -#define AUTO_STRUCT_INFO_LOCAL STRUCT_INFO -#define AUTO_TYPE_INFO_LOCAL DECLARE_TYPE_INFO -#define AUTO_TYPE_INFO_LOCAL_T DECLARE_TYPE_INFO_T - -// Overrides for basic types. -DECLARE_TYPE_INFO(void) - -BASIC_TYPE_INFO(bool) -BASIC_TYPE_INFO(char) -BASIC_TYPE_INFO(wchar_t) -BASIC_TYPE_INFO(signed char) -BASIC_TYPE_INFO(unsigned char) -BASIC_TYPE_INFO(short) -BASIC_TYPE_INFO(unsigned short) -BASIC_TYPE_INFO(int) -BASIC_TYPE_INFO(unsigned int) -BASIC_TYPE_INFO(long) -BASIC_TYPE_INFO(unsigned long) -BASIC_TYPE_INFO(int64) -BASIC_TYPE_INFO(uint64) - -BASIC_TYPE_INFO(float) -BASIC_TYPE_INFO(double) - -BASIC_TYPE_INFO(AZ::Uuid) - -DECLARE_TYPE_INFO(string) - -// All pointers share same TypeInfo. -const CTypeInfo&PtrTypeInfo(); -template<class T> -inline const CTypeInfo& TypeInfo([[maybe_unused]] T** t) -{ - return PtrTypeInfo(); -} - - -#endif // CRYINCLUDE_CRYCOMMON_TYPEINFO_DECL_H diff --git a/Code/CryEngine/CryCommon/TypeInfo_impl.h b/Code/CryEngine/CryCommon/TypeInfo_impl.h deleted file mode 100644 index 938a7b5e52..0000000000 --- a/Code/CryEngine/CryCommon/TypeInfo_impl.h +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Declaration of CTypeInfo, and other things to access meta-type info. - - -#ifndef CRYINCLUDE_CRYCOMMON_TYPEINFO_IMPL_H -#define CRYINCLUDE_CRYCOMMON_TYPEINFO_IMPL_H -#pragma once - - -#include "CryCustomTypes.h" - -#define ENABLE_TYPE_INFO_NAMES 1 - -//--------------------------------------------------------------------------- -// DECLARATION MACROS -// Used to construct meta TypeInfo objects in AutoTypeInfo files. -// Two possible levels of TypeInfo: default, with size and offset info only, allowing Endian conversion; -// and full, with string, attr, and enum info, allowing UI and serialisation. -// The full version is selected by the ENABLE_TYPE_INFO_NAMES macro. - -#ifdef ENABLE_TYPE_INFO - - #ifndef ENABLE_TYPE_INFO_NAMES -// This symbol must be defined only once per module. - #define ENABLE_TYPE_INFO_NAMES 0 - #endif - - #if ENABLE_TYPE_INFO_NAMES - #define TYPE_INFO_NAME(n) #n - #else - #define TYPE_INFO_NAME(n) "" - #endif - #define TYPE_INFO_NAME_T(n) #n "<>" - -// Set of template functions for automatically returning the base element type for any scalar or array variable. - -template<class T> -inline T& ElemType(T* at) -{ return *at; } - -template<class T, size_t N> -inline T& ElemType(T (*at)[N]) -{ return **at; } - -template<class T, size_t N, size_t N2> -inline T& ElemType(T (*at)[N][N2]) -{ return ***at; } - -template<class T, size_t N, size_t N2, size_t N3> -inline T& ElemType(T (*at)[N][N2][N3]) -{ return ****at; } - -template<class T> -inline T& ValType([[maybe_unused]] T t) -{ static T _t; return _t; } - -//--------------------------------------------------------------------------- -// Macros for constructing StructInfos (invoked by AutoTypeInfo.h) - - #define DEFINE_TYPE_INFO(T, Type, Args) \ - template<> \ - const CTypeInfo&TypeInfo(const T*) \ - { static Type Info Args; return Info; } \ - - #define STRUCT_INFO_EMPTY_BODY(T) \ - { \ - static CStructInfo Info(#T, sizeof(T), alignof(T)); \ - return Info; \ - } \ - - #define STRUCT_INFO_EMPTY(T) \ - const CTypeInfo&T::TypeInfo() const \ - STRUCT_INFO_EMPTY_BODY(T) \ - - #define STRUCT_INFO_T_EMPTY(T, Key, Arg) \ - template<Key Arg> \ - STRUCT_INFO_EMPTY(T<Arg>) - - #define STRUCT_INFO_TYPE_EMPTY(T) \ - DEFINE_TYPE_INFO(T, CStructInfo, (#T, sizeof(T), alignof(T))) - - #define STRUCT_INFO_TYPE_T_EMPTY(T, TArgs, TDecl) \ - template TDecl const CTypeInfo&TypeInfo(const T TArgs*) \ - STRUCT_INFO_EMPTY_BODY(T TArgs) \ - -// Define TypeInfo for a primitive type, without string conversion. - #define TYPE_INFO_PLAIN(T) DEFINE_TYPE_INFO(T, CTypeInfo, (#T, sizeof(T), alignof(T))) - -// Define TypeInfo for a basic type (undecomposable as far as TypeInfo cares), with external string converters. - #define TYPE_INFO_BASIC(T) DEFINE_TYPE_INFO(T, TTypeInfo<T>, (#T)) - -// Variant for int types, allowing conversion between sizes. - #define TYPE_INFO_INT(T) DEFINE_TYPE_INFO(T, TIntTypeInfo<T>, (#T)) - - #define STRUCT_INFO_BEGIN(T) \ - const CTypeInfo&T::TypeInfo() const { \ - static CStructInfo::CVarInfo Vars[] = { \ - - #define STRUCT_INFO_END(T) \ - }; \ - static CStructInfo Info(#T, sizeof(T), alignof(T), ARRAY_VAR(Vars)); \ - return Info; \ - } - - #define BASE_INFO_ATTRS(BaseType, Attrs) \ - { ::TypeInfo((const BaseType*)this), "", Attrs, uint32((char*)static_cast<const BaseType*>(this) - (char*)this), 1, 1, 0, 0, 0 }, - - #define BASE_INFO(BaseType) BASE_INFO_ATTRS(BaseType, "") - - #define ALIAS_INFO_ATTRS(AliasName, VarName, Attrs) \ - { ::TypeInfo(&ElemType(&VarName)), TYPE_INFO_NAME(AliasName), Attrs, uint32((char*)&VarName - (char*)this), sizeof(VarName) / sizeof(ElemType(&VarName)), 0, 0, 0, 0 }, - - #define ALIAS_INFO_STRINGNAME_ATTR(AliasStringName, VarName, Attrs) \ - { ::TypeInfo(&ElemType(&VarName)), AliasStringName, Attrs, uint32((char*)&VarName - (char*)this), sizeof(VarName) / sizeof(ElemType(&VarName)), 0, 0, 0, 0 }, - - #define VAR_INFO_ATTRS(VarName, Attrs) \ - ALIAS_INFO_ATTRS(VarName, VarName, Attrs) - - #define VAR_INFO(VarName) \ - VAR_INFO_ATTRS(VarName, "") - - #define ALIAS_INFO(AliasName, VarName) \ - ALIAS_INFO_ATTRS(AliasName, VarName, "") - - #define ATTRS_INFO(Attrs) \ - { ::TypeInfo((void*)0), "", Attrs, 0, 0, 0, 0, 0, 0 }, - - #define BITFIELD_INFO(VarName, Bits) \ - { ::TypeInfo(&ValType(VarName)), TYPE_INFO_NAME(VarName), "", 0, Bits, 0, 1, 0, 0 }, - -// Conversion macros for older system. - #define STRUCT_BASE_INFO(BaseType) BASE_INFO(BaseType) - #define STRUCT_VAR_INFO(VarName, InfoName) VAR_INFO(VarName) - #define STRUCT_BITFIELD_INFO(VarName, VarType, Bits) BITFIELD_INFO(VarName, Bits) - -// Template versions - -template<class T> -Array<CTypeInfo const*> TypeInfoArray1(T const* pt) -{ - static CTypeInfo const* s_info = &::TypeInfo(pt); - return ArrayT(&s_info, 1); -} - - #define STRUCT_INFO_T_BEGIN(T, Key, Arg) \ - template<Key Arg> \ - STRUCT_INFO_BEGIN(T<Arg>) - - #define STRUCT_INFO_T_END(T, Key, Arg) \ - }; \ - static CStructInfo Info(#T "<>", sizeof(T<Arg>), alignof(T<Arg>), ARRAY_VAR(Vars), TypeInfoArray1((Arg*)0)); \ - return Info; \ - } - - #define STRUCT_INFO_T2_BEGIN(T, Key1, Arg1, Key2, Arg2) \ - template<Key1 Arg1, Key2 Arg2> \ - const CTypeInfo&T<Arg1, Arg2>::TypeInfo() const { \ - typedef T<Arg1, Arg2> TThis; \ - static CStructInfo::CVarInfo Vars[] = { \ - - #define STRUCT_INFO_T2_END(T, Key1, Arg1, Key2, Arg2) \ - }; \ - static CTypeInfo const* TemplateTypes[] = { &::TypeInfo((Arg1*)0), &::TypeInfo((Arg2*)0) }; \ - static CStructInfo Info(#T "<,>", sizeof(TThis), alignof(TThis), ARRAY_VAR(Vars), ARRAY_VAR(TemplateTypes)); \ - return Info; \ - } - - #define STRUCT_INFO_T_INSTANTIATE(T, TArgs) \ - template const CTypeInfo& T<TArgs>::TypeInfo() const; - -//--------------------------------------------------------------------------- -// Enum type info - - #if ENABLE_TYPE_INFO_NAMES - -// Enums represented as full CEnumInfo types, with string conversion. - #define ENUM_INFO_BEGIN(T) \ - template<> \ - const CTypeInfo&TypeInfo(const T*) { \ - static CEnumDef::SElem Elems[] = { \ - - #define ENUM_INFO_END(T) \ - }; \ - typedef TIntType<sizeof(T)>::TType TInt; \ - static CEnumInfo<TInt> Info(#T, ARRAY_VAR(Elems)); \ - return Info; \ - } \ - - #define ENUM_ELEM_INFO(Scope, Elem) \ - { Scope Elem, #Elem }, - - #else // ENABLE_TYPE_INFO_NAMES - -// Enums represented as simple types, with no elements or string conversion. - #define ENUM_INFO_BEGIN(T) \ - TYPE_INFO_PLAIN(T) \ - - #define ENUM_INFO_END(T) - #define ENUM_ELEM_INFO(Scope, Elem) - - #endif // ENABLE_TYPE_INFO_NAMES - -#endif // ENABLE_TYPE_INFO - -#endif // CRYINCLUDE_CRYCOMMON_TYPEINFO_IMPL_H diff --git a/Code/CryEngine/CryCommon/UnicodeBinding.h b/Code/CryEngine/CryCommon/UnicodeBinding.h deleted file mode 100644 index afa2d0cc88..0000000000 --- a/Code/CryEngine/CryCommon/UnicodeBinding.h +++ /dev/null @@ -1,985 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Note: The utilities in this file should typically not be used directly, -// consider including UnicodeFunctions.h or UnicodeIterator.h instead. -// -// (At least) the following string types can be bound with these helper functions: -// Types Input Output Null-Terminator -// CryStringT<T>, (::string, ::wstring): yes yes implied by type (also Stack and Fixed variants) -// std::basic_string<T>, std::string, std::wstring: yes yes implied by type -// QString: yes yes implied by type -// std::vector<T>, std::list<T>, std::deque<T>: yes yes not present -// T[] (fixed-length buffer): yes yes guaranteed to be emitted on output, accepted on input -// T * and size_t (user-specified-size buffer): no yes guaranteed to be emitted on output -// const T * (null-terminated string): yes no expected -// const T[] (literal): yes no implied as the last item in the array -// pair of iterators over T: yes no should not be included in the range -// uint32 (single UCS code-point): yes no not present -// If some other string type is not listed, you can still use it for input easily by passing begin/end iterators. -// Note: For all types, T can be any 8-bit, 16-bit or 32-bit integral or character type. -// Further T types may be processed by explicitly passing InputEncoding and OutputEncoding. -// We never actively tested such scenario's, so no guarantees on floating and user-defined types as code-units. - - -#pragma once - -#ifndef assert -// Some tools use CRT's assert, most engine and game modules use CryAssert.h (via platform.h maybe). -// We don't want to force a choice upon all code that uses Unicode utilities, so we just assume assert is defined. -#error This header uses assert macro, please provide an applicable definition before including UnicodeXXX.h -#endif - -#include "UnicodeEncoding.h" -#include <string.h> // For str(n)len and memcpy. -#include <wchar.h> // For wcs(n)len. -#include <stddef.h> // For size_t and ptrdiff_t. -#include <iterator> // For std::iterator_traits. -#include <string> // For std::basic_string. -#include <vector> // For std::vector. -#include <list> // For std::list. -#include <deque> // For std::deque. -#include <type_traits> // ... standard type-traits (as of C++11). - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define UNICODEBINDING_H_SECTION_1 1 -#define UNICODEBINDING_H_SECTION_2 2 -#endif - -// Forward declare the supported types. -// Before actually instantiating a binding however, you need to have the full definition included. -// Also, this allows us to work with QChar/QString as declared names without a dependency on Qt. -template<typename T, size_t S> -class CryStackStringT; -template<size_t S> -class CryFixedStringT; -template<size_t S> -class CryFixedWStringT; -template<typename T> -class CryStringLocalT; -template<typename T> -class CryStringT; -class QChar; -class QString; -namespace Unicode -{ - namespace Detail - { - // Import standard type traits. - // This requires C++11 compiler support. - using std::add_const; - using std::conditional; - using std::extent; - using std::integral_constant; - using std::is_arithmetic; - using std::is_array; - using std::is_base_of; - using std::is_const; - using std::is_convertible; - using std::is_integral; - using std::is_pointer; - using std::is_same; - using std::make_unsigned; - using std::remove_cv; - using std::remove_extent; - using std::remove_pointer; - - // SVoid<T>: - // Result type will be void if T is well-formed. - // Note: This is mostly used to test the presence of member types at compile-time. - template<typename T> - struct SVoid - { - typedef void type; - }; - - // SValidChar<T, InferEncoding, Input>: - // Determine if T is a valid character type in the given compile-time context. - // The InferEncoding flag is set if the encoding has to be detected automatically. - // The Input flag is set if the type is used for input (and not set if the type is used for output). - template<typename T, bool InferEncoding, bool Input> - struct SValidChar - { - typedef typename remove_cv<T>::type BaseType; - static const bool isArithmeticType = is_arithmetic<BaseType>::value; - static const bool isQChar = is_same<BaseType, QChar>::value; - static const bool isUsable = isArithmeticType || isQChar; - static const bool isValidQualified = !is_const<T>::value || Input; - static const bool isKnownSize = sizeof(T) == 1 || sizeof(T) == 2 || sizeof(T) == 4; - static const bool isValidInferred = isKnownSize || !InferEncoding; - static const bool value = isUsable && isValidQualified && isValidInferred; - }; - - // SPackedIterators<T>: - // A pair of iterators over some range. - // Note: Packing iterators into a single object allows us to pass them as a single argument like all other types. - template<typename T> - struct SPackedIterators - { - const T begin, end; - SPackedIterators(const T& _begin, const T& _end) - : begin(_begin) - , end(_end) {} - }; - - // SPackedBuffer<T>: - // A buffer-pointer/length tuple. - // Note: Packing them into a single object allows us to pass them as a single argument like all other types. - template<typename T> - struct SPackedBuffer - { - T buffer; - size_t size; - SPackedBuffer(T _buffer, size_t _size) - : buffer(_buffer) - , size(_size) {} - }; - - // SDependentType<T, X>: - // Makes the name of type T dependent on X (which is otherwise meaningless). - // Note: This is used to force two-phase lookup so we don't need the definition of T until instantiation. - // This way we can convince standards-compliant compilers Clang and GCC to not require definition of forward-declared types. - // Specifically, we forward-declare Qt's QString and QChar, for which the definition will never be available outside Editor. - template<typename T, int X> - struct SDependentType - { - typedef T type; - }; - - // EBind: - // Methods of binding a type for input and/or output. - // Note: These are used for tag-dispatch by binding functions, and are private to the implementation. - enum EBind - { // Input Output Description - eBind_Impossible, // No No Can't bind this type. - eBind_Iterators, // Yes Yes Bind by using begin() and end() member functions. - eBind_Data, // Yes Yes Bind by using data() and size() member functions. - eBind_Literal, // Yes No Bind a fixed size buffer (const element, aka string literal). - eBind_Buffer, // Yes No Bind a fixed size buffer (non-const element) that may be null-terminated. - eBind_PackedBuffer, // No Yes Bind a user-specified size buffer (non-const element). - eBind_NullTerminated, // Yes No Bind a null-terminated buffer of unknown length (C string). - eBind_CodePoint, // Yes No Bind a single code-point value. - }; - - // SBindIterator<T, InferEncoding>: - // Find the EBind for input from iterator pair of type T at compile-time. - // If the type is not supported, the resulting value will be eBind_Impossible - template<typename T, bool InferEncoding, typename HasValueType = void, typename HasIteratorCategory = void> - struct SBindIterator - { - typedef const void CharType; - static const EBind value = eBind_Impossible; - }; - template<typename T, bool InferEncoding, typename HasValueType, typename HasIteratorCategory> - struct SBindIterator<T*, InferEncoding, HasValueType, HasIteratorCategory> - { - typedef typename add_const<T>::type CharType; - static const bool isValid = SValidChar<CharType, InferEncoding, true>::value; - static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; - }; - template<typename T, bool InferEncoding> - struct SBindIterator<T, InferEncoding, - typename SVoid<typename T::value_type>::type, - typename SVoid<typename T::iterator_category>::type - > - { - typedef typename add_const<typename T::value_type>::type CharType; - typedef typename T::iterator_category IteratorCategory; - static const bool isInputIterator = is_base_of<std::input_iterator_tag, IteratorCategory>::value; - static const bool isValid = SValidChar<CharType, InferEncoding, true>::value; - static const EBind value = isValid && isInputIterator ? eBind_Iterators : eBind_Impossible; - }; - - // SBindObject<T, InferEncoding>: - // Find the EBind for input from object of type T at compile-time. - // If the type is not supported, the resulting value will be eBind_Impossible. - template<typename T, bool InferEncoding> - struct SBindObject - { - typedef typename add_const< - typename conditional< - is_array<T>::value, - typename remove_extent<T>::type, - typename remove_pointer<T>::type - >::type - >::type CharType; - static const size_t FixedSize = extent<T>::value; - COMPILE_TIME_ASSERT(!is_array<T>::value || FixedSize > 0); - static const bool isConstArray = is_array<T>::value && is_const<typename remove_extent<T>::type>::value; - static const bool isBufferArray = is_array<T>::value && !isConstArray; - static const bool isPointer = is_pointer<T>::value; - static const bool isCodePoint = is_integral<T>::value; - static const bool isValidChar = SValidChar<CharType, InferEncoding, true>::value; - static const EBind value = - !isValidChar ? eBind_Impossible : - isConstArray ? eBind_Literal : - isBufferArray ? eBind_Buffer : - isPointer ? eBind_NullTerminated : - isCodePoint ? eBind_CodePoint : - eBind_Impossible; - }; - template<typename CharT, typename Traits, typename Allocator, bool InferEncoding> - struct SBindObject<std::basic_string<CharT, Traits, Allocator>, InferEncoding> - { - typedef typename add_const<CharT>::type CharType; - static const bool isValid = SValidChar<CharT, InferEncoding, true>::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template<typename T, typename Allocator, bool InferEncoding> - struct SBindObject<std::vector<T, Allocator>, InferEncoding> - { - typedef typename add_const<T>::type CharType; - static const bool isValid = SValidChar<T, InferEncoding, true>::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template<typename T, typename Allocator, bool InferEncoding> - struct SBindObject<std::list<T, Allocator>, InferEncoding> - { - typedef typename add_const<T>::type CharType; - static const bool isValid = SValidChar<T, InferEncoding, true>::value; - static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; - }; - template<typename T, typename Allocator, bool InferEncoding> - struct SBindObject<std::deque<T, Allocator>, InferEncoding> - { - typedef typename add_const<T>::type CharType; - static const bool isValid = SValidChar<T, InferEncoding, true>::value; - static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; - }; - template<typename T, bool InferEncoding> - struct SBindObject<CryStringT<T>, InferEncoding> - { - typedef typename add_const<T>::type CharType; - static const bool isValid = SValidChar<T, InferEncoding, true>::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template<typename T, bool InferEncoding> - struct SBindObject<CryStringLocalT<T>, InferEncoding> - { - typedef typename add_const<T>::type CharType; - static const bool isValid = SValidChar<T, InferEncoding, true>::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template<typename T, size_t S, bool InferEncoding> - struct SBindObject<CryStackStringT<T, S>, InferEncoding> - { - typedef typename add_const<T>::type CharType; - static const bool isValid = SValidChar<T, InferEncoding, true>::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template<size_t S, bool InferEncoding> - struct SBindObject<CryFixedStringT<S>, InferEncoding> - { - typedef char CharType; - static const bool isValid = SValidChar<CharType, InferEncoding, true>::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template<size_t S, bool InferEncoding> - struct SBindObject<CryFixedWStringT<S>, InferEncoding> - { - typedef wchar_t CharType; - static const bool isValid = SValidChar<CharType, InferEncoding, true>::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template<bool InferEncoding> - struct SBindObject<QString, InferEncoding> - { - typedef const QChar CharType; - static const EBind value = eBind_Data; - }; - template<typename T, bool InferEncoding> - struct SBindObject<SPackedIterators<T>, InferEncoding> - { - typedef typename SBindIterator<T, InferEncoding>::CharType CharType; - static const EBind value = eBind_Iterators; - }; - - // SBindOutput<T, InferEncoding>: - // Find the EBind for output to object of type T at compile-time. - // If the type is not supported, the resulting value will be eBind_Impossible. - template<typename T, bool InferEncoding> - struct SBindOutput - { - typedef typename remove_extent<T>::type CharType; - static const size_t FixedSize = extent<T>::value; - static const bool isArray = is_array<T>::value; - static const bool isValid = SValidChar<typename remove_extent<T>::type, InferEncoding, false>::value; - static const EBind value = isArray && isValid ? eBind_Buffer : eBind_Impossible; - }; - template<typename OutputCharType, bool InferEncoding> - struct SBindOutput<SPackedBuffer<OutputCharType*>, InferEncoding> - { - typedef OutputCharType CharType; - static const bool isValid = SValidChar<CharType, InferEncoding, false>::value; - static const EBind value = isValid ? eBind_PackedBuffer : eBind_Impossible; - }; - template<typename CharT, typename Traits, typename Allocator, bool InferEncoding> - struct SBindOutput<std::basic_string<CharT, Traits, Allocator>, InferEncoding> - { - typedef CharT CharType; - static const bool isValid = SValidChar<CharT, InferEncoding, false>::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template<typename T, typename Allocator, bool InferEncoding> - struct SBindOutput<std::vector<T, Allocator>, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar<T, InferEncoding, false>::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template<typename T, typename Allocator, bool InferEncoding> - struct SBindOutput<std::list<T, Allocator>, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar<T, InferEncoding, false>::value; - static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; - }; - template<typename T, typename Allocator, bool InferEncoding> - struct SBindOutput<std::deque<T, Allocator>, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar<T, InferEncoding, false>::value; - static const EBind value = isValid ? eBind_Iterators : eBind_Impossible; - }; - template<typename T, bool InferEncoding> - struct SBindOutput<CryStringT<T>, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar<T, InferEncoding, false>::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template<typename T, bool InferEncoding> - struct SBindOutput<CryStringLocalT<T>, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar<T, InferEncoding, false>::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template<typename T, size_t S, bool InferEncoding> - struct SBindOutput<CryStackStringT<T, S>, InferEncoding> - { - typedef T CharType; - static const bool isValid = SValidChar<T, InferEncoding, false>::value; - static const EBind value = isValid ? eBind_Data : eBind_Impossible; - }; - template<bool InferEncoding> - struct SBindOutput<QString, InferEncoding> - { - typedef QChar CharType; - static const EBind value = eBind_Data; - }; - - // SInferEncoding<T>: - // Infers the encoding of the given character type. - // Note: This will always pick an UTF encoding type based on the size of the element type. - template<typename T, bool Input> - struct SInferEncoding - { - typedef SBindObject<T, true> ObjectType; - typedef SBindIterator<T, true> IteratorType; - typedef typename conditional< - IteratorType::value != eBind_Impossible, - typename IteratorType::CharType, - typename ObjectType::CharType - >::type CharType; - static const EEncoding value = - sizeof(CharType) == 1 ? eEncoding_UTF8 : - sizeof(CharType) == 2 ? eEncoding_UTF16 : - eEncoding_UTF32; - COMPILE_TIME_ASSERT(value != eEncoding_UTF32 || sizeof(CharType) == 4); - }; - - // SBindCharacter<T, Input>: - // Pick the base character type to use during input or output with this element type. - template<typename T, bool Input, bool Integral = is_integral<T>::value, bool IsQChar = is_same<QChar, typename remove_cv<T>::type>::value> - struct SBindCharacter - { - typedef typename make_unsigned<T>::type BaseType; // The standard doesn't define if a character type is signed or unsigned. - typedef typename remove_cv<BaseType>::type UnqualifiedType; - typedef typename conditional<Input, const UnqualifiedType, UnqualifiedType>::type type; - }; - template<typename T, bool Input> - struct SBindCharacter<T, Input, false, false> - { - COMPILE_TIME_ASSERT(is_arithmetic<T>::value); - typedef typename remove_cv<T>::type UnqualifiedType; - typedef typename conditional<Input, const UnqualifiedType, UnqualifiedType>::type type; - }; - template<typename T, bool Input> - struct SBindCharacter<T, Input, false, true> - { - typedef typename conditional<Input, const uint16, uint16>::type type; - typedef typename SDependentType<QChar, Input>::type ActuallyQChar; // Force two-phase name lookup on QChar. - COMPILE_TIME_ASSERT(sizeof(ActuallyQChar) == sizeof(type)); // In case Qt ever changes QChar. - }; - - // SBindPointer<T, Input>: - // Pick the pointer type to use during input or output with buffers (potentially inside string types). - template<typename T, bool Input> - struct SBindPointer - { - COMPILE_TIME_ASSERT(is_pointer<T>::value || is_array<T>::value); - typedef typename conditional< - is_pointer<T>::value, - typename remove_pointer<T>::type, - typename remove_extent<T>::type - >::type UnboundCharType; - typedef typename SBindCharacter<UnboundCharType, Input>::type BoundCharType; - typedef BoundCharType* type; - }; - - // SAutomaticallyDeduced: - // Placeholder type that is never defined, used by SRequire for SFINAE overloading. - struct SAutomaticallyDeduced; - - // SRequire<Expr, T>: - // Helper for SFINAE overloading. - // Similar to C++11's std::enable_if, which is not in boost (with that exact name anyway). - template<bool SFINAE, typename T = SAutomaticallyDeduced> - struct SRequire - { - typedef T type; - }; - template<typename T> - struct SRequire<false, T> {}; - - // SafeCast<T, SourceChar>: - // Cast a pointer to type T, but only allowing safe casts. - // This guards against bad code in other functions since it prevents unintended casts. - template<typename T, typename SourceChar> - inline T SafeCast(SourceChar* ptr, typename SRequire<is_integral<SourceChar>::value>::type* = 0) - { - // Allow casts from pointer-to-integral to unrelated pointer-to-integral, provided they are of the same size. - typedef typename remove_pointer<T>::type TargetChar; - COMPILE_TIME_ASSERT(is_integral<SourceChar>::value && is_integral<TargetChar>::value); - COMPILE_TIME_ASSERT(sizeof(SourceChar) == sizeof(TargetChar)); - return reinterpret_cast<T>(ptr); - } - template<typename T, typename SourceChar> - inline T SafeCast(SourceChar* ptr, typename SRequire<is_same<typename remove_cv<SourceChar>::type, QChar>::value>::type* = 0) - { - // Allow casts from pointer-to-QChar to unrelated pointer-to-integral, provided they are of the same size. - typedef typename remove_pointer<T>::type TargetChar; - COMPILE_TIME_ASSERT(is_integral<TargetChar>::value); - COMPILE_TIME_ASSERT(sizeof(SourceChar) == sizeof(TargetChar)); - return reinterpret_cast<T>(ptr); - } - template<typename T, typename SourceChar> - inline T SafeCast(SourceChar* ptr, typename SRequire<!is_integral<SourceChar>::value&& !is_same<typename remove_cv<SourceChar>::type, QChar>::value>::type* = 0) - { - // Any other casts that are allowed by C++. - return static_cast<T>(ptr); - } - - // SCharacterTrait<T>: - // Exposes some basic traits for a given character. - // Note: Map to (hopefully optimized) CRT functions where possible. - template<typename T, size_t Size = sizeof(T)* is_integral<T>::value> - struct SCharacterTrait - { - static size_t StrLen(const T* nts) // Fall-back strlen. - { - size_t result = 0; - while (*nts != 0) - { - ++nts; - ++result; - } - return result; - } - static size_t StrNLen(const T* ptr, size_t len) // Fall-back strnlen. - { - size_t result = 0; - while (*ptr != 0 && result != len) - { - ++ptr; - ++result; - } - return result; - } - }; - template<typename T> - struct SCharacterTrait<T, sizeof(char)> - { - static size_t StrLen(const T* nts) // Narrow CRT strlen. - { - return ::strlen(SafeCast<const char*>(nts)); - } - static size_t StrNLen(const T* ptr, size_t len) // Narrow CRT strnlen. - { - return ::strnlen(SafeCast<const char*>(ptr), len); - } - }; - template<typename T> - struct SCharacterTrait<T, sizeof(wchar_t)> - { - static size_t StrLen(const T* nts) // Wide CRT strlen. - { - return ::wcslen(SafeCast<const wchar_t*>(nts)); - } - static size_t StrNLen(const T* ptr, size_t len) // Wide CRT strnlen. - { -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION UNICODEBINDING_H_SECTION_1 - #include AZ_RESTRICTED_FILE(UnicodeBinding_h) -#endif - return ::wcsnlen(SafeCast<const wchar_t*>(ptr), len); -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION UNICODEBINDING_H_SECTION_2 - #include AZ_RESTRICTED_FILE(UnicodeBinding_h) -#endif - } - }; - - // void Feed(const SPackedIterators<InputIteratorType> &its, Sink &out, tag): - // Feeds the provided sink from provided packed iterator-range. - template<typename InputIteratorType, typename Sink> - inline void Feed(const SPackedIterators<InputIteratorType>& its, Sink& out, integral_constant<EBind, eBind_Iterators>) - { - typedef typename std::iterator_traits<InputIteratorType>::value_type UnboundCharType; - typedef typename SBindCharacter<UnboundCharType, true>::type BoundCharType; - for (InputIteratorType it = its.begin; it != its.end; ++it) - { - const UnboundCharType unbound = *it; - const BoundCharType bound = static_cast<BoundCharType>(unbound); - const uint32 item = static_cast<uint32>(bound); - out(item); - } - } - - // void Feed(const SPackedIterators<const InputCharType *> &its, Sink &out, tag): - // Feeds the provided sink from provided packed pointer-range. - // This is slightly better code-generation than using generic iterators. - template<typename InputCharType, typename Sink> - inline void Feed(const SPackedIterators<const InputCharType*>& its, Sink& out, integral_constant<EBind, eBind_Iterators>) - { - typedef typename SBindPointer<const InputCharType*, true>::type PointerType; - assert(reinterpret_cast<size_t>(its.begin) <= reinterpret_cast<size_t>(its.end) && "Invalid range specified"); - const size_t length = its.end - its.begin; - PointerType ptr = SafeCast<PointerType>(its.begin); - assert((ptr || !length) && "Passed a non-empty range containing a null-pointer"); - for (size_t i = 0; i < length; ++i, ++ptr) - { - const uint32 item = static_cast<uint32>(*ptr); - out(item); - } - } - - // void Feed(const InputStringType &in, Sink &out, tag): - // Feeds the provided sink from a container, using it's iterators. - // Note: Dispatches to one of the packed-range overloads. - template<typename InputStringType, typename Sink> - inline void Feed(const InputStringType& in, Sink& out, integral_constant<EBind, eBind_Iterators> tag) - { - typedef typename InputStringType::const_iterator IteratorType; - Detail::SPackedIterators<IteratorType> its(in.begin(), in.end()); - Feed(its, out, tag); - } - - // void Feed(const InputStringType &in, Sink &out, tag): - // Feeds the provided sink from a string-object's buffer. - template<typename InputStringType, typename Sink> - inline void Feed(const InputStringType& in, Sink& out, integral_constant<EBind, eBind_Data>) - { - typedef typename InputStringType::size_type SizeType; - typedef typename InputStringType::value_type ValueType; - typedef typename SBindPointer<const ValueType*, true>::type PointerType; - const SizeType length = in.size(); - if (length) - { - PointerType ptr = SafeCast<PointerType>(in.data()); - for (SizeType i = 0; i < length; ++i, ++ptr) - { - const uint32 item = static_cast<uint32>(*ptr); - out(item); - } - } - } - - // void Feed(const InputStringType &in, Sink &out, tag): - // Feeds the provided sink from a string-literal. - // Note: The literal is assumed to be null-terminated. - // It's possible that a const-element fixed-size-buffer is mistaken as a literal. - // However, we expect no-one uses such buffers that are not null-terminated already. - // If somehow this use-case is desired, either terminate the buffer, or remove const from the buffer, or pass iterators. - template<typename InputStringType, typename Sink> - inline void Feed(const InputStringType& in, Sink& out, integral_constant<EBind, eBind_Literal>) - { - COMPILE_TIME_ASSERT(is_array<InputStringType>::value && extent<InputStringType>::value > 0); - typedef typename SBindPointer<InputStringType, true>::type PointerType; - const size_t length = extent<InputStringType>::value - 1; - PointerType ptr = SafeCast<PointerType>(in); - assert(ptr[length] == 0 && "Literal is not null-terminated"); - for (size_t i = 0; i < length; ++i, ++ptr) - { - const uint32 item = static_cast<uint32>(*ptr); - out(item); - } - } - - // void Feed(const InputStringType &in, Sink &out, tag): - // Feeds the provided sink from a non-const-element fixed-size buffer. - // Note: The buffer is allowed to be null-terminated, but it's not required. - template<typename InputStringType, typename Sink> - inline void Feed(const InputStringType& in, Sink& out, integral_constant<EBind, eBind_Buffer>) - { - COMPILE_TIME_ASSERT(is_array<InputStringType>::value && extent<InputStringType>::value > 0); - typedef typename SBindPointer<InputStringType, true>::type PointerType; - typedef typename SBindPointer<InputStringType, true>::BoundCharType CharType; - const size_t length = extent<InputStringType>::value; - PointerType ptr = SafeCast<PointerType>(in); - for (size_t i = 0; i < length; ++i, ++ptr) - { - const CharType unbound = *ptr; - if (unbound == 0) - { - break; - } - const uint32 item = static_cast<uint32>(unbound); - out(item); - } - } - - // void Feed(const InputStringType &in, Sink &out, tag): - // Feeds the provided sink from a null-terminated C-style string. - template<typename InputStringType, typename Sink> - inline void Feed(const InputStringType& in, Sink& out, integral_constant<EBind, eBind_NullTerminated>) - { - COMPILE_TIME_ASSERT(is_pointer<InputStringType>::value); - typedef typename SBindPointer<InputStringType, true>::type PointerType; - typedef typename SBindPointer<InputStringType, true>::BoundCharType CharType; - PointerType ptr = SafeCast<PointerType>(in); - if (ptr) - { - while (true) - { - const CharType unbound = *ptr; - ++ptr; - if (unbound == 0) - { - break; - } - const uint32 item = static_cast<uint32>(unbound); - out(item); - } - } - } - - // void Feed(const InputCharType &in, Sink &out, tag): - // Feeds the provided sink from a single value (interpreted as an UCS code-point). - template<typename InputCharType, typename Sink> - inline void Feed(const InputCharType& in, Sink& out, integral_constant<EBind, eBind_CodePoint>) - { - COMPILE_TIME_ASSERT(is_arithmetic<InputCharType>::value); - const uint32 item = static_cast<uint32>(in); - out(item); - } - - // size_t EncodedLength(const SPackedIterators<InputIteratorType> &its, tag): - // Determines the length of the input sequence in a range of iterators. - template<typename InputIteratorType> - inline size_t EncodedLength(const SPackedIterators<InputIteratorType>& its, integral_constant<EBind, eBind_Iterators>) - { - return std::distance(its.begin, its.end); // std::distance will pick optimal implementation depending on iterator category. - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of an input container, which would otherwise be enumerated with iterators. - template<typename InputStringType> - inline size_t EncodedLength(const InputStringType& in, integral_constant<EBind, eBind_Iterators>) - { - return in.size(); // Can there be a container without size()? At the very least, not in the supported types. - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of the input container. The container uses contiguous element layout. - template<typename InputStringType> - inline size_t EncodedLength(const InputStringType& in, integral_constant<EBind, eBind_Data>) - { - return in.size(); - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of the input string-literal. This is a compile-time constant. - template<typename InputStringType> - inline size_t EncodedLength(const InputStringType& in, integral_constant<EBind, eBind_Literal>) - { - COMPILE_TIME_ASSERT(is_array<InputStringType>::value && extent<InputStringType>::value > 0); - return extent<InputStringType>::value - 1; - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of the input fixed-size-buffer. We look for an (optional) null-terminator in the buffer. - template<typename InputStringType> - inline size_t EncodedLength(const InputStringType& in, integral_constant<EBind, eBind_Buffer>) - { - COMPILE_TIME_ASSERT(is_array<InputStringType>::value && extent<InputStringType>::value > 0); - typedef typename remove_extent<InputStringType>::type CharType; - return SCharacterTrait<CharType>::StrNLen(in, extent<InputStringType>::value); - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of the input used-specified buffer. We look for an (optional) null-terminator in the buffer. - template<typename InputCharType> - inline size_t EncodedLength(const SPackedBuffer<InputCharType*>& in, integral_constant<EBind, eBind_PackedBuffer>) - { - return in.buffer ? SCharacterTrait<InputCharType>::StrNLen(in.buffer, in.size) : 0; - } - - // size_t EncodedLength(const InputStringType &in, tag): - // Determines the length of the input null-terminated c-style string. We just use strlen() if available. - template<typename InputStringType> - inline size_t EncodedLength(const InputStringType& in, integral_constant<EBind, eBind_NullTerminated>) - { - COMPILE_TIME_ASSERT(is_pointer<InputStringType>::value); - typedef typename remove_pointer<InputStringType>::type CharType; - return in ? SCharacterTrait<CharType>::StrLen(in) : 0; - } - - // size_t EncodedLength(const InputCharType &in, tag): - // Determines the length of a single UCS code-point. This is always 1. - template<typename InputCharType> - inline size_t EncodedLength([[maybe_unused]] const InputCharType& in, integral_constant<EBind, eBind_CodePoint>) - { - COMPILE_TIME_ASSERT(is_arithmetic<InputCharType>::value); - return 1; - } - - // const void *EncodedPointer(const SPackedIterators<const InputCharType *> &its, tag): - // Get a pointer to contiguous storage for an iterator range. - // Note: This can only work if the iterators are pointers, or the storage won't be guaranteed contiguous. - template<typename InputCharType> - inline const void* EncodedPointer(const SPackedIterators<const InputCharType*>& its, integral_constant<EBind, eBind_Iterators>) - { - return its.begin; - } - - // const void *EncodedPointer(const InputStringType &in, tag): - // Get a pointer to contiguous storage for string/vector object. - // Note: This can only work for containers that actually use contiguous storage, which is determined by the SBindXXX helpers. - template<typename InputStringType> - inline const void* EncodedPointer(const InputStringType& in, integral_constant<EBind, eBind_Data>) - { - return in.data(); - } - - // const void *EncodedPointer(const InputStringType &in, tag): - // Get a pointer to contiguous storage for a string-literal. - template<typename InputStringType> - inline const void* EncodedPointer(const InputStringType& in, integral_constant<EBind, eBind_Literal>) - { - COMPILE_TIME_ASSERT(is_array<InputStringType>::value && extent<InputStringType>::value > 0); - return in; // We can just let the array type decay to a pointer. - } - - // const void *EncodedPointer(const InputStringType &in, tag): - // Get a pointer to contiguous storage for a fixed-size-buffer. - template<typename InputStringType> - inline const void* EncodedPointer(const InputStringType& in, integral_constant<EBind, eBind_Buffer>) - { - COMPILE_TIME_ASSERT(is_array<InputStringType>::value && extent<InputStringType>::value > 0); - return in; // We can just let the array type decay to a pointer. - } - - // const void *EncodedPointer(const InputStringType &in, tag): - // Get a pointer to contiguous storage for a null-terminated c-style-string. - template<typename InputStringType> - inline const void* EncodedPointer(const InputStringType& in, integral_constant<EBind, eBind_NullTerminated>) - { - COMPILE_TIME_ASSERT(is_pointer<InputStringType>::value); - return in; // Implied - } - - // const void *EncodedPointer(const InputCharType &in, tag): - // Get a pointer to contiguous storage for a single UCS code-point. - template<typename InputCharType> - inline const void* EncodedPointer(const InputCharType& in, integral_constant<EBind, eBind_CodePoint>) - { - COMPILE_TIME_ASSERT(is_arithmetic<InputCharType>::value); - return ∈ // Take the address of the parameter (which is kept on the stack of the caller). - } - - // SWriteSink<T, Append, BindMethod>: - // A helper that performs writing to the type T and can be passed as Sink type to a trans-coder helper. - template<typename T, bool Append, EBind> - struct SWriteSink; - template<typename T, bool Append> - struct SWriteSink<T, Append, eBind_Iterators> - { - typedef typename T::value_type OutputCharType; - T& out; - SWriteSink(T& _out, size_t) - : out(_out) - { - if (!Append) - { - // If not appending, clear the object beforehand. - out.clear(); - } - } - void operator()(uint32 item) - { - const OutputCharType bound = static_cast<OutputCharType>(item); - out.push_back(bound); // We assume this can't fail and STL container takes care of memory. - } - void operator()(const void*, size_t); // Not implemented. - void HintSequence(uint32 length) {} // Don't care about sequences. - bool CanWrite() const { return true; } // Always writable - }; - template<typename T, bool Append> - struct SWriteSink<T, Append, eBind_Data> - { - typedef SBindPointer<typename T::value_type*, false> BindHelper; - typedef typename BindHelper::UnboundCharType CharType; - CharType* ptr; - SWriteSink(T& out, size_t length) - { - const size_t offset = Append ? out.size() : 0; - length += offset; - out.resize(length); // resize() can't fail without exceptions, so assert instead. - assert((out.size() == length) && "Buffer resize failed (out-of-memory?)"); - const CharType* base = length ? out.data() : 0; - ptr = const_cast<CharType*>(base + offset); - } - void operator()(uint32 item) - { - *SafeCast<typename BindHelper::type>(ptr) = static_cast<typename BindHelper::BoundCharType>(item); - ++ptr; - } - void operator()(const void* src, size_t length) - { - ::memcpy(ptr, src, length * sizeof(CharType)); - ptr += length; - } - void HintSequence([[maybe_unused]] uint32 length) {} // Don't care about sequences. - bool CanWrite() const { return true; } // Always writable - }; - template<typename P, bool Append> - struct SWriteSink<SPackedBuffer<P>, Append, eBind_PackedBuffer> - { - typedef typename remove_pointer<P>::type ElementType; - typedef SBindPointer<ElementType*, false> BindHelper; - typedef typename BindHelper::UnboundCharType CharType; - CharType* ptr; - CharType* const terminator; - SWriteSink(CharType* _terminator) - : terminator(_terminator) {} - SWriteSink(SPackedBuffer<P>& out, size_t) - : terminator(out.size && out.buffer ? out.buffer + out.size - 1 : 0) - { - const size_t offset = Append - ? EncodedLength(out, integral_constant<EBind, eBind_PackedBuffer>()) - : 0; - const size_t fixedOffset = Append && offset >= out.size - ? out.size - 1 // In case the buffer is already full and not terminated. - : offset; - CharType* base = static_cast<CharType*>(out.buffer); - ptr = terminator ? base + fixedOffset : 0; - } - ~SWriteSink() - { - if (ptr) - { - *ptr = 0; // Guarantees that the output is null-terminated. - } - } - void operator()(uint32 item) - { - if (ptr != terminator) // Guarantees we don't overflow the buffer. - { - *SafeCast<typename BindHelper::type>(ptr) = static_cast<typename BindHelper::BoundCharType>(item); - ++ptr; - } - } - void operator()(const void* src, size_t length) - { - const size_t maxLength = terminator - ptr; - if (length > maxLength) - { - length = maxLength; - } - ::memcpy(ptr, src, length * sizeof(CharType)); - ptr += length; - } - void HintSequence(uint32 length) - { - if (terminator && (ptr + length >= terminator)) - { - // This sequence will overflow the buffer. - // In this case, we prefer to not generate any part of the sequence. - // Terminate at the current position and flag as full. - *ptr = 0; - ptr = terminator; - } - } - bool CanWrite() const - { - return terminator != ptr; - } - }; - template<typename T, bool Append> - struct SWriteSink<T, Append, eBind_Buffer> // Uses above implementation with specialized constructor - : SWriteSink<SPackedBuffer<typename remove_extent<T>::type*>, Append, eBind_PackedBuffer> - { - typedef typename remove_extent<T>::type ElementType; - typedef SWriteSink<SPackedBuffer<ElementType*>, Append, eBind_PackedBuffer> Super; - typedef SBindPointer<ElementType*, false> BindHelper; - typedef typename BindHelper::UnboundCharType CharType; - SWriteSink(T& out, size_t) - : Super(out + extent<T>::value - 1) - { - const size_t offset = Append - ? EncodedLength(out, integral_constant<EBind, eBind_Buffer>()) - : 0; - const size_t fixedOffset = Append && offset >= extent<T>::value - ? extent<T>::value - 1 // In case the buffer is already full and not terminated. - : offset; - Super::ptr = out + fixedOffset; // Qualification for Super required for two-phase lookup. - } - }; - - // SIsBlockCopyable<InputType, OutputType>: - // Check if block-copy optimization is possible for these types. - // InputType should be an instantiation of SBindObject or SBindIterator. - // OutputType should be an instantiation of SBindOutput. - // Note: This doesn't take into account safe/unsafe conversions, just if the underlying storage types are compatible. - template<typename InputType, typename OutputType> - struct SIsBlockCopyable - { - template<EBind M> - struct SIsContiguous - { - static const bool value = - M == eBind_Data || - M == eBind_Literal || - M == eBind_Buffer || - M == eBind_PackedBuffer || - M == eBind_NullTerminated || - M == eBind_CodePoint; - }; - template<typename T> - struct SIsPointers - { - static const bool value = false; - }; - template<typename T> - struct SIsPointers<SPackedIterators<T*> > - { - static const bool value = true; - }; - typedef typename SBindCharacter<typename InputType::CharType, true>::type InputCharType; - typedef typename SBindCharacter<typename OutputType::CharType, false>::type OutputCharType; - static const bool isIntegral = is_integral<InputCharType>::value && is_integral<OutputCharType>::value; - static const bool isSameSize = sizeof(InputCharType) == sizeof(OutputCharType); - static const bool isInputContiguous = (SIsContiguous<InputType::value>::value || SIsPointers<InputType>::value); - static const bool isOutputContiguous = (SIsContiguous<OutputType::value>::value || SIsPointers<OutputType>::value); - static const bool value = isIntegral && isSameSize && isInputContiguous && isOutputContiguous; - }; - } -} diff --git a/Code/CryEngine/CryCommon/UnicodeEncoding.h b/Code/CryEngine/CryCommon/UnicodeEncoding.h deleted file mode 100644 index 5a661513e1..0000000000 --- a/Code/CryEngine/CryCommon/UnicodeEncoding.h +++ /dev/null @@ -1,766 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Generic Unicode encoding helpers. -// -// Defines encoding and decoding functions used by the higher-level functions. -// These are used by the various conversion functions in UnicodeFunctions.h and UnicodeIterator.h. -// Note: You can use these functions manually for low-level functionality, but we don't recommend that. -// In that case, you probably want to check inside the nested Detail namespace for the elementary bits. - - -#pragma once -#include "BaseTypes.h" // For uint8, uint16, uint32 -#include "CompileTimeAssert.h" // For COMPILE_TIME_ASSERT macro -namespace Unicode -{ - // Supported encoding/conversion types. - enum EEncoding - { - // UTF-8 encoding, see http://www.unicode.org/resources/utf8.html. - // Input and output are supported. - // Note: This format maps the entire UCS, where each code-point can take [1, 4] 8-bit code-units. - // Note: This is a strict super-set of Latin1/ISO-885901 as well as ASCII. - eEncoding_UTF8, - - // UTF-16 encoding, see http://tools.ietf.org/html/rfc2781. - // Input and output are supported. - // Note: This format maps the entire UCS, where each code-point can take [1, 2] 16-bit code-units. - eEncoding_UTF16, - - // UTF-32 encoding, see http://www.unicode.org/reports/tr17/. - // Input and output are supported. - // Note: This format maps the entire UCS, each code-point is stored in a single 32-bit code-unit. - eEncoding_UTF32, - - // ASCII encoding, see http://en.wikipedia.org/wiki/ASCII. - // Input and output are supported (any output UCS values out of supported range are mapped to question mark). - // Note: Only values [U+0000, U+007F] can be mapped. - eEncoding_ASCII, - - // Latin1, aka ISO-8859-1 encoding, see http://en.wikipedia.org/wiki/ISO/IEC_8859-1. - // Only input is supported. - // Note: This is a strict super-set of ASCII, it additionally maps [U+00A0, U+00FF]. - eEncoding_Latin1, - - // Windows ANSI codepage 1252, see http://en.wikipedia.org/wiki/Windows-1252. - // Only input is supported. - // Note: This is a strict super-set of ASCII and Latin1/ISO-8859-1, it maps some code-units from [0x80, 0x9F]. - eEncoding_Win1252, - }; - - // Methods of recovery from invalid encoded sequences. - enum EErrorRecovery - { - // No attempt to detect invalid encoding is performed, the input is assumed to be valid. - // If the input is not valid, the output is undefined (in debug, this condition will cause an assert to trigger). - eErrorRecovery_None, - - // When an invalidly encoded sequence is detected, the sequence is discarded (will not be part of the output). - // Typically used for logic/hashing purposes when the input is almost certainly valid. - eErrorRecovery_Discard, - - // When an invalidly encoded sequence is detected, the sequence is replaced with the replacement-character (U+FFFD). - // Typically used when the output sequence is used for UI display purposes. - eErrorRecovery_Replace, - - // When an invalidly encoded sequence is detected, the sequence is replaced with the eEncoding_Latin1 equivalent. - // If the sequence is also not valid Latin1 encoded, the sequence is discarded. - // Typically used when reading generic text files with 1-byte code-units. - // Note: This recovery method can only be used when decoding UTF-8. - eErrorRecovery_FallbackLatin1ThenDiscard, - - // When an invalidly encoded sequence is detected, the sequence is replaced with the eEncoding_Win1252 equivalent. - // If the sequence is also not valid codepage 1252 encoded, the sequence is discarded. - // Typically used when reading text files generated on Windows with 1-byte code-units. - // Note: This recovery method can only be used when decoding UTF-8. - eErrorRecovery_FallbackWin1252ThenDiscard, - - // When an invalidly encoded sequence is detected, the sequence is replaced with the eEncoding_Latin1 equivalent. - // If the sequence is also not valid Latin1 encoded, it is replaced with the replacement-character (U+FFFD). - // Typically used when reading generic text files with 1-byte code-units. - // Note: This recovery method can only be used when decoding UTF-8. - eErrorRecovery_FallbackLatin1ThenReplace, - - // When an invalidly encoded sequence is detected, the sequence is replaced with the eEncoding_Win1252 equivalent. - // If the sequence is also not valid codepage 1252 encoded, it is replaced with the replacement-character (U+FFFD). - // Typically used when reading text files generated on Windows with 1-byte code-units. - // Note: This recovery method can only be used when decoding UTF-8. - eErrorRecovery_FallbackWin1252ThenReplace, - }; - - namespace Detail - { - // Decode<Encoding, Safe>(state, unit): Decodes a single code-unit of an encoding into an UCS code-point. - // When Safe flag is set, encoding errors are detected so a fall-back encoding or other recovery method can be used. - // Interpret return value as follows: - // < 0x001FFFFF: Decoded codepoint (== return value), call again with next code-unit and clear state. - // < 0x80000000: Intermediate state returned, call again with next code-unit and the returned state. - // >= 0x80000000: Bad encoding detected, up to 16 bits (UTF-16) or 24 bits (UTF-8, last in lower bits) - // contain previous consumed values (does not happen if Safe == false). - template<EEncoding InputEncoding, bool Safe> - inline uint32 Decode(uint32 state, uint32 unit); - - // Some constant values used when encoding/decoding. - enum - { - cDecodeShiftRemaining = 26, // Where to store the remaining count in the state. - cDecodeOneRemaining = 1 << cDecodeShiftRemaining, // Remaining value of one. - cDecodeMaskRemaining = 3 << cDecodeShiftRemaining, // All possible remaining bits that can be used. - cDecodeLeadBit = 1 << 22, // All bits up to and including this one are reserved. - cDecodeErrorBit = 1 << 31, // Set if an error occurs during decoding. - cDecodeOverlongBit = 1 << 30, // Set if overlong sequence was used. - cDecodeSurrogateBit = 1 << 29, // Set if surrogate code-point decoded in UTF-8. - cDecodeInvalidBit = 1 << 28, // Set if invalid code-point decoded (U+FFFE/FFFF). - cDecodeSuccess = 0, // Placeholder to indicate no error occurred. - cCodepointMax = 0x10FFFF, // The maximum value of an UCS code-point. - cLeadSurrogateFirst = 0xD800, // The first valid UTF-16 lead-surrogate value. - cLeadSurrogateLast = 0xDBFF, // The last valid UTF-16 lead-surrogate value. - cTrailSurrogateFirst = 0xDC00, // The first valid UTF-16 trail-surrogate value. - cTrailSurrogateLast = 0xDFFF, // The last valid UTF-16 trail-surrogate value. - cReplacementCharacter = 0xFFFD, // The default replacement character. - }; - - // Validate the UTF-8 state of a multi-byte sequence. - // The safe decoder of UTF-8 will call this function when a full potential code-point has been decoded. - // This function is (at most) called for 50% of the decoded UTF-8 code-units, but likely at much lower frequency. - inline uint32 DecodeValidate8(uint32 state) - { - uint32 errorbits = (state >> 8) | cDecodeErrorBit; - state ^= (state & 0x400000) >> 1; // For 3-byte sequences, bit 5 of the lead byte needs to be cleared. - const uint32 cp = - (state & 0x3F) | - ((state & 0x3F00) >> 2) | - ((state & 0x3F0000) >> 4) | - ((state & 0x07000000) >> 6); - if (cp <= cCodepointMax) - { - if (cp >= cLeadSurrogateFirst && cp <= cTrailSurrogateLast) - { - errorbits += cDecodeSurrogateBit; // CESU-8 encoding might have been used. - } - else - { - uint32 minval = 0x80; - minval += (0x00400000 & state) ? 0x800 - 0x80 : 0; - minval += (0x40000000 & state) ? 0x10000 - 0x80 : 0; - if (cp >= minval) - { - if ((cp & 0xFFFFFFFEU) != 0xFFFEU) - { - return cp; // Valid code-point. - } - errorbits += cDecodeInvalidBit; // Invalid character used. - } - errorbits += cDecodeOverlongBit; // Overlong encoding used. - } - } - return errorbits; - } - - // Decode UTF-8, unsafe. - template<> - inline uint32 Decode<eEncoding_UTF8, false>(uint32 state, uint32 unit) - { - if (state == 0) // First byte. - { - unit = unit & 0xFF; - if (unit < 0xC0) - { - return unit; // Single-unit (ASCII). - } - uint32 remaining = (unit >> 4) - 0xC; - remaining += (remaining == 0); - return (unit & 0x1F) + (remaining << cDecodeShiftRemaining); // Lead byte of multi-byte. - } - state = (state << 6) + (unit & 0x3F) + (state & cDecodeMaskRemaining) - cDecodeOneRemaining; // Apply c-byte. - return state & ~cDecodeLeadBit; // Mask off the lead bits of a 4-byte sequence. - } - - // Decode UTF-8, safe - template<> - inline uint32 Decode<eEncoding_UTF8, true>(uint32 state, uint32 unit) - { - if (unit <= 0xF4) // Discard out-of-range values immediately. - { - if (state == 0) // First byte. - { - if (unit < 0x80) - { - return unit; // Single-byte. - } - if (unit < 0xC2) - { - return cDecodeErrorBit; // Invalid continuation byte (or illegal 0xC0/0xC1). - } - uint32 remaining = (unit >> 4) - 0xC; - remaining += (remaining == 0); - return unit + (remaining << cDecodeShiftRemaining); // Multi-byte. - } - if ((unit & 0xC0) == 0x80) - { - const uint32 remaining = (state & cDecodeMaskRemaining) - cDecodeOneRemaining; - state = (state << 8) + unit; - if (remaining != 0) - { - return state | remaining; // Intermediate byte of a multi-byte sequence. - } - return DecodeValidate8(state); // Final byte of a multi-byte sequence. - } - } - return cDecodeErrorBit | state; - } - - // Decode UTF-16, unsafe. - template<> - inline uint32 Decode<eEncoding_UTF16, false>(uint32 state, uint32 unit) - { - const bool bLead = (unit >= cLeadSurrogateFirst) && (unit <= cLeadSurrogateLast); - const uint32 initial = unit + (bLead << cDecodeShiftRemaining); - const uint32 pair = 0x10000 + ((state & 0x3FF) << 10) + (unit & 0x3FF); - return state == 0 ? initial : pair; - } - - // Decode UTF-16, safe. - template<> - inline uint32 Decode<eEncoding_UTF16, true>(uint32 state, uint32 unit) - { - const bool bTrail = (unit >= cTrailSurrogateFirst) && (unit <= cTrailSurrogateLast); - if (state != 0 && !bTrail) - { - return cDecodeErrorBit + (state & 0xFFFF); // Lead surrogate without trail surrogate - } - uint32 result = Decode<eEncoding_UTF16, false>(state, unit); - bool bValid = (result & 0xFFFFFFFEU) != 0xFFFEU; - return bValid ? result : result + cDecodeErrorBit + cDecodeInvalidBit; - } - - // Decode UTF-32, unsafe. - template<> - inline uint32 Decode<eEncoding_UTF32, false>([[maybe_unused]] uint32 state, uint32 unit) - { - return unit; - } - - // Decode UTF-32, safe. - template<> - inline uint32 Decode<eEncoding_UTF32, true>([[maybe_unused]] uint32 state, uint32 unit) - { - if (unit > cCodepointMax) - { - return cDecodeErrorBit; - } - if (unit >= cLeadSurrogateFirst && unit <= cTrailSurrogateLast) - { - return cDecodeErrorBit | cDecodeSurrogateBit; - } - if ((unit & 0xFFFEU) == 0xFFFEU) - { - return cDecodeErrorBit | cDecodeInvalidBit; - } - return unit; - } - - // Decode ASCII, unsafe. - template<> - inline uint32 Decode<eEncoding_ASCII, false>([[maybe_unused]] uint32 state, uint32 unit) - { - return unit; - } - - // Decode ASCII, safe. - template<> - inline uint32 Decode<eEncoding_ASCII, true>([[maybe_unused]] uint32 state, uint32 unit) - { - if (unit > 0x7F) - { - return cDecodeErrorBit; - } - return unit; - } - - // Decode Latin1, unsafe. - template<> - inline uint32 Decode<eEncoding_Latin1, false>([[maybe_unused]] uint32 state, uint32 unit) - { - return unit; - } - - // Decode Latin1, safe. - template<> - inline uint32 Decode<eEncoding_Latin1, true>([[maybe_unused]] uint32 state, uint32 unit) - { - if ((unit >= 0x80 && unit <= 0x9F) || (unit > 0xFF)) - { - return cDecodeErrorBit; - } - return unit; - } - - // Decode Windows CP-1252, unsafe. - template<> - inline uint32 Decode<eEncoding_Win1252, false>([[maybe_unused]] uint32 state, uint32 unit) - { - static const uint16 cp1252[] = - { - 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, - 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F, - 0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, - 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178, - }; - return (unit < 0x80 || unit > 0x9F) ? unit : cp1252[unit - 0x80]; - } - - // Decode Windows CP-1252, safe. - template<> - inline uint32 Decode<eEncoding_Win1252, true>(uint32 state, uint32 unit) - { - if (unit > 0xFF) - { - return cDecodeErrorBit; - } - uint32 result = Decode<eEncoding_Win1252, false>(state, unit); - if (!(unit < 0x80 || unit > 0x9F) && (result == unit)) - { - return cDecodeErrorBit; // Not defined in codepage 1252. - } - return result; - } - - // SBase<T>: - // Utility to apply empty-base-optimization on type T. - // Will fall back to a member if T is a reference type. - template<typename T, int Tag = 0> - struct SBase - : T - { - SBase(T base) - : T(base) {} - T& GetBase() { return *this; } - const T& GetBase() const { return *this; } - }; - template<typename T, int Tag> - struct SBase<T&, Tag> - { - T& base; - SBase(T& b) - : base(b) {} - T& GetBase() { return base; } - const T& GetBase() const { return base; } - }; - - // SDecoder<Encoding, Sink, Recovery>: - // Functor to decode UCS code-points from an input range. - // Recovery functor will be invoked as a fall-back if decoding fails. - // This allows ensuring all the output is valid (even if the input isn't). - // Note: The destructor will automatically flush any remaining (erroneous) state, you can also call Finalize(). - template<EEncoding InputEncoding, typename Sink, typename Recovery = void> - struct SDecoder - : SBase<Sink, 1> - , SBase<Recovery, 2> - { - uint32 state; - SDecoder(Sink sink, Recovery recovery = Recovery()) - : SBase<Sink, 1>(sink) - , SBase<Recovery, 2>(recovery) - , state(0) {} - SDecoder() { Finalize(); } - Recovery& recovery() { return SBase<Recovery, 2>::GetBase(); } - Sink& sink() { return SBase<Sink, 1>::GetBase(); } - void operator()(uint32 unit) - { - state = Detail::Decode<InputEncoding, true>(state, unit); - if (state <= 0x1FFFFF) - { - sink()(state); - state = 0; - } - else if (state & Detail::cDecodeErrorBit) - { - recovery()(sink(), state, unit); - state = 0; - } - } - void Finalize() - { - if (state) - { - recovery()(sink(), state, 0); - state = 0; - } - } - }; - - // SDecoder<Encoding, Sink>: - // Functor to decode to UCS code-points from an input range. - // No attempt to discover or recover from encoding errors is made, can only safely be used with known-valid input. - template<EEncoding InputEncoding, typename Sink> - struct SDecoder<InputEncoding, Sink, void> - : SBase<Sink> - { - uint32 state; - SDecoder(Sink sink) - : SBase<Sink>(sink) - , state(0) {} - Sink& sink() { return SBase<Sink>::GetBase(); } - void operator()(uint32 unit) - { - state = Detail::Decode<InputEncoding, false>(state, unit); - if (state <= 0x1FFFFF) - { - sink()(state); - state = 0; - } - } - void Finalize() {} - }; - - // SEncoder<Encoding, Sink>: - // Generic Unicode encoder functor. - // Encoding must be one an encoding type for which output is supported. - // The Sink type must have HintSequence member for UTF-8 and UTF-16 (although it may be a no-op). - // In general, you feed operator() with UCS code-points and it will emit code-units. - template<EEncoding OutputEncoding, typename Sink> - struct SEncoder - { - static const bool value = false; - }; - - // SEncoder<Encoding, Sink>: - // Specialization of ASCII encoder functor. - // Note: Any out-of-range character is mapped to question mark. - template<typename Sink> - struct SEncoder<eEncoding_ASCII, Sink> - : SBase<Sink> - { - static const bool value = true; - typedef uint8 value_type; - SEncoder(Sink sink) - : SBase<Sink>(sink) {} - void operator()(uint32 cp) - { - cp = cp < 0x80 ? cp : (uint32)'?'; - SBase<Sink>::GetBase()(value_type(cp)); - } - }; - - // SEncoder<Encoding, Sink>: - // Specialization of UTF-8 encoder functor. - template<typename Sink> - struct SEncoder<eEncoding_UTF8, Sink> - : SBase<Sink> - { - static const bool value = true; - typedef uint8 value_type; - SEncoder(Sink sink) - : SBase<Sink>(sink) {} - Sink& sink() { return SBase<Sink>::GetBase(); } - void operator()(uint32 cp) - { - if (cp < 0x80) - { - // Single byte sequence. - sink()(value_type(cp)); - } - else - { - // Expand 21-bit value to 32-bit. - uint32 bits = - (cp & 0x00003F) + - ((cp & 0x000FC0) << 2) + - ((cp & 0x03F000) << 4) + - ((cp & 0x1C0000) << 6); - - // Type of sequence. - const bool bSeq4 = (cp >= 0x10000); - const bool bSeq3 = (cp >= 0x800); - - // Mask lead-bytes and continuation-bytes. - uint32 mask = 0xEFE0C080; - mask ^= (bSeq3 << 14); - mask += (bSeq4 ? 0xA00000 : 0); - bits |= mask; - - // Length of the sequence. - const uint32 length = (uint32)bSeq4 + (uint32)bSeq3 + 1; - sink().HintSequence(length); - - // Sink the multi-byte sequence. - if (bSeq4) - { - sink()(value_type(bits >> 24)); - } - if (bSeq3) - { - sink()(value_type(bits >> 16)); - } - sink()(value_type(bits >> 8)); - sink()(value_type(bits)); - } - } - }; - - // SEncoder<Encoding, Sink>: - // Specialization of UTF-16 encoder functor. - template<typename Sink> - struct SEncoder<eEncoding_UTF16, Sink> - : SBase<Sink> - { - static const bool value = true; - typedef uint16 value_type; - SEncoder(Sink sink) - : SBase<Sink>(sink) {} - Sink& sink() { return SBase<Sink>::GetBase(); } - void operator()(uint32 cp) - { - if (cp < 0x10000) - { - // Single unit - sink()(value_type(cp)); - } - else - { - // We will generate two-element sequence - sink().HintSequence(2); - - // Surrogate pair - cp -= 0x10000; - uint32 lead = ((cp >> 10) & 0x3FF) + Detail::cLeadSurrogateFirst; - uint32 trail = (cp & 0x3FF) + Detail::cTrailSurrogateFirst; - sink()(value_type(lead)); - sink()(value_type(trail)); - } - } - }; - - // SEncoder<Encoding, Sink>: - // Specialization of UTF-32 encoder functor. - // Note: This is a no-op, but we want to be able to express UTF-32 just like the other encodings. - template<typename Sink> - struct SEncoder<eEncoding_UTF32, Sink> - : SBase<Sink> - { - static const bool value = true; - typedef uint32 value_type; - SEncoder(Sink sink) - : SBase<Sink>(sink) {} - void operator()(uint32 cp) - { - SBase<Sink>::GetBase()(value_type(cp)); - } - }; - - // SDecoder<Encoding, SEncoder<Encoding>, void>: - // Specialization for unsafe no-op trans-coding. - // Since the conversion is a no-op, no need to keep any state or do any computation. - // Note: For a decoding with a fallback, this is not possible since we can't guarantee the input is valid. - template<EEncoding SameEncoding, typename Sink> - struct SDecoder<SameEncoding, SEncoder<SameEncoding, Sink>, void> - { - Sink sink; - SDecoder(Sink s) - : sink(s) {} - void operator()(uint32 unit) - { - sink(unit); - } - void Finalize() {} - }; - - // SRecoveryDiscard<Sink>: - // Recovery handler that, on encoding error, discards the offending sequence. - template<typename Sink> - struct SRecoveryDiscard - { - SRecoveryDiscard() {} - void operator()([[maybe_unused]] Sink& sink, [[maybe_unused]] uint32 error, [[maybe_unused]] uint32 unit) {} - }; - - // SRecoveryReplace<Sink>: - // Recovery handler that, on encoding error, replaces the sequence with replacement-character (U+FFFD). - // Note: This implementation matches a whole invalid sequence, it could be changed to emit for every code-unit. - template<typename Sink> - struct SRecoveryReplace - { - SRecoveryReplace() {} - void operator()(Sink& sink, uint32 error, uint32 unit) { sink(cReplacementCharacter); } - }; - - // SRecoveryFallback<Sink>: - // Recovery handler that, on encoding error, falls back to another encoding. - // The fallback encoding must be stateless (ie: ASCII, Latin1 or Win1252). - // This type assumes an 8-bit primary encoding since the only viable fallback encodings are 8-bit. - template<typename Sink, EEncoding FallbackEncoding, typename NextFallback> - struct SRecoveryFallback - : NextFallback - { - SRecoveryFallback() - : NextFallback() {} - void operator()(Sink& sink, uint32 error, uint32 unit) - { - SDecoder<FallbackEncoding, Sink&, NextFallback&> fallback(sink, *static_cast<NextFallback*>(this)); - uint8 byte1(error >> 16); - uint8 byte2(error >> 8); - uint8 byte3(error); - uint8 byte4(unit); - if (byte1) - { - fallback(byte1); - } - if (byte1 | byte2) - { - fallback(byte2); - } - if (byte1 | byte2 | byte3) - { - fallback(byte3); - } - fallback(byte4); - } - }; - - // SRecoveryFallbackHelper<Sink, RecoveryMethod>: - // Helper to pick a SRecoveryFallback instantiation based on RecoveryMethod. - template<EEncoding OutputEncoding, typename Sink, EErrorRecovery RecoveryMethod> - struct SRecoveryFallbackHelper - { - // A compilation error here means RecoveryMethod value was unexpected here - COMPILE_TIME_ASSERT( - RecoveryMethod == eErrorRecovery_FallbackLatin1ThenDiscard || - RecoveryMethod == eErrorRecovery_FallbackLatin1ThenReplace || - RecoveryMethod == eErrorRecovery_FallbackWin1252ThenDiscard || - RecoveryMethod == eErrorRecovery_FallbackWin1252ThenReplace); - typedef SEncoder<OutputEncoding, Sink> SinkType; - static const EEncoding FallbackEncoding = - RecoveryMethod == eErrorRecovery_FallbackLatin1ThenDiscard || - RecoveryMethod == eErrorRecovery_FallbackLatin1ThenReplace - ? eEncoding_Latin1 : eEncoding_Win1252; - template<typename Dummy, bool WithDiscard> - struct Pick - { - typedef SRecoveryDiscard<SinkType> type; - }; - template<typename Dummy> - struct Pick<Dummy, false> - { - typedef SRecoveryReplace<SinkType> type; - }; - typedef typename Pick<Sink, - RecoveryMethod == eErrorRecovery_FallbackLatin1ThenDiscard || - RecoveryMethod == eErrorRecovery_FallbackWin1252ThenDiscard>::type NextFallback; - typedef SRecoveryFallback<SinkType, FallbackEncoding, NextFallback> RecoveryType; - typedef SDecoder<eEncoding_UTF8, SinkType, RecoveryType> FullType; - }; - - // STranscoderSelect<InputEncoding, OutputEncoding, Sink, RecoveryMethod>: - // Derives a chained decoder/encoder pair that performs code-unit -> code-unit transform. - // The RecoveryMethod template parameter determines the behavior during encoding. - // This is the basic way to perform trans-coding, and is the type instantiated by the higher-level functions. - template<EEncoding InputEncoding, EEncoding OutputEncoding, typename Sink, EErrorRecovery RecoveryMethod> - struct STranscoderSelect; - template<EEncoding InputEncoding, EEncoding OutputEncoding, typename Sink> - struct STranscoderSelect<InputEncoding, OutputEncoding, Sink, eErrorRecovery_None> - : SDecoder<InputEncoding, SEncoder<OutputEncoding, Sink>, void> - { - typedef SDecoder<InputEncoding, SEncoder<OutputEncoding, Sink>, void> TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template<EEncoding InputEncoding, EEncoding OutputEncoding, typename Sink> - struct STranscoderSelect<InputEncoding, OutputEncoding, Sink, eErrorRecovery_Discard> - : SDecoder<InputEncoding, SEncoder<OutputEncoding, Sink>, SRecoveryDiscard<SEncoder<OutputEncoding, Sink> > > - { - typedef SRecoveryDiscard<SEncoder<OutputEncoding, Sink> > RecoveryType; - typedef SDecoder<InputEncoding, SEncoder<OutputEncoding, Sink>, RecoveryType> TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template<EEncoding InputEncoding, EEncoding OutputEncoding, typename Sink> - struct STranscoderSelect<InputEncoding, OutputEncoding, Sink, eErrorRecovery_Replace> - : SDecoder<InputEncoding, SEncoder<OutputEncoding, Sink>, SRecoveryReplace<SEncoder<OutputEncoding, Sink> > > - { - typedef SRecoveryReplace<SEncoder<OutputEncoding, Sink> > RecoveryType; - typedef SDecoder<InputEncoding, SEncoder<OutputEncoding, Sink>, RecoveryType> TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template<EEncoding OutputEncoding, typename Sink> - struct STranscoderSelect<eEncoding_UTF8, OutputEncoding, Sink, eErrorRecovery_FallbackLatin1ThenDiscard> - : SRecoveryFallbackHelper<OutputEncoding, Sink, eErrorRecovery_FallbackLatin1ThenDiscard>::FullType - { - static const EErrorRecovery RecoveryMethod = eErrorRecovery_FallbackLatin1ThenDiscard; - typedef typename SRecoveryFallbackHelper<OutputEncoding, Sink, RecoveryMethod>::RecoveryType RecoveryType; - typedef typename SRecoveryFallbackHelper<OutputEncoding, Sink, RecoveryMethod>::FullType TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template<EEncoding OutputEncoding, typename Sink> - struct STranscoderSelect<eEncoding_UTF8, OutputEncoding, Sink, eErrorRecovery_FallbackLatin1ThenReplace> - : SRecoveryFallbackHelper<OutputEncoding, Sink, eErrorRecovery_FallbackLatin1ThenReplace>::FullType - { - static const EErrorRecovery RecoveryMethod = eErrorRecovery_FallbackLatin1ThenReplace; - typedef typename SRecoveryFallbackHelper<OutputEncoding, Sink, RecoveryMethod>::RecoveryType RecoveryType; - typedef typename SRecoveryFallbackHelper<OutputEncoding, Sink, RecoveryMethod>::FullType TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template<EEncoding OutputEncoding, typename Sink> - struct STranscoderSelect<eEncoding_UTF8, OutputEncoding, Sink, eErrorRecovery_FallbackWin1252ThenDiscard> - : SRecoveryFallbackHelper<OutputEncoding, Sink, eErrorRecovery_FallbackWin1252ThenDiscard>::FullType - { - static const EErrorRecovery RecoveryMethod = eErrorRecovery_FallbackWin1252ThenDiscard; - typedef typename SRecoveryFallbackHelper<OutputEncoding, Sink, RecoveryMethod>::RecoveryType RecoveryType; - typedef typename SRecoveryFallbackHelper<OutputEncoding, Sink, RecoveryMethod>::FullType TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - template<EEncoding OutputEncoding, typename Sink> - struct STranscoderSelect<eEncoding_UTF8, OutputEncoding, Sink, eErrorRecovery_FallbackWin1252ThenReplace> - : SRecoveryFallbackHelper<OutputEncoding, Sink, eErrorRecovery_FallbackWin1252ThenReplace>::FullType - { - static const EErrorRecovery RecoveryMethod = eErrorRecovery_FallbackWin1252ThenReplace; - typedef typename SRecoveryFallbackHelper<OutputEncoding, Sink, RecoveryMethod>::RecoveryType RecoveryType; - typedef typename SRecoveryFallbackHelper<OutputEncoding, Sink, RecoveryMethod>::FullType TranscoderType; - STranscoderSelect(Sink sink) - : TranscoderType(sink) {} - }; - - // SIsSafeEncoding<R>: - // Check if the given recovery mode is safe. - // This is used for SFINAE checks in higher-level functions. - template<EErrorRecovery R> - struct SIsSafeEncoding - { - static const bool value = - R == eErrorRecovery_Discard || - R == eErrorRecovery_Replace || - R == eErrorRecovery_FallbackLatin1ThenDiscard || - R == eErrorRecovery_FallbackLatin1ThenReplace || - R == eErrorRecovery_FallbackWin1252ThenDiscard || - R == eErrorRecovery_FallbackWin1252ThenReplace; - }; - - // SIsCopyableEncoding<I, O>: - // Check if data in one encoding can be copied directly to another encoding. - // This is the basis for block-copy and string-assign optimizations in un-safe conversion functions. - // Note: There are more valid combinations, they are left out since those can't occur with the output encodings supported. - // Note: Only used for un-safe functions since it doesn't account for potential invalid sequences (they would be copied over). - template<EEncoding InputEncoding, EEncoding OutputEncoding> - struct SIsCopyableEncoding - { - static const bool value = - InputEncoding == eEncoding_ASCII || // ASCII and Latin1 values don't change in any encoding. - (InputEncoding == eEncoding_Latin1 && OutputEncoding != eEncoding_ASCII); // Except Latin1 -> ASCII is lossy. - }; - template<EEncoding SameEncoding> - struct SIsCopyableEncoding<SameEncoding, SameEncoding> - { - static const bool value = true; // If the input and output encodings are the same, then it's copyable. - }; - } -} diff --git a/Code/CryEngine/CryCommon/UnicodeFunctions.h b/Code/CryEngine/CryCommon/UnicodeFunctions.h deleted file mode 100644 index 75d82ec0f1..0000000000 --- a/Code/CryEngine/CryCommon/UnicodeFunctions.h +++ /dev/null @@ -1,1264 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Generic Unicode string functions. -// -// Implements the following functions: -// Analyze: Reports all information on the input string, (length for all encodings, validity- and non-ASCII flags). -// Validate: Checks if the input string is valid encoded. -// Length: Reports the encoded length of some known-valid input, as-if it was encoded in the given output encoding. -// LengthSafe: Reports the encoded length of some input, as-if it was encoded in the given output encoding/recovery. -// Convert: Converts input from a known-valid string type/encoding to another string type/encoding. -// ConvertSafe: Converts and recovers encoding errors from one string type/encoding to another string type/encoding. -// Append: Appends input from a known-valid string type/encoding to another string type/encoding. -// AppendSafe: Appends and recovers encoding errors from one string type/encoding to another string type/encoding. -// -// Note: Ideally the safe functions should be used only once when accepting input from the user or from a file. -// Afterwards, the content is known-safe and the unsafe functions can be used for optimal performance. -// Using ConvertSafe once with a reasonable fall-back (depending on the where the input is from) should be the goal. -// -// Each function has several overloads: -// - One variant to handle a string object / buffer / pointer (1 arg), and one to handle iterators (2 args). -// - One variant with automatic encoding (picks UTF encoding depending on character size), and one for specific encoding. -// - One variant that returns a new string, and one that takes an existing string to overwrite (Convert(Safe) only). -// Each function takes one default argument that employs SFINAE to pick the correct overload depending on the arguments. - - -#pragma once -#include "UnicodeBinding.h" -namespace Unicode -{ - // Results of analysis of an input range of code-units (in any encoding). - // This is returned by calling Analyze() function. - struct SAnalysisResult - { - // The type to use for counting units. - // Can be changed to uint64_t for dealing with 4GB+ of string data. - typedef uint32 size_type; - - size_type inputUnits; // The number of input units analyzed. - size_type outputUnits8; // The number of output units when encoded with UTF-8. - size_type outputUnits16; // The number of output units when encoded with UTF-16. - size_type outputUnits32; // The number of output units when encoded with UTF-32 (aka number of UCS code-points). - size_type cpNonAscii; // The number of non-ASCII UCS code-points encountered. - size_type cpInvalid; // The number of invalid UCS code-point encountered (or 0xFFFFFFFF if not available). - - // Default constructor, initialize everything to zero. - SAnalysisResult() - : inputUnits(0) - , outputUnits8(0) - , outputUnits16(0) - , outputUnits32(0) - , cpInvalid(0) - , cpNonAscii(0) {} - - // Check if the input range was empty. - bool IsEmpty() const { return inputUnits == 0; } - - // Check if the input range only contained ASCII characters. - bool IsAscii() const { return cpNonAscii == 0; } - - // Check if the input range was valid (has no encoding errors). - // Note: This returns false if an unsafe decoder was used for analysis. - bool IsValid() const { return cpInvalid == 0; } - - // Get the length of the input range, in source code-units. - size_type LengthInSourceUnits() const { return inputUnits; } - - // Get the length of the input range, in UCS code-points. - size_type LengthInUCS() const { return outputUnits32; } - - // Get the length of the input range when encoded with the given encoding, in code-units. - // Note: If the encoding is not supported for output, the function returns 0. - size_type LengthInEncodingUnits(EEncoding encoding) const - { - switch (encoding) - { - case eEncoding_ASCII: - case eEncoding_UTF32: - return outputUnits32; - case eEncoding_UTF16: - return outputUnits16; - case eEncoding_UTF8: - return outputUnits8; - default: - return 0; - } - } - - // Get the length of the input range when encoded with the given encoding, in bytes. - // Note: If the encoding is not supported for output, the function returns 0. - size_type LengthInEncodingBytes(EEncoding encoding) const - { - size_type units = LengthInEncodingUnits(encoding); - switch (encoding) - { - case eEncoding_UTF32: - return units << 2; - case eEncoding_UTF16: - return units << 1; - default: - return units; - } - } - }; - - namespace Detail - { - // SDummySink: - // A sink implementation that does nothing. - struct SDummySink - { - void operator()([[maybe_unused]] uint32 unit) {} - void HintSequence([[maybe_unused]] uint32 length) {} - }; - - // SCountingSink: - // A sink that counts the number of units of output. - struct SCountingSink - { - size_t result; - - SCountingSink() - : result(0) {} - void operator()([[maybe_unused]] uint32 unit) { ++result; } - void HintSequence([[maybe_unused]] uint32 length) {} - }; - - // SAnalysisSink: - // A sink that updates analysis statistics. - struct SAnalysisSink - { - SAnalysisResult& result; - - SAnalysisSink(SAnalysisResult& _result) - : result(_result) {} - void operator()(uint32 cp) - { - const bool isCat2 = cp >= 0x80; - const bool isCat3 = cp >= 0x800; - const bool isCat4 = cp >= 0x10000; - result.outputUnits32 += 1; - result.outputUnits16 += (1 + isCat4); - result.outputUnits8 += (1 + isCat4 + isCat3 + isCat2); - result.cpNonAscii += isCat2; - } - void HintSequence([[maybe_unused]] uint32 length) {} - }; - - // SAnalysisRecovery: - // A recovery helper for analysis that counts invalid sequences. - struct SAnalysisRecovery - { - SAnalysisRecovery() {} - void operator()(SAnalysisSink& sink, [[maybe_unused]] uint32 error, [[maybe_unused]] uint32 unit) - { - sink.result.cpInvalid += 1; - } - }; - - // SValidationRecovery: - // A recovery helper for validation, it tracks if there is any invalid sequence. - struct SValidationRecovery - { - bool isValid; - - SValidationRecovery() - : isValid(true) {} - void operator()([[maybe_unused]] SDummySink& sink, [[maybe_unused]] uint32 error, [[maybe_unused]] uint32 unit) - { - isValid = false; - } - }; - - // SAnalyzer<InputEncoding>: - // Helper to perform analysis, counts the input for a given encoding. - template<EEncoding InputEncoding> - struct SAnalyzer - { - SDecoder<InputEncoding, SAnalysisSink, SAnalysisRecovery> decoder; - - SAnalyzer(SAnalysisResult& result) - : decoder(result) {} - void operator()(uint32 item) - { - decoder.sink().result.inputUnits += 1; - decoder(item); - } - }; - - // Analyze<InputEncoding>(target, source): - // Analyze string and store analysis result. - // This is the generic function called by other Analyze overloads. - template<EEncoding InputEncoding, typename InputStringType> - inline void Analyze(SAnalysisResult& target, const InputStringType& source) - { - // Bind methods. - const EBind bindMethod = SBindObject<InputStringType, false>::value; - integral_constant<EBind, bindMethod> tag; - - // Analyze using helper. - SAnalyzer<InputEncoding> analyzer(target); - Feed(source, analyzer, tag); - } - - // Validate<InputEncoding>(source): - // Tests that the string is valid encoding. - // This is the generic function called by other Validate overloads. - template<EEncoding InputEncoding, typename InputStringType> - inline bool Validate(const InputStringType& source) - { - // Bind methods. - const EBind bindMethod = SBindObject<InputStringType, false>::value; - integral_constant<EBind, bindMethod> tag; - - // Validate using helper. - SDummySink sink; - SDecoder<InputEncoding, SDummySink, SValidationRecovery> validator(sink); - Feed(source, validator, tag); - return validator.recovery().isValid; - } - - // Length<InputEncoding, OutputEncoding>(str): - // Find length of a string (in code-units) after trans-coding from InputEncoding to OutputEncoding. - // This is the generic function called by the other Length overloads. - template<EEncoding InputEncoding, EEncoding OutputEncoding, typename InputStringType> - inline size_t Length(const InputStringType& source) - { - // If this assert hits, consider using LengthSafe. - assert((Detail::Validate<InputEncoding, InputStringType>(source)) && "Length was used with non-safe input"); - - // Bind methods. - const EBind bindMethod = SBindObject<InputStringType, false>::value; - integral_constant<EBind, bindMethod> tag; - - // All copyable encodings have the property that the number of input encoding units equals the output units. - // In addition, this also holds for UTF-32 (always 1) -> ASCII (always 1), even though it's lossy. - const bool isCopyable = SIsCopyableEncoding<InputEncoding, OutputEncoding>::value; - const bool isCountable = isCopyable || (InputEncoding == eEncoding_UTF32 && OutputEncoding == eEncoding_ASCII); - - if (isCountable) - { - // Optimization: The number of input units is equal to the number of output units. - return EncodedLength(source, tag); - } - else - { - // We need to perform the conversion. - SCountingSink sink; - STranscoderSelect<InputEncoding, OutputEncoding, SCountingSink&, eErrorRecovery_None> transcoder(sink); - Feed(source, transcoder, tag); - return sink.result; - } - } - - // LengthSafe<InputEncoding, OutputEncoding, Recovery>(str): - // Find length of a string (in code-units) after trans-coding from InputEncoding to OutputEncoding. - // Note: The Recovery type used during conversion may influence the result, so this needs to match if you use the length information. - // This is the generic function called by the other LengthSafe overloads. - template<EEncoding InputEncoding, EEncoding OutputEncoding, EErrorRecovery Recovery, typename InputStringType> - inline size_t LengthSafe(const InputStringType& source) - { - // SRequire a safe recovery method. - COMPILE_TIME_ASSERT(SIsSafeEncoding<Recovery>::value); - - // Bind methods. - const EBind bindMethod = SBindObject<InputStringType, false>::value; - integral_constant<EBind, bindMethod> tag; - - // We can't optimize here, since we cannot assume the input is validly encoded - SCountingSink sink; - STranscoderSelect<InputEncoding, OutputEncoding, SCountingSink&, Recovery> transcoder(sink); - Feed(source, transcoder, tag); - return sink.result; - } - - // SBlockCopy<Enable, SinkType, Append, OutputMethod, InputStringType, OutputStringType>: - // Helper for block-copying entire string at once (as an optimization) - // This optimization will effectively try to memcpy or assign the whole string at once. - // Note: We need to do some partial specialization here to find out if the optimization is valid, so we can't use a function in C++98. - template<bool Enable, typename SinkType, bool Append, EBind OutputMethod, typename InputStringType, typename OutputStringType> - struct SBlockCopy - { - static const EBind bindMethod = SBindObject<InputStringType, false>::value; - typedef integral_constant<EBind, bindMethod> TagType; - size_t operator()(OutputStringType& target, const InputStringType& source) - { - // Optimization: Use block copying for these types. - TagType tag; - const size_t length = EncodedLength(source, tag); - SinkType sink(target, length); - if (sink.CanWrite()) - { - const void* const dataPtr = EncodedPointer(source, tag); - sink(dataPtr, length); - } - return length; - } - }; - - // SBlockCopy<Enable, SinkType, Append, OutputMethod, InputStringType, OutputStringType>: - // Specialization that will use direct string assignment. - // Note: This optimization is not selected when appending, this could be a future optimization if this is common. - // Reason for this is that the += operator is not present on all supported types (ie, std::vector) - template<typename SinkType, typename SameStringType> - struct SBlockCopy<true, SinkType, false, eBind_Data, SameStringType, SameStringType> - { - size_t operator()(SameStringType& target, const SameStringType& source) - { - // Optimization: Use copy assignment. - target = source; - return source.size(); - } - }; - - // SBlockCopy<Enable, SinkType, Append, OutputMethod, InputStringType, OutputStringType>: - // Fall-back specialization for Enable == false. - // Note: This specialization has to exist for the linker, but should never be called (and optimized away). - template<typename SinkType, bool Append, EBind OutputMethod, typename InputStringType, typename OutputStringType> - struct SBlockCopy<false, SinkType, Append, OutputMethod, InputStringType, OutputStringType> - { - size_t operator()([[maybe_unused]] OutputStringType& target, [[maybe_unused]] const InputStringType& source) - { - assert(false && "Should never be called"); - return 0; - } - }; - - // Convert<InputEncoding, OutputEncoding, Append>(target, source): - // Trans-code a string from InputEncoding to OutputEncoding. - // This is the generic function that is called by Convert and Append overloads. - // Returns the number of code-units required for full output (excluding any terminators) - template<EEncoding InputEncoding, EEncoding OutputEncoding, bool Append, typename InputStringType, typename OutputStringType> - inline size_t Convert(OutputStringType& target, const InputStringType& source) - { - // If this assert hits, consider using ConvertSafe. - assert((Detail::Validate<InputEncoding, InputStringType>(source)) && "Convert was used with non-safe input"); - - // Bind methods. - const EBind inputBindMethod = SBindObject<InputStringType, false>::value; - const EBind outputBindMethod = SBindOutput<OutputStringType, false>::value; - integral_constant<EBind, inputBindMethod> tag; - typedef SWriteSink<OutputStringType, Append, outputBindMethod> SinkType; - - // Check if we can optimize this. - const bool isCopyable = SIsCopyableEncoding<InputEncoding, OutputEncoding>::value; - const bool isBlocks = SIsBlockCopyable<SBindObject<InputStringType, false>, SBindOutput<OutputStringType, false> >::value; - const bool useBlockCopy = isCopyable && isBlocks; - size_t length; - if (useBlockCopy) - { - // Use optimized path. - SBlockCopy<useBlockCopy, SinkType, Append, outputBindMethod, InputStringType, OutputStringType> blockCopy; - length = blockCopy(target, source); - } - else - { - // We need to perform the conversion code-unit by code-unit. - length = Detail::Length<InputEncoding, OutputEncoding, InputStringType>(source); - SinkType sink(target, length); - if (sink.CanWrite()) - { - STranscoderSelect<InputEncoding, OutputEncoding, SinkType&, eErrorRecovery_None> transcoder(sink); - Feed(source, transcoder, tag); - } - } - return length; - } - - // ConvertSafe<InputEncoding, OutputEncoding, Append, Recovery>(target, source): - // Safely trans-code a string from InputEncoding to OutputEncoding using the specified Recovery to handle encoding errors. - // This is the generic function called by ConvertSafe and AppendSafe overloads. - template<EEncoding InputEncoding, EEncoding OutputEncoding, bool Append, EErrorRecovery Recovery, typename InputStringType, typename OutputStringType> - inline size_t ConvertSafe(OutputStringType& target, const InputStringType& source) - { - // SRequire a safe recovery method. - COMPILE_TIME_ASSERT(SIsSafeEncoding<Recovery>::value); - - // Bind methods. - const EBind inputBindMethod = SBindObject<InputStringType, false>::value; - const EBind outputBindMethod = SBindOutput<OutputStringType, false>::value; - integral_constant<EBind, inputBindMethod> tag; - typedef SWriteSink<OutputStringType, Append, outputBindMethod> SinkType; - - // We can't optimize with block-copy here, since we cannot assume the input is validly encoded. - const size_t length = Detail::LengthSafe<InputEncoding, OutputEncoding, Recovery, InputStringType>(source); - SinkType sink(target, length); - if (sink.CanWrite()) - { - STranscoderSelect<InputEncoding, OutputEncoding, SinkType&, Recovery> transcoder(sink); - Feed(source, transcoder, tag); - } - return length; - } - - // SReqAutoObj<T>: - // Require that T is usable as input object, with automatic encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template<typename T, EEncoding E = eEncoding_UTF8, EErrorRecovery R = eErrorRecovery_Discard> - struct SReqAutoObj - : SRequire< - SBindObject<T, true>::value != eBind_Impossible&& - SEncoder<E, SDummySink>::value&& - SIsSafeEncoding<R>::value - > {}; - - // SReqAutoIts<T>: - // Require that T is usable as input iterator, with automatic encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template<typename T, EEncoding E = eEncoding_UTF8, EErrorRecovery R = eErrorRecovery_Discard> - struct SReqAutoIts - : SRequire< - SBindIterator<T, true>::value != eBind_Impossible&& - SEncoder<E, SDummySink>::value&& - SIsSafeEncoding<R>::value - > {}; - - // SReqAnyObj<T>: - // Require that T is usable as input object, with user-specified encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template<typename T, EEncoding E = eEncoding_UTF8, EErrorRecovery R = eErrorRecovery_Discard> - struct SReqAnyObj - : SRequire< - SBindObject<T, false>::value != eBind_Impossible&& - SEncoder<E, SDummySink>::value&& - SIsSafeEncoding<R>::value - > {}; - - // SReqAnyIts<T>: - // Require that T is usable as input iterator, with user-specified encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template<typename T, EEncoding E = eEncoding_UTF8, EErrorRecovery R = eErrorRecovery_Discard> - struct SReqAnyIts - : SRequire< - SBindIterator<T, false>::value != eBind_Impossible&& - SEncoder<E, SDummySink>::value&& - SIsSafeEncoding<R>::value - > {}; - - // SReqAutoObjOut<I, O>: - // Require that I is usable as input object, and O as output object, with automatic encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template<typename I, typename O, bool S, EEncoding E = eEncoding_UTF8, EErrorRecovery R = eErrorRecovery_Discard> - struct SReqAutoObjOut - : SRequire< - SBindObject<I, true>::value != eBind_Impossible&& - SBindOutput<typename conditional<S, SPackedBuffer<O>, O>::type, true>::value != eBind_Impossible&& - SEncoder<E, SDummySink>::value&& - SIsSafeEncoding<R>::value - > {}; - - // SReqAutoItsOut<I, O>: - // Require that I is usable as input iterator, and O as output object, with automatic encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template<typename I, typename O, bool S, EEncoding E = eEncoding_UTF8, EErrorRecovery R = eErrorRecovery_Discard> - struct SReqAutoItsOut - : SRequire< - SBindIterator<I, true>::value != eBind_Impossible&& - SBindOutput<typename conditional<S, SPackedBuffer<O>, O>::type, true>::value != eBind_Impossible&& - SEncoder<E, SDummySink>::value&& - SIsSafeEncoding<R>::value - > {}; - - // SReqAnyObjOut<I, O>: - // Require that I is usable as input object, and O as output object, with user-specified encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template<typename I, typename O, bool S, EEncoding E, EErrorRecovery R = eErrorRecovery_Discard> - struct SReqAnyObjOut - : SRequire< - SBindObject<I, false>::value != eBind_Impossible&& - SBindOutput<typename conditional<S, SPackedBuffer<O>, O>::type, false>::value != eBind_Impossible&& - SEncoder<E, SDummySink>::value&& - SIsSafeEncoding<R>::value - > {}; - - // SReqAnyItsOut<I, O>: - // Require that I is usable as input object, and O as output object, with user-specified encoding. - // This is used as a SFINAE argument for overload resolution of the main functions. - template<typename I, typename O, bool S, EEncoding E, EErrorRecovery R = eErrorRecovery_Discard> - struct SReqAnyItsOut - : SRequire< - SBindIterator<I, false>::value != eBind_Impossible&& - SBindOutput<typename conditional<S, SPackedBuffer<O>, O>::type, false>::value != eBind_Impossible&& - SEncoder<E, SDummySink>::value&& - SIsSafeEncoding<R>::value - > {}; - } - - // SAnalysisResult Analyze<InputEncoding>(str): - // Analyze the given string with the given encoding, providing information on validity and encoding length. - template<EEncoding InputEncoding, typename InputStringType> - inline SAnalysisResult Analyze(const InputStringType& str, - typename Detail::SReqAnyObj<InputStringType>::type* = 0) - { - SAnalysisResult result; - Detail::Analyze<InputEncoding, InputStringType>(result, str); - return result; - } - - // SAnalysisResult Analyze(str): - // Analyze the (assumed) Unicode string input, providing information on validity and encoding length. - // The Unicode encoding is picked automatically depending on the input type. - template<typename InputStringType> - inline SAnalysisResult Analyze(const InputStringType& str, - typename Detail::SReqAutoObj<InputStringType>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputStringType, true>::value; - SAnalysisResult result; - Detail::Analyze<InputEncoding, InputStringType>(result, str); - return result; - } - - // SAnalysisResult Analyze<InputEncoding>(begin, end): - // Analyze the given range with the given encoding, providing information on validity and encoding length. - template<EEncoding InputEncoding, typename InputIteratorType> - inline SAnalysisResult Analyze(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyIts<InputIteratorType>::type* = 0) - { - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - SAnalysisResult result; - Detail::Analyze<InputEncoding, InputStringType>(result, its); - return result; - } - - // SAnalysisResult Analyze(begin, end): - // Analyze the given (assumed) Unicode range, providing information on validity and encoding length. - // The Unicode encoding is picked automatically depending on the input type. - template<typename InputIteratorType> - inline SAnalysisResult Analyze(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoIts<InputIteratorType>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputIteratorType, true>::value; - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - SAnalysisResult result; - Detail::Analyze<InputEncoding, InputStringType>(result, its); - return result; - } - - // bool Validate<InputEncoding>(str): - // Checks if the given string is valid in the given encoding. - template<EEncoding InputEncoding, typename InputStringType> - inline bool Validate(const InputStringType& str, - typename Detail::SReqAnyObj<InputStringType>::type* = 0) - { - return Detail::Validate<InputEncoding, InputStringType>(str); - } - - // bool Validate(str): - // Checks if the given string is a valid Unicode string. - // The Unicode encoding is picked automatically depending on the input type. - template<typename InputStringType> - inline bool Validate(const InputStringType& str, - typename Detail::SReqAutoObj<InputStringType>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputStringType, true>::value; - return Detail::Validate<InputEncoding, InputStringType>(str); - } - - // bool Validate<InputEncoding>(begin, end): - // Checks if the given range is valid in the given encoding. - template<EEncoding InputEncoding, typename InputIteratorType> - inline bool Validate(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyIts<InputIteratorType>::type* = 0) - { - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - return Detail::Validate<InputEncoding, InputStringType>(its); - } - - // bool Validate(begin, end): - // Checks if the given range is valid Unicode. - // The Unicode encoding is picked automatically depending on the input type. - template<typename InputIteratorType> - inline bool Validate(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoIts<InputIteratorType>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputIteratorType, true>::value; - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - return Detail::Validate<InputEncoding, InputStringType>(its); - } - - // size_t Length<OutputEncoding, InputEncoding>(str): - // Get the length (in OutputEncoding) of the given known-valid string with the given InputEncoding. - // Note: Length assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use LengthSafe. - template<EEncoding OutputEncoding, EEncoding InputEncoding, typename InputStringType> - inline size_t Length(const InputStringType& str, - typename Detail::SReqAnyObj<InputStringType, OutputEncoding>::type* = 0) - { - return Detail::Length<InputEncoding, OutputEncoding, InputStringType>(str); - } - - // size_t Length<OutputEncoding>(str): - // Get the length (in OutputEncoding) of the given known-valid Unicode string. - // The Unicode encoding is picked automatically depending on the input type. - // Note: Length assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use LengthSafe. - template<EEncoding OutputEncoding, typename InputStringType> - inline size_t Length(const InputStringType& str, - typename Detail::SReqAutoObj<InputStringType, OutputEncoding>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputStringType, true>::value; - return Detail::Length<InputEncoding, OutputEncoding, InputStringType>(str); - } - - // size_t Length<OutputEncoding, InputEncoding>(begin, end): - // Get the length (in OutputEncoding) of the known-valid range with the given InputEncoding. - // Note: Length assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use LengthSafe. - template<EEncoding OutputEncoding, EEncoding InputEncoding, typename InputIteratorType> - inline size_t Length(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyIts<InputIteratorType, OutputEncoding>::type* = 0) - { - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - return Detail::Length<InputEncoding, OutputEncoding, InputStringType>(its); - } - - // size_t Length<OutputEncoding>(begin, end): - // Get the length (in OutputEncoding) of the known-valid Unicode range. - // The Unicode encoding is picked automatically depending on the input type. - // Note: Length assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use LengthSafe. - template<EEncoding OutputEncoding, typename InputIteratorType> - inline size_t Length(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoIts<InputIteratorType>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputIteratorType, true>::value; - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - return Detail::Length<InputEncoding, OutputEncoding, InputStringType>(its); - } - - // size_t LengthSafe<Recovery, OutputEncoding, InputEncoding>(str): - // Get the length (in OutputEncoding) of the given string with the given InputEncoding. - // Note: LengthSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Length. - template<EErrorRecovery Recovery, EEncoding OutputEncoding, EEncoding InputEncoding, typename InputStringType> - inline size_t LengthSafe(const InputStringType& str, - typename Detail::SReqAnyObj<InputStringType, OutputEncoding, Recovery>::type* = 0) - { - return Detail::LengthSafe<InputEncoding, OutputEncoding, Recovery, InputStringType>(str); - } - - // size_t LengthSafe<Recovery, OutputEncoding>(str): - // Get the length (in OutputEncoding) of the given Unicode string. - // The Unicode encoding is picked automatically depending on the input type. - // Note: LengthSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Length. - template<EErrorRecovery Recovery, EEncoding OutputEncoding, typename InputStringType> - inline size_t LengthSafe(const InputStringType& str, - typename Detail::SReqAutoObj<InputStringType, OutputEncoding, Recovery>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputStringType, true>::value; - return Detail::LengthSafe<InputEncoding, OutputEncoding, Recovery, InputStringType>(str); - } - - // size_t LengthSafe<Recovery, OutputEncoding, InputEncoding>(begin, end): - // Get the length (in OutputEncoding) of the range with the given InputEncoding. - // Note: LengthSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Length. - template<EErrorRecovery Recovery, EEncoding OutputEncoding, EEncoding InputEncoding, typename InputIteratorType> - inline size_t LengthSafe(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyIts<InputIteratorType, OutputEncoding, Recovery>::type* = 0) - { - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - return Detail::LengthSafe<InputEncoding, OutputEncoding, Recovery, InputStringType>(its); - } - - // size_t LengthSafe<Recovery, OutputEncoding>(begin, end): - // Get the length (in OutputEncoding) of the Unicode range. - // The Unicode encoding is picked automatically depending on the input type. - // Note: LengthSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Length. - template<EErrorRecovery Recovery, EEncoding OutputEncoding, typename InputIteratorType> - inline size_t LengthSafe(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoIts<InputIteratorType, OutputEncoding, Recovery>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputIteratorType, true>::value; - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - return Detail::LengthSafe<InputEncoding, OutputEncoding, Recovery, InputStringType>(its); - } - - // OutputStringType &Convert<OutputEncoding, InputEncoding>(result, str): - // Converts the given string in the given input encoding and stores into the result string with the given output encoding. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template<EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputStringType, typename InputStringType> - inline OutputStringType& Convert(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAnyObjOut<InputStringType, OutputStringType, false, OutputEncoding>::type* = 0) - { - Detail::Convert<InputEncoding, OutputEncoding, false, InputStringType, OutputStringType>(result, str); - return result; - } - - // OutputStringType &Convert(result, str): - // Converts the (assumed) Unicode string input and stores into the result Unicode string. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template<typename OutputStringType, typename InputStringType> - inline OutputStringType& Convert(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAutoObjOut<InputStringType, OutputStringType, false>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputStringType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputStringType, false>::value; - Detail::Convert<InputEncoding, OutputEncoding, false, InputStringType, OutputStringType>(result, str); - return result; - } - - // OutputStringType &Convert<OutputEncoding, InputEncoding>(result, begin, end): - // Converts the given range in the given input encoding and stores into the result string with the given output encoding. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template<EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputStringType, typename InputIteratorType> - inline OutputStringType& Convert(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut<InputIteratorType, OutputStringType, false, OutputEncoding>::type* = 0) - { - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - Detail::Convert<InputEncoding, OutputEncoding, false, InputStringType, OutputStringType>(result, its); - return result; - } - - // OutputStringType &Convert(result, begin, end): - // Converts the (assumed) Unicode range and stores into the result Unicode string. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template<typename OutputStringType, typename InputIteratorType> - inline OutputStringType& Convert(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut<InputIteratorType, OutputStringType, false>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputIteratorType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputStringType, false>::value; - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - Detail::Convert<InputEncoding, OutputEncoding, false, InputStringType, OutputStringType>(result, its); - return result; - } - - // size_t Convert<OutputEncoding, InputEncoding>(buffer, length, str): - // Converts the given string in the given input encoding and stores into the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template<EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputCharType, typename InputStringType> - inline size_t Convert(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAnyObjOut<InputStringType, OutputCharType*, true, OutputEncoding>::type* = 0) - { - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - OutputStringType result(buffer, length); - return Detail::Convert<InputEncoding, OutputEncoding, false, InputStringType, OutputStringType>(result, str) + 1; - } - - // size_t Convert(buffer, length, str): - // Converts the (assumed) Unicode string input and stores into the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the buffer type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template<typename OutputCharType, typename InputStringType> - inline size_t Convert(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAutoObjOut<InputStringType, OutputCharType*, true>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputStringType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputCharType*, false>::value; - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - OutputStringType result(buffer, length); - return Detail::Convert<InputEncoding, OutputEncoding, false, InputStringType, OutputStringType>(result, str) + 1; - } - - // size_t Convert<OutputEncoding, InputEncoding>(buffer, length, begin, end): - // Converts the given range in the given input encoding and stores into the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template<EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputCharType, typename InputIteratorType> - inline size_t Convert(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut<InputIteratorType, OutputCharType*, true, OutputEncoding>::type* = 0) - { - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert<InputEncoding, OutputEncoding, false, InputStringType, OutputStringType>(result, its) + 1; - } - - // size_t Convert(buffer, length, begin, end): - // Converts the (assumed) Unicode range and stores into the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template<typename OutputCharType, typename InputIteratorType> - inline size_t Convert(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut<InputIteratorType, OutputCharType*, true>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputIteratorType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputCharType*, false>::value; - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert<InputEncoding, OutputEncoding, false, InputStringType, OutputStringType>(result, its) + 1; - } - - // OutputStringType Convert<OutputStringType, OutputEncoding, InputEncoding>(str): - // Converts the given string in the given input encoding to a new string of the given type and output encoding. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template<typename OutputStringType, EEncoding OutputEncoding, EEncoding InputEncoding, typename InputStringType> - inline OutputStringType Convert(const InputStringType& str, - typename Detail::SReqAnyObjOut<InputStringType, OutputStringType, false, OutputEncoding>::type* = 0) - { - OutputStringType result; - Detail::Convert<InputEncoding, OutputEncoding, false, InputStringType, OutputStringType>(result, str); - return result; - } - - // OutputStringType Convert<OutputStringType>(str): - // Converts the (assumed) Unicode string input to a new Unicode string of the given type. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template<typename OutputStringType, typename InputStringType> - inline OutputStringType Convert(const InputStringType& str, - typename Detail::SReqAutoObjOut<InputStringType, OutputStringType, false>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputStringType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputStringType, false>::value; - OutputStringType result; - Detail::Convert<InputEncoding, OutputEncoding, false, InputStringType, OutputStringType>(result, str); - return result; - } - - // OutputStringType Convert<OutputStringType, OutputEncoding, InputEncoding>(begin, end): - // Converts the given range in the given input encoding to a new string of the given type and output encoding. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template<typename OutputStringType, EEncoding OutputEncoding, EEncoding InputEncoding, typename InputIteratorType> - inline OutputStringType Convert(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut<InputIteratorType, OutputStringType, false, OutputEncoding>::type* = 0) - { - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - OutputStringType result; - Detail::Convert<InputEncoding, OutputEncoding, false, InputStringType, OutputStringType>(result, its); - return result; - } - - // OutputStringType Convert<OutputStringType>(begin, end): - // Converts the (assumed) Unicode range to a new Unicode string of the given type. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: Convert assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use ConvertSafe. - template<typename OutputStringType, typename InputIteratorType> - inline OutputStringType Convert(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut<InputIteratorType, OutputStringType, false>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputIteratorType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputStringType, false>::value; - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - OutputStringType result; - Detail::Convert<InputEncoding, OutputEncoding, false, InputStringType, OutputStringType>(result, its); - return result; - } - - // OutputStringType &ConvertSafe<Recovery, OutputEncoding, InputEncoding>(result, str): - // Converts the given string in the given input encoding and stores into the result string with the given output encoding. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template<EErrorRecovery Recovery, EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputStringType, typename InputStringType> - inline OutputStringType& ConvertSafe(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAnyObjOut<InputStringType, OutputStringType, false, OutputEncoding, Recovery>::type* = 0) - { - Detail::ConvertSafe<InputEncoding, OutputEncoding, false, Recovery, InputStringType, OutputStringType>(result, str); - return result; - } - - // OutputStringType &ConvertSafe<Recovery>(result, str): - // Converts the (assumed) Unicode string input and stores into the result Unicode string. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template<EErrorRecovery Recovery, typename OutputStringType, typename InputStringType> - inline OutputStringType& ConvertSafe(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAutoObjOut<InputStringType, OutputStringType, false, eEncoding_UTF8, Recovery>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputStringType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputStringType, false>::value; - Detail::ConvertSafe<InputEncoding, OutputEncoding, false, Recovery, InputStringType, OutputStringType>(result, str); - return result; - } - - // OutputStringType &ConvertSafe<Recovery, OutputEncoding, InputEncoding>(result, begin, end): - // Converts the given range in the given input encoding and stores into the result string with the given output encoding. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template<EErrorRecovery Recovery, EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputStringType, typename InputIteratorType> - inline OutputStringType& ConvertSafe(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut<InputIteratorType, OutputStringType, false, OutputEncoding, Recovery>::type* = 0) - { - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - Detail::ConvertSafe<InputEncoding, OutputEncoding, false, Recovery, InputStringType, OutputStringType>(result, its); - return result; - } - - // OutputStringType &ConvertSafe<Recovery>(result, begin, end): - // Converts the (assumed) Unicode range and stores into the result Unicode string. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template<EErrorRecovery Recovery, typename OutputStringType, typename InputIteratorType> - inline OutputStringType& ConvertSafe(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut<InputIteratorType, OutputStringType, false, eEncoding_UTF8, Recovery>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputIteratorType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputStringType, false>::value; - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - Detail::ConvertSafe<InputEncoding, OutputEncoding, false, Recovery, InputStringType, OutputStringType>(result, its); - return result; - } - - // size_t ConvertSafe<Recovery, OutputEncoding, InputEncoding>(buffer, length, str): - // Converts the given string in the given input encoding and stores into the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template<EErrorRecovery Recovery, EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputCharType, typename InputStringType> - inline size_t ConvertSafe(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAnyObjOut<InputStringType, OutputCharType*, true, OutputEncoding, Recovery>::type* = 0) - { - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - OutputStringType result(buffer, length); - return Detail::ConvertSafe<InputEncoding, OutputEncoding, false, Recovery, InputStringType, OutputStringType>(result, str) + 1; - } - - // size_t ConvertSafe<Recovery>(buffer, length, str): - // Converts the (assumed) Unicode string input and stores into the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the buffer type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template<EErrorRecovery Recovery, typename OutputCharType, typename InputStringType> - inline size_t ConvertSafe(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAutoObjOut<InputStringType, OutputCharType*, true, eEncoding_UTF8, Recovery>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputStringType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputCharType*, false>::value; - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - OutputStringType result(buffer, length); - return Detail::ConvertSafe<InputEncoding, OutputEncoding, false, Recovery, InputStringType, OutputStringType>(result, str) + 1; - } - - // size_t ConvertSafe<Recovery, OutputEncoding, InputEncoding>(buffer, length, begin, end): - // Converts the given range in the given input encoding and stores into the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template<EErrorRecovery Recovery, EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputCharType, typename InputIteratorType> - inline size_t ConvertSafe(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut<InputIteratorType, OutputCharType*, true, OutputEncoding, Recovery>::type* = 0) - { - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::ConvertSafe<InputEncoding, OutputEncoding, false, Recovery, InputStringType, OutputStringType>(result, its) + 1; - } - - // size_t ConvertSafe<Recovery>(buffer, length, begin, end): - // Converts the (assumed) Unicode range and stores into the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template<EErrorRecovery Recovery, typename OutputCharType, typename InputIteratorType> - inline size_t ConvertSafe(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut<InputIteratorType, OutputCharType*, true, eEncoding_UTF8, Recovery>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputIteratorType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputCharType*, false>::value; - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert<InputEncoding, OutputEncoding, false, InputStringType, OutputStringType>(result, its) + 1; - } - - // OutputStringType ConvertSafe<Recovery, OutputStringType, OutputEncoding, InputEncoding>(str): - // Converts the given string in the given input encoding to a new string of the given type and output encoding. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template<EErrorRecovery Recovery, typename OutputStringType, EEncoding OutputEncoding, EEncoding InputEncoding, typename InputStringType> - inline OutputStringType ConvertSafe(const InputStringType& str, - typename Detail::SReqAnyObjOut<InputStringType, OutputStringType, false, OutputEncoding, Recovery>::type* = 0) - { - OutputStringType result; - Detail::ConvertSafe<InputEncoding, OutputEncoding, false, Recovery, InputStringType, OutputStringType>(result, str); - return result; - } - - // OutputStringType ConvertSafe<Recovery, OutputStringType>(str): - // Converts the (assumed) Unicode string input to a new Unicode string of the given type. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template<EErrorRecovery Recovery, typename OutputStringType, typename InputStringType> - inline OutputStringType ConvertSafe(const InputStringType& str, - typename Detail::SReqAutoObjOut<InputStringType, OutputStringType, false, eEncoding_UTF8, Recovery>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputStringType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputStringType, false>::value; - OutputStringType result; - Detail::ConvertSafe<InputEncoding, OutputEncoding, false, Recovery, InputStringType, OutputStringType>(result, str); - return result; - } - - // OutputStringType ConvertSafe<Recovery, OutputStringType, OutputEncoding, InputEncoding>(begin, end): - // Converts the given range in the given input encoding to a new string of the given type and output encoding. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template<EErrorRecovery Recovery, typename OutputStringType, EEncoding OutputEncoding, EEncoding InputEncoding, typename InputIteratorType> - inline OutputStringType ConvertSafe(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut<InputIteratorType, OutputStringType, false, OutputEncoding, Recovery>::type* = 0) - { - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - OutputStringType result; - Detail::ConvertSafe<InputEncoding, OutputEncoding, false, Recovery, InputStringType, OutputStringType>(result, its); - return result; - } - - // OutputStringType ConvertSafe<Recovery, OutputStringType>(begin, end): - // Converts the (assumed) Unicode range to a new Unicode string of the given type. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: ConvertSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Convert. - template<EErrorRecovery Recovery, typename OutputStringType, typename InputIteratorType> - inline OutputStringType ConvertSafe(InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut<InputIteratorType, OutputStringType, false, eEncoding_UTF8, Recovery>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputIteratorType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputStringType, false>::value; - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - OutputStringType result; - Detail::ConvertSafe<InputEncoding, OutputEncoding, false, Recovery, InputStringType, OutputStringType>(result, its); - return result; - } - - // OutputStringType &Append<OutputEncoding, InputEncoding>(result, str): - // Appends the given string in the given input encoding and stores at the end of the result string with the given output encoding. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template<EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputStringType, typename InputStringType> - inline OutputStringType& Append(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAnyObjOut<InputStringType, OutputStringType, false, OutputEncoding>::type* = 0) - { - Detail::Convert<InputEncoding, OutputEncoding, true, InputStringType, OutputStringType>(result, str); - return result; - } - - // OutputStringType &Append(result, str): - // Appends the (assumed) Unicode string input and stores at the end of the result Unicode string. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template<typename OutputStringType, typename InputStringType> - inline OutputStringType& Append(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAutoObjOut<InputStringType, OutputStringType, false>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputStringType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputStringType, false>::value; - Detail::Convert<InputEncoding, OutputEncoding, true, InputStringType, OutputStringType>(result, str); - return result; - } - - // OutputStringType &Append<OutputEncoding, InputEncoding>(result, begin, end): - // Appends the given range in the given input encoding and stores at the end of the result string with the given output encoding. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template<EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputStringType, typename InputIteratorType> - inline OutputStringType& Append(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut<InputIteratorType, OutputStringType, false, OutputEncoding>::type* = 0) - { - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - Detail::Convert<InputEncoding, OutputEncoding, true, InputStringType, OutputStringType>(result, its); - return result; - } - - // OutputStringType &Append(result, begin, end): - // Appends the (assumed) Unicode range and stores at the end of the result Unicode string. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template<typename OutputStringType, typename InputIteratorType> - inline OutputStringType& Append(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut<InputIteratorType, OutputStringType, false>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputIteratorType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputStringType, false>::value; - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - Detail::Convert<InputEncoding, OutputEncoding, true, InputStringType, OutputStringType>(result, its); - return result; - } - - // size_t Append<OutputEncoding, InputEncoding>(buffer, length, str): - // Appends the given string in the given input encoding to the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template<EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputCharType, typename InputStringType> - inline size_t Append(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAnyObjOut<InputStringType, OutputCharType*, true, OutputEncoding>::type* = 0) - { - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - OutputStringType result(buffer, length); - return Detail::Convert<InputEncoding, OutputEncoding, true, InputStringType, OutputStringType>(result, str) + 1; - } - - // size_t Append(buffer, length, str): - // Appends the (assumed) Unicode string input to the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the buffer type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template<typename OutputCharType, typename InputStringType> - inline size_t Append(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAutoObjOut<InputStringType, OutputCharType*, true>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputStringType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputCharType*, false>::value; - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - OutputStringType result(buffer, length); - return Detail::Convert<InputEncoding, OutputEncoding, true, InputStringType, OutputStringType>(result, str) + 1; - } - - // size_t Append<OutputEncoding, InputEncoding>(buffer, length, begin, end): - // Appends the given range in the given input encoding to the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template<EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputCharType, typename InputIteratorType> - inline size_t Append(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut<InputIteratorType, OutputCharType*, true, OutputEncoding>::type* = 0) - { - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert<InputEncoding, OutputEncoding, true, InputStringType, OutputStringType>(result, its) + 1; - } - - // size_t Append(buffer, length, begin, end): - // Appends the (assumed) Unicode range to the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: Append assumes the input is valid encoded, if this is not guaranteed (ie, user-input), use AppendSafe. - template<typename OutputCharType, typename InputIteratorType> - inline size_t Append(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut<InputIteratorType, OutputCharType*, true>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputIteratorType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputCharType*, false>::value; - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert<InputEncoding, OutputEncoding, true, InputStringType, OutputStringType>(result, its) + 1; - } - - // OutputStringType &AppendSafe<Recovery, OutputEncoding, InputEncoding>(result, str): - // Appends the given string in the given input encoding and stores at the end of the result string with the given output encoding. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template<EErrorRecovery Recovery, EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputStringType, typename InputStringType> - inline OutputStringType& AppendSafe(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAnyObjOut<InputStringType, OutputStringType, false, OutputEncoding, Recovery>::type* = 0) - { - Detail::ConvertSafe<InputEncoding, OutputEncoding, true, Recovery, InputStringType, OutputStringType>(result, str); - return result; - } - - // OutputStringType &AppendSafe<Recovery>(result, str): - // Appends the (assumed) Unicode string input and stores at the end of the result Unicode string. - // The Unicode encodings are picked automatically depending on the input type and output type. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template<EErrorRecovery Recovery, typename OutputStringType, typename InputStringType> - inline OutputStringType& AppendSafe(OutputStringType& result, const InputStringType& str, - typename Detail::SReqAutoObjOut<InputStringType, OutputStringType, false, eEncoding_UTF8, Recovery>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputStringType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputStringType, false>::value; - Detail::ConvertSafe<InputEncoding, OutputEncoding, true, Recovery, InputStringType, OutputStringType>(result, str); - return result; - } - - // OutputStringType &AppendSafe<Recovery, OutputEncoding, InputEncoding>(result, begin, end): - // Appends the given range in the given input encoding and stores at the end of the result string with the given output encoding. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template<EErrorRecovery Recovery, EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputStringType, typename InputIteratorType> - inline OutputStringType& AppendSafe(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut<InputIteratorType, OutputStringType, false, OutputEncoding, Recovery>::type* = 0) - { - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - Detail::ConvertSafe<InputEncoding, OutputEncoding, true, Recovery, InputStringType, OutputStringType>(result, its); - return result; - } - - // OutputStringType &AppendSafe<Recovery>(result, begin, end): - // Appends the (assumed) Unicode range and stores at the end of the result Unicode string. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template<EErrorRecovery Recovery, typename OutputStringType, typename InputIteratorType> - inline OutputStringType& AppendSafe(OutputStringType& result, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut<InputIteratorType, OutputStringType, false, eEncoding_UTF8, Recovery>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputIteratorType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputStringType, false>::value; - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - const InputStringType its(begin, end); - Detail::ConvertSafe<InputEncoding, OutputEncoding, true, Recovery, InputStringType, OutputStringType>(result, its); - return result; - } - - // size_t AppendSafe<Recovery, OutputEncoding, InputEncoding>(buffer, length, str): - // Appends the given string in the given input encoding to the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template<EErrorRecovery Recovery, EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputCharType, typename InputStringType> - inline size_t AppendSafe(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAnyObjOut<InputStringType, OutputCharType*, true, OutputEncoding, Recovery>::type* = 0) - { - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - OutputStringType result(buffer, length); - return Detail::ConvertSafe<InputEncoding, OutputEncoding, true, Recovery, InputStringType, OutputStringType>(result, str) + 1; - } - - // size_t AppendSafe<Recovery>(buffer, length, str): - // Appends the (assumed) Unicode string input to the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the buffer type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template<EErrorRecovery Recovery, typename OutputCharType, typename InputStringType> - inline size_t AppendSafe(OutputCharType* buffer, size_t length, const InputStringType& str, - typename Detail::SReqAutoObjOut<InputStringType, OutputCharType*, true, eEncoding_UTF8, Recovery>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputStringType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputCharType*, false>::value; - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - OutputStringType result(buffer, length); - return Detail::ConvertSafe<InputEncoding, OutputEncoding, true, Recovery, InputStringType, OutputStringType>(result, str) + 1; - } - - // size_t AppendSafe<Recovery, OutputEncoding, InputEncoding>(buffer, length, begin, end): - // Appends the given range in the given input encoding to the result buffer with the given output encoding. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template<EErrorRecovery Recovery, EEncoding OutputEncoding, EEncoding InputEncoding, typename OutputCharType, typename InputIteratorType> - inline size_t AppendSafe(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAnyItsOut<InputIteratorType, OutputCharType*, true, OutputEncoding, Recovery>::type* = 0) - { - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::ConvertSafe<InputEncoding, OutputEncoding, true, Recovery, InputStringType, OutputStringType>(result, its) + 1; - } - - // size_t AppendSafe<Recovery>(buffer, length, begin, end): - // Appends the (assumed) Unicode range to the result Unicode buffer. - // The Unicode encodings are picked automatically depending on the range type and output type. - // Returns the required length of the output buffer, in code-units, including the null-terminator. - // Note: AppendSafe uses the specified Recovery parameter to fix encoding errors, if the input is known-valid, use Append. - template<EErrorRecovery Recovery, typename OutputCharType, typename InputIteratorType> - inline size_t AppendSafe(OutputCharType* buffer, size_t length, InputIteratorType begin, InputIteratorType end, - typename Detail::SReqAutoItsOut<InputIteratorType, OutputCharType*, true, eEncoding_UTF8, Recovery>::type* = 0) - { - const EEncoding InputEncoding = Detail::SInferEncoding<InputIteratorType, true>::value; - const EEncoding OutputEncoding = Detail::SInferEncoding<OutputCharType*, false>::value; - typedef Detail::SPackedIterators<InputIteratorType> InputStringType; - typedef Detail::SPackedBuffer<OutputCharType*> OutputStringType; - const InputStringType its(begin, end); - OutputStringType result(buffer, length); - return Detail::Convert<InputEncoding, OutputEncoding, true, InputStringType, OutputStringType>(result, its) + 1; - } -} diff --git a/Code/CryEngine/CryCommon/UnicodeIterator.h b/Code/CryEngine/CryCommon/UnicodeIterator.h deleted file mode 100644 index 2ffe942df5..0000000000 --- a/Code/CryEngine/CryCommon/UnicodeIterator.h +++ /dev/null @@ -1,614 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Encoded Unicode sequence iteration. -// -// For lower level accessing of encoded text, an STL compatible iterator wrapper is provided. -// This iterator will decode the underlying sequence, abstracting it to a sequence of UCS code-points. -// Using the iterator wrapper, you can find where in an encoded string code-points (or encoding errors) are located. -// Note: The iterator is an input-only iterator, you cannot write to the underlying sequence. - - -#pragma once -#include "UnicodeBinding.h" -namespace Unicode -{ - namespace Detail - { - // MoveNext(it, checker, tag): - // Moves the iterator to the next UCS code-point in the encoded sequence. - // Non-specialized version (for 1:1 code-unit to code-point). - template<typename BaseIterator, typename BoundsChecker, EEncoding Encoding> - inline void MoveNext(BaseIterator& it, const BoundsChecker& checker, const integral_constant<EEncoding, Encoding>) - { - COMPILE_TIME_ASSERT( - Encoding == eEncoding_ASCII || - Encoding == eEncoding_UTF32 || - Encoding == eEncoding_Latin1 || - Encoding == eEncoding_Win1252); - assert(!checker.IsEnd(it) && "Attempt to iterate past the end of the sequence"); - - // All of these encodings use a single code-unit for each code-point. - ++it; - } - - // MoveNext(it, checker, tag): - // Moves the iterator to the next UCS code-point in the encoded sequence. - // Specialized for UTF-8. - template<typename BaseIterator, typename BoundsChecker> - inline void MoveNext(BaseIterator& it, const BoundsChecker& checker, integral_constant<EEncoding, eEncoding_UTF8>) - { - assert(!checker.IsEnd(it) && "Attempt to iterate past the end of the sequence"); - - // UTF-8: just need to skip up to 3 continuation bytes. - for (int i = 0; i < 4; ++i) - { - ++it; - if (checker.IsEnd(it)) // :WARN: always returns false if "safe" bool is false! - { - break; - } - uint32 val = static_cast<uint32>(*it); - if ((val & 0xC0) != 0x80) - { - break; - } - } - } - - // MoveNext(it, checker, tag): - // Moves the iterator to the next UCS code-point in the encoded sequence. - // Specialized for UTF-16. - template<typename BaseIterator, typename BoundsChecker> - inline void MoveNext(BaseIterator& it, const BoundsChecker& checker, integral_constant<EEncoding, eEncoding_UTF16>) - { - assert(!checker.IsEnd(it) && "Attempt to iterate past the end of the sequence"); - - // UTF-16: just need to skip one lead surrogate. - ++it; - uint32 val = static_cast<uint32>(*it); - if (val >= cLeadSurrogateFirst && val <= cLeadSurrogateLast) - { - if (!checker.IsEnd(it)) - { - ++it; - } - } - } - - // MovePrev(it, checker, tag): - // Moves the iterator to the previous UCS code-point in the encoded sequence. - // Non-specialized version (for 1:1 code-unit to code-point). - template<typename BaseIterator, typename BoundsChecker, EEncoding Encoding> - inline void MovePrev(BaseIterator& it, const BoundsChecker& checker, const integral_constant<EEncoding, Encoding>) - { - COMPILE_TIME_ASSERT( - Encoding == eEncoding_ASCII || - Encoding == eEncoding_UTF32 || - Encoding == eEncoding_Latin1 || - Encoding == eEncoding_Win1252); - assert(!checker.IsBegin(it) && "Attempt to iterate past the beginning of the sequence"); - - // All of these encodings use a single code-unit for each code-point. - --it; - } - - // MovePrev(it, checker, tag): - // Moves the iterator to the previous UCS code-point in the encoded sequence. - // Specialized for UTF-8. - template<typename BaseIterator, typename BoundsChecker> - inline void MovePrev(BaseIterator& it, const BoundsChecker& checker, integral_constant<EEncoding, eEncoding_UTF8>) - { - assert(!checker.IsBegin(it) && "Attempt to iterate past the beginning of the sequence"); - - // UTF-8: just need to skip up to 3 continuation bytes. - for (int i = 0; i < 4; ++i) - { - --it; - if (checker.IsBegin(it)) - { - break; - } - uint32 val = static_cast<uint32>(*it); - if ((val & 0xC0) != 0x80) - { - break; - } - } - } - - // MovePrev(it, checker, tag): - // Moves the iterator to the previous UCS code-point in the encoded sequence. - // Specialized for UTF-16. - template<typename BaseIterator, typename BoundsChecker> - inline void MovePrev(BaseIterator& it, const BoundsChecker& checker, integral_constant<EEncoding, eEncoding_UTF16>) - { - assert(!checker.IsBegin(it) && "Attempt to iterate past the beginning of the sequence"); - - // UTF-16: just need to skip one lead surrogate. - --it; - uint32 val = static_cast<uint32>(*it); - if (val >= cLeadSurrogateFirst && val <= cLeadSurrogateLast) - { - if (!checker.IsBegin(it)) - { - --it; - } - } - } - - // SBaseIterators<BaseIterator, BoundsChecked>: - // Utility to access base iterators properties from CIterator. - // This is the bounds-checked specialization, the range information is kept to defend against malformed sequences. - template<typename BaseIterator, bool BoundsChecked> - struct SBaseIterators - { - typedef BaseIterator type; - type begin, end; - type it; - - SBaseIterators(const BaseIterator& _begin, const BaseIterator& _end) - : begin(_begin) - , end(_end) - , it(_begin) {} - - SBaseIterators(const SBaseIterators& other) - : begin(other.begin) - , end(other.end) - , it(other.it) {} - - SBaseIterators& operator =(const SBaseIterators& other) - { - begin = other.begin; - end = other.end; - it = other.it; - return *this; - } - - bool IsBegin(const BaseIterator& _it) const - { - return begin == _it; - } - - bool IsEnd(const BaseIterator& _it) const - { - return end == _it; - } - - bool IsEqual(const SBaseIterators& other) const - { - return it == other.it - && begin == other.begin - && end == other.end; - } - - // Note: Only called inside assert. - // O(N) version; works with any forward-iterator (or better) - bool IsInRange(const BaseIterator& _it, std::forward_iterator_tag) const - { - for (BaseIterator i = begin; i != end; ++i) - { - if (_it == i) - { - return true; - } - } - return false; - } - - // Note: Only called inside assert. - // O(1) version; requires random-access-iterator. - bool IsInRange(const BaseIterator& _it, std::random_access_iterator_tag) const - { - return (begin <= _it && _it < end); - } - - // Note: Only called inside assert. - // Dispatches to the O(1) version if a random-access iterator is used (common case). - bool IsInRange(const BaseIterator& _it) const - { - return IsInRange(_it, typename std::iterator_traits<BaseIterator>::iterator_category()); - } - }; - - // SBaseIterators<BaseIterator, BoundsChecked>: - // Utility to access base iterators properties from CIterator. - // This is the un-checked specialization for known-safe sequences. - template<typename BaseIterator> - struct SBaseIterators<BaseIterator, false> - { - typedef BaseIterator type; - type it; - - explicit SBaseIterators(const BaseIterator& begin) - : it(begin) {} - - SBaseIterators(const BaseIterator& begin, const BaseIterator& end) - : it(begin) {} - - SBaseIterators(const SBaseIterators& other) - : it(other.it) {} - - SBaseIterators& operator =(const SBaseIterators& other) - { - it = other.it; - return *this; - } - - bool IsBegin(const BaseIterator&) const - { - return false; - } - - bool IsEnd(const BaseIterator&) const - { - return false; - } - - bool IsEqual(const SBaseIterators& other) const - { - return it == other.it; - } - - bool IsInRange(const BaseIterator&) const - { - return true; - } - }; - - // SIteratorSink<Safe>: - // Helper to store the last code-point and error bit that was decoded. - // This is the safe specialization for potentially malformed sequences. - template<bool Safe> - struct SIteratorSink - { - static const uint32 cEmpty = 0xFFFFFFFFU; - uint32 value; - bool error; - - void Clear() - { - value = cEmpty; - error = false; - } - - bool IsEmpty() const - { - return value == cEmpty; - } - - bool IsError() const - { - return error; - } - - const uint32& GetValue() const - { - return value; - } - - void MarkDecodingError() - { - value = cReplacementCharacter; - error = true; - } - - template<EEncoding Encoding, typename BaseIterator, bool BoundsChecked> - void Decode(const SBaseIterators<BaseIterator, BoundsChecked>& its, integral_constant<EEncoding, Encoding>) - { - typedef SDecoder<Encoding, SIteratorSink&, SIteratorSink&> DecoderType; - DecoderType decoder(*this, *this); - Clear(); - for (BaseIterator it = its.it; IsEmpty(); ++it) - { - uint32 val = static_cast<uint32>(*it); - decoder(val); - if (its.IsEnd(it)) - { - break; - } - } - if (IsEmpty()) - { - // If we still have neither a new value or an error flag, just treat as error. - // This can happen if we reached the end of the sequence, but it ends in an incomplete code-sequence. - MarkDecodingError(); - } - } - - template<EEncoding Encoding, typename BaseIterator, bool BoundsChecked> - void DecodeIfEmpty(const SBaseIterators<BaseIterator, BoundsChecked>& its, integral_constant<EEncoding, Encoding> tag) - { - if (IsEmpty()) - { - Decode(its, tag); - } - } - - void operator()(uint32 unit) - { - value = unit; - } - - void operator()(SIteratorSink&, uint32, uint32) - { - MarkDecodingError(); - } - }; - - // SIteratorSink<Safe>: - // Helper to store the last code-point that was decoded. - // This is the un-safe specialization for known-valid sequences. - // Note: No error-state is tracked since we won't handle that regardless for un-safe CIterator. - template<> - struct SIteratorSink<false> - { - static const uint32 cEmpty = 0xFFFFFFFFU; - uint32 value; - - void Clear() - { - value = cEmpty; - } - - bool IsEmpty() const - { - return value == cEmpty; - } - - bool IsError() const - { - return false; - } - - const uint32& GetValue() const - { - return value; - } - - template<EEncoding Encoding, typename BaseIterator, bool BoundsChecked> - void Decode(const SBaseIterators<BaseIterator, BoundsChecked>& its, integral_constant<EEncoding, Encoding>) - { - typedef SDecoder<Encoding, SIteratorSink&, void> DecoderType; - DecoderType decoder(*this); - for (BaseIterator it = its.it; IsEmpty(); ++it) - { - uint32 val = static_cast<uint32>(*it); - decoder(val); - } - } - - template<EEncoding Encoding, typename BaseIterator, bool BoundsChecked> - void DecodeIfEmpty(const SBaseIterators<BaseIterator, BoundsChecked>& its, integral_constant<EEncoding, Encoding> tag) - { - if (IsEmpty()) - { - Decode(its, tag); - } - } - - void operator()(uint32 unit) - { - value = unit; - } - }; - } - - // CIterator<BaseIterator [, Safe, Encoding]>: - // Helper class that can iterate over an encoded text sequence and read the underlying UCS code-points. - // If the Safe flag is set, bounds checking is performed inside multi-unit sequences to guard against decoding errors. - // This requires the user to know where the sequence ends (use the constructor taking two parameters). - // Note: The BaseIterator must be forward-iterator or better when Safe flag is set. - // If the Safe flag is not set, you must guarantee the sequence is validly encoded, and allows the use of the single argument constructor. - // In the case of unsafe iterator used for C-style string pointer, look for a U+0000 dereferenced value to end the iteration. - // Regardless of the Safe flag, the user must ensure that the iterator is never moved past the beginning or end of the range (just like any other STL iterator). - // Example of typical usage: - // string utf8 = "foo"; // UTF-8 - // for (Unicode::CIterator<string::const_iterator> it(utf8.begin(), utf8.end()); it != utf8.end(); ++it) - // { - // uint32 codepoint = *it; // 32-bit UCS code-point - // } - // Example unsafe usage: (for known-valid encoded C-style strings): - // const char *pValid = "foo"; // UTF-8 - // for (Unicode::CIterator<const char *, false> it = pValid; *it != 0; ++it) - // { - // uint32 codepoint = *it; // 32-bit UCS code-point - // } - template<typename BaseIterator, bool Safe = true, EEncoding Encoding = Detail::SInferEncoding<BaseIterator, true>::value> - class CIterator - { - // The iterator value in the encoded sequence. - // Optionally provides bounds-checking. - Detail::SBaseIterators<BaseIterator, Safe> its; - - // The cached UCS code-point at the current position. - // Mutable because dereferencing is conceptually const, but does cache some state in this case. - mutable Detail::SIteratorSink<Safe> sink; - - public: - // Types for compatibility with STL bidirectional iterator requirements. - typedef const uint32 value_type; - typedef const uint32& reference; - typedef const uint32* pointer; - typedef const ptrdiff_t difference_type; - typedef std::bidirectional_iterator_tag iterator_category; - - // Construct an iterator for the given range. - // The initial position of the iterator as at the beginning of the range. - CIterator(const BaseIterator& begin, const BaseIterator& end) - : its(begin, end) - { - sink.Clear(); - } - - // Construct an iterator from a single iterator (typically C-style string pointer). - // This can only be used for unsafe iterators. - template<typename IteratorType> - CIterator(const IteratorType& it, typename Detail::SRequire<!Safe&& Detail::is_convertible<IteratorType, BaseIterator>::value, IteratorType>::type* = 0) - : its(static_cast<const BaseIterator&>(it)) - { - sink.Clear(); - } - - // Copy-construct an iterator. - CIterator(const CIterator& other) - : its(other.its) - , sink(other.sink) {} - - // Copy-assign an iterator. - CIterator& operator =(const CIterator& other) - { - its = other.its; - sink = other.sink; - return *this; - } - - // Test if the iterator points at an encoding error in the underlying encoded sequence. - // If so, the function returns false. - // When using an un-safe iterator, this function always returns true, if a sequence can contain encoding errors, you must use the safe variant. - // Note: This requires the underlying iterator to be dereferenced, so you cannot use it only while the iterator is inside the valid range. - bool IsAtValidCodepoint() const - { - assert(!its.IsEnd(its.it) && "Attempt to dereference the past-the-end iterator"); - Detail::integral_constant<EEncoding, Encoding> tag; - sink.DecodeIfEmpty(its, tag); - return !sink.IsError(); - } - - // Gets the current position in the underlying encoded sequence. - // If the iterator points to an invalidly encoded sequence (ie, IsError() returns true), the direction of iteration is significant. - // In that case the returned position is approximated; to work around this: move all iterators of which the position is compared in the same direction. - const BaseIterator& GetPosition() const - { - return its.it; - } - - // Sets the current position in the underlying encoded sequence. - // You may not set the position outside the range for which this iterator was constructed. - void SetPosition(const BaseIterator& it) - { - assert(its.IsInRange(it) && "Attempt to set the underlying iterator outside of the supported range"); - its.it = it; - } - - // Test if this iterator is equal to another iterator instance. - // Note: In the presence of an invalidly encoded sequence (ie, IsError() returns true), the direction of iteration is significant. - // To work around this, you can either: - // 1) Move all iterators that will be compared in the same direction; or - // 2) Compare the dereferenced iterator value(s) instead (if applicable). - bool operator ==(const CIterator& other) const - { - return its.IsEqual(other.its); - } - - // Test if this iterator is equal to another base iterator. - // Note: If the provided iterator does not point to the the first code-unit of an UCS code-point, the behavior is undefined. - bool operator ==(const BaseIterator& other) const - { - return its.it == other; - } - - // Test if this iterator is equal to another iterator instance. - // Note: In the presence of an invalidly encoded sequence (ie, IsError() returns true), the direction of iteration is significant. - // To work around this, you can either: - // 1) Move all iterators that will be compared in the same direction; or - // 2) Compare the dereferenced iterator value(s) instead (if applicable). - bool operator !=(const CIterator& other) const - { - return !its.IsEqual(other.its); - } - - // Test if this iterator is equal to another base iterator. - // Note: If the provided iterator does not point to the the first code-unit of an UCS code-point, the behavior is undefined. - bool operator !=(const BaseIterator& other) const - { - return its.it != other; - } - - // Get the decoded UCS code-point at the current position in the sequence. - // If the iterator points to an invalidly encoded sequence (ie, IsError() returns true) the function returns U+FFFD (replacement character). - reference operator *() const - { - assert(!its.IsEnd(its.it) && "Attempt to dereference the past-the-end iterator"); - Detail::integral_constant<EEncoding, Encoding> tag; - sink.DecodeIfEmpty(its, tag); - return sink.GetValue(); - } - - // Advance the iterator to the next UCS code-point. - // Note: You must make sure the iterator is not at the end of the sequence, even in Safe mode. - // However, in Safe mode, the iterator will never move past the end of the sequence in the presence of encoding errors. - CIterator& operator ++() - { - Detail::integral_constant<EEncoding, Encoding> tag; - Detail::MoveNext(its.it, its, tag); - sink.Clear(); - return *this; - } - - // Go back to the previous UCS code-point. - // Note: You must make sure the iterator is not at the beginning of the sequence, even in Safe mode. - // However, in Safe mode, the iterators will never move past the beginning of the sequence in the presence of encoding errors. - CIterator& operator --() - { - Detail::integral_constant<EEncoding, Encoding> tag; - Detail::MovePrev(its.it, its, tag); - sink.Clear(); - return *this; - } - - // Advance the iterator to the next UCS code-point, return a copy of the iterator position before advancing. - // Note: You must make sure the iterator is not at the end of the sequence, even in Safe mode. - // However, in Safe mode, the iterator will never move past the end of the sequence in the presence of encoding errors. - CIterator operator ++(int) - { - CIterator result = *this; - ++*this; - return result; - } - - // Go back to the previous UCS code-point, return a copy of the iterator position before going back. - // Note: You must make sure the iterator is not at the beginning of the sequence, even in Safe mode. - // However, in Safe mode, the iterators will never move past the beginning of the sequence in the presence of encoding errors. - CIterator operator --(int) - { - CIterator result = *this; - --*this; - return result; - } - }; - - namespace Detail - { - // SIteratorSpecializer<T>: - // Specializes the CIterator template to use for a given string type. - // Note: The reason we use this is because MSVC doesn't want to deduce this on the MakeIterator declaration. - template<typename StringType> - struct SIteratorSpecializer - { - typedef CIterator<typename StringType::const_iterator> type; - }; - } - - // MakeIterator(const StringType &str): - // Helper function to make an UCS code-point iterator given an Unicode string. - // Example usage: - // string utf8 = "foo"; // UTF-8 - // auto it = Unicode::MakeIterator(utf8); - // while (it != utf8.end()) - // { - // uint32 codepoint = *it; // 32-bit UCS code-point - // } - // Or, in a for-loop: - // for (auto it = Unicode::MakeIterator(utf8); it != utf8.end(); ++it) {} - template<typename StringType> - inline typename Detail::SIteratorSpecializer<StringType>::type MakeIterator(const StringType& str) - { - return typename Detail::SIteratorSpecializer<StringType>::type(str.begin(), str.end()); - } -} diff --git a/Code/CryEngine/CryCommon/VRCommon.h b/Code/CryEngine/CryCommon/VRCommon.h deleted file mode 100644 index ea2abb9da7..0000000000 --- a/Code/CryEngine/CryCommon/VRCommon.h +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include <AzCore/RTTI/TypeInfo.h> -#include <AzCore/RTTI/ReflectContext.h> -#include <AzCore/Math/Vector3.h> -#include <AzCore/Math/Quaternion.h> -#include <AzCore/std/containers/array.h> - -#include <Cry_Math.h> - -#include <cstdint> - -namespace AZ -{ - namespace VR - { - /// - /// Enum to describe the stereo layout of content - /// - enum class StereoLayout : AZ::u32 - { - TOP_BOTTOM = 0, //Top is Left, Bottom is Right - BOTTOM_TOP, //Bottom is Left, Top is Right - //TODO: Figure out how to support LEFT_RIGHT and RIGHT_LEFT - //TOP_BOTTOM is preferred because of the way that scan lines are ordered - //LEFT_RIGHT, //Left is Left, Right is Right - //RIGHT_LEFT, //Right is Left, Left is Right - UNKNOWN //This content is either not stereo or its stereo format cannot be determined - }; - - - /// - /// Eye-specific camera info. - /// - struct PerEyeCameraInfo - { - float fov; ///< Field-of-view of this eye. Note that each eye may have different fields-of-view. - float aspectRatio; ///< Aspect-ratio of this eye. Note that each eye may have different aspect ratios. - AZ::Vector3 eyeOffset; ///< Camera-space offset for this eye relative to the non-stereo view. - - struct AsymmetricFrustumPlane - { - float horizontalDistance; ///< Horizontal frustum shift relative to the non-stereo frustum. - float verticalDistance; ///< Vertical frustum shift relative to the non-stereo frustum. - - AsymmetricFrustumPlane() - : horizontalDistance(1.6f) - , verticalDistance(0.9f) - { - } - }; - - AsymmetricFrustumPlane frustumPlane; - - PerEyeCameraInfo() - : aspectRatio(16.0f / 9.0f) - , fov(DEG2RAD(1.5f)) - , eyeOffset(0.65f, 0.0f, 0.0f) - { - } - }; - - /// - /// Types of social screens supported by the engine. - /// - enum class HMDSocialScreen - { - Off = -1, - UndistortedLeftEye, - UndistortedRightEye, - }; - - /// - /// Supported tracking levels. - /// - enum class HMDTrackingLevel - { - kHead, ///< The sensor reads as if the player is standing. - kFloor, ///< Sensor reads as if the player is seated/on the floor. - kFixed ///< Translation information is ignored, the view appears at the HMD origin - }; - - /// - /// Human-readable info about the connected device. This info is printed to the screen when a new device is detected. - /// - struct HMDDeviceInfo - { - AZ_TYPE_INFO(HMDDeviceInfo, "{DB83AF23-CF4E-491D-A346-F5DC834D1C74}") - - static void Reflect(AZ::ReflectContext* context); - - const char* productName; - const char* manufacturer; - - // Rendering resolution is defined as containing just a single eye. - unsigned int renderWidth; - unsigned int renderHeight; - - // Field of view is defined as the total field of view of the device which includes both eyes. - float fovH; - float fovV; - - HMDDeviceInfo() - : productName(nullptr) - , manufacturer(nullptr) - , renderWidth(0) - , renderHeight(0) - , fovH(0.0f) - , fovV(0.0f) - { - } - }; - - enum HMDStatus - { - HMDStatus_OrientationTracked = BIT(1), - HMDStatus_PositionTracked = BIT(2), - HMDStatus_CameraPoseTracked = BIT(3), - HMDStatus_PositionConnected = BIT(4), - HMDStatus_HmdConnected = BIT(5), - - HMDStatus_IsUsable = HMDStatus_HmdConnected | HMDStatus_OrientationTracked, - HMDStatus_ControllerValid = HMDStatus_OrientationTracked | HMDStatus_PositionConnected, - }; - - /// - /// Single device render target created and managed by the device. The renderer should make use of this render target in order to properly display - /// the rendered content to this HMD. - /// - struct HMDRenderTarget - { - void* deviceSwapTextureSet; ///< Device-represented texture. These textures are created and maintained by the HMD's specific SDK. - uint32 numTextures; ///< Number of textures inside of the swap set. - void** textures; ///< Access to the internal device textures. This array is exactly numTextures long. - - HMDRenderTarget() - : deviceSwapTextureSet(nullptr) - , numTextures(0) - , textures(nullptr) - { - } - }; - - enum class ControllerIndex - : uint32_t - { - LeftHand = 0, - RightHand, - MaxNumControllers - }; - - /// - /// A specific pose of the HMD. Every HMD device has their own way of representing their - /// current pose in 3D space. This structure acts as a common data set between any connected - /// device and the rest of the system. - /// - struct PoseState - { - AZ_TYPE_INFO(PoseState, "{040F18D7-1163-477B-8908-47CC35737DCE}") - - static void Reflect(AZ::ReflectContext* context); - - AZ::Quaternion orientation; ///< The current orientation of the HMD. - AZ::Vector3 position; ///< The current position of the HMD in local space as an offset from the centered pose. - - PoseState() - : orientation(AZ::Quaternion::CreateIdentity()) - , position(AZ::Vector3::CreateZero()) - { - } - }; - - /// - /// Dynamics (accelerations and velocities) of the current HMD. Many HMDs have the ability to track the current movements - /// of the VR device(s) for prediction. Note that not all devices may support velocities/accelerations. - /// - struct DynamicsState - { - AZ_TYPE_INFO(DynamicsState, "{5C5E2249-8844-4790-9F7A-88703A9C18DD}") - - static void Reflect(AZ::ReflectContext* context); - - /// Angular velocity/acceleration reported in local space. - AZ::Vector3 angularVelocity; - AZ::Vector3 angularAcceleration; - - /// Linear velocity/acceleration reported in local space. - AZ::Vector3 linearVelocity; - AZ::Vector3 linearAcceleration; - - DynamicsState() - : angularVelocity(0) - , angularAcceleration(0) - , linearVelocity(0) - , linearAcceleration(0) - { - } - }; - - /// - /// While tracking the HMD, certain parts of the devices may go off/online. For example, - /// a controller may be disconnected or the HMD may lose rotational tracking temporarily. This - /// struct stores a tracked state meaning a pose as well as flags that denote what part of the pose - /// is currently valid. - /// - struct TrackingState - { - AZ_TYPE_INFO(TrackingState, "{E9CB08E8-9996-478B-AABB-EC8CCCF3B403}") - - typedef uint32 StatusFlags; - - bool CheckStatusFlags(StatusFlags flags) const - { - // Multiple flags can be checked simultaneously. - return (statusFlags & flags) == flags; - } - - static void Reflect(AZ::ReflectContext* context); - - PoseState pose; ///< Current pose relating to this tracked state. - DynamicsState dynamics; ///< Current state of the physics dynamics for this device. - StatusFlags statusFlags; ///< Bitfield denoting current tracking status. Flags defined in the enum HMDStatus. - - TrackingState() - : statusFlags(0) - { - } - }; - - /// - /// Rectangle storing the playspace defined by the user when - /// setting up VR device. - /// - struct Playspace - { - AZ_TYPE_INFO(Playspace, "{05934537-80AA-4ABA-AB2C-71096FA7DC74}") - AZ_CLASS_ALLOCATOR_DECL - - static void Reflect(AZ::ReflectContext* context); - - bool isValid = false; ///< The playspace data is valid (calibrated). - AZStd::array<AZ::Vector3, 4> corners; ///< Playspace corners defined in device-local space. The center of the playspace is 0. - }; - - }//namespace VR - AZ_TYPE_INFO_SPECIALIZE(VR::ControllerIndex, "{90D4C80E-A1CC-4DBF-A131-0082C75835E8}"); -}//namespace AZ diff --git a/Code/CryEngine/CryCommon/VectorMap.h b/Code/CryEngine/CryCommon/VectorMap.h deleted file mode 100644 index 4a0db13ae6..0000000000 --- a/Code/CryEngine/CryCommon/VectorMap.h +++ /dev/null @@ -1,537 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : std::map replacement implemented using sorted vector. - - -#ifndef CRYINCLUDE_CRYCOMMON_VECTORMAP_H -#define CRYINCLUDE_CRYCOMMON_VECTORMAP_H -#pragma once - - -//-------------------------------------------------------------------------- -// VectorMap -// -// Usage Notes: -// This class is designed to be an (almost, see below) drop-in replacement -// for std::map. It features an almost identical interface, but it is -// implemented using a sorted vector rather than a tree. This is in most -// cases more efficient, as there is less dynamic memory allocation and -// pointer dereferencing. -// -// ************************************************************************* -// PLEASE NOTE: There is one vital difference between std::map and VectorMap -// that you will need to note before trying to replace std::map. Since -// VectorMap is implemented using a vector, iterators can and will be -// invalidated by many operations, such as insertions and deletions, and -// due to sorting potentially even normal lookups. Please Please PLEASE make -// sure that you are not storing any iterators to this class. -// ************************************************************************* -// -// The class varies from the std::set API in that two of the erase methods -// methods are not of void return type but return an iterator - this is -// required in practice because they invalidate iterators, as noted above. -// -// * iterator erase(iterator where); -// * iterator erase(iterator first, iterator last); -// -// -// Performance Notes: -// -// This class uses the empty base optimization hack to allow comparison -// predicate objects that have no state to take up no space in the object. -// As a result the size of the overall VectorMap instance is the same as -// that of the std::vector it uses to store the elements. -// -// In addition to the normal map interface, this class provides the -// following members that can be used to manage memory requirements: -// -// * void reserve(size_type count); -// Allocate enough space for count elements (see vector::reserve()). -// -// * size_type capacity() const; -// Report how many elements can be stored without reallocating (see -// vector::capacity()). -// -//-------------------------------------------------------------------------- - -template <typename K, typename V, typename T = std::less<K>, typename A = std::allocator<std::pair <K, V> > > -class VectorMap - : private T // Empty base optimization -{ -public: - typedef K key_type; - typedef V mapped_type; - typedef A allocator_type; - - typedef std::pair</*const */ key_type, mapped_type> value_type; - - typedef T key_compare; - - class FirstLess - { - public: - FirstLess(const key_compare& comp) - : m_comp(comp) {} - - bool operator()(const value_type& left, const value_type& right) const - { - return m_comp(left.first, right.first); - } - - private: - const key_compare& m_comp; - }; - - typedef std::vector<value_type, allocator_type> container_type; - typedef typename container_type::iterator iterator; - typedef typename container_type::const_iterator const_iterator; - typedef typename container_type::reverse_iterator reverse_iterator; - typedef typename container_type::const_reverse_iterator const_reverse_iterator; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef typename std::allocator_traits<allocator_type>::size_type size_type; - - VectorMap(); - explicit VectorMap(const key_compare& comp); - explicit VectorMap(const key_compare& comp, const allocator_type& alloc); - VectorMap(const VectorMap& right); - template <class InputIterator> - VectorMap(InputIterator first, InputIterator last); - template <class InputIterator> - VectorMap(InputIterator first, InputIterator last, const key_compare& comp); - template <class InputIterator> - VectorMap(InputIterator first, InputIterator last, const key_compare& comp, const allocator_type& alloc); - void SwapElementsWithVector(container_type& elementVector); - iterator begin(); - const_iterator begin() const; - size_type capacity() const; - void clear(); - void clearAndFreeMemory(); - size_type count(const key_type& key) const; - bool empty() const; - iterator end(); - const_iterator end() const; - std::pair<iterator, iterator> equal_range(const key_type& key); - std::pair<const_iterator, const_iterator> equal_range(const key_type& key) const; - iterator erase(iterator where); // See documentation above - iterator erase(iterator first, iterator last); // See documentation above - void erase(const key_type& key); - template <typename Predicate> - void erase_if(const Predicate& predicate); - iterator find(const key_type& key); - const_iterator find(const key_type& key) const; - allocator_type get_allocator() const; - std::pair<iterator, bool> insert(const value_type& val); - iterator insert(iterator where, const value_type& val); - template <class InputIterator> - void insert(InputIterator first, InputIterator last); - key_compare key_comp() const; - iterator lower_bound(const key_type& key); - const_iterator lower_bound(const key_type& key) const; - size_type max_size() const; - reverse_iterator rbegin(); - const_reverse_iterator rbegin() const; - reverse_iterator rend(); - const_reverse_iterator rend() const; - void reserve(size_type count); - size_type size() const; - void swap(VectorMap& other); - iterator upper_bound(const key_type& key); - const_iterator upper_bound(const key_type& key) const; - mapped_type& operator[](const key_type& key); - - template<typename Sizer> - void GetMemoryUsage(Sizer* pSizer) const - { - pSizer->AddObject(m_entries); - } -private: - container_type m_entries; -}; - -template <typename K, typename V, typename T, typename A> -VectorMap<K, V, T, A>::VectorMap() -{ -} - -template <typename K, typename V, typename T, typename A> -VectorMap<K, V, T, A>::VectorMap(const key_compare& comp) - : key_compare(comp) -{ -} - -template <typename K, typename V, typename T, typename A> -VectorMap<K, V, T, A>::VectorMap(const key_compare& comp, const allocator_type& alloc) - : key_compare(comp) - , m_entries(alloc) -{ -} - -template <typename K, typename V, typename T, typename A> -VectorMap<K, V, T, A>::VectorMap(const VectorMap& right) - : key_compare(right) - , m_entries(right.m_entries) -{ -} - -template <typename K, typename V, typename T, typename A> -template <class InputIterator> -VectorMap<K, V, T, A>::VectorMap(InputIterator first, InputIterator last) -{ - for (; first != last; ++first) - { - m_entries.push_back(*first); - } - std::sort(m_entries.begin(), m_entries.end(), FirstLess(static_cast<key_compare>(*this))); -} - -template <typename K, typename V, typename T, typename A> -template <class InputIterator> -VectorMap<K, V, T, A>::VectorMap(InputIterator first, InputIterator last, const key_compare& comp) - : key_compare(comp) -{ - for (; first != last; ++first) - { - m_entries.push_back(*first); - } - std::sort(m_entries.begin(), m_entries.end(), FirstLess(static_cast<key_compare>(*this))); -} - -template <typename K, typename V, typename T, typename A> -template <class InputIterator> -VectorMap<K, V, T, A>::VectorMap(InputIterator first, InputIterator last, const key_compare& comp, const allocator_type& alloc) - : key_compare(comp) - , m_entries(alloc) -{ - for (; first != last; ++first) - { - m_entries.push_back(*first); - } - std::sort(m_entries.begin(), m_entries.end(), FirstLess(static_cast<key_compare>(*this))); -} - -template <typename K, typename V, typename T, typename A> -void VectorMap<K, V, T, A>::SwapElementsWithVector(typename VectorMap<K, V, T, A>::container_type& elementVector) -{ - m_entries.swap(elementVector); - std::sort(m_entries.begin(), m_entries.end(), FirstLess(static_cast<key_compare>(*this))); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::iterator VectorMap<K, V, T, A>::begin() -{ - return m_entries.begin(); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::const_iterator VectorMap<K, V, T, A>::begin() const -{ - return m_entries.begin(); -} - -template <typename K, typename V, typename T, typename A> -void VectorMap<K, V, T, A>::clear() -{ - m_entries.resize(0); -} - -template <typename K, typename V, typename T, typename A> -void VectorMap<K, V, T, A>::clearAndFreeMemory() -{ - stl::free_container(m_entries); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::size_type VectorMap<K, V, T, A>::capacity() const -{ - return m_entries.capacity(); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::size_type VectorMap<K, V, T, A>::count(const key_type& key) const -{ - return size_type(std::binary_search(m_entries.begin(), m_entries.end(), value_type(key, mapped_type()), static_cast<key_compare>(*this))); -} - -template <typename K, typename V, typename T, typename A> -bool VectorMap<K, V, T, A>::empty() const -{ - return m_entries.empty(); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::iterator VectorMap<K, V, T, A>::end() -{ - return m_entries.end(); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::const_iterator VectorMap<K, V, T, A>::end() const -{ - return m_entries.end(); -} - -template <typename K, typename V, typename T, typename A> -std::pair<typename VectorMap<K, V, T, A>::iterator, typename VectorMap<K, V, T, A>::iterator> VectorMap<K, V, T, A>::equal_range(const key_type& key) -{ - iterator lower = lower_bound(key); - if (lower != m_entries.end() && key_compare::operator()(key, (*lower).first)) - { - lower = m_entries.end(); - } - iterator upper = lower; - if (upper != m_entries.end()) - { - ++upper; - } - return std::make_pair(lower, upper); -} - -template <typename K, typename V, typename T, typename A> -std::pair<typename VectorMap<K, V, T, A>::const_iterator, typename VectorMap<K, V, T, A>::const_iterator> VectorMap<K, V, T, A>::equal_range(const key_type& key) const -{ - const_iterator lower = lower_bound(key); - if (lower != m_entries.end() && key_compare::operator()(key, (*lower).first)) - { - lower = m_entries.end(); - } - const_iterator upper = lower; - if (upper != m_entries.end()) - { - ++upper; - } - return std::make_pair(lower, upper); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::iterator VectorMap<K, V, T, A>::erase(iterator where) -{ - return m_entries.erase(where); -} - -template <typename K, typename V, typename T, typename A> -template <typename Predicate> -void VectorMap<K, V, T, A>::erase_if(const Predicate& predicate) -{ - m_entries.erase(std::remove_if(m_entries.begin(), m_entries.end(), predicate), m_entries.end()); - std::sort(m_entries.begin(), m_entries.end(), FirstLess(static_cast<key_compare>(*this))); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::iterator VectorMap<K, V, T, A>::erase(iterator first, iterator last) -{ - return m_entries.erase(first, last); -} - -template <typename K, typename V, typename T, typename A> -void VectorMap<K, V, T, A>::erase(const key_type& key) -{ - iterator where = find(key); - - if (where != m_entries.end()) - { - m_entries.erase(where); - } -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::iterator VectorMap<K, V, T, A>::find(const key_type& key) -{ - iterator it = lower_bound(key); - if (it != m_entries.end() && key_compare::operator()(key, (*it).first)) - { - it = m_entries.end(); - } - return it; -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::const_iterator VectorMap<K, V, T, A>::find(const key_type& key) const -{ - const_iterator it = lower_bound(key); - if (it != m_entries.end() && key_compare::operator()(key, (*it).first)) - { - it = m_entries.end(); - } - return it; -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::allocator_type VectorMap<K, V, T, A>::get_allocator() const -{ - return m_entries.get_allocator(); -} - -template <typename K, typename V, typename T, typename A> -std::pair<typename VectorMap<K, V, T, A>::iterator, bool> VectorMap<K, V, T, A>::insert(const value_type& val) -{ - iterator it = lower_bound(val.first); - bool insertionMade = false; - if (it == m_entries.end() || key_compare::operator()(val.first, (*it).first)) - { - it = m_entries.insert(it, val), insertionMade = true; - } - return std::make_pair(it, insertionMade); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::iterator VectorMap<K, V, T, A>::insert(iterator where, const value_type& val) -{ - return insert(val); -} - -template <typename K, typename V, typename T, typename A> -template <class InputIterator> -void VectorMap<K, V, T, A>::insert(InputIterator first, InputIterator last) -{ - for (; first != last; ++first) - { - insert(*first); - } -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::key_compare VectorMap<K, V, T, A>::key_comp() const -{ - return static_cast<key_compare>(*this); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::iterator VectorMap<K, V, T, A>::lower_bound(const key_type& key) -{ - int count = 0; - count = m_entries.size(); - iterator first = m_entries.begin(); - iterator last = m_entries.end(); - for (; 0 < count; ) - { // divide and conquer, find half that contains answer - int count2 = count / 2; - iterator mid = first + count2; - - if (key_compare::operator()(mid->first, key)) - { - first = ++mid, count -= count2 + 1; - } - else - { - count = count2; - } - } - return first; -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::const_iterator VectorMap<K, V, T, A>::lower_bound(const key_type& key) const -{ - int count = 0; - count = m_entries.size(); - const_iterator first = m_entries.begin(); - const_iterator last = m_entries.end(); - for (; 0 < count; ) - { // divide and conquer, find half that contains answer - int count2 = count / 2; - const_iterator mid = first + count2; - - if (key_compare::operator()(mid->first, key)) - { - first = ++mid, count -= count2 + 1; - } - else - { - count = count2; - } - } - return first; -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::size_type VectorMap<K, V, T, A>::max_size() const -{ - return m_entries.max_size(); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::reverse_iterator VectorMap<K, V, T, A>::rbegin() -{ - return m_entries.rbegin(); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::const_reverse_iterator VectorMap<K, V, T, A>::rbegin() const -{ - return m_entries.rbegin(); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::reverse_iterator VectorMap<K, V, T, A>::rend() -{ - return m_entries.rend(); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::const_reverse_iterator VectorMap<K, V, T, A>::rend() const -{ - return m_entries.rend(); -} - -template <typename K, typename V, typename T, typename A> -void VectorMap<K, V, T, A>::reserve(size_type count) -{ - m_entries.reserve(count); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::size_type VectorMap<K, V, T, A>::size() const -{ - return m_entries.size(); -} - -template <typename K, typename V, typename T, typename A> -void VectorMap<K, V, T, A>::swap(VectorMap& other) -{ - m_entries.swap(other.m_entries); - std::swap(static_cast<key_compare&>(*this), static_cast<key_compare&>(other)); -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::iterator VectorMap<K, V, T, A>::upper_bound(const key_type& key) -{ - iterator upper = lower_bound(key); - if (upper != m_entries.end() && !key_compare::operator()(key, (*upper).first)) - { - ++upper; - } - return upper; -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::const_iterator VectorMap<K, V, T, A>::upper_bound(const key_type& key) const -{ - iterator upper = lower_bound(key); - if (upper != m_entries.end() && !key_compare::operator()(key, (*upper).first)) - { - ++upper; - } - return upper; -} - -template <typename K, typename V, typename T, typename A> -typename VectorMap<K, V, T, A>::mapped_type& VectorMap<K, V, T, A>::operator[](const key_type& key) -{ - iterator it = find(key); - if (it == m_entries.end()) - { - it = insert(value_type(key, mapped_type())).first; - } - return (*it).second; -} - -#endif // CRYINCLUDE_CRYCOMMON_VECTORMAP_H diff --git a/Code/CryEngine/CryCommon/VectorSet.h b/Code/CryEngine/CryCommon/VectorSet.h deleted file mode 100644 index 578d8c0f28..0000000000 --- a/Code/CryEngine/CryCommon/VectorSet.h +++ /dev/null @@ -1,491 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : std::set replacement implemented using sorted vector. - - -#ifndef CRYINCLUDE_CRYCOMMON_VECTORSET_H -#define CRYINCLUDE_CRYCOMMON_VECTORSET_H -#pragma once - - -//-------------------------------------------------------------------------- -// VectorSet -// -// Usage Notes: -// This class is designed to be an (almost, see below) drop-in replacement -// for std::set. It features an almost identical interface, but it is -// implemented using a sorted vector rather than a tree. This is in most -// cases more efficient, as there is less dynamic memory allocation and -// pointer dereferencing. -// -// ************************************************************************* -// PLEASE NOTE: There is one vital difference between std::set and VectorSet -// that you will need to note before trying to replace std::set. Since -// VectorSet is implemented using a vector, iterators can and will be -// invalidated by many operations, such as insertions and deletions, and -// due to sorting potentially even normal lookups. Please Please PLEASE make -// sure that you are not storing any iterators to this class. -// ************************************************************************* -// -// The class varies from the std::set API in that two of the erase methods -// methods are not of void return type but return an iterator - this is -// required in practice because they invalidate iterators, as noted above. -// -// * iterator erase(iterator where); -// * iterator erase(iterator first, iterator last); -// -// It also adds operator[] to the API. -// -// -// Performance Notes: -// -// This class uses the empty base optimization hack to allow comparison -// predicate objects that have no state to take up no space in the object. -// As a result the size of the overall VectorMap instance is the same as -// that of the std::vector it uses to store the elements. -// -// In addition to the normal map interface, this class provides the -// following members that can be used to manage memory requirements: -// -// * void reserve(size_type count); -// Allocate enough space for count elements (see vector::reserve()). -// -// * size_type capacity() const; -// Report how many elements can be stored without reallocating (see -// vector::capacity()). -// -// * void resize(size_type new_size, const_reference x=key_type()); -// see vector::resize()). -// -//-------------------------------------------------------------------------- - -template <typename K, typename T = AZStd::less<K>, typename A = AZ::StdLegacyAllocator > -class VectorSet - : private T // Empty base optimization -{ -public: - typedef K key_type; - typedef A allocator_type; - typedef T key_compare; - typedef T value_compare; - typedef AZStd::vector<key_type, allocator_type> container_type; - typedef typename container_type::iterator iterator; - typedef typename container_type::const_iterator const_iterator; - typedef typename container_type::reverse_iterator reverse_iterator; - typedef typename container_type::const_reverse_iterator const_reverse_iterator; - typedef typename container_type::size_type size_type; - typedef typename container_type::difference_type difference_type; - typedef key_type& reference; - typedef const key_type& const_reference; - typedef key_type* pointer; - typedef const key_type* const_pointer; - - VectorSet(); - explicit VectorSet(const key_compare& comp); - explicit VectorSet(const key_compare& comp, const allocator_type& allocator); - VectorSet(const VectorSet<K, T, A>& right); - template <class InputIterator> - VectorSet(InputIterator first, InputIterator last); - template <class InputIterator> - VectorSet(InputIterator first, InputIterator last, const key_compare& comp); - template <class InputIterator> - VectorSet(InputIterator first, InputIterator last, const key_compare& comp, const allocator_type& allocator); - void SwapElementsWithVector(container_type& elementVector); - const_iterator begin() const; - iterator begin(); - size_type capacity() const; - void resize(size_type __new_size, const_reference __x = key_type()); - void clear(); - size_type count(const_reference key) const; - bool empty() const; - const_iterator end() const; - iterator end(); - std::pair<const_iterator, const_iterator> equal_range(const_reference key) const; - std::pair<iterator, iterator> equal_range(const_reference key); - iterator erase(iterator where); // See documentation above - iterator erase(iterator first, iterator last); // See documentation above - size_t erase(const_reference key); - iterator find(const_reference key); - const_iterator find(const_reference key) const; - allocator_type get_allocator() const; - std::pair<iterator, bool> insert(const_reference value); - iterator insert(iterator _Where, const_reference value); - template<class InputIterator> - void insert(InputIterator first, InputIterator last); - key_compare key_comp() const; - const_iterator lower_bound(const_reference key) const; - iterator lower_bound(const_reference key); - size_type max_size() const; - const_reverse_iterator rbegin() const; - reverse_iterator rbegin(); - const_reverse_iterator rend() const; - reverse_iterator rend(); - void reserve(size_type count); - size_type size() const; - void swap(VectorSet& right); - const_iterator upper_bound(const_reference key) const; - iterator upper_bound(const_reference key); - value_compare value_comp() const; - reference operator[](int index); // See documentation above - const_reference operator[](int index) const; // See documentation above - - template<typename Sizer> - void GetMemoryUsage(Sizer* pSizer) const - { - pSizer->AddObject(m_entries); - } -private: - container_type m_entries; -}; - -template <typename K, typename T, typename A> -VectorSet<K, T, A>::VectorSet() -{ -} - -template <typename K, typename T, typename A> -VectorSet<K, T, A>::VectorSet(const key_compare& comp) - : key_compare(comp) -{ -} - -template <typename K, typename T, typename A> -VectorSet<K, T, A>::VectorSet(const key_compare& comp, const allocator_type& allocator) - : key_compare(comp) - , m_entries(allocator) -{ -} - -template <typename K, typename T, typename A> -VectorSet<K, T, A>::VectorSet(const VectorSet<K, T, A>& right) - : key_compare(right) - , m_entries(right.m_entries) -{ -} - -template <typename K, typename T, typename A> -template <class InputIterator> -VectorSet<K, T, A>::VectorSet(InputIterator first, InputIterator last) -{ - for (; first != last; ++first) - { - m_entries.push_back(*first); - } - std::sort(m_entries.begin(), m_entries.end(), static_cast<key_compare>(*this)); -} - -template <typename K, typename T, typename A> -template <class InputIterator> -VectorSet<K, T, A>::VectorSet(InputIterator first, InputIterator last, const key_compare& comp) - : key_compare(comp) -{ - for (; first != last; ++first) - { - m_entries.push_back(*first); - } - std::sort(m_entries.begin(), m_entries.end(), static_cast<key_compare>(*this)); -} - -template <typename K, typename T, typename A> -template <class InputIterator> -VectorSet<K, T, A>::VectorSet(InputIterator first, InputIterator last, const key_compare& comp, const allocator_type& allocator) - : key_compare(comp) - , m_entries(allocator) -{ - for (; first != last; ++first) - { - m_entries.push_back(*first); - } - std::sort(m_entries.begin(), m_entries.end(), static_cast<key_compare>(*this)); -} - -template <typename K, typename T, typename A> -void VectorSet<K, T, A>::SwapElementsWithVector(container_type& elementVector) -{ - m_entries.swap(elementVector); - std::sort(m_entries.begin(), m_entries.end(), static_cast<key_compare>(*this)); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::const_iterator VectorSet<K, T, A>::begin() const -{ - return m_entries.begin(); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::iterator VectorSet<K, T, A>::begin() -{ - return m_entries.begin(); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::size_type VectorSet<K, T, A>::capacity() const -{ - return m_entries.capacity(); -} - -template <typename K, typename T, typename A> -void VectorSet<K, T, A>::clear() -{ - m_entries.clear(); -} - -template <typename K, typename T, typename A> -void VectorSet<K, T, A>::resize(size_type __new_size, const_reference __x) -{ - m_entries.resize(__new_size, __x); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::size_type VectorSet<K, T, A>::count(const_reference key) const -{ - return size_type(std::binary_search(m_entries.begin(), m_entries.end(), key, static_cast<key_compare>(*this))); -} - -template <typename K, typename T, typename A> -bool VectorSet<K, T, A>::empty() const -{ - return m_entries.empty(); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::const_iterator VectorSet<K, T, A>::end() const -{ - return m_entries.end(); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::iterator VectorSet<K, T, A>::end() -{ - return m_entries.end(); -} - -template <typename K, typename T, typename A> -std::pair<typename VectorSet<K, T, A>::const_iterator, typename VectorSet<K, T, A>::const_iterator> VectorSet<K, T, A>::equal_range(const_reference key) const -{ - const_iterator lower = lower_bound(key); - if (lower != m_entries.end() && key_compare::operator()(key, *lower)) - { - lower = m_entries.end(); - } - const_iterator upper = lower; - if (upper != m_entries.end()) - { - ++upper; - } - return std::make_pair(lower, upper); -} - -template <typename K, typename T, typename A> -std::pair<typename VectorSet<K, T, A>::iterator, typename VectorSet<K, T, A>::iterator> VectorSet<K, T, A>::equal_range(const_reference key) -{ - iterator lower = lower_bound(key); - if (lower != m_entries.end() && key_compare::operator()(key, *lower)) - { - lower = m_entries.end(); - } - iterator upper = lower; - if (upper != m_entries.end()) - { - ++upper; - } - return std::make_pair(lower, upper); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::iterator VectorSet<K, T, A>::erase(iterator where) -{ - return m_entries.erase(where); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::iterator VectorSet<K, T, A>::erase(iterator first, iterator last) -{ - return m_entries.erase(first, last); -} - -template <typename K, typename T, typename A> -size_t VectorSet<K, T, A>::erase(const_reference key) -{ - iterator where = find(key); - - if (where != m_entries.end()) - { - // Note erasing entries does not invalidate the sort - no need to trigger a re-sort. - m_entries.erase(where); - return 1; - } - - return 0; -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::iterator VectorSet<K, T, A>::find(const_reference key) -{ - iterator it = lower_bound(key); - if (it != m_entries.end() && key_compare::operator()(key, *it)) - { - it = m_entries.end(); - } - return it; -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::const_iterator VectorSet<K, T, A>::find(const_reference key) const -{ - const_iterator it = lower_bound(key); - if (it != m_entries.end() && key_compare::operator()(key, *it)) - { - it = m_entries.end(); - } - return it; -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::allocator_type VectorSet<K, T, A>::get_allocator() const -{ - return m_entries.get_allocator(); -} - -template <typename K, typename T, typename A> -std::pair<typename VectorSet<K, T, A>::iterator, bool> VectorSet<K, T, A>::insert(const_reference value) -{ - iterator it = lower_bound(value); - bool insertionMade = false; - if (it == m_entries.end() || key_compare::operator()(value, (*it))) - { - it = m_entries.insert(it, value), insertionMade = true; - } - return std::make_pair(it, insertionMade); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::iterator VectorSet<K, T, A>::insert(iterator where, const_reference value) -{ - return insert(value); -} - -template <typename K, typename T, typename A> -template<class InputIterator> -void VectorSet<K, T, A>::insert(InputIterator first, InputIterator last) -{ - for (; first != last; ++first) - { - insert(*first); - } -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::key_compare VectorSet<K, T, A>::key_comp() const -{ - return static_cast<key_compare>(*this); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::const_iterator VectorSet<K, T, A>::lower_bound(const_reference key) const -{ - return std::lower_bound(m_entries.begin(), m_entries.end(), key, static_cast<key_compare>(*this)); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::iterator VectorSet<K, T, A>::lower_bound(const_reference key) -{ - return std::lower_bound(m_entries.begin(), m_entries.end(), key, static_cast<key_compare>(*this)); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::size_type VectorSet<K, T, A>::max_size() const -{ - return m_entries.max_size(); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::const_reverse_iterator VectorSet<K, T, A>::rbegin() const -{ - return m_entries.rbegin(); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::reverse_iterator VectorSet<K, T, A>::rbegin() -{ - return m_entries.rbegin(); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::const_reverse_iterator VectorSet<K, T, A>::rend() const -{ - return m_entries.rend(); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::reverse_iterator VectorSet<K, T, A>::rend() -{ - return m_entries.rend(); -} - -template <typename K, typename T, typename A> -void VectorSet<K, T, A>::reserve(size_type count) -{ - m_entries.reserve(count); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::size_type VectorSet<K, T, A>::size() const -{ - return m_entries.size(); -} - -template <typename K, typename T, typename A> -void VectorSet<K, T, A>::swap(VectorSet& other) -{ - m_entries.swap(other.m_entries); - std::swap(static_cast<key_compare&>(*this), static_cast<key_compare&>(other)); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::const_iterator VectorSet<K, T, A>::upper_bound(const_reference key) const -{ - const_iterator upper = lower_bound(key); - if (upper != m_entries.end() && !key_compare::operator()(key, *upper)) - { - ++upper; - } - return upper; -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::iterator VectorSet<K, T, A>::upper_bound(const_reference key) -{ - iterator upper = lower_bound(key); - if (upper != m_entries.end() && !key_compare::operator()(key, *upper)) - { - ++upper; - } - return upper; -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::value_compare VectorSet<K, T, A>::value_comp() const -{ - return static_cast<key_compare>(*this); -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::reference VectorSet<K, T, A>::operator[](int index) -{ - return m_entries[index]; -} - -template <typename K, typename T, typename A> -typename VectorSet<K, T, A>::const_reference VectorSet<K, T, A>::operator[](int index) const -{ - return m_entries[index]; -} - -#endif // CRYINCLUDE_CRYCOMMON_VECTORSET_H diff --git a/Code/CryEngine/CryCommon/Vertex.h b/Code/CryEngine/CryCommon/Vertex.h deleted file mode 100644 index 26d62f4a60..0000000000 --- a/Code/CryEngine/CryCommon/Vertex.h +++ /dev/null @@ -1,1088 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once -#include <AzCore/std/containers/vector.h> -#include <AzCore/std/string/string.h> -#include <AzCore/std/containers/array.h> -namespace AZ -{ - namespace Vertex - { - const uint32_t VERTEX_BUFFER_ALIGNMENT = 4; - // This enum must only have 8 entries because only 3 bits are used to store usage. - enum class AttributeUsage : uint8 - { - Position, - Color, - Normal, - TexCoord, - Weights, - Indices, - Tangent, - BiTangent, - NumUsages - }; - - struct AttributeUsageData - { - AZStd::string friendlyName; - AZStd::string semanticName; - }; - - static AttributeUsageData AttributeUsageDataTable[(uint)AttributeUsage::NumUsages] = - { - // {friendlyName, semanticName} - { "Position", "POSITION" }, - { "Color", "COLOR" }, - { "Normal", "NORMAL" }, - { "TexCoord", "TEXCOORD" }, - { "Weights", "BLENDWEIGHT" }, - { "Indices", "BLENDINDICES" }, - { "Tangent", "TEXCOORD" }, - { "BiTangent", "TEXCOORD" } - }; - - // This enum must have 32 or less entries as 5 bits are used to store type. - enum class AttributeType : uint8 - { - Float16_1 = 0, - Float16_2, - Float16_4, - - Float32_1, - Float32_2, - Float32_3, - Float32_4, - - Byte_1, - Byte_2, - Byte_4, - - Short_1, - Short_2, - Short_4, - - UInt16_1, - UInt16_2, - UInt16_4, - - UInt32_1, - UInt32_2, - UInt32_3, - UInt32_4, - - NumTypes - }; - - struct AttributeTypeData - { - AZStd::string friendlyName; - uint8 byteSize; - }; - - static AttributeTypeData AttributeTypeDataTable[(unsigned int)AZ::Vertex::AttributeType::NumTypes] = - { - { "Float16_1", 2 }, - { "Float16_2", 4 }, - { "Float16_4", 8 }, - - { "Float32_1", 4 }, - { "Float32_2", 8 }, - { "Float32_3", 12 }, - { "Float32_4", 16 }, - - { "Byte_1", 1 }, - { "Byte_2", 2 }, - { "Byte_4", 4 }, - - { "Short_1", 2 }, - { "Short_2", 4 }, - { "Short_4", 8 }, - - { "UInt16_1", 2 }, - { "UInt16_2", 4 }, - { "UInt16_4", 8 }, - - { "UInt32_1", 4 }, - { "UInt32_2", 8 }, - { "UInt32_3", 12 }, - { "UInt32_4", 16 }, - }; - - //! Stores the usage, type, and byte length of an individual vertex attribute - class Attribute - { - public: - // Usage stored in the 3 lower bits and Type stored in the 5 upper bits. - static const uint8 kUsageBitCount = 3; - static const uint8 kUsageMask = 0x07; - static const uint8 kTypeMask = 0xf8; - static uint8 CreateAttribute(AttributeUsage usage, AttributeType type) - { - return (static_cast<uint8>(type) << kUsageBitCount) | static_cast<uint8>(usage); - } - static AttributeUsage GetUsage(const uint8 attribute) - { - return static_cast<AttributeUsage>(attribute & kUsageMask); - } - static AttributeType GetType(const uint8 attribute) - { - return static_cast<AttributeType>((attribute & kTypeMask) >> kUsageBitCount); - } - static uint8 GetByteLength(const uint8 attribute) - { - return AttributeTypeDataTable[(uint)GetType(attribute)].byteSize; - } - static const AZStd::string& GetSemanticName(uint8 attribute) - { - return AttributeUsageDataTable[(uint)GetUsage(attribute)].semanticName; - } - }; - - //! Flexible vertex format class - class Format - { - public: - Format(){}; - - - //! Conversion from old hard-coded EVertexFormat enum to new, flexible vertex class - Format(EVertexFormat format) - { - m_enum = eVF_Unknown; - m_numAttributes = 0; - switch (format) - { - case eVF_Unknown: - m_enum = eVF_Unknown; - break; - case eVF_P3F_C4B_T2F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Byte_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - m_enum = eVF_P3F_C4B_T2F; - break; - case eVF_P3F_C4B_T2F_T2F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Byte_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - m_enum = eVF_P3F_C4B_T2F_T2F; - break; - case eVF_P3S_C4B_T2S: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float16_4));// vec3f16 is backed by a CryHalf4 - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Byte_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float16_2)); - m_enum = eVF_P3S_C4B_T2S; - break; - case eVF_P3S_C4B_T2S_T2S: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float16_4));// vec3f16 is backed by a CryHalf4 - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Byte_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float16_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float16_2)); - m_enum = eVF_P3S_C4B_T2S_T2S; - break; - case eVF_P3S_N4B_C4B_T2S: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float16_4));// vec3f16 is backed by a CryHalf4 - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Normal, AttributeType::Byte_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Byte_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float16_2)); - m_enum = eVF_P3S_N4B_C4B_T2S; - break; - case eVF_P3F_C4B_T4B_N3F2: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Byte_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Byte_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Tangent, AttributeType::Float32_3));//x-axis - AddAttribute(Attribute::CreateAttribute(AttributeUsage::BiTangent, AttributeType::Float32_3));//y-axis -#ifdef PARTICLE_MOTION_BLUR // Nonfunctional and disabled. - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3));//prevPos - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Tangent, AttributeType::Float32_3));//prevXTan - AddAttribute(Attribute::CreateAttribute(AttributeUsage::BiTangent, AttributeType::Float32_3));//prevYTan -#endif - m_enum = eVF_P3F_C4B_T4B_N3F2;// Particles. - break; - case eVF_TP3F_C4B_T2F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Byte_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - m_enum = eVF_TP3F_C4B_T2F;// Fonts (28 bytes). - break; - case eVF_TP3F_T2F_T3F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - m_enum = eVF_TP3F_T2F_T3F; - break; - case eVF_P3F_T3F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - m_enum = eVF_P3F_T3F; // Miscellaneus. - break; - case eVF_P3F_T2F_T3F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - m_enum = eVF_P3F_T2F_T3F; - break; - // Additional streams - case eVF_T2F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - m_enum = eVF_T2F; // Light maps TC (8 bytes). - break; - case eVF_W4B_I4S:// Skinned weights/indices stream. - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Weights, AttributeType::Byte_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Indices, AttributeType::UInt16_4)); - m_enum = eVF_W4B_I4S; - break; - case eVF_C4B_C4B:// SH coefficients. - // We use the "Weights" usage since sh coefs use an unknown usage of 4 bytes. - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Weights, AttributeType::Byte_4)); //coef0 - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Weights, AttributeType::Byte_4)); //coef1 - m_enum = eVF_C4B_C4B; - break; - case eVF_P3F_P3F_I4B:// Shape deformation stream. - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); //thin - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); //fat - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Indices, AttributeType::Byte_4)); - m_enum = eVF_P3F_P3F_I4B; - break; - case eVF_P3F:// Velocity stream. - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - m_enum = eVF_P3F; - break; - case eVF_C4B_T2S: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Byte_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float16_2)); - m_enum = eVF_C4B_T2S;// General (Position is merged with Tangent stream) - break; - case eVF_P2F_T4F_C4F: // Lens effects simulation - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - m_enum = eVF_P2F_T4F_C4F; - break; - case eVF_P2F_T4F_T4F_C4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - m_enum = eVF_P2F_T4F_T4F_C4F; - break; - case eVF_P2S_N4B_C4B_T1F:// terrain - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float16_2));// xy-coordinates in terrain - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Normal, AttributeType::Byte_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Byte_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1));// z-coordinate in terrain - m_enum = eVF_P2S_N4B_C4B_T1F; - break; - case eVF_P3F_C4B_T2S: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Byte_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float16_2)); - m_enum = eVF_P3F_C4B_T2S; - break; - case eVF_P2F_C4B_T2F_F4B: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Byte_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Indices, AttributeType::UInt16_2)); - m_enum = eVF_P2F_C4B_T2F_F4B; - break; - case eVF_P3F_C4B: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Byte_4)); - m_enum = eVF_P3F_C4B; - break; - case eVF_P3F_C4F_T2F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - m_enum = eVF_P3F_C4F_T2F; - break; - case eVF_P3F_C4F_T2F_T3F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - m_enum = eVF_P3F_C4F_T2F_T3F; - break; - case eVF_P3F_C4F_T2F_T3F_T3F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - m_enum = eVF_P3F_C4F_T2F_T3F_T3F; - break; - case eVF_P3F_C4F_T2F_T1F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - m_enum = eVF_P3F_C4F_T2F_T1F; - break; - case eVF_P3F_C4F_T2F_T1F_T3F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - m_enum = eVF_P3F_C4F_T2F_T1F_T3F; - break; - case eVF_P3F_C4F_T2F_T1F_T3F_T3F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - m_enum = eVF_P3F_C4F_T2F_T1F_T3F_T3F; - break; - case eVF_P3F_C4F_T4F_T2F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - m_enum = eVF_P3F_C4F_T4F_T2F; - break; - case eVF_P3F_C4F_T4F_T2F_T3F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - m_enum = eVF_P3F_C4F_T4F_T2F_T3F; - break; - case eVF_P3F_C4F_T4F_T2F_T3F_T3F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - m_enum = eVF_P3F_C4F_T4F_T2F_T3F_T3F; - break; - case eVF_P3F_C4F_T4F_T2F_T1F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - m_enum = eVF_P3F_C4F_T4F_T2F_T1F; - break; - case eVF_P3F_C4F_T4F_T2F_T1F_T3F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - m_enum = eVF_P3F_C4F_T4F_T2F_T1F_T3F; - break; - case eVF_P3F_C4F_T4F_T2F_T1F_T3F_T3F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - m_enum = eVF_P3F_C4F_T4F_T2F_T1F_T3F_T3F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T3F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T3F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T3F_T3F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T3F_T3F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T1F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T1F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T3F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T3F; - break; - case eVF_P4F_T2F_C4F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P4F_T2F_C4F_T4F_T4F; - break; - case eVF_P3F_C4F_T2F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T4F; - break; - case eVF_P3F_C4F_T2F_T3F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T3F_T4F; - break; - case eVF_P3F_C4F_T2F_T3F_T3F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T3F_T3F_T4F; - break; - case eVF_P3F_C4F_T2F_T1F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T1F_T4F; - break; - case eVF_P3F_C4F_T2F_T1F_T3F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T1F_T3F_T4F; - break; - case eVF_P3F_C4F_T2F_T1F_T3F_T3F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T1F_T3F_T3F_T4F; - break; - case eVF_P3F_C4F_T4F_T2F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T4F_T2F_T4F; - break; - case eVF_P3F_C4F_T4F_T2F_T3F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T4F_T2F_T3F_T4F; - break; - case eVF_P3F_C4F_T4F_T2F_T3F_T3F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T4F_T2F_T3F_T3F_T4F; - break; - case eVF_P3F_C4F_T4F_T2F_T1F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T4F_T2F_T1F_T4F; - break; - case eVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F; - break; - case eVF_P3F_C4F_T4F_T2F_T1F_T3F_T3F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T4F_T2F_T1F_T3F_T3F_T4F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T4F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T3F_T3F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T3F_T3F_T4F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T3F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T3F_T4F; - break; - case eVF_P4F_T2F_C4F_T4F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P4F_T2F_C4F_T4F_T4F_T4F; - break; - case eVF_P3F_C4F_T2F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T4F_T4F; - break; - case eVF_P3F_C4F_T2F_T3F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T3F_T4F_T4F; - break; - case eVF_P3F_C4F_T2F_T3F_T3F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T3F_T3F_T4F_T4F; - break; - case eVF_P3F_C4F_T2F_T1F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T1F_T4F_T4F; - break; - case eVF_P3F_C4F_T2F_T1F_T3F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T1F_T3F_T4F_T4F; - break; - case eVF_P3F_C4F_T2F_T1F_T3F_T3F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T1F_T3F_T3F_T4F_T4F; - break; - case eVF_P3F_C4F_T4F_T2F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T4F_T2F_T4F_T4F; - break; - case eVF_P3F_C4F_T4F_T2F_T3F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T4F_T2F_T3F_T4F_T4F; - break; - case eVF_P3F_C4F_T4F_T2F_T3F_T3F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T4F_T2F_T3F_T3F_T4F_T4F; - break; - case eVF_P3F_C4F_T4F_T2F_T1F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T4F_T2F_T1F_T4F_T4F; - break; - case eVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F_T4F; - break; - case eVF_P3F_C4F_T4F_T2F_T1F_T3F_T3F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T4F_T2F_T1F_T3F_T3F_T4F_T4F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T4F_T4F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F_T4F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T3F_T3F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T3F_T3F_T4F_T4F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F_T4F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F_T4F; - break; - case eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T3F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_1)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_3)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T3F_T4F_T4F; - break; - case eVF_P4F_T2F_C4F_T4F_T4F_T4F_T4F: - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Position, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_2)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::Color, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - AddAttribute(Attribute::CreateAttribute(AttributeUsage::TexCoord, AttributeType::Float32_4)); - m_enum = eVF_P4F_T2F_C4F_T4F_T4F_T4F_T4F; - break; - case eVF_Max: - default: - AZ_Error("VF", false, "Invalid vertex format"); - m_enum = eVF_Unknown; - } - CalculateStrideAndUsageCounts(); - } - - //! Get the equivalent old-style EVertexFormat enum - uint GetEnum() const { return m_enum; } - - static const uint8 kHas16BitFloatPosition = 0x4; - static const uint8 kHas16BitFloatTexCoords = 0x2; - static const uint8 kHas32BitFloatTexCoords = 0x1; - - - //! Helper function to check to see if the vertex format has a position attribute that uses 16 bit floats for the underlying type - bool Has16BitFloatPosition() const - { - return (m_flags & kHas16BitFloatPosition) != 0x0; - } - - //! Helper function to check to see if the vertex format has a texture coordinate attribute that uses 16 bit floats for the underlying type - bool Has16BitFloatTextureCoordinates() const - { - return (m_flags & kHas16BitFloatTexCoords) != 0x0; - } - - //! Helper function to check to see if the vertex format has a texture coordinate attribute that uses 32 bit floats for the underlying type - bool Has32BitFloatTextureCoordinates() const - { - return (m_flags & kHas32BitFloatTexCoords) != 0x0; - } - - - uint32 GetAttributeUsageCount(AttributeUsage usage) const - { - return (uint32)m_attributeUsageCounts[(uint)usage]; - } - - bool TryGetAttributeOffsetAndType(AttributeUsage usage, uint32 index, uint& outOffset, AttributeType& outType) const - { - outOffset = 0; - outType = AttributeType::NumTypes; - for (uint ii=0; ii < m_numAttributes; ++ii) - { - uint8 attribute = m_vertexAttributes[ii]; - if (Attribute::GetUsage(attribute) == usage) - { - if (index == 0) - { - outType = Attribute::GetType(attribute); - return true; - } - else - { - --index; - } - } - outOffset += Attribute::GetByteLength(attribute); - } - return false; - } - - uint8 GetAttributeByteLength(AttributeUsage usage) const - { - for (uint ii = 0; ii < m_numAttributes; ++ii) - { - uint8 attribute = m_vertexAttributes[ii]; - if (Attribute::GetUsage(attribute) == usage) - { - return Attribute::GetByteLength(attribute); - } - } - return 0; - } - - - const uint8* GetAttributes( uint32 &outCount) const - { - outCount = m_numAttributes; - return m_vertexAttributes; - } - - //! Return true if the vertex format is a superset of the input - bool IsSupersetOf(const AZ::Vertex::Format& input) const - { - uint32 count = 0; - const uint8* attributes = input.GetAttributes(count); - for ( uint8 ii=0; ii<count; ++ii) - { - const uint8 attribute = attributes[ii]; - if (GetAttributeUsageCount(Attribute::GetUsage(attribute)) < input.GetAttributeUsageCount(Attribute::GetUsage(attribute))) - { - return false; - } - } - return true; - } - - uint GetStride(void) const { return m_stride; } - - //! Returns the true if an attribute with the given usage is found, false otherwise - bool TryCalculateOffset(uint& offset, AttributeUsage usage, uint index = 0) const - { - offset = 0; - for (uint ii = 0; ii < m_numAttributes; ++ii) - { - uint8 attribute = m_vertexAttributes[ii]; - if (Attribute::GetUsage(attribute) == usage) - { - if (index == 0) - { - return true; - } - else - { - --index; - } - } - offset += Attribute::GetByteLength(attribute); - } - return false; - } - - // Quick comparison operators. - bool operator==(const Format& other) const - { - return m_enum == other.m_enum; - } - bool operator!=(const Format& other) const - { - return !(*this == other); - } - bool operator==(const EVertexFormat& other) const - { - return m_enum == other; - } - // Used in RendermeshMerger.cpp - // CHWShader_D3D::mfUpdateFXVertexFormat and CHWShader_D3D::mfVertexFormat want the max between two vertex formats...why? It seems like a bad guess of which vertex format to use since there's no particular order to EVertexFormats...other than the more specialized EVertexFormats come after the base EVertexFormats - bool operator<(const Format& other) const - { - return m_enum < other.m_enum; - } - bool operator<=(const Format& other) const - { - return (*this == other || *this < other); - } - bool operator>(const Format& other) const - { - return !(*this <= other); - } - bool operator>=(const Format& other) const - { - return (*this == other || *this > other); - } - private: - void AddAttribute(uint8 attribute) - { - AZ_Assert(m_numAttributes < kMaxAttributes, "Too many attributes added. Change the size of kMaxAttributes"); - m_vertexAttributes[m_numAttributes++] = attribute; - - // Update the flags. - AttributeUsage usage = Attribute::GetUsage(attribute); - AttributeType type = Attribute::GetType(attribute); - if (usage == AttributeUsage::TexCoord) - { - if (type == AttributeType::Float16_2) { - m_flags |= kHas16BitFloatTexCoords; - } - else if (type == AttributeType::Float32_2 || type == AttributeType::Float32_3 || type == AttributeType::Float32_4) { - m_flags |= kHas32BitFloatTexCoords; - } - } - else if (usage == AttributeUsage::Position && type == AttributeType::Float16_4) { - m_flags |= kHas16BitFloatPosition; - } - } - - //! Calculates the sum of the size in bytes of all attributes that make up this format - void CalculateStrideAndUsageCounts() - { - static_assert((uint32)AttributeUsage::NumUsages <= 8, "We use 3 bits to represent usage so we only support 8 usages for a vertex format attribute."); - static_assert((uint32)AttributeType::NumTypes <= 32, "We use 5 bits to represent type so we only support up to 32 types for a vertex format attribute."); - - for (uint index = 0; index < (uint)AttributeUsage::NumUsages; ++index) - { - m_attributeUsageCounts[index] = 0; - } - uint32 stride = 0; - for (uint ii = 0; ii < m_numAttributes; ++ii) - { - uint8 attribute = m_vertexAttributes[ii]; - stride += Attribute::GetByteLength(attribute); - m_attributeUsageCounts[(uint)Attribute::GetUsage(attribute)]++; - } - AZ_Assert(stride < (0x1 << (sizeof(m_stride) * 8)), "Vertex stride is larger than the maximum supported, update the type for m_stride in Vertex.h"); - - m_stride = stride; - } - - - -#ifdef PARTICLE_MOTION_BLUR - static const uint32_t kMaxAttributes = 8; -#else - static const uint32_t kMaxAttributes = 10; -#endif - uint8 m_vertexAttributes[kMaxAttributes] = { 0 }; - - uint8 m_attributeUsageCounts[(uint)AttributeUsage::NumUsages] = { 0 }; - uint8 m_numAttributes = 0; - uint8 m_enum = eVF_Unknown; - uint8 m_stride = 0; - uint8 m_flags = 0x0; - }; - - - // bNeedNormals=1 - float normals; bNeedNormals=2 - byte normals //waltont TODO (this was copied as is from vertexformats.h) this comment is out of date and the function does not even use all the parameters. This should be replaceable with the new vertex class, and should be replaced when refactoring CHWShader_D3D::mfVertexFormat which handles the shader parsing/serialization - _inline Format VertFormatForComponents([[maybe_unused]] bool bNeedCol, [[maybe_unused]] bool bHasTC, bool bHasTC2, bool bHasPS, bool bHasNormal) - { - AZ::Vertex::Format RequestedVertFormat; - - if (bHasPS) - { - RequestedVertFormat = AZ::Vertex::Format(eVF_P3F_C4B_T4B_N3F2); - } - else - if (bHasNormal) - { - RequestedVertFormat = AZ::Vertex::Format(eVF_P3S_N4B_C4B_T2S); - } - else - { - if (!bHasTC2) - { - RequestedVertFormat = AZ::Vertex::Format(eVF_P3S_C4B_T2S); - } - else - { - RequestedVertFormat = AZ::Vertex::Format(eVF_P3F_C4B_T2F_T2F); - } - } - - return RequestedVertFormat; - } - } -} diff --git a/Code/CryEngine/CryCommon/VertexFormats.h b/Code/CryEngine/CryCommon/VertexFormats.h deleted file mode 100644 index 5cfc210a28..0000000000 --- a/Code/CryEngine/CryCommon/VertexFormats.h +++ /dev/null @@ -1,1386 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_VERTEXFORMATS_H -#define CRYINCLUDE_CRYCOMMON_VERTEXFORMATS_H - -#pragma once - -#include <CryArray.h> -// Stream Configuration options -#define ENABLE_NORMALSTREAM_SUPPORT 1 - -enum EVertexFormat : uint8 -{ - eVF_Unknown, - - // Base stream - eVF_P3F_C4B_T2F, - eVF_P3F_C4B_T2F_T2F, - eVF_P3S_C4B_T2S, - eVF_P3S_C4B_T2S_T2S, // For UV2 support - eVF_P3S_N4B_C4B_T2S, - - eVF_P3F_C4B_T4B_N3F2, // Particles. - eVF_TP3F_C4B_T2F, // Fonts (28 bytes). - eVF_TP3F_T2F_T3F, // Miscellaneus. - eVF_P3F_T3F, // Miscellaneus. (AuxGeom) - eVF_P3F_T2F_T3F, // Miscellaneus. - - // Additional streams - eVF_T2F, // Light maps TC (8 bytes). - eVF_W4B_I4S, // Skinned weights/indices stream. - eVF_C4B_C4B, // SH coefficients. - eVF_P3F_P3F_I4B, // Shape deformation stream. - eVF_P3F, // Velocity stream. - - eVF_C4B_T2S, // General (Position is merged with Tangent stream) - - // Lens effects simulation - eVF_P2F_T4F_C4F, // primary - eVF_P2F_T4F_T4F_C4F, - - eVF_P2S_N4B_C4B_T1F, - eVF_P3F_C4B_T2S, - eVF_P2F_C4B_T2F_F4B, // UI - eVF_P3F_C4B,// Auxiliary geometry - - - eVF_P3F_C4F_T2F, //numbering for tracking the new vertex formats and for comparison with testing 23 - eVF_P3F_C4F_T2F_T3F, - eVF_P3F_C4F_T2F_T3F_T3F, - eVF_P3F_C4F_T2F_T1F, - eVF_P3F_C4F_T2F_T1F_T3F, - eVF_P3F_C4F_T2F_T1F_T3F_T3F, - eVF_P3F_C4F_T4F_T2F, - eVF_P3F_C4F_T4F_T2F_T3F, //30 - eVF_P3F_C4F_T4F_T2F_T3F_T3F, - eVF_P3F_C4F_T4F_T2F_T1F, - eVF_P3F_C4F_T4F_T2F_T1F_T3F, - eVF_P3F_C4F_T4F_T2F_T1F_T3F_T3F, - eVF_P3F_C4F_T2F_T2F_T1F, //35 - eVF_P3F_C4F_T2F_T2F_T1F_T3F, - eVF_P3F_C4F_T2F_T2F_T1F_T3F_T3F, - eVF_P3F_C4F_T2F_T2F_T1F_T1F, - eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F, - eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T3F, //40 - eVF_P4F_T2F_C4F_T4F_T4F, - eVF_P3F_C4F_T2F_T4F, - eVF_P3F_C4F_T2F_T3F_T4F, - eVF_P3F_C4F_T2F_T3F_T3F_T4F, - eVF_P3F_C4F_T2F_T1F_T4F, //45 - eVF_P3F_C4F_T2F_T1F_T3F_T4F, - eVF_P3F_C4F_T2F_T1F_T3F_T3F_T4F, - eVF_P3F_C4F_T4F_T2F_T4F, - eVF_P3F_C4F_T4F_T2F_T3F_T4F, - eVF_P3F_C4F_T4F_T2F_T3F_T3F_T4F, //50 - eVF_P3F_C4F_T4F_T2F_T1F_T4F, - eVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F, - eVF_P3F_C4F_T4F_T2F_T1F_T3F_T3F_T4F, - eVF_P3F_C4F_T2F_T2F_T1F_T4F, - eVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F, //55 - eVF_P3F_C4F_T2F_T2F_T1F_T3F_T3F_T4F, - eVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F, - eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F, - eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T3F_T4F, - eVF_P4F_T2F_C4F_T4F_T4F_T4F, //60 - eVF_P3F_C4F_T2F_T4F_T4F, - eVF_P3F_C4F_T2F_T3F_T4F_T4F, - eVF_P3F_C4F_T2F_T3F_T3F_T4F_T4F, - eVF_P3F_C4F_T2F_T1F_T4F_T4F, - eVF_P3F_C4F_T2F_T1F_T3F_T4F_T4F, //65 - eVF_P3F_C4F_T2F_T1F_T3F_T3F_T4F_T4F, - eVF_P3F_C4F_T4F_T2F_T4F_T4F, - eVF_P3F_C4F_T4F_T2F_T3F_T4F_T4F, - eVF_P3F_C4F_T4F_T2F_T3F_T3F_T4F_T4F, - eVF_P3F_C4F_T4F_T2F_T1F_T4F_T4F, //70 - eVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F_T4F, - eVF_P3F_C4F_T4F_T2F_T1F_T3F_T3F_T4F_T4F, - eVF_P3F_C4F_T2F_T2F_T1F_T4F_T4F, - eVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F_T4F, - eVF_P3F_C4F_T2F_T2F_T1F_T3F_T3F_T4F_T4F, //75 - eVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F_T4F, - eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F_T4F, - eVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T3F_T4F_T4F, - eVF_P4F_T2F_C4F_T4F_T4F_T4F_T4F, - - eVF_Max, -}; - - -typedef Vec4_tpl<int16> Vec4sf; // Used for tangents only. - -struct UCol -{ - union - { - uint32 dcolor; - uint8 bcolor[4]; - - struct - { - uint8 b, g, r, a; - }; - struct - { - uint8 z, y, x, w; - }; - }; - - // get normal vector from unsigned 8bit integers (can't point up/down and is not normal) - ILINE Vec3 GetN() - { - return Vec3 - ( - (bcolor[0] - 128.0f) / 127.5f, - (bcolor[1] - 128.0f) / 127.5f, - (bcolor[2] - 128.0f) / 127.5f - ); - } - - AUTO_STRUCT_INFO -}; - -struct Vec3f16 - : public CryHalf4 -{ - _inline Vec3f16() - { - } - _inline Vec3f16(f32 _x, f32 _y, f32 _z) - { - x = CryConvertFloatToHalf(_x); - y = CryConvertFloatToHalf(_y); - z = CryConvertFloatToHalf(_z); - w = CryConvertFloatToHalf(1.0f); - } - float operator[](int i) const - { - assert(i <= 3); - return CryConvertHalfToFloat(((CryHalf*)this)[i]); - } - _inline Vec3f16& operator = (const Vec3& sl) - { - x = CryConvertFloatToHalf(sl.x); - y = CryConvertFloatToHalf(sl.y); - z = CryConvertFloatToHalf(sl.z); - w = CryConvertFloatToHalf(1.0f); - return *this; - } - _inline Vec3f16& operator = (const Vec4A& sl) - { - x = CryConvertFloatToHalf(sl.x); - y = CryConvertFloatToHalf(sl.y); - z = CryConvertFloatToHalf(sl.z); - w = CryConvertFloatToHalf(sl.w); - return *this; - } - _inline Vec3 ToVec3() const - { - Vec3 v; - v.x = CryConvertHalfToFloat(x); - v.y = CryConvertHalfToFloat(y); - v.z = CryConvertHalfToFloat(z); - return v; - } -}; - -struct Vec2f16 - : public CryHalf2 -{ - _inline Vec2f16() - { - } - _inline Vec2f16(f32 _x, f32 _y) - { - x = CryConvertFloatToHalf(_x); - y = CryConvertFloatToHalf(_y); - } - Vec2f16& operator = (const Vec2f16& sl) - { - x = sl.x; - y = sl.y; - return *this; - } - Vec2f16& operator = (const Vec2& sl) - { - x = CryConvertFloatToHalf(sl.x); - y = CryConvertFloatToHalf(sl.y); - return *this; - } - float operator[](int i) const - { - assert(i <= 1); - return CryConvertHalfToFloat(((CryHalf*)this)[i]); - } - _inline Vec2 ToVec2() const - { - Vec2 v; - v.x = CryConvertHalfToFloat(x); - v.y = CryConvertHalfToFloat(y); - return v; - } -}; - - -struct SVF_P3F_C4B -{ - Vec3 xyz; - UCol color; -}; - -struct SVF_P3F_C4B_T2F -{ - Vec3 xyz; - UCol color; - Vec2 st; -}; - -struct SVF_P3F_C4B_T2F_T2F -{ - Vec3 xyz; - UCol color; - Vec2 st; - Vec2 st2; -}; - -struct SVF_P2F_C4B_T2F_F4B -{ - Vec2 xy; - UCol color; - Vec2 st; - uint8 texIndex; - uint8 texHasColorChannel; - uint8 texIndex2; - uint8 pad; -}; - -struct SVF_TP3F_C4B_T2F //Fonts -{ - Vec4 pos; - UCol color; - Vec2 st; -}; -struct SVF_P3S_C4B_T2S -{ - Vec3f16 xyz; - UCol color; - Vec2f16 st; - - AUTO_STRUCT_INFO -}; - -struct SVF_P3S_C4B_T2S_T2S -{ - Vec3f16 xyz; - UCol color; - Vec2f16 st; - Vec2f16 st2; - - AUTO_STRUCT_INFO -}; - -struct SVF_P3F_C4B_T2S -{ - Vec3 xyz; - UCol color; - Vec2f16 st; -}; - -struct SVF_P3S_N4B_C4B_T2S -{ - Vec3f16 xyz; - UCol normal; - UCol color; - Vec2f16 st; -}; - -struct SVF_P2S_N4B_C4B_T1F -{ - CryHalf2 xy; - UCol normal; - UCol color; - float z; -}; - -struct SVF_T2F -{ - Vec2 st; -}; -struct SVF_W4B_I4S -{ - UCol weights; - uint16 indices[4]; -}; -struct SVF_C4B_C4B -{ - UCol coef0; - UCol coef1; -}; -struct SVF_P3F_P3F_I4B -{ - Vec3 thin; - Vec3 fat; - UCol index; -}; -struct SVF_P3F -{ - Vec3 xyz; -}; -struct SVF_P3F_T3F -{ - Vec3 p; - Vec3 st; -}; -struct SVF_P3F_T2F_T3F -{ - Vec3 p; - Vec2 st0; - Vec3 st1; -}; -struct SVF_TP3F_T2F_T3F -{ - Vec4 p; - Vec2 st0; - Vec3 st1; -}; -struct SVF_P2F_T4F_C4F -{ - Vec2 p; - Vec4 st; - Vec4 color; -}; - -struct SVF_P2F_T4F_T4F_C4F -{ - Vec2 p; - Vec4 st; - Vec4 st2; - Vec4 color; -}; - -struct SVF_P3F_C4B_I4B_PS4F -{ - Vec3 xyz; - Vec2 prevXaxis; - Vec2 prevYaxis; - UCol color; - Vec3 prevPos; - struct SpriteInfo - { - uint8 tex_x, tex_y, tex_z, backlight; // xyzw - } info; - Vec2 xaxis; - Vec2 yaxis; -}; - -struct SVF_P3F_C4B_T4B_N3F2 -{ - Vec3 xyz; - UCol color; - UCol st; // st is used as a color, even though st usually refers to a TexCoord - Vec3 xaxis; - Vec3 yaxis; -#ifdef PARTICLE_MOTION_BLUR - Vec3 prevPos; - Vec3 prevXTan; - Vec3 prevYTan; -#endif -}; - -struct SVF_C4B_T2S -{ - UCol color; - Vec2f16 st; -}; - -struct SVF_P3F_C4F_T2F -{ - Vec3 xyz; - Vec4 color; - Vec2 st; -}; - -struct SVF_P3F_C4F_T2F_T3F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec3 st1; -}; - -struct SVF_P3F_C4F_T2F_T3F_T3F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec3 st1; - Vec3 st2; -}; - -struct SVF_P3F_C4F_T2F_T1F -{ - Vec3 xyz; - Vec4 color; - Vec2 st; - float z; -}; - -struct SVF_P3F_C4F_T2F_T1F_T3F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - float z; - Vec3 st1; -}; - -struct SVF_P3F_C4F_T2F_T1F_T3F_T3F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - float z; - Vec3 st1; - Vec3 st2; -}; - - -struct SVF_P3F_C4F_T4F_T2F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; -}; - -struct SVF_P3F_C4F_T4F_T2F_T3F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - Vec3 st2; -}; - -struct SVF_P3F_C4F_T4F_T2F_T3F_T3F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - Vec3 st2; - Vec3 st3; -}; - -struct SVF_P3F_C4F_T4F_T2F_T1F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - float z; -}; - -struct SVF_P3F_C4F_T4F_T2F_T1F_T3F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - float z; - Vec3 st2; -}; - -struct SVF_P3F_C4F_T4F_T2F_T1F_T3F_T3F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - float z; - Vec3 st2; - Vec3 st3; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T3F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z; - Vec3 st2; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T3F_T3F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z; - Vec3 st2; - Vec3 st3; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T1F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z0; - float z1; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z0; - float z1; - Vec3 st2; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T3F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z0; - float z1; - Vec3 st2; - Vec3 st3; -}; - -struct SVF_P4F_T2F_C4F_T4F_T4F -{ - Vec4 xyzw; - Vec2 st0; - Vec4 color; - Vec4 st1; - Vec4 st2; -}; - -struct SVF_P3F_C4F_T2F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec4 st1; -}; - -struct SVF_P3F_C4F_T2F_T3F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec3 st1; - Vec4 st2; -}; - -struct SVF_P3F_C4F_T2F_T3F_T3F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec3 st1; - Vec3 st2; - Vec4 st3; -}; - -struct SVF_P3F_C4F_T2F_T1F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - float z; - Vec4 st1; -}; - -struct SVF_P3F_C4F_T2F_T1F_T3F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - float z; - Vec3 st1; - Vec4 st2; -}; - -struct SVF_P3F_C4F_T2F_T1F_T3F_T3F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - float z; - Vec3 st1; - Vec3 st2; - Vec4 st3; -}; - -struct SVF_P3F_C4F_T4F_T2F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - Vec4 st2; -}; - -struct SVF_P3F_C4F_T4F_T2F_T3F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - Vec3 st2; - Vec4 st3; -}; - -struct SVF_P3F_C4F_T4F_T2F_T3F_T3F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - Vec3 st2; - Vec3 st3; - Vec4 st4; -}; - -struct SVF_P3F_C4F_T4F_T2F_T1F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - float z; - Vec4 st2; -}; - -struct SVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - float z; - Vec3 st2; - Vec4 st3; -}; - -struct SVF_P3F_C4F_T4F_T2F_T1F_T3F_T3F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - float z; - Vec3 st2; - Vec3 st3; - Vec4 st4; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z; - Vec4 st2; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z; - Vec3 st2; - Vec4 st3; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T3F_T3F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z; - Vec3 st2; - Vec3 st3; - Vec4 st4; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z0; - float z1; - Vec4 st2; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z0; - float z1; - Vec3 st2; - Vec4 st3; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T3F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z0; - float z1; - Vec3 st2; - Vec3 st3; - Vec4 st4; -}; - -struct SVF_P4F_T2F_C4F_T4F_T4F_T4F -{ - Vec4 xyzw; - Vec2 st0; - Vec4 color; - Vec4 st1; - Vec4 st2; - Vec4 st3; -}; - -struct SVF_P3F_C4F_T2F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec4 st1; - Vec4 st2; -}; - -struct SVF_P3F_C4F_T2F_T3F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec3 st1; - Vec4 st2; - Vec4 st3; -}; - -struct SVF_P3F_C4F_T2F_T3F_T3F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec3 st1; - Vec3 st2; - Vec4 st3; - Vec4 st4; -}; - -struct SVF_P3F_C4F_T2F_T1F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - float z; - Vec4 st1; - Vec4 st2; -}; - -struct SVF_P3F_C4F_T2F_T1F_T3F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - float z; - Vec3 st1; - Vec4 st2; - Vec4 st3; -}; - -struct SVF_P3F_C4F_T2F_T1F_T3F_T3F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - float z; - Vec3 st1; - Vec3 st2; - Vec4 st3; - Vec4 st4; -}; - -struct SVF_P3F_C4F_T4F_T2F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - Vec4 st2; - Vec4 st3; -}; - -struct SVF_P3F_C4F_T4F_T2F_T3F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - Vec3 st2; - Vec4 st3; - Vec4 st4; -}; - -struct SVF_P3F_C4F_T4F_T2F_T3F_T3F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - Vec3 st2; - Vec3 st3; - Vec4 st4; - Vec4 st5; -}; - -struct SVF_P3F_C4F_T4F_T2F_T1F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - float z; - Vec4 st2; - Vec4 st3; -}; - -struct SVF_P3F_C4F_T4F_T2F_T1F_T3F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - float z; - Vec3 st2; - Vec4 st3; - Vec4 st4; -}; - -struct SVF_P3F_C4F_T4F_T2F_T1F_T3F_T3F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec4 st0; - Vec2 st1; - float z; - Vec3 st2; - Vec3 st3; - Vec4 st4; - Vec4 st5; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z; - Vec4 st2; - Vec4 st3; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T3F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z; - Vec3 st2; - Vec4 st3; - Vec4 st4; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T3F_T3F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z; - Vec3 st2; - Vec3 st3; - Vec4 st4; - Vec4 st5; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T1F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z0; - float z1; - Vec4 st2; - Vec4 st3; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z0; - float z1; - Vec3 st2; - Vec4 st3; - Vec4 st4; -}; - -struct SVF_P3F_C4F_T2F_T2F_T1F_T1F_T3F_T3F_T4F_T4F -{ - Vec3 xyz; - Vec4 color; - Vec2 st0; - Vec2 st1; - float z0; - float z1; - Vec3 st2; - Vec3 st3; - Vec4 st4; - Vec4 st5; -}; - -struct SVF_P4F_T2F_C4F_T4F_T4F_T4F_T4F -{ - Vec4 xyzw; - Vec2 st0; - Vec4 color; - Vec4 st1; - Vec4 st2; - Vec4 st3; - Vec4 st4; -}; - - -//============================================================= -// Signed norm value packing [-1,+1] - -namespace PackingSNorm -{ - ILINE int16 tPackF2B(const float f) - { - return (int16)(f * 32767.0f); - } - - ILINE int16 tPackS2B(const int16 s) - { - return (int16)(s * 32767); - } - - ILINE float tPackB2F(const int16 i) - { - return (float)((float)i / 32767.0f); - } - - ILINE int16 tPackB2S(const int16 s) - { - // OPT: "(s >> 15) + !(s >> 15)" works as well - return (int16)(s / 32767); - } - - ILINE Vec4sf tPackF2Bv(const Vec4& v) - { - Vec4sf vs; - - vs.x = tPackF2B(v.x); - vs.y = tPackF2B(v.y); - vs.z = tPackF2B(v.z); - vs.w = tPackF2B(v.w); - - return vs; - } - - ILINE Vec4sf tPackF2Bv(const Vec3& v) - { - Vec4sf vs; - - vs.x = tPackF2B(v.x); - vs.y = tPackF2B(v.y); - vs.z = tPackF2B(v.z); - vs.w = tPackF2B(1.0f); - - return vs; - } - - ILINE Vec4 tPackB2F(const Vec4sf& v) - { - Vec4 vs; - - vs.x = tPackB2F(v.x); - vs.y = tPackB2F(v.y); - vs.z = tPackB2F(v.z); - vs.w = tPackB2F(v.w); - - return vs; - } - - ILINE void tPackB2F(const Vec4sf& v, Vec4& vDst) - { - vDst.x = tPackB2F(v.x); - vDst.y = tPackB2F(v.y); - vDst.z = tPackB2F(v.z); - vDst.w = 1.0f; - } - - ILINE void tPackB2FScale(const Vec4sf& v, Vec4& vDst, const Vec3& vScale) - { - vDst.x = (float)v.x * vScale.x; - vDst.y = (float)v.y * vScale.y; - vDst.z = (float)v.z * vScale.z; - vDst.w = 1.0f; - } - - ILINE void tPackB2FScale(const Vec4sf& v, Vec3& vDst, const Vec3& vScale) - { - vDst.x = (float)v.x * vScale.x; - vDst.y = (float)v.y * vScale.y; - vDst.z = (float)v.z * vScale.z; - } - - ILINE void tPackB2F(const Vec4sf& v, Vec3& vDst) - { - vDst.x = tPackB2F(v.x); - vDst.y = tPackB2F(v.y); - vDst.z = tPackB2F(v.z); - } -}; - -//============================================================= -// Pip => Graphics Pipeline structures, used for inputs for the GPU's Input Assembler -// These structures are optimized for fast decoding (ALU and bandwidth) and -// might be slow to encode on-the-fly - -struct SPipTangents -{ - SPipTangents() {} - -private: - Vec4sf Tangent; - Vec4sf Bitangent; - -public: - explicit SPipTangents(const Vec4sf& othert, const Vec4sf& otherb, const int16& othersign) - { - using namespace PackingSNorm; - Tangent = othert; - Tangent.w = PackingSNorm::tPackS2B(othersign); - Bitangent = otherb; - Bitangent.w = PackingSNorm::tPackS2B(othersign); - } - - explicit SPipTangents(const Vec4sf& othert, const Vec4sf& otherb, const SPipTangents& othersign) - { - Tangent = othert; - Tangent.w = othersign.Tangent.w; - Bitangent = otherb; - Bitangent.w = othersign.Bitangent.w; - } - - explicit SPipTangents(const Vec4sf& othert, const Vec4sf& otherb) - { - Tangent = othert; - Bitangent = otherb; - } - - explicit SPipTangents(const Vec3& othert, const Vec3& otherb, const int16& othersign) - { - Tangent = Vec4sf(PackingSNorm::tPackF2B(othert.x), PackingSNorm::tPackF2B(othert.y), PackingSNorm::tPackF2B(othert.z), PackingSNorm::tPackS2B(othersign)); - Bitangent = Vec4sf(PackingSNorm::tPackF2B(otherb.x), PackingSNorm::tPackF2B(otherb.y), PackingSNorm::tPackF2B(otherb.z), PackingSNorm::tPackS2B(othersign)); - } - - explicit SPipTangents(const Vec3& othert, const Vec3& otherb, const SPipTangents& othersign) - { - Tangent = Vec4sf(PackingSNorm::tPackF2B(othert.x), PackingSNorm::tPackF2B(othert.y), PackingSNorm::tPackF2B(othert.z), othersign.Tangent.w); - Bitangent = Vec4sf(PackingSNorm::tPackF2B(otherb.x), PackingSNorm::tPackF2B(otherb.y), PackingSNorm::tPackF2B(otherb.z), othersign.Bitangent.w); - } - - explicit SPipTangents(const Quat& other, const int16& othersign) - { - Vec3 othert = other.GetColumn0(); - Vec3 otherb = other.GetColumn1(); - - Tangent = Vec4sf(PackingSNorm::tPackF2B(othert.x), PackingSNorm::tPackF2B(othert.y), PackingSNorm::tPackF2B(othert.z), PackingSNorm::tPackS2B(othersign)); - Bitangent = Vec4sf(PackingSNorm::tPackF2B(otherb.x), PackingSNorm::tPackF2B(otherb.y), PackingSNorm::tPackF2B(otherb.z), PackingSNorm::tPackS2B(othersign)); - } - - void ExportTo(Vec4sf& othert, Vec4sf& otherb) const - { - othert = Tangent; - otherb = Bitangent; - } - - // get normal tangent and bitangent vectors - void GetTB(Vec4& othert, Vec4& otherb) const - { - othert = PackingSNorm::tPackB2F(Tangent); - otherb = PackingSNorm::tPackB2F(Bitangent); - } - - // get normal vector (perpendicular to tangent and bitangent plane) - ILINE Vec3 GetN() const - { - Vec4 tng, btg; - GetTB(tng, btg); - - Vec3 tng3(tng.x, tng.y, tng.z), - btg3(btg.x, btg.y, btg.z); - - // assumes w 1 or -1 - return tng3.Cross(btg3) * tng.w; - } - - // get normal vector (perpendicular to tangent and bitangent plane) - void GetN(Vec3& othern) const - { - othern = GetN(); - } - - // get the tangent-space basis as individual normal vectors (tangent, bitangent and normal) - void GetTBN(Vec3& othert, Vec3& otherb, Vec3& othern) const - { - Vec4 tng, btg; - GetTB(tng, btg); - - Vec3 tng3(tng.x, tng.y, tng.z), - btg3(btg.x, btg.y, btg.z); - - // assumes w 1 or -1 - othert = tng3; - otherb = btg3; - othern = tng3.Cross(btg3) * tng.w; - } - - // get normal vector sign (reflection) - ILINE int16 GetR() const - { - return PackingSNorm::tPackB2S(Tangent.w); - } - - // get normal vector sign (reflection) - void GetR(int16& sign) const - { - sign = GetR(); - } - - void TransformBy(const Matrix34& trn) - { - Vec4 tng, btg; - GetTB(tng, btg); - - Vec3 tng3(tng.x, tng.y, tng.z), - btg3(btg.x, btg.y, btg.z); - - tng3 = trn.TransformVector(tng3); - btg3 = trn.TransformVector(btg3); - - *this = SPipTangents(tng3, btg3, PackingSNorm::tPackB2S(Tangent.w)); - } - - void TransformSafelyBy(const Matrix34& trn) - { - Vec4 tng, btg; - GetTB(tng, btg); - - Vec3 tng3(tng.x, tng.y, tng.z), - btg3(btg.x, btg.y, btg.z); - - tng3 = trn.TransformVector(tng3); - btg3 = trn.TransformVector(btg3); - - // normalize in case "trn" wasn't length-preserving - tng3.Normalize(); - btg3.Normalize(); - - *this = SPipTangents(tng3, btg3, PackingSNorm::tPackB2S(Tangent.w)); - } - - friend struct SMeshTangents; -}; - -struct SPipQTangents -{ - SPipQTangents() {} - -private: - Vec4sf QTangent; - -public: - explicit SPipQTangents(const Vec4sf& other) - { - QTangent = other; - } - - bool operator ==(const SPipQTangents& other) const - { - return - QTangent[0] == other.QTangent[0] || - QTangent[1] == other.QTangent[1] || - QTangent[2] == other.QTangent[2] || - QTangent[3] == other.QTangent[3]; - } - - bool operator !=(const SPipQTangents& other) const - { - return !(*this == other); - } - - // get quaternion - ILINE Quat GetQ() const - { - Quat q; - - q.v.x = PackingSNorm::tPackB2F(QTangent.x); - q.v.y = PackingSNorm::tPackB2F(QTangent.y); - q.v.z = PackingSNorm::tPackB2F(QTangent.z); - q.w = PackingSNorm::tPackB2F(QTangent.w); - - return q; - } - - // get normal vector from quaternion - ILINE Vec3 GetN() const - { - const Quat q = GetQ(); - return q.GetColumn2() * (q.w < 0.0f ? -1.0f : +1.0f); - } - - friend struct SMeshQTangents; -}; - -struct SPipNormal - : public Vec3 -{ - SPipNormal() {} - - explicit SPipNormal(const Vec3& othern) - { - x = othern.x; - y = othern.y; - z = othern.z; - } - - // get normal vector - ILINE Vec3 GetN() const - { - return *this; - } - - // get normal vector - void GetN(Vec3& othern) const - { - othern = GetN(); - } - - void TransformBy(const Matrix34& trn) - { - *this = SPipNormal(trn.TransformVector(*this)); - } - - void TransformSafelyBy(const Matrix34& trn) - { - // normalize in case "trn" wasn't length-preserving - *this = SPipNormal(trn.TransformVector(*this).normalize()); - } - - friend struct SMeshNormal; -}; - -//================================================================================================== - -typedef SVF_P3F_C4B_T2F SAuxVertex; - -//////////////////////////////////////////////////////////////////////////////////////////////////// -// Vertex Sizes -//extern const int m_VertexSize[]; - -//============================================================================ -// Custom vertex streams definitions -// NOTE: If you add new stream ID also include vertex declarations creating in -// CD3D9Renderer::EF_InitD3DVertexDeclarations (D3DRendPipeline.cpp) - -// Stream IDs -enum EStreamIDs -{ - VSF_GENERAL, // General vertex buffer - VSF_TANGENTS, // Tangents buffer - VSF_QTANGENTS, // Tangents buffer - VSF_HWSKIN_INFO, // HW skinning buffer - VSF_VERTEX_VELOCITY, // Velocity buffer -# if ENABLE_NORMALSTREAM_SUPPORT - VSF_NORMALS, // Normals, used for skinning -#endif - // <- Insert new stream IDs here - VSF_NUM, // Number of vertex streams - - VSF_MORPHBUDDY = 8, // Morphing (from m_pMorphBuddy) - VSF_INSTANCED = 9, // Data is for instance stream - VSF_MORPHBUDDY_WEIGHTS = 15, // Morphing weights -}; - -// Stream Masks (Used during updating) -enum EStreamMasks -{ - VSM_GENERAL = 1 << VSF_GENERAL, - VSM_TANGENTS = ((1 << VSF_TANGENTS) | (1 << VSF_QTANGENTS)), - VSM_HWSKIN = 1 << VSF_HWSKIN_INFO, - VSM_VERTEX_VELOCITY = 1 << VSF_VERTEX_VELOCITY, -# if ENABLE_NORMALSTREAM_SUPPORT - VSM_NORMALS = 1 << VSF_NORMALS, -#endif - - VSM_MORPHBUDDY = 1 << VSF_MORPHBUDDY, - VSM_INSTANCED = 1 << VSF_INSTANCED, - - VSM_MASK = ((1 << VSF_NUM) - 1), -}; - -//================================================================================================================== - -#endif // CRYINCLUDE_CRYCOMMON_VERTEXFORMATS_H - diff --git a/Code/CryEngine/CryCommon/Win32specific.h b/Code/CryEngine/CryCommon/Win32specific.h deleted file mode 100644 index 8db99b4915..0000000000 --- a/Code/CryEngine/CryCommon/Win32specific.h +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Specific to Win32 declarations, inline functions etc. - - -#ifndef CRYINCLUDE_CRYCOMMON_WIN32SPECIFIC_H -#define CRYINCLUDE_CRYCOMMON_WIN32SPECIFIC_H -#pragma once - - -#define _CPU_X86 -#define _CPU_SSE -#ifdef _DEBUG -#define ILINE _inline -#else -#define ILINE __forceinline -#endif - -#define DEBUG_BREAK _asm { int 3 } -#define RC_EXECUTABLE "rc.exe" -#define DEPRECATED __declspec(deprecated) -#define TYPENAME(x) typeid(x).name() -#define SIZEOF_PTR 4 - -#ifndef _WIN32_WINNT -# define _WIN32_WINNT 0x501 -#endif - -////////////////////////////////////////////////////////////////////////// -// Standard includes. -////////////////////////////////////////////////////////////////////////// -#include <malloc.h> -#include <io.h> -#include <new.h> -#include <direct.h> -#include <fcntl.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <time.h> -////////////////////////////////////////////////////////////////////////// - -// Special intrinsics -#include <intrin.h> // moved here to prevent assert from being redefined when included elsewhere - - -////////////////////////////////////////////////////////////////////////// -// Define platform independent types. -////////////////////////////////////////////////////////////////////////// -#include "BaseTypes.h" - -#define THREADID_NULL -1 - -typedef unsigned char BYTE; -typedef unsigned int threadID; -typedef unsigned long DWORD; -typedef double real; // biggest float-type on this machine -typedef long LONG; - -#if defined(_WIN64) -typedef __int64 INT_PTR, * PINT_PTR; -typedef unsigned __int64 UINT_PTR, * PUINT_PTR; - -typedef __int64 LONG_PTR, * PLONG_PTR; -typedef unsigned __int64 ULONG_PTR, * PULONG_PTR; - -typedef ULONG_PTR DWORD_PTR, * PDWORD_PTR; -#else -typedef __w64 int INT_PTR, * PINT_PTR; -typedef __w64 unsigned int UINT_PTR, * PUINT_PTR; - -typedef __w64 long LONG_PTR, * PLONG_PTR; -typedef __w64 unsigned long ULONG_PTR, * PULONG_PTR; - -typedef ULONG_PTR DWORD_PTR, * PDWORD_PTR; -#endif - -typedef void* THREAD_HANDLE; -typedef void* EVENT_HANDLE; - -////////////////////////////////////////////////////////////////////////// -// Multi platform Hi resolution ticks function, should only be used for profiling. -////////////////////////////////////////////////////////////////////////// - - -int64 CryGetTicks(); -int64 CryGetTicksPerSec(); - -#ifndef SAFE_DELETE -#define SAFE_DELETE(p) { if (p) { delete (p); (p) = NULL; } \ -} -#endif - -#ifndef SAFE_DELETE_ARRAY -#define SAFE_DELETE_ARRAY(p) { if (p) { delete [] (p); (p) = NULL; } \ -} -#endif - -#ifndef SAFE_RELEASE -#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p) = NULL; } \ -} -#endif - -#define _MS_ALIGN(num) \ - AZ_PUSH_DISABLE_WARNING(4324, "-Wunknown-warning-option") \ - __declspec(align(num)) - -#define DEFINE_ALIGNED_DATA(type, name, alignment) _declspec(align(alignment)) type name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) static _declspec(align(alignment)) type name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) const _declspec(align(alignment)) type name; - -#ifndef FILE_ATTRIBUTE_NORMAL - #define FILE_ATTRIBUTE_NORMAL 0x00000080 -#endif - -#define FP16_TERRAIN -#define TARGET_DEFAULT_ALIGN (0x4U) - - -#endif // CRYINCLUDE_CRYCOMMON_WIN32SPECIFIC_H diff --git a/Code/CryEngine/CryCommon/Win64specific.h b/Code/CryEngine/CryCommon/Win64specific.h deleted file mode 100644 index cd493150f1..0000000000 --- a/Code/CryEngine/CryCommon/Win64specific.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Specific to Win32 declarations, inline functions etc. - - -#ifndef CRYINCLUDE_CRYCOMMON_WIN64SPECIFIC_H -#define CRYINCLUDE_CRYCOMMON_WIN64SPECIFIC_H -#pragma once - - -#define _CPU_AMD64 -#define _CPU_SSE -#define ILINE __forceinline - -#define DEBUG_BREAK CryDebugBreak() -#define RC_EXECUTABLE "rc.exe" -#define DEPRECATED __declspec(deprecated) -#define TYPENAME(x) typeid(x).name() -#define SIZEOF_PTR 8 - -#ifndef _WIN32_WINNT -# define _WIN32_WINNT 0x501 -#endif - -////////////////////////////////////////////////////////////////////////// -// Standard includes. -////////////////////////////////////////////////////////////////////////// -#include <stdexcept> -#include <malloc.h> -#include <io.h> -#include <new.h> -#include <direct.h> -#include <fcntl.h> -#include <sys/types.h> -#include <sys/stat.h> -#include <time.h> -////////////////////////////////////////////////////////////////////////// - -// Special intrinsics -#include <math.h> // Should be included before intrin.h -#include <intrin.h> - -////////////////////////////////////////////////////////////////////////// -// Define platform independent types. -////////////////////////////////////////////////////////////////////////// -#include "BaseTypes.h" - -#define THREADID_NULL -1 -typedef long LONG; -typedef unsigned char BYTE; -typedef unsigned long threadID; -typedef unsigned long DWORD; -typedef double real; //biggest float-type on this machine -typedef long LONG; - -typedef void* THREAD_HANDLE; -typedef void* EVENT_HANDLE; - -typedef __int64 INT_PTR, * PINT_PTR; -typedef unsigned __int64 UINT_PTR, * PUINT_PTR; - -typedef __int64 LONG_PTR, * PLONG_PTR; -typedef unsigned __int64 ULONG_PTR, * PULONG_PTR; - -typedef ULONG_PTR DWORD_PTR, * PDWORD_PTR; - -int64 CryGetTicks(); -int64 CryGetTicksPerSec(); - -#ifndef SAFE_DELETE -#define SAFE_DELETE(p) { if (p) { delete (p); (p) = NULL; } \ -} -#endif - -#ifndef SAFE_DELETE_ARRAY -#define SAFE_DELETE_ARRAY(p) { if (p) { delete [] (p); (p) = NULL; } \ -} -#endif - -#ifndef SAFE_RELEASE -#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p) = NULL; } \ -} -#endif - -#define _MS_ALIGN(num) \ - AZ_PUSH_DISABLE_WARNING(4324, "-Wunknown-warning-option") \ - __declspec(align(num)) - -#define DEFINE_ALIGNED_DATA(type, name, alignment) _declspec(align(alignment)) type name; -#define DEFINE_ALIGNED_DATA_STATIC(type, name, alignment) static _declspec(align(alignment)) type name; -#define DEFINE_ALIGNED_DATA_CONST(type, name, alignment) const _declspec(align(alignment)) type name; - -#define SIZEOF_PTR 8 - -#ifndef FILE_ATTRIBUTE_NORMAL - #define FILE_ATTRIBUTE_NORMAL 0x00000080 -#endif - -#define TARGET_DEFAULT_ALIGN (0x8U) - -#define PLATFORM_64BIT - -#endif // CRYINCLUDE_CRYCOMMON_WIN64SPECIFIC_H diff --git a/Code/CryEngine/CryCommon/WinBase.cpp b/Code/CryEngine/CryCommon/WinBase.cpp deleted file mode 100644 index 552d207934..0000000000 --- a/Code/CryEngine/CryCommon/WinBase.cpp +++ /dev/null @@ -1,1667 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Linux/Mac port support for Win32API calls -#if !defined(WIN32) - -#include "platform.h" // Note: This should be first to get consistent debugging definitions - -#include <CryAssert.h> - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define WINBASE_CPP_SECTION_1 1 -#define WINBASE_CPP_SECTION_2 2 -#define WINBASE_CPP_SECTION_3 3 -#define WINBASE_CPP_SECTION_4 4 -#define WINBASE_CPP_SECTION_5 5 -#define WINBASE_CPP_SECTION_6 6 -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION WINBASE_CPP_SECTION_1 - #include AZ_RESTRICTED_FILE(WinBase_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - #include <signal.h> -#endif - -#include <pthread.h> -#include <sys/types.h> -#include <fcntl.h> -#include <AzCore/IO/SystemFile.h> - -#ifdef APPLE -#include <mach/mach.h> -#include <mach/mach_time.h> -#include <sys/sysctl.h> // for total physical memory on Mac -#include <CoreFoundation/CoreFoundation.h> // for CryMessageBox -#include <mach/vm_statistics.h> // host_statistics -#include <mach/mach_types.h> -#include <mach/mach_init.h> -#include <mach/mach_host.h> -#endif - -#if defined(ANDROID) -#define FIX_FILENAME_CASE 0 // everything is lower case on android -#elif defined(LINUX) || defined(APPLE) -#define FIX_FILENAME_CASE 1 -#endif - -#include <sys/time.h> - - - -#if !defined(_RELEASE) || defined(_DEBUG) -#include <set> -unsigned int g_EnableMultipleAssert = 0;//set to something else than 0 if to enable already reported asserts -#endif - -#if defined(LINUX) || defined(APPLE) -#include <sys/types.h> -#include <unistd.h> -#include <utime.h> -#include <dirent.h> -#include "CryLibrary.h" -#endif - -#if defined(APPLE) - #include <AzFramework/Utils/SystemUtilsApple.h> -#endif - -#include "StringUtils.h" - -#if AZ_TRAIT_COMPILER_DEFINE_FS_ERRNO_TYPE -typedef int FS_ERRNO_TYPE; -#if AZ_TRAIT_COMPILER_DEFINE_FS_STAT_TYPE -typedef struct stat FS_STAT_TYPE; -#else -typedef struct stat64 FS_STAT_TYPE; -#endif -static const int FS_O_RDWR = O_RDWR; -static const int FS_O_RDONLY = O_RDONLY; -static const int FS_O_WRONLY = O_WRONLY; -static const FS_ERRNO_TYPE FS_EISDIR = EISDIR; - -#include <mutex> - -#elif AZ_TRAIT_COMPILER_DEFINE_FS_STAT_TYPE -#error cannot request AZ_TRAIT_COMPILER_DEFINE_FS_STAT_TYPE if AZ_TRAIT_COMPILER_DEFINE_FS_ERRNO_TYPE is zero -#endif - -#if AZ_TRAIT_COMPILER_DEFINE_SASSERTDATA_TYPE && (!defined(_RELEASE) || defined(_DEBUG)) -struct SAssertData -{ - int line; - char fileName[256 - sizeof(int)]; - const bool operator==(const SAssertData& crArg) const - { - return crArg.line == line && (strcmp(fileName, crArg.fileName) == 0); - } - - const bool operator<(const SAssertData& crArg) const - { - if (line == crArg.line) - { - return strcmp(fileName, crArg.fileName) < 0; - } - else - { - return line < crArg.line; - } - } - - SAssertData() - : line(-1){} - SAssertData(const int cLine, const char* cpFile) - : line(cLine) - { - azstrcpy(fileName, AZ_ARRAY_SIZE(fileName), cpFile); - } - - SAssertData(const SAssertData& crAssertData) - { - memcpy((void*)this, &crAssertData, sizeof(SAssertData)); - } - - void operator=(const SAssertData& crAssertData) - { - memcpy((void*)this, &crAssertData, sizeof(SAssertData)); - } -}; - - -//#define OUTPUT_ASSERT_TO_FILE - -void HandleAssert(const char* cpMessage, const char* cpFunc, const char* cpFile, const int cLine) -{ -#if defined(OUTPUT_ASSERT_TO_FILE) - static FILE* pAssertLogFile = nullptr; - if (!pAssertLogFile) - { - azfopen(&pAssertLogFile, "Assert.log", "w+"); - } -#endif - bool report = true; - static std::set<SAssertData> assertSet; - SAssertData assertData(cLine, cpFile); - if (!g_EnableMultipleAssert) - { - std::set<SAssertData>::const_iterator it = assertSet.find(assertData); - if (it != assertSet.end()) - { - report = false; - } - else - { - assertSet.insert(assertData); - } - } - else - { - assertSet.insert(assertData); - } - if (report) - { - //added function to be able to place a breakpoint here or to print out to other consoles - printf("ASSERT: %s in %s (%s : %d)\n", cpMessage, cpFunc, cpFile, cLine); -#if defined(OUTPUT_ASSERT_TO_FILE) - if (pAssertLogFile) - { - fprintf(pAssertLogFile, "ASSERT: %s in %s (%s : %d)\n", cpMessage, cpFunc, cpFile, cLine); - fflush(pAssertLogFile); - } -#endif - } -} -#endif - - -bool IsBadReadPtr(void* ptr, unsigned int size) -{ - //too complicated to really support it - return ptr ? false : true; -} - -////////////////////////////////////////////////////////////////////////// -char* _strtime(char* date) -{ - azstrcpy(date, AZ_ARRAY_SIZE(date), "0:0:0"); - return date; -} - -////////////////////////////////////////////////////////////////////////// -char* _strdate(char* date) -{ - azstrcpy(date, AZ_ARRAY_SIZE(date), "0"); - return date; -} - -////////////////////////////////////////////////////////////////////////// -char* strlwr (char* str) -{ - char* cp; /* traverses string for C locale conversion */ - - for (cp = str; *cp; ++cp) - { - if ('A' <= *cp && *cp <= 'Z') - { - *cp += 'a' - 'A'; - } - } - return str; -} - -char* strupr (char* str) -{ - char* cp; /* traverses string for C locale conversion */ - - for (cp = str; *cp; ++cp) - { - if ('a' <= *cp && *cp <= 'z') - { - *cp += 'A' - 'a'; - } - } - return str; -} - -char* ltoa (long i, char* a, int radix) -{ - if (a == NULL) - { - return NULL; - } - strcpy (a, "0"); - if (i && radix > 1 && radix < 37) - { - char buf[35]; - unsigned long u = i, p = 34; - buf[p] = 0; - if (i < 0 && radix == 10) - { - u = -i; - } - while (u) - { - unsigned int d = u % radix; - buf[--p] = d < 10 ? '0' + d : 'a' + d - 10; - u /= radix; - } - if (i < 0 && radix == 10) - { - buf[--p] = '-'; - } - strcpy (a, buf + p); - } - return a; -} - - -#if AZ_TRAIT_COMPILER_DEFINE_WCSICMP -// For Linux it's redefined to wcscasecmp and wcsncasecmp' -int wcsicmp (const wchar_t* s1, const wchar_t* s2) -{ - wint_t c1, c2; - - if (s1 == s2) - { - return 0; - } - - do - { - c1 = towlower(*s1++); - c2 = towlower(*s2++); - } - while (c1 && c1 == c2); - - return (int) (c1 - c2); -} - -int wcsnicmp (const wchar_t* s1, const wchar_t* s2, size_t count) -{ - wint_t c1, c2; - if (s1 == s2 || count == 0) - { - return 0; - } - - do - { - c1 = towlower(*s1++); - c2 = towlower(*s2++); - } - while ((--count) && c1 && (c1 == c2)); - return (int) (c1 - c2); -} -#endif - -#if defined(ANDROID) -// not defined in android-19 or prior -size_t wcsnlen(const wchar_t* str, size_t maxLen) -{ - size_t length; - for (length = 0; length < maxLen; ++length, ++str) - { - if (!*str) - { - break; - } - } - return length; -} - -char* stpcpy(char* dest, const char* str) -{ - while (*str != '\0') - { - *dest++ = *str++; - } - *dest = '\0'; - - return dest; -} -#endif - -void _makepath(char* path, const char* drive, const char* dir, const char* filename, const char* ext) -{ - char ch; - char tmp[MAX_PATH]; - if (!path) - { - return; - } - tmp[0] = '\0'; - if (drive && drive[0]) - { - tmp[0] = drive[0]; - tmp[1] = ':'; - tmp[2] = 0; - } - if (dir && dir[0]) - { - cry_strcat(tmp, dir); - ch = tmp[strlen(tmp) - 1]; - if (ch != '/' && ch != '\\') - { - cry_strcat(tmp, "\\"); - } - } - if (filename && filename[0]) - { - cry_strcat(tmp, filename); - if (ext && ext[0]) - { - if (ext[0] != '.') - { - cry_strcat(tmp, "."); - } - cry_strcat(tmp, ext); - } - } - azstrcpy(path, strlen(tmp) + 1, tmp); -} - -char* _ui64toa(unsigned long long value, char* str, int radix) -{ - if (str == 0) - { - return 0; - } - - char buffer[65]; - char* pos; - int digit; - - pos = &buffer[64]; - *pos = '\0'; - - do - { - digit = value % radix; - value = value / radix; - if (digit < 10) - { - *--pos = '0' + digit; - } - else - { - *--pos = 'a' + digit - 10; - } /* if */ - } while (value != 0L); - - memcpy(str, pos, &buffer[64] - pos + 1); - return str; -} - -long long _atoi64(const char* str) -{ - if (str == 0) - { - return -1; - } - unsigned long long RunningTotal = 0; - char bMinus = 0; - while (*str == ' ' || (*str >= '\011' && *str <= '\015')) - { - str++; - } /* while */ - if (*str == '+') - { - str++; - } - else if (*str == '-') - { - bMinus = 1; - str++; - } /* if */ - while (*str >= '0' && *str <= '9') - { - RunningTotal = RunningTotal * 10 + *str - '0'; - str++; - } /* while */ - return bMinus ? ((long long)-RunningTotal) : (long long)RunningTotal; -} - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION WINBASE_CPP_SECTION_2 - #include AZ_RESTRICTED_FILE(WinBase_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -bool QueryPerformanceCounter(LARGE_INTEGER* counter) -{ -#if defined(LINUX) - // replaced gettimeofday - // http://fixunix.com/kernel/378888-gettimeofday-resolution-linux.html - timespec tv; - clock_gettime(CLOCK_MONOTONIC, &tv); - counter->QuadPart = (uint64)tv.tv_sec * 1000000 + tv.tv_nsec / 1000; - return true; -#elif defined(APPLE) - counter->QuadPart = mach_absolute_time(); - return true; -#else - return false; -#endif -} - -bool QueryPerformanceFrequency(LARGE_INTEGER* frequency) -{ -#if defined(LINUX) - // On Linux we'll use gettimeofday(). The API resolution is microseconds, - // so we'll report that to the caller. - frequency->u.LowPart = 1000000; - frequency->u.HighPart = 0; - return true; -#elif defined(APPLE) - static mach_timebase_info_data_t s_kTimeBaseInfoData; - if (s_kTimeBaseInfoData.denom == 0) - { - mach_timebase_info(&s_kTimeBaseInfoData); - } - // mach_timebase_info_data_t expresses the tick period in nanoseconds - frequency->QuadPart = 1e+9 * (uint64_t)s_kTimeBaseInfoData.denom / (uint64_t)s_kTimeBaseInfoData.numer; - return true; -#else - return false; -#endif -} -#endif - -void _splitpath(const char* inpath, char* drv, char* dir, char* fname, char* ext) -{ - if (drv) - { - drv[0] = 0; - } - - typedef CryStackStringT<char, AZ_MAX_PATH_LEN> path_stack_string; - - const path_stack_string inPath(inpath); - string::size_type s = inPath.rfind('/', inPath.size());//position of last / - path_stack_string fName; - if (s == string::npos) - { - if (dir) - { - dir[0] = 0; - } - fName = inpath; //assign complete string as rest - } - else - { - if (dir) - { - azstrcpy(dir, AZ_MAX_PATH_LEN, (inPath.substr((string::size_type)0, (string::size_type)(s + 1))).c_str()); //assign directory - } - fName = inPath.substr((string::size_type)(s + 1)); //assign remaining string as rest - } - if (fName.size() == 0) - { - if (ext) - { - ext[0] = 0; - } - if (fname) - { - fname[0] = 0; - } - } - else - { - //dir and drive are now set - s = fName.find(".", (string::size_type)0);//position of first . - if (s == string::npos) - { - if (ext) - { - ext[0] = 0; - } - if (fname) - { - azstrcpy(fname, fName.size() + 1, fName.c_str()); //assign filename - } - } - else - { - if (ext) - { - azstrcpy(ext, AZ_MAX_PATH_LEN, (fName.substr(s)).c_str()); //assign extension including . - } - if (fname) - { - if (s == 0) - { - fname[0] = 0; - } - else - { - azstrcpy(fname, AZ_MAX_PATH_LEN, (fName.substr((string::size_type)0, s)).c_str()); //assign filename - } - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -int memicmp(LPCSTR s1, LPCSTR s2, DWORD len) -{ - int ret = 0; - while (len--) - { - if ((ret = tolower(*s1) - tolower(*s2))) - { - break; - } - s1++; - s2++; - } - return ret; -} - -//-----------------------------------------other stuff------------------------------------------------------------------- - -void GlobalMemoryStatus(LPMEMORYSTATUS lpmem) -{ - //not complete implementation -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION WINBASE_CPP_SECTION_3 - #include AZ_RESTRICTED_FILE(WinBase_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(APPLE) - - // Retrieve dwTotalPhys - int kMIB[] = {CTL_HW, HW_MEMSIZE}; - uint64_t dwTotalPhys; - size_t ulength = sizeof(dwTotalPhys); - if (sysctl(kMIB, 2, &dwTotalPhys, &ulength, NULL, 0) != 0) - { - gEnv->pLog->LogError("sysctl failed\n"); - } - else - { - lpmem->dwTotalPhys = static_cast<SIZE_T>(dwTotalPhys); - } - - // Get the page size - mach_port_t kHost(mach_host_self()); - vm_size_t uPageSize; - if (host_page_size(kHost, &uPageSize) != 0) - { - gEnv->pLog->LogError("host_page_size failed\n"); - } - else - { - // Get memory statistics - vm_statistics_data_t kVMStats; - mach_msg_type_number_t uCount(sizeof(kVMStats) / sizeof(natural_t)); - if (host_statistics(kHost, HOST_VM_INFO, (host_info_t)&kVMStats, &uCount) != 0) - { - gEnv->pLog->LogError("host_statistics failed\n"); - } - else - { - // Calculate dwAvailPhys - lpmem->dwAvailPhys = uPageSize * kVMStats.free_count; - } - } -#else - FILE* f; - lpmem->dwMemoryLoad = 0; - lpmem->dwTotalPhys = 16 * 1024 * 1024; - lpmem->dwAvailPhys = 16 * 1024 * 1024; - lpmem->dwTotalPageFile = 16 * 1024 * 1024; - lpmem->dwAvailPageFile = 16 * 1024 * 1024; - azfopen(&f, "/proc/meminfo", "r"); - if (f) - { - char buffer[256]; - memset(buffer, '0', 256); - int total, used, free, shared, buffers, cached; - - lpmem->dwLength = sizeof(MEMORYSTATUS); - lpmem->dwTotalPhys = lpmem->dwAvailPhys = 0; - lpmem->dwTotalPageFile = lpmem->dwAvailPageFile = 0; - while (fgets(buffer, sizeof(buffer), f)) - { - if (azsscanf(buffer, "Mem: %d %d %d %d %d %d", &total, &used, &free, &shared, &buffers, &cached)) - { - lpmem->dwTotalPhys += total; - lpmem->dwAvailPhys += free + buffers + cached; - } - if (azsscanf(buffer, "Swap: %d %d %d", &total, &used, &free)) - { - lpmem->dwTotalPageFile += total; - lpmem->dwAvailPageFile += free; - } - if (azsscanf(buffer, "MemTotal: %d", &total)) - { - lpmem->dwTotalPhys = total * 1024; - } - if (azsscanf(buffer, "MemFree: %d", &free)) - { - lpmem->dwAvailPhys = free * 1024; - } - if (azsscanf(buffer, "SwapTotal: %d", &total)) - { - lpmem->dwTotalPageFile = total * 1024; - } - if (azsscanf(buffer, "SwapFree: %d", &free)) - { - lpmem->dwAvailPageFile = free * 1024; - } - if (azsscanf(buffer, "Buffers: %d", &buffers)) - { - lpmem->dwAvailPhys += buffers * 1024; - } - if (azsscanf(buffer, "Cached: %d", &cached)) - { - lpmem->dwAvailPhys += cached * 1024; - } - } - fclose(f); - if (lpmem->dwTotalPhys) - { - DWORD TotalPhysical = lpmem->dwTotalPhys + lpmem->dwTotalPageFile; - DWORD AvailPhysical = lpmem->dwAvailPhys + lpmem->dwAvailPageFile; - lpmem->dwMemoryLoad = (TotalPhysical - AvailPhysical) / (TotalPhysical / 100); - } - } -#endif -} - -static const int YearLengths[2] = {DAYSPERNORMALYEAR, DAYSPERLEAPYEAR}; -static const int MonthLengths[2][MONSPERYEAR] = -{ - { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, - { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } -}; - -static int IsLeapYear(int Year) -{ - return Year % 4 == 0 && (Year % 100 != 0 || Year % 400 == 0) ? 1 : 0; -} - -static void NormalizeTimeFields(short* FieldToNormalize, short* CarryField, int Modulus) -{ - *FieldToNormalize = (short) (*FieldToNormalize - Modulus); - *CarryField = (short) (*CarryField + 1); -} - -bool TimeFieldsToTime(PTIME_FIELDS tfTimeFields, PLARGE_INTEGER Time) -{ - #define SECSPERMIN 60 - #define MINSPERHOUR 60 - #define HOURSPERDAY 24 - #define MONSPERYEAR 12 - - #define EPOCHYEAR 1601 - - #define SECSPERDAY 86400 - #define TICKSPERMSEC 10000 - #define TICKSPERSEC 10000000 - #define SECSPERHOUR 3600 - - int CurYear, CurMonth; - LONGLONG rcTime; - TIME_FIELDS TimeFields = *tfTimeFields; - - rcTime = 0; - while (TimeFields.Second >= SECSPERMIN) - { - NormalizeTimeFields(&TimeFields.Second, &TimeFields.Minute, SECSPERMIN); - } - while (TimeFields.Minute >= MINSPERHOUR) - { - NormalizeTimeFields(&TimeFields.Minute, &TimeFields.Hour, MINSPERHOUR); - } - while (TimeFields.Hour >= HOURSPERDAY) - { - NormalizeTimeFields(&TimeFields.Hour, &TimeFields.Day, HOURSPERDAY); - } - while (TimeFields.Day > MonthLengths[IsLeapYear(TimeFields.Year)][TimeFields.Month - 1]) - { - NormalizeTimeFields(&TimeFields.Day, &TimeFields.Month, SECSPERMIN); - } - while (TimeFields.Month > MONSPERYEAR) - { - NormalizeTimeFields(&TimeFields.Month, &TimeFields.Year, MONSPERYEAR); - } - for (CurYear = EPOCHYEAR; CurYear < TimeFields.Year; CurYear++) - { - rcTime += YearLengths[IsLeapYear(CurYear)]; - } - for (CurMonth = 1; CurMonth < TimeFields.Month; CurMonth++) - { - rcTime += MonthLengths[IsLeapYear(CurYear)][CurMonth - 1]; - } - rcTime += TimeFields.Day - 1; - rcTime *= SECSPERDAY; - rcTime += TimeFields.Hour * SECSPERHOUR + TimeFields.Minute * SECSPERMIN + TimeFields.Second; - - rcTime *= TICKSPERSEC; - rcTime += TimeFields.Milliseconds * TICKSPERMSEC; - - Time->QuadPart = rcTime; - - return true; -} - -BOOL SystemTimeToFileTime(const SYSTEMTIME* syst, LPFILETIME ft) -{ - TIME_FIELDS tf; - LARGE_INTEGER t; - - tf.Year = syst->wYear; - tf.Month = syst->wMonth; - tf.Day = syst->wDay; - tf.Hour = syst->wHour; - tf.Minute = syst->wMinute; - tf.Second = syst->wSecond; - tf.Milliseconds = syst->wMilliseconds; - - TimeFieldsToTime(&tf, &t); - ft->dwLowDateTime = t.u.LowPart; - ft->dwHighDateTime = t.u.HighPart; - return TRUE; -} - -void adaptFilenameToLinux(string& rAdjustedFilename) -{ - //first replace all \\ by / - string::size_type loc = 0; - while ((loc = rAdjustedFilename.find("\\", loc)) != string::npos) - { - rAdjustedFilename.replace(loc, 1, "/"); - } - loc = 0; - //remove /./ - while ((loc = rAdjustedFilename.find("/./", loc)) != string::npos) - { - rAdjustedFilename.replace(loc, 3, "/"); - } -} - -void replaceDoublePathFilename(char* szFileName) -{ - //replace "\.\" by "\" - string s(szFileName); - string::size_type loc = 0; - //remove /./ - while ((loc = s.find("/./", loc)) != string::npos) - { - s.replace(loc, 3, "/"); - } - loc = 0; - //remove "\.\" - while ((loc = s.find("\\.\\", loc)) != string::npos) - { - s.replace(loc, 3, "\\"); - } - azstrcpy((char*)szFileName, AZ_MAX_PATH_LEN, s.c_str()); -} - -const int comparePathNames(const char* cpFirst, const char* cpSecond, unsigned int len) -{ - //create two strings and replace the \\ by / and /./ by / - string first(cpFirst); - string second(cpSecond); - adaptFilenameToLinux(first); - adaptFilenameToLinux(second); - if (strlen(cpFirst) < len || strlen(cpSecond) < len) - { - return -1; - } - unsigned int length = std::min(std::min(first.size(), second.size()), (size_t)len); //make sure not to access invalid memory - return memicmp(first.c_str(), second.c_str(), length); -} - -#if defined(LINUX) || defined(APPLE) || defined(DEFINE_FIX_ONE_PATH_ELEMENT) -static bool FixOnePathElement(char* path) -{ - if (*path == '\0') - { - return true; - } - - if ((path[0] == '/') && (path[1] == '\0')) - { - return true; // root dir always exists. - } - if (strchr(path, '*') || strchr(path, '?')) - { - return true; // wildcard...stop correcting path. - } - struct stat statbuf; - if (stat(path, &statbuf) != -1) // current case exists. - { - return true; - } - - char* name = path; - char* ptr = strrchr(path, '/'); - if (ptr) - { - name = ptr + 1; - *ptr = '\0'; - } - - if (*name == '\0') // trailing '/' ? - { - *ptr = '/'; - return true; - } - - const char* parent; - if (ptr == path) - { - parent = "/"; - } - else if (ptr == NULL) - { - parent = "."; - } - else - { - parent = path; - } - - DIR* dirp = opendir(parent); - if (ptr) - { - *ptr = '/'; - } - - if (dirp == NULL) - { - return false; - } - - struct dirent* dent; - bool found = false; - while ((dent = readdir(dirp)) != NULL) - { - if (strcasecmp(dent->d_name, name) == 0) - { - azstrcpy(name, AZ_MAX_PATH_LEN, dent->d_name); - found = true; - break; - } - } - - closedir(dirp); - return found; -} -#endif - -#define Int32x32To64(a, b) ((uint64)((uint64)(a)) * (uint64)((uint64)(b))) - -////////////////////////////////////////////////////////////////////////// -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION WINBASE_CPP_SECTION_4 - #include AZ_RESTRICTED_FILE(WinBase_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -threadID GetCurrentThreadId() -{ - return threadID(pthread_self()); -} -#endif - -////////////////////////////////////////////////////////////////////////// -HANDLE CreateEvent -( - LPSECURITY_ATTRIBUTES lpEventAttributes, - BOOL bManualReset, - BOOL bInitialState, - LPCSTR lpName -) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "CreateEvent not implemented yet"); - return 0; -} - - -////////////////////////////////////////////////////////////////////////// -DWORD Sleep(DWORD dwMilliseconds) -{ -#if defined(LINUX) || defined(APPLE) - timespec req; - timespec rem; - - memset(&req, 0, sizeof(req)); - memset(&rem, 0, sizeof(rem)); - - time_t sec = (int)(dwMilliseconds / 1000); - req.tv_sec = sec; - req.tv_nsec = (dwMilliseconds - (sec * 1000)) * 1000000L; - if (nanosleep(&req, &rem) == -1) - { - nanosleep(&rem, 0); - } - - return 0; -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION WINBASE_CPP_SECTION_5 - #include AZ_RESTRICTED_FILE(WinBase_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - timeval tv, start, now; - uint64 tStart; - - memset(&tv, 0, sizeof tv); - memset(&start, 0, sizeof start); - memset(&now, 0, sizeof now); - gettimeofday(&now, NULL); - start = now; - tStart = (uint64)start.tv_sec * 1000000 + start.tv_usec; - while (true) - { - uint64 tNow, timePassed, timeRemaining; - tNow = (uint64)now.tv_sec * 1000000 + now.tv_usec; - timePassed = tNow - tStart; - if (timePassed >= dwMilliseconds) - { - break; - } - timeRemaining = dwMilliseconds * 1000 - timePassed; - tv.tv_sec = timeRemaining / 1000000; - tv.tv_usec = timeRemaining % 1000000; - select(1, NULL, NULL, NULL, &tv); - gettimeofday(&now, NULL); - } - return 0; -#endif -} - -////////////////////////////////////////////////////////////////////////// -DWORD SleepEx(DWORD dwMilliseconds, BOOL bAlertable) -{ - //TODO: implement - // CRY_ASSERT_MESSAGE(0, "SleepEx not implemented yet"); - printf("SleepEx not properly implemented yet\n"); - Sleep(dwMilliseconds); - return 0; -} - -////////////////////////////////////////////////////////////////////////// -DWORD WaitForSingleObjectEx(HANDLE hHandle, DWORD dwMilliseconds, BOOL bAlertable) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "WaitForSingleObjectEx not implemented yet"); - return 0; -} - -#if 0 -////////////////////////////////////////////////////////////////////////// -DWORD WaitForMultipleObjectsEx( - DWORD nCount, - const HANDLE* lpHandles, - BOOL bWaitAll, - DWORD dwMilliseconds, - BOOL bAlertable) -{ - //TODO: implement - return 0; -} -#endif - -////////////////////////////////////////////////////////////////////////// -DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "WaitForSingleObject not implemented yet"); - return 0; -} - -////////////////////////////////////////////////////////////////////////// -BOOL SetEvent(HANDLE hEvent) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "SetEvent not implemented yet"); - return TRUE; -} - -////////////////////////////////////////////////////////////////////////// -BOOL ResetEvent(HANDLE hEvent) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "ResetEvent not implemented yet"); - return TRUE; -} - -////////////////////////////////////////////////////////////////////////// -HANDLE CreateMutex -( - LPSECURITY_ATTRIBUTES lpMutexAttributes, - BOOL bInitialOwner, - LPCSTR lpName -) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "CreateMutex not implemented yet"); - return 0; -} - -////////////////////////////////////////////////////////////////////////// -BOOL ReleaseMutex(HANDLE hMutex) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "ReleaseMutex not implemented yet"); - return TRUE; -} - -////////////////////////////////////////////////////////////////////////// - - -typedef DWORD (* PTHREAD_START_ROUTINE)(LPVOID lpThreadParameter); -typedef PTHREAD_START_ROUTINE LPTHREAD_START_ROUTINE; - -////////////////////////////////////////////////////////////////////////// -HANDLE CreateThread -( - LPSECURITY_ATTRIBUTES lpThreadAttributes, - SIZE_T dwStackSize, - LPTHREAD_START_ROUTINE lpStartAddress, - LPVOID lpParameter, - DWORD dwCreationFlags, - LPDWORD lpThreadId -) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "CreateThread not implemented yet"); - return 0; -} - -#if defined(LINUX) || defined(APPLE) -BOOL GetComputerName(LPSTR lpBuffer, LPDWORD lpnSize) -{ - if (!lpBuffer || !lpnSize) - { - return FALSE; - } - - int err = gethostname(lpBuffer, *lpnSize); - - if (-1 == err) - { - CryLog("GetComputerName falied [%d]\n", errno); - return FALSE; - } - return TRUE; -} -#endif - -#if AZ_TRAIT_COMPILER_DEFINE_GETCURRENTPROCESSID -DWORD GetCurrentProcessId(void) -{ - return (DWORD)getpid(); -} -#endif - -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -void CrySleep(unsigned int dwMilliseconds) -{ - Sleep(dwMilliseconds); -} - -////////////////////////////////////////////////////////////////////////// -void CryLowLatencySleep(unsigned int dwMilliseconds) -{ -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION WINBASE_CPP_SECTION_6 - #include AZ_RESTRICTED_FILE(WinBase_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - CrySleep(dwMilliseconds); -#endif -} - -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -int CryMessageBox(const char* lpText, const char* lpCaption, unsigned int uType) -{ -#ifdef WIN32 -# error WIN32 is defined in WinBase.cpp (it is a non-Windows file) -#elif defined(MAC) - CFStringRef strText = CFStringCreateWithCString(NULL, lpText, kCFStringEncodingMacRoman); - CFStringRef strCaption = CFStringCreateWithCString(NULL, lpCaption, kCFStringEncodingMacRoman); - - CFStringRef strOk = CFSTR("OK"); - CFStringRef strCancel = CFSTR("Cancel"); - CFStringRef strRetry = CFSTR("Retry"); - CFStringRef strYes = CFSTR("Yes"); - CFStringRef strNo = CFSTR("No"); - CFStringRef strAbort = CFSTR("Abort"); - CFStringRef strIgnore = CFSTR("Ignore"); - CFStringRef strTryAgain = CFSTR("Try Again"); - CFStringRef strContinue = CFSTR("Continue"); - - CFStringRef defaultButton = nullptr; - CFStringRef alternativeButton = nullptr; - CFStringRef otherButton = nullptr; - - switch (uType & 0xf) - { - case MB_OKCANCEL: - defaultButton = strOk; - alternativeButton = strCancel; - break; - case MB_ABORTRETRYIGNORE: - defaultButton = strAbort; - alternativeButton = strRetry; - otherButton = strIgnore; - break; - case MB_YESNOCANCEL: - defaultButton = strYes; - alternativeButton = strNo; - otherButton = strCancel; - break; - case MB_YESNO: - defaultButton = strYes; - alternativeButton = strNo; - break; - case MB_RETRYCANCEL: - defaultButton = strRetry; - alternativeButton = strCancel; - break; - case MB_CANCELTRYCONTINUE: - defaultButton = strCancel; - alternativeButton = strTryAgain; - otherButton = strContinue; - break; - case MB_OK: - default: - defaultButton = strOk; - break; - } - - CFOptionFlags kResult; - CFUserNotificationDisplayAlert( - 0, // no timeout - kCFUserNotificationNoteAlertLevel, //change it depending message_type flags ( MB_ICONASTERISK.... etc.) - NULL, //icon url, use default, you can change it depending message_type flags - NULL, //not used - NULL, //localization of strings - strText, //header text - strCaption, //message text - defaultButton, //default "ok" text in button - alternativeButton, //alternate button title - otherButton, //other button title, null--> no other button - &kResult //response flags - ); - - if (strCaption) - { - CFRelease(strCaption); - } - if (strText) - { - CFRelease(strText); - } - - if (kResult == kCFUserNotificationDefaultResponse) - { - switch (uType & 0xf) - { - case MB_OK: - case MB_OKCANCEL: - default: - return IDOK; - case MB_ABORTRETRYIGNORE: - return IDABORT; - case MB_YESNOCANCEL: - case MB_YESNO: - return IDYES; - case MB_RETRYCANCEL: - return IDRETRY; - case MB_CANCELTRYCONTINUE: - return IDCANCEL; - } - } - else if (kResult == kCFUserNotificationAlternateResponse) - { - switch (uType & 0xf) - { - case MB_OKCANCEL: - case MB_RETRYCANCEL: - return IDCANCEL; - case MB_ABORTRETRYIGNORE: - return IDRETRY; - case MB_YESNOCANCEL: - case MB_YESNO: - return IDNO; - case MB_CANCELTRYCONTINUE: - return IDTRYAGAIN; - default: - assert(false); - return IDCANCEL; - } - } - else if (kResult == kCFUserNotificationOtherResponse) - { - switch (uType & 0xf) - { - case MB_ABORTRETRYIGNORE: - return IDIGNORE; - case MB_YESNOCANCEL: - return IDCANCEL; - case MB_CANCELTRYCONTINUE: - return IDCONTINUE; - default: - assert(false); - return IDCANCEL; - } - } - return 0; -#else - printf("Messagebox: cap: %s text:%s\n", lpCaption ? lpCaption : " ", lpText ? lpText : " "); - return 0; -#endif -} - -////////////////////////////////////////////////////////////////////////// -short CryGetAsyncKeyState(int vKey) -{ - //TODO: implement - CRY_ASSERT_MESSAGE(0, "CryGetAsyncKeyState not implemented yet"); - return 0; -} - -#if defined(LINUX) || defined(APPLE) || defined(DEFINE_CRY_INTERLOCKED_INCREMENT) -//[K01]: http://www.memoryhole.net/kyle/2007/05/atomic_incrementing.html -//http://forums.devx.com/archive/index.php/t-160558.html -////////////////////////////////////////////////////////////////////////// -DLL_EXPORT LONG CryInterlockedIncrement(LONG volatile* lpAddend) -{ - /*int r; - __asm__ __volatile__ ( - "lock ; xaddl %0, (%1) \n\t" - : "=r" (r) - : "r" (lpAddend), "0" (1) - : "memory" - ); - return (LONG) (r + 1); */// add, since we get the original value back. - return __sync_fetch_and_add(lpAddend, 1) + 1; -} - -////////////////////////////////////////////////////////////////////////// -DLL_EXPORT LONG CryInterlockedDecrement(LONG volatile* lpAddend) -{ - /*int r; - __asm__ __volatile__ ( - "lock ; xaddl %0, (%1) \n\t" - : "=r" (r) - : "r" (lpAddend), "0" (-1) - : "memory" - ); - return (LONG) (r - 1); */// subtract, since we get the original value back. - return __sync_fetch_and_sub(lpAddend, 1) - 1; -} - -////////////////////////////////////////////////////////////////////////// -DLL_EXPORT LONG CryInterlockedExchangeAdd(LONG volatile* lpAddend, LONG Value) -{ - /* LONG r; - __asm__ __volatile__ ( - #if defined(LINUX64) || defined(APPLE) // long is 64 bits on amd64. - "lock ; xaddq %0, (%1) \n\t" - #else - "lock ; xaddl %0, (%1) \n\t" - #endif - : "=r" (r) - : "r" (lpAddend), "0" (Value) - : "memory" - ); - return r;*/ - return __sync_fetch_and_add(lpAddend, Value); -} - -DLL_EXPORT LONG CryInterlockedOr(LONG volatile* Destination, LONG Value) -{ - return __sync_fetch_and_or(Destination, Value); -} - -DLL_EXPORT LONG CryInterlockedCompareExchange(LONG volatile* dst, LONG exchange, LONG comperand) -{ - return __sync_val_compare_and_swap(dst, comperand, exchange); - /*LONG r; - __asm__ __volatile__ ( - #if defined(LINUX64) || defined(APPLE) // long is 64 bits on amd64. - "lock ; cmpxchgq %2, (%1) \n\t" - #else - "lock ; cmpxchgl %2, (%1) \n\t" - #endif - : "=a" (r) - : "r" (dst), "r" (exchange), "0" (comperand) - : "memory" - ); - return r;*/ -} - - -DLL_EXPORT void* CryInterlockedCompareExchangePointer(void* volatile* dst, void* exchange, void* comperand) -{ - return __sync_val_compare_and_swap(dst, comperand, exchange); - //return (void*)CryInterlockedCompareExchange((long volatile*)dst, (long)exchange, (long)comperand); -} - -DLL_EXPORT void* CryInterlockedExchangePointer(void* volatile* dst, void* exchange) -{ - __sync_synchronize(); - return __sync_lock_test_and_set(dst, exchange); - //return (void*)CryInterlockedCompareExchange((long volatile*)dst, (long)exchange, (long)comperand); -} - -#if (defined(LINUX64) && !defined(ANDROID)) || defined(MAC) || defined(IOS_SIMULATOR) -DLL_EXPORT unsigned char _InterlockedCompareExchange128(int64 volatile* dst, int64 exchangehigh, int64 exchangelow, int64* comperand) -{ - bool bEquals; - __asm__ __volatile__ - ( - "lock cmpxchg16b %1\n\t" - "setz %0" - : "=q" (bEquals), "+m" (*dst), "+d" (comperand[1]), "+a" (comperand[0]) - : "c" (exchangehigh), "b" (exchangelow) - : "cc" - ); - return (char)bEquals; -} -#elif defined(INTERLOCKED_COMPARE_EXCHANGE_128_NOT_SUPPORTED) - // arm64 processors do not provide a cmpxchg16b (or equivalent) instruction, - // so _InterlockedCompareExchange128 is not implemented on arm64 platforms. -#endif - -threadID CryGetCurrentThreadId() -{ - return GetCurrentThreadId(); -} - -void CryDebugBreak() -{ - __builtin_trap(); -} -#endif//LINUX APPLE - -#if defined(APPLE) || defined(LINUX) -// WinAPI debug functions. -DLL_EXPORT void OutputDebugString(const char* outputString) -{ -#if !defined(_RELEASE) - // Emulates dev tools output in Xcode and cmd line launch with idevicedebug. - fprintf(stdout, "%s", outputString); -#endif -} - -DLL_EXPORT void DebugBreak() -{ - CryDebugBreak(); -} - -#endif - -// This code does not have a long life span and will be replaced soon -#if defined(APPLE) || defined(LINUX) || defined(DEFINE_LEGACY_CRY_FILE_OPERATIONS) - -typedef DIR* FS_DIR_TYPE; -typedef dirent FS_DIRENT_TYPE; -static const FS_ERRNO_TYPE FS_ENOENT = ENOENT; -static const FS_ERRNO_TYPE FS_EINVAL = EINVAL; -static const FS_DIR_TYPE FS_DIR_NULL = NULL; -static const unsigned char FS_TYPE_DIRECTORY = DT_DIR; - -typedef int FS_ERRNO_TYPE; - -#if defined(APPLE) -typedef struct stat FS_STAT_TYPE; -#else -typedef struct stat64 FS_STAT_TYPE; -#endif - -#include <mutex> - -bool CrySetFileAttributes(const char* lpFileName, uint32 dwFileAttributes) -{ - //TODO: implement - printf("CrySetFileAttributes not properly implemented yet\n"); - return false; -} - - -ILINE void FS_OPEN(const char* szFileName, int iFlags, int& iFileDesc, mode_t uMode, FS_ERRNO_TYPE& rErr) -{ - rErr = ((iFileDesc = open(szFileName, iFlags, uMode)) != -1) ? 0 : errno; -} - -ILINE void FS_CLOSE(int iFileDesc, FS_ERRNO_TYPE& rErr) -{ - rErr = close(iFileDesc) != -1 ? 0 : errno; -} - -ILINE void FS_CLOSE_NOERR(int iFileDesc) -{ - close(iFileDesc); -} - -ILINE void FS_OPENDIR(const char* szDirName, FS_DIR_TYPE& pDir, FS_ERRNO_TYPE& rErr) -{ - rErr = (pDir = opendir(szDirName)) != NULL ? 0 : errno; -} - -ILINE void FS_READDIR(FS_DIR_TYPE pDir, FS_DIRENT_TYPE& kEnt, uint64_t& uEntSize, FS_ERRNO_TYPE& rErr) -{ - errno = 0; // errno is used to determine if readdir succeeds after - FS_DIRENT_TYPE* pDirent(readdir(pDir)); - if (pDirent == NULL) - { - uEntSize = 0; - rErr = (errno == FS_ENOENT) ? 0 : errno; - } - else - { - kEnt = *pDirent; - uEntSize = static_cast<uint64_t>(sizeof(FS_DIRENT_TYPE)); - rErr = 0; - } -} - -ILINE void FS_STAT(const char* szFileName, FS_STAT_TYPE& kStat, FS_ERRNO_TYPE& rErr) -{ -#if defined(APPLE) - rErr = stat(szFileName, &kStat) != -1 ? 0 : errno; -#else - rErr = stat64(szFileName, &kStat) != -1 ? 0 : errno; -#endif -} - -ILINE void FS_FSTAT(int iFileDesc, FS_STAT_TYPE& kStat, FS_ERRNO_TYPE& rErr) -{ -#if defined(APPLE) - rErr = fstat(iFileDesc, &kStat) != -1 ? 0 : errno; -#else - rErr = fstat64(iFileDesc, &kStat) != -1 ? 0 : errno; -#endif -} - -ILINE void FS_CLOSEDIR(FS_DIR_TYPE pDir, FS_ERRNO_TYPE& rErr) -{ - errno = 0; - rErr = closedir(pDir) == 0 ? 0 : errno; -} - -ILINE void FS_CLOSEDIR_NOERR(FS_DIR_TYPE pDir) -{ - closedir(pDir); -} - -const bool GetFilenameNoCase -( - const char* file, - char* pAdjustedFilename, - const bool cCreateNew -) -{ - assert(file); - assert(pAdjustedFilename); - azstrcpy(pAdjustedFilename, AZ_MAX_PATH_LEN, file); - - // Fix the dirname case. - const int cLen = strlen(file); - for (int i = 0; i < cLen; ++i) - { - if (pAdjustedFilename[i] == '\\') - { - pAdjustedFilename[i] = '/'; - } - } - - char* slash; - const char* dirname; - char* name; - FS_ERRNO_TYPE fsErr = 0; - FS_DIRENT_TYPE dirent; - uint64_t direntSize = 0; - FS_DIR_TYPE fd = FS_DIR_NULL; - - if ( - (pAdjustedFilename) == (char*)-1) - { - return false; - } - - slash = strrchr(pAdjustedFilename, '/'); - if (slash) - { - dirname = pAdjustedFilename; - name = slash + 1; - *slash = 0; - } - else - { - dirname = "."; - name = pAdjustedFilename; - } - -#if !defined(LINUX) && !defined(APPLE) && !defined(DEFINE_SKIP_WILDCARD_CHECK) // fix the parent path anyhow. - // Check for wildcards. We'll always return true if the specified filename is - // a wildcard pattern. - if (strchr(name, '*') || strchr(name, '?')) - { - if (slash) - { - *slash = '/'; - } - return true; - } -#endif - - // Scan for the file. - bool found = false; - bool skipScan = false; - - if (slash) - { - *slash = '/'; - } - -#if FIX_FILENAME_CASE - char* path = pAdjustedFilename; - char* sep; - while ((sep = strchr(path, '/')) != NULL) - { - *sep = '\0'; - const bool exists = FixOnePathElement(pAdjustedFilename); - *sep = '/'; - if (!exists) - { - return false; - } - - path = sep + 1; - } - if (!FixOnePathElement(pAdjustedFilename)) // catch last filename. - { - return false; - } - -#else - for (char* c = pAdjustedFilename; *c; ++c) - { - *c = tolower(*c); - } -#endif - - return true; -} - -DWORD GetFileAttributes(LPCSTR lpFileName) -{ - struct stat fileStats; - const int success = stat(lpFileName, &fileStats); - if (success == -1) - { - char adjustedFilename[MAX_PATH]; - GetFilenameNoCase(lpFileName, adjustedFilename); - if (stat(adjustedFilename, &fileStats) == -1) - { - return (DWORD)INVALID_FILE_ATTRIBUTES; - } - } - DWORD ret = 0; - - const int acc = (fileStats.st_mode & S_IWRITE); - - if (acc != 0) - { - if (S_ISDIR(fileStats.st_mode) != 0) - { - ret |= FILE_ATTRIBUTE_DIRECTORY; - } - } - return (ret == 0) ? FILE_ATTRIBUTE_NORMAL : ret;//return file attribute normal as the default value, must only be set if no other attributes have been found -} - -uint32 CryGetFileAttributes(const char* lpFileName) -{ - - string fn = lpFileName; - adaptFilenameToLinux(fn); - const char* buffer = fn.c_str(); - return GetFileAttributes(buffer); - -} - -__finddata64_t::~__finddata64_t() -{ - if (m_Dir != FS_DIR_NULL) - { - FS_CLOSEDIR_NOERR(m_Dir); - m_Dir = FS_DIR_NULL; - } -} -#endif //defined(APPLE) || defined(LINUX) - -#endif // !defined(WIN32) diff --git a/Code/CryEngine/CryCommon/XMLBinaryHeaders.h b/Code/CryEngine/CryCommon/XMLBinaryHeaders.h deleted file mode 100644 index 2f5c23b3d2..0000000000 --- a/Code/CryEngine/CryCommon/XMLBinaryHeaders.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_XMLBINARYHEADERS_H -#define CRYINCLUDE_CRYCOMMON_XMLBINARYHEADERS_H -#pragma once - - -namespace XMLBinary -{ - class IDataWriter - { - public: - virtual ~IDataWriter() {} - virtual void Write(const void* pData, size_t size) = 0; - }; - - class IFilter - { - public: - enum EType - { - eType_ElementName, - eType_AttributeName - }; - virtual ~IFilter() {} - virtual bool IsAccepted(EType type, const char* pName) const = 0; - }; - - ////////////////////////////////////////////////////////////////////////// - typedef uint32 NodeIndex; // note: only uint32 or uint16 are supported - - template<int size> - struct Pad - { - char pad[size]; - }; - template<> - struct Pad<0> { }; - - struct Node - { - uint32 nTagStringOffset; // offset in CBinaryXmlData::pStringData - uint32 nContentStringOffset; // offset in CBinaryXmlData::pStringData - uint16 nAttributeCount; - uint16 nChildCount; - NodeIndex nParentIndex; - NodeIndex nFirstAttributeIndex; - NodeIndex nFirstChildIndex; - Pad<sizeof(uint32) - sizeof(NodeIndex)> reserved_for_alignment; - }; - - struct Attribute - { - uint32 nKeyStringOffset; // offset in CBinaryXmlData::pStringData - uint32 nValueStringOffset; // offset in CBinaryXmlData::pStringData - }; - - struct BinaryFileHeader - { - char szSignature[8]; - uint32 nXMLSize; - uint32 nNodeTablePosition; - uint32 nNodeCount; - uint32 nAttributeTablePosition; - uint32 nAttributeCount; - uint32 nChildTablePosition; - uint32 nChildCount; - uint32 nStringDataPosition; - uint32 nStringDataSize; - }; -} - -#endif // CRYINCLUDE_CRYCOMMON_XMLBINARYHEADERS_H diff --git a/Code/CryEngine/CryCommon/crycommon_files.cmake b/Code/CryEngine/CryCommon/crycommon_files.cmake deleted file mode 100644 index d3c725b7eb..0000000000 --- a/Code/CryEngine/CryCommon/crycommon_files.cmake +++ /dev/null @@ -1,271 +0,0 @@ -# -# Copyright (c) Contributors to the Open 3D Engine Project -# -# SPDX-License-Identifier: Apache-2.0 OR MIT -# -# - -set(FILES - CryCommon.cpp - IAudioInterfacesCommonData.h - IAudioSystem.h - ICmdLine.h - IConsole.h - IEntityRenderState.h - IEntityRenderState_info.cpp - IFont.h - IFunctorBase.h - IGem.h - IIndexedMesh.h - IIndexedMesh_info.cpp - ILevelSystem.h - ILocalizationManager.h - LocalizationManagerBus.h - LocalizationManagerBus.inl - ILog.h - IMaterial.h - IMiniLog.h - IMovieSystem.h - IPhysics.h - IPostEffectGroup.h - IProcess.h - IReadWriteXMLSink.h - IRenderAuxGeom.h - IRenderer.h - IRenderMesh.h - ISerialize.h - IShader.h - ISplines.h - IStatObj.h - StatObjBus.h - IStereoRenderer.h - ISurfaceType.h - ISystem.h - ITexture.h - ITimer.h - IValidator.h - IViewSystem.h - IWindowMessageHandler.h - IXml.h - MicrophoneBus.h - physinterface.h - HMDBus.h - VRCommon.h - StereoRendererBus.h - HeightmapUpdateNotificationBus.h - INavigationSystem.h - IMNM.h - SFunctor.h - FunctorBaseFunction.h - FunctorBaseMember.h - stridedptr.h - Options.h - SerializationTypes.h - CryEndian.h - CryRandomInternal.h - Random.h - LCGRandom.h - CryTypeInfo.cpp - BaseTypes.h - CompileTimeAssert.h - MemoryAccess.h - AnimKey.h - BitFiddling.h - Common_TypeInfo.cpp - CryArray.h - CryAssert.h - CryCrc32.h - CryCustomTypes.h - CryFile.h - CryFixedString.h - CryHeaders.h - CryHeaders_info.cpp - CryListenerSet.h - CryLegacyAllocator.h - CryName.h - CryPath.h - CryPodArray.h - CrySizer.h - CryString.h - CrySystemBus.h - CryThread.h - CryThreadImpl.h - CryTypeInfo.h - CryVersion.h - FrameProfiler.h - HeapAllocator.h - LegacyAllocator.h - MetaUtils.h - MiniQueue.h - MultiThread.h - MultiThread_Containers.h - NullAudioSystem.h - PNoise3.h - PoolAllocator.h - primitives.h - ProjectDefines.h - Range.h - ScopedVariableSetter.h - SerializeFwd.h - SimpleSerialize.h - smartptr.h - StlUtils.h - StringUtils.h - Synchronization.h - Tarray.h - Timer.h - TimeValue.h - TimeValue_info.h - TypeInfo_decl.h - TypeInfo_impl.h - UnicodeBinding.h - UnicodeEncoding.h - UnicodeFunctions.h - UnicodeIterator.h - VectorMap.h - VectorSet.h - VertexFormats.h - XMLBinaryHeaders.h - RenderBus.h - MainThreadRenderRequestBus.h - Cry_Matrix33.h - Cry_Matrix34.h - Cry_Matrix44.h - Cry_MatrixDiag.h - Cry_Vector4.h - Cry_Camera.h - Cry_Color.h - Cry_Geo.h - Cry_GeoDistance.h - Cry_GeoIntersect.h - Cry_GeoOverlap.h - Cry_Math.h - Cry_Quat.h - Cry_ValidNumber.h - Cry_Vector2.h - Cry_Vector3.h - Cry_XOptimise.h - CryHalf_info.h - CryHalf.inl - MathConversion.h - Cry_HWMatrix.h - Cry_HWVector3.h - AndroidSpecific.h - AppleSpecific.h - CryAssert_Android.h - CryAssert_impl.h - CryAssert_iOS.h - CryAssert_Linux.h - CryAssert_Mac.h - CryLibrary.cpp - CryLibrary.h - CryThread_dummy.h - CryThread_pthreads.h - CryThread_windows.h - CryThreadImpl_pthreads.h - CryThreadImpl_windows.h - CryWindows.h - Linux32Specific.h - Linux64Specific.h - Linux_Win32Wrapper.h - LinuxSpecific.h - LoadScreenBus.h - MacSpecific.h - platform.h - platform_impl.cpp - Win32specific.h - Win64specific.h - LyShine/IDraw2d.h - LyShine/ILyShine.h - LyShine/ISprite.h - LyShine/IRenderGraph.h - LyShine/UiAssetTypes.h - LyShine/UiComponentTypes.h - LyShine/UiBase.h - LyShine/UiEntityContext.h - LyShine/UiLayoutCellBase.h - LyShine/UiSerializeHelpers.h - LyShine/Animation/IUiAnimation.h - LyShine/Bus/UiAnimateEntityBus.h - LyShine/Bus/UiAnimationBus.h - LyShine/Bus/UiButtonBus.h - LyShine/Bus/UiCanvasBus.h - LyShine/Bus/UiCanvasManagerBus.h - LyShine/Bus/UiCanvasUpdateNotificationBus.h - LyShine/Bus/UiCheckboxBus.h - LyShine/Bus/UiCursorBus.h - LyShine/Bus/UiDraggableBus.h - LyShine/Bus/UiDropdownBus.h - LyShine/Bus/UiDropdownOptionBus.h - LyShine/Bus/UiDropTargetBus.h - LyShine/Bus/UiDynamicLayoutBus.h - LyShine/Bus/UiDynamicScrollBoxBus.h - LyShine/Bus/UiEditorBus.h - LyShine/Bus/UiEditorCanvasBus.h - LyShine/Bus/UiEditorChangeNotificationBus.h - LyShine/Bus/UiElementBus.h - LyShine/Bus/UiEntityContextBus.h - LyShine/Bus/UiFaderBus.h - LyShine/Bus/UiFlipbookAnimationBus.h - LyShine/Bus/UiGameEntityContextBus.h - LyShine/Bus/UiImageBus.h - LyShine/Bus/UiImageSequenceBus.h - LyShine/Bus/UiIndexableImageBus.h - LyShine/Bus/UiInitializationBus.h - LyShine/Bus/UiInteractableActionsBus.h - LyShine/Bus/UiInteractableBus.h - LyShine/Bus/UiInteractableStatesBus.h - LyShine/Bus/UiInteractionMaskBus.h - LyShine/Bus/UiLayoutBus.h - LyShine/Bus/UiLayoutCellBus.h - LyShine/Bus/UiLayoutCellDefaultBus.h - LyShine/Bus/UiLayoutColumnBus.h - LyShine/Bus/UiLayoutControllerBus.h - LyShine/Bus/UiLayoutFitterBus.h - LyShine/Bus/UiLayoutGridBus.h - LyShine/Bus/UiLayoutManagerBus.h - LyShine/Bus/UiLayoutRowBus.h - LyShine/Bus/UiMarkupButtonBus.h - LyShine/Bus/UiMaskBus.h - LyShine/Bus/UiNavigationBus.h - LyShine/Bus/UiParticleEmitterBus.h - LyShine/Bus/UiRadioButtonBus.h - LyShine/Bus/UiRadioButtonCommunicationBus.h - LyShine/Bus/UiRadioButtonGroupBus.h - LyShine/Bus/UiRadioButtonGroupCommunicationBus.h - LyShine/Bus/UiRenderBus.h - LyShine/Bus/UiRenderControlBus.h - LyShine/Bus/UiScrollableBus.h - LyShine/Bus/UiScrollBarBus.h - LyShine/Bus/UiScrollBoxBus.h - LyShine/Bus/UiScrollerBus.h - LyShine/Bus/UiSliderBus.h - LyShine/Bus/UiSpawnerBus.h - LyShine/Bus/UiSystemBus.h - LyShine/Bus/UiTextBus.h - LyShine/Bus/UiTextInputBus.h - LyShine/Bus/UiTooltipBus.h - LyShine/Bus/UiTooltipDataPopulatorBus.h - LyShine/Bus/UiTooltipDisplayBus.h - LyShine/Bus/UiTransform2dBus.h - LyShine/Bus/UiTransformBus.h - LyShine/Bus/UiVisualBus.h - LyShine/Bus/Sprite/UiSpriteBus.h - LyShine/Bus/World/UiCanvasOnMeshBus.h - LyShine/Bus/World/UiCanvasRefBus.h - LyShine/Bus/Tools/UiSystemToolsBus.h - Maestro/Bus/EditorSequenceAgentComponentBus.h - Maestro/Bus/EditorSequenceBus.h - Maestro/Bus/EditorSequenceComponentBus.h - Maestro/Bus/SequenceComponentBus.h - Maestro/Bus/SequenceAgentComponentBus.h - Maestro/Types/AnimNodeType.h - Maestro/Types/AnimParamType.h - Maestro/Types/AnimValue.h - Maestro/Types/AnimValueType.h - Maestro/Types/AssetBlendKey.h - Maestro/Types/AssetBlends.h - Maestro/Types/SequenceType.h - StaticInstance.h - WinBase.cpp -) diff --git a/Code/CryEngine/CryCommon/crycommon_testing_files.cmake b/Code/CryEngine/CryCommon/crycommon_testing_files.cmake deleted file mode 100644 index 5e7177b07f..0000000000 --- a/Code/CryEngine/CryCommon/crycommon_testing_files.cmake +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright (c) Contributors to the Open 3D Engine Project -# -# SPDX-License-Identifier: Apache-2.0 OR MIT -# -# - -set(FILES - Mocks/IAudioSystemMock.h - Mocks/IConsoleMock.h - Mocks/ICryPakMock.h - Mocks/ILogMock.h - Mocks/ISystemMock.h - Mocks/ITimerMock.h - Mocks/ICVarMock.h - Mocks/IRendererMock.h - Mocks/ITextureMock.h - Mocks/IRemoteConsoleMock.h -) diff --git a/Code/CryEngine/CryCommon/iOSSpecific.h b/Code/CryEngine/CryCommon/iOSSpecific.h deleted file mode 100644 index 35fa769388..0000000000 --- a/Code/CryEngine/CryCommon/iOSSpecific.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : iOS specific declarations - - -#ifndef CRYINCLUDE_CRYCOMMON_IOSSPECIFIC_H -#define CRYINCLUDE_CRYCOMMON_IOSSPECIFIC_H -#pragma once - - -#include "AppleSpecific.h" -#include <float.h> -#include <TargetConditionals.h> - -#if TARGET_IPHONE_SIMULATOR -#define IOS_SIMULATOR -#include <xmmintrin.h> -#define _CPU_AMD64 -#define _CPU_SSE -#else -#define _CPU_ARM -#define _CPU_NEON -#endif - -// detect 64bit iOS -#if defined(__LP64__) -#define PLATFORM_64BIT -#endif - -#if defined(_CPU_ARM) && defined(PLATFORM_64BIT) -# define INTERLOCKED_COMPARE_EXCHANGE_128_NOT_SUPPORTED -#endif // defined(_CPU_ARM) && defined(PLATFORM_64BIT) - -#ifndef MOBILE -#define MOBILE -#endif - -// stubs for virtual keys, isn't used on iOS -#define VK_UP 0 -#define VK_DOWN 0 -#define VK_RIGHT 0 -#define VK_LEFT 0 -#define VK_CONTROL 0 -#define VK_SCROLL 0 - - -//#define USE_CRT 1 -#if !defined(PLATFORM_64BIT) -#error "IOS build only supports the 64bit architecture" -#else -#define SIZEOF_PTR 8 -typedef uint64_t threadID; -#endif - -#endif // CRYINCLUDE_CRYCOMMON_IOSSPECIFIC_H diff --git a/Code/CryEngine/CryCommon/physinterface.h b/Code/CryEngine/CryCommon/physinterface.h deleted file mode 100644 index 873c72cb4b..0000000000 --- a/Code/CryEngine/CryCommon/physinterface.h +++ /dev/null @@ -1,3676 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : declarations of all physics interfaces and structures - - -#ifndef CRYINCLUDE_CRYCOMMON_PHYSINTERFACE_H -#define CRYINCLUDE_CRYCOMMON_PHYSINTERFACE_H -#pragma once - - -#include <SerializeFwd.h> - -#include "Cry_Geo.h" -#include "stridedptr.h" -#include "primitives.h" -#ifdef NEED_ENDIAN_SWAP - #include "CryEndian.h" -#endif - -#include <ISystem.h> - -////////////////////////////////////////////////////////////////////////// -// Physics defines. -////////////////////////////////////////////////////////////////////////// - -enum EPE_Params -{ - ePE_params_pos = 0, - ePE_player_dimensions = 1, - ePE_params_car = 2, - ePE_params_particle = 3, - ePE_player_dynamics = 4, - ePE_params_joint = 5, - ePE_params_part = 6, - ePE_params_sensors = 7, - ePE_params_articulated_body = 8, - ePE_params_outer_entity = 9, - ePE_simulation_params = 10, - ePE_params_foreign_data = 11, - ePE_params_buoyancy = 12, - ePE_params_rope = 13, - ePE_params_bbox = 14, - ePE_params_flags = 15, - ePE_params_wheel = 16, - ePE_params_softbody = 17, - ePE_params_area = 18, - ePE_tetrlattice_params = 19, - ePE_params_ground_plane = 20, - ePE_params_structural_joint = 21, - ePE_params_waterman = 22, - ePE_params_timeout = 23, - ePE_params_skeleton = 24, - ePE_params_structural_initial_velocity = 25, - ePE_params_collision_class = 26, - - ePE_Params_Count -}; - -enum EPE_Action -{ - ePE_action_move = 1, - ePE_action_impulse = 2, - ePE_action_drive = 3, - ePE_action_reset = 4, - ePE_action_add_constraint = 5, - ePE_action_update_constraint = 6, - ePE_action_register_coll_event = 7, - ePE_action_awake = 8, - ePE_action_remove_all_parts = 9, - ePE_action_set_velocity = 10, - ePE_action_attach_points = 11, - ePE_action_target_vtx = 12, - ePE_action_reset_part_mtx = 13, - ePE_action_notify = 14, - ePE_action_auto_part_detachment = 15, - ePE_action_move_parts = 16, - ePE_action_batch_parts_update = 17, - ePE_action_slice = 18, - pPE_action_syncliving = 19, - - ePE_Action_Count -}; - -enum EPE_GeomParams -{ - ePE_geomparams = 0, - ePE_cargeomparams = 1, - ePE_articgeomparams = 2, - - ePE_GeomParams_Count -}; - -enum EPE_Status -{ - ePE_status_pos = 1, - ePE_status_living = 2, - ePE_status_vehicle = 4, - ePE_status_wheel = 5, - ePE_status_joint = 6, - ePE_status_awake = 7, - ePE_status_dynamics = 8, - ePE_status_collisions = 9, - ePE_status_id = 10, - ePE_status_timeslices = 11, - ePE_status_nparts = 12, - ePE_status_contains_point = 13, - ePE_status_rope = 14, - ePE_status_vehicle_abilities = 15, - ePE_status_placeholder = 16, - ePE_status_softvtx = 17, - ePE_status_sensors = 18, - ePE_status_sample_contact_area = 19, - ePE_status_caps = 20, - ePE_status_check_stance = 21, - ePE_status_waterman = 22, - ePE_status_area = 23, - ePE_status_extent = 24, - ePE_status_random = 25, - ePE_status_constraint = 26, - ePE_status_netpos = 27, - - ePE_Status_Count -}; - -enum pe_type -{ - PE_NONE = 0, PE_STATIC = 1, PE_RIGID = 2, PE_WHEELEDVEHICLE = 3, PE_LIVING = 4, PE_PARTICLE = 5, PE_ARTICULATED = 6, PE_ROPE = 7, PE_SOFT = 8, PE_AREA = 9 -}; -enum sim_class -{ - SC_STATIC = 0, SC_SLEEPING_RIGID = 1, SC_ACTIVE_RIGID = 2, SC_LIVING = 3, SC_INDEPENDENT = 4, SC_TRIGGER = 6, SC_DELETED = 7 -}; -struct IGeometry; -struct IPhysicalEntity; -struct IGeomManager; -struct IPhysRenderer; -class ICrySizer; -struct IDeferredPhysicsEvent; -struct ILog; -IPhysicalEntity* const WORLD_ENTITY = (IPhysicalEntity*)-10; - -#ifndef USE_IMPROVED_RIGID_ENTITY_SYNCHRONISATION -# define USE_IMPROVED_RIGID_ENTITY_SYNCHRONISATION 1 -#endif - -/** - * 64-bit wrapper for foreign data on physical entities. - * Int and pointer values are regularly stored in foreign data, but we now also support - * 64-bit unsigned integers (AZ::EntityId). - * - Supports implicit two-way conversion as integer, pointer, int, or 64-bit unsigned integer. - * - Supports casting to typed pointers for compatibility with original void* foreign data. - */ -class PhysicsForeignData final -{ -public: - - PhysicsForeignData() - : m_data(0) {} - - /// Explicit or implicit creation from pointer, int, or unsigned int types. - PhysicsForeignData(void* data) - : m_data(reinterpret_cast<uint64>(data)) {} - PhysicsForeignData(int data) - : m_data(static_cast<uint64>(data)) {} - PhysicsForeignData(uint64 data) - : m_data(static_cast<uint64>(data)) {} - - /// Comparison operators. - bool operator==(const PhysicsForeignData& rhs) const - { - return m_data == rhs.m_data; - } - - bool operator!=(const PhysicsForeignData& rhs) const - { - return m_data != rhs.m_data; - } - - template<typename T> - bool operator==(T* data) const - { - return reinterpret_cast<T*>(m_data) == data; - } - - template<typename T> - bool operator==(const T* data) const - { - return reinterpret_cast<const T*>(m_data) == data; - } - - bool operator==(int data) const - { - return static_cast<int>(m_data) == data; - } - - bool operator==(uint64 data) const - { - return m_data == data; - } - - /// Using CryPhysics' existing pattern for marking fields as unused. - void MarkUnused() - { - m_data = uint64(1 << 31); - } - - bool IsUnused() const - { - return m_data == uint64(1 << 31); - } - - /// Bool operator for: if (foreignData) - operator bool() const - { - return m_data != 0; - } - - /// Void* cast conversion - operator void*() const - { - return reinterpret_cast<void*>(m_data); - } - - /// int cast conversion - operator int() const - { - return static_cast<int>(m_data); - } - - /// 64-bit unsigned int cast conversion - operator uint64() const - { - return m_data; - } - - /// Cast conversion to pointers or arbitrary types. - template<typename T> - operator T*() const - { - return reinterpret_cast<T*>(m_data); - } - -private: - - uint64 m_data; ///< Underlying 64-bit storage. -}; - -///////////////////////////////////////////////////////////////////////////////////// -//////////////////////////// IPhysicsStreamer Interface ///////////////////////////// -///////////////////////////////////////////////////////////////////////////////////// - -// this is a callback interface for on-demand physicalization, physics gets a pointer to an implementation -struct IPhysicsStreamer -{ - // <interfuscator:shuffle> - virtual ~IPhysicsStreamer(){} - // called whenever a placeholder (created through CreatePhysicalPlaceholder) requests a full entity - virtual int CreatePhysicalEntity(PhysicsForeignData foreignData, int iForeignData, int iForeignFlags) = 0; - // called whenever a placeholder-owned entity expires - virtual int DestroyPhysicalEntity(IPhysicalEntity* pent) = 0; - // called when on-demand entities in a box need to be physicalized - // (the grid is activated once RegisterBBoxInPODGrid is called) - virtual int CreatePhysicalEntitiesInBox(const Vec3& boxMin, const Vec3& boxMax) = 0; - // called when on-demand physicalized box expires. - // the streamer is expected to delete those that have a 0 refcounter, and keep the rest - virtual int DestroyPhysicalEntitiesInBox(const Vec3& boxMin, const Vec3& boxMax) = 0; - // </interfuscator:shuffle> -}; - -///////////////////////////////////////////////////////////////////////////////////// -/////////////////////////////// IPhysRenderer Interface ///////////////////////////// -///////////////////////////////////////////////////////////////////////////////////// - -// this is a callback interface for debug rendering, physics gets a pointer to an implementation -struct IPhysRenderer -{ - // <interfuscator:shuffle> - virtual ~IPhysRenderer(){} - // draws helpers for the specified geometry (idxColor is in 0..7 range) - virtual void DrawGeometry(IGeometry* pGeom, struct geom_world_data* pgwd, int idxColor = 0, int bSlowFadein = 0, const Vec3& sweepDir = Vec3(0)) = 0; - // draws a line for wireframe helpers - virtual void DrawLine(const Vec3& pt0, const Vec3& pt1, int idxColor = 0, int bSlowFadein = 0) = 0; - // gets a descriptive name of the phys entity's owner (used solely for debug output) - virtual const char* GetForeignName(PhysicsForeignData foreignData, int iForeignData, int iForeignFlags) = 0; - // draws a text line (stauration is 0..1 and is currently used to represent stress level on a breakable joint) - virtual void DrawText(const Vec3& pt, const char* txt, int idxColor, float saturation = 0) = 0; - // sets an offset that is to be added to all subsequent draw requests - virtual Vec3 SetOffset(const Vec3& offs = Vec3(ZERO)) = 0; - // draw a frame or a partial frame using a scale for the axes. - // pnt is the world space position - // axes are the 3 axes normalized - // scale is a scale applied on the axes - // limits are the x, y, z radians for the Y, Z, X plane. If the pointer is not null, limits will be drawn in form of arcs. - // bitfield for what axes are locked - virtual void DrawFrame(const Vec3& pnt, const Vec3* axes, const float scale, const Vec3* limits, const int axes_locked) = 0; - // </interfuscator:shuffle> -}; - -class CMemStream -{ // For "fastload" serialization -public: - - ILINE CMemStream(bool swap) - { - Prealloc(); - m_iPos = 0; - bDeleteBuf = true; - bSwapEndian = swap; - bMeasureOnly = 0; - } - - ILINE CMemStream(void* pbuf, int sz, bool swap) - { - m_pBuf = (char*)pbuf; - m_nSize = sz; - m_iPos = 0; - bDeleteBuf = false; - bSwapEndian = swap; - bMeasureOnly = 0; - } - ILINE CMemStream() - { - m_pBuf = (char*)m_dummyBuf; - m_iPos = 0; - m_nSize = 0; - bDeleteBuf = false; - bSwapEndian = false; - bMeasureOnly = -1; - } - - virtual ~CMemStream() - { - if (bDeleteBuf) - { - CryModuleFree(m_pBuf); - } - } - virtual void Prealloc() - { - m_pBuf = (char*)CryModuleMalloc(m_nSize = 0x1000); - } - - ILINE void* GetBuf() { return m_pBuf; } - ILINE int GetUsedSize() { return m_iPos; } - ILINE int GetAllocatedSize() { return m_nSize; } - - template<class ftype> - ILINE void Write(const ftype& op) { Write(&op, sizeof(op)); } - ILINE void Write(const void* pbuf, int sz) - { -#if defined(MEMSTREAM_DEBUG) - if (bMeasureOnly <= 0 && m_nSize && m_iPos + sz > m_nSize) - { - printf("overflow: %d + %d >= %d\n", m_iPos, sz, m_nSize); - } -#endif - if (!bMeasureOnly) - { - if (m_iPos + sz > m_nSize) - { - GrowBuf(sz); - } - memcpy(m_pBuf + m_iPos, pbuf, (unsigned int)sz); - } - m_iPos += sz; - } - - virtual void GrowBuf(int sz) - { - int prevsz = m_nSize; - char* prevbuf = m_pBuf; - m_pBuf = (char*)CryModuleMalloc(m_nSize = (m_iPos + sz - 1 & ~0xFFF) + 0x1000); - memcpy(m_pBuf, prevbuf, (unsigned int)prevsz); - CryModuleFree(prevbuf); - } - - template<class ftype> - ILINE void Read(ftype& op) - { - ReadRaw(&op, sizeof(op)); -#if defined (NEED_ENDIAN_SWAP) - if (bSwapEndian) - { - SwapEndian(op); - } -#endif - } - - template<class ftype> - ILINE ftype Read() - { - ftype val; - Read(val); - return val; - } - template<class ftype> - ILINE void ReadType(ftype* op, int count = 1) - { - ReadRaw(op, sizeof(*op) * count); -#if defined (NEED_ENDIAN_SWAP) - if (bSwapEndian) - { - while (count-- > 0) - { - SwapEndian(*op++); - } - } -#endif - } - ILINE void ReadRaw(void* pbuf, int sz) - { -#if defined(MEMSTREAM_DEBUG) - if (bMeasureOnly <= 0 && m_nSize && m_iPos + sz > m_nSize) - { - printf("overflow: %d + %d >= %d\n", m_iPos, sz, m_nSize); - } -#endif - memcpy(pbuf, (m_pBuf + m_iPos), (unsigned int)sz); - m_iPos += sz; - } - - char* m_pBuf, m_dummyBuf[4]; - int m_iPos, m_nSize; - bool bDeleteBuf; - bool bSwapEndian; - int bMeasureOnly; -}; - - -// Workaround for bug in GCC 4.8. The kind of access patterns here leads to an internal -// compiler error in GCC 4.8 when optimizing with debug symbols. Two possible solutions -// are available, compile in Profile mode without debug symbols or remove optimizations -// in the code where the bug occurs -// see http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59776 -#if defined(_PROFILE) && !defined(__clang__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 8) -// Cannot use #pragma GCC optimize("O0") because it causes a system crash when using -// the gcc compiler for another platform -#define CRY_GCC48_AVOID_OPTIMIZE __attribute__((optimize("-O0"))) -#else -#define CRY_GCC48_AVOID_OPTIMIZE -#endif -// unused_marker deliberately fills a variable with invalid data, -// so that later is_unused() can check whether it was initialized -// (this is used in all physics params/status/action structures) -class unused_marker -{ -public: - union f2i - { - float f; - uint32 i; - }; - union d2i - { - double d; - uint32 i[2]; - }; - unused_marker() {} - unused_marker& operator,(float& x) CRY_GCC48_AVOID_OPTIMIZE; - unused_marker& operator,(double& x) CRY_GCC48_AVOID_OPTIMIZE; - unused_marker& operator,(int& x) CRY_GCC48_AVOID_OPTIMIZE; - unused_marker& operator,(unsigned int& x) CRY_GCC48_AVOID_OPTIMIZE; - unused_marker& operator,(PhysicsForeignData& x) CRY_GCC48_AVOID_OPTIMIZE; - template<class ref> - unused_marker& operator,(ref*& x) { x = (ref*)-1; return *this; } - template<class F> - unused_marker& operator,(Vec3_tpl<F>& x) { return *this, x.x; } - template<class F> - unused_marker& operator,(Quat_tpl<F>& x) { return *this, x.w; } - template<class F> - unused_marker& operator,(strided_pointer<F>& x) { return *this, x.data; } -}; -inline unused_marker& unused_marker::operator,(float& x) { *alias_cast<int*>(&x) = 0xFFBFFFFF; return *this; } -inline unused_marker& unused_marker::operator,(double& x) { (alias_cast<int*>(&x))[false ? 1 : 0] = 0xFFF7FFFF; return *this; } -inline unused_marker& unused_marker::operator,(int& x) { x = 1 << 31; return *this; } -inline unused_marker& unused_marker::operator,(unsigned int& x) { x = 1u << 31; return *this; } -inline unused_marker& unused_marker::operator,(PhysicsForeignData& x) { x.MarkUnused(); return *this; } - -#undef CRY_GCC48_AVOID_OPTIMIZE - -inline bool is_unused(const float& x) { unused_marker::f2i u; u.f = x; return (u.i & 0xFFA00000) == 0xFFA00000; } - -inline bool is_unused(int x) { return x == 1 << 31; } -inline bool is_unused(unsigned int x) { return x == 1u << 31; } -inline bool is_unused(const PhysicsForeignData& x) { return x.IsUnused(); } -template<class ref> -bool is_unused(ref* x) { return x == (ref*)-1; } -template<class ref> -bool is_unused(strided_pointer<ref> x) { return is_unused(x.data); } -template<class F> -bool is_unused(const Ang3_tpl<F>& x) { return is_unused(x.x); } -template<class F> -bool is_unused(const Vec3_tpl<F>& x) { return is_unused(x.x); } -template<class F> -bool is_unused(const Quat_tpl<F>& x) { return is_unused(x.w); } -inline bool is_unused(const double& x) { unused_marker::d2i u; u.d = x; return (u.i[eLittleEndian ? 1 : 0] & 0xFFF40000) == 0xFFF40000; } -#define MARK_UNUSED unused_marker(), - - -// validators do nothing in the interface, but inside the physics they are redefined -// so that they check the input for consistency and report errors -#if !defined(VALIDATOR_LOG) -#define VALIDATOR_LOG(pLog, str) -#define VALIDATORS_START -#define VALIDATOR(member) -#define VALIDATOR_NORM(member) -#define VALIDATOR_NORM_MSG(member, msg, member1) -#define VALIDATOR_RANGE(member, minval, maxval) -#define VALIDATOR_RANGE2(member, minval, maxval) -#define VALIDATORS_END -#endif - - - -////////// physics entity collision filtering class enums ///////////////// - -enum pe_collision_class -{ - /// reserved basic collision classes - collision_class_terrain = 1 << 0, - collision_class_wheeled = 1 << 1, - collision_class_living = 1 << 2, - collision_class_articulated = 1 << 3, - collision_class_soft = 1 << 4, - collision_class_rope = 1 << 5, - collision_class_particle = 1 << 6, - // begin game specific ones from this enum - collision_class_game = 1 << 10, -}; - -struct SCollisionClass -{ - uint32 type; // collision_class flags to identify the enity - uint32 ignore; // another entity will be ignored if *any* of these bits are set in its type - - SCollisionClass() {} - - SCollisionClass(uint32 t, uint32 i) - { - type = t; - ignore = i; - } -}; - -ILINE int IgnoreCollision(const SCollisionClass& a, const SCollisionClass& b) -{ - return (a.type & b.ignore) | (b.type & a.ignore); -} - - - -// in physics interface [almost] all parameters are passed via structures -// this allows having stable interface methods and flexible default arguments system - -////////////////////////// Params structures ///////////////////// - -////////// common params -struct pe_params -{ - int type; -}; - -struct pe_params_pos - : pe_params // Sets position and orientation of entity -{ - enum entype - { - type_id = ePE_params_pos - }; - pe_params_pos() - { - type = type_id; - MARK_UNUSED pos, scale, q, iSimClass; - pMtx3x4 = 0; - pMtx3x3 = 0; - bRecalcBounds = 1; - bEntGridUseOBB = 0; - } - - Vec3 pos; - quaternionf q; - float scale; // note that since there's no per-entity scale, it gets 'baked' into individual parts' scales - Matrix34* pMtx3x4; // optional position+orientation - Matrix33* pMtx3x3; // optional orientation via 3x3 matrix - int iSimClass; // see the sim_class enum - int bRecalcBounds; // tells to recompute the bounding boxes - bool bEntGridUseOBB; // whether or not to use part OBBs rather than object AABB when registering in the entity grid - - VALIDATORS_START - VALIDATOR(pos) - VALIDATOR_NORM_MSG(q, "(perhaps non-uniform scaling was used?)", pos) - VALIDATOR(scale) - VALIDATORS_END -}; - -struct pe_params_bbox - : pe_params -{ - enum entype - { - type_id = ePE_params_bbox - }; - pe_params_bbox() { type = type_id; MARK_UNUSED BBox[0], BBox[1]; } - Vec3 BBox[2]; // force this bounding box (note that if the entity recomputes it later, it'll override this) - - VALIDATORS_START - VALIDATOR(BBox[0]) - VALIDATOR(BBox[1]) - VALIDATORS_END -}; - -struct pe_params_outer_entity - : pe_params -{ - enum entype - { - type_id = ePE_params_outer_entity - }; - pe_params_outer_entity() { type = type_id; pOuterEntity = 0; pBoundingGeometry = 0; } - - IPhysicalEntity* pOuterEntity; // outer entity is used to group together SC_INDEPENDENT entities (example: ropes on a tree trunk) - IGeometry* pBoundingGeometry; // optional geometry to test containment (used in pe_status_contains_point) -}; - -struct ITetrLattice; - -struct pe_params_part - : pe_params // Sets geometrical parameters of entity part -{ - enum entype - { - type_id = ePE_params_part - }; - pe_params_part() - { - type = type_id; - MARK_UNUSED pos, q, scale, partid, ipart, mass, density, pPhysGeom, pPhysGeomProxy, idmatBreakable, pLattice, pMatMapping, minContactDist, flagsCond, idSkeleton, invTimeStep, idParent; - pMtx3x4 = 0; - pMtx3x3 = 0; - bRecalcBBox = 1; - bAddrefGeoms = 0; - flagsOR = flagsColliderOR = 0; - flagsAND = flagsColliderAND = (unsigned)-1; - } - - int partid; // partid identifier of part - int ipart; // optionally, internal part slot number - int bRecalcBBox; // whether entity's bounding box should be recalculated - Vec3 pos; - quaternionf q; - float scale; - Matrix34* pMtx3x4; // optional position+orientation - Matrix33* pMtx3x3; // optional orientation via 3x3 matrix - unsigned int flagsCond; // if partid and ipart are not specified, check for parts with flagsCond set - unsigned int flagsOR, flagsAND; // new flags = (flags & flagsAND) | flagsOR - unsigned int flagsColliderOR, flagsColliderAND; - float mass; // either mass of density should be set; mass = density*volume - float density; - float minContactDist; // threshold for contact points generation - struct phys_geometry* pPhysGeom, * pPhysGeomProxy; // if present and different from pPhysGeomProxy, pPhysGeom is used for raytracing - int idmatBreakable; // if >=0, the part is procedurally breakable with this mat_id (see AddExplosionShape) - ITetrLattice* pLattice; // lattice is used for soft bodies and procedural structural breaking - int idSkeleton; // part with this id becomes this part's deformation skeleton - int* pMatMapping; // material mapping table for this part - int nMats; // number of pMatMapping entries - float invTimeStep; // 1.0f/time_step, ragdolls will compute joint's velocity if this and position is set - int bAddrefGeoms; // AddRef returned geometries if used in GetParams - int idParent; // parent for hierarchical breaking; it hides all children until at least one of them breaks off - - VALIDATORS_START - VALIDATOR(pos) - VALIDATOR_NORM_MSG(q, "(perhaps non-uniform scaling was used in the asset?)", pt) - VALIDATOR(scale) - VALIDATORS_END -}; - -struct pe_params_sensors - : pe_params // Attaches optional ray sensors to an entity; only living entities support it -{ - enum entype - { - type_id = ePE_params_sensors - }; - pe_params_sensors() { type = type_id; nSensors = 0; pOrigins = 0; pDirections = 0; } - - int nSensors; // nSensors number of sensors - const Vec3* pOrigins; // pOrigins sensors origins in entity CS - const Vec3* pDirections; // pDirections sensors directions (dir*ray length) in entity CS -}; - -struct pe_simulation_params - : pe_params -{ - enum entype - { - type_id = ePE_simulation_params - }; - pe_simulation_params() - { - type = type_id; - MARK_UNUSED maxTimeStep, gravity, minEnergy, damping, iSimClass, - dampingFreefall, gravityFreefall, mass, density, maxLoggedCollisions, maxRotVel, disablePreCG, maxFriction, collTypes; - } - - int iSimClass; - float maxTimeStep; // maximum time step that entity can accept (larger steps will be split) - float minEnergy; // minimun of kinetic energy below which entity falls asleep (divided by mass) - float damping; // damped velocity = oridinal velocity * (1 - damping*time interval) - Vec3 gravity; // per-entity gravity (note that if there are any phys areas with gravity, they will override it unless pef_ignore_areas is set - float dampingFreefall; // damping and gravity used when there are no collisions, - Vec3 gravityFreefall; // NOTE: if left unused, gravity value will be substituted (if provided) - float maxRotVel; // rotational velocity is clamped to this value - float mass; // either mass of density should be set; mass = density*volume - float density; - int maxLoggedCollisions; // maximum EventPhysCollisions reported per frame (only supported by rigid bodies/ragdolls/vehicles) - int disablePreCG; // disables Pre-CG solver for the group this body is in (recommended for balls) - float maxFriction; // sets upper friction limit for this object and all objects it's currently in contact with - int collTypes; // collision types (a combination of ent_xxx flags) -}; - -struct pe_params_foreign_data - : pe_params -{ - enum entype - { - type_id = ePE_params_foreign_data - }; - pe_params_foreign_data() { type = type_id; MARK_UNUSED pForeignData, iForeignData, iForeignFlags; iForeignFlagsAND = -1; iForeignFlagsOR = 0; } - - PhysicsForeignData pForeignData; // foreign data is an arbitrary pointer used to associate physical entity with its owner object - int iForeignData; // foreign data types (defined in IPhysics.h) - int iForeignFlags; // any flags the owner wants to store - int iForeignFlagsAND, iForeignFlagsOR; // when setting, flagsNew = flags & flagsAND | flagsOR -}; - -struct pe_params_buoyancy - : pe_params -{ - enum entype - { - type_id = ePE_params_buoyancy - }; - pe_params_buoyancy() - { - type = type_id; - iMedium = 0; - MARK_UNUSED waterDensity, kwaterDensity, waterDamping, - waterPlane.n, waterPlane.origin, waterEmin, waterResistance, kwaterResistance, waterFlow, flowVariance; - }; - - float waterDensity; // overrides water density from the current water volume for an entity; sets for water areas - float kwaterDensity; // scales water density from the current water volume (used for entities only) - // NOTE: for entities , waterDensity override is stored as kwaterDensity relative to the global area's density - float waterDamping; // uniform damping while submerged, will be scaled with submerged fraction - float waterResistance, kwaterResistance; // water's medium resistance; same comments on water and kwater.. apply - Vec3 waterFlow; // flow's movement vector; can only be set for a water area - float flowVariance; // not yet supported - primitives::plane waterPlane; // positive normal = above the water surface - float waterEmin; // sleep energy while floating with no contacts (see minEnergy in pe_simulation_params) - int iMedium; // 0 for water, 1 for air -}; - -enum phentity_flags -{ - // PE_PARTICLE-specific flags - particle_single_contact = 0x01, // full stop after first contact - particle_constant_orientation = 0x02, // forces constant orientation - particle_no_roll = 0x04, // 'sliding' mode; entity's 'normal' vector axis will be alinged with the ground normal - particle_no_path_alignment = 0x08, // unless set, entity's y axis will be aligned along the movement trajectory - particle_no_spin = 0x10, // disables spinning while flying - particle_no_self_collisions = 0x100, // disables collisions with other particles - particle_no_impulse = 0x200, // particle will not add hit impulse (expecting that some other system will) - - // PE_LIVING-specific flags - lef_push_objects = 0x01, lef_push_players = 0x02, // push objects and players during contacts - lef_snap_velocities = 0x04, // quantizes velocities after each step (was ised in MP for precise deterministic sync) - lef_loosen_stuck_checks = 0x08, // don't do additional intersection checks after each step (recommended for NPCs to improve performance) - lef_report_sliding_contacts = 0x10, // unless set, 'grazing' contacts are not reported - - // PE_ROPE-specific flags - rope_findiff_attached_vel = 0x01, // approximate velocity of the parent object as v = (pos1-pos0)/time_interval - rope_no_solver = 0x02, // no velocity solver; will rely on stiffness (if set) and positional length enforcement - rope_ignore_attachments = 0x4, // no collisions with objects the rope is attached to - rope_target_vtx_rel0 = 0x08, rope_target_vtx_rel1 = 0x10, // whether target vertices are set in the parent entity's frame - rope_subdivide_segs = 0x100, // turns on 'dynamic subdivision' mode (only in this mode contacts in a strained state are handled correctly) - rope_no_tears = 0x200, // rope will not tear when it reaches its force limit, but stretch - rope_collides = 0x200000, // rope will collide with objects other than the terrain - rope_collides_with_terrain = 0x400000, // rope will collide with the terrain - rope_collides_with_attachment = 0x80, // rope will collide with the objects it's attached to even if the other collision flags are not set - rope_no_stiffness_when_colliding = 0x10000000, // rope will use stiffness 0 if it has contacts - - // PE_SOFT-specific flags - se_skip_longest_edges = 0x01, // the longest edge in each triangle with not participate in the solver - se_rigid_core = 0x02, // soft body will have an additional rigid body core - - // PE_RIGID-specific flags (note that PE_ARTICULATED and PE_WHEELEDVEHICLE are derived from it) - ref_use_simple_solver = 0x01, // use penalty-based solver (obsolete) - ref_no_splashes = 0x04, // will not generate EventPhysCollisions when contacting water - ref_checksum_received = 0x04, ref_checksum_outofsync = 0x08, // obsolete - ref_small_and_fast = 0x100, // entity will trace rays against alive characters; set internally unless overriden - - // PE_ARTICULATED-specific flags - aef_recorded_physics = 0x02, // specifies a an entity that contains pre-baked physics simulation - - // PE_WHEELEDVEHICLE-specific flags - wwef_fake_inner_wheels = 0x08, // exclude wheels between the first and the last one from the solver - // (only wheels with non-0 suspension are considered) - - // general flags - pef_parts_traceable = 0x10, // each entity part will be registered separately in the entity grid - pef_disabled = 0x20, // entity will not be simulated - pef_never_break = 0x40, // entity will not break or deform other objects - pef_deforming = 0x80, // entity undergoes a dynamic breaking/deforming - pef_pushable_by_players = 0x200, // entity can be pushed by playerd - pef_traceable = 0x400, particle_traceable = 0x400, rope_traceable = 0x400, // entity is registered in the entity grid - pef_update = 0x800, // only entities with this flag are updated if ent_flagged_only is used in TimeStep() - pef_monitor_state_changes = 0x1000, // generate immediate events for simulation class changed (typically rigid bodies falling asleep) - pef_monitor_collisions = 0x2000, // generate immediate events for collisions - pef_monitor_env_changes = 0x4000, // generate immediate events when something breaks nearby - pef_never_affect_triggers = 0x8000, // don't generate events when moving through triggers - pef_invisible = 0x10000, // will apply certain optimizations for invisible entities - pef_ignore_ocean = 0x20000, // entity will ignore global water area - pef_fixed_damping = 0x40000, // entity will force its damping onto the entire group - pef_monitor_poststep = 0x80000, // entity will generate immediate post step events - pef_always_notify_on_deletion = 0x100000, // when deleted, entity will awake objects around it even if it's not referenced (has refcount 0) - pef_override_impulse_scale = 0x200000, // entity will ignore breakImpulseScale in PhysVars - pef_players_can_break = 0x400000, // playes can break the entiy by bumping into it - pef_cannot_squash_players = 0x10000000, // entity will never trigger 'squashed' state when colliding with players - pef_ignore_areas = 0x800000, // entity will ignore phys areas (gravity and water) - pef_log_state_changes = 0x1000000, // entity will log simulation class change events - pef_log_collisions = 0x2000000, // entity will log collision events - pef_log_env_changes = 0x4000000, // entity will log EventPhysEnvChange when something breaks nearby - pef_log_poststep = 0x8000000, // entity will log EventPhysPostStep events -}; - -struct pe_params_flags - : pe_params -{ - enum entype - { - type_id = ePE_params_flags - }; - pe_params_flags() { type = type_id; MARK_UNUSED flags, flagsOR, flagsAND; } - unsigned int flags; - unsigned int flagsOR; // when setting, flagsNew = (flags set ? flags:flagsOld) & flagsAND | flagsOR - unsigned int flagsAND; // when getting, only flags is filled -}; - - -struct pe_params_collision_class - : pe_params -{ - enum entype - { - type_id = ePE_params_collision_class - }; - pe_params_collision_class() { type = type_id; collisionClassOR.type = collisionClassOR.ignore = 0; collisionClassAND.type = collisionClassAND.ignore = (unsigned)-1; } - SCollisionClass collisionClassOR; // When getting both collisionClassOR and collisionClassAND are filled out - SCollisionClass collisionClassAND; // When setting first collisionClassAND is applied to mask bits, then collisionClassOR is applied to turn on collision bits -}; - -struct pe_params_ground_plane - : pe_params -{ - // used for breakable objects; pieces that are below ground (at least partially) stay in the entity - enum entype - { - type_id = ePE_params_ground_plane - }; - pe_params_ground_plane() { type = type_id; iPlane = 0; MARK_UNUSED ground.origin, ground.n; } - int iPlane; // index of the plane to be set (-1 removes existing planes) - primitives::plane ground; -}; - -enum special_joint_ids -{ - joint_impulse = 1000000 -}; -struct pe_params_structural_joint - : pe_params -{ - enum entype - { - type_id = ePE_params_structural_joint - }; - pe_params_structural_joint() - { - type = type_id; - id = 0; - bReplaceExisting = 0; - MARK_UNUSED idx, partid[0], partid[1], pt, n, maxForcePush, maxForcePull, maxForceShift, maxTorqueBend, maxTorqueTwist, damageAccum, damageAccumThresh, - bBreakable, szSensor, bBroken, partidEpicenter, axisx, limitConstraint, bConstraintWillIgnoreCollisions, dampingConstraint; - } - - int id; // joint's 'foreign' identifier - int idx; // joint's internal index - int bReplaceExisting; // if not set, SetParams will add a new joint even if id is already used - int partid[2]; // ids of the parts this joint connects (-1 for ground) - Vec3 pt; // point in entity space - Vec3 n; // push/pull direction in entity space - Vec3 axisx; // x axis in entity frame; only used for joints that can become dynamic constraints - float maxForcePush, maxForcePull, maxForceShift; // linear force limits - float maxTorqueBend, maxTorqueTwist; // angular force (torque) limits - float damageAccum, damageAccumThresh; // fraction of tension that gets accumulated, can be used to emulate an health system - Vec3 limitConstraint; // x=min angle, y=max angle, z=force limit - int bBreakable; // joint is at all breakable - int bConstraintWillIgnoreCollisions; // dynamic constraints will have constraint_ignore_buddy flag - int bDirectBreaksOnly; // joint can only be broken by direct impulses to one of the parts it connects - float dampingConstraint; // dynamic constraint's damping - float szSensor; // sensor geometry size; used to re-attach the joint when parts break off - int bBroken; // joint is broken - int partidEpicenter; // tension recomputation will start from this part (used for network playback, for instance) -}; - -struct pe_params_structural_initial_velocity - : pe_params -{ - // Setting of initial velocities of parts before breaking joints on clients through pe_params_structural_joint - enum entype - { - type_id = ePE_params_structural_initial_velocity - }; - pe_params_structural_initial_velocity() { type = type_id; } - - int partid; // id of the part to prepare for breakage - Vec3 v; // Initial velocity - Vec3 w; // Initial ang velocity -}; - - -struct pe_params_timeout - : pe_params -{ - // entities can be forced to go to sleep after some time without external impulses - enum entype - { - type_id = ePE_params_timeout - }; - pe_params_timeout() { type = type_id; MARK_UNUSED timeIdle, maxTimeIdle; } - float timeIdle; // current 'idle' time (time without any 'prods' from outside) - float maxTimeIdle; // sleep when timeIdle>maxTimeIdle; 0 turns this feature off -}; - -struct pe_params_skeleton - : pe_params -{ - // skeleton is a hidden mesh that uses cloth simulation to skin the main physics geometry - enum entype - { - type_id = ePE_params_skeleton - }; - pe_params_skeleton() { type = type_id; MARK_UNUSED partid, ipart, stiffness, thickness, maxStretch, maxImpulse, timeStep, nSteps, hardness, explosionScale, bReset; } - - int partid; // id of the skinned part - int ipart; // ..or its internal index - float stiffness; // skeleton's hardness against bending and shearing - float thickness; // skeleton's thickness for collisions - float maxStretch; // skeleton's maximal stretching - float maxImpulse; // skeleton impulse cap - float timeStep; // time step, used to simulate the skeleton (typically small) - int nSteps; // number of skeleton sub-steps per each structure update - float hardness; // skeleton's hardness against stretching - float explosionScale; // skeleton's explosion impulse scale - int bReset; // resets the skeleton to its original pose -}; - - -////////// articulated entity params -enum joint_flags -{ - angle0_locked = 1, all_angles_locked = 7, angle0_limit_reached = 010, angle0_auto_kd = 0100, joint_no_gravity = 01000, - joint_isolated_accelerations = 02000, joint_expand_hinge = 04000, angle0_gimbal_locked = 010000, - joint_dashpot_reached = 0100000, joint_ignore_impulses = 0200000 -}; - -struct pe_params_joint - : pe_params -{ - enum entype - { - type_id = ePE_params_joint - }; - pe_params_joint() - { - type = type_id; - for (int i = 0; i < 3; i++) - { - MARK_UNUSED limits[0][i], limits[1][i], qdashpot[i], kdashpot[i], bounciness[i], q[i], qext[i], ks[i], kd[i], qtarget[i]; - } - bNoUpdate = 0; - pMtx0 = 0; - flagsPivot = 3; - MARK_UNUSED flags, q0, pivot, ranimationTimeStep, nSelfCollidingParts, animationTimeStep, op[0]; - } - - unsigned int flags; // should be a combination of angle0,1,2_locked, angle0,1,2_auto_kd, joint_no_gravity - int flagsPivot; // if bit 0 is set, update pivot point in parent frame, if bit 1 - in child - Vec3 pivot; // joint pivot in entity CS - quaternionf q0; // orientation of child in parent coordinates that corresponds to angles (0,0,0) - Matrix33* pMtx0; // same as q0 - Vec3 limits[2]; // limits for each angle - Vec3 bounciness; // bounciness for each angle (applied when limit is reached) - Vec3 ks, kd; // stiffness and damping koefficients for each angle angular spring - Vec3 qdashpot; // limit vicinity where joints starts resisting movement - Vec3 kdashpot; // when dashpot is activated, this is roughly the angular speed, stopped in 2 sec - Ang3 q; // angles values - Ang3 qext; // additional angles values (angle[i] = q[i]+qext[i]; only q[i] is taken into account - // while calculating spring torque - Ang3 qtarget; - int op[2]; // body identifiers of parent (optional) and child respectively - int nSelfCollidingParts, * pSelfCollidingParts; // part ids of only parts that should be checked for self-collision - int bNoUpdate; // omit recalculation of body parameters after changing this joint - float animationTimeStep; // used to calculate joint velocities of animation - float ranimationTimeStep; // 1/animation time step, can be not specified (specifying just saves extra division operation) - - VALIDATORS_START - VALIDATOR(pivot) - VALIDATOR_NORM(q0) - VALIDATOR(q) - VALIDATOR(qext) - VALIDATORS_END -}; - -struct pe_params_articulated_body - : pe_params -{ - enum entype - { - type_id = ePE_params_articulated_body - }; - pe_params_articulated_body() - { - type = type_id; - MARK_UNUSED bGrounded, bInheritVel, bCheckCollisions, bCollisionResp, nJointsAlloc; - MARK_UNUSED bGrounded, bInheritVel, bCheckCollisions, bCollisionResp, a, wa, w, v, pivot, scaleBounceResponse, posHostPivot, qHostPivot; - MARK_UNUSED bAwake, pHost, nCollLyingMode, gravityLyingMode, dampingLyingMode, minEnergyLyingMode, iSimType, iSimTypeLyingMode, nRoots; - bApply_dqext = 0; - bRecalcJoints = 1; - } - - int bGrounded; // whether body's pivot is firmly attached to something or free - int bCheckCollisions; // only works with bCollisionResp set - int bCollisionResp; // when on, uses 'ragdoll' simulation mode, when off - 'skeleton' (for hit simulation on alive actors) - Vec3 pivot; // attachment position for grounded entities - Vec3 a; // acceleration of the ground for grounded entities - Vec3 wa; // angular acceleration of the ground for grounded entities - Vec3 w; // angular velocity of the ground for grounded entities - Vec3 v; // linear velocity of the ground for grounded entities - float scaleBounceResponse; // scales impulsive torque that is applied at a joint that has just reached its limit - int bApply_dqext; // adds current dqext to joints velocities. dqext is the speed of external animation and is calculated each time - // qext is set for joint (as difference between new value and current value, multiplied by inverse of animation timestep) - int bAwake; // current state - - IPhysicalEntity* pHost; // 'ground' entity - Vec3 posHostPivot; // attachment position inside pHost - quaternionf qHostPivot; - int bInheritVel; // take pHost velocity into account during the simulation - - int nCollLyingMode; // number of contacts that triggers 'lying mode' - Vec3 gravityLyingMode; // gravity override in lying mode - float dampingLyingMode; // damping override - float minEnergyLyingMode; // sleep speed override - int iSimType; // simulation type: 0-'joint-based', 1-'body-based'; fast motion forces joint-based mode automatically - int iSimTypeLyingMode; // simulation type override - int nRoots; // only used in GetParams - int nJointsAlloc; // pre-allocates this amount of joints and parts - - int bRecalcJoints; // re-build geometry positions from joint agnles -}; - -////////// living entity params - -struct pe_player_dimensions - : pe_params -{ - enum entype - { - type_id = ePE_player_dimensions - }; - pe_player_dimensions() - : dirUnproj(0, 0, 1) - , maxUnproj(0) - { - type = type_id; - MARK_UNUSED sizeCollider, heightPivot, heightCollider, heightEye, heightHead, headRadius, bUseCapsule, groundContactEps; - } - - float heightPivot; // offset from central ground position that is considered entity center - float heightEye; // vertical offset of camera - Vec3 sizeCollider; // collision cylinder dimensions - float heightCollider; // vertical offset of collision geometry center - float headRadius; // radius of the 'head' geometry (used for camera offset) - float heightHead; // center.z of the head geometry - Vec3 dirUnproj; // unprojection direction to test in case the new position overlaps with the environment (can be 0 for 'auto') - float maxUnproj; // maximum allowed unprojection - int bUseCapsule; // switches between capsule and cylinder collider geometry - float groundContactEps; // the amount that the living needs to move upwards before ground contact is lost. defaults to which ever is greater 0.004, or 0.01*geometryHeight - - VALIDATORS_START - VALIDATOR(heightPivot) - VALIDATOR(heightEye) - VALIDATOR_RANGE2(sizeCollider, 0, 100) - VALIDATORS_END -}; - -struct pe_player_dynamics - : pe_params -{ - enum entype - { - type_id = ePE_player_dynamics - }; - pe_player_dynamics() - { - type = type_id; - MARK_UNUSED kInertia, kInertiaAccel, kAirControl, gravity, gravity.z, nodSpeed, mass, bSwimming, surface_idx, bActive, collTypes, pLivingEntToIgnore; - MARK_UNUSED minSlideAngle, maxClimbAngle, maxJumpAngle, minFallAngle, kAirResistance, maxVelGround, timeImpulseRecover, bReleaseGroundColliderWhenNotActive; - } - - float kInertia; // inertia koefficient, the more it is, the less inertia is; 0 means no inertia - float kInertiaAccel; // inertia on acceleration - float kAirControl; // air control coefficient 0..1, 1 - special value (total control of movement) - float kAirResistance; // standard air resistance - Vec3 gravity; // gravity vector - float nodSpeed; // vertical camera shake speed after landings - int bSwimming; // whether entity is swimming (is not bound to ground plane) - float mass; // mass (in kg) - int surface_idx; // surface identifier for collisions - float minSlideAngle; // if surface slope is more than this angle, player starts sliding (angle is in degrees) - float maxClimbAngle; // player cannot climb surface which slope is steeper than this angle (angle is in degrees) - float maxJumpAngle; // player is not allowed to jump towards ground if this angle is exceeded (angle is in degrees) - float minFallAngle; // player starts falling when slope is steeper than this (angle is in degrees) - float maxVelGround; // player cannot stand on surfaces that are moving faster than this - float timeImpulseRecover; // forcefully turns on inertia for that duration after receiving an impulse - int collTypes; // entity types to check collisions against - IPhysicalEntity* pLivingEntToIgnore; // ignore collisions with this *living entity* (doesn't work with other entity types) - int bActive; // 0 disables all simulation for the character, apart from moving along the requested velocity - int bReleaseGroundColliderWhenNotActive; // when not 0, if the living entity is not active, the ground collider, if any, will be explicitly released during the simulation step. -}; - -////////// particle entity params - -struct pe_params_particle - : pe_params -{ - enum entype - { - type_id = ePE_params_particle - }; - pe_params_particle() - { - type = type_id; - MARK_UNUSED mass, size, thickness, wspin, accThrust, kAirResistance, kWaterResistance, velocity, heading, accLift, accThrust, gravity, waterGravity; - MARK_UNUSED surface_idx, normal, q0, minBounceVel, rollAxis, flags, pColliderToIgnore, iPierceability, areaCheckPeriod, minVel, collTypes, dontPlayHitEffect; - } - - unsigned int flags; // see entity flags - float mass; - float size; // pseudo-radius - float thickness; // thickness when lying on a surface (if left unused, size will be used) - Vec3 heading; // direction of movement - float velocity; // velocity along "heading" - float kAirResistance; // air resistance koefficient, F = kv - float kWaterResistance; // same for water - float accThrust; // acceleration along direction of movement - float accLift; // acceleration that lifts particle with the current speed - int surface_idx; - Vec3 wspin; // angular velocity - Vec3 gravity; // stores this gravity and uses it if the current area's gravity is equal to the global gravity - Vec3 waterGravity; // gravity when underwater - Vec3 normal; // aligns this direction with the surface normal when sliding - Vec3 rollAxis; // aligns this directon with the roll axis when rolling (0,0,0 to disable alignment) - quaternionf q0; // initial orientation (zero means x along direction of movement, z up) - float minBounceVel; // velocity threshold for bouncing->sliding switch - float minVel; // sleep speed threshold - IPhysicalEntity* pColliderToIgnore; // physical entity to ignore during collisions - int iPierceability; // pierceability for ray tests; pierceble hits slow the particle down, but don't stop it - int collTypes; // 'objtype' passed to RayWorldntersection - int areaCheckPeriod; // how often (in frames) world area checks are made - int dontPlayHitEffect; // prevent playing of material FX from now on - - VALIDATORS_START - VALIDATOR(mass) - VALIDATOR(size) - VALIDATOR(thickness) - VALIDATOR_NORM(heading) - VALIDATOR_NORM(q0) - VALIDATORS_END -}; - -////////// vehicle entity params - -struct pe_params_car - : pe_params -{ - enum entype - { - type_id = ePE_params_car - }; - pe_params_car() - { - type = type_id; - MARK_UNUSED engineMaxRPM, iIntegrationType, axleFriction, enginePower, maxSteer, maxTimeStep, minEnergy, damping, brakeTorque; - MARK_UNUSED engineMinRPM, engineShiftUpRPM, engineShiftDownRPM, engineIdleRPM, engineStartRPM, clutchSpeed, nGears, gearRatios, kStabilizer; - MARK_UNUSED slipThreshold, gearDirSwitchRPM, kDynFriction, minBrakingFriction, maxBrakingFriction, steerTrackNeutralTurn, maxGear, minGear, pullTilt; - MARK_UNUSED maxTilt, bKeepTractionWhenTilted; - } - - float axleFriction; // friction torque at axes divided by mass of vehicle - float enginePower; // power of engine (about 10,000 - 100,000) - float maxSteer; // maximum steering angle - float engineMaxRPM; // engine torque decreases to 0 after reaching this rotation speed - float brakeTorque; // torque applied when breaking using the engine - int iIntegrationType; // for suspensions; 0-explicit Euler, 1-implicit Euler - float maxTimeStep; // maximum time step when vehicle has only wheel contacts - float minEnergy; // minimum awake energy when vehicle has only wheel contacts - float damping; // damping when vehicle has only wheel contacts - float minBrakingFriction; // limits the the tire friction when handbraked - float maxBrakingFriction; // limits the the tire friction when handbraked - float kStabilizer; // stabilizer force, as a multiplier for kStiffness of respective suspensions - int nWheels; // the number of wheels - float engineMinRPM; // disengages the clutch when falling behind this limit, if braking with the engine - float engineShiftUpRPM; // RPM threshold for for automatic gear switching - float engineShiftDownRPM; - float engineIdleRPM; // RPM for idle state - float engineStartRPM; // sets this RPM when activating the engine - float clutchSpeed; // clutch engagement/disengagement speed - int nGears; - float* gearRatios; // assumes 0-backward gear, 1-neutral, 2 and above - forward - int maxGear, minGear; // additional gear index clamping - float slipThreshold; // lateral speed threshold for switchig a wheel to a 'slipping' mode - float gearDirSwitchRPM; // RPM threshold for switching back and forward gears - float kDynFriction; // friction modifier for sliping wheels - float steerTrackNeutralTurn; // for tracked vehicles, steering angle that causes equal but opposite forces on tracks - float pullTilt; // for tracked vehicles, tilt angle of pulling force towards ground - float maxTilt; // maximum wheel contact normal tilt (left or right) after which it acts as a locked part of the hull; it's a cosine of the angle - int bKeepTractionWhenTilted; // keeps wheel traction in tilted mode -}; - -struct pe_params_wheel - : pe_params -{ - enum entype - { - type_id = ePE_params_wheel - }; - pe_params_wheel() - { - type = type_id; - iWheel = 0; - MARK_UNUSED bDriving, iAxle, suspLenMax, suspLenInitial, minFriction, maxFriction, surface_idx, bCanBrake, bBlocked, - bRayCast, kStiffness, kDamping, kLatFriction, Tscale, w, bCanSteer, kStiffnessWeight; - } - - int iWheel; - int bDriving; - int iAxle; // wheels on the same axle align their coordinates (if only slightly misaligned) - // and apply stabilizer force (if set); axle<0 means the wheel does not affect the physics - int bCanBrake; // handbrake applies - int bBlocked; // locks the wheel (acts like a forced handbrake) - int bCanSteer; // can this wheel steer, 0 or 1 - float suspLenMax; // full suspension length (relaxed) - float suspLenInitial; // length in the initial state (used for automatic computations) - float minFriction; // surface friction is cropped to this min-max range - float maxFriction; - int surface_idx; - int bRayCast; // uses raycasts instead of cylinders - float kStiffness; // if 0, will be computed based on mass distribution, lenMax, and lenInitial - float kStiffnessWeight; // When autocalculating stiffness use this weight for this wheel. Note weights for wheels in front of the centre of mass do not influence the weights of wheels behind the centre of mass - // By default all weights are 1.0 and the sum doesn't have to add up to 1.0! - // Also a <=0 weight will leave the wheel out of the autocalculation. It will be get a stiffness of weight*mass*gravity/defaultLength/numWheels. weight=-1 is a good starting point for these wheels - float kDamping; // absolute value if >=0, otherwise -(fraction of 0-oscillation damping) - float kLatFriction; // lateral friction scale (doesn't apply when on handbrake) - float Tscale; // optional driving torque scale - float w; // rotational velocity; it's computed automatically, but can be overriden if needed -}; - -////////// rope entity params - -struct pe_params_rope - : pe_params -{ - enum entype - { - type_id = ePE_params_rope - }; - pe_params_rope() - { - type = type_id; - //START: Per bone UDP for stiffness, damping and thickness for touch bending vegetation - MARK_UNUSED length, mass, collDist, surface_idx, friction, nSegments, pPoints.data, pVelocities.data, pDamping, pStiffness, pThickness; - //END: Per bone UDP for stiffness, damping and thickness for touch bending vegetation - MARK_UNUSED pEntTiedTo[0], ptTiedTo[0], idPartTiedTo[0], pEntTiedTo[1], ptTiedTo[1], idPartTiedTo[1], stiffnessAnim, maxForce, - flagsCollider, nMaxSubVtx, stiffnessDecayAnim, dampingAnim, bTargetPoseActive, wind, windVariance, airResistance, waterResistance, density, collTypes, - jointLimit, jointLimitDecay, sensorRadius, frictionPull, stiffness, collisionBBox[0], penaltyScale, maxIters, attachmentZone, minSegLen, unprojLimit, noCollDist, hingeAxis; - bLocalPtTied = 0; - } - - float length; // 'target' length; 0 is allowed for ropes with dynamic subdivision - float mass; - float collDist; // thickness for collisions - int surface_idx; // for collision reports; friction is overriden - float friction; // friction for free state and lateral friction in strained state - float frictionPull; // friction in pull direction in strained state - float stiffness; // stiffness against stretching (used in the solver; it's *not* a spring, though) - float stiffnessAnim; // shape-preservation stiffness - float stiffnessDecayAnim; // the final shape stiffness will be interpolated from full to full*(1-decay) at the end - float dampingAnim; // damping for shape preservation forces - int bTargetPoseActive; // 0-no target pose (no shape-preservation stiffness), - // 1-simplified target pose (vertices are pulled directly to targets) - // 2-physically correct target pose (the rope applies penalty torques at joints) - Vec3 wind; // local wind in addition to one from phys areas - float windVariance; // wariance (applied to local only) - float airResistance; // needs to be >0 in order to be affetcted by the wind - float waterResistance; // medium resistance when underwater - float density; // used only to compute buoyancy - float jointLimit; // joint rotation limit (doesn't work when both ends are tied) - float jointLimitDecay; // joint limit change (0..1) towards the unattached rope end; can be positive or negative - float sensorRadius; // size of the sensor used to re-attach the rope if the host entity breaks - float maxForce; // force limit; when breached, the rope will detach itself unless rope_no_tears is set - float penaltyScale; // for the solver in strained state with subdivision on - float attachmentZone; // don't register solver contacts within this distance around attachment points (subdivision mode) - float minSegLen; // delete segments below this length in subdivision mode - float unprojLimit; // rotational unprojection limit per frame (no-subdivision mode) - float noCollDist; // fraction of the segment near the attachment point that doesn't collide (no-subdivision mode) - int maxIters; // tweak for the internal vertex solver - int nSegments; // segment count, changin will reset vertex positions - int flagsCollider; // only collide with entity parts flagged this way - int collTypes; // a selection of ent_xxx flags to collide against - int nMaxSubVtx; // maximum internal vertices per segment in subdivision mode - Vec3 collisionBBox[2]; // bbox for entity proximity query in host's space - // (used make all ropes belonging to one host share the same box, to automatically reuse the query results) - Vec3 hingeAxis; // only allow rotation around this axis (in parent's frame if rope_target_vtx_rel is set) - strided_pointer<Vec3> pPoints; - strided_pointer<Vec3> pVelocities; - - IPhysicalEntity* pEntTiedTo[2]; - int bLocalPtTied; // ptTiedTo is in tied part's local coordinates - Vec3 ptTiedTo[2]; - int idPartTiedTo[2]; - //START: Per bone UDP for stiffness, damping and thickness for touch bending vegetation - float* pDamping; - float* pStiffness; - float* pThickness; - //END: Per bone UDP for stiffness, damping and thickness for touch bending vegetation -}; - -////////// soft entity params - -struct pe_params_softbody - : pe_params -{ - enum entype - { - type_id = ePE_params_softbody - }; - pe_params_softbody() - { - type = type_id; - MARK_UNUSED thickness, maxSafeStep, ks, kdRatio, airResistance, wind, windVariance, nMaxIters, - accuracy, friction, impulseScale, explosionScale, collisionImpulseScale, maxCollisionImpulse, collTypes, waterResistance, massDecay, - shapeStiffnessNorm, shapeStiffnessTang, stiffnessAnim, stiffnessDecayAnim, dampingAnim, maxDistAnim, hostSpaceSim; - } - - float thickness; // thickness for collisions - float maxSafeStep; // time step cap - float ks; // stiffness against stretching (for soft bodies, <0 means fraction of maximum stable) - float kdRatio; // damping in stretch direction, in fractions of 0-oscillation damping - float friction; // overrides material friction - float waterResistance; - float airResistance; - Vec3 wind; // wind in addition to phys area wind - float windVariance; // wind variance, in fractions of 1 (currently changes 4 times/sec) - int nMaxIters; // tweak for the solver (complexity = O(nMaxIters*numVertices)) - float accuracy; // accuracy for the solver (velocity) - float impulseScale; // scale general incoming impulses - float explosionScale; // scale impulses from explosions - float collisionImpulseScale; // not used - float maxCollisionImpulse; // not used - int collTypes; // combination of ent_... flags - float massDecay; // decreases mass from attached points to free ends; mass_free = mass_attached/(1+decay) (can impove stability) - float shapeStiffnessNorm; // resistance to bending - float shapeStiffnessTang; // resistance to shearing - float stiffnessAnim; // strength of linear target pose pull - float stiffnessDecayAnim; // decay of stiffnessAnim - float dampingAnim; // damping for target pose pull - float maxDistAnim; // max deviation from the target pose at the rim; uses stiffnessDecalAnim to scale down closer to attached vtx - float hostSpaceSim; // 0 - world-space simulation, 1 - fully host-space simulation -}; - -/////////// area params - -struct params_wavesim -{ - params_wavesim() { MARK_UNUSED timeStep, waveSpeed, dampingCenter, dampingRim, minhSpread, minVel, simDepth, heightLimit, resistance; } - float timeStep; // fixed timestep used for the simulation - float waveSpeed; // wave propagation speed - float simDepth; // assumed height of moving water layer (relative to cell size) - float heightLimit; // hard limit on height changes (relative to cell size) - float resistance; // rate of velocity transfer from floating objects - float dampingCenter; // damping in the central tile - float dampingRim; // damping in the outer tiles - float minhSpread; // minimum height perturbation that activates a neighbouring tile - float minVel; // sleep speed threshold -}; - -struct pe_params_area - : pe_params -{ - enum entype - { - type_id = ePE_params_area - }; - pe_params_area() { type = type_id; MARK_UNUSED gravity, bUniform, damping, falloff0, bUseCallback, pGeom, volume, borderPad, bConvexBorder, objectVolumeThreshold, cellSize, growthReserve, volumeAccuracy; } - // water/air area params are set through pe_params_buoyancy - - Vec3 gravity; // see also bUniform - float falloff0; // parametric distance (0..1) where falloff starts - int bUniform; // gravity has same direction in every point or always points to the center - int bUseCallback; // will generate immediate EventPhysArea when needs to apply params to an entity - float damping; // uniform damping - IGeometry* pGeom; // phys geometry used in the area - float volume; // the area will try to maintain this volume by adjusting water level - float volumeAccuracy; // accuracy of level computation based on volume (in fractions of the volume) - float borderPad; // after adjusting level, expand the border by this distance - int bConvexBorder; // forces convex border after water level adjustments - float objectVolumeThreshold; // only consider entities larger than this for level adjustment (set in fractions of area volume) - float cellSize; // cell size for wave simulation - params_wavesim waveSim; - float growthReserve; // assume this area increase during level adjustment (only used for wave simulation) -}; - - -////////// water manager params - -struct pe_params_waterman - : pe_params - , params_wavesim -{ - enum entype - { - type_id = ePE_params_waterman - }; - pe_params_waterman() - { - type = type_id; - MARK_UNUSED posViewer, nExtraTiles, nCells, tileSize, timeStep, waveSpeed, - dampingCenter, dampingRim, minhSpread, minVel, simDepth, heightLimit, resistance; - } - - Vec3 posViewer; // water will only be simulated around this point - int nExtraTiles; // number of additional tiles in each direction around the one below posViewer (so total = (nExtarTiles*2+1)^2) - int nCells; // number of cells in each tile - float tileSize; -}; - - -////////////////////////// Action structures ///////////////////// - -////////// common actions -struct pe_action -{ - int type; -}; - -struct pe_action_impulse - : pe_action -{ - enum entype - { - type_id = ePE_action_impulse - }; - pe_action_impulse() { type = type_id; impulse.Set(0, 0, 0); MARK_UNUSED point, angImpulse, partid, ipart; iApplyTime = 2; iSource = 0; } - - Vec3 impulse; - Vec3 angImpulse; // optional - Vec3 point; // point of application, in world CS, optional - int partid; // receiver part identifier - int ipart; // alternatively, part index can be used - int iApplyTime; // 0-apply immediately, 1-apply before the next time step, 2-apply after the next time step - int iSource; // reserved for internal use - - VALIDATORS_START - VALIDATOR_RANGE2(impulse, 0, 1E12f) - VALIDATOR_RANGE2(angImpulse, 0, 1E8f) - VALIDATOR_RANGE2(point, 0, 1E6f) - VALIDATOR_RANGE(ipart, 0, 10000) - VALIDATORS_END -}; - -struct pe_action_reset - : pe_action // Resets dynamic state of an entity -{ - enum entype - { - type_id = ePE_action_reset - }; - pe_action_reset() { type = type_id; bClearContacts = 1; } - int bClearContacts; -}; - -enum constrflags // see pe_action_add_constraint -{ - local_frames = 1, // pt and qframe are in respective entities' coordinate frames - world_frames = 2, // pt and qframe are in the world frame - local_frames_part = 4, // pt and qframe are if respective entity parts' coordinate frames - constraint_inactive = 0x100, // constraint does nothing, except applying _ignore_buddy if set - constraint_ignore_buddy = 0x200, // disables collisions between the constrained entities - constraint_line = 0x400, // position if constrained to a line - constraint_plane = 0x800, // position is constrained to a plane - constraint_free_position = 0x1000, // position is unconstrained - constraint_no_rotation = 0x2000, // relative rotation is fully constrained - constraint_no_enforcement = 0x4000, // disables positional enforcement during fast movement (currently disabled unconditionally) - constraint_no_tears = 0x8000 // constraint is not deleted when force limit is reached -}; - -struct pe_action_add_constraint - : pe_action -{ - enum entype - { - type_id = ePE_action_add_constraint - }; - pe_action_add_constraint() - { - type = type_id; - pBuddy = 0; - flags = world_frames; - MARK_UNUSED id, pt[0], pt[1], partid[0], partid[1], qframe[0], qframe[1], xlimits[0], yzlimits[0], - pConstraintEntity, damping, sensorRadius, maxPullForce, maxBendTorque; - } - int id; // if not set, will be auto-assigned; return value of Action() - IPhysicalEntity* pBuddy; // the second constrained entity; can be WORLD_ENTITY for static attachments - Vec3 pt[2]; // pt[0] must be set; if pt[1] is not set, assumed to be equal to pt[1] - int partid[2]; // if not set, the first part is assumed - quaternionf qframe[2]; // constraint frames for constraint angles computation; if not set, identity in the specified frame is assumed - float xlimits[2]; // rotation limits around x axis ("twist"); if xlimits[0]>=[1], x axis is locked - float yzlimits[2]; // combined yz-rotation - "bending" of x axis; yzlimits[0] is ignored and assumed to be 0 during simulation - unsigned int flags; // see enum constrflags - float damping; // internal constraint damping - float sensorRadius; // used for sampling environment and re-attaching the constraint when something breaks - float maxPullForce, maxBendTorque; // positional and rotational force limits - IPhysicalEntity* pConstraintEntity; // used internally for creating dynamic rope constraints -}; - -struct pe_action_update_constraint - : pe_action -{ - enum entype - { - type_id = ePE_action_update_constraint - }; - pe_action_update_constraint() - { - type = type_id; - MARK_UNUSED idConstraint, pt[0], pt[1], qframe[0], qframe[1], maxPullForce, maxBendTorque, damping; - flagsOR = 0; - flagsAND = (unsigned int)-1; - bRemove = 0; - flags = world_frames; - } - int idConstraint; // doesn't have to be unique - can update several constraints with one id; if not set, updates all constraints - unsigned int flagsOR; - unsigned int flagsAND; - int bRemove; // permanently delete the constraint - Vec3 pt[2]; // local_frames_part is not supported currently - quaternionf qframe[2]; // update to constraint frames - float maxPullForce, maxBendTorque; - float damping; - int flags; // generally it's better to use flagsOR and/or flagsAND -}; - -struct pe_action_register_coll_event - : pe_action -{ - // this can be used to ask an entity to post a fake collision event to the log - enum entype - { - type_id = ePE_action_register_coll_event - }; - pe_action_register_coll_event() { type = type_id; MARK_UNUSED vSelf; } - - Vec3 pt; // collision point - Vec3 n; // collision normal - Vec3 v; // collider's velocity at pt - Vec3 vSelf; // optional override for the current entity's velocity at pt - float collMass; // collider's mass - IPhysicalEntity* pCollider; // collider entity - int partid[2]; - int idmat[2]; - short iPrim[2]; -}; - -struct pe_action_awake - : pe_action -{ - enum entype - { - type_id = ePE_action_awake - }; - pe_action_awake() { type = type_id; bAwake = 1; MARK_UNUSED minAwakeTime; } - int bAwake; - float minAwakeTime; // minimum time to stay awake after executing the action; supported only by some entity types -}; - -struct pe_action_remove_all_parts - : pe_action -{ - enum entype - { - type_id = ePE_action_remove_all_parts - }; - pe_action_remove_all_parts() { type = type_id; } -}; - -struct pe_action_reset_part_mtx - : pe_action -{ - // this will bake the part's matrix into the entity's matrix and clear the former - enum entype - { - type_id = ePE_action_reset_part_mtx - }; - pe_action_reset_part_mtx() { type = type_id; MARK_UNUSED ipart, partid; } - int ipart; - int partid; -}; - -struct pe_action_set_velocity - : pe_action -{ - enum entype - { - type_id = ePE_action_set_velocity - }; - pe_action_set_velocity() { type = type_id; MARK_UNUSED ipart, partid, v, w; bRotationAroundPivot = 0; } - int ipart; // if part is not set, vel is applied to the whole entity; the distinction makes sense only for ragdolls - int partid; - Vec3 v, w; - int bRotationAroundPivot; // if set, w is rotation around the entity's pivot, otherwise around its center of mass - - VALIDATORS_START - VALIDATOR_RANGE2(v, 0, 1E5f) - VALIDATOR_RANGE2(w, 0, 1E5f) - VALIDATORS_END -}; - -struct pe_action_notify - : pe_action -{ - enum entype - { - type_id = ePE_action_notify - }; - enum encodes - { - ParentChange = 0 - }; // the entity this one is attached to moved; only ropes handle it ATM, by immediately enforcing length - pe_action_notify() { type = type_id; iCode = ParentChange; } - int iCode; -}; - -struct pe_action_auto_part_detachment - : pe_action -{ - // this is used to PE_ARTICULATED entities with pre-baked physics simulation - enum entype - { - type_id = ePE_action_auto_part_detachment - }; - pe_action_auto_part_detachment() { type = type_id; MARK_UNUSED threshold, autoDetachmentDist; } - float threshold; // each part will receive a breakable joint with this force limit (which is assumed to be set in fractions of gravity) - float autoDetachmentDist; // additionally, a part will auto-detach itself once it's farther than that from the entity's pivot -}; - -struct pe_action_move_parts - : pe_action -{ - // this will move parts from one entity to another - enum entype - { - type_id = ePE_action_move_parts - }; - int idStart, idEnd; - int idOffset; // added once parts are in the new entity - IPhysicalEntity* pTarget; - Matrix34 mtxRel; // mtxInNewEntity = mtxRel*mtxCurrent - pe_action_move_parts() { type = type_id; idStart = 0; idEnd = 1 << 30; idOffset = 0; mtxRel.SetIdentity(); pTarget = 0; } -}; - -struct pe_action_batch_parts_update - : pe_action -{ - // updates positions of all parts from arrays - enum entype - { - type_id = ePE_action_batch_parts_update - }; - pe_action_batch_parts_update() { type = type_id; qOffs.SetIdentity(); posOffs.zero(); numParts = 0; pnumParts = 0; pIds = 0; pValidator = 0; } - int* pIds; - strided_pointer<quaternionf> qParts; - strided_pointer<Vec3> posParts; - int numParts; - int* pnumParts; - quaternionf qOffs; // extra rotation - Vec3 posOffs; // extra offset - struct Validator - { - virtual ~Validator() {} - virtual bool Lock() = 0; - virtual void Unlock() = 0; - }* pValidator; -}; - -struct pe_action_slice - : pe_action -{ - // slices entity's geometry with a shape - enum entype - { - type_id = ePE_action_slice - }; - pe_action_slice() { type = type_id; MARK_UNUSED ipart, partid; npt = 3; } - int ipart; - int partid; - Vec3* pt; - int npt; // only 3 is supported currently -}; - -////////// living entity actions - -struct pe_action_move - : pe_action // movement request for living entities -{ - enum entype - { - type_id = ePE_action_move - }; - pe_action_move() { type = type_id; iJump = 0; dt = 0; MARK_UNUSED dir; } - - Vec3 dir; // requested velocity vector - int iJump; // jump mode - 1-instant velocity change, 2-just adds to current velocity - float dt; // time interval for this action (doesn't need to be set normally) - - VALIDATORS_START - VALIDATOR_RANGE2(dir, 0, 1000) - VALIDATOR_RANGE(dt, 0, 2) - VALIDATORS_END -}; - -struct pe_action_syncliving - : pe_action // syncing living entity physics -{ - enum entype - { - type_id = pPE_action_syncliving - }; - pe_action_syncliving() { type = type_id; pos.zero(); vel.zero(); velRequested.zero(); } - Vec3 pos; - Vec3 vel; - Vec3 velRequested; -}; - -////////// vehicle entity actions - -struct pe_action_drive - : pe_action -{ - enum entype - { - type_id = ePE_action_drive - }; - pe_action_drive() { type = type_id; MARK_UNUSED pedal, dpedal, steer, dsteer, bHandBrake, clutch, iGear; ackermanOffset = 0.f; } - - float pedal; // engine pedal absolute value; active pedal always awakes the entity - float dpedal; // engine pedal delta - float steer; // steering angle absolute value - float ackermanOffset; // apply ackerman steering, 0.0 -> normal driving front wheels steer, back fixed. 1.0 -> front fixed, back steer. 0.5 -> both front and back steer - float dsteer; // steering angle delta - float clutch; // forces clutch; 0..1 - int bHandBrake; // removing handbrake will automatically awaken the vehicle if it's sleeping - int iGear; // 0-back; 1-neutral; 2+-forward -}; - -////////// rope entity actions - -struct pe_action_target_vtx - : pe_action -{ - enum entype - { - type_id = ePE_action_target_vtx - }; - pe_action_target_vtx() { type = type_id; MARK_UNUSED points, nPoints; posHost.zero(); qHost.SetIdentity(); } - - int nPoints; - Vec3* points; // coordinate frame is world, unless the rope has one of rope_target_vtx_rel flags - Vec3 posHost; // world position of the host the vertices are attached to - Quat qHost; -}; - -////////// soft entity actions - -struct pe_action_attach_points - : pe_action -{ - enum entype - { - type_id = ePE_action_attach_points - }; - pe_action_attach_points() { type = type_id; MARK_UNUSED partid, points; nPoints = 1; pEntity = WORLD_ENTITY; bLocal = 0; } - - IPhysicalEntity* pEntity; - int partid; - int* piVtx; // vertex indices to be attached to pEntity.partid - Vec3* points; // can set the desired attachment points; if not set, current positions are fixed in the target's frame - int nPoints; - int bLocal; // if true, points are in the attached part's CS -}; - -////////////////////////// Status structures ///////////////////// - -////////// common statuses -struct pe_status -{ - int type; -}; - -enum status_pos_flags -{ - status_local = 1, status_thread_safe = 2, status_addref_geoms = 4 -}; - -struct pe_status_pos - : pe_status -{ - enum entype - { - type_id = ePE_status_pos - }; - pe_status_pos() { type = type_id; ipart = partid = -1; flags = 0; pMtx3x4 = 0; pMtx3x3 = 0; iSimClass = 0; timeBack = 0; } - - int partid; // part identifier, -1 for entire entity - int ipart; // optionally, part slot index - unsigned int flags; // status_local if part coordinates should be returned in entity CS rather than world CS - unsigned int flagsOR; // boolean OR for all parts flags of the object (or just flags for the selected part) - unsigned int flagsAND; // boolean AND for all parts flags of the object (or just flags for the selected part) - Vec3 pos; // position of center - Vec3 BBox[2]; // bounding box relative to pos (bbox[0]-min, bbox[1]-max) - quaternionf q; - float scale; - int iSimClass; - Matrix34* pMtx3x4; // optional 3x4 transformation matrix - Matrix33* pMtx3x3; // optional 3x3 rotation+scale matrix - IGeometry* pGeom, * pGeomProxy; - float timeBack; // can retrieve previous position; only supported by rigid entities; pos and q; one step back -}; - -// Only works when USE_IMPROVED_RIGID_ENTITY_SYNCHRONISATION is 1 -struct pe_status_netpos - : pe_status -{ - enum entype - { - type_id = ePE_status_netpos - }; - pe_status_netpos() { type = type_id; } - - Vec3 pos; - quaternionf rot; - Vec3 vel; - Vec3 angvel; - float timeOffset; -}; - -struct pe_status_extent - : pe_status // Caches eForm extent of entity in pGeo -{ - enum entype - { - type_id = ePE_status_extent - }; - pe_status_extent() { type = type_id; eForm = EGeomForm(-1); extent = 0; } - - EGeomForm eForm; - float extent; -}; - -struct pe_status_random - : pe_status_extent // Generates random pos on entity, also caches extent -{ - enum entype - { - type_id = ePE_status_random - }; - pe_status_random() { type = type_id; ran.vPos.zero(); ran.vNorm.zero(); } - PosNorm ran; -}; - -struct pe_status_sensors - : pe_status // Requests status of attached to the entity sensors -{ - enum entype - { - type_id = ePE_status_sensors - }; - pe_status_sensors() { type = type_id; } - - Vec3* pPoints; // pointer to array of points where sensors touch environment (assigned by physical entity) - Vec3* pNormals; // pointer to array of surface normals at points where sensors touch environment - unsigned int flags; // bitmask of flags, bit==1 - sensor touched environment -}; - -struct pe_status_dynamics - : pe_status -{ - enum entype - { - type_id = ePE_status_dynamics - }; - pe_status_dynamics() - : v(ZERO) - , w(ZERO) - , a(ZERO) - , wa(ZERO) - , centerOfMass(ZERO) - { - MARK_UNUSED partid, ipart; - type = type_id; - mass = energy = 0; - nContacts = 0; - time_interval = 0; - submergedFraction = 0; - } - - int partid; - int ipart; - Vec3 v; // velocity - Vec3 w; // angular velocity - Vec3 a; // linear acceleration - Vec3 wa; // angular acceleration - Vec3 centerOfMass; - float submergedFraction; // percentage of the entity that is underwater; 0..1. not supported for individual parts - float mass; // entity's or part's mass - float energy; // kinetic energy; only supported by PE_ARTICULATED currently - int nContacts; - float time_interval; // not used -}; - -struct coll_history_item -{ - Vec3 pt; // collision area center - Vec3 n; // collision normal in entity CS - Vec3 v[2]; // velocities of contacting bodies at the point of impact - float mass[2]; // masses of contacting bodies - float age; // age of collision event - int idCollider; // id of collider (not a pointer, since collider can be destroyed before history item is queried) - int partid[2]; - int idmat[2]; // 0-this body material, 1-collider material -}; - -struct pe_status_collisions - : pe_status -{ - // obsolete, replaced with EventPhysCollision events - enum entype - { - type_id = ePE_status_collisions - }; - pe_status_collisions() { type = type_id; age = 0; len = 1; pHistory = 0; bClearHistory = 0; } - - coll_history_item* pHistory; // pointer to a user-provided array of history items - int len; // length of this array - float age; // maximum age of collision events (older events are ignored) - int bClearHistory; -}; - -struct pe_status_id - : pe_status -{ - // retrives surface id from geometry - enum entype - { - type_id = ePE_status_id - }; - pe_status_id() { type = type_id; ipart = partid = -1; bUseProxy = 1; } - - int ipart; - int partid; - int iPrim; // primitive index (only makes sense for meshes) - int iFeature; // feature id inside the primitive; doesn't affect the result currently - int bUseProxy; // use pPhysGeomProxy or pPhysGeom - int id; // surface id -}; - -struct pe_status_timeslices - : pe_status -{ - // only implemented for PE_LIVING and is obsolete, although still supported - enum entype - { - type_id = ePE_status_timeslices - }; - pe_status_timeslices() { type = type_id; pTimeSlices = 0; sz = 1; precision = 0.0001f; MARK_UNUSED time_interval; } - - float* pTimeSlices; - int sz; - float precision; // time surplus below this threshhold will be discarded - float time_interval; // if unused, time elapsed since the last action will be used -}; - -struct pe_status_nparts - : pe_status // GetStuts will return the number of parts -{ - enum entype - { - type_id = ePE_status_nparts - }; - pe_status_nparts() { type = type_id; } -}; - -struct pe_status_awake - : pe_status -{ - enum entype - { - type_id = ePE_status_awake - }; - pe_status_awake() { type = type_id; lag = 0; } - int lag; // GetStatus returns 1 ("awake") if the entity fell asleep later than this amount of frames before -}; - -struct pe_status_contains_point - : pe_status -{ - enum entype - { - type_id = ePE_status_contains_point - }; - pe_status_contains_point() { type = type_id; } - Vec3 pt; -}; - -struct pe_status_placeholder - : pe_status -{ - enum entype - { - type_id = ePE_status_placeholder - }; - pe_status_placeholder() { type = type_id; } - IPhysicalEntity* pFullEntity; // if called on a placeholder, returns the corresponding full entity -}; - -struct pe_status_sample_contact_area - : pe_status -{ - enum entype - { - type_id = ePE_status_sample_contact_area - }; - pe_status_sample_contact_area() { type = type_id; } - Vec3 ptTest; // checks if ptTest, projected along dirTest falls inside the convex hull of this entity's contacts - Vec3 dirTest; -}; - -struct pe_status_caps - : pe_status -{ - enum entype - { - type_id = ePE_status_caps - }; - pe_status_caps() { type = type_id; } - unsigned int bCanAlterOrientation; // the entity can change orientation that is explicitly set from outside (by baking it into parts/geometries) -}; - -struct pe_status_constraint - : pe_status -{ - enum entype - { - type_id = ePE_status_constraint - }; - pe_status_constraint() { type = type_id; idx = -1; } - int id; - int idx; - int flags; - Vec3 pt[2]; - Vec3 n; - IPhysicalEntity* pBuddyEntity; - IPhysicalEntity* pConstraintEntity; -}; - -////////// area status - -struct pe_status_area - : pe_status -{ - enum entype - { - type_id = ePE_status_area - }; - pe_status_area() { type = type_id; bUniformOnly = false; ctr.zero(); size.zero(); vel.zero(); MARK_UNUSED gravity; pLockUpdate = 0; pSurface = 0; } - - // inputs. - Vec3 ctr, size; // query bounds - Vec3 vel; - bool bUniformOnly; - - // outputs. - Vec3 gravity; - pe_params_buoyancy pb; - volatile int* pLockUpdate; - IGeometry* pSurface; -}; - -////////// living entity statuses - -struct pe_status_living - : pe_status -{ - enum entype - { - type_id = ePE_status_living - }; - pe_status_living() { type = type_id; } - - int bFlying; // whether entity has no contact with ground - float timeFlying; // for how long the entity was flying - Vec3 camOffset; // camera offset - Vec3 vel; // actual velocity (as rate of position change) - Vec3 velUnconstrained; // 'physical' movement velocity - Vec3 velRequested; // velocity requested in the last action - Vec3 velGround; // velocity of the object entity is standing on - float groundHeight; // position where the last contact with the ground occured - Vec3 groundSlope; - int groundSurfaceIdx; - int groundSurfaceIdxAux; // contact with the ground that also has default collision flags - IPhysicalEntity* pGroundCollider; // only returns an actual entity if the ground collider is not static - int iGroundColliderPart; - float timeSinceStanceChange; - //int bOnStairs; // tries to detect repeated abrupt ground height changes - int bStuck; // tries to detect cases when the entity cannot move as before because of collisions - volatile int* pLockStep; // internal timestepping lock - int iCurTime; // quantised time - int bSquashed; // entity is being pushed by heavy objects from opposite directions -}; - -struct pe_status_check_stance - : pe_status -{ - // checks whether new dimensions cause collisions; params have the same meaning as in pe_player_dimensions - enum entype - { - type_id = ePE_status_check_stance - }; - pe_status_check_stance() - : dirUnproj(0, 0, 1) - , unproj(0) { type = type_id; MARK_UNUSED pos, q, sizeCollider, heightCollider, bUseCapsule; } - - Vec3 pos; - quaternionf q; - Vec3 sizeCollider; - float heightCollider; - Vec3 dirUnproj; - float unproj; - int bUseCapsule; -}; - -////////// vehicle entity statuses - -struct pe_status_vehicle - : pe_status -{ - enum entype - { - type_id = ePE_status_vehicle - }; - pe_status_vehicle() { type = type_id; } - - float steer; // current steering angle - float pedal; // current engine pedal - int bHandBrake; // nonzero if handbrake is on - float footbrake; // nonzero if footbrake is pressed (range 0..1) - Vec3 vel; - int bWheelContact; // nonzero if at least one wheel touches ground - int iCurGear; - float engineRPM; - float clutch; - float drivingTorque; - int nActiveColliders; // number of non-static contacting entities -}; - -struct pe_status_wheel - : pe_status -{ - enum entype - { - type_id = ePE_status_wheel - }; - pe_status_wheel() { type = type_id; iWheel = 0; MARK_UNUSED partid; } - int iWheel; - int partid; - - int bContact; // nonzero if wheel touches ground - Vec3 ptContact; // point where wheel touches ground - Vec3 normContact; // contact normal - float w; // rotation speed - int bSlip; - Vec3 velSlip; // slip velocity - int contactSurfaceIdx; - float friction; // current friction applied - float suspLen; // current suspension spring length - float suspLenFull; // relaxed suspension spring length - float suspLen0; // initial suspension spring length - float r; // wheel radius - float torque; // driving torque - float steer; // current streeing angle - IPhysicalEntity* pCollider; -}; - -struct pe_status_vehicle_abilities - : pe_status -{ - enum entype - { - type_id = ePE_status_vehicle_abilities - }; - pe_status_vehicle_abilities() { type = type_id; MARK_UNUSED steer; } - - float steer; // should be set to requested steering angle - Vec3 rotPivot; // returns turning circle center - float maxVelocity; // calculates maximum velocity of forward movement along a plane (steer is ignored) -}; - -////////// articulated entity statuses - -struct pe_status_joint - : pe_status -{ - enum entype - { - type_id = ePE_status_joint - }; - pe_status_joint() { type = type_id; MARK_UNUSED partid, idChildBody; } - - int idChildBody; // requested joint is identified by child body id - int partid; // ..or, alternatively, by any of parts that belong to it - unsigned int flags; // joint flags - Ang3 q; // current joint angles (controlled by physics) - Ang3 qext; // external angles (from animation) - Ang3 dq; // current joint angular velocities - quaternionf quat0; // orientation of child inside parent that corresponds to 0 angles -}; - -////////// rope entity statuses - -struct pe_status_rope - : pe_status -{ - enum entype - { - type_id = ePE_status_rope - }; - pe_status_rope() - : pContactEnts(0) - { - type = type_id; - pPoints = pVelocities = pVtx = pContactNorms = 0; - nCollStat = nCollDyn = bTargetPoseActive = bStrained = 0; - stiffnessAnim = timeLastActive = 0; - nVtx = 0; - lock = 0; - } - - int nSegments; - Vec3* pPoints; // expects the caller to provide an array of nSegments+1, if 0, no points are returned - Vec3* pVelocities; // expects the caller to provide an array of nSegments+1, if 0, no velocities are returned - int nCollStat, nCollDyn; // number of rope contacts with static and dynamic objects - int bTargetPoseActive; // current traget pose mode (0, 1, or 2) - float stiffnessAnim; // current target pose stiffness - int bStrained; // whether the rope is strained, either along a line or wrapped around objects - strided_pointer<IPhysicalEntity*> pContactEnts; // returns a pointer to internal data, the caller doesn't need to provide it - int nVtx; // current number of vertices, used for ropes with dynamic subdivision - Vec3* pVtx; // expects the caller to provide the array - Vec3* pContactNorms; // normals for points (not vertices), expects a pointer from the caller - float timeLastActive; // physics time when the rope was last active (not asleep) - Vec3 posHost; // host (the entity part it's attached to) position that corresponds to the returned state - quaternionf qHost; // host's orientation - int lock; // for subdivided ropes: +1 to leave read-locked, -1 to release from a previously read-locked state; 0 - local locking only -}; - -////////// soft entity statuses - -enum ESSVFlags -{ - eSSV_LockPos = 1, // locks vertices (soft entity won't be able to update them until released) - eSSV_UnlockPos = 2 // release the vertices -}; - -struct pe_status_softvtx - : pe_status -{ - enum entype - { - type_id = ePE_status_softvtx - }; - pe_status_softvtx() - : pVtx(0) - , pNormals(0) { type = type_id; pVtxMap = 0; flags = 0; } - - int nVtx; - strided_pointer<Vec3> pVtx; // a pointer to an internal data; doesn't need to be filled - strided_pointer<Vec3> pNormals; // a pointer to an internal data; doesn't need to be filled - int* pVtxMap; // mapping table mesh vertex->simulated vertex (can be 0) - IGeometry* pMesh; // phys mesh that reflects the simulated data - int flags; // see ESSVFlags - quaternionf qHost; // host's orientation - Vec3 posHost; // host (the entity part it's attached to) position that corresponds to the returned state - Vec3 pos; // entity position that corresponds to the returned state - quaternionf q; // entity's orientation -}; - -////////// waterman statuses - -struct SWaterTileBase -{ - int bActive; - float* ph; // heights - Vec3* pvel; // velocities -}; - -struct pe_status_waterman - : pe_status -{ - enum entype - { - type_id = ePE_status_waterman - }; - pe_status_waterman() { type = type_id; } - - int bActive; - Matrix33 R; - Vec3 origin; - int nTiles, nCells; // number of tiles and cells in one dimension - SWaterTileBase** pTiles; // nTiles^2 entries -}; - -////////////////////////// Geometry structures ///////////////////// - -////////// common geometries -enum geom_flags -{ - // collisions between parts are checked if (part0->flagsCollider & part1->flags) !=0 - geom_colltype0 = 0x0001, geom_colltype1 = 0x0002, geom_colltype2 = 0x0004, geom_colltype3 = 0x0008, geom_colltype4 = 0x0010, - geom_colltype5 = 0x0020, geom_colltype6 = 0x0040, geom_colltype7 = 0x0080, geom_colltype8 = 0x0100, geom_colltype9 = 0x0200, - geom_colltype10 = 0x0400, geom_colltype11 = 0x0800, geom_colltype12 = 0x1000, geom_colltype13 = 0x2000, geom_colltype14 = 0x4000, - geom_colltype_ray = 0x8000, // special colltype used by raytracing by default - geom_floats = 0x10000, // colltype required to apply buoyancy - geom_proxy = 0x20000, // only used in AddGeometry to specify that this geometry should go to pPhysGeomProxy - geom_structure_changes = 0x40000, // part is breaking/deforming - geom_can_modify = 0x80000, // geometry is cloned and is used in this entity only - geom_squashy = 0x100000, // part has 'soft' collisions (used for tree foliage proxy) - geom_log_interactions = 0x200000, // part will post EventPhysBBoxOverlap whenever something happens inside its bbox - geom_monitor_contacts = 0x400000, // part needs collision callback from the solver (used internally) - geom_manually_breakable = 0x800000, // part is breakable outside the physics - geom_no_coll_response = 0x1000000, // collisions are detected and reported, but not processed - geom_mat_substitutor = 0x2000000, // geometry is used to change other collision's material id if the collision point is inside it - geom_break_approximation = 0x4000000, // applies capsule approximation after breaking (used for tree trunks) - geom_no_particle_impulse = 0x8000000, // phys particles don't apply impulses to this part; should be used in flagsCollider - geom_destroyed_on_break = 0x2000000, // should be used in flagsCollider - // mnemonic group names - geom_colltype_player = geom_colltype1, geom_colltype_explosion = geom_colltype2, - geom_colltype_vehicle = geom_colltype3, geom_colltype_foliage = geom_colltype4, geom_colltype_debris = geom_colltype5, - geom_colltype_foliage_proxy = geom_colltype13, geom_colltype_obstruct = geom_colltype14, - geom_colltype_solid = 0x0FFF & ~geom_colltype_explosion, geom_collides = 0xFFFF -}; - - - -struct pe_geomparams -{ - enum entype - { - type_id = ePE_geomparams - }; - pe_geomparams() - { - type = type_id; - density = mass = 0; - pos.Set(0, 0, 0); - q.SetIdentity(); - bRecalcBBox = 1; - flags = geom_colltype_solid | geom_colltype_ray | geom_floats | geom_colltype_explosion; - flagsCollider = geom_colltype0; - pMtx3x4 = 0; - pMtx3x3 = 0; - scale = 1.0f; - pLattice = 0; - pMatMapping = 0; - nMats = 0; - MARK_UNUSED surface_idx, minContactDist, idmatBreakable; - } - - int type; - float density; // 0 if mass is used - float mass; // 0 if density is used - Vec3 pos; // offset from object's geometrical pivot - quaternionf q; // orientation relative to object - float scale; - Matrix34* pMtx3x4; // optional full transform matrix - Matrix33* pMtx3x3; // optional 3x3 orintation+scale matrix - int surface_idx; // surface identifier (used if corresponding CGeometry does not contain materials) - unsigned int flags, flagsCollider; - float minContactDist; // contacts closer then this threshold are merged - int idmatBreakable; // index for procedural (boolean) breakability - ITetrLattice* pLattice; // optional tetrahedral lattice (for lattice breaking and soft bodies) - int* pMatMapping; // mapping of mat ids from geometry to final mat ids - int nMats; - int bRecalcBBox; // recalculate all bbox info after the part is added - - VALIDATORS_START - VALIDATOR_RANGE(density, -1E8, 1E8) - VALIDATOR_RANGE(mass, -1E8, 1E8) - VALIDATOR(pos) - VALIDATOR_NORM_MSG(q, "(perhaps non-uniform scaling was used in the asset?)", pt) - VALIDATORS_END -}; - -////////// articulated entity geometries - -struct pe_articgeomparams - : pe_geomparams -{ - enum entype - { - type_id = ePE_articgeomparams - }; - pe_articgeomparams() { type = type_id; idbody = 0; } - pe_articgeomparams(pe_geomparams& src) - { - type = type_id; - density = src.density; - mass = src.mass; - pos = src.pos; - q = src.q; - scale = src.scale; - surface_idx = src.surface_idx; - pLattice = src.pLattice; - pMatMapping = src.pMatMapping; - nMats = src.nMats; - pMtx3x4 = src.pMtx3x4; - pMtx3x3 = src.pMtx3x3; - flags = src.flags; - flagsCollider = src.flagsCollider; - idbody = 0; - idmatBreakable = src.idmatBreakable; - bRecalcBBox = src.bRecalcBBox; - if (!is_unused(src.minContactDist)) - { - minContactDist = src.minContactDist; - } - else - { - MARK_UNUSED minContactDist; - } - } - int idbody; // id of the subbody this geometry is attached to, the 1st add geometry specifies frame CS of this subbody -}; - -////////// vehicle entity geometries - -const int NMAXWHEELS = 30; -struct pe_cargeomparams - : pe_geomparams -{ - enum entype - { - type_id = ePE_cargeomparams - }; - pe_cargeomparams() - : pe_geomparams() { type = type_id; MARK_UNUSED bDriving, minFriction, maxFriction, bRayCast, kLatFriction; bCanBrake = 1; bCanSteer = 1; kStiffnessWeight = 1.f; } - pe_cargeomparams(pe_geomparams& src) - { - type = type_id; - density = src.density; - mass = src.mass; - pos = src.pos; - q = src.q; - surface_idx = src.surface_idx; - idmatBreakable = src.idmatBreakable; - pLattice = src.pLattice; - pMatMapping = src.pMatMapping; - nMats = src.nMats; - pMtx3x4 = src.pMtx3x4; - pMtx3x3 = src.pMtx3x3; - flags = src.flags; - flagsCollider = src.flagsCollider; - MARK_UNUSED bDriving, minFriction, maxFriction, bRayCast; - bCanBrake = 1, bCanSteer = 1; - kStiffnessWeight = 1.f; - } - int bDriving; // whether wheel is driving, -1 - geometry os not a wheel - int iAxle; // wheel axle, currently not used - int bCanBrake; // whether the wheel is locked during handbrakes - int bRayCast; // whether the wheel use simple raycasting instead of geometry sweep check - int bCanSteer; // wheel the wheel can steer - Vec3 pivot; // upper suspension point in vehicle CS - float lenMax; // relaxed suspension length - float lenInitial; // current suspension length (assumed to be length in rest state) - float kStiffness; // suspension stiffness, if 0 - calculate from lenMax, lenInitial, and vehicle mass and geometry - float kStiffnessWeight; // When autocalculating stiffness use this weight for this wheel. Note weights for wheels in front of the centre of mass do not influence the weights of wheels behind the centre of mass - float kDamping; // suspension damping, if <0 - calculate as -kdamping*(approximate zero oscillations damping) - float minFriction, maxFriction; // additional friction limits for tire friction - float kLatFriction; // coefficient for lateral friction -}; - -///////////////// tetrahedra lattice params //////////////////////// - -struct pe_tetrlattice_params - : pe_params -{ - enum entype - { - type_id = ePE_tetrlattice_params - }; - pe_tetrlattice_params() - { - type = type_id; - MARK_UNUSED nMaxCracks, maxForcePush, maxForcePull, maxForceShift, maxTorqueTwist, maxTorqueBend, crackWeaken, density; - } - - int nMaxCracks; // maximum cracks per update - float maxForcePush, maxForcePull, maxForceShift; // linear force limits - float maxTorqueTwist, maxTorqueBend; // angular force limits - float crackWeaken; // weakens faces neighbouring a newly generated crack (0..1) - float density; // also affects all force limits -}; - -///////////////////////////////////////////////////////////////////////////////////// -//////////////////////////// IGeometry Interface //////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////// - -struct geom_world_data // geometry orientation for Intersect() requests -{ - geom_world_data() - { - v.Set(0, 0, 0); - w.Set(0, 0, 0); - offset.Set(0, 0, 0); - R.SetIdentity(); - centerOfMass.Set(0, 0, 0); - scale = 1.0f; - iStartNode = 0; - } - Vec3 offset; - Matrix33 R; - float scale; - Vec3 v, w; // used to give hints about unprojection direction - Vec3 centerOfMass; // w is rotation around this point - int iStartNode; // for warm-starting (checks collisions in this node first) -}; - -struct intersection_params -{ - intersection_params() - { - iUnprojectionMode = 0; - vrel_min = 1E-6f; - time_interval = 100.0f; - maxSurfaceGapAngle = 1.0f * float(g_PI / 180); - pGlobalContacts = 0; - minAxisDist = 0; - bSweepTest = false; - centerOfRotation.Set(0, 0, 0); - axisContactNormal.Set(0, 0, 1); - unprojectionPlaneNormal.Set(0, 0, 0); - axisOfRotation.Set(0, 0, 0); - bKeepPrevContacts = false; - bStopAtFirstTri = false; - ptOutsidePivot[0].Set(1E11f, 1E11f, 1E11f); - ptOutsidePivot[1].Set(1E11f, 1E11f, 1E11f); - maxUnproj = 1E10f; - bNoAreaContacts = false; - bNoBorder = false; - bNoIntersection = 0; - bExactBorder = 0; - bThreadSafe = bThreadSafeMesh = 0; - } - int iUnprojectionMode; // 0-angular, 1-rotational - Vec3 centerOfRotation; // for mode 1 only - Vec3 axisOfRotation; // if left 0, will be set based on collision area normal - float time_interval; // used to set unprojection limits - float vrel_min; // if local relative velocity in contact area is above this, unprojects along its derection; otherwise along area normal - float maxSurfaceGapAngle; // theshold for generating area contacts - float minAxisDist; // disables rotational unprojection if contact point is closer than this to the axis - Vec3 unprojectionPlaneNormal; // restrict linear unprojection to this plane - Vec3 axisContactNormal; // a mild hint about possible contact normal - float maxUnproj; // unprojections longer than this are discarded - Vec3 ptOutsidePivot[2]; // discard contacts that are not facing outward wrt this point - bool bSweepTest; // requests a linear sweep test along v*time_interval (v from geom_world_data) - bool bKeepPrevContacts; // append results to existing contact buffer - bool bStopAtFirstTri; // stop after the first collision is detected - bool bNoAreaContacts; // don't try to detect contact areas - bool bNoBorder; // don't trace contact border - int bExactBorder; // always tries to return a consequtive border (useful for boolean ops) - int bNoIntersection; // don't find all intersection points (only applies to primitive-primitive collisions) - int bBothConvex; // (output) both operands were convex - int bThreadSafe; // set if it's known that no other thread will contend for the internal intersection data (only used in PrimitiveWorldIntersection now) - int bThreadSafeMesh; // set if it's known that no other thread will try to modify the colliding geometry - geom_contact* pGlobalContacts; // pointer to thread's global contact buffer -}; - -struct phys_geometry -{ - IGeometry* pGeom; - Vec3 Ibody; // tensor of inertia in body frame - quaternionf q; // body frame - Vec3 origin; - float V; // volume - int nRefCount; - int surface_idx; // used for primitives and meshes without per-face ids - int* pMatMapping; // mat mapping; can later be overridden inside entity part - int nMats; - PhysicsForeignData pForeignData; // any external pointer to be associated with phys geometry -}; - -struct bop_newvtx -{ - int idx; // vertex index in the resulting A phys mesh - int iBvtx; // -1 if intersection vertex, >=0 if B vertex - int idxTri[2]; // intersecting triangles' foreign indices -}; - -struct bop_newtri -{ - int idxNew; // a newly generated foreign index (can be remapped later) - int iop; // triangle source 0=A, 1=B - int idxOrg; // original (triangulated) triangle's foreign index - int iVtx[3]; // for each vertex, existing vertex index if >=0, -(new vertex index+1) if <0 - float areaOrg; // original triangle's area - Vec3 area[3]; // areas of compementary triangles for each vertex (divide by original tri area to get barycentric coords) -}; - -struct bop_vtxweld -{ - void set(int _ivtxDst, int _ivtxWelded) { ivtxDst = _ivtxDst; ivtxWelded = _ivtxWelded; } - int ivtxDst : 16; // ivtxWelded is getting replaced with ivtxDst - int ivtxWelded : 16; -}; - -struct bop_TJfix -{ - void set(int _iACJ, int _iAC, int _iABC, int _iCA, int _iTJvtx) { iACJ = _iACJ; iAC = _iAC; iABC = _iABC; iCA = _iCA; iTJvtx = _iTJvtx; } - // A _____J____ C (ACJ is a thin triangle on top of ABC; J is 'the junction vertex') - // \ . / in ABC: set A->Jnew - // \ . / in ACJ: set J->Jnew, A -> A from original ABC, C -> B from original ABC - // \/ - // B - int iABC; // big triangle's foreign idx - int iACJ; // small triangle's foreign idx - int iCA; // CA edge number in ABC - int iAC; // AC edge number in ACJ - int iTJvtx; // J vertex index -}; - -struct bop_meshupdate_thunk -{ - bop_meshupdate_thunk() { prevRef = nextRef = this; } - virtual ~bop_meshupdate_thunk() { prevRef->nextRef = nextRef; nextRef->prevRef = prevRef; prevRef = nextRef = this; } - bop_meshupdate_thunk* prevRef, * nextRef; -}; - -struct bop_meshupdate - : bop_meshupdate_thunk -{ - bop_meshupdate() { Reset(); } - virtual ~bop_meshupdate(); - - void Reset() - { - pRemovedVtx = 0; - pRemovedTri = 0; - pNewVtx = 0; - pNewTri = 0; - pWeldedVtx = 0; - pTJFixes = 0; - pMovedBoxes = 0; - nRemovedVtx = nRemovedTri = nNewVtx = nNewTri = nWeldedVtx = nTJFixes = nMovedBoxes = 0; - next = 0; - pMesh[0] = pMesh[1] = 0; - relScale = 1.0f; - } - - IGeometry* pMesh[2]; // 0-dst (A), 1-src (B) - int* pRemovedVtx; - int nRemovedVtx; - int* pRemovedTri; - int nRemovedTri; - bop_newvtx* pNewVtx; - int nNewVtx; - bop_newtri* pNewTri; - int nNewTri; - bop_vtxweld* pWeldedVtx; - int nWeldedVtx; - bop_TJfix* pTJFixes; - int nTJFixes; - bop_meshupdate* next; - primitives::box* pMovedBoxes; - int nMovedBoxes; - float relScale; -}; - -struct trinfo -{ - trinfo& operator=(trinfo& src) { ibuddy[0] = src.ibuddy[0]; ibuddy[1] = src.ibuddy[1]; ibuddy[2] = src.ibuddy[2]; return *this; } - index_t ibuddy[3]; -}; - -struct mesh_island // mesh island is a connected group of trinagles -{ - int itri; // first triangle - int nTris; // trinagle count - int iParent; // outer island is V<0 - int iChild; // first islands inside it with V<0 - int iNext; // maintains a linked list of iChild's inside iParent - float V; // can be negative (means it represents an inner surface) - Vec3 center; // geometrical center - int bProcessed; // for internal use -}; - -struct tri2isle // maintains a linked triangle list inside an island -{ - unsigned int inext : 16; - unsigned int isle : 15; - unsigned int bFree : 1; -}; - -struct mesh_data - : primitives::primitive -{ - index_t* pIndices; - char* pMats; - int* pForeignIdx; // an int associated with each face - strided_pointer<Vec3> pVertices; - Vec3* pNormals; - int* pVtxMap; // original vertex index->merged vertex index - trinfo* pTopology; // neighbours for each triangle's edge - int nTris, nVertices; - mesh_island* pIslands; - int nIslands; - tri2isle* pTri2Island; - int flags; -}; - -const int BOP_NEWIDX0 = 0x8000000; - -enum geomtypes -{ - GEOM_TRIMESH = primitives::triangle::type, GEOM_HEIGHTFIELD = primitives::heightfield::type, GEOM_CYLINDER = primitives::cylinder::type, - GEOM_CAPSULE = primitives::capsule::type, GEOM_RAY = primitives::ray::type, GEOM_SPHERE = primitives::sphere::type, - GEOM_BOX = primitives::box::type, GEOM_VOXELGRID = primitives::voxelgrid::type -}; -enum foreigntypes -{ - DATA_OWNED_OBJECT = 1, DATA_MESHUPDATE = -1, DATA_UNUSED = -2 -}; - -enum meshflags -{ - // mesh_shared_... flags mean that the mesh will not attempt to free the corresponding array upon deletion - mesh_shared_vtx = 1, mesh_shared_idx = 2, mesh_shared_mats = 4, mesh_shared_foreign_idx = 8, mesh_shared_normals = 0x10, - // bounding volume flags (if several are specified in CreateMesh(), the best fitting one will be used) - mesh_OBB = 0x20, mesh_AABB = 0x40, mesh_SingleBB = 0x80, mesh_AABB_rotated = 0x40000, mesh_VoxelGrid = 0x80000, - // mesh_multicontact is a hint on how many contacts per node to expect; 0-one contact, 2-no limit, 1-balanced - mesh_multicontact0 = 0x100, mesh_multicontact1 = 0x200, mesh_multicontact2 = 0x400, - // mesh_approx flags are used in CreateMesh to specify which primitive approximations to try - mesh_approx_cylinder = 0x800, mesh_approx_box = 0x1000, mesh_approx_sphere = 0x2000, mesh_approx_capsule = 0x200000, - mesh_keep_vtxmap = 0x8000, // keeps vertex map after adjacent vertices were merged - mesh_keep_vtxmap_for_saving = 0x10000, // deletes vertex map after loading - mesh_no_vtx_merge = 0x20000, // does not attempt to merge adjacent vertices - mesh_always_static = 0x100000, // simplifies phys mass properties calculation if by just setting them to 0 - mesh_full_serialization = 0x400000, // mesh will save all data to stream unconditionally - mesh_transient = 0x800000, // all mesh allocations will go to a flushable pool - mesh_no_booleans = 0x1000000, // disables boolean operations on the mesh - mesh_AABB_plane_optimise = 0x4000, // aabb generation is faster since it assumes the tri's are in a plane and distributed uniformly - mesh_no_filter = 0x2000000 // doesn't attempt to filter away degenerate triangles -}; -enum meshAuxData -{ - mesh_data_materials = 1, mesh_data_foreign_idx = 2, mesh_data_vtxmap = 4 -}; // used in DestroyAuxiliaryMeshData - -struct IOwnedObject -{ - // <interfuscator:shuffle> - virtual ~IOwnedObject(){} - virtual int Release() = 0; - // </interfuscator:shuffle> -}; - -struct SOcclusionCubeMap; - -struct IGeometry -{ - struct SBoxificationParams - { - SBoxificationParams() { minFaceArea = sqr(0.4f); distFilter = 0.2f; voxResolution = 100; maxFaceTiltAngle = DEG2RAD(10); minLayerFilling = 0.5f; maxLayerReusage = 0.8f; maxVoxIslandConnections = 0.5f; } - float minFaceArea; // ignore patches smaller than this in the box growing process - float distFilter; // smooth away details smaller than this (in terms of linear size) - int voxResolution; // resolution of the grid in the longest direction - float maxFaceTiltAngle; // tolerance for patch alignment with box faces - float minLayerFilling; // stop growing boxes once layer fill percentage falls below this - float maxLayerReusage; // stop growing a box if it goes through already used cells (> than this percentage) - float maxVoxIslandConnections; // ignore isolated voxel islands that have more than this amount of connections to the used ones - }; - // <interfuscator:shuffle> - virtual ~IGeometry(){} - virtual int GetType() = 0; // see enum geomtypes - virtual int AddRef() = 0; - virtual void Release() = 0; - virtual void Lock(int bWrite = 1) = 0; // locks the geometry for reading or writing - virtual void Unlock(int bWrite = 1) = 0; // bWrite should match the preceding Lock - virtual void GetBBox(primitives::box* pbox) = 0; // possibly oriented bbox (depends on BV tree type) - virtual int CalcPhysicalProperties(phys_geometry* pgeom) = 0; // O(num_triangles) for meshes, unless mesh_always_static is set - virtual int PointInsideStatus(const Vec3& pt) = 0; // for meshes, will create an auxiliary hashgrid for acceleration - // IntersectLocked - the main function for geomtries. pdata1,pdata2,pparams can be 0 - defaults will be assumed. - // returns a pointer to an internal thread-specific contact buffer, locked with the lock argument - virtual int IntersectLocked(IGeometry* pCollider, geom_world_data* pdata1, geom_world_data* pdata2, intersection_params* pparams, geom_contact*& pcontacts, WriteLockCond& lock) = 0; - virtual int IntersectLocked(IGeometry* pCollider, geom_world_data* pdata1, geom_world_data* pdata2, intersection_params* pparams, geom_contact*& pcontacts, WriteLockCond& lock, int iCaller) = 0; - // Intersect - same as Intersect, but doesn't lock pcontacts - virtual int Intersect(IGeometry* pCollider, geom_world_data* pdata1, geom_world_data* pdata2, intersection_params* pparams, geom_contact*& pcontacts) = 0; - // FindClosestPoint - for non-convex meshes only does local search, doesn't guarantee global minimum - // iFeature's format: (feature type: 2-face, 1-edge, 0-vertex)<<9 | feature index - // if ptdst0 and ptdst1 are different, searches for a closest point on a line segment - // ptres[0] is the closest point on the geometry, ptres[1] - on the test line segment - virtual int FindClosestPoint(geom_world_data* pgwd, int& iPrim, int& iFeature, const Vec3& ptdst0, const Vec3& ptdst1, Vec3* ptres, int nMaxIters = 10) = 0; - // CalcVolumetricPressure: a fairly correct computation of volumetric pressure with inverse-quadratic falloff (ex: explosions) - // for a surface fragment dS, impulse is: k*dS*cos(surface_normal,direction to epicenter) / max(rmin, distance to epicenter)^2 - // returns integral impulse and angular impulse - virtual void CalcVolumetricPressure(geom_world_data* gwd, const Vec3& epicenter, float k, float rmin, const Vec3& centerOfMass, Vec3& P, Vec3& L) = 0; - // CalculateBuoyancy: computes the submerged volume (return value) and the mass center of the submerged part - virtual float CalculateBuoyancy(const primitives::plane* pplane, const geom_world_data* pgwd, Vec3& submergedMassCenter) = 0; - // CalculateMediumResistance: computes medium resistance integral of the surface; self flow of the medium should be baked into pgwd - // for a surface fragment dS with normal n and velocity v impulse is: -n*max(0,n*v) (can be scaled by the medium resistance coeff. later) - virtual void CalculateMediumResistance(const primitives::plane* pplane, const geom_world_data* pgwd, Vec3& dPres, Vec3& dLres) = 0; - // DrawWireframe: draws physics helpers; iLevel>0 will draaw a level in the bounding volume tree - virtual void DrawWireframe(IPhysRenderer* pRenderer, geom_world_data* gwd, int iLevel, int idxColor) = 0; - virtual int GetPrimitiveId(int iPrim, int iFeature) = 0; // get material id for a primitive (iFeature is ignored currently) - // GetPrimitive: expects a valid pprim pointer, type depends on GetType; meshes return primitives::triangle - virtual int GetPrimitive(int iPrim, primitives::primitive* pprim) = 0; - virtual int GetForeignIdx(int iPrim) = 0; // only works for meshes - virtual Vec3 GetNormal(int iPrim, const Vec3& pt) = 0; // only implemented for meshes currently; pt is ignored - virtual int GetFeature(int iPrim, int iFeature, Vec3* pt) = 0; // returns vertices of face, edge, or vertex; only for boxes and meshes currently - virtual int IsConvex(float tolerance) = 0; - // PrepareForRayTest: creates an auxiliary hash structure for short rays test acceleration - virtual void PrepareForRayTest(float raylen) = 0; // raylen - 'expected' ray length to optimize the hash for - // BuildOcclusionCubemap: cubemap projection-based occlusion (used for explosions); pGrids are 6 [nRes^2] arrays - // iMode: 0 - update cubemap in pGrid0; 1 - build cubemap in pGrid1, grow edges by nGrow cells, and compare with pGrid0 - // all geometry closer than rmin is ignored (to avoid large projection scale); same if farther than rmax - virtual float BuildOcclusionCubemap(geom_world_data* pgwd, int iMode, SOcclusionCubeMap* cubemap0, SOcclusionCubeMap* cubemap1, int nGrow) = 0; - virtual void GetMemoryStatistics(ICrySizer* pSizer) = 0; - virtual void Save(CMemStream& stm) = 0; - virtual void Load(CMemStream& stm) = 0; - // Load: meshes can avoid storing vertex, index, and mat id data, in this case same arrays should be provided during loading - virtual void Load(CMemStream& stm, strided_pointer<const Vec3> pVertices, strided_pointer<unsigned short> pIndices, char* pIds) = 0; - virtual int GetPrimitiveCount() = 0; - virtual const primitives::primitive* GetData() = 0; // returns an pointer to an internal structure; for meshes returns mesh_data - virtual void SetData(const primitives::primitive*) = 0; // not supported by meshes - virtual float GetVolume() = 0; - virtual Vec3 GetCenter() = 0; - // Subtract: performs boolean subtraction; if bLogUpdates==1, will create bop_meshupdate inside the mesh - virtual int Subtract(IGeometry* pGeom, geom_world_data* pdata1, geom_world_data* pdata2, int bLogUpdates = 1) = 0; - virtual int GetSubtractionsCount() = 0; // number of Subtract()s the mesh has survived so far - // GetForeignData: returns a pointer associated with the geometry - // special: GetForeignData(DATA_MESHUPDATE) returns the internal bop_meshupdate list (does not interfere with the main foreign pointer) - virtual PhysicsForeignData GetForeignData(int iForeignData = 0) = 0; - virtual int GetiForeignData() = 0; // foreign data type - virtual void SetForeignData(PhysicsForeignData pForeignData, int iForeignData) = 0; - virtual int GetErrorCount() = 0; // for meshes, the number of edges that don't belong to exactly 2 triangles - virtual void DestroyAuxilaryMeshData(int idata) = 0; // see meshAuxData enum - virtual void RemapForeignIdx(int* pCurForeignIdx, int* pNewForeignIdx, int nTris) = 0; // used in rendermesh-physics sync after boolean ops - virtual void AppendVertices(Vec3* pVtx, int* pVtxMap, int nVtx) = 0; // used in rendermesh-physics sync after boolean ops - virtual float GetExtent(EGeomForm eForm) const = 0; - virtual void GetRandomPos(PosNorm& ran, EGeomForm eForm) const = 0; - virtual void CompactMemory() = 0; // used only by non-breakable meshes to compact non-shared vertices into same contingous block of memory - // Boxify: attempts to build a set of boxes covering the geometry's volume (only supported by trimeshes) - virtual int Boxify(primitives::box* pboxes, int nMaxBoxes, const SBoxificationParams& params) = 0; - // Sanity check the geometry. i.e. its tree doesn't have an excessive depth. returns 0 if fails - virtual int SanityCheck() = 0; - // </interfuscator:shuffle> -}; - - -///////////////////////////////////////////////////////////////////////////////////// -//////////////////////////// IGeometryManager Interface ///////////////////////////// -///////////////////////////////////////////////////////////////////////////////////// - -struct SMeshBVParams {}; - -struct SBVTreeParams - : SMeshBVParams -{ - int nMinTrisPerNode; // if a split creates a node with <nMinTris triangles, another split is attempted - int nMaxTrisPerNode; // nodes are split until they have more triangles than this - float favorAABB; // when several BV trees are requested in CreateMesh, it selects the one with the smallest volume; favorAABB scales AABB's volume down -}; - -struct SVoxGridParams - : SMeshBVParams // voxel grid is a regular 3d grid collision test acceleration structure -{ - Vec3 origin; - Vec3 step; - Vec3i size; -}; - -struct ITetrLattice -{ - // <interfuscator:shuffle> - virtual ~ITetrLattice(){} - virtual int SetParams(const pe_params*) = 0; // only accepts pe_tetrlattice_params - virtual int GetParams(pe_params*) = 0; - virtual void DrawWireframe(IPhysRenderer* pRenderer, geom_world_data* gwd, int idxColor) = 0; - virtual IGeometry* CreateSkinMesh(int nMaxTrisPerBVNode = 8) = 0; // builds triangle mesh for exterior faces - virtual int CheckPoint(const Vec3& pt, int* idx, float* w) = 0; // check if a point is inside any tetrahedron, fills barycentric weights[4] - virtual void Release() = 0; - // </interfuscator:shuffle> -}; - -struct IBreakableGrid2d -{ - // <interfuscator:shuffle> - virtual ~IBreakableGrid2d(){} - // BreakIntoChunks: emulates fracure in the grid around pt with dimensions r x ry - // ptout receives a pointer to a vertex array - // return value is an allocated array of indices, 3 per triangle, -1 marks contour end, -2 array end - // maxPatchTris tells to unite broken trianges into patches of up to this size; 0 means broken triangles are discarded - // jointhresh (0..1) affects the way triangles unite into patches - // seed bootsraps the RNG if >=0 - // hole edges are filtered to removes corners sharper than filterAng (except those that are formed by several joined triangles) - virtual int* BreakIntoChunks(const vector2df& pt, float r, vector2df*& ptout, int maxPatchTris, float jointhresh, int seed = -1, float filterAng = 0.0f, float ry = 0.0f) = 0; - virtual primitives::grid* GetGridData() = 0; - virtual bool IsEmpty() = 0; - virtual void Release() = 0; - virtual float GetFracture() = 0; // destroyed percentage so far - virtual void GetMemoryStatistics(ICrySizer* pSizer) const = 0; - // </interfuscator:shuffle> -}; - - -struct IGeomManager -{ - // <interfuscator:shuffle> - virtual ~IGeomManager(){} - virtual void InitGeoman() = 0; - virtual void ShutDownGeoman() = 0; - - // CreateMesh - depending on flags (see enum meshflags) can create either a mesh or a primitive that approximates - // approx_tolerance is the approximation tolerance in relative units - // pMats are per-face material ids (which can later be mapped via pMatMapping) - // pForeignIdx store any user data per face (internally indices might be sorted when building BV structure, pForegnIdx will reflect that) - virtual IGeometry* CreateMesh(strided_pointer<const Vec3> pVertices, strided_pointer<unsigned short> pIndices, char* pMats, int* pForeignIdx, int nTris, int flags, float approx_tolerance = 0.05f, int nMinTrisPerNode = 2, int nMaxTrisPerNode = 4, float favorAABB = 1.0f) = 0; - virtual IGeometry* CreateMesh(strided_pointer<const Vec3> pVertices, strided_pointer<unsigned short> pIndices, char* pMats, int* pForeignIdx, int nTris, int flags, float approx_tolerance, SMeshBVParams* pParams) = 0; // this version can take SVoxGridParams in pParams, if mesh_VoxelGrid is set - virtual IGeometry* CreatePrimitive(int type, const primitives::primitive* pprim) = 0; // used to create primitives explicitly - virtual void DestroyGeometry(IGeometry* pGeom) = 0; // just calls Release() on pGeom - - // RegisterGeometry: creates a phys_geometry structure for IGeometry, computes mass properties - // phys_geometries are managed in pools internally; the new structure has nRefCount 1 - // defSurfaceIdx will be used (until overwritten in entity part) if the geometry doesn't have per-face materials - virtual phys_geometry* RegisterGeometry(IGeometry* pGeom, int defSurfaceIdx = 0, int* pMatMapping = 0, int nMats = 0) = 0; - virtual int AddRefGeometry(phys_geometry* pgeom) = 0; - virtual int UnregisterGeometry(phys_geometry* pgeom) = 0; // decreases nRefCount, frees the pool slot if <=0 - virtual void SetGeomMatMapping(phys_geometry* pgeom, int* pMatMapping, int nMats) = 0; - - virtual void SaveGeometry(CMemStream& stm, IGeometry* pGeom) = 0; - virtual IGeometry* LoadGeometry(CMemStream& stm, strided_pointer<const Vec3> pVertices, strided_pointer<unsigned short> pIndices, char* pMats) = 0; - virtual void SavePhysGeometry(CMemStream& stm, phys_geometry* pgeom) = 0; - virtual phys_geometry* LoadPhysGeometry(CMemStream& stm, strided_pointer<const Vec3> pVertices, strided_pointer<unsigned short> pIndices, char* pIds) = 0; - virtual IGeometry* CloneGeometry(IGeometry* pGeom) = 0; - - virtual ITetrLattice* CreateTetrLattice(const Vec3* pt, int npt, const int* pTets, int nTets) = 0; - // RegisterCrack: cracks are used for ITertLattice-induced breaking to subtract a shape whenever a tetrahedral face breaks - // pVtx specify 3 control vertices; when applying, they are affinely stretched to match the broken face's corners - // idmat is breakability index - virtual int RegisterCrack(IGeometry* pGeom, Vec3* pVtx, int idmat) = 0; - virtual void UnregisterCrack(int id) = 0; - virtual void UnregisterAllCracks(void (* OnRemoveGeom)(IGeometry* pGeom) = 0) = 0; - // GetCrackGeom - creates a stretched crack based on the three corner vertices (pt[3]) - // pgwd receives it world transformation - virtual IGeometry* GetCrackGeom(const Vec3* pt, int idmat, geom_world_data* pgwd) = 0; - - // GenerateBreakebleGrid - creates a perturbed regular grid of points - // ptsrc's bbox is split into a nCells grid (with an additional border) - // vertices are randomly perturbed up to 0.4 cell size (seed can bootstrap the randomizer) - // ptsrc is "painted" into the grid, snapping the closest grid vertices to ptsrc (but no new ones are created at this stage) - // bStatic is ignored currently - virtual IBreakableGrid2d* GenerateBreakableGrid(vector2df* ptsrc, int npt, const vector2di& nCells, int bStatic = 1, int seed = -1) = 0; - - virtual void ReleaseGeomsImmediately(bool bReleaseImmediately) = 0; - // </interfuscator:shuffle> -}; - - -///////////////////////////////////////////////////////////////////////////////////// -////////////////////////////// IPhysUtils Interface ///////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////// - -typedef void* (* qhullmalloc)(size_t); - -struct IPhysUtils -{ - // <interfuscator:shuffle> - virtual ~IPhysUtils(){} - // CoverPolygonWithCircles - attempts to fits circles to roughly cover a polygon (can used to generate round spalshes over an area) - // bConsecutive is false, uses convex hull of the points - // center is a pre-calculated geometrical center of pt's - // outputs data into centers and radii arrays, which use global buffers; returns the number of circles - virtual int CoverPolygonWithCircles(strided_pointer<vector2df> pt, int npt, bool bConsecutive, const vector2df& center, vector2df*& centers, float*& radii, float minCircleRadius) = 0; - virtual int qhull(strided_pointer<Vec3> pts, int npts, index_t*& pTris, qhullmalloc qmalloc = 0) = 0; - virtual void DeletePointer(void* pdata) = 0; // should be used to free data allocated in physics - virtual int TriangulatePoly(vector2df* pVtx, int nVtx, int* pTris, int szTriBuf) = 0; - // </interfuscator:shuffle> -}; - -///////////////////////////////////////////////////////////////////////////////////// -//////////////////////////// IPhysicalEntity Interface ////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////// - -enum snapshot_flags -{ - ssf_compensate_time_diff = 1, ssf_checksum_only = 2, ssf_no_update = 4 -}; - -struct IPhysicalEntity -{ - // <interfuscator:shuffle> - virtual ~IPhysicalEntity(){} - virtual pe_type GetType() const = 0; // returns pe_type - - virtual int AddRef() = 0; - virtual int Release() = 0; - - // SetParams - changes parameters; can be queued and executed later if the physics is busy (unless bThreadSafe is flagged) - // returns !0 if successful - virtual int SetParams(const pe_params* params, int bThreadSafe = 0) = 0; - virtual int GetParams(pe_params* params) const = 0; // uses the same structures as SetParams; returns !0 if successful - virtual int GetStatus(pe_status* status) const = 0; // generally returns >0 if successful, but some pe_status'es have special meaning - virtual int Action(const pe_action*, int bThreadSafe = 0) = 0; // like SetParams, can get queued - - // AddGeometry - add a new entity part, containing pgeom; request can get queued - // params can be specialized depending on the entity type - // id is a requested geometry id (expected to be unique), if -1 - assign automatically - // returns geometry id (0..some number), -1 means error - virtual int AddGeometry(phys_geometry* pgeom, pe_geomparams* params, int id = -1, int bThreadSafe = 0) = 0; - virtual void RemoveGeometry(int id, int bThreadSafe = 0) = 0; // returns !0 if successful; can get queued - - virtual PhysicsForeignData GetForeignData(int itype = 0) const = 0; // returns entity's pForeignData if itype matches iForeignData, 0 otherwise - virtual int GetiForeignData() const = 0; // returns entity's iForegnData - - virtual int GetStateSnapshot(class CStream& stm, float time_back = 0, int flags = 0) = 0; // obsolete, was used in Far Cry - virtual int GetStateSnapshot(TSerialize ser, float time_back = 0, int flags = 0) = 0; - virtual int SetStateFromSnapshot(class CStream& stm, int flags = 0) = 0; // obsolete - virtual int PostSetStateFromSnapshot() = 0; // obsolete - virtual unsigned int GetStateChecksum() = 0; // obsolete - virtual void SetNetworkAuthority(int authoritive = -1, int paused = -1) = 0; // -1 dont change, 0 - set to false, 1 - set to true - - virtual int SetStateFromSnapshot(TSerialize ser, int flags = 0) = 0; - virtual int SetStateFromTypedSnapshot(TSerialize ser, int type, int flags = 0) = 0; - virtual int GetStateSnapshotTxt(char* txtbuf, int szbuf, float time_back = 0) = 0; // packs state into ASCII text - virtual void SetStateFromSnapshotTxt(const char* txtbuf, int szbuf) = 0; - - // DoStep: evolves entity in time. Normally this is called from PhysicalWorld::TimeStep - virtual int DoStep(float time_interval) = 0; - virtual int DoStep(float time_interval, int iCaller) = 0; - virtual void StartStep(float time_interval) = 0; // must be called before DoStep - virtual void StepBack(float time_interval) = 0; - - virtual void GetMemoryStatistics(ICrySizer* pSizer) const = 0; - // </interfuscator:shuffle> -}; - - -///////////////////////////////////////////////////////////////////////////////////// -//////////////////////////// IPhysicsEventClient Interface ////////////////////////// -///////////////////////////////////////////////////////////////////////////////////// - -struct IPhysicsEventClient // obsolete, replaced with event system (EventPhys...) -{ // <interfuscator:shuffle> - virtual ~IPhysicsEventClient(){} - virtual void OnBBoxOverlap(IPhysicalEntity* pEntity, PhysicsForeignData pForeignData, int iForeignData, IPhysicalEntity* pCollider, void* pColliderForeignData, int iColliderForeignData) = 0; - virtual void OnStateChange(IPhysicalEntity* pEntity, PhysicsForeignData pForeignData, int iForeignData, int iOldSimClass, int iNewSimClass) = 0; - virtual void OnCollision(IPhysicalEntity* pEntity, PhysicsForeignData pForeignData, int iForeignData, coll_history_item* pCollision) = 0; - virtual int OnImpulse(IPhysicalEntity* pEntity, PhysicsForeignData pForeignData, int iForeignData, pe_action_impulse* impulse) = 0; - virtual void OnPostStep(IPhysicalEntity* pEntity, PhysicsForeignData pForeignData, int iForeignData, float dt) = 0; - // </interfuscator:shuffle> -}; - -///////////////////////////////////////////////////////////////////////////////////// -///////////////////////////// IPhysicalWorld Interface ////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////// - -enum draw_helper_flags -{ - pe_helper_collisions = 1, pe_helper_geometry = 2, pe_helper_bbox = 4, pe_helper_lattice = 8 -}; -enum surface_flags -{ - sf_pierceable_mask = 0x0F, sf_max_pierceable = 0x0F, sf_important = 0x200, sf_manually_breakable = 0x400, sf_matbreakable_bit = 16 -}; -#define sf_pierceability(i) (i) -#define sf_matbreakable(i) (((i) + 1) << sf_matbreakable_bit) -enum rwi_flags // see RayWorldIntersection -{ - rwi_ignore_terrain_holes = 0x20, rwi_ignore_noncolliding = 0x40, rwi_ignore_back_faces = 0x80, rwi_ignore_solid_back_faces = 0x100, - rwi_pierceability_mask = 0x0F, rwi_pierceability0 = 0, rwi_stop_at_pierceable = 0x0F, - rwi_separate_important_hits = sf_important, // among pierceble hits, materials with sf_important will have priority - rwi_colltype_bit = 16, // used to manually specify collision geometry types (default is geom_colltype_ray) - rwi_colltype_any = 0x400, // if several colltype flag are specified, switches between requiring all or any of them in a geometry - rwi_queue = 0x800, // queues the RWI request, when done it'll generate EventPhysRWIResult - rwi_force_pierceable_noncoll = 0x1000, // non-colliding geometries will be treated as pierceable regardless of the actual material - rwi_update_last_hit = 0x4000, // update phitLast with the current hit results (should be set if the last hit should be reused for a "warm" start) - rwi_any_hit = 0x8000 // returns the first found hit for meshes, not necessarily the closets -}; -#define rwi_pierceability(pty) (pty) -#define rwi_colltype_all(colltypes) ((colltypes) << rwi_colltype_bit) -#define rwi_colltype_any(colltypes) ((colltypes) << rwi_colltype_bit | rwi_colltype_any) -enum entity_query_flags // see GetEntitiesInBox and RayWorldIntersection -{ - ent_static = 1, ent_sleeping_rigid = 2, ent_rigid = 4, ent_living = 8, ent_independent = 16, ent_deleted = 128, ent_terrain = 0x100, - ent_all = ent_static | ent_sleeping_rigid | ent_rigid | ent_living | ent_independent | ent_terrain, - ent_flagged_only = pef_update, ent_skip_flagged = pef_update * 2, // "flagged" meas has pef_update set - ent_areas = 32, ent_triggers = 64, - ent_ignore_noncolliding = 0x10000, - ent_sort_by_mass = 0x20000, // sort by mass in ascending order - ent_allocate_list = 0x40000, // if not set, the function will return an internal pointer - ent_addref_results = 0x100000, // will call AddRef on each entity in the list (expecting the caller call Release) - ent_water = 0x200, // can only be used in RayWorldIntersection - ent_no_ondemand_activation = 0x80000, // can only be used in RayWorldIntersection - ent_delayed_deformations = 0x80000 // queues procedural breakage requests; can only be used in SimulateExplosion -}; -enum phys_locks -{ - PLOCK_WORLD_STEP = 1, PLOCK_CALLER0, PLOCK_CALLER1, PLOCK_QUEUE, PLOCK_AREAS -}; - -struct phys_profile_info -{ - IPhysicalEntity* pEntity; - int nTicks, nCalls; - int nTicksLast, nCallsLast; - int nTicksAvg; - float nCallsAvg; - int nTicksPeak, nCallsPeak, peakAge; - int nTicksStep; - int id; - const char* pName; -}; - -struct phys_job_info -{ - int jobType; - int nInvocations; - int nFallbacks; - int64 nTicks, nLatency, nLatencyAbs; - int64 nTicksPeak, nLatencyPeak, nLatencyAbsPeak, peakAge; - const char* pName; -}; - -struct SolverSettings -{ - int nMaxStackSizeMC; // def 8 - float maxMassRatioMC; // def 50 - int nMaxMCiters; // def 1400 - int nMinMCiters; // def 4 - int nMaxMCitersHopeless; // def 400 - float accuracyMC; // def 0.005 - float accuracyLCPCG; // def 0.005 - int nMaxContacts; // def 150 - int nMaxPlaneContacts; // def 7 - int nMaxPlaneContactsDistress; // def 4 - int nMaxLCPCGsubiters; // def 120 - int nMaxLCPCGsubitersFinal; // def 250 - int nMaxLCPCGmicroiters; - int nMaxLCPCGmicroitersFinal; - int nMaxLCPCGiters; // def 5 - float minLCPCGimprovement; // def 0.1 - int nMaxLCPCGFruitlessIters; // def 4 - float accuracyLCPCGnoimprovement; // def 0.05 - float minSeparationSpeed; // def 0.02 - float maxvCG; - float maxwCG; - float maxvUnproj; - int bCGUnprojVel; - float maxMCMassRatio; - float maxMCVel; - int maxLCPCGContacts; -}; - -enum entity_out_of_bounds_flags -{ - raycast_out_of_bounds = 1, // Affects ray casts. NB, ray casting out of bounds entities can cause performance issues - get_entities_out_of_bounds = 2, // Affects GetEntitiesAround. -}; - -struct PhysicsVars - : SolverSettings -{ - int bFlyMode; - int iCollisionMode; - int bSingleStepMode; - int bDoStep; - float fixedTimestep; - float timeGranularity; - float maxWorldStep; - int iDrawHelpers; - int iOutOfBounds; - float maxContactGap; - float maxContactGapPlayer; - float minBounceSpeed; - int bProhibitUnprojection; - int bUseDistanceContacts; - float unprojVelScale; - float maxUnprojVel; - float maxUnprojVelRope; - int bEnforceContacts; - int nMaxSubsteps; - int nMaxSurfaces; - Vec3 gravity; - int nGroupDamping; - float groupDamping; - int nMaxSubstepsLargeGroup; - int nBodiesLargeGroup; - int bBreakOnValidation; - int bLogActiveObjects; - int bProfileEntities; - int bProfileFunx; - int bProfileGroups; - int nGEBMaxCells; - int nMaxEntityCells; - int nMaxAreaCells; - float maxVel; - float maxVelPlayers; - float maxVelBones; - float maxContactGapSimple; - float penaltyScale; - int bSkipRedundantColldet; - int bLimitSimpleSolverEnergy; - int nMaxEntityContacts; - int bLogLatticeTension; - int nMaxLatticeIters; - int bLogStructureChanges; - float tickBreakable; - float approxCapsLen; - int nMaxApproxCaps; - int bPlayersCanBreak; - float lastTimeStep; - int bMultithreaded; - float breakImpulseScale; - float rtimeGranularity; - float massLimitDebris; - int flagsColliderDebris; - int flagsANDDebris; - int maxRopeColliderSize; - int maxSplashesPerObj; - float splashDist0, minSplashForce0, minSplashVel0; - float splashDist1, minSplashForce1, minSplashVel1; - int bDebugExplosions; - float jointGravityStep; - float jointDmgAccum; - float jointDmgAccumThresh; - float timeScalePlayers; - float threadLag; - int numThreads; - int physCPU; - int physWorkerCPU; - Vec3 helperOffset; - int64 ticksPerSecond; - // net-synchronization related -#if USE_IMPROVED_RIGID_ENTITY_SYNCHRONISATION - float netInterpTime; - float netExtrapMaxTime; - int netSequenceFrequency; - int netDebugDraw; -#else - float netMinSnapDist; - float netVelSnapMul; - float netMinSnapDot; - float netAngSnapMul; - float netSmoothTime; -#endif - - int bEntGridUseOBB; - int nStartupOverloadChecks; - float breakageMinAxisInertia; // For procedural breaking, each axis must have a minium inertia compared to the axis with the largest inertia (0.01-1.00) - - int bForceSyncPhysics; -}; - -struct ray_hit -{ - float dist; - IPhysicalEntity* pCollider; - int ipart; - int partid; - short surface_idx; - short idmatOrg; // original material index, not mapped with material mapping - int foreignIdx; - int iNode; // BV tree node that had the intersection; can be used for "warm start" next time - Vec3 pt; - Vec3 n; // surface normal - int bTerrain; // global terrain hit - int iPrim; // hit triangle index - ray_hit* next; // reserved for internal use, do not change -}; - -struct ray_hit_cached // used in conjunction with rwi_reuse_last_hit -{ - ray_hit_cached() { pCollider = 0; ipart = 0; } - ray_hit_cached(const ray_hit& hit) { pCollider = hit.pCollider; ipart = hit.ipart; iNode = hit.iNode; } - ray_hit_cached& operator=(const ray_hit& hit) { pCollider = hit.pCollider; ipart = hit.ipart; iNode = hit.iNode; return *this; } - - IPhysicalEntity* pCollider; - int ipart; - int iNode; -}; - -#ifndef PWI_NAME_TAG -#define PWI_NAME_TAG "PrimitiveWorldIntersection" -#endif -#ifndef RWI_NAME_TAG -#define RWI_NAME_TAG "RayWorldIntersection" -#endif - -struct pe_explosion // see SimulateExplosion -{ - pe_explosion() { nOccRes = 0; nGrow = 0; rminOcc = 0.1f; holeSize = 0; explDir.Set(0, 0, 1); iholeType = 0; forceDeformEntities = false; } - Vec3 epicenter; // epicenter for the occlusion computation - Vec3 epicenterImp; // epicenter for impulse computation - // the impulse a surface fragment with area dS and normal n gets is: dS*k*n*max(0,n*dir_to_epicenter)/max(rmin, dist_to_epicenter)^2 - // k is selected in such way that at impulsivePressureAtR = k/r^2 - float rmin, rmax, r; - float impulsivePressureAtR; - int nOccRes; // resolution of the occlusion map (0 disables) - int nGrow; // grow occlusion projections by this amount of cells to allow explosion to reach around corners a bit - float rminOcc; // ignores geometry closer than this for occlusion computations - float holeSize; // explosion shape for iholeType will be scaled by this holeSize / shape's declared size - Vec3 explDir; // hit direction, for aligning the explosion boolean shape - int iholeType; // breakability index for the explosion (<0 disables) - bool forceDeformEntities; // force deformation even if breakImpulseScale is zero - // filled as results - IPhysicalEntity** pAffectedEnts; - float* pAffectedEntsExposure; // 0..1 exposure, computed from the occlusion map - int nAffectedEnts; -}; - -// Physics events can be logged or immediate. The former are posted to the event queue and the client handler is called -// during PumpLoggedEvents function. The latter are call client handlers immediately when they happen, which is likely -// to be inside the physics thread, so the handler must be thread-safe. -// In most cases, in order to generate events the entity must have the corresponding flag set -// Important Note: Please keep event ids contigous in respect to being stereo or mono events -struct EventPhys -{ - EventPhys* next; - int idval; -}; - -struct EventPhysStereo - : EventPhys // base for two-entity events, ids 0-2 -{ - IPhysicalEntity* pEntity[2]; - PhysicsForeignData pForeignData[2]; - int iForeignData[2]; -}; - -struct EventPhysMono - : EventPhys // base for one-entity events, ids 3-16 -{ - IPhysicalEntity* pEntity; - PhysicsForeignData pForeignData; - int iForeignData; -}; - -struct EventPhysBBoxOverlap - : EventPhysStereo // generated by triggers and parts with geom_log_interactions -{ - enum entype - { - id = 0, flagsCall = 0, flagsLog = 0 - }; - EventPhysBBoxOverlap() { idval = id; } -}; - -enum EventPhysCollisionState -{ - EPC_DEFERRED_INITIAL, EPC_DEFERRED_REQUEUE, EPC_DEFERRED_FINISHED -}; - -struct EventPhysCollision - : EventPhysStereo -{ - enum entype - { - id = 2, flagsCall = pef_monitor_collisions, flagsLog = pef_log_collisions - }; - EventPhysCollision() { idval = id; pEntContact = 0; iPrim[0] = iPrim[1] = -1; deferredState = EPC_DEFERRED_INITIAL; fDecalPlacementTestMaxSize = 1000.f; } - int idCollider; // in addition to pEntity[1] - Vec3 pt; // contact point in world coordinates - Vec3 n; // contact normal - Vec3 vloc[2]; // velocities at the contact point - float mass[2]; - int partid[2]; - short idmat[2]; - short iPrim[2]; - float penetration; // contact's penetration depth - float normImpulse; // impulse applied by the solver to resolve the collision - float radius; // some characteristic size of the contact area - void* pEntContact; // reserved for internal use - char deferredState; // EventPhysCollisionState - char deferredResult; // stores the result returned by the deferred event - float fDecalPlacementTestMaxSize; // maximum allowed size of decals caused by this collision -}; - -struct EventPhysStateChange - : EventPhysMono // triggered by simclass changes, even those caused by SetParams -{ - enum entype - { - id = 8, flagsCall = pef_monitor_state_changes, flagsLog = pef_log_state_changes - }; - EventPhysStateChange() { idval = id; } - int iSimClass[2]; - float timeIdle; // how long the entity stayed without external activation (such as impulses) - Vec3 BBoxOld[2]; - Vec3 BBoxNew[2]; -}; - -struct EventPhysEnvChange - : EventPhysMono // called when something around the entityy breaks -{ - enum entype - { - id = 3, flagsCall = pef_monitor_env_changes, flagsLog = pef_log_env_changes - }; - enum encode - { - EntStructureChange = 0 - }; - EventPhysEnvChange() { idval = id; } - int iCode; - IPhysicalEntity* pentSrc; // entity that broke - IPhysicalEntity* pentNew; // new entity that broke off the original one -}; - -struct EventPhysPostStep - : EventPhysMono // entity has just completed its step -{ - enum entype - { - id = 4, flagsCall = pef_monitor_poststep, flagsLog = pef_log_poststep - }; - EventPhysPostStep() { idval = id; } - float dt; - Vec3 pos; - quaternionf q; - int idStep; // world's internal step count -}; - -struct EventPhysUpdateMesh - : EventPhysMono // physics mesh changed -{ - enum entype - { - id = 5, flagsCall = 1, flagsLog = 2 - }; - enum reason - { - ReasonExplosion, ReasonFracture, ReasonRequest, ReasonDeform - }; - EventPhysUpdateMesh() { idval = id; idx = -1; pMesh = 0; } - int partid; - int bInvalid; - int iReason; // see enum reason - IGeometry* pMesh; // ->GetForeignData(DATA_MESHUPDATE) returns a list of bop_meshupdates - bop_meshupdate* pLastUpdate; // the last mesh update for at moment when the event was generated - Matrix34 mtxSkelToMesh; // skeleton's frame -> mesh's frame transform - IGeometry* pMeshSkel; // for deformable bodies - int idx; // used for event deferring by listeners -}; - -struct EventPhysCreateEntityPart - : EventPhysMono // a part broke off an existing entity -{ - enum entype - { - id = 6, flagsCall = 1, flagsLog = 2 - }; - enum reason - { - ReasonMeshSplit, ReasonJointsBroken - }; - EventPhysCreateEntityPart() { idval = id; idx = -1; } - IPhysicalEntity* pEntNew; // new physical entity (has type PE_RIGID) - int partidSrc; // original part id - int partidNew; // part id assigned to it in the new entity - int nTotParts; // total number of parts that broke off during this update (each will have its own event) - int bInvalid; // generated mesh was invalid (degenerate or flipped) - int iReason; - Vec3 breakImpulse; // impulse that initiated the breaking - Vec3 breakAngImpulse; - Vec3 v; // initial vel of ejected product - Vec3 w; // initial ang vel of ejected product - float breakSize; // if caused by an explosion, the explosion's rmin - float cutRadius; // if updated mesh was successfully approximated with capsules, this is their cross section at the point of breakage - Vec3 cutPtLoc[2]; // the cut's center in both entities' frames - Vec3 cutDirLoc[2]; // the cut area's normal - IGeometry* pMeshNew; // new mesh if was caused by boolean breaking, 0 if by joint breaking (i.e. no new mesh was created) - bop_meshupdate* pLastUpdate; // last meshupdate for the moment the event was reported - int idx; // used for event deferring by listeners -}; - -struct EventPhysRemoveEntityParts - : EventPhysMono -{ - enum entype - { - id = 7, flagsCall = 1, flagsLog = 2 - }; - EventPhysRemoveEntityParts() { idval = id; idOffs = 0; } - unsigned int partIds[4]; // remove parts with ids corresponding to the set bits in partIds[], +idOffs - int idOffs; - float massOrg; // entity's mass before the parts were removed -}; - -struct EventPhysRevealEntityPart - : EventPhysMono -{ - enum entype - { - id = 13, flagsCall = 1, flagsLog = 2 - }; - EventPhysRevealEntityPart() { idval = id; } - int partId; // id of a part that was hidden due to hierarchical breakability, but should be revealed now -}; - -struct EventPhysJointBroken - : EventPhysStereo -{ - enum entype - { - id = 1, flagsCall = 1, flagsLog = 2 - }; - EventPhysJointBroken() { idval = id; } - int idJoint; - int bJoint; // structural joint if 1, dynamics constraint if 0 - int partidEpicenter; // the "seed" part during the update - Vec3 pt; // joint's position in the entity frame - Vec3 n; // joint's z axis - int partid[2]; - int partmat[2]; // material id from the parts' first primitive - IPhysicalEntity* pNewEntity[2]; // only set for broken constraints -}; - -struct EventPhysRWIResult - : EventPhysMono -{ - enum entype - { - id = 9, flagsCall = 0, flagsLog = 0 - }; - EventPhysRWIResult() { idval = id; } - int (* OnEvent)(const EventPhysRWIResult*); - ray_hit* pHits; - int nHits, nMaxHits; - int bHitsFromPool; // 1 if hits reside in the internal physics hits pool -}; - -struct EventPhysPWIResult - : EventPhysMono -{ - enum entype - { - id = 10, flagsCall = 0, flagsLog = 0 - }; - EventPhysPWIResult() { idval = id; } - int (* OnEvent)(const EventPhysPWIResult*); - float dist; - Vec3 pt; - Vec3 n; - int idxMat; - int partId; -}; - -struct EventPhysArea - : EventPhysMono // for callback phys areas -{ - enum entype - { - id = 11, flagsCall = 0, flagsLog = 0 - }; - EventPhysArea() { idval = id; } - - Vec3 pt; // entity's center - Vec3 ptref; // for splines - closest point on spline to pt; for normal areas - area's world position - Vec3 dirref; // for splines, calculated force direction - pe_params_buoyancy pb; // can be filled by the caller - Vec3 gravity; // can be filled by the caller - IPhysicalEntity* pent; // the entity that entered the area and caused this event -}; - -struct EventPhysAreaChange - : EventPhysMono -{ - enum entype - { - id = 12, flagsCall = 0, flagsLog = 0 - }; - EventPhysAreaChange() { idval = id; pContainer = 0; } - - Vec3 boxAffected[2]; - quaternion q; - Vec3 pos; - float depth; - IPhysicalEntity* pContainer; - quaternion qContainer; - Vec3 posContainer; -}; - -struct EventPhysEntityDeleted - : EventPhysMono -{ - enum entype - { - id = 14, flagsCall = 0, flagsLog = 0 - }; - EventPhysEntityDeleted() { idval = id; } - int mode; -}; - -struct EventPhysPostPump - : EventPhys -{ - enum entype - { - id = 15, flagsCall = 0, flagsLog = 0 - }; - EventPhysPostPump() { idval = id; } -}; - -const int EVENT_TYPES_NUM = 16; - -// Physical entity iterator interface. This interface is used to traverse trough all the physical entities in an physical world. In a way, -// this iterator works a lot like a stl iterator. -struct IPhysicalEntityIt -{ - // <interfuscator:shuffle> - virtual ~IPhysicalEntityIt(){} - virtual void AddRef() = 0; - virtual void Release() = 0; // Deletes this iterator and frees any memory it might have allocated. - - virtual bool IsEnd() = 0; // Check whether current iterator position is the end position. - virtual IPhysicalEntity* Next() = 0; // returns the entity that the iterator points to before it goes to the next - virtual IPhysicalEntity* This() = 0; // returns the entity that the iterator points to - virtual void MoveFirst() = 0; // positions the iterator at the begining of the entity list - // </interfuscator:shuffle> -}; - - - -#endif // CRYINCLUDE_CRYCOMMON_PHYSINTERFACE_H diff --git a/Code/CryEngine/CryCommon/platform.h b/Code/CryEngine/CryCommon/platform.h deleted file mode 100644 index c0e6a50a49..0000000000 --- a/Code/CryEngine/CryCommon/platform.h +++ /dev/null @@ -1,816 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Platform dependend stuff. -// Include this file instead of windows h - -#pragma once - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define PLATFORM_H_SECTION_1 1 -#define PLATFORM_H_SECTION_2 2 -#define PLATFORM_H_SECTION_3 3 -#define PLATFORM_H_SECTION_4 4 -#define PLATFORM_H_SECTION_5 5 -#define PLATFORM_H_SECTION_6 6 -#define PLATFORM_H_SECTION_7 7 -#define PLATFORM_H_SECTION_8 8 -#define PLATFORM_H_SECTION_9 9 -#define PLATFORM_H_SECTION_10 10 -#define PLATFORM_H_SECTION_11 11 -#define PLATFORM_H_SECTION_12 12 -#define PLATFORM_H_SECTION_13 13 -#define PLATFORM_H_SECTION_14 14 -#define PLATFORM_H_SECTION_15 15 -#endif - -// certain C++ features are not available in some compiler versions -// turn them off here: -// #define _ALLOW_KEYWORD_MACROS -// #define _DISALLOW_INITIALIZER_LISTS -// #define _DISALLOW_ENUM_CLASS - -#if defined(_MSC_VER) - #define _ALLOW_KEYWORD_MACROS - - #define alignof _alignof - #if !defined(_HAS_EXCEPTIONS) - #define _HAS_EXCEPTIONS 0 - #endif -#elif defined(__GNUC__) - #define alignof __alignof__ -#endif - -// Alignment|InitializerList support. -#define _ALLOW_INITIALIZER_LISTS - -#if (defined(LINUX) && !defined(ANDROID)) || defined(APPLE) -#define _FILE_OFFSET_BITS 64 // define large file support > 2GB -#endif - -#include <AzCore/PlatformIncl.h> - -#include <cstring> - -#if defined(_MSC_VER) // We want the class name to be included, but __FUNCTION__ doesn't contain that on GCC/clang - #define __FUNC__ __FUNCTION__ -#else - #define __FUNC__ __PRETTY_FUNCTION__ -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_1 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(_DEBUG) && !defined(LINUX) && !defined(APPLE) - #include <crtdbg.h> -#endif - -#define RESTRICT_POINTER __restrict - -// we have to use it because of VS doesn't support restrict reference variables -#if defined(APPLE) || defined(LINUX) - #if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1) - #define GCC411_OR_LATER - #endif - #define RESTRICT_REFERENCE __restrict -#else - #define RESTRICT_REFERENCE -#endif - - -#ifndef CHECK_REFERENCE_COUNTS //define that in your StdAfx.h to override per-project -# define CHECK_REFERENCE_COUNTS 0 //default value -#endif - -#if CHECK_REFERENCE_COUNTS -# define CHECK_REFCOUNT_CRASH(x) { if (!(x)) {*((int*)0) = 0; } \ -} -#else -# define CHECK_REFCOUNT_CRASH(x) -#endif - -#ifndef GARBAGE_MEMORY_ON_FREE //define that in your StdAfx.h to override per-project -# define GARBAGE_MEMORY_ON_FREE 0 //default value -#endif - -#if GARBAGE_MEMORY_ON_FREE -# ifndef GARBAGE_MEMORY_RANDOM //define that in your StdAfx.h to override per-project -# define GARBAGE_MEMORY_RANDOM 1 //0 to change it to progressive pattern -# endif -#endif - -////////////////////////////////////////////////////////////////////////// -// Available predefined compiler macros for Visual C++. -// _MSC_VER // Indicates MS Visual C compiler version -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_2 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -// _WIN32, _WIN64 // Indicates target OS -#endif -// _M_IX86, _M_PPC // Indicates target processor -// _DEBUG // Building in Debug mode -// _DLL // Linking with DLL runtime libs -// _MT // Linking with multi-threaded runtime libs -////////////////////////////////////////////////////////////////////////// - -// -// Translate some predefined macros. -// - -// NDEBUG disables std asserts, etc. -// Define it automatically if not compiling with Debug libs, or with ADEBUG flag. -#if !defined(_DEBUG) && !defined(ADEBUG) && !defined(NDEBUG) - #define NDEBUG -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_3 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(MOBILE) - #define CONSOLE -#endif - -//render thread settings, as this is accessed inside 3dengine and renderer and needs to be compile time defined, we need to do it here -//enable this macro to strip out the overhead for render thread -// #define STRIP_RENDER_THREAD -#ifdef STRIP_RENDER_THREAD - #define RT_COMMAND_BUF_COUNT 1 -#else -//can be enhanced to triple buffering, FlushFrame needs to be adjusted and RenderObj would become 132 bytes - #define RT_COMMAND_BUF_COUNT 2 -#endif - - -// We use WIN macros without _. -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_4 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -#if defined(_WIN32) && !defined(LINUX32) && !defined(LINUX64) && !defined(APPLE) && !defined(WIN32) - #define WIN32 -#endif -#if defined(_WIN64) && !defined(WIN64) - #define WIN64 -#endif -#endif - -// In Win32 Release we use static linkage -#ifdef WIN32 - #if !defined(_RELEASE) || defined(RESOURCE_COMPILER) || defined(EDITOR) || defined(_FORCEDLL) -// All windows targets not in Release built as DLLs. - #ifndef _USRDLL - #define _USRDLL - #endif - #endif - -#endif //WIN32 - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_5 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(LINUX) || defined(APPLE) - #define __STDC_FORMAT_MACROS - #include <inttypes.h> - #if defined(APPLE) || defined(LINUX64) - // int64 is not the same type as the operating system's int64_t - #undef PRIX64 - #undef PRIx64 - #undef PRId64 - #undef PRIu64 - #define PRIX64 "llX" - #define PRIx64 "llx" - #define PRId64 "lld" - #define PRIu64 "llu" - #endif - #define PLATFORM_I64(x) x##ll -#else - #include <inttypes.h> - #define PLATFORM_I64(x) x##i64 -#endif - -#if !defined(PRISIZE_T) -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_6 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED - #elif defined(WIN64) - #define PRISIZE_T "I64u" //size_t defined as unsigned __int64 - #elif defined(WIN32) || defined(LINUX32) - #define PRISIZE_T "u" - #elif defined(MAC) || defined(LINUX64) || defined(IOS) - #define PRISIZE_T "lu" - #else - #error "Please defined PRISIZE_T for this platform" - #endif -#endif -#if !defined(PRI_THREADID) -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_7 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED - #elif defined(MAC) || defined(IOS) && defined(__LP64__) && defined(__LP64__) - #define PRI_THREADID "lld" - #elif defined(LINUX64) || defined(ANDROID) - #define PRI_THREADID "ld" - #else - #define PRI_THREADID "d" - #endif -#endif -#include "ProjectDefines.h" // to get some defines available in every CryEngine project - -// Function attribute for printf/scanf-style parameters. -// This enables extended argument checking by GCC. -// -// Usage: -// Put this after the function or method declaration (not the definition!), -// between the final closing parenthesis and the semicolon. -// The first parameter indicates the 1-based index of the format string -// parameter, the second parameter indicates the 1-based index of the first -// variable parameter. Example: -// void foobar(int a, const char *fmt, ...) PRINTF_PARAMS(2, 3); -// -// For va_list based printf style functions, specfy 0 as the second parameter. -// Example: -// void foobarv(int a, const char *fmt, va_list ap) PRINTF_PARAMS(2, 0); -// -// Note that 'this' is counted as a method argument. For non-static methods, -// add 1 to the indices. -// -// Use PRINTF_EMPTY_STRING when you want to format an empty string using -// a function defined with PRINTF_PARAMS to avoid zero length format string -// warnings when these checks are enabled. - -#if defined(__GNUC__) && !defined(_RELEASE) - #define PRINTF_PARAMS(...) __attribute__ ((format (printf, __VA_ARGS__))) - #define SCANF_PARAMS(...) __attribute__ ((format (scanf, __VA_ARGS__))) - #define PRINTF_EMPTY_FORMAT "%s", "" -#else - #define PRINTF_PARAMS(...) - #define SCANF_PARAMS(...) - #define PRINTF_EMPTY_FORMAT "" -#endif - -#if defined(IOS) -#define USE_PTHREAD_TLS -#endif - -// Storage class modifier for thread local storage. -// THEADLOCAL should NOT be defined to empty because that creates some -// really hard to find issues. -#if !defined(USE_PTHREAD_TLS) -# define THREADLOCAL AZ_TRAIT_COMPILER_THREAD_LOCAL -#endif //!defined(USE_PTHREAD_TLS) - - - -////////////////////////////////////////////////////////////////////////// -// define Read Write Barrier macro needed for lockless programming -////////////////////////////////////////////////////////////////////////// -#if defined(__arm__) -/** - * (ARMv7) Full memory barriar. - * - * None of GCC 4.6/4.8 or clang 3.3/3.4 have a builtin intrinsic for ARM's ldrex/strex or dmb - * instructions. This is a placeholder until supplied by the toolchain. - */ -inline void __dmb() -{ - // The linux kernel uses "dmb ish" to only sync with local monitor (arch/arm/include/asm/barrier.h): - //#define dmb(option) __asm__ __volatile__ ("dmb " #option : : : "memory") - //#define smp_mb() dmb(ish) - __asm__ __volatile__ ("dmb ish" : : : "memory"); -} - -#define READ_WRITE_BARRIER {__dmb(); } -#else - #define READ_WRITE_BARRIER -#endif -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// define macro to prevent memory reoderings of reads/and writes -//TODO implement for all GCC platforms, else there are potential crashes with strict aliasing - #define MEMORY_RW_REORDERING_BARRIER do { /*not implemented*/} while (0) - -//default stack size for threads, currently only used on pthread platforms -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_8 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(LINUX) || defined(APPLE) - #if !defined(_DEBUG) - #define SIMPLE_THREAD_STACK_SIZE_KB (256) - #else - #define SIMPLE_THREAD_STACK_SIZE_KB (256 * 4) - #endif -#else - #define SIMPLE_THREAD_STACK_SIZE_KB (32) -#endif - -#include <AzCore/PlatformDef.h> - -#if defined(AZ_MONOLITHIC_BUILD) - #define DLL_EXPORT - #define DLL_IMPORT -#else // AZ_MONOLITHIC_BUILD - #define DLL_EXPORT AZ_DLL_EXPORT - #define DLL_IMPORT AZ_DLL_IMPORT -#endif // AZ_MONOLITHIC_BUILD - - -////////////////////////////////////////////////////////////////////////// -// Define BIT macro for use in enums and bit masks. -#define BIT(x) (1 << (x)) -#define BIT64(x) (1ll << (x)) -#define TYPED_BIT(type, x) (type(1) << (x)) -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// Help message, all help text in code must be wrapped in this define. -// Only include these in non RELEASE builds -#if !defined(_RELEASE) - #define _HELP(x) x -#else - #define _HELP(x) "" -#endif -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// Globally Used Defines. -////////////////////////////////////////////////////////////////////////// -// CPU Types: _CPU_X86,_CPU_AMD64,_CPU_G5 -// Platform: WIN23,WIN64,LINUX32,LINUX64,MAC -// CPU supported functionality: _CPU_SSE -////////////////////////////////////////////////////////////////////////// - - - #if defined(_MSC_VER) - #define PREFAST_SUPPRESS_WARNING(W) __pragma(warning(suppress: W)) - #else - #define PREFAST_SUPPRESS_WARNING(W) - #endif - -#ifdef _PREFAST_ -# define PREFAST_ASSUME(cond) __analysis_assume(cond) -#else -# define PREFAST_ASSUME(cond) -#endif - - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_9 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - #if defined(WIN32) && !defined(WIN64) - #include "Win32specific.h" - #endif - - #if defined(WIN64) - #include "Win64specific.h" - #endif -#endif - -#if defined(LINUX64) && !defined(ANDROID) -#include "Linux64Specific.h" -#endif - -#if defined(LINUX32) && !defined(ANDROID) -#include "Linux32Specific.h" -#endif - -#if defined(ANDROID) -#include "AndroidSpecific.h" -#endif - - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_10 - #include AZ_RESTRICTED_FILE(platform_h) -#endif - -#if defined(MAC) -#include "MacSpecific.h" -#endif - -#if defined(IOS) -#include "iOSSpecific.h" -#endif - - -#if !defined(TARGET_DEFAULT_ALIGN) -# error "No default alignment specified for target architecture" -#endif - -// Indicates potentially dangerous cast on 64bit machines -typedef UINT_PTR TRUNCATE_PTR; -typedef UINT_PTR EXPAND_PTR; - -// Use static branch prediction to improve the generated assembly when possible. -// This feature has an indirect effect on runtime performance, as it ensures assembly code -// which is more likely needed (the programmer has to decide this), is directly after the if -// -// For reference, as far as i am aware, all compilers use the following heuristic for static branch prediction -// if branches are always taken -// forward jumps are not taken -// backwards jumps are taken (eg. jumping back to the beginning of a loop) -#if defined(__clang__) || defined(__GNUC__) -# define IF(condition, hint) if (__builtin_expect(!!(condition), hint)) -# define WHILE(condition, hint) while (__builtin_expect(!!(condition), hint)) -# define IF_UNLIKELY(condition) if (__builtin_expect(!!(condition), 0)) -# define IF_LIKELY(condition) if (__builtin_expect(!!(condition), 1)) -#else -// Fallback for compilers which don't support static branch prediction (like MSVC) -# define IF(condition, hint) if ((condition)) -# define WHILE(condition, hint) while ((condition)) -# define IF_UNLIKELY(condition) if ((condition)) -# define IF_LIKELY(condition) if ((condition)) -#endif // !defined(__clang__) || defined(__GNUC__) - -#include <stdio.h> - - -////////////////////////////////////////////////////////////////////////// -// Provide special cast function which mirrors C++ style casts to support aliasing correct type punning casts in gcc with strict-aliasing enabled -template<typename DestinationType, typename SourceType> -ILINE DestinationType alias_cast(SourceType pPtr) -{ - union - { - SourceType pSrc; - DestinationType pDst; - } conv_union; - conv_union.pSrc = pPtr; - return conv_union.pDst; -} - -#include "CryLegacyAllocator.h" - -////////////////////////////////////////////////////////////////////////// -#ifndef DEPRECATED -#define DEPRECATED -#endif - -////////////////////////////////////////////////////////////////////////// -// compile time error stuff -////////////////////////////////////////////////////////////////////////// -#undef STATIC_CHECK -#define STATIC_CHECK(expr, msg) static_assert(expr, #msg) - -// Assert dialog box macros -#include "CryAssert.h" - -// Replace standard assert calls by our custom one -// Works only ifdef USE_CRY_ASSERT && _DEBUG && WIN32 -#ifndef assert -#define assert CRY_ASSERT -#endif - -#include "CompileTimeAssert.h" -////////////////////////////////////////////////////////////////////////// -// Platform dependent functions that emulate Win32 API. -// Mostly used only for debugging! -////////////////////////////////////////////////////////////////////////// -void CryDebugBreak(); -void CrySleep(unsigned int dwMilliseconds); -void CryLowLatencySleep(unsigned int dwMilliseconds); -int CryMessageBox(const char* lpText, const char* lpCaption, unsigned int uType); -short CryGetAsyncKeyState(int vKey); -unsigned int CryGetFileAttributes(const char* lpFileName); - -inline void CryHeapCheck() -{ -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_11 - #include AZ_RESTRICTED_FILE(platform_h) -#elif !defined(LINUX) && !defined(APPLE) // todo: this might be readded with later xdks? -#if !defined(NDEBUG) - int Result = -#endif - _heapchk(); - assert(Result != _HEAPBADBEGIN); - assert(Result != _HEAPBADNODE); - assert(Result != _HEAPBADPTR); - assert(Result != _HEAPEMPTY); - assert(Result == _HEAPOK); -#endif -} - -//--------------------------------------------------------------------------- -// Useful function to clean the structure. -template <class T> -inline void ZeroStruct(T& t) -{ memset(static_cast<void*>(&t), 0, sizeof(t)); } - -// Useful functions to init and destroy objects. -template<class T> -inline void Construct(T& t) -{ new(&t)T(); } - -template<class T, class U> -inline void Construct(T& t, U const& u) -{ new(&t)T(u); } - -template<class T> -inline void Destruct(T& t) -{ t.~T(); } - -// Cast one type to another, asserting there is no conversion loss. -// Usage: DestType dest = check_cast<DestType>(src); -template<class D, class S> -inline D check_cast(S const& s) -{ - D d = D(s); - assert(S(d) == s); - return d; -} - -// Convert one type to another, asserting there is no conversion loss. -// Usage: DestType dest; check_convert(dest, src); -template<class D, class S> -inline D& check_convert(D& d, S const& s) -{ - d = D(s); - assert(S(d) == s); - return d; -} - -// Convert one type to another, asserting there is no conversion loss. -// Usage: DestType dest; check_convert(dest) = src; -template<class D> -struct CheckConvert -{ - CheckConvert(D& d) - : dest(&d) {} - - template<class S> - D& operator=(S const& s) - { - return check_convert(*dest, s); - } - -protected: - D* dest; -}; - -template<class D> -inline CheckConvert<D> check_convert(D& d) -{ - return d; -} - -//--------------------------------------------------------------------------- -// Use NoCopy as a base class to easily prevent copy init & assign for any class. -struct NoCopy -{ - NoCopy() {} -private: - NoCopy(const NoCopy&); - NoCopy& operator =(const NoCopy&); -}; - -//--------------------------------------------------------------------------- -// ZeroInit: base class to zero the memory of the derived class before initialization, so local objects initialize the same as static. -// Usage: -// class MyClass: ZeroInit<MyClass> {...} -// class MyChild: public MyClass, ZeroInit<MyChild> {...} // ZeroInit must be the last base class - -template<class TDerived> -struct ZeroInit -{ -#if defined(__clang__) || defined(__GNUC__) - bool __dummy; // Dummy var to create non-zero size, ensuring proper placement in TDerived -#endif - - ZeroInit(bool bZero = true) - { - // Optional bool arg to selectively disable zeroing. - if (bZero) - { - // Infer offset of this base class by static casting to derived class. - // Zero only the additional memory of the derived class. - TDerived* struct_end = static_cast<TDerived*>(this) + 1; - size_t memory_size = (char*)struct_end - (char*)this; - memset(this, 0, memory_size); - } - } -}; - -//--------------------------------------------------------------------------- -// Quick const-manipulation macros - -// Declare a const and variable version of a function simultaneously. -#define CONST_VAR_FUNCTION(head, body) \ - inline head body \ - inline const head const body - -template<class T> -inline -T& non_const(const T& t) -{ return const_cast<T&>(t); } - -#define using_type(super, type) \ - typedef typename super::type type; - -typedef unsigned char uchar; -typedef unsigned int uint; -typedef const char* cstr; - -//--------------------------------------------------------------------------- -// Align function works on integer or pointer values. -// Only support power-of-two alignment. -template<typename T> -inline -T Align(T nData, size_t nAlign) -{ - assert((nAlign & (nAlign - 1)) == 0); - size_t size = ((size_t)nData + (nAlign - 1)) & ~(nAlign - 1); - return T(size); -} - -template<typename T> -inline -bool IsAligned(T nData, size_t nAlign) -{ - assert((nAlign & (nAlign - 1)) == 0); - return (size_t(nData) & (nAlign - 1)) == 0; -} - -template<typename T, typename U> -inline -void SetFlags(T& dest, U flags, bool b) -{ - if (b) - { - dest |= flags; - } - else - { - dest &= ~flags; - } -} - -// Wrapper code for non-windows builds. -#if defined(LINUX) || defined(APPLE) - #include "Linux_Win32Wrapper.h" -#elif defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_12 - #include AZ_RESTRICTED_FILE(platform_h) -#endif - -// Platform wrappers must be included before CryString.h -# include "CryString.h" - -// Include support for meta-type data. -#include "TypeInfo_decl.h" - -// Include array. -#include <CryArray.h> - -bool CrySetFileAttributes(const char* lpFileName, uint32 dwFileAttributes); -threadID CryGetCurrentThreadId(); - -#if !defined(NOT_USE_CRY_STRING) -// Fixed-Sized (stack based string) -// put after the platform wrappers because of missing wcsicmp/wcsnicmp functions - #include "CryFixedString.h" -#endif - -// need this in a common header file and any other file would be too misleading -enum ETriState -{ - eTS_false, - eTS_true, - eTS_maybe -}; - - #ifdef __GNUC__ - #define NO_INLINE __attribute__ ((noinline)) -# define NO_INLINE_WEAK __attribute__ ((noinline)) __attribute__((weak)) // marks a function as no_inline, but also as weak to prevent multiple-defined errors - -# define __PACKED __attribute__ ((packed)) - #else - #define NO_INLINE _declspec(noinline) -# define NO_INLINE_WEAK _declspec(noinline) inline - -# define __PACKED - #endif - -// Fallback for Alignment macro of GCC/CLANG (must be after the class definition) -#if !defined(_ALIGN) - #define _ALIGN(num) AZ_POP_DISABLE_WARNING -#endif - -// Fallback for Alignment macro of MSVC (must be before the class definition) -#if !defined(_MS_ALIGN) - #define _MS_ALIGN(num) AZ_PUSH_DISABLE_WARNING(4324, "-Wunknown-warning-option") -#endif - -#if defined(WIN32) || defined(WIN64) -extern "C" { -__declspec(dllimport) unsigned long __stdcall TlsAlloc(); -__declspec(dllimport) void* __stdcall TlsGetValue(unsigned long dwTlsIndex); -__declspec(dllimport) int __stdcall TlsSetValue(unsigned long dwTlsIndex, void* lpTlsValue); -} - - #define TLS_DECLARE(type, var) extern int var##idx; - #define TLS_DEFINE(type, var) \ - int var##idx; \ - struct Init##var { \ - Init##var() { var##idx = TlsAlloc(); } \ - }; \ - Init##var g_init##var; - #define TLS_DEFINE_DEFAULT_VALUE(type, var, value) \ - int var##idx; \ - struct Init##var { \ - Init##var() { var##idx = TlsAlloc(); TlsSetValue(var##idx, reinterpret_cast<void*>(value)); } \ - }; \ - Init##var g_init##var; - #define TLS_GET(type, var) (type)TlsGetValue(var##idx) - #define TLS_SET(var, val) TlsSetValue(var##idx, reinterpret_cast<void*>(val)) -#elif defined(USE_PTHREAD_TLS) - #define TLS_DECLARE(_TYPE, _VAR) extern SCryPthreadTLS<_TYPE> _VAR##TLSKey; - #define TLS_DEFINE(_TYPE, _VAR) SCryPthreadTLS<_TYPE> _VAR##TLSKey; - #define TLS_DEFINE_DEFAULT_VALUE(_TYPE, _VAR, _DEFAULT) SCryPthreadTLS<_TYPE> _VAR##TLSKey = _DEFAULT; - #define TLS_GET(_TYPE, _VAR) _VAR##TLSKey.Get() - #define TLS_SET(_VAR, _VALUE) _VAR##TLSKey.Set(_VALUE) -#elif defined(THREADLOCAL) - #define TLS_DECLARE(type, var) extern THREADLOCAL type var; -#if defined(LINUX) || defined(MAC) - #define TLS_DEFINE(type, var) THREADLOCAL type var = 0; -#else - #define TLS_DEFINE(type, var) THREADLOCAL type var; -#endif // defined(LINUX) || defined(MAC) - #define TLS_DEFINE_DEFAULT_VALUE(type, var, value) THREADLOCAL type var = value; - #define TLS_GET(type, var) (var) - #define TLS_SET(var, val) (var = (val)) -#else // defined(THREADLOCAL) - #error "There's no support for thread local storage" -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_13 - #include AZ_RESTRICTED_FILE(platform_h) -#elif !defined(LINUX) && !defined(APPLE) -typedef int socklen_t; -#endif - - -// Include MultiThreading support. -#include "CryThread.h" -#include "MultiThread.h" - -// In RELEASE disable printf and fprintf -#if defined(_RELEASE) && !defined(RELEASE_LOGGING) - #if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_14 - #include AZ_RESTRICTED_FILE(platform_h) - #endif -#endif - -#define _STRINGIFY(x) #x -#define STRINGIFY(x) _STRINGIFY(x) - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_H_SECTION_15 - #include AZ_RESTRICTED_FILE(platform_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(WIN32) || defined(WIN64) - #define MESSAGE(msg) message(__FILE__ "(" STRINGIFY(__LINE__) "): " msg) -#else - #define MESSAGE(msg) -#endif - -void InitRootDir(char szExeFileName[] = nullptr, uint nExeSize = 0, char szExeRootName[] = nullptr, uint nRootSize = 0); diff --git a/Code/CryEngine/CryCommon/platform_impl.cpp b/Code/CryEngine/CryCommon/platform_impl.cpp deleted file mode 100644 index 7f21348007..0000000000 --- a/Code/CryEngine/CryCommon/platform_impl.cpp +++ /dev/null @@ -1,575 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include <platform.h> -#include <StringUtils.h> -#include <ISystem.h> -#include <Random.h> -#include <UnicodeFunctions.h> -#include <IConsole.h> - -#include <AzCore/Debug/Profiler.h> -#include <AzCore/Debug/ProfileModuleInit.h> -#include <AzCore/Memory/AllocatorManager.h> -#include <AzCore/Module/Environment.h> - -// Section dictionary -#if defined(AZ_RESTRICTED_PLATFORM) -#define PLATFORM_IMPL_H_SECTION_TRAITS 1 -#define PLATFORM_IMPL_H_SECTION_CRYLOWLATENCYSLEEP 2 -#define PLATFORM_IMPL_H_SECTION_CRYGETFILEATTRIBUTES 3 -#define PLATFORM_IMPL_H_SECTION_CRYSETFILEATTRIBUTES 4 -#define PLATFORM_IMPL_H_SECTION_CRY_FILE_ATTRIBUTE_STUBS 5 -#define PLATFORM_IMPL_H_SECTION_CRY_SYSTEM_FUNCTIONS 6 -#define PLATFORM_IMPL_H_SECTION_VIRTUAL_ALLOCATORS 7 -#endif - -struct SSystemGlobalEnvironment* gEnv = nullptr; - -// Traits -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_IMPL_H_SECTION_TRAITS - #include AZ_RESTRICTED_FILE(platform_impl_h) -#endif - -////////////////////////////////////////////////////////////////////////// -// If not in static library. -#include <CryThreadImpl.h> - -#if defined(WIN32) || defined(WIN64) -void CryPureCallHandler() -{ - CryFatalError("Pure function call"); -} - -void CryInvalidParameterHandler( - [[maybe_unused]] const wchar_t* expression, - [[maybe_unused]] const wchar_t* function, - [[maybe_unused]] const wchar_t* file, - [[maybe_unused]] unsigned int line, - [[maybe_unused]] uintptr_t pReserved) -{ - //size_t i; - //char sFunc[128]; - //char sExpression[128]; - //char sFile[128]; - //wcstombs_s( &i,sFunc,sizeof(sFunc),function,_TRUNCATE ); - //wcstombs_s( &i,sExpression,sizeof(sExpression),expression,_TRUNCATE ); - //wcstombs_s( &i,sFile,sizeof(sFile),file,_TRUNCATE ); - //CryFatalError( "Invalid parameter detected in function %s. File: %s Line: %d, Expression: %s",sFunc,sFile,line,sExpression ); - CryFatalError("Invalid parameter detected in CRT function\n"); -} - -void InitCRTHandlers() -{ - _set_purecall_handler(CryPureCallHandler); - _set_invalid_parameter_handler(CryInvalidParameterHandler); -} -#else -void InitCRTHandlers() {} -#endif - -#ifndef SOFTCODE -////////////////////////////////////////////////////////////////////////// -// This is an entry to DLL initialization function that must be called for each loaded module -////////////////////////////////////////////////////////////////////////// -extern "C" AZ_DLL_EXPORT void ModuleInitISystem(ISystem* pSystem, [[maybe_unused]] const char* moduleName) -{ - if (gEnv) // Already registered. - { - return; - } - - InitCRTHandlers(); - - if (pSystem) // DONT REMOVE THIS. ITS FOR RESOURCE COMPILER!!!! - { - gEnv = pSystem->GetGlobalEnvironment(); - assert(gEnv); - - if (!AZ::Environment::IsReady() || (AZ::Environment::GetInstance() != gEnv->pSharedEnvironment)) - { - AZ::Environment::Attach(gEnv->pSharedEnvironment); - AZ::AllocatorManager::Instance(); // Force the AllocatorManager to instantiate and register any allocators defined in data sections - } - AZ::Debug::ProfileModuleInit(); - } // if pSystem -} - -extern "C" AZ_DLL_EXPORT void ModuleShutdownISystem([[maybe_unused]] ISystem* pSystem) -{ - // Unregister with AZ environment. - AZ::Environment::Detach(); -} - -extern "C" AZ_DLL_EXPORT void InjectEnvironment(void* env) -{ - static bool injected = false; - if (!injected) - { - AZ::Environment::Attach(reinterpret_cast<AZ::EnvironmentInstance>(env)); - AZ::AllocatorManager::Instance(); // Force the AllocatorManager to instantiate and register any allocators defined in data sections - injected = true; - } -} - -extern "C" AZ_DLL_EXPORT void DetachEnvironment() -{ - AZ::Environment::Detach(); -} - -void* GetModuleInitISystemSymbol() -{ - return reinterpret_cast<void*>(&ModuleInitISystem); -} -void* GetModuleShutdownISystemSymbol() -{ - return reinterpret_cast<void*>(&ModuleShutdownISystem); -} -void* GetInjectEnvironmentSymbol() -{ - return reinterpret_cast<void*>(&InjectEnvironment); -} -void* GetDetachEnvironmentSymbol() -{ - return reinterpret_cast<void*>(&DetachEnvironment); -} - -#endif // !defined(SOFTCODE) - -bool g_bProfilerEnabled = false; - -////////////////////////////////////////////////////////////////////////// -// global random number generator used by cry_random functions -CRndGen CryRandom_Internal::g_random_generator; - - -////////////////////////////////////////////////////////////////////////// - -// when using STL Port _STLP_DEBUG and _STLP_DEBUG_TERMINATE - avoid actually -// crashing (default terminator seems to kill the thread, which isn't nice). -#ifdef _STLP_DEBUG_TERMINATE - -# ifdef __stl_debug_terminate -# undef __stl_debug_terminate -# endif - -void __stl_debug_terminate(void) -{ - assert(0 && "STL Debug Error"); -} -#endif - -#ifdef _STLP_DEBUG_MESSAGE - -# ifdef __stl_debug_message -# undef __stl_debug_message -# endif - -void __stl_debug_message(const char* format_str, ...) -{ - va_list __args; - va_start(__args, format_str); -#ifdef WIN32 - char __buffer [4096]; - azvsnprintf(__buffer, sizeof(__buffer) / sizeof(char), format_str, __args); - OutputDebugStringA(__buffer); -#endif - gEnv->pLog->LogV(ILog::eErrorAlways, format_str, __args); - va_end(__args); -} -#endif //_STLP_DEBUG_MESSAGE - - -#if defined(WIN32) || defined(WIN64) -#include <intrin.h> -#endif - -#if defined(APPLE) || defined(LINUX) -#include "CryAssert_impl.h" -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_IMPL_H_SECTION_CRY_SYSTEM_FUNCTIONS - #include AZ_RESTRICTED_FILE(platform_impl_h) -#endif - -#if defined (_WIN32) - -#include "CryAssert_impl.h" - -////////////////////////////////////////////////////////////////////////// -void CryDebugBreak() -{ -#if defined(WIN32) && !defined(RELEASE) - if (IsDebuggerPresent()) -#endif - { - DebugBreak(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CrySleep(unsigned int dwMilliseconds) -{ - AZ_PROFILE_FUNCTION_IDLE(AZ::Debug::ProfileCategory::System); - Sleep(dwMilliseconds); -} - -////////////////////////////////////////////////////////////////////////// -void CryLowLatencySleep(unsigned int dwMilliseconds) -{ - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::System); -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_IMPL_H_SECTION_CRYLOWLATENCYSLEEP - #include AZ_RESTRICTED_FILE(platform_impl_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - CrySleep(dwMilliseconds); -#endif -} - -////////////////////////////////////////////////////////////////////////// -int CryMessageBox([[maybe_unused]] const char* lpText, [[maybe_unused]] const char* lpCaption, [[maybe_unused]] unsigned int uType) -{ -#ifdef WIN32 -#if !defined(RESOURCE_COMPILER) - ICVar* const pCVar = gEnv && gEnv->pConsole ? gEnv->pConsole->GetCVar("sys_no_crash_dialog") : NULL; - if ((pCVar && pCVar->GetIVal() != 0) || (gEnv && gEnv->bNoAssertDialog)) - { - return 0; - } -#endif - wstring wideText, wideCaption; - Unicode::Convert(wideText, lpText); - Unicode::Convert(wideCaption, lpCaption); - return MessageBoxW(NULL, wideText.c_str(), wideCaption.c_str(), uType); -#else - return 0; -#endif -} - -// Initializes root folder of the game, optionally returns exe and path name. -void InitRootDir(char szExeFileName[], uint nExeSize, char szExeRootName[], [[maybe_unused]] uint nRootSize) -{ - WCHAR szPath[_MAX_PATH]; - size_t nLen = GetModuleFileNameW(GetModuleHandle(NULL), szPath, _MAX_PATH); - assert(nLen < _MAX_PATH && "The path to the current executable exceeds the expected length"); - - // Find path above exe name and deepest folder. - bool firstIteration = true; - for (size_t n = nLen - 1; n > 0; n--) - { - if (szPath[n] == '\\') - { - szPath[n] = 0; - - if (firstIteration) - { - // Return exe path - if (szExeRootName) - { - Unicode::Convert(szExeRootName, n+1, szPath); - } - - // Return exe name - if (szExeFileName) - { - Unicode::Convert(szExeFileName, nExeSize, szPath + n); - } - firstIteration = false; - } - // Check if the engineroot exists - wcscat_s(szPath, L"\\engine.json"); - WIN32_FILE_ATTRIBUTE_DATA data; - BOOL res = GetFileAttributesExW(szPath, GetFileExInfoStandard, &data); - if (res != 0 && data.dwFileAttributes != INVALID_FILE_ATTRIBUTES) - { - // Found file - szPath[n] = 0; - SetCurrentDirectoryW(szPath); - break; - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -short CryGetAsyncKeyState([[maybe_unused]] int vKey) -{ -#ifdef WIN32 - return GetAsyncKeyState(vKey); -#else - return 0; -#endif -} - -////////////////////////////////////////////////////////////////////////// -LONG CryInterlockedIncrement(int volatile* lpAddend) -{ - return InterlockedIncrement((volatile LONG*)lpAddend); -} - -////////////////////////////////////////////////////////////////////////// -LONG CryInterlockedDecrement(int volatile* lpAddend) -{ - return InterlockedDecrement((volatile LONG*)lpAddend); -} - -////////////////////////////////////////////////////////////////////////// -LONG CryInterlockedExchangeAdd(LONG volatile* lpAddend, LONG Value) -{ - return InterlockedExchangeAdd(lpAddend, Value); -} - -LONG CryInterlockedOr(LONG volatile* Destination, LONG Value) -{ - return InterlockedOr(Destination, Value); -} - -LONG CryInterlockedCompareExchange(LONG volatile* dst, LONG exchange, LONG comperand) -{ - return InterlockedCompareExchange(dst, exchange, comperand); -} - -void* CryInterlockedCompareExchangePointer(void* volatile* dst, void* exchange, void* comperand) -{ - return InterlockedCompareExchangePointer(dst, exchange, comperand); -} - -void* CryInterlockedExchangePointer(void* volatile* dst, void* exchange) -{ - return InterlockedExchangePointer(dst, exchange); -} - -void CryInterlockedAdd(volatile size_t* pVal, ptrdiff_t iAdd) -{ -#if defined (PLATFORM_64BIT) -#if !defined(NDEBUG) - size_t v = (size_t) -#endif - InterlockedAdd64((volatile int64*)pVal, iAdd); -#else - size_t v = (size_t)CryInterlockedExchangeAdd((volatile long*)pVal, (long)iAdd); - v += iAdd; -#endif - assert((iAdd == 0) || (iAdd < 0 && v < v - (size_t)iAdd) || (iAdd > 0 && v > v - (size_t)iAdd)); -} - -////////////////////////////////////////////////////////////////////////// -void* CryCreateCriticalSection() -{ - CRITICAL_SECTION* pCS = new CRITICAL_SECTION; - InitializeCriticalSection(pCS); - return pCS; -} - -void CryCreateCriticalSectionInplace(void* pCS) -{ - InitializeCriticalSection((CRITICAL_SECTION*)pCS); -} -////////////////////////////////////////////////////////////////////////// -void CryDeleteCriticalSection(void* cs) -{ - CRITICAL_SECTION* pCS = (CRITICAL_SECTION*)cs; - if (pCS->LockCount >= 0) - { - CryFatalError("Critical Section hanging lock"); - } - DeleteCriticalSection(pCS); - delete pCS; -} - -////////////////////////////////////////////////////////////////////////// -void CryDeleteCriticalSectionInplace(void* cs) -{ - CRITICAL_SECTION* pCS = (CRITICAL_SECTION*)cs; - if (pCS->LockCount >= 0) - { - CryFatalError("Critical Section hanging lock"); - } - DeleteCriticalSection(pCS); -} - -////////////////////////////////////////////////////////////////////////// -void CryEnterCriticalSection(void* cs) -{ - EnterCriticalSection((CRITICAL_SECTION*)cs); -} - -////////////////////////////////////////////////////////////////////////// -bool CryTryCriticalSection(void* cs) -{ - return TryEnterCriticalSection((CRITICAL_SECTION*)cs) != 0; -} - -////////////////////////////////////////////////////////////////////////// -void CryLeaveCriticalSection(void* cs) -{ - LeaveCriticalSection((CRITICAL_SECTION*)cs); -} - -////////////////////////////////////////////////////////////////////////// -uint32 CryGetFileAttributes(const char* lpFileName) -{ - WIN32_FILE_ATTRIBUTE_DATA data; - BOOL res; -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_IMPL_H_SECTION_CRYGETFILEATTRIBUTES - #include AZ_RESTRICTED_FILE(platform_impl_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - res = GetFileAttributesEx(lpFileName, GetFileExInfoStandard, &data); -#endif - return res ? data.dwFileAttributes : -1; -} - -////////////////////////////////////////////////////////////////////////// -bool CrySetFileAttributes(const char* lpFileName, uint32 dwFileAttributes) -{ -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_IMPL_H_SECTION_CRYSETFILEATTRIBUTES - #include AZ_RESTRICTED_FILE(platform_impl_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - return SetFileAttributes(lpFileName, dwFileAttributes) != 0; -#endif -} - -////////////////////////////////////////////////////////////////////////// -threadID CryGetCurrentThreadId() -{ - return GetCurrentThreadId(); -} - -#endif // _WIN32 - -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_IMPL_H_SECTION_CRY_FILE_ATTRIBUTE_STUBS - #include AZ_RESTRICTED_FILE(platform_impl_h) -#endif - -#if defined(AZ_PLATFORM_WINDOWS) -int64 CryGetTicks() -{ - LARGE_INTEGER li; - QueryPerformanceCounter(&li); - return li.QuadPart; -} - -int64 CryGetTicksPerSec() -{ - LARGE_INTEGER li; - QueryPerformanceFrequency(&li); - return li.QuadPart; -} -#endif - - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// -// Threads implementation. For static linking it must be declared inline otherwise creating multiple symbols -//////////////////////////////////////////////////////////////////////////////////////////////////////////// -#define THR_INLINE inline - -////////////////////////////////////////////////////////////////////////// -inline void CryDebugStr([[maybe_unused]] const char* format, ...) -{ - /* - #ifdef CRYSYSTEM_EXPORTS - va_list ArgList; - char szBuffer[65535]; - va_start(ArgList, format); - azvsnprintf(szBuffer,sizeof(szBuffer)-1, format, ArgList); - va_end(ArgList); - cry_strcat(szBuffer,"\n"); - OutputDebugString(szBuffer); - #endif - */ -} - -_MS_ALIGN(64) uint32 BoxSides[0x40 * 8] = { - 0, 0, 0, 0, 0, 0, 0, 0, //00 - 0, 4, 6, 2, 0, 0, 0, 4, //01 - 7, 5, 1, 3, 0, 0, 0, 4, //02 - 0, 0, 0, 0, 0, 0, 0, 0, //03 - 0, 1, 5, 4, 0, 0, 0, 4, //04 - 0, 1, 5, 4, 6, 2, 0, 6, //05 - 7, 5, 4, 0, 1, 3, 0, 6, //06 - 0, 0, 0, 0, 0, 0, 0, 0, //07 - 7, 3, 2, 6, 0, 0, 0, 4, //08 - 0, 4, 6, 7, 3, 2, 0, 6, //09 - 7, 5, 1, 3, 2, 6, 0, 6, //0a - 0, 0, 0, 0, 0, 0, 0, 0, //0b - 0, 0, 0, 0, 0, 0, 0, 0, //0c - 0, 0, 0, 0, 0, 0, 0, 0, //0d - 0, 0, 0, 0, 0, 0, 0, 0, //0e - 0, 0, 0, 0, 0, 0, 0, 0, //0f - 0, 2, 3, 1, 0, 0, 0, 4, //10 - 0, 4, 6, 2, 3, 1, 0, 6, //11 - 7, 5, 1, 0, 2, 3, 0, 6, //12 - 0, 0, 0, 0, 0, 0, 0, 0, //13 - 0, 2, 3, 1, 5, 4, 0, 6, //14 - 1, 5, 4, 6, 2, 3, 0, 6, //15 - 7, 5, 4, 0, 2, 3, 0, 6, //16 - 0, 0, 0, 0, 0, 0, 0, 0, //17 - 0, 2, 6, 7, 3, 1, 0, 6, //18 - 0, 4, 6, 7, 3, 1, 0, 6, //19 - 7, 5, 1, 0, 2, 6, 0, 6, //1a - 0, 0, 0, 0, 0, 0, 0, 0, //1b - 0, 0, 0, 0, 0, 0, 0, 0, //1c - 0, 0, 0, 0, 0, 0, 0, 0, //1d - 0, 0, 0, 0, 0, 0, 0, 0, //1e - 0, 0, 0, 0, 0, 0, 0, 0, //1f - 7, 6, 4, 5, 0, 0, 0, 4, //20 - 0, 4, 5, 7, 6, 2, 0, 6, //21 - 7, 6, 4, 5, 1, 3, 0, 6, //22 - 0, 0, 0, 0, 0, 0, 0, 0, //23 - 7, 6, 4, 0, 1, 5, 0, 6, //24 - 0, 1, 5, 7, 6, 2, 0, 6, //25 - 7, 6, 4, 0, 1, 3, 0, 6, //26 - 0, 0, 0, 0, 0, 0, 0, 0, //27 - 7, 3, 2, 6, 4, 5, 0, 6, //28 - 0, 4, 5, 7, 3, 2, 0, 6, //29 - 6, 4, 5, 1, 3, 2, 0, 6, //2a - 0, 0, 0, 0, 0, 0, 0, 0, //2b - 0, 0, 0, 0, 0, 0, 0, 0, //2c - 0, 0, 0, 0, 0, 0, 0, 0, //2d - 0, 0, 0, 0, 0, 0, 0, 0, //2e - 0, 0, 0, 0, 0, 0, 0, 0, //2f - 0, 0, 0, 0, 0, 0, 0, 0, //30 - 0, 0, 0, 0, 0, 0, 0, 0, //31 - 0, 0, 0, 0, 0, 0, 0, 0, //32 - 0, 0, 0, 0, 0, 0, 0, 0, //33 - 0, 0, 0, 0, 0, 0, 0, 0, //34 - 0, 0, 0, 0, 0, 0, 0, 0, //35 - 0, 0, 0, 0, 0, 0, 0, 0, //36 - 0, 0, 0, 0, 0, 0, 0, 0, //37 - 0, 0, 0, 0, 0, 0, 0, 0, //38 - 0, 0, 0, 0, 0, 0, 0, 0, //39 - 0, 0, 0, 0, 0, 0, 0, 0, //3a - 0, 0, 0, 0, 0, 0, 0, 0, //3b - 0, 0, 0, 0, 0, 0, 0, 0, //3c - 0, 0, 0, 0, 0, 0, 0, 0, //3d - 0, 0, 0, 0, 0, 0, 0, 0, //3e - 0, 0, 0, 0, 0, 0, 0, 0, //3f -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////// -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION PLATFORM_IMPL_H_SECTION_VIRTUAL_ALLOCATORS - #include AZ_RESTRICTED_FILE(platform_impl_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#endif diff --git a/Code/CryEngine/CryCommon/primitives.h b/Code/CryEngine/CryCommon/primitives.h deleted file mode 100644 index 16a9ffbbd7..0000000000 --- a/Code/CryEngine/CryCommon/primitives.h +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_PRIMITIVES_H -#define CRYINCLUDE_CRYCOMMON_PRIMITIVES_H -#pragma once - - - -typedef int index_t; -enum -{ - PHYS_MAX_INDICES = 1 << 30 -}; - -#include "stridedptr.h" - -namespace primitives { - ////////////////////////// primitives ////////////////////// - - struct primitive - { - }; - - struct box - : primitive - { - enum entype - { - type = 0 - }; - Matrix33 Basis; // v_box = Basis*v_world; Basis = Rotation.T() - int bOriented; - Vec3 center; - Vec3 size; - AUTO_STRUCT_INFO - }; - - struct triangle - : primitive - { - enum entype - { - type = 1 - }; - Vec3 pt[3]; - Vec3 n; - AUTO_STRUCT_INFO - }; - - struct indexed_triangle - : triangle - { - int idx; - AUTO_STRUCT_INFO - }; - - typedef float (* getHeightCallback)(int ix, int iy); - typedef unsigned char (* getSurfTypeCallback)(int ix, int iy); - - struct grid - : primitive - { - Matrix33 Basis; - int bOriented; - Vec3 origin; - vector2df step, stepr; - vector2di size; - vector2di stride; - int bCyclic; - grid() { bCyclic = 0; } - int inrange(int ix, int iy) { return bCyclic | -((ix - size.x & - 1 - ix & iy - size.y & - 1 - iy) >> 31); } - int getcell_safe(int ix, int iy) { int mask = -inrange(ix, iy); return (iy & size.y - 1) * stride.y + (ix & size.x - 1) * stride.x & mask | size.x * size.y & ~mask; } - int crop(int i, int icoord, int bAllowBorder = 1) { int brd = bAllowBorder + (1 << 30 & - bCyclic); return max(-brd, min(size[icoord] - 1 + brd, i)); } - vector2di cropxy(const vector2di& ic, int bAllowBorder = 1) { int brd = bAllowBorder + (1 << 30 & - bCyclic); return vector2di(max(-brd, min(size.x - 1 + brd, ic.x)), max(-brd, min(size.y - 1 + brd, ic.y))); } - int iscyclic() { return bCyclic; } - AUTO_STRUCT_INFO - }; - - struct heightfield - : grid - { - enum entype - { - type = 2 - }; - heightfield& operator=(const heightfield& src) - { - step = src.step; - stepr = src.stepr; - size = src.size; - stride = src.stride; - heightscale = src.heightscale; - typemask = src.typemask; - typehole = src.typehole; - typepower = src.typepower; - fpGetHeightCallback = src.fpGetHeightCallback; - fpGetSurfTypeCallback = src.fpGetSurfTypeCallback; - return *this; - } - - ILINE float getheight(int ix, int iy) const - { - float result = (*fpGetHeightCallback)(ix, iy); - return result * heightscale; - } - ILINE int gettype(int ix, int iy) const - { - int itype = (((*fpGetSurfTypeCallback)(ix, iy)) & typemask) >> typepower, idelta = itype - typehole; - return itype | ((idelta - 1) >> 31 ^ idelta >> 31); - } - - float heightscale; - unsigned short typemask; - int typehole; - int typepower; - getHeightCallback fpGetHeightCallback; - getSurfTypeCallback fpGetSurfTypeCallback; - }; - - struct ray - : primitive - { - enum entype - { - type = 3 - }; - Vec3 origin; - Vec3 dir; - AUTO_STRUCT_INFO - }; - - struct sphere - : primitive - { - enum entype - { - type = 4 - }; - Vec3 center; - float r; - AUTO_STRUCT_INFO - }; - - struct cylinder - : primitive - { - enum entype - { - type = 5 - }; - Vec3 center; - Vec3 axis; - float r, hh; - AUTO_STRUCT_INFO - }; - - struct capsule - : cylinder - { - enum entype - { - type = 6 - }; - AUTO_STRUCT_INFO - }; - - struct grid3d - : primitive - { - Matrix33 Basis; - int bOriented; - Vec3 origin; - Vec3 step, stepr; - Vec3i size; - Vec3i stride; - }; - - struct voxelgrid - : grid3d - { - enum entype - { - type = 7 - }; - Matrix33 R; - Vec3 offset; - float scale, rscale; - strided_pointer<Vec3> pVtx; - index_t* pIndices; - Vec3* pNormals; - char* pIds; - int* pCellTris; - int* pTriBuf; - }; - - struct plane - : primitive - { - enum entype - { - type = 8 - }; - Vec3 n; - Vec3 origin; - AUTO_STRUCT_INFO - }; - - struct coord_plane - : plane - { - Vec3 axes[2]; - AUTO_STRUCT_INFO - }; -} - -AUTO_TYPE_INFO(primitives::getHeightCallback) -AUTO_TYPE_INFO(primitives::getSurfTypeCallback) - -struct prim_inters -{ - prim_inters() { minPtDist2 = 0.0f; ptbest.zero(); } - Vec3 pt[2]; - Vec3 n; - unsigned char iFeature[2][2]; - float minPtDist2; - short id[2]; - int iNode[2]; - Vec3* ptborder; - int nborderpt, nbordersz; - Vec3 ptbest; - int nBestPtVal; -}; - -struct contact -{ - real t, taux; - Vec3 pt; - Vec3 n; - unsigned int iFeature[2]; -}; - -const int NPRIMS = 8; // since plane is currently not supported in collision checks - -///////////////////// geometry contact structures /////////////////// - -struct geom_contact_area -{ - enum entype - { - polygon, polyline - }; - int type; - int npt; - int nmaxpt; - float minedge; - int* piPrim[2]; - int* piFeature[2]; - Vec3* pt; - Vec3 n1; // normal of other object surface (or edge) -}; - -const int IFEAT_LOG2 = 23; -const int IDXMASK = ~(0xFF << IFEAT_LOG2); -const int TRIEND = 0x80 << IFEAT_LOG2; - -struct geom_contact -{ - real t; - Vec3 pt; - Vec3 n; - Vec3 dir; // unprojection direction - int iUnprojMode; - float vel; // original velocity along this direction, <0 if least squares normal was used - int id[2]; // external ids for colliding geometry parts - int iPrim[2]; - int iFeature[2]; - int iNode[2]; // BV-tree nodes of contacting primitives - Vec3* ptborder; // intersection border - int (*idxborder)[2]; // primitive index | primitive's feature's id << IFEAT_LOG2 - int nborderpt; - int bClosed; - Vec3 center; - bool bBorderConsecutive; - geom_contact_area* parea; -}; - -#endif // CRYINCLUDE_CRYCOMMON_PRIMITIVES_H diff --git a/Code/CryEngine/CryCommon/smartptr.h b/Code/CryEngine/CryCommon/smartptr.h deleted file mode 100644 index 74dcc6911a..0000000000 --- a/Code/CryEngine/CryCommon/smartptr.h +++ /dev/null @@ -1,443 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_SMARTPTR_H -#define CRYINCLUDE_CRYCOMMON_SMARTPTR_H -#pragma once - -#include <platform.h> -#include <type_traits> - -void CryFatalError(const char*, ...) PRINTF_PARAMS(1, 2); -#if defined(APPLE) - #include <cstddef> -#endif -////////////////////////////////////////////////////////////////// -// SMART POINTER -////////////////////////////////////////////////////////////////// -template <class _I> -class _smart_ptr -{ -private: - _I* p; -public: - _smart_ptr() - : p(NULL) {} - _smart_ptr(_I* p_) - { - p = p_; - if (p) - { - p->AddRef(); - } - } - - _smart_ptr(const _smart_ptr& p_) - { - p = p_.p; - if (p) - { - p->AddRef(); - } - } - - template <typename _Y> - _smart_ptr(const _smart_ptr<_Y>& p_) - { - p = p_.get(); - if (p) - { - p->AddRef(); - } - } - - ~_smart_ptr() - { - if (p) - { - p->Release(); - } - } - operator _I*() const { - return p; - } - - _I& operator*() const { return *p; } - _I* operator->(void) const { return p; } - _I* get() const { return p; } - _smart_ptr& operator=(_I* newp) - { - if (newp) - { - newp->AddRef(); - } - if (p) - { - p->Release(); - } - p = newp; - return *this; - } - - void reset() - { - _smart_ptr<_I>().swap(*this); - } - - void reset(_I* ptr) - { - _smart_ptr<_I>(ptr).swap(*this); - } - - void attach(_I* p_) - { - p = p_; - } - - _smart_ptr& operator=(const _smart_ptr& newp) - { - if (newp.p) - { - newp.p->AddRef(); - } - if (p) - { - p->Release(); - } - p = newp.p; - return *this; - } - - template <typename _Y> - _smart_ptr& operator=(const _smart_ptr<_Y>& newp) - { - _I* const p2 = newp.get(); - if (p2) - { - p2->AddRef(); - } - if (p) - { - p->Release(); - } - p = p2; - return *this; - } - - // set our contained pointer to null, but don't call Release() - // useful for when we want to do that ourselves, or when we know that - // the contained pointer is invalid - friend _I* ReleaseOwnership(_smart_ptr<_I>& ptr) - { - _I* ret = ptr.p; - ptr.p = 0; - return ret; - } - void swap(_smart_ptr<_I>& other) - { - std::swap(p, other.p); - } - - AUTO_STRUCT_INFO -}; - -template <typename T> -ILINE void swap(_smart_ptr<T>& a, _smart_ptr<T>& b) -{ - a.swap(b); -} - -// reference target without vtable for smart pointer -// implements AddRef() and Release() strategy using reference counter of the specified type -template <typename TDerived, typename Counter = int> -class _reference_target_no_vtable -{ -public: - _reference_target_no_vtable() - : m_nRefCounter (0) - { - } - - ~_reference_target_no_vtable() - { - //assert (!m_nRefCounter); - } - - void AddRef() - { - CHECK_REFCOUNT_CRASH(m_nRefCounter >= 0); - ++m_nRefCounter; - } - - void Release() - { - CHECK_REFCOUNT_CRASH(m_nRefCounter > 0); - if (--m_nRefCounter == 0) - { - delete static_cast<TDerived*>(this); - } - else if (m_nRefCounter < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } - } - // Warning: use for debugging/statistics purposes only! - Counter NumRefs() - { - return m_nRefCounter; - } -protected: - Counter m_nRefCounter; -}; - -// reference target with vtable for smart pointer -// implements AddRef() and Release() strategy using reference counter of the specified type -template <typename Counter> -class _reference_target -{ -public: - _reference_target() - : m_nRefCounter (0) - { - } - - virtual ~_reference_target() - { - //assert (!m_nRefCounter); - } - - void AddRef() - { - CHECK_REFCOUNT_CRASH(m_nRefCounter >= 0); - ++m_nRefCounter; - } - - void Release() - { - CHECK_REFCOUNT_CRASH(m_nRefCounter > 0); - if (--m_nRefCounter == 0) - { - delete this; - } - else if (m_nRefCounter < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } - } - // Warning: use for debugging/statistics purposes only! - Counter NumRefs() - { - return m_nRefCounter; - } -protected: - Counter m_nRefCounter; -}; - -// default implementation is int counter - for better alignment -typedef _reference_target<int> _reference_target_t; - - -// reference target for smart pointer with configurable destruct function -// implements AddRef() and Release() strategy using reference counter of the specified type -template <typename T, typename Counter = int> -class _cfg_reference_target -{ -public: - - typedef void (* DeleteFncPtr)(void*); - - _cfg_reference_target() - : m_nRefCounter (0) - , m_pDeleteFnc(operator delete) - { - } - - explicit _cfg_reference_target(DeleteFncPtr pDeleteFnc) - : m_nRefCounter (0) - , m_pDeleteFnc(pDeleteFnc) - { - } - - virtual ~_cfg_reference_target() - { - } - - void AddRef() - { - CHECK_REFCOUNT_CRASH(m_nRefCounter >= 0); - ++m_nRefCounter; - } - - void Release() - { - CHECK_REFCOUNT_CRASH(m_nRefCounter > 0); - if (--m_nRefCounter == 0) - { - assert(m_pDeleteFnc); - static_cast<T*>(this)->~T(); - m_pDeleteFnc(this); - } - else if (m_nRefCounter < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } - } - - // Sets the delete function with which this object is supposed to be deleted - void SetDeleteFnc(DeleteFncPtr pDeleteFnc) { m_pDeleteFnc = pDeleteFnc; } - - // Warning: use for debugging/statistics purposes only! - Counter NumRefs() - { - return m_nRefCounter; - } -protected: - Counter m_nRefCounter; - DeleteFncPtr m_pDeleteFnc; -}; - - -// base class for interfaces implementing reference counting -// derive your interface from this class and the descendants won't have to implement -// the reference counting logic -template <typename Counter> -class _i_reference_target -{ -public: - _i_reference_target() - : m_nRefCounter (0) - { - } - - virtual ~_i_reference_target() - { - } - - virtual void AddRef() - { - ++m_nRefCounter; - } - - virtual void Release() - { - if (--m_nRefCounter == 0) - { - delete this; - } - else if (m_nRefCounter < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } - } - - // Warning: use for debugging/statistics purposes only! - Counter NumRefs() const - { - return m_nRefCounter; - } -protected: - Counter m_nRefCounter; -}; - -class CMultiThreadRefCount -{ -public: - CMultiThreadRefCount() - : m_cnt(0) {} - virtual ~CMultiThreadRefCount() {} - - inline int AddRef() - { - return CryInterlockedIncrement(&m_cnt); - } - inline int Release() - { - const int nCount = CryInterlockedDecrement(&m_cnt); - assert(nCount >= 0); - if (nCount == 0) - { - delete this; - } - else if (nCount < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } - return nCount; - } - - inline int GetRefCount() const { return m_cnt; } - -protected: - // Allows the memory for the object to be deallocated in the dynamic module where it was originally constructed, as it may use different memory manager (Debug/Release configurations) - virtual void DeleteThis() { delete this; } - -private: - volatile int m_cnt; -}; - -// base class for interfaces implementing reference counting that needs to be thread-safe -// derive your interface from this class and the descendants won't have to implement -// the reference counting logic -template <typename Counter> -class _i_multithread_reference_target -{ -public: - _i_multithread_reference_target() - : m_nRefCounter(0) - { - } - - virtual ~_i_multithread_reference_target() - { - } - - virtual void AddRef() - { - CryInterlockedIncrement(&m_nRefCounter); - } - - virtual void Release() - { - const int nCount = CryInterlockedDecrement(&m_nRefCounter); - assert(nCount >= 0); - if (nCount == 0) - { - delete this; - } - else if (nCount < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } - } - - Counter NumRefs() const { return m_nRefCounter; } - -protected: - - volatile Counter m_nRefCounter; -}; - -typedef _i_reference_target<int> _i_reference_target_t; -typedef _i_multithread_reference_target<int> _i_multithread_reference_target_t; - -// TYPEDEF_AUTOPTR macro, declares Class_AutoPtr, which is the smart pointer to the given class, -// and Class_AutoArray, which is the array(STL vector) of autopointers -#ifdef ENABLE_NAIIVE_AUTOPTR -// naiive autopointer makes it easier for Visual Assist to parse the declaration and sometimes is easier for debug -#define TYPEDEF_AUTOPTR(T) typedef T* T##_AutoPtr; typedef std::vector<T##_AutoPtr> T##_AutoArray; -#else -#define TYPEDEF_AUTOPTR(T) typedef _smart_ptr<T> T##_AutoPtr; typedef std::vector<T##_AutoPtr> T##_AutoArray; -#endif - -#endif // CRYINCLUDE_CRYCOMMON_SMARTPTR_H diff --git a/Code/CryEngine/CryCommon/stridedptr.h b/Code/CryEngine/CryCommon/stridedptr.h deleted file mode 100644 index d5e0ec632a..0000000000 --- a/Code/CryEngine/CryCommon/stridedptr.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_STRIDEDPTR_H -#define CRYINCLUDE_CRYCOMMON_STRIDEDPTR_H -#pragma once - -#include <CryCommon/platform.h> -#include <CryCommon/CryEndian.h> - -template<class dtype> -class strided_pointer -{ -public: - strided_pointer() - : data(0) - , iStride(sizeof(dtype)) - { - } - - strided_pointer(dtype* pdata, int32 stride = sizeof(dtype)) - : data(pdata) - , iStride(stride) - { - } - - template<typename dtype1> - strided_pointer(dtype1* pdata) - { - set(pdata, sizeof(dtype1)); - } - - template<typename dtype1> - strided_pointer(const strided_pointer<dtype1>& src) - { - set(src.data, src.iStride); - } - - template<typename dtype1> - ILINE strided_pointer& operator=(const strided_pointer<dtype1>& src) - { - set(src.data, src.iStride); - return *this; - } - - ILINE dtype& operator[](int32 idx) { return *(dtype*)((char*)data + idx * iStride); } - ILINE const dtype& operator[](int32 idx) const { return *(const dtype*)((const char*)data + idx * iStride); } - ILINE strided_pointer<dtype> operator+(int32 idx) const { return strided_pointer<dtype>((dtype*)((char*)data + idx * iStride), iStride); } - ILINE strided_pointer<dtype> operator-(int32 idx) const { return strided_pointer<dtype>((dtype*)((char*)data - idx * iStride), iStride); } - - ILINE operator bool() const - { - return data != 0; - } - -private: - template<typename dtype1> - ILINE void set(dtype1* pdata, int32 stride) - { -# if !defined(eLittleEndian) -# error eLittleEndian is not defined, please include CryEndian.h. -# endif - COMPILE_TIME_ASSERT(metautils::is_const<dtype>::value || !metautils::is_const<dtype1>::value); - // note: we allow xint32 -> xint16 converting - COMPILE_TIME_ASSERT( - (metautils::is_same<typename metautils::remove_const<dtype1>::type, typename metautils::remove_const<dtype>::type>::value || - ((metautils::is_same<typename metautils::remove_const<dtype1>::type, sint32>::value || - metautils::is_same<typename metautils::remove_const<dtype1>::type, uint32>::value || - metautils::is_same<typename metautils::remove_const<dtype1>::type, sint16>::value || - metautils::is_same<typename metautils::remove_const<dtype1>::type, uint16>::value) && - (metautils::is_same<typename metautils::remove_const<dtype>::type, sint16>::value || - metautils::is_same<typename metautils::remove_const<dtype>::type, uint16>::value)))); - data = (dtype*)pdata + (sizeof(dtype1) / sizeof(dtype) - 1) * (int)eLittleEndian; - iStride = stride; - } - -private: - // Prevents assignment of a structure member's address by mistake: - // stridedPtrObject = &myStruct.member; - // Use explicit constructor instead: - // stridedPtrObject = strided_pointer<baseType>(&myStruct.member, sizeof(myStruct)); - // - // Keep it private and non-implemented. - strided_pointer& operator=(dtype* pdata); - - // Prevents using the address directly by mistake: - // memcpy(destination, stridedPtrObject, sizeof(baseType) * n); - // Use address of the first element instead: - // memcpy(destination, &stridedPtrObject[0], stridedPtrObject.iStride * n); - // - // Keep it private and non-implemented. - operator void*() const; - - // Prevents direct dereferencing to avoid confusing it with "normal" pointers: - // val = *stridedPtrObject; - // Use operator [] instead: - // val = stridedPtrObject[0]; - // - // Keep it private and non-implemented. - dtype& operator*() const; - -public: - dtype* data; - int32 iStride; -}; - - -#endif // CRYINCLUDE_CRYCOMMON_STRIDEDPTR_H diff --git a/Code/CryEngine/CrySystem/AZCoreLogSink.h b/Code/CryEngine/CrySystem/AZCoreLogSink.h deleted file mode 100644 index e5c0228a16..0000000000 --- a/Code/CryEngine/CrySystem/AZCoreLogSink.h +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include <AzCore/Memory/SystemAllocator.h> -#include <AzCore/Math/Crc.h> -#include <AzCore/Debug/TraceMessageBus.h> -#include <AzCore/std/containers/unordered_map.h> -#include <AzCore/Console/IConsole.h> - -#include <CryAssert.h> - -namespace AZ -{ - AZ_CVAR_EXTERNED(int, bg_traceLogLevel); -} - -/** - * Hook Trace bus so we can funnel AZ asserts, warnings, etc to CryEngine. - * - * Note: This is currently owned by CrySystem, because CrySystem owns - * the logging mechanism for which it is relevant. - */ -class AZCoreLogSink - : public AZ::Debug::TraceMessageBus::Handler -{ -public: - inline static void Connect() - { - GetInstance().m_ignoredAsserts = new IgnoredAssertMap(); - GetInstance().BusConnect(); - } - - inline static void Disconnect() - { - GetInstance().BusDisconnect(); - delete GetInstance().m_ignoredAsserts; - } - - static AZCoreLogSink& GetInstance() - { - static AZCoreLogSink s_sink; - return s_sink; - } - - static bool IsCryLogReady() - { - static bool hasSetCVar = false; - bool ready = gEnv && gEnv->pSystem && gEnv->pLog; - -#ifdef _RELEASE - if(!hasSetCVar && ready) - { - // AZ logging only has a concept of 3 levels (error, warning, info) but cry logging has 4 levels (..., messaging). If info level is set, we'll turn on messaging as well - int logLevel = AZ::bg_traceLogLevel == AZ::Debug::LogLevel::Info ? 4 : AZ::bg_traceLogLevel; - - gEnv->pConsole->GetCVar("log_WriteToFileVerbosity")->Set(logLevel); - hasSetCVar = true; - } -#endif - - return ready; - } - - bool OnPreAssert(const char* fileName, int line, const char* func, const char* message) override - { -#if defined(USE_CRY_ASSERT) && AZ_LEGACY_CRYSYSTEM_TRAIT_DO_PREASSERT - AZ::Crc32 crc; - crc.Add(&line, sizeof(line)); - if (fileName) - { - crc.Add(fileName, strlen(fileName)); - } - - bool* ignore = nullptr; - auto foundIter = m_ignoredAsserts->find(crc); - if (foundIter == m_ignoredAsserts->end()) - { - ignore = &((*m_ignoredAsserts)[crc]); - *ignore = false; - } - else - { - ignore = &((*m_ignoredAsserts)[crc]); - } - - if (!(*ignore)) - { - using namespace AZ::Debug; - - Trace::Output(nullptr, "\n==================================================================\n"); - AZ::OSString outputMsg = AZ::OSString::format("Trace::Assert\n %s(%d): '%s'\n%s\n", fileName, line, func, message); - Trace::Output(nullptr, outputMsg.c_str()); - - // Suppress 3 in stack depth - this function, the bus broadcast that got us here, and Trace::Assert - Trace::Output(nullptr, "------------------------------------------------\n"); - Trace::PrintCallstack(nullptr, 3); - Trace::Output(nullptr, "\n==================================================================\n"); - - AZ::EnvironmentVariable<bool> inEditorBatchMode = AZ::Environment::FindVariable<bool>("InEditorBatchMode"); - if (!inEditorBatchMode.IsConstructed() || !inEditorBatchMode.Get()) - { - // Note - CryAssertTrace doesn't actually print any info to logging - // it just stores the message internally for the message box in CryAssert to use - CryAssertTrace("%s", message); - if (CryAssert("Assertion failed", fileName, line, ignore) || Trace::IsDebuggerPresent()) - { - Trace::Break(); - } - } - } - else - { - CryLogAlways("%s", message); - } - - return true; // suppress default AzCore behavior. -#else - AZ_UNUSED(fileName); - AZ_UNUSED(line); - AZ_UNUSED(func); - AZ_UNUSED(message); - return false; // allow AZCore to do its default behavior. This usually results in an application shutdown. -#endif - } - - bool OnPreError(const char* window, const char* fileName, int line, const char* func, const char* message) override - { - AZ_UNUSED(fileName); - AZ_UNUSED(line); - AZ_UNUSED(func); - if (!IsCryLogReady()) - { - return false; // allow AZCore to do its default behavior. - } - gEnv->pLog->LogError("(%s) - %s", window, message); - return true; // suppress default AzCore behavior. - } - - bool OnPreWarning(const char* window, const char* fileName, int line, const char* func, const char* message) override - { - AZ_UNUSED(fileName); - AZ_UNUSED(line); - AZ_UNUSED(func); - - if (!IsCryLogReady()) - { - return false; // allow AZCore to do its default behavior. - } - - CryWarning(VALIDATOR_MODULE_UNKNOWN, VALIDATOR_WARNING, "(%s) - %s", window, message); - return true; // suppress default AzCore behavior. - } - - bool OnOutput(const char* window, const char* message) override - { - if (!IsCryLogReady()) - { - return false; // allow AZCore to do its default behavior. - } - - if (window == AZ::Debug::Trace::GetDefaultSystemWindow()) - { - CryLogAlways("%s", message); - } - else - { - CryLog("(%s) - %s", window, message); - } - - return true; // suppress default AzCore behavior. - } - -private: - - using IgnoredAssertMap = AZStd::unordered_map<AZ::Crc32, bool, AZStd::hash<AZ::Crc32>, AZStd::equal_to<AZ::Crc32>, AZ::OSStdAllocator>; - IgnoredAssertMap* m_ignoredAsserts; -}; diff --git a/Code/CryEngine/CrySystem/AZCrySystemInitLogSink.cpp b/Code/CryEngine/CrySystem/AZCrySystemInitLogSink.cpp deleted file mode 100644 index c34d990875..0000000000 --- a/Code/CryEngine/CrySystem/AZCrySystemInitLogSink.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include "CrySystem_precompiled.h" -#include <AZCrySystemInitLogSink.h> - -#include <AzCore/NativeUI/NativeUIRequests.h> -#include <AzCore/std/string/osstring.h> - -#include <ISystem.h> - -namespace AZ -{ - namespace Debug - { - void CrySystemInitLogSink::SetFatalMessageBox(bool enable) - { - m_isMessageBoxFatal = enable; - } - - void CrySystemInitLogSink::DisplayCollectedErrorStrings() const - { - if (m_errorStringsCollected.empty()) - { - return; - } - - AZ::OSString msgBoxMessage; - msgBoxMessage.append("O3DE could not initialize correctly for the following reason(s):"); - - for (const AZ::OSString& errMsg : m_errorStringsCollected) - { - msgBoxMessage.append("\n"); - msgBoxMessage.append(errMsg.c_str()); - } - - Trace::Output(nullptr, "\n==================================================================\n"); - Trace::Output(nullptr, msgBoxMessage.c_str()); - Trace::Output(nullptr, "\n==================================================================\n"); - - EBUS_EVENT(AZ::NativeUI::NativeUIRequestBus, DisplayOkDialog, "O3DE Initialization Failed", msgBoxMessage.c_str(), false); - } - } // namespace Debug -} // namespace AZ diff --git a/Code/CryEngine/CrySystem/AZCrySystemInitLogSink.h b/Code/CryEngine/CrySystem/AZCrySystemInitLogSink.h deleted file mode 100644 index e97c605b84..0000000000 --- a/Code/CryEngine/CrySystem/AZCrySystemInitLogSink.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include <AzFramework/Logging/StartupLogSinkReporter.h> - -namespace AZ -{ - namespace Debug - { - /** - * A handler for the TraceMessageBus which is meant to collect errors and asserts during CrySystem::Init to display them to the user. - * It will also elevate all output to CryLogAlways while it is in scope. - * As such, it assumes that it is being used within the CrySystem library and gEnv and gEnv->pSystem are valid. - */ - class CrySystemInitLogSink - : public StartupLogSink - { - public: - CrySystemInitLogSink() = default; - - /** - * Enables or disables the fatal flags to send to the platform specific message box - */ - void SetFatalMessageBox(bool enable = true); - - /** - * Formats the collected error messages into a platform specific message box to display to the user. - * This expects that a valid gEnv->pSystem exists, and the IOSPlatform has been initialzied. - * Will also log output messages to whatever medium is possible for OnOutput messages on TraceMessageBus (ex. debug output, logs). - */ - void DisplayCollectedErrorStrings() const override; - - protected: - bool m_isMessageBoxFatal = false; - }; - } // namespace Debug -} // namespace AZ - diff --git a/Code/CryEngine/CrySystem/CMakeLists.txt b/Code/CryEngine/CrySystem/CMakeLists.txt deleted file mode 100644 index 54a1ad9cc3..0000000000 --- a/Code/CryEngine/CrySystem/CMakeLists.txt +++ /dev/null @@ -1,51 +0,0 @@ -# -# Copyright (c) Contributors to the Open 3D Engine Project -# -# SPDX-License-Identifier: Apache-2.0 OR MIT -# -# - -add_subdirectory(XML) - -ly_add_target( - NAME CrySystem.Static STATIC - NAMESPACE Legacy - FILES_CMAKE - crysystem_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - . - BUILD_DEPENDENCIES - PRIVATE - 3rdParty::expat - 3rdParty::lz4 - 3rdParty::md5 - 3rdParty::tiff - 3rdParty::zlib - 3rdParty::zstd - Legacy::CryCommon - Legacy::CrySystem.XMLBinary - Legacy::RemoteConsoleCore - AZ::AzFramework -) - -ly_add_source_properties( - SOURCES SystemInit.cpp - PROPERTY COMPILE_DEFINITIONS - VALUES ${LY_PAL_TOOLS_DEFINES} -) - -ly_add_target( - NAME CrySystem ${PAL_TRAIT_MONOLITHIC_DRIVEN_LIBRARY_TYPE} - NAMESPACE Legacy - FILES_CMAKE - crysystem_shared_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - . - BUILD_DEPENDENCIES - PRIVATE - Legacy::CrySystem.Static - AZ::AzCore - Legacy::CryCommon -) diff --git a/Code/CryEngine/CrySystem/CmdLine.cpp b/Code/CryEngine/CrySystem/CmdLine.cpp deleted file mode 100644 index 37bc109cc0..0000000000 --- a/Code/CryEngine/CrySystem/CmdLine.cpp +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "CrySystem_precompiled.h" -#include "CmdLine.h" - - -void CCmdLine::PushCommand(const string& sCommand, const string& sParameter) -{ - if (sCommand.empty()) - { - return; - } - - ECmdLineArgType type = eCLAT_Normal; - const char* szCommand = sCommand.c_str(); - - if (sCommand[0] == '-') - { - type = eCLAT_Pre; - ++szCommand; - - // Handle cmd line parameters that use -- properly - if (szCommand[0] == '-') - { - ++szCommand; - } - } - else if (sCommand[0] == '+') - { - type = eCLAT_Post; - ++szCommand; - } - - m_args.push_back(CCmdLineArg(szCommand, sParameter.c_str(), type)); -} - -CCmdLine::CCmdLine(const char* commandLine) -{ - m_sCmdLine = commandLine; - - char* src = (char*)commandLine; - - string command, parameter; - - for (;; ) - { - if (*src == '\0') - { - break; - } - - string arg = Next(src); - - if (m_args.empty()) - { - // this is the filename, convert backslash to forward slash - arg.replace('\\', '/'); - m_args.push_back(CCmdLineArg("filename", arg.c_str(), eCLAT_Executable)); - } - else - { - bool bSecondCharIsNumber = false; - - if (arg[0] && arg[1] >= '0' && arg[1] <= '9') - { - bSecondCharIsNumber = true; - } - - if ((arg[0] == '-' && !bSecondCharIsNumber) - || (arg[0] == '+' && !bSecondCharIsNumber) - || command.empty()) // separator or first parameter - { - PushCommand(command, parameter); - - command = arg; - parameter = ""; - } - else - { - if (parameter.empty()) - { - parameter = arg; - } - else - { - parameter += string(" ") + arg; - } - } - } - } - - PushCommand(command, parameter); -} - -CCmdLine::~CCmdLine() -{ -} - -const ICmdLineArg* CCmdLine::GetArg(int n) const -{ - if ((n >= 0) && (n < (int)m_args.size())) - { - return &m_args[n]; - } - - return 0; -} - -int CCmdLine::GetArgCount() const -{ - return (int)m_args.size(); -} - -const ICmdLineArg* CCmdLine::FindArg(const ECmdLineArgType ArgType, const char* name, bool caseSensitive) const -{ - if (caseSensitive) - { - for (std::vector<CCmdLineArg>::const_iterator it = m_args.begin(); it != m_args.end(); ++it) - { - if (it->GetType() == ArgType) - { - if (!strcmp(it->GetName(), name)) - { - return &(*it); - } - } - } - } - else - { - for (std::vector<CCmdLineArg>::const_iterator it = m_args.begin(); it != m_args.end(); ++it) - { - if (it->GetType() == ArgType) - { - if (!_stricmp(it->GetName(), name)) - { - return &(*it); - } - } - } - } - - return 0; -} - - -string CCmdLine::Next(char*& src) -{ - char ch = 0; - char* org = src; - - ch = *src++; - while (ch) - { - switch (ch) - { - case '\'': - case '\"': - org = src; - - while ((*src++ != ch) && *src) - { - ; - } - - return string(org, src - 1); - - case '[': - org = src; - while ((*src++ != ']') && *src) - { - ; - } - return string(org, src - 1); - - case ' ': - ch = *src++; - continue; - default: - org = src - 1; - for (; *src != ' ' && *src != '\t' && *src; ++src) - { - ; - } - - return string(org, src); - } - ch = *src++; - } - - return string(); -} - - diff --git a/Code/CryEngine/CrySystem/CmdLine.h b/Code/CryEngine/CrySystem/CmdLine.h deleted file mode 100644 index ea1bfb60ef..0000000000 --- a/Code/CryEngine/CrySystem/CmdLine.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Implements the command line interface ICmdLine. - -#ifndef CRYINCLUDE_CRYSYSTEM_CMDLINE_H -#define CRYINCLUDE_CRYSYSTEM_CMDLINE_H - -#pragma once - - -#include <ICmdLine.h> -#include "CmdLineArg.h" - - -class CCmdLine - : public ICmdLine -{ -public: - CCmdLine(const char* commandLine); - virtual ~CCmdLine(); - - virtual const ICmdLineArg* GetArg(int n) const; - virtual int GetArgCount() const; - virtual const ICmdLineArg* FindArg(const ECmdLineArgType ArgType, const char* name, bool caseSensitive = false) const; - virtual const char* GetCommandLine() const { return m_sCmdLine; }; - -private: - void PushCommand(const string& sCommand, const string& sParameter); - string Next(char*& str); - - string m_sCmdLine; - std::vector<CCmdLineArg> m_args; -}; - - -#endif // CRYINCLUDE_CRYSYSTEM_CMDLINE_H diff --git a/Code/CryEngine/CrySystem/CmdLineArg.cpp b/Code/CryEngine/CrySystem/CmdLineArg.cpp deleted file mode 100644 index 07a0ee4024..0000000000 --- a/Code/CryEngine/CrySystem/CmdLineArg.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "CrySystem_precompiled.h" -#include "CmdLineArg.h" - - -CCmdLineArg::CCmdLineArg(const char* name, const char* value, ECmdLineArgType type) -{ - m_name = name; - m_value = value; - m_type = type; -} - -CCmdLineArg::~CCmdLineArg() -{ -} - -const char* CCmdLineArg::GetName() const -{ - return m_name.c_str(); -} -const char* CCmdLineArg::GetValue() const -{ - return m_value.c_str(); -} -const ECmdLineArgType CCmdLineArg::GetType() const -{ - return m_type; -} -const float CCmdLineArg::GetFValue() const -{ - return (float)atof(m_value.c_str()); -} -const int CCmdLineArg::GetIValue() const -{ - return atoi(m_value.c_str()); -} - - diff --git a/Code/CryEngine/CrySystem/CmdLineArg.h b/Code/CryEngine/CrySystem/CmdLineArg.h deleted file mode 100644 index 40e9ac9907..0000000000 --- a/Code/CryEngine/CrySystem/CmdLineArg.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Implements the command line argument interface ICmdLineArg. - - -#ifndef CRYINCLUDE_CRYSYSTEM_CMDLINEARG_H -#define CRYINCLUDE_CRYSYSTEM_CMDLINEARG_H - -#pragma once - -#include <ICmdLine.h> - - -class CCmdLineArg - : public ICmdLineArg -{ -public: - CCmdLineArg(const char* name, const char* value, ECmdLineArgType type); - virtual ~CCmdLineArg(); - - const char* GetName() const; - const char* GetValue() const; - const ECmdLineArgType GetType() const; - const float GetFValue() const; - const int GetIValue() const; - -private: - - ECmdLineArgType m_type; - string m_name; - string m_value; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_CMDLINEARG_H diff --git a/Code/CryEngine/CrySystem/ConsoleBatchFile.cpp b/Code/CryEngine/CrySystem/ConsoleBatchFile.cpp deleted file mode 100644 index 22c455b7a8..0000000000 --- a/Code/CryEngine/CrySystem/ConsoleBatchFile.cpp +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Executes an ASCII batch file of console commands... - - -#include "CrySystem_precompiled.h" -#include "ConsoleBatchFile.h" -#include "IConsole.h" -#include "ISystem.h" -#include "XConsole.h" -#include <CryPath.h> -#include <stdio.h> -#include "System.h" -#include <AzCore/IO/FileIO.h> - -IConsole* CConsoleBatchFile::m_pConsole = NULL; - -void CConsoleBatchFile::Init() -{ - m_pConsole = gEnv->pConsole; - REGISTER_COMMAND("exec", (ConsoleCommandFunc)ExecuteFileCmdFunc, 0, "executes a batch file of console commands"); -} - -////////////////////////////////////////////////////////////////////////// -void CConsoleBatchFile::ExecuteFileCmdFunc(IConsoleCmdArgs* args) -{ - if (!m_pConsole) - { - Init(); - } - - if (!args->GetArg(1)) - { - return; - } - - ExecuteConfigFile(args->GetArg(1)); -} - -////////////////////////////////////////////////////////////////////////// -bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) -{ - if (!sFilename) - { - return false; - } - - if (!m_pConsole) - { - Init(); - } - - string filename; - - if (sFilename[0] != '@') // console config files are actually by default in @root@ instead of @assets@ - { - // However, if we've passed in a relative or absolute path that matches an existing file name, - // don't change it. Only change it to "@root@/filename" and strip off any relative paths - // if the given pattern *didn't* match a file. - if (AZ::IO::FileIOBase::GetDirectInstance()->Exists(sFilename)) - { - filename = sFilename; - } - else - { - filename = PathUtil::Make("@root@", PathUtil::GetFile(sFilename)); - } - } - else - { - filename = sFilename; - } - - if (strlen(PathUtil::GetExt(filename)) == 0) - { - filename = PathUtil::ReplaceExtension(filename, "cfg"); - } - - ////////////////////////////////////////////////////////////////////////// - CCryFile file; - - { - const char* szLog = "Executing console batch file (try game,config,root):"; - string filenameLog; - string sfn = PathUtil::GetFile(filename); - - if (file.Open(filename, "rb", AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK)) - { - filenameLog = string("game/") + sfn; - } - else if (file.Open(string("config/") + sfn, "rb", AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK)) - { - filenameLog = string("game/config/") + sfn; - } - else if (file.Open(string("./") + sfn, "rb", AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK)) - { - filenameLog = string("./") + sfn; - } - else - { - CryLog("%s \"%s\" not found!", szLog, filename.c_str()); - return false; - } - - CryLog("%s \"%s\" found in %s ...", szLog, PathUtil::GetFile(filenameLog.c_str()), PathUtil::GetPath(filenameLog).c_str()); - } - - int nLen = file.GetLength(); - char* sAllText = new char [nLen + 16]; - file.ReadRaw(sAllText, nLen); - sAllText[nLen] = '\0'; - sAllText[nLen + 1] = '\0'; - - /* - This can't work properly as ShowConsole() can be called during the execution of the scripts, - which means bConsoleStatus is outdated and must not be set at the end of the function - - bool bConsoleStatus = ((CXConsole*)m_pConsole)->GetStatus(); - ((CXConsole*)m_pConsole)->SetStatus(false); - */ - - char* strLast = sAllText + nLen; - char* str = sAllText; - while (str < strLast) - { - char* s = str; - while (str < strLast && *str != '\n' && *str != '\r') - { - str++; - } - *str = '\0'; - str++; - while (str < strLast && (*str == '\n' || *str == '\r')) - { - str++; - } - - string strLine = s; - - - //trim all whitespace characters at the beginning and the end of the current line and store its size - strLine.Trim(); - size_t strLineSize = strLine.size(); - - //skip comments, comments start with ";" or "--" but may have preceding whitespace characters - if (strLineSize > 0) - { - if (strLine[0] == ';') - { - continue; - } - else if (strLine.find("--") == 0) - { - continue; - } - } - //skip empty lines - else - { - continue; - } - - { - m_pConsole->ExecuteString(strLine); - } - } - // See above - // ((CXConsole*)m_pConsole)->SetStatus(bConsoleStatus); - - delete []sAllText; - return true; -} diff --git a/Code/CryEngine/CrySystem/ConsoleBatchFile.h b/Code/CryEngine/CrySystem/ConsoleBatchFile.h deleted file mode 100644 index 52eaf053bc..0000000000 --- a/Code/CryEngine/CrySystem/ConsoleBatchFile.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Executes an ASCII batch file of console commands... - - -#ifndef CRYINCLUDE_CRYSYSTEM_CONSOLEBATCHFILE_H -#define CRYINCLUDE_CRYSYSTEM_CONSOLEBATCHFILE_H - -#pragma once - -struct IConsoleCmdArgs; -struct IConsole; - -class CConsoleBatchFile -{ -public: - static void Init(); - static bool ExecuteConfigFile(const char* filename); - -private: - static void ExecuteFileCmdFunc(IConsoleCmdArgs* args); - static IConsole* m_pConsole; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_CONSOLEBATCHFILE_H diff --git a/Code/CryEngine/CrySystem/ConsoleHelpGen.cpp b/Code/CryEngine/CrySystem/ConsoleHelpGen.cpp deleted file mode 100644 index 2845ca14ae..0000000000 --- a/Code/CryEngine/CrySystem/ConsoleHelpGen.cpp +++ /dev/null @@ -1,942 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "CrySystem_precompiled.h" - -#if defined(WIN32) || defined(WIN64) - -#include "ConsoleHelpGen.h" -#include "System.h" - - - -// remove bad characters, toupper, not very fast -string CConsoleHelpGen::FixAnchorName(const char* szName) -{ - string ret; - - const char* p = szName; - - while (*p) - { - if ((*p >= 'a' && *p <= 'z') - || (*p >= 'A' && *p <= 'Z') - || (*p >= '0' && *p <= '9')) - { - if (*p >= 'a' && *p <= 'z') - { - ret += *p - 'a' + 'A'; - } - else - { - ret += *p; - } - } - - ++p; - } - - return ret; -} - -string CConsoleHelpGen::GetCleanPrefix(const char* p) -{ - string sRet; - - while (*p != '_' && *p != 0) - { - sRet += *p++; - } - - return sRet; -} - - -string CConsoleHelpGen::SplitPrefixString_Part1(const char* p) -{ - string sRet; - - while (*p != 10 && *p != 13 && *p != 0) - { - sRet += *p++; - } - - return sRet; -} - -const char* CConsoleHelpGen::SplitPrefixString_Part2(const char* p) -{ - while (*p != 10 && *p != 13 && *p != 0) - { - p++; - } - - while (*p == 10 || *p == 13) - { - p++; - } - - return p; -} - -void CConsoleHelpGen::StartPage(FILE* f, const char* szPageName, const char* szPageDescription) const -{ - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "<HTML><HEAD><TITLE>%s", szPageName); - fprintf(f, "", szPageDescription); - fprintf(f, ""); - fprintf(f, ""); - fprintf(f, ""); - fprintf(f, ""); - fprintf(f, ""); - fprintf(f, ""); - fprintf(f, ""); - } -} - -void CConsoleHelpGen::EndPage(FILE* f) const -{ - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "

"); - } -} - - -void CConsoleHelpGen::KeyValue(FILE* f, const char* szKey, const char* szValue) const -{ - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "%s: %s
\n", szKey, szValue); - } - else if (m_eWorkMode == eWM_Confluence) - { - // fprintf(f,"*%s:* %s\n",szKey,szValue); - fprintf(f, "| *%s:* | %s |\n", szKey, szValue); - } - else - { - assert(0); - } -} - -void CConsoleHelpGen::LogVersion(FILE* f) const -{ - char s[1024]; - - { - GetModuleFileName(NULL, s, sizeof(s)); - - char fdir[_MAX_PATH]; - char fdrive[_MAX_PATH]; - char file[_MAX_PATH]; - char fext[_MAX_PATH]; - _splitpath_s(s, fdrive, fdir, file, fext); - - KeyValue(f, "Executable", (string(file) + fext).c_str()); - } - - { - time_t ltime; - - time(<ime); - tm today; - localtime_s(&today, <ime); - - strftime(s, 128, "%c", &today); - KeyValue(f, "Date(MM/DD/YY) Time", s); - } - - { - const SFileVersion& ver = gEnv->pSystem->GetFileVersion(); - ver.ToString(s, sizeof(s)); - - KeyValue(f, "FileVersion", s); - } - - { - const SFileVersion& ver = gEnv->pSystem->GetProductVersion(); - ver.ToString(s, sizeof(s)); - - KeyValue(f, "ProductVersion", s); - } - - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "
\n"); - } -} - -void CConsoleHelpGen::StartH1(FILE* f, const char* szName) const -{ - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "

%s

\n", szName); - } - else if (m_eWorkMode == eWM_Confluence) - { - fprintf(f, "h1. %s\n", szName); - } - else - { - assert(0); - } -} - -void CConsoleHelpGen::EndH1(FILE* f) const -{ - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "
\n"); - } -} - -void CConsoleHelpGen::StartH3(FILE* f, const char* szName) const -{ - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "

%s

    \n", szName); - } - else if (m_eWorkMode == eWM_Confluence) - { - fprintf(f, "\nh3. %s\n", szName); - } - else - { - assert(0); - } -} - -void CConsoleHelpGen::EndH3(FILE* f) const -{ - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "
\n"); - } - else if (m_eWorkMode == eWM_Confluence) - { - } - else - { - assert(0); - } -} - - - -void CConsoleHelpGen::StartCVar(FILE* f, const char* szName) const -{ - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "

%s

    \n", szName); - } - else if (m_eWorkMode == eWM_Confluence) - { - // fprintf(f,"\nh3. %s\n",szName); - fprintf(f, "\n

    %s
    \n", szName); - } - else - { - assert(0); - } -} - -void CConsoleHelpGen::EndCVar(FILE* f) const -{ - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "

\n"); - } - else if (m_eWorkMode == eWM_Confluence) - { - fprintf(f, "\n\n"); - } - else - { - assert(0); - } -} -void CConsoleHelpGen::SingleLinePrefix(FILE* f, const char* szPrefix, const char* szPrefixDesc, const char* szLink) const -{ - // group within the list of all groups (no elements) - - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "
  • %s_ %s
  • \n", szLink, szPrefix, szPrefixDesc); - } - else if (m_eWorkMode == eWM_Confluence) - { - string sPrefix; - - if (*szPrefix) - { - sPrefix = string(szPrefix) + "_"; - } - - // fprintf(f,"| %s | [%s|%s] |\n",sPrefix.c_str(),szPrefixDesc,szLink); // e.g. "" "CL_" "CC_" "I_" "T_" - fprintf(f, "{section:border=false}\n" - "{column:width=50px}{align:right}%s{align}{column}\n" - "{column:width=10px}{column}\n" - "{column}{align:left}[%s|%s]{align}{column}\n" - "{section}\n", - sPrefix.c_str(), szPrefixDesc, szLink); // e.g. "" "CL_" "CC_" "I_" "T_" - } - else - { - assert(0); - } -} - -void CConsoleHelpGen::StartPrefix(FILE* f, const char* szPrefix, const char* szPrefixDesc, const char* szLink) const -{ - // group before all the group elements - - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "
  • %s_ %s
    • \n", szLink, szPrefix, szPrefixDesc); - } - else if (m_eWorkMode == eWM_Confluence) - { - if (*szPrefix) - { - fprintf(f, "* [%s %s|%s]\n", szPrefix, szPrefixDesc, szLink); - } - else - { - fprintf(f, "* [%s|%s]\n", szPrefixDesc, szLink); - } - } - else - { - assert(0); - } -} - -void CConsoleHelpGen::EndPrefix(FILE* f) const -{ - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "
    \n"); - } -} - -void CConsoleHelpGen::SingleLineEntry_InGlobal(FILE* f, const char* szName, const char* szLink) const -{ - // element within a group - - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "
  • %s
  • \n", szLink, szName); - } - else if (m_eWorkMode == eWM_Confluence) - { - fprintf(f, "** [%s|%s]\n", szName, szLink); - } - else - { - assert(0); - } -} - - -void CConsoleHelpGen::SingleLineEntry_InGroup(FILE* f, const char* szName, const char* szLink) const -{ - // element within a group - - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "
  • %s
  • \n", szLink, szName); - } - else if (m_eWorkMode == eWM_Confluence) - { - fprintf(f, "* [%s|%s]\n", szName, szLink); - } - else - { - assert(0); - } -} - -// szName without # -void CConsoleHelpGen::Anchor(FILE* f, const char* szName) const -{ - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "\n", szName); - } - else if (m_eWorkMode == eWM_Confluence) - { - fprintf(f, "{anchor:%s}", szName); - } - else - { - assert(0); - } -} - -void CConsoleHelpGen::InsertConsoleVars(std::set& setCmdAndVars, const char* szLocalPrefix) const -{ - CXConsole::ConsoleVariablesMap::const_iterator itrVar, itrVarEnd = m_rParent.m_mapVariables.end(); - - for (itrVar = m_rParent.m_mapVariables.begin(); itrVar != itrVarEnd; ++itrVar) - { - ICVar* var = itrVar->second; - - if (_strnicmp(var->GetName(), szLocalPrefix, strlen(szLocalPrefix)) == 0) - { - setCmdAndVars.insert(var->GetName()); - } - } -} - - - -void CConsoleHelpGen::InsertConsoleCommands(std::set& setCmdAndVars, const char* szLocalPrefix) const -{ - CXConsole::ConsoleCommandsMap::const_iterator itrCmd, itrCmdEnd = m_rParent.m_mapCommands.end(); - - for (itrCmd = m_rParent.m_mapCommands.begin(); itrCmd != itrCmdEnd; ++itrCmd) - { - const CConsoleCommand& cmd = itrCmd->second; - - if (_strnicmp(cmd.m_sName, szLocalPrefix, strlen(szLocalPrefix)) == 0) - { - setCmdAndVars.insert(cmd.m_sName.c_str()); - } - } -} - - - -void CConsoleHelpGen::InsertConsoleVars(std::set& setCmdAndVars, std::map mapPrefix) const -{ - CXConsole::ConsoleVariablesMap::const_iterator itrVar, itrVarEnd = m_rParent.m_mapVariables.end(); - - for (itrVar = m_rParent.m_mapVariables.begin(); itrVar != itrVarEnd; ++itrVar) - { - ICVar* var = itrVar->second; - bool bInsert = true; - - { - std::map::const_iterator it2, end = mapPrefix.end(); - - for (it2 = mapPrefix.begin(); it2 != end; ++it2) - { - if (it2->first != "___" && _strnicmp(var->GetName(), it2->first, it2->first.size()) == 0) - { - bInsert = false; - break; - } - } - } - - if (bInsert) - { - setCmdAndVars.insert(var->GetName()); - } - } -} - - - -void CConsoleHelpGen::InsertConsoleCommands(std::set& setCmdAndVars, std::map mapPrefix) const -{ - CXConsole::ConsoleCommandsMap::const_iterator itrCmd, itrCmdEnd = m_rParent.m_mapCommands.end(); - - for (itrCmd = m_rParent.m_mapCommands.begin(); itrCmd != itrCmdEnd; ++itrCmd) - { - const CConsoleCommand& cmd = itrCmd->second; - bool bInsert = true; - - { - std::map::const_iterator it2, end = mapPrefix.end(); - - for (it2 = mapPrefix.begin(); it2 != end; ++it2) - { - if (it2->first != "___" && _strnicmp(cmd.m_sName, it2->first, it2->first.size()) == 0) - { - bInsert = false; - break; - } - } - } - - if (bInsert) - { - setCmdAndVars.insert(cmd.m_sName.c_str()); - } - } -} - -void CConsoleHelpGen::CreateSingleEntryFile(const char* szName) const -{ - assert(m_eWorkMode == eWM_Confluence); // only needed for confluence - - FILE* f3 = nullptr; - azfopen(&f3, (string(GetFolderName()) + GetFileExtension() + "/" + FixAnchorName(szName)).c_str(), "w"); - - if (!f3) - { - assert(0); - return; // error - } - - // StartPage(f3,szName,""); // HTML style - - IncludeSingleEntry(f3, szName); - - // EndPage(f3); // HTML style - - fclose(f3); -} - -const CConsoleCommand* CConsoleHelpGen::FindConsoleCommand(const char* szName) const -{ - CXConsole::ConsoleCommandsMap::const_iterator itrCmd, itrCmdEnd = m_rParent.m_mapCommands.end(); - - for (itrCmd = m_rParent.m_mapCommands.begin(); itrCmd != itrCmdEnd; ++itrCmd) - { - const CConsoleCommand& cmd = itrCmd->second; - - if (strcmp(cmd.m_sName.c_str(), szName) == 0) - { - return &cmd; - } - } - - return 0; -} - - -void CConsoleHelpGen::IncludeSingleEntry(FILE* f, const char* szName) const -{ - StartCVar(f, szName); - - uint32 dwFlags = 0; - const char* szHelp = ""; - - // slow but good for simpler code - if (ICVar* pVar = gEnv->pConsole->GetCVar(szName)) - { - dwFlags = pVar->GetFlags(); - szHelp = pVar->GetHelp(); - } - else if (const CConsoleCommand* pCommand = FindConsoleCommand(szName)) - { - dwFlags = pCommand->m_nFlags; - szHelp = pCommand->m_sHelp.c_str(); - } - else - { - assert(0); // internal error - } - const char* szFlags = CXConsole::GetFlagsString(dwFlags); - - if (*szFlags) - { - // fprintf(f3,"%%GRAY%% %s %%ENDCOLOR%%
    \n",szFlags); // twiki style - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "%s
    \n", szFlags); // simple HTML style - } - else if (m_eWorkMode == eWM_Confluence) - { - fprintf(f, "%s

    \n", szFlags); - } - else - { - assert(0); - } - } - - if (*szHelp == 0) - { - // fprintf(f,"%%TODO%%\n"); // wiki style, in our wiki %TODO% is defined as \"TODO\" - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "
    *TODO*
    \n"); // HTML style - } - else if (m_eWorkMode == eWM_Confluence) - { - fprintf(f, "{warning}TODO{warning}\n"); // Confluence style - } - else - { - assert(0); - } - } - else - { - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "
    \n%s\n
    \n", szHelp); // HTML style, to get fixed with font (layout in code is often making the assumption the forn is fixed width) - } - else if (m_eWorkMode == eWM_Confluence) - { - fprintf(f, "
    \n");
    -
    -            string sHelp = szHelp;
    -
    -            // currently not required as the {noformat} is used
    -            //          sHelp.replace("[","\\[");       sHelp.replace("]","\\]");
    -            //          sHelp.replace("{","\\{");       sHelp.replace("}","\\}");
    -            //          sHelp.replace("(","\\(");       sHelp.replace(")","\\)");
    -
    -            fprintf(f, "%s\n", sHelp.c_str());       // Confluence style
    -
    -            fprintf(f, "
    "); - } - else - { - assert(0); - } - } - - EndCVar(f); -} - -void CConsoleHelpGen::Work() -{ - // string sEngineFolder = string("@user@/")+GetFolderName(); - // gEnv->pCryPak->RemoveDir(sEngineFolder.c_str()); // todo: check if that works - // gEnv->pFileIO->CreatePath(sEngineFolder.c_str()); - - m_eWorkMode = eWM_HTML; - CreateMainPages(); - - m_eWorkMode = eWM_Confluence; - CreateMainPages(); - CreateFileForEachEntry(); - - m_eWorkMode = eWM_None; -} - - - -void CConsoleHelpGen::CreateFileForEachEntry() -{ - assert(m_eWorkMode == eWM_Confluence); // only needed for confluence - - // generate a single file for each console command - { - CXConsole::ConsoleCommandsMap::const_iterator itrCmd, itrCmdEnd = m_rParent.m_mapCommands.end(); - - for (itrCmd = m_rParent.m_mapCommands.begin(); itrCmd != itrCmdEnd; ++itrCmd) - { - const CConsoleCommand& cmd = itrCmd->second; - - CreateSingleEntryFile(cmd.m_sName.c_str()); - } - } - - // generate a single file for each console variable - { - CXConsole::ConsoleVariablesMap::iterator itrVar, itrVarEnd = m_rParent.m_mapVariables.end(); - - for (itrVar = m_rParent.m_mapVariables.begin(); itrVar != itrVarEnd; ++itrVar) - { - ICVar* var = itrVar->second; - - CreateSingleEntryFile(var->GetName()); - } - } -} - -void CConsoleHelpGen::CreateMainPages() -{ - gEnv->pFileIO->CreatePath(GetFolderName()); - - std::map mapPrefix; - - // order here doesn't matter, after the name some help can be added (after the first return) - mapPrefix[ "AI_"] = "Artificial Intelligence"; - mapPrefix[ "NET_"] = "Network"; - mapPrefix[ "ED_"] = "Editor"; - mapPrefix[ "ES_"] = "Entity System"; - mapPrefix[ "CON_"] = "Console"; - mapPrefix[ "AG_"] = "Animation Graph" "\n" "High level animation logic, describes animation selection and flow, matches animation state to current game logical state."; - mapPrefix[ "AC_"] = "Animated Character" "\n" "Better name would be 'Character Movement'.\nBridges game controlled movement and animation controlled movement."; - mapPrefix[ "CA_"] = "Character Animation" "\n" "Motion synthesize and playback, parameterization through blending and inversed kinematics."; - mapPrefix[ "E_"] = "3DEngine"; - mapPrefix[ "I_"] = "Input"; - mapPrefix[ "FG_"] = "Flow Graph" "\n" "hyper graph: game logic"; - mapPrefix[ "P_"] = "Physics"; - mapPrefix[ "R_"] = "Renderer"; - mapPrefix[ "S_"] = "Sound"; - mapPrefix[ "G_"] = "Game" "\n" "game specific, not part of CryEngine"; - mapPrefix[ "SYS_"] = "System"; - mapPrefix[ "V_"] = "Vehicle"; - mapPrefix[ "FT_"] = "Feature Test"; - mapPrefix[ "DEMO_"] = "Time Demo"; - mapPrefix[ "FT_"] = "Feature Test"; - mapPrefix[ "GL_"] = "Game Lobby"; - mapPrefix[ "HUD_"] = "Heads Up Display"; - mapPrefix[ "KC_"] = "Kill Cam"; - mapPrefix[ "PL_"] = "Player"; - mapPrefix[ "PP_"] = "Player Progression"; - mapPrefix[ "AIM_"] = "Aiming"; - mapPrefix["CAPTURE_"] = "Capture"; - mapPrefix[ "DS_"] = "Dialog Scripts"; - mapPrefix[ "GT_"] = "Game Token"; - mapPrefix[ "LOG_"] = "Logging"; - mapPrefix[ "MOV_"] = "Movie Sequences"; - mapPrefix[ "OSM_"] = "Overload Scene Manager"; - mapPrefix["PROFILE_"] = "Profiling"; - mapPrefix[ "STAP_"] = "Screen-space Torso Aim Pose"; - mapPrefix[ "LUA_"] = "Lua" "\n" "scripting system"; - mapPrefix[ "SV_"] = "Server"; - mapPrefix[ "MFX_"] = "Material Effects"; - mapPrefix[ "M_"] = "Multi threading"; - mapPrefix[ "CC_"] = "Character Customization"; - mapPrefix[ "CL_"] = "Client"; - mapPrefix[ "Q_"] = "Quality" "\n" "usually shader quality"; - mapPrefix[ "T_"] = "Timer"; - mapPrefix[ "___"] = "Remaining"; // key defined to get it sorted in the end - - FILE* f1 = nullptr; - azfopen(&f1, (string(GetFolderName()) + "/index" + GetFileExtension()).c_str(), "w"); - if (!f1) - { - return; - } - - StartPage(f1, "CryEngine ConsoleHTMLHelp", "main page"); - - StartH1(f1, "Console Commands and Variables"); - - LogVersion(f1); - - - if (m_eWorkMode == eWM_HTML) - { - fprintf(f1, "This list was exported from the engine by using the DumpCommandsVars console command.
    \n\n"); - } - else if (m_eWorkMode == eWM_Confluence) - { - fprintf(f1, "This list was exported from the engine by using the *DumpCommandsVars* console command.\n\n"); - } - else - { - assert(0); - } - - // show all registered Prefix with one line - { - std::map::const_iterator it, end = mapPrefix.end(); - - StartH3(f1, "Registered Prefixes"); - - for (it = mapPrefix.begin(); it != end; ++it) - { - const char* szLocalPrefix = it->first.c_str(); // can be 0 for remaining ones - string sCleanPrefix = GetCleanPrefix(szLocalPrefix); - string sPrefixName = SplitPrefixString_Part1(it->second); - - SingleLinePrefix(f1, sCleanPrefix.c_str(), sPrefixName.c_str(), (string("CONSOLEPREFIX") + FixAnchorName(sCleanPrefix.c_str()) + GetFileExtension()).c_str()); - // fprintf(f1," * [[CONSOLEPREFIX%s][%s_ %s]]\n",FixAnchorName(sCleanPrefix.c_str()).c_str(),sCleanPrefix.c_str(),sPrefixName.c_str()); - } - - EndH3(f1); // Registered prefixes - } - - - - - { - std::map::const_iterator it, it2, end = mapPrefix.end(); - - StartH3(f1, "Console Commands and Variables Sorted by Prefix"); - - for (it = mapPrefix.begin(); it != end; ++it) - { - const char* szLocalPrefix = it->first.c_str(); // can be 0 for remaining ones - string sCleanPrefix = GetCleanPrefix(szLocalPrefix); - string sPrefixName = SplitPrefixString_Part1(it->second); - - std::set setCmdAndVars; // to get console variables and commands sorted together - - if (strcmp("___", szLocalPrefix) != 0) - { - // insert all starting with the prefix - InsertConsoleVars(setCmdAndVars, szLocalPrefix); - InsertConsoleCommands(setCmdAndVars, szLocalPrefix); - } - else - { - // insert all not starting with any of the prefix - InsertConsoleVars(setCmdAndVars, mapPrefix); - InsertConsoleCommands(setCmdAndVars, mapPrefix); - } - - // ------------------------------- - - string sSubName = string("CONSOLEPREFIX") + sCleanPrefix; - - StartPrefix(f1, sCleanPrefix.c_str(), sPrefixName.c_str(), (sSubName + GetFileExtension()).c_str()); - - string sFileOut = string(GetFolderName()) + "/" + sSubName + GetFileExtension(); - FILE* f2 = nullptr; - azfopen(&f2, sFileOut.c_str(), "w"); - if (!f2) - { - fclose(f1); - return; - } - - // headline - { - string sHeadline; - - if (sCleanPrefix.empty()) - { - sHeadline = "Console Commands and Variables Without Special Prefix"; - } - else - { - sHeadline = string("Console Commands and Variables with Prefix ") + sCleanPrefix + "_"; - } - - StartH1(f2, sHeadline.c_str()); - } - - Explanation(f2, SplitPrefixString_Part2(it->second)); - - KeyValue(f2, "Possible Flags", CXConsole::GetFlagsString(0xffffffff)); - // fprintf(f2,"Possible Flags:
    \n"); - // fprintf(f2,"
    %s
    ",CXConsole::GetFlagsString(0xffffffff)); - - // log console variables and commands - { - StartH3(f2, "Alphabetically Sorted"); - - std::set::const_iterator itI, endI = setCmdAndVars.end(); - - for (itI = setCmdAndVars.begin(); itI != endI; ++itI) - { - SingleLineEntry_InGlobal(f1, *itI, (sSubName + GetFileExtension() + "#Anchor" + FixAnchorName(*itI)).c_str()); - SingleLineEntry_InGroup(f2, *itI, (string("#Anchor") + FixAnchorName(*itI)).c_str()); - } - - EndH3(f2); - } - - { - StartH3(f2, "Console Variables and Commands"); - - bool bFirst = true; - { - std::set::const_iterator itI, endI = setCmdAndVars.end(); - - for (itI = setCmdAndVars.begin(); itI != endI; ++itI) - { - if (!bFirst) - { - Separator(f2); - } - bFirst = false; - - Anchor(f2, (string("Anchor") + FixAnchorName(*itI)).c_str()); // anchor - - IncludeSingleEntry(f2, *itI); - } - } - EndH3(f2); - } - - EndH1(f2); // Console Commands and Variables ... - - fclose(f2); - f2 = 0; - - EndPrefix(f1); - } - - EndH3(f1); // Console commands and variables sorted by prefix - } - - EndH1(f1); - EndPage(f1); - - fclose(f1); - - m_rParent.ConsoleLogInputResponse("successfully wrote directory %s", GetFolderName()); -} - -void CConsoleHelpGen::Separator(FILE* f) const -{ - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "
    \n"); - } - else if (m_eWorkMode == eWM_Confluence) - { - // fprintf(f,"----\n"); - } - else - { - assert(0); - } -} - - -void CConsoleHelpGen::Explanation(FILE* f, const char* szText) const -{ - if (m_eWorkMode == eWM_HTML) - { - fprintf(f, "
    %s

    \n
    \n", szText); - } - else if (m_eWorkMode == eWM_Confluence) - { - // fprintf(f,"{quote}%s{quote}\n\n",szText); - fprintf(f, "%s\n\n", szText); - } - else - { - assert(0); - } -} - -const char* CConsoleHelpGen::GetFileExtension() const -{ - if (m_eWorkMode == eWM_HTML) - { - return ".html"; - } - else if (m_eWorkMode == eWM_Confluence) - { - } - else - { - assert(0); - } - - return ""; -} - -const char* CConsoleHelpGen::GetFolderName() const -{ - if (m_eWorkMode == eWM_HTML) - { - return "ConsoleHTMLHelp"; - } - else if (m_eWorkMode == eWM_Confluence) - { - return "ConsoleHTMLHelp/CRYAUTOGEN"; - } - else - { - assert(0); - } - - return 0; -} - - -#endif // defined(WIN32) || defined(WIN64) - diff --git a/Code/CryEngine/CrySystem/ConsoleHelpGen.h b/Code/CryEngine/CrySystem/ConsoleHelpGen.h deleted file mode 100644 index 1e1f04c34e..0000000000 --- a/Code/CryEngine/CrySystem/ConsoleHelpGen.h +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once -#ifndef CRYINCLUDE_CRYSYSTEM_CONSOLEHELPGEN_H -#define CRYINCLUDE_CRYSYSTEM_CONSOLEHELPGEN_H - -#if defined(WIN32) || defined(WIN64) - -#include "XConsole.h" // CXConsole, struct string_nocase_lt - - -// extract consoel variable and command help -// in some HTML pages and many small files that can be included in Confluence wiki -// pages (so maintain the documentation only in one place) -// -// Possible improvements/Known issues: -// - Nicer HTML layout (CSS?) -// - Searching in the content of the cvars is tricky (main page doesn't have help content) -// - %TODO% (was wiki image, should look good in confluence and HTML) -// - many small files should be stored in some extra folder for clearity -// - before generating the data the older directoy should be cleaned -// - file should be generated in the user folder -// - "wb" should be used instead of "w", to get the same result in unix -class CConsoleHelpGen -{ -public: - CConsoleHelpGen(CXConsole& rParent) - : m_rParent(rParent) - , m_eWorkMode(eWM_None) - { - } - - void Work(); - -private: // -------------------------------------------------------- - - enum EWorkMode - { - eWM_None, - eWM_HTML, - eWM_Confluence - }; - - // - void CreateMainPages(); - - // to create one file for for each cvar/command in confluence style - void CreateFileForEachEntry(); - - // insert if the name starts with the with prefix - void InsertConsoleVars(std::set& setCmdAndVars, const char* szPrefix) const; - // insert if the name starts with the with prefix - void InsertConsoleCommands(std::set& setCmdAndVars, const char* szPrefix) const; - // insert if the name does not start with any of the prefix in the map - void InsertConsoleVars(std::set& setCmdAndVars, std::map mapPrefix) const; - // insert if the name does not start with any of the prefix in the map - void InsertConsoleCommands(std::set& setCmdAndVars, std::map mapPrefix) const; - - // a single file for the entry is generate - void CreateSingleEntryFile(const char* szName) const; - - void IncludeSingleEntry(FILE* f, const char* szName) const; - - static string FixAnchorName(const char* szName); - static string GetCleanPrefix(const char* p); - // split before "|" (to get the prefix itself) - static string SplitPrefixString_Part1(const char* p); - // split string after "|" (to get the optional help) - static const char* SplitPrefixString_Part2(const char* p); - - void StartPage(FILE* f, const char* szPageName, const char* szPageDescription) const; - void EndPage(FILE* f) const; - void StartH1(FILE* f, const char* szName) const; - void EndH1(FILE* f) const; - void StartH3(FILE* f, const char* szName) const; - void EndH3(FILE* f) const; - void StartCVar(FILE* f, const char* szName) const; - void EndCVar(FILE* f) const; - void SingleLinePrefix(FILE* f, const char* szPrefix, const char* szPrefixDesc, const char* szLink) const; - void StartPrefix(FILE* f, const char* szPrefix, const char* szPrefixDesc, const char* szLink) const; - void EndPrefix(FILE* f) const; - void SingleLineEntry_InGlobal(FILE* f, const char* szName, const char* szLink) const; - void SingleLineEntry_InGroup(FILE* f, const char* szName, const char* szLink) const; - void Anchor(FILE* f, const char* szName) const; - - // to log some inital stats like date or application name - void KeyValue(FILE* f, const char* szKey, const char* szValue) const; - - // prefix explanation and indention for following text - void Explanation(FILE* f, const char* szText) const; - - void Separator(FILE* f) const; - - void LogVersion(FILE* f) const; - - // case senstive - // Returns - // 0 if not found - const CConsoleCommand* FindConsoleCommand(const char* szName) const; - - // ---------------------------------------------- - - // - const char* GetFolderName() const; - // - const char* GetFileExtension() const; - - // ---------------------------------------------- - - CXConsole& m_rParent; - EWorkMode m_eWorkMode; // during Work() thise true:HTML and false:Confluence at some point -}; - - -#endif // defined(WIN32) || defined(WIN64) -#endif // CRYINCLUDE_CRYSYSTEM_CONSOLEHELPGEN_H diff --git a/Code/CryEngine/CrySystem/CrySystem_precompiled.h b/Code/CryEngine/CrySystem/CrySystem_precompiled.h deleted file mode 100644 index 495df0e6c2..0000000000 --- a/Code/CryEngine/CrySystem/CrySystem_precompiled.h +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Precompiled Header. - - -#pragma once - -#include - -#include -#include -#include -#include - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define STDAFX_H_SECTION_1 1 -#define STDAFX_H_SECTION_2 2 -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION STDAFX_H_SECTION_1 -#include AZ_RESTRICTED_FILE(CrySystem_precompiled_h) -#elif defined(LINUX) // Scrubber friendly negated define pattern -#elif !defined(APPLE) - #include - #include -#endif - -//on mac the precompiled header is auto included in every .c and .cpp file, no include line necessary. -//.c files don't like the cpp things in here -#ifdef __cplusplus - -#include - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION STDAFX_H_SECTION_2 -#include AZ_RESTRICTED_FILE(CrySystem_precompiled_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(APPLE) // Scrubber friendly negated define pattern -#elif defined(ANDROID) // Scrubber friendly negated define pattern -#elif defined(LINUX) - # include -#else - # include -#endif - -//#define DEFINE_MODULE_NAME "CrySystem" - -#define CRYSYSTEM_EXPORTS - -#include - -#if defined(WIN32) || defined(WIN64) || defined(APPLE) || defined(LINUX) -#if defined(DEDICATED_SERVER) -// enable/disable map load slicing functionality from the build -#define MAP_LOADING_SLICING -#endif -#endif - -#ifdef WIN32 -#include -#include -#undef GetCharWidth -#undef GetUserName -#endif - -///////////////////////////////////////////////////////////////////////////// -// CRY Stuff //////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////// -#include "Cry_Math.h" -#include -#include -#include -#include -#include - - -inline int RoundToClosestMB(size_t memSize) -{ - // add half a MB and shift down to get closest MB - return((int) ((memSize + (1 << 19)) >> 20)); -} - - -////////////////////////////////////////////////////////////////////////// -// For faster compilation -////////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include -#include -#include -#include -#include - -///////////////////////////////////////////////////////////////////////////// -//forward declarations for common Interfaces. -///////////////////////////////////////////////////////////////////////////// -class ITexture; -struct IRenderer; -struct ISystem; -struct ITimer; -struct IFFont; -struct ICVar; -struct IConsole; -struct IProcess; -namespace AZ::IO -{ - struct IArchive; -} -struct ICryFont; -struct IMovieSystem; -struct IAudioSystem; -struct IPhysicalWorld; - -#endif //__cplusplus - - - diff --git a/Code/CryEngine/CrySystem/DebugCallStack.cpp b/Code/CryEngine/CrySystem/DebugCallStack.cpp deleted file mode 100644 index 1b15bace16..0000000000 --- a/Code/CryEngine/CrySystem/DebugCallStack.cpp +++ /dev/null @@ -1,895 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "CrySystem_precompiled.h" -#include "DebugCallStack.h" - -#if defined(WIN32) || defined(WIN64) - -#include -#include -#include "System.h" - -#include -#include - -#define VS_VERSION_INFO 1 -#define IDD_CRITICAL_ERROR 101 -#define IDB_CONFIRM_SAVE 102 -#define IDB_DONT_SAVE 103 -#define IDD_CONFIRM_SAVE_LEVEL 127 -#define IDB_CRASH_FACE 128 -#define IDD_EXCEPTION 245 -#define IDC_CALLSTACK 1001 -#define IDC_EXCEPTION_CODE 1002 -#define IDC_EXCEPTION_ADDRESS 1003 -#define IDC_EXCEPTION_MODULE 1004 -#define IDC_EXCEPTION_DESC 1005 -#define IDB_EXIT 1008 -#define IDB_IGNORE 1010 -__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); - } - - 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"); - - 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); - - - cry_strcat(errs, "\nCall Stack Trace:\n"); - - std::vector funcs; - { - 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 (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 = MiniDumpNormal; - 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 0c00540409..0000000000 --- a/Code/CryEngine/CrySystem/DebugCallStack.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#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 deleted file mode 100644 index 1bc580c3f1..0000000000 --- a/Code/CryEngine/CrySystem/DllMain.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "CrySystem_precompiled.h" -#include "System.h" -#include -#include "DebugCallStack.h" - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define DLLMAIN_CPP_SECTION_1 1 -#define DLLMAIN_CPP_SECTION_2 2 -#define DLLMAIN_CPP_SECTION_3 3 -#define DLLMAIN_CPP_SECTION_4 4 -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION DLLMAIN_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(DllMain_cpp) -#endif - -// For lua debugger -//#include - -HMODULE gDLLHandle = NULL; - -#if !defined(AZ_MONOLITHIC_BUILD) && defined(AZ_HAS_DLL_SUPPORT) && AZ_TRAIT_LEGACY_CRYSYSTEM_DEFINE_DLLMAIN -AZ_PUSH_DISABLE_WARNING(4447, "-Wunknown-warning-option") -BOOL APIENTRY DllMain(HANDLE hModule, - DWORD ul_reason_for_call, - [[maybe_unused]] LPVOID lpReserved - ) -AZ_POP_DISABLE_WARNING -{ - PREVENT_MODULE_AND_ENVIRONMENT_SYMBOL_STRIPPING - - gDLLHandle = (HMODULE)hModule; - switch (ul_reason_for_call) - { - case DLL_PROCESS_ATTACH: - break; - case DLL_THREAD_ATTACH: - - - break; - case DLL_THREAD_DETACH: - case DLL_PROCESS_DETACH: - break; - } - // int sbh = _set_sbh_threshold(1016); - - return TRUE; -} -#endif - -extern "C" -{ -CRYSYSTEM_API ISystem* CreateSystemInterface(const SSystemInitParams& startupParams) -{ - CSystem* pSystem = NULL; - - // We must attach to the environment prior to allocating CSystem, as opposed to waiting - // for ModuleInitISystem(), because the log message sink uses buses. - // Environment should have been attached via InjectEnvironment - AZ_Assert(AZ::Environment::IsReady(), "Environment is not attached, must be attached before CreateSystemInterface can be called"); - - pSystem = new CSystem(startupParams.pSharedEnvironment); - ModuleInitISystem(pSystem, "CrySystem"); - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION DLLMAIN_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(DllMain_cpp) -#endif - - // the earliest point the system exists - w2e tell the callback - if (startupParams.pUserCallback) - { - startupParams.pUserCallback->OnSystemConnect(pSystem); - } - -#if defined(WIN32) - // 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"); - const bool handlerIsSet = (envVar && *envVar); - if (!handlerIsSet) - { - ((DebugCallStack*)IDebugCallStack::instance())->installErrorHandler(pSystem); - } -#endif - - bool retVal = false; - { - AZ::Debug::StartupLogSinkReporter initLogSink; - retVal = pSystem->Init(startupParams); - if (!retVal) - { - initLogSink.GetContainedLogSink().SetFatalMessageBox(); - } - } - if (!retVal) - { - delete pSystem; - gEnv = nullptr; - - return 0; - } - - return pSystem; -} -}; - diff --git a/Code/CryEngine/CrySystem/Huffman.cpp b/Code/CryEngine/CrySystem/Huffman.cpp deleted file mode 100644 index 96e68a9954..0000000000 --- a/Code/CryEngine/CrySystem/Huffman.cpp +++ /dev/null @@ -1,462 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "CrySystem_precompiled.h" -#include "Huffman.h" - - -void HuffmanCoder::BitStreamBuilder::AddBits(uint32 value, uint32 numBits) -{ - if (numBits > 24) - { - AddBits(static_cast((value >> 24) & 0x000000ff), numBits - 24); - numBits = 24; - } - if (numBits > 16) - { - AddBits(static_cast((value >> 16) & 0x000000ff), numBits - 16); - numBits = 16; - } - if (numBits > 8) - { - AddBits(static_cast((value >> 8) & 0x000000ff), numBits - 8); - numBits = 8; - } - AddBits(static_cast(value & 0x000000ff), numBits); -} - -void HuffmanCoder::BitStreamBuilder::AddBits(uint8 value, uint32 numBits) -{ - if (m_mode != eM_WRITE) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Trying to write to a read only BitStreamBuilder"); - return; - } - uint8 mask; - mask = (uint8)(1 << (numBits - 1)); - while (mask != 0) - { - //CryLogAlways("mask is %u", mask); - if (mask & value) - { - //CryLogAlways("Buffer value was %u", *m_pBufferCursor.ptr); - *(m_pBufferCursor.ptr) |= m_mask; - //CryLogAlways("Buffer value now %u", *m_pBufferCursor.ptr); - } - //CryLogAlways("m_mask was %u", m_mask); - m_mask = m_mask >> 1; - //CryLogAlways("m_mask now %u", m_mask); - if (m_mask == 0) - { - if (m_pBufferCursor.ptr == m_pBufferEnd.ptr) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Bit Stream has consumed the last byte of the buffer and is requesting another. This stream will be truncated here."); - return; - } - //CryLogAlways("Buffer cursor was %u (%p)", *m_pBufferCursor.ptr, m_pBufferCursor.ptr); - m_pBufferCursor.ptr++; - //CryLogAlways("Buffer cursor now %u (%p)", *m_pBufferCursor.ptr, m_pBufferCursor.ptr); - m_mask = 0x80; - } - mask = mask >> 1L; - } -} - -//Returns 1 or 0 for valid values. Returns 2 if the buffer has run out or is the wrong type of builder. -uint8 HuffmanCoder::BitStreamBuilder::GetBit() -{ - if (m_mode != eM_READ) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Trying to read from a write only BitStreamBuilder"); - return 2; - } - uint8 value = 0; - - if (m_mask == 0) - { - if (m_pBufferCursor.const_ptr == m_pBufferEnd.const_ptr) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Bit Stream has consumed the last byte of the buffer and is requesting another. This stream will be truncated here."); - return 2; - } - //CryLogAlways("Buffer cursor was %u (%p)", *m_pBufferCursor.const_ptr, m_pBufferCursor.const_ptr); - m_pBufferCursor.const_ptr++; - //CryLogAlways("Buffer cursor now %u (%p)", *m_pBufferCursor.const_ptr, m_pBufferCursor.const_ptr); - m_mask = 0x80; - } - if (m_mask & *(m_pBufferCursor.const_ptr)) - { - value = 1; - } - //CryLogAlways("m_mask was %u", m_mask); - m_mask = m_mask >> 1; - //CryLogAlways("m_mask now %u", m_mask); - - return value; -} - -void HuffmanCoder::Init() -{ - SAFE_DELETE_ARRAY(m_TreeNodes); - SAFE_DELETE_ARRAY(m_Codes); - m_Counts = new uint32[MAX_NUM_SYMBOLS]; - memset(m_Counts, 0, sizeof(uint32) * MAX_NUM_SYMBOLS); - m_State = eHCS_OPEN; -} - -//Adds the values of an array of chars to the counts -void HuffmanCoder::Update(const uint8* const pSource, const size_t numBytes) -{ - if (m_State != eHCS_OPEN) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Trying to update a Huffman Coder that has not been initialized, or has been finalized"); - return; - } - - size_t i; - for (i = 0; i < numBytes; i++) - { - const int symbol = pSource[i]; - m_Counts[symbol]++; - } -} - -void HuffmanCoder::Finalize() -{ - if (m_State != eHCS_OPEN) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Trying to finalize a Huffman Coder that has not been initialized, or has been finalized"); - return; - } - - //Construct the tree - m_TreeNodes = new HuffmanTreeNode[MAX_NUM_NODES]; - memset(m_TreeNodes, 0, sizeof(HuffmanTreeNode) * MAX_NUM_NODES); - m_Codes = new HuffmanSymbolCode[MAX_NUM_CODES]; - memset(m_Codes, 0, sizeof(HuffmanSymbolCode) * MAX_NUM_CODES); - - ScaleCountsAndUpdateNodes(); - m_RootNode = BuildTree(); - ConvertTreeToCode(m_TreeNodes, m_Codes, 0, 0, m_RootNode); - - //Finalize the coder so that it won't accept any more strings - m_State = eHCS_FINAL; - - //Counts are no longer needed - SAFE_DELETE_ARRAY(m_Counts); -} - -void HuffmanCoder::CompressInput(const uint8* const pInput, const size_t numBytes, uint8* const pOutput, size_t* const outputSize) -{ - BitStreamBuilder streamBuilder(pOutput, pOutput + (*outputSize)); - for (size_t i = 0; i < numBytes; i++) - { - const int symbol = pInput[i]; - const uint32 value = m_Codes[symbol].value; - const uint32 numBits = m_Codes[symbol].numBits; - /*char szBits[33]; - memset(szBits, '0', 33); - for( uint32 j = 0; j < numBits; j++ ) - { - if( (value & (uint32)(1< END_OF_STREAM); - - if (node == END_OF_STREAM) - { - pOutput[numOutputBytes] = '\0'; - break; - } - code = node; -#if 0 - { - CryLogAlways("%c", code); - if (code == '\0') - { - CryLogAlways("EOM"); - } - } -#endif - pOutput[numOutputBytes] = (char)code; - numOutputBytes++; - if (numOutputBytes >= maxOutputSize) - { - pOutput[maxOutputSize - 1] = '\0'; - break; - } - } - - return numOutputBytes; -} - -//Private functions - -void HuffmanCoder::ScaleCountsAndUpdateNodes() -{ - unsigned long maxCount = 0; - int i; - - for (i = 0; i < MAX_NUM_SYMBOLS; i++) - { - const unsigned long count = m_Counts[i]; - if (count > maxCount) - { - maxCount = count; - } - } - if (maxCount == 0) - { - m_Counts[0] = 1; - maxCount = 1; - } - maxCount = maxCount / MAX_NUM_SYMBOLS; - maxCount = maxCount + 1; - for (i = 0; i < MAX_NUM_SYMBOLS; i++) - { - const unsigned long count = m_Counts[i]; - unsigned int scaledCount = (unsigned int)(count / maxCount); - if ((scaledCount == 0) && (count != 0)) - { - scaledCount = 1; - } - m_TreeNodes[i].count = scaledCount; - m_TreeNodes[i].child0 = END_OF_STREAM; - m_TreeNodes[i].child1 = END_OF_STREAM; - } - m_TreeNodes[END_OF_STREAM].count = 1; - m_TreeNodes[END_OF_STREAM].child0 = END_OF_STREAM; - m_TreeNodes[END_OF_STREAM].child1 = END_OF_STREAM; -} - -//Jake's file IO code. Kept in case we make the compression and table generation an offline task -/* Format is: startSymbol, stopSymbol, count0, count1, count2, ... countN, ..., 0 */ -/* When finding the start, stop symbols only break out if find more than 3 0's in the counts */ -/*static void outputCounts(FILE* const pFile, const HuffmanTreeNode* const pNodes) -{ - int first = 0; - int last; - int next; - - while ((first < MAX_NUM_SYMBOLS) && (pNodes[first].count == 0)) - { - first++; - } - last = first; - next = first; - for (; first < MAX_NUM_SYMBOLS; first = next) - { - int i; - last = first+1; - while (1) - { - for (; last < MAX_NUM_SYMBOLS; last++) - { - if (pNodes[last].count == 0) - { - break; - } - } - last--; - for (next = last+1; next < MAX_NUM_SYMBOLS; next++) - { - if (pNodes[next].count != 0) - { - break; - } - } - if (next == MAX_NUM_SYMBOLS) - { - break; - } - if ((next-last) > 3) - { - break; - } - last = next; - } - putc(first, pFile); - putc(last, pFile); - for (i = first; i <= last; i++) - { - const unsigned int count = pNodes[i].count; - putc((int)count, pFile); - } - } - putc(0xFF, pFile); - putc(0xFF, pFile); - putc((int)(pNodes[0xFF].count), pFile); -}*/ - -/*static void inputCounts(FILE* const pFile, HuffmanTreeNode* const pNodes) -{ - while (1) - { - int i; - const int first = getc(pFile); - const int last = getc(pFile); - for (i = first; i <= last; i++) - { - const int count = getc(pFile); - pNodes[i].count = (size_t)count; - pNodes[i].child0 = END_OF_STREAM; - pNodes[i].child1 = END_OF_STREAM; - } - if ((first == last) && (first == 0xFF)) - { - break; - } - } - pNodes[END_OF_STREAM].count = 1; - pNodes[END_OF_STREAM].child0 = END_OF_STREAM; - pNodes[END_OF_STREAM].child1 = END_OF_STREAM; -}*/ - -int HuffmanCoder::BuildTree() -{ - int min1; - int min2; - int nextFree; - - m_TreeNodes[MAX_NODE].count = 0xFFFFFFF; - for (nextFree = END_OF_STREAM + 1;; nextFree++) - { - int i; - min1 = MAX_NODE; - min2 = MAX_NODE; - for (i = 0; i < nextFree; i++) - { - const unsigned int count = m_TreeNodes[i].count; - if (count != 0) - { - if (count < m_TreeNodes[min1].count) - { - min2 = min1; - min1 = i; - } - else if (count < m_TreeNodes[min2].count) - { - min2 = i; - } - } - } - if (min2 == MAX_NODE) - { - break; - } - m_TreeNodes[nextFree].count = m_TreeNodes[min1].count + m_TreeNodes[min2].count; - - m_TreeNodes[min1].savedCount = m_TreeNodes[min1].count; - m_TreeNodes[min1].count = 0; - - m_TreeNodes[min2].savedCount = m_TreeNodes[min2].count; - m_TreeNodes[min2].count = 0; - - m_TreeNodes[nextFree].child0 = min1; - m_TreeNodes[nextFree].child1 = min2; - m_TreeNodes[nextFree].savedCount = 0; - } - - nextFree--; - m_TreeNodes[nextFree].savedCount = m_TreeNodes[nextFree].count; - - return nextFree; -} - -void HuffmanCoder::ConvertTreeToCode(const HuffmanTreeNode* const pNodes, HuffmanSymbolCode* const pCodes, - const unsigned int value, const unsigned int numBits, const int node) -{ - unsigned int nextValue; - unsigned int nextNumBits; - if (node <= END_OF_STREAM) - { - pCodes[node].value = value; - pCodes[node].numBits = numBits; - return; - } - nextValue = value << 1; - nextNumBits = numBits + 1; - ConvertTreeToCode(pNodes, pCodes, nextValue, nextNumBits, pNodes[node].child0); - nextValue = nextValue | 0x1; - ConvertTreeToCode(pNodes, pCodes, nextValue, nextNumBits, pNodes[node].child1); -} - -/*static void printChar(const int c) -{ - if (c >= ' ' && c < 127) - { - printf("'%c'", c); - } - else - { - printf("0x%03X", c); - } -} - -static void printModel(const HuffmanTreeNode* const pNodes, const HuffmanSymbolCode* const pCodes) -{ - int i; - for (i = 0; i < MAX_NODE; i++) - { - const unsigned int count = pNodes[i].savedCount; - if (count != 0) - { - printf("node="); - printChar(i); - printf(" count=%3d", count); - printf(" child0="); - printChar(pNodes[i].child0); - printf(" child1="); - printChar(pNodes[i].child1); - if (pCodes && (i <= END_OF_STREAM)) - { - printf(" Huffman code="); - binaryFilePrint(stdout, pCodes[i].value, pCodes[i].numBits); - } - printf("\n"); - } - } -}*/ diff --git a/Code/CryEngine/CrySystem/Huffman.h b/Code/CryEngine/CrySystem/Huffman.h deleted file mode 100644 index 5d8876b063..0000000000 --- a/Code/CryEngine/CrySystem/Huffman.h +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYSYSTEM_HUFFMAN_H -#define CRYINCLUDE_CRYSYSTEM_HUFFMAN_H -#pragma once - - -class HuffmanCoder -{ -private: - struct HuffmanTreeNode - { - uint32 count; - uint32 savedCount; - int child0; - int child1; - }; - - struct HuffmanSymbolCode - { - uint32 value; - uint32 numBits; - }; - - struct BitStreamBuilder - { - enum EModes - { - eM_WRITE, - eM_READ - }; - union buf_ptr - { - uint8* ptr; - const uint8* const_ptr; - }; - EModes m_mode; - uint8 m_mask; - buf_ptr m_pBufferStart; - buf_ptr m_pBufferCursor; - buf_ptr m_pBufferEnd; //Pointer to the last byte in the buffer - - BitStreamBuilder(uint8* pBufferStart, uint8* pBufferEnd) - : m_mode(eM_WRITE) - , m_mask(0x80) - { - m_pBufferStart.ptr = pBufferStart; - m_pBufferCursor.ptr = pBufferStart; - m_pBufferEnd.ptr = pBufferEnd; - } - BitStreamBuilder(const uint8* pBufferStart, const uint8* pBufferEnd) - : m_mode(eM_READ) - , m_mask(0x80) - { - m_pBufferStart.const_ptr = pBufferStart; - m_pBufferCursor.const_ptr = pBufferStart; - m_pBufferEnd.const_ptr = pBufferEnd; - } - - void AddBits(uint32 value, uint32 numBits); - void AddBits(uint8 value, uint32 numBits); - //Returns 1 or 0 for valid values. Returns 2 if the buffer has run out or is the wrong type of builder. - uint8 GetBit(); - }; - - const static int MAX_SYMBOL_VALUE = (255); - const static int MAX_NUM_SYMBOLS = (MAX_SYMBOL_VALUE + 1); - const static int END_OF_STREAM = (MAX_NUM_SYMBOLS); - const static int MAX_NUM_CODES = (MAX_NUM_SYMBOLS + 1); - const static int MAX_NUM_NODES = (MAX_NUM_CODES * 2); - const static int MAX_NODE = (MAX_NUM_NODES - 1); - - enum EHuffmanCoderState - { - eHCS_NEW, //Has been created, Init not called - eHCS_OPEN, //Init has been called, tree not yet constructed. Can accept new data. - eHCS_FINAL //Finalize has been called. Can no longer accept data, but can encode/decode. - }; - - HuffmanTreeNode* m_TreeNodes; - HuffmanSymbolCode* m_Codes; - uint32* m_Counts; - int m_RootNode; - uint32 m_RefCount; - EHuffmanCoderState m_State; - -public: - HuffmanCoder() - : m_TreeNodes(NULL) - , m_Codes(NULL) - , m_Counts(NULL) - , m_State(eHCS_NEW) - , m_RootNode(0) - , m_RefCount(0) {} - ~HuffmanCoder() - { - SAFE_DELETE_ARRAY(m_TreeNodes); - SAFE_DELETE_ARRAY(m_Codes); - SAFE_DELETE_ARRAY(m_Counts); - } - - //A bit like an MD5 generator, has three phases. - //Clears the existing data - void Init(); - //Adds the values of an array of chars to the counts - void Update(const uint8* const pSource, const size_t numBytes); - //Construct the coding tree using the counts - void Finalize(); - - //We typically create a Huffman Coder per localized string table loaded. Since we can and do unload strings at runtime, it's useful to keep a ref count of each coder. - inline void AddRef() { m_RefCount++; } - inline void DecRef() { m_RefCount = m_RefCount > 0 ? m_RefCount - 1 : 0; } - inline uint32 RefCount() { return m_RefCount; } - - void CompressInput(const uint8* const pInput, const size_t numBytes, uint8* const pOutput, size_t* const outputSize); - size_t UncompressInput(const uint8* const pInput, const size_t numBytes, uint8* const pOutput, const size_t maxOutputSize); - - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - - if (m_Counts != NULL) - { - pSizer->AddObject(m_Counts, sizeof(uint32), MAX_NUM_SYMBOLS); - } - if (m_TreeNodes != NULL) - { - pSizer->AddObject(m_TreeNodes, sizeof(HuffmanTreeNode), MAX_NUM_NODES); - } - if (m_Codes != NULL) - { - pSizer->AddObject(m_Codes, sizeof(HuffmanSymbolCode), MAX_NUM_CODES); - } - } - -private: - void ScaleCountsAndUpdateNodes(); - int BuildTree(); - void ConvertTreeToCode(const HuffmanTreeNode* const pNodes, HuffmanSymbolCode* const pCodes, const unsigned int value, const unsigned int numBits, const int node); -}; - -#endif // CRYINCLUDE_CRYSYSTEM_HUFFMAN_H diff --git a/Code/CryEngine/CrySystem/IDebugCallStack.cpp b/Code/CryEngine/CrySystem/IDebugCallStack.cpp deleted file mode 100644 index edc9e21f40..0000000000 --- a/Code/CryEngine/CrySystem/IDebugCallStack.cpp +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : A multiplatform base class for handling errors and collecting call stacks - - -#include "CrySystem_precompiled.h" -#include "IDebugCallStack.h" -#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, ...) -{ - 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 2bc50051e7..0000000000 --- a/Code/CryEngine/CrySystem/IDebugCallStack.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// 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/LevelSystem/LevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp deleted file mode 100644 index 81da76177f..0000000000 --- a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp +++ /dev/null @@ -1,994 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// [LYN-2376] Remove the entire file once legacy slice support is removed - -#include "CrySystem_precompiled.h" -#include "LevelSystem.h" -#include -#include "IMovieSystem.h" -#include -#include "CryPath.h" - -#include - -#include -#include -#include -#include -#include -#include - -#include "MainThreadRenderRequestBus.h" -#include -#include -#include -#include - -#include - -#ifdef WIN32 -#include -#endif - -namespace LegacyLevelSystem -{ -static constexpr const char* ArchiveExtension = ".pak"; - -void CLevelInfo::GetMemoryUsage(ICrySizer* pSizer) const -{ - pSizer->AddObject(m_levelName); - pSizer->AddObject(m_levelPath); -} - -////////////////////////////////////////////////////////////////////////// -bool CLevelInfo::OpenLevelPak() -{ - LOADING_TIME_PROFILE_SECTION; - - bool usePrefabSystemForLevels = false; - AzFramework::ApplicationRequests::Bus::BroadcastResult( - usePrefabSystemForLevels, &AzFramework::ApplicationRequests::IsPrefabSystemForLevelsEnabled); - - // The prefab system doesn't use level.pak - if (usePrefabSystemForLevels) - { - return false; - } - - AZStd::string levelpak(m_levelPath); - levelpak += "/level.pak"; - AZStd::fixed_string fullLevelPakPath; - bool bOk = gEnv->pCryPak->OpenPack( - levelpak.c_str(), m_isPak ? AZ::IO::IArchive::FLAGS_LEVEL_PAK_INSIDE_PAK : (unsigned)0, NULL, &fullLevelPakPath, false); - m_levelPakFullPath.assign(fullLevelPakPath.c_str()); - return bOk; -} - -////////////////////////////////////////////////////////////////////////// -void CLevelInfo::CloseLevelPak() -{ - LOADING_TIME_PROFILE_SECTION; - - bool usePrefabSystemForLevels = false; - AzFramework::ApplicationRequests::Bus::BroadcastResult( - usePrefabSystemForLevels, &AzFramework::ApplicationRequests::IsPrefabSystemForLevelsEnabled); - - // The prefab system doesn't use level.pak - if (usePrefabSystemForLevels) - { - return; - } - - if (!m_levelPakFullPath.empty()) - { - gEnv->pCryPak->ClosePack(m_levelPakFullPath.c_str(), AZ::IO::IArchive::FLAGS_PATH_REAL); - m_levelPakFullPath.clear(); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CLevelInfo::ReadInfo() -{ - bool usePrefabSystemForLevels = false; - AzFramework::ApplicationRequests::Bus::BroadcastResult( - usePrefabSystemForLevels, &AzFramework::ApplicationRequests::IsPrefabSystemForLevelsEnabled); - - // Set up a default game type for legacy code. - m_defaultGameTypeName = "Mission0"; - - if (usePrefabSystemForLevels) - { - return true; - } - - - AZStd::string levelPath(m_levelPath); - AZStd::string xmlFile(levelPath); - xmlFile += "/LevelInfo.xml"; - XmlNodeRef rootNode = GetISystem()->LoadXmlFromFile(xmlFile.c_str()); - - if (rootNode) - { - AZStd::string dataFile(levelPath); - dataFile += "/LevelDataAction.xml"; - XmlNodeRef dataNode = GetISystem()->LoadXmlFromFile(dataFile.c_str()); - if (!dataNode) - { - dataFile = levelPath + "/LevelData.xml"; - dataNode = GetISystem()->LoadXmlFromFile(dataFile.c_str()); - } - - if (dataNode) - { - XmlNodeRef gameTypesNode = dataNode->findChild("Missions"); - - if ((gameTypesNode != 0) && (gameTypesNode->getChildCount() > 0)) - { - m_defaultGameTypeName.clear(); - - for (int i = 0; i < gameTypesNode->getChildCount(); i++) - { - XmlNodeRef gameTypeNode = gameTypesNode->getChild(i); - - if (gameTypeNode->isTag("Mission")) - { - const char* gameTypeName = gameTypeNode->getAttr("Name"); - - if (gameTypeName) - { - m_defaultGameTypeName = gameTypeName; - break; - } - } - } - } - } - } - return rootNode != 0; -} - -////////////////////////////////////////////////////////////////////////// - -/// Used by console auto completion. -struct SLevelNameAutoComplete - : public IConsoleArgumentAutoComplete -{ - AZStd::vector levels; - virtual int GetCount() const { return levels.size(); }; - virtual const char* GetValue(int nIndex) const { return levels[nIndex].c_str(); }; -}; -// definition and declaration must be separated for devirtualization -static StaticInstance> g_LevelNameAutoComplete; - -//------------------------------------------------------------------------ -static void LoadMap(IConsoleCmdArgs* args) -{ - if (gEnv->pSystem && gEnv->pSystem->GetILevelSystem() && !gEnv->IsEditor()) - { - if (args->GetArgCount() > 1) - { - gEnv->pSystem->GetILevelSystem()->UnloadLevel(); - gEnv->pSystem->GetILevelSystem()->LoadLevel(args->GetArg(1)); - } - } -} - -//------------------------------------------------------------------------ -static void UnloadMap([[maybe_unused]] IConsoleCmdArgs* args) -{ - if (gEnv->pSystem && gEnv->pSystem->GetILevelSystem() && !gEnv->IsEditor()) - { - gEnv->pSystem->GetILevelSystem()->UnloadLevel(); - } -} - -//------------------------------------------------------------------------ -CLevelSystem::CLevelSystem(ISystem* pSystem, const char* levelsFolder) - : m_pSystem(pSystem) - , m_pCurrentLevel(0) - , m_pLoadingLevelInfo(0) -{ - LOADING_TIME_PROFILE_SECTION; - CRY_ASSERT(pSystem); - - //if (!gEnv->IsEditor()) - Rescan(levelsFolder); - - m_fLastLevelLoadTime = 0; - m_fLastTime = 0; - m_bLevelLoaded = false; - - m_levelLoadStartTime.SetValue(0); - - m_nLoadedLevelsCount = 0; - - REGISTER_COMMAND("map", LoadMap, VF_BLOCKFRAME, "Load a map"); - REGISTER_COMMAND("unload", UnloadMap, 0, "Unload current map"); - gEnv->pConsole->RegisterAutoComplete("map", &(*g_LevelNameAutoComplete)); - - AZ_Assert(gEnv && gEnv->pCryPak, "gEnv and CryPak must be initialized for loading levels."); - if (!gEnv || !gEnv->pCryPak) - { - return; - } - auto pPak = gEnv->pCryPak; - - if (AZ::IO::IArchive::LevelPackOpenEvent* levelPakOpenEvent = pPak->GetLevelPackOpenEvent()) - { - m_levelPackOpenHandler = AZ::IO::IArchive::LevelPackOpenEvent::Handler([this](const AZStd::vector& levelDirs) - { - for (AZStd::string dir : levelDirs) - { - AZ::StringFunc::Path::StripComponent(dir, true); - AZStd::string searchPattern = dir + AZ_FILESYSTEM_SEPARATOR_WILDCARD; - bool modFolder = false; - PopulateLevels(searchPattern, dir, gEnv->pCryPak, modFolder, false); - } - }); - m_levelPackOpenHandler.Connect(*levelPakOpenEvent); - } - - if (AZ::IO::IArchive::LevelPackCloseEvent* levelPakCloseEvent = pPak->GetLevelPackCloseEvent()) - { - m_levelPackCloseHandler = AZ::IO::IArchive::LevelPackCloseEvent::Handler([this](AZStd::string_view) - { - Rescan(ILevelSystem::LevelsDirectoryName); - }); - m_levelPackCloseHandler.Connect(*levelPakCloseEvent); - } -} - -//------------------------------------------------------------------------ -CLevelSystem::~CLevelSystem() -{ -} - -//------------------------------------------------------------------------ -void CLevelSystem::Rescan(const char* levelsFolder) -{ - if (levelsFolder) - { - m_levelsFolder = levelsFolder; - } - - CRY_ASSERT(!m_levelsFolder.empty()); - m_levelInfos.clear(); - m_levelInfos.reserve(64); - ScanFolder(0, false); - - g_LevelNameAutoComplete->levels.clear(); - for (int i = 0; i < (int)m_levelInfos.size(); i++) - { - g_LevelNameAutoComplete->levels.push_back(AZStd::string(PathUtil::GetFileName(m_levelInfos[i].GetName()).c_str())); - } -} - -//----------------------------------------------------------------------- -void CLevelSystem::ScanFolder(const char* subfolder, bool modFolder) -{ - AZStd::string folder; - if (subfolder && subfolder[0]) - { - folder = subfolder; - } - - AZStd::string search(m_levelsFolder); - if (!folder.empty()) - { - if (AZ::StringFunc::StartsWith(folder.c_str(), m_levelsFolder.c_str())) - { - search = folder; - } - else - { - search += "/" + folder; - } - } - search += "/*"; - - AZ_Assert(gEnv && gEnv->pCryPak, "gEnv and must be initialized for loading levels."); - if (!gEnv || !gEnv->pCryPak) - { - return; - } - auto pPak = gEnv->pCryPak; - - AZStd::unordered_set pakList; - - const bool allowFileSystem = true; - const uint32_t skipPakFiles = 1; - AZ::IO::ArchiveFileIterator handle = pPak->FindFirst(search.c_str(), AZ::IO::IArchive::eFileSearchType_AllowOnDiskOnly); - - if (handle) - { - do - { - AZStd::string extension; - AZStd::string levelName; - AZ::StringFunc::Path::Split(handle.m_filename.data(), nullptr, nullptr, &levelName, &extension); - if (extension == ArchiveExtension) - { - if (AZ::StringFunc::Equal(handle.m_filename.data(), LevelPakName)) - { - // level folder contain pak files like 'level.pak' - // which we only want to load during level loading. - continue; - } - - AZStd::string levelContainerPakPath; - AZ::StringFunc::Path::Join("@assets@", m_levelsFolder.c_str(), levelContainerPakPath); - if (subfolder && subfolder[0]) - { - AZ::StringFunc::Path::Join(levelContainerPakPath.c_str(), subfolder, levelContainerPakPath); - } - AZ::StringFunc::Path::Join(levelContainerPakPath.c_str(), handle.m_filename.data(), levelContainerPakPath); - pakList.emplace(levelContainerPakPath); - continue; - } - } while (handle = pPak->FindNext(handle)); - - pPak->FindClose(handle); - } - - // Open all the available paks found in the levels folder - for (auto iter = pakList.begin(); iter != pakList.end(); iter++) - { - AZStd::fixed_string fullLevelPakPath; - gEnv->pCryPak->OpenPack(iter->c_str(), (unsigned)0, nullptr, &fullLevelPakPath, false); - } - - // Levels in bundles now take priority over levels outside of bundles. - PopulateLevels(search, folder, pPak, modFolder, false); - // Load levels outside of the bundles to maintain backward compatibility. - PopulateLevels(search, folder, pPak, modFolder, true); - -} - -void CLevelSystem::PopulateLevels( - AZStd::string searchPattern, AZStd::string& folder, AZ::IO::IArchive* pPak, bool& modFolder, bool fromFileSystemOnly) -{ - { - // allow this find first to actually touch the file system - // (causes small overhead but with minimal amount of levels this should only be around 150ms on actual DVD Emu) - AZ::IO::ArchiveFileIterator handle = pPak->FindFirst(searchPattern.c_str(), AZ::IO::IArchive::eFileSearchType_AllowOnDiskOnly); - - if (handle) - { - do - { - if ((handle.m_fileDesc.nAttrib & AZ::IO::FileDesc::Attribute::Subdirectory) != AZ::IO::FileDesc::Attribute::Subdirectory || - handle.m_filename == "." || handle.m_filename == "..") - { - continue; - } - - AZStd::string levelFolder; - if (fromFileSystemOnly) - { - levelFolder = - (folder.empty() ? "" : (folder + "/")) + AZStd::string(handle.m_filename.data(), handle.m_filename.size()); - } - else - { - AZStd::string levelName(AZ::IO::PathView(handle.m_filename).Filename().Native()); - levelFolder = (folder.empty() ? "" : (folder + "/")) + levelName; - } - - AZStd::string levelPath; - if (AZ::StringFunc::StartsWith(levelFolder.c_str(), m_levelsFolder.c_str())) - { - levelPath = levelFolder; - } - else - { - levelPath = m_levelsFolder + "/" + levelFolder; - } - - const AZStd::string levelPakName = levelPath + "/" + LevelPakName; - const AZStd::string levelInfoName = levelPath + "/levelinfo.xml"; - - if (!pPak->IsFileExist( - levelPakName.c_str(), - fromFileSystemOnly ? AZ::IO::IArchive::eFileLocation_OnDisk : AZ::IO::IArchive::eFileLocation_InPak) && - !pPak->IsFileExist( - levelInfoName.c_str(), - fromFileSystemOnly ? AZ::IO::IArchive::eFileLocation_OnDisk : AZ::IO::IArchive::eFileLocation_InPak)) - { - ScanFolder(levelFolder.c_str(), modFolder); - continue; - } - - // With the level.pak workflow, levelPath and levelName will point to a directory. - // levelPath: levels/mylevel - // levelName: mylevel - CLevelInfo levelInfo; - levelInfo.m_levelPath = levelPath; - levelInfo.m_levelName = levelFolder; - levelInfo.m_isPak = !fromFileSystemOnly; - - CLevelInfo* pExistingInfo = GetLevelInfoInternal(levelInfo.m_levelName); - - // Don't add the level if it is already in the list - if (pExistingInfo == NULL) - { - m_levelInfos.push_back(levelInfo); - } - else - { - // Levels in bundles take priority over levels outside bundles. - if (!pExistingInfo->m_isPak && levelInfo.m_isPak) - { - *pExistingInfo = levelInfo; - } - } - } while (handle = pPak->FindNext(handle)); - - pPak->FindClose(handle); - } - } -} - -//------------------------------------------------------------------------ -int CLevelSystem::GetLevelCount() -{ - return (int)m_levelInfos.size(); -} - -//------------------------------------------------------------------------ -ILevelInfo* CLevelSystem::GetLevelInfo(int level) -{ - return GetLevelInfoInternal(level); -} - -//------------------------------------------------------------------------ -CLevelInfo* CLevelSystem::GetLevelInfoInternal(int level) -{ - if ((level >= 0) && (level < GetLevelCount())) - { - return &m_levelInfos[level]; - } - - return 0; -} - -//------------------------------------------------------------------------ -ILevelInfo* CLevelSystem::GetLevelInfo(const char* levelName) -{ - return GetLevelInfoInternal(levelName); -} - -//------------------------------------------------------------------------ -CLevelInfo* CLevelSystem::GetLevelInfoInternal(const AZStd::string& levelName) -{ - // If level not found by full name try comparing with only filename - for (AZStd::vector::iterator it = m_levelInfos.begin(); it != m_levelInfos.end(); ++it) - { - if (!azstricmp(it->GetName(), levelName.c_str())) - { - return &(*it); - } - } - - ////////////////////////////////////////////////////////////////////////// - for (AZStd::vector::iterator it = m_levelInfos.begin(); it != m_levelInfos.end(); ++it) - { - { - if (!azstricmp(PathUtil::GetFileName(it->GetName()), levelName.c_str())) - { - return &(*it); - } - } - } - - // Try stripping out the folder to find the raw filename - AZStd::string sLevelName(levelName); - size_t lastSlash = sLevelName.find_last_of('\\'); - if (lastSlash == AZStd::string::npos) - { - lastSlash = sLevelName.find_last_of('/'); - } - if (lastSlash != AZStd::string::npos) - { - sLevelName = sLevelName.substr(lastSlash + 1, sLevelName.size() - lastSlash - 1); - return GetLevelInfoInternal(sLevelName.c_str()); - } - - return 0; -} - -//------------------------------------------------------------------------ -void CLevelSystem::AddListener(ILevelSystemListener* pListener) -{ - AZStd::vector::iterator it = AZStd::find(m_listeners.begin(), m_listeners.end(), pListener); - - if (it == m_listeners.end()) - { - m_listeners.reserve(12); - m_listeners.push_back(pListener); - } -} - -//------------------------------------------------------------------------ -void CLevelSystem::RemoveListener(ILevelSystemListener* pListener) -{ - AZStd::vector::iterator it = AZStd::find(m_listeners.begin(), m_listeners.end(), pListener); - - if (it != m_listeners.end()) - { - m_listeners.erase(it); - - if (m_listeners.empty()) - { - m_listeners.shrink_to_fit(); - } - } -} - -//------------------------------------------------------------------------ -bool CLevelSystem::LoadLevel(const char* _levelName) -{ - if (gEnv->IsEditor()) - { - AZ_TracePrintf("CrySystem::CLevelSystem", "LoadLevel for %s was called in the editor - not actually loading.\n", _levelName); - return false; - } - - // If a level is currently loaded, unload it before loading the next one. - if (IsLevelLoaded()) - { - UnloadLevel(); - } - - gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_LOAD_PREPARE, 0, 0); - PrepareNextLevel(_levelName); - - ILevel* level = LoadLevelInternal(_levelName); - if (level) - { - OnLoadingComplete(_levelName); - } - - return (level != nullptr); -} -//------------------------------------------------------------------------ -ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) -{ - gEnv->pSystem->SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START); - AZ_ASSET_NAMED_SCOPE("Level: %s", _levelName); - - CryLog ("Level system is loading \"%s\"", _levelName); - INDENT_LOG_DURING_SCOPE(); - - char levelName[256]; - cry_strcpy(levelName, _levelName); - - // Not remove a scope!!! - { - LOADING_TIME_PROFILE_SECTION; - - //m_levelLoadStartTime = gEnv->pTimer->GetAsyncTime(); - - CLevelInfo* pLevelInfo = GetLevelInfoInternal(levelName); - - if (!pLevelInfo) - { - // alert the listener - OnLevelNotFound(levelName); - - return 0; - } - - m_bLevelLoaded = false; - - const bool bLoadingSameLevel = azstricmp(m_lastLevelName.c_str(), levelName) == 0; - m_lastLevelName = levelName; - - delete m_pCurrentLevel; - CLevel* pLevel = new CLevel(); - pLevel->m_levelInfo = *pLevelInfo; - m_pCurrentLevel = pLevel; - - ////////////////////////////////////////////////////////////////////////// - // Read main level info. - if (!pLevelInfo->ReadInfo()) - { - OnLoadingError(levelName, "Failed to read level info (level.pak might be corrupted)!"); - return 0; - } - //[AlexMcC|19.04.10]: Update the level's LevelInfo - pLevel->m_levelInfo = *pLevelInfo; - ////////////////////////////////////////////////////////////////////////// - - gEnv->pConsole->SetScrollMax(600); - ICVar* con_showonload = gEnv->pConsole->GetCVar("con_showonload"); - if (con_showonload && con_showonload->GetIVal() != 0) - { - gEnv->pConsole->ShowConsole(true); - ICVar* g_enableloadingscreen = gEnv->pConsole->GetCVar("g_enableloadingscreen"); - if (g_enableloadingscreen) - { - g_enableloadingscreen->Set(0); - } - } - - // Reset the camera to (1,1,1) (not (0,0,0) which is the invalid/uninitialised state, - // to avoid the hack in the renderer to not show anything if the camera is at the origin). - CCamera defaultCam; - defaultCam.SetPosition(Vec3(1.0f)); - m_pSystem->SetViewCamera(defaultCam); - - m_pLoadingLevelInfo = pLevelInfo; - OnLoadingStart(levelName); - - - auto pPak = gEnv->pCryPak; - - AZStd::string levelPath(pLevelInfo->GetPath()); - - ICVar* pSpamDelay = gEnv->pConsole->GetCVar("log_SpamDelay"); - float spamDelay = 0.0f; - if (pSpamDelay) - { - spamDelay = pSpamDelay->GetFVal(); - pSpamDelay->Set(0.0f); - } - - // Parse level specific config data. - AZStd::string const sLevelNameOnly(PathUtil::GetFileName(levelName)); - - if (!sLevelNameOnly.empty()) - { - const char* controlsPath = nullptr; - Audio::AudioSystemRequestBus::BroadcastResult(controlsPath, &Audio::AudioSystemRequestBus::Events::GetControlsPath); - if (controlsPath) - { - AZStd::string sAudioLevelPath(controlsPath); - sAudioLevelPath.append("levels/"); - sAudioLevelPath += sLevelNameOnly; - - Audio::SAudioManagerRequestData oAMData(sAudioLevelPath.c_str(), Audio::eADS_LEVEL_SPECIFIC); - Audio::SAudioRequest oAudioRequestData; - oAudioRequestData.nFlags = (Audio::eARF_PRIORITY_HIGH | Audio::eARF_EXECUTE_BLOCKING); // Needs to be blocking so data is available for next preloading request! - oAudioRequestData.pData = &oAMData; - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); - - Audio::SAudioManagerRequestData oAMData2(sAudioLevelPath.c_str(), Audio::eADS_LEVEL_SPECIFIC); - oAudioRequestData.pData = &oAMData2; - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); - - Audio::TAudioPreloadRequestID nPreloadRequestID = INVALID_AUDIO_PRELOAD_REQUEST_ID; - - Audio::AudioSystemRequestBus::BroadcastResult(nPreloadRequestID, &Audio::AudioSystemRequestBus::Events::GetAudioPreloadRequestID, sLevelNameOnly.c_str()); - if (nPreloadRequestID != INVALID_AUDIO_PRELOAD_REQUEST_ID) - { - Audio::SAudioManagerRequestData requestData(nPreloadRequestID, true); - oAudioRequestData.pData = &requestData; - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); - } - } - } - - { - AZStd::string missionXml("Mission_"); - missionXml += pLevelInfo->m_defaultGameTypeName; - missionXml += ".xml"; - AZStd::string xmlFile(pLevelInfo->GetPath()); - xmlFile += "/"; - xmlFile += missionXml; - - if (!gEnv->IsEditor()) - { - AZStd::string entitiesFilename = - AZStd::string::format("%s/%s.entities_xml", pLevelInfo->GetPath(), pLevelInfo->m_defaultGameTypeName.c_str()); - AZStd::vector fileBuffer; - CCryFile entitiesFile; - if (entitiesFile.Open(entitiesFilename.c_str(), "rt")) - { - fileBuffer.resize(entitiesFile.GetLength()); - - if (fileBuffer.size() == entitiesFile.ReadRaw(fileBuffer.begin(), fileBuffer.size())) - { - AZ::IO::ByteContainerStream> fileStream(&fileBuffer); - EBUS_EVENT(AzFramework::GameEntityContextRequestBus, LoadFromStream, fileStream, false); - } - } - } - } - - ////////////////////////////////////////////////////////////////////////// - // Movie system must be reset after entities. - ////////////////////////////////////////////////////////////////////////// - IMovieSystem* movieSys = gEnv->pMovieSystem; - if (movieSys != NULL) - { - // bSeekAllToStart needs to be false here as it's only of interest in the editor - movieSys->Reset(true, false); - } - - gEnv->pSystem->SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_PRECACHE); - - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - gEnv->pConsole->SetScrollMax(600 / 2); - - pPak->GetResourceList(AZ::IO::IArchive::RFOM_NextLevel)->Clear(); - - if (pSpamDelay) - { - pSpamDelay->Set(spamDelay); - } - - m_bLevelLoaded = true; - gEnv->pSystem->SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_END); - } - - GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_LOAD_END, 0, 0); - - if (auto cvar = gEnv->pConsole->GetCVar("sv_map"); cvar) - { - cvar->Set(levelName); - } - - gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_START, 0, 0); - - return m_pCurrentLevel; -} - -//------------------------------------------------------------------------ -void CLevelSystem::PrepareNextLevel(const char* levelName) -{ - CLevelInfo* pLevelInfo = GetLevelInfoInternal(levelName); - if (!pLevelInfo) - { - // alert the listener - OnLevelNotFound(levelName); - return; - } - - // This work not required in-editor. - if (!gEnv || !gEnv->IsEditor()) - { - m_levelLoadStartTime = gEnv->pTimer->GetAsyncTime(); - - // Open pak file for a new level. - pLevelInfo->OpenLevelPak(); - - // switched to level heap, so now imm start the loading screen (renderer will be reinitialized in the levelheap) - gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_LOAD_START_LOADINGSCREEN, 0, 0); - gEnv->pSystem->SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_PREPARE); - } - - for (AZStd::vector::const_iterator it = m_listeners.begin(); it != m_listeners.end(); ++it) - { - (*it)->OnPrepareNextLevel(pLevelInfo->GetName()); - } -} - -//------------------------------------------------------------------------ -void CLevelSystem::OnLevelNotFound(const char* levelName) -{ - for (AZStd::vector::const_iterator it = m_listeners.begin(); it != m_listeners.end(); ++it) - { - (*it)->OnLevelNotFound(levelName); - } -} - -//------------------------------------------------------------------------ -void CLevelSystem::OnLoadingStart(const char* levelName) -{ - if (gEnv->pCryPak->GetRecordFileOpenList() == AZ::IO::IArchive::RFOM_EngineStartup) - { - gEnv->pCryPak->RecordFileOpen(AZ::IO::IArchive::RFOM_Level); - } - - m_fLastTime = gEnv->pTimer->GetAsyncCurTime(); - - GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_LOAD_START, 0, 0); - - LOADING_TIME_PROFILE_SECTION(gEnv->pSystem); - - for (AZStd::vector::const_iterator it = m_listeners.begin(); it != m_listeners.end(); ++it) - { - (*it)->OnLoadingStart(levelName); - } -} - -//------------------------------------------------------------------------ -void CLevelSystem::OnLoadingError(const char* levelName, const char* error) -{ - ILevelInfo* pLevelInfo = m_pLoadingLevelInfo; - if (!pLevelInfo) - { - CRY_ASSERT(false); - return; - } - - for (AZStd::vector::const_iterator it = m_listeners.begin(); it != m_listeners.end(); ++it) - { - (*it)->OnLoadingError(levelName, error); - } - - ((CLevelInfo*)pLevelInfo)->CloseLevelPak(); -} - -//------------------------------------------------------------------------ -void CLevelSystem::OnLoadingComplete(const char* levelName) -{ - CTimeValue t = gEnv->pTimer->GetAsyncTime(); - m_fLastLevelLoadTime = (t - m_levelLoadStartTime).GetSeconds(); - - LogLoadingTime(); - - m_nLoadedLevelsCount++; - - // Hide console after loading. - gEnv->pConsole->ShowConsole(false); - - for (AZStd::vector::const_iterator it = m_listeners.begin(); it != m_listeners.end(); ++it) - { - (*it)->OnLoadingComplete(levelName); - } - -#if AZ_LOADSCREENCOMPONENT_ENABLED - EBUS_EVENT(LoadScreenBus, Stop); -#endif // if AZ_LOADSCREENCOMPONENT_ENABLED -} - -//------------------------------------------------------------------------ -void CLevelSystem::OnLoadingProgress(const char* levelName, int progressAmount) -{ - for (AZStd::vector::const_iterator it = m_listeners.begin(); it != m_listeners.end(); ++it) - { - (*it)->OnLoadingProgress(levelName, progressAmount); - } -} - -//------------------------------------------------------------------------ -void CLevelSystem::OnUnloadComplete(const char* levelName) -{ - for (AZStd::vector::const_iterator it = m_listeners.begin(); it != m_listeners.end(); ++it) - { - (*it)->OnUnloadComplete(levelName); - } -} - -////////////////////////////////////////////////////////////////////////// -void CLevelSystem::LogLoadingTime() -{ - if (gEnv->IsEditor()) - { - return; - } - - if (!GetISystem()->IsDevMode()) - { - return; - } - - char vers[128]; - GetISystem()->GetFileVersion().ToString(vers, sizeof(vers)); - - const char* sChain = ""; - if (m_nLoadedLevelsCount > 0) - { - sChain = " (Chained)"; - } - - AZStd::string text; - text.format("Game Level Load Time: [%s] Level %s loaded in %.2f seconds%s", vers, m_lastLevelName.c_str(), m_fLastLevelLoadTime, sChain); - gEnv->pLog->Log(text.c_str()); -} - -void CLevelSystem::GetMemoryUsage(ICrySizer* pSizer) const -{ - pSizer->AddObject(this, sizeof(*this)); - pSizer->AddObject(m_levelInfos); - pSizer->AddObject(m_levelsFolder); - pSizer->AddObject(m_listeners); -} - -////////////////////////////////////////////////////////////////////////// -void CLevelSystem::UnloadLevel() -{ - if (gEnv->IsEditor()) - { - return; - } - if (!m_pLoadingLevelInfo) - { - return; - } - - CryLog("UnloadLevel Start"); - INDENT_LOG_DURING_SCOPE(); - - // Flush core buses. We're about to unload Cry modules and need to ensure we don't have module-owned functions left behind. - AZ::Data::AssetBus::ExecuteQueuedEvents(); - AZ::TickBus::ExecuteQueuedEvents(); - AZ::MainThreadRenderRequestBus::ExecuteQueuedEvents(); - - if (gEnv && gEnv->pSystem) - { - // clear all error messages to prevent stalling due to runtime file access check during chainloading - gEnv->pSystem->ClearErrorMessages(); - } - - if (gEnv && gEnv->pCryPak) - { - gEnv->pCryPak->DisableRuntimeFileAccess(false); - } - - CTimeValue tBegin = gEnv->pTimer->GetAsyncTime(); - - // Clear level entities and prefab instances. - EBUS_EVENT(AzFramework::GameEntityContextRequestBus, ResetGameContext); - - if (gEnv->pMovieSystem) - { - gEnv->pMovieSystem->Reset(false, false); - gEnv->pMovieSystem->RemoveAllSequences(); - } - - // Unload level specific audio binary data. - Audio::SAudioManagerRequestData oAMData(Audio::eADS_LEVEL_SPECIFIC); - Audio::SAudioRequest oAudioRequestData; - oAudioRequestData.nFlags = (Audio::eARF_PRIORITY_HIGH | Audio::eARF_EXECUTE_BLOCKING); - oAudioRequestData.pData = &oAMData; - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); - - // Now unload level specific audio config data. - Audio::SAudioManagerRequestData oAMData2(Audio::eADS_LEVEL_SPECIFIC); - oAudioRequestData.pData = &oAMData2; - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); - - Audio::SAudioManagerRequestData oAMData3(Audio::eADS_LEVEL_SPECIFIC); - oAudioRequestData.pData = &oAMData3; - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); - - // Reset the camera to (0,0,0) which is the invalid/uninitialised state - CCamera defaultCam; - m_pSystem->SetViewCamera(defaultCam); - - OnUnloadComplete(m_lastLevelName.c_str()); - - // -- kenzo: this will close all pack files for this level - // (even the ones which were not added through here, if this is not desired, - // then change code to close only level.pak) - if (m_pLoadingLevelInfo) - { - ((CLevelInfo*)m_pLoadingLevelInfo)->CloseLevelPak(); - m_pLoadingLevelInfo = NULL; - } - - m_lastLevelName.clear(); - - SAFE_RELEASE(m_pCurrentLevel); - - // Force Lua garbage collection (may no longer be needed now the legacy renderer has been removed). - // Normally the GC step is triggered at the end of this method (by the ESYSTEM_EVENT_LEVEL_POST_UNLOAD event). - EBUS_EVENT(AZ::ScriptSystemRequestBus, GarbageCollect); - - // Perform level unload procedures for the LyShine UI system - if (gEnv && gEnv->pLyShine) - { - gEnv->pLyShine->OnLevelUnload(); - } - - m_bLevelLoaded = false; - - CTimeValue tUnloadTime = gEnv->pTimer->GetAsyncTime() - tBegin; - CryLog("UnloadLevel End: %.1f sec", tUnloadTime.GetSeconds()); - - // Must be sent last. - // Cleanup all containers - GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_POST_UNLOAD, 0, 0); - AzFramework::InputChannelRequestBus::Broadcast(&AzFramework::InputChannelRequests::ResetState); -} - -} // namespace LegacyLevelSystem diff --git a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.h b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.h deleted file mode 100644 index 1e46c76915..0000000000 --- a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.h +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include "ILevelSystem.h" -#include - -// [LYN-2376] Remove the entire file once legacy slice support is removed - -namespace LegacyLevelSystem -{ - -class CLevelInfo - : public ILevelInfo -{ - friend class CLevelSystem; -public: - CLevelInfo() = default; - - // ILevelInfo - virtual const char* GetName() const { return m_levelName.c_str(); } - virtual const char* GetPath() const { return m_levelPath.c_str(); } - virtual const char* GetAssetName() const { return m_levelAssetName.c_str(); } - // ~ILevelInfo - - - void GetMemoryUsage(ICrySizer*) const; - -private: - bool ReadInfo(); - - bool OpenLevelPak(); - void CloseLevelPak(); - - AZStd::string m_defaultGameTypeName; - AZStd::string m_levelName; - AZStd::string m_levelPath; - AZStd::string m_levelAssetName; - - AZStd::string m_levelPakFullPath; - - bool m_isPak = false; -}; - -struct ILevel -{ - virtual ~ILevel() = default; - virtual void Release() = 0; - virtual ILevelInfo* GetLevelInfo() = 0; -}; - -class CLevel - : public ILevel -{ - friend class CLevelSystem; -public: - CLevel() {} - virtual ~CLevel() = default; - - virtual void Release() { delete this; } - - virtual ILevelInfo* GetLevelInfo() { return &m_levelInfo; } - -private: - CLevelInfo m_levelInfo; -}; - -class CLevelSystem - : public ILevelSystem -{ -public: - CLevelSystem(ISystem* pSystem, const char* levelsFolder); - virtual ~CLevelSystem(); - - void Release() { delete this; }; - - // ILevelSystem - virtual void Rescan(const char* levelsFolder); - virtual int GetLevelCount(); - virtual ILevelInfo* GetLevelInfo(int level); - virtual ILevelInfo* GetLevelInfo(const char* levelName); - - virtual void AddListener(ILevelSystemListener* pListener); - virtual void RemoveListener(ILevelSystemListener* pListener); - - virtual bool LoadLevel(const char* levelName); - virtual void UnloadLevel(); - virtual bool IsLevelLoaded() { return m_bLevelLoaded; } - const char* GetCurrentLevelName() const override - { - if (m_pCurrentLevel && m_pCurrentLevel->GetLevelInfo()) - { - return m_pCurrentLevel->GetLevelInfo()->GetName(); - } - else - { - return ""; - } - } - - // If the level load failed then we need to have a different shutdown procedure vs when a level is naturally unloaded - virtual void SetLevelLoadFailed(bool loadFailed) { m_levelLoadFailed = loadFailed; } - virtual bool GetLevelLoadFailed() { return m_levelLoadFailed; } - - // Unsupported by legacy level system. - virtual AZ::Data::AssetType GetLevelAssetType() const { return {}; } - - // ~ILevelSystem - - void GetMemoryUsage(ICrySizer* s) const; - -private: - - float GetLastLevelLoadTime() { return m_fLastLevelLoadTime; } - - void ScanFolder(const char* subfolder, bool modFolder); - void PopulateLevels( - AZStd::string searchPattern, AZStd::string& folder, AZ::IO::IArchive* pPak, bool& modFolder, bool fromFileSystemOnly); - void PrepareNextLevel(const char* levelName); - ILevel* LoadLevelInternal(const char* _levelName); - - // Methods to notify ILevelSystemListener - void OnLevelNotFound(const char* levelName); - void OnLoadingStart(const char* levelName); - void OnLoadingComplete(const char* levelName); - void OnLoadingError(const char* levelName, const char* error); - void OnLoadingProgress(const char* levelName, int progressAmount); - void OnUnloadComplete(const char* levelName); - - void LogLoadingTime(); - bool LoadLevelInfo(CLevelInfo& levelInfo); - - // internal get functions for the level infos ... they preserve the type and don't - // directly cast to the interface - CLevelInfo* GetLevelInfoInternal(int level); - CLevelInfo* GetLevelInfoInternal(const AZStd::string& levelName); - - ISystem* m_pSystem; - AZStd::vector m_levelInfos; - AZStd::string m_levelsFolder; - ILevel* m_pCurrentLevel; - ILevelInfo* m_pLoadingLevelInfo; - - AZStd::string m_lastLevelName; - float m_fLastLevelLoadTime; - float m_fLastTime; - - bool m_bLevelLoaded; - bool m_levelLoadFailed = false; - - int m_nLoadedLevelsCount; - - CTimeValue m_levelLoadStartTime; - - AZStd::vector m_listeners; - - AZ::IO::IArchive::LevelPackOpenEvent::Handler m_levelPackOpenHandler; - AZ::IO::IArchive::LevelPackCloseEvent::Handler m_levelPackCloseHandler; - - static constexpr const char* LevelPakName = "level.pak"; -}; - -} // namespace LegacyLevelSystem diff --git a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp deleted file mode 100644 index 803b34d0d5..0000000000 --- a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp +++ /dev/null @@ -1,595 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include "CrySystem_precompiled.h" -#include "SpawnableLevelSystem.h" -#include -#include "IMovieSystem.h" - -#include - -#include -#include -#include -#include -#include - -#include "MainThreadRenderRequestBus.h" -#include -#include -#include -#include - -#include - -namespace LegacyLevelSystem -{ - //------------------------------------------------------------------------ - static void LoadLevel(const AZ::ConsoleCommandContainer& arguments) - { - AZ_Error("SpawnableLevelSystem", !arguments.empty(), "LoadLevel requires a level file name to be provided."); - AZ_Error("SpawnableLevelSystem", arguments.size() == 1, "LoadLevel requires a single level file name to be provided."); - - if (!arguments.empty() && gEnv->pSystem && gEnv->pSystem->GetILevelSystem() && !gEnv->IsEditor()) - { - gEnv->pSystem->GetILevelSystem()->LoadLevel(arguments[0].data()); - } - } - - //------------------------------------------------------------------------ - static void UnloadLevel([[maybe_unused]] const AZ::ConsoleCommandContainer& arguments) - { - AZ_Warning("SpawnableLevelSystem", !arguments.empty(), "UnloadLevel doesn't use any arguments."); - - if (gEnv->pSystem && gEnv->pSystem->GetILevelSystem() && !gEnv->IsEditor()) - { - gEnv->pSystem->GetILevelSystem()->UnloadLevel(); - } - } - - AZ_CONSOLEFREEFUNC(LoadLevel, AZ::ConsoleFunctorFlags::Null, "Unloads the current level and loads a new one with the given asset name"); - AZ_CONSOLEFREEFUNC(UnloadLevel, AZ::ConsoleFunctorFlags::Null, "Unloads the current level"); - - //------------------------------------------------------------------------ - SpawnableLevelSystem::SpawnableLevelSystem(ISystem* pSystem) - : m_pSystem(pSystem) - { - LOADING_TIME_PROFILE_SECTION; - CRY_ASSERT(pSystem); - - m_fLastLevelLoadTime = 0; - m_fLastTime = 0; - m_bLevelLoaded = false; - - m_levelLoadStartTime.SetValue(0); - m_nLoadedLevelsCount = 0; - - AZ_Assert(gEnv && gEnv->pCryPak, "gEnv and CryPak must be initialized for loading levels."); - if (!gEnv || !gEnv->pCryPak) - { - return; - } - - AzFramework::RootSpawnableNotificationBus::Handler::BusConnect(); - } - - //------------------------------------------------------------------------ - SpawnableLevelSystem::~SpawnableLevelSystem() - { - AzFramework::RootSpawnableNotificationBus::Handler::BusDisconnect(); - } - - void SpawnableLevelSystem::Release() - { - delete this; - } - - bool SpawnableLevelSystem::IsLevelLoaded() - { - return m_bLevelLoaded; - } - - const char* SpawnableLevelSystem::GetCurrentLevelName() const - { - return m_bLevelLoaded ? m_lastLevelName.c_str() : ""; - } - - // If the level load failed then we need to have a different shutdown procedure vs when a level is naturally unloaded - void SpawnableLevelSystem::SetLevelLoadFailed(bool loadFailed) - { - m_levelLoadFailed = loadFailed; - } - - bool SpawnableLevelSystem::GetLevelLoadFailed() - { - return m_levelLoadFailed; - } - - AZ::Data::AssetType SpawnableLevelSystem::GetLevelAssetType() const - { - return azrtti_typeid(); - } - - // The following methods are deprecated from ILevelSystem and will be removed once slice support is removed. - - // [LYN-2376] Remove once legacy slice support is removed - void SpawnableLevelSystem::Rescan([[maybe_unused]] const char* levelsFolder) - { - AZ_Assert(false, "Rescan - No longer supported."); - } - - // [LYN-2376] Remove once legacy slice support is removed - int SpawnableLevelSystem::GetLevelCount() - { - AZ_Assert(false, "GetLevelCount - No longer supported."); - return 0; - } - - // [LYN-2376] Remove once legacy slice support is removed - ILevelInfo* SpawnableLevelSystem::GetLevelInfo([[maybe_unused]] int level) - { - AZ_Assert(false, "GetLevelInfo - No longer supported."); - return nullptr; - } - - // [LYN-2376] Remove once legacy slice support is removed - ILevelInfo* SpawnableLevelSystem::GetLevelInfo([[maybe_unused]] const char* levelName) - { - AZ_Assert(false, "GetLevelInfo - No longer supported."); - return nullptr; - } - - //------------------------------------------------------------------------ - void SpawnableLevelSystem::AddListener(ILevelSystemListener* pListener) - { - AZStd::vector::iterator it = AZStd::find(m_listeners.begin(), m_listeners.end(), pListener); - - if (it == m_listeners.end()) - { - m_listeners.push_back(pListener); - } - } - - //------------------------------------------------------------------------ - void SpawnableLevelSystem::RemoveListener(ILevelSystemListener* pListener) - { - AZStd::vector::iterator it = AZStd::find(m_listeners.begin(), m_listeners.end(), pListener); - - if (it != m_listeners.end()) - { - m_listeners.erase(it); - } - } - - //------------------------------------------------------------------------ - bool SpawnableLevelSystem::LoadLevel(const char* levelName) - { - if (gEnv->IsEditor()) - { - AZ_TracePrintf("CrySystem::CLevelSystem", "LoadLevel for %s was called in the editor - not actually loading.\n", levelName); - return false; - } - - // If a level is currently loaded, unload it before loading the next one. - if (IsLevelLoaded()) - { - UnloadLevel(); - } - - gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_LOAD_PREPARE, 0, 0); - PrepareNextLevel(levelName); - - bool result = LoadLevelInternal(levelName); - if (result) - { - OnLoadingComplete(levelName); - } - - return result; - } - - //------------------------------------------------------------------------ - bool SpawnableLevelSystem::LoadLevelInternal(const char* levelName) - { - gEnv->pSystem->SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START); - AZ_ASSET_NAMED_SCOPE("Level: %s", levelName); - - INDENT_LOG_DURING_SCOPE(); - - AZ::Data::AssetId rootSpawnableAssetId; - AZ::Data::AssetCatalogRequestBus::BroadcastResult( - rootSpawnableAssetId, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, levelName, nullptr, false); - if (!rootSpawnableAssetId.IsValid()) - { - OnLoadingError(levelName, "AssetCatalog has no entry for the requested level."); - - return false; - } - - // This scope is specifically used for marking a loading time profile section - { - LOADING_TIME_PROFILE_SECTION; - - m_bLevelLoaded = false; - m_lastLevelName = levelName; - gEnv->pConsole->SetScrollMax(600); - ICVar* con_showonload = gEnv->pConsole->GetCVar("con_showonload"); - if (con_showonload && con_showonload->GetIVal() != 0) - { - gEnv->pConsole->ShowConsole(true); - ICVar* g_enableloadingscreen = gEnv->pConsole->GetCVar("g_enableloadingscreen"); - if (g_enableloadingscreen) - { - g_enableloadingscreen->Set(0); - } - } - - // This is a workaround until the replacement for GameEntityContext is done - AzFramework::GameEntityContextEventBus::Broadcast(&AzFramework::GameEntityContextEventBus::Events::OnPreGameEntitiesStarted); - - // Reset the camera to (1,1,1) (not (0,0,0) which is the invalid/uninitialised state, - // to avoid the hack in the renderer to not show anything if the camera is at the origin). - CCamera defaultCam; - defaultCam.SetPosition(Vec3(1.0f)); - m_pSystem->SetViewCamera(defaultCam); - - OnLoadingStart(levelName); - - auto pPak = gEnv->pCryPak; - - ICVar* pSpamDelay = gEnv->pConsole->GetCVar("log_SpamDelay"); - float spamDelay = 0.0f; - if (pSpamDelay) - { - spamDelay = pSpamDelay->GetFVal(); - pSpamDelay->Set(0.0f); - } - - // Parse level specific config data. - AZStd::string const sLevelNameOnly(PathUtil::GetFileName(levelName)); - - if (!sLevelNameOnly.empty()) - { - const char* controlsPath = nullptr; - Audio::AudioSystemRequestBus::BroadcastResult(controlsPath, &Audio::AudioSystemRequestBus::Events::GetControlsPath); - if (controlsPath) - { - AZStd::string sAudioLevelPath(controlsPath); - sAudioLevelPath.append("levels/"); - sAudioLevelPath += sLevelNameOnly; - - Audio::SAudioManagerRequestData oAMData( - sAudioLevelPath.c_str(), Audio::eADS_LEVEL_SPECIFIC); - Audio::SAudioRequest oAudioRequestData; - oAudioRequestData.nFlags = - (Audio::eARF_PRIORITY_HIGH | - Audio::eARF_EXECUTE_BLOCKING); // Needs to be blocking so data is available for next preloading request! - oAudioRequestData.pData = &oAMData; - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); - - Audio::SAudioManagerRequestData oAMData2( - sAudioLevelPath.c_str(), Audio::eADS_LEVEL_SPECIFIC); - oAudioRequestData.pData = &oAMData2; - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); - - Audio::TAudioPreloadRequestID nPreloadRequestID = INVALID_AUDIO_PRELOAD_REQUEST_ID; - - Audio::AudioSystemRequestBus::BroadcastResult( - nPreloadRequestID, &Audio::AudioSystemRequestBus::Events::GetAudioPreloadRequestID, sLevelNameOnly.c_str()); - if (nPreloadRequestID != INVALID_AUDIO_PRELOAD_REQUEST_ID) - { - Audio::SAudioManagerRequestData requestData(nPreloadRequestID, true); - oAudioRequestData.pData = &requestData; - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); - } - } - } - - - AZ::Data::Asset rootSpawnable( - rootSpawnableAssetId, azrtti_typeid(), levelName); - - m_rootSpawnableId = rootSpawnableAssetId; - m_rootSpawnableGeneration = AzFramework::RootSpawnableInterface::Get()->AssignRootSpawnable(rootSpawnable); - - // This is a workaround until the replacement for GameEntityContext is done - AzFramework::GameEntityContextEventBus::Broadcast(&AzFramework::GameEntityContextEventBus::Events::OnGameEntitiesStarted); - - ////////////////////////////////////////////////////////////////////////// - // Movie system must be reset after entities. - ////////////////////////////////////////////////////////////////////////// - IMovieSystem* movieSys = gEnv->pMovieSystem; - if (movieSys != NULL) - { - // bSeekAllToStart needs to be false here as it's only of interest in the editor - movieSys->Reset(true, false); - } - - gEnv->pSystem->SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_PRECACHE); - - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - gEnv->pConsole->SetScrollMax(600 / 2); - - pPak->GetResourceList(AZ::IO::IArchive::RFOM_NextLevel)->Clear(); - - if (pSpamDelay) - { - pSpamDelay->Set(spamDelay); - } - - m_bLevelLoaded = true; - gEnv->pSystem->SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_END); - } - - GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_LOAD_END, 0, 0); - - if (auto cvar = gEnv->pConsole->GetCVar("sv_map"); cvar) - { - cvar->Set(levelName); - } - - gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_START, 0, 0); - - return true; - } - - //------------------------------------------------------------------------ - void SpawnableLevelSystem::PrepareNextLevel(const char* levelName) - { - AZ::Data::AssetId rootSpawnableAssetId; - AZ::Data::AssetCatalogRequestBus::BroadcastResult( - rootSpawnableAssetId, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, levelName, nullptr, false); - if (!rootSpawnableAssetId.IsValid()) - { - // alert the listener - OnLevelNotFound(levelName); - return; - } - - // This work not required in-editor. - if (!gEnv || !gEnv->IsEditor()) - { - m_levelLoadStartTime = gEnv->pTimer->GetAsyncTime(); - - // switched to level heap, so now imm start the loading screen (renderer will be reinitialized in the levelheap) - gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_LOAD_START_LOADINGSCREEN, 0, 0); - gEnv->pSystem->SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_PREPARE); - } - - OnPrepareNextLevel(levelName); - } - - void SpawnableLevelSystem::OnPrepareNextLevel(const char* levelName) - { - AZ_TracePrintf("LevelSystem", "Level system is preparing to load '%s'\n", levelName); - - for (auto& listener : m_listeners) - { - listener->OnPrepareNextLevel(levelName); - } - } - - //------------------------------------------------------------------------ - void SpawnableLevelSystem::OnLevelNotFound(const char* levelName) - { - AZ_Error("LevelSystem", false, "Requested level not found: '%s'\n", levelName); - - for (auto& listener : m_listeners) - { - listener->OnLevelNotFound(levelName); - } - } - - //------------------------------------------------------------------------ - void SpawnableLevelSystem::OnLoadingStart(const char* levelName) - { - AZ_TracePrintf("LevelSystem", "Level system is loading '%s'\n", levelName); - - if (gEnv->pCryPak->GetRecordFileOpenList() == AZ::IO::IArchive::RFOM_EngineStartup) - { - gEnv->pCryPak->RecordFileOpen(AZ::IO::IArchive::RFOM_Level); - } - - m_fLastTime = gEnv->pTimer->GetAsyncCurTime(); - - GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_LOAD_START, 0, 0); - - LOADING_TIME_PROFILE_SECTION(gEnv->pSystem); - - for (auto& listener : m_listeners) - { - listener->OnLoadingStart(levelName); - } - } - - //------------------------------------------------------------------------ - void SpawnableLevelSystem::OnLoadingError(const char* levelName, const char* error) - { - AZ_Error("LevelSystem", false, "Error loading level '%s': %s\n", levelName, error); - - for (auto& listener : m_listeners) - { - listener->OnLoadingError(levelName, error); - } - } - - //------------------------------------------------------------------------ - void SpawnableLevelSystem::OnLoadingComplete(const char* levelName) - { - CTimeValue t = gEnv->pTimer->GetAsyncTime(); - m_fLastLevelLoadTime = (t - m_levelLoadStartTime).GetSeconds(); - - LogLoadingTime(); - - m_nLoadedLevelsCount++; - - // Hide console after loading. - gEnv->pConsole->ShowConsole(false); - - for (auto& listener : m_listeners) - { - listener->OnLoadingComplete(levelName); - } - - #if AZ_LOADSCREENCOMPONENT_ENABLED - EBUS_EVENT(LoadScreenBus, Stop); - #endif // if AZ_LOADSCREENCOMPONENT_ENABLED - - AZ_TracePrintf("LevelSystem", "Level load complete: '%s'\n", levelName); - } - - //------------------------------------------------------------------------ - void SpawnableLevelSystem::OnLoadingProgress(const char* levelName, int progressAmount) - { - for (auto& listener : m_listeners) - { - listener->OnLoadingProgress(levelName, progressAmount); - } - } - - //------------------------------------------------------------------------ - void SpawnableLevelSystem::OnUnloadComplete(const char* levelName) - { - for (auto& listener : m_listeners) - { - listener->OnUnloadComplete(levelName); - } - - AZ_TracePrintf("LevelSystem", "Level unload complete: '%s'\n", levelName); - } - - ////////////////////////////////////////////////////////////////////////// - void SpawnableLevelSystem::LogLoadingTime() - { - if (gEnv->IsEditor()) - { - return; - } - - if (!GetISystem()->IsDevMode()) - { - return; - } - - char vers[128]; - GetISystem()->GetFileVersion().ToString(vers, sizeof(vers)); - - const char* sChain = ""; - if (m_nLoadedLevelsCount > 0) - { - sChain = " (Chained)"; - } - - AZStd::string text; - text.format( - "Game Level Load Time: [%s] Level %s loaded in %.2f seconds%s", vers, m_lastLevelName.c_str(), m_fLastLevelLoadTime, sChain); - gEnv->pLog->Log(text.c_str()); - } - - ////////////////////////////////////////////////////////////////////////// - void SpawnableLevelSystem::UnloadLevel() - { - if (gEnv->IsEditor()) - { - return; - } - - if (m_lastLevelName.empty()) - { - return; - } - - AZ_TracePrintf("LevelSystem", "UnloadLevel Start\n"); - INDENT_LOG_DURING_SCOPE(); - - // Flush core buses. We're about to unload Cry modules and need to ensure we don't have module-owned functions left behind. - AZ::Data::AssetBus::ExecuteQueuedEvents(); - AZ::TickBus::ExecuteQueuedEvents(); - AZ::MainThreadRenderRequestBus::ExecuteQueuedEvents(); - - if (gEnv && gEnv->pSystem) - { - // clear all error messages to prevent stalling due to runtime file access check during chainloading - gEnv->pSystem->ClearErrorMessages(); - } - - if (gEnv && gEnv->pCryPak) - { - gEnv->pCryPak->DisableRuntimeFileAccess(false); - } - - CTimeValue tBegin = gEnv->pTimer->GetAsyncTime(); - - // Clear level entities and prefab instances. - EBUS_EVENT(AzFramework::GameEntityContextRequestBus, ResetGameContext); - - if (gEnv->pMovieSystem) - { - gEnv->pMovieSystem->Reset(false, false); - gEnv->pMovieSystem->RemoveAllSequences(); - } - - // Unload level specific audio binary data. - Audio::SAudioManagerRequestData oAMData(Audio::eADS_LEVEL_SPECIFIC); - Audio::SAudioRequest oAudioRequestData; - oAudioRequestData.nFlags = (Audio::eARF_PRIORITY_HIGH | Audio::eARF_EXECUTE_BLOCKING); - oAudioRequestData.pData = &oAMData; - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); - - // Now unload level specific audio config data. - Audio::SAudioManagerRequestData oAMData2(Audio::eADS_LEVEL_SPECIFIC); - oAudioRequestData.pData = &oAMData2; - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); - - Audio::SAudioManagerRequestData oAMData3(Audio::eADS_LEVEL_SPECIFIC); - oAudioRequestData.pData = &oAMData3; - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); - - // Reset the camera to (0,0,0) which is the invalid/uninitialised state - CCamera defaultCam; - m_pSystem->SetViewCamera(defaultCam); - - OnUnloadComplete(m_lastLevelName.c_str()); - - AzFramework::RootSpawnableInterface::Get()->ReleaseRootSpawnable(); - - m_lastLevelName.clear(); - - // Force Lua garbage collection (may no longer be needed now the legacy renderer has been removed). - // Normally the GC step is triggered at the end of this method (by the ESYSTEM_EVENT_LEVEL_POST_UNLOAD event). - EBUS_EVENT(AZ::ScriptSystemRequestBus, GarbageCollect); - - // Perform level unload procedures for the LyShine UI system - if (gEnv && gEnv->pLyShine) - { - gEnv->pLyShine->OnLevelUnload(); - } - - m_bLevelLoaded = false; - - CTimeValue tUnloadTime = gEnv->pTimer->GetAsyncTime() - tBegin; - AZ_TracePrintf("LevelSystem", "UnloadLevel End: %.1f sec\n", tUnloadTime.GetSeconds()); - - // Must be sent last. - // Cleanup all containers - GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_POST_UNLOAD, 0, 0); - AzFramework::InputChannelRequestBus::Broadcast(&AzFramework::InputChannelRequests::ResetState); - - AzFramework::GameEntityContextEventBus::Broadcast(&AzFramework::GameEntityContextEventBus::Events::OnGameEntitiesReset); - } - - void SpawnableLevelSystem::OnRootSpawnableAssigned( - [[maybe_unused]] AZ::Data::Asset rootSpawnable, [[maybe_unused]] uint32_t generation) - { - } - - void SpawnableLevelSystem::OnRootSpawnableReleased([[maybe_unused]] uint32_t generation) - { - } - -} // namespace LegacyLevelSystem diff --git a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.h b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.h deleted file mode 100644 index a261e7da9c..0000000000 --- a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include "ILevelSystem.h" -#include -#include -#include - -namespace LegacyLevelSystem -{ - -class SpawnableLevelSystem - : public ILevelSystem - , public AzFramework::RootSpawnableNotificationBus::Handler - { - public: - explicit SpawnableLevelSystem(ISystem* pSystem); - ~SpawnableLevelSystem() override; - - // ILevelSystem - void Release() override; - - void AddListener(ILevelSystemListener* pListener) override; - void RemoveListener(ILevelSystemListener* pListener) override; - - bool LoadLevel(const char* levelName) override; - void UnloadLevel() override; - bool IsLevelLoaded() override; - const char* GetCurrentLevelName() const override; - - // If the level load failed then we need to have a different shutdown procedure vs when a level is naturally unloaded - void SetLevelLoadFailed(bool loadFailed) override; - bool GetLevelLoadFailed() override; - AZ::Data::AssetType GetLevelAssetType() const override; - - // The following methods are deprecated from ILevelSystem and will be removed once slice support is removed. - - // [LYN-2376] Remove once legacy slice support is removed - void Rescan([[maybe_unused]] const char* levelsFolder) override; - int GetLevelCount() override; - ILevelInfo* GetLevelInfo([[maybe_unused]] int level) override; - ILevelInfo* GetLevelInfo([[maybe_unused]] const char* levelName) override; - - private: - void OnRootSpawnableAssigned(AZ::Data::Asset rootSpawnable, uint32_t generation) override; - void OnRootSpawnableReleased(uint32_t generation) override; - - void PrepareNextLevel(const char* levelName); - bool LoadLevelInternal(const char* levelName); - - // Methods to notify ILevelSystemListener - void OnPrepareNextLevel(const char* levelName); - void OnLevelNotFound(const char* levelName); - void OnLoadingStart(const char* levelName); - void OnLoadingComplete(const char* levelName); - void OnLoadingError(const char* levelName, const char* error); - void OnLoadingProgress(const char* levelName, int progressAmount); - void OnUnloadComplete(const char* levelName); - - void LogLoadingTime(); - - ISystem* m_pSystem{nullptr}; - - AZStd::string m_lastLevelName; - float m_fLastLevelLoadTime{0.0f}; - float m_fLastTime{0.0f}; - - bool m_bLevelLoaded{false}; - bool m_levelLoadFailed{false}; - - int m_nLoadedLevelsCount{0}; - - CTimeValue m_levelLoadStartTime; - - AZStd::vector m_listeners; - - // Information about the currently-loaded root spawnable, used for tracking loads and unloads. - uint64_t m_rootSpawnableGeneration{0}; - AZ::Data::AssetId m_rootSpawnableId{}; - }; - -} // namespace LegacyLevelSystem diff --git a/Code/CryEngine/CrySystem/LocalizedStringManager.cpp b/Code/CryEngine/CrySystem/LocalizedStringManager.cpp deleted file mode 100644 index 64489cb4fd..0000000000 --- a/Code/CryEngine/CrySystem/LocalizedStringManager.cpp +++ /dev/null @@ -1,2771 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "CrySystem_precompiled.h" - -#include "LocalizedStringManager.h" - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define LOCALIZEDSTRINGMANAGER_CPP_SECTION_1 1 -#endif - -#include -#include "System.h" // to access InitLocalization() -#include -#include -#include -#include -#include - -#include -#include - -#define MAX_CELL_COUNT 32 - -// CVAR names -const char c_sys_localization_debug[] = "sys_localization_debug"; -const char c_sys_localization_encode[] = "sys_localization_encode"; -#define LOC_WINDOW "Localization" -const char c_sys_localization_format[] = "sys_localization_format"; - -enum ELocalizedXmlColumns -{ - ELOCALIZED_COLUMN_SKIP = 0, - ELOCALIZED_COLUMN_KEY, - ELOCALIZED_COLUMN_AUDIOFILE, - ELOCALIZED_COLUMN_CHARACTER_NAME, - ELOCALIZED_COLUMN_SUBTITLE_TEXT, - ELOCALIZED_COLUMN_ACTOR_LINE, - ELOCALIZED_COLUMN_USE_SUBTITLE, - ELOCALIZED_COLUMN_VOLUME, - ELOCALIZED_COLUMN_SOUNDEVENT, - ELOCALIZED_COLUMN_RADIO_RATIO, - ELOCALIZED_COLUMN_EVENTPARAMETER, - ELOCALIZED_COLUMN_SOUNDMOOD, - ELOCALIZED_COLUMN_IS_DIRECT_RADIO, - // legacy names - ELOCALIZED_COLUMN_LEGACY_PERSON, - ELOCALIZED_COLUMN_LEGACY_CHARACTERNAME, - ELOCALIZED_COLUMN_LEGACY_TRANSLATED_CHARACTERNAME, - ELOCALIZED_COLUMN_LEGACY_ENGLISH_DIALOGUE, - ELOCALIZED_COLUMN_LEGACY_TRANSLATION, - ELOCALIZED_COLUMN_LEGACY_YOUR_TRANSLATION, - ELOCALIZED_COLUMN_LEGACY_ENGLISH_SUBTITLE, - ELOCALIZED_COLUMN_LEGACY_TRANSLATED_SUBTITLE, - ELOCALIZED_COLUMN_LEGACY_ORIGINAL_CHARACTER_NAME, - ELOCALIZED_COLUMN_LEGACY_TRANSLATED_CHARACTER_NAME, - ELOCALIZED_COLUMN_LEGACY_ORIGINAL_TEXT, - ELOCALIZED_COLUMN_LEGACY_TRANSLATED_TEXT, - ELOCALIZED_COLUMN_LEGACY_ORIGINAL_ACTOR_LINE, - ELOCALIZED_COLUMN_LEGACY_TRANSLATED_ACTOR_LINE, - ELOCALIZED_COLUMN_LAST, -}; - -// The order must match to the order of the ELocalizedXmlColumns -static const char* sLocalizedColumnNames[] = -{ - // everyhing read by the file will be convert to lower cases - "skip", - "key", - "audio_filename", - "character name", - "subtitle text", - "actor line", - "use subtitle", - "volume", - "prototype event", - "radio ratio", - "eventparameter", - "soundmood", - "is direct radio", - // legacy names - "person", - "character name", - "translated character name", - "english dialogue", - "translation", - "your translation", - "english subtitle", - "translated subtitle", - "original character name", - "translated character name", - "original text", - "translated text", - "original actor line", - "translated actor line", -}; - -//Please ensure that this array matches the contents of EPlatformIndependentLanguageID in ILocalizationManager.h -static const char* PLATFORM_INDEPENDENT_LANGUAGE_NAMES[ ILocalizationManager::ePILID_MAX_OR_INVALID ] = -{ - "en-US", // English (USA) - "en-GB", // English (UK) - "de-DE", // German - "ru-RU", // Russian (Russia) - "pl-PL", // Polish - "tr-TR", // Turkish - "es-ES", // Spanish (Spain) - "es-MX", // Spanish (Mexico) - "fr-FR", // French (France) - "fr-CA", // French (Canada) - "it-IT", // Italian - "pt-PT", // Portugese (Portugal) - "pt-BR", // Portugese (Brazil) - "ja-JP", // Japanese - "ko-KR", // Korean - "zh-CHT", // Traditional Chinese - "zh-CHS", // Simplified Chinese - "nl-NL", // Dutch (The Netherlands) - "fi-FI", // Finnish - "sv-SE", // Swedish - "cs-CZ", // Czech - "no-NO", // Norwegian - "ar-SA", // Arabic (Saudi Arabia) - "da-DK" // Danish (Denmark) -}; - -////////////////////////////////////////////////////////////////////////// -#if !defined(_RELEASE) -static void ReloadDialogData([[maybe_unused]] IConsoleCmdArgs* pArgs) -{ - LocalizationManagerRequestBus::Broadcast(&LocalizationManagerRequestBus::Events::ReloadData); - //CSystem *pSystem = (CSystem*) gEnv->pSystem; - //pSystem->InitLocalization(); - //pSystem->OpenBasicPaks(); -} -#endif //#if !defined(_RELEASE) - -////////////////////////////////////////////////////////////////////////// -#if !defined(_RELEASE) -static void TestFormatMessage ([[maybe_unused]] IConsoleCmdArgs* pArgs) -{ - string fmt1 ("abc %1 def % gh%2i %"); - string fmt2 ("abc %[action:abc] %2 def % gh%1i %1"); - string out1, out2; - LocalizationManagerRequestBus::Broadcast(&LocalizationManagerRequestBus::Events::FormatStringMessage, out1, fmt1, "first", "second", "third", nullptr); - CryLogAlways("%s", out1.c_str()); - LocalizationManagerRequestBus::Broadcast(&LocalizationManagerRequestBus::Events::FormatStringMessage, out2, fmt2, "second", nullptr, nullptr, nullptr); - CryLogAlways("%s", out2.c_str()); -} -#endif //#if !defined(_RELEASE) - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////// -CLocalizedStringsManager::CLocalizedStringsManager(ISystem* pSystem) - : m_cvarLocalizationDebug(0) - , m_cvarLocalizationEncode(1) - , m_availableLocalizations(0) -{ - m_pSystem = pSystem; - m_pSystem->GetISystemEventDispatcher()->RegisterListener(this); - - m_languages.reserve(4); - m_pLanguage = 0; - -#if !defined(_RELEASE) - m_haveWarnedAboutAtLeastOneLabel = false; - - REGISTER_COMMAND("ReloadDialogData", ReloadDialogData, VF_NULL, - "Reloads all localization dependent XML sheets for the currently set language."); - - REGISTER_COMMAND("_TestFormatMessage", TestFormatMessage, VF_NULL, ""); - - REGISTER_CVAR2(c_sys_localization_debug, &m_cvarLocalizationDebug, m_cvarLocalizationDebug, VF_CHEAT, - "Toggles debugging of the Localization Manager.\n" - "Usage: sys_localization_debug [0..3]\n" - "1: outputs warnings\n" - "2: outputs extended information and warnings\n" - "3: outputs CRC32 hashes and strings to help detect clashes\n" - "Default is 0 (off)."); - - REGISTER_CVAR2(c_sys_localization_encode, &m_cvarLocalizationEncode, m_cvarLocalizationEncode, VF_REQUIRE_APP_RESTART, - "Toggles encoding of translated text to save memory. REQUIRES RESTART.\n" - "Usage: sys_localization_encode [0..1]\n" - "0: No encoding, store as wide strings\n" - "1: Huffman encode translated text, saves approx 30% with a small runtime performance cost\n" - "Default is 1."); -#endif //#if !defined(_RELEASE) - - REGISTER_CVAR2(c_sys_localization_format, &m_cvarLocalizationFormat, 1, VF_NULL, - "Usage: sys_localization_format [0..1]\n" - " 0: Crytek Legacy Localization (Excel 2003)\n" - " 1: AGS XML\n" - "Default is 1 (AGS Xml)"); - //Check that someone hasn't added a language ID without a language name - assert(PLATFORM_INDEPENDENT_LANGUAGE_NAMES[ ILocalizationManager::ePILID_MAX_OR_INVALID - 1 ] != 0); - - // Populate available languages by scanning the localization directory for paks - // Default to US English if language is not supported - string sPath; - const string sLocalizationFolder(PathUtil::GetLocalizationFolder()); - ILocalizationManager::TLocalizationBitfield availableLanguages = 0; - - AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance(); - // test language name against supported languages - for (int i = 0; i < ILocalizationManager::ePILID_MAX_OR_INVALID; i++) - { - string sCurrentLanguage = LangNameFromPILID((ILocalizationManager::EPlatformIndependentLanguageID)i); - sPath = sLocalizationFolder.c_str() + sCurrentLanguage; - sPath.MakeLower(); - if (fileIO && fileIO->IsDirectory(sPath)) - { - availableLanguages |= ILocalizationManager::LocalizationBitfieldFromPILID((ILocalizationManager::EPlatformIndependentLanguageID)i); - if (m_cvarLocalizationDebug >= 2) - { - AZ_TracePrintf("Localization", "Detected language support for %s (id %d)", sCurrentLanguage.c_str(), i); - } - } - } - - AZ_Warning("Localization", !(m_cvarLocalizationFormat == 0 && availableLanguages == 0 && ProjectUsesLocalization()), "No localization files found!"); - - SetAvailableLocalizationsBitfield(availableLanguages); - LocalizationManagerRequestBus::Handler::BusConnect(); -} - -////////////////////////////////////////////////////////////////////// -CLocalizedStringsManager::~CLocalizedStringsManager() -{ - FreeData(); - LocalizationManagerRequestBus::Handler::BusDisconnect(); -} - -////////////////////////////////////////////////////////////////////// -void CLocalizedStringsManager::GetLoadedTags(TLocalizationTagVec& tagVec) -{ - TTagFileNames::const_iterator end = m_tagFileNames.end(); - for (TTagFileNames::const_iterator it = m_tagFileNames.begin(); it != end; ++it) - { - if (it->second.loaded) - { - tagVec.push_back(it->first); - } - } -} - -////////////////////////////////////////////////////////////////////// -void CLocalizedStringsManager::FreeLocalizationData() -{ - AutoLock lock(m_cs); //Make sure to lock, as this is a modifying operation - ListAndClearProblemLabels(); - - for (uint32 i = 0; i < m_languages.size(); i++) - { - if (m_cvarLocalizationEncode == 1) - { - auto pLanguage = m_languages[i]; - for (uint8 iEncoder = 0; iEncoder < pLanguage->m_vEncoders.size(); iEncoder++) - { - SAFE_DELETE(pLanguage->m_vEncoders[iEncoder]); - } - } - std::for_each(m_languages[i]->m_vLocalizedStrings.begin(), m_languages[i]->m_vLocalizedStrings.end(), stl::container_object_deleter()); - m_languages[i]->m_keysMap.clear(); - m_languages[i]->m_vLocalizedStrings.clear(); - } - m_loadedTables.clear(); -} - -////////////////////////////////////////////////////////////////////// -void CLocalizedStringsManager::FreeData() -{ - FreeLocalizationData(); - - for (uint32 i = 0; i < m_languages.size(); i++) - { - delete m_languages[i]; - } - m_languages.resize(0); - m_loadedTables.clear(); - - m_pLanguage = 0; -} - -////////////////////////////////////////////////////////////////////////// -const char* CLocalizedStringsManager::LangNameFromPILID(const ILocalizationManager::EPlatformIndependentLanguageID id) -{ - assert(id >= 0 && id < ILocalizationManager::ePILID_MAX_OR_INVALID); - return PLATFORM_INDEPENDENT_LANGUAGE_NAMES[ id ]; -} - -////////////////////////////////////////////////////////////////////////// -ILocalizationManager::EPlatformIndependentLanguageID CLocalizedStringsManager::PILIDFromLangName(AZStd::string langName) -{ - for (int i = 0; i < ILocalizationManager::ePILID_MAX_OR_INVALID; i++) - { - if (!_stricmp(langName.c_str(), PLATFORM_INDEPENDENT_LANGUAGE_NAMES[i])) - { - return (ILocalizationManager::EPlatformIndependentLanguageID)i; - } - } - return ILocalizationManager::ePILID_MAX_OR_INVALID; -} - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION LOCALIZEDSTRINGMANAGER_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(LocalizedStringManager_cpp) -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#endif // AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -////////////////////////////////////////////////////////////////////////// -ILocalizationManager::EPlatformIndependentLanguageID CLocalizedStringsManager::GetSystemLanguage() -{ - - return ILocalizationManager::EPlatformIndependentLanguageID::ePILID_English_US; -} -#endif // defined(AZ_RESTRICTED_PLATFORM) - -//Uses bitwise operations to compare the localizations we provide in this SKU and the languages that the platform supports. -//Returns !0 if we provide more localizations than are available as system languages -ILocalizationManager::TLocalizationBitfield CLocalizedStringsManager::MaskSystemLanguagesFromSupportedLocalizations(const ILocalizationManager::TLocalizationBitfield systemLanguages) -{ - return (~systemLanguages) & m_availableLocalizations; -} - -//Returns !0 if the language is supported. -ILocalizationManager::TLocalizationBitfield CLocalizedStringsManager::IsLanguageSupported(const ILocalizationManager::EPlatformIndependentLanguageID id) -{ - return m_availableLocalizations & (1 << id); -} - -////////////////////////////////////////////////////////////////////////// -void CLocalizedStringsManager::SetAvailableLocalizationsBitfield(const ILocalizationManager::TLocalizationBitfield availableLocalizations) -{ - m_availableLocalizations = availableLocalizations; -} - -////////////////////////////////////////////////////////////////////// -const char* CLocalizedStringsManager::GetLanguage() -{ - if (m_pLanguage == 0) - { - return ""; - } - return m_pLanguage->sLanguage.c_str(); -} - -////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::SetLanguage(const char* sLanguage) -{ - if (m_cvarLocalizationDebug >= 2) - { - CryLog(" Set language to %s", sLanguage); - } - - // Check if already language loaded. - for (uint32 i = 0; i < m_languages.size(); i++) - { - if (_stricmp(sLanguage, m_languages[i]->sLanguage) == 0) - { - InternalSetCurrentLanguage(m_languages[i]); - return true; - } - } - - SLanguage* pLanguage = new SLanguage; - m_languages.push_back(pLanguage); - - if (m_cvarLocalizationDebug >= 2) - { - CryLog(" Insert new language to %s", sLanguage); - } - - pLanguage->sLanguage = sLanguage; - InternalSetCurrentLanguage(pLanguage); - - //------------------------------------------------------------------------------------------------- - // input localization - //------------------------------------------------------------------------------------------------- - // keyboard - for (int i = 0; i <= 0x80; i++) - { - AddControl(i); - } - - // mouse - for (int i = 1; i <= 0x0f; i++) - { - AddControl(i * 0x10000); - } - - return (true); -} - -////////////////////////////////////////////////////////////////////////// -int CLocalizedStringsManager::GetLocalizationFormat() const -{ - return m_cvarLocalizationFormat; -} - -////////////////////////////////////////////////////////////////////////// -AZStd::string CLocalizedStringsManager::GetLocalizedSubtitleFilePath(const AZStd::string& localVideoPath, const AZStd::string& subtitleFileExtension) const -{ - AZStd::string sLocalizationFolder(PathUtil::GetLocalizationFolder().c_str()); - size_t backSlashIdx = sLocalizationFolder.find_first_of("\\", 0); - if (backSlashIdx != AZStd::string::npos) - { - sLocalizationFolder.replace(backSlashIdx, 2, "/"); - } - AZStd::string filePath(m_pLanguage->sLanguage.c_str()); - filePath = sLocalizationFolder.c_str() + filePath + "/" + localVideoPath; - return filePath.substr(0, filePath.find_last_of('.')).append(subtitleFileExtension); -} - -////////////////////////////////////////////////////////////////////////// -AZStd::string CLocalizedStringsManager::GetLocalizedLocXMLFilePath(const AZStd::string & localXmlPath) const -{ - AZStd::string sLocalizationFolder(PathUtil::GetLocalizationFolder().c_str()); - size_t backSlashIdx = sLocalizationFolder.find_first_of("\\", 0); - if (backSlashIdx != AZStd::string::npos) - { - sLocalizationFolder.replace(backSlashIdx, 2, "/"); - } - const AZStd::string& filePath = AZStd::string::format("%s%s/%s", sLocalizationFolder.c_str(), m_pLanguage->sLanguage.c_str(), localXmlPath.c_str()); - return filePath.substr(0, filePath.find_last_of('.')).append(".loc.xml"); -} - -////////////////////////////////////////////////////////////////////////// -void CLocalizedStringsManager::AddControl([[maybe_unused]] int nKey) -{ -} - -////////////////////////////////////////////////////////////////////////// -void CLocalizedStringsManager::ParseFirstLine(IXmlTableReader* pXmlTableReader, char* nCellIndexToType, std::map& SoundMoodIndex, std::map& EventParameterIndex) -{ - string sCellContent; - - for (;; ) - { - int nCellIndex = 0; - const char* pContent = 0; - size_t contentSize = 0; - if (!pXmlTableReader->ReadCell(nCellIndex, pContent, contentSize)) - { - break; - } - - if (nCellIndex >= MAX_CELL_COUNT) - { - break; - } - - if (contentSize <= 0) - { - continue; - } - - sCellContent.assign(pContent, contentSize); - sCellContent.MakeLower(); - - for (int i = 0; i < sizeof(sLocalizedColumnNames) / sizeof(sLocalizedColumnNames[0]); ++i) - { - const char* pFind = strstr(sCellContent.c_str(), sLocalizedColumnNames[i]); - if (pFind != 0) - { - nCellIndexToType[nCellIndex] = i; - - // find SoundMood - if (i == ELOCALIZED_COLUMN_SOUNDMOOD) - { - const char* pSoundMoodName = pFind + strlen(sLocalizedColumnNames[i]) + 1; - int nSoundMoodNameLength = sCellContent.length() - strlen(sLocalizedColumnNames[i]) - 1; - if (nSoundMoodNameLength > 0) - { - SoundMoodIndex[nCellIndex] = pSoundMoodName; - } - } - - // find EventParameter - if (i == ELOCALIZED_COLUMN_EVENTPARAMETER) - { - const char* pParameterName = pFind + strlen(sLocalizedColumnNames[i]) + 1; - int nParameterNameLength = sCellContent.length() - strlen(sLocalizedColumnNames[i]) - 1; - if (nParameterNameLength > 0) - { - EventParameterIndex[nCellIndex] = pParameterName; - } - } - - break; - } - // HACK until all columns are renamed to "Translation" - //if (_stricmp(sCellContent, "Your Translation") == 0) - //{ - // nCellIndexToType[nCellIndex] = ELOCALIZED_COLUMN_TRANSLATED_ACTOR_LINE; - // break; - //} - } - } -} - -// copy characters to lower-case 0-terminated buffer -static void CopyLowercase(char* dst, size_t dstSize, const char* src, size_t srcCount) -{ - if (dstSize > 0) - { - if (srcCount > dstSize - 1) - { - srcCount = dstSize - 1; - } - while (srcCount--) - { - const char c = *src++; - *dst++ = (c <= 'Z' && c >= 'A') ? c + ('a' - 'A') : c; - } - *dst = '\0'; - } -} - -////////////////////////////////////////////////////////////////////////// -static void ReplaceEndOfLine(CryFixedStringT& s) -{ - const string oldSubstr("\\n"); - const string newSubstr(" \n"); - size_t pos = 0; - for (;; ) - { - pos = s.find(oldSubstr, pos); - if (pos == CryFixedStringT::npos) - { - return; - } - s.replace(pos, oldSubstr.length(), newSubstr); - } -} - -////////////////////////////////////////////////////////////////////////// - -void CLocalizedStringsManager::OnSystemEvent( - ESystemEvent eEvent, [[maybe_unused]] UINT_PTR wparam, [[maybe_unused]] UINT_PTR lparam) -{ - // might want to add an event which tells us that we are loading the main menu - // so everything can be unloaded and init files reloaded so safe some memory - switch (eEvent) - { - case ESYSTEM_EVENT_LEVEL_LOAD_START: - { - // This event is here not of interest while we're in the Editor. - if (!gEnv->IsEditor()) - { - if (m_cvarLocalizationDebug >= 2) - { - CryLog(" Loading Requested Tags"); - } - - for (TStringVec::iterator it = m_tagLoadRequests.begin(); it != m_tagLoadRequests.end(); ++it) - { - LoadLocalizationDataByTag(*it); - } - } - - m_tagLoadRequests.clear(); - break; - } - case ESYSTEM_EVENT_EDITOR_ON_INIT: - { - // Load all tags after the Editor has finished initialization. - for (TTagFileNames::iterator it = m_tagFileNames.begin(); it != m_tagFileNames.end(); ++it) - { - LoadLocalizationDataByTag(it->first); - } - - break; - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::InitLocalizationData( - const char* sFileName, [[maybe_unused]] bool bReload) -{ - XmlNodeRef root = m_pSystem->LoadXmlFromFile(sFileName); - - if (!root) - { - CryLog("Loading Localization File %s failed!", sFileName); - return false; - } - - for (int i = 0; i < root->getChildCount(); i++) - { - XmlNodeRef typeNode = root->getChild(i); - string sType = typeNode->getTag(); - - // tags should be unique - if (m_tagFileNames.find(sType) != m_tagFileNames.end()) - { - continue; - } - - TStringVec vEntries; - for (int j = 0; j < typeNode->getChildCount(); j++) - { - XmlNodeRef entry = typeNode->getChild(j); - if (!entry->isTag("entry")) - { - continue; - } - - vEntries.push_back(entry->getContent()); - } - - CRY_ASSERT(m_tagFileNames.size() < 255); - - uint8 curNumTags = m_tagFileNames.size(); - - m_tagFileNames[sType].filenames = vEntries; - m_tagFileNames[sType].id = curNumTags + 1; - m_tagFileNames[sType].loaded = false; - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::RequestLoadLocalizationDataByTag(const char* sTag) -{ - TTagFileNames::iterator it = m_tagFileNames.find(sTag); - if (it == m_tagFileNames.end()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "[LocError] RequestLoadLocalizationDataByTag - Localization tag '%s' not found", sTag); - return false; - } - - if (m_cvarLocalizationDebug >= 2) - { - CryLog(" RequestLoadLocalizationDataByTag %s", sTag); - } - - m_tagLoadRequests.push_back(sTag); - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::LoadLocalizationDataByTag( - const char* sTag, bool bReload) -{ - TTagFileNames::iterator it = m_tagFileNames.find(sTag); - if (it == m_tagFileNames.end()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "[LocError] LoadLocalizationDataByTag - Localization tag '%s' not found", sTag); - return false; - } - - if (it->second.loaded) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "[LocError] LoadLocalizationDataByTag - Already loaded tag '%s'", sTag); - return true; - } - - bool bResult = true; - - stack_string const sLocalizationFolder(PathUtil::GetLocalizationFolder()); - - LoadFunc loadFunction = GetLoadFunction(); - TStringVec& vEntries = it->second.filenames; - for (TStringVec::iterator it2 = vEntries.begin(); it2 != vEntries.end(); ++it2) - { - //Only load files of the correct type for the configured format - if ((m_cvarLocalizationFormat == 0 && strstr(*it2, ".xml")) || (m_cvarLocalizationFormat == 1 && strstr(*it2, ".agsxml"))) - { - bResult &= (this->*loadFunction)(*it2, it->second.id, bReload); - } - } - - if (m_cvarLocalizationDebug >= 2) - { - CryLog(" LoadLocalizationDataByTag %s with result %d", sTag, bResult); - } - - it->second.loaded = true; - - return bResult; -} - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::ReleaseLocalizationDataByTag( - const char* sTag) -{ - INDENT_LOG_DURING_SCOPE(true, "Releasing localization data with the tag '%s'", sTag); - ListAndClearProblemLabels(); - - TTagFileNames::iterator it = m_tagFileNames.find(sTag); - if (it == m_tagFileNames.end()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "[LocError] ReleaseLocalizationDataByTag - Localization tag '%s' not found", sTag); - return false; - } - - if (it->second.loaded == false) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "[LocError] ReleaseLocalizationDataByTag - tag '%s' not loaded", sTag); - return false; - } - - const uint8 nTagID = it->second.id; - - tmapFilenames newLoadedTables; - for (tmapFilenames::iterator iter = m_loadedTables.begin(); iter != m_loadedTables.end(); iter++) - { - if (iter->second.nTagID != nTagID) - { - newLoadedTables[iter->first] = iter->second; - } - } - m_loadedTables = newLoadedTables; - - if (m_pLanguage) - { - //LARGE_INTEGER liStart; - //QueryPerformanceCounter(&liStart); - AutoLock lock(m_cs); //Make sure to lock, as this is a modifying operation - - bool bMapEntryErased = false; - //First, remove entries from the map - for (StringsKeyMap::iterator keyMapIt = m_pLanguage->m_keysMap.begin(); keyMapIt != m_pLanguage->m_keysMap.end(); ) - { - if (keyMapIt->second->nTagID == nTagID) - { - //VECTORMAP ONLY - keyMapIt = m_pLanguage->m_keysMap.erase(keyMapIt); - bMapEntryErased = true; - } - else - { - keyMapIt++; - } - } - - if (bMapEntryErased == true) - { - StringsKeyMap newMap = m_pLanguage->m_keysMap; - m_pLanguage->m_keysMap.clearAndFreeMemory(); - m_pLanguage->m_keysMap = newMap; - } - - bool bVecEntryErased = false; - //Then remove the entries in the storage vector - const uint32 numEntries = m_pLanguage->m_vLocalizedStrings.size(); - for (int32 i = numEntries - 1; i >= 0; i--) - { - SLocalizedStringEntry* entry = m_pLanguage->m_vLocalizedStrings[i]; - PREFAST_ASSUME(entry); - if (entry->nTagID == nTagID) - { - if (m_cvarLocalizationEncode == 1) - { - if (entry->huffmanTreeIndex != -1) - { - HuffmanCoder* pCoder = m_pLanguage->m_vEncoders[entry->huffmanTreeIndex]; - if (pCoder != NULL) - { - pCoder->DecRef(); - if (pCoder->RefCount() == 0) - { - if (m_cvarLocalizationDebug >= 2) - { - CryLog(" Releasing coder %u as it no longer has associated strings", entry->huffmanTreeIndex); - } - //This coding table no longer needed, it has no more associated strings - SAFE_DELETE(m_pLanguage->m_vEncoders[entry->huffmanTreeIndex]); - } - } - } - } - bVecEntryErased = true; - delete(entry); - m_pLanguage->m_vLocalizedStrings.erase(m_pLanguage->m_vLocalizedStrings.begin() + i); - } - } - - //Shrink the vector if necessary - if (bVecEntryErased == true) - { - SLanguage::TLocalizedStringEntries newVec = m_pLanguage->m_vLocalizedStrings; - m_pLanguage->m_vLocalizedStrings.clear(); - m_pLanguage->m_vLocalizedStrings = newVec; - } - - /*LARGE_INTEGER liEnd, liFreq; - QueryPerformanceCounter(&liEnd); - QueryPerformanceFrequency(&liFreq); - - CTimeValue lockTime = CTimeValue((liEnd.QuadPart - liStart.QuadPart) * CTimeValue::TIMEVALUE_PRECISION / liFreq.QuadPart); - if (m_cvarLocalizationDebug >= 2) - { - CryLog(" ReleaseLocalizationDataByTag %s lock time %fMS", sTag, lockTime.GetMilliSeconds()); - }*/ - } - - if (m_cvarLocalizationDebug >= 2) - { - CryLog(" ReleaseLocalizationDataByTag %s", sTag); - } - - it->second.loaded = false; - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::LoadAllLocalizationData(bool bReload) -{ - for (TTagFileNames::iterator it = m_tagFileNames.begin(); it != m_tagFileNames.end(); ++it) - { - if(!LoadLocalizationDataByTag(it->first, bReload)) - return false; - } - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::LoadExcelXmlSpreadsheet(const char* sFileName, bool bReload) -{ - LoadFunc loadFunction = GetLoadFunction(); - return (this->*loadFunction)(sFileName, 0, bReload); -} - -////////////////////////////////////////////////////////////////////// -// Loads a string-table from a Excel XML Spreadsheet file. -bool CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet(const char* sFileName, uint8 nTagID, bool bReload) -{ - LOADING_TIME_PROFILE_SECTION_ARGS(sFileName) - if (!m_pLanguage) - { - return false; - } - - //check if this table has already been loaded - if (!bReload) - { - if (m_loadedTables.find(CONST_TEMP_STRING(sFileName)) != m_loadedTables.end()) - { - return (true); - } - } - - ListAndClearProblemLabels(); - - IXmlTableReader* const pXmlTableReader = m_pSystem->GetXmlUtils()->CreateXmlTableReader(); - if (!pXmlTableReader) - { - CryLog("Loading Localization File %s failed (XML system failure)!", sFileName); - return false; - } - - XmlNodeRef root; - string sPath; - { - const string sLocalizationFolder(PathUtil::GetLocalizationRoot()); - const string& languageFolder = m_pLanguage->sLanguage; - sPath = sLocalizationFolder.c_str() + languageFolder + PathUtil::GetSlash() + sFileName; - root = m_pSystem->LoadXmlFromFile(sPath); - if (!root) - { - CryLog("Loading Localization File %s failed!", sPath.c_str()); - pXmlTableReader->Release(); - return false; - } - } - - // bug search, re-export to a file to compare it - //string sReExport = sFileName; - //sReExport += ".re"; - //root->saveToFile(sReExport.c_str()); - - CryLog("Loading Localization File %s", sFileName); - INDENT_LOG_DURING_SCOPE(); - - //Create a huffman coding table for these strings - if they're going to be encoded or compressed - HuffmanCoder* pEncoder = NULL; - uint8 iEncoder = 0; - size_t startOfStringsToCompress = 0; - if (m_cvarLocalizationEncode == 1) - { - { - for (iEncoder = 0; iEncoder < m_pLanguage->m_vEncoders.size(); iEncoder++) - { - if (m_pLanguage->m_vEncoders[iEncoder] == NULL) - { - m_pLanguage->m_vEncoders[iEncoder] = pEncoder = new HuffmanCoder(); - break; - } - } - if (iEncoder == m_pLanguage->m_vEncoders.size()) - { - pEncoder = new HuffmanCoder(); - m_pLanguage->m_vEncoders.push_back(pEncoder); - } - //Make a note of the current end of the loc strings array, as encoding is done in two passes. - //One pass to build the code table, another to apply it - pEncoder->Init(); - } - startOfStringsToCompress = m_pLanguage->m_vLocalizedStrings.size(); - } - - { - if (!pXmlTableReader->Begin(root)) - { - CryLog("Loading Localization File %s failed! The file is in an unsupported format.", sPath.c_str()); - pXmlTableReader->Release(); - return false; - } - } - - int rowCount = pXmlTableReader->GetEstimatedRowCount(); - { - AutoLock lock(m_cs); //Make sure to lock, as this is a modifying operation - m_pLanguage->m_vLocalizedStrings.reserve(m_pLanguage->m_vLocalizedStrings.size() + rowCount); - } - { - AutoLock lock(m_cs); //Make sure to lock, as this is a modifying operation - //VectorMap only, not applicable to std::map - m_pLanguage->m_keysMap.reserve(m_pLanguage->m_keysMap.size() + rowCount); - } - - { - pairFileName sNewFile; - sNewFile.first = sFileName; - sNewFile.second.bDataStripping = false; // this is off for now - sNewFile.second.nTagID = nTagID; - m_loadedTables.insert(sNewFile); - } - - // Cell Index - char nCellIndexToType[MAX_CELL_COUNT]; - memset(nCellIndexToType, 0, sizeof(nCellIndexToType)); - - // SoundMood Index - std::map SoundMoodIndex; - - // EventParameter Index - std::map EventParameterIndex; - - bool bFirstRow = true; - - CryFixedStringT sTmp; - - // lower case event name - char szLowerCaseEvent[128]; - // lower case key - char szLowerCaseKey[1024]; - // key CRC - uint32 keyCRC; - - size_t nMemSize = 0; - - for (;; ) - { - int nRowIndex = -1; - { - if (!pXmlTableReader->ReadRow(nRowIndex)) - { - break; - } - } - - if (bFirstRow) - { - bFirstRow = false; - ParseFirstLine(pXmlTableReader, nCellIndexToType, SoundMoodIndex, EventParameterIndex); - // Skip first row, it contains description only. - continue; - } - - bool bValidKey = false; - bool bValidTranslatedText = false; - bool bValidTranslatedCharacterName = false; - bool bValidTranslatedActorLine = false; - bool bUseSubtitle = true; - bool bIsDirectRadio = false; - bool bIsIntercepted = false; - - struct CConstCharArray - { - const char* ptr; - size_t count; - - CConstCharArray() - { - clear(); - } - void clear() - { - ptr = ""; - count = 0; - } - bool empty() const - { - return count == 0; - } - }; - - CConstCharArray sKeyString; - CConstCharArray sCharacterName; - CConstCharArray sTranslatedCharacterName; // Legacy, to be removed some day... - CConstCharArray sSubtitleText; - CConstCharArray sTranslatedText; // Legacy, to be removed some day... - CConstCharArray sActorLine; - CConstCharArray sTranslatedActorLine; // Legacy, to be removed some day... - CConstCharArray sSoundEvent; - - float fVolume = 1.0f; - float fRadioRatio = 1.0f; - float fEventParameterValue = 0.0f; - float fSoundMoodValue = 0.0f; - - int nItems = 0; - std::map SoundMoodValues; - std::map EventParameterValues; - - for (;; ) - { - int nCellIndex = -1; - CConstCharArray cell; - - { - if (!pXmlTableReader->ReadCell(nCellIndex, cell.ptr, cell.count)) - { - break; - } - } - - if (nCellIndex >= MAX_CELL_COUNT) - { - break; - } - - // skip empty cells - if (cell.count <= 0) - { - continue; - } - - const char nCellType = nCellIndexToType[nCellIndex]; - - switch (nCellType) - { - case ELOCALIZED_COLUMN_SKIP: - break; - case ELOCALIZED_COLUMN_KEY: - sKeyString = cell; - bValidKey = true; - ++nItems; - break; - case ELOCALIZED_COLUMN_AUDIOFILE: - sKeyString = cell; - bValidKey = true; - ++nItems; - break; - case ELOCALIZED_COLUMN_CHARACTER_NAME: - sCharacterName = cell; - ++nItems; - break; - case ELOCALIZED_COLUMN_SUBTITLE_TEXT: - sSubtitleText = cell; - ++nItems; - break; - case ELOCALIZED_COLUMN_ACTOR_LINE: - sActorLine = cell; - ++nItems; - break; - case ELOCALIZED_COLUMN_USE_SUBTITLE: - sTmp.assign(cell.ptr, cell.count); - bUseSubtitle = CryStringUtils::ToYesNoType(sTmp.c_str()) == CryStringUtils::YesNoType::No ? false : true; // favor yes (yes and invalid -> yes) - break; - case ELOCALIZED_COLUMN_VOLUME: - sTmp.assign(cell.ptr, cell.count); - fVolume = (float)atof(sTmp.c_str()); - ++nItems; - break; - case ELOCALIZED_COLUMN_SOUNDEVENT: - sSoundEvent = cell; - ++nItems; - break; - case ELOCALIZED_COLUMN_RADIO_RATIO: - sTmp.assign(cell.ptr, cell.count); - fRadioRatio = (float)atof(sTmp.c_str()); - ++nItems; - break; - case ELOCALIZED_COLUMN_EVENTPARAMETER: - sTmp.assign(cell.ptr, cell.count); - fEventParameterValue = (float)atof(sTmp.c_str()); - { - EventParameterValues[nCellIndex] = fEventParameterValue; - } - ++nItems; - break; - case ELOCALIZED_COLUMN_SOUNDMOOD: - sTmp.assign(cell.ptr, cell.count); - fSoundMoodValue = (float)atof(sTmp.c_str()); - { - SoundMoodValues[nCellIndex] = fSoundMoodValue; - } - ++nItems; - break; - case ELOCALIZED_COLUMN_IS_DIRECT_RADIO: - sTmp.assign(cell.ptr, cell.count); - if (!_stricmp(sTmp.c_str(), "intercept")) - { - bIsIntercepted = true; - } - bIsDirectRadio = bIsIntercepted || (CryStringUtils::ToYesNoType(sTmp.c_str()) == CryStringUtils::YesNoType::Yes ? true : false); // favor no (no and invalid -> no) - ++nItems; - break; - // legacy names - case ELOCALIZED_COLUMN_LEGACY_PERSON: - // old file often only have content in this column - if (!cell.empty()) - { - sCharacterName = cell; - sTranslatedCharacterName = cell; - bValidTranslatedCharacterName = true; - } - ++nItems; - break; - case ELOCALIZED_COLUMN_LEGACY_CHARACTERNAME: - sCharacterName = cell; - sTranslatedCharacterName = cell; - bValidTranslatedCharacterName = true; - ++nItems; - break; - case ELOCALIZED_COLUMN_LEGACY_TRANSLATED_CHARACTERNAME: - sTranslatedCharacterName = cell; - bValidTranslatedCharacterName = true; - ++nItems; - break; - case ELOCALIZED_COLUMN_LEGACY_ENGLISH_DIALOGUE: - // old file often only have content in this column - sActorLine = cell; - sSubtitleText = cell; - ++nItems; - break; - case ELOCALIZED_COLUMN_LEGACY_TRANSLATION: - sTranslatedActorLine = cell; - sTranslatedText = cell; - bValidTranslatedText = true; - ++nItems; - break; - case ELOCALIZED_COLUMN_LEGACY_YOUR_TRANSLATION: - sTranslatedActorLine = cell; - sTranslatedText = cell; - bValidTranslatedText = true; - ++nItems; - break; - case ELOCALIZED_COLUMN_LEGACY_ENGLISH_SUBTITLE: - sSubtitleText = cell; - ++nItems; - break; - case ELOCALIZED_COLUMN_LEGACY_TRANSLATED_SUBTITLE: - sTranslatedText = cell; - sTranslatedActorLine = cell; - bValidTranslatedText = true; - ++nItems; - break; - case ELOCALIZED_COLUMN_LEGACY_ORIGINAL_CHARACTER_NAME: - sCharacterName = cell; - ++nItems; - break; - case ELOCALIZED_COLUMN_LEGACY_TRANSLATED_CHARACTER_NAME: - sTranslatedCharacterName = cell; - bValidTranslatedCharacterName = true; - ++nItems; - break; - case ELOCALIZED_COLUMN_LEGACY_ORIGINAL_TEXT: - sSubtitleText = cell; - ++nItems; - break; - case ELOCALIZED_COLUMN_LEGACY_TRANSLATED_TEXT: - sTranslatedText = cell; - bValidTranslatedText = true; - ++nItems; - break; - case ELOCALIZED_COLUMN_LEGACY_ORIGINAL_ACTOR_LINE: - sActorLine = cell; - ++nItems; - break; - case ELOCALIZED_COLUMN_LEGACY_TRANSLATED_ACTOR_LINE: - sTranslatedActorLine = cell; - bValidTranslatedActorLine = true; - ++nItems; - break; - } - } - - if (!bValidKey) - { - continue; - } - - if (!bValidTranslatedText) - { - // if this is a dialog entry with a soundevent and with subtitles then a warning should be issued - if (m_cvarLocalizationDebug && !sSoundEvent.empty() && bUseSubtitle) - { - sTmp.assign(sKeyString.ptr, sKeyString.count); - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "[LocError] Key '%s' in file <%s> has no translated text", sTmp.c_str(), sFileName); - } - - // use translated actor line entry if available before falling back to original entry - if (!sTranslatedActorLine.empty()) - { - sTranslatedText = sTranslatedActorLine; - } - else - { - sTranslatedText = sSubtitleText; - } - } - - if (!bValidTranslatedActorLine) - { - // if this is a dialog entry with a soundevent then a warning should be issued - if (m_cvarLocalizationDebug && !sSoundEvent.empty()) - { - sTmp.assign(sKeyString.ptr, sKeyString.count); - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "[LocError] Key '%s' in file <%s> has no translated actor line", sTmp.c_str(), sFileName); - } - - // use translated text entry if available before falling back to original entry - if (!sTranslatedText.empty()) - { - sTranslatedActorLine = sTranslatedText; - } - else - { - sTranslatedActorLine = sSubtitleText; - } - } - - if (!sSoundEvent.empty() && !bValidTranslatedCharacterName) - { - if (m_cvarLocalizationDebug) - { - sTmp.assign(sKeyString.ptr, sKeyString.count); - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "[LocError] Key '%s' in file <%s> has no translated character name", sTmp.c_str(), sFileName); - } - - sTranslatedCharacterName = sCharacterName; - } - - if (nItems == 1) // skip lines which contain just one item in the key - { - continue; - } - - // reject to store text if line was marked with no subtitles in game mode - if (!gEnv->IsEditor()) - { - if (!bUseSubtitle) - { - sSubtitleText.clear(); - sTranslatedText.clear(); - } - } - - // Skip @ character in the key string. - if (!sKeyString.empty() && sKeyString.ptr[0] == '@') - { - sKeyString.ptr++; - sKeyString.count--; - } - - { - CopyLowercase(szLowerCaseEvent, sizeof(szLowerCaseEvent), sSoundEvent.ptr, sSoundEvent.count); - CopyLowercase(szLowerCaseKey, sizeof(szLowerCaseKey), sKeyString.ptr, sKeyString.count); - } - - //Compute the CRC32 of the key - keyCRC = CCrc32::Compute(szLowerCaseKey); - if (m_cvarLocalizationDebug >= 3) - { - CryLogAlways(" CRC32: 0x%8X, Key: %s", keyCRC, szLowerCaseKey); - } - - if (m_pLanguage->m_keysMap.find(keyCRC) != m_pLanguage->m_keysMap.end()) - { - sTmp.assign(sKeyString.ptr, sKeyString.count); - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "[LocError] Localized String '%s' Already Loaded for Language %s OR there is a CRC hash clash", sTmp.c_str(), m_pLanguage->sLanguage.c_str()); - continue; - } - - SLocalizedStringEntry* pEntry = new SLocalizedStringEntry(); - pEntry->flags = 0; - - if (bUseSubtitle == true) - { - pEntry->flags |= SLocalizedStringEntry::USE_SUBTITLE; - } - pEntry->nTagID = nTagID; - - if (gEnv->IsEditor()) - { - pEntry->pEditorExtension = new SLocalizedStringEntryEditorExtension(); - - pEntry->pEditorExtension->sKey = szLowerCaseKey; - - pEntry->pEditorExtension->nRow = nRowIndex; - - if (!sActorLine.empty()) - { - sTmp.assign(sActorLine.ptr, sActorLine.count); - ReplaceEndOfLine(sTmp); - pEntry->pEditorExtension->sOriginalActorLine.assign(sTmp.c_str()); - } - if (!sTranslatedActorLine.empty()) - { - sTmp.assign(sTranslatedActorLine.ptr, sTranslatedActorLine.count); - ReplaceEndOfLine(sTmp); - pEntry->pEditorExtension->sUtf8TranslatedActorLine.append(sTmp.c_str()); - } - if (bUseSubtitle && !sSubtitleText.empty()) - { - sTmp.assign(sSubtitleText.ptr, sSubtitleText.count); - ReplaceEndOfLine(sTmp); - pEntry->pEditorExtension->sOriginalText.assign(sTmp.c_str()); - } - // only use the translated character name - { - pEntry->pEditorExtension->sOriginalCharacterName.assign(sCharacterName.ptr, sCharacterName.count); - } - } - - if (bUseSubtitle && !sTranslatedText.empty()) - { - sTmp.assign(sTranslatedText.ptr, sTranslatedText.count); - ReplaceEndOfLine(sTmp); - if (m_cvarLocalizationEncode == 1) - { - pEncoder->Update((const uint8*)(sTmp.c_str()), sTmp.length()); - //CryLogAlways("%u Storing %s (%u)", m_pLanguage->m_vLocalizedStrings.size(), sTmp.c_str(), sTmp.length()); - pEntry->TranslatedText.szCompressed = new uint8[sTmp.length() + 1]; - pEntry->flags |= SLocalizedStringEntry::IS_COMPRESSED; - //Store the raw string. It'll be compressed later - memcpy(pEntry->TranslatedText.szCompressed, sTmp.c_str(), sTmp.length()); - pEntry->TranslatedText.szCompressed[sTmp.length()] = '\0'; //Null terminate - } - else - { - pEntry->TranslatedText.psUtf8Uncompressed = new string(sTmp.c_str(), sTmp.c_str() + sTmp.length()); - } - } - - // the following is used to cleverly assign strings - // we store all known string into the m_prototypeEvents set and assign known entries from there - // the CryString makes sure, that only the ref-count is increment on assignment - if (*szLowerCaseEvent) - { - PrototypeSoundEvents::iterator it = m_prototypeEvents.find(CONST_TEMP_STRING(szLowerCaseEvent)); - if (it != m_prototypeEvents.end()) - { - pEntry->sPrototypeSoundEvent = *it; - } - else - { - pEntry->sPrototypeSoundEvent = szLowerCaseEvent; - m_prototypeEvents.insert(pEntry->sPrototypeSoundEvent); - } - } - - const CConstCharArray sWho = sTranslatedCharacterName.empty() ? sCharacterName : sTranslatedCharacterName; - if (!sWho.empty()) - { - sTmp.assign(sWho.ptr, sWho.count); - ReplaceEndOfLine(sTmp); - sTmp.replace(" ", "_"); - string tmp; - { - tmp = sTmp.c_str(); - } - CharacterNameSet::iterator it = m_characterNameSet.find(tmp); - if (it != m_characterNameSet.end()) - { - pEntry->sCharacterName = *it; - } - else - { - pEntry->sCharacterName = tmp; - m_characterNameSet.insert(pEntry->sCharacterName); - } - } - - pEntry->fVolume = CryConvertFloatToHalf(fVolume); - - // SoundMood Entries - { - pEntry->SoundMoods.resize(SoundMoodValues.size()); - if (SoundMoodValues.size() > 0) - { - std::map::const_iterator itEnd = SoundMoodValues.end(); - int nSoundMoodCount = 0; - for (std::map::const_iterator it = SoundMoodValues.begin(); it != itEnd; ++it) - { - pEntry->SoundMoods[nSoundMoodCount].fValue = (*it).second; - pEntry->SoundMoods[nSoundMoodCount].sName = SoundMoodIndex[(*it).first]; - ++nSoundMoodCount; - } - } - } - - // EventParameter Entries - { - pEntry->EventParameters.resize(EventParameterValues.size()); - if (EventParameterValues.size() > 0) - { - std::map::const_iterator itEnd = EventParameterValues.end(); - int nEventParameterCount = 0; - for (std::map::const_iterator it = EventParameterValues.begin(); it != itEnd; ++it) - { - pEntry->EventParameters[nEventParameterCount].fValue = (*it).second; - pEntry->EventParameters[nEventParameterCount].sName = EventParameterIndex[(*it).first]; - ++nEventParameterCount; - } - } - } - - pEntry->fRadioRatio = CryConvertFloatToHalf(fRadioRatio); - - if (bIsDirectRadio == true) - { - pEntry->flags |= SLocalizedStringEntry::IS_DIRECTED_RADIO; - } - if (bIsIntercepted == true) - { - pEntry->flags |= SLocalizedStringEntry::IS_INTERCEPTED; - } - - nMemSize += sizeof(*pEntry) + pEntry->sCharacterName.length() * sizeof(char); - if (m_cvarLocalizationEncode == 0) - { - //Note that this isn't accurate if we're using encoding/compression to shrink the string as the encoding step hasn't happened yet - if (pEntry->TranslatedText.psUtf8Uncompressed) - { - nMemSize += pEntry->TranslatedText.psUtf8Uncompressed->length() * sizeof(char); - } - } - if (pEntry->pEditorExtension != NULL) - { - nMemSize += pEntry->pEditorExtension->sKey.length() - + pEntry->pEditorExtension->sOriginalActorLine.length() - + pEntry->pEditorExtension->sUtf8TranslatedActorLine.length() * sizeof(char) - + pEntry->pEditorExtension->sOriginalText.length() - + pEntry->pEditorExtension->sOriginalCharacterName.length(); - } - - - // Compression Preparation - //unsigned int nSourceSize = pEntry->swTranslatedText.length()*sizeof(wchar_t); - //if (nSourceSize) - // int zResult = Compress(pDest, nDestLen, pEntry->swTranslatedText.c_str(), nSourceSize); - - AddLocalizedString(m_pLanguage, pEntry, keyCRC); - } - - if (m_cvarLocalizationEncode == 1) - { - pEncoder->Finalize(); - - { - uint8 compressionBuffer[COMPRESSION_FIXED_BUFFER_LENGTH]; - //uint8 decompressionBuffer[COMPRESSION_FIXED_BUFFER_LENGTH]; - size_t uncompressedTotal = 0, compressedTotal = 0; - for (size_t stringToCompress = startOfStringsToCompress; stringToCompress < m_pLanguage->m_vLocalizedStrings.size(); stringToCompress++) - { - SLocalizedStringEntry* pStringToCompress = m_pLanguage->m_vLocalizedStrings[stringToCompress]; - if (pStringToCompress->TranslatedText.szCompressed != NULL) - { - size_t compBufSize = COMPRESSION_FIXED_BUFFER_LENGTH; - memset(compressionBuffer, 0, COMPRESSION_FIXED_BUFFER_LENGTH); - //CryLogAlways("%u Compressing %s (%p)", stringToCompress, pStringToCompress->szCompressedTranslatedText, pStringToCompress->szCompressedTranslatedText); - size_t inputStringLength = strlen((const char*)(pStringToCompress->TranslatedText.szCompressed)); - pEncoder->CompressInput(pStringToCompress->TranslatedText.szCompressed, inputStringLength, compressionBuffer, &compBufSize); - compressionBuffer[compBufSize] = 0; - pStringToCompress->huffmanTreeIndex = iEncoder; - pEncoder->AddRef(); - //CryLogAlways("Compressed %s (%u) to %s (%u)", pStringToCompress->szCompressedTranslatedText, strlen((const char*)pStringToCompress->szCompressedTranslatedText), compressionBuffer, compBufSize); - uncompressedTotal += inputStringLength; - compressedTotal += compBufSize; - - uint8* szCompressedString = new uint8[compBufSize]; - SAFE_DELETE_ARRAY(pStringToCompress->TranslatedText.szCompressed); - - memcpy(szCompressedString, compressionBuffer, compBufSize); - pStringToCompress->TranslatedText.szCompressed = szCompressedString; - - //Testing code - //memset( decompressionBuffer, 0, COMPRESSION_FIXED_BUFFER_LENGTH ); - //size_t decompBufSize = pEncoder->UncompressInput(compressionBuffer, COMPRESSION_FIXED_BUFFER_LENGTH, decompressionBuffer, COMPRESSION_FIXED_BUFFER_LENGTH); - //CryLogAlways("Decompressed %s (%u) to %s (%u)", compressionBuffer, compBufSize, decompressionBuffer, decompBufSize); - } - } - //CryLogAlways("[LOC PROFILING] %s, %u, Uncompressed %u, Compressed %u", sFileName, m_pLanguage->m_vLocalizedStrings.size() - startOfStringsToCompress, uncompressedTotal, compressedTotal); - } - } - - pXmlTableReader->Release(); - - return true; -} - -bool CLocalizedStringsManager::DoLoadAGSXmlDocument(const char* sFileName, uint8 nTagID, bool bReload) -{ - if (!sFileName) - { - return false; - } - if (!m_pLanguage) - { - return false; - } - if (!bReload) - { - if (m_loadedTables.find(CONST_TEMP_STRING(sFileName)) != m_loadedTables.end()) - { - return true; - } - } - ListAndClearProblemLabels(); - XmlNodeRef root; - string sPath; - { - const string sLocalizationFolder(PathUtil::GetLocalizationRoot()); - const string& languageFolder = m_pLanguage->sLanguage; - sPath = sLocalizationFolder.c_str() + languageFolder + PathUtil::GetSlash() + sFileName; - root = m_pSystem->LoadXmlFromFile(sPath); - if (!root) - { - AZ_TracePrintf(LOC_WINDOW, "Loading Localization File %s failed!", sPath.c_str()); - return false; - } - } - AZ_TracePrintf(LOC_WINDOW, "Loading Localization File %s", sPath.c_str()); - HuffmanCoder* pEncoder = nullptr; - uint8 iEncoder = 0; - size_t startOfStringsToCompress = 0; - if (m_cvarLocalizationEncode == 1) - { - { - for (iEncoder = 0; iEncoder < m_pLanguage->m_vEncoders.size(); iEncoder++) - { - if (m_pLanguage->m_vEncoders[iEncoder] == nullptr) - { - pEncoder = new HuffmanCoder(); - m_pLanguage->m_vEncoders[iEncoder] = pEncoder; - break; - } - } - if (iEncoder == m_pLanguage->m_vEncoders.size()) - { - pEncoder = new HuffmanCoder(); - m_pLanguage->m_vEncoders.push_back(pEncoder); - } - pEncoder->Init(); - } - startOfStringsToCompress = m_pLanguage->m_vLocalizedStrings.size(); - } - int rowCount = 0; - { - AutoLock lock(m_cs); // Make sure to lock, as this is a modifying operation - rowCount = root->getChildCount(); - { - m_pLanguage->m_vLocalizedStrings.reserve(m_pLanguage->m_vLocalizedStrings.size() + rowCount); - } - m_pLanguage->m_keysMap.reserve(m_pLanguage->m_keysMap.size() + rowCount); - } - { - pairFileName sNewFile; - sNewFile.first = sFileName; - sNewFile.second.bDataStripping = false; // this is off for now - sNewFile.second.nTagID = nTagID; - m_loadedTables.insert(sNewFile); - } - const char* key = nullptr; - AZStd::string keyString; - AZStd::string lowerKey; - AZStd::string textValue; - uint32 keyCRC=0; - for (int i = 0; i < rowCount; ++i) - { - XmlNodeRef childNode = root->getChild(i); - if (azstricmp(childNode->getTag(), "string") || !childNode->getAttr("key", &key)) - { - continue; - } - keyString = key; - textValue = childNode->getContent(); - if (textValue.empty()) - { - continue; - } - AzFramework::StringFunc::Replace(textValue, "\\n", " \n"); // carried over from helper func ReplaceEndOfLine(CryFixedStringT<>& s) - if (keyString[0] == '@') - { - AzFramework::StringFunc::LChop(keyString, 1); - } - lowerKey = keyString; - AZStd::to_lower(lowerKey.begin(), lowerKey.end()); - keyCRC = CCrc32::Compute(lowerKey.c_str()); - if (m_cvarLocalizationDebug >= 3) - { - CryLogAlways(" CRC32: 0%8X, Key: %s", keyCRC, lowerKey.c_str()); - } - if (m_pLanguage->m_keysMap.find(keyCRC) != m_pLanguage->m_keysMap.end()) - { - AZ_Warning(LOC_WINDOW, false, "Localized String '%s' Already Loaded for Language %s OR there is a CRC hash clash", keyString.c_str(), m_pLanguage->sLanguage.c_str()); - continue; - } - SLocalizedStringEntry* pEntry = new SLocalizedStringEntry; - pEntry->flags = SLocalizedStringEntry::USE_SUBTITLE; - pEntry->nTagID = nTagID; - if (gEnv->IsEditor()) - { - pEntry->pEditorExtension = new SLocalizedStringEntryEditorExtension(); - pEntry->pEditorExtension->sKey = lowerKey.c_str(); - pEntry->pEditorExtension->nRow = i; - { - pEntry->pEditorExtension->sUtf8TranslatedActorLine.append(textValue.c_str()); - } - { - pEntry->pEditorExtension->sOriginalText.assign(textValue.c_str()); - } - } - { - const char* textString = textValue.c_str(); - size_t textLength = textValue.length(); - if (m_cvarLocalizationEncode == 1) - { - pEncoder->Update((const uint8*)(textString), textLength); - pEntry->TranslatedText.szCompressed = new uint8[textLength + 1]; - pEntry->flags |= SLocalizedStringEntry::IS_COMPRESSED; - memcpy(pEntry->TranslatedText.szCompressed, textString, textLength); - pEntry->TranslatedText.szCompressed[textLength] = '\0'; //Null terminate - } - else - { - pEntry->TranslatedText.psUtf8Uncompressed = new string(textString, textString + textLength); - } - } - { - AddLocalizedString(m_pLanguage, pEntry, keyCRC); - } - } - if (m_cvarLocalizationEncode == 1) - { - { - pEncoder->Finalize(); - } - { - uint8 compressionBuffer[COMPRESSION_FIXED_BUFFER_LENGTH] = {}; - size_t uncompressedTotal = 0, compressedTotal = 0; - for (size_t stringToCompress = startOfStringsToCompress; stringToCompress < m_pLanguage->m_vLocalizedStrings.size(); stringToCompress++) - { - SLocalizedStringEntry* pStringToCompress = m_pLanguage->m_vLocalizedStrings[stringToCompress]; - if (pStringToCompress->TranslatedText.szCompressed != nullptr) - { - size_t compBufSize = COMPRESSION_FIXED_BUFFER_LENGTH; - memset(compressionBuffer, 0, COMPRESSION_FIXED_BUFFER_LENGTH); - size_t inputStringLength = strnlen((const char*)(pStringToCompress->TranslatedText.szCompressed), COMPRESSION_FIXED_BUFFER_LENGTH); - pEncoder->CompressInput(pStringToCompress->TranslatedText.szCompressed, inputStringLength, compressionBuffer, &compBufSize); - compressionBuffer[compBufSize] = 0; - pStringToCompress->huffmanTreeIndex = iEncoder; - pEncoder->AddRef(); - uncompressedTotal += inputStringLength; - compressedTotal += compBufSize; - uint8* szCompressedString = new uint8[compBufSize]; - SAFE_DELETE_ARRAY(pStringToCompress->TranslatedText.szCompressed); - memcpy(szCompressedString, compressionBuffer, compBufSize); - pStringToCompress->TranslatedText.szCompressed = szCompressedString; - } - } - } - } - return true; -} -////////////////////////////////////////////////////////////////////////// -CLocalizedStringsManager::LoadFunc CLocalizedStringsManager::GetLoadFunction() const -{ - CRY_ASSERT_MESSAGE(gEnv && gEnv->pConsole, "System environment or console missing!"); - if (gEnv && gEnv->pConsole) - { - if(m_cvarLocalizationFormat == 1) - { - return &CLocalizedStringsManager::DoLoadAGSXmlDocument; - } - } - return &CLocalizedStringsManager::DoLoadExcelXmlSpreadsheet; -} -void CLocalizedStringsManager::ReloadData() -{ - tmapFilenames temp = m_loadedTables; - - LoadFunc loadFunction = GetLoadFunction(); - FreeLocalizationData(); - for (tmapFilenames::iterator it = temp.begin(); it != temp.end(); it++) - { - (this->*loadFunction)((*it).first, (*it).second.nTagID, true); - } -} - -////////////////////////////////////////////////////////////////////////// -void CLocalizedStringsManager::AddLocalizedString(SLanguage* pLanguage, SLocalizedStringEntry* pEntry, const uint32 keyCRC32) -{ - pLanguage->m_vLocalizedStrings.push_back(pEntry); - int nId = (int)pLanguage->m_vLocalizedStrings.size() - 1; - pLanguage->m_keysMap[keyCRC32] = pEntry; - - if (m_cvarLocalizationDebug >= 2) - { - CryLog(" Add new string <%u> with ID %d to <%s>", keyCRC32, nId, pLanguage->sLanguage.c_str()); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::LocalizeString_ch(const char* sString, string& outLocalizedString, bool bEnglish) -{ - return LocalizeStringInternal(sString, strlen(sString), outLocalizedString, bEnglish); -} - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::LocalizeString_s(const string& sString, string& outLocalizedString, bool bEnglish) -{ - return LocalizeStringInternal(sString.c_str(), sString.length(), outLocalizedString, bEnglish); -} - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::LocalizeStringInternal(const char* pStr, size_t len, string& outLocalizedString, bool bEnglish) -{ - assert (m_pLanguage); - if (m_pLanguage == 0) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "LocalizeString: No language set."); - outLocalizedString.assign(pStr, pStr + len); - return false; - } - - // note: we don't write directly to outLocalizedString, in case it aliases pStr - string out; - - // scan the string - const char* pPos = pStr; - const char* pEnd = pStr + len; - while (true) - { - const char* pLabel = strchr(pPos, '@'); - if (!pLabel) - { - break; - } - // found an occurrence - - // we have skipped a few characters, so copy them over - if (pLabel != pPos) - { - out.append(pPos, pLabel); - } - - // Search label for first occurence of any label terminating character - const char* pLabelEnd = strpbrk(pLabel, " !\"#$%&\'()*+,./:;<=>\?[\\]^`{|}~\n\t\r"); - if (!pLabelEnd) - { - pLabelEnd = pEnd; - } - - // localize token - string token(pLabel, pLabelEnd); - string sLocalizedToken; - if (bEnglish) - { - GetEnglishString(token.c_str(), sLocalizedToken); - } - else - { - LocalizeLabel(token.c_str(), sLocalizedToken); - } - out.append(sLocalizedToken); - pPos = pLabelEnd; - } - out.append(pPos, pEnd); - out.swap(outLocalizedString); - return true; -} - -void CLocalizedStringsManager::LocalizeAndSubstituteInternal(AZStd::string& locString, const AZStd::vector& keys, const AZStd::vector& values) -{ - string outString; - LocalizeString_ch(locString.c_str(), outString); - locString = outString .c_str(); - if (values.size() != keys.size()) - { - AZ_Warning("game", false, "Localization Error: LocalizeAndSubstitute was given %u keys and %u values to replace. These numbers must be equal.", keys.size(), values.size()); - return; - } - size_t startIndex = locString.find('{'); - size_t endIndex = locString.find('}', startIndex); - while (startIndex != AZStd::string::npos && endIndex != AZStd::string::npos) - { - const size_t subLength = endIndex - startIndex - 1; - AZStd::string substituteOut = locString.substr(startIndex + 1, subLength).c_str(); - int index = 0; - if (LocalizationHelpers::IsKeyInList(keys, substituteOut, index)) - { - const char* value = values[index].c_str(); - locString.replace(startIndex, subLength + 2, value); - startIndex += strlen(value); - } - else - { - AZ_Warning("game", false, "Localization Error: Localized string '%s' contains a key '%s' that is not mapped to a data element.", locString.c_str(), substituteOut.c_str()); - startIndex += substituteOut.length(); - } - startIndex = locString.find_first_of('{', startIndex); - endIndex = locString.find_first_of('}', startIndex); - } -} -#if defined(LOG_DECOMP_TIMES) -static double g_fSecondsPerTick = 0.0; -static FILE* pDecompLog = NULL; -// engine independent game timer since gEnv/pSystem isn't available yet -static void LogDecompTimer(__int64 nTotalTicks, __int64 nDecompTicks, __int64 nAllocTicks) -{ - if (g_fSecondsPerTick == 0.0) - { - __int64 nPerfFreq; - QueryPerformanceFrequency((LARGE_INTEGER*)&nPerfFreq); - g_fSecondsPerTick = 1.0 / (double)nPerfFreq; - } - - if (!pDecompLog) - { - char szFilenameBuffer[MAX_PATH]; - time_t rawTime; - time(&rawTime); - struct tm* pTimeInfo = localtime(&rawTime); - - CreateDirectory("TestResults\\", 0); - strftime(szFilenameBuffer, sizeof(szFilenameBuffer), "TestResults\\Decomp_%Y_%m_%d-%H_%M_%S.csv", pTimeInfo); - pDecompLog = fopen(szFilenameBuffer, "wb"); - fprintf(pDecompLog, "Total,Decomp,Alloc\n"); - } - float nTotalMillis = float( g_fSecondsPerTick * 1000.0 * nTotalTicks ); - float nDecompMillis = float( g_fSecondsPerTick * 1000.0 * nDecompTicks ); - float nAllocMillis = float( g_fSecondsPerTick * 1000.0 * nAllocTicks ); - fprintf(pDecompLog, "%f,%f,%f\n", nTotalMillis, nDecompMillis, nAllocMillis); - fflush(pDecompLog); -} -#endif - -string CLocalizedStringsManager::SLocalizedStringEntry::GetTranslatedText(const SLanguage* pLanguage) const -{ - FUNCTION_PROFILER_FAST(GetISystem(), PROFILE_SYSTEM, g_bProfilerEnabled); - if ((flags & IS_COMPRESSED) != 0) - { -#if defined(LOG_DECOMP_TIMES) - __int64 nTotalTicks, nDecompTicks, nAllocTicks; - nTotalTicks = CryGetTicks(); -#endif //LOG_DECOMP_TIMES - - string outputString; - if (TranslatedText.szCompressed != NULL) - { - uint8 decompressionBuffer[COMPRESSION_FIXED_BUFFER_LENGTH]; - HuffmanCoder* pEncoder = pLanguage->m_vEncoders[huffmanTreeIndex]; - -#if defined(LOG_DECOMP_TIMES) - nDecompTicks = CryGetTicks(); -#endif //LOG_DECOMP_TIMES - - //We don't actually know how much memory was allocated for this string, but the maximum compression buffer size is known - size_t decompBufSize = pEncoder->UncompressInput(TranslatedText.szCompressed, COMPRESSION_FIXED_BUFFER_LENGTH, decompressionBuffer, COMPRESSION_FIXED_BUFFER_LENGTH); - assert(decompBufSize < COMPRESSION_FIXED_BUFFER_LENGTH && "Buffer overflow"); - -#if defined(LOG_DECOMP_TIMES) - nDecompTicks = CryGetTicks() - nDecompTicks; -#endif //LOG_DECOMP_TIMES - -#if !defined(NDEBUG) - size_t len = -#endif - strnlen((const char*)decompressionBuffer, COMPRESSION_FIXED_BUFFER_LENGTH); - assert(len < COMPRESSION_FIXED_BUFFER_LENGTH && "Buffer not null-terminated"); - - -#if defined(LOG_DECOMP_TIMES) - nAllocTicks = CryGetTicks(); -#endif //LOG_DECOMP_TIMES - - outputString.assign((const char*)decompressionBuffer, (const char*)decompressionBuffer + decompBufSize); - -#if defined(LOG_DECOMP_TIMES) - nAllocTicks = CryGetTicks() - nAllocTicks; - nTotalTicks = CryGetTicks() - nTotalTicks; - LogDecompTimer(nTotalTicks, nDecompTicks, nAllocTicks); -#endif //LOG_DECOMP_TIMES - } - return outputString; - } - else - { - if (TranslatedText.psUtf8Uncompressed != NULL) - { - return *TranslatedText.psUtf8Uncompressed; - } - else - { - string emptyOutputString; - return emptyOutputString; - } - } -} - -#ifndef _RELEASE -////////////////////////////////////////////////////////////////////////// -void CLocalizedStringsManager::LocalizedStringsManagerWarning(const char* label, const char* message) -{ - if (!m_warnedAboutLabels[label]) - { - CryWarning (VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "Failed to localize label '%s' - %s", label, message); - m_warnedAboutLabels[label] = true; - m_haveWarnedAboutAtLeastOneLabel = true; - } -} - -////////////////////////////////////////////////////////////////////////// -void CLocalizedStringsManager::ListAndClearProblemLabels() -{ - if (m_haveWarnedAboutAtLeastOneLabel) - { - CryLog ("These labels caused localization problems:"); - INDENT_LOG_DURING_SCOPE(); - - for (std::map::iterator iter = m_warnedAboutLabels.begin(); iter != m_warnedAboutLabels.end(); iter++) - { - CryLog ("%s", iter->first.c_str()); - } - - m_warnedAboutLabels.clear(); - m_haveWarnedAboutAtLeastOneLabel = false; - } -} -#endif - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::LocalizeLabel(const char* sLabel, string& outLocalString, bool bEnglish) -{ - assert(sLabel); - if (!m_pLanguage || !sLabel) - { - return false; - } - - // Label sign. - if (sLabel[0] == '@') - { - uint32 labelCRC32 = CCrc32::ComputeLowercase(sLabel + 1); // skip @ character. - { - AutoLock lock(m_cs); //Lock here, to prevent strings etc being modified underneath this lookup - SLocalizedStringEntry* entry = stl::find_in_map(m_pLanguage->m_keysMap, labelCRC32, NULL); - - if (entry != NULL) - { - - string translatedText = entry->GetTranslatedText(m_pLanguage); - if ((bEnglish || translatedText.empty()) && entry->pEditorExtension != NULL) - { - //assert(!"No Localization Text available!"); - outLocalString.assign(entry->pEditorExtension->sOriginalText); - return true; - } - else - { - outLocalString.swap(translatedText); - } - return true; - } - else - { - LocalizedStringsManagerWarning(sLabel, "entry not found in string table"); - } - } - } - else - { - LocalizedStringsManagerWarning(sLabel, "must start with @ symbol"); - } - - outLocalString.assign(sLabel); - - return false; -} - - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::GetEnglishString(const char* sKey, string& sLocalizedString) -{ - assert(sKey); - if (!m_pLanguage || !sKey) - { - return false; - } - - // Label sign. - if (sKey[0] == '@') - { - uint32 keyCRC32 = CCrc32::ComputeLowercase(sKey + 1); - { - AutoLock lock(m_cs); //Lock here, to prevent strings etc being modified underneath this lookup - SLocalizedStringEntry* entry = stl::find_in_map(m_pLanguage->m_keysMap, keyCRC32, NULL); // skip @ character. - if (entry != NULL && entry->pEditorExtension != NULL) - { - sLocalizedString = entry->pEditorExtension->sOriginalText; - return true; - } - else - { - keyCRC32 = CCrc32::ComputeLowercase(sKey); - entry = stl::find_in_map(m_pLanguage->m_keysMap, keyCRC32, NULL); - if (entry != NULL && entry->pEditorExtension != NULL) - { - sLocalizedString = entry->pEditorExtension->sOriginalText; - return true; - } - else - { - // CryWarning( VALIDATOR_MODULE_SYSTEM,VALIDATOR_WARNING,"Localized string for Label <%s> not found", sKey ); - sLocalizedString = sKey; - return false; - } - } - } - } - else - { - // CryWarning( VALIDATOR_MODULE_SYSTEM,VALIDATOR_WARNING,"Not a valid localized string Label <%s>, must start with @ symbol", sKey ); - } - - sLocalizedString = sKey; - return false; -} - -bool CLocalizedStringsManager::IsLocalizedInfoFound(const char* sKey) -{ - if (!m_pLanguage) - { - return false; - } - uint32 keyCRC32 = CCrc32::ComputeLowercase(sKey); - { - AutoLock lock(m_cs); //Lock here, to prevent strings etc being modified underneath this lookup - const SLocalizedStringEntry* entry = stl::find_in_map(m_pLanguage->m_keysMap, keyCRC32, NULL); - return (entry != NULL); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::GetLocalizedInfoByKey(const char* sKey, SLocalizedInfoGame& outGameInfo) -{ - if (!m_pLanguage) - { - return false; - } - - uint32 keyCRC32 = CCrc32::ComputeLowercase(sKey); - { - AutoLock lock(m_cs); //Lock here, to prevent strings etc being modified underneath this lookup - const SLocalizedStringEntry* entry = stl::find_in_map(m_pLanguage->m_keysMap, keyCRC32, NULL); - if (entry != NULL) - { - outGameInfo.szCharacterName = entry->sCharacterName; - outGameInfo.sUtf8TranslatedText = entry->GetTranslatedText(m_pLanguage); - - outGameInfo.bUseSubtitle = (entry->flags & SLocalizedStringEntry::USE_SUBTITLE); - - return true; - } - else - { - return false; - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::GetLocalizedInfoByKey(const char* sKey, SLocalizedSoundInfoGame* pOutSoundInfo) -{ - assert(sKey); - if (!m_pLanguage || !sKey || !pOutSoundInfo) - { - return false; - } - - bool bResult = false; - - uint32 keyCRC32 = CCrc32::ComputeLowercase(sKey); - { - AutoLock lock(m_cs); //Lock here, to prevent strings etc being modified underneath this lookup - const SLocalizedStringEntry* pEntry = stl::find_in_map(m_pLanguage->m_keysMap, keyCRC32, NULL); - if (pEntry != NULL) - { - bResult = true; - - pOutSoundInfo->szCharacterName = pEntry->sCharacterName; - pOutSoundInfo->sUtf8TranslatedText = pEntry->GetTranslatedText(m_pLanguage); - - //pOutSoundInfo->sOriginalActorLine = pEntry->sOriginalActorLine.c_str(); - //pOutSoundInfo->sTranslatedActorLine = pEntry->swTranslatedActorLine.c_str(); - //pOutSoundInfo->sOriginalText = pEntry->sOriginalText; - // original Character - - pOutSoundInfo->sSoundEvent = pEntry->sPrototypeSoundEvent.c_str(); - pOutSoundInfo->fVolume = CryConvertHalfToFloat(pEntry->fVolume); - pOutSoundInfo->fRadioRatio = CryConvertHalfToFloat(pEntry->fRadioRatio); - pOutSoundInfo->bUseSubtitle = (pEntry->flags & SLocalizedStringEntry::USE_SUBTITLE) != 0; - pOutSoundInfo->bIsDirectRadio = (pEntry->flags & SLocalizedStringEntry::IS_DIRECTED_RADIO) != 0; - pOutSoundInfo->bIsIntercepted = (pEntry->flags & SLocalizedStringEntry::IS_INTERCEPTED) != 0; - - //SoundMoods - if (pOutSoundInfo->nNumSoundMoods >= pEntry->SoundMoods.size()) - { - // enough space to copy data - int i = 0; - for (; i < pEntry->SoundMoods.size(); ++i) - { - pOutSoundInfo->pSoundMoods[i].sName = pEntry->SoundMoods[i].sName; - pOutSoundInfo->pSoundMoods[i].fValue = pEntry->SoundMoods[i].fValue; - } - // if mode is available fill it with default - for (; i < pOutSoundInfo->nNumSoundMoods; ++i) - { - pOutSoundInfo->pSoundMoods[i].sName = ""; - pOutSoundInfo->pSoundMoods[i].fValue = 0.0f; - } - pOutSoundInfo->nNumSoundMoods = pEntry->SoundMoods.size(); - } - else - { - // not enough memory, say what is needed - pOutSoundInfo->nNumSoundMoods = pEntry->SoundMoods.size(); - bResult = (pOutSoundInfo->pSoundMoods == NULL); // only report error if memory was provided but is too small - } - - //EventParameters - if (pOutSoundInfo->nNumEventParameters >= pEntry->EventParameters.size()) - { - // enough space to copy data - int i = 0; - for (; i < pEntry->EventParameters.size(); ++i) - { - pOutSoundInfo->pEventParameters[i].sName = pEntry->EventParameters[i].sName; - pOutSoundInfo->pEventParameters[i].fValue = pEntry->EventParameters[i].fValue; - } - // if mode is available fill it with default - for (; i < pOutSoundInfo->nNumEventParameters; ++i) - { - pOutSoundInfo->pEventParameters[i].sName = ""; - pOutSoundInfo->pEventParameters[i].fValue = 0.0f; - } - pOutSoundInfo->nNumEventParameters = pEntry->EventParameters.size(); - } - else - { - // not enough memory, say what is needed - pOutSoundInfo->nNumEventParameters = pEntry->EventParameters.size(); - bResult = (pOutSoundInfo->pSoundMoods == NULL); // only report error if memory was provided but is too small - } - } - } - - return bResult; -} - -////////////////////////////////////////////////////////////////////////// -int CLocalizedStringsManager::GetLocalizedStringCount() -{ - if (!m_pLanguage) - { - return 0; - } - return m_pLanguage->m_vLocalizedStrings.size(); -} - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::GetLocalizedInfoByIndex(int nIndex, SLocalizedInfoGame& outGameInfo) -{ - if (!m_pLanguage) - { - return false; - } - const std::vector& entryVec = m_pLanguage->m_vLocalizedStrings; - if (nIndex < 0 || nIndex >= (int)entryVec.size()) - { - return false; - } - const SLocalizedStringEntry* pEntry = entryVec[nIndex]; - - outGameInfo.szCharacterName = pEntry->sCharacterName; - outGameInfo.sUtf8TranslatedText = pEntry->GetTranslatedText(m_pLanguage); - - outGameInfo.bUseSubtitle = (pEntry->flags & SLocalizedStringEntry::USE_SUBTITLE); - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::GetLocalizedInfoByIndex(int nIndex, SLocalizedInfoEditor& outEditorInfo) -{ - if (!m_pLanguage) - { - return false; - } - const std::vector& entryVec = m_pLanguage->m_vLocalizedStrings; - if (nIndex < 0 || nIndex >= (int)entryVec.size()) - { - return false; - } - const SLocalizedStringEntry* pEntry = entryVec[nIndex]; - outEditorInfo.szCharacterName = pEntry->sCharacterName; - outEditorInfo.sUtf8TranslatedText = pEntry->GetTranslatedText(m_pLanguage); - - assert(pEntry->pEditorExtension != NULL); - - outEditorInfo.sKey = pEntry->pEditorExtension->sKey; - - outEditorInfo.sOriginalActorLine = pEntry->pEditorExtension->sOriginalActorLine; - outEditorInfo.sUtf8TranslatedActorLine = pEntry->pEditorExtension->sUtf8TranslatedActorLine; - - //outEditorInfo.sOriginalText = pEntry->sOriginalText; - outEditorInfo.sOriginalCharacterName = pEntry->pEditorExtension->sOriginalCharacterName; - - outEditorInfo.nRow = pEntry->pEditorExtension->nRow; - outEditorInfo.bUseSubtitle = (pEntry->flags & SLocalizedStringEntry::USE_SUBTITLE); - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CLocalizedStringsManager::GetSubtitle(const char* sKeyOrLabel, string& outSubtitle, bool bForceSubtitle) -{ - assert(sKeyOrLabel); - if (!m_pLanguage || !sKeyOrLabel || !*sKeyOrLabel) - { - return false; - } - if (*sKeyOrLabel == '@') - { - ++sKeyOrLabel; - } - - uint32 keyCRC32 = CCrc32::ComputeLowercase(sKeyOrLabel); - { - AutoLock lock(m_cs); //Lock here, to prevent strings etc being modified underneath this lookup - const SLocalizedStringEntry* pEntry = stl::find_in_map(m_pLanguage->m_keysMap, keyCRC32, NULL); - if (pEntry != NULL) - { - if ((pEntry->flags & SLocalizedStringEntry::USE_SUBTITLE) == false && !bForceSubtitle) - { - return false; - } - - // TODO verify that no fallback is needed - - outSubtitle = pEntry->GetTranslatedText(m_pLanguage); - - if (outSubtitle.empty() == true) - { - if (pEntry->pEditorExtension != NULL && pEntry->pEditorExtension->sUtf8TranslatedActorLine.empty() == false) - { - outSubtitle = pEntry->pEditorExtension->sUtf8TranslatedActorLine; - } - else if (pEntry->pEditorExtension != NULL && pEntry->pEditorExtension->sOriginalText.empty() == false) - { - outSubtitle = pEntry->pEditorExtension->sOriginalText; - } - else if (pEntry->pEditorExtension != NULL && pEntry->pEditorExtension->sOriginalActorLine.empty() == false) - { - outSubtitle = pEntry->pEditorExtension->sOriginalActorLine; - } - } - return true; - } - return false; - } -} - -template -void InternalFormatStringMessage(StringClass& outString, const StringClass& sString, const CharType** sParams, int nParams) -{ - static const CharType token = (CharType) '%'; - static const CharType tokens1[2] = { token, (CharType) '\0' }; - static const CharType tokens2[3] = { token, token, (CharType) '\0' }; - - int maxArgUsed = 0; - int lastPos = 0; - int curPos = 0; - const int sourceLen = sString.length(); - while (true) - { - int foundPos = sString.find(token, curPos); - if (foundPos != string::npos) - { - if (foundPos + 1 < sourceLen) - { - const int nArg = sString[foundPos + 1] - '1'; - if (nArg >= 0 && nArg <= 9) - { - if (nArg < nParams) - { - outString.append(sString, lastPos, foundPos - lastPos); - outString.append(sParams[nArg]); - curPos = foundPos + 2; - lastPos = curPos; - maxArgUsed = std::max(maxArgUsed, nArg); - } - else - { - StringClass tmp (sString); - tmp.replace(tokens1, tokens2); - if constexpr (sizeof(*tmp.c_str()) == sizeof(char)) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "Parameter for argument %d is missing. [%s]", nArg + 1, (const char*)tmp.c_str()); - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "Parameter for argument %d is missing. [%S]", nArg + 1, (const wchar_t*)tmp.c_str()); - } - curPos = foundPos + 1; - } - } - else - { - curPos = foundPos + 1; - } - } - else - { - curPos = foundPos + 1; - } - } - else - { - outString.append(sString, lastPos, sourceLen - lastPos); - break; - } - } -} - -template -void InternalFormatStringMessage(StringClass& outString, const StringClass& sString, const CharType* param1, const CharType* param2 = 0, const CharType* param3 = 0, const CharType* param4 = 0) -{ - static const int MAX_PARAMS = 4; - const CharType* params[MAX_PARAMS] = { param1, param2, param3, param4 }; - int nParams = 0; - while (nParams < MAX_PARAMS && params[nParams]) - { - ++nParams; - } - InternalFormatStringMessage(outString, sString, params, nParams); -} - -////////////////////////////////////////////////////////////////////////// -void CLocalizedStringsManager::FormatStringMessage_List(string& outString, const string& sString, const char** sParams, int nParams) -{ - InternalFormatStringMessage(outString, sString, sParams, nParams); -} - -////////////////////////////////////////////////////////////////////////// -void CLocalizedStringsManager::FormatStringMessage(string& outString, const string& sString, const char* param1, const char* param2, const char* param3, const char* param4) -{ - InternalFormatStringMessage(outString, sString, param1, param2, param3, param4); -} - -////////////////////////////////////////////////////////////////////////// -int CLocalizedStringsManager::GetMemoryUsage(ICrySizer* pSizer) -{ - pSizer->AddObject(this, sizeof(*this)); - pSizer->AddObject(m_languages); - pSizer->AddObject(m_prototypeEvents); - pSizer->AddObject(m_characterNameSet); - pSizer->AddObject(m_pLanguage); - - return 0; -} - -#if defined (WIN32) || defined(WIN64) -namespace -{ - struct LanguageID - { - const char* language; - unsigned long lcID; - }; - - LanguageID languageIDArray[] = - { - { "en-US", 0x0409 }, // English (USA) - { "en-GB", 0x0809 }, // English (UK) - { "de-DE", 0x0407 }, // German - { "ru-RU", 0x0419 }, // Russian (Russia) - { "pl-PL", 0x0415 }, // Polish - { "tr-TR", 0x041f }, // Turkish - { "es-ES", 0x0c0a }, // Spanish (Spain) - { "es-MX", 0x080a }, // Spanish (Mexico) - { "fr-FR", 0x040c }, // French (France) - { "fr-CA", 0x0c0c }, // French (Canada) - { "it-IT", 0x0410 }, // Italian - { "pt-PT", 0x0816 }, // Portugese (Portugal) - { "pt-BR", 0x0416 }, // Portugese (Brazil) - { "ja-JP", 0x0411 }, // Japanese - { "ko-KR", 0x0412 }, // Korean - { "zh-CHT", 0x0804 }, // Traditional Chinese - { "zh-CHS", 0x0804 }, // Simplified Chinese - { "nl-NL", 0x0413 }, // Dutch (The Netherlands) - { "fi-FI", 0x040b }, // Finnish - { "sv-SE", 0x041d }, // Swedish - { "cs-CZ", 0x0405 }, // Czech - { "no-NO", 0x0414 }, // Norwegian (Norway) - { "ar-SA", 0x0401 }, // Arabic (Saudi Arabia) - { "da-DK", 0x0406 }, // Danish (Denmark) - }; - - const size_t numLanguagesIDs = sizeof(languageIDArray) / sizeof(languageIDArray[0]); - - LanguageID GetLanguageID(const char* language) - { - // default is English (US) - const LanguageID defaultLanguage = { "en-US", 0x0409 }; - for (int i = 0; i < numLanguagesIDs; ++i) - { - if (_stricmp(language, languageIDArray[i].language) == 0) - { - return languageIDArray[i]; - } - } - return defaultLanguage; - } - - LanguageID g_currentLanguageID = { 0, 0 }; -}; -#endif - -void CLocalizedStringsManager::InternalSetCurrentLanguage(CLocalizedStringsManager::SLanguage* pLanguage) -{ - m_pLanguage = pLanguage; -#if defined (WIN32) || defined(WIN64) - if (m_pLanguage != 0) - { - g_currentLanguageID = GetLanguageID(m_pLanguage->sLanguage); - } - else - { - g_currentLanguageID.language = 0; - g_currentLanguageID.lcID = 0; - } -#endif - // TODO: on Linux based systems we should now set the locale - // Enabling this on windows something seems to get corrupted... - // on Windows we always use Windows Platform Functions, which use the lcid -#if 0 - if (g_currentLanguageID.language) - { - const char* currentLocale = setlocale(LC_ALL, 0); - if (0 == setlocale(LC_ALL, g_currentLanguageID.language)) - { - setlocale(LC_ALL, currentLocale); - } - } - else - { - setlocale(LC_ALL, "C"); - } -#endif - ReloadData(); - if (gEnv->pCryFont) - { - gEnv->pCryFont->OnLanguageChanged(); - } -} - -void CLocalizedStringsManager::LocalizeDuration(int seconds, string& outDurationString) -{ - int s = seconds; - int d, h, m; - d = s / 86400; - s -= d * 86400; - h = s / 3600; - s -= h * 3600; - m = s / 60; - s = s - m * 60; - string str; - if (d > 1) - { - str.Format("%d @ui_days %02d:%02d:%02d", d, h, m, s); - } - else if (d > 0) - { - str.Format("%d @ui_day %02d:%02d:%02d", d, h, m, s); - } - else if (h > 0) - { - str.Format("%02d:%02d:%02d", h, m, s); - } - else - { - str.Format("%02d:%02d", m, s); - } - LocalizeString_s(str, outDurationString); -} - -void CLocalizedStringsManager::LocalizeNumber(int number, string& outNumberString) -{ - if (number == 0) - { - outNumberString.assign("0"); - return; - } - - outNumberString.assign(""); - - int n = abs(number); - string separator; - CryFixedStringT<64> tmp; - LocalizeString_ch("@ui_thousand_separator", separator); - while (n > 0) - { - int a = n / 1000; - int b = n - (a * 1000); - if (a > 0) - { - tmp.Format("%s%03d%s", separator.c_str(), b, tmp.c_str()); - } - else - { - tmp.Format("%d%s", b, tmp.c_str()); - } - n = a; - } - - if (number < 0) - { - tmp.Format("-%s", tmp.c_str()); - } - - outNumberString.assign(tmp.c_str()); -} - -void CLocalizedStringsManager::LocalizeNumber_Decimal(float number, int decimals, string& outNumberString) -{ - if (number == 0.0f) - { - CryFixedStringT<64> tmp; - tmp.Format("%.*f", decimals, number); - outNumberString.assign(tmp.c_str()); - return; - } - - outNumberString.assign(""); - - string commaSeparator; - LocalizeString_ch("@ui_decimal_separator", commaSeparator); - float f = number > 0.0f ? number : -number; - int d = (int)f; - - string intPart; - LocalizeNumber(d, intPart); - - float decimalsOnly = f - (float)d; - - int decimalsAsInt = aznumeric_cast(int_round(decimalsOnly * pow(10.0f, decimals))); - - CryFixedStringT<64> tmp; - tmp.Format("%s%s%0*d", intPart.c_str(), commaSeparator.c_str(), decimals, decimalsAsInt); - - outNumberString.assign(tmp.c_str()); -} - -bool CLocalizedStringsManager::ProjectUsesLocalization() const -{ - ICVar* pCVar = gEnv->pConsole->GetCVar("sys_localization_folder"); - CRY_ASSERT_MESSAGE(pCVar, - "Console variable 'sys_localization_folder' not defined! " - "This was previously defined at startup in CSystem::CreateSystemVars."); - - // If game.cfg didn't provide a sys_localization_folder, we'll assume that - // the project doesn't want to use localization features. - return (pCVar->GetFlags() & VF_WASINCONFIG) != 0; -} - -#if defined (WIN32) || defined(WIN64) -namespace -{ - void UnixTimeToFileTime(time_t unixtime, FILETIME* filetime) - { - LONGLONG longlong = Int32x32To64(unixtime, 10000000) + 116444736000000000; - filetime->dwLowDateTime = (DWORD) longlong; - filetime->dwHighDateTime = (DWORD)(longlong >> 32); - } - - void UnixTimeToSystemTime(time_t unixtime, SYSTEMTIME* systemtime) - { - FILETIME filetime; - UnixTimeToFileTime(unixtime, &filetime); - FileTimeToSystemTime(&filetime, systemtime); - } - - time_t UnixTimeFromFileTime(const FILETIME* filetime) - { - LONGLONG longlong = filetime->dwHighDateTime; - longlong <<= 32; - longlong |= filetime->dwLowDateTime; - longlong -= 116444736000000000; - return longlong / 10000000; - } - - time_t UnixTimeFromSystemTime(const SYSTEMTIME* systemtime) - { - // convert systemtime to filetime - FILETIME filetime; - SystemTimeToFileTime(systemtime, &filetime); - // convert filetime to unixtime - time_t unixtime = UnixTimeFromFileTime(&filetime); - return unixtime; - } -}; - -void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, string& outTimeString) -{ - if (bMakeLocalTime) - { - struct tm thetime; - localtime_s(&thetime, &t); - t = gEnv->pTimer->DateToSecondsUTC(thetime); - } - outTimeString.resize(0); - LCID lcID = g_currentLanguageID.lcID ? g_currentLanguageID.lcID : LOCALE_USER_DEFAULT; - DWORD flags = bShowSeconds == false ? TIME_NOSECONDS : 0; - SYSTEMTIME systemTime; - UnixTimeToSystemTime(t, &systemTime); - int len = ::GetTimeFormatW(lcID, flags, &systemTime, 0, 0, 0); - if (len > 0) - { - // len includes terminating null! - CryFixedWStringT<256> tmpString; - tmpString.resize(len); - ::GetTimeFormatW(lcID, flags, &systemTime, 0, (wchar_t*) tmpString.c_str(), len); - Unicode::Convert(outTimeString, tmpString); - } -} - -void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, string& outDateString) -{ - if (bMakeLocalTime) - { - struct tm thetime; - localtime_s(&thetime, &t); - t = gEnv->pTimer->DateToSecondsUTC(thetime); - } - outDateString.resize(0); - LCID lcID = g_currentLanguageID.lcID ? g_currentLanguageID.lcID : LOCALE_USER_DEFAULT; - SYSTEMTIME systemTime; - UnixTimeToSystemTime(t, &systemTime); - - // len includes terminating null! - CryFixedWStringT<256> tmpString; - - if (bIncludeWeekday) - { - // Get name of day - int len = ::GetDateFormatW(lcID, 0, &systemTime, L"ddd", 0, 0); - if (len > 0) - { - // len includes terminating null! - tmpString.resize(len); - ::GetDateFormatW(lcID, 0, &systemTime, L"ddd", (wchar_t*) tmpString.c_str(), len); - string utf8; - Unicode::Convert(utf8, tmpString); - outDateString.append(utf8); - outDateString.append(" "); - } - } - DWORD flags = bShort ? DATE_SHORTDATE : DATE_LONGDATE; - int len = ::GetDateFormatW(lcID, flags, &systemTime, 0, 0, 0); - if (len > 0) - { - // len includes terminating null! - tmpString.resize(len); - ::GetDateFormatW(lcID, flags, &systemTime, 0, (wchar_t*) tmpString.c_str(), len); - string utf8; - Unicode::Convert(utf8, tmpString); - outDateString.append(utf8); - } -} - -#else // #if defined (WIN32) || defined(WIN64) - -void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, string& outTimeString) -{ - struct tm theTime; - if (bMakeLocalTime) - { -#if AZ_TRAIT_USE_SECURE_CRT_FUNCTIONS - localtime_s(&theTime, &t); -#else - theTime = *localtime(&t); -#endif - } - else - { -#if AZ_TRAIT_USE_SECURE_CRT_FUNCTIONS - gmtime_s(&theTime, &t); -#else - theTime = *gmtime(&t); -#endif - } - - wchar_t buf[256]; - const size_t bufSize = sizeof(buf) / sizeof(buf[0]); - wcsftime(buf, bufSize, bShowSeconds ? L"%#X" : L"%X", &theTime); - buf[bufSize - 1] = 0; - Unicode::Convert(outTimeString, buf); -} - -void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, string& outDateString) -{ - struct tm theTime; - if (bMakeLocalTime) - { -#if AZ_TRAIT_USE_SECURE_CRT_FUNCTIONS - localtime_s(&theTime, &t); -#else - theTime = *localtime(&t); -#endif - } - else - { -#if AZ_TRAIT_USE_SECURE_CRT_FUNCTIONS - gmtime_s(&theTime, &t); -#else - theTime = *gmtime(&t); -#endif - } - - wchar_t buf[256]; - const size_t bufSize = sizeof(buf) / sizeof(buf[0]); - const wchar_t* format = bShort ? (bIncludeWeekday ? L"%a %x" : L"%x") : L"%#x"; // long format always contains Weekday name - wcsftime(buf, bufSize, format, &theTime); - buf[bufSize - 1] = 0; - Unicode::Convert(outDateString, buf); -} - - - -#endif - - diff --git a/Code/CryEngine/CrySystem/LocalizedStringManager.h b/Code/CryEngine/CrySystem/LocalizedStringManager.h deleted file mode 100644 index 5b747e1721..0000000000 --- a/Code/CryEngine/CrySystem/LocalizedStringManager.h +++ /dev/null @@ -1,315 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include -#include -#include -#include - -#include "Huffman.h" - -////////////////////////////////////////////////////////////////////////// -/* - Manage Localization Data -*/ -class CLocalizedStringsManager - : public ILocalizationManager - , public ISystemEventListener -{ -public: - typedef std::vector TLocalizationTagVec; - - constexpr const static size_t LOADING_FIXED_STRING_LENGTH = 2048; - constexpr const static size_t COMPRESSION_FIXED_BUFFER_LENGTH = 6144; - - CLocalizedStringsManager(ISystem* pSystem); - virtual ~CLocalizedStringsManager(); - - // ILocalizationManager - const char* LangNameFromPILID(const ILocalizationManager::EPlatformIndependentLanguageID id); - ILocalizationManager::EPlatformIndependentLanguageID PILIDFromLangName(AZStd::string langName) override; - ILocalizationManager::EPlatformIndependentLanguageID GetSystemLanguage() override; - ILocalizationManager::TLocalizationBitfield MaskSystemLanguagesFromSupportedLocalizations(const ILocalizationManager::TLocalizationBitfield systemLanguages); - ILocalizationManager::TLocalizationBitfield IsLanguageSupported(const ILocalizationManager::EPlatformIndependentLanguageID id); - - const char* GetLanguage() override; - bool SetLanguage(const char* sLanguage) override; - - int GetLocalizationFormat() const override; - virtual AZStd::string GetLocalizedSubtitleFilePath(const AZStd::string& localVideoPath, const AZStd::string& subtitleFileExtension) const override; - virtual AZStd::string GetLocalizedLocXMLFilePath(const AZStd::string& localXmlPath) const override; - bool InitLocalizationData(const char* sFileName, bool bReload = false); - bool RequestLoadLocalizationDataByTag(const char* sTag); - bool LoadLocalizationDataByTag(const char* sTag, bool bReload = false); - bool ReleaseLocalizationDataByTag(const char* sTag); - - bool LoadAllLocalizationData(bool bReload = false) override; - bool LoadExcelXmlSpreadsheet(const char* sFileName, bool bReload = false) override; - void ReloadData() override; - void FreeData(); - - bool LocalizeString_s(const string& sString, string& outLocalizedString, bool bEnglish = false) override; - bool LocalizeString_ch(const char* sString, string& outLocalizedString, bool bEnglish = false) override; - - void LocalizeAndSubstituteInternal(AZStd::string& locString, const AZStd::vector& keys, const AZStd::vector& values) override; - bool LocalizeLabel(const char* sLabel, string& outLocalizedString, bool bEnglish = false) override; - bool IsLocalizedInfoFound(const char* sKey); - bool GetLocalizedInfoByKey(const char* sKey, SLocalizedInfoGame& outGameInfo); - bool GetLocalizedInfoByKey(const char* sKey, SLocalizedSoundInfoGame* pOutSoundInfoGame); - int GetLocalizedStringCount(); - bool GetLocalizedInfoByIndex(int nIndex, SLocalizedInfoGame& outGameInfo); - bool GetLocalizedInfoByIndex(int nIndex, SLocalizedInfoEditor& outEditorInfo); - - bool GetEnglishString(const char* sKey, string& sLocalizedString) override; - bool GetSubtitle(const char* sKeyOrLabel, string& outSubtitle, bool bForceSubtitle = false) override; - - void FormatStringMessage_List(string& outString, const string& sString, const char** sParams, int nParams) override; - void FormatStringMessage(string& outString, const string& sString, const char* param1, const char* param2 = 0, const char* param3 = 0, const char* param4 = 0) override; - - void LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, string& outTimeString) override; - void LocalizeDate(time_t t, bool bMakeLocalTime, bool bShort, bool bIncludeWeekday, string& outDateString) override; - void LocalizeDuration(int seconds, string& outDurationString) override; - void LocalizeNumber(int number, string& outNumberString) override; - void LocalizeNumber_Decimal(float number, int decimals, string& outNumberString) override; - - bool ProjectUsesLocalization() const override; - // ~ILocalizationManager - - // ISystemEventManager - void OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam); - // ~ISystemEventManager - - int GetMemoryUsage(ICrySizer* pSizer); - - void GetLoadedTags(TLocalizationTagVec& tagVec); - void FreeLocalizationData(); - -private: - void SetAvailableLocalizationsBitfield(const ILocalizationManager::TLocalizationBitfield availableLocalizations); - - bool LocalizeStringInternal(const char* pStr, size_t len, string& outLocalizedString, bool bEnglish); - - bool DoLoadExcelXmlSpreadsheet(const char* sFileName, uint8 tagID, bool bReload); - typedef bool(CLocalizedStringsManager::*LoadFunc)(const char*, uint8, bool); - bool DoLoadAGSXmlDocument(const char* sFileName, uint8 tagID, bool bReload); - LoadFunc GetLoadFunction() const; - - struct SLocalizedStringEntryEditorExtension - { - string sKey; // Map key text equivalent (without @) - string sOriginalActorLine; // english text - string sUtf8TranslatedActorLine; // localized text - string sOriginalText; // subtitle. if empty, uses English text - string sOriginalCharacterName; // english character name speaking via XML asset - - unsigned int nRow; // Number of row in XML file - - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - - pSizer->AddObject(sKey); - pSizer->AddObject(sOriginalActorLine); - pSizer->AddObject(sUtf8TranslatedActorLine); - pSizer->AddObject(sOriginalText); - pSizer->AddObject(sOriginalCharacterName); - } - }; - - struct SLanguage; - - //#define LOG_DECOMP_TIMES //If defined, will log decompression times to a file - - struct SLocalizedStringEntry - { - //Flags - enum - { - USE_SUBTITLE = BIT(0), //should a subtitle displayed for this key? - IS_DIRECTED_RADIO = BIT(1), //should the radio receiving hud be displayed? - IS_INTERCEPTED = BIT(2), //should the radio receiving hud show the interception display? - IS_COMPRESSED = BIT(3), //Translated text is compressed - }; - - union trans_text - { - string* psUtf8Uncompressed; - uint8* szCompressed; // Note that no size information is stored. This is for struct size optimization and unfortunately renders the size info inaccurate. - }; - - string sCharacterName; // character name speaking via XML asset - trans_text TranslatedText; // Subtitle of this line - - // audio specific part - string sPrototypeSoundEvent; // associated sound event prototype (radio, ...) - CryHalf fVolume; - CryHalf fRadioRatio; - // SoundMoods - DynArray SoundMoods; - // EventParameters - DynArray EventParameters; - // ~audio specific part - - // subtitle & radio flags - uint8 flags; - - // Index of Huffman tree for translated text. -1 = no tree assigned (error) - int8 huffmanTreeIndex; - - uint8 nTagID; - - // bool bDependentTranslation; // if the english/localized text contains other localization labels - - //Additional information for Sandbox. Null in game - SLocalizedStringEntryEditorExtension* pEditorExtension; - - SLocalizedStringEntry() - : flags(0) - , huffmanTreeIndex(-1) - , pEditorExtension(NULL) - { - TranslatedText.psUtf8Uncompressed = NULL; - }; - ~SLocalizedStringEntry() - { - SAFE_DELETE(pEditorExtension); - if ((flags & IS_COMPRESSED) == 0) - { - SAFE_DELETE(TranslatedText.psUtf8Uncompressed); - } - else - { - SAFE_DELETE_ARRAY(TranslatedText.szCompressed); - } - }; - - string GetTranslatedText(const SLanguage* pLanguage) const; - - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - - pSizer->AddObject(sCharacterName); - - if ((flags & IS_COMPRESSED) == 0 && TranslatedText.psUtf8Uncompressed != NULL) //Number of bytes stored for compressed text is unknown, which throws this GetMemoryUsage off - { - pSizer->AddObject(*TranslatedText.psUtf8Uncompressed); - } - - pSizer->AddObject(sPrototypeSoundEvent); - - pSizer->AddObject(SoundMoods); - pSizer->AddObject(EventParameters); - - if (pEditorExtension != NULL) - { - pEditorExtension->GetMemoryUsage(pSizer); - } - } - }; - - //Keys as CRC32. Strings previously, but these proved too large - typedef VectorMap StringsKeyMap; - - struct SLanguage - { - typedef std::vector TLocalizedStringEntries; - typedef std::vector THuffmanCoders; - - string sLanguage; - StringsKeyMap m_keysMap; - TLocalizedStringEntries m_vLocalizedStrings; - THuffmanCoders m_vEncoders; - - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - pSizer->AddObject(sLanguage); - pSizer->AddObject(m_vLocalizedStrings); - pSizer->AddObject(m_keysMap); - pSizer->AddObject(m_vEncoders); - } - }; - - struct SFileInfo - { - bool bDataStripping; - uint8 nTagID; - }; - -#ifndef _RELEASE - std::map m_warnedAboutLabels; - bool m_haveWarnedAboutAtLeastOneLabel; - - void LocalizedStringsManagerWarning(const char* label, const char* message); - void ListAndClearProblemLabels(); -#else - inline void LocalizedStringsManagerWarning(...) {}; - inline void ListAndClearProblemLabels() {}; -#endif - - void AddLocalizedString(SLanguage* pLanguage, SLocalizedStringEntry* pEntry, const uint32 keyCRC32); - void AddControl(int nKey); - ////////////////////////////////////////////////////////////////////////// - void ParseFirstLine(IXmlTableReader* pXmlTableReader, char* nCellIndexToType, std::map& SoundMoodIndex, std::map& EventParameterIndex); - void InternalSetCurrentLanguage(SLanguage* pLanguage); - ISystem* m_pSystem; - // Pointer to the current language. - SLanguage* m_pLanguage; - - // all loaded Localization Files - typedef std::pair pairFileName; - typedef std::map tmapFilenames; - tmapFilenames m_loadedTables; - - - // filenames per tag - typedef std::vector TStringVec; - struct STag - { - TStringVec filenames; - uint8 id; - bool loaded; - }; - typedef std::map TTagFileNames; - TTagFileNames m_tagFileNames; - TStringVec m_tagLoadRequests; - - // Array of loaded languages. - std::vector m_languages; - - typedef std::set PrototypeSoundEvents; - PrototypeSoundEvents m_prototypeEvents; // this set is purely used for clever string/string assigning to save memory - - struct less_strcmp - { - bool operator()(const string& left, const string& right) const - { - return strcmp(left.c_str(), right.c_str()) < 0; - } - }; - - typedef std::set CharacterNameSet; - CharacterNameSet m_characterNameSet; // this set is purely used for clever string/string assigning to save memory - - // CVARs - int m_cvarLocalizationDebug; - int m_cvarLocalizationEncode; //Encode/Compress translated text to save memory - int m_cvarLocalizationFormat; - - //The localizations that are available for this SKU. Used for determining what to show on a language select screen or whether to show one at all - TLocalizationBitfield m_availableLocalizations; - - //Lock for - mutable CryCriticalSection m_cs; - typedef CryAutoCriticalSection AutoLock; -}; - - diff --git a/Code/CryEngine/CrySystem/Log.cpp b/Code/CryEngine/CrySystem/Log.cpp deleted file mode 100644 index b3230f9f5f..0000000000 --- a/Code/CryEngine/CrySystem/Log.cpp +++ /dev/null @@ -1,1546 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Log related functions - - -#include "CrySystem_precompiled.h" -#include "Log.h" - -//this should not be included here -#include -#include -#include "System.h" -#include "CryPath.h" // PathUtil::ReplaceExtension() -#include "UnicodeFunctions.h" - -#include -#include -#include - -#ifdef WIN32 -#include -#endif - -#if defined(LINUX) || defined(APPLE) -#include -#endif - - -// Only accept logging from the main thread. -#ifdef WIN32 - -#define THREAD_SAFE_LOG -//#define THREAD_SAFE_LOG CryAutoCriticalSection scope_lock(m_logCriticalSection); - -#else -#define THREAD_SAFE_LOG -#endif //WIN32 - -#define LOG_BACKUP_PATH "@log@/LogBackups" - -#if defined(IOS) -#include -#endif - -////////////////////////////////////////////////////////////////////// -namespace LogCVars -{ - float s_log_tick = 0; - int max_backup_directory_size_mb = 200; //200MB default -}; - -#ifndef _RELEASE -static CLog::LogStringType indentString (" "); -#endif - -////////////////////////////////////////////////////////////////////// -CLog::CLog(ISystem* pSystem) -{ - memset(m_szFilename, 0, MAX_FILENAME_SIZE); - memset(m_sBackupFilename, 0, MAX_FILENAME_SIZE); - //memset(m_szTemp,0,MAX_TEMP_LENGTH_SIZE); - m_pSystem = pSystem; - m_pLogVerbosity = 0; - m_pLogWriteToFile = 0; - m_pLogWriteToFileVerbosity = 0; - m_pLogVerbosityOverridesWriteToFile = 0; - m_pLogIncludeTime = 0; - m_pLogSpamDelay = 0; - m_pLogModule = 0; - m_fLastLoadingUpdateTime = -1.f; // for streaming engine update - m_backupLogs = true; - -#if defined(SUPPORT_LOG_IDENTER) - m_indentation = 0; - BuildIndentString(); - m_topIndenter = NULL; -#endif - - m_nMainThreadId = CryGetCurrentThreadId(); - -#if defined(KEEP_LOG_FILE_OPEN) - m_bFirstLine = true; -#endif - - m_iLastHistoryItem = 0; - memset(m_history, 0, sizeof(m_history)); - - CheckAndPruneBackupLogs(); - -} - -void CLog::RegisterConsoleVariables() -{ - IConsole* console = m_pSystem->GetIConsole(); - -#ifdef _RELEASE - #if defined(RELEASE_LOGGING) - #define DEFAULT_VERBOSITY 0 - #else - #define DEFAULT_VERBOSITY -1 - #endif -#else - #define DEFAULT_VERBOSITY 3 -#endif - - if (console) - { - m_pLogVerbosity = REGISTER_INT("log_Verbosity", DEFAULT_VERBOSITY, VF_DUMPTODISK, - "defines the verbosity level for log messages written to console\n" - "-1=suppress all logs (including eAlways)\n" - "0=suppress all logs(except eAlways)\n" - "1=additional errors\n" - "2=additional warnings\n" - "3=additional messages\n" - "4=additional comments"); - - //writing to game.log during game play causes stalls on consoles - m_pLogWriteToFile = REGISTER_INT("log_WriteToFile", 1, VF_DUMPTODISK, "toggle whether to write log to file (game.log)"); - - m_pLogWriteToFileVerbosity = REGISTER_INT("log_WriteToFileVerbosity", DEFAULT_VERBOSITY, VF_DUMPTODISK, - "defines the verbosity level for log messages written to files\n" - "-1=suppress all logs (including eAlways)\n" - "0=suppress all logs(except eAlways)\n" - "1=additional errors\n" - "2=additional warnings\n" - "3=additional messages\n" - "4=additional comments"); - m_pLogVerbosityOverridesWriteToFile = REGISTER_INT("log_VerbosityOverridesWriteToFile", 1, VF_DUMPTODISK, "when enabled, setting log_verbosity to 0 will stop all logging including writing to file"); - - // put time into begin of the string if requested by cvar - m_pLogIncludeTime = REGISTER_INT("log_IncludeTime", 0, 0, - "Toggles time stamping of log entries.\n" - "Usage: log_IncludeTime [0/1/2/3/4/5]\n" - " 0=off (default)\n" - " 1=current time\n" - " 2=relative time\n" - " 3=current+relative time\n" - " 4=absolute time in seconds since this mode was started\n" - " 5=current time+server time" - " 6=current date+current time"); - - m_pLogSpamDelay = REGISTER_FLOAT("log_SpamDelay", 0.0f, 0, "Sets the minimum time interval between messages classified as spam"); - - m_pLogModule = REGISTER_STRING("log_Module", "", VF_NULL, "Only show warnings from specified module"); - - REGISTER_CVAR2("log_tick", &LogCVars::s_log_tick, LogCVars::s_log_tick, 0, "When not 0, writes tick log entry into the log file, every N seconds"); - - REGISTER_CVAR2("max_log_backup_mb", &LogCVars::max_backup_directory_size_mb, LogCVars::max_backup_directory_size_mb, 0, "Maximum size of backup logs to keep on disk (in MB)"); - -#if defined(KEEP_LOG_FILE_OPEN) - REGISTER_COMMAND("log_flush", &LogFlushFile, 0, "Flush the log file"); -#endif - } - #undef DEFAULT_VERBOSITY -} - -////////////////////////////////////////////////////////////////////// -CLog::~CLog() -{ -#if defined(SUPPORT_LOG_IDENTER) - while (m_topIndenter) - { - m_topIndenter->Enable(false); - } - - assert (m_indentation == 0); -#endif - - CreateBackupFile(); - - UnregisterConsoleVariables(); - - CloseLogFile(); -} - -void CLog::UnregisterConsoleVariables() -{ - m_pLogVerbosity = 0; - m_pLogWriteToFile = 0; - m_pLogWriteToFileVerbosity = 0; - m_pLogVerbosityOverridesWriteToFile = 0; - m_pLogIncludeTime = 0; - m_pLogSpamDelay = 0; -} - -////////////////////////////////////////////////////////////////////////// -void CLog::CloseLogFile() -{ - m_logFileHandle.Close(); -} - -////////////////////////////////////////////////////////////////////////// -bool CLog::OpenLogFile(const char* filename, int mode) -{ - if (m_logFileHandle.IsOpen()) - { - // Can only AZ_Assert if a file is open, otherwise the AZ_Assert - // would eventually lead to OpenLogFile being opened up again - AZ_Assert(false, "Attempt to open log file when one is already open. This would lead to a handle leak."); - return false; - } - - if (filename == nullptr || filename[0] == '\0') - { - return false; - } - - // it is assumed that @log@ points at the appropriate place (so for apple, to the user profile dir) - AZ::IO::FileIOBase* fileSystem = AZ::IO::FileIOBase::GetDirectInstance(); - if (AZ::IO::FixedMaxPath logFilePath; fileSystem->ReplaceAlias(logFilePath, filename)) - { - logFilePath = logFilePath.LexicallyNormal(); - m_logFileHandle.Open(logFilePath.c_str(), mode); - } - - if (m_logFileHandle.IsOpen()) - { -#if defined(KEEP_LOG_FILE_OPEN) - m_bFirstLine = true; -#endif - } - else - { -#if defined(LINUX) || defined(APPLE) - syslog(LOG_NOTICE, "Failed to open log file [%s], mode [%d]", filename, mode); -#endif - } - - return m_logFileHandle.IsOpen(); -} - -////////////////////////////////////////////////////////////////////////// -void CLog::SetVerbosity(int verbosity) -{ - if (m_pLogVerbosity) - { - m_pLogVerbosity->Set(verbosity); - } -} - -bool CLog::CheckLogFormatter(const char* formatter) -{ - if (!formatter) - { - AZ_Assert(false, "code problem - A message was sent to the log system with nullptr as the formatting string."); - return false; - } - - if (formatter[0] == 0) - { - // if there's nothing to log, we don't log anything. Blank lines at least contain a carriage return or something. - return false; - } - return true; -} - - -////////////////////////////////////////////////////////////////////////// -#if !defined(EXCLUDE_NORMAL_LOG) -void CLog::LogWarning(const char* szFormat, ...) -{ - if (!CheckLogFormatter(szFormat)) - { - return; - } - - va_list ArgList; - char szBuffer[MAX_WARNING_LENGTH]; - va_start(ArgList, szFormat); - vsnprintf_s(szBuffer, sizeof(szBuffer), sizeof(szBuffer) - 1, szFormat, ArgList); - szBuffer[sizeof(szBuffer) - 1] = '\0'; - va_end(ArgList); - - va_start(ArgList, szFormat); - LogV(eWarning, szFormat, ArgList); - va_end(ArgList); -} - -////////////////////////////////////////////////////////////////////////// -void CLog::LogError(const char* szFormat, ...) -{ - if (!CheckLogFormatter(szFormat)) - { - return; - } - - va_list ArgList; - char szBuffer[MAX_WARNING_LENGTH]; - va_start(ArgList, szFormat); - vsnprintf_s(szBuffer, sizeof(szBuffer), sizeof(szBuffer) - 1, szFormat, ArgList); - szBuffer[sizeof(szBuffer) - 1] = '\0'; - va_end(ArgList); - - va_start(ArgList, szFormat); - LogV(eError, szFormat, ArgList); - va_end(ArgList); -} - -////////////////////////////////////////////////////////////////////////// -void CLog::Log(const char* szFormat, ...) -{ - if (!CheckLogFormatter(szFormat)) - { - return; - } - - va_list arg; - va_start(arg, szFormat); - LogV (eMessage, szFormat, arg); - va_end(arg); -} - -////////////////////////////////////////////////////////////////////////// -void CLog::LogAlways(const char* szFormat, ...) -{ - if (!CheckLogFormatter(szFormat)) - { - return; - } - - va_list arg; - va_start(arg, szFormat); - LogV (eAlways, szFormat, arg); - va_end(arg); -} -#endif // !defined(EXCLUDE_NORMAL_LOG) - -int MatchStrings(const char* str0, const char* str1) -{ - const char* str[] = { str0, str1 }; - int i, bSkipWord, bAlpha[2], bWS[2], bStop = 0, nDiffs = 0, nWordDiffs, len = 0; - do - { - for (i = 0; i < 2; i++) // skip the spaces, stop at 0 - { - while (*str[i] == ' ') - { - if (!*str[i]++) - { - goto break2; - } - } - } - bWS[0] = bWS[1] = nWordDiffs = bSkipWord = 0; - do - { - for (i = bAlpha[0] = bAlpha[1] = 0; i < 2; i++) - { - if (!bWS[i]) - { - do - { - int chr = *str[i]++; - bSkipWord |= iszero(chr - '\\') | iszero(chr - '/') | iszero(chr - '_'); // ignore different words with \,_,/ - bAlpha[i] = inrange(chr, 'A' - 1, 'Z' + 1) | inrange(chr, 'a' - 1, 'z' + 1); - bWS[i] = iszero(chr - ' '); - bStop |= iszero(chr); - } while (!(bAlpha[i] | bWS[i] | bStop)); // wait for a letter or a space in each input string - } - } - len += bAlpha[0] & bAlpha[1]; - nWordDiffs += 1 - iszero((int)(*str[0] - *str[1])) & - (bAlpha[0] & bAlpha[1]); // count diffs in this word - } while ((1 - bWS[0] | 1 - bWS[1]) & 1 - bStop); // wait for space (word end) in both strings - nDiffs += nWordDiffs & ~-bSkipWord; - } while (!bStop); -break2: - return nDiffs * 10 < len; -} - -//will log the text both to file and console -////////////////////////////////////////////////////////////////////// -void CLog::LogV(const ELogType type, const char* szFormat, va_list args) -{ - // this is here in case someone called LogV directly, with an invalid formatter. - if (!CheckLogFormatter(szFormat)) - { - return; - } - - LogV(type, 0, szFormat, args); -} - -void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFormat, va_list args) -{ - // this is here in case someone called LogV directly, with an invalid formatter. - if (!CheckLogFormatter(szFormat)) - { - return; - - } - if (!szFormat) - { - return; - } - - if (m_pLogVerbosityOverridesWriteToFile && m_pLogVerbosityOverridesWriteToFile->GetIVal()) - { - if (m_pLogVerbosity && m_pLogVerbosity->GetIVal() < 0) - { - return; - } - } - - FUNCTION_PROFILER(GetISystem(), PROFILE_SYSTEM); - LOADING_TIME_PROFILE_SECTION(GetISystem()); - - bool bfile = false, bconsole = false; - const char* szCommand = szFormat; - - uint8 DefaultVerbosity = 0; // 0 == Always log (except for special -1 verbosity overrides) - - switch (type) - { - case eAlways: - DefaultVerbosity = 0; - break; - case eWarningAlways: - DefaultVerbosity = 0; - break; - case eErrorAlways: - DefaultVerbosity = 0; - break; - case eInput: - DefaultVerbosity = 0; - break; - case eInputResponse: - DefaultVerbosity = 0; - break; - case eError: - DefaultVerbosity = 1; - break; - case eWarning: - DefaultVerbosity = 2; - break; - case eMessage: - DefaultVerbosity = 3; - break; - case eComment: - DefaultVerbosity = 4; - break; - - default: - assert(0); - } - - szCommand = CheckAgainstVerbosity(szFormat, bfile, bconsole, DefaultVerbosity); - if (!bfile && !bconsole) - { - return; - } - - LogStringType tempString; - - char szBuffer[MAX_WARNING_LENGTH + 32]; - char* szString = szBuffer; - char* szAfterColour = szString; - size_t prefixSize = 0; - switch (type) - { - case eWarning: - case eWarningAlways: - cry_strcpy(szString, MAX_WARNING_LENGTH, "$6[Warning] "); - szString += 12; // strlen("$6[Warning] "); - szAfterColour += 2; - prefixSize = 12; - break; - - case eError: - case eErrorAlways: - cry_strcpy(szString, MAX_WARNING_LENGTH, "$4[Error] "); - szString += 10; // strlen("$4[Error] "); - szAfterColour += 2; - prefixSize = 10; - break; - - default: - break; - } - - int bufferlen = sizeof(szBuffer) - prefixSize; - if (bufferlen > 0) - { -#if defined(AZ_RESTRICTED_PLATFORM) -#include AZ_RESTRICTED_FILE(Log_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - int count = vsnprintf_s(szString, bufferlen, bufferlen - 1, szCommand, args); -#endif - if (count == -1 || count >= bufferlen) - { - szBuffer[sizeof(szBuffer) - 1] = '\0'; - } - } - - if (type == eWarningAlways || type == eWarning || type == eError || type == eErrorAlways) - { - const char* sAssetScope = GetAssetScopeString(); - if (*sAssetScope) - { - stack_string s = szBuffer; - s += "\t "; - s += sAssetScope; - cry_strcpy(szBuffer, s.c_str()); - } - } - - float dt; - const char* szSpamCheck = *szFormat == '%' ? szString : szFormat; - if (m_pLogSpamDelay && (dt = m_pLogSpamDelay->GetFVal()) > 0.0f && type != eAlways && type != eInputResponse) - { - const int sz = sizeof(m_history) / sizeof(m_history[0]); - int i, j; - float time = m_pSystem->GetITimer()->GetCurrTime(); - for (i = m_iLastHistoryItem, j = 0; m_history[i].time > time - dt && j < sz; j++, i = i - 1 & sz - 1) - { - if (m_history[i].type != type) - { - continue; - } - if (m_history[i].ptr == szSpamCheck && *(int*)m_history[i].str == *(int*)szFormat || MatchStrings(m_history[i].str, szSpamCheck)) - { - return; - } - } - i = m_iLastHistoryItem = m_iLastHistoryItem + 1 & sz - 1; - cry_strcpy(m_history[i].str, m_history[i].ptr = szSpamCheck); - m_history[i].type = type; - m_history[i].time = time; - } - - LogString(szAfterColour, type); - if (bfile) - { - LogStringToFile(szAfterColour, type, false, MessageQueueState::NotQueued); - } - if (bconsole) - { - LogStringToConsole(szBuffer, ELogType::eAlways, false); - } - - switch (type) - { - case eAlways: - case eInput: - case eInputResponse: - case eComment: - case eMessage: - GetISystem()->GetIRemoteConsole()->AddLogMessage(szString); - break; - case eWarning: - case eWarningAlways: - GetISystem()->GetIRemoteConsole()->AddLogWarning(szString); - break; - case eError: - case eErrorAlways: - GetISystem()->GetIRemoteConsole()->AddLogError(szString); - break; - } -} - -//will log the text both to the end of file and console -////////////////////////////////////////////////////////////////////// -#if !defined(EXCLUDE_NORMAL_LOG) -void CLog::LogPlus(const char* szFormat, ...) -{ - if (!CheckLogFormatter(szFormat)) - { - return; - } - - if (m_pLogVerbosity && m_pLogVerbosity->GetIVal() < 0) - { - return; - } - - if (m_pLogSpamDelay && m_pLogSpamDelay->GetFVal()) - { // Vlad: SpamDelay does not work correctly with LogPlus - return; - } - - LOADING_TIME_PROFILE_SECTION(GetISystem()); - - if (!szFormat) - { - return; - } - - bool bfile = false, bconsole = false; - const char* szCommand = CheckAgainstVerbosity(szFormat, bfile, bconsole); - if (!bfile && !bconsole) - { - return; - } - - va_list arglist; - - char szTemp[MAX_TEMP_LENGTH_SIZE]; - va_start(arglist, szFormat); - vsnprintf_s(szTemp, sizeof(szTemp), sizeof(szTemp) - 1, szCommand, arglist); - szTemp[sizeof(szTemp) - 1] = 0; - va_end(arglist); - - if (bfile) - { - LogToFilePlus(szTemp); - } - if (bconsole) - { - LogToConsolePlus(szTemp); - } -} - -//log to console only -////////////////////////////////////////////////////////////////////// -void CLog::LogStringToConsole(const char* szString, ELogType logType, bool bAdd) -{ - #if defined(_RELEASE) && defined(EXCLUDE_NORMAL_LOG) // no console logging in release - return; - #endif - - - if (LogToMainThread(szString, logType, bAdd, SLogMsg::Destination::Console)) - { - return; - } - - if (!szString) - { - return; - } - - if (!m_pSystem) - { - return; - } - IConsole* console = m_pSystem->GetIConsole(); - if (!console) - { - return; - } - - - LogStringType tempString; - tempString = szString; - if (tempString.length() > MAX_TEMP_LENGTH_SIZE) - { - tempString.erase(MAX_TEMP_LENGTH_SIZE); - } - // add \n at end. - if (tempString.length() > 0 && tempString[tempString.length() - 1] != '\n') - { - tempString += '\n'; - } - - if (bAdd) - { - console->PrintLinePlus(tempString.c_str()); - } - else - { - console->PrintLine(tempString.c_str()); - } - - // Call callback function. - if (!m_callbacks.empty()) - { - for (Callbacks::iterator it = m_callbacks.begin(); it != m_callbacks.end(); ++it) - { - (*it)->OnWriteToConsole(tempString.c_str(), !bAdd); - } - } -} - -//log to console only -////////////////////////////////////////////////////////////////////// -void CLog::LogToConsole(const char* szFormat, ...) -{ - if (!CheckLogFormatter(szFormat)) - { - return; - } - - if (m_pLogVerbosity && m_pLogVerbosity->GetIVal() < 0) - { - return; - } - - if (!szFormat) - { - return; - } - - bool bfile = false, bconsole = false; - const char* szCommand = CheckAgainstVerbosity(szFormat, bfile, bconsole); - if (!bconsole) - { - return; - } - - va_list arglist; - - char szBuffer[MAX_WARNING_LENGTH]; - va_start(arglist, szFormat); - vsnprintf_s(szBuffer, sizeof(szBuffer), sizeof(szBuffer) - 1, szCommand, arglist); - szBuffer[sizeof(szBuffer) - 1] = 0; - va_end(arglist); - - LogStringToConsole(szBuffer, ELogType::eAlways, false); -} - -////////////////////////////////////////////////////////////////////// -void CLog::LogToConsolePlus(const char* szFormat, ...) -{ - if (!CheckLogFormatter(szFormat)) - { - return; - } - - if (m_pLogVerbosity && m_pLogVerbosity->GetIVal() < 0) - { - return; - } - - if (!szFormat) - { - return; - } - - bool bfile = false, bconsole = false; - const char* szCommand = CheckAgainstVerbosity(szFormat, bfile, bconsole); - if (!bconsole) - { - return; - } - - va_list arglist; - - char szTemp[MAX_TEMP_LENGTH_SIZE]; - va_start(arglist, szFormat); - vsnprintf_s(szTemp, sizeof(szTemp), sizeof(szTemp) - 1, szCommand, arglist); - szTemp[sizeof(szTemp) - 1] = 0; - va_end(arglist); - - if (!m_pSystem) - { - return; - } - - LogStringToConsole(szTemp, ELogType::eAlways, true); -} -#endif // !defined(EXCLUDE_NORMAL_LOG) - - - -////////////////////////////////////////////////////////////////////// -static void RemoveColorCodeInPlace(CLog::LogStringType& rStr) -{ - char* s = (char*)rStr.c_str(); - char* d = s; - - while (*s != 0) - { - if (*s == '$' && *(s + 1) >= '0' && *(s + 1) <= '9') - { - s += 2; - continue; - } - - *d++ = *s++; - } - *d = 0; - - rStr.resize(d - rStr.c_str()); -} - -#if defined(SUPPORT_LOG_IDENTER) -////////////////////////////////////////////////////////////////////// -void CLog::BuildIndentString() -{ - m_indentWithString = ""; - - for (uint8 i = 0; i < m_indentation; ++i) - { - m_indentWithString = indentString + m_indentWithString; - } -} - -////////////////////////////////////////////////////////////////////// -void CLog::Indent(CLogIndenter* indenter) -{ - indenter->SetNextIndenter(m_topIndenter); - m_topIndenter = indenter; - ++m_indentation; - BuildIndentString(); -} - -////////////////////////////////////////////////////////////////////// -void CLog::Unindent(CLogIndenter* indenter) -{ - assert (indenter == m_topIndenter); - assert (m_indentation); - m_topIndenter = m_topIndenter->GetNextIndenter(); - --m_indentation; - BuildIndentString(); -} - -////////////////////////////////////////////////////////////////////////// -void CLog::PushAssetScopeName(const char* sAssetType, const char* sName) -{ - assert(sAssetType); - assert(sName); - - SAssetScopeInfo as; - as.sType = sAssetType; - as.sName = sName; - CryAutoCriticalSection scope_lock(m_assetScopeQueueLock); - m_assetScopeQueue.push_back(as); -} - -void CLog::PopAssetScopeName() -{ - CryAutoCriticalSection scope_lock(m_assetScopeQueueLock); - assert(!m_assetScopeQueue.empty()); - if (!m_assetScopeQueue.empty()) - { - m_assetScopeQueue.pop_back(); - } -} - -////////////////////////////////////////////////////////////////////////// -const char* CLog::GetAssetScopeString() -{ - CryAutoCriticalSection scope_lock(m_assetScopeQueueLock); - - m_assetScopeString.clear(); - for (size_t i = 0; i < m_assetScopeQueue.size(); i++) - { - m_assetScopeString += "["; - m_assetScopeString += m_assetScopeQueue[i].sType; - m_assetScopeString += "]"; - m_assetScopeString += m_assetScopeQueue[i].sName; - if (i < m_assetScopeQueue.size() - 1) - { - m_assetScopeString += " > "; - } - } - return m_assetScopeString.c_str(); -}; -#endif - -bool CLog::LogToMainThread(const char* szString, ELogType logType, bool bAdd, SLogMsg::Destination destination) -{ - if (CryGetCurrentThreadId() != m_nMainThreadId) - { - // When logging from other thread then main, push all log strings to queue. - SLogMsg msg; - cry_strcpy(msg.msg, szString); - msg.bAdd = bAdd; - msg.destination = destination; - msg.logType = logType; - m_threadSafeMsgQueue.push(msg); - return true; - } - return false; -} - -////////////////////////////////////////////////////////////////////// -#if !defined(EXCLUDE_NORMAL_LOG) -void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[maybe_unused]] MessageQueueState queueState) -{ -#if defined(_RELEASE) && defined(EXCLUDE_NORMAL_LOG) // no file logging in release - return; -#endif - - if (!szString) - { - return; - } - - if (!m_pSystem) - { - return; - } - - LogStringType tempString; - tempString = szString; - - // this is a temp timeStr, it is reused in many branches(moved here to reduce stack usage) - LogStringType timeStr; - - // Skip any non character. - if (tempString.length() > 0 && tempString.at(0) < 32) - { - tempString.erase(0, 1); - } - - RemoveColorCodeInPlace(tempString); - - bool bIsMainThread = LogToMainThread(szString, logType, bAdd, SLogMsg::Destination::File) == false; - -#if defined(_RELEASE) - if (!bIsMainThread) - { - return; - } -#endif - -#if defined(SUPPORT_LOG_IDENTER) - if (bIsMainThread) - { - if (m_topIndenter) - { - m_topIndenter->DisplaySectionText(); - } - tempString = m_indentWithString + tempString; - } -#endif - - if (m_pLogIncludeTime && gEnv && gEnv->pTimer) - { - uint32 dwCVarState = m_pLogIncludeTime->GetIVal(); - // char szTemp[MAX_TEMP_LENGTH_SIZE]; - - if (dwCVarState == 1) // Log_IncludeTime - { - char sTime[128]; - time_t ltime; - time(<ime); -#ifdef AZ_COMPILER_MSVC - struct tm today; - localtime_s(&today, <ime); - strftime(sTime, 20, "<%H:%M:%S> ", &today); -#else - auto today = localtime(<ime); - strftime(sTime, 20, "<%H:%M:%S> ", today); -#endif - - timeStr.clear(); - timeStr.assign(sTime); - tempString = timeStr + tempString; - } - else if (dwCVarState == 2) // Log_IncludeTime - { - static CTimeValue lasttime; - CTimeValue currenttime = gEnv->pTimer->GetAsyncTime(); - if (lasttime != CTimeValue()) - { - timeStr.clear(); - uint32 dwMs = (uint32)((currenttime - lasttime).GetMilliSeconds()); - timeStr.Format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000); - tempString = timeStr + tempString; - } - lasttime = currenttime; - } - else if (dwCVarState == 3) // Log_IncludeTime - { - char sTime[128]; - time_t ltime; - time(<ime); - -#ifdef AZ_COMPILER_MSVC - struct tm today; - localtime_s(&today, <ime); - strftime(sTime, 20, "<%H:%M:%S> ", &today); -#else - auto today = localtime(<ime); - strftime(sTime, 20, "<%H:%M:%S> ", today); -#endif - tempString = LogStringType(sTime) + tempString; - - static CTimeValue lasttime; - CTimeValue currenttime = gEnv->pTimer->GetAsyncTime(); - if (lasttime != CTimeValue()) - { - timeStr.clear(); - uint32 dwMs = (uint32)((currenttime - lasttime).GetMilliSeconds()); - timeStr.Format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000); - tempString = timeStr + tempString; - } - lasttime = currenttime; - } - else if (dwCVarState == 4) // Log_IncludeTime - { - static bool bFirst = true; - - if (gEnv->pTimer) - { - static CTimeValue lasttime; - CTimeValue currenttime = gEnv->pTimer->GetAsyncTime(); - if (lasttime != CTimeValue()) - { - timeStr.clear(); - uint32 dwMs = (uint32)((currenttime - lasttime).GetMilliSeconds()); - timeStr.Format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000); - tempString = timeStr + tempString; - } - if (bFirst) - { - lasttime = currenttime; - bFirst = false; - } - } - } - else if (dwCVarState == 5) // Log_IncludeTime - { - char sTime[128]; - time_t ltime; - time(<ime); - -#ifdef AZ_COMPILER_MSVC - struct tm today; - localtime_s(&today, <ime); - strftime(sTime, 20, "<%H:%M:%S> ", &today); -#else - auto today = localtime(<ime); - strftime(sTime, 20, "<%H:%M:%S> ", today); -#endif - tempString = LogStringType(sTime) + tempString; - } - else if (dwCVarState == 6) // Log_IncludeTime - { - char sTime[128]; - time_t ltime; - time(<ime); -#ifdef AZ_COMPILER_MSVC - struct tm today; - localtime_s(&today, <ime); - strftime(sTime, 40, "<%Y-%m-%d %H:%M:%S> ", &today); -#else - auto today = localtime(<ime); - strftime(sTime, 40, "<%Y-%m-%d %H:%M:%S> ", today); -#endif - tempString = LogStringType(sTime) + tempString; - } - } - - if (tempString.empty() || tempString[tempString.length() - 1] != '\n') - { - tempString += '\n'; - } - - // do not OutputDebugString in release. -#if !defined(_RELEASE) - if (queueState == MessageQueueState::NotQueued) - { - // Note: OutputDebugString(A) only accepts current ANSI code-page, and the W variant will call the A variant internally. - // Here we replace non-ASCII characters with '?', which is the same as OutputDebugStringW will do for non-ANSI. - // Thus, we discard slightly more characters (ie, those inside the current ANSI code-page, but outside ASCII). - // In exchange, we save double-converting that would have happened otherwise (UTF-8 -> UTF-16 -> ANSI). - LogStringType asciiString; - Unicode::ConvertSafe(asciiString, tempString); - OutputDebugString(asciiString.c_str()); - } - - if (!bIsMainThread) - { - return; - } -#endif // !defined(_RELEASE) - - - ////////////////////////////////////////////////////////////////////////// - // Call callback function. - if (!m_callbacks.empty()) - { - for (Callbacks::iterator it = m_callbacks.begin(); it != m_callbacks.end(); ++it) - { - (*it)->OnWriteToFile(tempString.c_str(), !bAdd); - } - } - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // Write to file. - ////////////////////////////////////////////////////////////////////////// - int logToFile = m_pLogWriteToFile ? m_pLogWriteToFile->GetIVal() : 1; - - if (logToFile) - { - if (!m_logFileHandle.IsOpen()) - { - constexpr auto openMode = AZ::IO::SystemFile::OpenMode::SF_OPEN_APPEND - | AZ::IO::SystemFile::OpenMode::SF_OPEN_CREATE - | AZ::IO::SystemFile::OpenMode::SF_OPEN_WRITE_ONLY; - OpenLogFile(m_szFilename, openMode); - } - - if (m_logFileHandle.IsOpen()) - { -#if defined(KEEP_LOG_FILE_OPEN) - if (m_bFirstLine) - { - m_bFirstLine = false; - } -#endif - if (bAdd) - { - // if adding to a prior line erase the \n at the end. - m_logFileHandle.Seek(-2, AZ::IO::SystemFile::SeekMode::SF_SEEK_END); - } - m_logFileHandle.Write(tempString.c_str(), tempString.size()); -#if !defined(KEEP_LOG_FILE_OPEN) - CloseLogFile(); -#endif - // do not use FLUSH on log files. Doing so will slow the engine down greatly when logging. - // (the log is flushed automatically when an unhandled exception occurs) - } - } -} - -void CLog::LogString(const char* szString, ELogType logType) -{ - if (LogToMainThread(szString, logType, false, SLogMsg::Destination::Default)) - { - return; - } - - for (auto callback : m_callbacks) - { - callback->OnWrite(szString, logType); - } -} - -//same as above but to a file -////////////////////////////////////////////////////////////////////// -void CLog::LogToFilePlus(const char* szFormat, ...) -{ - if (!CheckLogFormatter(szFormat)) - { - return; - } - - if (m_pLogVerbosity && m_pLogVerbosity->GetIVal() < 0) - { - return; - } - - if (!m_szFilename[0] || !szFormat) - { - return; - } - - bool bfile = false, bconsole = false; - const char* szCommand = CheckAgainstVerbosity(szFormat, bfile, bconsole); - if (!bfile) - { - return; - } - - char szTemp[MAX_TEMP_LENGTH_SIZE]; - va_list arglist; - va_start(arglist, szFormat); - vsnprintf_s(szTemp, sizeof(szTemp), sizeof(szTemp) - 1, szCommand, arglist); - szTemp[sizeof(szTemp) - 1] = 0; - va_end(arglist); - - LogStringToFile(szTemp, ELogType::eAlways, true, MessageQueueState::NotQueued); -} - -//log to the file specified in setfilename -////////////////////////////////////////////////////////////////////// -void CLog::LogToFile(const char* szFormat, ...) -{ - if (!CheckLogFormatter(szFormat)) - { - return; - } - - if (m_pLogVerbosity && m_pLogVerbosity->GetIVal() < 0) - { - return; - } - - if (!m_szFilename[0] || !szFormat) - { - return; - } - - bool bfile = false, bconsole = false; - const char* szCommand = CheckAgainstVerbosity(szFormat, bfile, bconsole); - if (!bfile) - { - return; - } - - char szTemp[MAX_TEMP_LENGTH_SIZE]; - va_list arglist; - va_start(arglist, szFormat); - vsnprintf_s(szTemp, sizeof(szTemp), sizeof(szTemp) - 1, szCommand, arglist); - szTemp[sizeof(szTemp) - 1] = 0; - va_end(arglist); - - LogStringToFile(szTemp, ELogType::eAlways, false, MessageQueueState::NotQueued); -} -#endif // !defined(EXCLUDE_NORMAL_LOG) - -////////////////////////////////////////////////////////////////////// -void CLog::CreateBackupFile() const -{ - LOADING_TIME_PROFILE_SECTION; - if (!m_backupLogs) - { - return; - } -#if AZ_LEGACY_CRYSYSTEM_TRAIT_ALLOW_CREATE_BACKUP_LOG_FILE - // simple: - // string bakpath = PathUtil::ReplaceExtension(m_szFilename,"bak"); - // CopyFile(m_szFilename,bakpath.c_str(),false); - - // boswej: only create a backup if logging to the engine root, otherwise the - // log output has been overridden and the user is responsible - string logDir = PathUtil::RemoveSlash(PathUtil::ToUnixPath(PathUtil::GetParentDirectory(m_szFilename))); - - string sExt = PathUtil::GetExt(m_szFilename); - string sFileWithoutExt = PathUtil::GetFileName(m_szFilename); - - { - assert(::strstr(sFileWithoutExt, ":") == 0); - assert(::strstr(sFileWithoutExt, "\\") == 0); - } - - PathUtil::RemoveExtension(sFileWithoutExt); - - AZ::IO::FileIOBase* fileSystem = AZ::IO::FileIOBase::GetDirectInstance(); - AZ::IO::HandleType inFileHandle = AZ::IO::InvalidHandle; - fileSystem->Open(m_szFilename, AZ::IO::OpenMode::ModeRead | AZ::IO::OpenMode::ModeBinary, inFileHandle); - - string sBackupNameAttachment; - - // parse backup name attachment - // e.g. BackupNameAttachment="attachment name" - if (inFileHandle != AZ::IO::InvalidHandle) - { - bool bKeyFound = false; - string sName; - - while (!fileSystem->Eof(inFileHandle)) - { - uint8 c = AZ::IO::GetC(inFileHandle); - - if (c == '\"') - { - if (!bKeyFound) - { - bKeyFound = true; - - if (sName.find("BackupNameAttachment=") == string::npos) - { -#ifdef WIN32 - OutputDebugString("Log::CreateBackupFile ERROR '"); - OutputDebugString(sName.c_str()); - OutputDebugString("' not recognized \n"); -#endif - assert(0); // broken log file? - first line should include this name - written by LogVersion() - return; - } - sName.clear(); - } - else - { - sBackupNameAttachment = sName; - break; - } - continue; - } - if (c >= ' ') - { - sName += c; - } - else - { - break; - } - } - fileSystem->Close(inFileHandle); - } - - string bakdest = PathUtil::Make(LOG_BACKUP_PATH, sFileWithoutExt + sBackupNameAttachment + "." + sExt); - fileSystem->CreatePath(LOG_BACKUP_PATH); - cry_strcpy(m_sBackupFilename, bakdest.c_str()); - // Remove any existing backup file with the same name first since the copy will fail otherwise. - fileSystem->Remove(m_sBackupFilename); - fileSystem->Copy(m_szFilename, bakdest); -#endif // AZ_LEGACY_CRYSYSTEM_TRAIT_ALLOW_CREATE_BACKUP_LOG_FILE -} - -void CLog::CheckAndPruneBackupLogs() const -{ - AZ::IO::FileIOBase* fileSystem = AZ::IO::FileIOBase::GetDirectInstance(); - - AZ::u64 totalBackupDirectorySize = 0; - - struct fileInfo - { - time_t modTime; - AZStd::string filename; - AZ::u64 filesize; - - fileInfo(time_t _modTime, const char* _name, AZ::u64 _size) - { - modTime = _modTime; - filename = _name; - filesize = _size; - } - }; - - AZStd::list fileInfoList; - - // Now that we've copied the new log over, lets check the size of the backup folder and trim it as necessary to keep it within appropriate limits - AZ::IO::Result res = fileSystem->FindFiles(LOG_BACKUP_PATH, "*", - [&totalBackupDirectorySize, &fileSystem, &fileInfoList](const char* fileName) - { - AZ::u64 size; - fileSystem->Size(fileName, size); - AZ::u64 modTime = fileSystem->ModificationTime(fileName); - fileInfoList.push_back(fileInfo(modTime, fileName, size)); - - totalBackupDirectorySize += size; - return true; - }); - - AZ::u64 max_size = LogCVars::max_backup_directory_size_mb; - max_size = max_size << 20; // Convert from MB to bytes - - if (totalBackupDirectorySize > max_size) - { - // Sort the list from lowest to highest modtime (oldest to newest logs) - fileInfoList.sort([](const fileInfo &a, const fileInfo&b) { return a.modTime < b.modTime; }); - - while (totalBackupDirectorySize > max_size && fileInfoList.size() > 0) - { - fileSystem->Remove(fileInfoList.front().filename.c_str()); - totalBackupDirectorySize -= fileInfoList.front().filesize; - fileInfoList.pop_front(); - } - } -} - -//set the file used to log to disk -////////////////////////////////////////////////////////////////////// -bool CLog::SetFileName(const char* fileNameOrAbsolutePath, bool backupLogs) -{ - m_backupLogs = backupLogs; - if (!fileNameOrAbsolutePath) - { - return false; - } - azstrncpy(m_szFilename, AZ_ARRAY_SIZE(m_szFilename), fileNameOrAbsolutePath, sizeof(m_szFilename)); - - CreateBackupFile(); - - AZ::IO::FileIOBase* fileSystem = AZ::IO::FileIOBase::GetDirectInstance(); - AZ::IO::FixedMaxPath newLogFilePath; - if (fileSystem->ReplaceAlias(newLogFilePath, m_szFilename)) - { - newLogFilePath = newLogFilePath.LexicallyNormal(); - } - if (m_logFileHandle.IsOpen() && newLogFilePath != m_logFileHandle.Name()) - { - constexpr auto openMode = AZ::IO::SystemFile::OpenMode::SF_OPEN_APPEND - | AZ::IO::SystemFile::OpenMode::SF_OPEN_CREATE - | AZ::IO::SystemFile::OpenMode::SF_OPEN_WRITE_ONLY; - if(AZ::IO::SystemFile newLogFile; newLogFile.Open(m_szFilename, openMode)) - { - m_logFileHandle = AZStd::move(newLogFile); - } - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -const char* CLog::GetFileName() -{ - return m_szFilename; -} - -const char* CLog::GetBackupFileName() -{ - return m_sBackupFilename; -} - -////////////////////////////////////////////////////////////////////// -void CLog::UpdateLoadingScreen(const char* szFormat, ...) -{ -#if !defined(EXCLUDE_NORMAL_LOG) - if (szFormat) - { - // This function is OK to call with nullptr, but then it does not log anything. - va_list args; - va_start(args, szFormat); - - LogV(ILog::eMessage, szFormat, args); - - va_end(args); - } -#endif -} - -////////////////////////////////////////////////////////////////////////// -int CLog::GetVerbosityLevel() -{ - if (m_pLogVerbosity) - { - return (m_pLogVerbosity->GetIVal()); - } - - return (0); -} - -////////////////////////////////////////////////////////////////////////////////////////////////// -// Checks the verbosity of the message and returns NULL if the message must NOT be -// logged, or the pointer to the part of the message that should be logged -// NOTE: -// Normally, this is either the pText pointer itself, or the pText+1, meaning -// the first verbosity character may be cut off) -// This is done in order to avoid modification of const char*, which may cause GPF -// sometimes, or kill the verbosity qualifier in the text that's gonna be passed next time. -const char* CLog::CheckAgainstVerbosity(const char* pText, bool& logtofile, bool& logtoconsole, const uint8 DefaultVerbosity) -{ - // the max verbosity (most detailed level) -#if defined(RELEASE) - const unsigned char nMaxVerbosity = 0; -#else // #if defined(RELEASE) - const unsigned char nMaxVerbosity = 8; -#endif // #if defined(RELEASE) - - // the current verbosity of the log - int nLogVerbosityConsole = m_pLogVerbosity ? m_pLogVerbosity->GetIVal() : nMaxVerbosity; - int nLogVerbosityFile = m_pLogWriteToFileVerbosity ? m_pLogWriteToFileVerbosity->GetIVal() : nMaxVerbosity; - - logtoconsole = (nLogVerbosityConsole >= DefaultVerbosity); - - //to preserve logging to TTY, logWriteToFile logic has been moved to inside logStringToFile - //int logToFileCVar = m_pLogWriteToFile ? m_pLogWriteToFile->GetIVal() : 1; - - logtofile = (nLogVerbosityFile >= DefaultVerbosity); - - return pText; -} - - -////////////////////////////////////////////////////////////////////////// -void CLog::AddCallback(ILogCallback* pCallback) -{ - stl::push_back_unique(m_callbacks, pCallback); -} - -////////////////////////////////////////////////////////////////////////// -void CLog::RemoveCallback(ILogCallback* pCallback) -{ - m_callbacks.remove(pCallback); -} - -////////////////////////////////////////////////////////////////////////// -void CLog::Update() -{ - FUNCTION_PROFILER_FAST(m_pSystem, PROFILE_SYSTEM, g_bProfilerEnabled); - - if (CryGetCurrentThreadId() == m_nMainThreadId) - { - if (!m_threadSafeMsgQueue.empty()) - { - CryAutoCriticalSection lock(m_threadSafeMsgQueue.get_lock()); // Get the lock and hold onto it until we clear the entire queue (prevents other threads adding more things in while we clear it) - // Must be called from main thread - SLogMsg msg; - while (m_threadSafeMsgQueue.try_pop(msg)) - { - if (msg.destination == SLogMsg::Destination::Console) - { - LogStringToConsole(msg.msg, msg.logType, msg.bAdd); - } - else if (msg.destination == SLogMsg::Destination::File) - { - LogStringToFile(msg.msg, msg.logType, msg.bAdd, MessageQueueState::Queued); - } - else - { - LogString(msg.msg, msg.logType); - } - } - stl::free_container(m_threadSafeMsgQueue); - } - - if (LogCVars::s_log_tick != 0) - { - static CTimeValue t0 = GetISystem()->GetITimer()->GetAsyncTime(); - CTimeValue t1 = GetISystem()->GetITimer()->GetAsyncTime(); - if (fabs((t1 - t0).GetSeconds()) > LogCVars::s_log_tick) - { - t0 = t1; - - char sTime[128]; - time_t ltime; - time(<ime); -#ifdef AZ_COMPILER_MSVC - struct tm today; - localtime_s(&today, <ime); - strftime(sTime, sizeof(sTime) - 1, "<%H:%M:%S> ", &today); -#else - auto today = localtime(<ime); - strftime(sTime, sizeof(sTime) - 1, "<%H:%M:%S> ", today); -#endif - LogAlways(" %s", sTime); - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -const char* CLog::GetModuleFilter() -{ - if (m_pLogModule) - { - return m_pLogModule->GetString(); - } - return ""; -} - -void CLog::FlushAndClose() -{ -#if defined(KEEP_LOG_FILE_OPEN) - if (m_logFileHandle.IsOpen()) - { - CloseLogFile(); - } -#endif -} - -#if defined(KEEP_LOG_FILE_OPEN) -void CLog::LogFlushFile([[maybe_unused]] IConsoleCmdArgs* pArgs) -{ - if ((gEnv) && (gEnv->pLog)) - { - gEnv->pLog->FlushAndClose(); - } -} -#endif diff --git a/Code/CryEngine/CrySystem/Log.h b/Code/CryEngine/CrySystem/Log.h deleted file mode 100644 index b6b5f26c1f..0000000000 --- a/Code/CryEngine/CrySystem/Log.h +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include -#include -#include -#include - -////////////////////////////////////////////////////////////////////// -#if defined(ANDROID) || defined(AZ_PLATFORM_MAC) - #define MAX_TEMP_LENGTH_SIZE 4098 -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) -#include AZ_RESTRICTED_FILE(Log_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - #define MAX_TEMP_LENGTH_SIZE 8196 -#endif -#define MAX_FILENAME_SIZE 256 - -#define KEEP_LOG_FILE_OPEN - - -////////////////////////////////////////////////////////////////////// -class CLog - : public ILog -{ -public: - typedef std::list Callbacks; - typedef CryStackStringT LogStringType; - - // constructor - CLog(ISystem* pSystem); - // destructor - ~CLog(); - - - // interface ILog, IMiniLog ------------------------------------------------- - - virtual void Release() { delete this; }; - virtual bool SetFileName(const char* fileNameOrAbsolutePath, bool backupLogs); - virtual const char* GetFileName(); - virtual const char* GetBackupFileName(); -#if !defined(EXCLUDE_NORMAL_LOG) - virtual void Log(const char* command, ...) PRINTF_PARAMS(2, 3); - virtual void LogAlways(const char* command, ...) PRINTF_PARAMS(2, 3); - virtual void LogWarning(const char* command, ...) PRINTF_PARAMS(2, 3); - virtual void LogError(const char* command, ...) PRINTF_PARAMS(2, 3); - virtual void LogPlus(const char* command, ...) PRINTF_PARAMS(2, 3); - virtual void LogToFile (const char* command, ...) PRINTF_PARAMS(2, 3); - virtual void LogToFilePlus(const char* command, ...) PRINTF_PARAMS(2, 3); - virtual void LogToConsole(const char* command, ...) PRINTF_PARAMS(2, 3); - virtual void LogToConsolePlus(const char* command, ...) PRINTF_PARAMS(2, 3); -#else - virtual void Log(const char* command, ...) PRINTF_PARAMS(2, 3) { - }; - virtual void LogAlways(const char* command, ...) PRINTF_PARAMS(2, 3) { - }; - virtual void LogWarning(const char* command, ...) PRINTF_PARAMS(2, 3) { - }; - virtual void LogError(const char* command, ...) PRINTF_PARAMS(2, 3) { - }; - virtual void LogPlus(const char* command, ...) PRINTF_PARAMS(2, 3) { - }; - virtual void LogToFile (const char* command, ...) PRINTF_PARAMS(2, 3) { - }; - virtual void LogToFilePlus(const char* command, ...) PRINTF_PARAMS(2, 3) { - }; - virtual void LogToConsole(const char* command, ...) PRINTF_PARAMS(2, 3) { - }; - virtual void LogToConsolePlus(const char* command, ...) PRINTF_PARAMS(2, 3) { - }; -#endif // !defined(EXCLUDE_NORMAL_LOG) - virtual void UpdateLoadingScreen(const char* command, ...) PRINTF_PARAMS(2, 3); - virtual void SetVerbosity(int verbosity); - virtual int GetVerbosityLevel(); - virtual void RegisterConsoleVariables(); - virtual void UnregisterConsoleVariables(); - virtual void AddCallback(ILogCallback* pCallback); - virtual void RemoveCallback(ILogCallback* pCallback); - virtual void LogV(ELogType ineType, int flags, const char* szFormat, va_list args); - virtual void LogV(ELogType ineType, const char* szFormat, va_list args); - virtual void Update(); - virtual const char* GetModuleFilter(); - virtual void FlushAndClose(); - -private: // ------------------------------------------------------------------- - struct SLogMsg - { - enum class Destination - { - Default, //LogString, sends OnWrite to anycallback registered with AddCallback - Console, - File - }; - char msg[512]; - ELogType logType; - bool bAdd; - Destination destination; - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const {} - }; - - void CheckAndPruneBackupLogs() const; - - bool IsError(ELogType logType) const { return logType == ELogType::eError || logType == ELogType::eErrorAlways || logType == ELogType::eWarning || logType == ELogType::eWarningAlways; } - - //helper function to pass calls to LogString... to the main thread, returns false if you are on the main thread already, in which case just process the work. - bool LogToMainThread(const char* szString, ELogType logType, bool bAdd, SLogMsg::Destination destination); - - enum class MessageQueueState - { - NotQueued, - Queued - }; - -#if !defined(EXCLUDE_NORMAL_LOG) - void LogString(const char* szString, ELogType logType); - void LogStringToFile(const char* szString, ELogType logType, bool bAdd, MessageQueueState queueState); - void LogStringToConsole(const char* szString, ELogType logType, bool bAdd); -#else - void LogString(const char* szString, ELogType logType) {} - void LogStringToFile(const char* szString, ELogType logType, bool bAdd, MessageQueueState queueState) {} - void LogStringToConsole(const char* szString, ELogType logType, bool bAdd) {} -#endif // !defined(EXCLUDE_NORMAL_LOG) - - bool OpenLogFile(const char* filename, int mode); - void CloseLogFile(); - - // will format the message into m_szTemp - void FormatMessage(const char* szCommand, ...) PRINTF_PARAMS(2, 3); - -#if defined(SUPPORT_LOG_IDENTER) - void Indent(CLogIndenter* indenter); - void Unindent(CLogIndenter* indenter); - void BuildIndentString(); - virtual void PushAssetScopeName(const char* sAssetType, const char* sName); - virtual void PopAssetScopeName(); - virtual const char* GetAssetScopeString(); -#endif - - ISystem* m_pSystem; // - float m_fLastLoadingUpdateTime; // for non-frequent streamingEngine update - char m_szFilename[MAX_FILENAME_SIZE]; // can be with path - mutable char m_sBackupFilename[MAX_FILENAME_SIZE]; // can be with path - AZ::IO::SystemFile m_logFileHandle; - - bool m_backupLogs; - -#if defined(SUPPORT_LOG_IDENTER) - uint8 m_indentation; - LogStringType m_indentWithString; - class CLogIndenter* m_topIndenter; - - struct SAssetScopeInfo - { - string sType; - string sName; - }; - - std::vector m_assetScopeQueue; - CryCriticalSection m_assetScopeQueueLock; - string m_assetScopeString; -#endif - - ICVar* m_pLogIncludeTime; // - - IConsole* m_pConsole; // - - CryCriticalSection m_logCriticalSection; - - struct SLogHistoryItem - { - char str[MAX_WARNING_LENGTH]; - const char* ptr; - ELogType type; - float time; - }; - SLogHistoryItem m_history[16]; - int m_iLastHistoryItem; - - static bool CheckLogFormatter(const char* formatter); - -#if defined(KEEP_LOG_FILE_OPEN) - static void LogFlushFile(IConsoleCmdArgs* pArgs); - - bool m_bFirstLine; -#endif - -public: // ------------------------------------------------------------------- - - void GetMemoryUsage(ICrySizer* pSizer) const - { - pSizer->AddObject(this, sizeof(*this)); - pSizer->AddObject(m_pLogVerbosity); - pSizer->AddObject(m_pLogWriteToFile); - pSizer->AddObject(m_pLogWriteToFileVerbosity); - pSizer->AddObject(m_pLogVerbosityOverridesWriteToFile); - pSizer->AddObject(m_pLogSpamDelay); - pSizer->AddObject(m_threadSafeMsgQueue); - } - // checks the verbosity of the message and returns NULL if the message must NOT be - // logged, or the pointer to the part of the message that should be logged - const char* CheckAgainstVerbosity(const char* pText, bool& logtofile, bool& logtoconsole, const uint8 DefaultVerbosity = 2); - - // create backup of log file, useful behavior - only on development platform - void CreateBackupFile() const; - - ICVar* m_pLogVerbosity; // - ICVar* m_pLogWriteToFile; // - ICVar* m_pLogWriteToFileVerbosity; // - ICVar* m_pLogVerbosityOverridesWriteToFile; // - ICVar* m_pLogSpamDelay; // - ICVar* m_pLogModule; // Module filter for log - Callbacks m_callbacks; // - - threadID m_nMainThreadId; - CryMT::queue m_threadSafeMsgQueue; -}; diff --git a/Code/CryEngine/CrySystem/RemoteConsole/RemoteConsole.cpp b/Code/CryEngine/CrySystem/RemoteConsole/RemoteConsole.cpp deleted file mode 100644 index 8f232d81bc..0000000000 --- a/Code/CryEngine/CrySystem/RemoteConsole/RemoteConsole.cpp +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "CrySystem_precompiled.h" -#include "RemoteConsole.h" - -#ifdef USE_REMOTE_CONSOLE - #include "RemoteConsole_impl.inl" -#else - #include "RemoteConsole_none.inl" -#endif diff --git a/Code/CryEngine/CrySystem/RemoteConsole/RemoteConsole.h b/Code/CryEngine/CrySystem/RemoteConsole/RemoteConsole.h deleted file mode 100644 index a5c6099e5c..0000000000 --- a/Code/CryEngine/CrySystem/RemoteConsole/RemoteConsole.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYSYSTEM_REMOTECONSOLE_REMOTECONSOLE_H -#define CRYINCLUDE_CRYSYSTEM_REMOTECONSOLE_REMOTECONSOLE_H -#pragma once - -#include -#include - -#if !defined(RELEASE) || defined(RELEASE_LOGGING) || defined(ENABLE_PROFILING_CODE) - #define USE_REMOTE_CONSOLE - - struct SRemoteServer; -#endif - - -///////////////////////////////////////////////////////////////////////////////////////////// -// CRemoteConsole -// -// IRemoteConsole implementation -// -///////////////////////////////////////////////////////////////////////////////////////////// -class CRemoteConsole - : public IRemoteConsole -{ -public: - static CRemoteConsole* GetInst() - { - static StaticInstance> inst; - return &inst; - } - - virtual void RegisterConsoleVariables(); - virtual void UnregisterConsoleVariables(); - - virtual void Start(); - virtual void Stop(); - virtual bool IsStarted() const { return m_running; } - - virtual void AddLogMessage(const char* log); - virtual void AddLogWarning(const char* log); - virtual void AddLogError(const char* log); - - virtual void Update(); - - virtual void RegisterListener(IRemoteConsoleListener* pListener, const char* name); - virtual void UnregisterListener(IRemoteConsoleListener* pListener); - - typedef CListenerSet TListener; - - - CRemoteConsole(); - virtual ~CRemoteConsole(); - - TListener m_listener; - int m_lastPortValue = 0; - volatile bool m_running; - -#if defined(USE_REMOTE_CONSOLE) - SRemoteServer* m_pServer; - ICVar* m_pLogEnableRemoteConsole = nullptr; - ICVar* m_remoteConsoleAllowedHostList = nullptr; - ICVar* m_remoteConsolePort = nullptr; -#endif -}; - -#endif // CRYINCLUDE_CRYSYSTEM_REMOTECONSOLE_REMOTECONSOLE_H diff --git a/Code/CryEngine/CrySystem/RemoteConsole/RemoteConsole_impl.inl b/Code/CryEngine/CrySystem/RemoteConsole/RemoteConsole_impl.inl deleted file mode 100644 index 375bc89327..0000000000 --- a/Code/CryEngine/CrySystem/RemoteConsole/RemoteConsole_impl.inl +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include - - -///////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////// -CRemoteConsole::CRemoteConsole() - : m_listener(1) - , m_lastPortValue(0) - , m_running(false) - - , m_pServer(nullptr) - , m_pLogEnableRemoteConsole(nullptr) - , m_remoteConsoleAllowedHostList(nullptr) - , m_remoteConsolePort(nullptr) -{ -} - -///////////////////////////////////////////////////////////////////////////////////////////// -CRemoteConsole::~CRemoteConsole() -{ - Stop(); -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::RegisterConsoleVariables() -{ - m_pLogEnableRemoteConsole = REGISTER_INT("log_EnableRemoteConsole", 1, VF_DUMPTODISK, "enables/disables the remote console"); - m_remoteConsoleAllowedHostList = REGISTER_STRING("log_RemoteConsoleAllowedAddresses", "", VF_DUMPTODISK, "COMMA separated list of allowed hosts or IP addresses which can connect"); - m_remoteConsolePort = REGISTER_INT("log_RemoteConsolePort", defaultRemoteConsolePort, VF_DUMPTODISK, "Base port (4600 for example) for remote console to listen on. It will start there and continue upwards until an unused one is found."); - m_lastPortValue = 0; -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::UnregisterConsoleVariables() -{ - m_pLogEnableRemoteConsole = nullptr; - m_remoteConsoleAllowedHostList = nullptr; - m_remoteConsolePort = nullptr; -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::Start() -{ - if (!IsStarted()) - { - m_pServer = new SRemoteServer; - - m_pServer->StartServer(); - m_running = true; - } -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::Stop() -{ - // make sure we don't stop if we never started the remote console in the first place - if (IsStarted()) - { - m_running = false; - m_pServer->StopServer(); - m_pServer->WaitForThread(); - - delete m_pServer; - m_pServer = nullptr; - } -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::AddLogMessage(const char* log) -{ - if (!IsStarted()) - { - return; - } - - IRemoteEvent* pEvent = new SStringEvent(log); - m_pServer->AddEvent(pEvent); -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::AddLogWarning(const char* log) -{ - if (!IsStarted()) - { - return; - } - - IRemoteEvent* pEvent = new SStringEvent(log); - m_pServer->AddEvent(pEvent); -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::AddLogError(const char* log) -{ - if (!IsStarted()) - { - return; - } - - IRemoteEvent* pEvent = new SStringEvent(log); - m_pServer->AddEvent(pEvent); -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::Update() -{ - if (m_pLogEnableRemoteConsole) - { - // we disable the remote console in the editor, since there is no reason to remote into it and we don't want it eating up that port - // number anyway and preventing the game from using it. - bool isEditor = gEnv && gEnv->IsEditor(); - bool isEnabled = (!isEditor) && (m_pLogEnableRemoteConsole->GetIVal()); - bool isStarted = IsStarted(); - - int newPortValue = m_remoteConsolePort->GetIVal(); - - // the editor never allows remote control. - if ((isEnabled) && (!isStarted)) - { - Start(); - } - else if (isStarted) - { - if ((!isEnabled) || (newPortValue != m_lastPortValue)) - { - Stop(); - } - } - - m_lastPortValue = newPortValue; - - } - - if (m_pServer) - { - TEventBuffer events; - m_pServer->GetEvents(events); - for (TEventBuffer::iterator it = events.begin(), end = events.end(); it != end; ++it) - { - IRemoteEvent* pEvent = *it; - switch (pEvent->GetType()) - { - case eCET_ConsoleCommand: - for (TListener::Notifier notifier(m_listener); notifier.IsValid(); notifier.Next()) - { - notifier->OnConsoleCommand(((SStringEvent*)pEvent)->GetData()); - } - break; - case eCET_GameplayEvent: - for (TListener::Notifier notifier(m_listener); notifier.IsValid(); notifier.Next()) - { - notifier->OnGameplayCommand(((SStringEvent*)pEvent)->GetData()); - } - break; - } - delete *it; - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::RegisterListener(IRemoteConsoleListener* pListener, const char* name) -{ - m_listener.Add(pListener, name); -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::UnregisterListener(IRemoteConsoleListener* pListener) -{ - m_listener.Remove(pListener); -} diff --git a/Code/CryEngine/CrySystem/RemoteConsole/RemoteConsole_none.inl b/Code/CryEngine/CrySystem/RemoteConsole/RemoteConsole_none.inl deleted file mode 100644 index e7fb4f8cd5..0000000000 --- a/Code/CryEngine/CrySystem/RemoteConsole/RemoteConsole_none.inl +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -///////////////////////////////////////////////////////////////////////////////////////////// -CRemoteConsole::CRemoteConsole() - : m_listener(1) - , m_lastPortValue(0) - , m_running(false) -{ -} - -///////////////////////////////////////////////////////////////////////////////////////////// -CRemoteConsole::~CRemoteConsole() -{ -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::RegisterConsoleVariables() -{ -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::UnregisterConsoleVariables() -{ -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::Start() -{ -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::Stop() -{ -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::AddLogMessage(const char* log) -{ -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::AddLogWarning(const char* log) -{ -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::AddLogError(const char* log) -{ -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::Update() -{ -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::RegisterListener(IRemoteConsoleListener* pListener, const char* name) -{ -} - -///////////////////////////////////////////////////////////////////////////////////////////// -void CRemoteConsole::UnregisterListener(IRemoteConsoleListener* pListener) -{ -} diff --git a/Code/CryEngine/CrySystem/SimpleStringPool.h b/Code/CryEngine/CrySystem/SimpleStringPool.h deleted file mode 100644 index 2bfe75176a..0000000000 --- a/Code/CryEngine/CrySystem/SimpleStringPool.h +++ /dev/null @@ -1,373 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYSYSTEM_SIMPLESTRINGPOOL_H -#define CRYINCLUDE_CRYSYSTEM_SIMPLESTRINGPOOL_H -#pragma once - -#include "ISystem.h" - -#include - -//TODO: Pull most of this into a cpp file! - - -struct SStringData -{ - SStringData(const char* szString, int nStrLen) - : m_szString(szString) - , m_nStrLen(nStrLen) - { - } - - const char* m_szString; - int m_nStrLen; - bool operator==(const SStringData& other) const - { - if (m_nStrLen != other.m_nStrLen) - { - return false; - } - - return strcmp(m_szString, other.m_szString) == 0; - } -private: -}; - -template<> -inline const char* stl::constchar_cast(const SStringData& in) -{ - return in.m_szString; -} - - -///////////////////////////////////////////////////////////////////// -// String pool implementation. -// Inspired by expat implementation. -///////////////////////////////////////////////////////////////////// -class CSimpleStringPool -{ -public: - enum - { - STD_BLOCK_SIZE = 1u << 16 - }; - struct BLOCK - { - BLOCK* next; - int size; - char s[1]; - }; - unsigned int m_blockSize; - BLOCK* m_blocks; - BLOCK* m_free_blocks; - const char* m_end; - char* m_ptr; - char* m_start; - int nUsedSpace; - int nUsedBlocks; - bool m_reuseStrings; - - typedef AZStd::unordered_map > TStringToExistingStringMap; - TStringToExistingStringMap m_stringToExistingStringMap; - - static size_t g_nTotalAllocInXmlStringPools; - - CSimpleStringPool() - { - m_blockSize = STD_BLOCK_SIZE - offsetof(BLOCK, s); - m_blocks = 0; - m_start = 0; - m_ptr = 0; - m_end = 0; - nUsedSpace = 0; - nUsedBlocks = 0; - m_free_blocks = 0; - m_reuseStrings = false; - } - - explicit CSimpleStringPool(bool reuseStrings) - : m_blockSize(STD_BLOCK_SIZE - offsetof(BLOCK, s)) - , m_blocks(NULL) - , m_free_blocks(NULL) - , m_end(0) - , m_ptr(0) - , m_start(0) - , nUsedSpace(0) - , nUsedBlocks(0) - , m_reuseStrings(reuseStrings) - { - } - - ~CSimpleStringPool() - { - BLOCK* pBlock = m_blocks; - while (pBlock) - { - BLOCK* temp = pBlock->next; - g_nTotalAllocInXmlStringPools -= (offsetof(BLOCK, s) + pBlock->size * sizeof(char)); - CryModuleFree(pBlock); - pBlock = temp; - } - pBlock = m_free_blocks; - while (pBlock) - { - BLOCK* temp = pBlock->next; - g_nTotalAllocInXmlStringPools -= (offsetof(BLOCK, s) + pBlock->size * sizeof(char)); - CryModuleFree(pBlock); - pBlock = temp; - } - m_blocks = 0; - m_ptr = 0; - m_start = 0; - m_end = 0; - } - void SetBlockSize(unsigned int nBlockSize) - { - if (nBlockSize > 1024 * 1024) - { - nBlockSize = 1024 * 1024; - } - unsigned int size = 512; - while (size < nBlockSize) - { - size *= 2; - } - - m_blockSize = size - offsetof(BLOCK, s); - } - void Clear() - { - BLOCK* pLast = m_free_blocks; - if (pLast) - { - while (pLast->next) - { - pLast = pLast->next; - } - - pLast->next = m_blocks; - } - else - { - m_free_blocks = m_blocks; - } - - m_blocks = 0; - m_start = 0; - m_ptr = 0; - m_end = 0; - nUsedSpace = 0; - if (m_reuseStrings) - { - m_stringToExistingStringMap.clear(); - } - } - char* Append(const char* ptr, int nStrLen) - { - // If a string does not fit within the remainder of the string pool, a new pool will be allocated with at least - // nStrLen + 1 size, which means this code does take care of incredibly large strings. - - if (m_reuseStrings) - { - if (char* existingString = FindExistingString(ptr, nStrLen)) - { - return existingString; - } - } - - char* ret = m_ptr; - if (m_ptr && nStrLen + 1 < (m_end - m_ptr)) - { - memcpy(m_ptr, ptr, nStrLen); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - } - else - { - int nNewBlockSize = std::max(nStrLen + 1, (int)m_blockSize); - AllocBlock(nNewBlockSize, nStrLen + 1); - PREFAST_ASSUME(m_ptr); - memcpy(m_ptr, ptr, nStrLen); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - ret = m_start; - } - - if (m_reuseStrings) - { - assert(!FindExistingString(ptr, nStrLen)); - m_stringToExistingStringMap[SStringData(ret, nStrLen)] = ret; - } - - nUsedSpace += nStrLen; - return ret; - } - char* ReplaceString(const char* str1, const char* str2) - { - if (m_reuseStrings) - { - CryFatalError("Can't replace strings in an xml node that reuses strings"); - } - - int nStrLen1 = strlen(str1); - int nStrLen2 = strlen(str2); - - // undo ptr1 add. - if (m_ptr != m_start) - { - m_ptr = m_ptr - nStrLen1 - 1; - } - - assert(m_ptr == str1); - - int nStrLen = nStrLen1 + nStrLen2; - - char* ret = m_ptr; - if (m_ptr && nStrLen + 1 < (m_end - m_ptr)) - { - if (m_ptr != str1) - { - memcpy(m_ptr, str1, nStrLen1); - } - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - } - else - { - int nNewBlockSize = std::max(nStrLen + 1, (int)m_blockSize); - if (m_ptr == m_start) - { - ReallocBlock(nNewBlockSize * 2); // Reallocate current block. - PREFAST_ASSUME(m_ptr); - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - } - else - { - AllocBlock(nNewBlockSize, nStrLen + 1); - PREFAST_ASSUME(m_ptr); - memcpy(m_ptr, str1, nStrLen1); - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - } - - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - ret = m_start; - } - nUsedSpace += nStrLen; - return ret; - } - - void GetMemoryUsage(ICrySizer* pSizer) const - { - BLOCK* pBlock = m_blocks; - while (pBlock) - { - pSizer->AddObject(pBlock, offsetof(BLOCK, s) + pBlock->size * sizeof(char)); - pBlock = pBlock->next; - } - - pBlock = m_free_blocks; - while (pBlock) - { - pSizer->AddObject(pBlock, offsetof(BLOCK, s) + pBlock->size * sizeof(char)); - pBlock = pBlock->next; - } - } - -private: - CSimpleStringPool(const CSimpleStringPool&); - CSimpleStringPool& operator = (const CSimpleStringPool&); - -private: - void AllocBlock(int blockSize, int nMinBlockSize) - { - if (m_free_blocks) - { - BLOCK* pBlock = m_free_blocks; - BLOCK* pPrev = 0; - while (pBlock) - { - if (pBlock->size >= nMinBlockSize) - { - // Reuse free block - if (pPrev) - { - pPrev->next = pBlock->next; - } - else - { - m_free_blocks = pBlock->next; - } - - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + pBlock->size; - return; - } - pPrev = pBlock; - pBlock = pBlock->next; - } - } - size_t nMallocSize = offsetof(BLOCK, s) + blockSize * sizeof(char); - g_nTotalAllocInXmlStringPools += nMallocSize; - - BLOCK* pBlock = (BLOCK*)CryModuleMalloc(nMallocSize); - ; - assert(pBlock); - pBlock->size = blockSize; - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + blockSize; - nUsedBlocks++; - } - void ReallocBlock(int blockSize) - { - if (m_reuseStrings) - { - CryFatalError("Can't replace strings in an xml node that reuses strings"); - } - - BLOCK* pThisBlock = m_blocks; - BLOCK* pPrevBlock = m_blocks->next; - m_blocks = pPrevBlock; - - size_t nMallocSize = offsetof(BLOCK, s) + blockSize * sizeof(char); - if (pThisBlock) - { - g_nTotalAllocInXmlStringPools -= (offsetof(BLOCK, s) + pThisBlock->size * sizeof(char)); - } - g_nTotalAllocInXmlStringPools += nMallocSize; - - - BLOCK* pBlock = (BLOCK*)CryModuleRealloc(pThisBlock, nMallocSize); - assert(pBlock); - pBlock->size = blockSize; - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + blockSize; - } - - char* FindExistingString(const char* szString, int nStrLen) - { - SStringData testData(szString, nStrLen); - char* szResult = stl::find_in_map(m_stringToExistingStringMap, testData, NULL); - assert(!szResult || !_stricmp(szResult, szString)); - return szResult; - } -}; - - -#endif // CRYINCLUDE_CRYSYSTEM_SIMPLESTRINGPOOL_H diff --git a/Code/CryEngine/CrySystem/System.cpp b/Code/CryEngine/CrySystem/System.cpp deleted file mode 100644 index 07160a7143..0000000000 --- a/Code/CryEngine/CrySystem/System.cpp +++ /dev/null @@ -1,1826 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : CryENGINE system core-handle all subsystems - - -#include "CrySystem_precompiled.h" -#include "System.h" -#include -#include -#include -#include -#include "CryLibrary.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define SYSTEM_CPP_SECTION_1 1 -#define SYSTEM_CPP_SECTION_2 2 -#define SYSTEM_CPP_SECTION_3 3 -#define SYSTEM_CPP_SECTION_4 4 -#define SYSTEM_CPP_SECTION_5 5 -#define SYSTEM_CPP_SECTION_6 6 -#define SYSTEM_CPP_SECTION_7 7 -#define SYSTEM_CPP_SECTION_8 8 -#define SYSTEM_CPP_SECTION_9 9 -#endif - -#if defined(_RELEASE) && AZ_LEGACY_CRYSYSTEM_TRAIT_USE_EXCLUDEUPDATE_ON_CONSOLE -//exclude some not needed functionality for release console builds -#define EXCLUDE_UPDATE_ON_CONSOLE -#endif - -#ifdef WIN32 -#define WIN32_LEAN_AND_MEAN -// If app hasn't chosen, set to work with Windows 98, Windows Me, Windows 2000, Windows XP and beyond -#include - -LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - CSystem* pSystem = 0; - if (gEnv) - { - pSystem = static_cast(gEnv->pSystem); - } - if (pSystem && !pSystem->IsQuitting()) - { - LRESULT result = 0; - bool bAny = false; - for (std::vector::const_iterator it = pSystem->m_windowMessageHandlers.begin(); it != pSystem->m_windowMessageHandlers.end(); ++it) - { - IWindowMessageHandler* pHandler = *it; - LRESULT maybeResult = 0xDEADDEAD; - if (pHandler->HandleMessage(hWnd, uMsg, wParam, lParam, &maybeResult)) - { - assert(maybeResult != 0xDEADDEAD && "Message handler indicated a resulting value, but no value was written"); - if (bAny) - { - assert(result == maybeResult && "Two window message handlers tried to return different result values"); - } - else - { - bAny = true; - result = maybeResult; - } - } - } - if (bAny) - { - // One of the registered handlers returned something - return result; - } - } - - // Handle with the default procedure -#if defined(UNICODE) || defined(_UNICODE) - assert(IsWindowUnicode(hWnd) && "Window should be Unicode when compiling with UNICODE"); -#else - if (!IsWindowUnicode(hWnd)) - { - return DefWindowProcA(hWnd, uMsg, wParam, lParam); - } -#endif - return DefWindowProcW(hWnd, uMsg, wParam, lParam); -} -#endif - -#if defined(LINUX) && !defined(ANDROID) -#include // for backtrace -#endif - -#if defined(ANDROID) -#include // for _Unwind_Backtrace and _Unwind_GetIP -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(System_cpp) -#endif - -#include -#include -#include -#include -#include -#include - -#include - -#include -#include "XConsole.h" -#include "Log.h" - -#include "XML/xml.h" -#include "XML/ReadWriteXMLSink.h" - -#include "LocalizedStringManager.h" -#include "XML/XmlUtils.h" -#include "SystemEventDispatcher.h" -#include "HMDBus.h" - -#include "zlib.h" -#include "RemoteConsole/RemoteConsole.h" - -#include -#include - -#include -#include -#include - -#ifdef WIN32 - -#include - -// To enable profiling with vtune (https://software.intel.com/en-us/intel-vtune-amplifier-xe), make sure the line below is not commented out -//#define PROFILE_WITH_VTUNE - -#include -#include -#endif - -#include - -#include - -// profilers api. -VTuneFunction VTResume = NULL; -VTuneFunction VTPause = NULL; - -// Define global cvars. -SSystemCVars g_cvars; - -#include - -#include -#include -#include "AZCoreLogSink.h" - -#if defined(ANDROID) -namespace -{ - struct Callstack - { - Callstack() - : addrs(NULL) - , ignore(0) - , count(0) - { - } - Callstack(void** addrs, size_t ignore, size_t count) - { - this->addrs = addrs; - this->ignore = ignore; - this->count = count; - } - void** addrs; - size_t ignore; - size_t count; - }; - - static _Unwind_Reason_Code trace_func(struct _Unwind_Context* context, void* arg) - { - Callstack* cs = static_cast(arg); - if (cs->count) - { - void* ip = (void*) _Unwind_GetIP(context); - if (ip) - { - if (cs->ignore) - { - cs->ignore--; - } - else - { - cs->addrs[0] = ip; - cs->addrs++; - cs->count--; - } - } - } - return _URC_NO_REASON; - } - - static int Backtrace(void** addrs, size_t ignore, size_t size) - { - Callstack cs(addrs, ignore, size); - _Unwind_Backtrace(trace_func, (void*) &cs); - return size - cs.count; - } -} -#endif - -///////////////////////////////////////////////////////////////////////////////// -// System Implementation. -////////////////////////////////////////////////////////////////////////// -CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) -{ - CrySystemRequestBus::Handler::BusConnect(); - - if (!pSharedEnvironment) - { - CryFatalError("No shared environment instance provided. " - "Cross-module sharing of EBuses and allocators " - "is not possible."); - } - - m_systemGlobalState = ESYSTEM_GLOBAL_STATE_UNKNOWN; - m_iHeight = 0; - m_iWidth = 0; - m_iColorBits = 0; - // CRT ALLOCATION threshold - - m_bIsAsserting = false; - m_pSystemEventDispatcher = new CSystemEventDispatcher(); // Must be first. - - if (m_pSystemEventDispatcher) - { - m_pSystemEventDispatcher->RegisterListener(this); - } - - ////////////////////////////////////////////////////////////////////////// - // Clear environment. - ////////////////////////////////////////////////////////////////////////// - memset(&m_env, 0, sizeof(m_env)); - - ////////////////////////////////////////////////////////////////////////// - // Initialize global environment interface pointers. - m_env.pSystem = this; - m_env.pTimer = &m_Time; - m_env.pNameTable = &m_nameTable; - m_env.bIgnoreAllAsserts = false; - m_env.bNoAssertDialog = false; - - m_env.pSharedEnvironment = pSharedEnvironment; - ////////////////////////////////////////////////////////////////////////// - - m_pIFont = NULL; - m_pIFontUi = NULL; - m_rWidth = NULL; - m_rHeight = NULL; - m_rWidthAndHeightAsFractionOfScreenSize = NULL; - m_rMaxWidth = NULL; - m_rMaxHeight = NULL; - m_rColorBits = NULL; - m_rDepthBits = NULL; - m_cvSSInfo = NULL; - m_rStencilBits = NULL; - m_rFullscreen = NULL; - m_sysNoUpdate = NULL; - m_pProcess = NULL; - m_pCmdLine = NULL; - m_pLevelSystem = NULL; - m_pViewSystem = NULL; - m_pLocalizationManager = NULL; -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(System_cpp) -#endif - m_sys_min_step = 0; - m_sys_max_step = 0; - - m_cvAIUpdate = NULL; - - m_pUserCallback = NULL; - m_sys_memory_debug = NULL; - m_sysWarnings = NULL; - m_sysKeyboard = NULL; - m_sys_firstlaunch = NULL; - m_sys_enable_budgetmonitoring = NULL; - m_sys_preload = NULL; - - // m_sys_filecache = NULL; - m_gpu_particle_physics = NULL; - - m_bInitializedSuccessfully = false; - m_bRelaunch = false; - m_iLoadingMode = 0; - m_bTestMode = false; - m_bEditor = false; - m_bPreviewMode = false; - m_bIgnoreUpdates = false; - m_bNoCrashDialog = false; - m_bNoErrorReportWindow = false; - - m_pCVarQuit = NULL; - - m_bForceNonDevMode = false; - m_bWasInDevMode = false; - m_bInDevMode = false; - m_bGameFolderWritable = false; - - m_bDrawConsole = true; - m_bDrawUI = true; - - m_nServerConfigSpec = CONFIG_VERYHIGH_SPEC; - m_nMaxConfigSpec = CONFIG_VERYHIGH_SPEC; - - m_bPaused = false; - m_bNoUpdate = false; - m_nUpdateCounter = 0; - m_iApplicationInstance = -1; - - - m_pXMLUtils = new CXmlUtils(this); - - if (!AZ::AllocatorInstance::IsReady()) - { - m_initedOSAllocator = true; - AZ::AllocatorInstance::Create(); - } - if (!AZ::AllocatorInstance::IsReady()) - { - m_initedSysAllocator = true; - AZ::AllocatorInstance::Create(); - AZ::Debug::Trace::Instance().Init(); - } - - m_bNeedDoWorkDuringOcclusionChecks = false; - - m_eRuntimeState = ESYSTEM_EVENT_LEVEL_UNLOAD; - - m_bHasRenderedErrorMessage = false; - - m_pDataProbe = nullptr; -#if AZ_LEGACY_CRYSYSTEM_TRAIT_USE_MESSAGE_HANDLER - RegisterWindowMessageHandler(this); -#endif - - m_ConfigPlatform = CONFIG_INVALID_PLATFORM; -} - -///////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////// -CSystem::~CSystem() -{ - ShutDown(); - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_USE_MESSAGE_HANDLER - UnregisterWindowMessageHandler(this); -#endif - - CRY_ASSERT(m_windowMessageHandlers.empty() && "There exists a dangling window message handler somewhere"); - - SAFE_DELETE(m_pXMLUtils); - SAFE_DELETE(m_pSystemEventDispatcher); - - AZCoreLogSink::Disconnect(); - if (m_initedSysAllocator) - { - AZ::Debug::Trace::Instance().Destroy(); - AZ::AllocatorInstance::Destroy(); - } - if (m_initedOSAllocator) - { - AZ::AllocatorInstance::Destroy(); - } - - AZ::Environment::Detach(); - - m_env.pSystem = 0; - gEnv = 0; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::Release() -{ - //Disconnect the render bus - AZ::RenderNotificationsBus::Handler::BusDisconnect(); - - delete this; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::FreeLib(AZStd::unique_ptr& hLibModule) -{ - if (hLibModule) - { - if (hLibModule->IsLoaded()) - { - hLibModule->Unload(); - } - hLibModule.release(); - } -} - -////////////////////////////////////////////////////////////////////////// -IRemoteConsole* CSystem::GetIRemoteConsole() -{ - return CRemoteConsole::GetInst(); -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::SetForceNonDevMode(const bool bValue) -{ - m_bForceNonDevMode = bValue; - if (bValue) - { - SetDevMode(false); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CSystem::GetForceNonDevMode() const -{ - return m_bForceNonDevMode; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::SetDevMode(bool bEnable) -{ - if (bEnable) - { - m_bWasInDevMode = true; - } - m_bInDevMode = bEnable; -} - - -/////////////////////////////////////////////////// -void CSystem::ShutDown() -{ - CryLogAlways("System Shutdown"); - - // don't broadcast OnCrySystemShutdown unless - // we'd previously broadcast OnCrySystemInitialized - if (m_bInitializedSuccessfully) - { - EBUS_EVENT(CrySystemEventBus, OnCrySystemShutdown, *this); - } - - if (m_pUserCallback) - { - m_pUserCallback->OnShutdown(); - } - - if (GetIRemoteConsole()->IsStarted()) - { - GetIRemoteConsole()->Stop(); - } - - if (m_sys_firstlaunch) - { - m_sys_firstlaunch->Set("0"); - } - - if ((m_bEditor) && (m_env.pConsole)) - { - // restore the old saved cvars - if (m_env.pConsole->GetCVar("r_Width")) - { - m_env.pConsole->GetCVar("r_Width")->Set(m_iWidth); - } - if (m_env.pConsole->GetCVar("r_Height")) - { - m_env.pConsole->GetCVar("r_Height")->Set(m_iHeight); - } - if (m_env.pConsole->GetCVar("r_ColorBits")) - { - m_env.pConsole->GetCVar("r_ColorBits")->Set(m_iColorBits); - } - } - - if (m_bEditor && !m_bRelaunch) - { - SaveConfiguration(); - } - - // Dispatch the full-shutdown event in case this is not a fast-shutdown. - if (m_pSystemEventDispatcher != NULL) - { - m_pSystemEventDispatcher->OnSystemEvent(ESYSTEM_EVENT_FULL_SHUTDOWN, 0, 0); - } - - // Shutdown any running VR devices. - EBUS_EVENT(AZ::VR::HMDInitRequestBus, Shutdown); - - if (gEnv && gEnv->pLyShine) - { - gEnv->pLyShine->Release(); - gEnv->pLyShine = nullptr; - } - - SAFE_RELEASE(m_env.pMovieSystem); - SAFE_RELEASE(m_env.pLyShine); - SAFE_RELEASE(m_env.pCryFont); - if (m_env.pConsole) - { - ((CXConsole*)m_env.pConsole)->FreeRenderResources(); - } - SAFE_RELEASE(m_pViewSystem); - SAFE_RELEASE(m_pLevelSystem); - - if (m_env.pLog) - { - m_env.pLog->UnregisterConsoleVariables(); - } - - GetIRemoteConsole()->UnregisterConsoleVariables(); - - // Release console variables. - - SAFE_RELEASE(m_pCVarQuit); - SAFE_RELEASE(m_rWidth); - SAFE_RELEASE(m_rHeight); - SAFE_RELEASE(m_rWidthAndHeightAsFractionOfScreenSize); - SAFE_RELEASE(m_rMaxWidth); - SAFE_RELEASE(m_rMaxHeight); - SAFE_RELEASE(m_rColorBits); - SAFE_RELEASE(m_rDepthBits); - SAFE_RELEASE(m_cvSSInfo); - SAFE_RELEASE(m_rStencilBits); - SAFE_RELEASE(m_rFullscreen); - - SAFE_RELEASE(m_sysWarnings); - SAFE_RELEASE(m_sysKeyboard); - SAFE_RELEASE(m_sys_firstlaunch); - SAFE_RELEASE(m_sys_enable_budgetmonitoring); - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_3 -#include AZ_RESTRICTED_FILE(System_cpp) -#endif - - SAFE_RELEASE(m_sys_min_step); - SAFE_RELEASE(m_sys_max_step); - - SAFE_DELETE(m_pLocalizationManager); - - delete m_pCmdLine; - m_pCmdLine = 0; - - // Audio System Shutdown! - // Shut down audio as late as possible but before the streaming system and console get released! - Audio::Gem::AudioSystemGemRequestBus::Broadcast(&Audio::Gem::AudioSystemGemRequestBus::Events::Release); - - // Shut down console as late as possible and after audio! - SAFE_RELEASE(m_env.pConsole); - - // Log must be last thing released. - if (m_env.pLog) - { - m_env.pLog->FlushAndClose(); - } - SAFE_RELEASE(m_env.pLog); // creates log backup - - ShutdownFileSystem(); - - ShutdownModuleLibraries(); - - EBUS_EVENT(CrySystemEventBus, OnCrySystemPostShutdown); -} - -///////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////// -void CSystem::Quit() -{ - CryLogAlways("CSystem::Quit invoked from thread %" PRI_THREADID " (main is %" PRI_THREADID ")", GetCurrentThreadId(), gEnv->mMainThreadId); - - AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::ExitMainLoop); - - // If this was set from anywhere but the main thread, bail and let the main thread handle shutdown - if (GetCurrentThreadId() != gEnv->mMainThreadId) - { - return; - } - - if (m_pUserCallback) - { - m_pUserCallback->OnQuit(); - } - - gEnv->pLog->FlushAndClose(); - - // Latest possible place to flush any pending messages to disk before the forceful termination. - if (auto logger = AZ::Interface::Get(); logger) - { - logger->Flush(); - } - - /* - * TODO: This call to _exit, _Exit, TerminateProcess etc. needs to - * eventually be removed. This causes an extremely early exit before we - * actually perform cleanup. When this gets called most managers are - * simply never deleted and we leave it to the OS to clean up our mess - * which is just really bad practice. However there are LOTS of issues - * with shutdown at the moment. Removing this will simply cause - * a crash when either the Editor or Launcher initiate shutdown. Both - * applications crash differently too. Bugs will be logged about those - * issues. - */ -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_4 -#include AZ_RESTRICTED_FILE(System_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(WIN32) || defined(WIN64) - TerminateProcess(GetCurrentProcess(), m_env.retCode); -#else - exit(m_env.retCode); -#endif - -#ifdef WIN32 - //Post a WM_QUIT message to the Win32 api which causes the message loop to END - //This is not the same as handling a WM_DESTROY event which destroys a window - //but keeps the message loop alive. - PostQuitMessage(0); -#endif -} -///////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////// -bool CSystem::IsQuitting() const -{ - bool wasExitMainLoopRequested = false; - AzFramework::ApplicationRequests::Bus::BroadcastResult(wasExitMainLoopRequested, &AzFramework::ApplicationRequests::WasExitMainLoopRequested); - return wasExitMainLoopRequested; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::SetIProcess(IProcess* process) -{ - m_pProcess = process; - //if (m_pProcess) - //m_pProcess->SetPMessage(""); -} - -////////////////////////////////////////////////////////////////////////// -ISystem* CSystem::GetCrySystem() -{ - return this; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::SleepIfNeeded() -{ - FUNCTION_PROFILER_FAST(this, PROFILE_SYSTEM, g_bProfilerEnabled); - - ITimer* const pTimer = gEnv->pTimer; - static bool firstCall = true; - - typedef MiniQueue PrevNow; - static PrevNow prevNow; - if (firstCall) - { - m_lastTickTime = pTimer->GetAsyncTime(); - prevNow.Push(m_lastTickTime); - firstCall = false; - return; - } - - const float maxRate = m_svDedicatedMaxRate->GetFVal(); - const float minTime = 1.0f / maxRate; - CTimeValue now = pTimer->GetAsyncTime(); - float elapsed = (now - m_lastTickTime).GetSeconds(); - - if (prevNow.Full()) - { - prevNow.Pop(); - } - prevNow.Push(now); - - static bool allowStallCatchup = true; - if (elapsed > minTime && allowStallCatchup) - { - allowStallCatchup = false; - m_lastTickTime = pTimer->GetAsyncTime(); - return; - } - allowStallCatchup = true; - - float totalElapsed = (now - prevNow.Front()).GetSeconds(); - float wantSleepTime = CLAMP(minTime * (prevNow.Size() - 1) - totalElapsed, 0, (minTime - elapsed) * 0.9f); - static float sleepTime = 0; - sleepTime = (15 * sleepTime + wantSleepTime) / 16; - int sleepMS = (int)(1000.0f * sleepTime + 0.5f); - if (sleepMS > 0) - { - AZ_PROFILE_FUNCTION_IDLE(AZ::Debug::ProfileCategory::System); - Sleep(sleepMS); - } - - m_lastTickTime = pTimer->GetAsyncTime(); -} - -extern DWORD g_idDebugThreads[]; -extern int g_nDebugThreads; -int prev_sys_float_exceptions = -1; - -////////////////////////////////////////////////////////////////////// -bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) -{ - // If we detect the quit flag at the start of Update, that means it was set - // from another thread, and we should quit immediately. Otherwise, it will - // be set by game logic or the console during Update and we will quit later - if (IsQuitting()) - { - Quit(); - return false; - } - -#ifndef EXCLUDE_UPDATE_ON_CONSOLE - // do the dedicated sleep earlier than the frame profiler to avoid having it counted - if (gEnv->IsDedicated()) - { - SleepIfNeeded(); - } -#endif //EXCLUDE_UPDATE_ON_CONSOLE - -#ifdef WIN32 - // enable/disable SSE fp exceptions (#nan and /0) - // need to do it each frame since sometimes they are being reset - _mm_setcsr(_mm_getcsr() & ~0x280 | (g_cvars.sys_float_exceptions > 0 ? 0 : 0x280)); -#endif //WIN32 - - FUNCTION_PROFILER_LEGACYONLY(GetISystem(), PROFILE_SYSTEM); - AZ_TRACE_METHOD(); - - m_nUpdateCounter++; -#ifndef EXCLUDE_UPDATE_ON_CONSOLE - if (m_pUserCallback) - { - m_pUserCallback->OnUpdate(); - } - - ////////////////////////////////////////////////////////////////////////// - // Enable/Disable floating exceptions. - ////////////////////////////////////////////////////////////////////////// - prev_sys_float_exceptions += 1 + g_cvars.sys_float_exceptions & prev_sys_float_exceptions >> 31; - if (prev_sys_float_exceptions != g_cvars.sys_float_exceptions) - { - prev_sys_float_exceptions = g_cvars.sys_float_exceptions; - - EnableFloatExceptions(g_cvars.sys_float_exceptions); - } -#endif //EXCLUDE_UPDATE_ON_CONSOLE - ////////////////////////////////////////////////////////////////////////// - - if (m_env.pLog) - { - m_env.pLog->Update(); - } - -#ifdef USE_REMOTE_CONSOLE - GetIRemoteConsole()->Update(); -#endif - if (nPauseMode != 0) - { - m_bPaused = true; - } - else - { - m_bPaused = false; - } - -#ifdef PROFILE_WITH_VTUNE - if (m_bInDevMode) - { - if (VTPause != NULL && VTResume != NULL) - { - static bool bVtunePaused = true; - - const AzFramework::InputChannel* inputChannelScrollLock = AzFramework::InputChannelRequests::FindInputChannel(AzFramework::InputDeviceKeyboard::Key::WindowsSystemScrollLock); - const bool bPaused = (inputChannelScrollLock ? inputChannelScrollLock->IsActive() : false); - - { - if (bVtunePaused && !bPaused) - { - GetIProfilingSystem()->VTuneResume(); - } - if (!bVtunePaused && bPaused) - { - GetIProfilingSystem()->VTunePause(); - } - bVtunePaused = bPaused; - } - } - } -#endif //PROFILE_WITH_VTUNE - -#ifndef EXCLUDE_UPDATE_ON_CONSOLE - if (m_bIgnoreUpdates) - { - return true; - } -#endif //EXCLUDE_UPDATE_ON_CONSOLE - - //static bool sbPause = false; - //bool bPause = false; - bool bNoUpdate = false; -#ifndef EXCLUDE_UPDATE_ON_CONSOLE - if (m_sysNoUpdate && m_sysNoUpdate->GetIVal()) - { - bNoUpdate = true; - } - - m_bNoUpdate = bNoUpdate; -#endif //EXCLUDE_UPDATE_ON_CONSOLE - - //check if we are quitting from the game - if (IsQuitting()) - { - Quit(); - return (false); - } - - //limit frame rate if vsync is turned off - //for consoles this is done inside renderthread to be vsync dependent - { - FRAME_PROFILER_LEGACYONLY("FRAME_CAP", gEnv->pSystem, PROFILE_SYSTEM); - AZ_TRACE_METHOD_NAME("FrameLimiter"); - static ICVar* pSysMaxFPS = NULL; - static ICVar* pVSync = NULL; - - if (pSysMaxFPS == NULL && gEnv && gEnv->pConsole) - { - pSysMaxFPS = gEnv->pConsole->GetCVar("sys_MaxFPS"); - } - if (pVSync == NULL && gEnv && gEnv->pConsole) - { - pVSync = gEnv->pConsole->GetCVar("r_Vsync"); - } - - if (pSysMaxFPS && pVSync) - { - int32 maxFPS = pSysMaxFPS->GetIVal(); - uint32 vSync = pVSync->GetIVal(); - - if (maxFPS == 0 && vSync == 0) - { - ILevelSystem* pLvlSys = GetILevelSystem(); - const bool inLevel = pLvlSys && pLvlSys->IsLevelLoaded(); - maxFPS = !inLevel || IsPaused() ? 60 : 0; - } - - if (maxFPS > 0 && vSync == 0) - { - CTimeValue timeFrameMax; - const float safeMarginFPS = 0.5f;//save margin to not drop below 30 fps - static CTimeValue sTimeLast = gEnv->pTimer->GetAsyncTime(); - timeFrameMax.SetMilliSeconds((int64)(1000.f / ((float)maxFPS + safeMarginFPS))); - const CTimeValue timeLast = timeFrameMax + sTimeLast; - while (timeLast.GetValue() > gEnv->pTimer->GetAsyncTime().GetValue()) - { - CrySleep(0); - } - sTimeLast = gEnv->pTimer->GetAsyncTime(); - } - } - } - - ////////////////////////////////////////////////////////////////////// - //update time subsystem - m_Time.UpdateOnFrameStart(); - - ////////////////////////////////////////////////////////////////////// - //update console system - if (m_env.pConsole) - { - FRAME_PROFILER("SysUpdate:Console", this, PROFILE_SYSTEM); - m_env.pConsole->Update(); - } - - if (IsQuitting()) - { - Quit(); - return false; - } - - ////////////////////////////////////////////////////////////////////// - //update sound system Part 1 if in Editor / in Game Mode Viewsystem updates the Listeners - if (!m_env.IsEditorGameMode()) - { - if ((updateFlags & ESYSUPDATE_EDITOR) != 0 && !bNoUpdate && nPauseMode != 1) - { - // updating the Listener Position in a first separate step. - // Updating all views here is a bit of a workaround, since we need - // to ensure that sound listeners owned by inactive views are also - // marked as inactive. Ideally that should happen when exiting game mode. - if (GetIViewSystem()) - { - FRAME_PROFILER("SysUpdate:UpdateSoundListeners", this, PROFILE_SYSTEM); - GetIViewSystem()->UpdateSoundListeners(); - } - } - } - - // Use UI timer for CryMovie, because it should not be affected by pausing game time - const float fMovieFrameTime = m_Time.GetFrameTime(ITimer::ETIMER_UI); - - // Run movie system pre-update - if (!bNoUpdate) - { - FRAME_PROFILER("SysUpdate:UpdateMovieSystem", this, PROFILE_SYSTEM); - UpdateMovieSystem(updateFlags, fMovieFrameTime, true); - } - - return !IsQuitting(); -} - -////////////////////////////////////////////////////////////////////// -bool CSystem::UpdatePostTickBus(int updateFlags, int /*nPauseMode*/) -{ - CTimeValue updateStart = gEnv->pTimer->GetAsyncTime(); - - // Run movie system post-update - if (!m_bNoUpdate) - { - const float fMovieFrameTime = m_Time.GetFrameTime(ITimer::ETIMER_UI); - FRAME_PROFILER("SysUpdate:UpdateMovieSystem", this, PROFILE_SYSTEM); - UpdateMovieSystem(updateFlags, fMovieFrameTime, false); - } - - ////////////////////////////////////////////////////////////////////// - //update sound system part 2 - if (!g_cvars.sys_deferAudioUpdateOptim && !m_bNoUpdate) - { - FRAME_PROFILER("SysUpdate:UpdateAudioSystems", this, PROFILE_SYSTEM); - UpdateAudioSystems(); - } - else - { - m_bNeedDoWorkDuringOcclusionChecks = true; - } - - //Now update frame statistics - CTimeValue cur_time = gEnv->pTimer->GetAsyncTime(); - - CTimeValue a_second(g_cvars.sys_update_profile_time); - std::vector< std::pair >::iterator it = m_updateTimes.begin(); - for (std::vector< std::pair >::iterator eit = m_updateTimes.end(); it != eit; ++it) - { - if ((cur_time - it->first) < a_second) - { - break; - } - } - - { - if (it != m_updateTimes.begin()) - { - m_updateTimes.erase(m_updateTimes.begin(), it); - } - - float updateTime = (cur_time - updateStart).GetMilliSeconds(); - m_updateTimes.push_back(std::make_pair(cur_time, updateTime)); - } - - { - FRAME_PROFILER("SysUpdate - SystemEventDispatcher::Update", this, PROFILE_SYSTEM); - m_pSystemEventDispatcher->Update(); - } - - if (!gEnv->IsEditing() && m_eRuntimeState == ESYSTEM_EVENT_LEVEL_GAMEPLAY_START) - { - gEnv->pCryPak->DisableRuntimeFileAccess(true); - } - - // Also broadcast for anyone else that needs to draw global debug to do so now - AzFramework::DebugDisplayEventBus::Broadcast(&AzFramework::DebugDisplayEvents::DrawGlobalDebugInfo); - - return !IsQuitting(); -} - - -bool CSystem::UpdateLoadtime() -{ - return !IsQuitting(); -} - -void CSystem::DoWorkDuringOcclusionChecks() -{ - if (g_cvars.sys_deferAudioUpdateOptim && !m_bNoUpdate) - { - UpdateAudioSystems(); - m_bNeedDoWorkDuringOcclusionChecks = false; - } -} - -void CSystem::UpdateAudioSystems() -{ - AZ_TRACE_METHOD(); - FRAME_PROFILER_LEGACYONLY("SysUpdate:Audio", this, PROFILE_SYSTEM); - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::ExternalUpdate); -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::GetUpdateStats(SSystemUpdateStats& stats) -{ - if (m_updateTimes.empty()) - { - stats = SSystemUpdateStats(); - } - else - { - stats.avgUpdateTime = 0; - stats.maxUpdateTime = -FLT_MAX; - stats.minUpdateTime = +FLT_MAX; - for (std::vector< std::pair >::const_iterator it = m_updateTimes.begin(), eit = m_updateTimes.end(); it != eit; ++it) - { - const float t = it->second; - stats.avgUpdateTime += t; - stats.maxUpdateTime = max(stats.maxUpdateTime, t); - stats.minUpdateTime = min(stats.minUpdateTime, t); - } - stats.avgUpdateTime /= m_updateTimes.size(); - } -} - - -////////////////////////////////////////////////////////////////////////// -void CSystem::UpdateMovieSystem(const int updateFlags, const float fFrameTime, const bool bPreUpdate) -{ - if (m_env.pMovieSystem && !(updateFlags & ESYSUPDATE_EDITOR) && g_cvars.sys_trackview) - { - float fMovieFrameTime = fFrameTime; - - if (fMovieFrameTime > g_cvars.sys_maxTimeStepForMovieSystem) - { - fMovieFrameTime = g_cvars.sys_maxTimeStepForMovieSystem; - } - - if (bPreUpdate) - { - m_env.pMovieSystem->PreUpdate(fMovieFrameTime); - } - else - { - m_env.pMovieSystem->PostUpdate(fMovieFrameTime); - } - } -} - -////////////////////////////////////////////////////////////////////////// -// XML stuff -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -XmlNodeRef CSystem::CreateXmlNode(const char* sNodeName, bool bReuseStrings, bool bIsProcessingInstruction) -{ - return new CXmlNode(sNodeName, bReuseStrings, bIsProcessingInstruction); -} - -////////////////////////////////////////////////////////////////////////// -IXmlUtils* CSystem::GetXmlUtils() -{ - return m_pXMLUtils; -} - -////////////////////////////////////////////////////////////////////////// -XmlNodeRef CSystem::LoadXmlFromFile(const char* sFilename, bool bReuseStrings) -{ - LOADING_TIME_PROFILE_SECTION_ARGS(sFilename); - - return m_pXMLUtils->LoadXmlFromFile(sFilename, bReuseStrings); -} - -////////////////////////////////////////////////////////////////////////// -XmlNodeRef CSystem::LoadXmlFromBuffer(const char* buffer, size_t size, bool bReuseStrings, bool bSuppressWarnings) -{ - LOADING_TIME_PROFILE_SECTION - return m_pXMLUtils->LoadXmlFromBuffer(buffer, size, bReuseStrings, bSuppressWarnings); -} - -////////////////////////////////////////////////////////////////////////// -bool CSystem::CheckLogVerbosity(int verbosity) -{ - if (verbosity <= m_env.pLog->GetVerbosityLevel()) - { - return true; - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::Warning(EValidatorModule module, EValidatorSeverity severity, int flags, const char* file, const char* format, ...) -{ - va_list args; - va_start(args, format); - WarningV(module, severity, flags, file, format, args); - va_end(args); -} - -////////////////////////////////////////////////////////////////////////// -int CSystem::ShowMessage(const char* text, const char* caption, unsigned int uType) -{ - if (m_pUserCallback) - { - return m_pUserCallback->ShowMessage(text, caption, uType); - } - return CryMessageBox(text, caption, uType); -} - -inline const char* ValidatorModuleToString(EValidatorModule module) -{ - switch (module) - { - case VALIDATOR_MODULE_RENDERER: - return "Renderer"; - case VALIDATOR_MODULE_3DENGINE: - return "3DEngine"; - case VALIDATOR_MODULE_ASSETS: - return "Assets"; - case VALIDATOR_MODULE_SYSTEM: - return "System"; - case VALIDATOR_MODULE_AUDIO: - return "Audio"; - case VALIDATOR_MODULE_MOVIE: - return "Movie"; - case VALIDATOR_MODULE_EDITOR: - return "Editor"; - case VALIDATOR_MODULE_NETWORK: - return "Network"; - case VALIDATOR_MODULE_PHYSICS: - return "Physics"; - case VALIDATOR_MODULE_ONLINE: - return "Online"; - case VALIDATOR_MODULE_FEATURETESTS: - return "FeatureTests"; - case VALIDATOR_MODULE_SHINE: - return "UI"; - } - return ""; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::WarningV(EValidatorModule module, EValidatorSeverity severity, int flags, const char* file, const char* format, va_list args) -{ - // Fran: No logging in a testing environment - if (m_env.pLog == 0) - { - return; - } - - const char* sModuleFilter = m_env.pLog->GetModuleFilter(); - if (sModuleFilter && *sModuleFilter != 0) - { - const char* sModule = ValidatorModuleToString(module); - if (strlen(sModule) > 1 || CryStringUtils::stristr(sModule, sModuleFilter) == 0) - { - // Filter out warnings from other modules. - return; - } - } - - bool bDbgBreak = false; - if (severity == VALIDATOR_ERROR_DBGBRK) - { - bDbgBreak = true; - severity = VALIDATOR_ERROR; // change it to a standard VALIDATOR_ERROR for simplicity in the rest of the system - } - - IMiniLog::ELogType ltype = ILog::eComment; - switch (severity) - { - case VALIDATOR_ERROR: - ltype = ILog::eError; - break; - case VALIDATOR_WARNING: - ltype = ILog::eWarning; - break; - case VALIDATOR_COMMENT: - ltype = ILog::eComment; - break; - default: - break; - } - char szBuffer[MAX_WARNING_LENGTH]; - vsnprintf_s(szBuffer, sizeof(szBuffer), sizeof(szBuffer) - 1, format, args); - - if (file && *file) - { - CryFixedStringT fmt = szBuffer; - fmt += " [File="; - fmt += file; - fmt += "]"; - - m_env.pLog->LogWithType(ltype, flags | VALIDATOR_FLAG_SKIP_VALIDATOR, "%s", fmt.c_str()); - } - else - { - m_env.pLog->LogWithType(ltype, flags | VALIDATOR_FLAG_SKIP_VALIDATOR, "%s", szBuffer); - } - - if (bDbgBreak && g_cvars.sys_error_debugbreak) - { - AZ::Debug::Trace::Break(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::GetLocalizedPath(const char* sLanguage, string& sLocalizedPath) -{ - // Omit the trailing slash! - string sLocalizationFolder(string().assign(PathUtil::GetLocalizationFolder(), 0, PathUtil::GetLocalizationFolder().size() - 1)); - - int locFormat = 0; - LocalizationManagerRequestBus::BroadcastResult(locFormat, &LocalizationManagerRequestBus::Events::GetLocalizationFormat); - if(locFormat == 1) - { - sLocalizedPath = sLocalizationFolder + "/" + sLanguage + ".loc.agsxml"; - } - else - { - if (sLocalizationFolder.compareNoCase("Languages") != 0) - { - sLocalizedPath = sLocalizationFolder + "/" + sLanguage + "_xml.pak"; - } - else - { - sLocalizedPath = string("Localized/") + sLanguage + "_xml.pak"; - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::GetLocalizedAudioPath(const char* sLanguage, string& sLocalizedPath) -{ - // Omit the trailing slash! - string sLocalizationFolder(string().assign(PathUtil::GetLocalizationFolder(), 0, PathUtil::GetLocalizationFolder().size() - 1)); - - if (sLocalizationFolder.compareNoCase("Languages") != 0) - { - sLocalizedPath = sLocalizationFolder + "/" + sLanguage + ".pak"; - } - else - { - sLocalizedPath = string("Localized/") + sLanguage + ".pak"; - } -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::CloseLanguagePak(const char* sLanguage) -{ - string sLocalizedPath; - GetLocalizedPath(sLanguage, sLocalizedPath); - m_env.pCryPak->ClosePacks({ sLocalizedPath.c_str(), sLocalizedPath.size() }); -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::CloseLanguageAudioPak(const char* sLanguage) -{ - string sLocalizedPath; - GetLocalizedAudioPath(sLanguage, sLocalizedPath); - m_env.pCryPak->ClosePacks({ sLocalizedPath.c_str(), sLocalizedPath.size() }); -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::Relaunch(bool bRelaunch) -{ - if (m_sys_firstlaunch) - { - m_sys_firstlaunch->Set("0"); - } - - m_bRelaunch = bRelaunch; - SaveConfiguration(); -} - -////////////////////////////////////////////////////////////////////////// -ILocalizationManager* CSystem::GetLocalizationManager() -{ - return m_pLocalizationManager; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::debug_GetCallStackRaw(void** callstack, uint32& callstackLength) -{ - uint32 callstackCapacity = callstackLength; - uint32 nNumStackFramesToSkip = 1; - - memset(callstack, 0, sizeof(void*) * callstackLength); - -#if !defined(ANDROID) - callstackLength = 0; -#endif - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_CAPTURESTACK - if (callstackCapacity > 0x40) - { - callstackCapacity = 0x40; - } - callstackLength = RtlCaptureStackBackTrace(nNumStackFramesToSkip, callstackCapacity, callstack, NULL); -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_7 -#include AZ_RESTRICTED_FILE(System_cpp) -#endif - - if (callstackLength > 0) - { - std::reverse(callstack, callstack + callstackLength); - } -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::ExecuteCommandLine(bool deferred) -{ - if (m_executedCommandLine) - { - return; - } - - m_executedCommandLine = true; - - // execute command line arguments e.g. +g_gametype ASSAULT +map "testy" - - ICmdLine* pCmdLine = GetICmdLine(); - assert(pCmdLine); - - const int iCnt = pCmdLine->GetArgCount(); - for (int i = 0; i < iCnt; ++i) - { - const ICmdLineArg* pCmd = pCmdLine->GetArg(i); - - if (pCmd->GetType() == eCLAT_Post) - { - string sLine = pCmd->GetName(); - { - if (pCmd->GetValue()) - { - sLine += string(" ") + pCmd->GetValue(); - } - - 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); - } - } - } - - //gEnv->pConsole->ExecuteString("sys_RestoreSpec test*"); // to get useful debugging information about current spec settings to the log file -} - -////////////////////////////////////////////////////////////////////////// -ESystemConfigSpec CSystem::GetMaxConfigSpec() const -{ - return m_nMaxConfigSpec; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::SetConfigPlatform(const ESystemConfigPlatform platform) -{ - m_ConfigPlatform = platform; -} - -////////////////////////////////////////////////////////////////////////// -ESystemConfigPlatform CSystem::GetConfigPlatform() const -{ - return m_ConfigPlatform; -} - -////////////////////////////////////////////////////////////////////////// -CPNoise3* CSystem::GetNoiseGen() -{ - static CPNoise3 m_pNoiseGen; - return &m_pNoiseGen; -} - -////////////////////////////////////////////////////////////////////////// -void CProfilingSystem::VTuneResume() -{ -#ifdef PROFILE_WITH_VTUNE - if (VTResume) - { - CryLogAlways("VTune Resume"); - VTResume(); - } -#endif -} - -////////////////////////////////////////////////////////////////////////// -void CProfilingSystem::VTunePause() -{ -#ifdef PROFILE_WITH_VTUNE - if (VTPause) - { - VTPause(); - CryLogAlways("VTune Pause"); - } -#endif -} - -////////////////////////////////////////////////////////////////////// -void CSystem::OnLanguageCVarChanged(ICVar* language) -{ - if (language && language->GetType() == CVAR_STRING) - { - CSystem* pSys = static_cast(gEnv->pSystem); - if (pSys && pSys->GetLocalizationManager()) - { - const char* lang = language->GetString(); - - // Hook up Localization initialization - int locFormat = 0; - LocalizationManagerRequestBus::BroadcastResult(locFormat, &LocalizationManagerRequestBus::Events::GetLocalizationFormat); - if (locFormat == 0) - { - const char* locLanguage = nullptr; - LocalizationManagerRequestBus::BroadcastResult(locLanguage, &LocalizationManagerRequestBus::Events::GetLanguage); - pSys->OpenLanguagePak(lang); - } - - LocalizationManagerRequestBus::Broadcast(&LocalizationManagerRequestBus::Events::SetLanguage, lang); - LocalizationManagerRequestBus::Broadcast(&LocalizationManagerRequestBus::Events::ReloadData); - - if (gEnv->pCryFont) - { - gEnv->pCryFont->OnLanguageChanged(); - } - } - } -} - -////////////////////////////////////////////////////////////////////// -void CSystem::OnLanguageAudioCVarChanged(ICVar* language) -{ - static Audio::SAudioRequest oLanguageRequest; - static Audio::SAudioManagerRequestData oLanguageRequestData; - - if (language && (language->GetType() == CVAR_STRING)) - { - oLanguageRequest.pData = &oLanguageRequestData; - oLanguageRequest.nFlags = Audio::eARF_PRIORITY_HIGH; - Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequest, oLanguageRequest); - } -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::OnLocalizationFolderCVarChanged(ICVar* const pLocalizationFolder) -{ - if (pLocalizationFolder && pLocalizationFolder->GetType() == CVAR_STRING) - { - CSystem* const pSystem = static_cast(gEnv->pSystem); - - if (pSystem != NULL && gEnv->pCryPak != NULL) - { - CLocalizedStringsManager* const pLocalizationManager = static_cast(pSystem->GetLocalizationManager()); - - if (pLocalizationManager) - { - // Get what is currently loaded - CLocalizedStringsManager::TLocalizationTagVec tagVec; - pLocalizationManager->GetLoadedTags(tagVec); - - // Release the old localization data. - CLocalizedStringsManager::TLocalizationTagVec::const_iterator end = tagVec.end(); - for (CLocalizedStringsManager::TLocalizationTagVec::const_iterator it = tagVec.begin(); it != end; ++it) - { - pLocalizationManager->ReleaseLocalizationDataByTag(it->c_str()); - } - - // Close the paks situated in the previous localization folder. - pSystem->CloseLanguagePak(pLocalizationManager->GetLanguage()); - pSystem->CloseLanguageAudioPak(pSystem->m_currentLanguageAudio.c_str()); - - // Set the new localization folder. - gEnv->pCryPak->SetLocalizationFolder(pLocalizationFolder->GetString()); - - // Now open the paks situated in the new localization folder. - pSystem->OpenLanguagePak(pLocalizationManager->GetLanguage()); - pSystem->OpenLanguageAudioPak(pSystem->m_currentLanguageAudio.c_str()); - - // And load the new data. - for (CLocalizedStringsManager::TLocalizationTagVec::const_iterator it = tagVec.begin(); it != end; ++it) - { - pLocalizationManager->LoadLocalizationDataByTag(it->c_str()); - } - } - } - } -} - -// Catch changes to assert verbosity and update the global used to track it -void CSystem::SetAssertLevel(int _assertlevel) -{ - AZ::EnvironmentVariable assertVerbosityLevel = AZ::Environment::FindVariable("assertVerbosityLevel"); - if (assertVerbosityLevel) - { - assertVerbosityLevel.Set(_assertlevel); - } -} - -void CSystem::OnAssertLevelCvarChanged(ICVar* pArgs) -{ - SetAssertLevel(pArgs->GetIVal()); -} - -void CSystem::SetLogLevel(int _loglevel) -{ - AZ::EnvironmentVariable logVerbosityLevel = AZ::Environment::FindVariable("sys_LogLevel"); - if (logVerbosityLevel.IsConstructed()) - { - logVerbosityLevel.Set(_loglevel); - } -} - -void CSystem::OnLogLevelCvarChanged(ICVar* pArgs) -{ - if (pArgs) - { - SetLogLevel(pArgs->GetIVal()); - } -} - - -void CSystem::OnSystemEvent(ESystemEvent event, [[maybe_unused]] UINT_PTR wparam, [[maybe_unused]] UINT_PTR lparam) -{ - switch (event) - { - case ESYSTEM_EVENT_LEVEL_LOAD_START_LOADINGSCREEN: - case ESYSTEM_EVENT_LEVEL_UNLOAD: - gEnv->pCryPak->DisableRuntimeFileAccess(false); - case ESYSTEM_EVENT_LEVEL_GAMEPLAY_START: - m_eRuntimeState = event; - break; - } -} - -ESystemGlobalState CSystem::GetSystemGlobalState(void) -{ - return m_systemGlobalState; -} - -const char* CSystem::GetSystemGlobalStateName(const ESystemGlobalState systemGlobalState) -{ - static const char* const s_systemGlobalStateNames[] = { - "UNKNOWN", // ESYSTEM_GLOBAL_STATE_UNKNOWN, - "INIT", // ESYSTEM_GLOBAL_STATE_INIT, - "RUNNING", // ESYSTEM_GLOBAL_STATE_RUNNING, - "LEVEL_LOAD_PREPARE", // ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_PREPARE, - "LEVEL_LOAD_START", // ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START, - "LEVEL_LOAD_MATERIALS", // ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_MATERIALS, - "LEVEL_LOAD_OBJECTS", // ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_OBJECTS, - "LEVEL_LOAD_STATIC_WORLD", // ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_STATIC_WORLD, - "LEVEL_LOAD_PRECACHE", // ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_PRECACHE, - "LEVEL_LOAD_TEXTURES", // ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_TEXTURES, - "LEVEL_LOAD_END", // ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_END, - "LEVEL_LOAD_COMPLETE" // ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_COMPLETE - }; - const size_t numElements = sizeof(s_systemGlobalStateNames) / sizeof(s_systemGlobalStateNames[0]); - const size_t index = (size_t)systemGlobalState; - if (index >= numElements) - { - return "INVALID INDEX"; - } - return s_systemGlobalStateNames[index]; -} - -void CSystem::SetSystemGlobalState(const ESystemGlobalState systemGlobalState) -{ - static CTimeValue s_startTime = CTimeValue(); - if (systemGlobalState != m_systemGlobalState) - { - if (gEnv && gEnv->pTimer) - { - const CTimeValue endTime = gEnv->pTimer->GetAsyncTime(); - const float numSeconds = endTime.GetDifferenceInSeconds(s_startTime); - CryLog("SetGlobalState %d->%d '%s'->'%s' %3.1f seconds", - m_systemGlobalState, systemGlobalState, - CSystem::GetSystemGlobalStateName(m_systemGlobalState), CSystem::GetSystemGlobalStateName(systemGlobalState), - numSeconds); - s_startTime = gEnv->pTimer->GetAsyncTime(); - } - } - m_systemGlobalState = systemGlobalState; - -#if AZ_LOADSCREENCOMPONENT_ENABLED - if (m_systemGlobalState == ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_COMPLETE) - { - EBUS_EVENT(LoadScreenBus, Stop); - } -#endif // if AZ_LOADSCREENCOMPONENT_ENABLED -} - -////////////////////////////////////////////////////////////////////////// -void* CSystem::GetRootWindowMessageHandler() -{ -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_9 - #include AZ_RESTRICTED_FILE(System_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(WIN32) - return reinterpret_cast(&WndProc); -#else - CRY_ASSERT(false && "This platform does not support window message handlers"); - return NULL; -#endif -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::RegisterWindowMessageHandler(IWindowMessageHandler* pHandler) -{ -#if AZ_LEGACY_CRYSYSTEM_TRAIT_USE_MESSAGE_HANDLER - assert(pHandler && !stl::find(m_windowMessageHandlers, pHandler) && "This IWindowMessageHandler is already registered"); - m_windowMessageHandlers.push_back(pHandler); -#else - CRY_ASSERT(false && "This platform does not support window message handlers"); -#endif -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::UnregisterWindowMessageHandler(IWindowMessageHandler* pHandler) -{ -#if AZ_LEGACY_CRYSYSTEM_TRAIT_USE_MESSAGE_HANDLER -#if !defined(NDEBUG) - bool bRemoved = -#endif - stl::find_and_erase(m_windowMessageHandlers, pHandler); - assert(pHandler && bRemoved && "This IWindowMessageHandler was not registered"); -#else - CRY_ASSERT(false && "This platform does not support window message handlers"); -#endif -} - -////////////////////////////////////////////////////////////////////////// -#if defined(WIN32) -bool CSystem::HandleMessage([[maybe_unused]] HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT* pResult) -{ - static bool sbInSizingModalLoop; - int x = LOWORD(lParam); - int y = HIWORD(lParam); - *pResult = 0; - switch (uMsg) - { - // System event translation - case WM_CLOSE: - /* - Trigger CSystem to call Quit() the next time - it calls Update(). HandleMessages can get messages - pumped to it from SyncMainWithRender which would - be called recurively by Quit(). Doing so would - cause the render thread to deadlock and the main - thread to spin in SRenderThread::WaitFlushFinishedCond. - */ - AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::ExitMainLoop); - return false; - case WM_MOVE: - GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_MOVE, x, y); - return false; - case WM_SIZE: - GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_RESIZE, x, y); - switch (wParam) - { - case SIZE_MINIMIZED: - EBUS_EVENT(AzFramework::WindowsLifecycleEvents::Bus, OnMinimized); - break; - case SIZE_MAXIMIZED: - EBUS_EVENT(AzFramework::WindowsLifecycleEvents::Bus, OnMaximized); - break; - case SIZE_RESTORED: - EBUS_EVENT(AzFramework::WindowsLifecycleEvents::Bus, OnRestored); - break; - } - return false; - case WM_WINDOWPOSCHANGED: - GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_POS_CHANGED, 1, 0); - return false; - case WM_STYLECHANGED: - GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_STYLE_CHANGED, 1, 0); - return false; - case WM_ACTIVATE: - // Pass HIWORD(wParam) as well to indicate whether this window is minimized or not - // HIWORD(wParam) != 0 is minimized, HIWORD(wParam) == 0 is not minimized - GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_ACTIVATE, LOWORD(wParam) != WA_INACTIVE, HIWORD(wParam)); - return true; - case WM_SETFOCUS: - EBUS_EVENT(AzFramework::WindowsLifecycleEvents::Bus, OnSetFocus); - GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_CHANGE_FOCUS, 1, 0); - return false; - case WM_KILLFOCUS: - EBUS_EVENT(AzFramework::WindowsLifecycleEvents::Bus, OnKillFocus); - GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_CHANGE_FOCUS, 0, 0); - return false; - case WM_INPUTLANGCHANGE: - GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LANGUAGE_CHANGE, wParam, lParam); - return false; - - case WM_SYSCOMMAND: - if ((wParam & 0xFFF0) == SC_SCREENSAVE) - { - // Check if screen saver is allowed - IConsole* const pConsole = gEnv->pConsole; - const ICVar* const pVar = pConsole ? pConsole->GetCVar("sys_screensaver_allowed") : 0; - return pVar && pVar->GetIVal() == 0; - } - return false; - - // Mouse activation - case WM_MOUSEACTIVATE: - *pResult = MA_ACTIVATEANDEAT; - return true; - - // Hardware mouse counters - case WM_ENTERSIZEMOVE: - sbInSizingModalLoop = true; - // Fall through intended - case WM_ENTERMENULOOP: - { - UiCursorBus::Broadcast(&UiCursorInterface::IncrementVisibleCounter); - return true; - } - case WM_CAPTURECHANGED: - // If WM_CAPTURECHANGED is received after WM_ENTERSIZEMOVE (ie, moving/resizing begins). - // but no matching WM_EXITSIZEMOVE is received (this can happen if the window is not actually moved). - // we still need to decrement the hardware mouse counter that was incremented when WM_ENTERSIZEMOVE was seen. - // So in this case, we effectively treat WM_CAPTURECHANGED as if it was the WM_EXITSIZEMOVE message. - // This behavior has only been reproduced the window is deactivated during the modal loop (ie, breakpoint triggered and focus moves to VS). - case WM_EXITSIZEMOVE: - if (!sbInSizingModalLoop) - { - return false; - } - sbInSizingModalLoop = false; - // Fall through intended - case WM_EXITMENULOOP: - { - UiCursorBus::Broadcast(&UiCursorInterface::DecrementVisibleCounter); - return (uMsg != WM_CAPTURECHANGED); - } - case WM_SYSKEYUP: - case WM_SYSKEYDOWN: - { - const bool bAlt = (lParam & (1 << 29)) != 0; - if (bAlt && wParam == VK_F4) - { - return false; // Pass though ALT+F4 - } - // Prevent game from entering menu loop! Editor does allow menu loop. - return !m_bEditor; - } - case WM_INPUT: - { - UINT rawInputSize; - const UINT rawInputHeaderSize = sizeof(RAWINPUTHEADER); - GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &rawInputSize, rawInputHeaderSize); - - AZStd::array rawInputBytesArray; - LPBYTE rawInputBytes = rawInputBytesArray.data(); - - const UINT bytesCopied = GetRawInputData((HRAWINPUT)lParam, RID_INPUT, rawInputBytes, &rawInputSize, rawInputHeaderSize); - CRY_ASSERT(bytesCopied == rawInputSize); - - RAWINPUT* rawInput = (RAWINPUT*)rawInputBytes; - CRY_ASSERT(rawInput); - - AzFramework::RawInputNotificationBusWindows::Broadcast(&AzFramework::RawInputNotificationsWindows::OnRawInputEvent, *rawInput); - - return false; - } - case WM_DEVICECHANGE: - { - if (wParam == 0x0007) // DBT_DEVNODES_CHANGED - { - AzFramework::RawInputNotificationBusWindows::Broadcast(&AzFramework::RawInputNotificationsWindows::OnRawInputDeviceChangeEvent); - } - return true; - } - case WM_CHAR: - { - const unsigned short codeUnitUTF16 = static_cast(wParam); - AzFramework::RawInputNotificationBusWindows::Broadcast(&AzFramework::RawInputNotificationsWindows::OnRawInputCodeUnitUTF16Event, codeUnitUTF16); - return true; - } - - // Any other event doesn't interest us - default: - return false; - } -} - -#endif - -std::shared_ptr CSystem::CreateLocalFileIO() -{ - return std::make_shared(); -} - -IViewSystem* CSystem::GetIViewSystem() -{ - return m_pViewSystem; -} - -ILevelSystem* CSystem::GetILevelSystem() -{ - return m_pLevelSystem; -} - -#undef EXCLUDE_UPDATE_ON_CONSOLE - diff --git a/Code/CryEngine/CrySystem/System.h b/Code/CryEngine/CrySystem/System.h deleted file mode 100644 index 8c122d0df2..0000000000 --- a/Code/CryEngine/CrySystem/System.h +++ /dev/null @@ -1,748 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once - -#include -#include -#include -#include - -#include "Timer.h" -#include -#include "CmdLine.h" -#include "CryName.h" - -#include -#include "RenderBus.h" - -#include - -#include - -namespace AzFramework -{ - class MissingAssetLogger; -} - -struct IConsoleCmdArgs; -class CWatchdogThread; - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define SYSTEM_H_SECTION_1 1 -#define SYSTEM_H_SECTION_2 2 -#define SYSTEM_H_SECTION_3 3 -#define SYSTEM_H_SECTION_4 4 -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_H_SECTION_1 -#include AZ_RESTRICTED_FILE(System_h) -#else -#if defined(WIN32) || defined(LINUX) || defined(APPLE) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_ALLOW_CREATE_BACKUP_LOG_FILE 1 -#endif -#if defined(WIN32) || (defined(LINUX) && !defined(ANDROID)) || defined(MAC) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_DEFINE_DETECT_PROCESSOR 1 -#endif - -////////////////////////////////////////////////////////////////////////// -#if defined(WIN32) || defined(APPLE) || defined(LINUX) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_DO_PREASSERT 1 -#endif -#if defined(MAC) || (defined(LINUX) && !defined(ANDROID)) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_ASM_VOLATILE_CPUID 1 -#endif -#if (defined(WIN32) && !defined(WIN64)) || (defined(LINUX) && !defined(ANDROID) && !defined(LINUX64)) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_HAS64BITEXT 1 -#endif -#if defined(WIN32) || (defined(LINUX) && !defined(ANDROID)) || defined(MAC) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_HTSUPPORTED 1 -#endif -#if defined(WIN32) || (defined(LINUX) && !defined(ANDROID)) || defined(MAC) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_HASCPUID 1 -#endif -#if defined(WIN32) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_HASAFFINITYMASK 1 -#endif - -#if defined(LINUX) || defined(APPLE) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_CRYPAK_POSIX 1 -#endif - -#if defined(WIN64) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_USE_BIT64 1 -#endif - -#if defined(WIN32) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_USE_PACKED_PEHEADER 1 -#endif -#if defined(WIN32) || defined(LINUX) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_USE_RENDERMEMORY_INFO 1 -#endif - -#if defined(WIN32) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_USE_HANDLER_SYNC_AFFINITY 1 -#endif - -#if defined(LINUX) || defined(APPLE) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_FORWARD_EXCEPTION_POINTERS 1 -#endif - -#if !defined(_WIN32) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_DEBUGCALLSTACK_SINGLETON 1 -#endif -#if !defined(LINUX) && !defined(APPLE) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_DEBUGCALLSTACK_TRANSLATE 1 -#endif -#if !defined(LINUX) && !defined(APPLE) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_DEBUGCALLSTACK_APPEND_MODULENAME 1 -#endif - -#if !(defined(ANDROID) || defined(IOS) || defined(LINUX)) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_IMAGEHANDLER_TIFFIO 1 -#endif - -#if 1 -#define AZ_LEGACY_CRYSYSTEM_TRAIT_JOBMANAGER_SIXWORKERTHREADS 0 -#endif - -#if defined(WIN32) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_MEMADDRESSRANGE_WINDOWS_STYLE 1 -#endif - -#if 1 -#define AZ_LEGACY_CRYSYSTEM_TRAIT_USE_EXCLUDEUPDATE_ON_CONSOLE 0 -#endif -#if defined(WIN32) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_USE_MESSAGE_HANDLER 1 -#endif -#if defined(WIN64) || defined(WIN32) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_CAPTURESTACK 1 -#endif - -#if !defined(LINUX) && !defined(APPLE) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_SYSTEMCFG_MODULENAME 1 -#endif - -#if defined(WIN32) || defined(WIN64) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_THREADINFO_WINDOWS_STYLE 1 -#endif - -#if defined(WIN32) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_THREADTASK_EXCEPTIONS 1 -#endif -////////////////////////////////////////////////////////////////////////// - -#if defined(APPLE) || defined(LINUX) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_FACTORY_REGISTRY_USE_PRINTF_FOR_FATAL 1 -#endif - -#if defined(LINUX) || defined(APPLE) -#define AZ_LEGACY_CRYSYSTEM_TRAIT_USE_FTELL_NOT_FTELLI64 1 -#endif - -#endif - -#if defined(USE_UNIXCONSOLE) || defined(USE_ANDROIDCONSOLE) || defined(USE_WINDOWSCONSOLE) || defined(USE_IOSCONSOLE) || defined(USE_NULLCONSOLE) -#define USE_DEDICATED_SERVER_CONSOLE -#endif - -#if defined(LINUX) - #include "CryLibrary.h" -#endif - -#ifdef WIN32 -typedef void* WIN_HMODULE; -#else -typedef void* WIN_HMODULE; -#endif - -//forward declarations -namespace Audio -{ - struct IAudioSystem; - struct IMusicSystem; -} // namespace Audio -struct IDataProbe; - -#define PHSYICS_OBJECT_ENTITY 0 - -typedef void (__cdecl * VTuneFunction)(void); -extern VTuneFunction VTResume; -extern VTuneFunction VTPause; - -#define MAX_STREAMING_POOL_INDEX 6 -#define MAX_THREAD_POOL_INDEX 6 - -struct SSystemCVars -{ - int sys_streaming_requests_grouping_time_period; - int sys_streaming_sleep; - int sys_streaming_memory_budget; - int sys_streaming_max_finalize_per_frame; - float sys_streaming_max_bandwidth; - int sys_streaming_cpu; - int sys_streaming_cpu_worker; - int sys_streaming_debug; - int sys_streaming_resetstats; - int sys_streaming_debug_filter; - float sys_streaming_debug_filter_min_time; - int sys_streaming_use_optical_drive_thread; - ICVar* sys_streaming_debug_filter_file_name; - ICVar* sys_localization_folder; - int sys_streaming_in_blocks; - - int sys_float_exceptions; - int sys_no_crash_dialog; - int sys_no_error_report_window; - int sys_dump_aux_threads; - int sys_WER; - int sys_dump_type; - int sys_ai; - int sys_entitysystem; - int sys_trackview; - int sys_vtune; - float sys_update_profile_time; - int sys_limit_phys_thread_count; - int sys_MaxFPS; - float sys_maxTimeStepForMovieSystem; - int sys_force_installtohdd_mode; - int sys_report_files_not_found_in_paks = 0; - -#ifdef USE_HTTP_WEBSOCKETS - int sys_simple_http_base_port; -#endif - - int sys_asserts; - int sys_error_debugbreak; - - int sys_FilesystemCaseSensitivity; - - int sys_deferAudioUpdateOptim; - - AZ::IO::ArchiveVars archiveVars; - -#if defined(WIN32) - int sys_display_threads; -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_H_SECTION_2 -#include AZ_RESTRICTED_FILE(System_h) -#endif -}; -extern SSystemCVars g_cvars; - -class CSystem; - -struct CProfilingSystem - : public IProfilingSystem -{ - ////////////////////////////////////////////////////////////////////////// - // VTune Profiling interface. - - // Summary: - // Resumes vtune data collection. - virtual void VTuneResume(); - // Summary: - // Pauses vtune data collection. - virtual void VTunePause(); - ////////////////////////////////////////////////////////////////////////// -}; - -class AssetSystem; - -/* -=========================================== -The System interface Class -=========================================== -*/ -class CXConsole; - -////////////////////////////////////////////////////////////////////// -//! ISystem implementation -class CSystem - : public ISystem - , public ILoadConfigurationEntrySink - , public ISystemEventListener - , public IWindowMessageHandler - , public AZ::RenderNotificationsBus::Handler - , public CrySystemRequestBus::Handler -{ -public: - CSystem(SharedEnvironmentInstance* pSharedEnvironment); - ~CSystem(); - - static void OnLanguageCVarChanged(ICVar* language); - static void OnLanguageAudioCVarChanged(ICVar* language); - static void OnLocalizationFolderCVarChanged(ICVar* const pLocalizationFolder); - // adding CVAR to toggle assert verbosity level - static void OnAssertLevelCvarChanged(ICVar* pArgs); - static void SetAssertLevel(int _assertlevel); - static void OnLogLevelCvarChanged(ICVar* pArgs); - static void SetLogLevel(int _logLevel); - - // interface ILoadConfigurationEntrySink ---------------------------------- - - virtual void OnLoadConfigurationEntry(const char* szKey, const char* szValue, const char* szGroup); - - // ISystemEventListener - virtual void OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam); - - /////////////////////////////////////////////////////////////////////////// - //! @name ISystem implementation - //@{ - virtual bool Init(const SSystemInitParams& startupParams); - virtual void Release(); - - virtual SSystemGlobalEnvironment* GetGlobalEnvironment() { return &m_env; } - - virtual bool UpdatePreTickBus(int updateFlags = 0, int nPauseMode = 0); - virtual bool UpdatePostTickBus(int updateFlags = 0, int nPauseMode = 0); - virtual bool UpdateLoadtime(); - virtual void DoWorkDuringOcclusionChecks(); - virtual bool NeedDoWorkDuringOcclusionChecks() { return m_bNeedDoWorkDuringOcclusionChecks; } - - //////////////////////////////////////////////////////////////////////// - // CrySystemRequestBus interface implementation - ISystem* GetCrySystem() override; - //////////////////////////////////////////////////////////////////////// - - void Relaunch(bool bRelaunch); - bool IsRelaunch() const { return m_bRelaunch; }; - - void SerializingFile(int mode) { m_iLoadingMode = mode; } - int IsSerializingFile() const { return m_iLoadingMode; } - void Quit(); - bool IsQuitting() const; - void ShutdownFileSystem(); // used to cleanup any file resources, such as cache handle. - void SetAffinity(); - virtual const char* GetUserName(); - virtual int GetApplicationInstance(); - int GetApplicationLogInstance(const char* logFilePath) override; - - ITimer* GetITimer(){ return m_env.pTimer; } - AZ::IO::IArchive* GetIPak() { return m_env.pCryPak; }; - IConsole* GetIConsole() { return m_env.pConsole; }; - IRemoteConsole* GetIRemoteConsole(); - IMovieSystem* GetIMovieSystem() { return m_env.pMovieSystem; }; - ICryFont* GetICryFont(){ return m_env.pCryFont; } - ILog* GetILog(){ return m_env.pLog; } - ICmdLine* GetICmdLine(){ return m_pCmdLine; } - INameTable* GetINameTable() { return m_env.pNameTable; }; - IViewSystem* GetIViewSystem(); - ILevelSystem* GetILevelSystem(); - ISystemEventDispatcher* GetISystemEventDispatcher() { return m_pSystemEventDispatcher; } - IProfilingSystem* GetIProfilingSystem() { return &m_ProfilingSystem; } - ////////////////////////////////////////////////////////////////////////// - // retrieves the perlin noise singleton instance - CPNoise3* GetNoiseGen(); - virtual uint64 GetUpdateCounter() { return m_nUpdateCounter; }; - - void DetectGameFolderAccessRights(); - - virtual void ExecuteCommandLine(bool deferred=true); - - virtual void GetUpdateStats(SSystemUpdateStats& stats); - - ////////////////////////////////////////////////////////////////////////// - virtual XmlNodeRef CreateXmlNode(const char* sNodeName = "", bool bReuseStrings = false, bool bIsProcessingInstruction = false); - virtual XmlNodeRef LoadXmlFromFile(const char* sFilename, bool bReuseStrings = false); - virtual XmlNodeRef LoadXmlFromBuffer(const char* buffer, size_t size, bool bReuseStrings = false, bool bSuppressWarnings = false); - virtual IXmlUtils* GetXmlUtils(); - ////////////////////////////////////////////////////////////////////////// - - void SetViewCamera(CCamera& Camera){ m_ViewCamera = Camera; } - CCamera& GetViewCamera() { return m_ViewCamera; } - - void IgnoreUpdates(bool bIgnore) { m_bIgnoreUpdates = bIgnore; }; - - void SetIProcess(IProcess* process); - IProcess* GetIProcess(){ return m_pProcess; } - - bool IsTestMode() const { return m_bTestMode; } - //@} - - void SleepIfNeeded(); - - virtual void FatalError(const char* format, ...) PRINTF_PARAMS(2, 3); - virtual void ReportBug(const char* format, ...) PRINTF_PARAMS(2, 3); - // Validator Warning. - void WarningV(EValidatorModule module, EValidatorSeverity severity, int flags, const char* file, const char* format, va_list args); - void Warning(EValidatorModule module, EValidatorSeverity severity, int flags, const char* file, const char* format, ...); - virtual int ShowMessage(const char* text, const char* caption, unsigned int uType); - bool CheckLogVerbosity(int verbosity); - - //! Return pointer to user defined callback. - ISystemUserCallback* GetUserCallback() const { return m_pUserCallback; }; - - ////////////////////////////////////////////////////////////////////////// - virtual void SaveConfiguration(); - virtual void LoadConfiguration(const char* sFilename, ILoadConfigurationEntrySink* pSink = 0, bool warnIfMissing = true); - virtual ESystemConfigSpec GetMaxConfigSpec() const; - virtual ESystemConfigPlatform GetConfigPlatform() const; - virtual void SetConfigPlatform(ESystemConfigPlatform platform); - ////////////////////////////////////////////////////////////////////////// - - virtual bool IsPaused() const { return m_bPaused; }; - - virtual ILocalizationManager* GetLocalizationManager(); - virtual void debug_GetCallStack(const char** pFunctions, int& nCount); - virtual void debug_LogCallStack(int nMaxFuncs = 32, int nFlags = 0); - // Get the current callstack in raw address form (more lightweight than the above functions) - // static as memReplay needs it before CSystem has been setup - expose a ISystem interface to this function if you need it outside CrySystem - static void debug_GetCallStackRaw(void** callstack, uint32& callstackLength); - -public: -#if !defined(RELEASE) - void SetVersionInfo(const char* const szVersion); -#endif - - void ShutdownModuleLibraries(); - -#if defined(WIN32) - friend LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); -#endif - virtual void* GetRootWindowMessageHandler(); - virtual void RegisterWindowMessageHandler(IWindowMessageHandler* pHandler); - virtual void UnregisterWindowMessageHandler(IWindowMessageHandler* pHandler); - - // IWindowMessageHandler -#if defined(WIN32) - virtual bool HandleMessage(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT* pResult); -#endif - // ~IWindowMessageHandler - -private: - - // Release all resources. - void ShutDown(); - - bool LoadEngineDLLs(); - - //! @name Initialization routines - //@{ - bool InitConsole(); - bool InitFileSystem(); - bool InitFileSystem_LoadEngineFolders(const SSystemInitParams& initParams); - bool InitAudioSystem(const SSystemInitParams& initParams); - - //@} - - ////////////////////////////////////////////////////////////////////////// - // Helper functions. - ////////////////////////////////////////////////////////////////////////// - void CreateSystemVars(); - void CreateAudioVars(); - - AZStd::unique_ptr LoadDLL(const char* dllName); - - void FreeLib(AZStd::unique_ptr& hLibModule); - - bool UnloadDLL(const char* dllName); - void QueryVersionInfo(); - void LogVersion(); - void LogBuildInfo(); - void SetDevMode(bool bEnable); - -#ifndef _RELEASE - static void SystemVersionChanged(ICVar* pCVar); -#endif // #ifndef _RELEASE - - bool ReLaunchMediaCenter(); - void UpdateAudioSystems(); - - void AddCVarGroupDirectory(const string& sPath); - - AZStd::unique_ptr LoadDynamiclibrary(const char* dllName) const; - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_H_SECTION_3 -#include AZ_RESTRICTED_FILE(System_h) -#elif defined(WIN32) - bool GetWinGameFolder(char* szMyDocumentsPath, int maxPathSize); -#endif - -public: - void EnableFloatExceptions(int type); - - // interface ISystem ------------------------------------------- - virtual IDataProbe* GetIDataProbe() { return m_pDataProbe; }; - virtual void SetForceNonDevMode(bool bValue); - virtual bool GetForceNonDevMode() const; - virtual bool WasInDevMode() const { return m_bWasInDevMode; }; - virtual bool IsDevMode() const { return m_bInDevMode && !GetForceNonDevMode(); } - - virtual void SetConsoleDrawEnabled(bool enabled) { m_bDrawConsole = enabled; } - virtual void SetUIDrawEnabled(bool enabled) { m_bDrawUI = enabled; } - - // ------------------------------------------------------------- - - //! attaches the given variable to the given container; - //! recreates the variable if necessary - ICVar* attachVariable (const char* szVarName, int* pContainer, const char* szComment, int dwFlags = 0); - - const CTimeValue& GetLastTickTime(void) const { return m_lastTickTime; } - const ICVar* GetDedicatedMaxRate(void) const { return m_svDedicatedMaxRate; } - - std::shared_ptr CreateLocalFileIO(); - -private: // ------------------------------------------------------ - - // System environment. - SSystemGlobalEnvironment m_env; - - CTimer m_Time; //!< - CCamera m_ViewCamera; //!< - bool m_bInitializedSuccessfully; //!< true if the system completed all initialization steps - 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_bEditor; //!< If running in Editor. - bool m_bNoCrashDialog; - bool m_bNoErrorReportWindow; - bool m_bPreviewMode; //!< If running in Preview mode. - bool m_bDedicatedServer; //!< If running as Dedicated server. - bool m_bIgnoreUpdates; //!< When set to true will ignore Update and Render calls, - bool m_bForceNonDevMode; //!< true when running on a cheat protected server or a client that is connected to it (not used in singlplayer) - bool m_bWasInDevMode; //!< Set to true if was in dev mode. - bool m_bInDevMode; //!< Set to true if was in dev mode. - bool m_bGameFolderWritable;//!< True when verified that current game folder have write access. - int m_ttMemStatSS; //!< Time to memstat screenshot - bool m_bDrawConsole; //!< Set to true if OK to draw the console. - bool m_bDrawUI; //!< Set to true if OK to draw UI. - - - std::map > m_moduleDLLHandles; - - //! current active process - IProcess* m_pProcess; - - CCamera m_PhysRendererCamera; - ICVar* m_p_draw_helpers_str; - int m_iJumpToPhysProfileEnt; - - CTimeValue m_lastTickTime; - - //! system event dispatcher - ISystemEventDispatcher* m_pSystemEventDispatcher; - - //! The default mono-spaced font for internal usage (profiling, debug info, etc.) - IFFont* m_pIFont; - - //! The default font for end-user UI interfaces - IFFont* m_pIFontUi; - - //! System to manage levels. - ILevelSystem* m_pLevelSystem; - - //! System to manage views. - IViewSystem* m_pViewSystem; - - // XML Utils interface. - class CXmlUtils* m_pXMLUtils; - - int m_iApplicationInstance; - - //! to hold the values stored in system.cfg - //! because editor uses it's own values, - //! and then saves them to file, overwriting the user's resolution. - int m_iHeight; - int m_iWidth; - int m_iColorBits; - - // System console variables. - ////////////////////////////////////////////////////////////////////////// - - // DLL names - ICVar* m_sys_dll_response_system; -#if !defined(_RELEASE) - ICVar* m_sys_resource_cache_folder; -#endif - -#if AZ_LOADSCREENCOMPONENT_ENABLED - ICVar* m_game_load_screen_uicanvas_path; - ICVar* m_level_load_screen_uicanvas_path; - ICVar* m_game_load_screen_sequence_to_auto_play; - ICVar* m_level_load_screen_sequence_to_auto_play; - ICVar* m_game_load_screen_sequence_fixed_fps; - ICVar* m_level_load_screen_sequence_fixed_fps; - ICVar* m_game_load_screen_max_fps; - ICVar* m_level_load_screen_max_fps; - ICVar* m_game_load_screen_minimum_time{}; - ICVar* m_level_load_screen_minimum_time{}; -#endif // if AZ_LOADSCREENCOMPONENT_ENABLED - - ICVar* m_sys_initpreloadpacks; - ICVar* m_sys_menupreloadpacks; - - ICVar* m_cvAIUpdate; - ICVar* m_rWidth; - ICVar* m_rHeight; - ICVar* m_rWidthAndHeightAsFractionOfScreenSize; - ICVar* m_rTabletWidthAndHeightAsFractionOfScreenSize; - ICVar* m_rHDRDolby; - ICVar* m_rMaxWidth; - ICVar* m_rMaxHeight; - ICVar* m_rColorBits; - ICVar* m_rDepthBits; - ICVar* m_rStencilBits; - ICVar* m_rFullscreen; - ICVar* m_rFullscreenWindow; - ICVar* m_rFullscreenNativeRes; - ICVar* m_rDisplayInfo; - ICVar* m_rOverscanBordersDrawDebugView; - ICVar* m_sysNoUpdate; - ICVar* m_cvEntitySuppressionLevel; - ICVar* m_pCVarQuit; - ICVar* m_cvMemStats; - ICVar* m_cvMemStatsThreshold; - ICVar* m_cvMemStatsMaxDepth; - ICVar* m_sysKeyboard; - ICVar* m_sysWarnings; //!< might be 0, "sys_warnings" - Treat warning as errors. - ICVar* m_cvSSInfo; //!< might be 0, "sys_SSInfo" 0/1 - get file sourcesafe info - ICVar* m_svDedicatedMaxRate; - ICVar* m_sys_firstlaunch; - ICVar* m_sys_asset_processor; - ICVar* m_sys_load_files_to_memory; - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_H_SECTION_4 -#include AZ_RESTRICTED_FILE(System_h) -#endif - - ICVar* m_sys_audio_disable; - - ICVar* m_sys_min_step; - ICVar* m_sys_max_step; - ICVar* m_sys_enable_budgetmonitoring; - ICVar* m_sys_memory_debug; - ICVar* m_sys_preload; - - // ICVar *m_sys_filecache; - ICVar* m_gpu_particle_physics; - - string m_sSavedRDriver; //!< to restore the driver when quitting the dedicated server - - ////////////////////////////////////////////////////////////////////////// - //! User define callback for system events. - ISystemUserCallback* m_pUserCallback; - - SFileVersion m_fileVersion; - SFileVersion m_productVersion; - SFileVersion m_buildVersion; - IDataProbe* m_pDataProbe; - - class CLocalizedStringsManager* m_pLocalizationManager; - - // Name table. - CNameTable m_nameTable; - - ESystemConfigSpec m_nServerConfigSpec; - ESystemConfigSpec m_nMaxConfigSpec; - ESystemConfigPlatform m_ConfigPlatform; - - CProfilingSystem m_ProfilingSystem; - - // Pause mode. - bool m_bPaused; - bool m_bNoUpdate; - - uint64 m_nUpdateCounter; - - bool m_executedCommandLine = false; - - AZStd::unique_ptr m_missingAssetLogger; - -public: - ICVar* m_sys_main_CPU; - ICVar* m_sys_streaming_CPU; - ICVar* m_sys_TaskThread_CPU[MAX_THREAD_POOL_INDEX]; - - ////////////////////////////////////////////////////////////////////////// - // File version. - ////////////////////////////////////////////////////////////////////////// - virtual const SFileVersion& GetFileVersion(); - virtual const SFileVersion& GetProductVersion(); - virtual const SFileVersion& GetBuildVersion(); - - bool InitVTuneProfiler(); - - void OpenBasicPaks(); - void OpenLanguagePak(const char* sLanguage); - void OpenLanguageAudioPak(const char* sLanguage); - void GetLocalizedPath(const char* sLanguage, string& sLocalizedPath); - void GetLocalizedAudioPath(const char* sLanguage, string& sLocalizedPath); - void CloseLanguagePak(const char* sLanguage); - void CloseLanguageAudioPak(const char* sLanguage); - void UpdateMovieSystem(const int updateFlags, const float fFrameTime, const bool bPreUpdate); - - ////////////////////////////////////////////////////////////////////////// - // CryAssert and error related. - virtual bool RegisterErrorObserver(IErrorObserver* errorObserver); - bool UnregisterErrorObserver(IErrorObserver* errorObserver); - virtual void OnAssert(const char* condition, const char* message, const char* fileName, unsigned int fileLineNumber); - void OnFatalError(const char* message); - - bool IsAssertDialogVisible() const; - void SetAssertVisible(bool bAssertVisble); - ////////////////////////////////////////////////////////////////////////// - - virtual void ClearErrorMessages() - { - m_ErrorMessages.clear(); - } - - bool IsLoading() - { - return m_eRuntimeState == ESYSTEM_EVENT_LEVEL_LOAD_START_LOADINGSCREEN; - } - - virtual ESystemGlobalState GetSystemGlobalState(void); - virtual void SetSystemGlobalState(ESystemGlobalState systemGlobalState); - -#if !defined(_RELEASE) - virtual bool IsSavingResourceList() const { return (g_cvars.archiveVars.nSaveLevelResourceList != 0); } -#endif - -private: - std::vector m_errorObservers; - ESystemGlobalState m_systemGlobalState; - static const char* GetSystemGlobalStateName(const ESystemGlobalState systemGlobalState); - -public: - void InitLocalization(); - -protected: // ------------------------------------------------------------- - - CCmdLine* m_pCmdLine; - - string m_currentLanguageAudio; - string m_systemConfigName; // computed from system_(hardwareplatform)_(assetsPlatform) - eg, system_android_android.cfg or system_windows_pc.cfg - - std::vector< std::pair > m_updateTimes; - - struct SErrorMessage - { - string m_Message; - float m_fTimeToShow; - float m_Color[4]; - bool m_HardFailure; - }; - typedef std::list TErrorMessages; - TErrorMessages m_ErrorMessages; - bool m_bHasRenderedErrorMessage; - bool m_bNeedDoWorkDuringOcclusionChecks; - - ESystemEvent m_eRuntimeState; - bool m_bIsAsserting; - - std::vector m_windowMessageHandlers; - bool m_initedOSAllocator = false; - bool m_initedSysAllocator = false; -}; diff --git a/Code/CryEngine/CrySystem/SystemCFG.cpp b/Code/CryEngine/CrySystem/SystemCFG.cpp deleted file mode 100644 index 0930045b3c..0000000000 --- a/Code/CryEngine/CrySystem/SystemCFG.cpp +++ /dev/null @@ -1,577 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : handles system cfg - - -#include "CrySystem_precompiled.h" -#include "System.h" -#include -#include "XConsole.h" -#include "CryFile.h" -#include "CryPath.h" - -#include -#include -#include -#include - -#include "SystemCFG.h" - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define SYSTEMCFG_CPP_SECTION_1 1 -#define SYSTEMCFG_CPP_SECTION_2 2 -#define SYSTEMCFG_CPP_SECTION_3 3 -#endif - -#if defined(LINUX) || defined(APPLE) -#include "ILog.h" - -#endif - -#ifndef EXE_VERSION_INFO_0 -#define EXE_VERSION_INFO_0 1 -#endif - -#ifndef EXE_VERSION_INFO_1 -#define EXE_VERSION_INFO_1 0 -#endif - -#ifndef EXE_VERSION_INFO_2 -#define EXE_VERSION_INFO_2 0 -#endif - -#ifndef EXE_VERSION_INFO_3 -#define EXE_VERSION_INFO_3 1 -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMCFG_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(SystemCFG_cpp) -#endif - -////////////////////////////////////////////////////////////////////////// -const SFileVersion& CSystem::GetFileVersion() -{ - return m_fileVersion; -} - -////////////////////////////////////////////////////////////////////////// -const SFileVersion& CSystem::GetProductVersion() -{ - return m_productVersion; -} - -////////////////////////////////////////////////////////////////////////// -const SFileVersion& CSystem::GetBuildVersion() -{ - return m_buildVersion; -} - -////////////////////////////////////////////////////////////////////////// -#ifndef _RELEASE -void CSystem::SystemVersionChanged(ICVar* pCVar) -{ - if (CSystem* pThis = static_cast(gEnv->pSystem)) - { - pThis->SetVersionInfo(pCVar->GetString()); - } -} - -void CSystem::SetVersionInfo(const char* const szVersion) -{ - m_fileVersion.Set(szVersion); - m_productVersion.Set(szVersion); - m_buildVersion.Set(szVersion); - CryLog("SetVersionInfo '%s'", szVersion); - CryLog("FileVersion: %d.%d.%d.%d", m_fileVersion.v[3], m_fileVersion.v[2], m_fileVersion.v[1], m_fileVersion.v[0]); - CryLog("ProductVersion: %d.%d.%d.%d", m_productVersion.v[3], m_productVersion.v[2], m_productVersion.v[1], m_productVersion.v[0]); - CryLog("BuildVersion: %d.%d.%d.%d", m_buildVersion.v[3], m_buildVersion.v[2], m_buildVersion.v[1], m_buildVersion.v[0]); -} -#endif // #ifndef _RELEASE - -////////////////////////////////////////////////////////////////////////// -void CSystem::QueryVersionInfo() -{ -#ifndef WIN32 - //do we need some other values here? - m_fileVersion.v[0] = m_productVersion.v[0] = EXE_VERSION_INFO_3; - m_fileVersion.v[1] = m_productVersion.v[1] = EXE_VERSION_INFO_2; - m_fileVersion.v[2] = m_productVersion.v[2] = EXE_VERSION_INFO_1; - m_fileVersion.v[3] = m_productVersion.v[3] = EXE_VERSION_INFO_0; - m_buildVersion = m_fileVersion; -#else //WIN32 - char moduleName[_MAX_PATH]; - DWORD dwHandle; - UINT len; - - char ver[1024 * 8]; - - GetModuleFileName(NULL, moduleName, _MAX_PATH); //retrieves the PATH for the current module - -#ifdef AZ_MONOLITHIC_BUILD - GetModuleFileName(NULL, moduleName, _MAX_PATH); //retrieves the PATH for the current module -#else // AZ_MONOLITHIC_BUILD - azstrcpy(moduleName, AZ_ARRAY_SIZE(moduleName), "CrySystem.dll"); // we want to version from the system dll -#endif // AZ_MONOLITHIC_BUILD - - int verSize = GetFileVersionInfoSize(moduleName, &dwHandle); - if (verSize > 0) - { - GetFileVersionInfo(moduleName, dwHandle, 1024 * 8, ver); - VS_FIXEDFILEINFO* vinfo; - VerQueryValue(ver, "\\", (void**)&vinfo, &len); - - const uint32 verIndices[4] = {0, 1, 2, 3}; - m_fileVersion.v[verIndices[0]] = m_productVersion.v[verIndices[0]] = vinfo->dwFileVersionLS & 0xFFFF; - m_fileVersion.v[verIndices[1]] = m_productVersion.v[verIndices[1]] = vinfo->dwFileVersionLS >> 16; - m_fileVersion.v[verIndices[2]] = m_productVersion.v[verIndices[2]] = vinfo->dwFileVersionMS & 0xFFFF; - m_fileVersion.v[verIndices[3]] = m_productVersion.v[verIndices[3]] = vinfo->dwFileVersionMS >> 16; - m_buildVersion = m_fileVersion; - - struct LANGANDCODEPAGE - { - WORD wLanguage; - WORD wCodePage; - }* lpTranslate; - - UINT count = 0; - char path[256]; - char* version = NULL; - - VerQueryValue(ver, "\\VarFileInfo\\Translation", (LPVOID*)&lpTranslate, &count); - if (lpTranslate != NULL) - { - azsnprintf(path, sizeof(path), "\\StringFileInfo\\%04x%04x\\InternalName", lpTranslate[0].wLanguage, lpTranslate[0].wCodePage); - VerQueryValue(ver, path, (LPVOID*)&version, &count); - if (version) - { - m_buildVersion.Set(version); - } - } - } -#endif //WIN32 -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::LogVersion() -{ - // Get time. - time_t ltime; - time(<ime); - -#ifdef AZ_COMPILER_MSVC - tm today; - localtime_s(&today, <ime); - char s[1024]; - strftime(s, 128, "%d %b %y (%H %M %S)", &today); -#else - char s[1024]; - auto today = localtime(<ime); - strftime(s, 128, "%d %b %y (%H %M %S)", today); -#endif - - const SFileVersion& ver = GetFileVersion(); - - CryLogAlways("BackupNameAttachment=\" Build(%d) %s\" -- used by backup system\n", ver.v[0], s); // read by CreateBackupFile() - - // Use strftime to build a customized time string. -#ifdef AZ_COMPILER_MSVC - strftime(s, 128, "Log Started at %c", &today); -#else - strftime(s, 128, "Log Started at %c", today); -#endif - CryLogAlways(s); - - CryLogAlways("Built on " __DATE__ " " __TIME__); - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMCFG_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(SystemCFG_cpp) -#elif defined(ANDROID) - CryLogAlways("Running 32 bit Android version API VER:%d", __ANDROID_API__); -#elif defined(IOS) - CryLogAlways("Running 64 bit iOS version"); -#elif defined(WIN64) - CryLogAlways("Running 64 bit Windows version"); -#elif defined(WIN32) - CryLogAlways("Running 32 bit Windows version"); -#elif defined(LINUX64) - CryLogAlways("Running 64 bit Linux version"); -#elif defined(LINUX32) - CryLogAlways("Running 32 bit Linux version"); -#elif defined(MAC) - CryLogAlways("Running 64 bit Mac version"); -#endif -#if AZ_LEGACY_CRYSYSTEM_TRAIT_SYSTEMCFG_MODULENAME - GetModuleFileName(NULL, s, sizeof(s)); - - // Log EXE filename only if possible (not full EXE path which could contain sensitive info) - AZStd::string exeName; - if (AzFramework::StringFunc::Path::GetFullFileName(s, exeName)) { - CryLogAlways("Executable: %s", exeName.c_str()); - } -#endif - - CryLogAlways("FileVersion: %d.%d.%d.%d", m_fileVersion.v[3], m_fileVersion.v[2], m_fileVersion.v[1], m_fileVersion.v[0]); -#if defined(LY_BUILD) - CryLogAlways("ProductVersion: %d.%d.%d.%d - Build %d", m_productVersion.v[3], m_productVersion.v[2], m_productVersion.v[1], m_productVersion.v[0], LY_BUILD); -#else // defined(LY_BUILD) - CryLogAlways("ProductVersion: %d.%d.%d.%d", m_productVersion.v[3], m_productVersion.v[2], m_productVersion.v[1], m_productVersion.v[0]); -#endif // defined(LY_BUILD) - - - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMCFG_CPP_SECTION_3 -#include AZ_RESTRICTED_FILE(SystemCFG_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(_MSC_VER) - CryLogAlways("Using Microsoft (tm) C++ Standard Library implementation\n"); -#elif defined(__clang__) - CryLogAlways("Using CLANG C++ Standard Library implementation\n"); -#elif defined(__GNUC__) - CryLogAlways("Using GNU C++ Standard Library implementation\n"); -#else -#error "Please specify C++ STL library" -#endif -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::LogBuildInfo() -{ - auto projectName = AZ::Utils::GetProjectName(); - CryLogAlways("GameName: %s", projectName.c_str()); - CryLogAlways("BuildTime: " __DATE__ " " __TIME__); -} - - - -////////////////////////////////////////////////////////////////////////// - - -////////////////////////////////////////////////////////////////////////// -class CCVarSaveDump - : public ICVarDumpSink -{ -public: - - CCVarSaveDump(FILE* pFile) - { - m_pFile = pFile; - } - - virtual void OnElementFound(ICVar* pCVar) - { - if (!pCVar) - { - return; - } - int nFlags = pCVar->GetFlags(); - if (((nFlags & VF_DUMPTODISK) && (nFlags & VF_MODIFIED)) || (nFlags & VF_WASINCONFIG)) - { - string szValue = pCVar->GetString(); - int pos; - - pos = 1; - for (;; ) - { - pos = szValue.find_first_of("\\", pos); - - if (pos == string::npos) - { - break; - } - - szValue.replace(pos, 1, "\\\\", 2); - pos += 2; - } - - // replace " with \" - pos = 1; - for (;; ) - { - pos = szValue.find_first_of("\"", pos); - - if (pos == string::npos) - { - break; - } - - szValue.replace(pos, 1, "\\\"", 2); - pos += 2; - } - - string szLine = pCVar->GetName(); - - if (pCVar->GetType() == CVAR_STRING) - { - szLine += " = \"" + szValue + "\"\r\n"; - } - else - { - szLine += " = " + szValue + "\r\n"; - } - - if (pCVar->GetFlags() & VF_WARNING_NOTUSED) - { - fputs("-- REMARK: the following was not assigned to a console variable\r\n", m_pFile); - } - - fputs(szLine.c_str(), m_pFile); - } - } - -private: // -------------------------------------------------------- - - FILE* m_pFile; // -}; - -////////////////////////////////////////////////////////////////////////// -void CSystem::SaveConfiguration() -{ -} - -////////////////////////////////////////////////////////////////////////// -// system cfg -////////////////////////////////////////////////////////////////////////// -CSystemConfiguration::CSystemConfiguration(const string& strSysConfigFilePath, CSystem* pSystem, ILoadConfigurationEntrySink* pSink, bool warnIfMissing) - : m_strSysConfigFilePath(strSysConfigFilePath) - , m_bError(false) - , m_pSink(pSink) - , m_warnIfMissing(warnIfMissing) -{ - assert(pSink); - - m_pSystem = pSystem; - m_bError = !ParseSystemConfig(); -} - -////////////////////////////////////////////////////////////////////////// -CSystemConfiguration::~CSystemConfiguration() -{ -} - -////////////////////////////////////////////////////////////////////////// -bool CSystemConfiguration::ParseSystemConfig() -{ - string filename = m_strSysConfigFilePath; - if (strlen(PathUtil::GetExt(filename)) == 0) - { - filename = PathUtil::ReplaceExtension(filename, "cfg"); - } - - CCryFile file; - string filenameLog; - { - int flags = AZ::IO::IArchive::FOPEN_HINT_QUIET | AZ::IO::IArchive::FOPEN_ONDISK; - - if (filename[0] == '@') - { - // this is used when theres a very specific file to read, like @user@/game.cfg which is read - // IN ADDITION to the one in the game folder, and afterwards to override values in it. - // if the file is missing and its already prefixed with an alias, there is no need to look any further. - if (!(file.Open(filename, "rb", flags))) - { - if (m_warnIfMissing) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "Config file %s not found!", filename.c_str()); - } - return false; - } - } - else - { - // otherwise, if the file isn't prefixed with an alias, then its likely one of the convenience mappings - // to either root or assets/config. this is done so that code can just request a simple file name and get its data - if ( - !(file.Open(filename, "rb", flags)) && - !(file.Open(string("@root@/") + filename, "rb", flags)) && - !(file.Open(string("@assets@/") + filename, "rb", flags)) && - !(file.Open(string("@assets@/config/") + filename, "rb", flags)) && - !(file.Open(string("@assets@/config/spec/") + filename, "rb", flags)) - ) - { - if (m_warnIfMissing) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "Config file %s not found!", filename.c_str()); - } - return false; - } - } - - filenameLog = file.GetAdjustedFilename(); - } - - INDENT_LOG_DURING_SCOPE(); - - int nLen = file.GetLength(); - if (nLen == 0) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "Couldn't get length for Config file %s", filename.c_str()); - return false; - } - char* sAllText = new char [nLen + 16]; - if (file.ReadRaw(sAllText, nLen) < (size_t)nLen) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "Couldn't read Config file %s", filename.c_str()); - return false; - } - sAllText[nLen] = '\0'; - sAllText[nLen + 1] = '\0'; - - string strGroup; // current group e.g. "[General]" - - char* strLast = sAllText + nLen; - char* str = sAllText; - while (str < strLast) - { - char* s = str; - while (str < strLast && *str != '\n' && *str != '\r') - { - str++; - } - *str = '\0'; - str++; - while (str < strLast && (*str == '\n' || *str == '\r')) - { - str++; - } - - string strLine = s; - - // detect groups e.g. "[General]" should set strGroup="General" - { - string strTrimmedLine(RemoveWhiteSpaces(strLine)); - size_t size = strTrimmedLine.size(); - - if (size >= 3) - { - if (strTrimmedLine[0] == '[' && strTrimmedLine[size - 1] == ']') // currently no comments are allowed to be behind groups - { - strGroup = &strTrimmedLine[1]; - strGroup.resize(size - 2); // remove [ and ] - continue; // next line - } - } - } - - //trim all whitespace characters at the beginning and the end of the current line and store its size - strLine.Trim(); - size_t strLineSize = strLine.size(); - - //skip comments, comments start with ";" or "--" but may have preceding whitespace characters - if (strLineSize > 0) - { - if (strLine[0] == ';') - { - continue; - } - else if (strLine.find("--") == 0) - { - continue; - } - } - //skip empty lines - else - { - continue; - } - - //if line contains a '=' try to read and assign console variable - string::size_type posEq(strLine.find("=", 0)); - if (string::npos != posEq) - { - string stemp(strLine, 0, posEq); - string strKey(RemoveWhiteSpaces(stemp)); - - { - // extract value - string::size_type posValueStart(strLine.find("\"", posEq + 1) + 1); - string::size_type posValueEnd(strLine.rfind('\"')); - - string strValue; - - if (string::npos != posValueStart && string::npos != posValueEnd) - { - strValue = string(strLine, posValueStart, posValueEnd - posValueStart); - } - else - { - string strTmp(strLine, posEq + 1, strLine.size() - (posEq + 1)); - strValue = RemoveWhiteSpaces(strTmp); - } - - { - // replace '\\\\' with '\\' and '\\\"' with '\"' - strValue.replace("\\\\", "\\"); - strValue.replace("\\\"", "\""); - - m_pSink->OnLoadConfigurationEntry(strKey, strValue, strGroup); - } - } - } - else - { - gEnv->pLog->LogWithType(ILog::eWarning, "%s -> invalid configuration line: %s", filename.c_str(), strLine.c_str()); - } - } - - delete []sAllText; - - CryLog("Loading Config file %s (%s)", filename.c_str(), filenameLog.c_str()); - - m_pSink->OnLoadConfigurationEntry_End(); - - return true; -} - - -////////////////////////////////////////////////////////////////////////// -void CSystem::OnLoadConfigurationEntry(const char* szKey, const char* szValue, [[maybe_unused]] const char* szGroup) -{ - bool azConsoleProcessed = false; - auto console = AZ::Interface::Get(); - if (console) - { - AZStd::string command(AZStd::string::format("%s %s", szKey, szValue)); - - azConsoleProcessed = console->PerformCommand(command.c_str()); - } - - if (!azConsoleProcessed) - { - if (!gEnv->pConsole) - { - return; - } - - if (*szKey != 0) - { - gEnv->pConsole->LoadConfigVar(szKey, szValue); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::LoadConfiguration(const char* sFilename, ILoadConfigurationEntrySink* pSink, bool warnIfMissing) -{ - if (sFilename && strlen(sFilename) > 0) - { - if (!pSink) - { - pSink = this; - } - - CSystemConfiguration tempConfig(sFilename, this, pSink, warnIfMissing); - } -} - diff --git a/Code/CryEngine/CrySystem/SystemCFG.h b/Code/CryEngine/CrySystem/SystemCFG.h deleted file mode 100644 index 4e8479d72f..0000000000 --- a/Code/CryEngine/CrySystem/SystemCFG.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYSYSTEM_SYSTEMCFG_H -#define CRYINCLUDE_CRYSYSTEM_SYSTEMCFG_H - -#pragma once - -#include -#include - -typedef string SysConfigKey; -typedef string SysConfigValue; - -////////////////////////////////////////////////////////////////////////// -class CSystemConfiguration -{ -public: - CSystemConfiguration(const string& strSysConfigFilePath, CSystem* pSystem, ILoadConfigurationEntrySink* pSink, bool warnIfMissing = true); - ~CSystemConfiguration(); - - string RemoveWhiteSpaces(string& s) - { - s.Trim(); - return s; - } - - bool IsError() const { return m_bError; } - -private: // ---------------------------------------- - - // Returns: - // success - bool ParseSystemConfig(); - - CSystem* m_pSystem; - string m_strSysConfigFilePath; - bool m_bError; - ILoadConfigurationEntrySink* m_pSink; // never 0 - bool m_warnIfMissing; -}; - - -#endif // CRYINCLUDE_CRYSYSTEM_SYSTEMCFG_H diff --git a/Code/CryEngine/CrySystem/SystemEventDispatcher.cpp b/Code/CryEngine/CrySystem/SystemEventDispatcher.cpp deleted file mode 100644 index c07bf8fb5d..0000000000 --- a/Code/CryEngine/CrySystem/SystemEventDispatcher.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "CrySystem_precompiled.h" -#include "SystemEventDispatcher.h" - -CSystemEventDispatcher::CSystemEventDispatcher() - : m_listeners(0) -{ -} - -bool CSystemEventDispatcher::RegisterListener(ISystemEventListener* pListener) -{ - m_listenerRegistrationLock.Lock(); - bool ret = m_listeners.Add(pListener); - m_listenerRegistrationLock.Unlock(); - return ret; -} - -bool CSystemEventDispatcher::RemoveListener(ISystemEventListener* pListener) -{ - m_listenerRegistrationLock.Lock(); - m_listeners.Remove(pListener); - m_listenerRegistrationLock.Unlock(); - return true; -} - - -////////////////////////////////////////////////////////////////////////// -void CSystemEventDispatcher::OnSystemEventAnyThread(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam) -{ - m_listenerRegistrationLock.Lock(); - for (TSystemEventListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) - { - notifier->OnSystemEventAnyThread(event, wparam, lparam); - } - m_listenerRegistrationLock.Unlock(); -} - - -////////////////////////////////////////////////////////////////////////// -void CSystemEventDispatcher::OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam) -{ - if (gEnv && gEnv->mMainThreadId == CryGetCurrentThreadId()) - { - for (TSystemEventListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) - { - notifier->OnSystemEvent(event, wparam, lparam); - } - } - else - { - SEventParams params; - params.event = event; - params.wparam = wparam; - params.lparam = lparam; - m_systemEventQueue.push(params); - } - - // Also dispatch the event on this thread. This technically means the event - // will be sent twice (thru different OnSystemEventXX functions), therefore it is up to listeners which one they react to. - OnSystemEventAnyThread(event, wparam, lparam); -} - -////////////////////////////////////////////////////////////////////////// -void CSystemEventDispatcher::Update() -{ - AZ_TRACE_METHOD(); - assert(gEnv && gEnv->mMainThreadId == CryGetCurrentThreadId()); - - SEventParams params; - while (m_systemEventQueue.try_pop(params)) - { - OnSystemEvent(params.event, params.wparam, params.lparam); - } -} - - - - diff --git a/Code/CryEngine/CrySystem/SystemEventDispatcher.h b/Code/CryEngine/CrySystem/SystemEventDispatcher.h deleted file mode 100644 index d07fea3a88..0000000000 --- a/Code/CryEngine/CrySystem/SystemEventDispatcher.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYSYSTEM_SYSTEMEVENTDISPATCHER_H -#define CRYINCLUDE_CRYSYSTEM_SYSTEMEVENTDISPATCHER_H -#pragma once - - -#include -#include - -class CSystemEventDispatcher - : public ISystemEventDispatcher -{ -public: - CSystemEventDispatcher(); - virtual ~CSystemEventDispatcher(){} - - // ISystemEventDispatcher - virtual bool RegisterListener(ISystemEventListener* pListener); - virtual bool RemoveListener(ISystemEventListener* pListener); - - virtual void OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam); - virtual void Update(); - - // ~ISystemEventDispatcher -private: - void OnSystemEventAnyThread(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam); - - typedef CListenerSet TSystemEventListeners; - TSystemEventListeners m_listeners; - - // for the events coming from other threads - struct SEventParams - { - ESystemEvent event; - UINT_PTR wparam; - UINT_PTR lparam; - }; - - typedef CryMT::queue TSystemEventQueue; - TSystemEventQueue m_systemEventQueue; - CryCriticalSection m_listenerRegistrationLock; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_SYSTEMEVENTDISPATCHER_H diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp deleted file mode 100644 index 4b07de6933..0000000000 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ /dev/null @@ -1,2218 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "CrySystem_precompiled.h" -#include "System.h" - -#if defined(AZ_RESTRICTED_PLATFORM) || defined(AZ_TOOLS_EXPAND_FOR_RESTRICTED_PLATFORMS) -#undef AZ_RESTRICTED_SECTION -#define SYSTEMINIT_CPP_SECTION_1 1 -#define SYSTEMINIT_CPP_SECTION_2 2 -#define SYSTEMINIT_CPP_SECTION_3 3 -#define SYSTEMINIT_CPP_SECTION_4 4 -#define SYSTEMINIT_CPP_SECTION_5 5 -#define SYSTEMINIT_CPP_SECTION_6 6 -#define SYSTEMINIT_CPP_SECTION_7 7 -#define SYSTEMINIT_CPP_SECTION_8 8 -#define SYSTEMINIT_CPP_SECTION_9 9 -#define SYSTEMINIT_CPP_SECTION_10 10 -#define SYSTEMINIT_CPP_SECTION_11 11 -#define SYSTEMINIT_CPP_SECTION_12 12 -#define SYSTEMINIT_CPP_SECTION_13 13 -#define SYSTEMINIT_CPP_SECTION_14 14 -#define SYSTEMINIT_CPP_SECTION_15 15 -#define SYSTEMINIT_CPP_SECTION_16 16 -#define SYSTEMINIT_CPP_SECTION_17 17 -#endif - -#include "CryLibrary.h" -#include "CryPath.h" -#include - -#include -#include - -#include // for AZ_MAX_PATH_LEN -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "AZCoreLogSink.h" -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#if defined(APPLE) || defined(LINUX) -#include -#include -#endif - -#ifdef WIN32 -#define WIN32_LEAN_AND_MEAN -#include "windows.h" -#include - -// To enable profiling with vtune (https://software.intel.com/en-us/intel-vtune-amplifier-xe), make sure the line below is not commented out -//#define PROFILE_WITH_VTUNE - -#endif //WIN32 - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include "XConsole.h" -#include "Log.h" -#include "XML/xml.h" -#include "LocalizedStringManager.h" -#include "SystemEventDispatcher.h" -#include "LevelSystem/LevelSystem.h" -#include "LevelSystem/SpawnableLevelSystem.h" -#include "ViewSystem/ViewSystem.h" -#include -#include -#include -#include - -#if defined(ANDROID) - #include -#endif - -#if defined(EXTERNAL_CRASH_REPORTING) -#include -#endif - -// select the asset processor based on cvars and defines. -// uncomment the following and edit the path where it is instantiated if you'd like to use the test file client -//#define USE_TEST_FILE_CLIENT - -#if defined(REMOTE_ASSET_PROCESSOR) -// Over here, we'd put the header to the Remote Asset Processor interface (as opposed to the Local built in version below) -# include -#endif - -#ifdef WIN32 -extern LONG WINAPI CryEngineExceptionFilterWER(struct _EXCEPTION_POINTERS* pExceptionPointers); -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_14 -#include AZ_RESTRICTED_FILE(SystemInit_cpp) -#endif - -#if AZ_TRAIT_USE_CRY_SIGNAL_HANDLER - -#include -#include -void CryEngineSignalHandler(int signal) -{ - char resolvedPath[_MAX_PATH]; - - // it is assumed that @log@ points at the appropriate place (so for apple, to the user profile dir) - if (AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath("@log@/crash.log", resolvedPath, _MAX_PATH)) - { - fprintf(stderr, "Crash Signal Handler - logged to %s\n", resolvedPath); - FILE* file = fopen(resolvedPath, "a"); - if (file) - { - char sTime[128]; - time_t ltime; - time(<ime); - struct tm* today = localtime(<ime); - strftime(sTime, 40, "<%Y-%m-%d %H:%M:%S> ", today); - fprintf(file, "%s: Error: signal %s:\n", sTime, strsignal(signal)); - fflush(file); - void* array[100]; - int s = backtrace(array, 100); - backtrace_symbols_fd(array, s, fileno(file)); - fclose(file); - CryLogAlways("Successfully recorded crash file: '%s'", resolvedPath); - abort(); - } - } - - CryLogAlways("Could not record crash file..."); - abort(); -} - -#endif // AZ_TRAIT_USE_CRY_SIGNAL_HANDLER - -////////////////////////////////////////////////////////////////////////// -#define DEFAULT_LOG_FILENAME "@log@/Log.txt" - -#define CRYENGINE_ENGINE_FOLDER "Engine" - -////////////////////////////////////////////////////////////////////////// -#define CRYENGINE_DEFAULT_LOCALIZATION_LANG "en-US" - -#define LOCALIZATION_TRANSLATIONS_LIST_FILE_NAME "Libs/Localization/localization.xml" - -////////////////////////////////////////////////////////////////////////// -#if defined(WIN32) || defined(LINUX) || defined(APPLE) -# define DLL_MODULE_INIT_ISYSTEM "ModuleInitISystem" -# define DLL_MODULE_SHUTDOWN_ISYSTEM "ModuleShutdownISystem" -# define DLL_INITFUNC_RENDERER "PackageRenderConstructor" -# define DLL_INITFUNC_SOUND "CreateSoundSystem" -# define DLL_INITFUNC_FONT "CreateCryFontInterface" -# define DLL_INITFUNC_3DENGINE "CreateCry3DEngine" -# define DLL_INITFUNC_UI "CreateLyShineInterface" -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(SystemInit_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -# define DLL_MODULE_INIT_ISYSTEM (LPCSTR)2 -# define DLL_MODULE_SHUTDOWN_ISYSTEM (LPCSTR)3 -# define DLL_INITFUNC_RENDERER (LPCSTR)1 -# define DLL_INITFUNC_RENDERER (LPCSTR)1 -# define DLL_INITFUNC_SOUND (LPCSTR)1 -# define DLL_INITFUNC_PHYSIC (LPCSTR)1 -# define DLL_INITFUNC_FONT (LPCSTR)1 -# define DLL_INITFUNC_3DENGINE (LPCSTR)1 -# define DLL_INITFUNC_UI (LPCSTR)1 -#endif - -#define AZ_TRACE_SYSTEM_WINDOW AZ::Debug::Trace::GetDefaultSystemWindow() - -#ifdef WIN32 -extern HMODULE gDLLHandle; -#endif - -namespace -{ -#if defined(AZ_PLATFORM_WINDOWS) - // on windows, we lock our cache using a lockfile. On other platforms this is not necessary since devices like ios, android, consoles cannot - // run more than one game process that uses the same folder anyway. - HANDLE g_cacheLock = INVALID_HANDLE_VALUE; -#endif -} - -//static int g_sysSpecChanged = false; - -struct SCVarsClientConfigSink - : public ILoadConfigurationEntrySink -{ - virtual void OnLoadConfigurationEntry(const char* szKey, const char* szValue, [[maybe_unused]] const char* szGroup) - { - gEnv->pConsole->SetClientDataProbeString(szKey, szValue); - } -}; - -////////////////////////////////////////////////////////////////////////// -static inline void InlineInitializationProcessing([[maybe_unused]] const char* sDescription) -{ - if (gEnv->pLog) - { - gEnv->pLog->UpdateLoadingScreen(0); - } -} - -////////////////////////////////////////////////////////////////////////// -AZ_PUSH_DISABLE_WARNING(4723, "-Wunknown-warning-option") // potential divide by 0 (needs to wrap the function) -static void CmdCrashTest(IConsoleCmdArgs* pArgs) -{ - assert(pArgs); - - if (pArgs->GetArgCount() == 2) - { - //This method intentionally crashes, a lot. - - int crashType = atoi(pArgs->GetArg(1)); - switch (crashType) - { - case 1: - { - int* p = 0; - PREFAST_SUPPRESS_WARNING(6011) * p = 0xABCD; - } - break; - case 2: - { - float a = 1.0f; - memset(&a, 0, sizeof(a)); - float* b = &a; - float c = 3; - CryLog("%f", (c / *b)); - } - break; - case 3: - while (true) - { - new char[10240]; - } - break; - case 4: - CryFatalError("sys_crashtest 4"); - break; - case 5: - while (true) - { - new char[128]; //testing the crash handler an exception in the cry memory allocation occurred - } - case 6: - { - AZ_Assert(false, "Testing assert for testing crashes"); - } - break; - case 7: - __debugbreak(); - break; - case 8: - CrySleep(1000 * 60 * 10); - break; - } - } -} -AZ_POP_DISABLE_WARNING - -////////////////////////////////////////////////////////////////////////// -struct SysSpecOverrideSink - : public ILoadConfigurationEntrySink -{ - virtual void OnLoadConfigurationEntry(const char* szKey, const char* szValue, const char* szGroup) - { - ICVar* pCvar = gEnv->pConsole->GetCVar(szKey); - - if (pCvar) - { - const bool wasNotInConfig = ((pCvar->GetFlags() & VF_WASINCONFIG) == 0); - bool applyCvar = wasNotInConfig; - if (applyCvar == false) - { - // Special handling for sys_spec_full - if (azstricmp(szKey, "sys_spec_full") == 0) - { - // If it is set to 0 then ignore this request to set to something else - // If it is set to 0 then the user wants to changes system spec settings in system.cfg - if (pCvar->GetIVal() != 0) - { - applyCvar = true; - } - } - else - { - // 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; - - if ((isConst || isCheat || isReadOnly) || isDeprecated) - { - allowApplyCvar = !isDeprecated && (gEnv->pSystem->IsDevMode()) || (gEnv->IsEditor()); - } - - if ((allowApplyCvar) || ALLOW_CONST_CVAR_MODIFICATIONS) - { - applyCvar = true; - } - } - } - - if (applyCvar) - { - pCvar->Set(szValue); - } - else - { - CryLogAlways("NOT VF_WASINCONFIG Ignoring cvar '%s' new value '%s' old value '%s' group '%s'", szKey, szValue, pCvar->GetString(), szGroup); - } - } - else - { - CryLogAlways("Can't find cvar '%s' value '%s' group '%s'", szKey, szValue, szGroup); - } - } -}; - -#if !defined(CONSOLE) -struct SysSpecOverrideSinkConsole - : public ILoadConfigurationEntrySink -{ - virtual void OnLoadConfigurationEntry(const char* szKey, const char* szValue, const char* szGroup) - { - // Ignore platform-specific cvars that should just be executed on the console - if (azstricmp(szGroup, "Platform") == 0) - { - return; - } - - ICVar* pCvar = gEnv->pConsole->GetCVar(szKey); - if (pCvar) - { - pCvar->Set(szValue); - } - else - { - // If the cvar doesn't exist, calling this function only saves the value in case it's registered later where - // at that point it will be set from the stored value. This is required because otherwise registering the - // cvar bypasses any callbacks and uses values directly from the cvar group files. - gEnv->pConsole->LoadConfigVar(szKey, szValue); - } - } -}; -#endif - -static ESystemConfigPlatform GetDevicePlatform() -{ -#if defined(AZ_PLATFORM_WINDOWS) || defined(AZ_PLATFORM_LINUX) - return CONFIG_PC; -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(SystemInit_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_PLATFORM_ANDROID) - return CONFIG_ANDROID; -#elif defined(AZ_PLATFORM_IOS) - return CONFIG_IOS; -#elif defined(AZ_PLATFORM_MAC) - return CONFIG_OSX_METAL; -#else - AZ_Assert(false, "Platform not supported"); - return CONFIG_INVALID_PLATFORM; -#endif -} - -////////////////////////////////////////////////////////////////////////// -#if !defined(AZ_MONOLITHIC_BUILD) - -AZStd::unique_ptr CSystem::LoadDynamiclibrary(const char* dllName) const -{ - AZStd::unique_ptr handle = AZ::DynamicModuleHandle::Create(dllName); - - bool libraryLoaded = handle->Load(false); - // We need to inject the environment first thing so that allocators are available immediately - InjectEnvironmentFunction injectEnv = handle->GetFunction(INJECT_ENVIRONMENT_FUNCTION); - if (injectEnv) - { - auto env = AZ::Environment::GetInstance(); - injectEnv(env); - } - - if (!libraryLoaded) - { - handle.release(); - } - return handle; -} - -////////////////////////////////////////////////////////////////////////// -AZStd::unique_ptr CSystem::LoadDLL(const char* dllName) -{ - LOADING_TIME_PROFILE_SECTION(GetISystem()); - - AZ_TracePrintf(AZ_TRACE_SYSTEM_WINDOW, "Loading DLL: %s", dllName); - - AZStd::unique_ptr handle = LoadDynamiclibrary(dllName); - - if (!handle) - { -#if defined(LINUX) || defined(APPLE) - AZ_Assert(false, "Error loading dylib: %s, error : %s\n", dllName, dlerror()); -#else - AZ_Assert(false, "Error loading dll: %s, error code %d", dllName, GetLastError()); -#endif - return handle; - } - - ////////////////////////////////////////////////////////////////////////// - // After loading DLL initialize it by calling ModuleInitISystem - ////////////////////////////////////////////////////////////////////////// - string moduleName = PathUtil::GetFileName(dllName); - - typedef void*(*PtrFunc_ModuleInitISystem)(ISystem* pSystem, const char* moduleName); - PtrFunc_ModuleInitISystem pfnModuleInitISystem = handle->GetFunction(DLL_MODULE_INIT_ISYSTEM); - if (pfnModuleInitISystem) - { - pfnModuleInitISystem(this, moduleName.c_str()); - } - - return handle; -} - -// TODO:DLL #endif //#if defined(AZ_HAS_DLL_SUPPORT) && !defined(AZ_MONOLITHIC_BUILD) -#endif //if !defined(AZ_MONOLITHIC_BUILD) -////////////////////////////////////////////////////////////////////////// -bool CSystem::LoadEngineDLLs() -{ - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CSystem::UnloadDLL(const char* dllName) -{ - bool isSuccess = false; - - CCryNameCRC key(dllName); - AZStd::unique_ptr empty; - AZStd::unique_ptr& hModule = stl::find_in_map_ref(m_moduleDLLHandles, key, empty); - if ((hModule) && (hModule->IsLoaded())) - { - DetachEnvironmentFunction detachEnv = hModule->GetFunction(DETACH_ENVIRONMENT_FUNCTION); - if (detachEnv) - { - detachEnv(); - } - - isSuccess = hModule->Unload(); - hModule.release(); - } - - return isSuccess; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::ShutdownModuleLibraries() -{ -#if !defined(AZ_MONOLITHIC_BUILD) - for (auto iterator = m_moduleDLLHandles.begin(); iterator != m_moduleDLLHandles.end(); ++iterator) - { - typedef void*( * PtrFunc_ModuleShutdownISystem )(ISystem* pSystem); - - PtrFunc_ModuleShutdownISystem pfnModuleShutdownISystem = iterator->second->GetFunction(DLL_MODULE_SHUTDOWN_ISYSTEM); - if (pfnModuleShutdownISystem) - { - pfnModuleShutdownISystem(this); - } - if (iterator->second->IsLoaded()) - { - iterator->second->Unload(); - } - iterator->second.release(); - } - - m_moduleDLLHandles.clear(); - -#endif // !defined(AZ_MONOLITHIC_BUILD) -} - -///////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////// - -#if defined(WIN32) || defined(WIN64) -wstring GetErrorStringUnsupportedGPU(const char* gpuName, unsigned int gpuVendorId, unsigned int gpuDeviceId) -{ - const size_t fullLangID = (size_t) GetKeyboardLayout(0); - const size_t primLangID = fullLangID & 0x3FF; - - const wchar_t* pFmt = L"Unsupported video card detected! Continuing to run might lead to unexpected results or crashes. " - L"Please check the manual for further information on hardware requirements.\n\n\"%S\" [vendor id = 0x%.4x, device id = 0x%.4x]"; - - switch (primLangID) - { - case 0x04: // Chinese - { - static const wchar_t fmt[] = {0x5075, 0x6E2C, 0x5230, 0x4E0D, 0x652F, 0x63F4, 0x7684, 0x986F, 0x793A, 0x5361, 0xFF01, 0x7E7C, 0x7E8C, 0x57F7, 0x884C, 0x53EF, 0x80FD, 0x5C0E, 0x81F4, 0x7121, 0x6CD5, 0x9810, 0x671F, 0x7684, 0x7D50, 0x679C, 0x6216, 0x7576, 0x6A5F, 0x3002, 0x8ACB, 0x6AA2, 0x67E5, 0x8AAA, 0x660E, 0x66F8, 0x4E0A, 0x7684, 0x786C, 0x9AD4, 0x9700, 0x6C42, 0x4EE5, 0x53D6, 0x5F97, 0x66F4, 0x591A, 0x76F8, 0x95DC, 0x8CC7, 0x8A0A, 0x3002, 0x000A, 0x000A, 0x0022, 0x0025, 0x0053, 0x0022, 0x0020, 0x005B, 0x5EE0, 0x5546, 0x7DE8, 0x865F, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x002C, 0x0020, 0x88DD, 0x7F6E, 0x7DE8, 0x865F, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x005D, 0}; - pFmt = fmt; - break; - } - case 0x05: // Czech - { - static const wchar_t fmt[] = {0x0042, 0x0079, 0x006C, 0x0061, 0x0020, 0x0064, 0x0065, 0x0074, 0x0065, 0x006B, 0x006F, 0x0076, 0x00E1, 0x006E, 0x0061, 0x0020, 0x0067, 0x0072, 0x0061, 0x0066, 0x0069, 0x0063, 0x006B, 0x00E1, 0x0020, 0x006B, 0x0061, 0x0072, 0x0074, 0x0061, 0x002C, 0x0020, 0x006B, 0x0074, 0x0065, 0x0072, 0x00E1, 0x0020, 0x006E, 0x0065, 0x006E, 0x00ED, 0x0020, 0x0070, 0x006F, 0x0064, 0x0070, 0x006F, 0x0072, 0x006F, 0x0076, 0x00E1, 0x006E, 0x0061, 0x002E, 0x0020, 0x0050, 0x006F, 0x006B, 0x0072, 0x0061, 0x010D, 0x006F, 0x0076, 0x00E1, 0x006E, 0x00ED, 0x0020, 0x006D, 0x016F, 0x017E, 0x0065, 0x0020, 0x0076, 0x00E9, 0x0073, 0x0074, 0x0020, 0x006B, 0x0065, 0x0020, 0x006B, 0x0072, 0x0069, 0x0074, 0x0069, 0x0063, 0x006B, 0x00FD, 0x006D, 0x0020, 0x0063, 0x0068, 0x0079, 0x0062, 0x00E1, 0x006D, 0x0020, 0x006E, 0x0065, 0x0062, 0x006F, 0x0020, 0x006E, 0x0065, 0x0073, 0x0074, 0x0061, 0x0062, 0x0069, 0x006C, 0x0069, 0x0074, 0x011B, 0x0020, 0x0073, 0x0079, 0x0073, 0x0074, 0x00E9, 0x006D, 0x0075, 0x002E, 0x0020, 0x0050, 0x0159, 0x0065, 0x010D, 0x0074, 0x011B, 0x0074, 0x0065, 0x0020, 0x0073, 0x0069, 0x0020, 0x0070, 0x0072, 0x006F, 0x0073, 0x00ED, 0x006D, 0x0020, 0x0075, 0x017E, 0x0069, 0x0076, 0x0061, 0x0074, 0x0065, 0x006C, 0x0073, 0x006B, 0x006F, 0x0075, 0x0020, 0x0070, 0x0159, 0x00ED, 0x0072, 0x0075, 0x010D, 0x006B, 0x0075, 0x0020, 0x0070, 0x0072, 0x006F, 0x0020, 0x0070, 0x006F, 0x0064, 0x0072, 0x006F, 0x0062, 0x006E, 0x00E9, 0x0020, 0x0069, 0x006E, 0x0066, 0x006F, 0x0072, 0x006D, 0x0061, 0x0063, 0x0065, 0x0020, 0x006F, 0x0020, 0x0073, 0x0079, 0x0073, 0x0074, 0x00E9, 0x006D, 0x006F, 0x0076, 0x00FD, 0x0063, 0x0068, 0x0020, 0x0070, 0x006F, 0x017E, 0x0061, 0x0064, 0x0061, 0x0076, 0x0063, 0x00ED, 0x0063, 0x0068, 0x002E, 0x000A, 0x000A, 0x0022, 0x0025, 0x0053, 0x0022, 0x0020, 0x005B, 0x0076, 0x0065, 0x006E, 0x0064, 0x006F, 0x0072, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x002C, 0x0020, 0x0064, 0x0065, 0x0076, 0x0069, 0x0063, 0x0065, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x005D, 0}; - pFmt = fmt; - break; - } - case 0x07: // German - { - static const wchar_t fmt[] = {0x004E, 0x0069, 0x0063, 0x0068, 0x0074, 0x002D, 0x0075, 0x006E, 0x0074, 0x0065, 0x0072, 0x0073, 0x0074, 0x00FC, 0x0074, 0x007A, 0x0074, 0x0065, 0x0020, 0x0056, 0x0069, 0x0064, 0x0065, 0x006F, 0x006B, 0x0061, 0x0072, 0x0074, 0x0065, 0x0020, 0x0067, 0x0065, 0x0066, 0x0075, 0x006E, 0x0064, 0x0065, 0x006E, 0x0021, 0x0020, 0x0046, 0x006F, 0x0072, 0x0074, 0x0066, 0x0061, 0x0068, 0x0072, 0x0065, 0x006E, 0x0020, 0x006B, 0x0061, 0x006E, 0x006E, 0x0020, 0x007A, 0x0075, 0x0020, 0x0075, 0x006E, 0x0065, 0x0072, 0x0077, 0x0061, 0x0072, 0x0074, 0x0065, 0x0074, 0x0065, 0x006E, 0x0020, 0x0045, 0x0072, 0x0067, 0x0065, 0x0062, 0x006E, 0x0069, 0x0073, 0x0073, 0x0065, 0x006E, 0x0020, 0x006F, 0x0064, 0x0065, 0x0072, 0x0020, 0x0041, 0x0062, 0x0073, 0x0074, 0x00FC, 0x0072, 0x007A, 0x0065, 0x006E, 0x0020, 0x0066, 0x00FC, 0x0068, 0x0072, 0x0065, 0x006E, 0x002E, 0x0020, 0x0042, 0x0069, 0x0074, 0x0074, 0x0065, 0x0020, 0x006C, 0x0069, 0x0065, 0x0073, 0x0020, 0x0064, 0x0061, 0x0073, 0x0020, 0x004D, 0x0061, 0x006E, 0x0075, 0x0061, 0x006C, 0x0020, 0x0066, 0x00FC, 0x0072, 0x0020, 0x0077, 0x0065, 0x0069, 0x0074, 0x0065, 0x0072, 0x0065, 0x0020, 0x0049, 0x006E, 0x0066, 0x006F, 0x0072, 0x006D, 0x0061, 0x0074, 0x0069, 0x006F, 0x006E, 0x0065, 0x006E, 0x0020, 0x007A, 0x0075, 0x0020, 0x0048, 0x0061, 0x0072, 0x0064, 0x0077, 0x0061, 0x0072, 0x0065, 0x002D, 0x0041, 0x006E, 0x0066, 0x006F, 0x0072, 0x0064, 0x0065, 0x0072, 0x0075, 0x006E, 0x0067, 0x0065, 0x006E, 0x002E, 0x000A, 0x000A, 0x0022, 0x0025, 0x0053, 0x0022, 0x0020, 0x005B, 0x0076, 0x0065, 0x006E, 0x0064, 0x006F, 0x0072, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x002C, 0x0020, 0x0064, 0x0065, 0x0076, 0x0069, 0x0063, 0x0065, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x005D, 0}; - pFmt = fmt; - break; - } - case 0x0a: // Spanish - { - static const wchar_t fmt[] = {0x0053, 0x0065, 0x0020, 0x0068, 0x0061, 0x0020, 0x0064, 0x0065, 0x0074, 0x0065, 0x0063, 0x0074, 0x0061, 0x0064, 0x006F, 0x0020, 0x0075, 0x006E, 0x0061, 0x0020, 0x0074, 0x0061, 0x0072, 0x006A, 0x0065, 0x0074, 0x0061, 0x0020, 0x0067, 0x0072, 0x00E1, 0x0066, 0x0069, 0x0063, 0x0061, 0x0020, 0x006E, 0x006F, 0x0020, 0x0063, 0x006F, 0x006D, 0x0070, 0x0061, 0x0074, 0x0069, 0x0062, 0x006C, 0x0065, 0x002E, 0x0020, 0x0053, 0x0069, 0x0020, 0x0073, 0x0069, 0x0067, 0x0075, 0x0065, 0x0073, 0x0020, 0x0065, 0x006A, 0x0065, 0x0063, 0x0075, 0x0074, 0x0061, 0x006E, 0x0064, 0x006F, 0x0020, 0x0065, 0x006C, 0x0020, 0x006A, 0x0075, 0x0065, 0x0067, 0x006F, 0x002C, 0x0020, 0x0065, 0x0073, 0x0020, 0x0070, 0x006F, 0x0073, 0x0069, 0x0062, 0x006C, 0x0065, 0x0020, 0x0071, 0x0075, 0x0065, 0x0020, 0x0073, 0x0065, 0x0020, 0x0070, 0x0072, 0x006F, 0x0064, 0x0075, 0x007A, 0x0063, 0x0061, 0x006E, 0x0020, 0x0065, 0x0066, 0x0065, 0x0063, 0x0074, 0x006F, 0x0073, 0x0020, 0x0069, 0x006E, 0x0065, 0x0073, 0x0070, 0x0065, 0x0072, 0x0061, 0x0064, 0x006F, 0x0073, 0x0020, 0x006F, 0x0020, 0x0071, 0x0075, 0x0065, 0x0020, 0x0065, 0x006C, 0x0020, 0x0070, 0x0072, 0x006F, 0x0067, 0x0072, 0x0061, 0x006D, 0x0061, 0x0020, 0x0064, 0x0065, 0x006A, 0x0065, 0x0020, 0x0064, 0x0065, 0x0020, 0x0066, 0x0075, 0x006E, 0x0063, 0x0069, 0x006F, 0x006E, 0x0061, 0x0072, 0x002E, 0x0020, 0x0050, 0x006F, 0x0072, 0x0020, 0x0066, 0x0061, 0x0076, 0x006F, 0x0072, 0x002C, 0x0020, 0x0063, 0x006F, 0x006D, 0x0070, 0x0072, 0x0075, 0x0065, 0x0062, 0x0061, 0x0020, 0x0065, 0x006C, 0x0020, 0x006D, 0x0061, 0x006E, 0x0075, 0x0061, 0x006C, 0x0020, 0x0070, 0x0061, 0x0072, 0x0061, 0x0020, 0x006F, 0x0062, 0x0074, 0x0065, 0x006E, 0x0065, 0x0072, 0x0020, 0x006D, 0x00E1, 0x0073, 0x0020, 0x0069, 0x006E, 0x0066, 0x006F, 0x0072, 0x006D, 0x0061, 0x0063, 0x0069, 0x00F3, 0x006E, 0x0020, 0x0061, 0x0063, 0x0065, 0x0072, 0x0063, 0x0061, 0x0020, 0x0064, 0x0065, 0x0020, 0x006C, 0x006F, 0x0073, 0x0020, 0x0072, 0x0065, 0x0071, 0x0075, 0x0069, 0x0073, 0x0069, 0x0074, 0x006F, 0x0073, 0x0020, 0x0064, 0x0065, 0x006C, 0x0020, 0x0073, 0x0069, 0x0073, 0x0074, 0x0065, 0x006D, 0x0061, 0x002E, 0x000A, 0x000A, 0x0022, 0x0025, 0x0053, 0x0022, 0x0020, 0x005B, 0x0076, 0x0065, 0x006E, 0x0064, 0x006F, 0x0072, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x002C, 0x0020, 0x0064, 0x0065, 0x0076, 0x0069, 0x0063, 0x0065, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x005D, 0}; - pFmt = fmt; - break; - } - case 0x0c: // French - { - static const wchar_t fmt[] = {0x0041, 0x0074, 0x0074, 0x0065, 0x006E, 0x0074, 0x0069, 0x006F, 0x006E, 0x002C, 0x0020, 0x006C, 0x0061, 0x0020, 0x0063, 0x0061, 0x0072, 0x0074, 0x0065, 0x0020, 0x0076, 0x0069, 0x0064, 0x00E9, 0x006F, 0x0020, 0x0064, 0x00E9, 0x0074, 0x0065, 0x0063, 0x0074, 0x00E9, 0x0065, 0x0020, 0x006E, 0x2019, 0x0065, 0x0073, 0x0074, 0x0020, 0x0070, 0x0061, 0x0073, 0x0020, 0x0073, 0x0075, 0x0070, 0x0070, 0x006F, 0x0072, 0x0074, 0x00E9, 0x0065, 0x0020, 0x0021, 0x0020, 0x0050, 0x006F, 0x0075, 0x0072, 0x0073, 0x0075, 0x0069, 0x0076, 0x0072, 0x0065, 0x0020, 0x006C, 0x2019, 0x0061, 0x0070, 0x0070, 0x006C, 0x0069, 0x0063, 0x0061, 0x0074, 0x0069, 0x006F, 0x006E, 0x0020, 0x0070, 0x006F, 0x0075, 0x0072, 0x0072, 0x0061, 0x0069, 0x0074, 0x0020, 0x0065, 0x006E, 0x0067, 0x0065, 0x006E, 0x0064, 0x0072, 0x0065, 0x0072, 0x0020, 0x0064, 0x0065, 0x0073, 0x0020, 0x0069, 0x006E, 0x0073, 0x0074, 0x0061, 0x0062, 0x0069, 0x006C, 0x0069, 0x0074, 0x00E9, 0x0073, 0x0020, 0x006F, 0x0075, 0x0020, 0x0064, 0x0065, 0x0073, 0x0020, 0x0063, 0x0072, 0x0061, 0x0073, 0x0068, 0x0073, 0x002E, 0x0020, 0x0056, 0x0065, 0x0075, 0x0069, 0x006C, 0x006C, 0x0065, 0x007A, 0x0020, 0x0076, 0x006F, 0x0075, 0x0073, 0x0020, 0x0072, 0x0065, 0x0070, 0x006F, 0x0072, 0x0074, 0x0065, 0x0072, 0x0020, 0x0061, 0x0075, 0x0020, 0x006D, 0x0061, 0x006E, 0x0075, 0x0065, 0x006C, 0x0020, 0x0070, 0x006F, 0x0075, 0x0072, 0x0020, 0x0070, 0x006C, 0x0075, 0x0073, 0x0020, 0x0064, 0x2019, 0x0069, 0x006E, 0x0066, 0x006F, 0x0072, 0x006D, 0x0061, 0x0074, 0x0069, 0x006F, 0x006E, 0x0073, 0x0020, 0x0073, 0x0075, 0x0072, 0x0020, 0x006C, 0x0065, 0x0073, 0x0020, 0x0070, 0x0072, 0x00E9, 0x002D, 0x0072, 0x0065, 0x0071, 0x0075, 0x0069, 0x0073, 0x0020, 0x006D, 0x0061, 0x0074, 0x00E9, 0x0072, 0x0069, 0x0065, 0x006C, 0x002E, 0x000A, 0x000A, 0x0022, 0x0025, 0x0053, 0x0022, 0x0020, 0x005B, 0x0076, 0x0065, 0x006E, 0x0064, 0x006F, 0x0072, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x002C, 0x0020, 0x0064, 0x0065, 0x0076, 0x0069, 0x0063, 0x0065, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x005D, 0}; - pFmt = fmt; - break; - } - case 0x10: // Italian - { - static const wchar_t fmt[] = {0x00C8, 0x0020, 0x0073, 0x0074, 0x0061, 0x0074, 0x0061, 0x0020, 0x0072, 0x0069, 0x006C, 0x0065, 0x0076, 0x0061, 0x0074, 0x0061, 0x0020, 0x0075, 0x006E, 0x0061, 0x0020, 0x0073, 0x0063, 0x0068, 0x0065, 0x0064, 0x0061, 0x0020, 0x0067, 0x0072, 0x0061, 0x0066, 0x0069, 0x0063, 0x0061, 0x0020, 0x006E, 0x006F, 0x006E, 0x0020, 0x0073, 0x0075, 0x0070, 0x0070, 0x006F, 0x0072, 0x0074, 0x0061, 0x0074, 0x0061, 0x0021, 0x0020, 0x0053, 0x0065, 0x0020, 0x0073, 0x0069, 0x0020, 0x0063, 0x006F, 0x006E, 0x0074, 0x0069, 0x006E, 0x0075, 0x0061, 0x002C, 0x0020, 0x0073, 0x0069, 0x0020, 0x0070, 0x006F, 0x0074, 0x0072, 0x0065, 0x0062, 0x0062, 0x0065, 0x0072, 0x006F, 0x0020, 0x0076, 0x0065, 0x0072, 0x0069, 0x0066, 0x0069, 0x0063, 0x0061, 0x0072, 0x0065, 0x0020, 0x0072, 0x0069, 0x0073, 0x0075, 0x006C, 0x0074, 0x0061, 0x0074, 0x0069, 0x0020, 0x0069, 0x006E, 0x0061, 0x0074, 0x0074, 0x0065, 0x0073, 0x0069, 0x0020, 0x006F, 0x0020, 0x0063, 0x0072, 0x0061, 0x0073, 0x0068, 0x002E, 0x0020, 0x0043, 0x006F, 0x006E, 0x0073, 0x0075, 0x006C, 0x0074, 0x0061, 0x0020, 0x0069, 0x006C, 0x0020, 0x006D, 0x0061, 0x006E, 0x0075, 0x0061, 0x006C, 0x0065, 0x0020, 0x0070, 0x0065, 0x0072, 0x0020, 0x0075, 0x006C, 0x0074, 0x0065, 0x0072, 0x0069, 0x006F, 0x0072, 0x0069, 0x0020, 0x0069, 0x006E, 0x0066, 0x006F, 0x0072, 0x006D, 0x0061, 0x007A, 0x0069, 0x006F, 0x006E, 0x0069, 0x0020, 0x0073, 0x0075, 0x0069, 0x0020, 0x0072, 0x0065, 0x0071, 0x0075, 0x0069, 0x0073, 0x0069, 0x0074, 0x0069, 0x0020, 0x0064, 0x0069, 0x0020, 0x0073, 0x0069, 0x0073, 0x0074, 0x0065, 0x006D, 0x0061, 0x002E, 0x000A, 0x000A, 0x0022, 0x0025, 0x0053, 0x0022, 0x0020, 0x005B, 0x0076, 0x0065, 0x006E, 0x0064, 0x006F, 0x0072, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x002C, 0x0020, 0x0064, 0x0065, 0x0076, 0x0069, 0x0063, 0x0065, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x005D, 0}; - pFmt = fmt; - break; - } - case 0x11: // Japanese - { - static const wchar_t fmt[] = {0x30B5, 0x30DD, 0x30FC, 0x30C8, 0x3055, 0x308C, 0x3066, 0x3044, 0x306A, 0x3044, 0x30D3, 0x30C7, 0x30AA, 0x30AB, 0x30FC, 0x30C9, 0x304C, 0x691C, 0x51FA, 0x3055, 0x308C, 0x307E, 0x3057, 0x305F, 0xFF01, 0x0020, 0x3053, 0x306E, 0x307E, 0x307E, 0x7D9A, 0x3051, 0x308B, 0x3068, 0x4E88, 0x671F, 0x3057, 0x306A, 0x3044, 0x7D50, 0x679C, 0x3084, 0x30AF, 0x30E9, 0x30C3, 0x30B7, 0x30E5, 0x306E, 0x6050, 0x308C, 0x304C, 0x3042, 0x308A, 0x307E, 0x3059, 0x3002, 0x0020, 0x30DE, 0x30CB, 0x30E5, 0x30A2, 0x30EB, 0x306E, 0x5FC5, 0x8981, 0x52D5, 0x4F5C, 0x74B0, 0x5883, 0x3092, 0x3054, 0x78BA, 0x8A8D, 0x304F, 0x3060, 0x3055, 0x3044, 0x3002, 0x000A, 0x000A, 0x0022, 0x0025, 0x0053, 0x0022, 0x0020, 0x005B, 0x30D9, 0x30F3, 0x30C0, 0x30FC, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x002C, 0x0020, 0x30C7, 0x30D0, 0x30A4, 0x30B9, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x005D, 0}; - pFmt = fmt; - break; - } - case 0x15: // Polish - { - static const wchar_t fmt[] = {0x0057, 0x0079, 0x006B, 0x0072, 0x0079, 0x0074, 0x006F, 0x0020, 0x006E, 0x0069, 0x0065, 0x006F, 0x0062, 0x0073, 0x0142, 0x0075, 0x0067, 0x0069, 0x0077, 0x0061, 0x006E, 0x0105, 0x0020, 0x006B, 0x0061, 0x0072, 0x0074, 0x0119, 0x0020, 0x0067, 0x0072, 0x0061, 0x0066, 0x0069, 0x0063, 0x007A, 0x006E, 0x0105, 0x0021, 0x0020, 0x0044, 0x0061, 0x006C, 0x0073, 0x007A, 0x0065, 0x0020, 0x006B, 0x006F, 0x0072, 0x007A, 0x0079, 0x0073, 0x0074, 0x0061, 0x006E, 0x0069, 0x0065, 0x0020, 0x007A, 0x0020, 0x0070, 0x0072, 0x006F, 0x0064, 0x0075, 0x006B, 0x0074, 0x0075, 0x0020, 0x006D, 0x006F, 0x017C, 0x0065, 0x0020, 0x0073, 0x0070, 0x006F, 0x0077, 0x006F, 0x0064, 0x006F, 0x0077, 0x0061, 0x0107, 0x0020, 0x006E, 0x0069, 0x0065, 0x0070, 0x006F, 0x017C, 0x0105, 0x0064, 0x0061, 0x006E, 0x0065, 0x0020, 0x007A, 0x0061, 0x0063, 0x0068, 0x006F, 0x0077, 0x0061, 0x006E, 0x0069, 0x0065, 0x0020, 0x006C, 0x0075, 0x0062, 0x0020, 0x0077, 0x0073, 0x0074, 0x0072, 0x007A, 0x0079, 0x006D, 0x0061, 0x006E, 0x0069, 0x0065, 0x0020, 0x0070, 0x0072, 0x006F, 0x0067, 0x0072, 0x0061, 0x006D, 0x0075, 0x002E, 0x0020, 0x0041, 0x0062, 0x0079, 0x0020, 0x0075, 0x007A, 0x0079, 0x0073, 0x006B, 0x0061, 0x0107, 0x0020, 0x0077, 0x0069, 0x0119, 0x0063, 0x0065, 0x006A, 0x0020, 0x0069, 0x006E, 0x0066, 0x006F, 0x0072, 0x006D, 0x0061, 0x0063, 0x006A, 0x0069, 0x002C, 0x0020, 0x0073, 0x006B, 0x006F, 0x006E, 0x0073, 0x0075, 0x006C, 0x0074, 0x0075, 0x006A, 0x0020, 0x0073, 0x0069, 0x0119, 0x0020, 0x007A, 0x0020, 0x0069, 0x006E, 0x0073, 0x0074, 0x0072, 0x0075, 0x006B, 0x0063, 0x006A, 0x0105, 0x0020, 0x006F, 0x0062, 0x0073, 0x0142, 0x0075, 0x0067, 0x0069, 0x002E, 0x000A, 0x000A, 0x0022, 0x0025, 0x0053, 0x0022, 0x0020, 0x005B, 0x0076, 0x0065, 0x006E, 0x0064, 0x006F, 0x0072, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x002C, 0x0020, 0x0064, 0x0065, 0x0076, 0x0069, 0x0063, 0x0065, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x005D, 0}; - pFmt = fmt; - break; - } - case 0x19: // Russian - { - static const wchar_t fmt[] = {0x0412, 0x0430, 0x0448, 0x0430, 0x0020, 0x0432, 0x0438, 0x0434, 0x0435, 0x043E, 0x0020, 0x043A, 0x0430, 0x0440, 0x0442, 0x0430, 0x0020, 0x043D, 0x0435, 0x0020, 0x043F, 0x043E, 0x0434, 0x0434, 0x0435, 0x0440, 0x0436, 0x0438, 0x0432, 0x0430, 0x0435, 0x0442, 0x0441, 0x044F, 0x0021, 0x0020, 0x042D, 0x0442, 0x043E, 0x0020, 0x043C, 0x043E, 0x0436, 0x0435, 0x0442, 0x0020, 0x043F, 0x0440, 0x0438, 0x0432, 0x0435, 0x0441, 0x0442, 0x0438, 0x0020, 0x043A, 0x0020, 0x043D, 0x0435, 0x043F, 0x0440, 0x0435, 0x0434, 0x0441, 0x043A, 0x0430, 0x0437, 0x0443, 0x0435, 0x043C, 0x043E, 0x043C, 0x0443, 0x0020, 0x043F, 0x043E, 0x0432, 0x0435, 0x0434, 0x0435, 0x043D, 0x0438, 0x044E, 0x0020, 0x0438, 0x0020, 0x0437, 0x0430, 0x0432, 0x0438, 0x0441, 0x0430, 0x043D, 0x0438, 0x044E, 0x0020, 0x0438, 0x0433, 0x0440, 0x044B, 0x002E, 0x0020, 0x0414, 0x043B, 0x044F, 0x0020, 0x043F, 0x043E, 0x043B, 0x0443, 0x0447, 0x0435, 0x043D, 0x0438, 0x044F, 0x0020, 0x0438, 0x043D, 0x0444, 0x043E, 0x0440, 0x043C, 0x0430, 0x0446, 0x0438, 0x0438, 0x0020, 0x043E, 0x0020, 0x0441, 0x0438, 0x0441, 0x0442, 0x0435, 0x043C, 0x043D, 0x044B, 0x0445, 0x0020, 0x0442, 0x0440, 0x0435, 0x0431, 0x043E, 0x0432, 0x0430, 0x043D, 0x0438, 0x044F, 0x0445, 0x0020, 0x043E, 0x0431, 0x0440, 0x0430, 0x0442, 0x0438, 0x0442, 0x0435, 0x0441, 0x044C, 0x0020, 0x043A, 0x0020, 0x0440, 0x0443, 0x043A, 0x043E, 0x0432, 0x043E, 0x0434, 0x0441, 0x0442, 0x0432, 0x0443, 0x0020, 0x043F, 0x043E, 0x043B, 0x044C, 0x0437, 0x043E, 0x0432, 0x0430, 0x0442, 0x0435, 0x043B, 0x044F, 0x002E, 0x000A, 0x000A, 0x0022, 0x0025, 0x0053, 0x0022, 0x0020, 0x005B, 0x0076, 0x0065, 0x006E, 0x0064, 0x006F, 0x0072, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x002C, 0x0020, 0x0064, 0x0065, 0x0076, 0x0069, 0x0063, 0x0065, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x005D, 0}; - pFmt = fmt; - break; - } - case 0x1f: // Turkish - { - static const wchar_t fmt[] = {0x0044, 0x0065, 0x0073, 0x0074, 0x0065, 0x006B, 0x006C, 0x0065, 0x006E, 0x006D, 0x0065, 0x0079, 0x0065, 0x006E, 0x0020, 0x0062, 0x0069, 0x0072, 0x0020, 0x0065, 0x006B, 0x0072, 0x0061, 0x006E, 0x0020, 0x006B, 0x0061, 0x0072, 0x0074, 0x0131, 0x0020, 0x0061, 0x006C, 0x0067, 0x0131, 0x006C, 0x0061, 0x006E, 0x0064, 0x0131, 0x0021, 0x0020, 0x0044, 0x0065, 0x0076, 0x0061, 0x006D, 0x0020, 0x0065, 0x0074, 0x006D, 0x0065, 0x006B, 0x0020, 0x0062, 0x0065, 0x006B, 0x006C, 0x0065, 0x006E, 0x006D, 0x0065, 0x0064, 0x0069, 0x006B, 0x0020, 0x0073, 0x006F, 0x006E, 0x0075, 0x00E7, 0x006C, 0x0061, 0x0072, 0x0061, 0x0020, 0x0076, 0x0065, 0x0020, 0x00E7, 0x00F6, 0x006B, 0x006D, 0x0065, 0x006C, 0x0065, 0x0072, 0x0065, 0x0020, 0x0079, 0x006F, 0x006C, 0x0020, 0x0061, 0x00E7, 0x0061, 0x0062, 0x0069, 0x006C, 0x0069, 0x0072, 0x002E, 0x0020, 0x0044, 0x006F, 0x006E, 0x0061, 0x006E, 0x0131, 0x006D, 0x0020, 0x0067, 0x0065, 0x0072, 0x0065, 0x006B, 0x006C, 0x0069, 0x006C, 0x0069, 0x006B, 0x006C, 0x0065, 0x0072, 0x0069, 0x0020, 0x0069, 0x00E7, 0x0069, 0x006E, 0x0020, 0x006C, 0x00FC, 0x0074, 0x0066, 0x0065, 0x006E, 0x0020, 0x0072, 0x0065, 0x0068, 0x0062, 0x0065, 0x0072, 0x0069, 0x006E, 0x0069, 0x007A, 0x0065, 0x0020, 0x0062, 0x0061, 0x015F, 0x0076, 0x0075, 0x0072, 0x0075, 0x006E, 0x002E, 0x000A, 0x000A, 0x0022, 0x0025, 0x0053, 0x0022, 0x0020, 0x005B, 0x0076, 0x0065, 0x006E, 0x0064, 0x006F, 0x0072, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x002C, 0x0020, 0x0064, 0x0065, 0x0076, 0x0069, 0x0063, 0x0065, 0x0020, 0x0069, 0x0064, 0x0020, 0x003D, 0x0020, 0x0030, 0x0078, 0x0025, 0x002E, 0x0034, 0x0078, 0x005D, 0}; - pFmt = fmt; - break; - } - - case 0x09: // English - default: - break; - } - - wchar_t msg[1024]; - msg[0] = L'\0'; - msg[sizeof(msg) / sizeof(msg[0]) - 1] = L'\0'; - azsnwprintf(msg, sizeof(msg) / sizeof(msg[0]) - 1, pFmt, gpuName, gpuVendorId, gpuDeviceId); - - return msg; -} -#endif - -///////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////// -bool CSystem::InitConsole() -{ - LOADING_TIME_PROFILE_SECTION(GetISystem()); - - if (m_env.pConsole) - { - m_env.pConsole->Init(this); - } - return true; -} - -////////////////////////////////////////////////////////////////////////// -// attaches the given variable to the given container; -// recreates the variable if necessary -ICVar* CSystem::attachVariable (const char* szVarName, int* pContainer, const char* szComment, int dwFlags) -{ - IConsole* pConsole = GetIConsole(); - - ICVar* pOldVar = pConsole->GetCVar (szVarName); - int nDefault = 0; - if (pOldVar) - { - nDefault = pOldVar->GetIVal(); - pConsole->UnregisterVariable(szVarName, true); - } - - // NOTE: maybe we should preserve the actual value of the variable across the registration, - // because of the strange architecture of IConsole that converts int->float->int - - REGISTER_CVAR2(szVarName, pContainer, *pContainer, dwFlags, szComment); - - ICVar* pVar = pConsole->GetCVar(szVarName); - -#ifdef _DEBUG - // test if the variable really has this container - assert (*pContainer == pVar->GetIVal()); - ++*pContainer; - assert (*pContainer == pVar->GetIVal()); - --*pContainer; -#endif - - if (pOldVar) - { - // carry on the default value from the old variable anyway - pVar->Set(nDefault); - } - return pVar; -} - -///////////////////////////////////////////////////////////////////////////////// -bool CSystem::InitFileSystem() -{ - LOADING_TIME_PROFILE_SECTION; - using namespace AzFramework::AssetSystem; - - if (m_pUserCallback) - { - m_pUserCallback->OnInitProgress("Initializing File System..."); - } - - // get the DirectInstance FileIOBase which should be the AZ::LocalFileIO - m_env.pFileIO = AZ::IO::FileIOBase::GetDirectInstance(); - - m_env.pCryPak = AZ::Interface::Get(); - m_env.pFileIO = AZ::IO::FileIOBase::GetInstance(); - AZ_Assert(m_env.pCryPak, "CryPak has not been initialized on AZ::Interface"); - AZ_Assert(m_env.pFileIO, "FileIOBase has not been initialized"); - - if (m_bEditor) - { - m_env.pCryPak->RecordFileOpen(AZ::IO::IArchive::RFOM_EngineStartup); - } - - //init crypak - if (m_env.pCryPak->Init("")) - { -#if !defined(_RELEASE) - const ICmdLineArg* pakalias = m_pCmdLine->FindArg(eCLAT_Pre, "pakalias"); -#else - const ICmdLineArg* pakalias = nullptr; -#endif // !defined(_RELEASE) - if (pakalias && strlen(pakalias->GetValue()) > 0) - { - m_env.pCryPak->ParseAliases(pakalias->GetValue()); - } - } - else - { - AZ_Assert(false, "Failed to initialize CryPak."); - return false; - } - - // Now that file systems are init, we will clear any events that have arrived - // during file system init, so that systems do not reload assets that were already compiled in the - // critical compilation section. - - AzFramework::LegacyAssetEventBus::ClearQueuedEvents(); - - //we are good to go - return true; -} - - -void CSystem::ShutdownFileSystem() -{ -#if defined(AZ_PLATFORM_WINDOWS) - if (g_cacheLock != INVALID_HANDLE_VALUE) - { - CloseHandle(g_cacheLock); - g_cacheLock = INVALID_HANDLE_VALUE; - } -#endif - - using namespace AZ::IO; - - FileIOBase* directInstance = FileIOBase::GetDirectInstance(); - FileIOBase* pakInstance = FileIOBase::GetInstance(); - - if (directInstance == m_env.pFileIO) - { - // we only mess with file io if we own the instance that we installed. - // if we dont' own the instance, then we never configured fileIO and we should not alter it. - delete directInstance; - FileIOBase::SetDirectInstance(nullptr); - - if (pakInstance != directInstance) - { - delete pakInstance; - FileIOBase::SetInstance(nullptr); - } - } - - m_env.pFileIO = nullptr; -} - -///////////////////////////////////////////////////////////////////////////////// -bool CSystem::InitFileSystem_LoadEngineFolders(const SSystemInitParams&) -{ - LOADING_TIME_PROFILE_SECTION; - { - LoadConfiguration(m_systemConfigName.c_str()); - AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "Loading system configuration from %s...", m_systemConfigName.c_str()); - } - -#if defined(AZ_PLATFORM_ANDROID) - AZ::Android::Utils::SetLoadFilesToMemory(m_sys_load_files_to_memory->GetString()); -#endif - - GetISystem()->SetConfigPlatform(GetDevicePlatform()); - - auto projectPath = AZ::Utils::GetProjectPath(); - AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "Project Path: %s\n", projectPath.empty() ? "None specified" : projectPath.c_str()); - - auto projectName = AZ::Utils::GetProjectName(); - AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "Project Name: %s\n", projectName.empty() ? "None specified" : projectName.c_str()); - - OpenBasicPaks(); - - // Load game-specific folder. - LoadConfiguration("game.cfg"); - // Load the client/sever-specific configuration - static const char* g_additionalConfig = gEnv->IsDedicated() ? "server_cfg" : "client_cfg"; - LoadConfiguration(g_additionalConfig, nullptr, false); - - // We do not use CVar groups on the consoles - AddCVarGroupDirectory("Config/CVarGroups"); - - return (true); -} - -////////////////////////////////////////////////////////////////////////// -bool CSystem::InitAudioSystem(const SSystemInitParams& initParams) -{ - LOADING_TIME_PROFILE_SECTION(GetISystem()); - - if (!Audio::Gem::AudioSystemGemRequestBus::HasHandlers()) - { - // AudioSystem Gem has not been enabled for this project. - // This should not generate an error, but calling scope will warn. - return false; - } - - bool useRealAudioSystem = false; - if (!initParams.bPreview - && !m_bDedicatedServer - && m_sys_audio_disable->GetIVal() == 0) - { - useRealAudioSystem = true; - } - - bool result = false; - if (useRealAudioSystem) - { - Audio::Gem::AudioSystemGemRequestBus::BroadcastResult(result, &Audio::Gem::AudioSystemGemRequestBus::Events::Initialize, &initParams); - } - else - { - Audio::Gem::AudioSystemGemRequestBus::BroadcastResult(result, &Audio::Gem::AudioSystemGemRequestBus::Events::Initialize, nullptr); - } - - if (result) - { - AZ_Assert(Audio::AudioSystemRequestBus::HasHandlers(), - "Initialization of the Audio System succeeded, but the Audio System EBus is not connected!\n"); - } - else - { - AZ_Error(AZ_TRACE_SYSTEM_WINDOW, result, "The Audio System did not initialize correctly!\n"); - } - - return result; -} - -////////////////////////////////////////////////////////////////////////// -bool CSystem::InitVTuneProfiler() -{ - LOADING_TIME_PROFILE_SECTION(GetISystem()); - -#ifdef PROFILE_WITH_VTUNE - - WIN_HMODULE hModule = LoadDLL("VTuneApi.dll"); - if (!hModule) - { - return false; - } - - VTPause = (VTuneFunction) CryGetProcAddress(hModule, "VTPause"); - VTResume = (VTuneFunction) CryGetProcAddress(hModule, "VTResume"); - if (!VTPause || !VTResume) - { - AZ_Assert(false, "VTune did not initialize correctly.") - return false; - } - else - { - AZ_TracePrintf(AZ_TRACE_SYSTEM_WINDOW, "VTune API Initialized"); - } -#endif //PROFILE_WITH_VTUNE - - return true; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::InitLocalization() -{ - LOADING_TIME_PROFILE_SECTION(GetISystem()); - // Set the localization folder - ICVar* pCVar = m_env.pConsole != 0 ? m_env.pConsole->GetCVar("sys_localization_folder") : 0; - if (pCVar) - { - static_cast(m_env.pCryPak)->SetLocalizationFolder(g_cvars.sys_localization_folder->GetString()); - } - - // Removed line that assigned language based on a #define - - if (m_pLocalizationManager == nullptr) - { - m_pLocalizationManager = new CLocalizedStringsManager(this); - } - - // Platform-specific implementation of getting the system language - ILocalizationManager::EPlatformIndependentLanguageID languageID = m_pLocalizationManager->GetSystemLanguage(); - if (!m_pLocalizationManager->IsLanguageSupported(languageID)) - { - languageID = ILocalizationManager::EPlatformIndependentLanguageID::ePILID_English_US; - } - - string language = m_pLocalizationManager->LangNameFromPILID(languageID); - m_pLocalizationManager->SetLanguage(language.c_str()); - if (m_pLocalizationManager->GetLocalizationFormat() == 1) - { - string translationsListXML = LOCALIZATION_TRANSLATIONS_LIST_FILE_NAME; - m_pLocalizationManager->InitLocalizationData(translationsListXML); - - m_pLocalizationManager->LoadAllLocalizationData(); - } - else - { - // if the language value cannot be found, let's default to the english pak - OpenLanguagePak(language); - } - - pCVar = m_env.pConsole != 0 ? m_env.pConsole->GetCVar("g_languageAudio") : 0; - if (pCVar) - { - if (strlen(pCVar->GetString()) == 0) - { - pCVar->Set(language); - } - else - { - language = pCVar->GetString(); - } - } - OpenLanguageAudioPak(language); -} - -void CSystem::OpenBasicPaks() -{ - static bool bBasicPaksLoaded = false; - if (bBasicPaksLoaded) - { - return; - } - bBasicPaksLoaded = true; - - LOADING_TIME_PROFILE_SECTION; - - // open pak files - constexpr AZStd::string_view paksFolder = "@assets@/*.pak"; // (@assets@ assumed) - m_env.pCryPak->OpenPacks(paksFolder); - - InlineInitializationProcessing("CSystem::OpenBasicPaks OpenPacks( paksFolder.c_str() )"); - - ////////////////////////////////////////////////////////////////////////// - // Open engine packs - ////////////////////////////////////////////////////////////////////////// - - const char* const assetsDir = "@assets@"; - - // After game paks to have same search order as with files on disk - m_env.pCryPak->OpenPack(assetsDir, "Engine.pak"); - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_15 -#include AZ_RESTRICTED_FILE(SystemInit_cpp) -#endif - -#ifdef AZ_PLATFORM_ANDROID - // Load Android Obb files if available - const char* obbStorage = AZ::Android::Utils::GetObbStoragePath(); - AZStd::string mainObbPath = AZStd::move(AZStd::string::format("%s/%s", obbStorage, AZ::Android::Utils::GetObbFileName(true))); - AZStd::string patchObbPath = AZStd::move(AZStd::string::format("%s/%s", obbStorage, AZ::Android::Utils::GetObbFileName(false))); - m_env.pCryPak->OpenPack(assetsDir, mainObbPath.c_str()); - m_env.pCryPak->OpenPack(assetsDir, patchObbPath.c_str()); -#endif //AZ_PLATFORM_ANDROID - - InlineInitializationProcessing("CSystem::OpenBasicPaks OpenPacks( Engine... )"); - - // Load paks required for game init to mem - gEnv->pCryPak->LoadPakToMemory("Engine.pak", AZ::IO::IArchive::eInMemoryPakLocale_GPU); -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::OpenLanguagePak(const char* sLanguage) -{ - // Don't attempt to open a language PAK file if the game doesn't have a - // loc folder configured. - bool projUsesLocalization = false; - LocalizationManagerRequestBus::BroadcastResult(projUsesLocalization, &LocalizationManagerRequestBus::Events::ProjectUsesLocalization); - if (!projUsesLocalization) - { - return; - } - - // Initialize languages. - - // Omit the trailing slash! - string sLocalizationFolder = PathUtil::GetLocalizationFolder(); - - // load xml pak with full filenames to perform wildcard searches. - string sLocalizedPath; - GetLocalizedPath(sLanguage, sLocalizedPath); - if (!m_env.pCryPak->OpenPacks({ sLocalizationFolder.c_str(), sLocalizationFolder.size() }, { sLocalizedPath.c_str(), sLocalizedPath.size() }, 0)) - { - // make sure the localized language is found - not really necessary, for TC - AZ_Printf("Localization", "Localized language content(%s) not available or modified from the original installation.", sLanguage); - } -} - - -////////////////////////////////////////////////////////////////////////// -void CSystem::OpenLanguageAudioPak([[maybe_unused]] const char* sLanguage) -{ - // Don't attempt to open a language PAK file if the game doesn't have a - // loc folder configured. - bool projUsesLocalization = false; - LocalizationManagerRequestBus::BroadcastResult(projUsesLocalization, &LocalizationManagerRequestBus::Events::ProjectUsesLocalization); - if (!projUsesLocalization) - { - return; - } - - // Initialize languages. - - int nPakFlags = 0; - - // Omit the trailing slash! - string sLocalizationFolder(string().assign(PathUtil::GetLocalizationFolder(), 0, PathUtil::GetLocalizationFolder().size() - 1)); - - if (sLocalizationFolder.compareNoCase("Languages") == 0) - { - sLocalizationFolder = "@assets@"; - } - - // load localized pak with crc32 filenames on consoles to save memory. - string sLocalizedPath = "loc.pak"; - - if (!m_env.pCryPak->OpenPacks(sLocalizationFolder.c_str(), sLocalizedPath.c_str(), nPakFlags)) - { - // make sure the localized language is found - not really necessary, for TC - AZ_Error(AZ_TRACE_SYSTEM_WINDOW, false, "Localized language content(%s) not available or modified from the original installation.", sLanguage); - } -} - - -string GetUniqueLogFileName(string logFileName) -{ - string logFileNamePrefix = logFileName; - if ((logFileNamePrefix[0] != '@') && (AzFramework::StringFunc::Path::IsRelative(logFileNamePrefix))) - { - logFileNamePrefix = "@log@/"; - logFileNamePrefix += logFileName; - } - - char resolvedLogFilePathBuffer[AZ_MAX_PATH_LEN] = { 0 }; - AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(logFileNamePrefix.c_str(), resolvedLogFilePathBuffer, AZ_MAX_PATH_LEN); - - int instance = gEnv->pSystem->GetApplicationLogInstance(resolvedLogFilePathBuffer); - - if (instance == 0) - { - return logFileNamePrefix; - } - - string logFileExtension; - size_t extensionIndex = logFileName.find_last_of('.'); - if (extensionIndex != string::npos) - { - logFileExtension = logFileName.substr(extensionIndex, logFileName.length() - extensionIndex); - logFileNamePrefix = logFileName.substr(0, extensionIndex); - } - - logFileName.Format("%s(%d)%s", logFileNamePrefix.c_str(), instance, logFileExtension.c_str()); - - return logFileName; -} - -class AzConsoleToCryConsoleBinder final -{ -public: - static void OnInvoke(IConsoleCmdArgs* args) - { - std::string command = args->GetCommandLine(); - const size_t delim = command.find_first_of('='); - if (delim != std::string::npos) - { - // All Cry executed cfg files will come in through this pathway in addition to regular commands - // We strip out the = sign at this layer to maintain compatibility with cvars that use the '=' as a separator - // Swap the '=' character for a space - command[delim] = ' '; - } - - AZ::Interface::Get()->PerformCommand(command.c_str(), AZ::ConsoleSilentMode::Silent, AZ::ConsoleInvokedFrom::CryBinding); - } - - static void OnVarChanged(ICVar* cvar) - { - AZ::CVarFixedString command = AZ::CVarFixedString::format("%s %s", cvar->GetName(), cvar->GetString()); - AZ::Interface::Get()->PerformCommand(command.c_str(), AZ::ConsoleSilentMode::Silent, AZ::ConsoleInvokedFrom::CryBinding); - } - - static void Visit(AZ::ConsoleFunctorBase* functor) - { - if (gEnv->pConsole == nullptr) - { - AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "Cry console was NULL while attempting to register Az CVars and CFuncs.\n"); - return; - } - - int32_t cryFlags = VF_NET_SYNCED; - if ((functor->GetFlags() & AZ::ConsoleFunctorFlags::DontReplicate) != AZ::ConsoleFunctorFlags::Null) - { - cryFlags = VF_NULL; - } - if ((functor->GetFlags() & AZ::ConsoleFunctorFlags::ServerOnly) != AZ::ConsoleFunctorFlags::Null) - { - cryFlags |= VF_DEDI_ONLY; - } - if ((functor->GetFlags() & AZ::ConsoleFunctorFlags::ReadOnly) != AZ::ConsoleFunctorFlags::Null) - { - cryFlags |= VF_READONLY; - } - if ((functor->GetFlags() & AZ::ConsoleFunctorFlags::IsCheat) != AZ::ConsoleFunctorFlags::Null) - { - cryFlags |= VF_CHEAT; - } - if ((functor->GetFlags() & AZ::ConsoleFunctorFlags::IsInvisible) != AZ::ConsoleFunctorFlags::Null) - { - cryFlags |= VF_INVISIBLE; - } - if ((functor->GetFlags() & AZ::ConsoleFunctorFlags::IsDeprecated) != AZ::ConsoleFunctorFlags::Null) - { - cryFlags |= VF_DEPRECATED; - } - if ((functor->GetFlags() & AZ::ConsoleFunctorFlags::NeedsReload) != AZ::ConsoleFunctorFlags::Null) - { - cryFlags |= VF_REQUIRE_APP_RESTART; - } - if ((functor->GetFlags() & AZ::ConsoleFunctorFlags::AllowClientSet) != AZ::ConsoleFunctorFlags::Null) - { - cryFlags |= VF_DEV_ONLY; - } - - gEnv->pConsole->RemoveCommand(functor->GetName()); - if (functor->GetTypeId() != AZ::TypeId::CreateNull()) - { - AZ::CVarFixedString value; - functor->GetValue(value); - gEnv->pConsole->RegisterString(functor->GetName(), value.c_str(), cryFlags, functor->GetDesc(), AzConsoleToCryConsoleBinder::OnVarChanged); - } - else - { - gEnv->pConsole->AddCommand(functor->GetName(), AzConsoleToCryConsoleBinder::OnInvoke, cryFlags, functor->GetDesc()); - } - } - - using CommandRegisteredHandler = AZ::IConsole::ConsoleCommandRegisteredEvent::Handler; - static inline CommandRegisteredHandler s_commandRegisteredHandler = CommandRegisteredHandler([](AZ::ConsoleFunctorBase* functor) { Visit(functor); }); -}; - -// System initialization -///////////////////////////////////////////////////////////////////////////////// -// INIT -///////////////////////////////////////////////////////////////////////////////// -bool CSystem::Init(const SSystemInitParams& startupParams) -{ -#if AZ_TRAIT_USE_CRY_SIGNAL_HANDLER - signal(SIGSEGV, CryEngineSignalHandler); - signal(SIGTRAP, CryEngineSignalHandler); - signal(SIGILL, CryEngineSignalHandler); -#endif // AZ_TRAIT_USE_CRY_SIGNAL_HANDLER - - // Temporary Fix for an issue accessing gEnv from this object instance. The gEnv is not resolving to the - // global gEnv, instead its resolving an some uninitialized gEnv elsewhere (NULL). Since gEnv is - // initialized to this instance's SSystemGlobalEnvironment (m_env), we will force set it again here - // to m_env - if (!gEnv) - { - gEnv = &m_env; - } - - LOADING_TIME_PROFILE_SECTION; - - SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_INIT); - gEnv->mMainThreadId = GetCurrentThreadId(); //Set this ASAP on startup - - InlineInitializationProcessing("CSystem::Init start"); - - m_env.bNoAssertDialog = false; - - m_bNoCrashDialog = gEnv->IsDedicated(); - - if (startupParams.bUnattendedMode) - { - m_bNoCrashDialog = true; - m_env.bNoAssertDialog = true; //this also suppresses CryMessageBox - g_cvars.sys_no_crash_dialog = true; - } - -#if defined(AZ_PLATFORM_LINUX) - // Linux is all console for now and so no room for dialog boxes! - m_env.bNoAssertDialog = true; -#endif - - m_pCmdLine = new CCmdLine(startupParams.szSystemCmdLine); - - AZCoreLogSink::Connect(); - - // Registers all AZ Console Variables functors specified within CrySystem - if (auto azConsole = AZ::Interface::Get(); azConsole) - { - azConsole->LinkDeferredFunctors(AZ::ConsoleFunctorBase::GetDeferredHead()); - } - - if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry) - { - AZ::SettingsRegistryInterface::FixedValueString assetPlatform; - if (!AZ::SettingsRegistryMergeUtils::PlatformGet(*settingsRegistry, assetPlatform, - AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey, "assets")) - { - assetPlatform = AzFramework::OSPlatformToDefaultAssetPlatform(AZ_TRAIT_OS_PLATFORM_CODENAME); - AZ_Warning(AZ_TRACE_SYSTEM_WINDOW, false, R"(A valid asset platform is missing in "%s/assets" key in the SettingsRegistry.)""\n" - R"(This typically done by setting the "assets" field within a .setreg file)""\n" - R"(A fallback of %s will be used.)", - AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey, - assetPlatform.c_str()); - } - - m_systemConfigName = "system_" AZ_TRAIT_OS_PLATFORM_CODENAME_LOWER "_"; - m_systemConfigName += assetPlatform.c_str(); - m_systemConfigName += ".cfg"; - } - -#if defined(WIN32) || defined(WIN64) - // check OS version - we only want to run on XP or higher - talk to Martin Mittring if you want to change this - { - OSVERSIONINFO osvi; - - osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); -AZ_PUSH_DISABLE_WARNING(4996, "-Wunknown-warning-option") - GetVersionExA(&osvi); -AZ_POP_DISABLE_WARNING - - bool bIsWindowsXPorLater = osvi.dwMajorVersion > 5 || (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion >= 1); - - if (!bIsWindowsXPorLater) - { - AZ_Error(AZ_TRACE_SYSTEM_WINDOW, false, "Open 3D Engine requires an OS version of Windows XP or later."); - return false; - } - } -#endif - - // Get file version information. - QueryVersionInfo(); - DetectGameFolderAccessRights(); - - m_bEditor = startupParams.bEditor; - m_bPreviewMode = startupParams.bPreview; - m_bTestMode = startupParams.bTestMode; - m_pUserCallback = startupParams.pUserCallback; - - m_bDedicatedServer = startupParams.bDedicatedServer; - m_currentLanguageAudio = ""; - -#if !defined(CONSOLE) - m_env.SetIsEditor(m_bEditor); - m_env.SetIsEditorGameMode(false); - m_env.SetIsEditorSimulationMode(false); -#endif - - m_env.SetToolMode(startupParams.bToolMode); - - if (m_bEditor) - { - m_bInDevMode = true; - } - - if (!gEnv->IsDedicated()) - { - const ICmdLineArg* crashdialog = m_pCmdLine->FindArg(eCLAT_Post, "sys_no_crash_dialog"); - if (crashdialog) - { - m_bNoCrashDialog = true; - } - } - -#if !defined(_RELEASE) - if (!m_bDedicatedServer) - { - const ICmdLineArg* dedicated = m_pCmdLine->FindArg(eCLAT_Pre, "dedicated"); - if (dedicated) - { - m_bDedicatedServer = true; - } - } -#endif // !defined(_RELEASE) - -#if !defined(CONSOLE) - gEnv->SetIsDedicated(m_bDedicatedServer); -#endif - - { - EBUS_EVENT(CrySystemEventBus, OnCrySystemPreInitialize, *this, startupParams); - - ////////////////////////////////////////////////////////////////////////// - // File system, must be very early - ////////////////////////////////////////////////////////////////////////// - if (!InitFileSystem()) - { - return false; - } - ////////////////////////////////////////////////////////////////////////// - InlineInitializationProcessing("CSystem::Init InitFileSystem"); - - m_missingAssetLogger = AZStd::make_unique(); - - ////////////////////////////////////////////////////////////////////////// - // Logging is only available after file system initialization. - ////////////////////////////////////////////////////////////////////////// - if (!startupParams.pLog) - { - m_env.pLog = new CLog(this); - if (startupParams.pLogCallback) - { - m_env.pLog->AddCallback(startupParams.pLogCallback); - } - - const ICmdLineArg* logfile = m_pCmdLine->FindArg(eCLAT_Pre, "logfile"); //see if the user specified a log name, if so use it - if (logfile && strlen(logfile->GetValue()) > 0) - { - m_env.pLog->SetFileName(logfile->GetValue(), startupParams.autoBackupLogs); - } - else if (startupParams.sLogFileName) //otherwise see if the startup params has a log file name, if so use it - { - const string sUniqueLogFileName = GetUniqueLogFileName(startupParams.sLogFileName); - m_env.pLog->SetFileName(sUniqueLogFileName.c_str(), startupParams.autoBackupLogs); - } - else//use the default log name - { - m_env.pLog->SetFileName(DEFAULT_LOG_FILENAME, startupParams.autoBackupLogs); - } - } - else - { - m_env.pLog = startupParams.pLog; - } - - // The log backup system expects the version number to be the first line of the log - // so we log this immediately after setting the log filename - LogVersion(); - - bool devModeEnable = true; - -#if defined(_RELEASE) - // disable devmode by default in release builds outside the editor - devModeEnable = m_bEditor; -#endif - - // disable devmode in launcher if someone really wants to (even in non release builds) - if (!m_bEditor && m_pCmdLine->FindArg(eCLAT_Pre, "nodevmode")) - { - devModeEnable = false; - } - - SetDevMode(devModeEnable); - - ////////////////////////////////////////////////////////////////////////// - // CREATE CONSOLE - ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bSkipConsole) - { - m_env.pConsole = new CXConsole; - - if (startupParams.pPrintSync) - { - m_env.pConsole->AddOutputPrintSink(startupParams.pPrintSync); - } - } - - ////////////////////////////////////////////////////////////////////////// - - if (m_pUserCallback) - { - m_pUserCallback->OnInit(this); - } - - m_env.pLog->RegisterConsoleVariables(); - - GetIRemoteConsole()->RegisterConsoleVariables(); - - if (!startupParams.bSkipConsole) - { - // Register system console variables. - CreateSystemVars(); - - // Register Audio-related system CVars - CreateAudioVars(); - - // Register any AZ CVar commands created above with the AZ Console system. - AZ::ConsoleFunctorBase*& deferredHead = AZ::ConsoleFunctorBase::GetDeferredHead(); - AZ::Interface::Get()->LinkDeferredFunctors(deferredHead); - - // Callback - if (m_pUserCallback && m_env.pConsole) - { - m_pUserCallback->OnConsoleCreated(m_env.pConsole); - } - - // Let listeners know its safe to register cvars - EBUS_EVENT(CrySystemEventBus, OnCrySystemCVarRegistry); - } - - - // Set this as soon as the system cvars got initialized. - static_cast(m_env.pCryPak)->SetLocalizationFolder(g_cvars.sys_localization_folder->GetString()); - - InlineInitializationProcessing("CSystem::Init Create console"); - - // Need to load the engine.pak that includes the config files needed during initialization - m_env.pCryPak->OpenPack("@assets@", "Engine.pak"); - - InitFileSystem_LoadEngineFolders(startupParams); - -#if !defined(RELEASE) || defined(RELEASE_LOGGING) - // now that the system cfgs have been loaded, we can start the remote console - GetIRemoteConsole()->Update(); -#endif - - InlineInitializationProcessing("CSystem::Init Load Engine Folders"); - - ////////////////////////////////////////////////////////////////////////// - //Load config files - ////////////////////////////////////////////////////////////////////////// - - int curSpecVal = 0; - ICVar* pSysSpecCVar = gEnv->pConsole->GetCVar("r_GraphicsQuality"); - if (gEnv->pSystem->IsDevMode()) - { - if (pSysSpecCVar && pSysSpecCVar->GetFlags() & VF_WASINCONFIG) - { - curSpecVal = pSysSpecCVar->GetIVal(); - pSysSpecCVar->SetFlags(pSysSpecCVar->GetFlags() | VF_SYSSPEC_OVERWRITE); - } - } - - // tools may not interact with @user@ - if (!gEnv->IsInToolMode()) - { - if (m_pCmdLine->FindArg(eCLAT_Pre, "ResetProfile") == 0) - { - LoadConfiguration("@user@/game.cfg", 0, false); - } - } - - // If sys spec variable was specified, is not 0, and we are in devmode restore the value from before loading game.cfg - // This enables setting of a specific sys_spec outside menu and game.cfg - if (gEnv->pSystem->IsDevMode()) - { - if (pSysSpecCVar && curSpecVal && curSpecVal != pSysSpecCVar->GetIVal()) - { - pSysSpecCVar->Set(curSpecVal); - } - } - - { - // We have to load this file again since first time we did it without devmode - LoadConfiguration(m_systemConfigName.c_str()); - // Optional user defined overrides - LoadConfiguration("user.cfg"); - -#if defined(ENABLE_STATS_AGENT) - if (m_pCmdLine->FindArg(eCLAT_Pre, "useamblecfg")) - { - LoadConfiguration("amble.cfg"); - } -#endif - } - -#if defined(PERFORMANCE_BUILD) - LoadConfiguration("performance.cfg"); -#endif - - ////////////////////////////////////////////////////////////////////////// - if (g_cvars.sys_asserts == 0) - { - gEnv->bIgnoreAllAsserts = true; - } - if (g_cvars.sys_asserts == 2) - { - gEnv->bNoAssertDialog = true; - } - - LogBuildInfo(); - - InlineInitializationProcessing("CSystem::Init LoadConfigurations"); - -#ifdef WIN32 - if (g_cvars.sys_WER) - { - SetUnhandledExceptionFilter(CryEngineExceptionFilterWER); - } -#endif - - ////////////////////////////////////////////////////////////////////////// - // Localization - ////////////////////////////////////////////////////////////////////////// - { - InitLocalization(); - } - InlineInitializationProcessing("CSystem::Init InitLocalizations"); - - ////////////////////////////////////////////////////////////////////////// - // Open basic pak files after intro movie playback started - ////////////////////////////////////////////////////////////////////////// - OpenBasicPaks(); - - ////////////////////////////////////////////////////////////////////////// - // AUDIO - ////////////////////////////////////////////////////////////////////////// - { - if (InitAudioSystem(startupParams)) - { - // Pump the Log - Audio initialization happened on a non-main thread, there may be log messages queued up. - gEnv->pLog->Update(); - } - else - { - // Failure to initialize audio system is no longer a fatal or an error. A warning is sufficient. - AZ_Warning(AZ_TRACE_SYSTEM_WINDOW, false, "