Alexhas2 commited on
Commit
1e67697
·
verified ·
1 Parent(s): 1d73d61

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySet.cpp +148 -0
  2. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySet.h +149 -0
  3. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySourceInterface.cpp +10 -0
  4. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySourceInterface.h +36 -0
  5. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySystemComponent.cpp +528 -0
  6. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySystemComponent.h +110 -0
  7. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySystemGlobals.cpp +20 -0
  8. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySystemGlobals.h +20 -0
  9. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilityTagRelationshipMapping.cpp +63 -0
  10. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilityTagRelationshipMapping.h +60 -0
  11. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGameplayAbilityTargetData_SingleTargetHit.cpp +32 -0
  12. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGameplayAbilityTargetData_SingleTargetHit.h +45 -0
  13. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGameplayCueManager.cpp +406 -0
  14. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGameplayCueManager.h +79 -0
  15. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGameplayEffectContext.cpp +67 -0
  16. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGameplayEffectContext.h +82 -0
  17. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGlobalAbilitySystem.cpp +156 -0
  18. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGlobalAbilitySystem.h +81 -0
  19. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraTaggedActor.cpp +30 -0
  20. LyraStarterGame/Source/LyraGame/AbilitySystem/LyraTaggedActor.h +36 -0
  21. LyraStarterGame/Source/LyraGame/Animation/LyraAnimInstance.cpp +65 -0
  22. LyraStarterGame/Source/LyraGame/Animation/LyraAnimInstance.h +46 -0
  23. LyraStarterGame/Source/LyraGame/Audio/LyraAudioMixEffectsSubsystem.cpp +353 -0
  24. LyraStarterGame/Source/LyraGame/Audio/LyraAudioMixEffectsSubsystem.h +112 -0
  25. LyraStarterGame/Source/LyraGame/Audio/LyraAudioSettings.cpp +8 -0
  26. LyraStarterGame/Source/LyraGame/Audio/LyraAudioSettings.h +80 -0
  27. LyraStarterGame/Source/LyraGame/Camera/LyraCameraAssistInterface.h +41 -0
  28. LyraStarterGame/Source/LyraGame/Camera/LyraCameraComponent.cpp +126 -0
  29. LyraStarterGame/Source/LyraGame/Camera/LyraCameraComponent.h +70 -0
  30. LyraStarterGame/Source/LyraGame/Camera/LyraCameraMode.cpp +465 -0
  31. LyraStarterGame/Source/LyraGame/Camera/LyraCameraMode.h +203 -0
  32. LyraStarterGame/Source/LyraGame/Camera/LyraCameraMode_ThirdPerson.cpp +373 -0
  33. LyraStarterGame/Source/LyraGame/Camera/LyraCameraMode_ThirdPerson.h +114 -0
  34. LyraStarterGame/Source/LyraGame/Camera/LyraPenetrationAvoidanceFeeler.h +66 -0
  35. LyraStarterGame/Source/LyraGame/Camera/LyraPlayerCameraManager.cpp +66 -0
  36. LyraStarterGame/Source/LyraGame/Camera/LyraPlayerCameraManager.h +46 -0
  37. LyraStarterGame/Source/LyraGame/Camera/LyraUICameraManagerComponent.cpp +65 -0
  38. LyraStarterGame/Source/LyraGame/Camera/LyraUICameraManagerComponent.h +45 -0
  39. LyraStarterGame/Source/LyraGame/Character/LyraCharacter.cpp +682 -0
  40. LyraStarterGame/Source/LyraGame/Character/LyraCharacter.h +231 -0
  41. LyraStarterGame/Source/LyraGame/Character/LyraCharacterMovementComponent.cpp +131 -0
  42. LyraStarterGame/Source/LyraGame/Character/LyraCharacterMovementComponent.h +84 -0
  43. LyraStarterGame/Source/LyraGame/Character/LyraCharacterWithAbilities.cpp +39 -0
  44. LyraStarterGame/Source/LyraGame/Character/LyraCharacterWithAbilities.h +43 -0
  45. LyraStarterGame/Source/LyraGame/Character/LyraHealthComponent.cpp +312 -0
  46. LyraStarterGame/Source/LyraGame/Character/LyraHealthComponent.h +135 -0
  47. LyraStarterGame/Source/LyraGame/Character/LyraHeroComponent.cpp +512 -0
  48. LyraStarterGame/Source/LyraGame/Character/LyraHeroComponent.h +108 -0
  49. LyraStarterGame/Source/LyraGame/Character/LyraPawn.cpp +112 -0
  50. LyraStarterGame/Source/LyraGame/Character/LyraPawn.h +68 -0
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySet.cpp ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraAbilitySet.h"
4
+
5
+ #include "AbilitySystem/Abilities/LyraGameplayAbility.h"
6
+ #include "LyraAbilitySystemComponent.h"
7
+ #include "LyraLogChannels.h"
8
+
9
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraAbilitySet)
10
+
11
+ void FLyraAbilitySet_GrantedHandles::AddAbilitySpecHandle(const FGameplayAbilitySpecHandle& Handle)
12
+ {
13
+ if (Handle.IsValid())
14
+ {
15
+ AbilitySpecHandles.Add(Handle);
16
+ }
17
+ }
18
+
19
+ void FLyraAbilitySet_GrantedHandles::AddGameplayEffectHandle(const FActiveGameplayEffectHandle& Handle)
20
+ {
21
+ if (Handle.IsValid())
22
+ {
23
+ GameplayEffectHandles.Add(Handle);
24
+ }
25
+ }
26
+
27
+ void FLyraAbilitySet_GrantedHandles::AddAttributeSet(UAttributeSet* Set)
28
+ {
29
+ GrantedAttributeSets.Add(Set);
30
+ }
31
+
32
+ void FLyraAbilitySet_GrantedHandles::TakeFromAbilitySystem(ULyraAbilitySystemComponent* LyraASC)
33
+ {
34
+ check(LyraASC);
35
+
36
+ if (!LyraASC->IsOwnerActorAuthoritative())
37
+ {
38
+ // Must be authoritative to give or take ability sets.
39
+ return;
40
+ }
41
+
42
+ for (const FGameplayAbilitySpecHandle& Handle : AbilitySpecHandles)
43
+ {
44
+ if (Handle.IsValid())
45
+ {
46
+ LyraASC->ClearAbility(Handle);
47
+ }
48
+ }
49
+
50
+ for (const FActiveGameplayEffectHandle& Handle : GameplayEffectHandles)
51
+ {
52
+ if (Handle.IsValid())
53
+ {
54
+ LyraASC->RemoveActiveGameplayEffect(Handle);
55
+ }
56
+ }
57
+
58
+ for (UAttributeSet* Set : GrantedAttributeSets)
59
+ {
60
+ LyraASC->RemoveSpawnedAttribute(Set);
61
+ }
62
+
63
+ AbilitySpecHandles.Reset();
64
+ GameplayEffectHandles.Reset();
65
+ GrantedAttributeSets.Reset();
66
+ }
67
+
68
+ ULyraAbilitySet::ULyraAbilitySet(const FObjectInitializer& ObjectInitializer)
69
+ : Super(ObjectInitializer)
70
+ {
71
+ }
72
+
73
+ void ULyraAbilitySet::GiveToAbilitySystem(ULyraAbilitySystemComponent* LyraASC, FLyraAbilitySet_GrantedHandles* OutGrantedHandles, UObject* SourceObject) const
74
+ {
75
+ check(LyraASC);
76
+
77
+ if (!LyraASC->IsOwnerActorAuthoritative())
78
+ {
79
+ // Must be authoritative to give or take ability sets.
80
+ return;
81
+ }
82
+
83
+ // Grant the attribute sets.
84
+ for (int32 SetIndex = 0; SetIndex < GrantedAttributes.Num(); ++SetIndex)
85
+ {
86
+ const FLyraAbilitySet_AttributeSet& SetToGrant = GrantedAttributes[SetIndex];
87
+
88
+ if (!IsValid(SetToGrant.AttributeSet))
89
+ {
90
+ UE_LOG(LogLyraAbilitySystem, Error, TEXT("GrantedAttributes[%d] on ability set [%s] is not valid"), SetIndex, *GetNameSafe(this));
91
+ continue;
92
+ }
93
+
94
+ UAttributeSet* NewSet = NewObject<UAttributeSet>(LyraASC->GetOwner(), SetToGrant.AttributeSet);
95
+ LyraASC->AddAttributeSetSubobject(NewSet);
96
+
97
+ if (OutGrantedHandles)
98
+ {
99
+ OutGrantedHandles->AddAttributeSet(NewSet);
100
+ }
101
+ }
102
+
103
+ // Grant the gameplay abilities.
104
+ for (int32 AbilityIndex = 0; AbilityIndex < GrantedGameplayAbilities.Num(); ++AbilityIndex)
105
+ {
106
+ const FLyraAbilitySet_GameplayAbility& AbilityToGrant = GrantedGameplayAbilities[AbilityIndex];
107
+
108
+ if (!IsValid(AbilityToGrant.Ability))
109
+ {
110
+ UE_LOG(LogLyraAbilitySystem, Error, TEXT("GrantedGameplayAbilities[%d] on ability set [%s] is not valid."), AbilityIndex, *GetNameSafe(this));
111
+ continue;
112
+ }
113
+
114
+ ULyraGameplayAbility* AbilityCDO = AbilityToGrant.Ability->GetDefaultObject<ULyraGameplayAbility>();
115
+
116
+ FGameplayAbilitySpec AbilitySpec(AbilityCDO, AbilityToGrant.AbilityLevel);
117
+ AbilitySpec.SourceObject = SourceObject;
118
+ AbilitySpec.GetDynamicSpecSourceTags().AddTag(AbilityToGrant.InputTag);
119
+
120
+ const FGameplayAbilitySpecHandle AbilitySpecHandle = LyraASC->GiveAbility(AbilitySpec);
121
+
122
+ if (OutGrantedHandles)
123
+ {
124
+ OutGrantedHandles->AddAbilitySpecHandle(AbilitySpecHandle);
125
+ }
126
+ }
127
+
128
+ // Grant the gameplay effects.
129
+ for (int32 EffectIndex = 0; EffectIndex < GrantedGameplayEffects.Num(); ++EffectIndex)
130
+ {
131
+ const FLyraAbilitySet_GameplayEffect& EffectToGrant = GrantedGameplayEffects[EffectIndex];
132
+
133
+ if (!IsValid(EffectToGrant.GameplayEffect))
134
+ {
135
+ UE_LOG(LogLyraAbilitySystem, Error, TEXT("GrantedGameplayEffects[%d] on ability set [%s] is not valid"), EffectIndex, *GetNameSafe(this));
136
+ continue;
137
+ }
138
+
139
+ const UGameplayEffect* GameplayEffect = EffectToGrant.GameplayEffect->GetDefaultObject<UGameplayEffect>();
140
+ const FActiveGameplayEffectHandle GameplayEffectHandle = LyraASC->ApplyGameplayEffectToSelf(GameplayEffect, EffectToGrant.EffectLevel, LyraASC->MakeEffectContext());
141
+
142
+ if (OutGrantedHandles)
143
+ {
144
+ OutGrantedHandles->AddGameplayEffectHandle(GameplayEffectHandle);
145
+ }
146
+ }
147
+ }
148
+
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySet.h ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "ActiveGameplayEffectHandle.h"
6
+ #include "Engine/DataAsset.h"
7
+ #include "AttributeSet.h"
8
+ #include "GameplayTagContainer.h"
9
+
10
+ #include "GameplayAbilitySpecHandle.h"
11
+ #include "LyraAbilitySet.generated.h"
12
+
13
+ class UAttributeSet;
14
+ class UGameplayEffect;
15
+ class ULyraAbilitySystemComponent;
16
+ class ULyraGameplayAbility;
17
+ class UObject;
18
+
19
+
20
+ /**
21
+ * FLyraAbilitySet_GameplayAbility
22
+ *
23
+ * Data used by the ability set to grant gameplay abilities.
24
+ */
25
+ USTRUCT(BlueprintType)
26
+ struct FLyraAbilitySet_GameplayAbility
27
+ {
28
+ GENERATED_BODY()
29
+
30
+ public:
31
+
32
+ // Gameplay ability to grant.
33
+ UPROPERTY(EditDefaultsOnly)
34
+ TSubclassOf<ULyraGameplayAbility> Ability = nullptr;
35
+
36
+ // Level of ability to grant.
37
+ UPROPERTY(EditDefaultsOnly)
38
+ int32 AbilityLevel = 1;
39
+
40
+ // Tag used to process input for the ability.
41
+ UPROPERTY(EditDefaultsOnly, Meta = (Categories = "InputTag"))
42
+ FGameplayTag InputTag;
43
+ };
44
+
45
+
46
+ /**
47
+ * FLyraAbilitySet_GameplayEffect
48
+ *
49
+ * Data used by the ability set to grant gameplay effects.
50
+ */
51
+ USTRUCT(BlueprintType)
52
+ struct FLyraAbilitySet_GameplayEffect
53
+ {
54
+ GENERATED_BODY()
55
+
56
+ public:
57
+
58
+ // Gameplay effect to grant.
59
+ UPROPERTY(EditDefaultsOnly)
60
+ TSubclassOf<UGameplayEffect> GameplayEffect = nullptr;
61
+
62
+ // Level of gameplay effect to grant.
63
+ UPROPERTY(EditDefaultsOnly)
64
+ float EffectLevel = 1.0f;
65
+ };
66
+
67
+ /**
68
+ * FLyraAbilitySet_AttributeSet
69
+ *
70
+ * Data used by the ability set to grant attribute sets.
71
+ */
72
+ USTRUCT(BlueprintType)
73
+ struct FLyraAbilitySet_AttributeSet
74
+ {
75
+ GENERATED_BODY()
76
+
77
+ public:
78
+ // Gameplay effect to grant.
79
+ UPROPERTY(EditDefaultsOnly)
80
+ TSubclassOf<UAttributeSet> AttributeSet;
81
+
82
+ };
83
+
84
+ /**
85
+ * FLyraAbilitySet_GrantedHandles
86
+ *
87
+ * Data used to store handles to what has been granted by the ability set.
88
+ */
89
+ USTRUCT(BlueprintType)
90
+ struct FLyraAbilitySet_GrantedHandles
91
+ {
92
+ GENERATED_BODY()
93
+
94
+ public:
95
+
96
+ void AddAbilitySpecHandle(const FGameplayAbilitySpecHandle& Handle);
97
+ void AddGameplayEffectHandle(const FActiveGameplayEffectHandle& Handle);
98
+ void AddAttributeSet(UAttributeSet* Set);
99
+
100
+ void TakeFromAbilitySystem(ULyraAbilitySystemComponent* LyraASC);
101
+
102
+ protected:
103
+
104
+ // Handles to the granted abilities.
105
+ UPROPERTY()
106
+ TArray<FGameplayAbilitySpecHandle> AbilitySpecHandles;
107
+
108
+ // Handles to the granted gameplay effects.
109
+ UPROPERTY()
110
+ TArray<FActiveGameplayEffectHandle> GameplayEffectHandles;
111
+
112
+ // Pointers to the granted attribute sets
113
+ UPROPERTY()
114
+ TArray<TObjectPtr<UAttributeSet>> GrantedAttributeSets;
115
+ };
116
+
117
+
118
+ /**
119
+ * ULyraAbilitySet
120
+ *
121
+ * Non-mutable data asset used to grant gameplay abilities and gameplay effects.
122
+ */
123
+ UCLASS(BlueprintType, Const)
124
+ class ULyraAbilitySet : public UPrimaryDataAsset
125
+ {
126
+ GENERATED_BODY()
127
+
128
+ public:
129
+
130
+ ULyraAbilitySet(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
131
+
132
+ // Grants the ability set to the specified ability system component.
133
+ // The returned handles can be used later to take away anything that was granted.
134
+ void GiveToAbilitySystem(ULyraAbilitySystemComponent* LyraASC, FLyraAbilitySet_GrantedHandles* OutGrantedHandles, UObject* SourceObject = nullptr) const;
135
+
136
+ protected:
137
+
138
+ // Gameplay abilities to grant when this ability set is granted.
139
+ UPROPERTY(EditDefaultsOnly, Category = "Gameplay Abilities", meta=(TitleProperty=Ability))
140
+ TArray<FLyraAbilitySet_GameplayAbility> GrantedGameplayAbilities;
141
+
142
+ // Gameplay effects to grant when this ability set is granted.
143
+ UPROPERTY(EditDefaultsOnly, Category = "Gameplay Effects", meta=(TitleProperty=GameplayEffect))
144
+ TArray<FLyraAbilitySet_GameplayEffect> GrantedGameplayEffects;
145
+
146
+ // Attribute sets to grant when this ability set is granted.
147
+ UPROPERTY(EditDefaultsOnly, Category = "Attribute Sets", meta=(TitleProperty=AttributeSet))
148
+ TArray<FLyraAbilitySet_AttributeSet> GrantedAttributes;
149
+ };
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySourceInterface.cpp ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraAbilitySourceInterface.h"
4
+
5
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraAbilitySourceInterface)
6
+
7
+ ULyraAbilitySourceInterface::ULyraAbilitySourceInterface(const FObjectInitializer& ObjectInitializer)
8
+ : Super(ObjectInitializer)
9
+ {}
10
+
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySourceInterface.h ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "UObject/Interface.h"
6
+
7
+ #include "LyraAbilitySourceInterface.generated.h"
8
+
9
+ class UObject;
10
+ class UPhysicalMaterial;
11
+ struct FGameplayTagContainer;
12
+
13
+ /** Base interface for anything acting as a ability calculation source */
14
+ UINTERFACE()
15
+ class ULyraAbilitySourceInterface : public UInterface
16
+ {
17
+ GENERATED_UINTERFACE_BODY()
18
+ };
19
+
20
+ class ILyraAbilitySourceInterface
21
+ {
22
+ GENERATED_IINTERFACE_BODY()
23
+
24
+ /**
25
+ * Compute the multiplier for effect falloff with distance
26
+ *
27
+ * @param Distance Distance from source to target for ability calculations (distance bullet traveled for a gun, etc...)
28
+ * @param SourceTags Aggregated Tags from the source
29
+ * @param TargetTags Aggregated Tags currently on the target
30
+ *
31
+ * @return Multiplier to apply to the base attribute value due to distance
32
+ */
33
+ virtual float GetDistanceAttenuation(float Distance, const FGameplayTagContainer* SourceTags = nullptr, const FGameplayTagContainer* TargetTags = nullptr) const = 0;
34
+
35
+ virtual float GetPhysicalMaterialAttenuation(const UPhysicalMaterial* PhysicalMaterial, const FGameplayTagContainer* SourceTags = nullptr, const FGameplayTagContainer* TargetTags = nullptr) const = 0;
36
+ };
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySystemComponent.cpp ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraAbilitySystemComponent.h"
4
+
5
+ #include "AbilitySystem/Abilities/LyraGameplayAbility.h"
6
+ #include "AbilitySystem/LyraAbilityTagRelationshipMapping.h"
7
+ #include "Animation/LyraAnimInstance.h"
8
+ #include "Engine/World.h"
9
+ #include "GameFramework/Pawn.h"
10
+ #include "LyraGlobalAbilitySystem.h"
11
+ #include "LyraLogChannels.h"
12
+ #include "System/LyraAssetManager.h"
13
+ #include "System/LyraGameData.h"
14
+
15
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraAbilitySystemComponent)
16
+
17
+ UE_DEFINE_GAMEPLAY_TAG(TAG_Gameplay_AbilityInputBlocked, "Gameplay.AbilityInputBlocked");
18
+
19
+ ULyraAbilitySystemComponent::ULyraAbilitySystemComponent(const FObjectInitializer& ObjectInitializer)
20
+ : Super(ObjectInitializer)
21
+ {
22
+ InputPressedSpecHandles.Reset();
23
+ InputReleasedSpecHandles.Reset();
24
+ InputHeldSpecHandles.Reset();
25
+
26
+ FMemory::Memset(ActivationGroupCounts, 0, sizeof(ActivationGroupCounts));
27
+ }
28
+
29
+ void ULyraAbilitySystemComponent::EndPlay(const EEndPlayReason::Type EndPlayReason)
30
+ {
31
+ if (ULyraGlobalAbilitySystem* GlobalAbilitySystem = UWorld::GetSubsystem<ULyraGlobalAbilitySystem>(GetWorld()))
32
+ {
33
+ GlobalAbilitySystem->UnregisterASC(this);
34
+ }
35
+
36
+ Super::EndPlay(EndPlayReason);
37
+ }
38
+
39
+ void ULyraAbilitySystemComponent::InitAbilityActorInfo(AActor* InOwnerActor, AActor* InAvatarActor)
40
+ {
41
+ FGameplayAbilityActorInfo* ActorInfo = AbilityActorInfo.Get();
42
+ check(ActorInfo);
43
+ check(InOwnerActor);
44
+
45
+ const bool bHasNewPawnAvatar = Cast<APawn>(InAvatarActor) && (InAvatarActor != ActorInfo->AvatarActor);
46
+
47
+ Super::InitAbilityActorInfo(InOwnerActor, InAvatarActor);
48
+
49
+ if (bHasNewPawnAvatar)
50
+ {
51
+ // Notify all abilities that a new pawn avatar has been set
52
+ for (const FGameplayAbilitySpec& AbilitySpec : ActivatableAbilities.Items)
53
+ {
54
+ PRAGMA_DISABLE_DEPRECATION_WARNINGS
55
+ ensureMsgf(AbilitySpec.Ability && AbilitySpec.Ability->GetInstancingPolicy() != EGameplayAbilityInstancingPolicy::NonInstanced, TEXT("InitAbilityActorInfo: All Abilities should be Instanced (NonInstanced is being deprecated due to usability issues)."));
56
+ PRAGMA_ENABLE_DEPRECATION_WARNINGS
57
+
58
+ TArray<UGameplayAbility*> Instances = AbilitySpec.GetAbilityInstances();
59
+ for (UGameplayAbility* AbilityInstance : Instances)
60
+ {
61
+ ULyraGameplayAbility* LyraAbilityInstance = Cast<ULyraGameplayAbility>(AbilityInstance);
62
+ if (LyraAbilityInstance)
63
+ {
64
+ // Ability instances may be missing for replays
65
+ LyraAbilityInstance->OnPawnAvatarSet();
66
+ }
67
+ }
68
+ }
69
+
70
+ // Register with the global system once we actually have a pawn avatar. We wait until this time since some globally-applied effects may require an avatar.
71
+ if (ULyraGlobalAbilitySystem* GlobalAbilitySystem = UWorld::GetSubsystem<ULyraGlobalAbilitySystem>(GetWorld()))
72
+ {
73
+ GlobalAbilitySystem->RegisterASC(this);
74
+ }
75
+
76
+ if (ULyraAnimInstance* LyraAnimInst = Cast<ULyraAnimInstance>(ActorInfo->GetAnimInstance()))
77
+ {
78
+ LyraAnimInst->InitializeWithAbilitySystem(this);
79
+ }
80
+
81
+ TryActivateAbilitiesOnSpawn();
82
+ }
83
+ }
84
+
85
+ void ULyraAbilitySystemComponent::TryActivateAbilitiesOnSpawn()
86
+ {
87
+ ABILITYLIST_SCOPE_LOCK();
88
+ for (const FGameplayAbilitySpec& AbilitySpec : ActivatableAbilities.Items)
89
+ {
90
+ if (const ULyraGameplayAbility* LyraAbilityCDO = Cast<ULyraGameplayAbility>(AbilitySpec.Ability))
91
+ {
92
+ LyraAbilityCDO->TryActivateAbilityOnSpawn(AbilityActorInfo.Get(), AbilitySpec);
93
+ }
94
+ }
95
+ }
96
+
97
+ void ULyraAbilitySystemComponent::CancelAbilitiesByFunc(TShouldCancelAbilityFunc ShouldCancelFunc, bool bReplicateCancelAbility)
98
+ {
99
+ ABILITYLIST_SCOPE_LOCK();
100
+ for (const FGameplayAbilitySpec& AbilitySpec : ActivatableAbilities.Items)
101
+ {
102
+ if (!AbilitySpec.IsActive())
103
+ {
104
+ continue;
105
+ }
106
+
107
+ ULyraGameplayAbility* LyraAbilityCDO = Cast<ULyraGameplayAbility>(AbilitySpec.Ability);
108
+ if (!LyraAbilityCDO)
109
+ {
110
+ UE_LOG(LogLyraAbilitySystem, Error, TEXT("CancelAbilitiesByFunc: Non-LyraGameplayAbility %s was Granted to ASC. Skipping."), *AbilitySpec.Ability.GetName());
111
+ continue;
112
+ }
113
+
114
+ PRAGMA_DISABLE_DEPRECATION_WARNINGS
115
+ ensureMsgf(AbilitySpec.Ability->GetInstancingPolicy() != EGameplayAbilityInstancingPolicy::NonInstanced, TEXT("CancelAbilitiesByFunc: All Abilities should be Instanced (NonInstanced is being deprecated due to usability issues)."));
116
+ PRAGMA_ENABLE_DEPRECATION_WARNINGS
117
+
118
+ // Cancel all the spawned instances.
119
+ TArray<UGameplayAbility*> Instances = AbilitySpec.GetAbilityInstances();
120
+ for (UGameplayAbility* AbilityInstance : Instances)
121
+ {
122
+ ULyraGameplayAbility* LyraAbilityInstance = CastChecked<ULyraGameplayAbility>(AbilityInstance);
123
+
124
+ if (ShouldCancelFunc(LyraAbilityInstance, AbilitySpec.Handle))
125
+ {
126
+ if (LyraAbilityInstance->CanBeCanceled())
127
+ {
128
+ LyraAbilityInstance->CancelAbility(AbilitySpec.Handle, AbilityActorInfo.Get(), LyraAbilityInstance->GetCurrentActivationInfo(), bReplicateCancelAbility);
129
+ }
130
+ else
131
+ {
132
+ UE_LOG(LogLyraAbilitySystem, Error, TEXT("CancelAbilitiesByFunc: Can't cancel ability [%s] because CanBeCanceled is false."), *LyraAbilityInstance->GetName());
133
+ }
134
+ }
135
+ }
136
+ }
137
+ }
138
+
139
+ void ULyraAbilitySystemComponent::CancelInputActivatedAbilities(bool bReplicateCancelAbility)
140
+ {
141
+ auto ShouldCancelFunc = [this](const ULyraGameplayAbility* LyraAbility, FGameplayAbilitySpecHandle Handle)
142
+ {
143
+ const ELyraAbilityActivationPolicy ActivationPolicy = LyraAbility->GetActivationPolicy();
144
+ return ((ActivationPolicy == ELyraAbilityActivationPolicy::OnInputTriggered) || (ActivationPolicy == ELyraAbilityActivationPolicy::WhileInputActive));
145
+ };
146
+
147
+ CancelAbilitiesByFunc(ShouldCancelFunc, bReplicateCancelAbility);
148
+ }
149
+
150
+ void ULyraAbilitySystemComponent::AbilitySpecInputPressed(FGameplayAbilitySpec& Spec)
151
+ {
152
+ Super::AbilitySpecInputPressed(Spec);
153
+
154
+ // We don't support UGameplayAbility::bReplicateInputDirectly.
155
+ // Use replicated events instead so that the WaitInputPress ability task works.
156
+ if (Spec.IsActive())
157
+ {
158
+ PRAGMA_DISABLE_DEPRECATION_WARNINGS
159
+ const UGameplayAbility* Instance = Spec.GetPrimaryInstance();
160
+ FPredictionKey OriginalPredictionKey = Instance ? Instance->GetCurrentActivationInfo().GetActivationPredictionKey() : Spec.ActivationInfo.GetActivationPredictionKey();
161
+ PRAGMA_ENABLE_DEPRECATION_WARNINGS
162
+
163
+ // Invoke the InputPressed event. This is not replicated here. If someone is listening, they may replicate the InputPressed event to the server.
164
+ InvokeReplicatedEvent(EAbilityGenericReplicatedEvent::InputPressed, Spec.Handle, OriginalPredictionKey);
165
+ }
166
+ }
167
+
168
+ void ULyraAbilitySystemComponent::AbilitySpecInputReleased(FGameplayAbilitySpec& Spec)
169
+ {
170
+ Super::AbilitySpecInputReleased(Spec);
171
+
172
+ // We don't support UGameplayAbility::bReplicateInputDirectly.
173
+ // Use replicated events instead so that the WaitInputRelease ability task works.
174
+ if (Spec.IsActive())
175
+ {
176
+ PRAGMA_DISABLE_DEPRECATION_WARNINGS
177
+ const UGameplayAbility* Instance = Spec.GetPrimaryInstance();
178
+ FPredictionKey OriginalPredictionKey = Instance ? Instance->GetCurrentActivationInfo().GetActivationPredictionKey() : Spec.ActivationInfo.GetActivationPredictionKey();
179
+ PRAGMA_ENABLE_DEPRECATION_WARNINGS
180
+
181
+ // Invoke the InputReleased event. This is not replicated here. If someone is listening, they may replicate the InputReleased event to the server.
182
+ InvokeReplicatedEvent(EAbilityGenericReplicatedEvent::InputReleased, Spec.Handle, OriginalPredictionKey);
183
+ }
184
+ }
185
+
186
+ void ULyraAbilitySystemComponent::AbilityInputTagPressed(const FGameplayTag& InputTag)
187
+ {
188
+ if (InputTag.IsValid())
189
+ {
190
+ for (const FGameplayAbilitySpec& AbilitySpec : ActivatableAbilities.Items)
191
+ {
192
+ if (AbilitySpec.Ability && (AbilitySpec.GetDynamicSpecSourceTags().HasTagExact(InputTag)))
193
+ {
194
+ InputPressedSpecHandles.AddUnique(AbilitySpec.Handle);
195
+ InputHeldSpecHandles.AddUnique(AbilitySpec.Handle);
196
+ }
197
+ }
198
+ }
199
+ }
200
+
201
+ void ULyraAbilitySystemComponent::AbilityInputTagReleased(const FGameplayTag& InputTag)
202
+ {
203
+ if (InputTag.IsValid())
204
+ {
205
+ for (const FGameplayAbilitySpec& AbilitySpec : ActivatableAbilities.Items)
206
+ {
207
+ if (AbilitySpec.Ability && (AbilitySpec.GetDynamicSpecSourceTags().HasTagExact(InputTag)))
208
+ {
209
+ InputReleasedSpecHandles.AddUnique(AbilitySpec.Handle);
210
+ InputHeldSpecHandles.Remove(AbilitySpec.Handle);
211
+ }
212
+ }
213
+ }
214
+ }
215
+
216
+ void ULyraAbilitySystemComponent::ProcessAbilityInput(float DeltaTime, bool bGamePaused)
217
+ {
218
+ if (HasMatchingGameplayTag(TAG_Gameplay_AbilityInputBlocked))
219
+ {
220
+ ClearAbilityInput();
221
+ return;
222
+ }
223
+
224
+ static TArray<FGameplayAbilitySpecHandle> AbilitiesToActivate;
225
+ AbilitiesToActivate.Reset();
226
+
227
+ //@TODO: See if we can use FScopedServerAbilityRPCBatcher ScopedRPCBatcher in some of these loops
228
+
229
+ //
230
+ // Process all abilities that activate when the input is held.
231
+ //
232
+ for (const FGameplayAbilitySpecHandle& SpecHandle : InputHeldSpecHandles)
233
+ {
234
+ if (const FGameplayAbilitySpec* AbilitySpec = FindAbilitySpecFromHandle(SpecHandle))
235
+ {
236
+ if (AbilitySpec->Ability && !AbilitySpec->IsActive())
237
+ {
238
+ const ULyraGameplayAbility* LyraAbilityCDO = Cast<ULyraGameplayAbility>(AbilitySpec->Ability);
239
+ if (LyraAbilityCDO && LyraAbilityCDO->GetActivationPolicy() == ELyraAbilityActivationPolicy::WhileInputActive)
240
+ {
241
+ AbilitiesToActivate.AddUnique(AbilitySpec->Handle);
242
+ }
243
+ }
244
+ }
245
+ }
246
+
247
+ //
248
+ // Process all abilities that had their input pressed this frame.
249
+ //
250
+ for (const FGameplayAbilitySpecHandle& SpecHandle : InputPressedSpecHandles)
251
+ {
252
+ if (FGameplayAbilitySpec* AbilitySpec = FindAbilitySpecFromHandle(SpecHandle))
253
+ {
254
+ if (AbilitySpec->Ability)
255
+ {
256
+ AbilitySpec->InputPressed = true;
257
+
258
+ if (AbilitySpec->IsActive())
259
+ {
260
+ // Ability is active so pass along the input event.
261
+ AbilitySpecInputPressed(*AbilitySpec);
262
+ }
263
+ else
264
+ {
265
+ const ULyraGameplayAbility* LyraAbilityCDO = Cast<ULyraGameplayAbility>(AbilitySpec->Ability);
266
+
267
+ if (LyraAbilityCDO && LyraAbilityCDO->GetActivationPolicy() == ELyraAbilityActivationPolicy::OnInputTriggered)
268
+ {
269
+ AbilitiesToActivate.AddUnique(AbilitySpec->Handle);
270
+ }
271
+ }
272
+ }
273
+ }
274
+ }
275
+
276
+ //
277
+ // Try to activate all the abilities that are from presses and holds.
278
+ // We do it all at once so that held inputs don't activate the ability
279
+ // and then also send a input event to the ability because of the press.
280
+ //
281
+ for (const FGameplayAbilitySpecHandle& AbilitySpecHandle : AbilitiesToActivate)
282
+ {
283
+ TryActivateAbility(AbilitySpecHandle);
284
+ }
285
+
286
+ //
287
+ // Process all abilities that had their input released this frame.
288
+ //
289
+ for (const FGameplayAbilitySpecHandle& SpecHandle : InputReleasedSpecHandles)
290
+ {
291
+ if (FGameplayAbilitySpec* AbilitySpec = FindAbilitySpecFromHandle(SpecHandle))
292
+ {
293
+ if (AbilitySpec->Ability)
294
+ {
295
+ AbilitySpec->InputPressed = false;
296
+
297
+ if (AbilitySpec->IsActive())
298
+ {
299
+ // Ability is active so pass along the input event.
300
+ AbilitySpecInputReleased(*AbilitySpec);
301
+ }
302
+ }
303
+ }
304
+ }
305
+
306
+ //
307
+ // Clear the cached ability handles.
308
+ //
309
+ InputPressedSpecHandles.Reset();
310
+ InputReleasedSpecHandles.Reset();
311
+ }
312
+
313
+ void ULyraAbilitySystemComponent::ClearAbilityInput()
314
+ {
315
+ InputPressedSpecHandles.Reset();
316
+ InputReleasedSpecHandles.Reset();
317
+ InputHeldSpecHandles.Reset();
318
+ }
319
+
320
+ void ULyraAbilitySystemComponent::NotifyAbilityActivated(const FGameplayAbilitySpecHandle Handle, UGameplayAbility* Ability)
321
+ {
322
+ Super::NotifyAbilityActivated(Handle, Ability);
323
+
324
+ if (ULyraGameplayAbility* LyraAbility = Cast<ULyraGameplayAbility>(Ability))
325
+ {
326
+ AddAbilityToActivationGroup(LyraAbility->GetActivationGroup(), LyraAbility);
327
+ }
328
+ }
329
+
330
+ void ULyraAbilitySystemComponent::NotifyAbilityFailed(const FGameplayAbilitySpecHandle Handle, UGameplayAbility* Ability, const FGameplayTagContainer& FailureReason)
331
+ {
332
+ Super::NotifyAbilityFailed(Handle, Ability, FailureReason);
333
+
334
+ if (APawn* Avatar = Cast<APawn>(GetAvatarActor()))
335
+ {
336
+ if (!Avatar->IsLocallyControlled() && Ability->IsSupportedForNetworking())
337
+ {
338
+ ClientNotifyAbilityFailed(Ability, FailureReason);
339
+ return;
340
+ }
341
+ }
342
+
343
+ HandleAbilityFailed(Ability, FailureReason);
344
+ }
345
+
346
+ void ULyraAbilitySystemComponent::NotifyAbilityEnded(FGameplayAbilitySpecHandle Handle, UGameplayAbility* Ability, bool bWasCancelled)
347
+ {
348
+ Super::NotifyAbilityEnded(Handle, Ability, bWasCancelled);
349
+
350
+ if (ULyraGameplayAbility* LyraAbility = Cast<ULyraGameplayAbility>(Ability))
351
+ {
352
+ RemoveAbilityFromActivationGroup(LyraAbility->GetActivationGroup(), LyraAbility);
353
+ }
354
+ }
355
+
356
+ void ULyraAbilitySystemComponent::ApplyAbilityBlockAndCancelTags(const FGameplayTagContainer& AbilityTags, UGameplayAbility* RequestingAbility, bool bEnableBlockTags, const FGameplayTagContainer& BlockTags, bool bExecuteCancelTags, const FGameplayTagContainer& CancelTags)
357
+ {
358
+ FGameplayTagContainer ModifiedBlockTags = BlockTags;
359
+ FGameplayTagContainer ModifiedCancelTags = CancelTags;
360
+
361
+ if (TagRelationshipMapping)
362
+ {
363
+ // Use the mapping to expand the ability tags into block and cancel tag
364
+ TagRelationshipMapping->GetAbilityTagsToBlockAndCancel(AbilityTags, &ModifiedBlockTags, &ModifiedCancelTags);
365
+ }
366
+
367
+ Super::ApplyAbilityBlockAndCancelTags(AbilityTags, RequestingAbility, bEnableBlockTags, ModifiedBlockTags, bExecuteCancelTags, ModifiedCancelTags);
368
+
369
+ //@TODO: Apply any special logic like blocking input or movement
370
+ }
371
+
372
+ void ULyraAbilitySystemComponent::HandleChangeAbilityCanBeCanceled(const FGameplayTagContainer& AbilityTags, UGameplayAbility* RequestingAbility, bool bCanBeCanceled)
373
+ {
374
+ Super::HandleChangeAbilityCanBeCanceled(AbilityTags, RequestingAbility, bCanBeCanceled);
375
+
376
+ //@TODO: Apply any special logic like blocking input or movement
377
+ }
378
+
379
+ void ULyraAbilitySystemComponent::GetAdditionalActivationTagRequirements(const FGameplayTagContainer& AbilityTags, FGameplayTagContainer& OutActivationRequired, FGameplayTagContainer& OutActivationBlocked) const
380
+ {
381
+ if (TagRelationshipMapping)
382
+ {
383
+ TagRelationshipMapping->GetRequiredAndBlockedActivationTags(AbilityTags, &OutActivationRequired, &OutActivationBlocked);
384
+ }
385
+ }
386
+
387
+ void ULyraAbilitySystemComponent::SetTagRelationshipMapping(ULyraAbilityTagRelationshipMapping* NewMapping)
388
+ {
389
+ TagRelationshipMapping = NewMapping;
390
+ }
391
+
392
+ void ULyraAbilitySystemComponent::ClientNotifyAbilityFailed_Implementation(const UGameplayAbility* Ability, const FGameplayTagContainer& FailureReason)
393
+ {
394
+ HandleAbilityFailed(Ability, FailureReason);
395
+ }
396
+
397
+ void ULyraAbilitySystemComponent::HandleAbilityFailed(const UGameplayAbility* Ability, const FGameplayTagContainer& FailureReason)
398
+ {
399
+ //UE_LOG(LogLyraAbilitySystem, Warning, TEXT("Ability %s failed to activate (tags: %s)"), *GetPathNameSafe(Ability), *FailureReason.ToString());
400
+
401
+ if (const ULyraGameplayAbility* LyraAbility = Cast<const ULyraGameplayAbility>(Ability))
402
+ {
403
+ LyraAbility->OnAbilityFailedToActivate(FailureReason);
404
+ }
405
+ }
406
+
407
+ bool ULyraAbilitySystemComponent::IsActivationGroupBlocked(ELyraAbilityActivationGroup Group) const
408
+ {
409
+ bool bBlocked = false;
410
+
411
+ switch (Group)
412
+ {
413
+ case ELyraAbilityActivationGroup::Independent:
414
+ // Independent abilities are never blocked.
415
+ bBlocked = false;
416
+ break;
417
+
418
+ case ELyraAbilityActivationGroup::Exclusive_Replaceable:
419
+ case ELyraAbilityActivationGroup::Exclusive_Blocking:
420
+ // Exclusive abilities can activate if nothing is blocking.
421
+ bBlocked = (ActivationGroupCounts[(uint8)ELyraAbilityActivationGroup::Exclusive_Blocking] > 0);
422
+ break;
423
+
424
+ default:
425
+ checkf(false, TEXT("IsActivationGroupBlocked: Invalid ActivationGroup [%d]\n"), (uint8)Group);
426
+ break;
427
+ }
428
+
429
+ return bBlocked;
430
+ }
431
+
432
+ void ULyraAbilitySystemComponent::AddAbilityToActivationGroup(ELyraAbilityActivationGroup Group, ULyraGameplayAbility* LyraAbility)
433
+ {
434
+ check(LyraAbility);
435
+ check(ActivationGroupCounts[(uint8)Group] < INT32_MAX);
436
+
437
+ ActivationGroupCounts[(uint8)Group]++;
438
+
439
+ const bool bReplicateCancelAbility = false;
440
+
441
+ switch (Group)
442
+ {
443
+ case ELyraAbilityActivationGroup::Independent:
444
+ // Independent abilities do not cancel any other abilities.
445
+ break;
446
+
447
+ case ELyraAbilityActivationGroup::Exclusive_Replaceable:
448
+ case ELyraAbilityActivationGroup::Exclusive_Blocking:
449
+ CancelActivationGroupAbilities(ELyraAbilityActivationGroup::Exclusive_Replaceable, LyraAbility, bReplicateCancelAbility);
450
+ break;
451
+
452
+ default:
453
+ checkf(false, TEXT("AddAbilityToActivationGroup: Invalid ActivationGroup [%d]\n"), (uint8)Group);
454
+ break;
455
+ }
456
+
457
+ const int32 ExclusiveCount = ActivationGroupCounts[(uint8)ELyraAbilityActivationGroup::Exclusive_Replaceable] + ActivationGroupCounts[(uint8)ELyraAbilityActivationGroup::Exclusive_Blocking];
458
+ if (!ensure(ExclusiveCount <= 1))
459
+ {
460
+ UE_LOG(LogLyraAbilitySystem, Error, TEXT("AddAbilityToActivationGroup: Multiple exclusive abilities are running."));
461
+ }
462
+ }
463
+
464
+ void ULyraAbilitySystemComponent::RemoveAbilityFromActivationGroup(ELyraAbilityActivationGroup Group, ULyraGameplayAbility* LyraAbility)
465
+ {
466
+ check(LyraAbility);
467
+ check(ActivationGroupCounts[(uint8)Group] > 0);
468
+
469
+ ActivationGroupCounts[(uint8)Group]--;
470
+ }
471
+
472
+ void ULyraAbilitySystemComponent::CancelActivationGroupAbilities(ELyraAbilityActivationGroup Group, ULyraGameplayAbility* IgnoreLyraAbility, bool bReplicateCancelAbility)
473
+ {
474
+ auto ShouldCancelFunc = [this, Group, IgnoreLyraAbility](const ULyraGameplayAbility* LyraAbility, FGameplayAbilitySpecHandle Handle)
475
+ {
476
+ return ((LyraAbility->GetActivationGroup() == Group) && (LyraAbility != IgnoreLyraAbility));
477
+ };
478
+
479
+ CancelAbilitiesByFunc(ShouldCancelFunc, bReplicateCancelAbility);
480
+ }
481
+
482
+ void ULyraAbilitySystemComponent::AddDynamicTagGameplayEffect(const FGameplayTag& Tag)
483
+ {
484
+ const TSubclassOf<UGameplayEffect> DynamicTagGE = ULyraAssetManager::GetSubclass(ULyraGameData::Get().DynamicTagGameplayEffect);
485
+ if (!DynamicTagGE)
486
+ {
487
+ UE_LOG(LogLyraAbilitySystem, Warning, TEXT("AddDynamicTagGameplayEffect: Unable to find DynamicTagGameplayEffect [%s]."), *ULyraGameData::Get().DynamicTagGameplayEffect.GetAssetName());
488
+ return;
489
+ }
490
+
491
+ const FGameplayEffectSpecHandle SpecHandle = MakeOutgoingSpec(DynamicTagGE, 1.0f, MakeEffectContext());
492
+ FGameplayEffectSpec* Spec = SpecHandle.Data.Get();
493
+
494
+ if (!Spec)
495
+ {
496
+ UE_LOG(LogLyraAbilitySystem, Warning, TEXT("AddDynamicTagGameplayEffect: Unable to make outgoing spec for [%s]."), *GetNameSafe(DynamicTagGE));
497
+ return;
498
+ }
499
+
500
+ Spec->DynamicGrantedTags.AddTag(Tag);
501
+
502
+ ApplyGameplayEffectSpecToSelf(*Spec);
503
+ }
504
+
505
+ void ULyraAbilitySystemComponent::RemoveDynamicTagGameplayEffect(const FGameplayTag& Tag)
506
+ {
507
+ const TSubclassOf<UGameplayEffect> DynamicTagGE = ULyraAssetManager::GetSubclass(ULyraGameData::Get().DynamicTagGameplayEffect);
508
+ if (!DynamicTagGE)
509
+ {
510
+ UE_LOG(LogLyraAbilitySystem, Warning, TEXT("RemoveDynamicTagGameplayEffect: Unable to find gameplay effect [%s]."), *ULyraGameData::Get().DynamicTagGameplayEffect.GetAssetName());
511
+ return;
512
+ }
513
+
514
+ FGameplayEffectQuery Query = FGameplayEffectQuery::MakeQuery_MatchAnyOwningTags(FGameplayTagContainer(Tag));
515
+ Query.EffectDefinition = DynamicTagGE;
516
+
517
+ RemoveActiveEffects(Query);
518
+ }
519
+
520
+ void ULyraAbilitySystemComponent::GetAbilityTargetData(const FGameplayAbilitySpecHandle AbilityHandle, FGameplayAbilityActivationInfo ActivationInfo, FGameplayAbilityTargetDataHandle& OutTargetDataHandle)
521
+ {
522
+ TSharedPtr<FAbilityReplicatedDataCache> ReplicatedData = AbilityTargetDataMap.Find(FGameplayAbilitySpecHandleAndPredictionKey(AbilityHandle, ActivationInfo.GetActivationPredictionKey()));
523
+ if (ReplicatedData.IsValid())
524
+ {
525
+ OutTargetDataHandle = ReplicatedData->TargetData;
526
+ }
527
+ }
528
+
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySystemComponent.h ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "Abilities/LyraGameplayAbility.h"
6
+ #include "AbilitySystemComponent.h"
7
+ #include "NativeGameplayTags.h"
8
+
9
+ #include "LyraAbilitySystemComponent.generated.h"
10
+
11
+ #define UE_API LYRAGAME_API
12
+
13
+ class AActor;
14
+ class UGameplayAbility;
15
+ class ULyraAbilityTagRelationshipMapping;
16
+ class UObject;
17
+ struct FFrame;
18
+ struct FGameplayAbilityTargetDataHandle;
19
+
20
+ LYRAGAME_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(TAG_Gameplay_AbilityInputBlocked);
21
+
22
+ /**
23
+ * ULyraAbilitySystemComponent
24
+ *
25
+ * Base ability system component class used by this project.
26
+ */
27
+ UCLASS(MinimalAPI)
28
+ class ULyraAbilitySystemComponent : public UAbilitySystemComponent
29
+ {
30
+ GENERATED_BODY()
31
+
32
+ public:
33
+
34
+ UE_API ULyraAbilitySystemComponent(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
35
+
36
+ //~UActorComponent interface
37
+ UE_API virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
38
+ //~End of UActorComponent interface
39
+
40
+ UE_API virtual void InitAbilityActorInfo(AActor* InOwnerActor, AActor* InAvatarActor) override;
41
+
42
+ typedef TFunctionRef<bool(const ULyraGameplayAbility* LyraAbility, FGameplayAbilitySpecHandle Handle)> TShouldCancelAbilityFunc;
43
+ UE_API void CancelAbilitiesByFunc(TShouldCancelAbilityFunc ShouldCancelFunc, bool bReplicateCancelAbility);
44
+
45
+ UE_API void CancelInputActivatedAbilities(bool bReplicateCancelAbility);
46
+
47
+ UE_API void AbilityInputTagPressed(const FGameplayTag& InputTag);
48
+ UE_API void AbilityInputTagReleased(const FGameplayTag& InputTag);
49
+
50
+ UE_API void ProcessAbilityInput(float DeltaTime, bool bGamePaused);
51
+ UE_API void ClearAbilityInput();
52
+
53
+ UE_API bool IsActivationGroupBlocked(ELyraAbilityActivationGroup Group) const;
54
+ UE_API void AddAbilityToActivationGroup(ELyraAbilityActivationGroup Group, ULyraGameplayAbility* LyraAbility);
55
+ UE_API void RemoveAbilityFromActivationGroup(ELyraAbilityActivationGroup Group, ULyraGameplayAbility* LyraAbility);
56
+ UE_API void CancelActivationGroupAbilities(ELyraAbilityActivationGroup Group, ULyraGameplayAbility* IgnoreLyraAbility, bool bReplicateCancelAbility);
57
+
58
+ // Uses a gameplay effect to add the specified dynamic granted tag.
59
+ UE_API void AddDynamicTagGameplayEffect(const FGameplayTag& Tag);
60
+
61
+ // Removes all active instances of the gameplay effect that was used to add the specified dynamic granted tag.
62
+ UE_API void RemoveDynamicTagGameplayEffect(const FGameplayTag& Tag);
63
+
64
+ /** Gets the ability target data associated with the given ability handle and activation info */
65
+ UE_API void GetAbilityTargetData(const FGameplayAbilitySpecHandle AbilityHandle, FGameplayAbilityActivationInfo ActivationInfo, FGameplayAbilityTargetDataHandle& OutTargetDataHandle);
66
+
67
+ /** Sets the current tag relationship mapping, if null it will clear it out */
68
+ UE_API void SetTagRelationshipMapping(ULyraAbilityTagRelationshipMapping* NewMapping);
69
+
70
+ /** Looks at ability tags and gathers additional required and blocking tags */
71
+ UE_API void GetAdditionalActivationTagRequirements(const FGameplayTagContainer& AbilityTags, FGameplayTagContainer& OutActivationRequired, FGameplayTagContainer& OutActivationBlocked) const;
72
+
73
+ UE_API void TryActivateAbilitiesOnSpawn();
74
+
75
+ protected:
76
+
77
+ UE_API virtual void AbilitySpecInputPressed(FGameplayAbilitySpec& Spec) override;
78
+ UE_API virtual void AbilitySpecInputReleased(FGameplayAbilitySpec& Spec) override;
79
+
80
+ UE_API virtual void NotifyAbilityActivated(const FGameplayAbilitySpecHandle Handle, UGameplayAbility* Ability) override;
81
+ UE_API virtual void NotifyAbilityFailed(const FGameplayAbilitySpecHandle Handle, UGameplayAbility* Ability, const FGameplayTagContainer& FailureReason) override;
82
+ UE_API virtual void NotifyAbilityEnded(FGameplayAbilitySpecHandle Handle, UGameplayAbility* Ability, bool bWasCancelled) override;
83
+ UE_API virtual void ApplyAbilityBlockAndCancelTags(const FGameplayTagContainer& AbilityTags, UGameplayAbility* RequestingAbility, bool bEnableBlockTags, const FGameplayTagContainer& BlockTags, bool bExecuteCancelTags, const FGameplayTagContainer& CancelTags) override;
84
+ UE_API virtual void HandleChangeAbilityCanBeCanceled(const FGameplayTagContainer& AbilityTags, UGameplayAbility* RequestingAbility, bool bCanBeCanceled) override;
85
+
86
+ /** Notify client that an ability failed to activate */
87
+ UFUNCTION(Client, Unreliable)
88
+ UE_API void ClientNotifyAbilityFailed(const UGameplayAbility* Ability, const FGameplayTagContainer& FailureReason);
89
+
90
+ UE_API void HandleAbilityFailed(const UGameplayAbility* Ability, const FGameplayTagContainer& FailureReason);
91
+ protected:
92
+
93
+ // If set, this table is used to look up tag relationships for activate and cancel
94
+ UPROPERTY()
95
+ TObjectPtr<ULyraAbilityTagRelationshipMapping> TagRelationshipMapping;
96
+
97
+ // Handles to abilities that had their input pressed this frame.
98
+ TArray<FGameplayAbilitySpecHandle> InputPressedSpecHandles;
99
+
100
+ // Handles to abilities that had their input released this frame.
101
+ TArray<FGameplayAbilitySpecHandle> InputReleasedSpecHandles;
102
+
103
+ // Handles to abilities that have their input held.
104
+ TArray<FGameplayAbilitySpecHandle> InputHeldSpecHandles;
105
+
106
+ // Number of abilities running in each activation group.
107
+ int32 ActivationGroupCounts[(uint8)ELyraAbilityActivationGroup::MAX];
108
+ };
109
+
110
+ #undef UE_API
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySystemGlobals.cpp ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraAbilitySystemGlobals.h"
4
+
5
+ #include "LyraGameplayEffectContext.h"
6
+
7
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraAbilitySystemGlobals)
8
+
9
+ struct FGameplayEffectContext;
10
+
11
+ ULyraAbilitySystemGlobals::ULyraAbilitySystemGlobals(const FObjectInitializer& ObjectInitializer)
12
+ : Super(ObjectInitializer)
13
+ {
14
+ }
15
+
16
+ FGameplayEffectContext* ULyraAbilitySystemGlobals::AllocGameplayEffectContext() const
17
+ {
18
+ return new FLyraGameplayEffectContext();
19
+ }
20
+
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilitySystemGlobals.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "AbilitySystemGlobals.h"
6
+
7
+ #include "LyraAbilitySystemGlobals.generated.h"
8
+
9
+ class UObject;
10
+ struct FGameplayEffectContext;
11
+
12
+ UCLASS(Config=Game)
13
+ class ULyraAbilitySystemGlobals : public UAbilitySystemGlobals
14
+ {
15
+ GENERATED_UCLASS_BODY()
16
+
17
+ //~UAbilitySystemGlobals interface
18
+ virtual FGameplayEffectContext* AllocGameplayEffectContext() const override;
19
+ //~End of UAbilitySystemGlobals interface
20
+ };
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilityTagRelationshipMapping.cpp ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "AbilitySystem/LyraAbilityTagRelationshipMapping.h"
4
+
5
+
6
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraAbilityTagRelationshipMapping)
7
+
8
+ void ULyraAbilityTagRelationshipMapping::GetAbilityTagsToBlockAndCancel(const FGameplayTagContainer& AbilityTags, FGameplayTagContainer* OutTagsToBlock, FGameplayTagContainer* OutTagsToCancel) const
9
+ {
10
+ // Simple iteration for now
11
+ for (int32 i = 0; i < AbilityTagRelationships.Num(); i++)
12
+ {
13
+ const FLyraAbilityTagRelationship& Tags = AbilityTagRelationships[i];
14
+ if (AbilityTags.HasTag(Tags.AbilityTag))
15
+ {
16
+ if (OutTagsToBlock)
17
+ {
18
+ OutTagsToBlock->AppendTags(Tags.AbilityTagsToBlock);
19
+ }
20
+ if (OutTagsToCancel)
21
+ {
22
+ OutTagsToCancel->AppendTags(Tags.AbilityTagsToCancel);
23
+ }
24
+ }
25
+ }
26
+ }
27
+
28
+ void ULyraAbilityTagRelationshipMapping::GetRequiredAndBlockedActivationTags(const FGameplayTagContainer& AbilityTags, FGameplayTagContainer* OutActivationRequired, FGameplayTagContainer* OutActivationBlocked) const
29
+ {
30
+ // Simple iteration for now
31
+ for (int32 i = 0; i < AbilityTagRelationships.Num(); i++)
32
+ {
33
+ const FLyraAbilityTagRelationship& Tags = AbilityTagRelationships[i];
34
+ if (AbilityTags.HasTag(Tags.AbilityTag))
35
+ {
36
+ if (OutActivationRequired)
37
+ {
38
+ OutActivationRequired->AppendTags(Tags.ActivationRequiredTags);
39
+ }
40
+ if (OutActivationBlocked)
41
+ {
42
+ OutActivationBlocked->AppendTags(Tags.ActivationBlockedTags);
43
+ }
44
+ }
45
+ }
46
+ }
47
+
48
+ bool ULyraAbilityTagRelationshipMapping::IsAbilityCancelledByTag(const FGameplayTagContainer& AbilityTags, const FGameplayTag& ActionTag) const
49
+ {
50
+ // Simple iteration for now
51
+ for (int32 i = 0; i < AbilityTagRelationships.Num(); i++)
52
+ {
53
+ const FLyraAbilityTagRelationship& Tags = AbilityTagRelationships[i];
54
+
55
+ if (Tags.AbilityTag == ActionTag && Tags.AbilityTagsToCancel.HasAny(AbilityTags))
56
+ {
57
+ return true;
58
+ }
59
+ }
60
+
61
+ return false;
62
+ }
63
+
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraAbilityTagRelationshipMapping.h ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "Engine/DataAsset.h"
6
+ #include "GameplayTagContainer.h"
7
+
8
+ #include "LyraAbilityTagRelationshipMapping.generated.h"
9
+
10
+ class UObject;
11
+
12
+ /** Struct that defines the relationship between different ability tags */
13
+ USTRUCT()
14
+ struct FLyraAbilityTagRelationship
15
+ {
16
+ GENERATED_BODY()
17
+
18
+ /** The tag that this container relationship is about. Single tag, but abilities can have multiple of these */
19
+ UPROPERTY(EditAnywhere, Category = Ability, meta = (Categories = "Gameplay.Action"))
20
+ FGameplayTag AbilityTag;
21
+
22
+ /** The other ability tags that will be blocked by any ability using this tag */
23
+ UPROPERTY(EditAnywhere, Category = Ability)
24
+ FGameplayTagContainer AbilityTagsToBlock;
25
+
26
+ /** The other ability tags that will be canceled by any ability using this tag */
27
+ UPROPERTY(EditAnywhere, Category = Ability)
28
+ FGameplayTagContainer AbilityTagsToCancel;
29
+
30
+ /** If an ability has the tag, this is implicitly added to the activation required tags of the ability */
31
+ UPROPERTY(EditAnywhere, Category = Ability)
32
+ FGameplayTagContainer ActivationRequiredTags;
33
+
34
+ /** If an ability has the tag, this is implicitly added to the activation blocked tags of the ability */
35
+ UPROPERTY(EditAnywhere, Category = Ability)
36
+ FGameplayTagContainer ActivationBlockedTags;
37
+ };
38
+
39
+
40
+ /** Mapping of how ability tags block or cancel other abilities */
41
+ UCLASS()
42
+ class ULyraAbilityTagRelationshipMapping : public UDataAsset
43
+ {
44
+ GENERATED_BODY()
45
+
46
+ private:
47
+ /** The list of relationships between different gameplay tags (which ones block or cancel others) */
48
+ UPROPERTY(EditAnywhere, Category = Ability, meta=(TitleProperty="AbilityTag"))
49
+ TArray<FLyraAbilityTagRelationship> AbilityTagRelationships;
50
+
51
+ public:
52
+ /** Given a set of ability tags, parse the tag relationship and fill out tags to block and cancel */
53
+ void GetAbilityTagsToBlockAndCancel(const FGameplayTagContainer& AbilityTags, FGameplayTagContainer* OutTagsToBlock, FGameplayTagContainer* OutTagsToCancel) const;
54
+
55
+ /** Given a set of ability tags, add additional required and blocking tags */
56
+ void GetRequiredAndBlockedActivationTags(const FGameplayTagContainer& AbilityTags, FGameplayTagContainer* OutActivationRequired, FGameplayTagContainer* OutActivationBlocked) const;
57
+
58
+ /** Returns true if the specified ability tags are canceled by the passed in action tag */
59
+ bool IsAbilityCancelledByTag(const FGameplayTagContainer& AbilityTags, const FGameplayTag& ActionTag) const;
60
+ };
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGameplayAbilityTargetData_SingleTargetHit.cpp ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraGameplayAbilityTargetData_SingleTargetHit.h"
4
+
5
+ #include "LyraGameplayEffectContext.h"
6
+
7
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraGameplayAbilityTargetData_SingleTargetHit)
8
+
9
+ struct FGameplayEffectContextHandle;
10
+
11
+ //////////////////////////////////////////////////////////////////////
12
+
13
+ void FLyraGameplayAbilityTargetData_SingleTargetHit::AddTargetDataToContext(FGameplayEffectContextHandle& Context, bool bIncludeActorArray) const
14
+ {
15
+ FGameplayAbilityTargetData_SingleTargetHit::AddTargetDataToContext(Context, bIncludeActorArray);
16
+
17
+ // Add game-specific data
18
+ if (FLyraGameplayEffectContext* TypedContext = FLyraGameplayEffectContext::ExtractEffectContext(Context))
19
+ {
20
+ TypedContext->CartridgeID = CartridgeID;
21
+ }
22
+ }
23
+
24
+ bool FLyraGameplayAbilityTargetData_SingleTargetHit::NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess)
25
+ {
26
+ FGameplayAbilityTargetData_SingleTargetHit::NetSerialize(Ar, Map, bOutSuccess);
27
+
28
+ Ar << CartridgeID;
29
+
30
+ return true;
31
+ }
32
+
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGameplayAbilityTargetData_SingleTargetHit.h ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "Abilities/GameplayAbilityTargetTypes.h"
6
+
7
+ #include "LyraGameplayAbilityTargetData_SingleTargetHit.generated.h"
8
+
9
+ class FArchive;
10
+ struct FGameplayEffectContextHandle;
11
+
12
+
13
+ /** Game-specific additions to SingleTargetHit tracking */
14
+ USTRUCT()
15
+ struct FLyraGameplayAbilityTargetData_SingleTargetHit : public FGameplayAbilityTargetData_SingleTargetHit
16
+ {
17
+ GENERATED_BODY()
18
+
19
+ FLyraGameplayAbilityTargetData_SingleTargetHit()
20
+ : CartridgeID(-1)
21
+ { }
22
+
23
+ virtual void AddTargetDataToContext(FGameplayEffectContextHandle& Context, bool bIncludeActorArray) const override;
24
+
25
+ /** ID to allow the identification of multiple bullets that were part of the same cartridge */
26
+ UPROPERTY()
27
+ int32 CartridgeID;
28
+
29
+ bool NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess);
30
+
31
+ virtual UScriptStruct* GetScriptStruct() const override
32
+ {
33
+ return FLyraGameplayAbilityTargetData_SingleTargetHit::StaticStruct();
34
+ }
35
+ };
36
+
37
+ template<>
38
+ struct TStructOpsTypeTraits<FLyraGameplayAbilityTargetData_SingleTargetHit> : public TStructOpsTypeTraitsBase2<FLyraGameplayAbilityTargetData_SingleTargetHit>
39
+ {
40
+ enum
41
+ {
42
+ WithNetSerializer = true // For now this is REQUIRED for FGameplayAbilityTargetDataHandle net serialization to work
43
+ };
44
+ };
45
+
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGameplayCueManager.cpp ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraGameplayCueManager.h"
4
+ #include "Engine/AssetManager.h"
5
+ #include "LyraLogChannels.h"
6
+ #include "GameplayCueSet.h"
7
+ #include "AbilitySystemGlobals.h"
8
+ #include "GameplayTagsManager.h"
9
+ #include "UObject/UObjectThreadContext.h"
10
+ #include "Async/Async.h"
11
+
12
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraGameplayCueManager)
13
+
14
+ //////////////////////////////////////////////////////////////////////
15
+
16
+ enum class ELyraEditorLoadMode
17
+ {
18
+ // Loads all cues upfront; longer loading speed in the editor but short PIE times and effects never fail to play
19
+ LoadUpfront,
20
+
21
+ // Outside of editor: Async loads as cue tag are registered
22
+ // In editor: Async loads when cues are invoked
23
+ // Note: This can cause some 'why didn't I see the effect for X' issues in PIE and is good for iteration speed but otherwise bad for designers
24
+ PreloadAsCuesAreReferenced_GameOnly,
25
+
26
+ // Async loads as cue tag are registered
27
+ PreloadAsCuesAreReferenced
28
+ };
29
+
30
+ namespace LyraGameplayCueManagerCvars
31
+ {
32
+ static FAutoConsoleCommand CVarDumpGameplayCues(
33
+ TEXT("Lyra.DumpGameplayCues"),
34
+ TEXT("Shows all assets that were loaded via LyraGameplayCueManager and are currently in memory."),
35
+ FConsoleCommandWithArgsDelegate::CreateStatic(ULyraGameplayCueManager::DumpGameplayCues));
36
+
37
+ static ELyraEditorLoadMode LoadMode = ELyraEditorLoadMode::LoadUpfront;
38
+ }
39
+
40
+ const bool bPreloadEvenInEditor = true;
41
+
42
+ //////////////////////////////////////////////////////////////////////
43
+
44
+ struct FGameplayCueTagThreadSynchronizeGraphTask : public FAsyncGraphTaskBase
45
+ {
46
+ TFunction<void()> TheTask;
47
+ FGameplayCueTagThreadSynchronizeGraphTask(TFunction<void()>&& Task) : TheTask(MoveTemp(Task)) { }
48
+ void DoTask(ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent) { TheTask(); }
49
+ ENamedThreads::Type GetDesiredThread() { return ENamedThreads::GameThread; }
50
+ };
51
+
52
+ //////////////////////////////////////////////////////////////////////
53
+
54
+ ULyraGameplayCueManager::ULyraGameplayCueManager(const FObjectInitializer& ObjectInitializer)
55
+ : Super(ObjectInitializer)
56
+ {
57
+ }
58
+
59
+ ULyraGameplayCueManager* ULyraGameplayCueManager::Get()
60
+ {
61
+ return Cast<ULyraGameplayCueManager>(UAbilitySystemGlobals::Get().GetGameplayCueManager());
62
+ }
63
+
64
+ void ULyraGameplayCueManager::OnCreated()
65
+ {
66
+ Super::OnCreated();
67
+
68
+ UpdateDelayLoadDelegateListeners();
69
+ }
70
+
71
+ void ULyraGameplayCueManager::LoadAlwaysLoadedCues()
72
+ {
73
+ if (ShouldDelayLoadGameplayCues())
74
+ {
75
+ UGameplayTagsManager& TagManager = UGameplayTagsManager::Get();
76
+
77
+ //@TODO: Try to collect these by filtering GameplayCue. tags out of native gameplay tags?
78
+ TArray<FName> AdditionalAlwaysLoadedCueTags;
79
+
80
+ for (const FName& CueTagName : AdditionalAlwaysLoadedCueTags)
81
+ {
82
+ FGameplayTag CueTag = TagManager.RequestGameplayTag(CueTagName, /*ErrorIfNotFound=*/ false);
83
+ if (CueTag.IsValid())
84
+ {
85
+ ProcessTagToPreload(CueTag, nullptr);
86
+ }
87
+ else
88
+ {
89
+ UE_LOG(LogLyra, Warning, TEXT("ULyraGameplayCueManager::AdditionalAlwaysLoadedCueTags contains invalid tag %s"), *CueTagName.ToString());
90
+ }
91
+ }
92
+ }
93
+ }
94
+
95
+ bool ULyraGameplayCueManager::ShouldAsyncLoadRuntimeObjectLibraries() const
96
+ {
97
+ switch (LyraGameplayCueManagerCvars::LoadMode)
98
+ {
99
+ case ELyraEditorLoadMode::LoadUpfront:
100
+ return true;
101
+ case ELyraEditorLoadMode::PreloadAsCuesAreReferenced_GameOnly:
102
+ #if WITH_EDITOR
103
+ if (GIsEditor)
104
+ {
105
+ return false;
106
+ }
107
+ #endif
108
+ break;
109
+ case ELyraEditorLoadMode::PreloadAsCuesAreReferenced:
110
+ break;
111
+ }
112
+
113
+ return !ShouldDelayLoadGameplayCues();
114
+ }
115
+
116
+ bool ULyraGameplayCueManager::ShouldSyncLoadMissingGameplayCues() const
117
+ {
118
+ return false;
119
+ }
120
+
121
+ bool ULyraGameplayCueManager::ShouldAsyncLoadMissingGameplayCues() const
122
+ {
123
+ return true;
124
+ }
125
+
126
+ void ULyraGameplayCueManager::DumpGameplayCues(const TArray<FString>& Args)
127
+ {
128
+ ULyraGameplayCueManager* GCM = Cast<ULyraGameplayCueManager>(UAbilitySystemGlobals::Get().GetGameplayCueManager());
129
+ if (!GCM)
130
+ {
131
+ UE_LOG(LogLyra, Error, TEXT("DumpGameplayCues failed. No ULyraGameplayCueManager found."));
132
+ return;
133
+ }
134
+
135
+ const bool bIncludeRefs = Args.Contains(TEXT("Refs"));
136
+
137
+ UE_LOG(LogLyra, Log, TEXT("=========== Dumping Always Loaded Gameplay Cue Notifies ==========="));
138
+ for (UClass* CueClass : GCM->AlwaysLoadedCues)
139
+ {
140
+ UE_LOG(LogLyra, Log, TEXT(" %s"), *GetPathNameSafe(CueClass));
141
+ }
142
+
143
+ UE_LOG(LogLyra, Log, TEXT("=========== Dumping Preloaded Gameplay Cue Notifies ==========="));
144
+ for (UClass* CueClass : GCM->PreloadedCues)
145
+ {
146
+ TSet<FObjectKey>* ReferencerSet = GCM->PreloadedCueReferencers.Find(CueClass);
147
+ int32 NumRefs = ReferencerSet ? ReferencerSet->Num() : 0;
148
+ UE_LOG(LogLyra, Log, TEXT(" %s (%d refs)"), *GetPathNameSafe(CueClass), NumRefs);
149
+ if (bIncludeRefs && ReferencerSet)
150
+ {
151
+ for (const FObjectKey& Ref : *ReferencerSet)
152
+ {
153
+ UObject* RefObject = Ref.ResolveObjectPtr();
154
+ UE_LOG(LogLyra, Log, TEXT(" ^- %s"), *GetPathNameSafe(RefObject));
155
+ }
156
+ }
157
+ }
158
+
159
+ UE_LOG(LogLyra, Log, TEXT("=========== Dumping Gameplay Cue Notifies loaded on demand ==========="));
160
+ int32 NumMissingCuesLoaded = 0;
161
+ if (GCM->RuntimeGameplayCueObjectLibrary.CueSet)
162
+ {
163
+ for (const FGameplayCueNotifyData& CueData : GCM->RuntimeGameplayCueObjectLibrary.CueSet->GameplayCueData)
164
+ {
165
+ if (CueData.LoadedGameplayCueClass && !GCM->AlwaysLoadedCues.Contains(CueData.LoadedGameplayCueClass) && !GCM->PreloadedCues.Contains(CueData.LoadedGameplayCueClass))
166
+ {
167
+ NumMissingCuesLoaded++;
168
+ UE_LOG(LogLyra, Log, TEXT(" %s"), *CueData.LoadedGameplayCueClass->GetPathName());
169
+ }
170
+ }
171
+ }
172
+
173
+ UE_LOG(LogLyra, Log, TEXT("=========== Gameplay Cue Notify summary ==========="));
174
+ UE_LOG(LogLyra, Log, TEXT(" ... %d cues in always loaded list"), GCM->AlwaysLoadedCues.Num());
175
+ UE_LOG(LogLyra, Log, TEXT(" ... %d cues in preloaded list"), GCM->PreloadedCues.Num());
176
+ UE_LOG(LogLyra, Log, TEXT(" ... %d cues loaded on demand"), NumMissingCuesLoaded);
177
+ UE_LOG(LogLyra, Log, TEXT(" ... %d cues in total"), GCM->AlwaysLoadedCues.Num() + GCM->PreloadedCues.Num() + NumMissingCuesLoaded);
178
+ }
179
+
180
+ void ULyraGameplayCueManager::OnGameplayTagLoaded(const FGameplayTag& Tag)
181
+ {
182
+ FScopeLock ScopeLock(&LoadedGameplayTagsToProcessCS);
183
+ bool bStartTask = LoadedGameplayTagsToProcess.Num() == 0;
184
+ FUObjectSerializeContext* LoadContext = FUObjectThreadContext::Get().GetSerializeContext();
185
+ UObject* OwningObject = LoadContext ? LoadContext->SerializedObject : nullptr;
186
+ LoadedGameplayTagsToProcess.Emplace(Tag, OwningObject);
187
+ if (bStartTask)
188
+ {
189
+ TGraphTask<FGameplayCueTagThreadSynchronizeGraphTask>::CreateTask().ConstructAndDispatchWhenReady([]()
190
+ {
191
+ if (GIsRunning)
192
+ {
193
+ if (ULyraGameplayCueManager* StrongThis = Get())
194
+ {
195
+ // If we are garbage collecting we cannot call StaticFindObject (or a few other static uobject functions), so we'll just wait until the GC is over and process the tags then
196
+ if (IsGarbageCollecting())
197
+ {
198
+ StrongThis->bProcessLoadedTagsAfterGC = true;
199
+ }
200
+ else
201
+ {
202
+ StrongThis->ProcessLoadedTags();
203
+ }
204
+ }
205
+ }
206
+ });
207
+ }
208
+ }
209
+
210
+ void ULyraGameplayCueManager::HandlePostGarbageCollect()
211
+ {
212
+ if (bProcessLoadedTagsAfterGC)
213
+ {
214
+ ProcessLoadedTags();
215
+ }
216
+ bProcessLoadedTagsAfterGC = false;
217
+ }
218
+
219
+ void ULyraGameplayCueManager::ProcessLoadedTags()
220
+ {
221
+ TArray<FLoadedGameplayTagToProcessData> TaskLoadedGameplayTagsToProcess;
222
+ {
223
+ // Lock LoadedGameplayTagsToProcess just long enough to make a copy and clear
224
+ FScopeLock TaskScopeLock(&LoadedGameplayTagsToProcessCS);
225
+ TaskLoadedGameplayTagsToProcess = LoadedGameplayTagsToProcess;
226
+ LoadedGameplayTagsToProcess.Empty();
227
+ }
228
+
229
+ // This might return during shutdown, and we don't want to proceed if that is the case
230
+ if (GIsRunning)
231
+ {
232
+ if (RuntimeGameplayCueObjectLibrary.CueSet)
233
+ {
234
+ for (const FLoadedGameplayTagToProcessData& LoadedTagData : TaskLoadedGameplayTagsToProcess)
235
+ {
236
+ if (RuntimeGameplayCueObjectLibrary.CueSet->GameplayCueDataMap.Contains(LoadedTagData.Tag))
237
+ {
238
+ if (!LoadedTagData.WeakOwner.IsStale())
239
+ {
240
+ ProcessTagToPreload(LoadedTagData.Tag, LoadedTagData.WeakOwner.Get());
241
+ }
242
+ }
243
+ }
244
+ }
245
+ else
246
+ {
247
+ UE_LOG(LogLyra, Warning, TEXT("ULyraGameplayCueManager::OnGameplayTagLoaded processed loaded tag(s) but RuntimeGameplayCueObjectLibrary.CueSet was null. Skipping processing."));
248
+ }
249
+ }
250
+ }
251
+
252
+ void ULyraGameplayCueManager::ProcessTagToPreload(const FGameplayTag& Tag, UObject* OwningObject)
253
+ {
254
+ switch (LyraGameplayCueManagerCvars::LoadMode)
255
+ {
256
+ case ELyraEditorLoadMode::LoadUpfront:
257
+ return;
258
+ case ELyraEditorLoadMode::PreloadAsCuesAreReferenced_GameOnly:
259
+ #if WITH_EDITOR
260
+ if (GIsEditor)
261
+ {
262
+ return;
263
+ }
264
+ #endif
265
+ break;
266
+ case ELyraEditorLoadMode::PreloadAsCuesAreReferenced:
267
+ break;
268
+ }
269
+
270
+ check(RuntimeGameplayCueObjectLibrary.CueSet);
271
+
272
+ int32* DataIdx = RuntimeGameplayCueObjectLibrary.CueSet->GameplayCueDataMap.Find(Tag);
273
+ if (DataIdx && RuntimeGameplayCueObjectLibrary.CueSet->GameplayCueData.IsValidIndex(*DataIdx))
274
+ {
275
+ const FGameplayCueNotifyData& CueData = RuntimeGameplayCueObjectLibrary.CueSet->GameplayCueData[*DataIdx];
276
+
277
+ UClass* LoadedGameplayCueClass = FindObject<UClass>(nullptr, *CueData.GameplayCueNotifyObj.ToString());
278
+ if (LoadedGameplayCueClass)
279
+ {
280
+ RegisterPreloadedCue(LoadedGameplayCueClass, OwningObject);
281
+ }
282
+ else
283
+ {
284
+ bool bAlwaysLoadedCue = OwningObject == nullptr;
285
+ TWeakObjectPtr<UObject> WeakOwner = OwningObject;
286
+ StreamableManager.RequestAsyncLoad(CueData.GameplayCueNotifyObj, FStreamableDelegate::CreateUObject(this, &ThisClass::OnPreloadCueComplete, CueData.GameplayCueNotifyObj, WeakOwner, bAlwaysLoadedCue), FStreamableManager::DefaultAsyncLoadPriority, false, false, TEXT("GameplayCueManager"));
287
+ }
288
+ }
289
+ }
290
+
291
+ void ULyraGameplayCueManager::OnPreloadCueComplete(FSoftObjectPath Path, TWeakObjectPtr<UObject> OwningObject, bool bAlwaysLoadedCue)
292
+ {
293
+ if (bAlwaysLoadedCue || OwningObject.IsValid())
294
+ {
295
+ if (UClass* LoadedGameplayCueClass = Cast<UClass>(Path.ResolveObject()))
296
+ {
297
+ RegisterPreloadedCue(LoadedGameplayCueClass, OwningObject.Get());
298
+ }
299
+ }
300
+ }
301
+
302
+ void ULyraGameplayCueManager::RegisterPreloadedCue(UClass* LoadedGameplayCueClass, UObject* OwningObject)
303
+ {
304
+ check(LoadedGameplayCueClass);
305
+
306
+ const bool bAlwaysLoadedCue = OwningObject == nullptr;
307
+ if (bAlwaysLoadedCue)
308
+ {
309
+ AlwaysLoadedCues.Add(LoadedGameplayCueClass);
310
+ PreloadedCues.Remove(LoadedGameplayCueClass);
311
+ PreloadedCueReferencers.Remove(LoadedGameplayCueClass);
312
+ }
313
+ else if ((OwningObject != LoadedGameplayCueClass) && (OwningObject != LoadedGameplayCueClass->GetDefaultObject()) && !AlwaysLoadedCues.Contains(LoadedGameplayCueClass))
314
+ {
315
+ PreloadedCues.Add(LoadedGameplayCueClass);
316
+ TSet<FObjectKey>& ReferencerSet = PreloadedCueReferencers.FindOrAdd(LoadedGameplayCueClass);
317
+ ReferencerSet.Add(OwningObject);
318
+ }
319
+ }
320
+
321
+ void ULyraGameplayCueManager::HandlePostLoadMap(UWorld* NewWorld)
322
+ {
323
+ if (RuntimeGameplayCueObjectLibrary.CueSet)
324
+ {
325
+ for (UClass* CueClass : AlwaysLoadedCues)
326
+ {
327
+ RuntimeGameplayCueObjectLibrary.CueSet->RemoveLoadedClass(CueClass);
328
+ }
329
+
330
+ for (UClass* CueClass : PreloadedCues)
331
+ {
332
+ RuntimeGameplayCueObjectLibrary.CueSet->RemoveLoadedClass(CueClass);
333
+ }
334
+ }
335
+
336
+ for (auto CueIt = PreloadedCues.CreateIterator(); CueIt; ++CueIt)
337
+ {
338
+ TSet<FObjectKey>& ReferencerSet = PreloadedCueReferencers.FindChecked(*CueIt);
339
+ for (auto RefIt = ReferencerSet.CreateIterator(); RefIt; ++RefIt)
340
+ {
341
+ if (!RefIt->ResolveObjectPtr())
342
+ {
343
+ RefIt.RemoveCurrent();
344
+ }
345
+ }
346
+ if (ReferencerSet.Num() == 0)
347
+ {
348
+ PreloadedCueReferencers.Remove(*CueIt);
349
+ CueIt.RemoveCurrent();
350
+ }
351
+ }
352
+ }
353
+
354
+ void ULyraGameplayCueManager::UpdateDelayLoadDelegateListeners()
355
+ {
356
+ UGameplayTagsManager::Get().OnGameplayTagLoadedDelegate.RemoveAll(this);
357
+ FCoreUObjectDelegates::GetPostGarbageCollect().RemoveAll(this);
358
+ FCoreUObjectDelegates::PostLoadMapWithWorld.RemoveAll(this);
359
+
360
+ switch (LyraGameplayCueManagerCvars::LoadMode)
361
+ {
362
+ case ELyraEditorLoadMode::LoadUpfront:
363
+ return;
364
+ case ELyraEditorLoadMode::PreloadAsCuesAreReferenced_GameOnly:
365
+ #if WITH_EDITOR
366
+ if (GIsEditor)
367
+ {
368
+ return;
369
+ }
370
+ #endif
371
+ break;
372
+ case ELyraEditorLoadMode::PreloadAsCuesAreReferenced:
373
+ break;
374
+ }
375
+
376
+ UGameplayTagsManager::Get().OnGameplayTagLoadedDelegate.AddUObject(this, &ThisClass::OnGameplayTagLoaded);
377
+ FCoreUObjectDelegates::GetPostGarbageCollect().AddUObject(this, &ThisClass::HandlePostGarbageCollect);
378
+ FCoreUObjectDelegates::PostLoadMapWithWorld.AddUObject(this, &ThisClass::HandlePostLoadMap);
379
+ }
380
+
381
+ bool ULyraGameplayCueManager::ShouldDelayLoadGameplayCues() const
382
+ {
383
+ const bool bClientDelayLoadGameplayCues = true;
384
+ return !IsRunningDedicatedServer() && bClientDelayLoadGameplayCues;
385
+ }
386
+
387
+ const FPrimaryAssetType UFortAssetManager_GameplayCueRefsType = TEXT("GameplayCueRefs");
388
+ const FName UFortAssetManager_GameplayCueRefsName = TEXT("GameplayCueReferences");
389
+ const FName UFortAssetManager_LoadStateClient = FName(TEXT("Client"));
390
+
391
+ void ULyraGameplayCueManager::RefreshGameplayCuePrimaryAsset()
392
+ {
393
+ TArray<FSoftObjectPath> CuePaths;
394
+ UGameplayCueSet* RuntimeGameplayCueSet = GetRuntimeCueSet();
395
+ if (RuntimeGameplayCueSet)
396
+ {
397
+ RuntimeGameplayCueSet->GetSoftObjectPaths(CuePaths);
398
+ }
399
+
400
+ FAssetBundleData BundleData;
401
+ BundleData.AddBundleAssetsTruncated(UFortAssetManager_LoadStateClient, CuePaths);
402
+
403
+ FPrimaryAssetId PrimaryAssetId = FPrimaryAssetId(UFortAssetManager_GameplayCueRefsType, UFortAssetManager_GameplayCueRefsName);
404
+ UAssetManager::Get().AddDynamicAsset(PrimaryAssetId, FSoftObjectPath(), BundleData);
405
+ }
406
+
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGameplayCueManager.h ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "GameplayCueManager.h"
6
+
7
+ #include "LyraGameplayCueManager.generated.h"
8
+
9
+ class FString;
10
+ class UClass;
11
+ class UObject;
12
+ class UWorld;
13
+ struct FObjectKey;
14
+
15
+ /**
16
+ * ULyraGameplayCueManager
17
+ *
18
+ * Game-specific manager for gameplay cues
19
+ */
20
+ UCLASS()
21
+ class ULyraGameplayCueManager : public UGameplayCueManager
22
+ {
23
+ GENERATED_BODY()
24
+
25
+ public:
26
+ ULyraGameplayCueManager(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
27
+
28
+ static ULyraGameplayCueManager* Get();
29
+
30
+ //~UGameplayCueManager interface
31
+ virtual void OnCreated() override;
32
+ virtual bool ShouldAsyncLoadRuntimeObjectLibraries() const override;
33
+ virtual bool ShouldSyncLoadMissingGameplayCues() const override;
34
+ virtual bool ShouldAsyncLoadMissingGameplayCues() const override;
35
+ //~End of UGameplayCueManager interface
36
+
37
+ static void DumpGameplayCues(const TArray<FString>& Args);
38
+
39
+ // When delay loading cues, this will load the cues that must be always loaded anyway
40
+ void LoadAlwaysLoadedCues();
41
+
42
+ // Updates the bundles for the singular gameplay cue primary asset
43
+ void RefreshGameplayCuePrimaryAsset();
44
+
45
+ private:
46
+ void OnGameplayTagLoaded(const FGameplayTag& Tag);
47
+ void HandlePostGarbageCollect();
48
+ void ProcessLoadedTags();
49
+ void ProcessTagToPreload(const FGameplayTag& Tag, UObject* OwningObject);
50
+ void OnPreloadCueComplete(FSoftObjectPath Path, TWeakObjectPtr<UObject> OwningObject, bool bAlwaysLoadedCue);
51
+ void RegisterPreloadedCue(UClass* LoadedGameplayCueClass, UObject* OwningObject);
52
+ void HandlePostLoadMap(UWorld* NewWorld);
53
+ void UpdateDelayLoadDelegateListeners();
54
+ bool ShouldDelayLoadGameplayCues() const;
55
+
56
+ private:
57
+ struct FLoadedGameplayTagToProcessData
58
+ {
59
+ FGameplayTag Tag;
60
+ TWeakObjectPtr<UObject> WeakOwner;
61
+
62
+ FLoadedGameplayTagToProcessData() {}
63
+ FLoadedGameplayTagToProcessData(const FGameplayTag& InTag, const TWeakObjectPtr<UObject>& InWeakOwner) : Tag(InTag), WeakOwner(InWeakOwner) {}
64
+ };
65
+
66
+ private:
67
+ // Cues that were preloaded on the client due to being referenced by content
68
+ UPROPERTY(transient)
69
+ TSet<TObjectPtr<UClass>> PreloadedCues;
70
+ TMap<FObjectKey, TSet<FObjectKey>> PreloadedCueReferencers;
71
+
72
+ // Cues that were preloaded on the client and will always be loaded (code referenced or explicitly always loaded)
73
+ UPROPERTY(transient)
74
+ TSet<TObjectPtr<UClass>> AlwaysLoadedCues;
75
+
76
+ TArray<FLoadedGameplayTagToProcessData> LoadedGameplayTagsToProcess;
77
+ FCriticalSection LoadedGameplayTagsToProcessCS;
78
+ bool bProcessLoadedTagsAfterGC = false;
79
+ };
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGameplayEffectContext.cpp ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraGameplayEffectContext.h"
4
+
5
+ #include "AbilitySystem/LyraAbilitySourceInterface.h"
6
+ #include "Engine/HitResult.h"
7
+ #include "PhysicalMaterials/PhysicalMaterial.h"
8
+
9
+ #if UE_WITH_IRIS
10
+ #include "Iris/ReplicationState/PropertyNetSerializerInfoRegistry.h"
11
+ #include "Serialization/GameplayEffectContextNetSerializer.h"
12
+ #endif
13
+
14
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraGameplayEffectContext)
15
+
16
+ class FArchive;
17
+
18
+ FLyraGameplayEffectContext* FLyraGameplayEffectContext::ExtractEffectContext(struct FGameplayEffectContextHandle Handle)
19
+ {
20
+ FGameplayEffectContext* BaseEffectContext = Handle.Get();
21
+ if ((BaseEffectContext != nullptr) && BaseEffectContext->GetScriptStruct()->IsChildOf(FLyraGameplayEffectContext::StaticStruct()))
22
+ {
23
+ return (FLyraGameplayEffectContext*)BaseEffectContext;
24
+ }
25
+
26
+ return nullptr;
27
+ }
28
+
29
+ bool FLyraGameplayEffectContext::NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess)
30
+ {
31
+ FGameplayEffectContext::NetSerialize(Ar, Map, bOutSuccess);
32
+
33
+ // Not serialized for post-activation use:
34
+ // CartridgeID
35
+
36
+ return true;
37
+ }
38
+
39
+ #if UE_WITH_IRIS
40
+ namespace UE::Net
41
+ {
42
+ // Forward to FGameplayEffectContextNetSerializer
43
+ // Note: If FLyraGameplayEffectContext::NetSerialize() is modified, a custom NetSerializesr must be implemented as the current fallback will no longer be sufficient.
44
+ UE_NET_IMPLEMENT_FORWARDING_NETSERIALIZER_AND_REGISTRY_DELEGATES(LyraGameplayEffectContext, FGameplayEffectContextNetSerializer);
45
+ }
46
+ #endif
47
+
48
+ void FLyraGameplayEffectContext::SetAbilitySource(const ILyraAbilitySourceInterface* InObject, float InSourceLevel)
49
+ {
50
+ AbilitySourceObject = MakeWeakObjectPtr(Cast<const UObject>(InObject));
51
+ //SourceLevel = InSourceLevel;
52
+ }
53
+
54
+ const ILyraAbilitySourceInterface* FLyraGameplayEffectContext::GetAbilitySource() const
55
+ {
56
+ return Cast<ILyraAbilitySourceInterface>(AbilitySourceObject.Get());
57
+ }
58
+
59
+ const UPhysicalMaterial* FLyraGameplayEffectContext::GetPhysicalMaterial() const
60
+ {
61
+ if (const FHitResult* HitResultPtr = GetHitResult())
62
+ {
63
+ return HitResultPtr->PhysMaterial.Get();
64
+ }
65
+ return nullptr;
66
+ }
67
+
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGameplayEffectContext.h ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "GameplayEffectTypes.h"
6
+
7
+ #include "LyraGameplayEffectContext.generated.h"
8
+
9
+ class AActor;
10
+ class FArchive;
11
+ class ILyraAbilitySourceInterface;
12
+ class UObject;
13
+ class UPhysicalMaterial;
14
+
15
+ USTRUCT()
16
+ struct FLyraGameplayEffectContext : public FGameplayEffectContext
17
+ {
18
+ GENERATED_BODY()
19
+
20
+ FLyraGameplayEffectContext()
21
+ : FGameplayEffectContext()
22
+ {
23
+ }
24
+
25
+ FLyraGameplayEffectContext(AActor* InInstigator, AActor* InEffectCauser)
26
+ : FGameplayEffectContext(InInstigator, InEffectCauser)
27
+ {
28
+ }
29
+
30
+ /** Returns the wrapped FLyraGameplayEffectContext from the handle, or nullptr if it doesn't exist or is the wrong type */
31
+ static LYRAGAME_API FLyraGameplayEffectContext* ExtractEffectContext(struct FGameplayEffectContextHandle Handle);
32
+
33
+ /** Sets the object used as the ability source */
34
+ void SetAbilitySource(const ILyraAbilitySourceInterface* InObject, float InSourceLevel);
35
+
36
+ /** Returns the ability source interface associated with the source object. Only valid on the authority. */
37
+ const ILyraAbilitySourceInterface* GetAbilitySource() const;
38
+
39
+ virtual FGameplayEffectContext* Duplicate() const override
40
+ {
41
+ FLyraGameplayEffectContext* NewContext = new FLyraGameplayEffectContext();
42
+ *NewContext = *this;
43
+ if (GetHitResult())
44
+ {
45
+ // Does a deep copy of the hit result
46
+ NewContext->AddHitResult(*GetHitResult(), true);
47
+ }
48
+ return NewContext;
49
+ }
50
+
51
+ virtual UScriptStruct* GetScriptStruct() const override
52
+ {
53
+ return FLyraGameplayEffectContext::StaticStruct();
54
+ }
55
+
56
+ /** Overridden to serialize new fields */
57
+ virtual bool NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess) override;
58
+
59
+ /** Returns the physical material from the hit result if there is one */
60
+ const UPhysicalMaterial* GetPhysicalMaterial() const;
61
+
62
+ public:
63
+ /** ID to allow the identification of multiple bullets that were part of the same cartridge */
64
+ UPROPERTY()
65
+ int32 CartridgeID = -1;
66
+
67
+ protected:
68
+ /** Ability Source object (should implement ILyraAbilitySourceInterface). NOT replicated currently */
69
+ UPROPERTY()
70
+ TWeakObjectPtr<const UObject> AbilitySourceObject;
71
+ };
72
+
73
+ template<>
74
+ struct TStructOpsTypeTraits<FLyraGameplayEffectContext> : public TStructOpsTypeTraitsBase2<FLyraGameplayEffectContext>
75
+ {
76
+ enum
77
+ {
78
+ WithNetSerializer = true,
79
+ WithCopy = true
80
+ };
81
+ };
82
+
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGlobalAbilitySystem.cpp ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraGlobalAbilitySystem.h"
4
+
5
+ #include "AbilitySystem/LyraAbilitySystemComponent.h"
6
+
7
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraGlobalAbilitySystem)
8
+
9
+ void FGlobalAppliedAbilityList::AddToASC(TSubclassOf<UGameplayAbility> Ability, ULyraAbilitySystemComponent* ASC)
10
+ {
11
+ if (FGameplayAbilitySpecHandle* SpecHandle = Handles.Find(ASC))
12
+ {
13
+ RemoveFromASC(ASC);
14
+ }
15
+
16
+ UGameplayAbility* AbilityCDO = Ability->GetDefaultObject<UGameplayAbility>();
17
+ FGameplayAbilitySpec AbilitySpec(AbilityCDO);
18
+ const FGameplayAbilitySpecHandle AbilitySpecHandle = ASC->GiveAbility(AbilitySpec);
19
+ Handles.Add(ASC, AbilitySpecHandle);
20
+ }
21
+
22
+ void FGlobalAppliedAbilityList::RemoveFromASC(ULyraAbilitySystemComponent* ASC)
23
+ {
24
+ if (FGameplayAbilitySpecHandle* SpecHandle = Handles.Find(ASC))
25
+ {
26
+ ASC->ClearAbility(*SpecHandle);
27
+ Handles.Remove(ASC);
28
+ }
29
+ }
30
+
31
+ void FGlobalAppliedAbilityList::RemoveFromAll()
32
+ {
33
+ for (auto& KVP : Handles)
34
+ {
35
+ if (KVP.Key != nullptr)
36
+ {
37
+ KVP.Key->ClearAbility(KVP.Value);
38
+ }
39
+ }
40
+ Handles.Empty();
41
+ }
42
+
43
+
44
+
45
+ void FGlobalAppliedEffectList::AddToASC(TSubclassOf<UGameplayEffect> Effect, ULyraAbilitySystemComponent* ASC)
46
+ {
47
+ if (FActiveGameplayEffectHandle* EffectHandle = Handles.Find(ASC))
48
+ {
49
+ RemoveFromASC(ASC);
50
+ }
51
+
52
+ const UGameplayEffect* GameplayEffectCDO = Effect->GetDefaultObject<UGameplayEffect>();
53
+ const FActiveGameplayEffectHandle GameplayEffectHandle = ASC->ApplyGameplayEffectToSelf(GameplayEffectCDO, /*Level=*/ 1, ASC->MakeEffectContext());
54
+ Handles.Add(ASC, GameplayEffectHandle);
55
+ }
56
+
57
+ void FGlobalAppliedEffectList::RemoveFromASC(ULyraAbilitySystemComponent* ASC)
58
+ {
59
+ if (FActiveGameplayEffectHandle* EffectHandle = Handles.Find(ASC))
60
+ {
61
+ ASC->RemoveActiveGameplayEffect(*EffectHandle);
62
+ Handles.Remove(ASC);
63
+ }
64
+ }
65
+
66
+ void FGlobalAppliedEffectList::RemoveFromAll()
67
+ {
68
+ for (auto& KVP : Handles)
69
+ {
70
+ if (KVP.Key != nullptr)
71
+ {
72
+ KVP.Key->RemoveActiveGameplayEffect(KVP.Value);
73
+ }
74
+ }
75
+ Handles.Empty();
76
+ }
77
+
78
+ ULyraGlobalAbilitySystem::ULyraGlobalAbilitySystem()
79
+ {
80
+ }
81
+
82
+ void ULyraGlobalAbilitySystem::ApplyAbilityToAll(TSubclassOf<UGameplayAbility> Ability)
83
+ {
84
+ if ((Ability.Get() != nullptr) && (!AppliedAbilities.Contains(Ability)))
85
+ {
86
+ FGlobalAppliedAbilityList& Entry = AppliedAbilities.Add(Ability);
87
+ for (ULyraAbilitySystemComponent* ASC : RegisteredASCs)
88
+ {
89
+ Entry.AddToASC(Ability, ASC);
90
+ }
91
+ }
92
+ }
93
+
94
+ void ULyraGlobalAbilitySystem::ApplyEffectToAll(TSubclassOf<UGameplayEffect> Effect)
95
+ {
96
+ if ((Effect.Get() != nullptr) && (!AppliedEffects.Contains(Effect)))
97
+ {
98
+ FGlobalAppliedEffectList& Entry = AppliedEffects.Add(Effect);
99
+ for (ULyraAbilitySystemComponent* ASC : RegisteredASCs)
100
+ {
101
+ Entry.AddToASC(Effect, ASC);
102
+ }
103
+ }
104
+ }
105
+
106
+ void ULyraGlobalAbilitySystem::RemoveAbilityFromAll(TSubclassOf<UGameplayAbility> Ability)
107
+ {
108
+ if ((Ability.Get() != nullptr) && AppliedAbilities.Contains(Ability))
109
+ {
110
+ FGlobalAppliedAbilityList& Entry = AppliedAbilities[Ability];
111
+ Entry.RemoveFromAll();
112
+ AppliedAbilities.Remove(Ability);
113
+ }
114
+ }
115
+
116
+ void ULyraGlobalAbilitySystem::RemoveEffectFromAll(TSubclassOf<UGameplayEffect> Effect)
117
+ {
118
+ if ((Effect.Get() != nullptr) && AppliedEffects.Contains(Effect))
119
+ {
120
+ FGlobalAppliedEffectList& Entry = AppliedEffects[Effect];
121
+ Entry.RemoveFromAll();
122
+ AppliedEffects.Remove(Effect);
123
+ }
124
+ }
125
+
126
+ void ULyraGlobalAbilitySystem::RegisterASC(ULyraAbilitySystemComponent* ASC)
127
+ {
128
+ check(ASC);
129
+
130
+ for (auto& Entry : AppliedAbilities)
131
+ {
132
+ Entry.Value.AddToASC(Entry.Key, ASC);
133
+ }
134
+ for (auto& Entry : AppliedEffects)
135
+ {
136
+ Entry.Value.AddToASC(Entry.Key, ASC);
137
+ }
138
+
139
+ RegisteredASCs.AddUnique(ASC);
140
+ }
141
+
142
+ void ULyraGlobalAbilitySystem::UnregisterASC(ULyraAbilitySystemComponent* ASC)
143
+ {
144
+ check(ASC);
145
+ for (auto& Entry : AppliedAbilities)
146
+ {
147
+ Entry.Value.RemoveFromASC(ASC);
148
+ }
149
+ for (auto& Entry : AppliedEffects)
150
+ {
151
+ Entry.Value.RemoveFromASC(ASC);
152
+ }
153
+
154
+ RegisteredASCs.Remove(ASC);
155
+ }
156
+
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraGlobalAbilitySystem.h ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "ActiveGameplayEffectHandle.h"
6
+ #include "Subsystems/WorldSubsystem.h"
7
+ #include "GameplayAbilitySpecHandle.h"
8
+ #include "Templates/SubclassOf.h"
9
+
10
+ #include "LyraGlobalAbilitySystem.generated.h"
11
+
12
+ class UGameplayAbility;
13
+ class UGameplayEffect;
14
+ class ULyraAbilitySystemComponent;
15
+ class UObject;
16
+ struct FActiveGameplayEffectHandle;
17
+ struct FFrame;
18
+ struct FGameplayAbilitySpecHandle;
19
+
20
+ USTRUCT()
21
+ struct FGlobalAppliedAbilityList
22
+ {
23
+ GENERATED_BODY()
24
+
25
+ UPROPERTY()
26
+ TMap<TObjectPtr<ULyraAbilitySystemComponent>, FGameplayAbilitySpecHandle> Handles;
27
+
28
+ void AddToASC(TSubclassOf<UGameplayAbility> Ability, ULyraAbilitySystemComponent* ASC);
29
+ void RemoveFromASC(ULyraAbilitySystemComponent* ASC);
30
+ void RemoveFromAll();
31
+ };
32
+
33
+ USTRUCT()
34
+ struct FGlobalAppliedEffectList
35
+ {
36
+ GENERATED_BODY()
37
+
38
+ UPROPERTY()
39
+ TMap<TObjectPtr<ULyraAbilitySystemComponent>, FActiveGameplayEffectHandle> Handles;
40
+
41
+ void AddToASC(TSubclassOf<UGameplayEffect> Effect, ULyraAbilitySystemComponent* ASC);
42
+ void RemoveFromASC(ULyraAbilitySystemComponent* ASC);
43
+ void RemoveFromAll();
44
+ };
45
+
46
+ UCLASS()
47
+ class ULyraGlobalAbilitySystem : public UWorldSubsystem
48
+ {
49
+ GENERATED_BODY()
50
+
51
+ public:
52
+ ULyraGlobalAbilitySystem();
53
+
54
+ UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="Lyra")
55
+ void ApplyAbilityToAll(TSubclassOf<UGameplayAbility> Ability);
56
+
57
+ UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category="Lyra")
58
+ void ApplyEffectToAll(TSubclassOf<UGameplayEffect> Effect);
59
+
60
+ UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category = "Lyra")
61
+ void RemoveAbilityFromAll(TSubclassOf<UGameplayAbility> Ability);
62
+
63
+ UFUNCTION(BlueprintCallable, BlueprintAuthorityOnly, Category = "Lyra")
64
+ void RemoveEffectFromAll(TSubclassOf<UGameplayEffect> Effect);
65
+
66
+ /** Register an ASC with global system and apply any active global effects/abilities. */
67
+ void RegisterASC(ULyraAbilitySystemComponent* ASC);
68
+
69
+ /** Removes an ASC from the global system, along with any active global effects/abilities. */
70
+ void UnregisterASC(ULyraAbilitySystemComponent* ASC);
71
+
72
+ private:
73
+ UPROPERTY()
74
+ TMap<TSubclassOf<UGameplayAbility>, FGlobalAppliedAbilityList> AppliedAbilities;
75
+
76
+ UPROPERTY()
77
+ TMap<TSubclassOf<UGameplayEffect>, FGlobalAppliedEffectList> AppliedEffects;
78
+
79
+ UPROPERTY()
80
+ TArray<TObjectPtr<ULyraAbilitySystemComponent>> RegisteredASCs;
81
+ };
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraTaggedActor.cpp ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraTaggedActor.h"
4
+ #include "UObject/UnrealType.h"
5
+
6
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraTaggedActor)
7
+
8
+ ALyraTaggedActor::ALyraTaggedActor(const FObjectInitializer& ObjectInitializer)
9
+ : Super(ObjectInitializer)
10
+ {
11
+ }
12
+
13
+ void ALyraTaggedActor::GetOwnedGameplayTags(FGameplayTagContainer& TagContainer) const
14
+ {
15
+ TagContainer.AppendTags(StaticGameplayTags);
16
+ }
17
+
18
+ #if WITH_EDITOR
19
+ bool ALyraTaggedActor::CanEditChange(const FProperty* InProperty) const
20
+ {
21
+ // Prevent editing of the other tags property
22
+ if (InProperty->GetFName() == GET_MEMBER_NAME_CHECKED(AActor, Tags))
23
+ {
24
+ return false;
25
+ }
26
+
27
+ return Super::CanEditChange(InProperty);
28
+ }
29
+ #endif
30
+
LyraStarterGame/Source/LyraGame/AbilitySystem/LyraTaggedActor.h ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "GameFramework/Actor.h"
6
+ #include "GameplayTagAssetInterface.h"
7
+ #include "GameplayTagContainer.h"
8
+
9
+ #include "LyraTaggedActor.generated.h"
10
+
11
+ // An actor that implements the gameplay tag asset interface
12
+ UCLASS()
13
+ class ALyraTaggedActor : public AActor, public IGameplayTagAssetInterface
14
+ {
15
+ GENERATED_BODY()
16
+
17
+ public:
18
+
19
+ ALyraTaggedActor(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
20
+
21
+ //~IGameplayTagAssetInterface
22
+ virtual void GetOwnedGameplayTags(FGameplayTagContainer& TagContainer) const override;
23
+ //~End of IGameplayTagAssetInterface
24
+
25
+ //~UObject interface
26
+ #if WITH_EDITOR
27
+ virtual bool CanEditChange(const FProperty* InProperty) const override;
28
+ #endif
29
+ //~End of UObject interface
30
+
31
+ protected:
32
+ // Gameplay-related tags associated with this actor
33
+ UPROPERTY(EditAnywhere, BlueprintReadOnly, Category=Actor)
34
+ FGameplayTagContainer StaticGameplayTags;
35
+ };
36
+
LyraStarterGame/Source/LyraGame/Animation/LyraAnimInstance.cpp ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraAnimInstance.h"
4
+ #include "AbilitySystemGlobals.h"
5
+ #include "Character/LyraCharacter.h"
6
+ #include "Character/LyraCharacterMovementComponent.h"
7
+
8
+ #if WITH_EDITOR
9
+ #include "Misc/DataValidation.h"
10
+ #endif
11
+
12
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraAnimInstance)
13
+
14
+
15
+ ULyraAnimInstance::ULyraAnimInstance(const FObjectInitializer& ObjectInitializer)
16
+ : Super(ObjectInitializer)
17
+ {
18
+ }
19
+
20
+ void ULyraAnimInstance::InitializeWithAbilitySystem(UAbilitySystemComponent* ASC)
21
+ {
22
+ check(ASC);
23
+
24
+ GameplayTagPropertyMap.Initialize(this, ASC);
25
+ }
26
+
27
+ #if WITH_EDITOR
28
+ EDataValidationResult ULyraAnimInstance::IsDataValid(FDataValidationContext& Context) const
29
+ {
30
+ Super::IsDataValid(Context);
31
+
32
+ GameplayTagPropertyMap.IsDataValid(this, Context);
33
+
34
+ return ((Context.GetNumErrors() > 0) ? EDataValidationResult::Invalid : EDataValidationResult::Valid);
35
+ }
36
+ #endif // WITH_EDITOR
37
+
38
+ void ULyraAnimInstance::NativeInitializeAnimation()
39
+ {
40
+ Super::NativeInitializeAnimation();
41
+
42
+ if (AActor* OwningActor = GetOwningActor())
43
+ {
44
+ if (UAbilitySystemComponent* ASC = UAbilitySystemGlobals::GetAbilitySystemComponentFromActor(OwningActor))
45
+ {
46
+ InitializeWithAbilitySystem(ASC);
47
+ }
48
+ }
49
+ }
50
+
51
+ void ULyraAnimInstance::NativeUpdateAnimation(float DeltaSeconds)
52
+ {
53
+ Super::NativeUpdateAnimation(DeltaSeconds);
54
+
55
+ const ALyraCharacter* Character = Cast<ALyraCharacter>(GetOwningActor());
56
+ if (!Character)
57
+ {
58
+ return;
59
+ }
60
+
61
+ ULyraCharacterMovementComponent* CharMoveComp = CastChecked<ULyraCharacterMovementComponent>(Character->GetCharacterMovement());
62
+ const FLyraCharacterGroundInfo& GroundInfo = CharMoveComp->GetGroundInfo();
63
+ GroundDistance = GroundInfo.GroundDistance;
64
+ }
65
+
LyraStarterGame/Source/LyraGame/Animation/LyraAnimInstance.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "Animation/AnimInstance.h"
6
+ #include "GameplayEffectTypes.h"
7
+ #include "LyraAnimInstance.generated.h"
8
+
9
+ class UAbilitySystemComponent;
10
+
11
+
12
+ /**
13
+ * ULyraAnimInstance
14
+ *
15
+ * The base game animation instance class used by this project.
16
+ */
17
+ UCLASS(Config = Game)
18
+ class ULyraAnimInstance : public UAnimInstance
19
+ {
20
+ GENERATED_BODY()
21
+
22
+ public:
23
+
24
+ ULyraAnimInstance(const FObjectInitializer& ObjectInitializer);
25
+
26
+ virtual void InitializeWithAbilitySystem(UAbilitySystemComponent* ASC);
27
+
28
+ protected:
29
+
30
+ #if WITH_EDITOR
31
+ virtual EDataValidationResult IsDataValid(class FDataValidationContext& Context) const override;
32
+ #endif // WITH_EDITOR
33
+
34
+ virtual void NativeInitializeAnimation() override;
35
+ virtual void NativeUpdateAnimation(float DeltaSeconds) override;
36
+
37
+ protected:
38
+
39
+ // Gameplay tags that can be mapped to blueprint variables. The variables will automatically update as the tags are added or removed.
40
+ // These should be used instead of manually querying for the gameplay tags.
41
+ UPROPERTY(EditDefaultsOnly, Category = "GameplayTags")
42
+ FGameplayTagBlueprintPropertyMap GameplayTagPropertyMap;
43
+
44
+ UPROPERTY(BlueprintReadOnly, Category = "Character State Data")
45
+ float GroundDistance = -1.0f;
46
+ };
LyraStarterGame/Source/LyraGame/Audio/LyraAudioMixEffectsSubsystem.cpp ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+
4
+ #include "Audio/LyraAudioMixEffectsSubsystem.h"
5
+
6
+ #include "AudioMixerBlueprintLibrary.h"
7
+ #include "AudioModulationStatics.h"
8
+ #include "Engine/GameInstance.h"
9
+ #include "Engine/World.h"
10
+ #include "LoadingScreenManager.h"
11
+ #include "LyraAudioSettings.h"
12
+ #include "Settings/LyraSettingsLocal.h"
13
+ #include "Sound/SoundEffectSubmix.h"
14
+ #include "SoundControlBus.h"
15
+ #include "SoundControlBusMix.h"
16
+
17
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraAudioMixEffectsSubsystem)
18
+
19
+ class FSubsystemCollectionBase;
20
+
21
+ void ULyraAudioMixEffectsSubsystem::Initialize(FSubsystemCollectionBase& Collection)
22
+ {
23
+ Super::Initialize(Collection);
24
+ }
25
+
26
+ void ULyraAudioMixEffectsSubsystem::Deinitialize()
27
+ {
28
+ if (ULoadingScreenManager* LoadingScreenManager = UGameInstance::GetSubsystem<ULoadingScreenManager>(GetWorld()->GetGameInstance()))
29
+ {
30
+ LoadingScreenManager->OnLoadingScreenVisibilityChangedDelegate().RemoveAll(this);
31
+ ApplyOrRemoveLoadingScreenMix(false);
32
+ }
33
+
34
+ Super::Deinitialize();
35
+ }
36
+
37
+ bool ULyraAudioMixEffectsSubsystem::ShouldCreateSubsystem(UObject* Outer) const
38
+ {
39
+ bool bShouldCreateSubsystem = Super::ShouldCreateSubsystem(Outer);
40
+
41
+ if (Outer)
42
+ {
43
+ if (UWorld* World = Outer->GetWorld())
44
+ {
45
+ bShouldCreateSubsystem = DoesSupportWorldType(World->WorldType) && bShouldCreateSubsystem;
46
+ }
47
+ }
48
+
49
+ return bShouldCreateSubsystem;
50
+ }
51
+
52
+ void ULyraAudioMixEffectsSubsystem::PostInitialize()
53
+ {
54
+ if (const ULyraAudioSettings* LyraAudioSettings = GetDefault<ULyraAudioSettings>())
55
+ {
56
+ if (UObject* ObjPath = LyraAudioSettings->DefaultControlBusMix.TryLoad())
57
+ {
58
+ if (USoundControlBusMix* SoundControlBusMix = Cast<USoundControlBusMix>(ObjPath))
59
+ {
60
+ DefaultBaseMix = SoundControlBusMix;
61
+ }
62
+ else
63
+ {
64
+ ensureMsgf(SoundControlBusMix, TEXT("Default Control Bus Mix reference missing from Lyra Audio Settings."));
65
+ }
66
+ }
67
+
68
+ if (UObject* ObjPath = LyraAudioSettings->LoadingScreenControlBusMix.TryLoad())
69
+ {
70
+ if (USoundControlBusMix* SoundControlBusMix = Cast<USoundControlBusMix>(ObjPath))
71
+ {
72
+ LoadingScreenMix = SoundControlBusMix;
73
+ }
74
+ else
75
+ {
76
+ ensureMsgf(SoundControlBusMix, TEXT("Loading Screen Control Bus Mix reference missing from Lyra Audio Settings."));
77
+ }
78
+ }
79
+
80
+ if (UObject* ObjPath = LyraAudioSettings->UserSettingsControlBusMix.TryLoad())
81
+ {
82
+ if (USoundControlBusMix* SoundControlBusMix = Cast<USoundControlBusMix>(ObjPath))
83
+ {
84
+ UserMix = SoundControlBusMix;
85
+ }
86
+ else
87
+ {
88
+ ensureMsgf(SoundControlBusMix, TEXT("User Control Bus Mix reference missing from Lyra Audio Settings."));
89
+ }
90
+ }
91
+
92
+ if (UObject* ObjPath = LyraAudioSettings->OverallVolumeControlBus.TryLoad())
93
+ {
94
+ if (USoundControlBus* SoundControlBus = Cast<USoundControlBus>(ObjPath))
95
+ {
96
+ OverallControlBus = SoundControlBus;
97
+ }
98
+ else
99
+ {
100
+ ensureMsgf(SoundControlBus, TEXT("Overall Control Bus reference missing from Lyra Audio Settings."));
101
+ }
102
+ }
103
+
104
+ if (UObject* ObjPath = LyraAudioSettings->MusicVolumeControlBus.TryLoad())
105
+ {
106
+ if (USoundControlBus* SoundControlBus = Cast<USoundControlBus>(ObjPath))
107
+ {
108
+ MusicControlBus = SoundControlBus;
109
+ }
110
+ else
111
+ {
112
+ ensureMsgf(SoundControlBus, TEXT("Music Control Bus reference missing from Lyra Audio Settings."));
113
+ }
114
+ }
115
+
116
+ if (UObject* ObjPath = LyraAudioSettings->SoundFXVolumeControlBus.TryLoad())
117
+ {
118
+ if (USoundControlBus* SoundControlBus = Cast<USoundControlBus>(ObjPath))
119
+ {
120
+ SoundFXControlBus = SoundControlBus;
121
+ }
122
+ else
123
+ {
124
+ ensureMsgf(SoundControlBus, TEXT("SoundFX Control Bus reference missing from Lyra Audio Settings."));
125
+ }
126
+ }
127
+
128
+ if (UObject* ObjPath = LyraAudioSettings->DialogueVolumeControlBus.TryLoad())
129
+ {
130
+ if (USoundControlBus* SoundControlBus = Cast<USoundControlBus>(ObjPath))
131
+ {
132
+ DialogueControlBus = SoundControlBus;
133
+ }
134
+ else
135
+ {
136
+ ensureMsgf(SoundControlBus, TEXT("Dialogue Control Bus reference missing from Lyra Audio Settings."));
137
+ }
138
+ }
139
+
140
+ if (UObject* ObjPath = LyraAudioSettings->VoiceChatVolumeControlBus.TryLoad())
141
+ {
142
+ if (USoundControlBus* SoundControlBus = Cast<USoundControlBus>(ObjPath))
143
+ {
144
+ VoiceChatControlBus = SoundControlBus;
145
+ }
146
+ else
147
+ {
148
+ ensureMsgf(SoundControlBus, TEXT("VoiceChat Control Bus reference missing from Lyra Audio Settings."));
149
+ }
150
+ }
151
+
152
+ // Load HDR Submix Effect Chain
153
+ for (const FLyraSubmixEffectChainMap& SoftSubmixEffectChain : LyraAudioSettings->HDRAudioSubmixEffectChain)
154
+ {
155
+ FLyraAudioSubmixEffectsChain NewEffectChain;
156
+
157
+ if (UObject* SubmixObjPath = SoftSubmixEffectChain.Submix.LoadSynchronous())
158
+ {
159
+ if (USoundSubmix* Submix = Cast<USoundSubmix>(SubmixObjPath))
160
+ {
161
+ NewEffectChain.Submix = Submix;
162
+ TArray<USoundEffectSubmixPreset*> NewPresetChain;
163
+
164
+ for (const TSoftObjectPtr<USoundEffectSubmixPreset>& SoftEffect : SoftSubmixEffectChain.SubmixEffectChain)
165
+ {
166
+ if (UObject* EffectObjPath = SoftEffect.LoadSynchronous())
167
+ {
168
+ if (USoundEffectSubmixPreset* SubmixPreset = Cast<USoundEffectSubmixPreset>(EffectObjPath))
169
+ {
170
+ NewPresetChain.Add(SubmixPreset);
171
+ }
172
+ }
173
+ }
174
+
175
+ NewEffectChain.SubmixEffectChain.Append(NewPresetChain);
176
+ }
177
+ }
178
+
179
+ HDRSubmixEffectChain.Add(NewEffectChain);
180
+ }
181
+
182
+ // Load LDR Submix Effect Chain
183
+ for (const FLyraSubmixEffectChainMap& SoftSubmixEffectChain : LyraAudioSettings->LDRAudioSubmixEffectChain)
184
+ {
185
+ FLyraAudioSubmixEffectsChain NewEffectChain;
186
+
187
+ if (UObject* SubmixObjPath = SoftSubmixEffectChain.Submix.LoadSynchronous())
188
+ {
189
+ if (USoundSubmix* Submix = Cast<USoundSubmix>(SubmixObjPath))
190
+ {
191
+ NewEffectChain.Submix = Submix;
192
+ TArray<USoundEffectSubmixPreset*> NewPresetChain;
193
+
194
+ for (const TSoftObjectPtr<USoundEffectSubmixPreset>& SoftEffect : SoftSubmixEffectChain.SubmixEffectChain)
195
+ {
196
+ if (UObject* EffectObjPath = SoftEffect.LoadSynchronous())
197
+ {
198
+ if (USoundEffectSubmixPreset* SubmixPreset = Cast<USoundEffectSubmixPreset>(EffectObjPath))
199
+ {
200
+ NewPresetChain.Add(SubmixPreset);
201
+ }
202
+ }
203
+ }
204
+
205
+ NewEffectChain.SubmixEffectChain.Append(NewPresetChain);
206
+ }
207
+ }
208
+
209
+ LDRSubmixEffectChain.Add(NewEffectChain);
210
+ }
211
+ }
212
+
213
+ // Register with the loading screen manager
214
+ if (ULoadingScreenManager* LoadingScreenManager = UGameInstance::GetSubsystem<ULoadingScreenManager>(GetWorld()->GetGameInstance()))
215
+ {
216
+ LoadingScreenManager->OnLoadingScreenVisibilityChangedDelegate().AddUObject(this, &ThisClass::OnLoadingScreenStatusChanged);
217
+ ApplyOrRemoveLoadingScreenMix(LoadingScreenManager->GetLoadingScreenDisplayStatus());
218
+ }
219
+ }
220
+
221
+ void ULyraAudioMixEffectsSubsystem::OnWorldBeginPlay(UWorld& InWorld)
222
+ {
223
+ if (const UWorld* World = InWorld.GetWorld())
224
+ {
225
+ // Activate the default base mix
226
+ if (DefaultBaseMix)
227
+ {
228
+ UAudioModulationStatics::ActivateBusMix(World, DefaultBaseMix);
229
+ }
230
+
231
+ // Retrieve the user settings
232
+ if (const ULyraSettingsLocal* LyraSettingsLocal = GetDefault<ULyraSettingsLocal>())
233
+ {
234
+ // Activate the User Mix
235
+ if (UserMix)
236
+ {
237
+ UAudioModulationStatics::ActivateBusMix(World, UserMix);
238
+
239
+ if (OverallControlBus && MusicControlBus && SoundFXControlBus && DialogueControlBus && VoiceChatControlBus)
240
+ {
241
+ const FSoundControlBusMixStage OverallControlBusMixStage = UAudioModulationStatics::CreateBusMixStage(World, OverallControlBus, LyraSettingsLocal->GetOverallVolume());
242
+ const FSoundControlBusMixStage MusicControlBusMixStage = UAudioModulationStatics::CreateBusMixStage(World, MusicControlBus, LyraSettingsLocal->GetMusicVolume());
243
+ const FSoundControlBusMixStage SoundFXControlBusMixStage = UAudioModulationStatics::CreateBusMixStage(World, SoundFXControlBus, LyraSettingsLocal->GetSoundFXVolume());
244
+ const FSoundControlBusMixStage DialogueControlBusMixStage = UAudioModulationStatics::CreateBusMixStage(World, DialogueControlBus, LyraSettingsLocal->GetDialogueVolume());
245
+ const FSoundControlBusMixStage VoiceChatControlBusMixStage = UAudioModulationStatics::CreateBusMixStage(World, VoiceChatControlBus, LyraSettingsLocal->GetVoiceChatVolume());
246
+
247
+ TArray<FSoundControlBusMixStage> ControlBusMixStageArray;
248
+ ControlBusMixStageArray.Add(OverallControlBusMixStage);
249
+ ControlBusMixStageArray.Add(MusicControlBusMixStage);
250
+ ControlBusMixStageArray.Add(SoundFXControlBusMixStage);
251
+ ControlBusMixStageArray.Add(DialogueControlBusMixStage);
252
+ ControlBusMixStageArray.Add(VoiceChatControlBusMixStage);
253
+
254
+ UAudioModulationStatics::UpdateMix(World, UserMix, ControlBusMixStageArray);
255
+ }
256
+ }
257
+
258
+ ApplyDynamicRangeEffectsChains(LyraSettingsLocal->IsHDRAudioModeEnabled());
259
+ }
260
+ }
261
+ }
262
+
263
+ void ULyraAudioMixEffectsSubsystem::ApplyDynamicRangeEffectsChains(bool bHDRAudio)
264
+ {
265
+ TArray<FLyraAudioSubmixEffectsChain> AudioSubmixEffectsChainToApply;
266
+ TArray<FLyraAudioSubmixEffectsChain> AudioSubmixEffectsChainToClear;
267
+
268
+ // If HDR Audio is selected, then we clear out any existing LDR Submix Effect Chain Overrides
269
+ // otherwise the reverse is the case.
270
+ if (bHDRAudio)
271
+ {
272
+ AudioSubmixEffectsChainToApply.Append(HDRSubmixEffectChain);
273
+ AudioSubmixEffectsChainToClear.Append(LDRSubmixEffectChain);
274
+ }
275
+ else
276
+ {
277
+ AudioSubmixEffectsChainToApply.Append(LDRSubmixEffectChain);
278
+ AudioSubmixEffectsChainToClear.Append(HDRSubmixEffectChain);
279
+ }
280
+
281
+ // We want to collect just the submixes we need to actually clear, otherwise they'll be overridden by the new settings
282
+ TArray<USoundSubmix*> SubmixesLeftToClear;
283
+
284
+ // We want to get the submixes that are not being overridden by the new effect chains, so we can clear those out separately
285
+ for (const FLyraAudioSubmixEffectsChain& EffectChainToClear : AudioSubmixEffectsChainToClear)
286
+ {
287
+ bool bAddToList = true;
288
+
289
+ for (const FLyraAudioSubmixEffectsChain& SubmixEffectChain : AudioSubmixEffectsChainToApply)
290
+ {
291
+ if (SubmixEffectChain.Submix == EffectChainToClear.Submix)
292
+ {
293
+ bAddToList = false;
294
+
295
+ break;
296
+ }
297
+ }
298
+
299
+ if (bAddToList)
300
+ {
301
+ SubmixesLeftToClear.Add(EffectChainToClear.Submix);
302
+ }
303
+ }
304
+
305
+
306
+ // Override submixes
307
+ for (const FLyraAudioSubmixEffectsChain& SubmixEffectChain : AudioSubmixEffectsChainToApply)
308
+ {
309
+ if (SubmixEffectChain.Submix)
310
+ {
311
+ UAudioMixerBlueprintLibrary::SetSubmixEffectChainOverride(GetWorld(), SubmixEffectChain.Submix, SubmixEffectChain.SubmixEffectChain, 0.1f);
312
+
313
+ }
314
+ }
315
+
316
+ // Clear remaining submixes
317
+ for (USoundSubmix* Submix : SubmixesLeftToClear)
318
+ {
319
+ UAudioMixerBlueprintLibrary::ClearSubmixEffectChainOverride(GetWorld(), Submix, 0.1f);
320
+ }
321
+ }
322
+
323
+ void ULyraAudioMixEffectsSubsystem::OnLoadingScreenStatusChanged(bool bShowingLoadingScreen)
324
+ {
325
+ ApplyOrRemoveLoadingScreenMix(bShowingLoadingScreen);
326
+ }
327
+
328
+ void ULyraAudioMixEffectsSubsystem::ApplyOrRemoveLoadingScreenMix(bool bWantsLoadingScreenMix)
329
+ {
330
+ UWorld* World = GetWorld();
331
+
332
+ if (bAppliedLoadingScreenMix != bWantsLoadingScreenMix && LoadingScreenMix && World)
333
+ {
334
+ if (bWantsLoadingScreenMix)
335
+ {
336
+ // Apply the mix
337
+ UAudioModulationStatics::ActivateBusMix(World, LoadingScreenMix);
338
+ }
339
+ else
340
+ {
341
+ // Remove the mix
342
+ UAudioModulationStatics::DeactivateBusMix(World, LoadingScreenMix);
343
+ }
344
+ bAppliedLoadingScreenMix = bWantsLoadingScreenMix;
345
+ }
346
+ }
347
+
348
+ bool ULyraAudioMixEffectsSubsystem::DoesSupportWorldType(const EWorldType::Type World) const
349
+ {
350
+ // We only need this subsystem on Game worlds (PIE included)
351
+ return (World == EWorldType::Game || World == EWorldType::PIE);
352
+ }
353
+
LyraStarterGame/Source/LyraGame/Audio/LyraAudioMixEffectsSubsystem.h ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "Subsystems/WorldSubsystem.h"
6
+
7
+ #include "LyraAudioMixEffectsSubsystem.generated.h"
8
+
9
+ #define UE_API LYRAGAME_API
10
+
11
+ class FSubsystemCollectionBase;
12
+ class UObject;
13
+ class USoundControlBus;
14
+ class USoundControlBusMix;
15
+ class USoundEffectSubmixPreset;
16
+ class USoundSubmix;
17
+ class UWorld;
18
+
19
+ USTRUCT()
20
+ struct FLyraAudioSubmixEffectsChain
21
+ {
22
+ GENERATED_BODY()
23
+
24
+ // Submix on which to apply the Submix Effect Chain Override
25
+ UPROPERTY(Transient)
26
+ TObjectPtr<USoundSubmix> Submix = nullptr;
27
+
28
+ // Submix Effect Chain Override (Effects processed in Array index order)
29
+ UPROPERTY(Transient)
30
+ TArray<TObjectPtr<USoundEffectSubmixPreset>> SubmixEffectChain;
31
+ };
32
+
33
+ /**
34
+ * This subsystem is meant to automatically engage default and user control bus mixes
35
+ * to retrieve previously saved user settings and apply them to the activated user mix.
36
+ * Additionally, this subsystem will automatically apply HDR/LDR Audio Submix Effect Chain Overrides
37
+ * based on the user's preference for HDR Audio. Submix Effect Chain Overrides are defined in the
38
+ * Lyra Audio Settings.
39
+ */
40
+ UCLASS(MinimalAPI)
41
+ class ULyraAudioMixEffectsSubsystem : public UWorldSubsystem
42
+ {
43
+ GENERATED_BODY()
44
+
45
+ public:
46
+ // USubsystem implementation Begin
47
+ UE_API virtual void Initialize(FSubsystemCollectionBase& Collection) override;
48
+ UE_API virtual void Deinitialize() override;
49
+ // USubsystem implementation End
50
+
51
+ UE_API virtual bool ShouldCreateSubsystem(UObject* Outer) const override;
52
+
53
+ /** Called once all UWorldSubsystems have been initialized */
54
+ UE_API virtual void PostInitialize() override;
55
+
56
+ /** Called when world is ready to start gameplay before the game mode transitions to the correct state and call BeginPlay on all actors */
57
+ UE_API virtual void OnWorldBeginPlay(UWorld& InWorld) override;
58
+
59
+ /** Set whether the HDR Audio Submix Effect Chain Override settings are applied */
60
+ UE_API void ApplyDynamicRangeEffectsChains(bool bHDRAudio);
61
+
62
+ protected:
63
+ UE_API void OnLoadingScreenStatusChanged(bool bShowingLoadingScreen);
64
+ UE_API void ApplyOrRemoveLoadingScreenMix(bool bWantsLoadingScreenMix);
65
+
66
+ // Called when determining whether to create this Subsystem
67
+ UE_API virtual bool DoesSupportWorldType(const EWorldType::Type WorldType) const override;
68
+
69
+ // Default Sound Control Bus Mix retrieved from the Lyra Audio Settings
70
+ UPROPERTY(Transient)
71
+ TObjectPtr<USoundControlBusMix> DefaultBaseMix = nullptr;
72
+
73
+ // Loading Screen Sound Control Bus Mix retrieved from the Lyra Audio Settings
74
+ UPROPERTY(Transient)
75
+ TObjectPtr<USoundControlBusMix> LoadingScreenMix = nullptr;
76
+
77
+ // User Sound Control Bus Mix retrieved from the Lyra Audio Settings
78
+ UPROPERTY(Transient)
79
+ TObjectPtr<USoundControlBusMix> UserMix = nullptr;
80
+
81
+ // Overall Sound Control Bus retrieved from the Lyra Audio Settings and linked to the UI and game settings in LyraSettingsLocal
82
+ UPROPERTY(Transient)
83
+ TObjectPtr<USoundControlBus> OverallControlBus = nullptr;
84
+
85
+ // Music Sound Control Bus retrieved from the Lyra Audio Settings and linked to the UI and game settings in LyraSettingsLocal
86
+ UPROPERTY(Transient)
87
+ TObjectPtr<USoundControlBus> MusicControlBus = nullptr;
88
+
89
+ // SoundFX Sound Control Bus retrieved from the Lyra Audio Settings and linked to the UI and game settings in LyraSettingsLocal
90
+ UPROPERTY(Transient)
91
+ TObjectPtr<USoundControlBus> SoundFXControlBus = nullptr;
92
+
93
+ // Dialogue Sound Control Bus retrieved from the Lyra Audio Settings and linked to the UI and game settings in LyraSettingsLocal
94
+ UPROPERTY(Transient)
95
+ TObjectPtr<USoundControlBus> DialogueControlBus = nullptr;
96
+
97
+ // VoiceChat Sound Control Bus retrieved from the Lyra Audio Settings and linked to the UI and game settings in LyraSettingsLocal
98
+ UPROPERTY(Transient)
99
+ TObjectPtr<USoundControlBus> VoiceChatControlBus = nullptr;
100
+
101
+ // Submix Effect Chain Overrides to apply when HDR Audio is turned on
102
+ UPROPERTY(Transient)
103
+ TArray<FLyraAudioSubmixEffectsChain> HDRSubmixEffectChain;
104
+
105
+ // Submix Effect hain Overrides to apply when HDR Audio is turned off
106
+ UPROPERTY(Transient)
107
+ TArray<FLyraAudioSubmixEffectsChain> LDRSubmixEffectChain;
108
+
109
+ bool bAppliedLoadingScreenMix = false;
110
+ };
111
+
112
+ #undef UE_API
LyraStarterGame/Source/LyraGame/Audio/LyraAudioSettings.cpp ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+
4
+ #include "Audio/LyraAudioSettings.h"
5
+
6
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraAudioSettings)
7
+
8
+
LyraStarterGame/Source/LyraGame/Audio/LyraAudioSettings.h ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "Engine/DeveloperSettings.h"
6
+ #include "UObject/SoftObjectPtr.h"
7
+
8
+ #include "LyraAudioSettings.generated.h"
9
+
10
+ class UObject;
11
+ class USoundEffectSubmixPreset;
12
+ class USoundSubmix;
13
+
14
+ USTRUCT()
15
+ struct FLyraSubmixEffectChainMap
16
+ {
17
+ GENERATED_BODY()
18
+
19
+ UPROPERTY(EditAnywhere, meta = (AllowedClasses = "/Script/Engine.SoundSubmix"))
20
+ TSoftObjectPtr<USoundSubmix> Submix = nullptr;
21
+
22
+ UPROPERTY(EditAnywhere, meta = (AllowedClasses = "/Script/Engine.SoundEffectSubmixPreset"))
23
+ TArray<TSoftObjectPtr<USoundEffectSubmixPreset>> SubmixEffectChain;
24
+
25
+ };
26
+
27
+ /**
28
+ *
29
+ */
30
+ UCLASS(MinimalAPI, config = Game, defaultconfig, meta = (DisplayName = "LyraAudioSettings"))
31
+ class ULyraAudioSettings : public UDeveloperSettings
32
+ {
33
+ GENERATED_BODY()
34
+
35
+ public:
36
+
37
+ /** The Default Base Control Bus Mix */
38
+ UPROPERTY(config, EditAnywhere, Category = MixSettings, meta = (AllowedClasses = "/Script/AudioModulation.SoundControlBusMix"))
39
+ FSoftObjectPath DefaultControlBusMix;
40
+
41
+ /** The Loading Screen Control Bus Mix - Called during loading screens to cover background audio events */
42
+ UPROPERTY(config, EditAnywhere, Category = MixSettings, meta = (AllowedClasses = "/Script/AudioModulation.SoundControlBusMix"))
43
+ FSoftObjectPath LoadingScreenControlBusMix;
44
+
45
+ /** The Default Base Control Bus Mix */
46
+ UPROPERTY(config, EditAnywhere, Category = UserMixSettings, meta = (AllowedClasses = "/Script/AudioModulation.SoundControlBusMix"))
47
+ FSoftObjectPath UserSettingsControlBusMix;
48
+
49
+ /** Control Bus assigned to the Overall sound volume setting */
50
+ UPROPERTY(config, EditAnywhere, Category = UserMixSettings, meta = (AllowedClasses = "/Script/AudioModulation.SoundControlBus"))
51
+ FSoftObjectPath OverallVolumeControlBus;
52
+
53
+ /** Control Bus assigned to the Music sound volume setting */
54
+ UPROPERTY(config, EditAnywhere, Category = UserMixSettings, meta = (AllowedClasses = "/Script/AudioModulation.SoundControlBus"))
55
+ FSoftObjectPath MusicVolumeControlBus;
56
+
57
+ /** Control Bus assigned to the SoundFX sound volume setting */
58
+ UPROPERTY(config, EditAnywhere, Category = UserMixSettings, meta = (AllowedClasses = "/Script/AudioModulation.SoundControlBus"))
59
+ FSoftObjectPath SoundFXVolumeControlBus;
60
+
61
+ /** Control Bus assigned to the Dialogue sound volume setting */
62
+ UPROPERTY(config, EditAnywhere, Category = UserMixSettings, meta = (AllowedClasses = "/Script/AudioModulation.SoundControlBus"))
63
+ FSoftObjectPath DialogueVolumeControlBus;
64
+
65
+ /** Control Bus assigned to the VoiceChat sound volume setting */
66
+ UPROPERTY(config, EditAnywhere, Category = UserMixSettings, meta = (AllowedClasses = "/Script/AudioModulation.SoundControlBus"))
67
+ FSoftObjectPath VoiceChatVolumeControlBus;
68
+
69
+ /** Submix Processing Chains to achieve high dynamic range audio output */
70
+ UPROPERTY(config, EditAnywhere, Category = EffectSettings)
71
+ TArray<FLyraSubmixEffectChainMap> HDRAudioSubmixEffectChain;
72
+
73
+ /** Submix Processing Chains to achieve low dynamic range audio output */
74
+ UPROPERTY(config, EditAnywhere, Category = EffectSettings)
75
+ TArray<FLyraSubmixEffectChainMap> LDRAudioSubmixEffectChain;
76
+
77
+ private:
78
+
79
+
80
+ };
LyraStarterGame/Source/LyraGame/Camera/LyraCameraAssistInterface.h ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "CoreMinimal.h"
6
+ #include "UObject/Interface.h"
7
+
8
+ #include "LyraCameraAssistInterface.generated.h"
9
+
10
+ /** */
11
+ UINTERFACE(BlueprintType)
12
+ class ULyraCameraAssistInterface : public UInterface
13
+ {
14
+ GENERATED_BODY()
15
+ };
16
+
17
+ class ILyraCameraAssistInterface
18
+ {
19
+ GENERATED_BODY()
20
+
21
+ public:
22
+ /**
23
+ * Get the list of actors that we're allowing the camera to penetrate. Useful in 3rd person cameras
24
+ * when you need the following camera to ignore things like the a collection of view targets, the pawn,
25
+ * a vehicle..etc.
26
+ */
27
+ virtual void GetIgnoredActorsForCameraPentration(TArray<const AActor*>& OutActorsAllowPenetration) const { }
28
+
29
+ /**
30
+ * The target actor to prevent penetration on. Normally, this is almost always the view target, which if
31
+ * unimplemented will remain true. However, sometimes the view target, isn't the same as the root actor
32
+ * you need to keep in frame.
33
+ */
34
+ virtual TOptional<AActor*> GetCameraPreventPenetrationTarget() const
35
+ {
36
+ return TOptional<AActor*>();
37
+ }
38
+
39
+ /** Called if the camera penetrates the focal target. Useful if you want to hide the target actor when being overlapped. */
40
+ virtual void OnCameraPenetratingTarget() { }
41
+ };
LyraStarterGame/Source/LyraGame/Camera/LyraCameraComponent.cpp ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraCameraComponent.h"
4
+
5
+ #include "Engine/Canvas.h"
6
+ #include "Engine/Engine.h"
7
+ #include "GameFramework/Pawn.h"
8
+ #include "GameFramework/PlayerController.h"
9
+ #include "LyraCameraMode.h"
10
+
11
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraCameraComponent)
12
+
13
+
14
+ ULyraCameraComponent::ULyraCameraComponent(const FObjectInitializer& ObjectInitializer)
15
+ : Super(ObjectInitializer)
16
+ {
17
+ CameraModeStack = nullptr;
18
+ FieldOfViewOffset = 0.0f;
19
+ }
20
+
21
+ void ULyraCameraComponent::OnRegister()
22
+ {
23
+ Super::OnRegister();
24
+
25
+ if (!CameraModeStack)
26
+ {
27
+ CameraModeStack = NewObject<ULyraCameraModeStack>(this);
28
+ check(CameraModeStack);
29
+ }
30
+ }
31
+
32
+ void ULyraCameraComponent::GetCameraView(float DeltaTime, FMinimalViewInfo& DesiredView)
33
+ {
34
+ check(CameraModeStack);
35
+
36
+ UpdateCameraModes();
37
+
38
+ FLyraCameraModeView CameraModeView;
39
+ CameraModeStack->EvaluateStack(DeltaTime, CameraModeView);
40
+
41
+ // Keep player controller in sync with the latest view.
42
+ if (APawn* TargetPawn = Cast<APawn>(GetTargetActor()))
43
+ {
44
+ if (APlayerController* PC = TargetPawn->GetController<APlayerController>())
45
+ {
46
+ PC->SetControlRotation(CameraModeView.ControlRotation);
47
+ }
48
+ }
49
+
50
+ // Apply any offset that was added to the field of view.
51
+ CameraModeView.FieldOfView += FieldOfViewOffset;
52
+ FieldOfViewOffset = 0.0f;
53
+
54
+ // Keep camera component in sync with the latest view.
55
+ SetWorldLocationAndRotation(CameraModeView.Location, CameraModeView.Rotation);
56
+ FieldOfView = CameraModeView.FieldOfView;
57
+
58
+ // Fill in desired view.
59
+ DesiredView.Location = CameraModeView.Location;
60
+ DesiredView.Rotation = CameraModeView.Rotation;
61
+ DesiredView.FOV = CameraModeView.FieldOfView;
62
+ DesiredView.OrthoWidth = OrthoWidth;
63
+ DesiredView.OrthoNearClipPlane = OrthoNearClipPlane;
64
+ DesiredView.OrthoFarClipPlane = OrthoFarClipPlane;
65
+ DesiredView.AspectRatio = AspectRatio;
66
+ DesiredView.bConstrainAspectRatio = bConstrainAspectRatio;
67
+ DesiredView.bUseFieldOfViewForLOD = bUseFieldOfViewForLOD;
68
+ DesiredView.ProjectionMode = ProjectionMode;
69
+
70
+ // See if the CameraActor wants to override the PostProcess settings used.
71
+ DesiredView.PostProcessBlendWeight = PostProcessBlendWeight;
72
+ if (PostProcessBlendWeight > 0.0f)
73
+ {
74
+ DesiredView.PostProcessSettings = PostProcessSettings;
75
+ }
76
+
77
+
78
+ if (IsXRHeadTrackedCamera())
79
+ {
80
+ // In XR much of the camera behavior above is irrellevant, but the post process settings are not.
81
+ Super::GetCameraView(DeltaTime, DesiredView);
82
+ }
83
+ }
84
+
85
+ void ULyraCameraComponent::UpdateCameraModes()
86
+ {
87
+ check(CameraModeStack);
88
+
89
+ if (CameraModeStack->IsStackActivate())
90
+ {
91
+ if (DetermineCameraModeDelegate.IsBound())
92
+ {
93
+ if (const TSubclassOf<ULyraCameraMode> CameraMode = DetermineCameraModeDelegate.Execute())
94
+ {
95
+ CameraModeStack->PushCameraMode(CameraMode);
96
+ }
97
+ }
98
+ }
99
+ }
100
+
101
+ void ULyraCameraComponent::DrawDebug(UCanvas* Canvas) const
102
+ {
103
+ check(Canvas);
104
+
105
+ FDisplayDebugManager& DisplayDebugManager = Canvas->DisplayDebugManager;
106
+
107
+ DisplayDebugManager.SetFont(GEngine->GetSmallFont());
108
+ DisplayDebugManager.SetDrawColor(FColor::Yellow);
109
+ DisplayDebugManager.DrawString(FString::Printf(TEXT("LyraCameraComponent: %s"), *GetNameSafe(GetTargetActor())));
110
+
111
+ DisplayDebugManager.SetDrawColor(FColor::White);
112
+ DisplayDebugManager.DrawString(FString::Printf(TEXT(" Location: %s"), *GetComponentLocation().ToCompactString()));
113
+ DisplayDebugManager.DrawString(FString::Printf(TEXT(" Rotation: %s"), *GetComponentRotation().ToCompactString()));
114
+ DisplayDebugManager.DrawString(FString::Printf(TEXT(" FOV: %f"), FieldOfView));
115
+
116
+ check(CameraModeStack);
117
+ CameraModeStack->DrawDebug(Canvas);
118
+ }
119
+
120
+ void ULyraCameraComponent::GetBlendInfo(float& OutWeightOfTopLayer, FGameplayTag& OutTagOfTopLayer) const
121
+ {
122
+ check(CameraModeStack);
123
+ CameraModeStack->GetBlendInfo(/*out*/ OutWeightOfTopLayer, /*out*/ OutTagOfTopLayer);
124
+ }
125
+
126
+
LyraStarterGame/Source/LyraGame/Camera/LyraCameraComponent.h ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "Camera/CameraComponent.h"
6
+ #include "GameFramework/Actor.h"
7
+
8
+ #include "LyraCameraComponent.generated.h"
9
+
10
+ class UCanvas;
11
+ class ULyraCameraMode;
12
+ class ULyraCameraModeStack;
13
+ class UObject;
14
+ struct FFrame;
15
+ struct FGameplayTag;
16
+ struct FMinimalViewInfo;
17
+ template <class TClass> class TSubclassOf;
18
+
19
+ DECLARE_DELEGATE_RetVal(TSubclassOf<ULyraCameraMode>, FLyraCameraModeDelegate);
20
+
21
+
22
+ /**
23
+ * ULyraCameraComponent
24
+ *
25
+ * The base camera component class used by this project.
26
+ */
27
+ UCLASS()
28
+ class ULyraCameraComponent : public UCameraComponent
29
+ {
30
+ GENERATED_BODY()
31
+
32
+ public:
33
+
34
+ ULyraCameraComponent(const FObjectInitializer& ObjectInitializer);
35
+
36
+ // Returns the camera component if one exists on the specified actor.
37
+ UFUNCTION(BlueprintPure, Category = "Lyra|Camera")
38
+ static ULyraCameraComponent* FindCameraComponent(const AActor* Actor) { return (Actor ? Actor->FindComponentByClass<ULyraCameraComponent>() : nullptr); }
39
+
40
+ // Returns the target actor that the camera is looking at.
41
+ virtual AActor* GetTargetActor() const { return GetOwner(); }
42
+
43
+ // Delegate used to query for the best camera mode.
44
+ FLyraCameraModeDelegate DetermineCameraModeDelegate;
45
+
46
+ // Add an offset to the field of view. The offset is only for one frame, it gets cleared once it is applied.
47
+ void AddFieldOfViewOffset(float FovOffset) { FieldOfViewOffset += FovOffset; }
48
+
49
+ virtual void DrawDebug(UCanvas* Canvas) const;
50
+
51
+ // Gets the tag associated with the top layer and the blend weight of it
52
+ void GetBlendInfo(float& OutWeightOfTopLayer, FGameplayTag& OutTagOfTopLayer) const;
53
+
54
+ protected:
55
+
56
+ virtual void OnRegister() override;
57
+ virtual void GetCameraView(float DeltaTime, FMinimalViewInfo& DesiredView) override;
58
+
59
+ virtual void UpdateCameraModes();
60
+
61
+ protected:
62
+
63
+ // Stack used to blend the camera modes.
64
+ UPROPERTY()
65
+ TObjectPtr<ULyraCameraModeStack> CameraModeStack;
66
+
67
+ // Offset applied to the field of view. The offset is only for one frame, it gets cleared once it is applied.
68
+ float FieldOfViewOffset;
69
+
70
+ };
LyraStarterGame/Source/LyraGame/Camera/LyraCameraMode.cpp ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraCameraMode.h"
4
+
5
+ #include "Components/CapsuleComponent.h"
6
+ #include "Engine/Canvas.h"
7
+ #include "GameFramework/Character.h"
8
+ #include "LyraCameraComponent.h"
9
+ #include "LyraPlayerCameraManager.h"
10
+
11
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraCameraMode)
12
+
13
+
14
+ //////////////////////////////////////////////////////////////////////////
15
+ // FLyraCameraModeView
16
+ //////////////////////////////////////////////////////////////////////////
17
+ FLyraCameraModeView::FLyraCameraModeView()
18
+ : Location(ForceInit)
19
+ , Rotation(ForceInit)
20
+ , ControlRotation(ForceInit)
21
+ , FieldOfView(LYRA_CAMERA_DEFAULT_FOV)
22
+ {
23
+ }
24
+
25
+ void FLyraCameraModeView::Blend(const FLyraCameraModeView& Other, float OtherWeight)
26
+ {
27
+ if (OtherWeight <= 0.0f)
28
+ {
29
+ return;
30
+ }
31
+ else if (OtherWeight >= 1.0f)
32
+ {
33
+ *this = Other;
34
+ return;
35
+ }
36
+
37
+ Location = FMath::Lerp(Location, Other.Location, OtherWeight);
38
+
39
+ const FRotator DeltaRotation = (Other.Rotation - Rotation).GetNormalized();
40
+ Rotation = Rotation + (OtherWeight * DeltaRotation);
41
+
42
+ const FRotator DeltaControlRotation = (Other.ControlRotation - ControlRotation).GetNormalized();
43
+ ControlRotation = ControlRotation + (OtherWeight * DeltaControlRotation);
44
+
45
+ FieldOfView = FMath::Lerp(FieldOfView, Other.FieldOfView, OtherWeight);
46
+ }
47
+
48
+
49
+ //////////////////////////////////////////////////////////////////////////
50
+ // ULyraCameraMode
51
+ //////////////////////////////////////////////////////////////////////////
52
+ ULyraCameraMode::ULyraCameraMode()
53
+ {
54
+ FieldOfView = LYRA_CAMERA_DEFAULT_FOV;
55
+ ViewPitchMin = LYRA_CAMERA_DEFAULT_PITCH_MIN;
56
+ ViewPitchMax = LYRA_CAMERA_DEFAULT_PITCH_MAX;
57
+
58
+ BlendTime = 0.5f;
59
+ BlendFunction = ELyraCameraModeBlendFunction::EaseOut;
60
+ BlendExponent = 4.0f;
61
+ BlendAlpha = 1.0f;
62
+ BlendWeight = 1.0f;
63
+ }
64
+
65
+ ULyraCameraComponent* ULyraCameraMode::GetLyraCameraComponent() const
66
+ {
67
+ return CastChecked<ULyraCameraComponent>(GetOuter());
68
+ }
69
+
70
+ UWorld* ULyraCameraMode::GetWorld() const
71
+ {
72
+ return HasAnyFlags(RF_ClassDefaultObject) ? nullptr : GetOuter()->GetWorld();
73
+ }
74
+
75
+ AActor* ULyraCameraMode::GetTargetActor() const
76
+ {
77
+ const ULyraCameraComponent* LyraCameraComponent = GetLyraCameraComponent();
78
+
79
+ return LyraCameraComponent->GetTargetActor();
80
+ }
81
+
82
+ FVector ULyraCameraMode::GetPivotLocation() const
83
+ {
84
+ const AActor* TargetActor = GetTargetActor();
85
+ check(TargetActor);
86
+
87
+ if (const APawn* TargetPawn = Cast<APawn>(TargetActor))
88
+ {
89
+ // Height adjustments for characters to account for crouching.
90
+ if (const ACharacter* TargetCharacter = Cast<ACharacter>(TargetPawn))
91
+ {
92
+ const ACharacter* TargetCharacterCDO = TargetCharacter->GetClass()->GetDefaultObject<ACharacter>();
93
+ check(TargetCharacterCDO);
94
+
95
+ const UCapsuleComponent* CapsuleComp = TargetCharacter->GetCapsuleComponent();
96
+ check(CapsuleComp);
97
+
98
+ const UCapsuleComponent* CapsuleCompCDO = TargetCharacterCDO->GetCapsuleComponent();
99
+ check(CapsuleCompCDO);
100
+
101
+ const float DefaultHalfHeight = CapsuleCompCDO->GetUnscaledCapsuleHalfHeight();
102
+ const float ActualHalfHeight = CapsuleComp->GetUnscaledCapsuleHalfHeight();
103
+ const float HeightAdjustment = (DefaultHalfHeight - ActualHalfHeight) + TargetCharacterCDO->BaseEyeHeight;
104
+
105
+ return TargetCharacter->GetActorLocation() + (FVector::UpVector * HeightAdjustment);
106
+ }
107
+
108
+ return TargetPawn->GetPawnViewLocation();
109
+ }
110
+
111
+ return TargetActor->GetActorLocation();
112
+ }
113
+
114
+ FRotator ULyraCameraMode::GetPivotRotation() const
115
+ {
116
+ const AActor* TargetActor = GetTargetActor();
117
+ check(TargetActor);
118
+
119
+ if (const APawn* TargetPawn = Cast<APawn>(TargetActor))
120
+ {
121
+ return TargetPawn->GetViewRotation();
122
+ }
123
+
124
+ return TargetActor->GetActorRotation();
125
+ }
126
+
127
+ void ULyraCameraMode::UpdateCameraMode(float DeltaTime)
128
+ {
129
+ UpdateView(DeltaTime);
130
+ UpdateBlending(DeltaTime);
131
+ }
132
+
133
+ void ULyraCameraMode::UpdateView(float DeltaTime)
134
+ {
135
+ FVector PivotLocation = GetPivotLocation();
136
+ FRotator PivotRotation = GetPivotRotation();
137
+
138
+ PivotRotation.Pitch = FMath::ClampAngle(PivotRotation.Pitch, ViewPitchMin, ViewPitchMax);
139
+
140
+ View.Location = PivotLocation;
141
+ View.Rotation = PivotRotation;
142
+ View.ControlRotation = View.Rotation;
143
+ View.FieldOfView = FieldOfView;
144
+ }
145
+
146
+ void ULyraCameraMode::SetBlendWeight(float Weight)
147
+ {
148
+ BlendWeight = FMath::Clamp(Weight, 0.0f, 1.0f);
149
+
150
+ // Since we're setting the blend weight directly, we need to calculate the blend alpha to account for the blend function.
151
+ const float InvExponent = (BlendExponent > 0.0f) ? (1.0f / BlendExponent) : 1.0f;
152
+
153
+ switch (BlendFunction)
154
+ {
155
+ case ELyraCameraModeBlendFunction::Linear:
156
+ BlendAlpha = BlendWeight;
157
+ break;
158
+
159
+ case ELyraCameraModeBlendFunction::EaseIn:
160
+ BlendAlpha = FMath::InterpEaseIn(0.0f, 1.0f, BlendWeight, InvExponent);
161
+ break;
162
+
163
+ case ELyraCameraModeBlendFunction::EaseOut:
164
+ BlendAlpha = FMath::InterpEaseOut(0.0f, 1.0f, BlendWeight, InvExponent);
165
+ break;
166
+
167
+ case ELyraCameraModeBlendFunction::EaseInOut:
168
+ BlendAlpha = FMath::InterpEaseInOut(0.0f, 1.0f, BlendWeight, InvExponent);
169
+ break;
170
+
171
+ default:
172
+ checkf(false, TEXT("SetBlendWeight: Invalid BlendFunction [%d]\n"), (uint8)BlendFunction);
173
+ break;
174
+ }
175
+ }
176
+
177
+ void ULyraCameraMode::UpdateBlending(float DeltaTime)
178
+ {
179
+ if (BlendTime > 0.0f)
180
+ {
181
+ BlendAlpha += (DeltaTime / BlendTime);
182
+ BlendAlpha = FMath::Min(BlendAlpha, 1.0f);
183
+ }
184
+ else
185
+ {
186
+ BlendAlpha = 1.0f;
187
+ }
188
+
189
+ const float Exponent = (BlendExponent > 0.0f) ? BlendExponent : 1.0f;
190
+
191
+ switch (BlendFunction)
192
+ {
193
+ case ELyraCameraModeBlendFunction::Linear:
194
+ BlendWeight = BlendAlpha;
195
+ break;
196
+
197
+ case ELyraCameraModeBlendFunction::EaseIn:
198
+ BlendWeight = FMath::InterpEaseIn(0.0f, 1.0f, BlendAlpha, Exponent);
199
+ break;
200
+
201
+ case ELyraCameraModeBlendFunction::EaseOut:
202
+ BlendWeight = FMath::InterpEaseOut(0.0f, 1.0f, BlendAlpha, Exponent);
203
+ break;
204
+
205
+ case ELyraCameraModeBlendFunction::EaseInOut:
206
+ BlendWeight = FMath::InterpEaseInOut(0.0f, 1.0f, BlendAlpha, Exponent);
207
+ break;
208
+
209
+ default:
210
+ checkf(false, TEXT("UpdateBlending: Invalid BlendFunction [%d]\n"), (uint8)BlendFunction);
211
+ break;
212
+ }
213
+ }
214
+
215
+ void ULyraCameraMode::DrawDebug(UCanvas* Canvas) const
216
+ {
217
+ check(Canvas);
218
+
219
+ FDisplayDebugManager& DisplayDebugManager = Canvas->DisplayDebugManager;
220
+
221
+ DisplayDebugManager.SetDrawColor(FColor::White);
222
+ DisplayDebugManager.DrawString(FString::Printf(TEXT(" LyraCameraMode: %s (%f)"), *GetName(), BlendWeight));
223
+ }
224
+
225
+
226
+ //////////////////////////////////////////////////////////////////////////
227
+ // ULyraCameraModeStack
228
+ //////////////////////////////////////////////////////////////////////////
229
+ ULyraCameraModeStack::ULyraCameraModeStack()
230
+ {
231
+ bIsActive = true;
232
+ }
233
+
234
+ void ULyraCameraModeStack::ActivateStack()
235
+ {
236
+ if (!bIsActive)
237
+ {
238
+ bIsActive = true;
239
+
240
+ // Notify camera modes that they are being activated.
241
+ for (ULyraCameraMode* CameraMode : CameraModeStack)
242
+ {
243
+ check(CameraMode);
244
+ CameraMode->OnActivation();
245
+ }
246
+ }
247
+ }
248
+
249
+ void ULyraCameraModeStack::DeactivateStack()
250
+ {
251
+ if (bIsActive)
252
+ {
253
+ bIsActive = false;
254
+
255
+ // Notify camera modes that they are being deactivated.
256
+ for (ULyraCameraMode* CameraMode : CameraModeStack)
257
+ {
258
+ check(CameraMode);
259
+ CameraMode->OnDeactivation();
260
+ }
261
+ }
262
+ }
263
+
264
+ void ULyraCameraModeStack::PushCameraMode(TSubclassOf<ULyraCameraMode> CameraModeClass)
265
+ {
266
+ if (!CameraModeClass)
267
+ {
268
+ return;
269
+ }
270
+
271
+ ULyraCameraMode* CameraMode = GetCameraModeInstance(CameraModeClass);
272
+ check(CameraMode);
273
+
274
+ int32 StackSize = CameraModeStack.Num();
275
+
276
+ if ((StackSize > 0) && (CameraModeStack[0] == CameraMode))
277
+ {
278
+ // Already top of stack.
279
+ return;
280
+ }
281
+
282
+ // See if it's already in the stack and remove it.
283
+ // Figure out how much it was contributing to the stack.
284
+ int32 ExistingStackIndex = INDEX_NONE;
285
+ float ExistingStackContribution = 1.0f;
286
+
287
+ for (int32 StackIndex = 0; StackIndex < StackSize; ++StackIndex)
288
+ {
289
+ if (CameraModeStack[StackIndex] == CameraMode)
290
+ {
291
+ ExistingStackIndex = StackIndex;
292
+ ExistingStackContribution *= CameraMode->GetBlendWeight();
293
+ break;
294
+ }
295
+ else
296
+ {
297
+ ExistingStackContribution *= (1.0f - CameraModeStack[StackIndex]->GetBlendWeight());
298
+ }
299
+ }
300
+
301
+ if (ExistingStackIndex != INDEX_NONE)
302
+ {
303
+ CameraModeStack.RemoveAt(ExistingStackIndex);
304
+ StackSize--;
305
+ }
306
+ else
307
+ {
308
+ ExistingStackContribution = 0.0f;
309
+ }
310
+
311
+ // Decide what initial weight to start with.
312
+ const bool bShouldBlend = ((CameraMode->GetBlendTime() > 0.0f) && (StackSize > 0));
313
+ const float BlendWeight = (bShouldBlend ? ExistingStackContribution : 1.0f);
314
+
315
+ CameraMode->SetBlendWeight(BlendWeight);
316
+
317
+ // Add new entry to top of stack.
318
+ CameraModeStack.Insert(CameraMode, 0);
319
+
320
+ // Make sure stack bottom is always weighted 100%.
321
+ CameraModeStack.Last()->SetBlendWeight(1.0f);
322
+
323
+ // Let the camera mode know if it's being added to the stack.
324
+ if (ExistingStackIndex == INDEX_NONE)
325
+ {
326
+ CameraMode->OnActivation();
327
+ }
328
+ }
329
+
330
+ bool ULyraCameraModeStack::EvaluateStack(float DeltaTime, FLyraCameraModeView& OutCameraModeView)
331
+ {
332
+ if (!bIsActive)
333
+ {
334
+ return false;
335
+ }
336
+
337
+ UpdateStack(DeltaTime);
338
+ BlendStack(OutCameraModeView);
339
+
340
+ return true;
341
+ }
342
+
343
+ ULyraCameraMode* ULyraCameraModeStack::GetCameraModeInstance(TSubclassOf<ULyraCameraMode> CameraModeClass)
344
+ {
345
+ check(CameraModeClass);
346
+
347
+ // First see if we already created one.
348
+ for (ULyraCameraMode* CameraMode : CameraModeInstances)
349
+ {
350
+ if ((CameraMode != nullptr) && (CameraMode->GetClass() == CameraModeClass))
351
+ {
352
+ return CameraMode;
353
+ }
354
+ }
355
+
356
+ // Not found, so we need to create it.
357
+ ULyraCameraMode* NewCameraMode = NewObject<ULyraCameraMode>(GetOuter(), CameraModeClass, NAME_None, RF_NoFlags);
358
+ check(NewCameraMode);
359
+
360
+ CameraModeInstances.Add(NewCameraMode);
361
+
362
+ return NewCameraMode;
363
+ }
364
+
365
+ void ULyraCameraModeStack::UpdateStack(float DeltaTime)
366
+ {
367
+ const int32 StackSize = CameraModeStack.Num();
368
+ if (StackSize <= 0)
369
+ {
370
+ return;
371
+ }
372
+
373
+ int32 RemoveCount = 0;
374
+ int32 RemoveIndex = INDEX_NONE;
375
+
376
+ for (int32 StackIndex = 0; StackIndex < StackSize; ++StackIndex)
377
+ {
378
+ ULyraCameraMode* CameraMode = CameraModeStack[StackIndex];
379
+ check(CameraMode);
380
+
381
+ CameraMode->UpdateCameraMode(DeltaTime);
382
+
383
+ if (CameraMode->GetBlendWeight() >= 1.0f)
384
+ {
385
+ // Everything below this mode is now irrelevant and can be removed.
386
+ RemoveIndex = (StackIndex + 1);
387
+ RemoveCount = (StackSize - RemoveIndex);
388
+ break;
389
+ }
390
+ }
391
+
392
+ if (RemoveCount > 0)
393
+ {
394
+ // Let the camera modes know they being removed from the stack.
395
+ for (int32 StackIndex = RemoveIndex; StackIndex < StackSize; ++StackIndex)
396
+ {
397
+ ULyraCameraMode* CameraMode = CameraModeStack[StackIndex];
398
+ check(CameraMode);
399
+
400
+ CameraMode->OnDeactivation();
401
+ }
402
+
403
+ CameraModeStack.RemoveAt(RemoveIndex, RemoveCount);
404
+ }
405
+ }
406
+
407
+ void ULyraCameraModeStack::BlendStack(FLyraCameraModeView& OutCameraModeView) const
408
+ {
409
+ const int32 StackSize = CameraModeStack.Num();
410
+ if (StackSize <= 0)
411
+ {
412
+ return;
413
+ }
414
+
415
+ // Start at the bottom and blend up the stack
416
+ const ULyraCameraMode* CameraMode = CameraModeStack[StackSize - 1];
417
+ check(CameraMode);
418
+
419
+ OutCameraModeView = CameraMode->GetCameraModeView();
420
+
421
+ for (int32 StackIndex = (StackSize - 2); StackIndex >= 0; --StackIndex)
422
+ {
423
+ CameraMode = CameraModeStack[StackIndex];
424
+ check(CameraMode);
425
+
426
+ OutCameraModeView.Blend(CameraMode->GetCameraModeView(), CameraMode->GetBlendWeight());
427
+ }
428
+ }
429
+
430
+ void ULyraCameraModeStack::DrawDebug(UCanvas* Canvas) const
431
+ {
432
+ check(Canvas);
433
+
434
+ FDisplayDebugManager& DisplayDebugManager = Canvas->DisplayDebugManager;
435
+
436
+ DisplayDebugManager.SetDrawColor(FColor::Green);
437
+ DisplayDebugManager.DrawString(FString(TEXT(" --- Camera Modes (Begin) ---")));
438
+
439
+ for (const ULyraCameraMode* CameraMode : CameraModeStack)
440
+ {
441
+ check(CameraMode);
442
+ CameraMode->DrawDebug(Canvas);
443
+ }
444
+
445
+ DisplayDebugManager.SetDrawColor(FColor::Green);
446
+ DisplayDebugManager.DrawString(FString::Printf(TEXT(" --- Camera Modes (End) ---")));
447
+ }
448
+
449
+ void ULyraCameraModeStack::GetBlendInfo(float& OutWeightOfTopLayer, FGameplayTag& OutTagOfTopLayer) const
450
+ {
451
+ if (CameraModeStack.Num() == 0)
452
+ {
453
+ OutWeightOfTopLayer = 1.0f;
454
+ OutTagOfTopLayer = FGameplayTag();
455
+ return;
456
+ }
457
+ else
458
+ {
459
+ ULyraCameraMode* TopEntry = CameraModeStack.Last();
460
+ check(TopEntry);
461
+ OutWeightOfTopLayer = TopEntry->GetBlendWeight();
462
+ OutTagOfTopLayer = TopEntry->GetCameraTypeTag();
463
+ }
464
+ }
465
+
LyraStarterGame/Source/LyraGame/Camera/LyraCameraMode.h ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "Engine/World.h"
6
+ #include "GameplayTagContainer.h"
7
+
8
+ #include "LyraCameraMode.generated.h"
9
+
10
+ #define UE_API LYRAGAME_API
11
+
12
+ class AActor;
13
+ class UCanvas;
14
+ class ULyraCameraComponent;
15
+
16
+ /**
17
+ * ELyraCameraModeBlendFunction
18
+ *
19
+ * Blend function used for transitioning between camera modes.
20
+ */
21
+ UENUM(BlueprintType)
22
+ enum class ELyraCameraModeBlendFunction : uint8
23
+ {
24
+ // Does a simple linear interpolation.
25
+ Linear,
26
+
27
+ // Immediately accelerates, but smoothly decelerates into the target. Ease amount controlled by the exponent.
28
+ EaseIn,
29
+
30
+ // Smoothly accelerates, but does not decelerate into the target. Ease amount controlled by the exponent.
31
+ EaseOut,
32
+
33
+ // Smoothly accelerates and decelerates. Ease amount controlled by the exponent.
34
+ EaseInOut,
35
+
36
+ COUNT UMETA(Hidden)
37
+ };
38
+
39
+
40
+ /**
41
+ * FLyraCameraModeView
42
+ *
43
+ * View data produced by the camera mode that is used to blend camera modes.
44
+ */
45
+ struct FLyraCameraModeView
46
+ {
47
+ public:
48
+
49
+ FLyraCameraModeView();
50
+
51
+ void Blend(const FLyraCameraModeView& Other, float OtherWeight);
52
+
53
+ public:
54
+
55
+ FVector Location;
56
+ FRotator Rotation;
57
+ FRotator ControlRotation;
58
+ float FieldOfView;
59
+ };
60
+
61
+
62
+ /**
63
+ * ULyraCameraMode
64
+ *
65
+ * Base class for all camera modes.
66
+ */
67
+ UCLASS(MinimalAPI, Abstract, NotBlueprintable)
68
+ class ULyraCameraMode : public UObject
69
+ {
70
+ GENERATED_BODY()
71
+
72
+ public:
73
+
74
+ UE_API ULyraCameraMode();
75
+
76
+ UE_API ULyraCameraComponent* GetLyraCameraComponent() const;
77
+
78
+ UE_API virtual UWorld* GetWorld() const override;
79
+
80
+ UE_API AActor* GetTargetActor() const;
81
+
82
+ const FLyraCameraModeView& GetCameraModeView() const { return View; }
83
+
84
+ // Called when this camera mode is activated on the camera mode stack.
85
+ virtual void OnActivation() {};
86
+
87
+ // Called when this camera mode is deactivated on the camera mode stack.
88
+ virtual void OnDeactivation() {};
89
+
90
+ UE_API void UpdateCameraMode(float DeltaTime);
91
+
92
+ float GetBlendTime() const { return BlendTime; }
93
+ float GetBlendWeight() const { return BlendWeight; }
94
+ UE_API void SetBlendWeight(float Weight);
95
+
96
+ FGameplayTag GetCameraTypeTag() const
97
+ {
98
+ return CameraTypeTag;
99
+ }
100
+
101
+ UE_API virtual void DrawDebug(UCanvas* Canvas) const;
102
+
103
+ protected:
104
+
105
+ UE_API virtual FVector GetPivotLocation() const;
106
+ UE_API virtual FRotator GetPivotRotation() const;
107
+
108
+ UE_API virtual void UpdateView(float DeltaTime);
109
+ UE_API virtual void UpdateBlending(float DeltaTime);
110
+
111
+ protected:
112
+ // A tag that can be queried by gameplay code that cares when a kind of camera mode is active
113
+ // without having to ask about a specific mode (e.g., when aiming downsights to get more accuracy)
114
+ UPROPERTY(EditDefaultsOnly, Category = "Blending")
115
+ FGameplayTag CameraTypeTag;
116
+
117
+ // View output produced by the camera mode.
118
+ FLyraCameraModeView View;
119
+
120
+ // The horizontal field of view (in degrees).
121
+ UPROPERTY(EditDefaultsOnly, Category = "View", Meta = (UIMin = "5.0", UIMax = "170", ClampMin = "5.0", ClampMax = "170.0"))
122
+ float FieldOfView;
123
+
124
+ // Minimum view pitch (in degrees).
125
+ UPROPERTY(EditDefaultsOnly, Category = "View", Meta = (UIMin = "-89.9", UIMax = "89.9", ClampMin = "-89.9", ClampMax = "89.9"))
126
+ float ViewPitchMin;
127
+
128
+ // Maximum view pitch (in degrees).
129
+ UPROPERTY(EditDefaultsOnly, Category = "View", Meta = (UIMin = "-89.9", UIMax = "89.9", ClampMin = "-89.9", ClampMax = "89.9"))
130
+ float ViewPitchMax;
131
+
132
+ // How long it takes to blend in this mode.
133
+ UPROPERTY(EditDefaultsOnly, Category = "Blending")
134
+ float BlendTime;
135
+
136
+ // Function used for blending.
137
+ UPROPERTY(EditDefaultsOnly, Category = "Blending")
138
+ ELyraCameraModeBlendFunction BlendFunction;
139
+
140
+ // Exponent used by blend functions to control the shape of the curve.
141
+ UPROPERTY(EditDefaultsOnly, Category = "Blending")
142
+ float BlendExponent;
143
+
144
+ // Linear blend alpha used to determine the blend weight.
145
+ float BlendAlpha;
146
+
147
+ // Blend weight calculated using the blend alpha and function.
148
+ float BlendWeight;
149
+
150
+ protected:
151
+ /** If true, skips all interpolation and puts camera in ideal location. Automatically set to false next frame. */
152
+ UPROPERTY(transient)
153
+ uint32 bResetInterpolation:1;
154
+ };
155
+
156
+
157
+ /**
158
+ * ULyraCameraModeStack
159
+ *
160
+ * Stack used for blending camera modes.
161
+ */
162
+ UCLASS()
163
+ class ULyraCameraModeStack : public UObject
164
+ {
165
+ GENERATED_BODY()
166
+
167
+ public:
168
+
169
+ ULyraCameraModeStack();
170
+
171
+ void ActivateStack();
172
+ void DeactivateStack();
173
+
174
+ bool IsStackActivate() const { return bIsActive; }
175
+
176
+ void PushCameraMode(TSubclassOf<ULyraCameraMode> CameraModeClass);
177
+
178
+ bool EvaluateStack(float DeltaTime, FLyraCameraModeView& OutCameraModeView);
179
+
180
+ void DrawDebug(UCanvas* Canvas) const;
181
+
182
+ // Gets the tag associated with the top layer and the blend weight of it
183
+ void GetBlendInfo(float& OutWeightOfTopLayer, FGameplayTag& OutTagOfTopLayer) const;
184
+
185
+ protected:
186
+
187
+ ULyraCameraMode* GetCameraModeInstance(TSubclassOf<ULyraCameraMode> CameraModeClass);
188
+
189
+ void UpdateStack(float DeltaTime);
190
+ void BlendStack(FLyraCameraModeView& OutCameraModeView) const;
191
+
192
+ protected:
193
+
194
+ bool bIsActive;
195
+
196
+ UPROPERTY()
197
+ TArray<TObjectPtr<ULyraCameraMode>> CameraModeInstances;
198
+
199
+ UPROPERTY()
200
+ TArray<TObjectPtr<ULyraCameraMode>> CameraModeStack;
201
+ };
202
+
203
+ #undef UE_API
LyraStarterGame/Source/LyraGame/Camera/LyraCameraMode_ThirdPerson.cpp ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraCameraMode_ThirdPerson.h"
4
+ #include "Camera/LyraCameraMode.h"
5
+ #include "Components/PrimitiveComponent.h"
6
+ #include "Camera/LyraPenetrationAvoidanceFeeler.h"
7
+ #include "Curves/CurveVector.h"
8
+ #include "Engine/Canvas.h"
9
+ #include "GameFramework/CameraBlockingVolume.h"
10
+ #include "LyraCameraAssistInterface.h"
11
+ #include "GameFramework/Controller.h"
12
+ #include "GameFramework/Character.h"
13
+ #include "Math/RotationMatrix.h"
14
+
15
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraCameraMode_ThirdPerson)
16
+
17
+ namespace LyraCameraMode_ThirdPerson_Statics
18
+ {
19
+ static const FName NAME_IgnoreCameraCollision = TEXT("IgnoreCameraCollision");
20
+ }
21
+
22
+ ULyraCameraMode_ThirdPerson::ULyraCameraMode_ThirdPerson()
23
+ {
24
+ TargetOffsetCurve = nullptr;
25
+
26
+ PenetrationAvoidanceFeelers.Add(FLyraPenetrationAvoidanceFeeler(FRotator(+00.0f, +00.0f, 0.0f), 1.00f, 1.00f, 14.f, 0));
27
+ PenetrationAvoidanceFeelers.Add(FLyraPenetrationAvoidanceFeeler(FRotator(+00.0f, +16.0f, 0.0f), 0.75f, 0.75f, 00.f, 3));
28
+ PenetrationAvoidanceFeelers.Add(FLyraPenetrationAvoidanceFeeler(FRotator(+00.0f, -16.0f, 0.0f), 0.75f, 0.75f, 00.f, 3));
29
+ PenetrationAvoidanceFeelers.Add(FLyraPenetrationAvoidanceFeeler(FRotator(+00.0f, +32.0f, 0.0f), 0.50f, 0.50f, 00.f, 5));
30
+ PenetrationAvoidanceFeelers.Add(FLyraPenetrationAvoidanceFeeler(FRotator(+00.0f, -32.0f, 0.0f), 0.50f, 0.50f, 00.f, 5));
31
+ PenetrationAvoidanceFeelers.Add(FLyraPenetrationAvoidanceFeeler(FRotator(+20.0f, +00.0f, 0.0f), 1.00f, 1.00f, 00.f, 4));
32
+ PenetrationAvoidanceFeelers.Add(FLyraPenetrationAvoidanceFeeler(FRotator(-20.0f, +00.0f, 0.0f), 0.50f, 0.50f, 00.f, 4));
33
+ }
34
+
35
+ void ULyraCameraMode_ThirdPerson::UpdateView(float DeltaTime)
36
+ {
37
+ UpdateForTarget(DeltaTime);
38
+ UpdateCrouchOffset(DeltaTime);
39
+
40
+ FVector PivotLocation = GetPivotLocation() + CurrentCrouchOffset;
41
+ FRotator PivotRotation = GetPivotRotation();
42
+
43
+ PivotRotation.Pitch = FMath::ClampAngle(PivotRotation.Pitch, ViewPitchMin, ViewPitchMax);
44
+
45
+ View.Location = PivotLocation;
46
+ View.Rotation = PivotRotation;
47
+ View.ControlRotation = View.Rotation;
48
+ View.FieldOfView = FieldOfView;
49
+
50
+ // Apply third person offset using pitch.
51
+ if (!bUseRuntimeFloatCurves)
52
+ {
53
+ if (TargetOffsetCurve)
54
+ {
55
+ const FVector TargetOffset = TargetOffsetCurve->GetVectorValue(PivotRotation.Pitch);
56
+ View.Location = PivotLocation + PivotRotation.RotateVector(TargetOffset);
57
+ }
58
+ }
59
+ else
60
+ {
61
+ FVector TargetOffset(0.0f);
62
+
63
+ TargetOffset.X = TargetOffsetX.GetRichCurveConst()->Eval(PivotRotation.Pitch);
64
+ TargetOffset.Y = TargetOffsetY.GetRichCurveConst()->Eval(PivotRotation.Pitch);
65
+ TargetOffset.Z = TargetOffsetZ.GetRichCurveConst()->Eval(PivotRotation.Pitch);
66
+
67
+ View.Location = PivotLocation + PivotRotation.RotateVector(TargetOffset);
68
+ }
69
+
70
+ // Adjust final desired camera location to prevent any penetration
71
+ UpdatePreventPenetration(DeltaTime);
72
+ }
73
+
74
+ void ULyraCameraMode_ThirdPerson::UpdateForTarget(float DeltaTime)
75
+ {
76
+
77
+ if (const ACharacter* TargetCharacter = Cast<ACharacter>(GetTargetActor()))
78
+ {
79
+ if (TargetCharacter->IsCrouched())
80
+ {
81
+ const ACharacter* TargetCharacterCDO = TargetCharacter->GetClass()->GetDefaultObject<ACharacter>();
82
+ const float CrouchedHeightAdjustment = TargetCharacterCDO->CrouchedEyeHeight - TargetCharacterCDO->BaseEyeHeight;
83
+
84
+ SetTargetCrouchOffset(FVector(0.f, 0.f, CrouchedHeightAdjustment));
85
+
86
+ return;
87
+ }
88
+ }
89
+
90
+ SetTargetCrouchOffset(FVector::ZeroVector);
91
+ }
92
+
93
+ void ULyraCameraMode_ThirdPerson::DrawDebug(UCanvas* Canvas) const
94
+ {
95
+ Super::DrawDebug(Canvas);
96
+
97
+ #if ENABLE_DRAW_DEBUG
98
+ FDisplayDebugManager& DisplayDebugManager = Canvas->DisplayDebugManager;
99
+ for (int i = 0; i < DebugActorsHitDuringCameraPenetration.Num(); i++)
100
+ {
101
+ DisplayDebugManager.DrawString(
102
+ FString::Printf(TEXT("HitActorDuringPenetration[%d]: %s")
103
+ , i
104
+ , *DebugActorsHitDuringCameraPenetration[i]->GetName()));
105
+ }
106
+
107
+ LastDrawDebugTime = GetWorld()->GetTimeSeconds();
108
+ #endif
109
+ }
110
+
111
+ void ULyraCameraMode_ThirdPerson::UpdatePreventPenetration(float DeltaTime)
112
+ {
113
+ if (!bPreventPenetration)
114
+ {
115
+ return;
116
+ }
117
+
118
+ AActor* TargetActor = GetTargetActor();
119
+
120
+ APawn* TargetPawn = Cast<APawn>(TargetActor);
121
+ AController* TargetController = TargetPawn ? TargetPawn->GetController() : nullptr;
122
+ ILyraCameraAssistInterface* TargetControllerAssist = Cast<ILyraCameraAssistInterface>(TargetController);
123
+
124
+ ILyraCameraAssistInterface* TargetActorAssist = Cast<ILyraCameraAssistInterface>(TargetActor);
125
+
126
+ TOptional<AActor*> OptionalPPTarget = TargetActorAssist ? TargetActorAssist->GetCameraPreventPenetrationTarget() : TOptional<AActor*>();
127
+ AActor* PPActor = OptionalPPTarget.IsSet() ? OptionalPPTarget.GetValue() : TargetActor;
128
+ ILyraCameraAssistInterface* PPActorAssist = OptionalPPTarget.IsSet() ? Cast<ILyraCameraAssistInterface>(PPActor) : nullptr;
129
+
130
+ const UPrimitiveComponent* PPActorRootComponent = Cast<UPrimitiveComponent>(PPActor->GetRootComponent());
131
+ if (PPActorRootComponent)
132
+ {
133
+ // Attempt at picking SafeLocation automatically, so we reduce camera translation when aiming.
134
+ // Our camera is our reticle, so we want to preserve our aim and keep that as steady and smooth as possible.
135
+ // Pick closest point on capsule to our aim line.
136
+ FVector ClosestPointOnLineToCapsuleCenter;
137
+ FVector SafeLocation = PPActor->GetActorLocation();
138
+ FMath::PointDistToLine(SafeLocation, View.Rotation.Vector(), View.Location, ClosestPointOnLineToCapsuleCenter);
139
+
140
+ // Adjust Safe distance height to be same as aim line, but within capsule.
141
+ float const PushInDistance = PenetrationAvoidanceFeelers[0].Extent + CollisionPushOutDistance;
142
+ float const MaxHalfHeight = PPActor->GetSimpleCollisionHalfHeight() - PushInDistance;
143
+ SafeLocation.Z = FMath::Clamp(ClosestPointOnLineToCapsuleCenter.Z, SafeLocation.Z - MaxHalfHeight, SafeLocation.Z + MaxHalfHeight);
144
+
145
+ float DistanceSqr;
146
+ PPActorRootComponent->GetSquaredDistanceToCollision(ClosestPointOnLineToCapsuleCenter, DistanceSqr, SafeLocation);
147
+ // Push back inside capsule to avoid initial penetration when doing line checks.
148
+ if (PenetrationAvoidanceFeelers.Num() > 0)
149
+ {
150
+ SafeLocation += (SafeLocation - ClosestPointOnLineToCapsuleCenter).GetSafeNormal() * PushInDistance;
151
+ }
152
+
153
+ // Then aim line to desired camera position
154
+ bool const bSingleRayPenetrationCheck = !bDoPredictiveAvoidance;
155
+ PreventCameraPenetration(*PPActor, SafeLocation, View.Location, DeltaTime, AimLineToDesiredPosBlockedPct, bSingleRayPenetrationCheck);
156
+
157
+ ILyraCameraAssistInterface* AssistArray[] = { TargetControllerAssist, TargetActorAssist, PPActorAssist };
158
+
159
+ if (AimLineToDesiredPosBlockedPct < ReportPenetrationPercent)
160
+ {
161
+ for (ILyraCameraAssistInterface* Assist : AssistArray)
162
+ {
163
+ if (Assist)
164
+ {
165
+ // camera is too close, tell the assists
166
+ Assist->OnCameraPenetratingTarget();
167
+ }
168
+ }
169
+ }
170
+ }
171
+ }
172
+
173
+ void ULyraCameraMode_ThirdPerson::PreventCameraPenetration(class AActor const& ViewTarget, FVector const& SafeLoc, FVector& CameraLoc, float const& DeltaTime, float& DistBlockedPct, bool bSingleRayOnly)
174
+ {
175
+ #if ENABLE_DRAW_DEBUG
176
+ DebugActorsHitDuringCameraPenetration.Reset();
177
+ #endif
178
+
179
+ float HardBlockedPct = DistBlockedPct;
180
+ float SoftBlockedPct = DistBlockedPct;
181
+
182
+ FVector BaseRay = CameraLoc - SafeLoc;
183
+ FRotationMatrix BaseRayMatrix(BaseRay.Rotation());
184
+ FVector BaseRayLocalUp, BaseRayLocalFwd, BaseRayLocalRight;
185
+
186
+ BaseRayMatrix.GetScaledAxes(BaseRayLocalFwd, BaseRayLocalRight, BaseRayLocalUp);
187
+
188
+ float DistBlockedPctThisFrame = 1.f;
189
+
190
+ int32 const NumRaysToShoot = bSingleRayOnly ? FMath::Min(1, PenetrationAvoidanceFeelers.Num()) : PenetrationAvoidanceFeelers.Num();
191
+ FCollisionQueryParams SphereParams(SCENE_QUERY_STAT(CameraPen), false, nullptr/*PlayerCamera*/);
192
+
193
+ SphereParams.AddIgnoredActor(&ViewTarget);
194
+
195
+ //TODO ILyraCameraTarget.GetIgnoredActorsForCameraPentration();
196
+ //if (IgnoreActorForCameraPenetration)
197
+ //{
198
+ // SphereParams.AddIgnoredActor(IgnoreActorForCameraPenetration);
199
+ //}
200
+
201
+ FCollisionShape SphereShape = FCollisionShape::MakeSphere(0.f);
202
+ UWorld* World = GetWorld();
203
+
204
+ for (int32 RayIdx = 0; RayIdx < NumRaysToShoot; ++RayIdx)
205
+ {
206
+ FLyraPenetrationAvoidanceFeeler& Feeler = PenetrationAvoidanceFeelers[RayIdx];
207
+ if (Feeler.FramesUntilNextTrace <= 0)
208
+ {
209
+ // calc ray target
210
+ FVector RayTarget;
211
+ {
212
+ FVector RotatedRay = BaseRay.RotateAngleAxis(Feeler.AdjustmentRot.Yaw, BaseRayLocalUp);
213
+ RotatedRay = RotatedRay.RotateAngleAxis(Feeler.AdjustmentRot.Pitch, BaseRayLocalRight);
214
+ RayTarget = SafeLoc + RotatedRay;
215
+ }
216
+
217
+ // cast for world and pawn hits separately. this is so we can safely ignore the
218
+ // camera's target pawn
219
+ SphereShape.Sphere.Radius = Feeler.Extent;
220
+ ECollisionChannel TraceChannel = ECC_Camera; //(Feeler.PawnWeight > 0.f) ? ECC_Pawn : ECC_Camera;
221
+
222
+ // do multi-line check to make sure the hits we throw out aren't
223
+ // masking real hits behind (these are important rays).
224
+
225
+ // MT-> passing camera as actor so that camerablockingvolumes know when it's the camera doing traces
226
+ FHitResult Hit;
227
+ const bool bHit = World->SweepSingleByChannel(Hit, SafeLoc, RayTarget, FQuat::Identity, TraceChannel, SphereShape, SphereParams);
228
+ #if ENABLE_DRAW_DEBUG
229
+ if (World->TimeSince(LastDrawDebugTime) < 1.f)
230
+ {
231
+ DrawDebugSphere(World, SafeLoc, SphereShape.Sphere.Radius, 8, FColor::Red);
232
+ DrawDebugSphere(World, bHit ? Hit.Location : RayTarget, SphereShape.Sphere.Radius, 8, FColor::Red);
233
+ DrawDebugLine(World, SafeLoc, bHit ? Hit.Location : RayTarget, FColor::Red);
234
+ }
235
+ #endif // ENABLE_DRAW_DEBUG
236
+
237
+ Feeler.FramesUntilNextTrace = Feeler.TraceInterval;
238
+
239
+ const AActor* HitActor = Hit.GetActor();
240
+
241
+ if (bHit && HitActor)
242
+ {
243
+ bool bIgnoreHit = false;
244
+
245
+ if (HitActor->ActorHasTag(LyraCameraMode_ThirdPerson_Statics::NAME_IgnoreCameraCollision))
246
+ {
247
+ bIgnoreHit = true;
248
+ SphereParams.AddIgnoredActor(HitActor);
249
+ }
250
+
251
+ // Ignore CameraBlockingVolume hits that occur in front of the ViewTarget.
252
+ if (!bIgnoreHit && HitActor->IsA<ACameraBlockingVolume>())
253
+ {
254
+ const FVector ViewTargetForwardXY = ViewTarget.GetActorForwardVector().GetSafeNormal2D();
255
+ const FVector ViewTargetLocation = ViewTarget.GetActorLocation();
256
+ const FVector HitOffset = Hit.Location - ViewTargetLocation;
257
+ const FVector HitDirectionXY = HitOffset.GetSafeNormal2D();
258
+ const float DotHitDirection = FVector::DotProduct(ViewTargetForwardXY, HitDirectionXY);
259
+ if (DotHitDirection > 0.0f)
260
+ {
261
+ bIgnoreHit = true;
262
+ // Ignore this CameraBlockingVolume on the remaining sweeps.
263
+ SphereParams.AddIgnoredActor(HitActor);
264
+ }
265
+ else
266
+ {
267
+ #if ENABLE_DRAW_DEBUG
268
+ DebugActorsHitDuringCameraPenetration.AddUnique(TObjectPtr<const AActor>(HitActor));
269
+ #endif
270
+ }
271
+ }
272
+
273
+ if (!bIgnoreHit)
274
+ {
275
+ float const Weight = Cast<APawn>(Hit.GetActor()) ? Feeler.PawnWeight : Feeler.WorldWeight;
276
+ float NewBlockPct = Hit.Time;
277
+ NewBlockPct += (1.f - NewBlockPct) * (1.f - Weight);
278
+
279
+ // Recompute blocked pct taking into account pushout distance.
280
+ NewBlockPct = ((Hit.Location - SafeLoc).Size() - CollisionPushOutDistance) / (RayTarget - SafeLoc).Size();
281
+ DistBlockedPctThisFrame = FMath::Min(NewBlockPct, DistBlockedPctThisFrame);
282
+
283
+ // This feeler got a hit, so do another trace next frame
284
+ Feeler.FramesUntilNextTrace = 0;
285
+
286
+ #if ENABLE_DRAW_DEBUG
287
+ DebugActorsHitDuringCameraPenetration.AddUnique(TObjectPtr<const AActor>(HitActor));
288
+ #endif
289
+ }
290
+ }
291
+
292
+ if (RayIdx == 0)
293
+ {
294
+ // don't interpolate toward this one, snap to it
295
+ // assumes ray 0 is the center/main ray
296
+ HardBlockedPct = DistBlockedPctThisFrame;
297
+ }
298
+ else
299
+ {
300
+ SoftBlockedPct = DistBlockedPctThisFrame;
301
+ }
302
+ }
303
+ else
304
+ {
305
+ --Feeler.FramesUntilNextTrace;
306
+ }
307
+ }
308
+
309
+ if (bResetInterpolation)
310
+ {
311
+ DistBlockedPct = DistBlockedPctThisFrame;
312
+ }
313
+ else if (DistBlockedPct < DistBlockedPctThisFrame)
314
+ {
315
+ // interpolate smoothly out
316
+ if (PenetrationBlendOutTime > DeltaTime)
317
+ {
318
+ DistBlockedPct = DistBlockedPct + DeltaTime / PenetrationBlendOutTime * (DistBlockedPctThisFrame - DistBlockedPct);
319
+ }
320
+ else
321
+ {
322
+ DistBlockedPct = DistBlockedPctThisFrame;
323
+ }
324
+ }
325
+ else
326
+ {
327
+ if (DistBlockedPct > HardBlockedPct)
328
+ {
329
+ DistBlockedPct = HardBlockedPct;
330
+ }
331
+ else if (DistBlockedPct > SoftBlockedPct)
332
+ {
333
+ // interpolate smoothly in
334
+ if (PenetrationBlendInTime > DeltaTime)
335
+ {
336
+ DistBlockedPct = DistBlockedPct - DeltaTime / PenetrationBlendInTime * (DistBlockedPct - SoftBlockedPct);
337
+ }
338
+ else
339
+ {
340
+ DistBlockedPct = SoftBlockedPct;
341
+ }
342
+ }
343
+ }
344
+
345
+ DistBlockedPct = FMath::Clamp<float>(DistBlockedPct, 0.f, 1.f);
346
+ if (DistBlockedPct < (1.f - ZERO_ANIMWEIGHT_THRESH))
347
+ {
348
+ CameraLoc = SafeLoc + (CameraLoc - SafeLoc) * DistBlockedPct;
349
+ }
350
+ }
351
+
352
+ void ULyraCameraMode_ThirdPerson::SetTargetCrouchOffset(FVector NewTargetOffset)
353
+ {
354
+ CrouchOffsetBlendPct = 0.0f;
355
+ InitialCrouchOffset = CurrentCrouchOffset;
356
+ TargetCrouchOffset = NewTargetOffset;
357
+ }
358
+
359
+
360
+ void ULyraCameraMode_ThirdPerson::UpdateCrouchOffset(float DeltaTime)
361
+ {
362
+ if (CrouchOffsetBlendPct < 1.0f)
363
+ {
364
+ CrouchOffsetBlendPct = FMath::Min(CrouchOffsetBlendPct + DeltaTime * CrouchOffsetBlendMultiplier, 1.0f);
365
+ CurrentCrouchOffset = FMath::InterpEaseInOut(InitialCrouchOffset, TargetCrouchOffset, CrouchOffsetBlendPct, 1.0f);
366
+ }
367
+ else
368
+ {
369
+ CurrentCrouchOffset = TargetCrouchOffset;
370
+ CrouchOffsetBlendPct = 1.0f;
371
+ }
372
+ }
373
+
LyraStarterGame/Source/LyraGame/Camera/LyraCameraMode_ThirdPerson.h ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "LyraCameraMode.h"
6
+ #include "Curves/CurveFloat.h"
7
+ #include "LyraPenetrationAvoidanceFeeler.h"
8
+ #include "DrawDebugHelpers.h"
9
+ #include "LyraCameraMode_ThirdPerson.generated.h"
10
+
11
+ class UCurveVector;
12
+
13
+ /**
14
+ * ULyraCameraMode_ThirdPerson
15
+ *
16
+ * A basic third person camera mode.
17
+ */
18
+ UCLASS(Abstract, Blueprintable)
19
+ class ULyraCameraMode_ThirdPerson : public ULyraCameraMode
20
+ {
21
+ GENERATED_BODY()
22
+
23
+ public:
24
+
25
+ ULyraCameraMode_ThirdPerson();
26
+
27
+ protected:
28
+
29
+ virtual void UpdateView(float DeltaTime) override;
30
+
31
+ void UpdateForTarget(float DeltaTime);
32
+ void UpdatePreventPenetration(float DeltaTime);
33
+ void PreventCameraPenetration(class AActor const& ViewTarget, FVector const& SafeLoc, FVector& CameraLoc, float const& DeltaTime, float& DistBlockedPct, bool bSingleRayOnly);
34
+
35
+ virtual void DrawDebug(UCanvas* Canvas) const override;
36
+
37
+ protected:
38
+
39
+ // Curve that defines local-space offsets from the target using the view pitch to evaluate the curve.
40
+ UPROPERTY(EditDefaultsOnly, Category = "Third Person", Meta = (EditCondition = "!bUseRuntimeFloatCurves"))
41
+ TObjectPtr<const UCurveVector> TargetOffsetCurve;
42
+
43
+ // UE-103986: Live editing of RuntimeFloatCurves during PIE does not work (unlike curve assets).
44
+ // Once that is resolved this will become the default and TargetOffsetCurve will be removed.
45
+ UPROPERTY(EditDefaultsOnly, Category = "Third Person")
46
+ bool bUseRuntimeFloatCurves;
47
+
48
+ UPROPERTY(EditDefaultsOnly, Category = "Third Person", Meta = (EditCondition = "bUseRuntimeFloatCurves"))
49
+ FRuntimeFloatCurve TargetOffsetX;
50
+
51
+ UPROPERTY(EditDefaultsOnly, Category = "Third Person", Meta = (EditCondition = "bUseRuntimeFloatCurves"))
52
+ FRuntimeFloatCurve TargetOffsetY;
53
+
54
+ UPROPERTY(EditDefaultsOnly, Category = "Third Person", Meta = (EditCondition = "bUseRuntimeFloatCurves"))
55
+ FRuntimeFloatCurve TargetOffsetZ;
56
+
57
+ // Alters the speed that a crouch offset is blended in or out
58
+ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Third Person")
59
+ float CrouchOffsetBlendMultiplier = 5.0f;
60
+
61
+ // Penetration prevention
62
+ public:
63
+ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Collision")
64
+ float PenetrationBlendInTime = 0.1f;
65
+
66
+ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Collision")
67
+ float PenetrationBlendOutTime = 0.15f;
68
+
69
+ /** If true, does collision checks to keep the camera out of the world. */
70
+ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Collision")
71
+ bool bPreventPenetration = true;
72
+
73
+ /** If true, try to detect nearby walls and move the camera in anticipation. Helps prevent popping. */
74
+ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Collision")
75
+ bool bDoPredictiveAvoidance = true;
76
+
77
+ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Collision")
78
+ float CollisionPushOutDistance = 2.f;
79
+
80
+ /** When the camera's distance is pushed into this percentage of its full distance due to penetration */
81
+ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Collision")
82
+ float ReportPenetrationPercent = 0.f;
83
+
84
+ /**
85
+ * These are the feeler rays that are used to find where to place the camera.
86
+ * Index: 0 : This is the normal feeler we use to prevent collisions.
87
+ * Index: 1+ : These feelers are used if you bDoPredictiveAvoidance=true, to scan for potential impacts if the player
88
+ * were to rotate towards that direction and primitively collide the camera so that it pulls in before
89
+ * impacting the occluder.
90
+ */
91
+ UPROPERTY(EditDefaultsOnly, Category = "Collision")
92
+ TArray<FLyraPenetrationAvoidanceFeeler> PenetrationAvoidanceFeelers;
93
+
94
+ UPROPERTY(Transient)
95
+ float AimLineToDesiredPosBlockedPct;
96
+
97
+ UPROPERTY(Transient)
98
+ TArray<TObjectPtr<const AActor>> DebugActorsHitDuringCameraPenetration;
99
+
100
+ #if ENABLE_DRAW_DEBUG
101
+ mutable float LastDrawDebugTime = -MAX_FLT;
102
+ #endif
103
+
104
+ protected:
105
+
106
+ void SetTargetCrouchOffset(FVector NewTargetOffset);
107
+ void UpdateCrouchOffset(float DeltaTime);
108
+
109
+ FVector InitialCrouchOffset = FVector::ZeroVector;
110
+ FVector TargetCrouchOffset = FVector::ZeroVector;
111
+ float CrouchOffsetBlendPct = 1.0f;
112
+ FVector CurrentCrouchOffset = FVector::ZeroVector;
113
+
114
+ };
LyraStarterGame/Source/LyraGame/Camera/LyraPenetrationAvoidanceFeeler.h ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "CoreMinimal.h"
6
+
7
+ #include "LyraPenetrationAvoidanceFeeler.generated.h"
8
+
9
+ /**
10
+ * Struct defining a feeler ray used for camera penetration avoidance.
11
+ */
12
+ USTRUCT()
13
+ struct FLyraPenetrationAvoidanceFeeler
14
+ {
15
+ GENERATED_BODY()
16
+
17
+ /** FRotator describing deviance from main ray */
18
+ UPROPERTY(EditAnywhere, Category=PenetrationAvoidanceFeeler)
19
+ FRotator AdjustmentRot;
20
+
21
+ /** how much this feeler affects the final position if it hits the world */
22
+ UPROPERTY(EditAnywhere, Category=PenetrationAvoidanceFeeler)
23
+ float WorldWeight;
24
+
25
+ /** how much this feeler affects the final position if it hits a APawn (setting to 0 will not attempt to collide with pawns at all) */
26
+ UPROPERTY(EditAnywhere, Category=PenetrationAvoidanceFeeler)
27
+ float PawnWeight;
28
+
29
+ /** extent to use for collision when tracing this feeler */
30
+ UPROPERTY(EditAnywhere, Category=PenetrationAvoidanceFeeler)
31
+ float Extent;
32
+
33
+ /** minimum frame interval between traces with this feeler if nothing was hit last frame */
34
+ UPROPERTY(EditAnywhere, Category=PenetrationAvoidanceFeeler)
35
+ int32 TraceInterval;
36
+
37
+ /** number of frames since this feeler was used */
38
+ UPROPERTY(transient)
39
+ int32 FramesUntilNextTrace;
40
+
41
+
42
+ FLyraPenetrationAvoidanceFeeler()
43
+ : AdjustmentRot(ForceInit)
44
+ , WorldWeight(0)
45
+ , PawnWeight(0)
46
+ , Extent(0)
47
+ , TraceInterval(0)
48
+ , FramesUntilNextTrace(0)
49
+ {
50
+ }
51
+
52
+ FLyraPenetrationAvoidanceFeeler(const FRotator& InAdjustmentRot,
53
+ const float& InWorldWeight,
54
+ const float& InPawnWeight,
55
+ const float& InExtent,
56
+ const int32& InTraceInterval = 0,
57
+ const int32& InFramesUntilNextTrace = 0)
58
+ : AdjustmentRot(InAdjustmentRot)
59
+ , WorldWeight(InWorldWeight)
60
+ , PawnWeight(InPawnWeight)
61
+ , Extent(InExtent)
62
+ , TraceInterval(InTraceInterval)
63
+ , FramesUntilNextTrace(InFramesUntilNextTrace)
64
+ {
65
+ }
66
+ };
LyraStarterGame/Source/LyraGame/Camera/LyraPlayerCameraManager.cpp ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraPlayerCameraManager.h"
4
+
5
+ #include "Async/TaskGraphInterfaces.h"
6
+ #include "Engine/Canvas.h"
7
+ #include "Engine/Engine.h"
8
+ #include "GameFramework/Pawn.h"
9
+ #include "GameFramework/PlayerController.h"
10
+ #include "LyraCameraComponent.h"
11
+ #include "LyraUICameraManagerComponent.h"
12
+
13
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraPlayerCameraManager)
14
+
15
+ class FDebugDisplayInfo;
16
+
17
+ static FName UICameraComponentName(TEXT("UICamera"));
18
+
19
+ ALyraPlayerCameraManager::ALyraPlayerCameraManager(const FObjectInitializer& ObjectInitializer)
20
+ : Super(ObjectInitializer)
21
+ {
22
+ DefaultFOV = LYRA_CAMERA_DEFAULT_FOV;
23
+ ViewPitchMin = LYRA_CAMERA_DEFAULT_PITCH_MIN;
24
+ ViewPitchMax = LYRA_CAMERA_DEFAULT_PITCH_MAX;
25
+
26
+ UICamera = CreateDefaultSubobject<ULyraUICameraManagerComponent>(UICameraComponentName);
27
+ }
28
+
29
+ ULyraUICameraManagerComponent* ALyraPlayerCameraManager::GetUICameraComponent() const
30
+ {
31
+ return UICamera;
32
+ }
33
+
34
+ void ALyraPlayerCameraManager::UpdateViewTarget(FTViewTarget& OutVT, float DeltaTime)
35
+ {
36
+ // If the UI Camera is looking at something, let it have priority.
37
+ if (UICamera->NeedsToUpdateViewTarget())
38
+ {
39
+ Super::UpdateViewTarget(OutVT, DeltaTime);
40
+ UICamera->UpdateViewTarget(OutVT, DeltaTime);
41
+ return;
42
+ }
43
+
44
+ Super::UpdateViewTarget(OutVT, DeltaTime);
45
+ }
46
+
47
+ void ALyraPlayerCameraManager::DisplayDebug(UCanvas* Canvas, const FDebugDisplayInfo& DebugDisplay, float& YL, float& YPos)
48
+ {
49
+ check(Canvas);
50
+
51
+ FDisplayDebugManager& DisplayDebugManager = Canvas->DisplayDebugManager;
52
+
53
+ DisplayDebugManager.SetFont(GEngine->GetSmallFont());
54
+ DisplayDebugManager.SetDrawColor(FColor::Yellow);
55
+ DisplayDebugManager.DrawString(FString::Printf(TEXT("LyraPlayerCameraManager: %s"), *GetNameSafe(this)));
56
+
57
+ Super::DisplayDebug(Canvas, DebugDisplay, YL, YPos);
58
+
59
+ const APawn* Pawn = (PCOwner ? PCOwner->GetPawn() : nullptr);
60
+
61
+ if (const ULyraCameraComponent* CameraComponent = ULyraCameraComponent::FindCameraComponent(Pawn))
62
+ {
63
+ CameraComponent->DrawDebug(Canvas);
64
+ }
65
+ }
66
+
LyraStarterGame/Source/LyraGame/Camera/LyraPlayerCameraManager.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "Camera/PlayerCameraManager.h"
6
+
7
+ #include "LyraPlayerCameraManager.generated.h"
8
+
9
+ class FDebugDisplayInfo;
10
+ class UCanvas;
11
+ class UObject;
12
+
13
+
14
+ #define LYRA_CAMERA_DEFAULT_FOV (80.0f)
15
+ #define LYRA_CAMERA_DEFAULT_PITCH_MIN (-89.0f)
16
+ #define LYRA_CAMERA_DEFAULT_PITCH_MAX (89.0f)
17
+
18
+ class ULyraUICameraManagerComponent;
19
+
20
+ /**
21
+ * ALyraPlayerCameraManager
22
+ *
23
+ * The base player camera manager class used by this project.
24
+ */
25
+ UCLASS(notplaceable, MinimalAPI)
26
+ class ALyraPlayerCameraManager : public APlayerCameraManager
27
+ {
28
+ GENERATED_BODY()
29
+
30
+ public:
31
+
32
+ ALyraPlayerCameraManager(const FObjectInitializer& ObjectInitializer);
33
+
34
+ ULyraUICameraManagerComponent* GetUICameraComponent() const;
35
+
36
+ protected:
37
+
38
+ virtual void UpdateViewTarget(FTViewTarget& OutVT, float DeltaTime) override;
39
+
40
+ virtual void DisplayDebug(UCanvas* Canvas, const FDebugDisplayInfo& DebugDisplay, float& YL, float& YPos) override;
41
+
42
+ private:
43
+ /** The UI Camera Component, controls the camera when UI is doing something important that gameplay doesn't get priority over. */
44
+ UPROPERTY(Transient)
45
+ TObjectPtr<ULyraUICameraManagerComponent> UICamera;
46
+ };
LyraStarterGame/Source/LyraGame/Camera/LyraUICameraManagerComponent.cpp ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraUICameraManagerComponent.h"
4
+
5
+ #include "GameFramework/HUD.h"
6
+ #include "GameFramework/PlayerController.h"
7
+ #include "LyraPlayerCameraManager.h"
8
+
9
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraUICameraManagerComponent)
10
+
11
+ class AActor;
12
+ class FDebugDisplayInfo;
13
+
14
+ ULyraUICameraManagerComponent* ULyraUICameraManagerComponent::GetComponent(APlayerController* PC)
15
+ {
16
+ if (PC != nullptr)
17
+ {
18
+ if (ALyraPlayerCameraManager* PCCamera = Cast<ALyraPlayerCameraManager>(PC->PlayerCameraManager))
19
+ {
20
+ return PCCamera->GetUICameraComponent();
21
+ }
22
+ }
23
+
24
+ return nullptr;
25
+ }
26
+
27
+ ULyraUICameraManagerComponent::ULyraUICameraManagerComponent()
28
+ {
29
+ bWantsInitializeComponent = true;
30
+
31
+ if (!HasAnyFlags(RF_ClassDefaultObject))
32
+ {
33
+ // Register "showdebug" hook.
34
+ if (!IsRunningDedicatedServer())
35
+ {
36
+ AHUD::OnShowDebugInfo.AddUObject(this, &ThisClass::OnShowDebugInfo);
37
+ }
38
+ }
39
+ }
40
+
41
+ void ULyraUICameraManagerComponent::InitializeComponent()
42
+ {
43
+ Super::InitializeComponent();
44
+ }
45
+
46
+ void ULyraUICameraManagerComponent::SetViewTarget(AActor* InViewTarget, FViewTargetTransitionParams TransitionParams)
47
+ {
48
+ TGuardValue<bool> UpdatingViewTargetGuard(bUpdatingViewTarget, true);
49
+
50
+ ViewTarget = InViewTarget;
51
+ CastChecked<ALyraPlayerCameraManager>(GetOwner())->SetViewTarget(ViewTarget, TransitionParams);
52
+ }
53
+
54
+ bool ULyraUICameraManagerComponent::NeedsToUpdateViewTarget() const
55
+ {
56
+ return false;
57
+ }
58
+
59
+ void ULyraUICameraManagerComponent::UpdateViewTarget(struct FTViewTarget& OutVT, float DeltaTime)
60
+ {
61
+ }
62
+
63
+ void ULyraUICameraManagerComponent::OnShowDebugInfo(AHUD* HUD, UCanvas* Canvas, const FDebugDisplayInfo& DisplayInfo, float& YL, float& YPos)
64
+ {
65
+ }
LyraStarterGame/Source/LyraGame/Camera/LyraUICameraManagerComponent.h ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "Camera/PlayerCameraManager.h"
6
+
7
+ #include "LyraUICameraManagerComponent.generated.h"
8
+
9
+ class ALyraPlayerCameraManager;
10
+
11
+ class AActor;
12
+ class AHUD;
13
+ class APlayerController;
14
+ class FDebugDisplayInfo;
15
+ class UCanvas;
16
+ class UObject;
17
+
18
+ UCLASS( Transient, Within=LyraPlayerCameraManager )
19
+ class ULyraUICameraManagerComponent : public UActorComponent
20
+ {
21
+ GENERATED_BODY()
22
+
23
+ public:
24
+ static ULyraUICameraManagerComponent* GetComponent(APlayerController* PC);
25
+
26
+ public:
27
+ ULyraUICameraManagerComponent();
28
+ virtual void InitializeComponent() override;
29
+
30
+ bool IsSettingViewTarget() const { return bUpdatingViewTarget; }
31
+ AActor* GetViewTarget() const { return ViewTarget; }
32
+ void SetViewTarget(AActor* InViewTarget, FViewTargetTransitionParams TransitionParams = FViewTargetTransitionParams());
33
+
34
+ bool NeedsToUpdateViewTarget() const;
35
+ void UpdateViewTarget(struct FTViewTarget& OutVT, float DeltaTime);
36
+
37
+ void OnShowDebugInfo(AHUD* HUD, UCanvas* Canvas, const FDebugDisplayInfo& DisplayInfo, float& YL, float& YPos);
38
+
39
+ private:
40
+ UPROPERTY(Transient)
41
+ TObjectPtr<AActor> ViewTarget;
42
+
43
+ UPROPERTY(Transient)
44
+ bool bUpdatingViewTarget;
45
+ };
LyraStarterGame/Source/LyraGame/Character/LyraCharacter.cpp ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraCharacter.h"
4
+
5
+ #include "AbilitySystem/LyraAbilitySystemComponent.h"
6
+ #include "Camera/LyraCameraComponent.h"
7
+ #include "Character/LyraHealthComponent.h"
8
+ #include "Character/LyraPawnExtensionComponent.h"
9
+ #include "Components/CapsuleComponent.h"
10
+ #include "Components/SkeletalMeshComponent.h"
11
+ #include "LyraCharacterMovementComponent.h"
12
+ #include "LyraGameplayTags.h"
13
+ #include "LyraLogChannels.h"
14
+ #include "Net/UnrealNetwork.h"
15
+ #include "Player/LyraPlayerController.h"
16
+ #include "Player/LyraPlayerState.h"
17
+ #include "System/LyraSignificanceManager.h"
18
+ #include "TimerManager.h"
19
+
20
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraCharacter)
21
+
22
+ class AActor;
23
+ class FLifetimeProperty;
24
+ class IRepChangedPropertyTracker;
25
+ class UInputComponent;
26
+
27
+ static FName NAME_LyraCharacterCollisionProfile_Capsule(TEXT("LyraPawnCapsule"));
28
+ static FName NAME_LyraCharacterCollisionProfile_Mesh(TEXT("LyraPawnMesh"));
29
+
30
+ ALyraCharacter::ALyraCharacter(const FObjectInitializer& ObjectInitializer)
31
+ : Super(ObjectInitializer.SetDefaultSubobjectClass<ULyraCharacterMovementComponent>(ACharacter::CharacterMovementComponentName))
32
+ {
33
+ // Avoid ticking characters if possible.
34
+ PrimaryActorTick.bCanEverTick = false;
35
+ PrimaryActorTick.bStartWithTickEnabled = false;
36
+
37
+ SetNetCullDistanceSquared(900000000.0f);
38
+
39
+ UCapsuleComponent* CapsuleComp = GetCapsuleComponent();
40
+ check(CapsuleComp);
41
+ CapsuleComp->InitCapsuleSize(40.0f, 90.0f);
42
+ CapsuleComp->SetCollisionProfileName(NAME_LyraCharacterCollisionProfile_Capsule);
43
+
44
+ USkeletalMeshComponent* MeshComp = GetMesh();
45
+ check(MeshComp);
46
+ MeshComp->SetRelativeRotation(FRotator(0.0f, -90.0f, 0.0f)); // Rotate mesh to be X forward since it is exported as Y forward.
47
+ MeshComp->SetCollisionProfileName(NAME_LyraCharacterCollisionProfile_Mesh);
48
+
49
+ ULyraCharacterMovementComponent* LyraMoveComp = CastChecked<ULyraCharacterMovementComponent>(GetCharacterMovement());
50
+ LyraMoveComp->GravityScale = 1.0f;
51
+ LyraMoveComp->MaxAcceleration = 2400.0f;
52
+ LyraMoveComp->BrakingFrictionFactor = 1.0f;
53
+ LyraMoveComp->BrakingFriction = 6.0f;
54
+ LyraMoveComp->GroundFriction = 8.0f;
55
+ LyraMoveComp->BrakingDecelerationWalking = 1400.0f;
56
+ LyraMoveComp->bUseControllerDesiredRotation = false;
57
+ LyraMoveComp->bOrientRotationToMovement = false;
58
+ LyraMoveComp->RotationRate = FRotator(0.0f, 720.0f, 0.0f);
59
+ LyraMoveComp->bAllowPhysicsRotationDuringAnimRootMotion = false;
60
+ LyraMoveComp->GetNavAgentPropertiesRef().bCanCrouch = true;
61
+ LyraMoveComp->bCanWalkOffLedgesWhenCrouching = true;
62
+ LyraMoveComp->SetCrouchedHalfHeight(65.0f);
63
+
64
+ PawnExtComponent = CreateDefaultSubobject<ULyraPawnExtensionComponent>(TEXT("PawnExtensionComponent"));
65
+ PawnExtComponent->OnAbilitySystemInitialized_RegisterAndCall(FSimpleMulticastDelegate::FDelegate::CreateUObject(this, &ThisClass::OnAbilitySystemInitialized));
66
+ PawnExtComponent->OnAbilitySystemUninitialized_Register(FSimpleMulticastDelegate::FDelegate::CreateUObject(this, &ThisClass::OnAbilitySystemUninitialized));
67
+
68
+ HealthComponent = CreateDefaultSubobject<ULyraHealthComponent>(TEXT("HealthComponent"));
69
+ HealthComponent->OnDeathStarted.AddDynamic(this, &ThisClass::OnDeathStarted);
70
+ HealthComponent->OnDeathFinished.AddDynamic(this, &ThisClass::OnDeathFinished);
71
+
72
+ CameraComponent = CreateDefaultSubobject<ULyraCameraComponent>(TEXT("CameraComponent"));
73
+ CameraComponent->SetRelativeLocation(FVector(-300.0f, 0.0f, 75.0f));
74
+
75
+ bUseControllerRotationPitch = false;
76
+ bUseControllerRotationYaw = true;
77
+ bUseControllerRotationRoll = false;
78
+
79
+ BaseEyeHeight = 80.0f;
80
+ CrouchedEyeHeight = 50.0f;
81
+ }
82
+
83
+ void ALyraCharacter::PreInitializeComponents()
84
+ {
85
+ Super::PreInitializeComponents();
86
+ }
87
+
88
+ void ALyraCharacter::BeginPlay()
89
+ {
90
+ Super::BeginPlay();
91
+
92
+ UWorld* World = GetWorld();
93
+
94
+ const bool bRegisterWithSignificanceManager = !IsNetMode(NM_DedicatedServer);
95
+ if (bRegisterWithSignificanceManager)
96
+ {
97
+ if (ULyraSignificanceManager* SignificanceManager = USignificanceManager::Get<ULyraSignificanceManager>(World))
98
+ {
99
+ //@TODO: SignificanceManager->RegisterObject(this, (EFortSignificanceType)SignificanceType);
100
+ }
101
+ }
102
+ }
103
+
104
+ void ALyraCharacter::EndPlay(const EEndPlayReason::Type EndPlayReason)
105
+ {
106
+ Super::EndPlay(EndPlayReason);
107
+
108
+ UWorld* World = GetWorld();
109
+
110
+ const bool bRegisterWithSignificanceManager = !IsNetMode(NM_DedicatedServer);
111
+ if (bRegisterWithSignificanceManager)
112
+ {
113
+ if (ULyraSignificanceManager* SignificanceManager = USignificanceManager::Get<ULyraSignificanceManager>(World))
114
+ {
115
+ SignificanceManager->UnregisterObject(this);
116
+ }
117
+ }
118
+ }
119
+
120
+ void ALyraCharacter::Reset()
121
+ {
122
+ DisableMovementAndCollision();
123
+
124
+ K2_OnReset();
125
+
126
+ UninitAndDestroy();
127
+ }
128
+
129
+ void ALyraCharacter::GetLifetimeReplicatedProps(TArray< FLifetimeProperty >& OutLifetimeProps) const
130
+ {
131
+ Super::GetLifetimeReplicatedProps(OutLifetimeProps);
132
+
133
+ DOREPLIFETIME_CONDITION(ThisClass, ReplicatedAcceleration, COND_SimulatedOnly);
134
+ DOREPLIFETIME(ThisClass, MyTeamID)
135
+ }
136
+
137
+ void ALyraCharacter::PreReplication(IRepChangedPropertyTracker& ChangedPropertyTracker)
138
+ {
139
+ Super::PreReplication(ChangedPropertyTracker);
140
+
141
+ if (UCharacterMovementComponent* MovementComponent = GetCharacterMovement())
142
+ {
143
+ // Compress Acceleration: XY components as direction + magnitude, Z component as direct value
144
+ const double MaxAccel = MovementComponent->MaxAcceleration;
145
+ const FVector CurrentAccel = MovementComponent->GetCurrentAcceleration();
146
+ double AccelXYRadians, AccelXYMagnitude;
147
+ FMath::CartesianToPolar(CurrentAccel.X, CurrentAccel.Y, AccelXYMagnitude, AccelXYRadians);
148
+
149
+ ReplicatedAcceleration.AccelXYRadians = FMath::FloorToInt((AccelXYRadians / TWO_PI) * 255.0); // [0, 2PI] -> [0, 255]
150
+ ReplicatedAcceleration.AccelXYMagnitude = FMath::FloorToInt((AccelXYMagnitude / MaxAccel) * 255.0); // [0, MaxAccel] -> [0, 255]
151
+ ReplicatedAcceleration.AccelZ = FMath::FloorToInt((CurrentAccel.Z / MaxAccel) * 127.0); // [-MaxAccel, MaxAccel] -> [-127, 127]
152
+ }
153
+ }
154
+
155
+ void ALyraCharacter::NotifyControllerChanged()
156
+ {
157
+ const FGenericTeamId OldTeamId = GetGenericTeamId();
158
+
159
+ Super::NotifyControllerChanged();
160
+
161
+ // Update our team ID based on the controller
162
+ if (HasAuthority() && (GetController() != nullptr))
163
+ {
164
+ if (ILyraTeamAgentInterface* ControllerWithTeam = Cast<ILyraTeamAgentInterface>(GetController()))
165
+ {
166
+ MyTeamID = ControllerWithTeam->GetGenericTeamId();
167
+ ConditionalBroadcastTeamChanged(this, OldTeamId, MyTeamID);
168
+ }
169
+ }
170
+ }
171
+
172
+ ALyraPlayerController* ALyraCharacter::GetLyraPlayerController() const
173
+ {
174
+ return CastChecked<ALyraPlayerController>(GetController(), ECastCheckedType::NullAllowed);
175
+ }
176
+
177
+ ALyraPlayerState* ALyraCharacter::GetLyraPlayerState() const
178
+ {
179
+ return CastChecked<ALyraPlayerState>(GetPlayerState(), ECastCheckedType::NullAllowed);
180
+ }
181
+
182
+ ULyraAbilitySystemComponent* ALyraCharacter::GetLyraAbilitySystemComponent() const
183
+ {
184
+ return Cast<ULyraAbilitySystemComponent>(GetAbilitySystemComponent());
185
+ }
186
+
187
+ UAbilitySystemComponent* ALyraCharacter::GetAbilitySystemComponent() const
188
+ {
189
+ if (PawnExtComponent == nullptr)
190
+ {
191
+ return nullptr;
192
+ }
193
+
194
+ return PawnExtComponent->GetLyraAbilitySystemComponent();
195
+ }
196
+
197
+ void ALyraCharacter::OnAbilitySystemInitialized()
198
+ {
199
+ ULyraAbilitySystemComponent* LyraASC = GetLyraAbilitySystemComponent();
200
+ check(LyraASC);
201
+
202
+ HealthComponent->InitializeWithAbilitySystem(LyraASC);
203
+
204
+ InitializeGameplayTags();
205
+ }
206
+
207
+ void ALyraCharacter::OnAbilitySystemUninitialized()
208
+ {
209
+ HealthComponent->UninitializeFromAbilitySystem();
210
+ }
211
+
212
+ void ALyraCharacter::PossessedBy(AController* NewController)
213
+ {
214
+ const FGenericTeamId OldTeamID = MyTeamID;
215
+
216
+ Super::PossessedBy(NewController);
217
+
218
+ PawnExtComponent->HandleControllerChanged();
219
+
220
+ // Grab the current team ID and listen for future changes
221
+ if (ILyraTeamAgentInterface* ControllerAsTeamProvider = Cast<ILyraTeamAgentInterface>(NewController))
222
+ {
223
+ MyTeamID = ControllerAsTeamProvider->GetGenericTeamId();
224
+ ControllerAsTeamProvider->GetTeamChangedDelegateChecked().AddDynamic(this, &ThisClass::OnControllerChangedTeam);
225
+ }
226
+ ConditionalBroadcastTeamChanged(this, OldTeamID, MyTeamID);
227
+ }
228
+
229
+ void ALyraCharacter::UnPossessed()
230
+ {
231
+ AController* const OldController = GetController();
232
+
233
+ // Stop listening for changes from the old controller
234
+ const FGenericTeamId OldTeamID = MyTeamID;
235
+ if (ILyraTeamAgentInterface* ControllerAsTeamProvider = Cast<ILyraTeamAgentInterface>(OldController))
236
+ {
237
+ ControllerAsTeamProvider->GetTeamChangedDelegateChecked().RemoveAll(this);
238
+ }
239
+
240
+ Super::UnPossessed();
241
+
242
+ PawnExtComponent->HandleControllerChanged();
243
+
244
+ // Determine what the new team ID should be afterwards
245
+ MyTeamID = DetermineNewTeamAfterPossessionEnds(OldTeamID);
246
+ ConditionalBroadcastTeamChanged(this, OldTeamID, MyTeamID);
247
+ }
248
+
249
+ void ALyraCharacter::OnRep_Controller()
250
+ {
251
+ Super::OnRep_Controller();
252
+
253
+ PawnExtComponent->HandleControllerChanged();
254
+ }
255
+
256
+ void ALyraCharacter::OnRep_PlayerState()
257
+ {
258
+ Super::OnRep_PlayerState();
259
+
260
+ PawnExtComponent->HandlePlayerStateReplicated();
261
+ }
262
+
263
+ void ALyraCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
264
+ {
265
+ Super::SetupPlayerInputComponent(PlayerInputComponent);
266
+
267
+ PawnExtComponent->SetupPlayerInputComponent();
268
+ }
269
+
270
+ void ALyraCharacter::InitializeGameplayTags()
271
+ {
272
+ // Clear tags that may be lingering on the ability system from the previous pawn.
273
+ if (ULyraAbilitySystemComponent* LyraASC = GetLyraAbilitySystemComponent())
274
+ {
275
+ for (const TPair<uint8, FGameplayTag>& TagMapping : LyraGameplayTags::MovementModeTagMap)
276
+ {
277
+ if (TagMapping.Value.IsValid())
278
+ {
279
+ LyraASC->SetLooseGameplayTagCount(TagMapping.Value, 0);
280
+ }
281
+ }
282
+
283
+ for (const TPair<uint8, FGameplayTag>& TagMapping : LyraGameplayTags::CustomMovementModeTagMap)
284
+ {
285
+ if (TagMapping.Value.IsValid())
286
+ {
287
+ LyraASC->SetLooseGameplayTagCount(TagMapping.Value, 0);
288
+ }
289
+ }
290
+
291
+ ULyraCharacterMovementComponent* LyraMoveComp = CastChecked<ULyraCharacterMovementComponent>(GetCharacterMovement());
292
+ SetMovementModeTag(LyraMoveComp->MovementMode, LyraMoveComp->CustomMovementMode, true);
293
+ }
294
+ }
295
+
296
+ void ALyraCharacter::GetOwnedGameplayTags(FGameplayTagContainer& TagContainer) const
297
+ {
298
+ if (const ULyraAbilitySystemComponent* LyraASC = GetLyraAbilitySystemComponent())
299
+ {
300
+ LyraASC->GetOwnedGameplayTags(TagContainer);
301
+ }
302
+ }
303
+
304
+ bool ALyraCharacter::HasMatchingGameplayTag(FGameplayTag TagToCheck) const
305
+ {
306
+ if (const ULyraAbilitySystemComponent* LyraASC = GetLyraAbilitySystemComponent())
307
+ {
308
+ return LyraASC->HasMatchingGameplayTag(TagToCheck);
309
+ }
310
+
311
+ return false;
312
+ }
313
+
314
+ bool ALyraCharacter::HasAllMatchingGameplayTags(const FGameplayTagContainer& TagContainer) const
315
+ {
316
+ if (const ULyraAbilitySystemComponent* LyraASC = GetLyraAbilitySystemComponent())
317
+ {
318
+ return LyraASC->HasAllMatchingGameplayTags(TagContainer);
319
+ }
320
+
321
+ return false;
322
+ }
323
+
324
+ bool ALyraCharacter::HasAnyMatchingGameplayTags(const FGameplayTagContainer& TagContainer) const
325
+ {
326
+ if (const ULyraAbilitySystemComponent* LyraASC = GetLyraAbilitySystemComponent())
327
+ {
328
+ return LyraASC->HasAnyMatchingGameplayTags(TagContainer);
329
+ }
330
+
331
+ return false;
332
+ }
333
+
334
+ void ALyraCharacter::FellOutOfWorld(const class UDamageType& dmgType)
335
+ {
336
+ HealthComponent->DamageSelfDestruct(/*bFellOutOfWorld=*/ true);
337
+ }
338
+
339
+ void ALyraCharacter::OnDeathStarted(AActor*)
340
+ {
341
+ DisableMovementAndCollision();
342
+ }
343
+
344
+ void ALyraCharacter::OnDeathFinished(AActor*)
345
+ {
346
+ GetWorld()->GetTimerManager().SetTimerForNextTick(this, &ThisClass::DestroyDueToDeath);
347
+ }
348
+
349
+
350
+ void ALyraCharacter::DisableMovementAndCollision()
351
+ {
352
+ if (GetController())
353
+ {
354
+ GetController()->SetIgnoreMoveInput(true);
355
+ }
356
+
357
+ UCapsuleComponent* CapsuleComp = GetCapsuleComponent();
358
+ check(CapsuleComp);
359
+ CapsuleComp->SetCollisionEnabled(ECollisionEnabled::NoCollision);
360
+ CapsuleComp->SetCollisionResponseToAllChannels(ECR_Ignore);
361
+
362
+ ULyraCharacterMovementComponent* LyraMoveComp = CastChecked<ULyraCharacterMovementComponent>(GetCharacterMovement());
363
+ LyraMoveComp->StopMovementImmediately();
364
+ LyraMoveComp->DisableMovement();
365
+ }
366
+
367
+ void ALyraCharacter::DestroyDueToDeath()
368
+ {
369
+ K2_OnDeathFinished();
370
+
371
+ UninitAndDestroy();
372
+ }
373
+
374
+
375
+ void ALyraCharacter::UninitAndDestroy()
376
+ {
377
+ if (GetLocalRole() == ROLE_Authority)
378
+ {
379
+ DetachFromControllerPendingDestroy();
380
+ SetLifeSpan(0.1f);
381
+ }
382
+
383
+ // Uninitialize the ASC if we're still the avatar actor (otherwise another pawn already did it when they became the avatar actor)
384
+ if (ULyraAbilitySystemComponent* LyraASC = GetLyraAbilitySystemComponent())
385
+ {
386
+ if (LyraASC->GetAvatarActor() == this)
387
+ {
388
+ PawnExtComponent->UninitializeAbilitySystem();
389
+ }
390
+ }
391
+
392
+ SetActorHiddenInGame(true);
393
+ }
394
+
395
+ void ALyraCharacter::OnMovementModeChanged(EMovementMode PrevMovementMode, uint8 PreviousCustomMode)
396
+ {
397
+ Super::OnMovementModeChanged(PrevMovementMode, PreviousCustomMode);
398
+
399
+ ULyraCharacterMovementComponent* LyraMoveComp = CastChecked<ULyraCharacterMovementComponent>(GetCharacterMovement());
400
+
401
+ SetMovementModeTag(PrevMovementMode, PreviousCustomMode, false);
402
+ SetMovementModeTag(LyraMoveComp->MovementMode, LyraMoveComp->CustomMovementMode, true);
403
+ }
404
+
405
+ void ALyraCharacter::SetMovementModeTag(EMovementMode MovementMode, uint8 CustomMovementMode, bool bTagEnabled)
406
+ {
407
+ if (ULyraAbilitySystemComponent* LyraASC = GetLyraAbilitySystemComponent())
408
+ {
409
+ const FGameplayTag* MovementModeTag = nullptr;
410
+ if (MovementMode == MOVE_Custom)
411
+ {
412
+ MovementModeTag = LyraGameplayTags::CustomMovementModeTagMap.Find(CustomMovementMode);
413
+ }
414
+ else
415
+ {
416
+ MovementModeTag = LyraGameplayTags::MovementModeTagMap.Find(MovementMode);
417
+ }
418
+
419
+ if (MovementModeTag && MovementModeTag->IsValid())
420
+ {
421
+ LyraASC->SetLooseGameplayTagCount(*MovementModeTag, (bTagEnabled ? 1 : 0));
422
+ }
423
+ }
424
+ }
425
+
426
+ void ALyraCharacter::ToggleCrouch()
427
+ {
428
+ const ULyraCharacterMovementComponent* LyraMoveComp = CastChecked<ULyraCharacterMovementComponent>(GetCharacterMovement());
429
+
430
+ if (IsCrouched() || LyraMoveComp->bWantsToCrouch)
431
+ {
432
+ UnCrouch();
433
+ }
434
+ else if (LyraMoveComp->IsMovingOnGround())
435
+ {
436
+ Crouch();
437
+ }
438
+ }
439
+
440
+ void ALyraCharacter::OnStartCrouch(float HalfHeightAdjust, float ScaledHalfHeightAdjust)
441
+ {
442
+ if (ULyraAbilitySystemComponent* LyraASC = GetLyraAbilitySystemComponent())
443
+ {
444
+ LyraASC->SetLooseGameplayTagCount(LyraGameplayTags::Status_Crouching, 1);
445
+ }
446
+
447
+
448
+ Super::OnStartCrouch(HalfHeightAdjust, ScaledHalfHeightAdjust);
449
+ }
450
+
451
+ void ALyraCharacter::OnEndCrouch(float HalfHeightAdjust, float ScaledHalfHeightAdjust)
452
+ {
453
+ if (ULyraAbilitySystemComponent* LyraASC = GetLyraAbilitySystemComponent())
454
+ {
455
+ LyraASC->SetLooseGameplayTagCount(LyraGameplayTags::Status_Crouching, 0);
456
+ }
457
+
458
+ Super::OnEndCrouch(HalfHeightAdjust, ScaledHalfHeightAdjust);
459
+ }
460
+
461
+ bool ALyraCharacter::CanJumpInternal_Implementation() const
462
+ {
463
+ // same as ACharacter's implementation but without the crouch check
464
+ return JumpIsAllowedInternal();
465
+ }
466
+
467
+ void ALyraCharacter::OnRep_ReplicatedAcceleration()
468
+ {
469
+ if (ULyraCharacterMovementComponent* LyraMovementComponent = Cast<ULyraCharacterMovementComponent>(GetCharacterMovement()))
470
+ {
471
+ // Decompress Acceleration
472
+ const double MaxAccel = LyraMovementComponent->MaxAcceleration;
473
+ const double AccelXYMagnitude = double(ReplicatedAcceleration.AccelXYMagnitude) * MaxAccel / 255.0; // [0, 255] -> [0, MaxAccel]
474
+ const double AccelXYRadians = double(ReplicatedAcceleration.AccelXYRadians) * TWO_PI / 255.0; // [0, 255] -> [0, 2PI]
475
+
476
+ FVector UnpackedAcceleration(FVector::ZeroVector);
477
+ FMath::PolarToCartesian(AccelXYMagnitude, AccelXYRadians, UnpackedAcceleration.X, UnpackedAcceleration.Y);
478
+ UnpackedAcceleration.Z = double(ReplicatedAcceleration.AccelZ) * MaxAccel / 127.0; // [-127, 127] -> [-MaxAccel, MaxAccel]
479
+
480
+ LyraMovementComponent->SetReplicatedAcceleration(UnpackedAcceleration);
481
+ }
482
+ }
483
+
484
+ void ALyraCharacter::SetGenericTeamId(const FGenericTeamId& NewTeamID)
485
+ {
486
+ if (GetController() == nullptr)
487
+ {
488
+ if (HasAuthority())
489
+ {
490
+ const FGenericTeamId OldTeamID = MyTeamID;
491
+ MyTeamID = NewTeamID;
492
+ ConditionalBroadcastTeamChanged(this, OldTeamID, MyTeamID);
493
+ }
494
+ else
495
+ {
496
+ UE_LOG(LogLyraTeams, Error, TEXT("You can't set the team ID on a character (%s) except on the authority"), *GetPathNameSafe(this));
497
+ }
498
+ }
499
+ else
500
+ {
501
+ UE_LOG(LogLyraTeams, Error, TEXT("You can't set the team ID on a possessed character (%s); it's driven by the associated controller"), *GetPathNameSafe(this));
502
+ }
503
+ }
504
+
505
+ FGenericTeamId ALyraCharacter::GetGenericTeamId() const
506
+ {
507
+ return MyTeamID;
508
+ }
509
+
510
+ FOnLyraTeamIndexChangedDelegate* ALyraCharacter::GetOnTeamIndexChangedDelegate()
511
+ {
512
+ return &OnTeamChangedDelegate;
513
+ }
514
+
515
+ void ALyraCharacter::OnControllerChangedTeam(UObject* TeamAgent, int32 OldTeam, int32 NewTeam)
516
+ {
517
+ const FGenericTeamId MyOldTeamID = MyTeamID;
518
+ MyTeamID = IntegerToGenericTeamId(NewTeam);
519
+ ConditionalBroadcastTeamChanged(this, MyOldTeamID, MyTeamID);
520
+ }
521
+
522
+ void ALyraCharacter::OnRep_MyTeamID(FGenericTeamId OldTeamID)
523
+ {
524
+ ConditionalBroadcastTeamChanged(this, OldTeamID, MyTeamID);
525
+ }
526
+
527
+ bool ALyraCharacter::UpdateSharedReplication()
528
+ {
529
+ if (GetLocalRole() == ROLE_Authority)
530
+ {
531
+ FSharedRepMovement SharedMovement;
532
+ if (SharedMovement.FillForCharacter(this))
533
+ {
534
+ // Only call FastSharedReplication if data has changed since the last frame.
535
+ // Skipping this call will cause replication to reuse the same bunch that we previously
536
+ // produced, but not send it to clients that already received. (But a new client who has not received
537
+ // it, will get it this frame)
538
+ if (!SharedMovement.Equals(LastSharedReplication, this))
539
+ {
540
+ LastSharedReplication = SharedMovement;
541
+ SetReplicatedMovementMode(SharedMovement.RepMovementMode);
542
+
543
+ FastSharedReplication(SharedMovement);
544
+ }
545
+ return true;
546
+ }
547
+ }
548
+
549
+ // We cannot fastrep right now. Don't send anything.
550
+ return false;
551
+ }
552
+
553
+ void ALyraCharacter::FastSharedReplication_Implementation(const FSharedRepMovement& SharedRepMovement)
554
+ {
555
+ if (GetWorld()->IsPlayingReplay())
556
+ {
557
+ return;
558
+ }
559
+
560
+ // Timestamp is checked to reject old moves.
561
+ if (GetLocalRole() == ROLE_SimulatedProxy)
562
+ {
563
+ // Timestamp
564
+ SetReplicatedServerLastTransformUpdateTimeStamp(SharedRepMovement.RepTimeStamp);
565
+
566
+ // Movement mode
567
+ if (GetReplicatedMovementMode() != SharedRepMovement.RepMovementMode)
568
+ {
569
+ SetReplicatedMovementMode(SharedRepMovement.RepMovementMode);
570
+ GetCharacterMovement()->bNetworkMovementModeChanged = true;
571
+ GetCharacterMovement()->bNetworkUpdateReceived = true;
572
+ }
573
+
574
+ // Location, Rotation, Velocity, etc.
575
+ FRepMovement& MutableRepMovement = GetReplicatedMovement_Mutable();
576
+ MutableRepMovement = SharedRepMovement.RepMovement;
577
+
578
+ // This also sets LastRepMovement
579
+ OnRep_ReplicatedMovement();
580
+
581
+ // Jump force
582
+ SetProxyIsJumpForceApplied(SharedRepMovement.bProxyIsJumpForceApplied);
583
+
584
+ // Crouch
585
+ if (IsCrouched() != SharedRepMovement.bIsCrouched)
586
+ {
587
+ SetIsCrouched(SharedRepMovement.bIsCrouched);
588
+ OnRep_IsCrouched();
589
+ }
590
+ }
591
+ }
592
+
593
+ FSharedRepMovement::FSharedRepMovement()
594
+ {
595
+ RepMovement.LocationQuantizationLevel = EVectorQuantization::RoundTwoDecimals;
596
+ }
597
+
598
+ bool FSharedRepMovement::FillForCharacter(ACharacter* Character)
599
+ {
600
+ if (USceneComponent* PawnRootComponent = Character->GetRootComponent())
601
+ {
602
+ UCharacterMovementComponent* CharacterMovement = Character->GetCharacterMovement();
603
+
604
+ RepMovement.Location = FRepMovement::RebaseOntoZeroOrigin(PawnRootComponent->GetComponentLocation(), Character);
605
+ RepMovement.Rotation = PawnRootComponent->GetComponentRotation();
606
+ RepMovement.LinearVelocity = CharacterMovement->Velocity;
607
+ RepMovementMode = CharacterMovement->PackNetworkMovementMode();
608
+ bProxyIsJumpForceApplied = Character->GetProxyIsJumpForceApplied() || (Character->JumpForceTimeRemaining > 0.0f);
609
+ bIsCrouched = Character->IsCrouched();
610
+
611
+ // Timestamp is sent as zero if unused
612
+ if ((CharacterMovement->NetworkSmoothingMode == ENetworkSmoothingMode::Linear) || CharacterMovement->bNetworkAlwaysReplicateTransformUpdateTimestamp)
613
+ {
614
+ RepTimeStamp = CharacterMovement->GetServerLastTransformUpdateTimeStamp();
615
+ }
616
+ else
617
+ {
618
+ RepTimeStamp = 0.f;
619
+ }
620
+
621
+ return true;
622
+ }
623
+ return false;
624
+ }
625
+
626
+ bool FSharedRepMovement::Equals(const FSharedRepMovement& Other, ACharacter* Character) const
627
+ {
628
+ if (RepMovement.Location != Other.RepMovement.Location)
629
+ {
630
+ return false;
631
+ }
632
+
633
+ if (RepMovement.Rotation != Other.RepMovement.Rotation)
634
+ {
635
+ return false;
636
+ }
637
+
638
+ if (RepMovement.LinearVelocity != Other.RepMovement.LinearVelocity)
639
+ {
640
+ return false;
641
+ }
642
+
643
+ if (RepMovementMode != Other.RepMovementMode)
644
+ {
645
+ return false;
646
+ }
647
+
648
+ if (bProxyIsJumpForceApplied != Other.bProxyIsJumpForceApplied)
649
+ {
650
+ return false;
651
+ }
652
+
653
+ if (bIsCrouched != Other.bIsCrouched)
654
+ {
655
+ return false;
656
+ }
657
+
658
+ return true;
659
+ }
660
+
661
+ bool FSharedRepMovement::NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess)
662
+ {
663
+ bOutSuccess = true;
664
+ RepMovement.NetSerialize(Ar, Map, bOutSuccess);
665
+ Ar << RepMovementMode;
666
+ Ar << bProxyIsJumpForceApplied;
667
+ Ar << bIsCrouched;
668
+
669
+ // Timestamp, if non-zero.
670
+ uint8 bHasTimeStamp = (RepTimeStamp != 0.f);
671
+ Ar.SerializeBits(&bHasTimeStamp, 1);
672
+ if (bHasTimeStamp)
673
+ {
674
+ Ar << RepTimeStamp;
675
+ }
676
+ else
677
+ {
678
+ RepTimeStamp = 0.f;
679
+ }
680
+
681
+ return true;
682
+ }
LyraStarterGame/Source/LyraGame/Character/LyraCharacter.h ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "AbilitySystemInterface.h"
6
+ #include "GameplayCueInterface.h"
7
+ #include "GameplayTagAssetInterface.h"
8
+ #include "ModularCharacter.h"
9
+ #include "Teams/LyraTeamAgentInterface.h"
10
+
11
+ #include "LyraCharacter.generated.h"
12
+
13
+ #define UE_API LYRAGAME_API
14
+
15
+ class AActor;
16
+ class AController;
17
+ class ALyraPlayerController;
18
+ class ALyraPlayerState;
19
+ class FLifetimeProperty;
20
+ class IRepChangedPropertyTracker;
21
+ class UAbilitySystemComponent;
22
+ class UInputComponent;
23
+ class ULyraAbilitySystemComponent;
24
+ class ULyraCameraComponent;
25
+ class ULyraHealthComponent;
26
+ class ULyraPawnExtensionComponent;
27
+ class UObject;
28
+ struct FFrame;
29
+ struct FGameplayTag;
30
+ struct FGameplayTagContainer;
31
+
32
+
33
+ /**
34
+ * FLyraReplicatedAcceleration: Compressed representation of acceleration
35
+ */
36
+ USTRUCT()
37
+ struct FLyraReplicatedAcceleration
38
+ {
39
+ GENERATED_BODY()
40
+
41
+ UPROPERTY()
42
+ uint8 AccelXYRadians = 0; // Direction of XY accel component, quantized to represent [0, 2*pi]
43
+
44
+ UPROPERTY()
45
+ uint8 AccelXYMagnitude = 0; //Accel rate of XY component, quantized to represent [0, MaxAcceleration]
46
+
47
+ UPROPERTY()
48
+ int8 AccelZ = 0; // Raw Z accel rate component, quantized to represent [-MaxAcceleration, MaxAcceleration]
49
+ };
50
+
51
+ /** The type we use to send FastShared movement updates. */
52
+ USTRUCT()
53
+ struct FSharedRepMovement
54
+ {
55
+ GENERATED_BODY()
56
+
57
+ FSharedRepMovement();
58
+
59
+ bool FillForCharacter(ACharacter* Character);
60
+ bool Equals(const FSharedRepMovement& Other, ACharacter* Character) const;
61
+
62
+ bool NetSerialize(FArchive& Ar, class UPackageMap* Map, bool& bOutSuccess);
63
+
64
+ UPROPERTY(Transient)
65
+ FRepMovement RepMovement;
66
+
67
+ UPROPERTY(Transient)
68
+ float RepTimeStamp = 0.0f;
69
+
70
+ UPROPERTY(Transient)
71
+ uint8 RepMovementMode = 0;
72
+
73
+ UPROPERTY(Transient)
74
+ bool bProxyIsJumpForceApplied = false;
75
+
76
+ UPROPERTY(Transient)
77
+ bool bIsCrouched = false;
78
+ };
79
+
80
+ template<>
81
+ struct TStructOpsTypeTraits<FSharedRepMovement> : public TStructOpsTypeTraitsBase2<FSharedRepMovement>
82
+ {
83
+ enum
84
+ {
85
+ WithNetSerializer = true,
86
+ WithNetSharedSerialization = true,
87
+ };
88
+ };
89
+
90
+ /**
91
+ * ALyraCharacter
92
+ *
93
+ * The base character pawn class used by this project.
94
+ * Responsible for sending events to pawn components.
95
+ * New behavior should be added via pawn components when possible.
96
+ */
97
+ UCLASS(MinimalAPI, Config = Game, Meta = (ShortTooltip = "The base character pawn class used by this project."))
98
+ class ALyraCharacter : public AModularCharacter, public IAbilitySystemInterface, public IGameplayCueInterface, public IGameplayTagAssetInterface, public ILyraTeamAgentInterface
99
+ {
100
+ GENERATED_BODY()
101
+
102
+ public:
103
+
104
+ UE_API ALyraCharacter(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
105
+
106
+ UFUNCTION(BlueprintCallable, Category = "Lyra|Character")
107
+ UE_API ALyraPlayerController* GetLyraPlayerController() const;
108
+
109
+ UFUNCTION(BlueprintCallable, Category = "Lyra|Character")
110
+ UE_API ALyraPlayerState* GetLyraPlayerState() const;
111
+
112
+ UFUNCTION(BlueprintCallable, Category = "Lyra|Character")
113
+ UE_API ULyraAbilitySystemComponent* GetLyraAbilitySystemComponent() const;
114
+ UE_API virtual UAbilitySystemComponent* GetAbilitySystemComponent() const override;
115
+
116
+ UE_API virtual void GetOwnedGameplayTags(FGameplayTagContainer& TagContainer) const override;
117
+ UE_API virtual bool HasMatchingGameplayTag(FGameplayTag TagToCheck) const override;
118
+ UE_API virtual bool HasAllMatchingGameplayTags(const FGameplayTagContainer& TagContainer) const override;
119
+ UE_API virtual bool HasAnyMatchingGameplayTags(const FGameplayTagContainer& TagContainer) const override;
120
+
121
+ UE_API void ToggleCrouch();
122
+
123
+ //~AActor interface
124
+ UE_API virtual void PreInitializeComponents() override;
125
+ UE_API virtual void BeginPlay() override;
126
+ UE_API virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
127
+ UE_API virtual void Reset() override;
128
+ UE_API virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
129
+ UE_API virtual void PreReplication(IRepChangedPropertyTracker& ChangedPropertyTracker) override;
130
+ //~End of AActor interface
131
+
132
+ //~APawn interface
133
+ UE_API virtual void NotifyControllerChanged() override;
134
+ //~End of APawn interface
135
+
136
+ //~ILyraTeamAgentInterface interface
137
+ UE_API virtual void SetGenericTeamId(const FGenericTeamId& NewTeamID) override;
138
+ UE_API virtual FGenericTeamId GetGenericTeamId() const override;
139
+ UE_API virtual FOnLyraTeamIndexChangedDelegate* GetOnTeamIndexChangedDelegate() override;
140
+ //~End of ILyraTeamAgentInterface interface
141
+
142
+ /** RPCs that is called on frames when default property replication is skipped. This replicates a single movement update to everyone. */
143
+ UFUNCTION(NetMulticast, unreliable)
144
+ UE_API void FastSharedReplication(const FSharedRepMovement& SharedRepMovement);
145
+
146
+ // Last FSharedRepMovement we sent, to avoid sending repeatedly.
147
+ FSharedRepMovement LastSharedReplication;
148
+
149
+ UE_API virtual bool UpdateSharedReplication();
150
+
151
+ protected:
152
+
153
+ UE_API virtual void OnAbilitySystemInitialized();
154
+ UE_API virtual void OnAbilitySystemUninitialized();
155
+
156
+ UE_API virtual void PossessedBy(AController* NewController) override;
157
+ UE_API virtual void UnPossessed() override;
158
+
159
+ UE_API virtual void OnRep_Controller() override;
160
+ UE_API virtual void OnRep_PlayerState() override;
161
+
162
+ UE_API virtual void SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) override;
163
+
164
+ UE_API void InitializeGameplayTags();
165
+
166
+ UE_API virtual void FellOutOfWorld(const class UDamageType& dmgType) override;
167
+
168
+ // Begins the death sequence for the character (disables collision, disables movement, etc...)
169
+ UFUNCTION()
170
+ UE_API virtual void OnDeathStarted(AActor* OwningActor);
171
+
172
+ // Ends the death sequence for the character (detaches controller, destroys pawn, etc...)
173
+ UFUNCTION()
174
+ UE_API virtual void OnDeathFinished(AActor* OwningActor);
175
+
176
+ UE_API void DisableMovementAndCollision();
177
+ UE_API void DestroyDueToDeath();
178
+ UE_API void UninitAndDestroy();
179
+
180
+ // Called when the death sequence for the character has completed
181
+ UFUNCTION(BlueprintImplementableEvent, meta=(DisplayName="OnDeathFinished"))
182
+ UE_API void K2_OnDeathFinished();
183
+
184
+ UE_API virtual void OnMovementModeChanged(EMovementMode PrevMovementMode, uint8 PreviousCustomMode) override;
185
+ UE_API void SetMovementModeTag(EMovementMode MovementMode, uint8 CustomMovementMode, bool bTagEnabled);
186
+
187
+ UE_API virtual void OnStartCrouch(float HalfHeightAdjust, float ScaledHalfHeightAdjust) override;
188
+ UE_API virtual void OnEndCrouch(float HalfHeightAdjust, float ScaledHalfHeightAdjust) override;
189
+
190
+ UE_API virtual bool CanJumpInternal_Implementation() const;
191
+
192
+ private:
193
+
194
+ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Lyra|Character", Meta = (AllowPrivateAccess = "true"))
195
+ TObjectPtr<ULyraPawnExtensionComponent> PawnExtComponent;
196
+
197
+ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Lyra|Character", Meta = (AllowPrivateAccess = "true"))
198
+ TObjectPtr<ULyraHealthComponent> HealthComponent;
199
+
200
+ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Lyra|Character", Meta = (AllowPrivateAccess = "true"))
201
+ TObjectPtr<ULyraCameraComponent> CameraComponent;
202
+
203
+ UPROPERTY(Transient, ReplicatedUsing = OnRep_ReplicatedAcceleration)
204
+ FLyraReplicatedAcceleration ReplicatedAcceleration;
205
+
206
+ UPROPERTY(ReplicatedUsing = OnRep_MyTeamID)
207
+ FGenericTeamId MyTeamID;
208
+
209
+ UPROPERTY()
210
+ FOnLyraTeamIndexChangedDelegate OnTeamChangedDelegate;
211
+
212
+ protected:
213
+ // Called to determine what happens to the team ID when possession ends
214
+ virtual FGenericTeamId DetermineNewTeamAfterPossessionEnds(FGenericTeamId OldTeamID) const
215
+ {
216
+ // This could be changed to return, e.g., OldTeamID if you want to keep it assigned afterwards, or return an ID for some neutral faction, or etc...
217
+ return FGenericTeamId::NoTeam;
218
+ }
219
+
220
+ private:
221
+ UFUNCTION()
222
+ UE_API void OnControllerChangedTeam(UObject* TeamAgent, int32 OldTeam, int32 NewTeam);
223
+
224
+ UFUNCTION()
225
+ UE_API void OnRep_ReplicatedAcceleration();
226
+
227
+ UFUNCTION()
228
+ UE_API void OnRep_MyTeamID(FGenericTeamId OldTeamID);
229
+ };
230
+
231
+ #undef UE_API
LyraStarterGame/Source/LyraGame/Character/LyraCharacterMovementComponent.cpp ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraCharacterMovementComponent.h"
4
+
5
+ #include "AbilitySystemComponent.h"
6
+ #include "AbilitySystemGlobals.h"
7
+ #include "Components/CapsuleComponent.h"
8
+ #include "Engine/World.h"
9
+ #include "GameFramework/Character.h"
10
+
11
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraCharacterMovementComponent)
12
+
13
+ UE_DEFINE_GAMEPLAY_TAG(TAG_Gameplay_MovementStopped, "Gameplay.MovementStopped");
14
+
15
+ namespace LyraCharacter
16
+ {
17
+ static float GroundTraceDistance = 100000.0f;
18
+ FAutoConsoleVariableRef CVar_GroundTraceDistance(TEXT("LyraCharacter.GroundTraceDistance"), GroundTraceDistance, TEXT("Distance to trace down when generating ground information."), ECVF_Cheat);
19
+ };
20
+
21
+
22
+ ULyraCharacterMovementComponent::ULyraCharacterMovementComponent(const FObjectInitializer& ObjectInitializer)
23
+ : Super(ObjectInitializer)
24
+ {
25
+ }
26
+
27
+ void ULyraCharacterMovementComponent::SimulateMovement(float DeltaTime)
28
+ {
29
+ if (bHasReplicatedAcceleration)
30
+ {
31
+ // Preserve our replicated acceleration
32
+ const FVector OriginalAcceleration = Acceleration;
33
+ Super::SimulateMovement(DeltaTime);
34
+ Acceleration = OriginalAcceleration;
35
+ }
36
+ else
37
+ {
38
+ Super::SimulateMovement(DeltaTime);
39
+ }
40
+ }
41
+
42
+ bool ULyraCharacterMovementComponent::CanAttemptJump() const
43
+ {
44
+ // Same as UCharacterMovementComponent's implementation but without the crouch check
45
+ return IsJumpAllowed() &&
46
+ (IsMovingOnGround() || IsFalling()); // Falling included for double-jump and non-zero jump hold time, but validated by character.
47
+ }
48
+
49
+ void ULyraCharacterMovementComponent::InitializeComponent()
50
+ {
51
+ Super::InitializeComponent();
52
+ }
53
+
54
+ const FLyraCharacterGroundInfo& ULyraCharacterMovementComponent::GetGroundInfo()
55
+ {
56
+ if (!CharacterOwner || (GFrameCounter == CachedGroundInfo.LastUpdateFrame))
57
+ {
58
+ return CachedGroundInfo;
59
+ }
60
+
61
+ if (MovementMode == MOVE_Walking)
62
+ {
63
+ CachedGroundInfo.GroundHitResult = CurrentFloor.HitResult;
64
+ CachedGroundInfo.GroundDistance = 0.0f;
65
+ }
66
+ else
67
+ {
68
+ const UCapsuleComponent* CapsuleComp = CharacterOwner->GetCapsuleComponent();
69
+ check(CapsuleComp);
70
+
71
+ const float CapsuleHalfHeight = CapsuleComp->GetUnscaledCapsuleHalfHeight();
72
+ const ECollisionChannel CollisionChannel = (UpdatedComponent ? UpdatedComponent->GetCollisionObjectType() : ECC_Pawn);
73
+ const FVector TraceStart(GetActorLocation());
74
+ const FVector TraceEnd(TraceStart.X, TraceStart.Y, (TraceStart.Z - LyraCharacter::GroundTraceDistance - CapsuleHalfHeight));
75
+
76
+ FCollisionQueryParams QueryParams(SCENE_QUERY_STAT(LyraCharacterMovementComponent_GetGroundInfo), false, CharacterOwner);
77
+ FCollisionResponseParams ResponseParam;
78
+ InitCollisionParams(QueryParams, ResponseParam);
79
+
80
+ FHitResult HitResult;
81
+ GetWorld()->LineTraceSingleByChannel(HitResult, TraceStart, TraceEnd, CollisionChannel, QueryParams, ResponseParam);
82
+
83
+ CachedGroundInfo.GroundHitResult = HitResult;
84
+ CachedGroundInfo.GroundDistance = LyraCharacter::GroundTraceDistance;
85
+
86
+ if (MovementMode == MOVE_NavWalking)
87
+ {
88
+ CachedGroundInfo.GroundDistance = 0.0f;
89
+ }
90
+ else if (HitResult.bBlockingHit)
91
+ {
92
+ CachedGroundInfo.GroundDistance = FMath::Max((HitResult.Distance - CapsuleHalfHeight), 0.0f);
93
+ }
94
+ }
95
+
96
+ CachedGroundInfo.LastUpdateFrame = GFrameCounter;
97
+
98
+ return CachedGroundInfo;
99
+ }
100
+
101
+ void ULyraCharacterMovementComponent::SetReplicatedAcceleration(const FVector& InAcceleration)
102
+ {
103
+ bHasReplicatedAcceleration = true;
104
+ Acceleration = InAcceleration;
105
+ }
106
+
107
+ FRotator ULyraCharacterMovementComponent::GetDeltaRotation(float DeltaTime) const
108
+ {
109
+ if (UAbilitySystemComponent* ASC = UAbilitySystemGlobals::GetAbilitySystemComponentFromActor(GetOwner()))
110
+ {
111
+ if (ASC->HasMatchingGameplayTag(TAG_Gameplay_MovementStopped))
112
+ {
113
+ return FRotator(0,0,0);
114
+ }
115
+ }
116
+
117
+ return Super::GetDeltaRotation(DeltaTime);
118
+ }
119
+
120
+ float ULyraCharacterMovementComponent::GetMaxSpeed() const
121
+ {
122
+ if (UAbilitySystemComponent* ASC = UAbilitySystemGlobals::GetAbilitySystemComponentFromActor(GetOwner()))
123
+ {
124
+ if (ASC->HasMatchingGameplayTag(TAG_Gameplay_MovementStopped))
125
+ {
126
+ return 0;
127
+ }
128
+ }
129
+
130
+ return Super::GetMaxSpeed();
131
+ }
LyraStarterGame/Source/LyraGame/Character/LyraCharacterMovementComponent.h ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "GameFramework/CharacterMovementComponent.h"
6
+ #include "NativeGameplayTags.h"
7
+
8
+ #include "LyraCharacterMovementComponent.generated.h"
9
+
10
+ #define UE_API LYRAGAME_API
11
+
12
+ class UObject;
13
+ struct FFrame;
14
+
15
+ LYRAGAME_API UE_DECLARE_GAMEPLAY_TAG_EXTERN(TAG_Gameplay_MovementStopped);
16
+
17
+ /**
18
+ * FLyraCharacterGroundInfo
19
+ *
20
+ * Information about the ground under the character. It only gets updated as needed.
21
+ */
22
+ USTRUCT(BlueprintType)
23
+ struct FLyraCharacterGroundInfo
24
+ {
25
+ GENERATED_BODY()
26
+
27
+ FLyraCharacterGroundInfo()
28
+ : LastUpdateFrame(0)
29
+ , GroundDistance(0.0f)
30
+ {}
31
+
32
+ uint64 LastUpdateFrame;
33
+
34
+ UPROPERTY(BlueprintReadOnly)
35
+ FHitResult GroundHitResult;
36
+
37
+ UPROPERTY(BlueprintReadOnly)
38
+ float GroundDistance;
39
+ };
40
+
41
+
42
+ /**
43
+ * ULyraCharacterMovementComponent
44
+ *
45
+ * The base character movement component class used by this project.
46
+ */
47
+ UCLASS(MinimalAPI, Config = Game)
48
+ class ULyraCharacterMovementComponent : public UCharacterMovementComponent
49
+ {
50
+ GENERATED_BODY()
51
+
52
+ public:
53
+
54
+ UE_API ULyraCharacterMovementComponent(const FObjectInitializer& ObjectInitializer);
55
+
56
+ UE_API virtual void SimulateMovement(float DeltaTime) override;
57
+
58
+ UE_API virtual bool CanAttemptJump() const override;
59
+
60
+ // Returns the current ground info. Calling this will update the ground info if it's out of date.
61
+ UFUNCTION(BlueprintCallable, Category = "Lyra|CharacterMovement")
62
+ UE_API const FLyraCharacterGroundInfo& GetGroundInfo();
63
+
64
+ UE_API void SetReplicatedAcceleration(const FVector& InAcceleration);
65
+
66
+ //~UMovementComponent interface
67
+ UE_API virtual FRotator GetDeltaRotation(float DeltaTime) const override;
68
+ UE_API virtual float GetMaxSpeed() const override;
69
+ //~End of UMovementComponent interface
70
+
71
+ protected:
72
+
73
+ UE_API virtual void InitializeComponent() override;
74
+
75
+ protected:
76
+
77
+ // Cached ground info for the character. Do not access this directly! It's only updated when accessed via GetGroundInfo().
78
+ FLyraCharacterGroundInfo CachedGroundInfo;
79
+
80
+ UPROPERTY(Transient)
81
+ bool bHasReplicatedAcceleration = false;
82
+ };
83
+
84
+ #undef UE_API
LyraStarterGame/Source/LyraGame/Character/LyraCharacterWithAbilities.cpp ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraCharacterWithAbilities.h"
4
+
5
+ #include "AbilitySystem/Attributes/LyraCombatSet.h"
6
+ #include "AbilitySystem/Attributes/LyraHealthSet.h"
7
+ #include "AbilitySystem/LyraAbilitySystemComponent.h"
8
+ #include "Async/TaskGraphInterfaces.h"
9
+
10
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraCharacterWithAbilities)
11
+
12
+ ALyraCharacterWithAbilities::ALyraCharacterWithAbilities(const FObjectInitializer& ObjectInitializer)
13
+ : Super(ObjectInitializer)
14
+ {
15
+ AbilitySystemComponent = ObjectInitializer.CreateDefaultSubobject<ULyraAbilitySystemComponent>(this, TEXT("AbilitySystemComponent"));
16
+ AbilitySystemComponent->SetIsReplicated(true);
17
+ AbilitySystemComponent->SetReplicationMode(EGameplayEffectReplicationMode::Mixed);
18
+
19
+ // These attribute sets will be detected by AbilitySystemComponent::InitializeComponent. Keeping a reference so that the sets don't get garbage collected before that.
20
+ HealthSet = CreateDefaultSubobject<ULyraHealthSet>(TEXT("HealthSet"));
21
+ CombatSet = CreateDefaultSubobject<ULyraCombatSet>(TEXT("CombatSet"));
22
+
23
+ // AbilitySystemComponent needs to be updated at a high frequency.
24
+ SetNetUpdateFrequency(100.0f);
25
+ }
26
+
27
+ void ALyraCharacterWithAbilities::PostInitializeComponents()
28
+ {
29
+ Super::PostInitializeComponents();
30
+
31
+ check(AbilitySystemComponent);
32
+ AbilitySystemComponent->InitAbilityActorInfo(this, this);
33
+ }
34
+
35
+ UAbilitySystemComponent* ALyraCharacterWithAbilities::GetAbilitySystemComponent() const
36
+ {
37
+ return AbilitySystemComponent;
38
+ }
39
+
LyraStarterGame/Source/LyraGame/Character/LyraCharacterWithAbilities.h ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "Character/LyraCharacter.h"
6
+
7
+ #include "LyraCharacterWithAbilities.generated.h"
8
+
9
+ #define UE_API LYRAGAME_API
10
+
11
+ class UAbilitySystemComponent;
12
+ class ULyraAbilitySystemComponent;
13
+ class UObject;
14
+
15
+ // ALyraCharacter typically gets the ability system component from the possessing player state
16
+ // This represents a character with a self-contained ability system component.
17
+ UCLASS(MinimalAPI, Blueprintable)
18
+ class ALyraCharacterWithAbilities : public ALyraCharacter
19
+ {
20
+ GENERATED_BODY()
21
+
22
+ public:
23
+ UE_API ALyraCharacterWithAbilities(const FObjectInitializer& ObjectInitializer);
24
+
25
+ UE_API virtual void PostInitializeComponents() override;
26
+
27
+ UE_API virtual UAbilitySystemComponent* GetAbilitySystemComponent() const override;
28
+
29
+ private:
30
+
31
+ // The ability system component sub-object used by player characters.
32
+ UPROPERTY(VisibleAnywhere, Category = "Lyra|PlayerState")
33
+ TObjectPtr<ULyraAbilitySystemComponent> AbilitySystemComponent;
34
+
35
+ // Health attribute set used by this actor.
36
+ UPROPERTY()
37
+ TObjectPtr<const class ULyraHealthSet> HealthSet;
38
+ // Combat attribute set used by this actor.
39
+ UPROPERTY()
40
+ TObjectPtr<const class ULyraCombatSet> CombatSet;
41
+ };
42
+
43
+ #undef UE_API
LyraStarterGame/Source/LyraGame/Character/LyraHealthComponent.cpp ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "Character/LyraHealthComponent.h"
4
+
5
+ #include "AbilitySystem/Attributes/LyraAttributeSet.h"
6
+ #include "LyraLogChannels.h"
7
+ #include "System/LyraAssetManager.h"
8
+ #include "System/LyraGameData.h"
9
+ #include "LyraGameplayTags.h"
10
+ #include "Net/UnrealNetwork.h"
11
+ #include "GameplayEffectExtension.h"
12
+ #include "AbilitySystem/LyraAbilitySystemComponent.h"
13
+ #include "AbilitySystem/Attributes/LyraHealthSet.h"
14
+ #include "Messages/LyraVerbMessage.h"
15
+ #include "Messages/LyraVerbMessageHelpers.h"
16
+ #include "GameFramework/GameplayMessageSubsystem.h"
17
+ #include "GameFramework/PlayerState.h"
18
+ #include "Engine/World.h"
19
+
20
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraHealthComponent)
21
+
22
+ UE_DEFINE_GAMEPLAY_TAG_STATIC(TAG_Lyra_Elimination_Message, "Lyra.Elimination.Message");
23
+
24
+
25
+ ULyraHealthComponent::ULyraHealthComponent(const FObjectInitializer& ObjectInitializer)
26
+ : Super(ObjectInitializer)
27
+ {
28
+ PrimaryComponentTick.bStartWithTickEnabled = false;
29
+ PrimaryComponentTick.bCanEverTick = false;
30
+
31
+ SetIsReplicatedByDefault(true);
32
+
33
+ AbilitySystemComponent = nullptr;
34
+ HealthSet = nullptr;
35
+ DeathState = ELyraDeathState::NotDead;
36
+ }
37
+
38
+ void ULyraHealthComponent::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
39
+ {
40
+ Super::GetLifetimeReplicatedProps(OutLifetimeProps);
41
+
42
+ DOREPLIFETIME(ULyraHealthComponent, DeathState);
43
+ }
44
+
45
+ void ULyraHealthComponent::OnUnregister()
46
+ {
47
+ UninitializeFromAbilitySystem();
48
+
49
+ Super::OnUnregister();
50
+ }
51
+
52
+ void ULyraHealthComponent::InitializeWithAbilitySystem(ULyraAbilitySystemComponent* InASC)
53
+ {
54
+ AActor* Owner = GetOwner();
55
+ check(Owner);
56
+
57
+ if (AbilitySystemComponent)
58
+ {
59
+ UE_LOG(LogLyra, Error, TEXT("LyraHealthComponent: Health component for owner [%s] has already been initialized with an ability system."), *GetNameSafe(Owner));
60
+ return;
61
+ }
62
+
63
+ AbilitySystemComponent = InASC;
64
+ if (!AbilitySystemComponent)
65
+ {
66
+ UE_LOG(LogLyra, Error, TEXT("LyraHealthComponent: Cannot initialize health component for owner [%s] with NULL ability system."), *GetNameSafe(Owner));
67
+ return;
68
+ }
69
+
70
+ HealthSet = AbilitySystemComponent->GetSet<ULyraHealthSet>();
71
+ if (!HealthSet)
72
+ {
73
+ UE_LOG(LogLyra, Error, TEXT("LyraHealthComponent: Cannot initialize health component for owner [%s] with NULL health set on the ability system."), *GetNameSafe(Owner));
74
+ return;
75
+ }
76
+
77
+ // Register to listen for attribute changes.
78
+ HealthSet->OnHealthChanged.AddUObject(this, &ThisClass::HandleHealthChanged);
79
+ HealthSet->OnMaxHealthChanged.AddUObject(this, &ThisClass::HandleMaxHealthChanged);
80
+ HealthSet->OnOutOfHealth.AddUObject(this, &ThisClass::HandleOutOfHealth);
81
+
82
+ // TEMP: Reset attributes to default values. Eventually this will be driven by a spread sheet.
83
+ AbilitySystemComponent->SetNumericAttributeBase(ULyraHealthSet::GetHealthAttribute(), HealthSet->GetMaxHealth());
84
+
85
+ ClearGameplayTags();
86
+
87
+ OnHealthChanged.Broadcast(this, HealthSet->GetHealth(), HealthSet->GetHealth(), nullptr);
88
+ OnMaxHealthChanged.Broadcast(this, HealthSet->GetHealth(), HealthSet->GetHealth(), nullptr);
89
+ }
90
+
91
+ void ULyraHealthComponent::UninitializeFromAbilitySystem()
92
+ {
93
+ ClearGameplayTags();
94
+
95
+ if (HealthSet)
96
+ {
97
+ HealthSet->OnHealthChanged.RemoveAll(this);
98
+ HealthSet->OnMaxHealthChanged.RemoveAll(this);
99
+ HealthSet->OnOutOfHealth.RemoveAll(this);
100
+ }
101
+
102
+ HealthSet = nullptr;
103
+ AbilitySystemComponent = nullptr;
104
+ }
105
+
106
+ void ULyraHealthComponent::ClearGameplayTags()
107
+ {
108
+ if (AbilitySystemComponent)
109
+ {
110
+ AbilitySystemComponent->SetLooseGameplayTagCount(LyraGameplayTags::Status_Death_Dying, 0);
111
+ AbilitySystemComponent->SetLooseGameplayTagCount(LyraGameplayTags::Status_Death_Dead, 0);
112
+ }
113
+ }
114
+
115
+ float ULyraHealthComponent::GetHealth() const
116
+ {
117
+ return (HealthSet ? HealthSet->GetHealth() : 0.0f);
118
+ }
119
+
120
+ float ULyraHealthComponent::GetMaxHealth() const
121
+ {
122
+ return (HealthSet ? HealthSet->GetMaxHealth() : 0.0f);
123
+ }
124
+
125
+ float ULyraHealthComponent::GetHealthNormalized() const
126
+ {
127
+ if (HealthSet)
128
+ {
129
+ const float Health = HealthSet->GetHealth();
130
+ const float MaxHealth = HealthSet->GetMaxHealth();
131
+
132
+ return ((MaxHealth > 0.0f) ? (Health / MaxHealth) : 0.0f);
133
+ }
134
+
135
+ return 0.0f;
136
+ }
137
+
138
+ void ULyraHealthComponent::HandleHealthChanged(AActor* DamageInstigator, AActor* DamageCauser, const FGameplayEffectSpec* DamageEffectSpec, float DamageMagnitude, float OldValue, float NewValue)
139
+ {
140
+ OnHealthChanged.Broadcast(this, OldValue, NewValue, DamageInstigator);
141
+ }
142
+
143
+ void ULyraHealthComponent::HandleMaxHealthChanged(AActor* DamageInstigator, AActor* DamageCauser, const FGameplayEffectSpec* DamageEffectSpec, float DamageMagnitude, float OldValue, float NewValue)
144
+ {
145
+ OnMaxHealthChanged.Broadcast(this, OldValue, NewValue, DamageInstigator);
146
+ }
147
+
148
+ void ULyraHealthComponent::HandleOutOfHealth(AActor* DamageInstigator, AActor* DamageCauser, const FGameplayEffectSpec* DamageEffectSpec, float DamageMagnitude, float OldValue, float NewValue)
149
+ {
150
+ #if WITH_SERVER_CODE
151
+ if (AbilitySystemComponent && DamageEffectSpec)
152
+ {
153
+ // Send the "GameplayEvent.Death" gameplay event through the owner's ability system. This can be used to trigger a death gameplay ability.
154
+ {
155
+ FGameplayEventData Payload;
156
+ Payload.EventTag = LyraGameplayTags::GameplayEvent_Death;
157
+ Payload.Instigator = DamageInstigator;
158
+ Payload.Target = AbilitySystemComponent->GetAvatarActor();
159
+ Payload.OptionalObject = DamageEffectSpec->Def;
160
+ Payload.ContextHandle = DamageEffectSpec->GetEffectContext();
161
+ Payload.InstigatorTags = *DamageEffectSpec->CapturedSourceTags.GetAggregatedTags();
162
+ Payload.TargetTags = *DamageEffectSpec->CapturedTargetTags.GetAggregatedTags();
163
+ Payload.EventMagnitude = DamageMagnitude;
164
+
165
+ FScopedPredictionWindow NewScopedWindow(AbilitySystemComponent, true);
166
+ AbilitySystemComponent->HandleGameplayEvent(Payload.EventTag, &Payload);
167
+ }
168
+
169
+ // Send a standardized verb message that other systems can observe
170
+ {
171
+ FLyraVerbMessage Message;
172
+ Message.Verb = TAG_Lyra_Elimination_Message;
173
+ Message.Instigator = DamageInstigator;
174
+ Message.InstigatorTags = *DamageEffectSpec->CapturedSourceTags.GetAggregatedTags();
175
+ Message.Target = ULyraVerbMessageHelpers::GetPlayerStateFromObject(AbilitySystemComponent->GetAvatarActor());
176
+ Message.TargetTags = *DamageEffectSpec->CapturedTargetTags.GetAggregatedTags();
177
+ //@TODO: Fill out context tags, and any non-ability-system source/instigator tags
178
+ //@TODO: Determine if it's an opposing team kill, self-own, team kill, etc...
179
+
180
+ UGameplayMessageSubsystem& MessageSystem = UGameplayMessageSubsystem::Get(GetWorld());
181
+ MessageSystem.BroadcastMessage(Message.Verb, Message);
182
+ }
183
+
184
+ //@TODO: assist messages (could compute from damage dealt elsewhere)?
185
+ }
186
+
187
+ #endif // #if WITH_SERVER_CODE
188
+ }
189
+
190
+ void ULyraHealthComponent::OnRep_DeathState(ELyraDeathState OldDeathState)
191
+ {
192
+ const ELyraDeathState NewDeathState = DeathState;
193
+
194
+ // Revert the death state for now since we rely on StartDeath and FinishDeath to change it.
195
+ DeathState = OldDeathState;
196
+
197
+ if (OldDeathState > NewDeathState)
198
+ {
199
+ // The server is trying to set us back but we've already predicted past the server state.
200
+ UE_LOG(LogLyra, Warning, TEXT("LyraHealthComponent: Predicted past server death state [%d] -> [%d] for owner [%s]."), (uint8)OldDeathState, (uint8)NewDeathState, *GetNameSafe(GetOwner()));
201
+ return;
202
+ }
203
+
204
+ if (OldDeathState == ELyraDeathState::NotDead)
205
+ {
206
+ if (NewDeathState == ELyraDeathState::DeathStarted)
207
+ {
208
+ StartDeath();
209
+ }
210
+ else if (NewDeathState == ELyraDeathState::DeathFinished)
211
+ {
212
+ StartDeath();
213
+ FinishDeath();
214
+ }
215
+ else
216
+ {
217
+ UE_LOG(LogLyra, Error, TEXT("LyraHealthComponent: Invalid death transition [%d] -> [%d] for owner [%s]."), (uint8)OldDeathState, (uint8)NewDeathState, *GetNameSafe(GetOwner()));
218
+ }
219
+ }
220
+ else if (OldDeathState == ELyraDeathState::DeathStarted)
221
+ {
222
+ if (NewDeathState == ELyraDeathState::DeathFinished)
223
+ {
224
+ FinishDeath();
225
+ }
226
+ else
227
+ {
228
+ UE_LOG(LogLyra, Error, TEXT("LyraHealthComponent: Invalid death transition [%d] -> [%d] for owner [%s]."), (uint8)OldDeathState, (uint8)NewDeathState, *GetNameSafe(GetOwner()));
229
+ }
230
+ }
231
+
232
+ ensureMsgf((DeathState == NewDeathState), TEXT("LyraHealthComponent: Death transition failed [%d] -> [%d] for owner [%s]."), (uint8)OldDeathState, (uint8)NewDeathState, *GetNameSafe(GetOwner()));
233
+ }
234
+
235
+ void ULyraHealthComponent::StartDeath()
236
+ {
237
+ if (DeathState != ELyraDeathState::NotDead)
238
+ {
239
+ return;
240
+ }
241
+
242
+ DeathState = ELyraDeathState::DeathStarted;
243
+
244
+ if (AbilitySystemComponent)
245
+ {
246
+ AbilitySystemComponent->SetLooseGameplayTagCount(LyraGameplayTags::Status_Death_Dying, 1);
247
+ }
248
+
249
+ AActor* Owner = GetOwner();
250
+ check(Owner);
251
+
252
+ OnDeathStarted.Broadcast(Owner);
253
+
254
+ Owner->ForceNetUpdate();
255
+ }
256
+
257
+ void ULyraHealthComponent::FinishDeath()
258
+ {
259
+ if (DeathState != ELyraDeathState::DeathStarted)
260
+ {
261
+ return;
262
+ }
263
+
264
+ DeathState = ELyraDeathState::DeathFinished;
265
+
266
+ if (AbilitySystemComponent)
267
+ {
268
+ AbilitySystemComponent->SetLooseGameplayTagCount(LyraGameplayTags::Status_Death_Dead, 1);
269
+ }
270
+
271
+ AActor* Owner = GetOwner();
272
+ check(Owner);
273
+
274
+ OnDeathFinished.Broadcast(Owner);
275
+
276
+ Owner->ForceNetUpdate();
277
+ }
278
+
279
+ void ULyraHealthComponent::DamageSelfDestruct(bool bFellOutOfWorld)
280
+ {
281
+ if ((DeathState == ELyraDeathState::NotDead) && AbilitySystemComponent)
282
+ {
283
+ const TSubclassOf<UGameplayEffect> DamageGE = ULyraAssetManager::GetSubclass(ULyraGameData::Get().DamageGameplayEffect_SetByCaller);
284
+ if (!DamageGE)
285
+ {
286
+ UE_LOG(LogLyra, Error, TEXT("LyraHealthComponent: DamageSelfDestruct failed for owner [%s]. Unable to find gameplay effect [%s]."), *GetNameSafe(GetOwner()), *ULyraGameData::Get().DamageGameplayEffect_SetByCaller.GetAssetName());
287
+ return;
288
+ }
289
+
290
+ FGameplayEffectSpecHandle SpecHandle = AbilitySystemComponent->MakeOutgoingSpec(DamageGE, 1.0f, AbilitySystemComponent->MakeEffectContext());
291
+ FGameplayEffectSpec* Spec = SpecHandle.Data.Get();
292
+
293
+ if (!Spec)
294
+ {
295
+ UE_LOG(LogLyra, Error, TEXT("LyraHealthComponent: DamageSelfDestruct failed for owner [%s]. Unable to make outgoing spec for [%s]."), *GetNameSafe(GetOwner()), *GetNameSafe(DamageGE));
296
+ return;
297
+ }
298
+
299
+ Spec->AddDynamicAssetTag(TAG_Gameplay_DamageSelfDestruct);
300
+
301
+ if (bFellOutOfWorld)
302
+ {
303
+ Spec->AddDynamicAssetTag(TAG_Gameplay_FellOutOfWorld);
304
+ }
305
+
306
+ const float DamageAmount = GetMaxHealth();
307
+
308
+ Spec->SetSetByCallerMagnitude(LyraGameplayTags::SetByCaller_Damage, DamageAmount);
309
+ AbilitySystemComponent->ApplyGameplayEffectSpecToSelf(*Spec);
310
+ }
311
+ }
312
+
LyraStarterGame/Source/LyraGame/Character/LyraHealthComponent.h ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "Components/GameFrameworkComponent.h"
6
+
7
+ #include "LyraHealthComponent.generated.h"
8
+
9
+ #define UE_API LYRAGAME_API
10
+
11
+ class ULyraHealthComponent;
12
+
13
+ class ULyraAbilitySystemComponent;
14
+ class ULyraHealthSet;
15
+ class UObject;
16
+ struct FFrame;
17
+ struct FGameplayEffectSpec;
18
+
19
+ DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FLyraHealth_DeathEvent, AActor*, OwningActor);
20
+ DECLARE_DYNAMIC_MULTICAST_DELEGATE_FourParams(FLyraHealth_AttributeChanged, ULyraHealthComponent*, HealthComponent, float, OldValue, float, NewValue, AActor*, Instigator);
21
+
22
+ /**
23
+ * ELyraDeathState
24
+ *
25
+ * Defines current state of death.
26
+ */
27
+ UENUM(BlueprintType)
28
+ enum class ELyraDeathState : uint8
29
+ {
30
+ NotDead = 0,
31
+ DeathStarted,
32
+ DeathFinished
33
+ };
34
+
35
+
36
+ /**
37
+ * ULyraHealthComponent
38
+ *
39
+ * An actor component used to handle anything related to health.
40
+ */
41
+ UCLASS(MinimalAPI, Blueprintable, Meta=(BlueprintSpawnableComponent))
42
+ class ULyraHealthComponent : public UGameFrameworkComponent
43
+ {
44
+ GENERATED_BODY()
45
+
46
+ public:
47
+
48
+ UE_API ULyraHealthComponent(const FObjectInitializer& ObjectInitializer);
49
+
50
+ // Returns the health component if one exists on the specified actor.
51
+ UFUNCTION(BlueprintPure, Category = "Lyra|Health")
52
+ static ULyraHealthComponent* FindHealthComponent(const AActor* Actor) { return (Actor ? Actor->FindComponentByClass<ULyraHealthComponent>() : nullptr); }
53
+
54
+ // Initialize the component using an ability system component.
55
+ UFUNCTION(BlueprintCallable, Category = "Lyra|Health")
56
+ UE_API void InitializeWithAbilitySystem(ULyraAbilitySystemComponent* InASC);
57
+
58
+ // Uninitialize the component, clearing any references to the ability system.
59
+ UFUNCTION(BlueprintCallable, Category = "Lyra|Health")
60
+ UE_API void UninitializeFromAbilitySystem();
61
+
62
+ // Returns the current health value.
63
+ UFUNCTION(BlueprintCallable, Category = "Lyra|Health")
64
+ UE_API float GetHealth() const;
65
+
66
+ // Returns the current maximum health value.
67
+ UFUNCTION(BlueprintCallable, Category = "Lyra|Health")
68
+ UE_API float GetMaxHealth() const;
69
+
70
+ // Returns the current health in the range [0.0, 1.0].
71
+ UFUNCTION(BlueprintCallable, Category = "Lyra|Health")
72
+ UE_API float GetHealthNormalized() const;
73
+
74
+ UFUNCTION(BlueprintCallable, Category = "Lyra|Health")
75
+ ELyraDeathState GetDeathState() const { return DeathState; }
76
+
77
+ UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "Lyra|Health", Meta = (ExpandBoolAsExecs = "ReturnValue"))
78
+ bool IsDeadOrDying() const { return (DeathState > ELyraDeathState::NotDead); }
79
+
80
+ // Begins the death sequence for the owner.
81
+ UE_API virtual void StartDeath();
82
+
83
+ // Ends the death sequence for the owner.
84
+ UE_API virtual void FinishDeath();
85
+
86
+ // Applies enough damage to kill the owner.
87
+ UE_API virtual void DamageSelfDestruct(bool bFellOutOfWorld = false);
88
+
89
+ public:
90
+
91
+ // Delegate fired when the health value has changed. This is called on the client but the instigator may not be valid
92
+ UPROPERTY(BlueprintAssignable)
93
+ FLyraHealth_AttributeChanged OnHealthChanged;
94
+
95
+ // Delegate fired when the max health value has changed. This is called on the client but the instigator may not be valid
96
+ UPROPERTY(BlueprintAssignable)
97
+ FLyraHealth_AttributeChanged OnMaxHealthChanged;
98
+
99
+ // Delegate fired when the death sequence has started.
100
+ UPROPERTY(BlueprintAssignable)
101
+ FLyraHealth_DeathEvent OnDeathStarted;
102
+
103
+ // Delegate fired when the death sequence has finished.
104
+ UPROPERTY(BlueprintAssignable)
105
+ FLyraHealth_DeathEvent OnDeathFinished;
106
+
107
+ protected:
108
+
109
+ UE_API virtual void OnUnregister() override;
110
+
111
+ UE_API void ClearGameplayTags();
112
+
113
+ UE_API virtual void HandleHealthChanged(AActor* DamageInstigator, AActor* DamageCauser, const FGameplayEffectSpec* DamageEffectSpec, float DamageMagnitude, float OldValue, float NewValue);
114
+ UE_API virtual void HandleMaxHealthChanged(AActor* DamageInstigator, AActor* DamageCauser, const FGameplayEffectSpec* DamageEffectSpec, float DamageMagnitude, float OldValue, float NewValue);
115
+ UE_API virtual void HandleOutOfHealth(AActor* DamageInstigator, AActor* DamageCauser, const FGameplayEffectSpec* DamageEffectSpec, float DamageMagnitude, float OldValue, float NewValue);
116
+
117
+ UFUNCTION()
118
+ UE_API virtual void OnRep_DeathState(ELyraDeathState OldDeathState);
119
+
120
+ protected:
121
+
122
+ // Ability system used by this component.
123
+ UPROPERTY()
124
+ TObjectPtr<ULyraAbilitySystemComponent> AbilitySystemComponent;
125
+
126
+ // Health set used by this component.
127
+ UPROPERTY()
128
+ TObjectPtr<const ULyraHealthSet> HealthSet;
129
+
130
+ // Replicated state used to handle dying.
131
+ UPROPERTY(ReplicatedUsing = OnRep_DeathState)
132
+ ELyraDeathState DeathState;
133
+ };
134
+
135
+ #undef UE_API
LyraStarterGame/Source/LyraGame/Character/LyraHeroComponent.cpp ADDED
@@ -0,0 +1,512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraHeroComponent.h"
4
+ #include "Components/GameFrameworkComponentDelegates.h"
5
+ #include "Logging/MessageLog.h"
6
+ #include "LyraLogChannels.h"
7
+ #include "EnhancedInputSubsystems.h"
8
+ #include "Player/LyraPlayerController.h"
9
+ #include "Player/LyraPlayerState.h"
10
+ #include "Player/LyraLocalPlayer.h"
11
+ #include "Character/LyraPawnExtensionComponent.h"
12
+ #include "Character/LyraPawnData.h"
13
+ #include "Character/LyraCharacter.h"
14
+ #include "AbilitySystem/LyraAbilitySystemComponent.h"
15
+ #include "Input/LyraInputConfig.h"
16
+ #include "Input/LyraInputComponent.h"
17
+ #include "Camera/LyraCameraComponent.h"
18
+ #include "LyraGameplayTags.h"
19
+ #include "Components/GameFrameworkComponentManager.h"
20
+ #include "PlayerMappableInputConfig.h"
21
+ #include "Camera/LyraCameraMode.h"
22
+ #include "UserSettings/EnhancedInputUserSettings.h"
23
+ #include "InputMappingContext.h"
24
+
25
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraHeroComponent)
26
+
27
+ #if WITH_EDITOR
28
+ #include "Misc/UObjectToken.h"
29
+ #endif // WITH_EDITOR
30
+
31
+ namespace LyraHero
32
+ {
33
+ static const float LookYawRate = 300.0f;
34
+ static const float LookPitchRate = 165.0f;
35
+ };
36
+
37
+ const FName ULyraHeroComponent::NAME_BindInputsNow("BindInputsNow");
38
+ const FName ULyraHeroComponent::NAME_ActorFeatureName("Hero");
39
+
40
+ ULyraHeroComponent::ULyraHeroComponent(const FObjectInitializer& ObjectInitializer)
41
+ : Super(ObjectInitializer)
42
+ {
43
+ AbilityCameraMode = nullptr;
44
+ bReadyToBindInputs = false;
45
+ }
46
+
47
+ void ULyraHeroComponent::OnRegister()
48
+ {
49
+ Super::OnRegister();
50
+
51
+ if (!GetPawn<APawn>())
52
+ {
53
+ UE_LOG(LogLyra, Error, TEXT("[ULyraHeroComponent::OnRegister] This component has been added to a blueprint whose base class is not a Pawn. To use this component, it MUST be placed on a Pawn Blueprint."));
54
+
55
+ #if WITH_EDITOR
56
+ if (GIsEditor)
57
+ {
58
+ static const FText Message = NSLOCTEXT("LyraHeroComponent", "NotOnPawnError", "has been added to a blueprint whose base class is not a Pawn. To use this component, it MUST be placed on a Pawn Blueprint. This will cause a crash if you PIE!");
59
+ static const FName HeroMessageLogName = TEXT("LyraHeroComponent");
60
+
61
+ FMessageLog(HeroMessageLogName).Error()
62
+ ->AddToken(FUObjectToken::Create(this, FText::FromString(GetNameSafe(this))))
63
+ ->AddToken(FTextToken::Create(Message));
64
+
65
+ FMessageLog(HeroMessageLogName).Open();
66
+ }
67
+ #endif
68
+ }
69
+ else
70
+ {
71
+ // Register with the init state system early, this will only work if this is a game world
72
+ RegisterInitStateFeature();
73
+ }
74
+ }
75
+
76
+ bool ULyraHeroComponent::CanChangeInitState(UGameFrameworkComponentManager* Manager, FGameplayTag CurrentState, FGameplayTag DesiredState) const
77
+ {
78
+ check(Manager);
79
+
80
+ APawn* Pawn = GetPawn<APawn>();
81
+
82
+ if (!CurrentState.IsValid() && DesiredState == LyraGameplayTags::InitState_Spawned)
83
+ {
84
+ // As long as we have a real pawn, let us transition
85
+ if (Pawn)
86
+ {
87
+ return true;
88
+ }
89
+ }
90
+ else if (CurrentState == LyraGameplayTags::InitState_Spawned && DesiredState == LyraGameplayTags::InitState_DataAvailable)
91
+ {
92
+ // The player state is required.
93
+ if (!GetPlayerState<ALyraPlayerState>())
94
+ {
95
+ return false;
96
+ }
97
+
98
+ // If we're authority or autonomous, we need to wait for a controller with registered ownership of the player state.
99
+ if (Pawn->GetLocalRole() != ROLE_SimulatedProxy)
100
+ {
101
+ AController* Controller = GetController<AController>();
102
+
103
+ const bool bHasControllerPairedWithPS = (Controller != nullptr) && \
104
+ (Controller->PlayerState != nullptr) && \
105
+ (Controller->PlayerState->GetOwner() == Controller);
106
+
107
+ if (!bHasControllerPairedWithPS)
108
+ {
109
+ return false;
110
+ }
111
+ }
112
+
113
+ const bool bIsLocallyControlled = Pawn->IsLocallyControlled();
114
+ const bool bIsBot = Pawn->IsBotControlled();
115
+
116
+ if (bIsLocallyControlled && !bIsBot)
117
+ {
118
+ ALyraPlayerController* LyraPC = GetController<ALyraPlayerController>();
119
+
120
+ // The input component and local player is required when locally controlled.
121
+ if (!Pawn->InputComponent || !LyraPC || !LyraPC->GetLocalPlayer())
122
+ {
123
+ return false;
124
+ }
125
+ }
126
+
127
+ return true;
128
+ }
129
+ else if (CurrentState == LyraGameplayTags::InitState_DataAvailable && DesiredState == LyraGameplayTags::InitState_DataInitialized)
130
+ {
131
+ // Wait for player state and extension component
132
+ ALyraPlayerState* LyraPS = GetPlayerState<ALyraPlayerState>();
133
+
134
+ return LyraPS && Manager->HasFeatureReachedInitState(Pawn, ULyraPawnExtensionComponent::NAME_ActorFeatureName, LyraGameplayTags::InitState_DataInitialized);
135
+ }
136
+ else if (CurrentState == LyraGameplayTags::InitState_DataInitialized && DesiredState == LyraGameplayTags::InitState_GameplayReady)
137
+ {
138
+ // TODO add ability initialization checks?
139
+ return true;
140
+ }
141
+
142
+ return false;
143
+ }
144
+
145
+ void ULyraHeroComponent::HandleChangeInitState(UGameFrameworkComponentManager* Manager, FGameplayTag CurrentState, FGameplayTag DesiredState)
146
+ {
147
+ if (CurrentState == LyraGameplayTags::InitState_DataAvailable && DesiredState == LyraGameplayTags::InitState_DataInitialized)
148
+ {
149
+ APawn* Pawn = GetPawn<APawn>();
150
+ ALyraPlayerState* LyraPS = GetPlayerState<ALyraPlayerState>();
151
+ if (!ensure(Pawn && LyraPS))
152
+ {
153
+ return;
154
+ }
155
+
156
+ const ULyraPawnData* PawnData = nullptr;
157
+
158
+ if (ULyraPawnExtensionComponent* PawnExtComp = ULyraPawnExtensionComponent::FindPawnExtensionComponent(Pawn))
159
+ {
160
+ PawnData = PawnExtComp->GetPawnData<ULyraPawnData>();
161
+
162
+ // The player state holds the persistent data for this player (state that persists across deaths and multiple pawns).
163
+ // The ability system component and attribute sets live on the player state.
164
+ PawnExtComp->InitializeAbilitySystem(LyraPS->GetLyraAbilitySystemComponent(), LyraPS);
165
+ }
166
+
167
+ if (ALyraPlayerController* LyraPC = GetController<ALyraPlayerController>())
168
+ {
169
+ if (Pawn->InputComponent != nullptr)
170
+ {
171
+ InitializePlayerInput(Pawn->InputComponent);
172
+ }
173
+ }
174
+
175
+ // Hook up the delegate for all pawns, in case we spectate later
176
+ if (PawnData)
177
+ {
178
+ if (ULyraCameraComponent* CameraComponent = ULyraCameraComponent::FindCameraComponent(Pawn))
179
+ {
180
+ CameraComponent->DetermineCameraModeDelegate.BindUObject(this, &ThisClass::DetermineCameraMode);
181
+ }
182
+ }
183
+ }
184
+ }
185
+
186
+ void ULyraHeroComponent::OnActorInitStateChanged(const FActorInitStateChangedParams& Params)
187
+ {
188
+ if (Params.FeatureName == ULyraPawnExtensionComponent::NAME_ActorFeatureName)
189
+ {
190
+ if (Params.FeatureState == LyraGameplayTags::InitState_DataInitialized)
191
+ {
192
+ // If the extension component says all all other components are initialized, try to progress to next state
193
+ CheckDefaultInitialization();
194
+ }
195
+ }
196
+ }
197
+
198
+ void ULyraHeroComponent::CheckDefaultInitialization()
199
+ {
200
+ static const TArray<FGameplayTag> StateChain = { LyraGameplayTags::InitState_Spawned, LyraGameplayTags::InitState_DataAvailable, LyraGameplayTags::InitState_DataInitialized, LyraGameplayTags::InitState_GameplayReady };
201
+
202
+ // This will try to progress from spawned (which is only set in BeginPlay) through the data initialization stages until it gets to gameplay ready
203
+ ContinueInitStateChain(StateChain);
204
+ }
205
+
206
+ void ULyraHeroComponent::BeginPlay()
207
+ {
208
+ Super::BeginPlay();
209
+
210
+ // Listen for when the pawn extension component changes init state
211
+ BindOnActorInitStateChanged(ULyraPawnExtensionComponent::NAME_ActorFeatureName, FGameplayTag(), false);
212
+
213
+ // Notifies that we are done spawning, then try the rest of initialization
214
+ ensure(TryToChangeInitState(LyraGameplayTags::InitState_Spawned));
215
+ CheckDefaultInitialization();
216
+ }
217
+
218
+ void ULyraHeroComponent::EndPlay(const EEndPlayReason::Type EndPlayReason)
219
+ {
220
+ UnregisterInitStateFeature();
221
+
222
+ Super::EndPlay(EndPlayReason);
223
+ }
224
+
225
+ void ULyraHeroComponent::InitializePlayerInput(UInputComponent* PlayerInputComponent)
226
+ {
227
+ check(PlayerInputComponent);
228
+
229
+ const APawn* Pawn = GetPawn<APawn>();
230
+ if (!Pawn)
231
+ {
232
+ return;
233
+ }
234
+
235
+ const APlayerController* PC = GetController<APlayerController>();
236
+ check(PC);
237
+
238
+ const ULyraLocalPlayer* LP = Cast<ULyraLocalPlayer>(PC->GetLocalPlayer());
239
+ check(LP);
240
+
241
+ UEnhancedInputLocalPlayerSubsystem* Subsystem = LP->GetSubsystem<UEnhancedInputLocalPlayerSubsystem>();
242
+ check(Subsystem);
243
+
244
+ Subsystem->ClearAllMappings();
245
+
246
+ if (const ULyraPawnExtensionComponent* PawnExtComp = ULyraPawnExtensionComponent::FindPawnExtensionComponent(Pawn))
247
+ {
248
+ if (const ULyraPawnData* PawnData = PawnExtComp->GetPawnData<ULyraPawnData>())
249
+ {
250
+ if (const ULyraInputConfig* InputConfig = PawnData->InputConfig)
251
+ {
252
+ for (const FInputMappingContextAndPriority& Mapping : DefaultInputMappings)
253
+ {
254
+ if (UInputMappingContext* IMC = Mapping.InputMapping.LoadSynchronous())
255
+ {
256
+ if (Mapping.bRegisterWithSettings)
257
+ {
258
+ if (UEnhancedInputUserSettings* Settings = Subsystem->GetUserSettings())
259
+ {
260
+ Settings->RegisterInputMappingContext(IMC);
261
+ }
262
+
263
+ FModifyContextOptions Options = {};
264
+ Options.bIgnoreAllPressedKeysUntilRelease = false;
265
+ // Actually add the config to the local player
266
+ Subsystem->AddMappingContext(IMC, Mapping.Priority, Options);
267
+ }
268
+ }
269
+ }
270
+
271
+ // The Lyra Input Component has some additional functions to map Gameplay Tags to an Input Action.
272
+ // If you want this functionality but still want to change your input component class, make it a subclass
273
+ // of the ULyraInputComponent or modify this component accordingly.
274
+ ULyraInputComponent* LyraIC = Cast<ULyraInputComponent>(PlayerInputComponent);
275
+ if (ensureMsgf(LyraIC, TEXT("Unexpected Input Component class! The Gameplay Abilities will not be bound to their inputs. Change the input component to ULyraInputComponent or a subclass of it.")))
276
+ {
277
+ // Add the key mappings that may have been set by the player
278
+ LyraIC->AddInputMappings(InputConfig, Subsystem);
279
+
280
+ // This is where we actually bind and input action to a gameplay tag, which means that Gameplay Ability Blueprints will
281
+ // be triggered directly by these input actions Triggered events.
282
+ TArray<uint32> BindHandles;
283
+ LyraIC->BindAbilityActions(InputConfig, this, &ThisClass::Input_AbilityInputTagPressed, &ThisClass::Input_AbilityInputTagReleased, /*out*/ BindHandles);
284
+
285
+ LyraIC->BindNativeAction(InputConfig, LyraGameplayTags::InputTag_Move, ETriggerEvent::Triggered, this, &ThisClass::Input_Move, /*bLogIfNotFound=*/ false);
286
+ LyraIC->BindNativeAction(InputConfig, LyraGameplayTags::InputTag_Look_Mouse, ETriggerEvent::Triggered, this, &ThisClass::Input_LookMouse, /*bLogIfNotFound=*/ false);
287
+ LyraIC->BindNativeAction(InputConfig, LyraGameplayTags::InputTag_Look_Stick, ETriggerEvent::Triggered, this, &ThisClass::Input_LookStick, /*bLogIfNotFound=*/ false);
288
+ LyraIC->BindNativeAction(InputConfig, LyraGameplayTags::InputTag_Crouch, ETriggerEvent::Triggered, this, &ThisClass::Input_Crouch, /*bLogIfNotFound=*/ false);
289
+ LyraIC->BindNativeAction(InputConfig, LyraGameplayTags::InputTag_AutoRun, ETriggerEvent::Triggered, this, &ThisClass::Input_AutoRun, /*bLogIfNotFound=*/ false);
290
+ }
291
+ }
292
+ }
293
+ }
294
+
295
+ if (ensure(!bReadyToBindInputs))
296
+ {
297
+ bReadyToBindInputs = true;
298
+ }
299
+
300
+ UGameFrameworkComponentManager::SendGameFrameworkComponentExtensionEvent(const_cast<APlayerController*>(PC), NAME_BindInputsNow);
301
+ UGameFrameworkComponentManager::SendGameFrameworkComponentExtensionEvent(const_cast<APawn*>(Pawn), NAME_BindInputsNow);
302
+ }
303
+
304
+ void ULyraHeroComponent::AddAdditionalInputConfig(const ULyraInputConfig* InputConfig)
305
+ {
306
+ TArray<uint32> BindHandles;
307
+
308
+ const APawn* Pawn = GetPawn<APawn>();
309
+ if (!Pawn)
310
+ {
311
+ return;
312
+ }
313
+
314
+ const APlayerController* PC = GetController<APlayerController>();
315
+ check(PC);
316
+
317
+ const ULocalPlayer* LP = PC->GetLocalPlayer();
318
+ check(LP);
319
+
320
+ UEnhancedInputLocalPlayerSubsystem* Subsystem = LP->GetSubsystem<UEnhancedInputLocalPlayerSubsystem>();
321
+ check(Subsystem);
322
+
323
+ if (const ULyraPawnExtensionComponent* PawnExtComp = ULyraPawnExtensionComponent::FindPawnExtensionComponent(Pawn))
324
+ {
325
+ ULyraInputComponent* LyraIC = Pawn->FindComponentByClass<ULyraInputComponent>();
326
+ if (ensureMsgf(LyraIC, TEXT("Unexpected Input Component class! The Gameplay Abilities will not be bound to their inputs. Change the input component to ULyraInputComponent or a subclass of it.")))
327
+ {
328
+ LyraIC->BindAbilityActions(InputConfig, this, &ThisClass::Input_AbilityInputTagPressed, &ThisClass::Input_AbilityInputTagReleased, /*out*/ BindHandles);
329
+ }
330
+ }
331
+ }
332
+
333
+ void ULyraHeroComponent::RemoveAdditionalInputConfig(const ULyraInputConfig* InputConfig)
334
+ {
335
+ //@TODO: Implement me!
336
+ }
337
+
338
+ bool ULyraHeroComponent::IsReadyToBindInputs() const
339
+ {
340
+ return bReadyToBindInputs;
341
+ }
342
+
343
+ void ULyraHeroComponent::Input_AbilityInputTagPressed(FGameplayTag InputTag)
344
+ {
345
+ if (const APawn* Pawn = GetPawn<APawn>())
346
+ {
347
+ if (const ULyraPawnExtensionComponent* PawnExtComp = ULyraPawnExtensionComponent::FindPawnExtensionComponent(Pawn))
348
+ {
349
+ if (ULyraAbilitySystemComponent* LyraASC = PawnExtComp->GetLyraAbilitySystemComponent())
350
+ {
351
+ LyraASC->AbilityInputTagPressed(InputTag);
352
+ }
353
+ }
354
+ }
355
+ }
356
+
357
+ void ULyraHeroComponent::Input_AbilityInputTagReleased(FGameplayTag InputTag)
358
+ {
359
+ const APawn* Pawn = GetPawn<APawn>();
360
+ if (!Pawn)
361
+ {
362
+ return;
363
+ }
364
+
365
+ if (const ULyraPawnExtensionComponent* PawnExtComp = ULyraPawnExtensionComponent::FindPawnExtensionComponent(Pawn))
366
+ {
367
+ if (ULyraAbilitySystemComponent* LyraASC = PawnExtComp->GetLyraAbilitySystemComponent())
368
+ {
369
+ LyraASC->AbilityInputTagReleased(InputTag);
370
+ }
371
+ }
372
+ }
373
+
374
+ void ULyraHeroComponent::Input_Move(const FInputActionValue& InputActionValue)
375
+ {
376
+ APawn* Pawn = GetPawn<APawn>();
377
+ AController* Controller = Pawn ? Pawn->GetController() : nullptr;
378
+
379
+ // If the player has attempted to move again then cancel auto running
380
+ if (ALyraPlayerController* LyraController = Cast<ALyraPlayerController>(Controller))
381
+ {
382
+ LyraController->SetIsAutoRunning(false);
383
+ }
384
+
385
+ if (Controller)
386
+ {
387
+ const FVector2D Value = InputActionValue.Get<FVector2D>();
388
+ const FRotator MovementRotation(0.0f, Controller->GetControlRotation().Yaw, 0.0f);
389
+
390
+ if (Value.X != 0.0f)
391
+ {
392
+ const FVector MovementDirection = MovementRotation.RotateVector(FVector::RightVector);
393
+ Pawn->AddMovementInput(MovementDirection, Value.X);
394
+ }
395
+
396
+ if (Value.Y != 0.0f)
397
+ {
398
+ const FVector MovementDirection = MovementRotation.RotateVector(FVector::ForwardVector);
399
+ Pawn->AddMovementInput(MovementDirection, Value.Y);
400
+ }
401
+ }
402
+ }
403
+
404
+ void ULyraHeroComponent::Input_LookMouse(const FInputActionValue& InputActionValue)
405
+ {
406
+ APawn* Pawn = GetPawn<APawn>();
407
+
408
+ if (!Pawn)
409
+ {
410
+ return;
411
+ }
412
+
413
+ const FVector2D Value = InputActionValue.Get<FVector2D>();
414
+
415
+ if (Value.X != 0.0f)
416
+ {
417
+ Pawn->AddControllerYawInput(Value.X);
418
+ }
419
+
420
+ if (Value.Y != 0.0f)
421
+ {
422
+ Pawn->AddControllerPitchInput(Value.Y);
423
+ }
424
+ }
425
+
426
+ void ULyraHeroComponent::Input_LookStick(const FInputActionValue& InputActionValue)
427
+ {
428
+ APawn* Pawn = GetPawn<APawn>();
429
+
430
+ if (!Pawn)
431
+ {
432
+ return;
433
+ }
434
+
435
+ const FVector2D Value = InputActionValue.Get<FVector2D>();
436
+
437
+ const UWorld* World = GetWorld();
438
+ check(World);
439
+
440
+ if (Value.X != 0.0f)
441
+ {
442
+ Pawn->AddControllerYawInput(Value.X * LyraHero::LookYawRate * World->GetDeltaSeconds());
443
+ }
444
+
445
+ if (Value.Y != 0.0f)
446
+ {
447
+ Pawn->AddControllerPitchInput(Value.Y * LyraHero::LookPitchRate * World->GetDeltaSeconds());
448
+ }
449
+ }
450
+
451
+ void ULyraHeroComponent::Input_Crouch(const FInputActionValue& InputActionValue)
452
+ {
453
+ if (ALyraCharacter* Character = GetPawn<ALyraCharacter>())
454
+ {
455
+ Character->ToggleCrouch();
456
+ }
457
+ }
458
+
459
+ void ULyraHeroComponent::Input_AutoRun(const FInputActionValue& InputActionValue)
460
+ {
461
+ if (APawn* Pawn = GetPawn<APawn>())
462
+ {
463
+ if (ALyraPlayerController* Controller = Cast<ALyraPlayerController>(Pawn->GetController()))
464
+ {
465
+ // Toggle auto running
466
+ Controller->SetIsAutoRunning(!Controller->GetIsAutoRunning());
467
+ }
468
+ }
469
+ }
470
+
471
+ TSubclassOf<ULyraCameraMode> ULyraHeroComponent::DetermineCameraMode() const
472
+ {
473
+ if (AbilityCameraMode)
474
+ {
475
+ return AbilityCameraMode;
476
+ }
477
+
478
+ const APawn* Pawn = GetPawn<APawn>();
479
+ if (!Pawn)
480
+ {
481
+ return nullptr;
482
+ }
483
+
484
+ if (ULyraPawnExtensionComponent* PawnExtComp = ULyraPawnExtensionComponent::FindPawnExtensionComponent(Pawn))
485
+ {
486
+ if (const ULyraPawnData* PawnData = PawnExtComp->GetPawnData<ULyraPawnData>())
487
+ {
488
+ return PawnData->DefaultCameraMode;
489
+ }
490
+ }
491
+
492
+ return nullptr;
493
+ }
494
+
495
+ void ULyraHeroComponent::SetAbilityCameraMode(TSubclassOf<ULyraCameraMode> CameraMode, const FGameplayAbilitySpecHandle& OwningSpecHandle)
496
+ {
497
+ if (CameraMode)
498
+ {
499
+ AbilityCameraMode = CameraMode;
500
+ AbilityCameraModeOwningSpecHandle = OwningSpecHandle;
501
+ }
502
+ }
503
+
504
+ void ULyraHeroComponent::ClearAbilityCameraMode(const FGameplayAbilitySpecHandle& OwningSpecHandle)
505
+ {
506
+ if (AbilityCameraModeOwningSpecHandle == OwningSpecHandle)
507
+ {
508
+ AbilityCameraMode = nullptr;
509
+ AbilityCameraModeOwningSpecHandle = FGameplayAbilitySpecHandle();
510
+ }
511
+ }
512
+
LyraStarterGame/Source/LyraGame/Character/LyraHeroComponent.h ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "Components/GameFrameworkInitStateInterface.h"
6
+ #include "Components/PawnComponent.h"
7
+ #include "GameFeatures/GameFeatureAction_AddInputContextMapping.h"
8
+ #include "GameplayAbilitySpecHandle.h"
9
+ #include "LyraHeroComponent.generated.h"
10
+
11
+ #define UE_API LYRAGAME_API
12
+
13
+ namespace EEndPlayReason { enum Type : int; }
14
+ struct FLoadedMappableConfigPair;
15
+ struct FMappableConfigPair;
16
+
17
+ class UGameFrameworkComponentManager;
18
+ class UInputComponent;
19
+ class ULyraCameraMode;
20
+ class ULyraInputConfig;
21
+ class UObject;
22
+ struct FActorInitStateChangedParams;
23
+ struct FFrame;
24
+ struct FGameplayTag;
25
+ struct FInputActionValue;
26
+
27
+ /**
28
+ * Component that sets up input and camera handling for player controlled pawns (or bots that simulate players).
29
+ * This depends on a PawnExtensionComponent to coordinate initialization.
30
+ */
31
+ UCLASS(MinimalAPI, Blueprintable, Meta=(BlueprintSpawnableComponent))
32
+ class ULyraHeroComponent : public UPawnComponent, public IGameFrameworkInitStateInterface
33
+ {
34
+ GENERATED_BODY()
35
+
36
+ public:
37
+
38
+ UE_API ULyraHeroComponent(const FObjectInitializer& ObjectInitializer);
39
+
40
+ /** Returns the hero component if one exists on the specified actor. */
41
+ UFUNCTION(BlueprintPure, Category = "Lyra|Hero")
42
+ static ULyraHeroComponent* FindHeroComponent(const AActor* Actor) { return (Actor ? Actor->FindComponentByClass<ULyraHeroComponent>() : nullptr); }
43
+
44
+ /** Overrides the camera from an active gameplay ability */
45
+ UE_API void SetAbilityCameraMode(TSubclassOf<ULyraCameraMode> CameraMode, const FGameplayAbilitySpecHandle& OwningSpecHandle);
46
+
47
+ /** Clears the camera override if it is set */
48
+ UE_API void ClearAbilityCameraMode(const FGameplayAbilitySpecHandle& OwningSpecHandle);
49
+
50
+ /** Adds mode-specific input config */
51
+ UE_API void AddAdditionalInputConfig(const ULyraInputConfig* InputConfig);
52
+
53
+ /** Removes a mode-specific input config if it has been added */
54
+ UE_API void RemoveAdditionalInputConfig(const ULyraInputConfig* InputConfig);
55
+
56
+ /** True if this is controlled by a real player and has progressed far enough in initialization where additional input bindings can be added */
57
+ UE_API bool IsReadyToBindInputs() const;
58
+
59
+ /** The name of the extension event sent via UGameFrameworkComponentManager when ability inputs are ready to bind */
60
+ static UE_API const FName NAME_BindInputsNow;
61
+
62
+ /** The name of this component-implemented feature */
63
+ static UE_API const FName NAME_ActorFeatureName;
64
+
65
+ //~ Begin IGameFrameworkInitStateInterface interface
66
+ virtual FName GetFeatureName() const override { return NAME_ActorFeatureName; }
67
+ UE_API virtual bool CanChangeInitState(UGameFrameworkComponentManager* Manager, FGameplayTag CurrentState, FGameplayTag DesiredState) const override;
68
+ UE_API virtual void HandleChangeInitState(UGameFrameworkComponentManager* Manager, FGameplayTag CurrentState, FGameplayTag DesiredState) override;
69
+ UE_API virtual void OnActorInitStateChanged(const FActorInitStateChangedParams& Params) override;
70
+ UE_API virtual void CheckDefaultInitialization() override;
71
+ //~ End IGameFrameworkInitStateInterface interface
72
+
73
+ protected:
74
+
75
+ UE_API virtual void OnRegister() override;
76
+ UE_API virtual void BeginPlay() override;
77
+ UE_API virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
78
+
79
+ UE_API virtual void InitializePlayerInput(UInputComponent* PlayerInputComponent);
80
+
81
+ UE_API void Input_AbilityInputTagPressed(FGameplayTag InputTag);
82
+ UE_API void Input_AbilityInputTagReleased(FGameplayTag InputTag);
83
+
84
+ UE_API void Input_Move(const FInputActionValue& InputActionValue);
85
+ UE_API void Input_LookMouse(const FInputActionValue& InputActionValue);
86
+ UE_API void Input_LookStick(const FInputActionValue& InputActionValue);
87
+ UE_API void Input_Crouch(const FInputActionValue& InputActionValue);
88
+ UE_API void Input_AutoRun(const FInputActionValue& InputActionValue);
89
+
90
+ UE_API TSubclassOf<ULyraCameraMode> DetermineCameraMode() const;
91
+
92
+ protected:
93
+
94
+ UPROPERTY(EditAnywhere)
95
+ TArray<FInputMappingContextAndPriority> DefaultInputMappings;
96
+
97
+ /** Camera mode set by an ability. */
98
+ UPROPERTY()
99
+ TSubclassOf<ULyraCameraMode> AbilityCameraMode;
100
+
101
+ /** Spec handle for the last ability to set a camera mode. */
102
+ FGameplayAbilitySpecHandle AbilityCameraModeOwningSpecHandle;
103
+
104
+ /** True when player input bindings have been applied, will never be true for non - players */
105
+ bool bReadyToBindInputs;
106
+ };
107
+
108
+ #undef UE_API
LyraStarterGame/Source/LyraGame/Character/LyraPawn.cpp ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #include "LyraPawn.h"
4
+
5
+ #include "GameFramework/Controller.h"
6
+ #include "LyraLogChannels.h"
7
+ #include "Net/UnrealNetwork.h"
8
+ #include "UObject/ScriptInterface.h"
9
+
10
+ #include UE_INLINE_GENERATED_CPP_BY_NAME(LyraPawn)
11
+
12
+ class FLifetimeProperty;
13
+ class UObject;
14
+
15
+ ALyraPawn::ALyraPawn(const FObjectInitializer& ObjectInitializer)
16
+ : Super(ObjectInitializer)
17
+ {
18
+ }
19
+
20
+ void ALyraPawn::GetLifetimeReplicatedProps(TArray< FLifetimeProperty >& OutLifetimeProps) const
21
+ {
22
+ Super::GetLifetimeReplicatedProps(OutLifetimeProps);
23
+
24
+ DOREPLIFETIME(ThisClass, MyTeamID);
25
+ }
26
+
27
+ void ALyraPawn::PreInitializeComponents()
28
+ {
29
+ Super::PreInitializeComponents();
30
+ }
31
+
32
+ void ALyraPawn::EndPlay(const EEndPlayReason::Type EndPlayReason)
33
+ {
34
+ Super::EndPlay(EndPlayReason);
35
+ }
36
+
37
+ void ALyraPawn::PossessedBy(AController* NewController)
38
+ {
39
+ const FGenericTeamId OldTeamID = MyTeamID;
40
+
41
+ Super::PossessedBy(NewController);
42
+
43
+ // Grab the current team ID and listen for future changes
44
+ if (ILyraTeamAgentInterface* ControllerAsTeamProvider = Cast<ILyraTeamAgentInterface>(NewController))
45
+ {
46
+ MyTeamID = ControllerAsTeamProvider->GetGenericTeamId();
47
+ ControllerAsTeamProvider->GetTeamChangedDelegateChecked().AddDynamic(this, &ThisClass::OnControllerChangedTeam);
48
+ }
49
+ ConditionalBroadcastTeamChanged(this, OldTeamID, MyTeamID);
50
+ }
51
+
52
+ void ALyraPawn::UnPossessed()
53
+ {
54
+ AController* const OldController = GetController();
55
+
56
+ // Stop listening for changes from the old controller
57
+ const FGenericTeamId OldTeamID = MyTeamID;
58
+ if (ILyraTeamAgentInterface* ControllerAsTeamProvider = Cast<ILyraTeamAgentInterface>(OldController))
59
+ {
60
+ ControllerAsTeamProvider->GetTeamChangedDelegateChecked().RemoveAll(this);
61
+ }
62
+
63
+ Super::UnPossessed();
64
+
65
+ // Determine what the new team ID should be afterwards
66
+ MyTeamID = DetermineNewTeamAfterPossessionEnds(OldTeamID);
67
+ ConditionalBroadcastTeamChanged(this, OldTeamID, MyTeamID);
68
+ }
69
+
70
+ void ALyraPawn::SetGenericTeamId(const FGenericTeamId& NewTeamID)
71
+ {
72
+ if (GetController() == nullptr)
73
+ {
74
+ if (HasAuthority())
75
+ {
76
+ const FGenericTeamId OldTeamID = MyTeamID;
77
+ MyTeamID = NewTeamID;
78
+ ConditionalBroadcastTeamChanged(this, OldTeamID, MyTeamID);
79
+ }
80
+ else
81
+ {
82
+ UE_LOG(LogLyraTeams, Error, TEXT("You can't set the team ID on a pawn (%s) except on the authority"), *GetPathNameSafe(this));
83
+ }
84
+ }
85
+ else
86
+ {
87
+ UE_LOG(LogLyraTeams, Error, TEXT("You can't set the team ID on a possessed pawn (%s); it's driven by the associated controller"), *GetPathNameSafe(this));
88
+ }
89
+ }
90
+
91
+ FGenericTeamId ALyraPawn::GetGenericTeamId() const
92
+ {
93
+ return MyTeamID;
94
+ }
95
+
96
+ FOnLyraTeamIndexChangedDelegate* ALyraPawn::GetOnTeamIndexChangedDelegate()
97
+ {
98
+ return &OnTeamChangedDelegate;
99
+ }
100
+
101
+ void ALyraPawn::OnControllerChangedTeam(UObject* TeamAgent, int32 OldTeam, int32 NewTeam)
102
+ {
103
+ const FGenericTeamId MyOldTeamID = MyTeamID;
104
+ MyTeamID = IntegerToGenericTeamId(NewTeam);
105
+ ConditionalBroadcastTeamChanged(this, MyOldTeamID, MyTeamID);
106
+ }
107
+
108
+ void ALyraPawn::OnRep_MyTeamID(FGenericTeamId OldTeamID)
109
+ {
110
+ ConditionalBroadcastTeamChanged(this, OldTeamID, MyTeamID);
111
+ }
112
+
LyraStarterGame/Source/LyraGame/Character/LyraPawn.h ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright Epic Games, Inc. All Rights Reserved.
2
+
3
+ #pragma once
4
+
5
+ #include "ModularPawn.h"
6
+ #include "Teams/LyraTeamAgentInterface.h"
7
+
8
+ #include "LyraPawn.generated.h"
9
+
10
+ #define UE_API LYRAGAME_API
11
+
12
+ class AController;
13
+ class UObject;
14
+ struct FFrame;
15
+
16
+ /**
17
+ * ALyraPawn
18
+ */
19
+ UCLASS(MinimalAPI)
20
+ class ALyraPawn : public AModularPawn, public ILyraTeamAgentInterface
21
+ {
22
+ GENERATED_BODY()
23
+
24
+ public:
25
+
26
+ UE_API ALyraPawn(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
27
+
28
+ //~AActor interface
29
+ UE_API virtual void PreInitializeComponents() override;
30
+ UE_API virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
31
+ //~End of AActor interface
32
+
33
+ //~APawn interface
34
+ UE_API virtual void PossessedBy(AController* NewController) override;
35
+ UE_API virtual void UnPossessed() override;
36
+ //~End of APawn interface
37
+
38
+ //~ILyraTeamAgentInterface interface
39
+ UE_API virtual void SetGenericTeamId(const FGenericTeamId& NewTeamID) override;
40
+ UE_API virtual FGenericTeamId GetGenericTeamId() const override;
41
+ UE_API virtual FOnLyraTeamIndexChangedDelegate* GetOnTeamIndexChangedDelegate() override;
42
+ //~End of ILyraTeamAgentInterface interface
43
+
44
+ protected:
45
+ // Called to determine what happens to the team ID when possession ends
46
+ virtual FGenericTeamId DetermineNewTeamAfterPossessionEnds(FGenericTeamId OldTeamID) const
47
+ {
48
+ // This could be changed to return, e.g., OldTeamID if you want to keep it assigned afterwards, or return an ID for some neutral faction, or etc...
49
+ return FGenericTeamId::NoTeam;
50
+ }
51
+
52
+ private:
53
+ UFUNCTION()
54
+ UE_API void OnControllerChangedTeam(UObject* TeamAgent, int32 OldTeam, int32 NewTeam);
55
+
56
+ private:
57
+ UPROPERTY(ReplicatedUsing = OnRep_MyTeamID)
58
+ FGenericTeamId MyTeamID;
59
+
60
+ UPROPERTY()
61
+ FOnLyraTeamIndexChangedDelegate OnTeamChangedDelegate;
62
+
63
+ private:
64
+ UFUNCTION()
65
+ UE_API void OnRep_MyTeamID(FGenericTeamId OldTeamID);
66
+ };
67
+
68
+ #undef UE_API